@psnext/slingcli 2.4.20260523-2 → 2.4.20260523-3
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/bin/sling.js +65 -19
- package/package.json +2 -2
- package/slingshot/index.js +29 -29
package/slingshot/index.js
CHANGED
|
@@ -28,12 +28,12 @@ var xO=Object.create;var Zh=Object.defineProperty;var yO=Object.getOwnPropertyDe
|
|
|
28
28
|
`);l.content=[{type:"text",text:f},...d]}else{u.length>0&&(l.content=u);let f=p[0].thinkingSignature;t.provider==="opencode-go"&&f==="reasoning"&&(f="reasoning_content"),f&&f.length>0&&(l[f]=p.map(x=>x.thinking).join(`
|
|
29
29
|
`))}else u.length>0&&(l.content=u);let m=c.content.filter(C9);if(m.length>0){l.tool_calls=m.map(x=>({id:x.id,type:"function",function:{name:x.name,arguments:JSON.stringify(x.arguments)}}));let f=m.filter(x=>x.thoughtSignature).map(x=>{try{return JSON.parse(x.thoughtSignature)}catch{return null}}).filter(Boolean);f.length>0&&(l.reasoning_details=f)}n.requiresReasoningContentOnAssistantMessages&&t.reasoning&&l.reasoning_content===void 0&&(l.reasoning_content="");let g=l.content;if(!(g!=null&&g.length>0)&&!l.tool_calls)continue;i.push(l)}else if(c.role==="toolResult"){let l=[],d=a;for(;d<r.length&&r[d].role==="toolResult";d++){let u=r[d],p=u.content.filter(OS).map(f=>f.text).join(`
|
|
30
30
|
`),m=u.content.some(f=>f.type==="image"),g=p.length>0,h={role:"tool",content:fe(g?p:"(see attached image)"),tool_call_id:u.toolCallId};if(n.requiresToolResultName&&u.toolName&&(h.name=u.toolName),i.push(h),m&&t.input.includes("image"))for(let f of u.content)T9(f)&&l.push({type:"image_url",image_url:{url:`data:${f.mimeType};base64,${f.data}`}})}a=d-1,l.length>0?(n.requiresAssistantAfterToolResult&&i.push({role:"assistant",content:"I have processed the tool results."}),i.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...l]}),o="user"):o="toolResult";continue}o=c.role}return i}function W9(t,e){return t.map(n=>({type:"function",function:{name:n.name,description:n.description,parameters:n.parameters,...e.supportsStrictMode!==!1&&{strict:!1}}}))}function LS(t,e){let n=t.prompt_tokens||0,i=t.prompt_tokens_details?.cached_tokens??t.prompt_cache_hit_tokens??0,s=t.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,n-i-s),o=t.completion_tokens||0,a={input:r,output:o,cacheRead:i,cacheWrite:s,totalTokens:r+o+i+s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return fn(e,a),a}function U9(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${t}`}}}function F9(t){let e=t.provider,n=t.baseUrl,i=e==="zai"||n.includes("api.z.ai"),s=e==="together"||n.includes("api.together.ai")||n.includes("api.together.xyz"),r=e==="moonshotai"||e==="moonshotai-cn"||n.includes("api.moonshot."),o=e==="cloudflare-workers-ai"||n.includes("api.cloudflare.com"),a=e==="cloudflare-ai-gateway"||n.includes("gateway.ai.cloudflare.com"),c=e==="cerebras"||n.includes("cerebras.ai")||e==="xai"||n.includes("api.x.ai")||s||n.includes("chutes.ai")||n.includes("deepseek.com")||i||r||e==="opencode"||n.includes("opencode.ai")||o||a,l=n.includes("chutes.ai")||r||a||s,d=e==="xai"||n.includes("api.x.ai"),u=e==="deepseek"||n.includes("deepseek.com"),p=e==="openrouter"&&t.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!c,supportsDeveloperRole:!c,supportsReasoningEffort:!d&&!i&&!r&&!s&&!a,supportsUsageInStreaming:!0,maxTokensField:l?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:u,thinkingFormat:u?"deepseek":i?"zai":s?"together":e==="openrouter"||n.includes("openrouter.ai")?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!r&&!s&&!a,cacheControlFormat:p,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(s||o||a)}}function Eg(t){let e=F9(t);return t.compat?{supportsStore:t.compat.supportsStore??e.supportsStore,supportsDeveloperRole:t.compat.supportsDeveloperRole??e.supportsDeveloperRole,supportsReasoningEffort:t.compat.supportsReasoningEffort??e.supportsReasoningEffort,supportsUsageInStreaming:t.compat.supportsUsageInStreaming??e.supportsUsageInStreaming,maxTokensField:t.compat.maxTokensField??e.maxTokensField,requiresToolResultName:t.compat.requiresToolResultName??e.requiresToolResultName,requiresAssistantAfterToolResult:t.compat.requiresAssistantAfterToolResult??e.requiresAssistantAfterToolResult,requiresThinkingAsText:t.compat.requiresThinkingAsText??e.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:t.compat.requiresReasoningContentOnAssistantMessages??e.requiresReasoningContentOnAssistantMessages,thinkingFormat:t.compat.thinkingFormat??e.thinkingFormat,openRouterRouting:t.compat.openRouterRouting??{},vercelGatewayRouting:t.compat.vercelGatewayRouting??e.vercelGatewayRouting,zaiToolStream:t.compat.zaiToolStream??e.zaiToolStream,supportsStrictMode:t.compat.supportsStrictMode??e.supportsStrictMode,cacheControlFormat:t.compat.cacheControlFormat??e.cacheControlFormat,sendSessionAffinityHeaders:t.compat.sendSessionAffinityHeaders??e.sendSessionAffinityHeaders,supportsLongCacheRetention:t.compat.supportsLongCacheRetention??e.supportsLongCacheRetention}:e}var US,k9,BS=Ne(()=>{"use strict";Gn();In();Rn();tr();Vo();Oi();rd();od();qc();Li();Xo();US=(t,e,n)=>{let i=new it;return(async()=>{let s={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let r=n?.apiKey||Ke(t.provider)||"",o=Eg(t),a=WS(n?.cacheRetention),c=a==="none"?void 0:n?.sessionId,l=M9(t,e,r,n?.headers,c,o),d=I9(t,e,n,o,a),u=await n?.onPayload?.(d,t);u!==void 0&&(d=u);let p={...n?.signal?{signal:n.signal}:{},...n?.timeoutMs!==void 0?{timeout:n.timeoutMs}:{},...n?.maxRetries!==void 0?{maxRetries:n.maxRetries}:{}},{data:m,response:g}=await l.chat.completions.create(d,p).withResponse();await n?.onResponse?.({status:g.status,headers:gn(g.headers)},t),i.push({type:"start",partial:s});let h=null,f=null,x=!1,y=new Map,w=new Map,P=s.content,_=M=>P.indexOf(M),R=M=>{let I=_(M);I!==-1&&(M.type==="text"?i.push({type:"text_end",contentIndex:I,content:M.text,partial:s}):M.type==="thinking"?i.push({type:"thinking_end",contentIndex:I,content:M.thinking,partial:s}):M.type==="toolCall"&&(M.arguments=Gt(M.partialArgs),delete M.partialArgs,delete M.streamIndex,i.push({type:"toolcall_end",contentIndex:I,toolCall:M,partial:s})))},L=()=>(h||(h={type:"text",text:""},P.push(h),i.push({type:"text_start",contentIndex:_(h),partial:s})),h),E=M=>(f||(f={type:"thinking",thinking:"",thinkingSignature:M},P.push(f),i.push({type:"thinking_start",contentIndex:_(f),partial:s})),f),W=M=>{let I=typeof M.index=="number"?M.index:void 0,O=I!==void 0?y.get(I):void 0;return!O&&M.id&&(O=w.get(M.id)),O||(O={type:"toolCall",id:M.id||"",name:M.function?.name||"",arguments:{},partialArgs:"",streamIndex:I},I!==void 0&&y.set(I,O),M.id&&w.set(M.id,O),P.push(O),i.push({type:"toolcall_start",contentIndex:_(O),partial:s})),I!==void 0&&O.streamIndex===void 0&&(O.streamIndex=I,y.set(I,O)),M.id&&w.set(M.id,O),O};for await(let M of m){if(!M||typeof M!="object")continue;s.responseId||=M.id,typeof M.model=="string"&&M.model.length>0&&M.model!==t.id&&(s.responseModel||=M.model),M.usage&&(s.usage=LS(M.usage,t));let I=Array.isArray(M.choices)?M.choices[0]:void 0;if(I){if(!M.usage&&I.usage&&(s.usage=LS(I.usage,t)),I.finish_reason){let O=U9(I.finish_reason);s.stopReason=O.stopReason,O.errorMessage&&(s.errorMessage=O.errorMessage),x=!0}if(I.delta){if(I.delta.content!==null&&I.delta.content!==void 0&&I.delta.content.length>0){let G=L();G.text+=I.delta.content,i.push({type:"text_delta",contentIndex:_(G),delta:I.delta.content,partial:s})}let O=["reasoning_content","reasoning","reasoning_text"],F=I.delta,N=null;for(let G of O){let Z=F[G];if(typeof Z=="string"&&Z.length>0){N=G;break}}if(N){let G=F[N];if(typeof G=="string"&&G.length>0){let Z=t.provider==="opencode-go"&&N==="reasoning"?"reasoning_content":N,de=E(Z);de.thinking+=G,i.push({type:"thinking_delta",contentIndex:_(de),delta:G,partial:s})}}if(I?.delta?.tool_calls)for(let G of I.delta.tool_calls){let Z=W(G);!Z.id&&G.id&&(Z.id=G.id,w.set(G.id,Z)),!Z.name&&G.function?.name&&(Z.name=G.function.name);let de="";G.function?.arguments&&(de=G.function.arguments,Z.partialArgs=(Z.partialArgs??"")+G.function.arguments,Z.arguments=Gt(Z.partialArgs)),i.push({type:"toolcall_delta",contentIndex:_(Z),delta:de,partial:s})}let H=I.delta.reasoning_details;if(H&&Array.isArray(H)){for(let G of H)if(G.type==="reasoning.encrypted"&&G.id&&G.data){let Z=s.content.find(de=>de.type==="toolCall"&&de.id===G.id);Z&&(Z.thoughtSignature=JSON.stringify(G))}}}}}for(let M of P)R(M);if(n?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted")throw new Error("Request was aborted");if(s.stopReason==="error")throw new Error(s.errorMessage||"Provider returned an error stop reason");if(!x)throw new Error("Stream ended without finish_reason");i.push({type:"done",reason:s.stopReason,message:s}),i.end()}catch(r){for(let a of s.content)delete a.index,delete a.partialArgs,delete a.streamIndex;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=r instanceof Error?r.message:JSON.stringify(r);let o=r?.error?.metadata?.raw;o&&(s.errorMessage+=`
|
|
31
|
-
${o}`),i.push({type:"error",reason:s.stopReason,error:s}),i.end()}})(),i},k9=(t,e,n)=>{let i=n?.apiKey||Ke(t.provider);if(!i)throw new Error(`No API key for provider: ${t.provider}`);let s=Pt(t,n,i),r=n?.reasoning?Rt(t,n.reasoning):void 0,o=r==="off"?void 0:r,a=n?.toolChoice;return US(t,e,{...s,reasoningEffort:o,toolChoice:a})}});var GS={};Ei(GS,{streamOpenAIResponses:()=>qS,streamSimpleOpenAIResponses:()=>j9});import D9 from"openai";function NS(t){return t||(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long"?"long":"short")}function jS(t){return{sendSessionIdHeader:t.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:t.compat?.supportsLongCacheRetention??!0}}function B9(t,e){return e==="long"&&t.supportsLongCacheRetention?"24h":void 0}function N9(t){if(t instanceof Error){let e=t.status,n=typeof e=="number"?e:void 0;return n!==void 0?`OpenAI API error (${n}): ${t.message}`:t.message}try{return JSON.stringify(t)}catch{return String(t)}}function q9(t,e,n,i,s){if(!n){if(!process.env.OPENAI_API_KEY)throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");n=process.env.OPENAI_API_KEY}let r=jS(t),o={...t.headers};if(t.provider==="github-copilot"){let c=Qo(e.messages),l=Yo({messages:e.messages,hasImages:c});Object.assign(o,l)}s&&(r.sendSessionIdHeader&&(o.session_id=s),o["x-client-request-id"]=s),i&&Object.assign(o,i);let a=t.provider==="cloudflare-ai-gateway"?{...o,Authorization:o.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:o;return new D9({apiKey:n,baseURL:sd(t.provider)?Jo(t):t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:a})}function G9(t,e,n){let i=nr(t,e,$9),s=NS(n?.cacheRetention),r=jS(t),o={model:t.id,input:i,stream:!0,prompt_cache_key:s==="none"?void 0:ys(n?.sessionId),prompt_cache_retention:B9(r,s),store:!1};if(n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),e.tools&&e.tools.length>0&&(o.tools=Zo(e.tools)),t.reasoning)if(n?.reasoningEffort||n?.reasoningSummary){let a=n?.reasoningEffort?t.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:"medium";o.reasoning={effort:a,summary:n?.reasoningSummary||"auto"},o.include=["reasoning.encrypted_content"]}else t.provider!=="github-copilot"&&t.thinkingLevelMap?.off!==null&&(o.reasoning={effort:t.thinkingLevelMap?.off??"none"});return o}function K9(t,e){switch(e){case"flex":return .5;case"priority":return t.id==="gpt-5.5"?2.5:2;default:return 1}}function H9(t,e,n){let i=K9(n,e);i!==1&&(t.cost.input*=i,t.cost.output*=i,t.cost.cacheRead*=i,t.cost.cacheWrite*=i,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite)}var $9,qS,j9,KS=Ne(()=>{"use strict";Gn();In();Rn();tr();rd();od();qc();pd();Li();$9=new Set(["openai","openai-codex","opencode"]);qS=(t,e,n)=>{let i=new it;return(async()=>{let s={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let r=n?.apiKey||Ke(t.provider)||"",a=NS(n?.cacheRetention)==="none"?void 0:n?.sessionId,c=q9(t,e,r,n?.headers,a),l=G9(t,e,n),d=await n?.onPayload?.(l,t);d!==void 0&&(l=d);let u={...n?.signal?{signal:n.signal}:{},...n?.timeoutMs!==void 0?{timeout:n.timeoutMs}:{},...n?.maxRetries!==void 0?{maxRetries:n.maxRetries}:{}},{data:p,response:m}=await c.responses.create(l,u).withResponse();if(await n?.onResponse?.({status:m.status,headers:gn(m.headers)},t),i.push({type:"start",partial:s}),await ir(p,s,i,t,{serviceTier:n?.serviceTier,applyServiceTierPricing:(g,h)=>H9(g,h,t)}),n?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");i.push({type:"done",reason:s.stopReason,message:s}),i.end()}catch(r){for(let o of s.content)delete o.index,delete o.partialJson;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=N9(r),i.push({type:"error",reason:s.stopReason,error:s}),i.end()}})(),i},j9=(t,e,n)=>{let i=n?.apiKey||Ke(t.provider);if(!i)throw new Error(`No API key for provider: ${t.provider}`);let s=Pt(t,n,i),r=n?.reasoning?Rt(t,n.reasoning):void 0;return qS(t,e,{...s,reasoningEffort:r==="off"?void 0:r})}});var Ut=T(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.HasPropertyKey=gj;xt.IsAsyncIterator=fj;xt.IsArray=Bb;xt.IsBigInt=bj;xt.IsBoolean=xj;xt.IsDate=yj;xt.IsFunction=vj;xt.IsIterator=wj;xt.IsNull=Sj;xt.IsNumber=Cj;xt.IsObject=Nb;xt.IsRegExp=Tj;xt.IsString=kj;xt.IsSymbol=Mj;xt.IsUint8Array=jb;xt.IsUndefined=Ij;function gj(t,e){return e in t}function fj(t){return Nb(t)&&!Bb(t)&&!jb(t)&&Symbol.asyncIterator in t}function Bb(t){return Array.isArray(t)}function bj(t){return typeof t=="bigint"}function xj(t){return typeof t=="boolean"}function yj(t){return t instanceof globalThis.Date}function vj(t){return typeof t=="function"}function wj(t){return Nb(t)&&!Bb(t)&&!jb(t)&&Symbol.iterator in t}function Sj(t){return t===null}function Cj(t){return typeof t=="number"}function Nb(t){return typeof t=="object"&&t!==null}function Tj(t){return t instanceof globalThis.RegExp}function kj(t){return typeof t=="string"}function Mj(t){return typeof t=="symbol"}function jb(t){return t instanceof globalThis.Uint8Array}function Ij(t){return t===void 0}});var tn=T(Qi=>{"use strict";var Rj=Qi&&Qi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Pj=Qi&&Qi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_j=Qi&&Qi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Rj(n,e,i[s]);return Pj(n,e),n}})();Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Clone=Uj;var du=_j(Ut());function Ej(t){return t.map(e=>Mm(e))}function Aj(t){return new Date(t.getTime())}function Oj(t){return new Uint8Array(t)}function Lj(t){return new RegExp(t.source,t.flags)}function Wj(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Mm(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Mm(t[n]);return e}function Mm(t){return du.IsArray(t)?Ej(t):du.IsDate(t)?Aj(t):du.IsUint8Array(t)?Oj(t):du.IsRegExp(t)?Lj(t):du.IsObject(t)?Wj(t):t}function Uj(t){return Mm(t)}});var Rm=T(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});Im.CloneRest=Fj;Im.CloneType=YI;var QI=tn();function Fj(t){return t.map(e=>YI(e))}function YI(t,e){return e===void 0?(0,QI.Clone)(t):(0,QI.Clone)({...e,...t})}});var qb=T(Bs=>{"use strict";var Dj=Bs&&Bs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),XI=Bs&&Bs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Dj(e,t,n)};Object.defineProperty(Bs,"__esModule",{value:!0});XI(Rm(),Bs);XI(tn(),Bs)});var cR=T(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.IsAsyncIterator=$j;ke.IsIterator=Bj;ke.IsStandardObject=Nj;ke.IsInstanceObject=jj;ke.IsPromise=qj;ke.IsDate=Gj;ke.IsMap=Kj;ke.IsSet=Hj;ke.IsRegExp=zj;ke.IsTypedArray=Vj;ke.IsInt8Array=Jj;ke.IsUint8Array=Qj;ke.IsUint8ClampedArray=Yj;ke.IsInt16Array=Xj;ke.IsUint16Array=Zj;ke.IsInt32Array=eq;ke.IsUint32Array=tq;ke.IsFloat32Array=nq;ke.IsFloat64Array=iq;ke.IsBigInt64Array=sq;ke.IsBigUint64Array=rq;ke.HasPropertyKey=oq;ke.IsObject=pu;ke.IsArray=ZI;ke.IsUndefined=eR;ke.IsNull=tR;ke.IsBoolean=nR;ke.IsNumber=iR;ke.IsInteger=aq;ke.IsBigInt=sR;ke.IsString=rR;ke.IsFunction=oR;ke.IsSymbol=aR;ke.IsValueType=cq;function $j(t){return pu(t)&&globalThis.Symbol.asyncIterator in t}function Bj(t){return pu(t)&&globalThis.Symbol.iterator in t}function Nj(t){return pu(t)&&(globalThis.Object.getPrototypeOf(t)===Object.prototype||globalThis.Object.getPrototypeOf(t)===null)}function jj(t){return pu(t)&&!ZI(t)&&oR(t.constructor)&&t.constructor.name!=="Object"}function qj(t){return t instanceof globalThis.Promise}function Gj(t){return t instanceof Date&&globalThis.Number.isFinite(t.getTime())}function Kj(t){return t instanceof globalThis.Map}function Hj(t){return t instanceof globalThis.Set}function zj(t){return t instanceof globalThis.RegExp}function Vj(t){return globalThis.ArrayBuffer.isView(t)}function Jj(t){return t instanceof globalThis.Int8Array}function Qj(t){return t instanceof globalThis.Uint8Array}function Yj(t){return t instanceof globalThis.Uint8ClampedArray}function Xj(t){return t instanceof globalThis.Int16Array}function Zj(t){return t instanceof globalThis.Uint16Array}function eq(t){return t instanceof globalThis.Int32Array}function tq(t){return t instanceof globalThis.Uint32Array}function nq(t){return t instanceof globalThis.Float32Array}function iq(t){return t instanceof globalThis.Float64Array}function sq(t){return t instanceof globalThis.BigInt64Array}function rq(t){return t instanceof globalThis.BigUint64Array}function oq(t,e){return e in t}function pu(t){return t!==null&&typeof t=="object"}function ZI(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function eR(t){return t===void 0}function tR(t){return t===null}function nR(t){return typeof t=="boolean"}function iR(t){return typeof t=="number"}function aq(t){return globalThis.Number.isInteger(t)}function sR(t){return typeof t=="bigint"}function rR(t){return typeof t=="string"}function oR(t){return typeof t=="function"}function aR(t){return typeof t=="symbol"}function cq(t){return sR(t)||nR(t)||tR(t)||iR(t)||rR(t)||aR(t)||eR(t)}});var lR=T(Wr=>{"use strict";var lq=Wr&&Wr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),uq=Wr&&Wr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&lq(e,t,n)};Object.defineProperty(Wr,"__esModule",{value:!0});uq(cR(),Wr)});var dR=T(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});_m.TypeSystemPolicy=void 0;var Pm=lR(),uR;(function(t){t.InstanceMode="default",t.ExactOptionalPropertyTypes=!1,t.AllowArrayObject=!1,t.AllowNaN=!1,t.AllowNullVoid=!1;function e(o,a){return t.ExactOptionalPropertyTypes?a in o:o[a]!==void 0}t.IsExactOptionalProperty=e;function n(o){let a=(0,Pm.IsObject)(o);return t.AllowArrayObject?a:a&&!(0,Pm.IsArray)(o)}t.IsObjectLike=n;function i(o){return n(o)&&!(o instanceof Date)&&!(o instanceof Uint8Array)}t.IsRecordLike=i;function s(o){return t.AllowNaN?(0,Pm.IsNumber)(o):Number.isFinite(o)}t.IsNumberLike=s;function r(o){let a=(0,Pm.IsUndefined)(o);return t.AllowNullVoid?a||o===null:a}t.IsVoidLike=r})(uR||(_m.TypeSystemPolicy=uR={}))});var pR=T(Yi=>{"use strict";var dq=Yi&&Yi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),pq=Yi&&Yi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),mq=Yi&&Yi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&dq(n,e,i[s]);return pq(n,e),n}})();Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Immutable=Em;var mu=mq(Ut());function hq(t){return globalThis.Object.freeze(t).map(e=>Em(e))}function gq(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Em(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Em(t[n]);return globalThis.Object.freeze(e)}function Em(t){return mu.IsArray(t)?hq(t):mu.IsDate(t)?t:mu.IsUint8Array(t)?t:mu.IsRegExp(t)?t:mu.IsObject(t)?gq(t):t}});var le=T(Gb=>{"use strict";Object.defineProperty(Gb,"__esModule",{value:!0});Gb.CreateType=yq;var fq=dR(),bq=pR(),xq=tn();function yq(t,e){let n=e!==void 0?{...e,...t}:t;switch(fq.TypeSystemPolicy.InstanceMode){case"freeze":return(0,bq.Immutable)(n);case"clone":return(0,xq.Clone)(n);default:return n}}});var Xi=T(Ur=>{"use strict";var vq=Ur&&Ur.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wq=Ur&&Ur.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vq(e,t,n)};Object.defineProperty(Ur,"__esModule",{value:!0});wq(le(),Ur)});var mR=T(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.TypeBoxError=void 0;var Kb=class extends Error{constructor(e){super(e)}};Am.TypeBoxError=Kb});var xi=T(Fr=>{"use strict";var Sq=Fr&&Fr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cq=Fr&&Fr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Sq(e,t,n)};Object.defineProperty(Fr,"__esModule",{value:!0});Cq(mR(),Fr)});var hu=T(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Kind=Fn.Hint=Fn.OptionalKind=Fn.ReadonlyKind=Fn.TransformKind=void 0;Fn.TransformKind=Symbol.for("TypeBox.Transform");Fn.ReadonlyKind=Symbol.for("TypeBox.Readonly");Fn.OptionalKind=Symbol.for("TypeBox.Optional");Fn.Hint=Symbol.for("TypeBox.Hint");Fn.Kind=Symbol.for("TypeBox.Kind")});var oe=T(Dr=>{"use strict";var Tq=Dr&&Dr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kq=Dr&&Dr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tq(e,t,n)};Object.defineProperty(Dr,"__esModule",{value:!0});kq(hu(),Dr)});var Me=T(re=>{"use strict";var Mq=re&&re.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Iq=re&&re.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Rq=re&&re.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Mq(n,e,i[s]);return Iq(n,e),n}})();Object.defineProperty(re,"__esModule",{value:!0});re.IsReadonly=Pq;re.IsOptional=_q;re.IsAny=hR;re.IsArgument=gR;re.IsArray=fR;re.IsAsyncIterator=bR;re.IsBigInt=xR;re.IsBoolean=yR;re.IsComputed=vR;re.IsConstructor=wR;re.IsDate=SR;re.IsFunction=CR;re.IsImport=Eq;re.IsInteger=TR;re.IsProperties=Aq;re.IsIntersect=kR;re.IsIterator=MR;re.IsKindOf=Se;re.IsLiteralString=Oq;re.IsLiteralNumber=Lq;re.IsLiteralBoolean=Wq;re.IsLiteralValue=Uq;re.IsLiteral=gu;re.IsMappedKey=IR;re.IsMappedResult=RR;re.IsNever=PR;re.IsNot=_R;re.IsNull=ER;re.IsNumber=AR;re.IsObject=OR;re.IsPromise=LR;re.IsRecord=WR;re.IsRecursive=Fq;re.IsRef=UR;re.IsRegExp=FR;re.IsString=DR;re.IsSymbol=$R;re.IsTemplateLiteral=BR;re.IsThis=NR;re.IsTransform=Dq;re.IsTuple=jR;re.IsUndefined=qR;re.IsUnion=GR;re.IsUint8Array=KR;re.IsUnknown=HR;re.IsUnsafe=zR;re.IsVoid=VR;re.IsKind=JR;re.IsSchema=$q;var nn=Rq(Ut()),Zi=oe();function Pq(t){return nn.IsObject(t)&&t[Zi.ReadonlyKind]==="Readonly"}function _q(t){return nn.IsObject(t)&&t[Zi.OptionalKind]==="Optional"}function hR(t){return Se(t,"Any")}function gR(t){return Se(t,"Argument")}function fR(t){return Se(t,"Array")}function bR(t){return Se(t,"AsyncIterator")}function xR(t){return Se(t,"BigInt")}function yR(t){return Se(t,"Boolean")}function vR(t){return Se(t,"Computed")}function wR(t){return Se(t,"Constructor")}function SR(t){return Se(t,"Date")}function CR(t){return Se(t,"Function")}function Eq(t){return Se(t,"Import")}function TR(t){return Se(t,"Integer")}function Aq(t){return nn.IsObject(t)}function kR(t){return Se(t,"Intersect")}function MR(t){return Se(t,"Iterator")}function Se(t,e){return nn.IsObject(t)&&Zi.Kind in t&&t[Zi.Kind]===e}function Oq(t){return gu(t)&&nn.IsString(t.const)}function Lq(t){return gu(t)&&nn.IsNumber(t.const)}function Wq(t){return gu(t)&&nn.IsBoolean(t.const)}function Uq(t){return nn.IsBoolean(t)||nn.IsNumber(t)||nn.IsString(t)}function gu(t){return Se(t,"Literal")}function IR(t){return Se(t,"MappedKey")}function RR(t){return Se(t,"MappedResult")}function PR(t){return Se(t,"Never")}function _R(t){return Se(t,"Not")}function ER(t){return Se(t,"Null")}function AR(t){return Se(t,"Number")}function OR(t){return Se(t,"Object")}function LR(t){return Se(t,"Promise")}function WR(t){return Se(t,"Record")}function Fq(t){return nn.IsObject(t)&&Zi.Hint in t&&t[Zi.Hint]==="Recursive"}function UR(t){return Se(t,"Ref")}function FR(t){return Se(t,"RegExp")}function DR(t){return Se(t,"String")}function $R(t){return Se(t,"Symbol")}function BR(t){return Se(t,"TemplateLiteral")}function NR(t){return Se(t,"This")}function Dq(t){return nn.IsObject(t)&&Zi.TransformKind in t}function jR(t){return Se(t,"Tuple")}function qR(t){return Se(t,"Undefined")}function GR(t){return Se(t,"Union")}function KR(t){return Se(t,"Uint8Array")}function HR(t){return Se(t,"Unknown")}function zR(t){return Se(t,"Unsafe")}function VR(t){return Se(t,"Void")}function JR(t){return nn.IsObject(t)&&Zi.Kind in t&&nn.IsString(t[Zi.Kind])}function $q(t){return hR(t)||gR(t)||fR(t)||yR(t)||xR(t)||bR(t)||vR(t)||wR(t)||SR(t)||CR(t)||TR(t)||kR(t)||MR(t)||gu(t)||IR(t)||RR(t)||PR(t)||_R(t)||ER(t)||AR(t)||OR(t)||LR(t)||WR(t)||UR(t)||FR(t)||DR(t)||$R(t)||BR(t)||NR(t)||jR(t)||qR(t)||GR(t)||KR(t)||HR(t)||zR(t)||VR(t)||JR(t)}});var DP=T(ie=>{"use strict";var Bq=ie&&ie.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Nq=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jq=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Bq(n,e,i[s]);return Nq(n,e),n}})();Object.defineProperty(ie,"__esModule",{value:!0});ie.TypeGuardUnknownTypeError=void 0;ie.IsReadonly=zq;ie.IsOptional=Vq;ie.IsAny=ZR;ie.IsArgument=eP;ie.IsArray=tP;ie.IsAsyncIterator=nP;ie.IsBigInt=iP;ie.IsBoolean=sP;ie.IsComputed=rP;ie.IsConstructor=oP;ie.IsDate=aP;ie.IsFunction=cP;ie.IsImport=Jq;ie.IsInteger=lP;ie.IsProperties=Om;ie.IsIntersect=uP;ie.IsIterator=dP;ie.IsKindOf=Ce;ie.IsLiteralString=pP;ie.IsLiteralNumber=mP;ie.IsLiteralBoolean=Qq;ie.IsLiteral=bu;ie.IsLiteralValue=hP;ie.IsMappedKey=gP;ie.IsMappedResult=fP;ie.IsNever=bP;ie.IsNot=xP;ie.IsNull=yP;ie.IsNumber=vP;ie.IsObject=wP;ie.IsPromise=SP;ie.IsRecord=CP;ie.IsRecursive=Yq;ie.IsRef=TP;ie.IsRegExp=kP;ie.IsString=MP;ie.IsSymbol=IP;ie.IsTemplateLiteral=RP;ie.IsThis=PP;ie.IsTransform=_P;ie.IsTuple=EP;ie.IsUndefined=AP;ie.IsUnionLiteral=Xq;ie.IsUnion=Jb;ie.IsUint8Array=OP;ie.IsUnknown=LP;ie.IsUnsafe=WP;ie.IsVoid=UP;ie.IsKind=FP;ie.IsSchema=yt;var se=jq(Ut()),yi=oe(),qq=xi(),Hb=class extends qq.TypeBoxError{};ie.TypeGuardUnknownTypeError=Hb;var Gq=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function QR(t){try{return new RegExp(t),!0}catch{return!1}}function zb(t){if(!se.IsString(t))return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function YR(t){return Vb(t)||yt(t)}function fu(t){return se.IsUndefined(t)||se.IsBigInt(t)}function Be(t){return se.IsUndefined(t)||se.IsNumber(t)}function Vb(t){return se.IsUndefined(t)||se.IsBoolean(t)}function Ue(t){return se.IsUndefined(t)||se.IsString(t)}function Kq(t){return se.IsUndefined(t)||se.IsString(t)&&zb(t)&&QR(t)}function Hq(t){return se.IsUndefined(t)||se.IsString(t)&&zb(t)}function XR(t){return se.IsUndefined(t)||yt(t)}function zq(t){return se.IsObject(t)&&t[yi.ReadonlyKind]==="Readonly"}function Vq(t){return se.IsObject(t)&&t[yi.OptionalKind]==="Optional"}function ZR(t){return Ce(t,"Any")&&Ue(t.$id)}function eP(t){return Ce(t,"Argument")&&se.IsNumber(t.index)}function tP(t){return Ce(t,"Array")&&t.type==="array"&&Ue(t.$id)&&yt(t.items)&&Be(t.minItems)&&Be(t.maxItems)&&Vb(t.uniqueItems)&&XR(t.contains)&&Be(t.minContains)&&Be(t.maxContains)}function nP(t){return Ce(t,"AsyncIterator")&&t.type==="AsyncIterator"&&Ue(t.$id)&&yt(t.items)}function iP(t){return Ce(t,"BigInt")&&t.type==="bigint"&&Ue(t.$id)&&fu(t.exclusiveMaximum)&&fu(t.exclusiveMinimum)&&fu(t.maximum)&&fu(t.minimum)&&fu(t.multipleOf)}function sP(t){return Ce(t,"Boolean")&&t.type==="boolean"&&Ue(t.$id)}function rP(t){return Ce(t,"Computed")&&se.IsString(t.target)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))}function oP(t){return Ce(t,"Constructor")&&t.type==="Constructor"&&Ue(t.$id)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))&&yt(t.returns)}function aP(t){return Ce(t,"Date")&&t.type==="Date"&&Ue(t.$id)&&Be(t.exclusiveMaximumTimestamp)&&Be(t.exclusiveMinimumTimestamp)&&Be(t.maximumTimestamp)&&Be(t.minimumTimestamp)&&Be(t.multipleOfTimestamp)}function cP(t){return Ce(t,"Function")&&t.type==="Function"&&Ue(t.$id)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))&&yt(t.returns)}function Jq(t){return Ce(t,"Import")&&se.HasPropertyKey(t,"$defs")&&se.IsObject(t.$defs)&&Om(t.$defs)&&se.HasPropertyKey(t,"$ref")&&se.IsString(t.$ref)&&t.$ref in t.$defs}function lP(t){return Ce(t,"Integer")&&t.type==="integer"&&Ue(t.$id)&&Be(t.exclusiveMaximum)&&Be(t.exclusiveMinimum)&&Be(t.maximum)&&Be(t.minimum)&&Be(t.multipleOf)}function Om(t){return se.IsObject(t)&&Object.entries(t).every(([e,n])=>zb(e)&&yt(n))}function uP(t){return Ce(t,"Intersect")&&!(se.IsString(t.type)&&t.type!=="object")&&se.IsArray(t.allOf)&&t.allOf.every(e=>yt(e)&&!_P(e))&&Ue(t.type)&&(Vb(t.unevaluatedProperties)||XR(t.unevaluatedProperties))&&Ue(t.$id)}function dP(t){return Ce(t,"Iterator")&&t.type==="Iterator"&&Ue(t.$id)&&yt(t.items)}function Ce(t,e){return se.IsObject(t)&&yi.Kind in t&&t[yi.Kind]===e}function pP(t){return bu(t)&&se.IsString(t.const)}function mP(t){return bu(t)&&se.IsNumber(t.const)}function Qq(t){return bu(t)&&se.IsBoolean(t.const)}function bu(t){return Ce(t,"Literal")&&Ue(t.$id)&&hP(t.const)}function hP(t){return se.IsBoolean(t)||se.IsNumber(t)||se.IsString(t)}function gP(t){return Ce(t,"MappedKey")&&se.IsArray(t.keys)&&t.keys.every(e=>se.IsNumber(e)||se.IsString(e))}function fP(t){return Ce(t,"MappedResult")&&Om(t.properties)}function bP(t){return Ce(t,"Never")&&se.IsObject(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function xP(t){return Ce(t,"Not")&&yt(t.not)}function yP(t){return Ce(t,"Null")&&t.type==="null"&&Ue(t.$id)}function vP(t){return Ce(t,"Number")&&t.type==="number"&&Ue(t.$id)&&Be(t.exclusiveMaximum)&&Be(t.exclusiveMinimum)&&Be(t.maximum)&&Be(t.minimum)&&Be(t.multipleOf)}function wP(t){return Ce(t,"Object")&&t.type==="object"&&Ue(t.$id)&&Om(t.properties)&&YR(t.additionalProperties)&&Be(t.minProperties)&&Be(t.maxProperties)}function SP(t){return Ce(t,"Promise")&&t.type==="Promise"&&Ue(t.$id)&&yt(t.item)}function CP(t){return Ce(t,"Record")&&t.type==="object"&&Ue(t.$id)&&YR(t.additionalProperties)&&se.IsObject(t.patternProperties)&&(e=>{let n=Object.getOwnPropertyNames(e.patternProperties);return n.length===1&&QR(n[0])&&se.IsObject(e.patternProperties)&&yt(e.patternProperties[n[0]])})(t)}function Yq(t){return se.IsObject(t)&&yi.Hint in t&&t[yi.Hint]==="Recursive"}function TP(t){return Ce(t,"Ref")&&Ue(t.$id)&&se.IsString(t.$ref)}function kP(t){return Ce(t,"RegExp")&&Ue(t.$id)&&se.IsString(t.source)&&se.IsString(t.flags)&&Be(t.maxLength)&&Be(t.minLength)}function MP(t){return Ce(t,"String")&&t.type==="string"&&Ue(t.$id)&&Be(t.minLength)&&Be(t.maxLength)&&Kq(t.pattern)&&Hq(t.format)}function IP(t){return Ce(t,"Symbol")&&t.type==="symbol"&&Ue(t.$id)}function RP(t){return Ce(t,"TemplateLiteral")&&t.type==="string"&&se.IsString(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function PP(t){return Ce(t,"This")&&Ue(t.$id)&&se.IsString(t.$ref)}function _P(t){return se.IsObject(t)&&yi.TransformKind in t}function EP(t){return Ce(t,"Tuple")&&t.type==="array"&&Ue(t.$id)&&se.IsNumber(t.minItems)&&se.IsNumber(t.maxItems)&&t.minItems===t.maxItems&&(se.IsUndefined(t.items)&&se.IsUndefined(t.additionalItems)&&t.minItems===0||se.IsArray(t.items)&&t.items.every(e=>yt(e)))}function AP(t){return Ce(t,"Undefined")&&t.type==="undefined"&&Ue(t.$id)}function Xq(t){return Jb(t)&&t.anyOf.every(e=>pP(e)||mP(e))}function Jb(t){return Ce(t,"Union")&&Ue(t.$id)&&se.IsObject(t)&&se.IsArray(t.anyOf)&&t.anyOf.every(e=>yt(e))}function OP(t){return Ce(t,"Uint8Array")&&t.type==="Uint8Array"&&Ue(t.$id)&&Be(t.minByteLength)&&Be(t.maxByteLength)}function LP(t){return Ce(t,"Unknown")&&Ue(t.$id)}function WP(t){return Ce(t,"Unsafe")}function UP(t){return Ce(t,"Void")&&t.type==="void"&&Ue(t.$id)}function FP(t){return se.IsObject(t)&&yi.Kind in t&&se.IsString(t[yi.Kind])&&!Gq.includes(t[yi.Kind])}function yt(t){return se.IsObject(t)&&(ZR(t)||eP(t)||tP(t)||sP(t)||iP(t)||nP(t)||rP(t)||oP(t)||aP(t)||cP(t)||lP(t)||uP(t)||dP(t)||bu(t)||gP(t)||fP(t)||bP(t)||xP(t)||yP(t)||vP(t)||wP(t)||SP(t)||CP(t)||TP(t)||kP(t)||MP(t)||IP(t)||RP(t)||PP(t)||EP(t)||AP(t)||Jb(t)||OP(t)||LP(t)||WP(t)||UP(t)||FP(t))}});var Yb=T(sn=>{"use strict";var Zq=sn&&sn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),e7=sn&&sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Qb=sn&&sn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Zq(n,e,i[s]);return e7(n,e),n}})();Object.defineProperty(sn,"__esModule",{value:!0});sn.ValueGuard=sn.TypeGuard=sn.KindGuard=void 0;sn.KindGuard=Qb(Me());sn.TypeGuard=Qb(DP());sn.ValueGuard=Qb(Ut())});var $P=T(Xb=>{"use strict";Object.defineProperty(Xb,"__esModule",{value:!0});Xb.Increment=t7;function t7(t){return(parseInt(t)+1).toString()}});var BP=T($r=>{"use strict";var n7=$r&&$r.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),i7=$r&&$r.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&n7(e,t,n)};Object.defineProperty($r,"__esModule",{value:!0});i7($P(),$r)});var NP=T(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.PatternNeverExact=et.PatternStringExact=et.PatternNumberExact=et.PatternBooleanExact=et.PatternNever=et.PatternString=et.PatternNumber=et.PatternBoolean=void 0;et.PatternBoolean="(true|false)";et.PatternNumber="(0|[1-9][0-9]*)";et.PatternString="(.*)";et.PatternNever="(?!.*)";et.PatternBooleanExact=`^${et.PatternBoolean}$`;et.PatternNumberExact=`^${et.PatternNumber}$`;et.PatternStringExact=`^${et.PatternString}$`;et.PatternNeverExact=`^${et.PatternNever}$`});var xu=T(Br=>{"use strict";var s7=Br&&Br.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),r7=Br&&Br.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&s7(e,t,n)};Object.defineProperty(Br,"__esModule",{value:!0});r7(NP(),Br)});var jP=T(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.Entries=o7;Ns.Clear=a7;Ns.Delete=c7;Ns.Has=l7;Ns.Set=u7;Ns.Get=d7;var dc=new Map;function o7(){return new Map(dc)}function a7(){return dc.clear()}function c7(t){return dc.delete(t)}function l7(t){return dc.has(t)}function u7(t,e){dc.set(t,e)}function d7(t){return dc.get(t)}});var qP=T(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.Entries=p7;js.Clear=m7;js.Delete=h7;js.Has=g7;js.Set=f7;js.Get=b7;var pc=new Map;function p7(){return new Map(pc)}function m7(){return pc.clear()}function h7(t){return pc.delete(t)}function g7(t){return pc.has(t)}function f7(t,e){pc.set(t,e)}function b7(t){return pc.get(t)}});var KP=T(Dn=>{"use strict";var x7=Dn&&Dn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),y7=Dn&&Dn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),GP=Dn&&Dn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&x7(n,e,i[s]);return y7(n,e),n}})();Object.defineProperty(Dn,"__esModule",{value:!0});Dn.TypeRegistry=Dn.FormatRegistry=void 0;Dn.FormatRegistry=GP(jP());Dn.TypeRegistry=GP(qP())});var VP=T(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.SetIncludes=HP;vi.SetIsSubset=v7;vi.SetDistinct=w7;vi.SetIntersect=zP;vi.SetUnion=S7;vi.SetComplement=C7;vi.SetIntersectMany=k7;vi.SetUnionMany=M7;function HP(t,e){return t.includes(e)}function v7(t,e){return t.every(n=>HP(e,n))}function w7(t){return[...new Set(t)]}function zP(t,e){return t.filter(n=>e.includes(n))}function S7(t,e){return[...t,...e]}function C7(t,e){return t.filter(n=>!e.includes(n))}function T7(t,e){return t.reduce((n,i)=>zP(n,i),e)}function k7(t){return t.length===1?t[0]:t.length>1?T7(t.slice(1),t[0]):[]}function M7(t){let e=[];for(let n of t)e.push(...n);return e}});var yu=T(Nr=>{"use strict";var I7=Nr&&Nr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),R7=Nr&&Nr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&I7(e,t,n)};Object.defineProperty(Nr,"__esModule",{value:!0});R7(VP(),Nr)});var JP=T(Zb=>{"use strict";Object.defineProperty(Zb,"__esModule",{value:!0});Zb.Any=E7;var P7=Xi(),_7=oe();function E7(t){return(0,P7.CreateType)({[_7.Kind]:"Any"},t)}});var mc=T(jr=>{"use strict";var A7=jr&&jr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),O7=jr&&jr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&A7(e,t,n)};Object.defineProperty(jr,"__esModule",{value:!0});O7(JP(),jr)});var QP=T(ex=>{"use strict";Object.defineProperty(ex,"__esModule",{value:!0});ex.Array=U7;var L7=le(),W7=oe();function U7(t,e){return(0,L7.CreateType)({[W7.Kind]:"Array",type:"array",items:t},e)}});var hc=T(qr=>{"use strict";var F7=qr&&qr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),D7=qr&&qr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&F7(e,t,n)};Object.defineProperty(qr,"__esModule",{value:!0});D7(QP(),qr)});var YP=T(tx=>{"use strict";Object.defineProperty(tx,"__esModule",{value:!0});tx.Argument=N7;var $7=le(),B7=oe();function N7(t){return(0,$7.CreateType)({[B7.Kind]:"Argument",index:t})}});var Lm=T(Gr=>{"use strict";var j7=Gr&&Gr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),q7=Gr&&Gr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&j7(e,t,n)};Object.defineProperty(Gr,"__esModule",{value:!0});q7(YP(),Gr)});var XP=T(nx=>{"use strict";Object.defineProperty(nx,"__esModule",{value:!0});nx.AsyncIterator=H7;var G7=oe(),K7=le();function H7(t,e){return(0,K7.CreateType)({[G7.Kind]:"AsyncIterator",type:"AsyncIterator",items:t},e)}});var gc=T(Kr=>{"use strict";var z7=Kr&&Kr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),V7=Kr&&Kr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&z7(e,t,n)};Object.defineProperty(Kr,"__esModule",{value:!0});V7(XP(),Kr)});var ZP=T(ix=>{"use strict";Object.defineProperty(ix,"__esModule",{value:!0});ix.Computed=Y7;var J7=Xi(),Q7=hu();function Y7(t,e,n){return(0,J7.CreateType)({[Q7.Kind]:"Computed",target:t,parameters:e},n)}});var qs=T(Hr=>{"use strict";var X7=Hr&&Hr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Z7=Hr&&Hr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&X7(e,t,n)};Object.defineProperty(Hr,"__esModule",{value:!0});Z7(ZP(),Hr)});var Wm=T(sx=>{"use strict";Object.defineProperty(sx,"__esModule",{value:!0});sx.Discard=tG;function eG(t,e){let{[e]:n,...i}=t;return i}function tG(t,e){return e.reduce((n,i)=>eG(n,i),t)}});var es=T(zr=>{"use strict";var nG=zr&&zr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),iG=zr&&zr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&nG(e,t,n)};Object.defineProperty(zr,"__esModule",{value:!0});iG(Wm(),zr)});var e_=T(rx=>{"use strict";Object.defineProperty(rx,"__esModule",{value:!0});rx.Never=oG;var sG=le(),rG=oe();function oG(t){return(0,sG.CreateType)({[rG.Kind]:"Never",not:{}},t)}});var vt=T(Vr=>{"use strict";var aG=Vr&&Vr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),cG=Vr&&Vr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aG(e,t,n)};Object.defineProperty(Vr,"__esModule",{value:!0});cG(e_(),Vr)});var t_=T(ox=>{"use strict";Object.defineProperty(ox,"__esModule",{value:!0});ox.MappedKey=dG;var lG=le(),uG=oe();function dG(t){return(0,lG.CreateType)({[uG.Kind]:"MappedKey",keys:t})}});var cx=T(ax=>{"use strict";Object.defineProperty(ax,"__esModule",{value:!0});ax.MappedResult=hG;var pG=le(),mG=oe();function hG(t){return(0,pG.CreateType)({[mG.Kind]:"MappedResult",properties:t})}});var n_=T(lx=>{"use strict";Object.defineProperty(lx,"__esModule",{value:!0});lx.Constructor=bG;var gG=le(),fG=oe();function bG(t,e,n){return(0,gG.CreateType)({[fG.Kind]:"Constructor",type:"Constructor",parameters:t,returns:e},n)}});var fc=T(Jr=>{"use strict";var xG=Jr&&Jr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),yG=Jr&&Jr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xG(e,t,n)};Object.defineProperty(Jr,"__esModule",{value:!0});yG(n_(),Jr)});var i_=T(ux=>{"use strict";Object.defineProperty(ux,"__esModule",{value:!0});ux.Function=SG;var vG=le(),wG=oe();function SG(t,e,n){return(0,vG.CreateType)({[wG.Kind]:"Function",type:"Function",parameters:t,returns:e},n)}});var Gs=T(Qr=>{"use strict";var CG=Qr&&Qr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),TG=Qr&&Qr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&CG(e,t,n)};Object.defineProperty(Qr,"__esModule",{value:!0});TG(i_(),Qr)});var px=T(dx=>{"use strict";Object.defineProperty(dx,"__esModule",{value:!0});dx.UnionCreate=IG;var kG=le(),MG=oe();function IG(t,e){return(0,kG.CreateType)({[MG.Kind]:"Union",anyOf:t},e)}});var a_=T(mx=>{"use strict";Object.defineProperty(mx,"__esModule",{value:!0});mx.UnionEvaluated=UG;var RG=le(),PG=oe(),_G=es(),EG=vt(),AG=wi(),s_=px(),o_=Me();function OG(t){return t.some(e=>(0,o_.IsOptional)(e))}function r_(t){return t.map(e=>(0,o_.IsOptional)(e)?LG(e):e)}function LG(t){return(0,_G.Discard)(t,[PG.OptionalKind])}function WG(t,e){return OG(t)?(0,AG.Optional)((0,s_.UnionCreate)(r_(t),e)):(0,s_.UnionCreate)(r_(t),e)}function UG(t,e){return t.length===1?(0,RG.CreateType)(t[0],e):t.length===0?(0,EG.Never)(e):WG(t,e)}});var l_=T(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var oPe=oe()});var u_=T(hx=>{"use strict";Object.defineProperty(hx,"__esModule",{value:!0});hx.Union=BG;var FG=vt(),DG=le(),$G=px();function BG(t,e){return t.length===0?(0,FG.Never)(e):t.length===1?(0,DG.CreateType)(t[0],e):(0,$G.UnionCreate)(t,e)}});var st=T(ts=>{"use strict";var NG=ts&&ts.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),gx=ts&&ts.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&NG(e,t,n)};Object.defineProperty(ts,"__esModule",{value:!0});gx(a_(),ts);gx(l_(),ts);gx(u_(),ts)});var Um=T(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.TemplateLiteralParserError=void 0;bc.TemplateLiteralParse=Yr;bc.TemplateLiteralParseExact=QG;var jG=xi(),vu=class extends jG.TypeBoxError{};bc.TemplateLiteralParserError=vu;function qG(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function fx(t,e,n){return t[e]===n&&t.charCodeAt(e-1)!==92}function ns(t,e){return fx(t,e,"(")}function wu(t,e){return fx(t,e,")")}function d_(t,e){return fx(t,e,"|")}function GG(t){if(!(ns(t,0)&&wu(t,t.length-1)))return!1;let e=0;for(let n=0;n<t.length;n++)if(ns(t,n)&&(e+=1),wu(t,n)&&(e-=1),e===0&&n!==t.length-1)return!1;return!0}function KG(t){return t.slice(1,t.length-1)}function HG(t){let e=0;for(let n=0;n<t.length;n++)if(ns(t,n)&&(e+=1),wu(t,n)&&(e-=1),d_(t,n)&&e===0)return!0;return!1}function zG(t){for(let e=0;e<t.length;e++)if(ns(t,e))return!0;return!1}function VG(t){let[e,n]=[0,0],i=[];for(let r=0;r<t.length;r++)if(ns(t,r)&&(e+=1),wu(t,r)&&(e-=1),d_(t,r)&&e===0){let o=t.slice(n,r);o.length>0&&i.push(Yr(o)),n=r+1}let s=t.slice(n);return s.length>0&&i.push(Yr(s)),i.length===0?{type:"const",const:""}:i.length===1?i[0]:{type:"or",expr:i}}function JG(t){function e(s,r){if(!ns(s,r))throw new vu("TemplateLiteralParser: Index must point to open parens");let o=0;for(let a=r;a<s.length;a++)if(ns(s,a)&&(o+=1),wu(s,a)&&(o-=1),o===0)return[r,a];throw new vu("TemplateLiteralParser: Unclosed group parens in expression")}function n(s,r){for(let o=r;o<s.length;o++)if(ns(s,o))return[r,o];return[r,s.length]}let i=[];for(let s=0;s<t.length;s++)if(ns(t,s)){let[r,o]=e(t,s),a=t.slice(r,o+1);i.push(Yr(a)),s=o}else{let[r,o]=n(t,s),a=t.slice(r,o);a.length>0&&i.push(Yr(a)),s=o-1}return i.length===0?{type:"const",const:""}:i.length===1?i[0]:{type:"and",expr:i}}function Yr(t){return GG(t)?Yr(KG(t)):HG(t)?VG(t):zG(t)?JG(t):{type:"const",const:qG(t)}}function QG(t){return Yr(t.slice(1,t.length-1))}});var bx=T(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.TemplateLiteralFiniteError=void 0;xc.IsTemplateLiteralExpressionFinite=Dm;xc.IsTemplateLiteralFinite=nK;var YG=Um(),XG=xi(),Fm=class extends XG.TypeBoxError{};xc.TemplateLiteralFiniteError=Fm;function ZG(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="0"&&t.expr[1].type==="const"&&t.expr[1].const==="[1-9][0-9]*"}function eK(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="true"&&t.expr[1].type==="const"&&t.expr[1].const==="false"}function tK(t){return t.type==="const"&&t.const===".*"}function Dm(t){return ZG(t)||tK(t)?!1:eK(t)?!0:t.type==="and"?t.expr.every(e=>Dm(e)):t.type==="or"?t.expr.every(e=>Dm(e)):t.type==="const"?!0:(()=>{throw new Fm("Unknown expression type")})()}function nK(t){let e=(0,YG.TemplateLiteralParseExact)(t.pattern);return Dm(e)}});var xx=T(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.TemplateLiteralGenerateError=void 0;yc.TemplateLiteralExpressionGenerate=Bm;yc.TemplateLiteralGenerate=lK;var iK=bx(),sK=Um(),rK=xi(),$m=class extends rK.TypeBoxError{};yc.TemplateLiteralGenerateError=$m;function*p_(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let n of p_(t.slice(1)))yield`${e}${n}`}function*oK(t){return yield*p_(t.expr.map(e=>[...Bm(e)]))}function*aK(t){for(let e of t.expr)yield*Bm(e)}function*cK(t){return yield t.const}function*Bm(t){return t.type==="and"?yield*oK(t):t.type==="or"?yield*aK(t):t.type==="const"?yield*cK(t):(()=>{throw new $m("Unknown expression")})()}function lK(t){let e=(0,sK.TemplateLiteralParseExact)(t.pattern);return(0,iK.IsTemplateLiteralExpressionFinite)(e)?[...Bm(e)]:[]}});var m_=T(yx=>{"use strict";Object.defineProperty(yx,"__esModule",{value:!0});yx.Literal=pK;var uK=le(),dK=oe();function pK(t,e){return(0,uK.CreateType)({[dK.Kind]:"Literal",const:t,type:typeof t},e)}});var Ft=T(Xr=>{"use strict";var mK=Xr&&Xr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),hK=Xr&&Xr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&mK(e,t,n)};Object.defineProperty(Xr,"__esModule",{value:!0});hK(m_(),Xr)});var h_=T(vx=>{"use strict";Object.defineProperty(vx,"__esModule",{value:!0});vx.Boolean=bK;var gK=oe(),fK=Xi();function bK(t){return(0,fK.CreateType)({[gK.Kind]:"Boolean",type:"boolean"},t)}});var Su=T(Zr=>{"use strict";var xK=Zr&&Zr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),yK=Zr&&Zr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xK(e,t,n)};Object.defineProperty(Zr,"__esModule",{value:!0});yK(h_(),Zr)});var g_=T(wx=>{"use strict";Object.defineProperty(wx,"__esModule",{value:!0});wx.BigInt=SK;var vK=oe(),wK=Xi();function SK(t){return(0,wK.CreateType)({[vK.Kind]:"BigInt",type:"bigint"},t)}});var vc=T(eo=>{"use strict";var CK=eo&&eo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),TK=eo&&eo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&CK(e,t,n)};Object.defineProperty(eo,"__esModule",{value:!0});TK(g_(),eo)});var f_=T(Sx=>{"use strict";Object.defineProperty(Sx,"__esModule",{value:!0});Sx.Number=IK;var kK=le(),MK=oe();function IK(t){return(0,kK.CreateType)({[MK.Kind]:"Number",type:"number"},t)}});var Ks=T(to=>{"use strict";var RK=to&&to.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),PK=to&&to.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&RK(e,t,n)};Object.defineProperty(to,"__esModule",{value:!0});PK(f_(),to)});var b_=T(Cx=>{"use strict";Object.defineProperty(Cx,"__esModule",{value:!0});Cx.String=AK;var _K=le(),EK=oe();function AK(t){return(0,_K.CreateType)({[EK.Kind]:"String",type:"string"},t)}});var io=T(no=>{"use strict";var OK=no&&no.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),LK=no&&no.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&OK(e,t,n)};Object.defineProperty(no,"__esModule",{value:!0});LK(b_(),no)});var Mx=T(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});kx.TemplateLiteralSyntax=qK;var Cu=Ft(),WK=Su(),UK=vc(),FK=Ks(),DK=io(),$K=st(),BK=vt();function*NK(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield(0,WK.Boolean)():e==="number"?yield(0,FK.Number)():e==="bigint"?yield(0,UK.BigInt)():e==="string"?yield(0,DK.String)():yield(()=>{let n=e.split("|").map(i=>(0,Cu.Literal)(i.trim()));return n.length===0?(0,BK.Never)():n.length===1?n[0]:(0,$K.UnionEvaluated)(n)})()}function*jK(t){if(t[1]!=="{"){let e=(0,Cu.Literal)("$"),n=Tx(t.slice(1));return yield*[e,...n]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let n=NK(t.slice(2,e)),i=Tx(t.slice(e+1));return yield*[...n,...i]}yield(0,Cu.Literal)(t)}function*Tx(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let n=(0,Cu.Literal)(t.slice(0,e)),i=jK(t.slice(e));return yield*[n,...i]}yield(0,Cu.Literal)(t)}function qK(t){return[...Tx(t)]}});var Ix=T(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.TemplateLiteralPatternError=void 0;ku.TemplateLiteralPattern=zK;var Tu=xu(),GK=oe(),KK=xi(),Hs=Me(),Nm=class extends KK.TypeBoxError{};ku.TemplateLiteralPatternError=Nm;function HK(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x_(t,e){return(0,Hs.IsTemplateLiteral)(t)?t.pattern.slice(1,t.pattern.length-1):(0,Hs.IsUnion)(t)?`(${t.anyOf.map(n=>x_(n,e)).join("|")})`:(0,Hs.IsNumber)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsInteger)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsBigInt)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsString)(t)?`${e}${Tu.PatternString}`:(0,Hs.IsLiteral)(t)?`${e}${HK(t.const.toString())}`:(0,Hs.IsBoolean)(t)?`${e}${Tu.PatternBoolean}`:(()=>{throw new Nm(`Unexpected Kind '${t[GK.Kind]}'`)})()}function zK(t){return`^${t.map(e=>x_(e,"")).join("")}$`}});var y_=T(Rx=>{"use strict";Object.defineProperty(Rx,"__esModule",{value:!0});Rx.TemplateLiteralToUnion=YK;var VK=st(),JK=Ft(),QK=xx();function YK(t){let n=(0,QK.TemplateLiteralGenerate)(t).map(i=>(0,JK.Literal)(i));return(0,VK.UnionEvaluated)(n)}});var w_=T(Px=>{"use strict";Object.defineProperty(Px,"__esModule",{value:!0});Px.TemplateLiteral=nH;var XK=le(),ZK=Mx(),v_=Ix(),eH=Ut(),tH=oe();function nH(t,e){let n=(0,eH.IsString)(t)?(0,v_.TemplateLiteralPattern)((0,ZK.TemplateLiteralSyntax)(t)):(0,v_.TemplateLiteralPattern)(t);return(0,XK.CreateType)({[tH.Kind]:"TemplateLiteral",type:"string",pattern:n},e)}});var Si=T(Sn=>{"use strict";var iH=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),so=Sn&&Sn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iH(e,t,n)};Object.defineProperty(Sn,"__esModule",{value:!0});so(bx(),Sn);so(xx(),Sn);so(Mx(),Sn);so(Um(),Sn);so(Ix(),Sn);so(y_(),Sn);so(w_(),Sn)});var jm=T(_x=>{"use strict";Object.defineProperty(_x,"__esModule",{value:!0});_x.IndexPropertyKeys=S_;var sH=Si(),Mu=Me();function rH(t){return(0,sH.TemplateLiteralGenerate)(t).map(n=>n.toString())}function oH(t){let e=[];for(let n of t)e.push(...S_(n));return e}function aH(t){return[t.toString()]}function S_(t){return[...new Set((0,Mu.IsTemplateLiteral)(t)?rH(t):(0,Mu.IsUnion)(t)?oH(t.anyOf):(0,Mu.IsLiteral)(t)?aH(t.const):(0,Mu.IsNumber)(t)?["[number]"]:(0,Mu.IsInteger)(t)?["[number]"]:[])]}});var Ax=T(Ex=>{"use strict";Object.defineProperty(Ex,"__esModule",{value:!0});Ex.IndexFromMappedResult=mH;var cH=ot(),lH=jm(),uH=ti();function dH(t,e,n){let i={};for(let s of Object.getOwnPropertyNames(e))i[s]=(0,uH.Index)(t,(0,lH.IndexPropertyKeys)(e[s]),n);return i}function pH(t,e,n){return dH(t,e.properties,n)}function mH(t,e,n){let i=pH(t,e,n);return(0,cH.MappedResult)(i)}});var Gm=T(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.IndexFromPropertyKey=Lx;wc.IndexFromPropertyKeys=M_;wc.IndexFromComputed=IH;wc.Index=RH;var hH=le(),gH=xi(),T_=qs(),qm=vt(),fH=Cn(),Ox=st(),bH=jm(),xH=Wx(),yH=Ax(),rn=Me();function k_(t,e){return t.map(n=>Lx(n,e))}function vH(t){return t.filter(e=>!(0,rn.IsNever)(e))}function wH(t,e){return(0,fH.IntersectEvaluated)(vH(k_(t,e)))}function SH(t){return t.some(e=>(0,rn.IsNever)(e))?[]:t}function CH(t,e){return(0,Ox.UnionEvaluated)(SH(k_(t,e)))}function TH(t,e){return e in t?t[e]:e==="[number]"?(0,Ox.UnionEvaluated)(t):(0,qm.Never)()}function kH(t,e){return e==="[number]"?t:(0,qm.Never)()}function MH(t,e){return e in t?t[e]:(0,qm.Never)()}function Lx(t,e){return(0,rn.IsIntersect)(t)?wH(t.allOf,e):(0,rn.IsUnion)(t)?CH(t.anyOf,e):(0,rn.IsTuple)(t)?TH(t.items??[],e):(0,rn.IsArray)(t)?kH(t.items,e):(0,rn.IsObject)(t)?MH(t.properties,e):(0,qm.Never)()}function M_(t,e){return e.map(n=>Lx(t,n))}function C_(t,e){return(0,Ox.UnionEvaluated)(M_(t,e))}function IH(t,e){return(0,T_.Computed)("Index",[t,e])}function RH(t,e,n){if((0,rn.IsRef)(t)||(0,rn.IsRef)(e)){let i="Index types using Ref parameters require both Type and Key to be of TSchema";if(!(0,rn.IsSchema)(t)||!(0,rn.IsSchema)(e))throw new gH.TypeBoxError(i);return(0,T_.Computed)("Index",[t,e])}return(0,rn.IsMappedResult)(e)?(0,yH.IndexFromMappedResult)(t,e,n):(0,rn.IsMappedKey)(e)?(0,xH.IndexFromMappedKey)(t,e,n):(0,hH.CreateType)((0,rn.IsSchema)(e)?C_(t,(0,bH.IndexPropertyKeys)(e)):C_(t,e),n)}});var Wx=T(Ux=>{"use strict";Object.defineProperty(Ux,"__esModule",{value:!0});Ux.IndexFromMappedKey=WH;var PH=Gm(),_H=ot(),EH=tn();function AH(t,e,n){return{[e]:(0,PH.Index)(t,[e],(0,EH.Clone)(n))}}function OH(t,e,n){return e.reduce((i,s)=>({...i,...AH(t,s,n)}),{})}function LH(t,e,n){return OH(t,e.keys,n)}function WH(t,e,n){let i=LH(t,e,n);return(0,_H.MappedResult)(i)}});var ti=T(Ci=>{"use strict";var UH=Ci&&Ci.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Km=Ci&&Ci.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&UH(e,t,n)};Object.defineProperty(Ci,"__esModule",{value:!0});Km(Wx(),Ci);Km(Ax(),Ci);Km(jm(),Ci);Km(Gm(),Ci)});var I_=T(Fx=>{"use strict";Object.defineProperty(Fx,"__esModule",{value:!0});Fx.Iterator=$H;var FH=le(),DH=oe();function $H(t,e){return(0,FH.CreateType)({[DH.Kind]:"Iterator",type:"Iterator",items:t},e)}});var Sc=T(ro=>{"use strict";var BH=ro&&ro.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),NH=ro&&ro.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&BH(e,t,n)};Object.defineProperty(ro,"__esModule",{value:!0});NH(I_(),ro)});var P_=T(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});Hm.Object=void 0;var jH=le(),R_=oe(),qH=Me();function GH(t){return globalThis.Object.keys(t).filter(e=>!(0,qH.IsOptional)(t[e]))}function KH(t,e){let n=GH(t),i=n.length>0?{[R_.Kind]:"Object",type:"object",required:n,properties:t}:{[R_.Kind]:"Object",type:"object",properties:t};return(0,jH.CreateType)(i,e)}Hm.Object=KH});var on=T(oo=>{"use strict";var HH=oo&&oo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),zH=oo&&oo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HH(e,t,n)};Object.defineProperty(oo,"__esModule",{value:!0});zH(P_(),oo)});var __=T(Dx=>{"use strict";Object.defineProperty(Dx,"__esModule",{value:!0});Dx.Promise=QH;var VH=le(),JH=oe();function QH(t,e){return(0,VH.CreateType)({[JH.Kind]:"Promise",type:"Promise",item:t},e)}});var Iu=T(ao=>{"use strict";var YH=ao&&ao.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),XH=ao&&ao.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&YH(e,t,n)};Object.defineProperty(ao,"__esModule",{value:!0});XH(__(),ao)});var Bx=T($x=>{"use strict";Object.defineProperty($x,"__esModule",{value:!0});$x.Readonly=rz;var E_=le(),A_=oe(),ZH=es(),ez=Nx(),tz=Me();function nz(t){return(0,E_.CreateType)((0,ZH.Discard)(t,[A_.ReadonlyKind]))}function iz(t){return(0,E_.CreateType)({...t,[A_.ReadonlyKind]:"Readonly"})}function sz(t,e){return e===!1?nz(t):iz(t)}function rz(t,e){let n=e??!0;return(0,tz.IsMappedResult)(t)?(0,ez.ReadonlyFromMappedResult)(t,n):sz(t,n)}});var Nx=T(jx=>{"use strict";Object.defineProperty(jx,"__esModule",{value:!0});jx.ReadonlyFromMappedResult=uz;var oz=ot(),az=Bx();function cz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,az.Readonly)(t[i],e);return n}function lz(t,e){return cz(t.properties,e)}function uz(t,e){let n=lz(t,e);return(0,oz.MappedResult)(n)}});var Vs=T(zs=>{"use strict";var dz=zs&&zs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),O_=zs&&zs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&dz(e,t,n)};Object.defineProperty(zs,"__esModule",{value:!0});O_(Nx(),zs);O_(Bx(),zs)});var W_=T(qx=>{"use strict";Object.defineProperty(qx,"__esModule",{value:!0});qx.Tuple=mz;var pz=le(),L_=oe();function mz(t,e){return(0,pz.CreateType)(t.length>0?{[L_.Kind]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[L_.Kind]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}});var is=T(co=>{"use strict";var hz=co&&co.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),gz=co&&co.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&hz(e,t,n)};Object.defineProperty(co,"__esModule",{value:!0});gz(W_(),co)});var N_=T(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.MappedFunctionReturnType=B_;zm.Mapped=Wz;var Gx=oe(),U_=es(),fz=hc(),bz=gc(),xz=fc(),yz=Gs(),vz=ti(),wz=Cn(),Sz=Sc(),F_=Ft(),D_=on(),Cz=wi(),Tz=Iu(),kz=Vs(),Mz=is(),Iz=st(),Rz=yu(),Pz=cx(),Dt=Me();function $_(t,e){return t in e?$n(t,e[t]):(0,Pz.MappedResult)(e)}function _z(t){return{[t]:(0,F_.Literal)(t)}}function Ez(t){let e={};for(let n of t)e[n]=(0,F_.Literal)(n);return e}function Az(t,e){return(0,Rz.SetIncludes)(e,t)?_z(t):Ez(e)}function Oz(t,e){let n=Az(t,e);return $_(t,n)}function Ru(t,e){return e.map(n=>$n(t,n))}function Lz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(e))n[i]=$n(t,e[i]);return n}function $n(t,e){let n={...e};return(0,Dt.IsOptional)(e)?(0,Cz.Optional)($n(t,(0,U_.Discard)(e,[Gx.OptionalKind]))):(0,Dt.IsReadonly)(e)?(0,kz.Readonly)($n(t,(0,U_.Discard)(e,[Gx.ReadonlyKind]))):(0,Dt.IsMappedResult)(e)?$_(t,e.properties):(0,Dt.IsMappedKey)(e)?Oz(t,e.keys):(0,Dt.IsConstructor)(e)?(0,xz.Constructor)(Ru(t,e.parameters),$n(t,e.returns),n):(0,Dt.IsFunction)(e)?(0,yz.Function)(Ru(t,e.parameters),$n(t,e.returns),n):(0,Dt.IsAsyncIterator)(e)?(0,bz.AsyncIterator)($n(t,e.items),n):(0,Dt.IsIterator)(e)?(0,Sz.Iterator)($n(t,e.items),n):(0,Dt.IsIntersect)(e)?(0,wz.Intersect)(Ru(t,e.allOf),n):(0,Dt.IsUnion)(e)?(0,Iz.Union)(Ru(t,e.anyOf),n):(0,Dt.IsTuple)(e)?(0,Mz.Tuple)(Ru(t,e.items??[]),n):(0,Dt.IsObject)(e)?(0,D_.Object)(Lz(t,e.properties),n):(0,Dt.IsArray)(e)?(0,fz.Array)($n(t,e.items),n):(0,Dt.IsPromise)(e)?(0,Tz.Promise)($n(t,e.item),n):e}function B_(t,e){let n={};for(let i of t)n[i]=$n(i,e);return n}function Wz(t,e,n){let i=(0,Dt.IsSchema)(t)?(0,vz.IndexPropertyKeys)(t):t,s=e({[Gx.Kind]:"MappedKey",keys:i}),r=B_(i,s);return(0,D_.Object)(r,n)}});var ot=T(ss=>{"use strict";var Uz=ss&&ss.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Kx=ss&&ss.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Uz(e,t,n)};Object.defineProperty(ss,"__esModule",{value:!0});Kx(t_(),ss);Kx(cx(),ss);Kx(N_(),ss)});var zx=T(Hx=>{"use strict";Object.defineProperty(Hx,"__esModule",{value:!0});Hx.Optional=qz;var j_=le(),q_=oe(),Fz=es(),Dz=Vx(),$z=Me();function Bz(t){return(0,j_.CreateType)((0,Fz.Discard)(t,[q_.OptionalKind]))}function Nz(t){return(0,j_.CreateType)({...t,[q_.OptionalKind]:"Optional"})}function jz(t,e){return e===!1?Bz(t):Nz(t)}function qz(t,e){let n=e??!0;return(0,$z.IsMappedResult)(t)?(0,Dz.OptionalFromMappedResult)(t,n):jz(t,n)}});var Vx=T(Jx=>{"use strict";Object.defineProperty(Jx,"__esModule",{value:!0});Jx.OptionalFromMappedResult=Vz;var Gz=ot(),Kz=zx();function Hz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,Kz.Optional)(t[i],e);return n}function zz(t,e){return Hz(t.properties,e)}function Vz(t,e){let n=zz(t,e);return(0,Gz.MappedResult)(n)}});var wi=T(Js=>{"use strict";var Jz=Js&&Js.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),G_=Js&&Js.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Jz(e,t,n)};Object.defineProperty(Js,"__esModule",{value:!0});G_(Vx(),Js);G_(zx(),Js)});var Xx=T(Yx=>{"use strict";Object.defineProperty(Yx,"__esModule",{value:!0});Yx.IntersectCreate=Yz;var Qz=le(),K_=oe(),Qx=Me();function Yz(t,e={}){let n=t.every(s=>(0,Qx.IsObject)(s)),i=(0,Qx.IsSchema)(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return(0,Qz.CreateType)(e.unevaluatedProperties===!1||(0,Qx.IsSchema)(e.unevaluatedProperties)||n?{...i,[K_.Kind]:"Intersect",type:"object",allOf:t}:{...i,[K_.Kind]:"Intersect",allOf:t},e)}});var V_=T(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});ey.IntersectEvaluated=oV;var Xz=oe(),Zz=le(),eV=es(),tV=vt(),nV=wi(),H_=Xx(),Zx=Me();function iV(t){return t.every(e=>(0,Zx.IsOptional)(e))}function sV(t){return(0,eV.Discard)(t,[Xz.OptionalKind])}function z_(t){return t.map(e=>(0,Zx.IsOptional)(e)?sV(e):e)}function rV(t,e){return iV(t)?(0,nV.Optional)((0,H_.IntersectCreate)(z_(t),e)):(0,H_.IntersectCreate)(z_(t),e)}function oV(t,e={}){if(t.length===1)return(0,Zz.CreateType)(t[0],e);if(t.length===0)return(0,tV.Never)(e);if(t.some(n=>(0,Zx.IsTransform)(n)))throw new Error("Cannot intersect transform types");return rV(t,e)}});var Q_=T(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});var YPe=oe()});var Y_=T(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});ty.Intersect=dV;var aV=le(),cV=vt(),lV=Xx(),uV=Me();function dV(t,e){if(t.length===1)return(0,aV.CreateType)(t[0],e);if(t.length===0)return(0,cV.Never)(e);if(t.some(n=>(0,uV.IsTransform)(n)))throw new Error("Cannot intersect transform types");return(0,lV.IntersectCreate)(t,e)}});var Cn=T(rs=>{"use strict";var pV=rs&&rs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ny=rs&&rs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&pV(e,t,n)};Object.defineProperty(rs,"__esModule",{value:!0});ny(V_(),rs);ny(Q_(),rs);ny(Y_(),rs)});var X_=T(iy=>{"use strict";Object.defineProperty(iy,"__esModule",{value:!0});iy.Ref=fV;var mV=xi(),hV=le(),gV=oe();function fV(...t){let[e,n]=typeof t[0]=="string"?[t[0],t[1]]:[t[0].$id,t[1]];if(typeof e!="string")throw new mV.TypeBoxError("Ref: $ref must be a string");return(0,hV.CreateType)({[gV.Kind]:"Ref",$ref:e},n)}});var Qs=T(lo=>{"use strict";var bV=lo&&lo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xV=lo&&lo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bV(e,t,n)};Object.defineProperty(lo,"__esModule",{value:!0});xV(X_(),lo)});var eE=T(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});oy.Awaited=ry;var yV=le(),sy=qs(),vV=Cn(),wV=st(),SV=Qs(),Pu=Me();function CV(t,e){return(0,sy.Computed)("Awaited",[(0,sy.Computed)(t,e)])}function TV(t){return(0,sy.Computed)("Awaited",[(0,SV.Ref)(t)])}function kV(t){return(0,vV.Intersect)(Z_(t))}function MV(t){return(0,wV.Union)(Z_(t))}function IV(t){return ry(t)}function Z_(t){return t.map(e=>ry(e))}function ry(t,e){return(0,yV.CreateType)((0,Pu.IsComputed)(t)?CV(t.target,t.parameters):(0,Pu.IsIntersect)(t)?kV(t.allOf):(0,Pu.IsUnion)(t)?MV(t.anyOf):(0,Pu.IsPromise)(t)?IV(t.item):(0,Pu.IsRef)(t)?TV(t.$ref):t,e)}});var _u=T(uo=>{"use strict";var RV=uo&&uo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),PV=uo&&uo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&RV(e,t,n)};Object.defineProperty(uo,"__esModule",{value:!0});PV(eE(),uo)});var Jm=T(Vm=>{"use strict";Object.defineProperty(Vm,"__esModule",{value:!0});Vm.KeyOfPropertyKeys=cy;Vm.KeyOfPattern=UV;var tE=yu(),Cc=Me();function nE(t){let e=[];for(let n of t)e.push(cy(n));return e}function _V(t){let e=nE(t);return(0,tE.SetUnionMany)(e)}function EV(t){let e=nE(t);return(0,tE.SetIntersectMany)(e)}function AV(t){return t.map((e,n)=>n.toString())}function OV(t){return["[number]"]}function LV(t){return globalThis.Object.getOwnPropertyNames(t)}function WV(t){return ay?globalThis.Object.getOwnPropertyNames(t).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function cy(t){return(0,Cc.IsIntersect)(t)?_V(t.allOf):(0,Cc.IsUnion)(t)?EV(t.anyOf):(0,Cc.IsTuple)(t)?AV(t.items??[]):(0,Cc.IsArray)(t)?OV(t.items):(0,Cc.IsObject)(t)?LV(t.properties):(0,Cc.IsRecord)(t)?WV(t.patternProperties):[]}var ay=!1;function UV(t){ay=!0;let e=cy(t);return ay=!1,`^(${e.map(i=>`(${i})`).join("|")})$`}});var dy=T(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});Qm.KeyOfPropertyKeysToRest=iE;Qm.KeyOf=zV;var FV=le(),DV=Ft(),$V=Ks(),uy=qs(),BV=Qs(),NV=Jm(),jV=st(),qV=py(),ly=Me();function GV(t,e){return(0,uy.Computed)("KeyOf",[(0,uy.Computed)(t,e)])}function KV(t){return(0,uy.Computed)("KeyOf",[(0,BV.Ref)(t)])}function HV(t,e){let n=(0,NV.KeyOfPropertyKeys)(t),i=iE(n),s=(0,jV.UnionEvaluated)(i);return(0,FV.CreateType)(s,e)}function iE(t){return t.map(e=>e==="[number]"?(0,$V.Number)():(0,DV.Literal)(e))}function zV(t,e){return(0,ly.IsComputed)(t)?GV(t.target,t.parameters):(0,ly.IsRef)(t)?KV(t.$ref):(0,ly.IsMappedResult)(t)?(0,qV.KeyOfFromMappedResult)(t,e):HV(t,e)}});var py=T(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});my.KeyOfFromMappedResult=ZV;var VV=ot(),JV=dy(),QV=tn();function YV(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,JV.KeyOf)(t[i],(0,QV.Clone)(e));return n}function XV(t,e){return YV(t.properties,e)}function ZV(t,e){let n=XV(t,e);return(0,VV.MappedResult)(n)}});var sE=T(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});hy.KeyOfPropertyEntries=nJ;var eJ=Gm(),tJ=Jm();function nJ(t){let e=(0,tJ.KeyOfPropertyKeys)(t),n=(0,eJ.IndexFromPropertyKeys)(t,e);return e.map((i,s)=>[e[s],n[s]])}});var Tc=T(Ti=>{"use strict";var iJ=Ti&&Ti.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ym=Ti&&Ti.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iJ(e,t,n)};Object.defineProperty(Ti,"__esModule",{value:!0});Ym(py(),Ti);Ym(sE(),Ti);Ym(Jm(),Ti);Ym(dy(),Ti)});var rE=T(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});gy.Composite=hJ;var sJ=Cn(),rJ=ti(),oJ=Tc(),aJ=on(),cJ=yu(),lJ=Me();function uJ(t){let e=[];for(let n of t)e.push(...(0,oJ.KeyOfPropertyKeys)(n));return(0,cJ.SetDistinct)(e)}function dJ(t){return t.filter(e=>!(0,lJ.IsNever)(e))}function pJ(t,e){let n=[];for(let i of t)n.push(...(0,rJ.IndexFromPropertyKeys)(i,[e]));return dJ(n)}function mJ(t,e){let n={};for(let i of e)n[i]=(0,sJ.IntersectEvaluated)(pJ(t,i));return n}function hJ(t,e){let n=uJ(t),i=mJ(t,n);return(0,aJ.Object)(i,e)}});var Xm=T(po=>{"use strict";var gJ=po&&po.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),fJ=po&&po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gJ(e,t,n)};Object.defineProperty(po,"__esModule",{value:!0});fJ(rE(),po)});var oE=T(fy=>{"use strict";Object.defineProperty(fy,"__esModule",{value:!0});fy.Date=yJ;var bJ=oe(),xJ=le();function yJ(t){return(0,xJ.CreateType)({[bJ.Kind]:"Date",type:"Date"},t)}});var Eu=T(mo=>{"use strict";var vJ=mo&&mo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wJ=mo&&mo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vJ(e,t,n)};Object.defineProperty(mo,"__esModule",{value:!0});wJ(oE(),mo)});var aE=T(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});by.Null=TJ;var SJ=le(),CJ=oe();function TJ(t){return(0,SJ.CreateType)({[CJ.Kind]:"Null",type:"null"},t)}});var Au=T(ho=>{"use strict";var kJ=ho&&ho.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),MJ=ho&&ho.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&kJ(e,t,n)};Object.defineProperty(ho,"__esModule",{value:!0});MJ(aE(),ho)});var cE=T(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});xy.Symbol=PJ;var IJ=le(),RJ=oe();function PJ(t){return(0,IJ.CreateType)({[RJ.Kind]:"Symbol",type:"symbol"},t)}});var Ou=T(go=>{"use strict";var _J=go&&go.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),EJ=go&&go.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_J(e,t,n)};Object.defineProperty(go,"__esModule",{value:!0});EJ(cE(),go)});var lE=T(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});yy.Undefined=LJ;var AJ=le(),OJ=oe();function LJ(t){return(0,AJ.CreateType)({[OJ.Kind]:"Undefined",type:"undefined"},t)}});var Lu=T(fo=>{"use strict";var WJ=fo&&fo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),UJ=fo&&fo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WJ(e,t,n)};Object.defineProperty(fo,"__esModule",{value:!0});UJ(lE(),fo)});var uE=T(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});vy.Uint8Array=$J;var FJ=le(),DJ=oe();function $J(t){return(0,FJ.CreateType)({[DJ.Kind]:"Uint8Array",type:"Uint8Array"},t)}});var Wu=T(bo=>{"use strict";var BJ=bo&&bo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),NJ=bo&&bo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&BJ(e,t,n)};Object.defineProperty(bo,"__esModule",{value:!0});NJ(uE(),bo)});var dE=T(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});wy.Unknown=GJ;var jJ=le(),qJ=oe();function GJ(t){return(0,jJ.CreateType)({[qJ.Kind]:"Unknown"},t)}});var yo=T(xo=>{"use strict";var KJ=xo&&xo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),HJ=xo&&xo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&KJ(e,t,n)};Object.defineProperty(xo,"__esModule",{value:!0});HJ(dE(),xo)});var hE=T(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});ky.Const=rQ;var pE=mc(),zJ=vc(),VJ=Eu(),JJ=Gs(),Sy=Ft(),QJ=Au(),mE=on(),YJ=Ou(),XJ=is(),Cy=Vs(),ZJ=Lu(),eQ=Wu(),tQ=yo(),nQ=Xi(),an=Ut();function iQ(t){return t.map(e=>Ty(e,!1))}function sQ(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,Cy.Readonly)(Ty(t[n],!1));return e}function Zm(t,e){return e===!0?t:(0,Cy.Readonly)(t)}function Ty(t,e){return(0,an.IsAsyncIterator)(t)||(0,an.IsIterator)(t)?Zm((0,pE.Any)(),e):(0,an.IsArray)(t)?(0,Cy.Readonly)((0,XJ.Tuple)(iQ(t))):(0,an.IsUint8Array)(t)?(0,eQ.Uint8Array)():(0,an.IsDate)(t)?(0,VJ.Date)():(0,an.IsObject)(t)?Zm((0,mE.Object)(sQ(t)),e):(0,an.IsFunction)(t)?Zm((0,JJ.Function)([],(0,tQ.Unknown)()),e):(0,an.IsUndefined)(t)?(0,ZJ.Undefined)():(0,an.IsNull)(t)?(0,QJ.Null)():(0,an.IsSymbol)(t)?(0,YJ.Symbol)():(0,an.IsBigInt)(t)?(0,zJ.BigInt)():(0,an.IsNumber)(t)||(0,an.IsBoolean)(t)||(0,an.IsString)(t)?(0,Sy.Literal)(t):(0,mE.Object)({})}function rQ(t,e){return(0,nQ.CreateType)(Ty(t,!0),e)}});var eh=T(vo=>{"use strict";var oQ=vo&&vo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),aQ=vo&&vo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&oQ(e,t,n)};Object.defineProperty(vo,"__esModule",{value:!0});aQ(hE(),vo)});var gE=T(os=>{"use strict";var cQ=os&&os.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),lQ=os&&os.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uQ=os&&os.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&cQ(n,e,i[s]);return lQ(n,e),n}})();Object.defineProperty(os,"__esModule",{value:!0});os.ConstructorParameters=hQ;var dQ=is(),pQ=vt(),mQ=uQ(Me());function hQ(t,e){return mQ.IsConstructor(t)?(0,dQ.Tuple)(t.parameters,e):(0,pQ.Never)(e)}});var th=T(wo=>{"use strict";var gQ=wo&&wo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),fQ=wo&&wo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gQ(e,t,n)};Object.defineProperty(wo,"__esModule",{value:!0});fQ(gE(),wo)});var fE=T(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});My.Enum=wQ;var bQ=Ft(),xQ=oe(),yQ=st(),vQ=Ut();function wQ(t,e){if((0,vQ.IsUndefined)(t))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(t).filter(r=>isNaN(r)).map(r=>t[r]),s=[...new Set(n)].map(r=>(0,bQ.Literal)(r));return(0,yQ.Union)(s,{...e,[xQ.Hint]:"Enum"})}});var nh=T(So=>{"use strict";var SQ=So&&So.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),CQ=So&&So.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&SQ(e,t,n)};Object.defineProperty(So,"__esModule",{value:!0});CQ(fE(),So)});var Ly=T(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.ExtendsResult=Co.ExtendsResolverError=void 0;Co.ExtendsCheck=pY;var bE=mc(),TQ=Gs(),Ey=Ks(),Ry=io(),kQ=yo(),xE=Si(),kc=xu(),CE=oe(),MQ=xi(),k=Yb(),ih=class extends MQ.TypeBoxError{};Co.ExtendsResolverError=ih;var B;(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(B||(Co.ExtendsResult=B={}));function Bn(t){return t===B.False?t:B.True}function Mc(t){throw new ih(t)}function at(t){return k.TypeGuard.IsNever(t)||k.TypeGuard.IsIntersect(t)||k.TypeGuard.IsUnion(t)||k.TypeGuard.IsUnknown(t)||k.TypeGuard.IsAny(t)}function ct(t,e){return k.TypeGuard.IsNever(e)?ME(t,e):k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsUnknown(e)?_E(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):Mc("StructuralRight")}function Ay(t,e){return B.True}function IQ(t,e){return k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)&&e.anyOf.some(n=>k.TypeGuard.IsAny(n)||k.TypeGuard.IsUnknown(n))?B.True:k.TypeGuard.IsUnion(e)?B.Union:k.TypeGuard.IsUnknown(e)||k.TypeGuard.IsAny(e)?B.True:B.Union}function RQ(t,e){return k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:k.TypeGuard.IsNever(t)?B.True:B.False}function PQ(t,e){return k.TypeGuard.IsObject(e)&&rh(e)?B.True:at(e)?ct(t,e):k.TypeGuard.IsArray(e)?Bn(Fe(t.items,e.items)):B.False}function _Q(t,e){return at(e)?ct(t,e):k.TypeGuard.IsAsyncIterator(e)?Bn(Fe(t.items,e.items)):B.False}function EQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsBigInt(e)?B.True:B.False}function TE(t,e){return k.TypeGuard.IsLiteralBoolean(t)||k.TypeGuard.IsBoolean(t)?B.True:B.False}function AQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsBoolean(e)?B.True:B.False}function OQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsConstructor(e)?t.parameters.length>e.parameters.length?B.False:t.parameters.every((n,i)=>Bn(Fe(e.parameters[i],n))===B.True)?Bn(Fe(t.returns,e.returns)):B.False:B.False}function LQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsDate(e)?B.True:B.False}function WQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsFunction(e)?t.parameters.length>e.parameters.length?B.False:t.parameters.every((n,i)=>Bn(Fe(e.parameters[i],n))===B.True)?Bn(Fe(t.returns,e.returns)):B.False:B.False}function kE(t,e){return k.TypeGuard.IsLiteral(t)&&k.ValueGuard.IsNumber(t.const)||k.TypeGuard.IsNumber(t)||k.TypeGuard.IsInteger(t)?B.True:B.False}function UQ(t,e){return k.TypeGuard.IsInteger(e)||k.TypeGuard.IsNumber(e)?B.True:at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):B.False}function sh(t,e){return e.allOf.every(n=>Fe(t,n)===B.True)?B.True:B.False}function FQ(t,e){return t.allOf.some(n=>Fe(n,e)===B.True)?B.True:B.False}function DQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsIterator(e)?Bn(Fe(t.items,e.items)):B.False}function $Q(t,e){return k.TypeGuard.IsLiteral(e)&&e.const===t.const?B.True:at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsString(e)?PE(t,e):k.TypeGuard.IsNumber(e)?IE(t,e):k.TypeGuard.IsInteger(e)?kE(t,e):k.TypeGuard.IsBoolean(e)?TE(t,e):B.False}function ME(t,e){return B.False}function BQ(t,e){return B.True}function yE(t){let[e,n]=[t,0];for(;k.TypeGuard.IsNot(e);)e=e.not,n+=1;return n%2===0?e:(0,kQ.Unknown)()}function NQ(t,e){return k.TypeGuard.IsNot(t)?Fe(yE(t),e):k.TypeGuard.IsNot(e)?Fe(t,yE(e)):Mc("Invalid fallthrough for Not")}function jQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsNull(e)?B.True:B.False}function IE(t,e){return k.TypeGuard.IsLiteralNumber(t)||k.TypeGuard.IsNumber(t)||k.TypeGuard.IsInteger(t)?B.True:B.False}function qQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsInteger(e)||k.TypeGuard.IsNumber(e)?B.True:B.False}function cn(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function vE(t){return rh(t)}function wE(t){return cn(t,0)||cn(t,1)&&"description"in t.properties&&k.TypeGuard.IsUnion(t.properties.description)&&t.properties.description.anyOf.length===2&&(k.TypeGuard.IsString(t.properties.description.anyOf[0])&&k.TypeGuard.IsUndefined(t.properties.description.anyOf[1])||k.TypeGuard.IsString(t.properties.description.anyOf[1])&&k.TypeGuard.IsUndefined(t.properties.description.anyOf[0]))}function Iy(t){return cn(t,0)}function SE(t){return cn(t,0)}function GQ(t){return cn(t,0)}function KQ(t){return cn(t,0)}function HQ(t){return rh(t)}function zQ(t){let e=(0,Ey.Number)();return cn(t,0)||cn(t,1)&&"length"in t.properties&&Bn(Fe(t.properties.length,e))===B.True}function VQ(t){return cn(t,0)}function rh(t){let e=(0,Ey.Number)();return cn(t,0)||cn(t,1)&&"length"in t.properties&&Bn(Fe(t.properties.length,e))===B.True}function JQ(t){let e=(0,TQ.Function)([(0,bE.Any)()],(0,bE.Any)());return cn(t,0)||cn(t,1)&&"then"in t.properties&&Bn(Fe(t.properties.then,e))===B.True}function RE(t,e){return Fe(t,e)===B.False||k.TypeGuard.IsOptional(t)&&!k.TypeGuard.IsOptional(e)?B.False:B.True}function Et(t,e){return k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:k.TypeGuard.IsNever(t)||k.TypeGuard.IsLiteralString(t)&&vE(e)||k.TypeGuard.IsLiteralNumber(t)&&Iy(e)||k.TypeGuard.IsLiteralBoolean(t)&&SE(e)||k.TypeGuard.IsSymbol(t)&&wE(e)||k.TypeGuard.IsBigInt(t)&&GQ(e)||k.TypeGuard.IsString(t)&&vE(e)||k.TypeGuard.IsSymbol(t)&&wE(e)||k.TypeGuard.IsNumber(t)&&Iy(e)||k.TypeGuard.IsInteger(t)&&Iy(e)||k.TypeGuard.IsBoolean(t)&&SE(e)||k.TypeGuard.IsUint8Array(t)&&HQ(e)||k.TypeGuard.IsDate(t)&&KQ(e)||k.TypeGuard.IsConstructor(t)&&VQ(e)||k.TypeGuard.IsFunction(t)&&zQ(e)?B.True:k.TypeGuard.IsRecord(t)&&k.TypeGuard.IsString(Py(t))?e[CE.Hint]==="Record"?B.True:B.False:k.TypeGuard.IsRecord(t)&&k.TypeGuard.IsNumber(Py(t))&&cn(e,0)?B.True:B.False}function QQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsObject(e)?(()=>{for(let n of Object.getOwnPropertyNames(e.properties)){if(!(n in t.properties)&&!k.TypeGuard.IsOptional(e.properties[n]))return B.False;if(k.TypeGuard.IsOptional(e.properties[n]))return B.True;if(RE(t.properties[n],e.properties[n])===B.False)return B.False}return B.True})():B.False}function YQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)&&JQ(e)?B.True:k.TypeGuard.IsPromise(e)?Bn(Fe(t.item,e.item)):B.False}function Py(t){return kc.PatternNumberExact in t.patternProperties?(0,Ey.Number)():kc.PatternStringExact in t.patternProperties?(0,Ry.String)():Mc("Unknown record key pattern")}function _y(t){return kc.PatternNumberExact in t.patternProperties?t.patternProperties[kc.PatternNumberExact]:kc.PatternStringExact in t.patternProperties?t.patternProperties[kc.PatternStringExact]:Mc("Unable to get record value schema")}function Nn(t,e){let[n,i]=[Py(e),_y(e)];return k.TypeGuard.IsLiteralString(t)&&k.TypeGuard.IsNumber(n)&&Bn(Fe(t,i))===B.True?B.True:k.TypeGuard.IsUint8Array(t)&&k.TypeGuard.IsNumber(n)||k.TypeGuard.IsString(t)&&k.TypeGuard.IsNumber(n)||k.TypeGuard.IsArray(t)&&k.TypeGuard.IsNumber(n)?Fe(t,i):k.TypeGuard.IsObject(t)?(()=>{for(let s of Object.getOwnPropertyNames(t.properties))if(RE(i,t.properties[s])===B.False)return B.False;return B.True})():B.False}function XQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Fe(_y(t),_y(e)):B.False}function ZQ(t,e){let n=k.TypeGuard.IsRegExp(t)?(0,Ry.String)():t,i=k.TypeGuard.IsRegExp(e)?(0,Ry.String)():e;return Fe(n,i)}function PE(t,e){return k.TypeGuard.IsLiteral(t)&&k.ValueGuard.IsString(t.const)||k.TypeGuard.IsString(t)?B.True:B.False}function eY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsString(e)?B.True:B.False}function tY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsSymbol(e)?B.True:B.False}function nY(t,e){return k.TypeGuard.IsTemplateLiteral(t)?Fe((0,xE.TemplateLiteralToUnion)(t),e):k.TypeGuard.IsTemplateLiteral(e)?Fe(t,(0,xE.TemplateLiteralToUnion)(e)):Mc("Invalid fallthrough for TemplateLiteral")}function iY(t,e){return k.TypeGuard.IsArray(e)&&t.items!==void 0&&t.items.every(n=>Fe(n,e.items)===B.True)}function sY(t,e){return k.TypeGuard.IsNever(t)?B.True:k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:B.False}function rY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)&&rh(e)||k.TypeGuard.IsArray(e)&&iY(t,e)?B.True:k.TypeGuard.IsTuple(e)?k.ValueGuard.IsUndefined(t.items)&&!k.ValueGuard.IsUndefined(e.items)||!k.ValueGuard.IsUndefined(t.items)&&k.ValueGuard.IsUndefined(e.items)?B.False:k.ValueGuard.IsUndefined(t.items)&&!k.ValueGuard.IsUndefined(e.items)||t.items.every((n,i)=>Fe(n,e.items[i])===B.True)?B.True:B.False:B.False}function oY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsUint8Array(e)?B.True:B.False}function aY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsVoid(e)?uY(t,e):k.TypeGuard.IsUndefined(e)?B.True:B.False}function Oy(t,e){return e.anyOf.some(n=>Fe(t,n)===B.True)?B.True:B.False}function cY(t,e){return t.anyOf.every(n=>Fe(n,e)===B.True)?B.True:B.False}function _E(t,e){return B.True}function lY(t,e){return k.TypeGuard.IsNever(e)?ME(t,e):k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):k.TypeGuard.IsString(e)?PE(t,e):k.TypeGuard.IsNumber(e)?IE(t,e):k.TypeGuard.IsInteger(e)?kE(t,e):k.TypeGuard.IsBoolean(e)?TE(t,e):k.TypeGuard.IsArray(e)?RQ(t,e):k.TypeGuard.IsTuple(e)?sY(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsUnknown(e)?B.True:B.False}function uY(t,e){return k.TypeGuard.IsUndefined(t)||k.TypeGuard.IsUndefined(t)?B.True:B.False}function dY(t,e){return k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsUnknown(e)?_E(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsVoid(e)?B.True:B.False}function Fe(t,e){return k.TypeGuard.IsTemplateLiteral(t)||k.TypeGuard.IsTemplateLiteral(e)?nY(t,e):k.TypeGuard.IsRegExp(t)||k.TypeGuard.IsRegExp(e)?ZQ(t,e):k.TypeGuard.IsNot(t)||k.TypeGuard.IsNot(e)?NQ(t,e):k.TypeGuard.IsAny(t)?IQ(t,e):k.TypeGuard.IsArray(t)?PQ(t,e):k.TypeGuard.IsBigInt(t)?EQ(t,e):k.TypeGuard.IsBoolean(t)?AQ(t,e):k.TypeGuard.IsAsyncIterator(t)?_Q(t,e):k.TypeGuard.IsConstructor(t)?OQ(t,e):k.TypeGuard.IsDate(t)?LQ(t,e):k.TypeGuard.IsFunction(t)?WQ(t,e):k.TypeGuard.IsInteger(t)?UQ(t,e):k.TypeGuard.IsIntersect(t)?FQ(t,e):k.TypeGuard.IsIterator(t)?DQ(t,e):k.TypeGuard.IsLiteral(t)?$Q(t,e):k.TypeGuard.IsNever(t)?BQ(t,e):k.TypeGuard.IsNull(t)?jQ(t,e):k.TypeGuard.IsNumber(t)?qQ(t,e):k.TypeGuard.IsObject(t)?QQ(t,e):k.TypeGuard.IsRecord(t)?XQ(t,e):k.TypeGuard.IsString(t)?eY(t,e):k.TypeGuard.IsSymbol(t)?tY(t,e):k.TypeGuard.IsTuple(t)?rY(t,e):k.TypeGuard.IsPromise(t)?YQ(t,e):k.TypeGuard.IsUint8Array(t)?oY(t,e):k.TypeGuard.IsUndefined(t)?aY(t,e):k.TypeGuard.IsUnion(t)?cY(t,e):k.TypeGuard.IsUnknown(t)?lY(t,e):k.TypeGuard.IsVoid(t)?dY(t,e):Mc(`Unknown left type operand '${t[CE.Kind]}'`)}function pY(t,e){return Fe(t,e)}});var Uy=T(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});Wy.ExtendsFromMappedResult=xY;var mY=ot(),hY=oh(),gY=tn();function fY(t,e,n,i,s){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=(0,hY.Extends)(t[o],e,n,i,(0,gY.Clone)(s));return r}function bY(t,e,n,i,s){return fY(t.properties,e,n,i,s)}function xY(t,e,n,i,s){let r=bY(t,e,n,i,s);return(0,mY.MappedResult)(r)}});var oh=T(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});Dy.Extends=CY;var EE=le(),yY=st(),Fy=Ly(),vY=$y(),wY=Uy(),AE=Me();function SY(t,e,n,i){let s=(0,Fy.ExtendsCheck)(t,e);return s===Fy.ExtendsResult.Union?(0,yY.Union)([n,i]):s===Fy.ExtendsResult.True?n:i}function CY(t,e,n,i,s){return(0,AE.IsMappedResult)(t)?(0,wY.ExtendsFromMappedResult)(t,e,n,i,s):(0,AE.IsMappedKey)(t)?(0,EE.CreateType)((0,vY.ExtendsFromMappedKey)(t,e,n,i,s)):(0,EE.CreateType)(SY(t,e,n,i),s)}});var $y=T(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});By.ExtendsFromMappedKey=EY;var TY=ot(),kY=Ft(),MY=oh(),IY=tn();function RY(t,e,n,i,s){return{[t]:(0,MY.Extends)((0,kY.Literal)(t),e,n,i,(0,IY.Clone)(s))}}function PY(t,e,n,i,s){return t.reduce((r,o)=>({...r,...RY(o,e,n,i,s)}),{})}function _Y(t,e,n,i,s){return PY(t.keys,e,n,i,s)}function EY(t,e,n,i,s){let r=_Y(t,e,n,i,s);return(0,TY.MappedResult)(r)}});var OE=T(Ny=>{"use strict";Object.defineProperty(Ny,"__esModule",{value:!0});Ny.ExtendsUndefinedCheck=ch;var ah=oe();function AY(t){return t.allOf.every(e=>ch(e))}function OY(t){return t.anyOf.some(e=>ch(e))}function LY(t){return!ch(t.not)}function ch(t){return t[ah.Kind]==="Intersect"?AY(t):t[ah.Kind]==="Union"?OY(t):t[ah.Kind]==="Not"?LY(t):t[ah.Kind]==="Undefined"}});var Ic=T(ni=>{"use strict";var WY=ni&&ni.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Uu=ni&&ni.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WY(e,t,n)};Object.defineProperty(ni,"__esModule",{value:!0});Uu(Ly(),ni);Uu($y(),ni);Uu(Uy(),ni);Uu(OE(),ni);Uu(oh(),ni)});var qy=T(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});jy.ExcludeFromTemplateLiteral=DY;var UY=lh(),FY=Si();function DY(t,e){return(0,UY.Exclude)((0,FY.TemplateLiteralToUnion)(t),e)}});var lh=T(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});Hy.Exclude=GY;var Gy=le(),$Y=st(),BY=vt(),uh=Ic(),NY=zy(),jY=qy(),Ky=Me();function qY(t,e){let n=t.filter(i=>(0,uh.ExtendsCheck)(i,e)===uh.ExtendsResult.False);return n.length===1?n[0]:(0,$Y.Union)(n)}function GY(t,e,n={}){return(0,Ky.IsTemplateLiteral)(t)?(0,Gy.CreateType)((0,jY.ExcludeFromTemplateLiteral)(t,e),n):(0,Ky.IsMappedResult)(t)?(0,Gy.CreateType)((0,NY.ExcludeFromMappedResult)(t,e),n):(0,Gy.CreateType)((0,Ky.IsUnion)(t)?qY(t.anyOf,e):(0,uh.ExtendsCheck)(t,e)!==uh.ExtendsResult.False?(0,BY.Never)():t,n)}});var zy=T(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});Vy.ExcludeFromMappedResult=JY;var KY=ot(),HY=lh();function zY(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,HY.Exclude)(t[i],e);return n}function VY(t,e){return zY(t.properties,e)}function JY(t,e){let n=VY(t,e);return(0,KY.MappedResult)(n)}});var dh=T(as=>{"use strict";var QY=as&&as.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Jy=as&&as.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&QY(e,t,n)};Object.defineProperty(as,"__esModule",{value:!0});Jy(zy(),as);Jy(qy(),as);Jy(lh(),as)});var Yy=T(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});Qy.ExtractFromTemplateLiteral=ZY;var YY=ph(),XY=Si();function ZY(t,e){return(0,YY.Extract)((0,XY.TemplateLiteralToUnion)(t),e)}});var ph=T(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});ev.Extract=rX;var Xy=le(),eX=st(),tX=vt(),mh=Ic(),nX=tv(),iX=Yy(),Zy=Me();function sX(t,e){let n=t.filter(i=>(0,mh.ExtendsCheck)(i,e)!==mh.ExtendsResult.False);return n.length===1?n[0]:(0,eX.Union)(n)}function rX(t,e,n){return(0,Zy.IsTemplateLiteral)(t)?(0,Xy.CreateType)((0,iX.ExtractFromTemplateLiteral)(t,e),n):(0,Zy.IsMappedResult)(t)?(0,Xy.CreateType)((0,nX.ExtractFromMappedResult)(t,e),n):(0,Xy.CreateType)((0,Zy.IsUnion)(t)?sX(t.anyOf,e):(0,mh.ExtendsCheck)(t,e)!==mh.ExtendsResult.False?t:(0,tX.Never)(),n)}});var tv=T(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});nv.ExtractFromMappedResult=uX;var oX=ot(),aX=ph();function cX(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,aX.Extract)(t[i],e);return n}function lX(t,e){return cX(t.properties,e)}function uX(t,e){let n=lX(t,e);return(0,oX.MappedResult)(n)}});var hh=T(cs=>{"use strict";var dX=cs&&cs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),iv=cs&&cs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&dX(e,t,n)};Object.defineProperty(cs,"__esModule",{value:!0});iv(tv(),cs);iv(Yy(),cs);iv(ph(),cs)});var LE=T(ls=>{"use strict";var pX=ls&&ls.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),mX=ls&&ls.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hX=ls&&ls.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&pX(n,e,i[s]);return mX(n,e),n}})();Object.defineProperty(ls,"__esModule",{value:!0});ls.InstanceType=xX;var gX=le(),fX=vt(),bX=hX(Me());function xX(t,e){return bX.IsConstructor(t)?(0,gX.CreateType)(t.returns,e):(0,fX.Never)(e)}});var gh=T(To=>{"use strict";var yX=To&&To.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),vX=To&&To.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yX(e,t,n)};Object.defineProperty(To,"__esModule",{value:!0});vX(LE(),To)});var WE=T(sv=>{"use strict";Object.defineProperty(sv,"__esModule",{value:!0});sv.ReadonlyOptional=CX;var wX=Vs(),SX=wi();function CX(t){return(0,wX.Readonly)((0,SX.Optional)(t))}});var Fu=T(ko=>{"use strict";var TX=ko&&ko.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kX=ko&&ko.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&TX(e,t,n)};Object.defineProperty(ko,"__esModule",{value:!0});kX(WE(),ko)});var BE=T(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.Record=jX;Rc.RecordPattern=ov;Rc.RecordKey=qX;Rc.RecordValue=GX;var MX=le(),FE=oe(),IX=vt(),RX=Ks(),DE=on(),UE=io(),PX=st(),_X=Si(),Mo=xu(),$E=ti(),EX=Ut(),ki=Me();function Io(t,e,n){return(0,MX.CreateType)({[FE.Kind]:"Record",type:"object",patternProperties:{[t]:e}},n)}function rv(t,e,n){let i={};for(let s of t)i[s]=e;return(0,DE.Object)(i,{...n,[FE.Hint]:"Record"})}function AX(t,e,n){return(0,_X.IsTemplateLiteralFinite)(t)?rv((0,$E.IndexPropertyKeys)(t),e,n):Io(t.pattern,e,n)}function OX(t,e,n){return rv((0,$E.IndexPropertyKeys)((0,PX.Union)(t)),e,n)}function LX(t,e,n){return rv([t.toString()],e,n)}function WX(t,e,n){return Io(t.source,e,n)}function UX(t,e,n){let i=(0,EX.IsUndefined)(t.pattern)?Mo.PatternStringExact:t.pattern;return Io(i,e,n)}function FX(t,e,n){return Io(Mo.PatternStringExact,e,n)}function DX(t,e,n){return Io(Mo.PatternNeverExact,e,n)}function $X(t,e,n){return(0,DE.Object)({true:e,false:e},n)}function BX(t,e,n){return Io(Mo.PatternNumberExact,e,n)}function NX(t,e,n){return Io(Mo.PatternNumberExact,e,n)}function jX(t,e,n={}){return(0,ki.IsUnion)(t)?OX(t.anyOf,e,n):(0,ki.IsTemplateLiteral)(t)?AX(t,e,n):(0,ki.IsLiteral)(t)?LX(t.const,e,n):(0,ki.IsBoolean)(t)?$X(t,e,n):(0,ki.IsInteger)(t)?BX(t,e,n):(0,ki.IsNumber)(t)?NX(t,e,n):(0,ki.IsRegExp)(t)?WX(t,e,n):(0,ki.IsString)(t)?UX(t,e,n):(0,ki.IsAny)(t)?FX(t,e,n):(0,ki.IsNever)(t)?DX(t,e,n):(0,IX.Never)(n)}function ov(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function qX(t){let e=ov(t);return e===Mo.PatternStringExact?(0,UE.String)():e===Mo.PatternNumberExact?(0,RX.Number)():(0,UE.String)({pattern:e})}function GX(t){return t.patternProperties[ov(t)]}});var Pc=T(Ro=>{"use strict";var KX=Ro&&Ro.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),HX=Ro&&Ro.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&KX(e,t,n)};Object.defineProperty(Ro,"__esModule",{value:!0});HX(BE(),Ro)});var jE=T(Mi=>{"use strict";var zX=Mi&&Mi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),VX=Mi&&Mi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),NE=Mi&&Mi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&zX(n,e,i[s]);return VX(n,e),n}})();Object.defineProperty(Mi,"__esModule",{value:!0});Mi.FromTypes=_c;Mi.Instantiate=fZ;var JX=Rm(),QX=yo(),YX=Fu(),XX=Vs(),ZX=wi(),eZ=on(),av=Pc(),tZ=NE(Ut()),ln=NE(Me());function nZ(t,e){return e.parameters=_c(t,e.parameters),e.returns=ii(t,e.returns),e}function iZ(t,e){return e.parameters=_c(t,e.parameters),e.returns=ii(t,e.returns),e}function sZ(t,e){return e.allOf=_c(t,e.allOf),e}function rZ(t,e){return e.anyOf=_c(t,e.anyOf),e}function oZ(t,e){return tZ.IsUndefined(e.items)||(e.items=_c(t,e.items)),e}function aZ(t,e){return e.items=ii(t,e.items),e}function cZ(t,e){return e.items=ii(t,e.items),e}function lZ(t,e){return e.items=ii(t,e.items),e}function uZ(t,e){return e.item=ii(t,e.item),e}function dZ(t,e){let n=gZ(t,e.properties);return{...e,...(0,eZ.Object)(n)}}function pZ(t,e){let n=ii(t,(0,av.RecordKey)(e)),i=ii(t,(0,av.RecordValue)(e)),s=(0,av.Record)(n,i);return{...e,...s}}function mZ(t,e){return e.index in t?t[e.index]:(0,QX.Unknown)()}function hZ(t,e){let n=ln.IsReadonly(e),i=ln.IsOptional(e),s=ii(t,e);return n&&i?(0,YX.ReadonlyOptional)(s):n&&!i?(0,XX.Readonly)(s):!n&&i?(0,ZX.Optional)(s):s}function gZ(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,i)=>({...n,[i]:hZ(t,e[i])}),{})}function _c(t,e){return e.map(n=>ii(t,n))}function ii(t,e){return ln.IsConstructor(e)?nZ(t,e):ln.IsFunction(e)?iZ(t,e):ln.IsIntersect(e)?sZ(t,e):ln.IsUnion(e)?rZ(t,e):ln.IsTuple(e)?oZ(t,e):ln.IsArray(e)?aZ(t,e):ln.IsAsyncIterator(e)?cZ(t,e):ln.IsIterator(e)?lZ(t,e):ln.IsPromise(e)?uZ(t,e):ln.IsObject(e)?dZ(t,e):ln.IsRecord(e)?pZ(t,e):ln.IsArgument(e)?mZ(t,e):e}function fZ(t,e){return ii(e,(0,JX.CloneType)(t))}});var fh=T(Po=>{"use strict";var bZ=Po&&Po.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xZ=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bZ(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});xZ(jE(),Po)});var qE=T(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});cv.Integer=wZ;var yZ=le(),vZ=oe();function wZ(t){return(0,yZ.CreateType)({[vZ.Kind]:"Integer",type:"integer"},t)}});var bh=T(_o=>{"use strict";var SZ=_o&&_o.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),CZ=_o&&_o.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&SZ(e,t,n)};Object.defineProperty(_o,"__esModule",{value:!0});CZ(qE(),_o)});var uv=T(lv=>{"use strict";Object.defineProperty(lv,"__esModule",{value:!0});lv.IntrinsicFromMappedKey=EZ;var TZ=ot(),kZ=Eo(),MZ=Ft(),IZ=tn();function RZ(t,e,n){return{[t]:(0,kZ.Intrinsic)((0,MZ.Literal)(t),e,(0,IZ.Clone)(n))}}function PZ(t,e,n){return t.reduce((s,r)=>({...s,...RZ(r,e,n)}),{})}function _Z(t,e,n){return PZ(t.keys,e,n)}function EZ(t,e,n){let i=_Z(t,e,n);return(0,TZ.MappedResult)(i)}});var Eo=T(dv=>{"use strict";Object.defineProperty(dv,"__esModule",{value:!0});dv.Intrinsic=VE;var AZ=le(),xh=Si(),OZ=uv(),GE=Ft(),KE=st(),yh=Me();function LZ(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),n].join("")}function WZ(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),n].join("")}function UZ(t){return t.toUpperCase()}function FZ(t){return t.toLowerCase()}function DZ(t,e,n){let i=(0,xh.TemplateLiteralParseExact)(t.pattern);if(!(0,xh.IsTemplateLiteralExpressionFinite)(i))return{...t,pattern:HE(t.pattern,e)};let o=[...(0,xh.TemplateLiteralExpressionGenerate)(i)].map(l=>(0,GE.Literal)(l)),a=zE(o,e),c=(0,KE.Union)(a);return(0,xh.TemplateLiteral)([c],n)}function HE(t,e){return typeof t=="string"?e==="Uncapitalize"?LZ(t):e==="Capitalize"?WZ(t):e==="Uppercase"?UZ(t):e==="Lowercase"?FZ(t):t:t.toString()}function zE(t,e){return t.map(n=>VE(n,e))}function VE(t,e,n={}){return(0,yh.IsMappedKey)(t)?(0,OZ.IntrinsicFromMappedKey)(t,e,n):(0,yh.IsTemplateLiteral)(t)?DZ(t,e,n):(0,yh.IsUnion)(t)?(0,KE.Union)(zE(t.anyOf,e),n):(0,yh.IsLiteral)(t)?(0,GE.Literal)(HE(t.const,e),n):(0,AZ.CreateType)(t,n)}});var JE=T(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});pv.Capitalize=BZ;var $Z=Eo();function BZ(t,e={}){return(0,$Z.Intrinsic)(t,"Capitalize",e)}});var QE=T(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});mv.Lowercase=jZ;var NZ=Eo();function jZ(t,e={}){return(0,NZ.Intrinsic)(t,"Lowercase",e)}});var YE=T(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});hv.Uncapitalize=GZ;var qZ=Eo();function GZ(t,e={}){return(0,qZ.Intrinsic)(t,"Uncapitalize",e)}});var XE=T(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});gv.Uppercase=HZ;var KZ=Eo();function HZ(t,e={}){return(0,KZ.Intrinsic)(t,"Uppercase",e)}});var vh=T(jn=>{"use strict";var zZ=jn&&jn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ec=jn&&jn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zZ(e,t,n)};Object.defineProperty(jn,"__esModule",{value:!0});Ec(JE(),jn);Ec(uv(),jn);Ec(Eo(),jn);Ec(QE(),jn);Ec(YE(),jn);Ec(XE(),jn)});var bv=T(fv=>{"use strict";Object.defineProperty(fv,"__esModule",{value:!0});fv.OmitFromMappedResult=ZZ;var VZ=ot(),JZ=wh(),QZ=tn();function YZ(t,e,n){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=(0,JZ.Omit)(t[s],e,(0,QZ.Clone)(n));return i}function XZ(t,e,n){return YZ(t.properties,e,n)}function ZZ(t,e,n){let i=XZ(t,e,n);return(0,VZ.MappedResult)(i)}});var wh=T(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});vv.Omit=gee;var eee=le(),tee=Wm(),nee=hu(),xv=qs(),iee=Ft(),see=ti(),ree=Cn(),ZE=st(),eA=on(),oee=wv(),aee=bv(),us=Me(),cee=Ut();function lee(t,e){return t.map(n=>yv(n,e))}function uee(t,e){return t.map(n=>yv(n,e))}function dee(t,e){let{[e]:n,...i}=t;return i}function pee(t,e){return e.reduce((n,i)=>dee(n,i),t)}function mee(t,e,n){let i=(0,tee.Discard)(t,[nee.TransformKind,"$id","required","properties"]),s=pee(n,e);return(0,eA.Object)(s,i)}function hee(t){let e=t.reduce((n,i)=>(0,us.IsLiteralValue)(i)?[...n,(0,iee.Literal)(i)]:n,[]);return(0,ZE.Union)(e)}function yv(t,e){return(0,us.IsIntersect)(t)?(0,ree.Intersect)(lee(t.allOf,e)):(0,us.IsUnion)(t)?(0,ZE.Union)(uee(t.anyOf,e)):(0,us.IsObject)(t)?mee(t,e,t.properties):(0,eA.Object)({})}function gee(t,e,n){let i=(0,cee.IsArray)(e)?hee(e):e,s=(0,us.IsSchema)(e)?(0,see.IndexPropertyKeys)(e):e,r=(0,us.IsRef)(t),o=(0,us.IsRef)(e);return(0,us.IsMappedResult)(t)?(0,aee.OmitFromMappedResult)(t,s,n):(0,us.IsMappedKey)(e)?(0,oee.OmitFromMappedKey)(t,e,n):r&&o?(0,xv.Computed)("Omit",[t,i],n):!r&&o?(0,xv.Computed)("Omit",[t,i],n):r&&!o?(0,xv.Computed)("Omit",[t,i],n):(0,eee.CreateType)({...yv(t,s),...n})}});var wv=T(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});Sv.OmitFromMappedKey=See;var fee=ot(),bee=wh(),xee=tn();function yee(t,e,n){return{[e]:(0,bee.Omit)(t,[e],(0,xee.Clone)(n))}}function vee(t,e,n){return e.reduce((i,s)=>({...i,...yee(t,s,n)}),{})}function wee(t,e,n){return vee(t,e.keys,n)}function See(t,e,n){let i=wee(t,e,n);return(0,fee.MappedResult)(i)}});var Du=T(ds=>{"use strict";var Cee=ds&&ds.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cv=ds&&ds.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Cee(e,t,n)};Object.defineProperty(ds,"__esModule",{value:!0});Cv(wv(),ds);Cv(bv(),ds);Cv(wh(),ds)});var kv=T(Tv=>{"use strict";Object.defineProperty(Tv,"__esModule",{value:!0});Tv.PickFromMappedResult=Pee;var Tee=ot(),kee=Sh(),Mee=tn();function Iee(t,e,n){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=(0,kee.Pick)(t[s],e,(0,Mee.Clone)(n));return i}function Ree(t,e,n){return Iee(t.properties,e,n)}function Pee(t,e,n){let i=Ree(t,e,n);return(0,Tee.MappedResult)(i)}});var Sh=T(Rv=>{"use strict";Object.defineProperty(Rv,"__esModule",{value:!0});Rv.Pick=Gee;var _ee=le(),Eee=Wm(),Mv=qs(),Aee=Cn(),Oee=Ft(),tA=on(),nA=st(),Lee=ti(),Wee=hu(),ps=Me(),Uee=Ut(),Fee=Pv(),Dee=kv();function $ee(t,e){return t.map(n=>Iv(n,e))}function Bee(t,e){return t.map(n=>Iv(n,e))}function Nee(t,e){let n={};for(let i of e)i in t&&(n[i]=t[i]);return n}function jee(t,e,n){let i=(0,Eee.Discard)(t,[Wee.TransformKind,"$id","required","properties"]),s=Nee(n,e);return(0,tA.Object)(s,i)}function qee(t){let e=t.reduce((n,i)=>(0,ps.IsLiteralValue)(i)?[...n,(0,Oee.Literal)(i)]:n,[]);return(0,nA.Union)(e)}function Iv(t,e){return(0,ps.IsIntersect)(t)?(0,Aee.Intersect)($ee(t.allOf,e)):(0,ps.IsUnion)(t)?(0,nA.Union)(Bee(t.anyOf,e)):(0,ps.IsObject)(t)?jee(t,e,t.properties):(0,tA.Object)({})}function Gee(t,e,n){let i=(0,Uee.IsArray)(e)?qee(e):e,s=(0,ps.IsSchema)(e)?(0,Lee.IndexPropertyKeys)(e):e,r=(0,ps.IsRef)(t),o=(0,ps.IsRef)(e);return(0,ps.IsMappedResult)(t)?(0,Dee.PickFromMappedResult)(t,s,n):(0,ps.IsMappedKey)(e)?(0,Fee.PickFromMappedKey)(t,e,n):r&&o?(0,Mv.Computed)("Pick",[t,i],n):!r&&o?(0,Mv.Computed)("Pick",[t,i],n):r&&!o?(0,Mv.Computed)("Pick",[t,i],n):(0,_ee.CreateType)({...Iv(t,s),...n})}});var Pv=T(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});_v.PickFromMappedKey=Yee;var Kee=ot(),Hee=Sh(),zee=tn();function Vee(t,e,n){return{[e]:(0,Hee.Pick)(t,[e],(0,zee.Clone)(n))}}function Jee(t,e,n){return e.reduce((i,s)=>({...i,...Vee(t,s,n)}),{})}function Qee(t,e,n){return Jee(t,e.keys,n)}function Yee(t,e,n){let i=Qee(t,e,n);return(0,Kee.MappedResult)(i)}});var $u=T(ms=>{"use strict";var Xee=ms&&ms.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ev=ms&&ms.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Xee(e,t,n)};Object.defineProperty(ms,"__esModule",{value:!0});Ev(Pv(),ms);Ev(kv(),ms);Ev(Sh(),ms)});var Ov=T(hs=>{"use strict";var Zee=hs&&hs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ete=hs&&hs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tte=hs&&hs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Zee(n,e,i[s]);return ete(n,e),n}})();Object.defineProperty(hs,"__esModule",{value:!0});hs.Partial=hte;var nte=le(),Av=qs(),ite=wi(),sA=on(),ste=Cn(),rte=st(),ote=Qs(),ate=es(),cte=oe(),lte=Lv(),$t=tte(Me());function ute(t,e){return(0,Av.Computed)("Partial",[(0,Av.Computed)(t,e)])}function dte(t){return(0,Av.Computed)("Partial",[(0,ote.Ref)(t)])}function pte(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,ite.Optional)(t[n]);return e}function mte(t,e){let n=(0,ate.Discard)(t,[cte.TransformKind,"$id","required","properties"]),i=pte(e);return(0,sA.Object)(i,n)}function iA(t){return t.map(e=>rA(e))}function rA(t){return $t.IsComputed(t)?ute(t.target,t.parameters):$t.IsRef(t)?dte(t.$ref):$t.IsIntersect(t)?(0,ste.Intersect)(iA(t.allOf)):$t.IsUnion(t)?(0,rte.Union)(iA(t.anyOf)):$t.IsObject(t)?mte(t,t.properties):$t.IsBigInt(t)||$t.IsBoolean(t)||$t.IsInteger(t)||$t.IsLiteral(t)||$t.IsNull(t)||$t.IsNumber(t)||$t.IsString(t)||$t.IsSymbol(t)||$t.IsUndefined(t)?t:(0,sA.Object)({})}function hte(t,e){return $t.IsMappedResult(t)?(0,lte.PartialFromMappedResult)(t,e):(0,nte.CreateType)({...rA(t),...e})}});var Lv=T(Wv=>{"use strict";Object.defineProperty(Wv,"__esModule",{value:!0});Wv.PartialFromMappedResult=vte;var gte=ot(),fte=Ov(),bte=tn();function xte(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,fte.Partial)(t[i],(0,bte.Clone)(e));return n}function yte(t,e){return xte(t.properties,e)}function vte(t,e){let n=yte(t,e);return(0,gte.MappedResult)(n)}});var Bu=T(Ys=>{"use strict";var wte=Ys&&Ys.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),oA=Ys&&Ys.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&wte(e,t,n)};Object.defineProperty(Ys,"__esModule",{value:!0});oA(Lv(),Ys);oA(Ov(),Ys)});var Fv=T(gs=>{"use strict";var Ste=gs&&gs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cte=gs&&gs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Tte=gs&&gs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Ste(n,e,i[s]);return Cte(n,e),n}})();Object.defineProperty(gs,"__esModule",{value:!0});gs.Required=Lte;var kte=le(),Uv=qs(),cA=on(),Mte=Cn(),Ite=st(),Rte=Qs(),lA=oe(),uA=es(),Pte=Dv(),Bt=Tte(Me());function _te(t,e){return(0,Uv.Computed)("Required",[(0,Uv.Computed)(t,e)])}function Ete(t){return(0,Uv.Computed)("Required",[(0,Rte.Ref)(t)])}function Ate(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,uA.Discard)(t[n],[lA.OptionalKind]);return e}function Ote(t,e){let n=(0,uA.Discard)(t,[lA.TransformKind,"$id","required","properties"]),i=Ate(e);return(0,cA.Object)(i,n)}function aA(t){return t.map(e=>dA(e))}function dA(t){return Bt.IsComputed(t)?_te(t.target,t.parameters):Bt.IsRef(t)?Ete(t.$ref):Bt.IsIntersect(t)?(0,Mte.Intersect)(aA(t.allOf)):Bt.IsUnion(t)?(0,Ite.Union)(aA(t.anyOf)):Bt.IsObject(t)?Ote(t,t.properties):Bt.IsBigInt(t)||Bt.IsBoolean(t)||Bt.IsInteger(t)||Bt.IsLiteral(t)||Bt.IsNull(t)||Bt.IsNumber(t)||Bt.IsString(t)||Bt.IsSymbol(t)||Bt.IsUndefined(t)?t:(0,cA.Object)({})}function Lte(t,e){return Bt.IsMappedResult(t)?(0,Pte.RequiredFromMappedResult)(t,e):(0,kte.CreateType)({...dA(t),...e})}});var Dv=T($v=>{"use strict";Object.defineProperty($v,"__esModule",{value:!0});$v.RequiredFromMappedResult=$te;var Wte=ot(),Ute=Fv();function Fte(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,Ute.Required)(t[i],e);return n}function Dte(t,e){return Fte(t.properties,e)}function $te(t,e){let n=Dte(t,e);return(0,Wte.MappedResult)(n)}});var Nu=T(Xs=>{"use strict";var Bte=Xs&&Xs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),pA=Xs&&Xs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Bte(e,t,n)};Object.defineProperty(Xs,"__esModule",{value:!0});pA(Dv(),Xs);pA(Fv(),Xs)});var fA=T(si=>{"use strict";var Nte=si&&si.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),jte=si&&si.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qte=si&&si.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Nte(n,e,i[s]);return jte(n,e),n}})();Object.defineProperty(si,"__esModule",{value:!0});si.FromType=dn;si.ComputeType=gA;si.ComputeModuleProperties=Ine;var un=Xi(),Gte=qb(),mA=es(),Kte=hc(),Hte=_u(),zte=gc(),Vte=fc(),Jte=ti(),Qte=Gs(),Yte=Cn(),Xte=Sc(),Zte=Tc(),ene=on(),tne=Du(),nne=$u(),Bv=vt(),ine=Bu(),hA=Pc(),sne=Nu(),rne=is(),one=st(),Ch=oe(),Mt=qte(Me());function ane(t,e){return e.map(n=>Mt.IsRef(n)?Nv(t,n.$ref):dn(t,n))}function Nv(t,e){return e in t?Mt.IsRef(t[e])?Nv(t,t[e].$ref):dn(t,t[e]):(0,Bv.Never)()}function cne(t){return(0,Hte.Awaited)(t[0])}function lne(t){return(0,Jte.Index)(t[0],t[1])}function une(t){return(0,Zte.KeyOf)(t[0])}function dne(t){return(0,ine.Partial)(t[0])}function pne(t){return(0,tne.Omit)(t[0],t[1])}function mne(t){return(0,nne.Pick)(t[0],t[1])}function hne(t){return(0,sne.Required)(t[0])}function gne(t,e,n){let i=ane(t,n);return e==="Awaited"?cne(i):e==="Index"?lne(i):e==="KeyOf"?une(i):e==="Partial"?dne(i):e==="Omit"?pne(i):e==="Pick"?mne(i):e==="Required"?hne(i):(0,Bv.Never)()}function fne(t,e){return(0,Kte.Array)(dn(t,e))}function bne(t,e){return(0,zte.AsyncIterator)(dn(t,e))}function xne(t,e,n){return(0,Vte.Constructor)(ju(t,e),dn(t,n))}function yne(t,e,n){return(0,Qte.Function)(ju(t,e),dn(t,n))}function vne(t,e){return(0,Yte.Intersect)(ju(t,e))}function wne(t,e){return(0,Xte.Iterator)(dn(t,e))}function Sne(t,e){return(0,ene.Object)(globalThis.Object.keys(e).reduce((n,i)=>({...n,[i]:dn(t,e[i])}),{}))}function Cne(t,e){let[n,i]=[dn(t,(0,hA.RecordValue)(e)),(0,hA.RecordPattern)(e)],s=(0,Gte.CloneType)(e);return s.patternProperties[i]=n,s}function Tne(t,e){return Mt.IsRef(e)?{...Nv(t,e.$ref),[Ch.TransformKind]:e[Ch.TransformKind]}:e}function kne(t,e){return(0,rne.Tuple)(ju(t,e))}function Mne(t,e){return(0,one.Union)(ju(t,e))}function ju(t,e){return e.map(n=>dn(t,n))}function dn(t,e){return Mt.IsOptional(e)?(0,un.CreateType)(dn(t,(0,mA.Discard)(e,[Ch.OptionalKind])),e):Mt.IsReadonly(e)?(0,un.CreateType)(dn(t,(0,mA.Discard)(e,[Ch.ReadonlyKind])),e):Mt.IsTransform(e)?(0,un.CreateType)(Tne(t,e),e):Mt.IsArray(e)?(0,un.CreateType)(fne(t,e.items),e):Mt.IsAsyncIterator(e)?(0,un.CreateType)(bne(t,e.items),e):Mt.IsComputed(e)?(0,un.CreateType)(gne(t,e.target,e.parameters)):Mt.IsConstructor(e)?(0,un.CreateType)(xne(t,e.parameters,e.returns),e):Mt.IsFunction(e)?(0,un.CreateType)(yne(t,e.parameters,e.returns),e):Mt.IsIntersect(e)?(0,un.CreateType)(vne(t,e.allOf),e):Mt.IsIterator(e)?(0,un.CreateType)(wne(t,e.items),e):Mt.IsObject(e)?(0,un.CreateType)(Sne(t,e.properties),e):Mt.IsRecord(e)?(0,un.CreateType)(Cne(t,e)):Mt.IsTuple(e)?(0,un.CreateType)(kne(t,e.items||[]),e):Mt.IsUnion(e)?(0,un.CreateType)(Mne(t,e.anyOf),e):e}function gA(t,e){return e in t?dn(t,t[e]):(0,Bv.Never)()}function Ine(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,n)=>({...e,[n]:gA(t,n)}),{})}});var xA=T(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.TModule=void 0;qu.Module=_ne;var bA=Xi(),Rne=oe(),Pne=fA(),Th=class{constructor(e){let n=(0,Pne.ComputeModuleProperties)(e),i=this.WithIdentifiers(n);this.$defs=i}Import(e,n){let i={...this.$defs,[e]:(0,bA.CreateType)(this.$defs[e],n)};return(0,bA.CreateType)({[Rne.Kind]:"Import",$defs:i,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,i)=>({...n,[i]:{...e[i],$id:i}}),{})}};qu.TModule=Th;function _ne(t){return new Th(t)}});var kh=T(Ao=>{"use strict";var Ene=Ao&&Ao.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ane=Ao&&Ao.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ene(e,t,n)};Object.defineProperty(Ao,"__esModule",{value:!0});Ane(xA(),Ao)});var yA=T(jv=>{"use strict";Object.defineProperty(jv,"__esModule",{value:!0});jv.Not=Wne;var One=le(),Lne=oe();function Wne(t,e){return(0,One.CreateType)({[Lne.Kind]:"Not",not:t},e)}});var Mh=T(Oo=>{"use strict";var Une=Oo&&Oo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Fne=Oo&&Oo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Une(e,t,n)};Object.defineProperty(Oo,"__esModule",{value:!0});Fne(yA(),Oo)});var vA=T(fs=>{"use strict";var Dne=fs&&fs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),$ne=fs&&fs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bne=fs&&fs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Dne(n,e,i[s]);return $ne(n,e),n}})();Object.defineProperty(fs,"__esModule",{value:!0});fs.Parameters=Gne;var Nne=is(),jne=vt(),qne=Bne(Me());function Gne(t,e){return qne.IsFunction(t)?(0,Nne.Tuple)(t.parameters,e):(0,jne.Never)()}});var Ih=T(Lo=>{"use strict";var Kne=Lo&&Lo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Hne=Lo&&Lo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Kne(e,t,n)};Object.defineProperty(Lo,"__esModule",{value:!0});Hne(vA(),Lo)});var SA=T(qv=>{"use strict";Object.defineProperty(qv,"__esModule",{value:!0});qv.Recursive=Yne;var zne=Rm(),Vne=le(),Jne=Ut(),wA=oe(),Qne=0;function Yne(t,e={}){(0,Jne.IsUndefined)(e.$id)&&(e.$id=`T${Qne++}`);let n=(0,zne.CloneType)(t({[wA.Kind]:"This",$ref:`${e.$id}`}));return n.$id=e.$id,(0,Vne.CreateType)({[wA.Hint]:"Recursive",...n},e)}});var Rh=T(Wo=>{"use strict";var Xne=Wo&&Wo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Zne=Wo&&Wo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Xne(e,t,n)};Object.defineProperty(Wo,"__esModule",{value:!0});Zne(SA(),Wo)});var CA=T(Gv=>{"use strict";Object.defineProperty(Gv,"__esModule",{value:!0});Gv.RegExp=iie;var eie=le(),tie=Ut(),nie=oe();function iie(t,e){let n=(0,tie.IsString)(t)?new globalThis.RegExp(t):t;return(0,eie.CreateType)({[nie.Kind]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},e)}});var Ph=T(Uo=>{"use strict";var sie=Uo&&Uo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),rie=Uo&&Uo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&sie(e,t,n)};Object.defineProperty(Uo,"__esModule",{value:!0});rie(CA(),Uo)});var TA=T(Hv=>{"use strict";Object.defineProperty(Hv,"__esModule",{value:!0});Hv.Rest=aie;var Kv=Me();function oie(t){return(0,Kv.IsIntersect)(t)?t.allOf:(0,Kv.IsUnion)(t)?t.anyOf:(0,Kv.IsTuple)(t)?t.items??[]:[]}function aie(t){return oie(t)}});var _h=T(Fo=>{"use strict";var cie=Fo&&Fo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),lie=Fo&&Fo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&cie(e,t,n)};Object.defineProperty(Fo,"__esModule",{value:!0});lie(TA(),Fo)});var kA=T(bs=>{"use strict";var uie=bs&&bs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),die=bs&&bs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pie=bs&&bs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&uie(n,e,i[s]);return die(n,e),n}})();Object.defineProperty(bs,"__esModule",{value:!0});bs.ReturnType=fie;var mie=le(),hie=vt(),gie=pie(Me());function fie(t,e){return gie.IsFunction(t)?(0,mie.CreateType)(t.returns,e):(0,hie.Never)(e)}});var Eh=T(Do=>{"use strict";var bie=Do&&Do.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xie=Do&&Do.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bie(e,t,n)};Object.defineProperty(Do,"__esModule",{value:!0});xie(kA(),Do)});var IA=T(MA=>{"use strict";Object.defineProperty(MA,"__esModule",{value:!0})});var PA=T(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});var FEe=oe()});var EA=T(Zs=>{"use strict";var yie=Zs&&Zs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),_A=Zs&&Zs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yie(e,t,n)};Object.defineProperty(Zs,"__esModule",{value:!0});_A(IA(),Zs);_A(PA(),Zs)});var OA=T(AA=>{"use strict";Object.defineProperty(AA,"__esModule",{value:!0})});var LA=T($o=>{"use strict";var vie=$o&&$o.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wie=$o&&$o.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vie(e,t,n)};Object.defineProperty($o,"__esModule",{value:!0});wie(OA(),$o)});var WA=T(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.TransformEncodeBuilder=Bo.TransformDecodeBuilder=void 0;Bo.Transform=Cie;var Ah=oe(),Sie=Me(),Oh=class{constructor(e){this.schema=e}Decode(e){return new Lh(this.schema,e)}};Bo.TransformDecodeBuilder=Oh;var Lh=class{constructor(e,n){this.schema=e,this.decode=n}EncodeTransform(e,n){let r={Encode:o=>n[Ah.TransformKind].Encode(e(o)),Decode:o=>this.decode(n[Ah.TransformKind].Decode(o))};return{...n,[Ah.TransformKind]:r}}EncodeSchema(e,n){let i={Decode:this.decode,Encode:e};return{...n,[Ah.TransformKind]:i}}Encode(e){return(0,Sie.IsTransform)(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}};Bo.TransformEncodeBuilder=Lh;function Cie(t){return new Oh(t)}});var Wh=T(No=>{"use strict";var Tie=No&&No.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kie=No&&No.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tie(e,t,n)};Object.defineProperty(No,"__esModule",{value:!0});kie(WA(),No)});var FA=T(zv=>{"use strict";Object.defineProperty(zv,"__esModule",{value:!0});zv.Unsafe=Iie;var Mie=le(),UA=oe();function Iie(t={}){return(0,Mie.CreateType)({[UA.Kind]:t[UA.Kind]??"Unsafe"},t)}});var Uh=T(jo=>{"use strict";var Rie=jo&&jo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Pie=jo&&jo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Rie(e,t,n)};Object.defineProperty(jo,"__esModule",{value:!0});Pie(FA(),jo)});var DA=T(Vv=>{"use strict";Object.defineProperty(Vv,"__esModule",{value:!0});Vv.Void=Aie;var _ie=le(),Eie=oe();function Aie(t){return(0,_ie.CreateType)({[Eie.Kind]:"Void",type:"void"},t)}});var Fh=T(qo=>{"use strict";var Oie=qo&&qo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Lie=qo&&qo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Oie(e,t,n)};Object.defineProperty(qo,"__esModule",{value:!0});Lie(DA(),qo)});var Qv=T($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});$h.JsonTypeBuilder=void 0;var Wie=mc(),Uie=hc(),Fie=Su(),Die=Xm(),$ie=eh(),Bie=nh(),Nie=dh(),jie=Ic(),qie=hh(),Gie=ti(),Kie=bh(),Hie=Cn(),Dh=vh(),zie=Tc(),Vie=Ft(),Jie=ot(),Qie=vt(),Yie=Mh(),Xie=Au(),Zie=kh(),ese=Ks(),tse=on(),nse=Du(),ise=wi(),sse=Bu(),rse=$u(),ose=Vs(),ase=Fu(),cse=Pc(),lse=Rh(),use=Qs(),dse=Nu(),pse=_h(),mse=io(),hse=Si(),gse=Wh(),fse=is(),bse=st(),xse=yo(),yse=Uh(),Jv=class{ReadonlyOptional(e){return(0,ase.ReadonlyOptional)(e)}Readonly(e,n){return(0,ose.Readonly)(e,n??!0)}Optional(e,n){return(0,ise.Optional)(e,n??!0)}Any(e){return(0,Wie.Any)(e)}Array(e,n){return(0,Uie.Array)(e,n)}Boolean(e){return(0,Fie.Boolean)(e)}Capitalize(e,n){return(0,Dh.Capitalize)(e,n)}Composite(e,n){return(0,Die.Composite)(e,n)}Const(e,n){return(0,$ie.Const)(e,n)}Enum(e,n){return(0,Bie.Enum)(e,n)}Exclude(e,n,i){return(0,Nie.Exclude)(e,n,i)}Extends(e,n,i,s,r){return(0,jie.Extends)(e,n,i,s,r)}Extract(e,n,i){return(0,qie.Extract)(e,n,i)}Index(e,n,i){return(0,Gie.Index)(e,n,i)}Integer(e){return(0,Kie.Integer)(e)}Intersect(e,n){return(0,Hie.Intersect)(e,n)}KeyOf(e,n){return(0,zie.KeyOf)(e,n)}Literal(e,n){return(0,Vie.Literal)(e,n)}Lowercase(e,n){return(0,Dh.Lowercase)(e,n)}Mapped(e,n,i){return(0,Jie.Mapped)(e,n,i)}Module(e){return(0,Zie.Module)(e)}Never(e){return(0,Qie.Never)(e)}Not(e,n){return(0,Yie.Not)(e,n)}Null(e){return(0,Xie.Null)(e)}Number(e){return(0,ese.Number)(e)}Object(e,n){return(0,tse.Object)(e,n)}Omit(e,n,i){return(0,nse.Omit)(e,n,i)}Partial(e,n){return(0,sse.Partial)(e,n)}Pick(e,n,i){return(0,rse.Pick)(e,n,i)}Record(e,n,i){return(0,cse.Record)(e,n,i)}Recursive(e,n){return(0,lse.Recursive)(e,n)}Ref(...e){return(0,use.Ref)(e[0],e[1])}Required(e,n){return(0,dse.Required)(e,n)}Rest(e){return(0,pse.Rest)(e)}String(e){return(0,mse.String)(e)}TemplateLiteral(e,n){return(0,hse.TemplateLiteral)(e,n)}Transform(e){return(0,gse.Transform)(e)}Tuple(e,n){return(0,fse.Tuple)(e,n)}Uncapitalize(e,n){return(0,Dh.Uncapitalize)(e,n)}Union(e,n){return(0,bse.Union)(e,n)}Unknown(e){return(0,xse.Unknown)(e)}Unsafe(e){return(0,yse.Unsafe)(e)}Uppercase(e,n){return(0,Dh.Uppercase)(e,n)}};$h.JsonTypeBuilder=Jv});var $A=T($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.Rest=$.Required=$.RegExp=$.Ref=$.Recursive=$.Record=$.ReadonlyOptional=$.Readonly=$.Promise=$.Pick=$.Partial=$.Parameters=$.Optional=$.Omit=$.Object=$.Number=$.Null=$.Not=$.Never=$.Module=$.Mapped=$.Literal=$.KeyOf=$.Iterator=$.Uppercase=$.Lowercase=$.Uncapitalize=$.Capitalize=$.Intersect=$.Integer=$.Instantiate=$.InstanceType=$.Index=$.Function=$.Extract=$.Extends=$.Exclude=$.Enum=$.Date=$.ConstructorParameters=$.Constructor=$.Const=$.Composite=$.Boolean=$.BigInt=$.Awaited=$.AsyncIterator=$.Array=$.Argument=$.Any=void 0;$.Void=$.Unsafe=$.Unknown=$.Union=$.Undefined=$.Uint8Array=$.Tuple=$.Transform=$.TemplateLiteral=$.Symbol=$.String=$.ReturnType=void 0;var vse=mc();Object.defineProperty($,"Any",{enumerable:!0,get:function(){return vse.Any}});var wse=Lm();Object.defineProperty($,"Argument",{enumerable:!0,get:function(){return wse.Argument}});var Sse=hc();Object.defineProperty($,"Array",{enumerable:!0,get:function(){return Sse.Array}});var Cse=gc();Object.defineProperty($,"AsyncIterator",{enumerable:!0,get:function(){return Cse.AsyncIterator}});var Tse=_u();Object.defineProperty($,"Awaited",{enumerable:!0,get:function(){return Tse.Awaited}});var kse=vc();Object.defineProperty($,"BigInt",{enumerable:!0,get:function(){return kse.BigInt}});var Mse=Su();Object.defineProperty($,"Boolean",{enumerable:!0,get:function(){return Mse.Boolean}});var Ise=Xm();Object.defineProperty($,"Composite",{enumerable:!0,get:function(){return Ise.Composite}});var Rse=eh();Object.defineProperty($,"Const",{enumerable:!0,get:function(){return Rse.Const}});var Pse=fc();Object.defineProperty($,"Constructor",{enumerable:!0,get:function(){return Pse.Constructor}});var _se=th();Object.defineProperty($,"ConstructorParameters",{enumerable:!0,get:function(){return _se.ConstructorParameters}});var Ese=Eu();Object.defineProperty($,"Date",{enumerable:!0,get:function(){return Ese.Date}});var Ase=nh();Object.defineProperty($,"Enum",{enumerable:!0,get:function(){return Ase.Enum}});var Ose=dh();Object.defineProperty($,"Exclude",{enumerable:!0,get:function(){return Ose.Exclude}});var Lse=Ic();Object.defineProperty($,"Extends",{enumerable:!0,get:function(){return Lse.Extends}});var Wse=hh();Object.defineProperty($,"Extract",{enumerable:!0,get:function(){return Wse.Extract}});var Use=Gs();Object.defineProperty($,"Function",{enumerable:!0,get:function(){return Use.Function}});var Fse=ti();Object.defineProperty($,"Index",{enumerable:!0,get:function(){return Fse.Index}});var Dse=gh();Object.defineProperty($,"InstanceType",{enumerable:!0,get:function(){return Dse.InstanceType}});var $se=fh();Object.defineProperty($,"Instantiate",{enumerable:!0,get:function(){return $se.Instantiate}});var Bse=bh();Object.defineProperty($,"Integer",{enumerable:!0,get:function(){return Bse.Integer}});var Nse=Cn();Object.defineProperty($,"Intersect",{enumerable:!0,get:function(){return Nse.Intersect}});var Bh=vh();Object.defineProperty($,"Capitalize",{enumerable:!0,get:function(){return Bh.Capitalize}});Object.defineProperty($,"Uncapitalize",{enumerable:!0,get:function(){return Bh.Uncapitalize}});Object.defineProperty($,"Lowercase",{enumerable:!0,get:function(){return Bh.Lowercase}});Object.defineProperty($,"Uppercase",{enumerable:!0,get:function(){return Bh.Uppercase}});var jse=Sc();Object.defineProperty($,"Iterator",{enumerable:!0,get:function(){return jse.Iterator}});var qse=Tc();Object.defineProperty($,"KeyOf",{enumerable:!0,get:function(){return qse.KeyOf}});var Gse=Ft();Object.defineProperty($,"Literal",{enumerable:!0,get:function(){return Gse.Literal}});var Kse=ot();Object.defineProperty($,"Mapped",{enumerable:!0,get:function(){return Kse.Mapped}});var Hse=kh();Object.defineProperty($,"Module",{enumerable:!0,get:function(){return Hse.Module}});var zse=vt();Object.defineProperty($,"Never",{enumerable:!0,get:function(){return zse.Never}});var Vse=Mh();Object.defineProperty($,"Not",{enumerable:!0,get:function(){return Vse.Not}});var Jse=Au();Object.defineProperty($,"Null",{enumerable:!0,get:function(){return Jse.Null}});var Qse=Ks();Object.defineProperty($,"Number",{enumerable:!0,get:function(){return Qse.Number}});var Yse=on();Object.defineProperty($,"Object",{enumerable:!0,get:function(){return Yse.Object}});var Xse=Du();Object.defineProperty($,"Omit",{enumerable:!0,get:function(){return Xse.Omit}});var Zse=wi();Object.defineProperty($,"Optional",{enumerable:!0,get:function(){return Zse.Optional}});var ere=Ih();Object.defineProperty($,"Parameters",{enumerable:!0,get:function(){return ere.Parameters}});var tre=Bu();Object.defineProperty($,"Partial",{enumerable:!0,get:function(){return tre.Partial}});var nre=$u();Object.defineProperty($,"Pick",{enumerable:!0,get:function(){return nre.Pick}});var ire=Iu();Object.defineProperty($,"Promise",{enumerable:!0,get:function(){return ire.Promise}});var sre=Vs();Object.defineProperty($,"Readonly",{enumerable:!0,get:function(){return sre.Readonly}});var rre=Fu();Object.defineProperty($,"ReadonlyOptional",{enumerable:!0,get:function(){return rre.ReadonlyOptional}});var ore=Pc();Object.defineProperty($,"Record",{enumerable:!0,get:function(){return ore.Record}});var are=Rh();Object.defineProperty($,"Recursive",{enumerable:!0,get:function(){return are.Recursive}});var cre=Qs();Object.defineProperty($,"Ref",{enumerable:!0,get:function(){return cre.Ref}});var lre=Ph();Object.defineProperty($,"RegExp",{enumerable:!0,get:function(){return lre.RegExp}});var ure=Nu();Object.defineProperty($,"Required",{enumerable:!0,get:function(){return ure.Required}});var dre=_h();Object.defineProperty($,"Rest",{enumerable:!0,get:function(){return dre.Rest}});var pre=Eh();Object.defineProperty($,"ReturnType",{enumerable:!0,get:function(){return pre.ReturnType}});var mre=io();Object.defineProperty($,"String",{enumerable:!0,get:function(){return mre.String}});var hre=Ou();Object.defineProperty($,"Symbol",{enumerable:!0,get:function(){return hre.Symbol}});var gre=Si();Object.defineProperty($,"TemplateLiteral",{enumerable:!0,get:function(){return gre.TemplateLiteral}});var fre=Wh();Object.defineProperty($,"Transform",{enumerable:!0,get:function(){return fre.Transform}});var bre=is();Object.defineProperty($,"Tuple",{enumerable:!0,get:function(){return bre.Tuple}});var xre=Wu();Object.defineProperty($,"Uint8Array",{enumerable:!0,get:function(){return xre.Uint8Array}});var yre=Lu();Object.defineProperty($,"Undefined",{enumerable:!0,get:function(){return yre.Undefined}});var vre=st();Object.defineProperty($,"Union",{enumerable:!0,get:function(){return vre.Union}});var wre=yo();Object.defineProperty($,"Unknown",{enumerable:!0,get:function(){return wre.Unknown}});var Sre=Uh();Object.defineProperty($,"Unsafe",{enumerable:!0,get:function(){return Sre.Unsafe}});var Cre=Fh();Object.defineProperty($,"Void",{enumerable:!0,get:function(){return Cre.Void}})});var BA=T(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});Nh.JavaScriptTypeBuilder=void 0;var Tre=Qv(),kre=Lm(),Mre=gc(),Ire=_u(),Rre=vc(),Pre=fc(),_re=th(),Ere=Eu(),Are=Gs(),Ore=gh(),Lre=fh(),Wre=Sc(),Ure=Ih(),Fre=Iu(),Dre=Ph(),$re=Eh(),Bre=Ou(),Nre=Wu(),jre=Lu(),qre=Fh(),Yv=class extends Tre.JsonTypeBuilder{Argument(e){return(0,kre.Argument)(e)}AsyncIterator(e,n){return(0,Mre.AsyncIterator)(e,n)}Awaited(e,n){return(0,Ire.Awaited)(e,n)}BigInt(e){return(0,Rre.BigInt)(e)}ConstructorParameters(e,n){return(0,_re.ConstructorParameters)(e,n)}Constructor(e,n,i){return(0,Pre.Constructor)(e,n,i)}Date(e={}){return(0,Ere.Date)(e)}Function(e,n,i){return(0,Are.Function)(e,n,i)}InstanceType(e,n){return(0,Ore.InstanceType)(e,n)}Instantiate(e,n){return(0,Lre.Instantiate)(e,n)}Iterator(e,n){return(0,Wre.Iterator)(e,n)}Parameters(e,n){return(0,Ure.Parameters)(e,n)}Promise(e,n){return(0,Fre.Promise)(e,n)}RegExp(e,n){return(0,Dre.RegExp)(e,n)}ReturnType(e,n){return(0,$re.ReturnType)(e,n)}Symbol(e){return(0,Bre.Symbol)(e)}Undefined(e){return(0,jre.Undefined)(e)}Uint8Array(e){return(0,Nre.Uint8Array)(e)}Void(e){return(0,qre.Void)(e)}};Nh.JavaScriptTypeBuilder=Yv});var NA=T(pn=>{"use strict";var Gre=pn&&pn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Kre=pn&&pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Hre=pn&&pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Gre(n,e,i[s]);return Kre(n,e),n}})();Object.defineProperty(pn,"__esModule",{value:!0});pn.Type=pn.JavaScriptTypeBuilder=pn.JsonTypeBuilder=void 0;var zre=Qv();Object.defineProperty(pn,"JsonTypeBuilder",{enumerable:!0,get:function(){return zre.JsonTypeBuilder}});var Vre=Hre($A()),Jre=BA();Object.defineProperty(pn,"JavaScriptTypeBuilder",{enumerable:!0,get:function(){return Jre.JavaScriptTypeBuilder}});var Qre=Vre;pn.Type=Qre});var jA=T(z=>{"use strict";var Yre=z&&z.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Q=z&&z.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Yre(e,t,n)};Object.defineProperty(z,"__esModule",{value:!0});Q(qb(),z);Q(Xi(),z);Q(xi(),z);Q(Yb(),z);Q(BP(),z);Q(xu(),z);Q(KP(),z);Q(yu(),z);Q(oe(),z);Q(mc(),z);Q(hc(),z);Q(Lm(),z);Q(gc(),z);Q(_u(),z);Q(vc(),z);Q(Su(),z);Q(Xm(),z);Q(eh(),z);Q(fc(),z);Q(th(),z);Q(Eu(),z);Q(nh(),z);Q(dh(),z);Q(Ic(),z);Q(hh(),z);Q(Gs(),z);Q(ti(),z);Q(gh(),z);Q(fh(),z);Q(bh(),z);Q(Cn(),z);Q(Sc(),z);Q(vh(),z);Q(Tc(),z);Q(Ft(),z);Q(kh(),z);Q(ot(),z);Q(vt(),z);Q(Mh(),z);Q(Au(),z);Q(Ks(),z);Q(on(),z);Q(Du(),z);Q(wi(),z);Q(Ih(),z);Q(Bu(),z);Q($u(),z);Q(Iu(),z);Q(Vs(),z);Q(Fu(),z);Q(Pc(),z);Q(Rh(),z);Q(Qs(),z);Q(Ph(),z);Q(Nu(),z);Q(_h(),z);Q(Eh(),z);Q(EA(),z);Q(LA(),z);Q(io(),z);Q(Ou(),z);Q(Si(),z);Q(Wh(),z);Q(is(),z);Q(Wu(),z);Q(Lu(),z);Q(st(),z);Q(yo(),z);Q(Uh(),z);Q(Fh(),z);Q(NA(),z)});import{randomBytes as OB}from"node:crypto";import{accessSync as Coe,constants as Toe,existsSync as tg,readFileSync as RO,realpathSync as koe}from"fs";import{homedir as Dc}from"os";import{basename as Roe,dirname as Yu,join as ht,resolve as ng,sep as Poe,win32 as _oe}from"path";import{fileURLToPath as PO}from"url";import{spawn as kO,spawnSync as MO}from"node:child_process";import hw from"cross-spawn";var IO=100;function Qu(t,e,n){return process.platform==="win32"?hw(t,e,n):kO(t,e,n)}function zo(t,e,n){return process.platform==="win32"?hw.sync(t,e,n):MO(t,e,n)}function eg(t){return new Promise((e,n)=>{let i=!1,s=!1,r=null,o,a=t.stdout===null,c=t.stderr===null,l=()=>{o&&(clearTimeout(o),o=void 0),t.removeListener("error",g),t.removeListener("exit",h),t.removeListener("close",f),t.stdout?.removeListener("end",p),t.stderr?.removeListener("end",m)},d=x=>{i||(i=!0,l(),t.stdout?.destroy(),t.stderr?.destroy(),e(x))},u=()=>{!s||i||a&&c&&d(r)},p=()=>{a=!0,u()},m=()=>{c=!0,u()},g=x=>{i||(i=!0,l(),n(x))},h=x=>{s=!0,r=x,u(),i||(o=setTimeout(()=>d(x),IO))},f=x=>{d(x)};t.stdout?.once("end",p),t.stderr?.once("end",m),t.once("error",g),t.once("exit",h),t.once("close",f)})}var _O=PO(import.meta.url),gw=Yu(_O),Xu=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),Ooe=!!process.versions.bun;function ai(){let t=process.env.PI_PACKAGE_DIR;if(t)return t==="~"?Dc():t.startsWith("~/")?Dc()+t.slice(1):t;if(Xu)return Yu(process.execPath);let e=gw;for(;e!==Yu(e);){if(tg(ht(e,"package.json")))return e;e=Yu(e)}return gw}function ig(){if(Xu)return ht(ai(),"theme");let t=ai(),e=tg(ht(t,"src"))?"src":"dist";return ht(t,e,"modes","interactive","theme")}function EO(){return ht(ai(),"package.json")}function sg(){return ng(ht(ai(),"README.md"))}function Zu(){return ng(ht(ai(),"docs"))}function ed(){return ng(ht(ai(),"CHANGELOG.md"))}function AO(){if(Xu)return ht(ai(),"assets");let t=ai(),e=tg(ht(t,"src"))?"src":"dist";return ht(t,e,"modes","interactive","assets")}function fw(t){return ht(AO(),t)}var td=JSON.parse(RO(EO(),"utf-8")),bw=td.piConfig?.name,OO=td.name||"@earendil-works/pi-coding-agent",Ot=bw||"pi",rg=bw?Ot:"\u03C0",St=td.piConfig?.configDir||".pi",Ai=td.version||"0.0.0",xw=`${Ot.toUpperCase()}_CODING_AGENT_DIR`,yw=`${Ot.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function vw(t){return t==="~"?Dc():t.startsWith("~/")?Dc()+t.slice(1):t}var LO="https://pi.dev/session/";function ww(t){return`${process.env.PI_SHARE_VIEWER_URL||LO}#${t}`}function Pe(){let t=process.env[xw];return t?vw(t):ht(Dc(),St,"agent")}function $c(){return ht(Pe(),"themes")}function og(){return ht(Pe(),"auth.json")}function Bc(){return ht(Pe(),"bin")}function Sw(){return ht(Pe(),"sessions")}function Cw(){return ht(Pe(),`${Ot}-debug.log`)}import{Type as dle}from"typebox";var Tw=new Map;function WO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function UO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function Mn(t,e){Tw.set(t.api,{provider:{api:t.api,stream:WO(t.api,t.stream),streamSimple:UO(t.api,t.streamSimple)},sourceId:e})}function kw(t){return Tw.get(t)?.provider}Gn();var Iw={openrouter:{"black-forest-labs/flux.2-flex":{id:"black-forest-labs/flux.2-flex",name:"Black Forest Labs: FLUX.2 Flex",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-klein-4b":{id:"black-forest-labs/flux.2-klein-4b",name:"Black Forest Labs: FLUX.2 Klein 4B",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-max":{id:"black-forest-labs/flux.2-max",name:"Black Forest Labs: FLUX.2 Max",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-pro":{id:"black-forest-labs/flux.2-pro",name:"Black Forest Labs: FLUX.2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"bytedance-seed/seedream-4.5":{id:"bytedance-seed/seedream-4.5",name:"ByteDance Seed: Seedream 4.5",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"google/gemini-2.5-flash-image":{id:"google/gemini-2.5-flash-image",name:"Google: Nano Banana (Gemini 2.5 Flash Image)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:.08333333333333334}},"google/gemini-3-pro-image-preview":{id:"google/gemini-3-pro-image-preview",name:"Google: Nano Banana Pro (Gemini 3 Pro Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375}},"google/gemini-3.1-flash-image-preview":{id:"google/gemini-3.1-flash-image-preview",name:"Google: Nano Banana 2 (Gemini 3.1 Flash Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.5,output:3,cacheRead:0,cacheWrite:0}},"openai/gpt-5-image":{id:"openai/gpt-5-image",name:"OpenAI: GPT-5 Image",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:10,output:10,cacheRead:1.25,cacheWrite:0}},"openai/gpt-5-image-mini":{id:"openai/gpt-5-image-mini",name:"OpenAI: GPT-5 Image Mini",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2.5,output:2,cacheRead:.25,cacheWrite:0}},"openai/gpt-5.4-image-2":{id:"openai/gpt-5.4-image-2",name:"OpenAI: GPT-5.4 Image 2",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:8,output:15,cacheRead:2,cacheWrite:0}},"openrouter/auto":{id:"openrouter/auto",name:"Auto Router",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["text","image"],cost:{input:-1e6,output:-1e6,cacheRead:0,cacheWrite:0}},"recraft/recraft-v3":{id:"recraft/recraft-v3",name:"Recraft: Recraft V3",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4":{id:"recraft/recraft-v4",name:"Recraft: Recraft V4",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-pro":{id:"recraft/recraft-v4-pro",name:"Recraft: Recraft V4 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-pro-vector":{id:"recraft/recraft-v4-pro-vector",name:"Recraft: Recraft V4 Pro Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-vector":{id:"recraft/recraft-v4-vector",name:"Recraft: Recraft V4 Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1":{id:"recraft/recraft-v4.1",name:"Recraft: Recraft V4.1",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-pro":{id:"recraft/recraft-v4.1-pro",name:"Recraft: Recraft V4.1 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-pro-vector":{id:"recraft/recraft-v4.1-pro-vector",name:"Recraft: Recraft V4.1 Pro Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-utility":{id:"recraft/recraft-v4.1-utility",name:"Recraft: Recraft V4.1 Utility",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-utility-pro":{id:"recraft/recraft-v4.1-utility-pro",name:"Recraft: Recraft V4.1 Utility Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-vector":{id:"recraft/recraft-v4.1-vector",name:"Recraft: Recraft V4.1 Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast":{id:"sourceful/riverflow-v2-fast",name:"Sourceful: Riverflow V2 Fast",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast-preview":{id:"sourceful/riverflow-v2-fast-preview",name:"Sourceful: Riverflow V2 Fast Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-max-preview":{id:"sourceful/riverflow-v2-max-preview",name:"Sourceful: Riverflow V2 Max Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-pro":{id:"sourceful/riverflow-v2-pro",name:"Sourceful: Riverflow V2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-standard-preview":{id:"sourceful/riverflow-v2-standard-preview",name:"Sourceful: Riverflow V2 Standard Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"x-ai/grok-imagine-image-quality":{id:"x-ai/grok-imagine-image-quality",name:"xAI: Grok Imagine Image Quality",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}}};var jO=new Map;for(let[t,e]of Object.entries(Iw)){let n=new Map;for(let[i,s]of Object.entries(e))n.set(i,s);jO.set(t,n)}var qO=new Map;function GO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function Rw(t,e){qO.set(t.api,{provider:{api:t.api,generateImages:GO(t.api,t.generateImages)},sourceId:e})}var Ew;function QO(t,e){return{api:t.api,provider:t.provider,model:t.id,output:[],stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function YO(){return Ew||=Promise.resolve().then(()=>(_w(),Pw)).then(t=>t),Ew}var XO=async(t,e,n)=>{try{return await(await YO()).generateImagesOpenRouter(t,e,n)}catch(i){return QO(t,i)}};function ZO(){Rw({api:"openrouter-images",generateImages:XO})}ZO();In();Rn();Rn();var z9=t=>import(import.meta.url.endsWith(".js")?t.replace(/\.ts$/,".js"):t),HS,zS,VS,JS,QS,YS,XS,ZS,eC,tC;function nC(t,e){(async()=>{for await(let n of e)t.push(n);t.end()})()}function iC(t,e){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function Wi(t){return(e,n,i)=>{let s=new it;return t().then(r=>{let o=r.stream(e,n,i);nC(s,o)}).catch(r=>{let o=iC(e,r);s.push({type:"error",reason:"error",error:o}),s.end(o)}),s}}function Ui(t){return(e,n,i)=>{let s=new it;return t().then(r=>{let o=r.streamSimple(e,n,i);nC(s,o)}).catch(r=>{let o=iC(e,r);s.push({type:"error",reason:"error",error:o}),s.end(o)}),s}}function sC(){return HS||=Promise.resolve().then(()=>(Gw(),qw)).then(t=>{let e=t;return{stream:e.streamAnthropic,streamSimple:e.streamSimpleAnthropic}}),HS}function rC(){return zS||=Promise.resolve().then(()=>(zw(),Hw)).then(t=>{let e=t;return{stream:e.streamAzureOpenAIResponses,streamSimple:e.streamSimpleAzureOpenAIResponses}}),zS}function oC(){return VS||=Promise.resolve().then(()=>(Yw(),Qw)).then(t=>{let e=t;return{stream:e.streamGoogle,streamSimple:e.streamSimpleGoogle}}),VS}function aC(){return JS||=Promise.resolve().then(()=>(iS(),nS)).then(t=>{let e=t;return{stream:e.streamGoogleVertex,streamSimple:e.streamSimpleGoogleVertex}}),JS}function cC(){return QS||=Promise.resolve().then(()=>(lS(),cS)).then(t=>{let e=t;return{stream:e.streamMistral,streamSimple:e.streamSimpleMistral}}),QS}function lC(){return YS||=Promise.resolve().then(()=>(AS(),ES)).then(t=>{let e=t;return{stream:e.streamOpenAICodexResponses,streamSimple:e.streamSimpleOpenAICodexResponses}}),YS}function uC(){return XS||=Promise.resolve().then(()=>(BS(),$S)).then(t=>{let e=t;return{stream:e.streamOpenAICompletions,streamSimple:e.streamSimpleOpenAICompletions}}),XS}function dC(){return ZS||=Promise.resolve().then(()=>(KS(),GS)).then(t=>{let e=t;return{stream:e.streamOpenAIResponses,streamSimple:e.streamSimpleOpenAIResponses}}),ZS}function pC(){return eC?Promise.resolve(eC):(tC||=z9("./amazon-bedrock.ts").then(t=>{let e=t;return{stream:e.streamBedrock,streamSimple:e.streamSimpleBedrock}}),tC)}var V9=Wi(sC),J9=Ui(sC),Q9=Wi(rC),Y9=Ui(rC),X9=Wi(oC),Z9=Ui(oC),eW=Wi(aC),tW=Ui(aC),nW=Wi(cC),iW=Ui(cC),sW=Wi(lC),rW=Ui(lC),oW=Wi(uC),aW=Ui(uC),cW=Wi(dC),lW=Ui(dC),uW=Wi(pC),dW=Ui(pC);function pW(){Mn({api:"anthropic-messages",stream:V9,streamSimple:J9}),Mn({api:"openai-completions",stream:oW,streamSimple:aW}),Mn({api:"mistral-conversations",stream:nW,streamSimple:iW}),Mn({api:"openai-responses",stream:cW,streamSimple:lW}),Mn({api:"azure-openai-responses",stream:Q9,streamSimple:Y9}),Mn({api:"openai-codex-responses",stream:sW,streamSimple:rW}),Mn({api:"google-generative-ai",stream:X9,streamSimple:Z9}),Mn({api:"google-vertex",stream:eW,streamSimple:tW}),Mn({api:"bedrock-converse-stream",stream:uW,streamSimple:dW})}pW();kg();Gn();function mW(t){let e=kw(t);if(!e)throw new Error(`No API provider registered for api: ${t}`);return e}function hW(t,e,n){return mW(t.api).stream(t,e,n)}async function mC(t,e,n){return hW(t,e,n).result()}Mg();Rn();Vo();import{Type as ile}from"typebox";import{Compile as ole}from"typebox/compile";import{Value as cle}from"typebox/value";import*as Lt from"node:fs";import*as gr from"node:path";import{spawn as fW}from"child_process";import{readdirSync as bW,statSync as hC}from"fs";import{homedir as gC}from"os";import{basename as Ag,dirname as kd,join as ws}from"path";function Td(t,e){let n=t.toLowerCase(),i=e.toLowerCase(),s=d=>{if(d.length===0)return{matches:!0,score:0};if(d.length>i.length)return{matches:!1,score:0};let u=0,p=0,m=-1,g=0;for(let h=0;h<i.length&&u<d.length;h++)if(i[h]===d[u]){let f=h===0||/[\s\-_./:]/.test(i[h-1]);m===h-1?(g++,p-=g*5):(g=0,m>=0&&(p+=(h-m-1)*2)),f&&(p-=10),p+=h*.1,m=h,u++}return u<d.length?{matches:!1,score:0}:(d===i&&(p-=100),{matches:!0,score:p})},r=s(n);if(r.matches)return r;let o=n.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),a=n.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),c=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:a?`${a.groups?.letters??""}${a.groups?.digits??""}`:"";if(!c)return r;let l=s(c);return l.matches?{matches:!0,score:l.score+5}:r}function Kt(t,e,n){if(!e.trim())return t;let i=e.trim().split(/\s+/).filter(r=>r.length>0);if(i.length===0)return t;let s=[];for(let r of t){let o=n(r),a=0,c=!0;for(let l of i){let d=Td(l,o);if(d.matches)a+=d.score;else{c=!1;break}}c&&s.push({item:r,totalScore:a})}return s.sort((r,o)=>r.totalScore-o.totalScore),s.map(r=>r.item)}var wC=new Set([" "," ",'"',"'","="]);function rr(t){return t.replace(/\\/g,"/")}function xW(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yW(t){let e=rr(t);if(!e.includes("/"))return e;let n=e.endsWith("/"),i=e.replace(/^\/+|\/+$/g,"");if(!i)return e;let s="[\\\\/]",r=i.split("/").filter(Boolean).map(a=>xW(a));if(r.length===0)return e;let o=r.join(s);return n&&(o+=s),o}function fC(t){for(let e=t.length-1;e>=0;e-=1)if(wC.has(t[e]??""))return e;return-1}function vW(t){let e=!1,n=-1;for(let i=0;i<t.length;i+=1)t[i]==='"'&&(e=!e,e&&(n=i));return e?n:null}function bC(t,e){return e===0||wC.has(t[e-1]??"")}function xC(t){let e=vW(t);return e===null?null:e>0&&t[e-1]==="@"?bC(t,e-1)?t.slice(e-1):null:bC(t,e)?t.slice(e):null}function yC(t){return t.startsWith('@"')?{rawPrefix:t.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:t.startsWith('"')?{rawPrefix:t.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:t.startsWith("@")?{rawPrefix:t.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:t,isAtPrefix:!1,isQuotedPrefix:!1}}function vC(t,e){let n=e.isQuotedPrefix||t.includes(" "),i=e.isAtPrefix?"@":"";return n?`${`${i}"`}${t}"`:`${i}${t}`}async function wW(t,e,n,i,s){let r=["--base-directory",t,"--max-results",String(i),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return rr(n).includes("/")&&r.push("--full-path"),n&&r.push(yW(n)),await new Promise(o=>{if(s.aborted){o([]);return}let a=fW(e,r,{stdio:["ignore","pipe","pipe"]}),c="",l=!1,d=p=>{l||(l=!0,s.removeEventListener("abort",u),o(p))},u=()=>{a.exitCode===null&&a.kill("SIGKILL")};s.addEventListener("abort",u,{once:!0}),a.stdout.setEncoding("utf-8"),a.stdout.on("data",p=>{c+=p}),a.on("error",()=>{d([])}),a.on("close",p=>{if(s.aborted||p!==0||!c){d([]);return}let m=c.trim().split(`
|
|
31
|
+
${o}`),i.push({type:"error",reason:s.stopReason,error:s}),i.end()}})(),i},k9=(t,e,n)=>{let i=n?.apiKey||Ke(t.provider);if(!i)throw new Error(`No API key for provider: ${t.provider}`);let s=Pt(t,n,i),r=n?.reasoning?Rt(t,n.reasoning):void 0,o=r==="off"?void 0:r,a=n?.toolChoice;return US(t,e,{...s,reasoningEffort:o,toolChoice:a})}});var GS={};Ei(GS,{streamOpenAIResponses:()=>qS,streamSimpleOpenAIResponses:()=>j9});import D9 from"openai";function NS(t){return t||(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long"?"long":"short")}function jS(t){return{sendSessionIdHeader:t.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:t.compat?.supportsLongCacheRetention??!0}}function B9(t,e){return e==="long"&&t.supportsLongCacheRetention?"24h":void 0}function N9(t){if(t instanceof Error){let e=t.status,n=typeof e=="number"?e:void 0;return n!==void 0?`OpenAI API error (${n}): ${t.message}`:t.message}try{return JSON.stringify(t)}catch{return String(t)}}function q9(t,e,n,i,s){if(!n){if(!process.env.OPENAI_API_KEY)throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");n=process.env.OPENAI_API_KEY}let r=jS(t),o={...t.headers};if(t.provider==="github-copilot"){let c=Qo(e.messages),l=Yo({messages:e.messages,hasImages:c});Object.assign(o,l)}s&&(r.sendSessionIdHeader&&(o.session_id=s),o["x-client-request-id"]=s),i&&Object.assign(o,i);let a=t.provider==="cloudflare-ai-gateway"?{...o,Authorization:o.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:o;return new D9({apiKey:n,baseURL:sd(t.provider)?Jo(t):t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:a})}function G9(t,e,n){let i=nr(t,e,$9),s=NS(n?.cacheRetention),r=jS(t),o={model:t.id,input:i,stream:!0,prompt_cache_key:s==="none"?void 0:ys(n?.sessionId),prompt_cache_retention:B9(r,s),store:!1};if(n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),e.tools&&e.tools.length>0&&(o.tools=Zo(e.tools)),t.reasoning)if(n?.reasoningEffort||n?.reasoningSummary){let a=n?.reasoningEffort?t.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:"medium";o.reasoning={effort:a,summary:n?.reasoningSummary||"auto"},o.include=["reasoning.encrypted_content"]}else t.provider!=="github-copilot"&&t.thinkingLevelMap?.off!==null&&(o.reasoning={effort:t.thinkingLevelMap?.off??"none"});return o}function K9(t,e){switch(e){case"flex":return .5;case"priority":return t.id==="gpt-5.5"?2.5:2;default:return 1}}function H9(t,e,n){let i=K9(n,e);i!==1&&(t.cost.input*=i,t.cost.output*=i,t.cost.cacheRead*=i,t.cost.cacheWrite*=i,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite)}var $9,qS,j9,KS=Ne(()=>{"use strict";Gn();In();Rn();tr();rd();od();qc();pd();Li();$9=new Set(["openai","openai-codex","opencode"]);qS=(t,e,n)=>{let i=new it;return(async()=>{let s={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let r=n?.apiKey||Ke(t.provider)||"",a=NS(n?.cacheRetention)==="none"?void 0:n?.sessionId,c=q9(t,e,r,n?.headers,a),l=G9(t,e,n),d=await n?.onPayload?.(l,t);d!==void 0&&(l=d);let u={...n?.signal?{signal:n.signal}:{},...n?.timeoutMs!==void 0?{timeout:n.timeoutMs}:{},...n?.maxRetries!==void 0?{maxRetries:n.maxRetries}:{}},{data:p,response:m}=await c.responses.create(l,u).withResponse();if(await n?.onResponse?.({status:m.status,headers:gn(m.headers)},t),i.push({type:"start",partial:s}),await ir(p,s,i,t,{serviceTier:n?.serviceTier,applyServiceTierPricing:(g,h)=>H9(g,h,t)}),n?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");i.push({type:"done",reason:s.stopReason,message:s}),i.end()}catch(r){for(let o of s.content)delete o.index,delete o.partialJson;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=N9(r),i.push({type:"error",reason:s.stopReason,error:s}),i.end()}})(),i},j9=(t,e,n)=>{let i=n?.apiKey||Ke(t.provider);if(!i)throw new Error(`No API key for provider: ${t.provider}`);let s=Pt(t,n,i),r=n?.reasoning?Rt(t,n.reasoning):void 0;return qS(t,e,{...s,reasoningEffort:r==="off"?void 0:r})}});var Ut=T(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.HasPropertyKey=gj;xt.IsAsyncIterator=fj;xt.IsArray=Bb;xt.IsBigInt=bj;xt.IsBoolean=xj;xt.IsDate=yj;xt.IsFunction=vj;xt.IsIterator=wj;xt.IsNull=Sj;xt.IsNumber=Cj;xt.IsObject=Nb;xt.IsRegExp=Tj;xt.IsString=kj;xt.IsSymbol=Mj;xt.IsUint8Array=jb;xt.IsUndefined=Ij;function gj(t,e){return e in t}function fj(t){return Nb(t)&&!Bb(t)&&!jb(t)&&Symbol.asyncIterator in t}function Bb(t){return Array.isArray(t)}function bj(t){return typeof t=="bigint"}function xj(t){return typeof t=="boolean"}function yj(t){return t instanceof globalThis.Date}function vj(t){return typeof t=="function"}function wj(t){return Nb(t)&&!Bb(t)&&!jb(t)&&Symbol.iterator in t}function Sj(t){return t===null}function Cj(t){return typeof t=="number"}function Nb(t){return typeof t=="object"&&t!==null}function Tj(t){return t instanceof globalThis.RegExp}function kj(t){return typeof t=="string"}function Mj(t){return typeof t=="symbol"}function jb(t){return t instanceof globalThis.Uint8Array}function Ij(t){return t===void 0}});var tn=T(Qi=>{"use strict";var Rj=Qi&&Qi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Pj=Qi&&Qi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_j=Qi&&Qi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Rj(n,e,i[s]);return Pj(n,e),n}})();Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Clone=Uj;var du=_j(Ut());function Ej(t){return t.map(e=>Mm(e))}function Aj(t){return new Date(t.getTime())}function Oj(t){return new Uint8Array(t)}function Lj(t){return new RegExp(t.source,t.flags)}function Wj(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Mm(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Mm(t[n]);return e}function Mm(t){return du.IsArray(t)?Ej(t):du.IsDate(t)?Aj(t):du.IsUint8Array(t)?Oj(t):du.IsRegExp(t)?Lj(t):du.IsObject(t)?Wj(t):t}function Uj(t){return Mm(t)}});var Rm=T(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});Im.CloneRest=Fj;Im.CloneType=YI;var QI=tn();function Fj(t){return t.map(e=>YI(e))}function YI(t,e){return e===void 0?(0,QI.Clone)(t):(0,QI.Clone)({...e,...t})}});var qb=T(Bs=>{"use strict";var Dj=Bs&&Bs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),XI=Bs&&Bs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Dj(e,t,n)};Object.defineProperty(Bs,"__esModule",{value:!0});XI(Rm(),Bs);XI(tn(),Bs)});var cR=T(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.IsAsyncIterator=$j;ke.IsIterator=Bj;ke.IsStandardObject=Nj;ke.IsInstanceObject=jj;ke.IsPromise=qj;ke.IsDate=Gj;ke.IsMap=Kj;ke.IsSet=Hj;ke.IsRegExp=zj;ke.IsTypedArray=Vj;ke.IsInt8Array=Jj;ke.IsUint8Array=Qj;ke.IsUint8ClampedArray=Yj;ke.IsInt16Array=Xj;ke.IsUint16Array=Zj;ke.IsInt32Array=eq;ke.IsUint32Array=tq;ke.IsFloat32Array=nq;ke.IsFloat64Array=iq;ke.IsBigInt64Array=sq;ke.IsBigUint64Array=rq;ke.HasPropertyKey=oq;ke.IsObject=pu;ke.IsArray=ZI;ke.IsUndefined=eR;ke.IsNull=tR;ke.IsBoolean=nR;ke.IsNumber=iR;ke.IsInteger=aq;ke.IsBigInt=sR;ke.IsString=rR;ke.IsFunction=oR;ke.IsSymbol=aR;ke.IsValueType=cq;function $j(t){return pu(t)&&globalThis.Symbol.asyncIterator in t}function Bj(t){return pu(t)&&globalThis.Symbol.iterator in t}function Nj(t){return pu(t)&&(globalThis.Object.getPrototypeOf(t)===Object.prototype||globalThis.Object.getPrototypeOf(t)===null)}function jj(t){return pu(t)&&!ZI(t)&&oR(t.constructor)&&t.constructor.name!=="Object"}function qj(t){return t instanceof globalThis.Promise}function Gj(t){return t instanceof Date&&globalThis.Number.isFinite(t.getTime())}function Kj(t){return t instanceof globalThis.Map}function Hj(t){return t instanceof globalThis.Set}function zj(t){return t instanceof globalThis.RegExp}function Vj(t){return globalThis.ArrayBuffer.isView(t)}function Jj(t){return t instanceof globalThis.Int8Array}function Qj(t){return t instanceof globalThis.Uint8Array}function Yj(t){return t instanceof globalThis.Uint8ClampedArray}function Xj(t){return t instanceof globalThis.Int16Array}function Zj(t){return t instanceof globalThis.Uint16Array}function eq(t){return t instanceof globalThis.Int32Array}function tq(t){return t instanceof globalThis.Uint32Array}function nq(t){return t instanceof globalThis.Float32Array}function iq(t){return t instanceof globalThis.Float64Array}function sq(t){return t instanceof globalThis.BigInt64Array}function rq(t){return t instanceof globalThis.BigUint64Array}function oq(t,e){return e in t}function pu(t){return t!==null&&typeof t=="object"}function ZI(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function eR(t){return t===void 0}function tR(t){return t===null}function nR(t){return typeof t=="boolean"}function iR(t){return typeof t=="number"}function aq(t){return globalThis.Number.isInteger(t)}function sR(t){return typeof t=="bigint"}function rR(t){return typeof t=="string"}function oR(t){return typeof t=="function"}function aR(t){return typeof t=="symbol"}function cq(t){return sR(t)||nR(t)||tR(t)||iR(t)||rR(t)||aR(t)||eR(t)}});var lR=T(Wr=>{"use strict";var lq=Wr&&Wr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),uq=Wr&&Wr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&lq(e,t,n)};Object.defineProperty(Wr,"__esModule",{value:!0});uq(cR(),Wr)});var dR=T(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});_m.TypeSystemPolicy=void 0;var Pm=lR(),uR;(function(t){t.InstanceMode="default",t.ExactOptionalPropertyTypes=!1,t.AllowArrayObject=!1,t.AllowNaN=!1,t.AllowNullVoid=!1;function e(o,a){return t.ExactOptionalPropertyTypes?a in o:o[a]!==void 0}t.IsExactOptionalProperty=e;function n(o){let a=(0,Pm.IsObject)(o);return t.AllowArrayObject?a:a&&!(0,Pm.IsArray)(o)}t.IsObjectLike=n;function i(o){return n(o)&&!(o instanceof Date)&&!(o instanceof Uint8Array)}t.IsRecordLike=i;function s(o){return t.AllowNaN?(0,Pm.IsNumber)(o):Number.isFinite(o)}t.IsNumberLike=s;function r(o){let a=(0,Pm.IsUndefined)(o);return t.AllowNullVoid?a||o===null:a}t.IsVoidLike=r})(uR||(_m.TypeSystemPolicy=uR={}))});var pR=T(Yi=>{"use strict";var dq=Yi&&Yi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),pq=Yi&&Yi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),mq=Yi&&Yi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&dq(n,e,i[s]);return pq(n,e),n}})();Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Immutable=Em;var mu=mq(Ut());function hq(t){return globalThis.Object.freeze(t).map(e=>Em(e))}function gq(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Em(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Em(t[n]);return globalThis.Object.freeze(e)}function Em(t){return mu.IsArray(t)?hq(t):mu.IsDate(t)?t:mu.IsUint8Array(t)?t:mu.IsRegExp(t)?t:mu.IsObject(t)?gq(t):t}});var le=T(Gb=>{"use strict";Object.defineProperty(Gb,"__esModule",{value:!0});Gb.CreateType=yq;var fq=dR(),bq=pR(),xq=tn();function yq(t,e){let n=e!==void 0?{...e,...t}:t;switch(fq.TypeSystemPolicy.InstanceMode){case"freeze":return(0,bq.Immutable)(n);case"clone":return(0,xq.Clone)(n);default:return n}}});var Xi=T(Ur=>{"use strict";var vq=Ur&&Ur.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wq=Ur&&Ur.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vq(e,t,n)};Object.defineProperty(Ur,"__esModule",{value:!0});wq(le(),Ur)});var mR=T(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.TypeBoxError=void 0;var Kb=class extends Error{constructor(e){super(e)}};Am.TypeBoxError=Kb});var xi=T(Fr=>{"use strict";var Sq=Fr&&Fr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cq=Fr&&Fr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Sq(e,t,n)};Object.defineProperty(Fr,"__esModule",{value:!0});Cq(mR(),Fr)});var hu=T(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Kind=Fn.Hint=Fn.OptionalKind=Fn.ReadonlyKind=Fn.TransformKind=void 0;Fn.TransformKind=Symbol.for("TypeBox.Transform");Fn.ReadonlyKind=Symbol.for("TypeBox.Readonly");Fn.OptionalKind=Symbol.for("TypeBox.Optional");Fn.Hint=Symbol.for("TypeBox.Hint");Fn.Kind=Symbol.for("TypeBox.Kind")});var oe=T(Dr=>{"use strict";var Tq=Dr&&Dr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kq=Dr&&Dr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tq(e,t,n)};Object.defineProperty(Dr,"__esModule",{value:!0});kq(hu(),Dr)});var Me=T(re=>{"use strict";var Mq=re&&re.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Iq=re&&re.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Rq=re&&re.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Mq(n,e,i[s]);return Iq(n,e),n}})();Object.defineProperty(re,"__esModule",{value:!0});re.IsReadonly=Pq;re.IsOptional=_q;re.IsAny=hR;re.IsArgument=gR;re.IsArray=fR;re.IsAsyncIterator=bR;re.IsBigInt=xR;re.IsBoolean=yR;re.IsComputed=vR;re.IsConstructor=wR;re.IsDate=SR;re.IsFunction=CR;re.IsImport=Eq;re.IsInteger=TR;re.IsProperties=Aq;re.IsIntersect=kR;re.IsIterator=MR;re.IsKindOf=Se;re.IsLiteralString=Oq;re.IsLiteralNumber=Lq;re.IsLiteralBoolean=Wq;re.IsLiteralValue=Uq;re.IsLiteral=gu;re.IsMappedKey=IR;re.IsMappedResult=RR;re.IsNever=PR;re.IsNot=_R;re.IsNull=ER;re.IsNumber=AR;re.IsObject=OR;re.IsPromise=LR;re.IsRecord=WR;re.IsRecursive=Fq;re.IsRef=UR;re.IsRegExp=FR;re.IsString=DR;re.IsSymbol=$R;re.IsTemplateLiteral=BR;re.IsThis=NR;re.IsTransform=Dq;re.IsTuple=jR;re.IsUndefined=qR;re.IsUnion=GR;re.IsUint8Array=KR;re.IsUnknown=HR;re.IsUnsafe=zR;re.IsVoid=VR;re.IsKind=JR;re.IsSchema=$q;var nn=Rq(Ut()),Zi=oe();function Pq(t){return nn.IsObject(t)&&t[Zi.ReadonlyKind]==="Readonly"}function _q(t){return nn.IsObject(t)&&t[Zi.OptionalKind]==="Optional"}function hR(t){return Se(t,"Any")}function gR(t){return Se(t,"Argument")}function fR(t){return Se(t,"Array")}function bR(t){return Se(t,"AsyncIterator")}function xR(t){return Se(t,"BigInt")}function yR(t){return Se(t,"Boolean")}function vR(t){return Se(t,"Computed")}function wR(t){return Se(t,"Constructor")}function SR(t){return Se(t,"Date")}function CR(t){return Se(t,"Function")}function Eq(t){return Se(t,"Import")}function TR(t){return Se(t,"Integer")}function Aq(t){return nn.IsObject(t)}function kR(t){return Se(t,"Intersect")}function MR(t){return Se(t,"Iterator")}function Se(t,e){return nn.IsObject(t)&&Zi.Kind in t&&t[Zi.Kind]===e}function Oq(t){return gu(t)&&nn.IsString(t.const)}function Lq(t){return gu(t)&&nn.IsNumber(t.const)}function Wq(t){return gu(t)&&nn.IsBoolean(t.const)}function Uq(t){return nn.IsBoolean(t)||nn.IsNumber(t)||nn.IsString(t)}function gu(t){return Se(t,"Literal")}function IR(t){return Se(t,"MappedKey")}function RR(t){return Se(t,"MappedResult")}function PR(t){return Se(t,"Never")}function _R(t){return Se(t,"Not")}function ER(t){return Se(t,"Null")}function AR(t){return Se(t,"Number")}function OR(t){return Se(t,"Object")}function LR(t){return Se(t,"Promise")}function WR(t){return Se(t,"Record")}function Fq(t){return nn.IsObject(t)&&Zi.Hint in t&&t[Zi.Hint]==="Recursive"}function UR(t){return Se(t,"Ref")}function FR(t){return Se(t,"RegExp")}function DR(t){return Se(t,"String")}function $R(t){return Se(t,"Symbol")}function BR(t){return Se(t,"TemplateLiteral")}function NR(t){return Se(t,"This")}function Dq(t){return nn.IsObject(t)&&Zi.TransformKind in t}function jR(t){return Se(t,"Tuple")}function qR(t){return Se(t,"Undefined")}function GR(t){return Se(t,"Union")}function KR(t){return Se(t,"Uint8Array")}function HR(t){return Se(t,"Unknown")}function zR(t){return Se(t,"Unsafe")}function VR(t){return Se(t,"Void")}function JR(t){return nn.IsObject(t)&&Zi.Kind in t&&nn.IsString(t[Zi.Kind])}function $q(t){return hR(t)||gR(t)||fR(t)||yR(t)||xR(t)||bR(t)||vR(t)||wR(t)||SR(t)||CR(t)||TR(t)||kR(t)||MR(t)||gu(t)||IR(t)||RR(t)||PR(t)||_R(t)||ER(t)||AR(t)||OR(t)||LR(t)||WR(t)||UR(t)||FR(t)||DR(t)||$R(t)||BR(t)||NR(t)||jR(t)||qR(t)||GR(t)||KR(t)||HR(t)||zR(t)||VR(t)||JR(t)}});var DP=T(ie=>{"use strict";var Bq=ie&&ie.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Nq=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jq=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Bq(n,e,i[s]);return Nq(n,e),n}})();Object.defineProperty(ie,"__esModule",{value:!0});ie.TypeGuardUnknownTypeError=void 0;ie.IsReadonly=zq;ie.IsOptional=Vq;ie.IsAny=ZR;ie.IsArgument=eP;ie.IsArray=tP;ie.IsAsyncIterator=nP;ie.IsBigInt=iP;ie.IsBoolean=sP;ie.IsComputed=rP;ie.IsConstructor=oP;ie.IsDate=aP;ie.IsFunction=cP;ie.IsImport=Jq;ie.IsInteger=lP;ie.IsProperties=Om;ie.IsIntersect=uP;ie.IsIterator=dP;ie.IsKindOf=Ce;ie.IsLiteralString=pP;ie.IsLiteralNumber=mP;ie.IsLiteralBoolean=Qq;ie.IsLiteral=bu;ie.IsLiteralValue=hP;ie.IsMappedKey=gP;ie.IsMappedResult=fP;ie.IsNever=bP;ie.IsNot=xP;ie.IsNull=yP;ie.IsNumber=vP;ie.IsObject=wP;ie.IsPromise=SP;ie.IsRecord=CP;ie.IsRecursive=Yq;ie.IsRef=TP;ie.IsRegExp=kP;ie.IsString=MP;ie.IsSymbol=IP;ie.IsTemplateLiteral=RP;ie.IsThis=PP;ie.IsTransform=_P;ie.IsTuple=EP;ie.IsUndefined=AP;ie.IsUnionLiteral=Xq;ie.IsUnion=Jb;ie.IsUint8Array=OP;ie.IsUnknown=LP;ie.IsUnsafe=WP;ie.IsVoid=UP;ie.IsKind=FP;ie.IsSchema=yt;var se=jq(Ut()),yi=oe(),qq=xi(),Hb=class extends qq.TypeBoxError{};ie.TypeGuardUnknownTypeError=Hb;var Gq=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function QR(t){try{return new RegExp(t),!0}catch{return!1}}function zb(t){if(!se.IsString(t))return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function YR(t){return Vb(t)||yt(t)}function fu(t){return se.IsUndefined(t)||se.IsBigInt(t)}function Be(t){return se.IsUndefined(t)||se.IsNumber(t)}function Vb(t){return se.IsUndefined(t)||se.IsBoolean(t)}function Ue(t){return se.IsUndefined(t)||se.IsString(t)}function Kq(t){return se.IsUndefined(t)||se.IsString(t)&&zb(t)&&QR(t)}function Hq(t){return se.IsUndefined(t)||se.IsString(t)&&zb(t)}function XR(t){return se.IsUndefined(t)||yt(t)}function zq(t){return se.IsObject(t)&&t[yi.ReadonlyKind]==="Readonly"}function Vq(t){return se.IsObject(t)&&t[yi.OptionalKind]==="Optional"}function ZR(t){return Ce(t,"Any")&&Ue(t.$id)}function eP(t){return Ce(t,"Argument")&&se.IsNumber(t.index)}function tP(t){return Ce(t,"Array")&&t.type==="array"&&Ue(t.$id)&&yt(t.items)&&Be(t.minItems)&&Be(t.maxItems)&&Vb(t.uniqueItems)&&XR(t.contains)&&Be(t.minContains)&&Be(t.maxContains)}function nP(t){return Ce(t,"AsyncIterator")&&t.type==="AsyncIterator"&&Ue(t.$id)&&yt(t.items)}function iP(t){return Ce(t,"BigInt")&&t.type==="bigint"&&Ue(t.$id)&&fu(t.exclusiveMaximum)&&fu(t.exclusiveMinimum)&&fu(t.maximum)&&fu(t.minimum)&&fu(t.multipleOf)}function sP(t){return Ce(t,"Boolean")&&t.type==="boolean"&&Ue(t.$id)}function rP(t){return Ce(t,"Computed")&&se.IsString(t.target)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))}function oP(t){return Ce(t,"Constructor")&&t.type==="Constructor"&&Ue(t.$id)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))&&yt(t.returns)}function aP(t){return Ce(t,"Date")&&t.type==="Date"&&Ue(t.$id)&&Be(t.exclusiveMaximumTimestamp)&&Be(t.exclusiveMinimumTimestamp)&&Be(t.maximumTimestamp)&&Be(t.minimumTimestamp)&&Be(t.multipleOfTimestamp)}function cP(t){return Ce(t,"Function")&&t.type==="Function"&&Ue(t.$id)&&se.IsArray(t.parameters)&&t.parameters.every(e=>yt(e))&&yt(t.returns)}function Jq(t){return Ce(t,"Import")&&se.HasPropertyKey(t,"$defs")&&se.IsObject(t.$defs)&&Om(t.$defs)&&se.HasPropertyKey(t,"$ref")&&se.IsString(t.$ref)&&t.$ref in t.$defs}function lP(t){return Ce(t,"Integer")&&t.type==="integer"&&Ue(t.$id)&&Be(t.exclusiveMaximum)&&Be(t.exclusiveMinimum)&&Be(t.maximum)&&Be(t.minimum)&&Be(t.multipleOf)}function Om(t){return se.IsObject(t)&&Object.entries(t).every(([e,n])=>zb(e)&&yt(n))}function uP(t){return Ce(t,"Intersect")&&!(se.IsString(t.type)&&t.type!=="object")&&se.IsArray(t.allOf)&&t.allOf.every(e=>yt(e)&&!_P(e))&&Ue(t.type)&&(Vb(t.unevaluatedProperties)||XR(t.unevaluatedProperties))&&Ue(t.$id)}function dP(t){return Ce(t,"Iterator")&&t.type==="Iterator"&&Ue(t.$id)&&yt(t.items)}function Ce(t,e){return se.IsObject(t)&&yi.Kind in t&&t[yi.Kind]===e}function pP(t){return bu(t)&&se.IsString(t.const)}function mP(t){return bu(t)&&se.IsNumber(t.const)}function Qq(t){return bu(t)&&se.IsBoolean(t.const)}function bu(t){return Ce(t,"Literal")&&Ue(t.$id)&&hP(t.const)}function hP(t){return se.IsBoolean(t)||se.IsNumber(t)||se.IsString(t)}function gP(t){return Ce(t,"MappedKey")&&se.IsArray(t.keys)&&t.keys.every(e=>se.IsNumber(e)||se.IsString(e))}function fP(t){return Ce(t,"MappedResult")&&Om(t.properties)}function bP(t){return Ce(t,"Never")&&se.IsObject(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function xP(t){return Ce(t,"Not")&&yt(t.not)}function yP(t){return Ce(t,"Null")&&t.type==="null"&&Ue(t.$id)}function vP(t){return Ce(t,"Number")&&t.type==="number"&&Ue(t.$id)&&Be(t.exclusiveMaximum)&&Be(t.exclusiveMinimum)&&Be(t.maximum)&&Be(t.minimum)&&Be(t.multipleOf)}function wP(t){return Ce(t,"Object")&&t.type==="object"&&Ue(t.$id)&&Om(t.properties)&&YR(t.additionalProperties)&&Be(t.minProperties)&&Be(t.maxProperties)}function SP(t){return Ce(t,"Promise")&&t.type==="Promise"&&Ue(t.$id)&&yt(t.item)}function CP(t){return Ce(t,"Record")&&t.type==="object"&&Ue(t.$id)&&YR(t.additionalProperties)&&se.IsObject(t.patternProperties)&&(e=>{let n=Object.getOwnPropertyNames(e.patternProperties);return n.length===1&&QR(n[0])&&se.IsObject(e.patternProperties)&&yt(e.patternProperties[n[0]])})(t)}function Yq(t){return se.IsObject(t)&&yi.Hint in t&&t[yi.Hint]==="Recursive"}function TP(t){return Ce(t,"Ref")&&Ue(t.$id)&&se.IsString(t.$ref)}function kP(t){return Ce(t,"RegExp")&&Ue(t.$id)&&se.IsString(t.source)&&se.IsString(t.flags)&&Be(t.maxLength)&&Be(t.minLength)}function MP(t){return Ce(t,"String")&&t.type==="string"&&Ue(t.$id)&&Be(t.minLength)&&Be(t.maxLength)&&Kq(t.pattern)&&Hq(t.format)}function IP(t){return Ce(t,"Symbol")&&t.type==="symbol"&&Ue(t.$id)}function RP(t){return Ce(t,"TemplateLiteral")&&t.type==="string"&&se.IsString(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function PP(t){return Ce(t,"This")&&Ue(t.$id)&&se.IsString(t.$ref)}function _P(t){return se.IsObject(t)&&yi.TransformKind in t}function EP(t){return Ce(t,"Tuple")&&t.type==="array"&&Ue(t.$id)&&se.IsNumber(t.minItems)&&se.IsNumber(t.maxItems)&&t.minItems===t.maxItems&&(se.IsUndefined(t.items)&&se.IsUndefined(t.additionalItems)&&t.minItems===0||se.IsArray(t.items)&&t.items.every(e=>yt(e)))}function AP(t){return Ce(t,"Undefined")&&t.type==="undefined"&&Ue(t.$id)}function Xq(t){return Jb(t)&&t.anyOf.every(e=>pP(e)||mP(e))}function Jb(t){return Ce(t,"Union")&&Ue(t.$id)&&se.IsObject(t)&&se.IsArray(t.anyOf)&&t.anyOf.every(e=>yt(e))}function OP(t){return Ce(t,"Uint8Array")&&t.type==="Uint8Array"&&Ue(t.$id)&&Be(t.minByteLength)&&Be(t.maxByteLength)}function LP(t){return Ce(t,"Unknown")&&Ue(t.$id)}function WP(t){return Ce(t,"Unsafe")}function UP(t){return Ce(t,"Void")&&t.type==="void"&&Ue(t.$id)}function FP(t){return se.IsObject(t)&&yi.Kind in t&&se.IsString(t[yi.Kind])&&!Gq.includes(t[yi.Kind])}function yt(t){return se.IsObject(t)&&(ZR(t)||eP(t)||tP(t)||sP(t)||iP(t)||nP(t)||rP(t)||oP(t)||aP(t)||cP(t)||lP(t)||uP(t)||dP(t)||bu(t)||gP(t)||fP(t)||bP(t)||xP(t)||yP(t)||vP(t)||wP(t)||SP(t)||CP(t)||TP(t)||kP(t)||MP(t)||IP(t)||RP(t)||PP(t)||EP(t)||AP(t)||Jb(t)||OP(t)||LP(t)||WP(t)||UP(t)||FP(t))}});var Yb=T(sn=>{"use strict";var Zq=sn&&sn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),e7=sn&&sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Qb=sn&&sn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Zq(n,e,i[s]);return e7(n,e),n}})();Object.defineProperty(sn,"__esModule",{value:!0});sn.ValueGuard=sn.TypeGuard=sn.KindGuard=void 0;sn.KindGuard=Qb(Me());sn.TypeGuard=Qb(DP());sn.ValueGuard=Qb(Ut())});var $P=T(Xb=>{"use strict";Object.defineProperty(Xb,"__esModule",{value:!0});Xb.Increment=t7;function t7(t){return(parseInt(t)+1).toString()}});var BP=T($r=>{"use strict";var n7=$r&&$r.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),i7=$r&&$r.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&n7(e,t,n)};Object.defineProperty($r,"__esModule",{value:!0});i7($P(),$r)});var NP=T(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.PatternNeverExact=et.PatternStringExact=et.PatternNumberExact=et.PatternBooleanExact=et.PatternNever=et.PatternString=et.PatternNumber=et.PatternBoolean=void 0;et.PatternBoolean="(true|false)";et.PatternNumber="(0|[1-9][0-9]*)";et.PatternString="(.*)";et.PatternNever="(?!.*)";et.PatternBooleanExact=`^${et.PatternBoolean}$`;et.PatternNumberExact=`^${et.PatternNumber}$`;et.PatternStringExact=`^${et.PatternString}$`;et.PatternNeverExact=`^${et.PatternNever}$`});var xu=T(Br=>{"use strict";var s7=Br&&Br.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),r7=Br&&Br.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&s7(e,t,n)};Object.defineProperty(Br,"__esModule",{value:!0});r7(NP(),Br)});var jP=T(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.Entries=o7;Ns.Clear=a7;Ns.Delete=c7;Ns.Has=l7;Ns.Set=u7;Ns.Get=d7;var dc=new Map;function o7(){return new Map(dc)}function a7(){return dc.clear()}function c7(t){return dc.delete(t)}function l7(t){return dc.has(t)}function u7(t,e){dc.set(t,e)}function d7(t){return dc.get(t)}});var qP=T(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.Entries=p7;js.Clear=m7;js.Delete=h7;js.Has=g7;js.Set=f7;js.Get=b7;var pc=new Map;function p7(){return new Map(pc)}function m7(){return pc.clear()}function h7(t){return pc.delete(t)}function g7(t){return pc.has(t)}function f7(t,e){pc.set(t,e)}function b7(t){return pc.get(t)}});var KP=T(Dn=>{"use strict";var x7=Dn&&Dn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),y7=Dn&&Dn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),GP=Dn&&Dn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&x7(n,e,i[s]);return y7(n,e),n}})();Object.defineProperty(Dn,"__esModule",{value:!0});Dn.TypeRegistry=Dn.FormatRegistry=void 0;Dn.FormatRegistry=GP(jP());Dn.TypeRegistry=GP(qP())});var VP=T(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.SetIncludes=HP;vi.SetIsSubset=v7;vi.SetDistinct=w7;vi.SetIntersect=zP;vi.SetUnion=S7;vi.SetComplement=C7;vi.SetIntersectMany=k7;vi.SetUnionMany=M7;function HP(t,e){return t.includes(e)}function v7(t,e){return t.every(n=>HP(e,n))}function w7(t){return[...new Set(t)]}function zP(t,e){return t.filter(n=>e.includes(n))}function S7(t,e){return[...t,...e]}function C7(t,e){return t.filter(n=>!e.includes(n))}function T7(t,e){return t.reduce((n,i)=>zP(n,i),e)}function k7(t){return t.length===1?t[0]:t.length>1?T7(t.slice(1),t[0]):[]}function M7(t){let e=[];for(let n of t)e.push(...n);return e}});var yu=T(Nr=>{"use strict";var I7=Nr&&Nr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),R7=Nr&&Nr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&I7(e,t,n)};Object.defineProperty(Nr,"__esModule",{value:!0});R7(VP(),Nr)});var JP=T(Zb=>{"use strict";Object.defineProperty(Zb,"__esModule",{value:!0});Zb.Any=E7;var P7=Xi(),_7=oe();function E7(t){return(0,P7.CreateType)({[_7.Kind]:"Any"},t)}});var mc=T(jr=>{"use strict";var A7=jr&&jr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),O7=jr&&jr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&A7(e,t,n)};Object.defineProperty(jr,"__esModule",{value:!0});O7(JP(),jr)});var QP=T(ex=>{"use strict";Object.defineProperty(ex,"__esModule",{value:!0});ex.Array=U7;var L7=le(),W7=oe();function U7(t,e){return(0,L7.CreateType)({[W7.Kind]:"Array",type:"array",items:t},e)}});var hc=T(qr=>{"use strict";var F7=qr&&qr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),D7=qr&&qr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&F7(e,t,n)};Object.defineProperty(qr,"__esModule",{value:!0});D7(QP(),qr)});var YP=T(tx=>{"use strict";Object.defineProperty(tx,"__esModule",{value:!0});tx.Argument=N7;var $7=le(),B7=oe();function N7(t){return(0,$7.CreateType)({[B7.Kind]:"Argument",index:t})}});var Lm=T(Gr=>{"use strict";var j7=Gr&&Gr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),q7=Gr&&Gr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&j7(e,t,n)};Object.defineProperty(Gr,"__esModule",{value:!0});q7(YP(),Gr)});var XP=T(nx=>{"use strict";Object.defineProperty(nx,"__esModule",{value:!0});nx.AsyncIterator=H7;var G7=oe(),K7=le();function H7(t,e){return(0,K7.CreateType)({[G7.Kind]:"AsyncIterator",type:"AsyncIterator",items:t},e)}});var gc=T(Kr=>{"use strict";var z7=Kr&&Kr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),V7=Kr&&Kr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&z7(e,t,n)};Object.defineProperty(Kr,"__esModule",{value:!0});V7(XP(),Kr)});var ZP=T(ix=>{"use strict";Object.defineProperty(ix,"__esModule",{value:!0});ix.Computed=Y7;var J7=Xi(),Q7=hu();function Y7(t,e,n){return(0,J7.CreateType)({[Q7.Kind]:"Computed",target:t,parameters:e},n)}});var qs=T(Hr=>{"use strict";var X7=Hr&&Hr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Z7=Hr&&Hr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&X7(e,t,n)};Object.defineProperty(Hr,"__esModule",{value:!0});Z7(ZP(),Hr)});var Wm=T(sx=>{"use strict";Object.defineProperty(sx,"__esModule",{value:!0});sx.Discard=tG;function eG(t,e){let{[e]:n,...i}=t;return i}function tG(t,e){return e.reduce((n,i)=>eG(n,i),t)}});var es=T(zr=>{"use strict";var nG=zr&&zr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),iG=zr&&zr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&nG(e,t,n)};Object.defineProperty(zr,"__esModule",{value:!0});iG(Wm(),zr)});var e_=T(rx=>{"use strict";Object.defineProperty(rx,"__esModule",{value:!0});rx.Never=oG;var sG=le(),rG=oe();function oG(t){return(0,sG.CreateType)({[rG.Kind]:"Never",not:{}},t)}});var vt=T(Vr=>{"use strict";var aG=Vr&&Vr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),cG=Vr&&Vr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aG(e,t,n)};Object.defineProperty(Vr,"__esModule",{value:!0});cG(e_(),Vr)});var t_=T(ox=>{"use strict";Object.defineProperty(ox,"__esModule",{value:!0});ox.MappedKey=dG;var lG=le(),uG=oe();function dG(t){return(0,lG.CreateType)({[uG.Kind]:"MappedKey",keys:t})}});var cx=T(ax=>{"use strict";Object.defineProperty(ax,"__esModule",{value:!0});ax.MappedResult=hG;var pG=le(),mG=oe();function hG(t){return(0,pG.CreateType)({[mG.Kind]:"MappedResult",properties:t})}});var n_=T(lx=>{"use strict";Object.defineProperty(lx,"__esModule",{value:!0});lx.Constructor=bG;var gG=le(),fG=oe();function bG(t,e,n){return(0,gG.CreateType)({[fG.Kind]:"Constructor",type:"Constructor",parameters:t,returns:e},n)}});var fc=T(Jr=>{"use strict";var xG=Jr&&Jr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),yG=Jr&&Jr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xG(e,t,n)};Object.defineProperty(Jr,"__esModule",{value:!0});yG(n_(),Jr)});var i_=T(ux=>{"use strict";Object.defineProperty(ux,"__esModule",{value:!0});ux.Function=SG;var vG=le(),wG=oe();function SG(t,e,n){return(0,vG.CreateType)({[wG.Kind]:"Function",type:"Function",parameters:t,returns:e},n)}});var Gs=T(Qr=>{"use strict";var CG=Qr&&Qr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),TG=Qr&&Qr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&CG(e,t,n)};Object.defineProperty(Qr,"__esModule",{value:!0});TG(i_(),Qr)});var px=T(dx=>{"use strict";Object.defineProperty(dx,"__esModule",{value:!0});dx.UnionCreate=IG;var kG=le(),MG=oe();function IG(t,e){return(0,kG.CreateType)({[MG.Kind]:"Union",anyOf:t},e)}});var a_=T(mx=>{"use strict";Object.defineProperty(mx,"__esModule",{value:!0});mx.UnionEvaluated=UG;var RG=le(),PG=oe(),_G=es(),EG=vt(),AG=wi(),s_=px(),o_=Me();function OG(t){return t.some(e=>(0,o_.IsOptional)(e))}function r_(t){return t.map(e=>(0,o_.IsOptional)(e)?LG(e):e)}function LG(t){return(0,_G.Discard)(t,[PG.OptionalKind])}function WG(t,e){return OG(t)?(0,AG.Optional)((0,s_.UnionCreate)(r_(t),e)):(0,s_.UnionCreate)(r_(t),e)}function UG(t,e){return t.length===1?(0,RG.CreateType)(t[0],e):t.length===0?(0,EG.Never)(e):WG(t,e)}});var l_=T(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var aPe=oe()});var u_=T(hx=>{"use strict";Object.defineProperty(hx,"__esModule",{value:!0});hx.Union=BG;var FG=vt(),DG=le(),$G=px();function BG(t,e){return t.length===0?(0,FG.Never)(e):t.length===1?(0,DG.CreateType)(t[0],e):(0,$G.UnionCreate)(t,e)}});var st=T(ts=>{"use strict";var NG=ts&&ts.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),gx=ts&&ts.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&NG(e,t,n)};Object.defineProperty(ts,"__esModule",{value:!0});gx(a_(),ts);gx(l_(),ts);gx(u_(),ts)});var Um=T(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.TemplateLiteralParserError=void 0;bc.TemplateLiteralParse=Yr;bc.TemplateLiteralParseExact=QG;var jG=xi(),vu=class extends jG.TypeBoxError{};bc.TemplateLiteralParserError=vu;function qG(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function fx(t,e,n){return t[e]===n&&t.charCodeAt(e-1)!==92}function ns(t,e){return fx(t,e,"(")}function wu(t,e){return fx(t,e,")")}function d_(t,e){return fx(t,e,"|")}function GG(t){if(!(ns(t,0)&&wu(t,t.length-1)))return!1;let e=0;for(let n=0;n<t.length;n++)if(ns(t,n)&&(e+=1),wu(t,n)&&(e-=1),e===0&&n!==t.length-1)return!1;return!0}function KG(t){return t.slice(1,t.length-1)}function HG(t){let e=0;for(let n=0;n<t.length;n++)if(ns(t,n)&&(e+=1),wu(t,n)&&(e-=1),d_(t,n)&&e===0)return!0;return!1}function zG(t){for(let e=0;e<t.length;e++)if(ns(t,e))return!0;return!1}function VG(t){let[e,n]=[0,0],i=[];for(let r=0;r<t.length;r++)if(ns(t,r)&&(e+=1),wu(t,r)&&(e-=1),d_(t,r)&&e===0){let o=t.slice(n,r);o.length>0&&i.push(Yr(o)),n=r+1}let s=t.slice(n);return s.length>0&&i.push(Yr(s)),i.length===0?{type:"const",const:""}:i.length===1?i[0]:{type:"or",expr:i}}function JG(t){function e(s,r){if(!ns(s,r))throw new vu("TemplateLiteralParser: Index must point to open parens");let o=0;for(let a=r;a<s.length;a++)if(ns(s,a)&&(o+=1),wu(s,a)&&(o-=1),o===0)return[r,a];throw new vu("TemplateLiteralParser: Unclosed group parens in expression")}function n(s,r){for(let o=r;o<s.length;o++)if(ns(s,o))return[r,o];return[r,s.length]}let i=[];for(let s=0;s<t.length;s++)if(ns(t,s)){let[r,o]=e(t,s),a=t.slice(r,o+1);i.push(Yr(a)),s=o}else{let[r,o]=n(t,s),a=t.slice(r,o);a.length>0&&i.push(Yr(a)),s=o-1}return i.length===0?{type:"const",const:""}:i.length===1?i[0]:{type:"and",expr:i}}function Yr(t){return GG(t)?Yr(KG(t)):HG(t)?VG(t):zG(t)?JG(t):{type:"const",const:qG(t)}}function QG(t){return Yr(t.slice(1,t.length-1))}});var bx=T(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.TemplateLiteralFiniteError=void 0;xc.IsTemplateLiteralExpressionFinite=Dm;xc.IsTemplateLiteralFinite=nK;var YG=Um(),XG=xi(),Fm=class extends XG.TypeBoxError{};xc.TemplateLiteralFiniteError=Fm;function ZG(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="0"&&t.expr[1].type==="const"&&t.expr[1].const==="[1-9][0-9]*"}function eK(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="true"&&t.expr[1].type==="const"&&t.expr[1].const==="false"}function tK(t){return t.type==="const"&&t.const===".*"}function Dm(t){return ZG(t)||tK(t)?!1:eK(t)?!0:t.type==="and"?t.expr.every(e=>Dm(e)):t.type==="or"?t.expr.every(e=>Dm(e)):t.type==="const"?!0:(()=>{throw new Fm("Unknown expression type")})()}function nK(t){let e=(0,YG.TemplateLiteralParseExact)(t.pattern);return Dm(e)}});var xx=T(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.TemplateLiteralGenerateError=void 0;yc.TemplateLiteralExpressionGenerate=Bm;yc.TemplateLiteralGenerate=lK;var iK=bx(),sK=Um(),rK=xi(),$m=class extends rK.TypeBoxError{};yc.TemplateLiteralGenerateError=$m;function*p_(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let n of p_(t.slice(1)))yield`${e}${n}`}function*oK(t){return yield*p_(t.expr.map(e=>[...Bm(e)]))}function*aK(t){for(let e of t.expr)yield*Bm(e)}function*cK(t){return yield t.const}function*Bm(t){return t.type==="and"?yield*oK(t):t.type==="or"?yield*aK(t):t.type==="const"?yield*cK(t):(()=>{throw new $m("Unknown expression")})()}function lK(t){let e=(0,sK.TemplateLiteralParseExact)(t.pattern);return(0,iK.IsTemplateLiteralExpressionFinite)(e)?[...Bm(e)]:[]}});var m_=T(yx=>{"use strict";Object.defineProperty(yx,"__esModule",{value:!0});yx.Literal=pK;var uK=le(),dK=oe();function pK(t,e){return(0,uK.CreateType)({[dK.Kind]:"Literal",const:t,type:typeof t},e)}});var Ft=T(Xr=>{"use strict";var mK=Xr&&Xr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),hK=Xr&&Xr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&mK(e,t,n)};Object.defineProperty(Xr,"__esModule",{value:!0});hK(m_(),Xr)});var h_=T(vx=>{"use strict";Object.defineProperty(vx,"__esModule",{value:!0});vx.Boolean=bK;var gK=oe(),fK=Xi();function bK(t){return(0,fK.CreateType)({[gK.Kind]:"Boolean",type:"boolean"},t)}});var Su=T(Zr=>{"use strict";var xK=Zr&&Zr.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),yK=Zr&&Zr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xK(e,t,n)};Object.defineProperty(Zr,"__esModule",{value:!0});yK(h_(),Zr)});var g_=T(wx=>{"use strict";Object.defineProperty(wx,"__esModule",{value:!0});wx.BigInt=SK;var vK=oe(),wK=Xi();function SK(t){return(0,wK.CreateType)({[vK.Kind]:"BigInt",type:"bigint"},t)}});var vc=T(eo=>{"use strict";var CK=eo&&eo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),TK=eo&&eo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&CK(e,t,n)};Object.defineProperty(eo,"__esModule",{value:!0});TK(g_(),eo)});var f_=T(Sx=>{"use strict";Object.defineProperty(Sx,"__esModule",{value:!0});Sx.Number=IK;var kK=le(),MK=oe();function IK(t){return(0,kK.CreateType)({[MK.Kind]:"Number",type:"number"},t)}});var Ks=T(to=>{"use strict";var RK=to&&to.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),PK=to&&to.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&RK(e,t,n)};Object.defineProperty(to,"__esModule",{value:!0});PK(f_(),to)});var b_=T(Cx=>{"use strict";Object.defineProperty(Cx,"__esModule",{value:!0});Cx.String=AK;var _K=le(),EK=oe();function AK(t){return(0,_K.CreateType)({[EK.Kind]:"String",type:"string"},t)}});var io=T(no=>{"use strict";var OK=no&&no.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),LK=no&&no.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&OK(e,t,n)};Object.defineProperty(no,"__esModule",{value:!0});LK(b_(),no)});var Mx=T(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});kx.TemplateLiteralSyntax=qK;var Cu=Ft(),WK=Su(),UK=vc(),FK=Ks(),DK=io(),$K=st(),BK=vt();function*NK(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield(0,WK.Boolean)():e==="number"?yield(0,FK.Number)():e==="bigint"?yield(0,UK.BigInt)():e==="string"?yield(0,DK.String)():yield(()=>{let n=e.split("|").map(i=>(0,Cu.Literal)(i.trim()));return n.length===0?(0,BK.Never)():n.length===1?n[0]:(0,$K.UnionEvaluated)(n)})()}function*jK(t){if(t[1]!=="{"){let e=(0,Cu.Literal)("$"),n=Tx(t.slice(1));return yield*[e,...n]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let n=NK(t.slice(2,e)),i=Tx(t.slice(e+1));return yield*[...n,...i]}yield(0,Cu.Literal)(t)}function*Tx(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let n=(0,Cu.Literal)(t.slice(0,e)),i=jK(t.slice(e));return yield*[n,...i]}yield(0,Cu.Literal)(t)}function qK(t){return[...Tx(t)]}});var Ix=T(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.TemplateLiteralPatternError=void 0;ku.TemplateLiteralPattern=zK;var Tu=xu(),GK=oe(),KK=xi(),Hs=Me(),Nm=class extends KK.TypeBoxError{};ku.TemplateLiteralPatternError=Nm;function HK(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x_(t,e){return(0,Hs.IsTemplateLiteral)(t)?t.pattern.slice(1,t.pattern.length-1):(0,Hs.IsUnion)(t)?`(${t.anyOf.map(n=>x_(n,e)).join("|")})`:(0,Hs.IsNumber)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsInteger)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsBigInt)(t)?`${e}${Tu.PatternNumber}`:(0,Hs.IsString)(t)?`${e}${Tu.PatternString}`:(0,Hs.IsLiteral)(t)?`${e}${HK(t.const.toString())}`:(0,Hs.IsBoolean)(t)?`${e}${Tu.PatternBoolean}`:(()=>{throw new Nm(`Unexpected Kind '${t[GK.Kind]}'`)})()}function zK(t){return`^${t.map(e=>x_(e,"")).join("")}$`}});var y_=T(Rx=>{"use strict";Object.defineProperty(Rx,"__esModule",{value:!0});Rx.TemplateLiteralToUnion=YK;var VK=st(),JK=Ft(),QK=xx();function YK(t){let n=(0,QK.TemplateLiteralGenerate)(t).map(i=>(0,JK.Literal)(i));return(0,VK.UnionEvaluated)(n)}});var w_=T(Px=>{"use strict";Object.defineProperty(Px,"__esModule",{value:!0});Px.TemplateLiteral=nH;var XK=le(),ZK=Mx(),v_=Ix(),eH=Ut(),tH=oe();function nH(t,e){let n=(0,eH.IsString)(t)?(0,v_.TemplateLiteralPattern)((0,ZK.TemplateLiteralSyntax)(t)):(0,v_.TemplateLiteralPattern)(t);return(0,XK.CreateType)({[tH.Kind]:"TemplateLiteral",type:"string",pattern:n},e)}});var Si=T(Sn=>{"use strict";var iH=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),so=Sn&&Sn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iH(e,t,n)};Object.defineProperty(Sn,"__esModule",{value:!0});so(bx(),Sn);so(xx(),Sn);so(Mx(),Sn);so(Um(),Sn);so(Ix(),Sn);so(y_(),Sn);so(w_(),Sn)});var jm=T(_x=>{"use strict";Object.defineProperty(_x,"__esModule",{value:!0});_x.IndexPropertyKeys=S_;var sH=Si(),Mu=Me();function rH(t){return(0,sH.TemplateLiteralGenerate)(t).map(n=>n.toString())}function oH(t){let e=[];for(let n of t)e.push(...S_(n));return e}function aH(t){return[t.toString()]}function S_(t){return[...new Set((0,Mu.IsTemplateLiteral)(t)?rH(t):(0,Mu.IsUnion)(t)?oH(t.anyOf):(0,Mu.IsLiteral)(t)?aH(t.const):(0,Mu.IsNumber)(t)?["[number]"]:(0,Mu.IsInteger)(t)?["[number]"]:[])]}});var Ax=T(Ex=>{"use strict";Object.defineProperty(Ex,"__esModule",{value:!0});Ex.IndexFromMappedResult=mH;var cH=ot(),lH=jm(),uH=ti();function dH(t,e,n){let i={};for(let s of Object.getOwnPropertyNames(e))i[s]=(0,uH.Index)(t,(0,lH.IndexPropertyKeys)(e[s]),n);return i}function pH(t,e,n){return dH(t,e.properties,n)}function mH(t,e,n){let i=pH(t,e,n);return(0,cH.MappedResult)(i)}});var Gm=T(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.IndexFromPropertyKey=Lx;wc.IndexFromPropertyKeys=M_;wc.IndexFromComputed=IH;wc.Index=RH;var hH=le(),gH=xi(),T_=qs(),qm=vt(),fH=Cn(),Ox=st(),bH=jm(),xH=Wx(),yH=Ax(),rn=Me();function k_(t,e){return t.map(n=>Lx(n,e))}function vH(t){return t.filter(e=>!(0,rn.IsNever)(e))}function wH(t,e){return(0,fH.IntersectEvaluated)(vH(k_(t,e)))}function SH(t){return t.some(e=>(0,rn.IsNever)(e))?[]:t}function CH(t,e){return(0,Ox.UnionEvaluated)(SH(k_(t,e)))}function TH(t,e){return e in t?t[e]:e==="[number]"?(0,Ox.UnionEvaluated)(t):(0,qm.Never)()}function kH(t,e){return e==="[number]"?t:(0,qm.Never)()}function MH(t,e){return e in t?t[e]:(0,qm.Never)()}function Lx(t,e){return(0,rn.IsIntersect)(t)?wH(t.allOf,e):(0,rn.IsUnion)(t)?CH(t.anyOf,e):(0,rn.IsTuple)(t)?TH(t.items??[],e):(0,rn.IsArray)(t)?kH(t.items,e):(0,rn.IsObject)(t)?MH(t.properties,e):(0,qm.Never)()}function M_(t,e){return e.map(n=>Lx(t,n))}function C_(t,e){return(0,Ox.UnionEvaluated)(M_(t,e))}function IH(t,e){return(0,T_.Computed)("Index",[t,e])}function RH(t,e,n){if((0,rn.IsRef)(t)||(0,rn.IsRef)(e)){let i="Index types using Ref parameters require both Type and Key to be of TSchema";if(!(0,rn.IsSchema)(t)||!(0,rn.IsSchema)(e))throw new gH.TypeBoxError(i);return(0,T_.Computed)("Index",[t,e])}return(0,rn.IsMappedResult)(e)?(0,yH.IndexFromMappedResult)(t,e,n):(0,rn.IsMappedKey)(e)?(0,xH.IndexFromMappedKey)(t,e,n):(0,hH.CreateType)((0,rn.IsSchema)(e)?C_(t,(0,bH.IndexPropertyKeys)(e)):C_(t,e),n)}});var Wx=T(Ux=>{"use strict";Object.defineProperty(Ux,"__esModule",{value:!0});Ux.IndexFromMappedKey=WH;var PH=Gm(),_H=ot(),EH=tn();function AH(t,e,n){return{[e]:(0,PH.Index)(t,[e],(0,EH.Clone)(n))}}function OH(t,e,n){return e.reduce((i,s)=>({...i,...AH(t,s,n)}),{})}function LH(t,e,n){return OH(t,e.keys,n)}function WH(t,e,n){let i=LH(t,e,n);return(0,_H.MappedResult)(i)}});var ti=T(Ci=>{"use strict";var UH=Ci&&Ci.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Km=Ci&&Ci.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&UH(e,t,n)};Object.defineProperty(Ci,"__esModule",{value:!0});Km(Wx(),Ci);Km(Ax(),Ci);Km(jm(),Ci);Km(Gm(),Ci)});var I_=T(Fx=>{"use strict";Object.defineProperty(Fx,"__esModule",{value:!0});Fx.Iterator=$H;var FH=le(),DH=oe();function $H(t,e){return(0,FH.CreateType)({[DH.Kind]:"Iterator",type:"Iterator",items:t},e)}});var Sc=T(ro=>{"use strict";var BH=ro&&ro.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),NH=ro&&ro.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&BH(e,t,n)};Object.defineProperty(ro,"__esModule",{value:!0});NH(I_(),ro)});var P_=T(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});Hm.Object=void 0;var jH=le(),R_=oe(),qH=Me();function GH(t){return globalThis.Object.keys(t).filter(e=>!(0,qH.IsOptional)(t[e]))}function KH(t,e){let n=GH(t),i=n.length>0?{[R_.Kind]:"Object",type:"object",required:n,properties:t}:{[R_.Kind]:"Object",type:"object",properties:t};return(0,jH.CreateType)(i,e)}Hm.Object=KH});var on=T(oo=>{"use strict";var HH=oo&&oo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),zH=oo&&oo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HH(e,t,n)};Object.defineProperty(oo,"__esModule",{value:!0});zH(P_(),oo)});var __=T(Dx=>{"use strict";Object.defineProperty(Dx,"__esModule",{value:!0});Dx.Promise=QH;var VH=le(),JH=oe();function QH(t,e){return(0,VH.CreateType)({[JH.Kind]:"Promise",type:"Promise",item:t},e)}});var Iu=T(ao=>{"use strict";var YH=ao&&ao.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),XH=ao&&ao.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&YH(e,t,n)};Object.defineProperty(ao,"__esModule",{value:!0});XH(__(),ao)});var Bx=T($x=>{"use strict";Object.defineProperty($x,"__esModule",{value:!0});$x.Readonly=rz;var E_=le(),A_=oe(),ZH=es(),ez=Nx(),tz=Me();function nz(t){return(0,E_.CreateType)((0,ZH.Discard)(t,[A_.ReadonlyKind]))}function iz(t){return(0,E_.CreateType)({...t,[A_.ReadonlyKind]:"Readonly"})}function sz(t,e){return e===!1?nz(t):iz(t)}function rz(t,e){let n=e??!0;return(0,tz.IsMappedResult)(t)?(0,ez.ReadonlyFromMappedResult)(t,n):sz(t,n)}});var Nx=T(jx=>{"use strict";Object.defineProperty(jx,"__esModule",{value:!0});jx.ReadonlyFromMappedResult=uz;var oz=ot(),az=Bx();function cz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,az.Readonly)(t[i],e);return n}function lz(t,e){return cz(t.properties,e)}function uz(t,e){let n=lz(t,e);return(0,oz.MappedResult)(n)}});var Vs=T(zs=>{"use strict";var dz=zs&&zs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),O_=zs&&zs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&dz(e,t,n)};Object.defineProperty(zs,"__esModule",{value:!0});O_(Nx(),zs);O_(Bx(),zs)});var W_=T(qx=>{"use strict";Object.defineProperty(qx,"__esModule",{value:!0});qx.Tuple=mz;var pz=le(),L_=oe();function mz(t,e){return(0,pz.CreateType)(t.length>0?{[L_.Kind]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[L_.Kind]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}});var is=T(co=>{"use strict";var hz=co&&co.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),gz=co&&co.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&hz(e,t,n)};Object.defineProperty(co,"__esModule",{value:!0});gz(W_(),co)});var N_=T(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.MappedFunctionReturnType=B_;zm.Mapped=Wz;var Gx=oe(),U_=es(),fz=hc(),bz=gc(),xz=fc(),yz=Gs(),vz=ti(),wz=Cn(),Sz=Sc(),F_=Ft(),D_=on(),Cz=wi(),Tz=Iu(),kz=Vs(),Mz=is(),Iz=st(),Rz=yu(),Pz=cx(),Dt=Me();function $_(t,e){return t in e?$n(t,e[t]):(0,Pz.MappedResult)(e)}function _z(t){return{[t]:(0,F_.Literal)(t)}}function Ez(t){let e={};for(let n of t)e[n]=(0,F_.Literal)(n);return e}function Az(t,e){return(0,Rz.SetIncludes)(e,t)?_z(t):Ez(e)}function Oz(t,e){let n=Az(t,e);return $_(t,n)}function Ru(t,e){return e.map(n=>$n(t,n))}function Lz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(e))n[i]=$n(t,e[i]);return n}function $n(t,e){let n={...e};return(0,Dt.IsOptional)(e)?(0,Cz.Optional)($n(t,(0,U_.Discard)(e,[Gx.OptionalKind]))):(0,Dt.IsReadonly)(e)?(0,kz.Readonly)($n(t,(0,U_.Discard)(e,[Gx.ReadonlyKind]))):(0,Dt.IsMappedResult)(e)?$_(t,e.properties):(0,Dt.IsMappedKey)(e)?Oz(t,e.keys):(0,Dt.IsConstructor)(e)?(0,xz.Constructor)(Ru(t,e.parameters),$n(t,e.returns),n):(0,Dt.IsFunction)(e)?(0,yz.Function)(Ru(t,e.parameters),$n(t,e.returns),n):(0,Dt.IsAsyncIterator)(e)?(0,bz.AsyncIterator)($n(t,e.items),n):(0,Dt.IsIterator)(e)?(0,Sz.Iterator)($n(t,e.items),n):(0,Dt.IsIntersect)(e)?(0,wz.Intersect)(Ru(t,e.allOf),n):(0,Dt.IsUnion)(e)?(0,Iz.Union)(Ru(t,e.anyOf),n):(0,Dt.IsTuple)(e)?(0,Mz.Tuple)(Ru(t,e.items??[]),n):(0,Dt.IsObject)(e)?(0,D_.Object)(Lz(t,e.properties),n):(0,Dt.IsArray)(e)?(0,fz.Array)($n(t,e.items),n):(0,Dt.IsPromise)(e)?(0,Tz.Promise)($n(t,e.item),n):e}function B_(t,e){let n={};for(let i of t)n[i]=$n(i,e);return n}function Wz(t,e,n){let i=(0,Dt.IsSchema)(t)?(0,vz.IndexPropertyKeys)(t):t,s=e({[Gx.Kind]:"MappedKey",keys:i}),r=B_(i,s);return(0,D_.Object)(r,n)}});var ot=T(ss=>{"use strict";var Uz=ss&&ss.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Kx=ss&&ss.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Uz(e,t,n)};Object.defineProperty(ss,"__esModule",{value:!0});Kx(t_(),ss);Kx(cx(),ss);Kx(N_(),ss)});var zx=T(Hx=>{"use strict";Object.defineProperty(Hx,"__esModule",{value:!0});Hx.Optional=qz;var j_=le(),q_=oe(),Fz=es(),Dz=Vx(),$z=Me();function Bz(t){return(0,j_.CreateType)((0,Fz.Discard)(t,[q_.OptionalKind]))}function Nz(t){return(0,j_.CreateType)({...t,[q_.OptionalKind]:"Optional"})}function jz(t,e){return e===!1?Bz(t):Nz(t)}function qz(t,e){let n=e??!0;return(0,$z.IsMappedResult)(t)?(0,Dz.OptionalFromMappedResult)(t,n):jz(t,n)}});var Vx=T(Jx=>{"use strict";Object.defineProperty(Jx,"__esModule",{value:!0});Jx.OptionalFromMappedResult=Vz;var Gz=ot(),Kz=zx();function Hz(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,Kz.Optional)(t[i],e);return n}function zz(t,e){return Hz(t.properties,e)}function Vz(t,e){let n=zz(t,e);return(0,Gz.MappedResult)(n)}});var wi=T(Js=>{"use strict";var Jz=Js&&Js.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),G_=Js&&Js.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Jz(e,t,n)};Object.defineProperty(Js,"__esModule",{value:!0});G_(Vx(),Js);G_(zx(),Js)});var Xx=T(Yx=>{"use strict";Object.defineProperty(Yx,"__esModule",{value:!0});Yx.IntersectCreate=Yz;var Qz=le(),K_=oe(),Qx=Me();function Yz(t,e={}){let n=t.every(s=>(0,Qx.IsObject)(s)),i=(0,Qx.IsSchema)(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return(0,Qz.CreateType)(e.unevaluatedProperties===!1||(0,Qx.IsSchema)(e.unevaluatedProperties)||n?{...i,[K_.Kind]:"Intersect",type:"object",allOf:t}:{...i,[K_.Kind]:"Intersect",allOf:t},e)}});var V_=T(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});ey.IntersectEvaluated=oV;var Xz=oe(),Zz=le(),eV=es(),tV=vt(),nV=wi(),H_=Xx(),Zx=Me();function iV(t){return t.every(e=>(0,Zx.IsOptional)(e))}function sV(t){return(0,eV.Discard)(t,[Xz.OptionalKind])}function z_(t){return t.map(e=>(0,Zx.IsOptional)(e)?sV(e):e)}function rV(t,e){return iV(t)?(0,nV.Optional)((0,H_.IntersectCreate)(z_(t),e)):(0,H_.IntersectCreate)(z_(t),e)}function oV(t,e={}){if(t.length===1)return(0,Zz.CreateType)(t[0],e);if(t.length===0)return(0,tV.Never)(e);if(t.some(n=>(0,Zx.IsTransform)(n)))throw new Error("Cannot intersect transform types");return rV(t,e)}});var Q_=T(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});var XPe=oe()});var Y_=T(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});ty.Intersect=dV;var aV=le(),cV=vt(),lV=Xx(),uV=Me();function dV(t,e){if(t.length===1)return(0,aV.CreateType)(t[0],e);if(t.length===0)return(0,cV.Never)(e);if(t.some(n=>(0,uV.IsTransform)(n)))throw new Error("Cannot intersect transform types");return(0,lV.IntersectCreate)(t,e)}});var Cn=T(rs=>{"use strict";var pV=rs&&rs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ny=rs&&rs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&pV(e,t,n)};Object.defineProperty(rs,"__esModule",{value:!0});ny(V_(),rs);ny(Q_(),rs);ny(Y_(),rs)});var X_=T(iy=>{"use strict";Object.defineProperty(iy,"__esModule",{value:!0});iy.Ref=fV;var mV=xi(),hV=le(),gV=oe();function fV(...t){let[e,n]=typeof t[0]=="string"?[t[0],t[1]]:[t[0].$id,t[1]];if(typeof e!="string")throw new mV.TypeBoxError("Ref: $ref must be a string");return(0,hV.CreateType)({[gV.Kind]:"Ref",$ref:e},n)}});var Qs=T(lo=>{"use strict";var bV=lo&&lo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xV=lo&&lo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bV(e,t,n)};Object.defineProperty(lo,"__esModule",{value:!0});xV(X_(),lo)});var eE=T(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});oy.Awaited=ry;var yV=le(),sy=qs(),vV=Cn(),wV=st(),SV=Qs(),Pu=Me();function CV(t,e){return(0,sy.Computed)("Awaited",[(0,sy.Computed)(t,e)])}function TV(t){return(0,sy.Computed)("Awaited",[(0,SV.Ref)(t)])}function kV(t){return(0,vV.Intersect)(Z_(t))}function MV(t){return(0,wV.Union)(Z_(t))}function IV(t){return ry(t)}function Z_(t){return t.map(e=>ry(e))}function ry(t,e){return(0,yV.CreateType)((0,Pu.IsComputed)(t)?CV(t.target,t.parameters):(0,Pu.IsIntersect)(t)?kV(t.allOf):(0,Pu.IsUnion)(t)?MV(t.anyOf):(0,Pu.IsPromise)(t)?IV(t.item):(0,Pu.IsRef)(t)?TV(t.$ref):t,e)}});var _u=T(uo=>{"use strict";var RV=uo&&uo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),PV=uo&&uo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&RV(e,t,n)};Object.defineProperty(uo,"__esModule",{value:!0});PV(eE(),uo)});var Jm=T(Vm=>{"use strict";Object.defineProperty(Vm,"__esModule",{value:!0});Vm.KeyOfPropertyKeys=cy;Vm.KeyOfPattern=UV;var tE=yu(),Cc=Me();function nE(t){let e=[];for(let n of t)e.push(cy(n));return e}function _V(t){let e=nE(t);return(0,tE.SetUnionMany)(e)}function EV(t){let e=nE(t);return(0,tE.SetIntersectMany)(e)}function AV(t){return t.map((e,n)=>n.toString())}function OV(t){return["[number]"]}function LV(t){return globalThis.Object.getOwnPropertyNames(t)}function WV(t){return ay?globalThis.Object.getOwnPropertyNames(t).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function cy(t){return(0,Cc.IsIntersect)(t)?_V(t.allOf):(0,Cc.IsUnion)(t)?EV(t.anyOf):(0,Cc.IsTuple)(t)?AV(t.items??[]):(0,Cc.IsArray)(t)?OV(t.items):(0,Cc.IsObject)(t)?LV(t.properties):(0,Cc.IsRecord)(t)?WV(t.patternProperties):[]}var ay=!1;function UV(t){ay=!0;let e=cy(t);return ay=!1,`^(${e.map(i=>`(${i})`).join("|")})$`}});var dy=T(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});Qm.KeyOfPropertyKeysToRest=iE;Qm.KeyOf=zV;var FV=le(),DV=Ft(),$V=Ks(),uy=qs(),BV=Qs(),NV=Jm(),jV=st(),qV=py(),ly=Me();function GV(t,e){return(0,uy.Computed)("KeyOf",[(0,uy.Computed)(t,e)])}function KV(t){return(0,uy.Computed)("KeyOf",[(0,BV.Ref)(t)])}function HV(t,e){let n=(0,NV.KeyOfPropertyKeys)(t),i=iE(n),s=(0,jV.UnionEvaluated)(i);return(0,FV.CreateType)(s,e)}function iE(t){return t.map(e=>e==="[number]"?(0,$V.Number)():(0,DV.Literal)(e))}function zV(t,e){return(0,ly.IsComputed)(t)?GV(t.target,t.parameters):(0,ly.IsRef)(t)?KV(t.$ref):(0,ly.IsMappedResult)(t)?(0,qV.KeyOfFromMappedResult)(t,e):HV(t,e)}});var py=T(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});my.KeyOfFromMappedResult=ZV;var VV=ot(),JV=dy(),QV=tn();function YV(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,JV.KeyOf)(t[i],(0,QV.Clone)(e));return n}function XV(t,e){return YV(t.properties,e)}function ZV(t,e){let n=XV(t,e);return(0,VV.MappedResult)(n)}});var sE=T(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});hy.KeyOfPropertyEntries=nJ;var eJ=Gm(),tJ=Jm();function nJ(t){let e=(0,tJ.KeyOfPropertyKeys)(t),n=(0,eJ.IndexFromPropertyKeys)(t,e);return e.map((i,s)=>[e[s],n[s]])}});var Tc=T(Ti=>{"use strict";var iJ=Ti&&Ti.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ym=Ti&&Ti.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iJ(e,t,n)};Object.defineProperty(Ti,"__esModule",{value:!0});Ym(py(),Ti);Ym(sE(),Ti);Ym(Jm(),Ti);Ym(dy(),Ti)});var rE=T(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});gy.Composite=hJ;var sJ=Cn(),rJ=ti(),oJ=Tc(),aJ=on(),cJ=yu(),lJ=Me();function uJ(t){let e=[];for(let n of t)e.push(...(0,oJ.KeyOfPropertyKeys)(n));return(0,cJ.SetDistinct)(e)}function dJ(t){return t.filter(e=>!(0,lJ.IsNever)(e))}function pJ(t,e){let n=[];for(let i of t)n.push(...(0,rJ.IndexFromPropertyKeys)(i,[e]));return dJ(n)}function mJ(t,e){let n={};for(let i of e)n[i]=(0,sJ.IntersectEvaluated)(pJ(t,i));return n}function hJ(t,e){let n=uJ(t),i=mJ(t,n);return(0,aJ.Object)(i,e)}});var Xm=T(po=>{"use strict";var gJ=po&&po.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),fJ=po&&po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gJ(e,t,n)};Object.defineProperty(po,"__esModule",{value:!0});fJ(rE(),po)});var oE=T(fy=>{"use strict";Object.defineProperty(fy,"__esModule",{value:!0});fy.Date=yJ;var bJ=oe(),xJ=le();function yJ(t){return(0,xJ.CreateType)({[bJ.Kind]:"Date",type:"Date"},t)}});var Eu=T(mo=>{"use strict";var vJ=mo&&mo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wJ=mo&&mo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vJ(e,t,n)};Object.defineProperty(mo,"__esModule",{value:!0});wJ(oE(),mo)});var aE=T(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});by.Null=TJ;var SJ=le(),CJ=oe();function TJ(t){return(0,SJ.CreateType)({[CJ.Kind]:"Null",type:"null"},t)}});var Au=T(ho=>{"use strict";var kJ=ho&&ho.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),MJ=ho&&ho.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&kJ(e,t,n)};Object.defineProperty(ho,"__esModule",{value:!0});MJ(aE(),ho)});var cE=T(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});xy.Symbol=PJ;var IJ=le(),RJ=oe();function PJ(t){return(0,IJ.CreateType)({[RJ.Kind]:"Symbol",type:"symbol"},t)}});var Ou=T(go=>{"use strict";var _J=go&&go.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),EJ=go&&go.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_J(e,t,n)};Object.defineProperty(go,"__esModule",{value:!0});EJ(cE(),go)});var lE=T(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});yy.Undefined=LJ;var AJ=le(),OJ=oe();function LJ(t){return(0,AJ.CreateType)({[OJ.Kind]:"Undefined",type:"undefined"},t)}});var Lu=T(fo=>{"use strict";var WJ=fo&&fo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),UJ=fo&&fo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WJ(e,t,n)};Object.defineProperty(fo,"__esModule",{value:!0});UJ(lE(),fo)});var uE=T(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});vy.Uint8Array=$J;var FJ=le(),DJ=oe();function $J(t){return(0,FJ.CreateType)({[DJ.Kind]:"Uint8Array",type:"Uint8Array"},t)}});var Wu=T(bo=>{"use strict";var BJ=bo&&bo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),NJ=bo&&bo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&BJ(e,t,n)};Object.defineProperty(bo,"__esModule",{value:!0});NJ(uE(),bo)});var dE=T(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});wy.Unknown=GJ;var jJ=le(),qJ=oe();function GJ(t){return(0,jJ.CreateType)({[qJ.Kind]:"Unknown"},t)}});var yo=T(xo=>{"use strict";var KJ=xo&&xo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),HJ=xo&&xo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&KJ(e,t,n)};Object.defineProperty(xo,"__esModule",{value:!0});HJ(dE(),xo)});var hE=T(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});ky.Const=rQ;var pE=mc(),zJ=vc(),VJ=Eu(),JJ=Gs(),Sy=Ft(),QJ=Au(),mE=on(),YJ=Ou(),XJ=is(),Cy=Vs(),ZJ=Lu(),eQ=Wu(),tQ=yo(),nQ=Xi(),an=Ut();function iQ(t){return t.map(e=>Ty(e,!1))}function sQ(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,Cy.Readonly)(Ty(t[n],!1));return e}function Zm(t,e){return e===!0?t:(0,Cy.Readonly)(t)}function Ty(t,e){return(0,an.IsAsyncIterator)(t)||(0,an.IsIterator)(t)?Zm((0,pE.Any)(),e):(0,an.IsArray)(t)?(0,Cy.Readonly)((0,XJ.Tuple)(iQ(t))):(0,an.IsUint8Array)(t)?(0,eQ.Uint8Array)():(0,an.IsDate)(t)?(0,VJ.Date)():(0,an.IsObject)(t)?Zm((0,mE.Object)(sQ(t)),e):(0,an.IsFunction)(t)?Zm((0,JJ.Function)([],(0,tQ.Unknown)()),e):(0,an.IsUndefined)(t)?(0,ZJ.Undefined)():(0,an.IsNull)(t)?(0,QJ.Null)():(0,an.IsSymbol)(t)?(0,YJ.Symbol)():(0,an.IsBigInt)(t)?(0,zJ.BigInt)():(0,an.IsNumber)(t)||(0,an.IsBoolean)(t)||(0,an.IsString)(t)?(0,Sy.Literal)(t):(0,mE.Object)({})}function rQ(t,e){return(0,nQ.CreateType)(Ty(t,!0),e)}});var eh=T(vo=>{"use strict";var oQ=vo&&vo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),aQ=vo&&vo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&oQ(e,t,n)};Object.defineProperty(vo,"__esModule",{value:!0});aQ(hE(),vo)});var gE=T(os=>{"use strict";var cQ=os&&os.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),lQ=os&&os.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uQ=os&&os.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&cQ(n,e,i[s]);return lQ(n,e),n}})();Object.defineProperty(os,"__esModule",{value:!0});os.ConstructorParameters=hQ;var dQ=is(),pQ=vt(),mQ=uQ(Me());function hQ(t,e){return mQ.IsConstructor(t)?(0,dQ.Tuple)(t.parameters,e):(0,pQ.Never)(e)}});var th=T(wo=>{"use strict";var gQ=wo&&wo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),fQ=wo&&wo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gQ(e,t,n)};Object.defineProperty(wo,"__esModule",{value:!0});fQ(gE(),wo)});var fE=T(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});My.Enum=wQ;var bQ=Ft(),xQ=oe(),yQ=st(),vQ=Ut();function wQ(t,e){if((0,vQ.IsUndefined)(t))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(t).filter(r=>isNaN(r)).map(r=>t[r]),s=[...new Set(n)].map(r=>(0,bQ.Literal)(r));return(0,yQ.Union)(s,{...e,[xQ.Hint]:"Enum"})}});var nh=T(So=>{"use strict";var SQ=So&&So.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),CQ=So&&So.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&SQ(e,t,n)};Object.defineProperty(So,"__esModule",{value:!0});CQ(fE(),So)});var Ly=T(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.ExtendsResult=Co.ExtendsResolverError=void 0;Co.ExtendsCheck=pY;var bE=mc(),TQ=Gs(),Ey=Ks(),Ry=io(),kQ=yo(),xE=Si(),kc=xu(),CE=oe(),MQ=xi(),k=Yb(),ih=class extends MQ.TypeBoxError{};Co.ExtendsResolverError=ih;var B;(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(B||(Co.ExtendsResult=B={}));function Bn(t){return t===B.False?t:B.True}function Mc(t){throw new ih(t)}function at(t){return k.TypeGuard.IsNever(t)||k.TypeGuard.IsIntersect(t)||k.TypeGuard.IsUnion(t)||k.TypeGuard.IsUnknown(t)||k.TypeGuard.IsAny(t)}function ct(t,e){return k.TypeGuard.IsNever(e)?ME(t,e):k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsUnknown(e)?_E(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):Mc("StructuralRight")}function Ay(t,e){return B.True}function IQ(t,e){return k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)&&e.anyOf.some(n=>k.TypeGuard.IsAny(n)||k.TypeGuard.IsUnknown(n))?B.True:k.TypeGuard.IsUnion(e)?B.Union:k.TypeGuard.IsUnknown(e)||k.TypeGuard.IsAny(e)?B.True:B.Union}function RQ(t,e){return k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:k.TypeGuard.IsNever(t)?B.True:B.False}function PQ(t,e){return k.TypeGuard.IsObject(e)&&rh(e)?B.True:at(e)?ct(t,e):k.TypeGuard.IsArray(e)?Bn(Fe(t.items,e.items)):B.False}function _Q(t,e){return at(e)?ct(t,e):k.TypeGuard.IsAsyncIterator(e)?Bn(Fe(t.items,e.items)):B.False}function EQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsBigInt(e)?B.True:B.False}function TE(t,e){return k.TypeGuard.IsLiteralBoolean(t)||k.TypeGuard.IsBoolean(t)?B.True:B.False}function AQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsBoolean(e)?B.True:B.False}function OQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsConstructor(e)?t.parameters.length>e.parameters.length?B.False:t.parameters.every((n,i)=>Bn(Fe(e.parameters[i],n))===B.True)?Bn(Fe(t.returns,e.returns)):B.False:B.False}function LQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsDate(e)?B.True:B.False}function WQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsFunction(e)?t.parameters.length>e.parameters.length?B.False:t.parameters.every((n,i)=>Bn(Fe(e.parameters[i],n))===B.True)?Bn(Fe(t.returns,e.returns)):B.False:B.False}function kE(t,e){return k.TypeGuard.IsLiteral(t)&&k.ValueGuard.IsNumber(t.const)||k.TypeGuard.IsNumber(t)||k.TypeGuard.IsInteger(t)?B.True:B.False}function UQ(t,e){return k.TypeGuard.IsInteger(e)||k.TypeGuard.IsNumber(e)?B.True:at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):B.False}function sh(t,e){return e.allOf.every(n=>Fe(t,n)===B.True)?B.True:B.False}function FQ(t,e){return t.allOf.some(n=>Fe(n,e)===B.True)?B.True:B.False}function DQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsIterator(e)?Bn(Fe(t.items,e.items)):B.False}function $Q(t,e){return k.TypeGuard.IsLiteral(e)&&e.const===t.const?B.True:at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsString(e)?PE(t,e):k.TypeGuard.IsNumber(e)?IE(t,e):k.TypeGuard.IsInteger(e)?kE(t,e):k.TypeGuard.IsBoolean(e)?TE(t,e):B.False}function ME(t,e){return B.False}function BQ(t,e){return B.True}function yE(t){let[e,n]=[t,0];for(;k.TypeGuard.IsNot(e);)e=e.not,n+=1;return n%2===0?e:(0,kQ.Unknown)()}function NQ(t,e){return k.TypeGuard.IsNot(t)?Fe(yE(t),e):k.TypeGuard.IsNot(e)?Fe(t,yE(e)):Mc("Invalid fallthrough for Not")}function jQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsNull(e)?B.True:B.False}function IE(t,e){return k.TypeGuard.IsLiteralNumber(t)||k.TypeGuard.IsNumber(t)||k.TypeGuard.IsInteger(t)?B.True:B.False}function qQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsInteger(e)||k.TypeGuard.IsNumber(e)?B.True:B.False}function cn(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function vE(t){return rh(t)}function wE(t){return cn(t,0)||cn(t,1)&&"description"in t.properties&&k.TypeGuard.IsUnion(t.properties.description)&&t.properties.description.anyOf.length===2&&(k.TypeGuard.IsString(t.properties.description.anyOf[0])&&k.TypeGuard.IsUndefined(t.properties.description.anyOf[1])||k.TypeGuard.IsString(t.properties.description.anyOf[1])&&k.TypeGuard.IsUndefined(t.properties.description.anyOf[0]))}function Iy(t){return cn(t,0)}function SE(t){return cn(t,0)}function GQ(t){return cn(t,0)}function KQ(t){return cn(t,0)}function HQ(t){return rh(t)}function zQ(t){let e=(0,Ey.Number)();return cn(t,0)||cn(t,1)&&"length"in t.properties&&Bn(Fe(t.properties.length,e))===B.True}function VQ(t){return cn(t,0)}function rh(t){let e=(0,Ey.Number)();return cn(t,0)||cn(t,1)&&"length"in t.properties&&Bn(Fe(t.properties.length,e))===B.True}function JQ(t){let e=(0,TQ.Function)([(0,bE.Any)()],(0,bE.Any)());return cn(t,0)||cn(t,1)&&"then"in t.properties&&Bn(Fe(t.properties.then,e))===B.True}function RE(t,e){return Fe(t,e)===B.False||k.TypeGuard.IsOptional(t)&&!k.TypeGuard.IsOptional(e)?B.False:B.True}function Et(t,e){return k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:k.TypeGuard.IsNever(t)||k.TypeGuard.IsLiteralString(t)&&vE(e)||k.TypeGuard.IsLiteralNumber(t)&&Iy(e)||k.TypeGuard.IsLiteralBoolean(t)&&SE(e)||k.TypeGuard.IsSymbol(t)&&wE(e)||k.TypeGuard.IsBigInt(t)&&GQ(e)||k.TypeGuard.IsString(t)&&vE(e)||k.TypeGuard.IsSymbol(t)&&wE(e)||k.TypeGuard.IsNumber(t)&&Iy(e)||k.TypeGuard.IsInteger(t)&&Iy(e)||k.TypeGuard.IsBoolean(t)&&SE(e)||k.TypeGuard.IsUint8Array(t)&&HQ(e)||k.TypeGuard.IsDate(t)&&KQ(e)||k.TypeGuard.IsConstructor(t)&&VQ(e)||k.TypeGuard.IsFunction(t)&&zQ(e)?B.True:k.TypeGuard.IsRecord(t)&&k.TypeGuard.IsString(Py(t))?e[CE.Hint]==="Record"?B.True:B.False:k.TypeGuard.IsRecord(t)&&k.TypeGuard.IsNumber(Py(t))&&cn(e,0)?B.True:B.False}function QQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsObject(e)?(()=>{for(let n of Object.getOwnPropertyNames(e.properties)){if(!(n in t.properties)&&!k.TypeGuard.IsOptional(e.properties[n]))return B.False;if(k.TypeGuard.IsOptional(e.properties[n]))return B.True;if(RE(t.properties[n],e.properties[n])===B.False)return B.False}return B.True})():B.False}function YQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)&&JQ(e)?B.True:k.TypeGuard.IsPromise(e)?Bn(Fe(t.item,e.item)):B.False}function Py(t){return kc.PatternNumberExact in t.patternProperties?(0,Ey.Number)():kc.PatternStringExact in t.patternProperties?(0,Ry.String)():Mc("Unknown record key pattern")}function _y(t){return kc.PatternNumberExact in t.patternProperties?t.patternProperties[kc.PatternNumberExact]:kc.PatternStringExact in t.patternProperties?t.patternProperties[kc.PatternStringExact]:Mc("Unable to get record value schema")}function Nn(t,e){let[n,i]=[Py(e),_y(e)];return k.TypeGuard.IsLiteralString(t)&&k.TypeGuard.IsNumber(n)&&Bn(Fe(t,i))===B.True?B.True:k.TypeGuard.IsUint8Array(t)&&k.TypeGuard.IsNumber(n)||k.TypeGuard.IsString(t)&&k.TypeGuard.IsNumber(n)||k.TypeGuard.IsArray(t)&&k.TypeGuard.IsNumber(n)?Fe(t,i):k.TypeGuard.IsObject(t)?(()=>{for(let s of Object.getOwnPropertyNames(t.properties))if(RE(i,t.properties[s])===B.False)return B.False;return B.True})():B.False}function XQ(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Fe(_y(t),_y(e)):B.False}function ZQ(t,e){let n=k.TypeGuard.IsRegExp(t)?(0,Ry.String)():t,i=k.TypeGuard.IsRegExp(e)?(0,Ry.String)():e;return Fe(n,i)}function PE(t,e){return k.TypeGuard.IsLiteral(t)&&k.ValueGuard.IsString(t.const)||k.TypeGuard.IsString(t)?B.True:B.False}function eY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsString(e)?B.True:B.False}function tY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsSymbol(e)?B.True:B.False}function nY(t,e){return k.TypeGuard.IsTemplateLiteral(t)?Fe((0,xE.TemplateLiteralToUnion)(t),e):k.TypeGuard.IsTemplateLiteral(e)?Fe(t,(0,xE.TemplateLiteralToUnion)(e)):Mc("Invalid fallthrough for TemplateLiteral")}function iY(t,e){return k.TypeGuard.IsArray(e)&&t.items!==void 0&&t.items.every(n=>Fe(n,e.items)===B.True)}function sY(t,e){return k.TypeGuard.IsNever(t)?B.True:k.TypeGuard.IsUnknown(t)?B.False:k.TypeGuard.IsAny(t)?B.Union:B.False}function rY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)&&rh(e)||k.TypeGuard.IsArray(e)&&iY(t,e)?B.True:k.TypeGuard.IsTuple(e)?k.ValueGuard.IsUndefined(t.items)&&!k.ValueGuard.IsUndefined(e.items)||!k.ValueGuard.IsUndefined(t.items)&&k.ValueGuard.IsUndefined(e.items)?B.False:k.ValueGuard.IsUndefined(t.items)&&!k.ValueGuard.IsUndefined(e.items)||t.items.every((n,i)=>Fe(n,e.items[i])===B.True)?B.True:B.False:B.False}function oY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsUint8Array(e)?B.True:B.False}function aY(t,e){return at(e)?ct(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsRecord(e)?Nn(t,e):k.TypeGuard.IsVoid(e)?uY(t,e):k.TypeGuard.IsUndefined(e)?B.True:B.False}function Oy(t,e){return e.anyOf.some(n=>Fe(t,n)===B.True)?B.True:B.False}function cY(t,e){return t.anyOf.every(n=>Fe(n,e)===B.True)?B.True:B.False}function _E(t,e){return B.True}function lY(t,e){return k.TypeGuard.IsNever(e)?ME(t,e):k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):k.TypeGuard.IsString(e)?PE(t,e):k.TypeGuard.IsNumber(e)?IE(t,e):k.TypeGuard.IsInteger(e)?kE(t,e):k.TypeGuard.IsBoolean(e)?TE(t,e):k.TypeGuard.IsArray(e)?RQ(t,e):k.TypeGuard.IsTuple(e)?sY(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsUnknown(e)?B.True:B.False}function uY(t,e){return k.TypeGuard.IsUndefined(t)||k.TypeGuard.IsUndefined(t)?B.True:B.False}function dY(t,e){return k.TypeGuard.IsIntersect(e)?sh(t,e):k.TypeGuard.IsUnion(e)?Oy(t,e):k.TypeGuard.IsUnknown(e)?_E(t,e):k.TypeGuard.IsAny(e)?Ay(t,e):k.TypeGuard.IsObject(e)?Et(t,e):k.TypeGuard.IsVoid(e)?B.True:B.False}function Fe(t,e){return k.TypeGuard.IsTemplateLiteral(t)||k.TypeGuard.IsTemplateLiteral(e)?nY(t,e):k.TypeGuard.IsRegExp(t)||k.TypeGuard.IsRegExp(e)?ZQ(t,e):k.TypeGuard.IsNot(t)||k.TypeGuard.IsNot(e)?NQ(t,e):k.TypeGuard.IsAny(t)?IQ(t,e):k.TypeGuard.IsArray(t)?PQ(t,e):k.TypeGuard.IsBigInt(t)?EQ(t,e):k.TypeGuard.IsBoolean(t)?AQ(t,e):k.TypeGuard.IsAsyncIterator(t)?_Q(t,e):k.TypeGuard.IsConstructor(t)?OQ(t,e):k.TypeGuard.IsDate(t)?LQ(t,e):k.TypeGuard.IsFunction(t)?WQ(t,e):k.TypeGuard.IsInteger(t)?UQ(t,e):k.TypeGuard.IsIntersect(t)?FQ(t,e):k.TypeGuard.IsIterator(t)?DQ(t,e):k.TypeGuard.IsLiteral(t)?$Q(t,e):k.TypeGuard.IsNever(t)?BQ(t,e):k.TypeGuard.IsNull(t)?jQ(t,e):k.TypeGuard.IsNumber(t)?qQ(t,e):k.TypeGuard.IsObject(t)?QQ(t,e):k.TypeGuard.IsRecord(t)?XQ(t,e):k.TypeGuard.IsString(t)?eY(t,e):k.TypeGuard.IsSymbol(t)?tY(t,e):k.TypeGuard.IsTuple(t)?rY(t,e):k.TypeGuard.IsPromise(t)?YQ(t,e):k.TypeGuard.IsUint8Array(t)?oY(t,e):k.TypeGuard.IsUndefined(t)?aY(t,e):k.TypeGuard.IsUnion(t)?cY(t,e):k.TypeGuard.IsUnknown(t)?lY(t,e):k.TypeGuard.IsVoid(t)?dY(t,e):Mc(`Unknown left type operand '${t[CE.Kind]}'`)}function pY(t,e){return Fe(t,e)}});var Uy=T(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});Wy.ExtendsFromMappedResult=xY;var mY=ot(),hY=oh(),gY=tn();function fY(t,e,n,i,s){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=(0,hY.Extends)(t[o],e,n,i,(0,gY.Clone)(s));return r}function bY(t,e,n,i,s){return fY(t.properties,e,n,i,s)}function xY(t,e,n,i,s){let r=bY(t,e,n,i,s);return(0,mY.MappedResult)(r)}});var oh=T(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});Dy.Extends=CY;var EE=le(),yY=st(),Fy=Ly(),vY=$y(),wY=Uy(),AE=Me();function SY(t,e,n,i){let s=(0,Fy.ExtendsCheck)(t,e);return s===Fy.ExtendsResult.Union?(0,yY.Union)([n,i]):s===Fy.ExtendsResult.True?n:i}function CY(t,e,n,i,s){return(0,AE.IsMappedResult)(t)?(0,wY.ExtendsFromMappedResult)(t,e,n,i,s):(0,AE.IsMappedKey)(t)?(0,EE.CreateType)((0,vY.ExtendsFromMappedKey)(t,e,n,i,s)):(0,EE.CreateType)(SY(t,e,n,i),s)}});var $y=T(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});By.ExtendsFromMappedKey=EY;var TY=ot(),kY=Ft(),MY=oh(),IY=tn();function RY(t,e,n,i,s){return{[t]:(0,MY.Extends)((0,kY.Literal)(t),e,n,i,(0,IY.Clone)(s))}}function PY(t,e,n,i,s){return t.reduce((r,o)=>({...r,...RY(o,e,n,i,s)}),{})}function _Y(t,e,n,i,s){return PY(t.keys,e,n,i,s)}function EY(t,e,n,i,s){let r=_Y(t,e,n,i,s);return(0,TY.MappedResult)(r)}});var OE=T(Ny=>{"use strict";Object.defineProperty(Ny,"__esModule",{value:!0});Ny.ExtendsUndefinedCheck=ch;var ah=oe();function AY(t){return t.allOf.every(e=>ch(e))}function OY(t){return t.anyOf.some(e=>ch(e))}function LY(t){return!ch(t.not)}function ch(t){return t[ah.Kind]==="Intersect"?AY(t):t[ah.Kind]==="Union"?OY(t):t[ah.Kind]==="Not"?LY(t):t[ah.Kind]==="Undefined"}});var Ic=T(ni=>{"use strict";var WY=ni&&ni.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Uu=ni&&ni.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WY(e,t,n)};Object.defineProperty(ni,"__esModule",{value:!0});Uu(Ly(),ni);Uu($y(),ni);Uu(Uy(),ni);Uu(OE(),ni);Uu(oh(),ni)});var qy=T(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});jy.ExcludeFromTemplateLiteral=DY;var UY=lh(),FY=Si();function DY(t,e){return(0,UY.Exclude)((0,FY.TemplateLiteralToUnion)(t),e)}});var lh=T(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});Hy.Exclude=GY;var Gy=le(),$Y=st(),BY=vt(),uh=Ic(),NY=zy(),jY=qy(),Ky=Me();function qY(t,e){let n=t.filter(i=>(0,uh.ExtendsCheck)(i,e)===uh.ExtendsResult.False);return n.length===1?n[0]:(0,$Y.Union)(n)}function GY(t,e,n={}){return(0,Ky.IsTemplateLiteral)(t)?(0,Gy.CreateType)((0,jY.ExcludeFromTemplateLiteral)(t,e),n):(0,Ky.IsMappedResult)(t)?(0,Gy.CreateType)((0,NY.ExcludeFromMappedResult)(t,e),n):(0,Gy.CreateType)((0,Ky.IsUnion)(t)?qY(t.anyOf,e):(0,uh.ExtendsCheck)(t,e)!==uh.ExtendsResult.False?(0,BY.Never)():t,n)}});var zy=T(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});Vy.ExcludeFromMappedResult=JY;var KY=ot(),HY=lh();function zY(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,HY.Exclude)(t[i],e);return n}function VY(t,e){return zY(t.properties,e)}function JY(t,e){let n=VY(t,e);return(0,KY.MappedResult)(n)}});var dh=T(as=>{"use strict";var QY=as&&as.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Jy=as&&as.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&QY(e,t,n)};Object.defineProperty(as,"__esModule",{value:!0});Jy(zy(),as);Jy(qy(),as);Jy(lh(),as)});var Yy=T(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});Qy.ExtractFromTemplateLiteral=ZY;var YY=ph(),XY=Si();function ZY(t,e){return(0,YY.Extract)((0,XY.TemplateLiteralToUnion)(t),e)}});var ph=T(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});ev.Extract=rX;var Xy=le(),eX=st(),tX=vt(),mh=Ic(),nX=tv(),iX=Yy(),Zy=Me();function sX(t,e){let n=t.filter(i=>(0,mh.ExtendsCheck)(i,e)!==mh.ExtendsResult.False);return n.length===1?n[0]:(0,eX.Union)(n)}function rX(t,e,n){return(0,Zy.IsTemplateLiteral)(t)?(0,Xy.CreateType)((0,iX.ExtractFromTemplateLiteral)(t,e),n):(0,Zy.IsMappedResult)(t)?(0,Xy.CreateType)((0,nX.ExtractFromMappedResult)(t,e),n):(0,Xy.CreateType)((0,Zy.IsUnion)(t)?sX(t.anyOf,e):(0,mh.ExtendsCheck)(t,e)!==mh.ExtendsResult.False?t:(0,tX.Never)(),n)}});var tv=T(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});nv.ExtractFromMappedResult=uX;var oX=ot(),aX=ph();function cX(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,aX.Extract)(t[i],e);return n}function lX(t,e){return cX(t.properties,e)}function uX(t,e){let n=lX(t,e);return(0,oX.MappedResult)(n)}});var hh=T(cs=>{"use strict";var dX=cs&&cs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),iv=cs&&cs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&dX(e,t,n)};Object.defineProperty(cs,"__esModule",{value:!0});iv(tv(),cs);iv(Yy(),cs);iv(ph(),cs)});var LE=T(ls=>{"use strict";var pX=ls&&ls.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),mX=ls&&ls.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hX=ls&&ls.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&pX(n,e,i[s]);return mX(n,e),n}})();Object.defineProperty(ls,"__esModule",{value:!0});ls.InstanceType=xX;var gX=le(),fX=vt(),bX=hX(Me());function xX(t,e){return bX.IsConstructor(t)?(0,gX.CreateType)(t.returns,e):(0,fX.Never)(e)}});var gh=T(To=>{"use strict";var yX=To&&To.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),vX=To&&To.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yX(e,t,n)};Object.defineProperty(To,"__esModule",{value:!0});vX(LE(),To)});var WE=T(sv=>{"use strict";Object.defineProperty(sv,"__esModule",{value:!0});sv.ReadonlyOptional=CX;var wX=Vs(),SX=wi();function CX(t){return(0,wX.Readonly)((0,SX.Optional)(t))}});var Fu=T(ko=>{"use strict";var TX=ko&&ko.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kX=ko&&ko.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&TX(e,t,n)};Object.defineProperty(ko,"__esModule",{value:!0});kX(WE(),ko)});var BE=T(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.Record=jX;Rc.RecordPattern=ov;Rc.RecordKey=qX;Rc.RecordValue=GX;var MX=le(),FE=oe(),IX=vt(),RX=Ks(),DE=on(),UE=io(),PX=st(),_X=Si(),Mo=xu(),$E=ti(),EX=Ut(),ki=Me();function Io(t,e,n){return(0,MX.CreateType)({[FE.Kind]:"Record",type:"object",patternProperties:{[t]:e}},n)}function rv(t,e,n){let i={};for(let s of t)i[s]=e;return(0,DE.Object)(i,{...n,[FE.Hint]:"Record"})}function AX(t,e,n){return(0,_X.IsTemplateLiteralFinite)(t)?rv((0,$E.IndexPropertyKeys)(t),e,n):Io(t.pattern,e,n)}function OX(t,e,n){return rv((0,$E.IndexPropertyKeys)((0,PX.Union)(t)),e,n)}function LX(t,e,n){return rv([t.toString()],e,n)}function WX(t,e,n){return Io(t.source,e,n)}function UX(t,e,n){let i=(0,EX.IsUndefined)(t.pattern)?Mo.PatternStringExact:t.pattern;return Io(i,e,n)}function FX(t,e,n){return Io(Mo.PatternStringExact,e,n)}function DX(t,e,n){return Io(Mo.PatternNeverExact,e,n)}function $X(t,e,n){return(0,DE.Object)({true:e,false:e},n)}function BX(t,e,n){return Io(Mo.PatternNumberExact,e,n)}function NX(t,e,n){return Io(Mo.PatternNumberExact,e,n)}function jX(t,e,n={}){return(0,ki.IsUnion)(t)?OX(t.anyOf,e,n):(0,ki.IsTemplateLiteral)(t)?AX(t,e,n):(0,ki.IsLiteral)(t)?LX(t.const,e,n):(0,ki.IsBoolean)(t)?$X(t,e,n):(0,ki.IsInteger)(t)?BX(t,e,n):(0,ki.IsNumber)(t)?NX(t,e,n):(0,ki.IsRegExp)(t)?WX(t,e,n):(0,ki.IsString)(t)?UX(t,e,n):(0,ki.IsAny)(t)?FX(t,e,n):(0,ki.IsNever)(t)?DX(t,e,n):(0,IX.Never)(n)}function ov(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function qX(t){let e=ov(t);return e===Mo.PatternStringExact?(0,UE.String)():e===Mo.PatternNumberExact?(0,RX.Number)():(0,UE.String)({pattern:e})}function GX(t){return t.patternProperties[ov(t)]}});var Pc=T(Ro=>{"use strict";var KX=Ro&&Ro.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),HX=Ro&&Ro.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&KX(e,t,n)};Object.defineProperty(Ro,"__esModule",{value:!0});HX(BE(),Ro)});var jE=T(Mi=>{"use strict";var zX=Mi&&Mi.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),VX=Mi&&Mi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),NE=Mi&&Mi.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&zX(n,e,i[s]);return VX(n,e),n}})();Object.defineProperty(Mi,"__esModule",{value:!0});Mi.FromTypes=_c;Mi.Instantiate=fZ;var JX=Rm(),QX=yo(),YX=Fu(),XX=Vs(),ZX=wi(),eZ=on(),av=Pc(),tZ=NE(Ut()),ln=NE(Me());function nZ(t,e){return e.parameters=_c(t,e.parameters),e.returns=ii(t,e.returns),e}function iZ(t,e){return e.parameters=_c(t,e.parameters),e.returns=ii(t,e.returns),e}function sZ(t,e){return e.allOf=_c(t,e.allOf),e}function rZ(t,e){return e.anyOf=_c(t,e.anyOf),e}function oZ(t,e){return tZ.IsUndefined(e.items)||(e.items=_c(t,e.items)),e}function aZ(t,e){return e.items=ii(t,e.items),e}function cZ(t,e){return e.items=ii(t,e.items),e}function lZ(t,e){return e.items=ii(t,e.items),e}function uZ(t,e){return e.item=ii(t,e.item),e}function dZ(t,e){let n=gZ(t,e.properties);return{...e,...(0,eZ.Object)(n)}}function pZ(t,e){let n=ii(t,(0,av.RecordKey)(e)),i=ii(t,(0,av.RecordValue)(e)),s=(0,av.Record)(n,i);return{...e,...s}}function mZ(t,e){return e.index in t?t[e.index]:(0,QX.Unknown)()}function hZ(t,e){let n=ln.IsReadonly(e),i=ln.IsOptional(e),s=ii(t,e);return n&&i?(0,YX.ReadonlyOptional)(s):n&&!i?(0,XX.Readonly)(s):!n&&i?(0,ZX.Optional)(s):s}function gZ(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,i)=>({...n,[i]:hZ(t,e[i])}),{})}function _c(t,e){return e.map(n=>ii(t,n))}function ii(t,e){return ln.IsConstructor(e)?nZ(t,e):ln.IsFunction(e)?iZ(t,e):ln.IsIntersect(e)?sZ(t,e):ln.IsUnion(e)?rZ(t,e):ln.IsTuple(e)?oZ(t,e):ln.IsArray(e)?aZ(t,e):ln.IsAsyncIterator(e)?cZ(t,e):ln.IsIterator(e)?lZ(t,e):ln.IsPromise(e)?uZ(t,e):ln.IsObject(e)?dZ(t,e):ln.IsRecord(e)?pZ(t,e):ln.IsArgument(e)?mZ(t,e):e}function fZ(t,e){return ii(e,(0,JX.CloneType)(t))}});var fh=T(Po=>{"use strict";var bZ=Po&&Po.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xZ=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bZ(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});xZ(jE(),Po)});var qE=T(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});cv.Integer=wZ;var yZ=le(),vZ=oe();function wZ(t){return(0,yZ.CreateType)({[vZ.Kind]:"Integer",type:"integer"},t)}});var bh=T(_o=>{"use strict";var SZ=_o&&_o.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),CZ=_o&&_o.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&SZ(e,t,n)};Object.defineProperty(_o,"__esModule",{value:!0});CZ(qE(),_o)});var uv=T(lv=>{"use strict";Object.defineProperty(lv,"__esModule",{value:!0});lv.IntrinsicFromMappedKey=EZ;var TZ=ot(),kZ=Eo(),MZ=Ft(),IZ=tn();function RZ(t,e,n){return{[t]:(0,kZ.Intrinsic)((0,MZ.Literal)(t),e,(0,IZ.Clone)(n))}}function PZ(t,e,n){return t.reduce((s,r)=>({...s,...RZ(r,e,n)}),{})}function _Z(t,e,n){return PZ(t.keys,e,n)}function EZ(t,e,n){let i=_Z(t,e,n);return(0,TZ.MappedResult)(i)}});var Eo=T(dv=>{"use strict";Object.defineProperty(dv,"__esModule",{value:!0});dv.Intrinsic=VE;var AZ=le(),xh=Si(),OZ=uv(),GE=Ft(),KE=st(),yh=Me();function LZ(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),n].join("")}function WZ(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),n].join("")}function UZ(t){return t.toUpperCase()}function FZ(t){return t.toLowerCase()}function DZ(t,e,n){let i=(0,xh.TemplateLiteralParseExact)(t.pattern);if(!(0,xh.IsTemplateLiteralExpressionFinite)(i))return{...t,pattern:HE(t.pattern,e)};let o=[...(0,xh.TemplateLiteralExpressionGenerate)(i)].map(l=>(0,GE.Literal)(l)),a=zE(o,e),c=(0,KE.Union)(a);return(0,xh.TemplateLiteral)([c],n)}function HE(t,e){return typeof t=="string"?e==="Uncapitalize"?LZ(t):e==="Capitalize"?WZ(t):e==="Uppercase"?UZ(t):e==="Lowercase"?FZ(t):t:t.toString()}function zE(t,e){return t.map(n=>VE(n,e))}function VE(t,e,n={}){return(0,yh.IsMappedKey)(t)?(0,OZ.IntrinsicFromMappedKey)(t,e,n):(0,yh.IsTemplateLiteral)(t)?DZ(t,e,n):(0,yh.IsUnion)(t)?(0,KE.Union)(zE(t.anyOf,e),n):(0,yh.IsLiteral)(t)?(0,GE.Literal)(HE(t.const,e),n):(0,AZ.CreateType)(t,n)}});var JE=T(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});pv.Capitalize=BZ;var $Z=Eo();function BZ(t,e={}){return(0,$Z.Intrinsic)(t,"Capitalize",e)}});var QE=T(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});mv.Lowercase=jZ;var NZ=Eo();function jZ(t,e={}){return(0,NZ.Intrinsic)(t,"Lowercase",e)}});var YE=T(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});hv.Uncapitalize=GZ;var qZ=Eo();function GZ(t,e={}){return(0,qZ.Intrinsic)(t,"Uncapitalize",e)}});var XE=T(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});gv.Uppercase=HZ;var KZ=Eo();function HZ(t,e={}){return(0,KZ.Intrinsic)(t,"Uppercase",e)}});var vh=T(jn=>{"use strict";var zZ=jn&&jn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ec=jn&&jn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zZ(e,t,n)};Object.defineProperty(jn,"__esModule",{value:!0});Ec(JE(),jn);Ec(uv(),jn);Ec(Eo(),jn);Ec(QE(),jn);Ec(YE(),jn);Ec(XE(),jn)});var bv=T(fv=>{"use strict";Object.defineProperty(fv,"__esModule",{value:!0});fv.OmitFromMappedResult=ZZ;var VZ=ot(),JZ=wh(),QZ=tn();function YZ(t,e,n){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=(0,JZ.Omit)(t[s],e,(0,QZ.Clone)(n));return i}function XZ(t,e,n){return YZ(t.properties,e,n)}function ZZ(t,e,n){let i=XZ(t,e,n);return(0,VZ.MappedResult)(i)}});var wh=T(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});vv.Omit=gee;var eee=le(),tee=Wm(),nee=hu(),xv=qs(),iee=Ft(),see=ti(),ree=Cn(),ZE=st(),eA=on(),oee=wv(),aee=bv(),us=Me(),cee=Ut();function lee(t,e){return t.map(n=>yv(n,e))}function uee(t,e){return t.map(n=>yv(n,e))}function dee(t,e){let{[e]:n,...i}=t;return i}function pee(t,e){return e.reduce((n,i)=>dee(n,i),t)}function mee(t,e,n){let i=(0,tee.Discard)(t,[nee.TransformKind,"$id","required","properties"]),s=pee(n,e);return(0,eA.Object)(s,i)}function hee(t){let e=t.reduce((n,i)=>(0,us.IsLiteralValue)(i)?[...n,(0,iee.Literal)(i)]:n,[]);return(0,ZE.Union)(e)}function yv(t,e){return(0,us.IsIntersect)(t)?(0,ree.Intersect)(lee(t.allOf,e)):(0,us.IsUnion)(t)?(0,ZE.Union)(uee(t.anyOf,e)):(0,us.IsObject)(t)?mee(t,e,t.properties):(0,eA.Object)({})}function gee(t,e,n){let i=(0,cee.IsArray)(e)?hee(e):e,s=(0,us.IsSchema)(e)?(0,see.IndexPropertyKeys)(e):e,r=(0,us.IsRef)(t),o=(0,us.IsRef)(e);return(0,us.IsMappedResult)(t)?(0,aee.OmitFromMappedResult)(t,s,n):(0,us.IsMappedKey)(e)?(0,oee.OmitFromMappedKey)(t,e,n):r&&o?(0,xv.Computed)("Omit",[t,i],n):!r&&o?(0,xv.Computed)("Omit",[t,i],n):r&&!o?(0,xv.Computed)("Omit",[t,i],n):(0,eee.CreateType)({...yv(t,s),...n})}});var wv=T(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});Sv.OmitFromMappedKey=See;var fee=ot(),bee=wh(),xee=tn();function yee(t,e,n){return{[e]:(0,bee.Omit)(t,[e],(0,xee.Clone)(n))}}function vee(t,e,n){return e.reduce((i,s)=>({...i,...yee(t,s,n)}),{})}function wee(t,e,n){return vee(t,e.keys,n)}function See(t,e,n){let i=wee(t,e,n);return(0,fee.MappedResult)(i)}});var Du=T(ds=>{"use strict";var Cee=ds&&ds.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cv=ds&&ds.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Cee(e,t,n)};Object.defineProperty(ds,"__esModule",{value:!0});Cv(wv(),ds);Cv(bv(),ds);Cv(wh(),ds)});var kv=T(Tv=>{"use strict";Object.defineProperty(Tv,"__esModule",{value:!0});Tv.PickFromMappedResult=Pee;var Tee=ot(),kee=Sh(),Mee=tn();function Iee(t,e,n){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=(0,kee.Pick)(t[s],e,(0,Mee.Clone)(n));return i}function Ree(t,e,n){return Iee(t.properties,e,n)}function Pee(t,e,n){let i=Ree(t,e,n);return(0,Tee.MappedResult)(i)}});var Sh=T(Rv=>{"use strict";Object.defineProperty(Rv,"__esModule",{value:!0});Rv.Pick=Gee;var _ee=le(),Eee=Wm(),Mv=qs(),Aee=Cn(),Oee=Ft(),tA=on(),nA=st(),Lee=ti(),Wee=hu(),ps=Me(),Uee=Ut(),Fee=Pv(),Dee=kv();function $ee(t,e){return t.map(n=>Iv(n,e))}function Bee(t,e){return t.map(n=>Iv(n,e))}function Nee(t,e){let n={};for(let i of e)i in t&&(n[i]=t[i]);return n}function jee(t,e,n){let i=(0,Eee.Discard)(t,[Wee.TransformKind,"$id","required","properties"]),s=Nee(n,e);return(0,tA.Object)(s,i)}function qee(t){let e=t.reduce((n,i)=>(0,ps.IsLiteralValue)(i)?[...n,(0,Oee.Literal)(i)]:n,[]);return(0,nA.Union)(e)}function Iv(t,e){return(0,ps.IsIntersect)(t)?(0,Aee.Intersect)($ee(t.allOf,e)):(0,ps.IsUnion)(t)?(0,nA.Union)(Bee(t.anyOf,e)):(0,ps.IsObject)(t)?jee(t,e,t.properties):(0,tA.Object)({})}function Gee(t,e,n){let i=(0,Uee.IsArray)(e)?qee(e):e,s=(0,ps.IsSchema)(e)?(0,Lee.IndexPropertyKeys)(e):e,r=(0,ps.IsRef)(t),o=(0,ps.IsRef)(e);return(0,ps.IsMappedResult)(t)?(0,Dee.PickFromMappedResult)(t,s,n):(0,ps.IsMappedKey)(e)?(0,Fee.PickFromMappedKey)(t,e,n):r&&o?(0,Mv.Computed)("Pick",[t,i],n):!r&&o?(0,Mv.Computed)("Pick",[t,i],n):r&&!o?(0,Mv.Computed)("Pick",[t,i],n):(0,_ee.CreateType)({...Iv(t,s),...n})}});var Pv=T(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});_v.PickFromMappedKey=Yee;var Kee=ot(),Hee=Sh(),zee=tn();function Vee(t,e,n){return{[e]:(0,Hee.Pick)(t,[e],(0,zee.Clone)(n))}}function Jee(t,e,n){return e.reduce((i,s)=>({...i,...Vee(t,s,n)}),{})}function Qee(t,e,n){return Jee(t,e.keys,n)}function Yee(t,e,n){let i=Qee(t,e,n);return(0,Kee.MappedResult)(i)}});var $u=T(ms=>{"use strict";var Xee=ms&&ms.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ev=ms&&ms.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Xee(e,t,n)};Object.defineProperty(ms,"__esModule",{value:!0});Ev(Pv(),ms);Ev(kv(),ms);Ev(Sh(),ms)});var Ov=T(hs=>{"use strict";var Zee=hs&&hs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ete=hs&&hs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tte=hs&&hs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Zee(n,e,i[s]);return ete(n,e),n}})();Object.defineProperty(hs,"__esModule",{value:!0});hs.Partial=hte;var nte=le(),Av=qs(),ite=wi(),sA=on(),ste=Cn(),rte=st(),ote=Qs(),ate=es(),cte=oe(),lte=Lv(),$t=tte(Me());function ute(t,e){return(0,Av.Computed)("Partial",[(0,Av.Computed)(t,e)])}function dte(t){return(0,Av.Computed)("Partial",[(0,ote.Ref)(t)])}function pte(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,ite.Optional)(t[n]);return e}function mte(t,e){let n=(0,ate.Discard)(t,[cte.TransformKind,"$id","required","properties"]),i=pte(e);return(0,sA.Object)(i,n)}function iA(t){return t.map(e=>rA(e))}function rA(t){return $t.IsComputed(t)?ute(t.target,t.parameters):$t.IsRef(t)?dte(t.$ref):$t.IsIntersect(t)?(0,ste.Intersect)(iA(t.allOf)):$t.IsUnion(t)?(0,rte.Union)(iA(t.anyOf)):$t.IsObject(t)?mte(t,t.properties):$t.IsBigInt(t)||$t.IsBoolean(t)||$t.IsInteger(t)||$t.IsLiteral(t)||$t.IsNull(t)||$t.IsNumber(t)||$t.IsString(t)||$t.IsSymbol(t)||$t.IsUndefined(t)?t:(0,sA.Object)({})}function hte(t,e){return $t.IsMappedResult(t)?(0,lte.PartialFromMappedResult)(t,e):(0,nte.CreateType)({...rA(t),...e})}});var Lv=T(Wv=>{"use strict";Object.defineProperty(Wv,"__esModule",{value:!0});Wv.PartialFromMappedResult=vte;var gte=ot(),fte=Ov(),bte=tn();function xte(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,fte.Partial)(t[i],(0,bte.Clone)(e));return n}function yte(t,e){return xte(t.properties,e)}function vte(t,e){let n=yte(t,e);return(0,gte.MappedResult)(n)}});var Bu=T(Ys=>{"use strict";var wte=Ys&&Ys.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),oA=Ys&&Ys.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&wte(e,t,n)};Object.defineProperty(Ys,"__esModule",{value:!0});oA(Lv(),Ys);oA(Ov(),Ys)});var Fv=T(gs=>{"use strict";var Ste=gs&&gs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Cte=gs&&gs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Tte=gs&&gs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Ste(n,e,i[s]);return Cte(n,e),n}})();Object.defineProperty(gs,"__esModule",{value:!0});gs.Required=Lte;var kte=le(),Uv=qs(),cA=on(),Mte=Cn(),Ite=st(),Rte=Qs(),lA=oe(),uA=es(),Pte=Dv(),Bt=Tte(Me());function _te(t,e){return(0,Uv.Computed)("Required",[(0,Uv.Computed)(t,e)])}function Ete(t){return(0,Uv.Computed)("Required",[(0,Rte.Ref)(t)])}function Ate(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=(0,uA.Discard)(t[n],[lA.OptionalKind]);return e}function Ote(t,e){let n=(0,uA.Discard)(t,[lA.TransformKind,"$id","required","properties"]),i=Ate(e);return(0,cA.Object)(i,n)}function aA(t){return t.map(e=>dA(e))}function dA(t){return Bt.IsComputed(t)?_te(t.target,t.parameters):Bt.IsRef(t)?Ete(t.$ref):Bt.IsIntersect(t)?(0,Mte.Intersect)(aA(t.allOf)):Bt.IsUnion(t)?(0,Ite.Union)(aA(t.anyOf)):Bt.IsObject(t)?Ote(t,t.properties):Bt.IsBigInt(t)||Bt.IsBoolean(t)||Bt.IsInteger(t)||Bt.IsLiteral(t)||Bt.IsNull(t)||Bt.IsNumber(t)||Bt.IsString(t)||Bt.IsSymbol(t)||Bt.IsUndefined(t)?t:(0,cA.Object)({})}function Lte(t,e){return Bt.IsMappedResult(t)?(0,Pte.RequiredFromMappedResult)(t,e):(0,kte.CreateType)({...dA(t),...e})}});var Dv=T($v=>{"use strict";Object.defineProperty($v,"__esModule",{value:!0});$v.RequiredFromMappedResult=$te;var Wte=ot(),Ute=Fv();function Fte(t,e){let n={};for(let i of globalThis.Object.getOwnPropertyNames(t))n[i]=(0,Ute.Required)(t[i],e);return n}function Dte(t,e){return Fte(t.properties,e)}function $te(t,e){let n=Dte(t,e);return(0,Wte.MappedResult)(n)}});var Nu=T(Xs=>{"use strict";var Bte=Xs&&Xs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),pA=Xs&&Xs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Bte(e,t,n)};Object.defineProperty(Xs,"__esModule",{value:!0});pA(Dv(),Xs);pA(Fv(),Xs)});var fA=T(si=>{"use strict";var Nte=si&&si.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),jte=si&&si.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qte=si&&si.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Nte(n,e,i[s]);return jte(n,e),n}})();Object.defineProperty(si,"__esModule",{value:!0});si.FromType=dn;si.ComputeType=gA;si.ComputeModuleProperties=Ine;var un=Xi(),Gte=qb(),mA=es(),Kte=hc(),Hte=_u(),zte=gc(),Vte=fc(),Jte=ti(),Qte=Gs(),Yte=Cn(),Xte=Sc(),Zte=Tc(),ene=on(),tne=Du(),nne=$u(),Bv=vt(),ine=Bu(),hA=Pc(),sne=Nu(),rne=is(),one=st(),Ch=oe(),Mt=qte(Me());function ane(t,e){return e.map(n=>Mt.IsRef(n)?Nv(t,n.$ref):dn(t,n))}function Nv(t,e){return e in t?Mt.IsRef(t[e])?Nv(t,t[e].$ref):dn(t,t[e]):(0,Bv.Never)()}function cne(t){return(0,Hte.Awaited)(t[0])}function lne(t){return(0,Jte.Index)(t[0],t[1])}function une(t){return(0,Zte.KeyOf)(t[0])}function dne(t){return(0,ine.Partial)(t[0])}function pne(t){return(0,tne.Omit)(t[0],t[1])}function mne(t){return(0,nne.Pick)(t[0],t[1])}function hne(t){return(0,sne.Required)(t[0])}function gne(t,e,n){let i=ane(t,n);return e==="Awaited"?cne(i):e==="Index"?lne(i):e==="KeyOf"?une(i):e==="Partial"?dne(i):e==="Omit"?pne(i):e==="Pick"?mne(i):e==="Required"?hne(i):(0,Bv.Never)()}function fne(t,e){return(0,Kte.Array)(dn(t,e))}function bne(t,e){return(0,zte.AsyncIterator)(dn(t,e))}function xne(t,e,n){return(0,Vte.Constructor)(ju(t,e),dn(t,n))}function yne(t,e,n){return(0,Qte.Function)(ju(t,e),dn(t,n))}function vne(t,e){return(0,Yte.Intersect)(ju(t,e))}function wne(t,e){return(0,Xte.Iterator)(dn(t,e))}function Sne(t,e){return(0,ene.Object)(globalThis.Object.keys(e).reduce((n,i)=>({...n,[i]:dn(t,e[i])}),{}))}function Cne(t,e){let[n,i]=[dn(t,(0,hA.RecordValue)(e)),(0,hA.RecordPattern)(e)],s=(0,Gte.CloneType)(e);return s.patternProperties[i]=n,s}function Tne(t,e){return Mt.IsRef(e)?{...Nv(t,e.$ref),[Ch.TransformKind]:e[Ch.TransformKind]}:e}function kne(t,e){return(0,rne.Tuple)(ju(t,e))}function Mne(t,e){return(0,one.Union)(ju(t,e))}function ju(t,e){return e.map(n=>dn(t,n))}function dn(t,e){return Mt.IsOptional(e)?(0,un.CreateType)(dn(t,(0,mA.Discard)(e,[Ch.OptionalKind])),e):Mt.IsReadonly(e)?(0,un.CreateType)(dn(t,(0,mA.Discard)(e,[Ch.ReadonlyKind])),e):Mt.IsTransform(e)?(0,un.CreateType)(Tne(t,e),e):Mt.IsArray(e)?(0,un.CreateType)(fne(t,e.items),e):Mt.IsAsyncIterator(e)?(0,un.CreateType)(bne(t,e.items),e):Mt.IsComputed(e)?(0,un.CreateType)(gne(t,e.target,e.parameters)):Mt.IsConstructor(e)?(0,un.CreateType)(xne(t,e.parameters,e.returns),e):Mt.IsFunction(e)?(0,un.CreateType)(yne(t,e.parameters,e.returns),e):Mt.IsIntersect(e)?(0,un.CreateType)(vne(t,e.allOf),e):Mt.IsIterator(e)?(0,un.CreateType)(wne(t,e.items),e):Mt.IsObject(e)?(0,un.CreateType)(Sne(t,e.properties),e):Mt.IsRecord(e)?(0,un.CreateType)(Cne(t,e)):Mt.IsTuple(e)?(0,un.CreateType)(kne(t,e.items||[]),e):Mt.IsUnion(e)?(0,un.CreateType)(Mne(t,e.anyOf),e):e}function gA(t,e){return e in t?dn(t,t[e]):(0,Bv.Never)()}function Ine(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,n)=>({...e,[n]:gA(t,n)}),{})}});var xA=T(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.TModule=void 0;qu.Module=_ne;var bA=Xi(),Rne=oe(),Pne=fA(),Th=class{constructor(e){let n=(0,Pne.ComputeModuleProperties)(e),i=this.WithIdentifiers(n);this.$defs=i}Import(e,n){let i={...this.$defs,[e]:(0,bA.CreateType)(this.$defs[e],n)};return(0,bA.CreateType)({[Rne.Kind]:"Import",$defs:i,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,i)=>({...n,[i]:{...e[i],$id:i}}),{})}};qu.TModule=Th;function _ne(t){return new Th(t)}});var kh=T(Ao=>{"use strict";var Ene=Ao&&Ao.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Ane=Ao&&Ao.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ene(e,t,n)};Object.defineProperty(Ao,"__esModule",{value:!0});Ane(xA(),Ao)});var yA=T(jv=>{"use strict";Object.defineProperty(jv,"__esModule",{value:!0});jv.Not=Wne;var One=le(),Lne=oe();function Wne(t,e){return(0,One.CreateType)({[Lne.Kind]:"Not",not:t},e)}});var Mh=T(Oo=>{"use strict";var Une=Oo&&Oo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Fne=Oo&&Oo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Une(e,t,n)};Object.defineProperty(Oo,"__esModule",{value:!0});Fne(yA(),Oo)});var vA=T(fs=>{"use strict";var Dne=fs&&fs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),$ne=fs&&fs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bne=fs&&fs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Dne(n,e,i[s]);return $ne(n,e),n}})();Object.defineProperty(fs,"__esModule",{value:!0});fs.Parameters=Gne;var Nne=is(),jne=vt(),qne=Bne(Me());function Gne(t,e){return qne.IsFunction(t)?(0,Nne.Tuple)(t.parameters,e):(0,jne.Never)()}});var Ih=T(Lo=>{"use strict";var Kne=Lo&&Lo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Hne=Lo&&Lo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Kne(e,t,n)};Object.defineProperty(Lo,"__esModule",{value:!0});Hne(vA(),Lo)});var SA=T(qv=>{"use strict";Object.defineProperty(qv,"__esModule",{value:!0});qv.Recursive=Yne;var zne=Rm(),Vne=le(),Jne=Ut(),wA=oe(),Qne=0;function Yne(t,e={}){(0,Jne.IsUndefined)(e.$id)&&(e.$id=`T${Qne++}`);let n=(0,zne.CloneType)(t({[wA.Kind]:"This",$ref:`${e.$id}`}));return n.$id=e.$id,(0,Vne.CreateType)({[wA.Hint]:"Recursive",...n},e)}});var Rh=T(Wo=>{"use strict";var Xne=Wo&&Wo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Zne=Wo&&Wo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Xne(e,t,n)};Object.defineProperty(Wo,"__esModule",{value:!0});Zne(SA(),Wo)});var CA=T(Gv=>{"use strict";Object.defineProperty(Gv,"__esModule",{value:!0});Gv.RegExp=iie;var eie=le(),tie=Ut(),nie=oe();function iie(t,e){let n=(0,tie.IsString)(t)?new globalThis.RegExp(t):t;return(0,eie.CreateType)({[nie.Kind]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},e)}});var Ph=T(Uo=>{"use strict";var sie=Uo&&Uo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),rie=Uo&&Uo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&sie(e,t,n)};Object.defineProperty(Uo,"__esModule",{value:!0});rie(CA(),Uo)});var TA=T(Hv=>{"use strict";Object.defineProperty(Hv,"__esModule",{value:!0});Hv.Rest=aie;var Kv=Me();function oie(t){return(0,Kv.IsIntersect)(t)?t.allOf:(0,Kv.IsUnion)(t)?t.anyOf:(0,Kv.IsTuple)(t)?t.items??[]:[]}function aie(t){return oie(t)}});var _h=T(Fo=>{"use strict";var cie=Fo&&Fo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),lie=Fo&&Fo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&cie(e,t,n)};Object.defineProperty(Fo,"__esModule",{value:!0});lie(TA(),Fo)});var kA=T(bs=>{"use strict";var uie=bs&&bs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),die=bs&&bs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pie=bs&&bs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&uie(n,e,i[s]);return die(n,e),n}})();Object.defineProperty(bs,"__esModule",{value:!0});bs.ReturnType=fie;var mie=le(),hie=vt(),gie=pie(Me());function fie(t,e){return gie.IsFunction(t)?(0,mie.CreateType)(t.returns,e):(0,hie.Never)(e)}});var Eh=T(Do=>{"use strict";var bie=Do&&Do.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),xie=Do&&Do.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bie(e,t,n)};Object.defineProperty(Do,"__esModule",{value:!0});xie(kA(),Do)});var IA=T(MA=>{"use strict";Object.defineProperty(MA,"__esModule",{value:!0})});var PA=T(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});var DEe=oe()});var EA=T(Zs=>{"use strict";var yie=Zs&&Zs.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),_A=Zs&&Zs.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yie(e,t,n)};Object.defineProperty(Zs,"__esModule",{value:!0});_A(IA(),Zs);_A(PA(),Zs)});var OA=T(AA=>{"use strict";Object.defineProperty(AA,"__esModule",{value:!0})});var LA=T($o=>{"use strict";var vie=$o&&$o.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),wie=$o&&$o.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vie(e,t,n)};Object.defineProperty($o,"__esModule",{value:!0});wie(OA(),$o)});var WA=T(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.TransformEncodeBuilder=Bo.TransformDecodeBuilder=void 0;Bo.Transform=Cie;var Ah=oe(),Sie=Me(),Oh=class{constructor(e){this.schema=e}Decode(e){return new Lh(this.schema,e)}};Bo.TransformDecodeBuilder=Oh;var Lh=class{constructor(e,n){this.schema=e,this.decode=n}EncodeTransform(e,n){let r={Encode:o=>n[Ah.TransformKind].Encode(e(o)),Decode:o=>this.decode(n[Ah.TransformKind].Decode(o))};return{...n,[Ah.TransformKind]:r}}EncodeSchema(e,n){let i={Decode:this.decode,Encode:e};return{...n,[Ah.TransformKind]:i}}Encode(e){return(0,Sie.IsTransform)(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}};Bo.TransformEncodeBuilder=Lh;function Cie(t){return new Oh(t)}});var Wh=T(No=>{"use strict";var Tie=No&&No.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),kie=No&&No.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tie(e,t,n)};Object.defineProperty(No,"__esModule",{value:!0});kie(WA(),No)});var FA=T(zv=>{"use strict";Object.defineProperty(zv,"__esModule",{value:!0});zv.Unsafe=Iie;var Mie=le(),UA=oe();function Iie(t={}){return(0,Mie.CreateType)({[UA.Kind]:t[UA.Kind]??"Unsafe"},t)}});var Uh=T(jo=>{"use strict";var Rie=jo&&jo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Pie=jo&&jo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Rie(e,t,n)};Object.defineProperty(jo,"__esModule",{value:!0});Pie(FA(),jo)});var DA=T(Vv=>{"use strict";Object.defineProperty(Vv,"__esModule",{value:!0});Vv.Void=Aie;var _ie=le(),Eie=oe();function Aie(t){return(0,_ie.CreateType)({[Eie.Kind]:"Void",type:"void"},t)}});var Fh=T(qo=>{"use strict";var Oie=qo&&qo.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Lie=qo&&qo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Oie(e,t,n)};Object.defineProperty(qo,"__esModule",{value:!0});Lie(DA(),qo)});var Qv=T($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});$h.JsonTypeBuilder=void 0;var Wie=mc(),Uie=hc(),Fie=Su(),Die=Xm(),$ie=eh(),Bie=nh(),Nie=dh(),jie=Ic(),qie=hh(),Gie=ti(),Kie=bh(),Hie=Cn(),Dh=vh(),zie=Tc(),Vie=Ft(),Jie=ot(),Qie=vt(),Yie=Mh(),Xie=Au(),Zie=kh(),ese=Ks(),tse=on(),nse=Du(),ise=wi(),sse=Bu(),rse=$u(),ose=Vs(),ase=Fu(),cse=Pc(),lse=Rh(),use=Qs(),dse=Nu(),pse=_h(),mse=io(),hse=Si(),gse=Wh(),fse=is(),bse=st(),xse=yo(),yse=Uh(),Jv=class{ReadonlyOptional(e){return(0,ase.ReadonlyOptional)(e)}Readonly(e,n){return(0,ose.Readonly)(e,n??!0)}Optional(e,n){return(0,ise.Optional)(e,n??!0)}Any(e){return(0,Wie.Any)(e)}Array(e,n){return(0,Uie.Array)(e,n)}Boolean(e){return(0,Fie.Boolean)(e)}Capitalize(e,n){return(0,Dh.Capitalize)(e,n)}Composite(e,n){return(0,Die.Composite)(e,n)}Const(e,n){return(0,$ie.Const)(e,n)}Enum(e,n){return(0,Bie.Enum)(e,n)}Exclude(e,n,i){return(0,Nie.Exclude)(e,n,i)}Extends(e,n,i,s,r){return(0,jie.Extends)(e,n,i,s,r)}Extract(e,n,i){return(0,qie.Extract)(e,n,i)}Index(e,n,i){return(0,Gie.Index)(e,n,i)}Integer(e){return(0,Kie.Integer)(e)}Intersect(e,n){return(0,Hie.Intersect)(e,n)}KeyOf(e,n){return(0,zie.KeyOf)(e,n)}Literal(e,n){return(0,Vie.Literal)(e,n)}Lowercase(e,n){return(0,Dh.Lowercase)(e,n)}Mapped(e,n,i){return(0,Jie.Mapped)(e,n,i)}Module(e){return(0,Zie.Module)(e)}Never(e){return(0,Qie.Never)(e)}Not(e,n){return(0,Yie.Not)(e,n)}Null(e){return(0,Xie.Null)(e)}Number(e){return(0,ese.Number)(e)}Object(e,n){return(0,tse.Object)(e,n)}Omit(e,n,i){return(0,nse.Omit)(e,n,i)}Partial(e,n){return(0,sse.Partial)(e,n)}Pick(e,n,i){return(0,rse.Pick)(e,n,i)}Record(e,n,i){return(0,cse.Record)(e,n,i)}Recursive(e,n){return(0,lse.Recursive)(e,n)}Ref(...e){return(0,use.Ref)(e[0],e[1])}Required(e,n){return(0,dse.Required)(e,n)}Rest(e){return(0,pse.Rest)(e)}String(e){return(0,mse.String)(e)}TemplateLiteral(e,n){return(0,hse.TemplateLiteral)(e,n)}Transform(e){return(0,gse.Transform)(e)}Tuple(e,n){return(0,fse.Tuple)(e,n)}Uncapitalize(e,n){return(0,Dh.Uncapitalize)(e,n)}Union(e,n){return(0,bse.Union)(e,n)}Unknown(e){return(0,xse.Unknown)(e)}Unsafe(e){return(0,yse.Unsafe)(e)}Uppercase(e,n){return(0,Dh.Uppercase)(e,n)}};$h.JsonTypeBuilder=Jv});var $A=T($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.Rest=$.Required=$.RegExp=$.Ref=$.Recursive=$.Record=$.ReadonlyOptional=$.Readonly=$.Promise=$.Pick=$.Partial=$.Parameters=$.Optional=$.Omit=$.Object=$.Number=$.Null=$.Not=$.Never=$.Module=$.Mapped=$.Literal=$.KeyOf=$.Iterator=$.Uppercase=$.Lowercase=$.Uncapitalize=$.Capitalize=$.Intersect=$.Integer=$.Instantiate=$.InstanceType=$.Index=$.Function=$.Extract=$.Extends=$.Exclude=$.Enum=$.Date=$.ConstructorParameters=$.Constructor=$.Const=$.Composite=$.Boolean=$.BigInt=$.Awaited=$.AsyncIterator=$.Array=$.Argument=$.Any=void 0;$.Void=$.Unsafe=$.Unknown=$.Union=$.Undefined=$.Uint8Array=$.Tuple=$.Transform=$.TemplateLiteral=$.Symbol=$.String=$.ReturnType=void 0;var vse=mc();Object.defineProperty($,"Any",{enumerable:!0,get:function(){return vse.Any}});var wse=Lm();Object.defineProperty($,"Argument",{enumerable:!0,get:function(){return wse.Argument}});var Sse=hc();Object.defineProperty($,"Array",{enumerable:!0,get:function(){return Sse.Array}});var Cse=gc();Object.defineProperty($,"AsyncIterator",{enumerable:!0,get:function(){return Cse.AsyncIterator}});var Tse=_u();Object.defineProperty($,"Awaited",{enumerable:!0,get:function(){return Tse.Awaited}});var kse=vc();Object.defineProperty($,"BigInt",{enumerable:!0,get:function(){return kse.BigInt}});var Mse=Su();Object.defineProperty($,"Boolean",{enumerable:!0,get:function(){return Mse.Boolean}});var Ise=Xm();Object.defineProperty($,"Composite",{enumerable:!0,get:function(){return Ise.Composite}});var Rse=eh();Object.defineProperty($,"Const",{enumerable:!0,get:function(){return Rse.Const}});var Pse=fc();Object.defineProperty($,"Constructor",{enumerable:!0,get:function(){return Pse.Constructor}});var _se=th();Object.defineProperty($,"ConstructorParameters",{enumerable:!0,get:function(){return _se.ConstructorParameters}});var Ese=Eu();Object.defineProperty($,"Date",{enumerable:!0,get:function(){return Ese.Date}});var Ase=nh();Object.defineProperty($,"Enum",{enumerable:!0,get:function(){return Ase.Enum}});var Ose=dh();Object.defineProperty($,"Exclude",{enumerable:!0,get:function(){return Ose.Exclude}});var Lse=Ic();Object.defineProperty($,"Extends",{enumerable:!0,get:function(){return Lse.Extends}});var Wse=hh();Object.defineProperty($,"Extract",{enumerable:!0,get:function(){return Wse.Extract}});var Use=Gs();Object.defineProperty($,"Function",{enumerable:!0,get:function(){return Use.Function}});var Fse=ti();Object.defineProperty($,"Index",{enumerable:!0,get:function(){return Fse.Index}});var Dse=gh();Object.defineProperty($,"InstanceType",{enumerable:!0,get:function(){return Dse.InstanceType}});var $se=fh();Object.defineProperty($,"Instantiate",{enumerable:!0,get:function(){return $se.Instantiate}});var Bse=bh();Object.defineProperty($,"Integer",{enumerable:!0,get:function(){return Bse.Integer}});var Nse=Cn();Object.defineProperty($,"Intersect",{enumerable:!0,get:function(){return Nse.Intersect}});var Bh=vh();Object.defineProperty($,"Capitalize",{enumerable:!0,get:function(){return Bh.Capitalize}});Object.defineProperty($,"Uncapitalize",{enumerable:!0,get:function(){return Bh.Uncapitalize}});Object.defineProperty($,"Lowercase",{enumerable:!0,get:function(){return Bh.Lowercase}});Object.defineProperty($,"Uppercase",{enumerable:!0,get:function(){return Bh.Uppercase}});var jse=Sc();Object.defineProperty($,"Iterator",{enumerable:!0,get:function(){return jse.Iterator}});var qse=Tc();Object.defineProperty($,"KeyOf",{enumerable:!0,get:function(){return qse.KeyOf}});var Gse=Ft();Object.defineProperty($,"Literal",{enumerable:!0,get:function(){return Gse.Literal}});var Kse=ot();Object.defineProperty($,"Mapped",{enumerable:!0,get:function(){return Kse.Mapped}});var Hse=kh();Object.defineProperty($,"Module",{enumerable:!0,get:function(){return Hse.Module}});var zse=vt();Object.defineProperty($,"Never",{enumerable:!0,get:function(){return zse.Never}});var Vse=Mh();Object.defineProperty($,"Not",{enumerable:!0,get:function(){return Vse.Not}});var Jse=Au();Object.defineProperty($,"Null",{enumerable:!0,get:function(){return Jse.Null}});var Qse=Ks();Object.defineProperty($,"Number",{enumerable:!0,get:function(){return Qse.Number}});var Yse=on();Object.defineProperty($,"Object",{enumerable:!0,get:function(){return Yse.Object}});var Xse=Du();Object.defineProperty($,"Omit",{enumerable:!0,get:function(){return Xse.Omit}});var Zse=wi();Object.defineProperty($,"Optional",{enumerable:!0,get:function(){return Zse.Optional}});var ere=Ih();Object.defineProperty($,"Parameters",{enumerable:!0,get:function(){return ere.Parameters}});var tre=Bu();Object.defineProperty($,"Partial",{enumerable:!0,get:function(){return tre.Partial}});var nre=$u();Object.defineProperty($,"Pick",{enumerable:!0,get:function(){return nre.Pick}});var ire=Iu();Object.defineProperty($,"Promise",{enumerable:!0,get:function(){return ire.Promise}});var sre=Vs();Object.defineProperty($,"Readonly",{enumerable:!0,get:function(){return sre.Readonly}});var rre=Fu();Object.defineProperty($,"ReadonlyOptional",{enumerable:!0,get:function(){return rre.ReadonlyOptional}});var ore=Pc();Object.defineProperty($,"Record",{enumerable:!0,get:function(){return ore.Record}});var are=Rh();Object.defineProperty($,"Recursive",{enumerable:!0,get:function(){return are.Recursive}});var cre=Qs();Object.defineProperty($,"Ref",{enumerable:!0,get:function(){return cre.Ref}});var lre=Ph();Object.defineProperty($,"RegExp",{enumerable:!0,get:function(){return lre.RegExp}});var ure=Nu();Object.defineProperty($,"Required",{enumerable:!0,get:function(){return ure.Required}});var dre=_h();Object.defineProperty($,"Rest",{enumerable:!0,get:function(){return dre.Rest}});var pre=Eh();Object.defineProperty($,"ReturnType",{enumerable:!0,get:function(){return pre.ReturnType}});var mre=io();Object.defineProperty($,"String",{enumerable:!0,get:function(){return mre.String}});var hre=Ou();Object.defineProperty($,"Symbol",{enumerable:!0,get:function(){return hre.Symbol}});var gre=Si();Object.defineProperty($,"TemplateLiteral",{enumerable:!0,get:function(){return gre.TemplateLiteral}});var fre=Wh();Object.defineProperty($,"Transform",{enumerable:!0,get:function(){return fre.Transform}});var bre=is();Object.defineProperty($,"Tuple",{enumerable:!0,get:function(){return bre.Tuple}});var xre=Wu();Object.defineProperty($,"Uint8Array",{enumerable:!0,get:function(){return xre.Uint8Array}});var yre=Lu();Object.defineProperty($,"Undefined",{enumerable:!0,get:function(){return yre.Undefined}});var vre=st();Object.defineProperty($,"Union",{enumerable:!0,get:function(){return vre.Union}});var wre=yo();Object.defineProperty($,"Unknown",{enumerable:!0,get:function(){return wre.Unknown}});var Sre=Uh();Object.defineProperty($,"Unsafe",{enumerable:!0,get:function(){return Sre.Unsafe}});var Cre=Fh();Object.defineProperty($,"Void",{enumerable:!0,get:function(){return Cre.Void}})});var BA=T(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});Nh.JavaScriptTypeBuilder=void 0;var Tre=Qv(),kre=Lm(),Mre=gc(),Ire=_u(),Rre=vc(),Pre=fc(),_re=th(),Ere=Eu(),Are=Gs(),Ore=gh(),Lre=fh(),Wre=Sc(),Ure=Ih(),Fre=Iu(),Dre=Ph(),$re=Eh(),Bre=Ou(),Nre=Wu(),jre=Lu(),qre=Fh(),Yv=class extends Tre.JsonTypeBuilder{Argument(e){return(0,kre.Argument)(e)}AsyncIterator(e,n){return(0,Mre.AsyncIterator)(e,n)}Awaited(e,n){return(0,Ire.Awaited)(e,n)}BigInt(e){return(0,Rre.BigInt)(e)}ConstructorParameters(e,n){return(0,_re.ConstructorParameters)(e,n)}Constructor(e,n,i){return(0,Pre.Constructor)(e,n,i)}Date(e={}){return(0,Ere.Date)(e)}Function(e,n,i){return(0,Are.Function)(e,n,i)}InstanceType(e,n){return(0,Ore.InstanceType)(e,n)}Instantiate(e,n){return(0,Lre.Instantiate)(e,n)}Iterator(e,n){return(0,Wre.Iterator)(e,n)}Parameters(e,n){return(0,Ure.Parameters)(e,n)}Promise(e,n){return(0,Fre.Promise)(e,n)}RegExp(e,n){return(0,Dre.RegExp)(e,n)}ReturnType(e,n){return(0,$re.ReturnType)(e,n)}Symbol(e){return(0,Bre.Symbol)(e)}Undefined(e){return(0,jre.Undefined)(e)}Uint8Array(e){return(0,Nre.Uint8Array)(e)}Void(e){return(0,qre.Void)(e)}};Nh.JavaScriptTypeBuilder=Yv});var NA=T(pn=>{"use strict";var Gre=pn&&pn.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Kre=pn&&pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Hre=pn&&pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Gre(n,e,i[s]);return Kre(n,e),n}})();Object.defineProperty(pn,"__esModule",{value:!0});pn.Type=pn.JavaScriptTypeBuilder=pn.JsonTypeBuilder=void 0;var zre=Qv();Object.defineProperty(pn,"JsonTypeBuilder",{enumerable:!0,get:function(){return zre.JsonTypeBuilder}});var Vre=Hre($A()),Jre=BA();Object.defineProperty(pn,"JavaScriptTypeBuilder",{enumerable:!0,get:function(){return Jre.JavaScriptTypeBuilder}});var Qre=Vre;pn.Type=Qre});var jA=T(z=>{"use strict";var Yre=z&&z.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Q=z&&z.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Yre(e,t,n)};Object.defineProperty(z,"__esModule",{value:!0});Q(qb(),z);Q(Xi(),z);Q(xi(),z);Q(Yb(),z);Q(BP(),z);Q(xu(),z);Q(KP(),z);Q(yu(),z);Q(oe(),z);Q(mc(),z);Q(hc(),z);Q(Lm(),z);Q(gc(),z);Q(_u(),z);Q(vc(),z);Q(Su(),z);Q(Xm(),z);Q(eh(),z);Q(fc(),z);Q(th(),z);Q(Eu(),z);Q(nh(),z);Q(dh(),z);Q(Ic(),z);Q(hh(),z);Q(Gs(),z);Q(ti(),z);Q(gh(),z);Q(fh(),z);Q(bh(),z);Q(Cn(),z);Q(Sc(),z);Q(vh(),z);Q(Tc(),z);Q(Ft(),z);Q(kh(),z);Q(ot(),z);Q(vt(),z);Q(Mh(),z);Q(Au(),z);Q(Ks(),z);Q(on(),z);Q(Du(),z);Q(wi(),z);Q(Ih(),z);Q(Bu(),z);Q($u(),z);Q(Iu(),z);Q(Vs(),z);Q(Fu(),z);Q(Pc(),z);Q(Rh(),z);Q(Qs(),z);Q(Ph(),z);Q(Nu(),z);Q(_h(),z);Q(Eh(),z);Q(EA(),z);Q(LA(),z);Q(io(),z);Q(Ou(),z);Q(Si(),z);Q(Wh(),z);Q(is(),z);Q(Wu(),z);Q(Lu(),z);Q(st(),z);Q(yo(),z);Q(Uh(),z);Q(Fh(),z);Q(NA(),z)});import{randomBytes as OB}from"node:crypto";import{accessSync as Coe,constants as Toe,existsSync as tg,readFileSync as RO,realpathSync as koe}from"fs";import{homedir as Dc}from"os";import{basename as Roe,dirname as Yu,join as ht,resolve as ng,sep as Poe,win32 as _oe}from"path";import{fileURLToPath as PO}from"url";import{spawn as kO,spawnSync as MO}from"node:child_process";import hw from"cross-spawn";var IO=100;function Qu(t,e,n){return process.platform==="win32"?hw(t,e,n):kO(t,e,n)}function zo(t,e,n){return process.platform==="win32"?hw.sync(t,e,n):MO(t,e,n)}function eg(t){return new Promise((e,n)=>{let i=!1,s=!1,r=null,o,a=t.stdout===null,c=t.stderr===null,l=()=>{o&&(clearTimeout(o),o=void 0),t.removeListener("error",g),t.removeListener("exit",h),t.removeListener("close",f),t.stdout?.removeListener("end",p),t.stderr?.removeListener("end",m)},d=x=>{i||(i=!0,l(),t.stdout?.destroy(),t.stderr?.destroy(),e(x))},u=()=>{!s||i||a&&c&&d(r)},p=()=>{a=!0,u()},m=()=>{c=!0,u()},g=x=>{i||(i=!0,l(),n(x))},h=x=>{s=!0,r=x,u(),i||(o=setTimeout(()=>d(x),IO))},f=x=>{d(x)};t.stdout?.once("end",p),t.stderr?.once("end",m),t.once("error",g),t.once("exit",h),t.once("close",f)})}var _O=PO(import.meta.url),gw=Yu(_O),Xu=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),Ooe=!!process.versions.bun;function ai(){let t=process.env.PI_PACKAGE_DIR;if(t)return t==="~"?Dc():t.startsWith("~/")?Dc()+t.slice(1):t;if(Xu)return Yu(process.execPath);let e=gw;for(;e!==Yu(e);){if(tg(ht(e,"package.json")))return e;e=Yu(e)}return gw}function ig(){if(Xu)return ht(ai(),"theme");let t=ai(),e=tg(ht(t,"src"))?"src":"dist";return ht(t,e,"modes","interactive","theme")}function EO(){return ht(ai(),"package.json")}function sg(){return ng(ht(ai(),"README.md"))}function Zu(){return ng(ht(ai(),"docs"))}function ed(){return ng(ht(ai(),"CHANGELOG.md"))}function AO(){if(Xu)return ht(ai(),"assets");let t=ai(),e=tg(ht(t,"src"))?"src":"dist";return ht(t,e,"modes","interactive","assets")}function fw(t){return ht(AO(),t)}var td=JSON.parse(RO(EO(),"utf-8")),bw=td.piConfig?.name,OO=td.name||"@earendil-works/pi-coding-agent",Ot=bw||"pi",rg=bw?Ot:"\u03C0",St=td.piConfig?.configDir||".pi",Ai=td.version||"0.0.0",xw=`${Ot.toUpperCase()}_CODING_AGENT_DIR`,yw=`${Ot.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function vw(t){return t==="~"?Dc():t.startsWith("~/")?Dc()+t.slice(1):t}var LO="https://pi.dev/session/";function ww(t){return`${process.env.PI_SHARE_VIEWER_URL||LO}#${t}`}function _e(){let t=process.env[xw];return t?vw(t):ht(Dc(),St,"agent")}function $c(){return ht(_e(),"themes")}function og(){return ht(_e(),"auth.json")}function Bc(){return ht(_e(),"bin")}function Sw(){return ht(_e(),"sessions")}function Cw(){return ht(_e(),`${Ot}-debug.log`)}import{Type as dle}from"typebox";var Tw=new Map;function WO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function UO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function Mn(t,e){Tw.set(t.api,{provider:{api:t.api,stream:WO(t.api,t.stream),streamSimple:UO(t.api,t.streamSimple)},sourceId:e})}function kw(t){return Tw.get(t)?.provider}Gn();var Iw={openrouter:{"black-forest-labs/flux.2-flex":{id:"black-forest-labs/flux.2-flex",name:"Black Forest Labs: FLUX.2 Flex",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-klein-4b":{id:"black-forest-labs/flux.2-klein-4b",name:"Black Forest Labs: FLUX.2 Klein 4B",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-max":{id:"black-forest-labs/flux.2-max",name:"Black Forest Labs: FLUX.2 Max",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-pro":{id:"black-forest-labs/flux.2-pro",name:"Black Forest Labs: FLUX.2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"bytedance-seed/seedream-4.5":{id:"bytedance-seed/seedream-4.5",name:"ByteDance Seed: Seedream 4.5",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"google/gemini-2.5-flash-image":{id:"google/gemini-2.5-flash-image",name:"Google: Nano Banana (Gemini 2.5 Flash Image)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:.08333333333333334}},"google/gemini-3-pro-image-preview":{id:"google/gemini-3-pro-image-preview",name:"Google: Nano Banana Pro (Gemini 3 Pro Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375}},"google/gemini-3.1-flash-image-preview":{id:"google/gemini-3.1-flash-image-preview",name:"Google: Nano Banana 2 (Gemini 3.1 Flash Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.5,output:3,cacheRead:0,cacheWrite:0}},"openai/gpt-5-image":{id:"openai/gpt-5-image",name:"OpenAI: GPT-5 Image",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:10,output:10,cacheRead:1.25,cacheWrite:0}},"openai/gpt-5-image-mini":{id:"openai/gpt-5-image-mini",name:"OpenAI: GPT-5 Image Mini",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2.5,output:2,cacheRead:.25,cacheWrite:0}},"openai/gpt-5.4-image-2":{id:"openai/gpt-5.4-image-2",name:"OpenAI: GPT-5.4 Image 2",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:8,output:15,cacheRead:2,cacheWrite:0}},"openrouter/auto":{id:"openrouter/auto",name:"Auto Router",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["text","image"],cost:{input:-1e6,output:-1e6,cacheRead:0,cacheWrite:0}},"recraft/recraft-v3":{id:"recraft/recraft-v3",name:"Recraft: Recraft V3",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4":{id:"recraft/recraft-v4",name:"Recraft: Recraft V4",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-pro":{id:"recraft/recraft-v4-pro",name:"Recraft: Recraft V4 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-pro-vector":{id:"recraft/recraft-v4-pro-vector",name:"Recraft: Recraft V4 Pro Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-vector":{id:"recraft/recraft-v4-vector",name:"Recraft: Recraft V4 Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1":{id:"recraft/recraft-v4.1",name:"Recraft: Recraft V4.1",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-pro":{id:"recraft/recraft-v4.1-pro",name:"Recraft: Recraft V4.1 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-pro-vector":{id:"recraft/recraft-v4.1-pro-vector",name:"Recraft: Recraft V4.1 Pro Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-utility":{id:"recraft/recraft-v4.1-utility",name:"Recraft: Recraft V4.1 Utility",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-utility-pro":{id:"recraft/recraft-v4.1-utility-pro",name:"Recraft: Recraft V4.1 Utility Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4.1-vector":{id:"recraft/recraft-v4.1-vector",name:"Recraft: Recraft V4.1 Vector",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast":{id:"sourceful/riverflow-v2-fast",name:"Sourceful: Riverflow V2 Fast",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast-preview":{id:"sourceful/riverflow-v2-fast-preview",name:"Sourceful: Riverflow V2 Fast Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-max-preview":{id:"sourceful/riverflow-v2-max-preview",name:"Sourceful: Riverflow V2 Max Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-pro":{id:"sourceful/riverflow-v2-pro",name:"Sourceful: Riverflow V2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-standard-preview":{id:"sourceful/riverflow-v2-standard-preview",name:"Sourceful: Riverflow V2 Standard Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"x-ai/grok-imagine-image-quality":{id:"x-ai/grok-imagine-image-quality",name:"xAI: Grok Imagine Image Quality",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}}};var jO=new Map;for(let[t,e]of Object.entries(Iw)){let n=new Map;for(let[i,s]of Object.entries(e))n.set(i,s);jO.set(t,n)}var qO=new Map;function GO(t,e){return(n,i,s)=>{if(n.api!==t)throw new Error(`Mismatched api: ${n.api} expected ${t}`);return e(n,i,s)}}function Rw(t,e){qO.set(t.api,{provider:{api:t.api,generateImages:GO(t.api,t.generateImages)},sourceId:e})}var Ew;function QO(t,e){return{api:t.api,provider:t.provider,model:t.id,output:[],stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function YO(){return Ew||=Promise.resolve().then(()=>(_w(),Pw)).then(t=>t),Ew}var XO=async(t,e,n)=>{try{return await(await YO()).generateImagesOpenRouter(t,e,n)}catch(i){return QO(t,i)}};function ZO(){Rw({api:"openrouter-images",generateImages:XO})}ZO();In();Rn();Rn();var z9=t=>import(import.meta.url.endsWith(".js")?t.replace(/\.ts$/,".js"):t),HS,zS,VS,JS,QS,YS,XS,ZS,eC,tC;function nC(t,e){(async()=>{for await(let n of e)t.push(n);t.end()})()}function iC(t,e){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function Wi(t){return(e,n,i)=>{let s=new it;return t().then(r=>{let o=r.stream(e,n,i);nC(s,o)}).catch(r=>{let o=iC(e,r);s.push({type:"error",reason:"error",error:o}),s.end(o)}),s}}function Ui(t){return(e,n,i)=>{let s=new it;return t().then(r=>{let o=r.streamSimple(e,n,i);nC(s,o)}).catch(r=>{let o=iC(e,r);s.push({type:"error",reason:"error",error:o}),s.end(o)}),s}}function sC(){return HS||=Promise.resolve().then(()=>(Gw(),qw)).then(t=>{let e=t;return{stream:e.streamAnthropic,streamSimple:e.streamSimpleAnthropic}}),HS}function rC(){return zS||=Promise.resolve().then(()=>(zw(),Hw)).then(t=>{let e=t;return{stream:e.streamAzureOpenAIResponses,streamSimple:e.streamSimpleAzureOpenAIResponses}}),zS}function oC(){return VS||=Promise.resolve().then(()=>(Yw(),Qw)).then(t=>{let e=t;return{stream:e.streamGoogle,streamSimple:e.streamSimpleGoogle}}),VS}function aC(){return JS||=Promise.resolve().then(()=>(iS(),nS)).then(t=>{let e=t;return{stream:e.streamGoogleVertex,streamSimple:e.streamSimpleGoogleVertex}}),JS}function cC(){return QS||=Promise.resolve().then(()=>(lS(),cS)).then(t=>{let e=t;return{stream:e.streamMistral,streamSimple:e.streamSimpleMistral}}),QS}function lC(){return YS||=Promise.resolve().then(()=>(AS(),ES)).then(t=>{let e=t;return{stream:e.streamOpenAICodexResponses,streamSimple:e.streamSimpleOpenAICodexResponses}}),YS}function uC(){return XS||=Promise.resolve().then(()=>(BS(),$S)).then(t=>{let e=t;return{stream:e.streamOpenAICompletions,streamSimple:e.streamSimpleOpenAICompletions}}),XS}function dC(){return ZS||=Promise.resolve().then(()=>(KS(),GS)).then(t=>{let e=t;return{stream:e.streamOpenAIResponses,streamSimple:e.streamSimpleOpenAIResponses}}),ZS}function pC(){return eC?Promise.resolve(eC):(tC||=z9("./amazon-bedrock.ts").then(t=>{let e=t;return{stream:e.streamBedrock,streamSimple:e.streamSimpleBedrock}}),tC)}var V9=Wi(sC),J9=Ui(sC),Q9=Wi(rC),Y9=Ui(rC),X9=Wi(oC),Z9=Ui(oC),eW=Wi(aC),tW=Ui(aC),nW=Wi(cC),iW=Ui(cC),sW=Wi(lC),rW=Ui(lC),oW=Wi(uC),aW=Ui(uC),cW=Wi(dC),lW=Ui(dC),uW=Wi(pC),dW=Ui(pC);function pW(){Mn({api:"anthropic-messages",stream:V9,streamSimple:J9}),Mn({api:"openai-completions",stream:oW,streamSimple:aW}),Mn({api:"mistral-conversations",stream:nW,streamSimple:iW}),Mn({api:"openai-responses",stream:cW,streamSimple:lW}),Mn({api:"azure-openai-responses",stream:Q9,streamSimple:Y9}),Mn({api:"openai-codex-responses",stream:sW,streamSimple:rW}),Mn({api:"google-generative-ai",stream:X9,streamSimple:Z9}),Mn({api:"google-vertex",stream:eW,streamSimple:tW}),Mn({api:"bedrock-converse-stream",stream:uW,streamSimple:dW})}pW();kg();Gn();function mW(t){let e=kw(t);if(!e)throw new Error(`No API provider registered for api: ${t}`);return e}function hW(t,e,n){return mW(t.api).stream(t,e,n)}async function mC(t,e,n){return hW(t,e,n).result()}Mg();Rn();Vo();import{Type as ile}from"typebox";import{Compile as ole}from"typebox/compile";import{Value as cle}from"typebox/value";import*as Lt from"node:fs";import*as gr from"node:path";import{spawn as fW}from"child_process";import{readdirSync as bW,statSync as hC}from"fs";import{homedir as gC}from"os";import{basename as Ag,dirname as kd,join as ws}from"path";function Td(t,e){let n=t.toLowerCase(),i=e.toLowerCase(),s=d=>{if(d.length===0)return{matches:!0,score:0};if(d.length>i.length)return{matches:!1,score:0};let u=0,p=0,m=-1,g=0;for(let h=0;h<i.length&&u<d.length;h++)if(i[h]===d[u]){let f=h===0||/[\s\-_./:]/.test(i[h-1]);m===h-1?(g++,p-=g*5):(g=0,m>=0&&(p+=(h-m-1)*2)),f&&(p-=10),p+=h*.1,m=h,u++}return u<d.length?{matches:!1,score:0}:(d===i&&(p-=100),{matches:!0,score:p})},r=s(n);if(r.matches)return r;let o=n.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),a=n.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),c=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:a?`${a.groups?.letters??""}${a.groups?.digits??""}`:"";if(!c)return r;let l=s(c);return l.matches?{matches:!0,score:l.score+5}:r}function Kt(t,e,n){if(!e.trim())return t;let i=e.trim().split(/\s+/).filter(r=>r.length>0);if(i.length===0)return t;let s=[];for(let r of t){let o=n(r),a=0,c=!0;for(let l of i){let d=Td(l,o);if(d.matches)a+=d.score;else{c=!1;break}}c&&s.push({item:r,totalScore:a})}return s.sort((r,o)=>r.totalScore-o.totalScore),s.map(r=>r.item)}var wC=new Set([" "," ",'"',"'","="]);function rr(t){return t.replace(/\\/g,"/")}function xW(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yW(t){let e=rr(t);if(!e.includes("/"))return e;let n=e.endsWith("/"),i=e.replace(/^\/+|\/+$/g,"");if(!i)return e;let s="[\\\\/]",r=i.split("/").filter(Boolean).map(a=>xW(a));if(r.length===0)return e;let o=r.join(s);return n&&(o+=s),o}function fC(t){for(let e=t.length-1;e>=0;e-=1)if(wC.has(t[e]??""))return e;return-1}function vW(t){let e=!1,n=-1;for(let i=0;i<t.length;i+=1)t[i]==='"'&&(e=!e,e&&(n=i));return e?n:null}function bC(t,e){return e===0||wC.has(t[e-1]??"")}function xC(t){let e=vW(t);return e===null?null:e>0&&t[e-1]==="@"?bC(t,e-1)?t.slice(e-1):null:bC(t,e)?t.slice(e):null}function yC(t){return t.startsWith('@"')?{rawPrefix:t.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:t.startsWith('"')?{rawPrefix:t.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:t.startsWith("@")?{rawPrefix:t.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:t,isAtPrefix:!1,isQuotedPrefix:!1}}function vC(t,e){let n=e.isQuotedPrefix||t.includes(" "),i=e.isAtPrefix?"@":"";return n?`${`${i}"`}${t}"`:`${i}${t}`}async function wW(t,e,n,i,s){let r=["--base-directory",t,"--max-results",String(i),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return rr(n).includes("/")&&r.push("--full-path"),n&&r.push(yW(n)),await new Promise(o=>{if(s.aborted){o([]);return}let a=fW(e,r,{stdio:["ignore","pipe","pipe"]}),c="",l=!1,d=p=>{l||(l=!0,s.removeEventListener("abort",u),o(p))},u=()=>{a.exitCode===null&&a.kill("SIGKILL")};s.addEventListener("abort",u,{once:!0}),a.stdout.setEncoding("utf-8"),a.stdout.on("data",p=>{c+=p}),a.on("error",()=>{d([])}),a.on("close",p=>{if(s.aborted||p!==0||!c){d([]);return}let m=c.trim().split(`
|
|
32
32
|
`).filter(Boolean),g=[];for(let h of m){let f=rr(h),x=f.endsWith("/"),y=x?f.slice(0,-1):f;y===".git"||y.startsWith(".git/")||y.includes("/.git/")||g.push({path:f,isDirectory:x})}d(g)})})}var Qc=class{constructor(e=[],n,i=null){this.commands=e,this.basePath=n,this.fdPath=i}async getSuggestions(e,n,i,s){let o=(e[n]||"").slice(0,i),a=this.extractAtPrefix(o);if(a){let{rawPrefix:d,isQuotedPrefix:u}=yC(a),p=await this.getFuzzyFileSuggestions(d,{isQuotedPrefix:u,signal:s.signal});return p.length===0?null:{items:p,prefix:a}}if(!s.force&&o.startsWith("/")){let d=o.indexOf(" ");if(d===-1){let h=o.slice(1),f=this.commands.map(y=>{let w="name"in y?y.name:y.value,P="argumentHint"in y&&y.argumentHint?y.argumentHint:void 0,_=y.description??"",R=P?_?`${P} \u2014 ${_}`:P:_;return{name:w,label:w,description:R||void 0}}),x=Kt(f,h,y=>y.name).map(y=>({value:y.name,label:y.label,...y.description&&{description:y.description}}));return x.length===0?null:{items:x,prefix:o}}let u=o.slice(1,d),p=o.slice(d+1),m=this.commands.find(h=>("name"in h?h.name:h.value)===u);if(!m||!("getArgumentCompletions"in m)||!m.getArgumentCompletions)return null;let g=await m.getArgumentCompletions(p);return!Array.isArray(g)||g.length===0?null:{items:g,prefix:p}}let c=this.extractPathPrefix(o,s.force??!1);if(c===null)return null;let l=this.getFileSuggestions(c);return l.length===0?null:{items:l,prefix:c}}applyCompletion(e,n,i,s,r){let o=e[n]||"",a=o.slice(0,i-r.length),c=o.slice(i),l=r.startsWith('"')||r.startsWith('@"'),d=c.startsWith('"'),u=s.value.endsWith('"'),p=l&&u&&d?c.slice(1):c;if(r.startsWith("/")&&a.trim()===""&&!r.slice(1).includes("/")){let P=`${a}/${s.value} ${p}`,_=[...e];return _[n]=P,{lines:_,cursorLine:n,cursorCol:a.length+s.value.length+2}}if(r.startsWith("@")){let P=s.label.endsWith("/"),_=P?"":" ",R=`${a+s.value}${_}${p}`,L=[...e];L[n]=R;let E=s.value.endsWith('"'),W=P&&E?s.value.length-1:s.value.length;return{lines:L,cursorLine:n,cursorCol:a.length+W+_.length}}let g=o.slice(0,i);if(g.includes("/")&&g.includes(" ")){let P=a+s.value+p,_=[...e];_[n]=P;let R=s.label.endsWith("/"),L=s.value.endsWith('"'),E=R&&L?s.value.length-1:s.value.length;return{lines:_,cursorLine:n,cursorCol:a.length+E}}let h=a+s.value+p,f=[...e];f[n]=h;let x=s.label.endsWith("/"),y=s.value.endsWith('"'),w=x&&y?s.value.length-1:s.value.length;return{lines:f,cursorLine:n,cursorCol:a.length+w}}extractAtPrefix(e){let n=xC(e);if(n?.startsWith('@"'))return n;let i=fC(e),s=i===-1?0:i+1;return e[s]==="@"?e.slice(s):null}extractPathPrefix(e,n=!1){let i=xC(e);if(i)return i;let s=fC(e),r=s===-1?e:e.slice(s+1);return n||r.includes("/")||r.startsWith(".")||r.startsWith("~/")||r===""&&e.endsWith(" ")?r:null}expandHomePath(e){if(e.startsWith("~/")){let n=ws(gC(),e.slice(2));return e.endsWith("/")&&!n.endsWith("/")?`${n}/`:n}else if(e==="~")return gC();return e}resolveScopedFuzzyQuery(e){let n=rr(e),i=n.lastIndexOf("/");if(i===-1)return null;let s=n.slice(0,i+1),r=n.slice(i+1),o;s.startsWith("~/")?o=this.expandHomePath(s):s.startsWith("/")?o=s:o=ws(this.basePath,s);try{if(!hC(o).isDirectory())return null}catch{return null}return{baseDir:o,query:r,displayBase:s}}scopedPathForDisplay(e,n){let i=rr(n);return e==="/"?`/${i}`:`${rr(e)}${i}`}getFileSuggestions(e){try{let n,i,{rawPrefix:s,isAtPrefix:r,isQuotedPrefix:o}=yC(e),a=s;if(a.startsWith("~")&&(a=this.expandHomePath(a)),s===""||s==="./"||s==="../"||s==="~"||s==="~/"||s==="/"||r&&s==="")s.startsWith("~")||a.startsWith("/")?n=a:n=ws(this.basePath,a),i="";else if(s.endsWith("/"))s.startsWith("~")||a.startsWith("/")?n=a:n=ws(this.basePath,a),i="";else{let u=kd(a),p=Ag(a);s.startsWith("~")||a.startsWith("/")?n=u:n=ws(this.basePath,u),i=p}let l=bW(n,{withFileTypes:!0}),d=[];for(let u of l){if(!u.name.toLowerCase().startsWith(i.toLowerCase()))continue;let p=u.isDirectory();if(!p&&u.isSymbolicLink())try{let y=ws(n,u.name);p=hC(y).isDirectory()}catch{}let m,g=u.name,h=s;if(h.endsWith("/"))m=h+g;else if(h.includes("/")||h.includes("\\"))if(h.startsWith("~/")){let y=h.slice(2),w=kd(y);m=`~/${w==="."?g:ws(w,g)}`}else if(h.startsWith("/")){let y=kd(h);y==="/"?m=`/${g}`:m=`${y}/${g}`}else m=ws(kd(h),g),h.startsWith("./")&&!m.startsWith("./")&&(m=`./${m}`);else h.startsWith("~")?m=`~/${g}`:m=g;m=rr(m);let f=p?`${m}/`:m,x=vC(f,{isDirectory:p,isAtPrefix:r,isQuotedPrefix:o});d.push({value:x,label:g+(p?"/":"")})}return d.sort((u,p)=>{let m=u.value.endsWith("/"),g=p.value.endsWith("/");return m&&!g?-1:!m&&g?1:u.label.localeCompare(p.label)}),d}catch{return[]}}scoreEntry(e,n,i){let r=Ag(e).toLowerCase(),o=n.toLowerCase(),a=0;return r===o?a=100:r.startsWith(o)?a=80:r.includes(o)?a=50:e.toLowerCase().includes(o)&&(a=30),i&&a>0&&(a+=10),a}async getFuzzyFileSuggestions(e,n){if(!this.fdPath||n.signal.aborted)return[];try{let i=this.resolveScopedFuzzyQuery(e),s=i?.baseDir??this.basePath,r=i?.query??e,o=await wW(s,this.fdPath,r,100,n.signal);if(n.signal.aborted)return[];let a=o.map(d=>({...d,score:r?this.scoreEntry(d.path,r,d.isDirectory):1})).filter(d=>d.score>0);a.sort((d,u)=>u.score-d.score);let c=a.slice(0,20),l=[];for(let{path:d,isDirectory:u}of c){let p=u?d.slice(0,-1):d,m=i?this.scopedPathForDisplay(i.displayBase,p):p,g=Ag(p),h=u?`${m}/`:m,f=vC(h,{isDirectory:u,isAtPrefix:!0,isQuotedPrefix:n.isQuotedPrefix});l.push({value:f,label:g+(u?"/":""),description:m})}return l}catch{return[]}}shouldTriggerFileCompletion(e,n,i){let r=(e[n]||"").slice(0,i);return!(r.trim().startsWith("/")&&!r.trim().includes(" "))}};import{eastAsianWidth as SC}from"get-east-asian-width";var Fi=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Md(){return Fi}function SW(t){let e=t.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||t.includes("\uFE0F")||t.length>2}var CW=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),TW=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),kW=new RegExp("^\\p{RGI_Emoji}$","v"),MW=512,Yc=new Map;function Wg(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32||n>126)return!1}return!0}function IW(t,e){if(e<=0||t.length===0)return{text:"",width:0};if(Wg(t)){let c=t.slice(0,e);return{text:c,width:c.length}}let n=t.includes("\x1B"),i=t.includes(" ");if(!n&&!i){let c="",l=0;for(let{segment:d}of Fi.segment(t)){let u=or(d);if(l+u>e)break;c+=d,l+=u}return{text:c,width:l}}let s="",r=0,o=0,a="";for(;o<t.length;){let c=bn(t,o);if(c){a+=c.code,o+=c.length;continue}if(t[o]===" "){if(r+3>e)break;a&&(s+=a,a=""),s+=" ",r+=3,o++;continue}let l=o;for(;l<t.length&&t[l]!==" "&&!bn(t,l);)l++;for(let{segment:d}of Fi.segment(t.slice(o,l))){let u=or(d);if(r+u>e)return{text:s,width:r};a&&(s+=a,a=""),s+=d,r+=u}o=l}return{text:s,width:r}}function Og(t,e,n,i,s,r){let o="\x1B[0m",a=e+i,c;return n.length>0?c=`${t}${o}${n}${o}`:c=`${t}${o}`,r?c+" ".repeat(Math.max(0,s-a)):c}function or(t){if(CW.test(t))return 0;if(SW(t)&&kW.test(t))return 2;let n=t.replace(TW,"").codePointAt(0);if(n===void 0)return 0;if(n>=127462&&n<=127487)return 2;let i=SC(n);if(t.length>1)for(let s of t.slice(1)){let r=s.codePointAt(0);r>=65280&&r<=65519?i+=SC(r):(r===3635||r===3763)&&(i+=1)}return i}function j(t){if(t.length===0)return 0;if(Wg(t))return t.length;let e=Yc.get(t);if(e!==void 0)return e;let n=t;if(t.includes(" ")&&(n=n.replace(/\t/g," ")),n.includes("\x1B")){let s="",r=0;for(;r<n.length;){let o=bn(n,r);if(o){r+=o.length;continue}s+=n[r],r++}n=s}let i=0;for(let{segment:s}of Fi.segment(n))i+=or(s);if(Yc.size>=MW){let s=Yc.keys().next().value;s!==void 0&&Yc.delete(s)}return Yc.set(t,i),i}var RW=/[\u0e33\u0eb3]/,PW=/[\u0e33\u0eb3]/g;function CC(t){return RW.test(t)?t.replace(PW,e=>e==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2"):t}function bn(t,e){if(e>=t.length||t[e]!=="\x1B")return null;let n=t[e+1];if(n==="["){let i=e+2;for(;i<t.length&&!/[mGKHJ]/.test(t[i]);)i++;return i<t.length?{code:t.substring(e,i+1),length:i+1-e}:null}if(n==="]"){let i=e+2;for(;i<t.length;){if(t[i]==="\x07")return{code:t.substring(e,i+1),length:i+1-e};if(t[i]==="\x1B"&&t[i+1]==="\\")return{code:t.substring(e,i+2),length:i+2-e};i++}return null}if(n==="_"){let i=e+2;for(;i<t.length;){if(t[i]==="\x07")return{code:t.substring(e,i+1),length:i+1-e};if(t[i]==="\x1B"&&t[i+1]==="\\")return{code:t.substring(e,i+2),length:i+2-e};i++}return null}return null}function _W(t){if(!t.startsWith("\x1B]8;"))return;let e=t.endsWith("\x07")?"\x07":"\x1B\\",n=t.slice(4,e==="\x07"?-1:-2),i=n.indexOf(";");if(i===-1)return;let s=n.slice(0,i),r=n.slice(i+1);return r?{params:s,url:r,terminator:e}:null}function EW(t){return`\x1B]8;${t.params};${t.url}${t.terminator}`}function AW(t){return`\x1B]8;;${t}`}var Xc=class{constructor(){this.bold=!1;this.dim=!1;this.italic=!1;this.underline=!1;this.blink=!1;this.inverse=!1;this.hidden=!1;this.strikethrough=!1;this.fgColor=null;this.bgColor=null;this.activeHyperlink=null}process(e){let n=_W(e);if(n!==void 0){this.activeHyperlink=n;return}if(!e.endsWith("m"))return;let i=e.match(/\x1b\[([\d;]*)m/);if(!i)return;let s=i[1];if(s===""||s==="0"){this.reset();return}let r=s.split(";"),o=0;for(;o<r.length;){let a=Number.parseInt(r[o],10);if(a===38||a===48){if(r[o+1]==="5"&&r[o+2]!==void 0){let c=`${r[o]};${r[o+1]};${r[o+2]}`;a===38?this.fgColor=c:this.bgColor=c,o+=3;continue}else if(r[o+1]==="2"&&r[o+4]!==void 0){let c=`${r[o]};${r[o+1]};${r[o+2]};${r[o+3]};${r[o+4]}`;a===38?this.fgColor=c:this.bgColor=c,o+=5;continue}}switch(a){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:a>=30&&a<=37||a>=90&&a<=97?this.fgColor=String(a):(a>=40&&a<=47||a>=100&&a<=107)&&(this.bgColor=String(a));break}o++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let n=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(n+=EW(this.activeHyperlink)),n}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.activeHyperlink&&(e+=AW(this.activeHyperlink.terminator)),e}};function TC(t,e){let n=0;for(;n<t.length;){let i=bn(t,n);i?(e.process(i.code),n+=i.length):n++}}function OW(t){let e=[],n="",i="",s=!1,r=0;for(;r<t.length;){let o=bn(t,r);if(o){i+=o.code,r+=o.length;continue}let a=t[r],c=a===" ";c!==s&&n&&(e.push(n),n=""),i&&(n+=i,i=""),s=c,n+=a,r++}return i&&(n+=i),n&&e.push(n),e}function zn(t,e){if(!t)return[""];let n=t.split(`
|
|
33
|
-
`),i=[],s=new Xc;for(let r of n){let o=i.length>0?s.getActiveCodes():"";i.push(...LW(o+r,e)),TC(r,s)}return i.length>0?i:[""]}function LW(t,e){if(!t)return[""];if(j(t)<=e)return[t];let i=[],s=new Xc,r=OW(t),o="",a=0;for(let c of r){let l=j(c),d=c.trim()==="";if(l>e&&!d){if(o){let m=s.getLineEndReset();m&&(o+=m),i.push(o),o="",a=0}let p=UW(c,e,s);i.push(...p.slice(0,-1)),o=p[p.length-1],a=j(o);continue}if(a+l>e&&a>0){let p=o.trimEnd(),m=s.getLineEndReset();m&&(p+=m),i.push(p),d?(o=s.getActiveCodes(),a=0):(o=s.getActiveCodes()+c,a=l)}else o+=c,a+=l;TC(c,s)}return o&&i.push(o),i.length>0?i.map(c=>c.trimEnd()):[""]}var WW=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function Ht(t){return/\s/.test(t)}function zt(t){return WW.test(t)}function UW(t,e,n){let i=[],s=n.getActiveCodes(),r=0,o=0,a=[];for(;o<t.length;){let c=bn(t,o);if(c)a.push({type:"ansi",value:c.code}),o+=c.length;else{let l=o;for(;l<t.length&&!bn(t,l);)l++;let d=t.slice(o,l);for(let u of Fi.segment(d))a.push({type:"grapheme",value:u.segment});o=l}}for(let c of a){if(c.type==="ansi"){s+=c.value,n.process(c.value);continue}let l=c.value;if(!l)continue;let d=j(l);if(r+d>e){let u=n.getLineEndReset();u&&(s+=u),i.push(s),s=n.getActiveCodes(),r=0}s+=l,r+=d}return s&&i.push(s),i.length>0?i:[""]}function Ss(t,e,n){let i=j(t),s=Math.max(0,e-i),r=" ".repeat(s),o=t+r;return n(o)}function X(t,e,n="...",i=!1){if(e<=0)return"";if(t.length===0)return i?" ".repeat(e):"";let s=j(n);if(s>=e){let h=j(t);if(h<=e)return i?t+" ".repeat(e-h):t;let f=IW(n,e);return f.width===0?i?" ".repeat(e):"":Og("",0,f.text,f.width,e,i)}if(Wg(t)){if(t.length<=e)return i?t+" ".repeat(e-t.length):t;let h=e-s;return Og(t.slice(0,h),h,n,s,e,i)}let r=e-s,o="",a="",c=0,l=0,d=!0,u=!1,p=!1,m=t.includes("\x1B"),g=t.includes(" ");if(!m&&!g){for(let{segment:h}of Fi.segment(t)){let f=or(h);if(d&&l+f<=r?(o+=h,l+=f):d=!1,c+=f,c>e){u=!0;break}}p=!u}else{let h=0;for(;h<t.length;){let f=bn(t,h);if(f){a+=f.code,h+=f.length;continue}if(t[h]===" "){if(d&&l+3<=r?(a&&(o+=a,a=""),o+=" ",l+=3):(d=!1,a=""),c+=3,c>e){u=!0;break}h++;continue}let x=h;for(;x<t.length&&t[x]!==" "&&!bn(t,x);)x++;for(let{segment:y}of Fi.segment(t.slice(h,x))){let w=or(y);if(d&&l+w<=r?(a&&(o+=a,a=""),o+=y,l+=w):(d=!1,a=""),c+=w,c>e){u=!0;break}}if(u)break;h=x}p=h>=t.length}return!u&&p?i?t+" ".repeat(Math.max(0,e-c)):t:Og(o,l,n,s,e,i)}function ta(t,e,n,i=!1){return Ug(t,e,n,i).text}function Ug(t,e,n,i=!1){if(n<=0)return{text:"",width:0};let s=e+n,r="",o=0,a=0,c=0,l="";for(;c<t.length;){let d=bn(t,c);if(d){a>=e&&a<s?r+=d.code:a<e&&(l+=d.code),c+=d.length;continue}let u=c;for(;u<t.length&&!bn(t,u);)u++;for(let{segment:p}of Fi.segment(t.slice(c,u))){let m=or(p),g=a>=e&&a<s,h=!i||a+m<=s;if(g&&h&&(l&&(r+=l,l=""),r+=p,o+=m),a+=m,a>=s)break}if(c=u,a>=s)break}return{text:r,width:o}}var Lg=new Xc;function kC(t,e,n,i,s=!1){let r="",o=0,a="",c=0,l=0,d=0,u="",p=!1,m=n+i;for(Lg.clear();d<t.length;){let g=bn(t,d);if(g){Lg.process(g.code),l<e?u+=g.code:l>=n&&l<m&&p&&(a+=g.code),d+=g.length;continue}let h=d;for(;h<t.length&&!bn(t,h);)h++;for(let{segment:f}of Fi.segment(t.slice(d,h))){let x=or(f);if(l<e?(u&&(r+=u,u=""),r+=f,o+=x):l>=n&&l<m&&(!s||l+x<=m)&&(p||(a+=Lg.getActiveCodes(),p=!0),a+=f,c+=x),l+=x,i<=0?l>=e:l>=m)break}if(d=h,i<=0?l>=e:l>=m)break}return{before:r,beforeWidth:o,after:a,afterWidth:c}}var ut=class{constructor(e=1,n=1,i){this.children=[];this.paddingX=e,this.paddingY=n,this.bgFn=i}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let n=this.children.indexOf(e);n!==-1&&(this.children.splice(n,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}invalidateCache(){this.cache=void 0}matchCache(e,n,i){let s=this.cache;return!!s&&s.width===e&&s.bgSample===i&&s.childLines.length===n.length&&s.childLines.every((r,o)=>r===n[o])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}render(e){if(this.children.length===0)return[];let n=Math.max(1,e-this.paddingX*2),i=" ".repeat(this.paddingX),s=[];for(let a of this.children){let c=a.render(n);for(let l of c)s.push(i+l)}if(s.length===0)return[];let r=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(e,s,r))return this.cache.lines;let o=[];for(let a=0;a<this.paddingY;a++)o.push(this.applyBg("",e));for(let a of s)o.push(this.applyBg(a,e));for(let a=0;a<this.paddingY;a++)o.push(this.applyBg("",e));return this.cache={childLines:s,width:e,bgSample:r,lines:o},o}applyBg(e,n){let i=j(e),s=Math.max(0,n-i),r=e+" ".repeat(s);return this.bgFn?Ss(r,n,this.bgFn):r}};var Di=!1;function el(t){Di=t}var ar={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:t=>`ctrl+${t}`,shift:t=>`shift+${t}`,alt:t=>`alt+${t}`,super:t=>`super+${t}`,ctrlShift:t=>`ctrl+shift+${t}`,shiftCtrl:t=>`shift+ctrl+${t}`,ctrlAlt:t=>`ctrl+alt+${t}`,altCtrl:t=>`alt+ctrl+${t}`,shiftAlt:t=>`shift+alt+${t}`,altShift:t=>`alt+shift+${t}`,ctrlSuper:t=>`ctrl+super+${t}`,superCtrl:t=>`super+ctrl+${t}`,shiftSuper:t=>`shift+super+${t}`,superShift:t=>`super+shift+${t}`,altSuper:t=>`alt+super+${t}`,superAlt:t=>`super+alt+${t}`,ctrlShiftAlt:t=>`ctrl+shift+alt+${t}`,ctrlShiftSuper:t=>`ctrl+shift+super+${t}`},RC=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),ee={shift:1,alt:2,ctrl:4,super:8},Zc=192,Ae={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},gt={up:-1,down:-2,right:-3,left:-4},je={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},FW=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,gt.left],[57418,gt.right],[57419,gt.up],[57420,gt.down],[57421,je.pageUp],[57422,je.pageDown],[57423,je.home],[57424,je.end],[57425,je.insert],[57426,je.delete]]);function Fg(t){return FW.get(t)??t}function _d(t,e){return(e&~Zc&ee.shift)!==0&&t>=65&&t<=90?t+32:t}var Pn={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},DW={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},$W={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var Vt=(t,e)=>e.includes(t),xn=(t,e,n)=>n===ee.shift?Vt(t,DW[e]):n===ee.ctrl?Vt(t,$W[e]):!1,Id="press";function Vn(t){return t.includes("\x1B[200~")?!1:!!(t.includes(":3u")||t.includes(":3~")||t.includes(":3A")||t.includes(":3B")||t.includes(":3C")||t.includes(":3D")||t.includes(":3H")||t.includes(":3F"))}function Rd(t){if(!t)return"press";let e=parseInt(t,10);return e===2?"repeat":e===3?"release":"press"}function BW(t){let e=t.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let r=parseInt(e[1],10),o=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,a=e[3]?parseInt(e[3],10):void 0,c=e[4]?parseInt(e[4],10):1,l=Rd(e[5]);return Id=l,{codepoint:r,shiftedKey:o,baseLayoutKey:a,modifier:c-1,eventType:l}}let n=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(n){let r=parseInt(n[1],10),o=Rd(n[2]),a={A:-1,B:-2,C:-3,D:-4};return Id=o,{codepoint:a[n[3]],modifier:r-1,eventType:o}}let i=t.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let r=parseInt(i[1],10),o=i[2]?parseInt(i[2],10):1,a=Rd(i[3]),l={2:je.insert,3:je.delete,5:je.pageUp,6:je.pageDown,7:je.home,8:je.end}[r];if(l!==void 0)return Id=a,{codepoint:l,modifier:o-1,eventType:a}}let s=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(s){let r=parseInt(s[1],10),o=Rd(s[2]),a=s[3]==="H"?je.home:je.end;return Id=o,{codepoint:a,modifier:r-1,eventType:o}}return null}function me(t,e,n){let i=BW(t);if(!i)return!1;let s=i.modifier&~Zc,r=n&~Zc;if(s!==r)return!1;let o=_d(Fg(i.codepoint),i.modifier),a=_d(Fg(e),n);if(o===a)return!0;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===e){let c=o,l=c>=97&&c<=122,d=RC.has(String.fromCharCode(c));if(!l&&!d)return!0}return!1}function Dg(t){let e=t.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let n=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:n-1}}function _n(t,e,n){let i=Dg(t);return i?i.codepoint===e&&i.modifier===n:!1}function NW(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function MC(t,e){return t==="\x7F"?e===0:t!=="\b"?!1:NW()?e===ee.ctrl:e===0}function jW(t){let e=t.toLowerCase(),n=e.charCodeAt(0);return n>=97&&n<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(n&31):e==="-"?"":null}function IC(t){return t>="0"&&t<="9"}function Pd(t,e,n){if(n===0)return!1;let i=Dg(t);return!i||i.modifier!==n?!1:_d(i.codepoint,i.modifier)===_d(e,n)}function qW(t){let e=t.toLowerCase().split("+"),n=e[e.length-1];return n?{key:n,ctrl:e.includes("ctrl"),shift:e.includes("shift"),alt:e.includes("alt"),super:e.includes("super")}:null}function _e(t,e){let n=qW(e);if(!n)return!1;let{key:i,ctrl:s,shift:r,alt:o,super:a}=n,c=0;switch(r&&(c|=ee.shift),o&&(c|=ee.alt),s&&(c|=ee.ctrl),a&&(c|=ee.super),i){case"escape":case"esc":return c!==0?!1:t==="\x1B"||me(t,Ae.escape,0)||_n(t,Ae.escape,0);case"space":return!Di&&(c===ee.ctrl&&t==="\0"||c===ee.alt&&t==="\x1B ")?!0:c===0?t===" "||me(t,Ae.space,0)||_n(t,Ae.space,0):me(t,Ae.space,c)||_n(t,Ae.space,c);case"tab":return c===ee.shift?t==="\x1B[Z"||me(t,Ae.tab,ee.shift)||_n(t,Ae.tab,ee.shift):c===0?t===" "||me(t,Ae.tab,0):me(t,Ae.tab,c)||_n(t,Ae.tab,c);case"enter":case"return":return c===ee.shift?me(t,Ae.enter,ee.shift)||me(t,Ae.kpEnter,ee.shift)||_n(t,Ae.enter,ee.shift)?!0:Di?t==="\x1B\r"||t===`
|
|
34
|
-
`:!1:c===ee.alt?me(t,
|
|
35
|
-
`||t==="\x1BOM"||me(t,Ae.enter,0)||me(t,Ae.kpEnter,0):me(t,Ae.enter,c)||me(t,Ae.kpEnter,c)||_n(t,Ae.enter,c);case"backspace":return c===ee.alt?t==="\x1B\x7F"||t==="\x1B\b"?!0:me(t,Ae.backspace,ee.alt)||_n(t,Ae.backspace,ee.alt):c===ee.ctrl?MC(t,ee.ctrl)?!0:me(t,Ae.backspace,ee.ctrl)||_n(t,Ae.backspace,ee.ctrl):c===0?MC(t,0)||me(t,Ae.backspace,0)||_n(t,Ae.backspace,0):me(t,Ae.backspace,c)||_n(t,Ae.backspace,c);case"insert":return c===0?Vt(t,Pn.insert)||me(t,je.insert,0):xn(t,"insert",c)?!0:me(t,je.insert,c);case"delete":return c===0?Vt(t,Pn.delete)||me(t,je.delete,0):xn(t,"delete",c)?!0:me(t,je.delete,c);case"clear":return c===0?Vt(t,Pn.clear):xn(t,"clear",c);case"home":return c===0?Vt(t,Pn.home)||me(t,je.home,0):xn(t,"home",c)?!0:me(t,je.home,c);case"end":return c===0?Vt(t,Pn.end)||me(t,je.end,0):xn(t,"end",c)?!0:me(t,je.end,c);case"pageup":return c===0?Vt(t,Pn.pageUp)||me(t,je.pageUp,0):xn(t,"pageUp",c)?!0:me(t,je.pageUp,c);case"pagedown":return c===0?Vt(t,Pn.pageDown)||me(t,je.pageDown,0):xn(t,"pageDown",c)?!0:me(t,je.pageDown,c);case"up":return c===ee.alt?t==="\x1Bp"||me(t,gt.up,ee.alt):c===0?Vt(t,Pn.up)||me(t,gt.up,0):xn(t,"up",c)?!0:me(t,gt.up,c);case"down":return c===ee.alt?t==="\x1Bn"||me(t,gt.down,ee.alt):c===0?Vt(t,Pn.down)||me(t,gt.down,0):xn(t,"down",c)?!0:me(t,gt.down,c);case"left":return c===ee.alt?t==="\x1B[1;3D"||!Di&&t==="\x1BB"||t==="\x1Bb"||me(t,gt.left,ee.alt):c===ee.ctrl?t==="\x1B[1;5D"||xn(t,"left",ee.ctrl)||me(t,gt.left,ee.ctrl):c===0?Vt(t,Pn.left)||me(t,gt.left,0):xn(t,"left",c)?!0:me(t,gt.left,c);case"right":return c===ee.alt?t==="\x1B[1;3C"||!Di&&t==="\x1BF"||t==="\x1Bf"||me(t,gt.right,ee.alt):c===ee.ctrl?t==="\x1B[1;5C"||xn(t,"right",ee.ctrl)||me(t,gt.right,ee.ctrl):c===0?Vt(t,Pn.right)||me(t,gt.right,0):xn(t,"right",c)?!0:me(t,gt.right,c);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return c!==0?!1:Vt(t,Pn[i])}if(i.length===1&&(i>="a"&&i<="z"||IC(i)||RC.has(i))){let l=i.charCodeAt(0),d=jW(i),u=i>="a"&&i<="z",p=IC(i);return c===ee.ctrl+ee.alt&&!Di&&d&&t===`\x1B${d}`||c===ee.alt&&!Di&&(u||p)&&t===`\x1B${i}`?!0:c===ee.ctrl?d&&t===d?!0:me(t,l,ee.ctrl)||Pd(t,l,ee.ctrl):c===ee.shift+ee.ctrl?me(t,l,ee.shift+ee.ctrl)||Pd(t,l,ee.shift+ee.ctrl):c===ee.shift?u&&t===i.toUpperCase()?!0:me(t,l,ee.shift)||Pd(t,l,ee.shift):c!==0?me(t,l,c)||Pd(t,l,c):t===i||me(t,l,0)}return!1}var GW=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KW=ee.shift|Zc;function Ed(t){let e=t.match(GW);if(!e)return;let n=Number.parseInt(e[1]??"",10);if(!Number.isFinite(n))return;let i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,s=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(s)?s-1:0;if((r&~KW)!==0||r&(ee.alt|ee.ctrl))return;let o=n;if(r&ee.shift&&typeof i=="number"&&(o=i),o=Fg(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function HW(t){let e=Dg(t);if(!(!e||(e.modifier&~Zc&~ee.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function $g(t){return Ed(t)??HW(t)}var ia={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:"pageUp",description:"Page up"},"tui.editor.pageDown":{defaultKeys:"pageDown",description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:"shift+enter",description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"}};function Bg(t){if(t===void 0)return[];let e=Array.isArray(t)?t:[t],n=new Set,i=[];for(let s of e)n.has(s)||(n.add(s),i.push(s));return i}var na=class{constructor(e,n={}){this.keysById=new Map;this.conflicts=[];this.definitions=e,this.userBindings=n,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[n,i]of Object.entries(this.userBindings))if(n in this.definitions)for(let s of Bg(i)){let r=e.get(s)??new Set;r.add(n),e.set(s,r)}for(let[n,i]of e)i.size>1&&this.conflicts.push({key:n,keybindings:[...i]});for(let[n,i]of Object.entries(this.definitions)){let s=this.userBindings[n],r=Bg(s===void 0?i.defaultKeys:s);this.keysById.set(n,r)}}matches(e,n){let i=this.keysById.get(n)??[];for(let s of i)if(_e(e,s))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let n of Object.keys(this.definitions)){let i=this.keysById.get(n)??[];e[n]=i.length===1?i[0]:[...i]}return e}},Ad=null;function tl(t){Ad=t}function ve(){return Ad||(Ad=new na(ia)),Ad}var A=class{constructor(e="",n=1,i=1,s){this.text=e,this.paddingX=n,this.paddingY=i,this.customBgFn=s}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let u=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u}let n=this.text.replace(/\t/g," "),i=Math.max(1,e-this.paddingX*2),s=zn(n,i),r=" ".repeat(this.paddingX),o=" ".repeat(this.paddingX),a=[];for(let u of s){let p=r+u+o;if(this.customBgFn)a.push(Ss(p,e,this.customBgFn));else{let m=j(p),g=Math.max(0,e-m);a.push(p+" ".repeat(g))}}let c=" ".repeat(e),l=[];for(let u=0;u<this.paddingY;u++){let p=this.customBgFn?Ss(c,e,this.customBgFn):c;l.push(p)}let d=[...l,...a,...l];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d.length>0?d:[""]}};var PC=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_C=80,Jt=class extends A{constructor(n,i,s,r="Loading...",o){super("",1,0);this.frames=[...PC];this.intervalMs=_C;this.currentFrame=0;this.intervalId=null;this.ui=null;this.renderIndicatorVerbatim=!1;this.message="Loading...";this.ui=n,this.spinnerColorFn=i,this.messageColorFn=s,this.message=r,this.setIndicator(o)}render(n){return["",...super.render(n)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(n){this.message=n,this.updateDisplay()}setIndicator(n){this.renderIndicatorVerbatim=n!==void 0,this.frames=n?.frames!==void 0?[...n.frames]:[...PC],this.intervalMs=n?.intervalMs&&n.intervalMs>0?n.intervalMs:_C,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}updateDisplay(){let n=this.frames[this.currentFrame]??"",i=this.renderIndicatorVerbatim?n:this.spinnerColorFn(n),s=n.length>0?`${i} `:"";this.setText(`${s}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var nl=class extends Jt{constructor(){super(...arguments);this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(n){ve().matches(n,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var sa=class{constructor(){this.ring=[]}push(e,n){if(e)if(n.accumulate&&this.ring.length>0){let i=this.ring.pop();this.ring.push(n.prepend?e+i:i+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};import*as Cs from"node:fs";import*as Vg from"node:os";import*as oa from"node:path";import{performance as Hg}from"node:perf_hooks";var Ng=null,OC={widthPx:9,heightPx:18};function Od(){return OC}function jg(t){OC=t}function LC(){let t=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",i=n==="truecolor"||n==="24bit";return!!process.env.TMUX||e.startsWith("tmux")||e.startsWith("screen")?{images:null,trueColor:i,hyperlinks:!1}:process.env.KITTY_WINDOW_ID||t==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:t==="ghostty"||e.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||t==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||t==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:t==="vscode"?{images:null,trueColor:!0,hyperlinks:!0}:t==="alacritty"?{images:null,trueColor:!0,hyperlinks:!0}:{images:null,trueColor:i||!!process.env.WT_SESSION,hyperlinks:!1}}function dt(){return Ng||(Ng=LC()),Ng}var EC="\x1B_G",AC="\x1B]1337;File=";function cr(t){return t.startsWith(EC)||t.startsWith(AC)?!0:t.includes(EC)||t.includes(AC)}function qg(){return Math.floor(Math.random()*4294967294)+1}function WC(t,e={}){let i=["a=T","f=100","q=2"];if(e.moveCursor===!1&&i.push("C=1"),e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),t.length<=4096)return`\x1B_G${i.join(",")};${t}\x1B\\`;let s=[],r=0,o=!0;for(;r<t.length;){let a=t.slice(r,r+4096),c=r+4096>=t.length;o?(s.push(`\x1B_G${i.join(",")},m=1;${a}\x1B\\`),o=!1):c?s.push(`\x1B_Gm=0;${a}\x1B\\`):s.push(`\x1B_Gm=1;${a}\x1B\\`),r+=4096}return s.join("")}function Gg(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function UC(t,e={}){let n=[`inline=${e.inline!==!1?1:0}`];if(e.width!==void 0&&n.push(`width=${e.width}`),e.height!==void 0&&n.push(`height=${e.height}`),e.name){let i=Buffer.from(e.name).toString("base64");n.push(`name=${i}`)}return e.preserveAspectRatio===!1&&n.push("preserveAspectRatio=0"),`\x1B]1337;File=${n.join(";")}:${t}\x07`}function zW(t,e,n,i={widthPx:9,heightPx:18}){let s=Math.max(1,Math.floor(e)),r=n===void 0?void 0:Math.max(1,Math.floor(n)),o=Math.max(1,t.widthPx),a=Math.max(1,t.heightPx),c=s*i.widthPx/o,l=r===void 0?c:r*i.heightPx/a,d=Math.min(c,l),u=o*d,p=a*d,m=Math.ceil(u/i.widthPx),g=Math.ceil(p/i.heightPx);return{columns:Math.max(1,Math.min(s,m)),rows:Math.max(1,r===void 0?g:Math.min(r,g))}}function FC(t){try{let e=Buffer.from(t,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let n=e.readUInt32BE(16),i=e.readUInt32BE(20);return{widthPx:n,heightPx:i}}catch{return null}}function DC(t){try{let e=Buffer.from(t,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let n=2;for(;n<e.length-9;){if(e[n]!==255){n++;continue}let i=e[n+1];if(i>=192&&i<=194){let r=e.readUInt16BE(n+5);return{widthPx:e.readUInt16BE(n+7),heightPx:r}}if(n+3>=e.length)return null;let s=e.readUInt16BE(n+2);if(s<2)return null;n+=2+s}return null}catch{return null}}function $C(t){try{let e=Buffer.from(t,"base64");if(e.length<10)return null;let n=e.slice(0,6).toString("ascii");if(n!=="GIF87a"&&n!=="GIF89a")return null;let i=e.readUInt16LE(6),s=e.readUInt16LE(8);return{widthPx:i,heightPx:s}}catch{return null}}function BC(t){try{let e=Buffer.from(t,"base64");if(e.length<30)return null;let n=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if(n!=="RIFF"||i!=="WEBP")return null;let s=e.slice(12,16).toString("ascii");if(s==="VP8 "){if(e.length<30)return null;let r=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:r,heightPx:o}}else if(s==="VP8L"){if(e.length<25)return null;let r=e.readUInt32LE(21),o=(r&16383)+1,a=(r>>14&16383)+1;return{widthPx:o,heightPx:a}}else if(s==="VP8X"){if(e.length<30)return null;let r=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:r,heightPx:o}}return null}catch{return null}}function il(t,e){return e==="image/png"?FC(t):e==="image/jpeg"?DC(t):e==="image/gif"?$C(t):e==="image/webp"?BC(t):null}function Kg(t,e,n={}){let i=dt();if(!i.images)return null;let s=n.maxWidthCells??80,r=zW(e,s,n.maxHeightCells,Od());return i.images==="kitty"?{sequence:WC(t,{columns:r.columns,rows:r.rows,imageId:n.imageId,moveCursor:n.moveCursor}),rows:r.rows,imageId:n.imageId}:i.images==="iterm2"?{sequence:UC(t,{width:r.columns,height:"auto",preserveAspectRatio:n.preserveAspectRatio??!0}),rows:r.rows}:null}function sl(t,e){return`\x1B]8;;${e}\x1B\\${t}\x1B]8;;\x1B\\`}function ra(t,e,n){let i=[];return n&&i.push(n),i.push(`[${t}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}var NC="\x1B_G";function zg(t){let e=t.indexOf(NC);if(e===-1)return[];let n=e+NC.length,i=t.indexOf(";",n);if(i===-1)return[];let s=t.slice(n,i);for(let r of s.split(",")){let[o,a]=r.split("=",2);if(o!=="i"||a===void 0)continue;let c=Number(a);if(Number.isInteger(c)&&c>0&&c<=4294967295)return[c]}return[]}function Jg(t){return t!==null&&"focused"in t}var lr="\x1B_pi:c\x07";function jC(t,e){if(t===void 0)return;if(typeof t=="number")return t;let n=t.match(/^(\d+(?:\.\d+)?)%$/);if(n)return Math.floor(e*parseFloat(n[1])/100)}function VW(){return!!process.env.TERMUX_VERSION}var K=class{constructor(){this.children=[]}addChild(e){this.children.push(e)}removeChild(e){let n=this.children.indexOf(e);n!==-1&&this.children.splice(n,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}render(e){let n=[];for(let i of this.children){let s=i.render(e);for(let r of s)n.push(r)}return n}},Ts=class t extends K{constructor(n,i){super();this.previousLines=[];this.previousKittyImageIds=new Set;this.previousWidth=0;this.previousHeight=0;this.focusedComponent=null;this.inputListeners=new Set;this.renderRequested=!1;this.lastRenderAt=0;this.cursorRow=0;this.hardwareCursorRow=0;this.showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1";this.clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1";this.maxLinesRendered=0;this.previousViewportTop=0;this.fullRedrawCount=0;this.stopped=!1;this.focusOrderCounter=0;this.overlayStack=[];this.terminal=n,i!==void 0&&(this.showHardwareCursor=i)}static{this.MIN_RENDER_INTERVAL_MS=16}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(n){this.showHardwareCursor!==n&&(this.showHardwareCursor=n,n||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(n){this.clearOnShrink=n}setFocus(n){Jg(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=n,Jg(n)&&(n.focused=!0)}showOverlay(n,i){let s={component:n,options:i,preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(s),!i?.nonCapturing&&this.isOverlayVisible(s)&&this.setFocus(n),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let r=this.overlayStack.indexOf(s);if(r!==-1){if(this.overlayStack.splice(r,1),this.focusedComponent===n){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??s.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:r=>{if(s.hidden!==r){if(s.hidden=r,r){if(this.focusedComponent===n){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??s.preFocus)}}else!i?.nonCapturing&&this.isOverlayVisible(s)&&(s.focusOrder=++this.focusOrderCounter,this.setFocus(n));this.requestRender()}},isHidden:()=>s.hidden,focus:()=>{!this.overlayStack.includes(s)||!this.isOverlayVisible(s)||(this.focusedComponent!==n&&this.setFocus(n),s.focusOrder=++this.focusOrderCounter,this.requestRender())},unfocus:()=>{if(this.focusedComponent!==n)return;let r=this.getTopmostVisibleOverlay();this.setFocus(r&&r!==s?r.component:s.preFocus),this.requestRender()},isFocused:()=>this.focusedComponent===n}}hideOverlay(){let n=this.overlayStack.pop();if(n){if(this.focusedComponent===n.component){let i=this.getTopmostVisibleOverlay();this.setFocus(i?.component??n.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(n=>this.isOverlayVisible(n))}isOverlayVisible(n){return n.hidden?!1:n.options?.visible?n.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){for(let n=this.overlayStack.length-1;n>=0;n--)if(!this.overlayStack[n].options?.nonCapturing&&this.isOverlayVisible(this.overlayStack[n]))return this.overlayStack[n]}invalidate(){super.invalidate();for(let n of this.overlayStack)n.component.invalidate?.()}start(){this.stopped=!1,this.terminal.start(n=>this.handleInput(n),()=>this.requestRender()),this.terminal.hideCursor(),this.queryCellSize(),this.requestRender()}addInputListener(n){return this.inputListeners.add(n),()=>{this.inputListeners.delete(n)}}removeInputListener(n){this.inputListeners.delete(n)}queryCellSize(){dt().images&&this.terminal.write("\x1B[16t")}stop(){if(this.stopped=!0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.previousLines.length>0){let i=this.previousLines.length-this.hardwareCursorRow;i>0?this.terminal.write(`\x1B[${i}B`):i<0&&this.terminal.write(`\x1B[${-i}A`),this.terminal.write(`\r
|
|
36
|
-
`)}this.terminal.showCursor(),this.terminal.stop()}requestRender(n=!1){if(n){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.renderRequested=!0,process.nextTick(()=>{this.stopped||!this.renderRequested||(this.renderRequested=!1,this.lastRenderAt=Hg.now(),this.doRender())});return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let n=Hg.now()-this.lastRenderAt,i=Math.max(0,t.MIN_RENDER_INTERVAL_MS-n);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=Hg.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},i)}handleInput(n){if(this.inputListeners.size>0){let s=n;for(let r of this.inputListeners){let o=r(s);if(o?.consume)return;o?.data!==void 0&&(s=o.data)}if(s.length===0)return;n=s}if(this.consumeCellSizeResponse(n))return;if(
|
|
33
|
+
`),i=[],s=new Xc;for(let r of n){let o=i.length>0?s.getActiveCodes():"";i.push(...LW(o+r,e)),TC(r,s)}return i.length>0?i:[""]}function LW(t,e){if(!t)return[""];if(j(t)<=e)return[t];let i=[],s=new Xc,r=OW(t),o="",a=0;for(let c of r){let l=j(c),d=c.trim()==="";if(l>e&&!d){if(o){let m=s.getLineEndReset();m&&(o+=m),i.push(o),o="",a=0}let p=UW(c,e,s);i.push(...p.slice(0,-1)),o=p[p.length-1],a=j(o);continue}if(a+l>e&&a>0){let p=o.trimEnd(),m=s.getLineEndReset();m&&(p+=m),i.push(p),d?(o=s.getActiveCodes(),a=0):(o=s.getActiveCodes()+c,a=l)}else o+=c,a+=l;TC(c,s)}return o&&i.push(o),i.length>0?i.map(c=>c.trimEnd()):[""]}var WW=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function Ht(t){return/\s/.test(t)}function zt(t){return WW.test(t)}function UW(t,e,n){let i=[],s=n.getActiveCodes(),r=0,o=0,a=[];for(;o<t.length;){let c=bn(t,o);if(c)a.push({type:"ansi",value:c.code}),o+=c.length;else{let l=o;for(;l<t.length&&!bn(t,l);)l++;let d=t.slice(o,l);for(let u of Fi.segment(d))a.push({type:"grapheme",value:u.segment});o=l}}for(let c of a){if(c.type==="ansi"){s+=c.value,n.process(c.value);continue}let l=c.value;if(!l)continue;let d=j(l);if(r+d>e){let u=n.getLineEndReset();u&&(s+=u),i.push(s),s=n.getActiveCodes(),r=0}s+=l,r+=d}return s&&i.push(s),i.length>0?i:[""]}function Ss(t,e,n){let i=j(t),s=Math.max(0,e-i),r=" ".repeat(s),o=t+r;return n(o)}function X(t,e,n="...",i=!1){if(e<=0)return"";if(t.length===0)return i?" ".repeat(e):"";let s=j(n);if(s>=e){let h=j(t);if(h<=e)return i?t+" ".repeat(e-h):t;let f=IW(n,e);return f.width===0?i?" ".repeat(e):"":Og("",0,f.text,f.width,e,i)}if(Wg(t)){if(t.length<=e)return i?t+" ".repeat(e-t.length):t;let h=e-s;return Og(t.slice(0,h),h,n,s,e,i)}let r=e-s,o="",a="",c=0,l=0,d=!0,u=!1,p=!1,m=t.includes("\x1B"),g=t.includes(" ");if(!m&&!g){for(let{segment:h}of Fi.segment(t)){let f=or(h);if(d&&l+f<=r?(o+=h,l+=f):d=!1,c+=f,c>e){u=!0;break}}p=!u}else{let h=0;for(;h<t.length;){let f=bn(t,h);if(f){a+=f.code,h+=f.length;continue}if(t[h]===" "){if(d&&l+3<=r?(a&&(o+=a,a=""),o+=" ",l+=3):(d=!1,a=""),c+=3,c>e){u=!0;break}h++;continue}let x=h;for(;x<t.length&&t[x]!==" "&&!bn(t,x);)x++;for(let{segment:y}of Fi.segment(t.slice(h,x))){let w=or(y);if(d&&l+w<=r?(a&&(o+=a,a=""),o+=y,l+=w):(d=!1,a=""),c+=w,c>e){u=!0;break}}if(u)break;h=x}p=h>=t.length}return!u&&p?i?t+" ".repeat(Math.max(0,e-c)):t:Og(o,l,n,s,e,i)}function ta(t,e,n,i=!1){return Ug(t,e,n,i).text}function Ug(t,e,n,i=!1){if(n<=0)return{text:"",width:0};let s=e+n,r="",o=0,a=0,c=0,l="";for(;c<t.length;){let d=bn(t,c);if(d){a>=e&&a<s?r+=d.code:a<e&&(l+=d.code),c+=d.length;continue}let u=c;for(;u<t.length&&!bn(t,u);)u++;for(let{segment:p}of Fi.segment(t.slice(c,u))){let m=or(p),g=a>=e&&a<s,h=!i||a+m<=s;if(g&&h&&(l&&(r+=l,l=""),r+=p,o+=m),a+=m,a>=s)break}if(c=u,a>=s)break}return{text:r,width:o}}var Lg=new Xc;function kC(t,e,n,i,s=!1){let r="",o=0,a="",c=0,l=0,d=0,u="",p=!1,m=n+i;for(Lg.clear();d<t.length;){let g=bn(t,d);if(g){Lg.process(g.code),l<e?u+=g.code:l>=n&&l<m&&p&&(a+=g.code),d+=g.length;continue}let h=d;for(;h<t.length&&!bn(t,h);)h++;for(let{segment:f}of Fi.segment(t.slice(d,h))){let x=or(f);if(l<e?(u&&(r+=u,u=""),r+=f,o+=x):l>=n&&l<m&&(!s||l+x<=m)&&(p||(a+=Lg.getActiveCodes(),p=!0),a+=f,c+=x),l+=x,i<=0?l>=e:l>=m)break}if(d=h,i<=0?l>=e:l>=m)break}return{before:r,beforeWidth:o,after:a,afterWidth:c}}var ut=class{constructor(e=1,n=1,i){this.children=[];this.paddingX=e,this.paddingY=n,this.bgFn=i}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let n=this.children.indexOf(e);n!==-1&&(this.children.splice(n,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}invalidateCache(){this.cache=void 0}matchCache(e,n,i){let s=this.cache;return!!s&&s.width===e&&s.bgSample===i&&s.childLines.length===n.length&&s.childLines.every((r,o)=>r===n[o])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}render(e){if(this.children.length===0)return[];let n=Math.max(1,e-this.paddingX*2),i=" ".repeat(this.paddingX),s=[];for(let a of this.children){let c=a.render(n);for(let l of c)s.push(i+l)}if(s.length===0)return[];let r=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(e,s,r))return this.cache.lines;let o=[];for(let a=0;a<this.paddingY;a++)o.push(this.applyBg("",e));for(let a of s)o.push(this.applyBg(a,e));for(let a=0;a<this.paddingY;a++)o.push(this.applyBg("",e));return this.cache={childLines:s,width:e,bgSample:r,lines:o},o}applyBg(e,n){let i=j(e),s=Math.max(0,n-i),r=e+" ".repeat(s);return this.bgFn?Ss(r,n,this.bgFn):r}};var Di=!1;function el(t){Di=t}var ar={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:t=>`ctrl+${t}`,shift:t=>`shift+${t}`,alt:t=>`alt+${t}`,super:t=>`super+${t}`,ctrlShift:t=>`ctrl+shift+${t}`,shiftCtrl:t=>`shift+ctrl+${t}`,ctrlAlt:t=>`ctrl+alt+${t}`,altCtrl:t=>`alt+ctrl+${t}`,shiftAlt:t=>`shift+alt+${t}`,altShift:t=>`alt+shift+${t}`,ctrlSuper:t=>`ctrl+super+${t}`,superCtrl:t=>`super+ctrl+${t}`,shiftSuper:t=>`shift+super+${t}`,superShift:t=>`super+shift+${t}`,altSuper:t=>`alt+super+${t}`,superAlt:t=>`super+alt+${t}`,ctrlShiftAlt:t=>`ctrl+shift+alt+${t}`,ctrlShiftSuper:t=>`ctrl+shift+super+${t}`},RC=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),ee={shift:1,alt:2,ctrl:4,super:8},Zc=192,Oe={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},gt={up:-1,down:-2,right:-3,left:-4},je={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},FW=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,gt.left],[57418,gt.right],[57419,gt.up],[57420,gt.down],[57421,je.pageUp],[57422,je.pageDown],[57423,je.home],[57424,je.end],[57425,je.insert],[57426,je.delete]]);function Fg(t){return FW.get(t)??t}function _d(t,e){return(e&~Zc&ee.shift)!==0&&t>=65&&t<=90?t+32:t}var Pn={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},DW={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},$W={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var Vt=(t,e)=>e.includes(t),xn=(t,e,n)=>n===ee.shift?Vt(t,DW[e]):n===ee.ctrl?Vt(t,$W[e]):!1,Id="press";function Vn(t){return t.includes("\x1B[200~")?!1:!!(t.includes(":3u")||t.includes(":3~")||t.includes(":3A")||t.includes(":3B")||t.includes(":3C")||t.includes(":3D")||t.includes(":3H")||t.includes(":3F"))}function Rd(t){if(!t)return"press";let e=parseInt(t,10);return e===2?"repeat":e===3?"release":"press"}function BW(t){let e=t.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let r=parseInt(e[1],10),o=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,a=e[3]?parseInt(e[3],10):void 0,c=e[4]?parseInt(e[4],10):1,l=Rd(e[5]);return Id=l,{codepoint:r,shiftedKey:o,baseLayoutKey:a,modifier:c-1,eventType:l}}let n=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(n){let r=parseInt(n[1],10),o=Rd(n[2]),a={A:-1,B:-2,C:-3,D:-4};return Id=o,{codepoint:a[n[3]],modifier:r-1,eventType:o}}let i=t.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let r=parseInt(i[1],10),o=i[2]?parseInt(i[2],10):1,a=Rd(i[3]),l={2:je.insert,3:je.delete,5:je.pageUp,6:je.pageDown,7:je.home,8:je.end}[r];if(l!==void 0)return Id=a,{codepoint:l,modifier:o-1,eventType:a}}let s=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(s){let r=parseInt(s[1],10),o=Rd(s[2]),a=s[3]==="H"?je.home:je.end;return Id=o,{codepoint:a,modifier:r-1,eventType:o}}return null}function me(t,e,n){let i=BW(t);if(!i)return!1;let s=i.modifier&~Zc,r=n&~Zc;if(s!==r)return!1;let o=_d(Fg(i.codepoint),i.modifier),a=_d(Fg(e),n);if(o===a)return!0;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===e){let c=o,l=c>=97&&c<=122,d=RC.has(String.fromCharCode(c));if(!l&&!d)return!0}return!1}function Dg(t){let e=t.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let n=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:n-1}}function _n(t,e,n){let i=Dg(t);return i?i.codepoint===e&&i.modifier===n:!1}function NW(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function MC(t,e){return t==="\x7F"?e===0:t!=="\b"?!1:NW()?e===ee.ctrl:e===0}function jW(t){let e=t.toLowerCase(),n=e.charCodeAt(0);return n>=97&&n<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(n&31):e==="-"?"":null}function IC(t){return t>="0"&&t<="9"}function Pd(t,e,n){if(n===0)return!1;let i=Dg(t);return!i||i.modifier!==n?!1:_d(i.codepoint,i.modifier)===_d(e,n)}function qW(t){let e=t.toLowerCase().split("+"),n=e[e.length-1];return n?{key:n,ctrl:e.includes("ctrl"),shift:e.includes("shift"),alt:e.includes("alt"),super:e.includes("super")}:null}function Ee(t,e){let n=qW(e);if(!n)return!1;let{key:i,ctrl:s,shift:r,alt:o,super:a}=n,c=0;switch(r&&(c|=ee.shift),o&&(c|=ee.alt),s&&(c|=ee.ctrl),a&&(c|=ee.super),i){case"escape":case"esc":return c!==0?!1:t==="\x1B"||me(t,Oe.escape,0)||_n(t,Oe.escape,0);case"space":return!Di&&(c===ee.ctrl&&t==="\0"||c===ee.alt&&t==="\x1B ")?!0:c===0?t===" "||me(t,Oe.space,0)||_n(t,Oe.space,0):me(t,Oe.space,c)||_n(t,Oe.space,c);case"tab":return c===ee.shift?t==="\x1B[Z"||me(t,Oe.tab,ee.shift)||_n(t,Oe.tab,ee.shift):c===0?t===" "||me(t,Oe.tab,0):me(t,Oe.tab,c)||_n(t,Oe.tab,c);case"enter":case"return":return c===ee.shift?me(t,Oe.enter,ee.shift)||me(t,Oe.kpEnter,ee.shift)||_n(t,Oe.enter,ee.shift)?!0:Di?t==="\x1B\r"||t===`
|
|
34
|
+
`:!1:c===ee.alt?me(t,Oe.enter,ee.alt)||me(t,Oe.kpEnter,ee.alt)||_n(t,Oe.enter,ee.alt)?!0:Di?!1:t==="\x1B\r":c===0?t==="\r"||!Di&&t===`
|
|
35
|
+
`||t==="\x1BOM"||me(t,Oe.enter,0)||me(t,Oe.kpEnter,0):me(t,Oe.enter,c)||me(t,Oe.kpEnter,c)||_n(t,Oe.enter,c);case"backspace":return c===ee.alt?t==="\x1B\x7F"||t==="\x1B\b"?!0:me(t,Oe.backspace,ee.alt)||_n(t,Oe.backspace,ee.alt):c===ee.ctrl?MC(t,ee.ctrl)?!0:me(t,Oe.backspace,ee.ctrl)||_n(t,Oe.backspace,ee.ctrl):c===0?MC(t,0)||me(t,Oe.backspace,0)||_n(t,Oe.backspace,0):me(t,Oe.backspace,c)||_n(t,Oe.backspace,c);case"insert":return c===0?Vt(t,Pn.insert)||me(t,je.insert,0):xn(t,"insert",c)?!0:me(t,je.insert,c);case"delete":return c===0?Vt(t,Pn.delete)||me(t,je.delete,0):xn(t,"delete",c)?!0:me(t,je.delete,c);case"clear":return c===0?Vt(t,Pn.clear):xn(t,"clear",c);case"home":return c===0?Vt(t,Pn.home)||me(t,je.home,0):xn(t,"home",c)?!0:me(t,je.home,c);case"end":return c===0?Vt(t,Pn.end)||me(t,je.end,0):xn(t,"end",c)?!0:me(t,je.end,c);case"pageup":return c===0?Vt(t,Pn.pageUp)||me(t,je.pageUp,0):xn(t,"pageUp",c)?!0:me(t,je.pageUp,c);case"pagedown":return c===0?Vt(t,Pn.pageDown)||me(t,je.pageDown,0):xn(t,"pageDown",c)?!0:me(t,je.pageDown,c);case"up":return c===ee.alt?t==="\x1Bp"||me(t,gt.up,ee.alt):c===0?Vt(t,Pn.up)||me(t,gt.up,0):xn(t,"up",c)?!0:me(t,gt.up,c);case"down":return c===ee.alt?t==="\x1Bn"||me(t,gt.down,ee.alt):c===0?Vt(t,Pn.down)||me(t,gt.down,0):xn(t,"down",c)?!0:me(t,gt.down,c);case"left":return c===ee.alt?t==="\x1B[1;3D"||!Di&&t==="\x1BB"||t==="\x1Bb"||me(t,gt.left,ee.alt):c===ee.ctrl?t==="\x1B[1;5D"||xn(t,"left",ee.ctrl)||me(t,gt.left,ee.ctrl):c===0?Vt(t,Pn.left)||me(t,gt.left,0):xn(t,"left",c)?!0:me(t,gt.left,c);case"right":return c===ee.alt?t==="\x1B[1;3C"||!Di&&t==="\x1BF"||t==="\x1Bf"||me(t,gt.right,ee.alt):c===ee.ctrl?t==="\x1B[1;5C"||xn(t,"right",ee.ctrl)||me(t,gt.right,ee.ctrl):c===0?Vt(t,Pn.right)||me(t,gt.right,0):xn(t,"right",c)?!0:me(t,gt.right,c);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return c!==0?!1:Vt(t,Pn[i])}if(i.length===1&&(i>="a"&&i<="z"||IC(i)||RC.has(i))){let l=i.charCodeAt(0),d=jW(i),u=i>="a"&&i<="z",p=IC(i);return c===ee.ctrl+ee.alt&&!Di&&d&&t===`\x1B${d}`||c===ee.alt&&!Di&&(u||p)&&t===`\x1B${i}`?!0:c===ee.ctrl?d&&t===d?!0:me(t,l,ee.ctrl)||Pd(t,l,ee.ctrl):c===ee.shift+ee.ctrl?me(t,l,ee.shift+ee.ctrl)||Pd(t,l,ee.shift+ee.ctrl):c===ee.shift?u&&t===i.toUpperCase()?!0:me(t,l,ee.shift)||Pd(t,l,ee.shift):c!==0?me(t,l,c)||Pd(t,l,c):t===i||me(t,l,0)}return!1}var GW=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KW=ee.shift|Zc;function Ed(t){let e=t.match(GW);if(!e)return;let n=Number.parseInt(e[1]??"",10);if(!Number.isFinite(n))return;let i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,s=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(s)?s-1:0;if((r&~KW)!==0||r&(ee.alt|ee.ctrl))return;let o=n;if(r&ee.shift&&typeof i=="number"&&(o=i),o=Fg(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function HW(t){let e=Dg(t);if(!(!e||(e.modifier&~Zc&~ee.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function $g(t){return Ed(t)??HW(t)}var ia={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:"pageUp",description:"Page up"},"tui.editor.pageDown":{defaultKeys:"pageDown",description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:"shift+enter",description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"}};function Bg(t){if(t===void 0)return[];let e=Array.isArray(t)?t:[t],n=new Set,i=[];for(let s of e)n.has(s)||(n.add(s),i.push(s));return i}var na=class{constructor(e,n={}){this.keysById=new Map;this.conflicts=[];this.definitions=e,this.userBindings=n,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[n,i]of Object.entries(this.userBindings))if(n in this.definitions)for(let s of Bg(i)){let r=e.get(s)??new Set;r.add(n),e.set(s,r)}for(let[n,i]of e)i.size>1&&this.conflicts.push({key:n,keybindings:[...i]});for(let[n,i]of Object.entries(this.definitions)){let s=this.userBindings[n],r=Bg(s===void 0?i.defaultKeys:s);this.keysById.set(n,r)}}matches(e,n){let i=this.keysById.get(n)??[];for(let s of i)if(Ee(e,s))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let n of Object.keys(this.definitions)){let i=this.keysById.get(n)??[];e[n]=i.length===1?i[0]:[...i]}return e}},Ad=null;function tl(t){Ad=t}function ve(){return Ad||(Ad=new na(ia)),Ad}var A=class{constructor(e="",n=1,i=1,s){this.text=e,this.paddingX=n,this.paddingY=i,this.customBgFn=s}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let u=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u}let n=this.text.replace(/\t/g," "),i=Math.max(1,e-this.paddingX*2),s=zn(n,i),r=" ".repeat(this.paddingX),o=" ".repeat(this.paddingX),a=[];for(let u of s){let p=r+u+o;if(this.customBgFn)a.push(Ss(p,e,this.customBgFn));else{let m=j(p),g=Math.max(0,e-m);a.push(p+" ".repeat(g))}}let c=" ".repeat(e),l=[];for(let u=0;u<this.paddingY;u++){let p=this.customBgFn?Ss(c,e,this.customBgFn):c;l.push(p)}let d=[...l,...a,...l];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d.length>0?d:[""]}};var PC=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_C=80,Jt=class extends A{constructor(n,i,s,r="Loading...",o){super("",1,0);this.frames=[...PC];this.intervalMs=_C;this.currentFrame=0;this.intervalId=null;this.ui=null;this.renderIndicatorVerbatim=!1;this.message="Loading...";this.ui=n,this.spinnerColorFn=i,this.messageColorFn=s,this.message=r,this.setIndicator(o)}render(n){return["",...super.render(n)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(n){this.message=n,this.updateDisplay()}setIndicator(n){this.renderIndicatorVerbatim=n!==void 0,this.frames=n?.frames!==void 0?[...n.frames]:[...PC],this.intervalMs=n?.intervalMs&&n.intervalMs>0?n.intervalMs:_C,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}updateDisplay(){let n=this.frames[this.currentFrame]??"",i=this.renderIndicatorVerbatim?n:this.spinnerColorFn(n),s=n.length>0?`${i} `:"";this.setText(`${s}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var nl=class extends Jt{constructor(){super(...arguments);this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(n){ve().matches(n,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var sa=class{constructor(){this.ring=[]}push(e,n){if(e)if(n.accumulate&&this.ring.length>0){let i=this.ring.pop();this.ring.push(n.prepend?e+i:i+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};import*as Cs from"node:fs";import*as Vg from"node:os";import*as oa from"node:path";import{performance as Hg}from"node:perf_hooks";var Ng=null,OC={widthPx:9,heightPx:18};function Od(){return OC}function jg(t){OC=t}function LC(){let t=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",i=n==="truecolor"||n==="24bit";return!!process.env.TMUX||e.startsWith("tmux")||e.startsWith("screen")?{images:null,trueColor:i,hyperlinks:!1}:process.env.KITTY_WINDOW_ID||t==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:t==="ghostty"||e.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||t==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||t==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:t==="vscode"?{images:null,trueColor:!0,hyperlinks:!0}:t==="alacritty"?{images:null,trueColor:!0,hyperlinks:!0}:{images:null,trueColor:i||!!process.env.WT_SESSION,hyperlinks:!1}}function dt(){return Ng||(Ng=LC()),Ng}var EC="\x1B_G",AC="\x1B]1337;File=";function cr(t){return t.startsWith(EC)||t.startsWith(AC)?!0:t.includes(EC)||t.includes(AC)}function qg(){return Math.floor(Math.random()*4294967294)+1}function WC(t,e={}){let i=["a=T","f=100","q=2"];if(e.moveCursor===!1&&i.push("C=1"),e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),t.length<=4096)return`\x1B_G${i.join(",")};${t}\x1B\\`;let s=[],r=0,o=!0;for(;r<t.length;){let a=t.slice(r,r+4096),c=r+4096>=t.length;o?(s.push(`\x1B_G${i.join(",")},m=1;${a}\x1B\\`),o=!1):c?s.push(`\x1B_Gm=0;${a}\x1B\\`):s.push(`\x1B_Gm=1;${a}\x1B\\`),r+=4096}return s.join("")}function Gg(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function UC(t,e={}){let n=[`inline=${e.inline!==!1?1:0}`];if(e.width!==void 0&&n.push(`width=${e.width}`),e.height!==void 0&&n.push(`height=${e.height}`),e.name){let i=Buffer.from(e.name).toString("base64");n.push(`name=${i}`)}return e.preserveAspectRatio===!1&&n.push("preserveAspectRatio=0"),`\x1B]1337;File=${n.join(";")}:${t}\x07`}function zW(t,e,n,i={widthPx:9,heightPx:18}){let s=Math.max(1,Math.floor(e)),r=n===void 0?void 0:Math.max(1,Math.floor(n)),o=Math.max(1,t.widthPx),a=Math.max(1,t.heightPx),c=s*i.widthPx/o,l=r===void 0?c:r*i.heightPx/a,d=Math.min(c,l),u=o*d,p=a*d,m=Math.ceil(u/i.widthPx),g=Math.ceil(p/i.heightPx);return{columns:Math.max(1,Math.min(s,m)),rows:Math.max(1,r===void 0?g:Math.min(r,g))}}function FC(t){try{let e=Buffer.from(t,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let n=e.readUInt32BE(16),i=e.readUInt32BE(20);return{widthPx:n,heightPx:i}}catch{return null}}function DC(t){try{let e=Buffer.from(t,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let n=2;for(;n<e.length-9;){if(e[n]!==255){n++;continue}let i=e[n+1];if(i>=192&&i<=194){let r=e.readUInt16BE(n+5);return{widthPx:e.readUInt16BE(n+7),heightPx:r}}if(n+3>=e.length)return null;let s=e.readUInt16BE(n+2);if(s<2)return null;n+=2+s}return null}catch{return null}}function $C(t){try{let e=Buffer.from(t,"base64");if(e.length<10)return null;let n=e.slice(0,6).toString("ascii");if(n!=="GIF87a"&&n!=="GIF89a")return null;let i=e.readUInt16LE(6),s=e.readUInt16LE(8);return{widthPx:i,heightPx:s}}catch{return null}}function BC(t){try{let e=Buffer.from(t,"base64");if(e.length<30)return null;let n=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if(n!=="RIFF"||i!=="WEBP")return null;let s=e.slice(12,16).toString("ascii");if(s==="VP8 "){if(e.length<30)return null;let r=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:r,heightPx:o}}else if(s==="VP8L"){if(e.length<25)return null;let r=e.readUInt32LE(21),o=(r&16383)+1,a=(r>>14&16383)+1;return{widthPx:o,heightPx:a}}else if(s==="VP8X"){if(e.length<30)return null;let r=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:r,heightPx:o}}return null}catch{return null}}function il(t,e){return e==="image/png"?FC(t):e==="image/jpeg"?DC(t):e==="image/gif"?$C(t):e==="image/webp"?BC(t):null}function Kg(t,e,n={}){let i=dt();if(!i.images)return null;let s=n.maxWidthCells??80,r=zW(e,s,n.maxHeightCells,Od());return i.images==="kitty"?{sequence:WC(t,{columns:r.columns,rows:r.rows,imageId:n.imageId,moveCursor:n.moveCursor}),rows:r.rows,imageId:n.imageId}:i.images==="iterm2"?{sequence:UC(t,{width:r.columns,height:"auto",preserveAspectRatio:n.preserveAspectRatio??!0}),rows:r.rows}:null}function sl(t,e){return`\x1B]8;;${e}\x1B\\${t}\x1B]8;;\x1B\\`}function ra(t,e,n){let i=[];return n&&i.push(n),i.push(`[${t}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}var NC="\x1B_G";function zg(t){let e=t.indexOf(NC);if(e===-1)return[];let n=e+NC.length,i=t.indexOf(";",n);if(i===-1)return[];let s=t.slice(n,i);for(let r of s.split(",")){let[o,a]=r.split("=",2);if(o!=="i"||a===void 0)continue;let c=Number(a);if(Number.isInteger(c)&&c>0&&c<=4294967295)return[c]}return[]}function Jg(t){return t!==null&&"focused"in t}var lr="\x1B_pi:c\x07";function jC(t,e){if(t===void 0)return;if(typeof t=="number")return t;let n=t.match(/^(\d+(?:\.\d+)?)%$/);if(n)return Math.floor(e*parseFloat(n[1])/100)}function VW(){return!!process.env.TERMUX_VERSION}var K=class{constructor(){this.children=[]}addChild(e){this.children.push(e)}removeChild(e){let n=this.children.indexOf(e);n!==-1&&this.children.splice(n,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}render(e){let n=[];for(let i of this.children){let s=i.render(e);for(let r of s)n.push(r)}return n}},Ts=class t extends K{constructor(n,i){super();this.previousLines=[];this.previousKittyImageIds=new Set;this.previousWidth=0;this.previousHeight=0;this.focusedComponent=null;this.inputListeners=new Set;this.renderRequested=!1;this.lastRenderAt=0;this.cursorRow=0;this.hardwareCursorRow=0;this.showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1";this.clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1";this.maxLinesRendered=0;this.previousViewportTop=0;this.fullRedrawCount=0;this.stopped=!1;this.focusOrderCounter=0;this.overlayStack=[];this.terminal=n,i!==void 0&&(this.showHardwareCursor=i)}static{this.MIN_RENDER_INTERVAL_MS=16}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(n){this.showHardwareCursor!==n&&(this.showHardwareCursor=n,n||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(n){this.clearOnShrink=n}setFocus(n){Jg(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=n,Jg(n)&&(n.focused=!0)}showOverlay(n,i){let s={component:n,options:i,preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(s),!i?.nonCapturing&&this.isOverlayVisible(s)&&this.setFocus(n),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let r=this.overlayStack.indexOf(s);if(r!==-1){if(this.overlayStack.splice(r,1),this.focusedComponent===n){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??s.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:r=>{if(s.hidden!==r){if(s.hidden=r,r){if(this.focusedComponent===n){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??s.preFocus)}}else!i?.nonCapturing&&this.isOverlayVisible(s)&&(s.focusOrder=++this.focusOrderCounter,this.setFocus(n));this.requestRender()}},isHidden:()=>s.hidden,focus:()=>{!this.overlayStack.includes(s)||!this.isOverlayVisible(s)||(this.focusedComponent!==n&&this.setFocus(n),s.focusOrder=++this.focusOrderCounter,this.requestRender())},unfocus:()=>{if(this.focusedComponent!==n)return;let r=this.getTopmostVisibleOverlay();this.setFocus(r&&r!==s?r.component:s.preFocus),this.requestRender()},isFocused:()=>this.focusedComponent===n}}hideOverlay(){let n=this.overlayStack.pop();if(n){if(this.focusedComponent===n.component){let i=this.getTopmostVisibleOverlay();this.setFocus(i?.component??n.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(n=>this.isOverlayVisible(n))}isOverlayVisible(n){return n.hidden?!1:n.options?.visible?n.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){for(let n=this.overlayStack.length-1;n>=0;n--)if(!this.overlayStack[n].options?.nonCapturing&&this.isOverlayVisible(this.overlayStack[n]))return this.overlayStack[n]}invalidate(){super.invalidate();for(let n of this.overlayStack)n.component.invalidate?.()}start(){this.stopped=!1,this.terminal.start(n=>this.handleInput(n),()=>this.requestRender()),this.terminal.hideCursor(),this.queryCellSize(),this.requestRender()}addInputListener(n){return this.inputListeners.add(n),()=>{this.inputListeners.delete(n)}}removeInputListener(n){this.inputListeners.delete(n)}queryCellSize(){dt().images&&this.terminal.write("\x1B[16t")}stop(){if(this.stopped=!0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.previousLines.length>0){let i=this.previousLines.length-this.hardwareCursorRow;i>0?this.terminal.write(`\x1B[${i}B`):i<0&&this.terminal.write(`\x1B[${-i}A`),this.terminal.write(`\r
|
|
36
|
+
`)}this.terminal.showCursor(),this.terminal.stop()}requestRender(n=!1){if(n){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.renderRequested=!0,process.nextTick(()=>{this.stopped||!this.renderRequested||(this.renderRequested=!1,this.lastRenderAt=Hg.now(),this.doRender())});return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let n=Hg.now()-this.lastRenderAt,i=Math.max(0,t.MIN_RENDER_INTERVAL_MS-n);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=Hg.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},i)}handleInput(n){if(this.inputListeners.size>0){let s=n;for(let r of this.inputListeners){let o=r(s);if(o?.consume)return;o?.data!==void 0&&(s=o.data)}if(s.length===0)return;n=s}if(this.consumeCellSizeResponse(n))return;if(Ee(n,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let i=this.overlayStack.find(s=>s.component===this.focusedComponent);if(i&&!this.isOverlayVisible(i)){let s=this.getTopmostVisibleOverlay();s?this.setFocus(s.component):this.setFocus(i.preFocus)}if(this.focusedComponent?.handleInput){if(Vn(n)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(n),this.requestRender()}}consumeCellSizeResponse(n){let i=n.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!i)return!1;let s=parseInt(i[1],10),r=parseInt(i[2],10);return s<=0||r<=0||(jg({widthPx:r,heightPx:s}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(n,i,s,r){let o=n??{},a=typeof o.margin=="number"?{top:o.margin,right:o.margin,bottom:o.margin,left:o.margin}:o.margin??{},c=Math.max(0,a.top??0),l=Math.max(0,a.right??0),d=Math.max(0,a.bottom??0),u=Math.max(0,a.left??0),p=Math.max(1,s-u-l),m=Math.max(1,r-c-d),g=jC(o.width,s)??Math.min(80,p);o.minWidth!==void 0&&(g=Math.max(g,o.minWidth)),g=Math.max(1,Math.min(g,p));let h=jC(o.maxHeight,r);h!==void 0&&(h=Math.max(1,Math.min(h,m)));let f=h!==void 0?Math.min(i,h):i,x,y;if(o.row!==void 0)if(typeof o.row=="string"){let w=o.row.match(/^(\d+(?:\.\d+)?)%$/);if(w){let P=Math.max(0,m-f),_=parseFloat(w[1])/100;x=c+Math.floor(P*_)}else x=this.resolveAnchorRow("center",f,m,c)}else x=o.row;else{let w=o.anchor??"center";x=this.resolveAnchorRow(w,f,m,c)}if(o.col!==void 0)if(typeof o.col=="string"){let w=o.col.match(/^(\d+(?:\.\d+)?)%$/);if(w){let P=Math.max(0,p-g),_=parseFloat(w[1])/100;y=u+Math.floor(P*_)}else y=this.resolveAnchorCol("center",g,p,u)}else y=o.col;else{let w=o.anchor??"center";y=this.resolveAnchorCol(w,g,p,u)}return o.offsetY!==void 0&&(x+=o.offsetY),o.offsetX!==void 0&&(y+=o.offsetX),x=Math.max(c,Math.min(x,r-d-f)),y=Math.max(u,Math.min(y,s-l-g)),{width:g,row:x,col:y,maxHeight:h}}resolveAnchorRow(n,i,s,r){switch(n){case"top-left":case"top-center":case"top-right":return r;case"bottom-left":case"bottom-center":case"bottom-right":return r+s-i;case"left-center":case"center":case"right-center":return r+Math.floor((s-i)/2)}}resolveAnchorCol(n,i,s,r){switch(n){case"top-left":case"left-center":case"bottom-left":return r;case"top-right":case"right-center":case"bottom-right":return r+s-i;case"top-center":case"center":case"bottom-center":return r+Math.floor((s-i)/2)}}compositeOverlays(n,i,s){if(this.overlayStack.length===0)return n;let r=[...n],o=[],a=r.length,c=this.overlayStack.filter(u=>this.isOverlayVisible(u));c.sort((u,p)=>u.focusOrder-p.focusOrder);for(let u of c){let{component:p,options:m}=u,{width:g,maxHeight:h}=this.resolveOverlayLayout(m,0,i,s),f=p.render(g);h!==void 0&&f.length>h&&(f=f.slice(0,h));let{row:x,col:y}=this.resolveOverlayLayout(m,f.length,i,s);o.push({overlayLines:f,row:x,col:y,w:g}),a=Math.max(a,x+f.length)}let l=Math.max(r.length,s,a);for(;r.length<l;)r.push("");let d=Math.max(0,l-s);for(let{overlayLines:u,row:p,col:m,w:g}of o)for(let h=0;h<u.length;h++){let f=d+p+h;if(f>=0&&f<r.length){let x=j(u[h])>g?ta(u[h],0,g,!0):u[h];r[f]=this.compositeLineAt(r[f],x,m,g,i)}}return r}static{this.SEGMENT_RESET="\x1B[0m\x1B]8;;\x07"}applyLineResets(n){let i=t.SEGMENT_RESET;for(let s=0;s<n.length;s++){let r=n[s];cr(r)||(n[s]=CC(r)+i)}return n}collectKittyImageIds(n){let i=new Set;for(let s of n)for(let r of zg(s))i.add(r);return i}deleteKittyImages(n){let i="";for(let s of n)i+=Gg(s);return i}expandLastChangedForKittyImages(n,i){let s=i;for(let r=n;r<this.previousLines.length;r++)zg(this.previousLines[r]).length>0&&(s=Math.max(s,r));return s}deleteChangedKittyImages(n,i){if(n<0||i<n)return"";let s=new Set,r=Math.min(i,this.previousLines.length-1);for(let o=n;o<=r;o++)for(let a of zg(this.previousLines[o]??""))s.add(a);return this.deleteKittyImages(s)}compositeLineAt(n,i,s,r,o){if(cr(n))return n;let a=s+r,c=kC(n,s,a,o-a,!0),l=Ug(i,0,r,!0),d=Math.max(0,s-c.beforeWidth),u=Math.max(0,r-l.width),p=Math.max(s,c.beforeWidth),m=Math.max(r,l.width),g=Math.max(0,o-p-m),h=Math.max(0,g-c.afterWidth),f=t.SEGMENT_RESET,x=c.before+" ".repeat(d)+f+l.text+" ".repeat(u)+f+c.after+" ".repeat(h);return j(x)<=o?x:ta(x,0,o,!0)}extractCursorPosition(n,i){let s=Math.max(0,n.length-i);for(let r=n.length-1;r>=s;r--){let o=n[r],a=o.indexOf(lr);if(a!==-1){let c=o.slice(0,a),l=j(c);return n[r]=o.slice(0,a)+o.slice(a+lr.length),{row:r,col:l}}}return null}doRender(){if(this.stopped)return;let n=this.terminal.columns,i=this.terminal.rows,s=this.previousWidth!==0&&this.previousWidth!==n,r=this.previousHeight!==0&&this.previousHeight!==i,o=this.previousHeight>0?this.previousViewportTop+this.previousHeight:i,a=r?Math.max(0,o-i):this.previousViewportTop,c=a,l=this.hardwareCursorRow,d=I=>{let O=l-a;return I-c-O},u=this.render(n);this.overlayStack.length>0&&(u=this.compositeOverlays(u,n,i));let p=this.extractCursorPosition(u,i);u=this.applyLineResets(u);let m=I=>{this.fullRedrawCount+=1;let O="\x1B[?2026h";I&&(O+=this.deleteKittyImages(this.previousKittyImageIds),O+="\x1B[2J\x1B[H\x1B[3J");for(let N=0;N<u.length;N++)N>0&&(O+=`\r
|
|
37
37
|
`),O+=u[N];O+="\x1B[?2026l",this.terminal.write(O),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=this.cursorRow,I?this.maxLinesRendered=u.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length);let F=Math.max(i,u.length);this.previousViewportTop=Math.max(0,F-i),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=n,this.previousHeight=i},g=process.env.PI_DEBUG_REDRAW==="1",h=I=>{if(!g)return;let O=oa.join(Vg.homedir(),".pi","agent","pi-debug.log"),F=`[${new Date().toISOString()}] fullRender: ${I} (prev=${this.previousLines.length}, new=${u.length}, height=${i})
|
|
38
38
|
`;Cs.appendFileSync(O,F)};if(this.previousLines.length===0&&!s&&!r){h("first render"),m(!1);return}if(s){h(`terminal width changed (${this.previousWidth} -> ${n})`),m(!0);return}if(r&&!VW()){h(`terminal height changed (${this.previousHeight} -> ${i})`),m(!0);return}if(this.clearOnShrink&&u.length<this.maxLinesRendered&&this.overlayStack.length===0){h(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),m(!0);return}let f=-1,x=-1,y=Math.max(u.length,this.previousLines.length);for(let I=0;I<y;I++){let O=I<this.previousLines.length?this.previousLines[I]:"",F=I<u.length?u[I]:"";O!==F&&(f===-1&&(f=I),x=I)}let w=u.length>this.previousLines.length;w&&(f===-1&&(f=this.previousLines.length),x=u.length-1),f!==-1&&(x=this.expandLastChangedForKittyImages(f,x));let P=w&&f===this.previousLines.length&&f>0;if(f===-1){this.positionHardwareCursor(p,u.length),this.previousViewportTop=a,this.previousHeight=i;return}if(f>=u.length){if(this.previousLines.length>u.length){let I="\x1B[?2026h";I+=this.deleteChangedKittyImages(f,x);let O=Math.max(0,u.length-1);if(O<a){h(`deleted lines moved viewport up (${O} < ${a})`),m(!0);return}let F=d(O);F>0?I+=`\x1B[${F}B`:F<0&&(I+=`\x1B[${-F}A`),I+="\r";let N=this.previousLines.length-u.length;if(N>i){h(`extraLines > height (${N} > ${i})`),m(!0);return}N>0&&(I+="\x1B[1B");for(let H=0;H<N;H++)I+="\r\x1B[2K",H<N-1&&(I+="\x1B[1B");N>0&&(I+=`\x1B[${N}A`),I+="\x1B[?2026l",this.terminal.write(I),this.cursorRow=O,this.hardwareCursorRow=O}this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=n,this.previousHeight=i,this.previousViewportTop=a;return}if(f<a){h(`firstChanged < viewportTop (${f} < ${a})`),m(!0);return}let _="\x1B[?2026h";_+=this.deleteChangedKittyImages(f,x);let R=a+i-1,L=P?f-1:f;if(L>R){let I=Math.max(0,Math.min(i-1,l-a)),O=i-1-I;O>0&&(_+=`\x1B[${O}B`);let F=L-R;_+=`\r
|
|
39
39
|
`.repeat(F),a+=F,c+=F,l=L}let E=d(L);E>0?_+=`\x1B[${E}B`:E<0&&(_+=`\x1B[${-E}A`),_+=P?`\r
|
|
@@ -43,15 +43,15 @@ ${o}`),i.push({type:"error",reason:s.stopReason,error:s}),i.end()}})(),i},k9=(t,
|
|
|
43
43
|
`);throw new Error(G)}_+=O}let M=W;if(this.previousLines.length>u.length){if(W<u.length-1){let O=u.length-1-W;_+=`\x1B[${O}B`,M=u.length-1}let I=this.previousLines.length-u.length;for(let O=u.length;O<this.previousLines.length;O++)_+=`\r
|
|
44
44
|
\x1B[2K`;_+=`\x1B[${I}A`}if(_+="\x1B[?2026l",process.env.PI_TUI_DEBUG==="1"){let I="/tmp/tui";Cs.mkdirSync(I,{recursive:!0});let O=oa.join(I,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),F=[`firstChanged: ${f}`,`viewportTop: ${c}`,`cursorRow: ${this.cursorRow}`,`height: ${i}`,`lineDiff: ${E}`,`hardwareCursorRow: ${l}`,`renderEnd: ${W}`,`finalCursorRow: ${M}`,`cursorPos: ${JSON.stringify(p)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(_)].join(`
|
|
45
45
|
`);Cs.writeFileSync(O,F)}this.terminal.write(_),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=M,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(a,M-i+1),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=n,this.previousHeight=i}positionHardwareCursor(n,i){if(!n||i<=0){this.terminal.hideCursor();return}let s=Math.max(0,Math.min(n.row,i-1)),r=Math.max(0,n.col),o=s-this.hardwareCursorRow,a="";o>0?a+=`\x1B[${o}B`:o<0&&(a+=`\x1B[${-o}A`),a+=`\x1B[${r+1}G`,a&&this.terminal.write(a),this.hardwareCursorRow=s,this.showHardwareCursor?this.terminal.showCursor():this.terminal.hideCursor()}};var aa=class{constructor(){this.stack=[]}push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var qC=32,GC=2,JW=10,QW=t=>t.replace(/[\r\n]+/g," ").trim(),YW=(t,e,n)=>Math.max(e,Math.min(t,n)),Qt=class{constructor(e,n,i,s={}){this.items=[];this.filteredItems=[];this.selectedIndex=0;this.maxVisible=5;this.items=e,this.filteredItems=e,this.maxVisible=n,this.theme=i,this.layout=s}setFilter(e){this.filteredItems=this.items.filter(n=>n.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let n=[];if(this.filteredItems.length===0)return n.push(this.theme.noMatch(" No matching commands")),n;let i=this.getPrimaryColumnWidth(),s=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),r=Math.min(s+this.maxVisible,this.filteredItems.length);for(let o=s;o<r;o++){let a=this.filteredItems[o];if(!a)continue;let c=o===this.selectedIndex,l=a.description?QW(a.description):void 0;n.push(this.renderItem(a,c,e,l,i))}if(s>0||r<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;n.push(this.theme.scrollInfo(X(o,e-2,"")))}return n}handleInput(e){let n=ve();if(n.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(n.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(n.matches(e,"tui.select.confirm")){let i=this.filteredItems[this.selectedIndex];i&&this.onSelect&&this.onSelect(i)}else n.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}renderItem(e,n,i,s,r){let o=n?"\u2192 ":" ",a=j(o);if(s&&i>40){let d=Math.max(1,Math.min(r,i-a-4)),u=Math.max(1,d-GC),p=this.truncatePrimary(e,n,u,d),m=j(p),g=" ".repeat(Math.max(1,d-m)),h=a+m+g.length,f=i-h-2;if(f>JW){let x=X(s,f,"");if(n)return this.theme.selectedText(`${o}${p}${g}${x}`);let y=this.theme.description(g+x);return o+p+y}}let c=i-a-2,l=this.truncatePrimary(e,n,c,c);return n?this.theme.selectedText(`${o}${l}`):o+l}getPrimaryColumnWidth(){let{min:e,max:n}=this.getPrimaryColumnBounds(),i=this.filteredItems.reduce((s,r)=>Math.max(s,j(this.getDisplayValue(r))+GC),0);return YW(i,e,n)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??qC,n=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??qC;return{min:Math.max(1,Math.min(e,n)),max:Math.max(1,Math.max(e,n))}}truncatePrimary(e,n,i,s){let r=this.getDisplayValue(e),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:r,maxWidth:i,columnWidth:s,item:e,isSelected:n}):X(r,i,"");return X(o,i,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var Ld=Md(),XW=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,ZW=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function li(t){return t.length>=10&&ZW.test(t)}function e5(t,e){if(e.size===0||!t.includes("[paste #"))return Ld.segment(t);let n=[];for(let o of t.matchAll(XW)){let a=Number.parseInt(o[1],10);e.has(a)&&n.push({start:o.index,end:o.index+o[0].length})}if(n.length===0)return Ld.segment(t);let i=Ld.segment(t),s=[],r=0;for(let o of i){for(;r<n.length&&n[r].end<=o.index;)r++;let a=r<n.length?n[r]:null;if(a&&o.index>=a.start&&o.index<a.end){if(o.index===a.start){let c=t.slice(a.start,a.end);s.push({segment:c,index:a.start,input:t})}}else s.push(o)}return s}function Qg(t,e,n){if(!t||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(j(t)<=e)return[{text:t,startIndex:0,endIndex:t.length}];let s=[],r=n??[...Ld.segment(t)],o=0,a=0,c=-1,l=0;for(let d=0;d<r.length;d++){let u=r[d],p=u.segment,m=j(p),g=u.index,h=!li(p)&&Ht(p);if(o+m>e&&(c>=0&&o-l+m<=e?(s.push({text:t.slice(a,c),startIndex:a,endIndex:c}),a=c,o-=l):a<g&&(s.push({text:t.slice(a,g),startIndex:a,endIndex:g}),a=g,o=0),c=-1),m>e){let x=Qg(p,e);for(let w=0;w<x.length-1;w++){let P=x[w];s.push({text:P.text,startIndex:g+P.startIndex,endIndex:g+P.endIndex})}let y=x[x.length-1];a=g+y.startIndex,o=j(y.text),c=-1;continue}o+=m;let f=r[d+1];h&&f&&(li(f.segment)||!Ht(f.segment))&&(c=f.index,l=o)}return s.push({text:t.slice(a),startIndex:a,endIndex:t.length}),s}var t5={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},n5=20,ur=class{constructor(e,n,i={}){this.state={lines:[""],cursorLine:0,cursorCol:0};this.focused=!1;this.paddingX=0;this.lastWidth=80;this.scrollOffset=0;this.autocompleteState=null;this.autocompletePrefix="";this.autocompleteMaxVisible=5;this.autocompleteRequestTask=Promise.resolve();this.autocompleteStartToken=0;this.autocompleteRequestId=0;this.pastes=new Map;this.pasteCounter=0;this.pasteBuffer="";this.isInPaste=!1;this.history=[];this.historyIndex=-1;this.killRing=new sa;this.lastAction=null;this.jumpMode=null;this.preferredVisualCol=null;this.snappedFromCursorCol=null;this.undoStack=new aa;this.disableSubmit=!1;this.tui=e,this.theme=n,this.borderColor=n.borderColor;let s=i.paddingX??0;this.paddingX=Number.isFinite(s)?Math.max(0,Math.floor(s)):0;let r=i.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(r)?Math.max(3,Math.min(20,Math.floor(r))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e){return e5(e,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let n=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==n&&(this.paddingX=n,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let n=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==n&&(this.autocompleteMaxVisible=n,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e}addToHistory(e){let n=e.trim();n&&(this.history.length>0&&this.history[0]===n||(this.history.unshift(n),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let n=this.historyIndex-e;n<-1||n>=this.history.length||(this.historyIndex===-1&&n>=0&&this.pushUndoSnapshot(),this.historyIndex=n,this.historyIndex===-1?this.setTextInternal(""):this.setTextInternal(this.history[this.historyIndex]||""))}setTextInternal(e){let n=e.split(`
|
|
46
|
-
`);this.state.lines=n.length===0?[""]:n,this.state.cursorLine=this.state.lines.length-1,this.setCursorCol(this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}render(e){let n=Math.max(0,Math.floor((e-1)/2)),i=Math.min(this.paddingX,n),s=Math.max(1,e-i*2),r=Math.max(1,s-(i?0:1));this.lastWidth=r;let o=this.borderColor("\u2500"),a=this.layoutText(r),c=this.tui.terminal.rows,l=Math.max(5,Math.floor(c*.3)),d=a.findIndex(y=>y.hasCursor);d===-1&&(d=0),d<this.scrollOffset?this.scrollOffset=d:d>=this.scrollOffset+l&&(this.scrollOffset=d-l+1);let u=Math.max(0,a.length-l);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,u));let p=a.slice(this.scrollOffset,this.scrollOffset+l),m=[],g=" ".repeat(i),h=g;if(this.scrollOffset>0){let y=`\u2500\u2500\u2500 \u2191 ${this.scrollOffset} more `,w=e-j(y);w>=0?m.push(this.borderColor(y+"\u2500".repeat(w))):m.push(this.borderColor(X(y,e)))}else m.push(o.repeat(e));let f=this.focused&&!this.autocompleteState;for(let y of p){let w=y.text,P=j(y.text),_=!1;if(y.hasCursor&&y.cursorPos!==void 0){let E=w.slice(0,y.cursorPos),W=w.slice(y.cursorPos),M=f?lr:"";if(W.length>0){let O=[...this.segment(W)][0]?.segment||"",F=W.slice(O.length),N=`\x1B[7m${O}\x1B[0m`;w=E+M+N+F}else w=E+M+"\x1B[7m \x1B[0m",P=P+1,P>s&&i>0&&(_=!0)}let R=" ".repeat(Math.max(0,s-P)),L=_?h.slice(1):h;m.push(`${g}${w}${R}${L}`)}let x=a.length-(this.scrollOffset+p.length);if(x>0){let y=`\u2500\u2500\u2500 \u2193 ${x} more `,w=e-j(y);m.push(this.borderColor(y+"\u2500".repeat(Math.max(0,w))))}else m.push(o.repeat(e));if(this.autocompleteState&&this.autocompleteList){let y=this.autocompleteList.render(s);for(let w of y){let P=j(w),_=" ".repeat(Math.max(0,s-P));m.push(`${g}${w}${_}${h}`)}}return m}handleInput(e){let n=ve();if(this.jumpMode!==null){if(n.matches(e,"tui.editor.jumpForward")||n.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let s=$g(e)??(e.charCodeAt(0)>=32?e:void 0);if(s!==void 0){let r=this.jumpMode;this.jumpMode=null,this.jumpToChar(s,r);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let s=this.pasteBuffer.indexOf("\x1B[201~");if(s!==-1){let r=this.pasteBuffer.substring(0,s);r.length>0&&this.handlePaste(r),this.isInPaste=!1;let o=this.pasteBuffer.substring(s+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(n.matches(e,"tui.input.copy"))return;if(n.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(n.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")){this.autocompleteList.handleInput(e);return}if(n.matches(e,"tui.input.tab")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(n.matches(e,"tui.select.confirm")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);if(this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(n.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(n.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(n.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(n.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(n.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(n.matches(e,"tui.editor.deleteCharBackward")||
|
|
47
|
-
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,n)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(n.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let s=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&s[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(n.matches(e,"tui.editor.cursorUp")){this.isEditorEmpty()?this.navigateHistory(-1):this.historyIndex>-1&&this.isOnFirstVisualLine()?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(n.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(n.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(n.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(n.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(n.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(n.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(n.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(
|
|
46
|
+
`);this.state.lines=n.length===0?[""]:n,this.state.cursorLine=this.state.lines.length-1,this.setCursorCol(this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}render(e){let n=Math.max(0,Math.floor((e-1)/2)),i=Math.min(this.paddingX,n),s=Math.max(1,e-i*2),r=Math.max(1,s-(i?0:1));this.lastWidth=r;let o=this.borderColor("\u2500"),a=this.layoutText(r),c=this.tui.terminal.rows,l=Math.max(5,Math.floor(c*.3)),d=a.findIndex(y=>y.hasCursor);d===-1&&(d=0),d<this.scrollOffset?this.scrollOffset=d:d>=this.scrollOffset+l&&(this.scrollOffset=d-l+1);let u=Math.max(0,a.length-l);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,u));let p=a.slice(this.scrollOffset,this.scrollOffset+l),m=[],g=" ".repeat(i),h=g;if(this.scrollOffset>0){let y=`\u2500\u2500\u2500 \u2191 ${this.scrollOffset} more `,w=e-j(y);w>=0?m.push(this.borderColor(y+"\u2500".repeat(w))):m.push(this.borderColor(X(y,e)))}else m.push(o.repeat(e));let f=this.focused&&!this.autocompleteState;for(let y of p){let w=y.text,P=j(y.text),_=!1;if(y.hasCursor&&y.cursorPos!==void 0){let E=w.slice(0,y.cursorPos),W=w.slice(y.cursorPos),M=f?lr:"";if(W.length>0){let O=[...this.segment(W)][0]?.segment||"",F=W.slice(O.length),N=`\x1B[7m${O}\x1B[0m`;w=E+M+N+F}else w=E+M+"\x1B[7m \x1B[0m",P=P+1,P>s&&i>0&&(_=!0)}let R=" ".repeat(Math.max(0,s-P)),L=_?h.slice(1):h;m.push(`${g}${w}${R}${L}`)}let x=a.length-(this.scrollOffset+p.length);if(x>0){let y=`\u2500\u2500\u2500 \u2193 ${x} more `,w=e-j(y);m.push(this.borderColor(y+"\u2500".repeat(Math.max(0,w))))}else m.push(o.repeat(e));if(this.autocompleteState&&this.autocompleteList){let y=this.autocompleteList.render(s);for(let w of y){let P=j(w),_=" ".repeat(Math.max(0,s-P));m.push(`${g}${w}${_}${h}`)}}return m}handleInput(e){let n=ve();if(this.jumpMode!==null){if(n.matches(e,"tui.editor.jumpForward")||n.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let s=$g(e)??(e.charCodeAt(0)>=32?e:void 0);if(s!==void 0){let r=this.jumpMode;this.jumpMode=null,this.jumpToChar(s,r);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let s=this.pasteBuffer.indexOf("\x1B[201~");if(s!==-1){let r=this.pasteBuffer.substring(0,s);r.length>0&&this.handlePaste(r),this.isInPaste=!1;let o=this.pasteBuffer.substring(s+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(n.matches(e,"tui.input.copy"))return;if(n.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(n.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")){this.autocompleteList.handleInput(e);return}if(n.matches(e,"tui.input.tab")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(n.matches(e,"tui.select.confirm")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);if(this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(n.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(n.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(n.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(n.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(n.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(n.matches(e,"tui.editor.deleteCharBackward")||Ee(e,"shift+backspace")){this.handleBackspace();return}if(n.matches(e,"tui.editor.deleteCharForward")||Ee(e,"shift+delete")){this.handleForwardDelete();return}if(n.matches(e,"tui.editor.yank")){this.yank();return}if(n.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(n.matches(e,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(n.matches(e,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(n.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(n.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(n.matches(e,"tui.input.newLine")||e.charCodeAt(0)===10&&e.length>1||e==="\x1B\r"||e==="\x1B[13;2~"||e.length>1&&e.includes("\x1B")&&e.includes("\r")||e===`
|
|
47
|
+
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,n)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(n.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let s=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&s[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(n.matches(e,"tui.editor.cursorUp")){this.isEditorEmpty()?this.navigateHistory(-1):this.historyIndex>-1&&this.isOnFirstVisualLine()?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(n.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(n.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(n.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(n.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(n.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(n.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(n.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(Ee(e,"shift+space")){this.insertCharacter(" ");return}let i=$g(e);if(i!==void 0){this.insertCharacter(i);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let n=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return n.push({text:"",hasCursor:!0,cursorPos:0}),n;for(let i=0;i<this.state.lines.length;i++){let s=this.state.lines[i]||"",r=i===this.state.cursorLine;if(j(s)<=e)r?n.push({text:s,hasCursor:!0,cursorPos:this.state.cursorCol}):n.push({text:s,hasCursor:!1});else{let a=Qg(s,e,[...this.segment(s)]);for(let c=0;c<a.length;c++){let l=a[c];if(!l)continue;let d=this.state.cursorCol,u=c===a.length-1,p=!1,m=0;r&&(u?(p=d>=l.startIndex,m=d-l.startIndex):(p=d>=l.startIndex&&d<l.endIndex,p&&(m=d-l.startIndex,m>l.text.length&&(m=l.text.length)))),p?n.push({text:l.text,hasCursor:!0,cursorPos:m}):n.push({text:l.text,hasCursor:!1})}}}return n}getText(){return this.state.lines.join(`
|
|
48
48
|
`)}expandPasteMarkers(e){let n=e;for(let[i,s]of this.pastes){let r=new RegExp(`\\[paste #${i}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");n=n.replace(r,()=>s)}return n}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
|
|
49
49
|
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.historyIndex=-1;let n=this.normalizeText(e);this.getText()!==n&&this.pushUndoSnapshot(),this.setTextInternal(n)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.historyIndex=-1,this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
|
|
50
50
|
`).replace(/\r/g,`
|
|
51
51
|
`).replace(/\t/g," ")}insertTextAtCursorInternal(e){if(!e)return;let n=this.normalizeText(e),i=n.split(`
|
|
52
52
|
`),s=this.state.lines[this.state.cursorLine]||"",r=s.slice(0,this.state.cursorCol),o=s.slice(this.state.cursorCol);i.length===1?(this.state.lines[this.state.cursorLine]=r+n+o,this.setCursorCol(this.state.cursorCol+n.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),r+i[0],...i.slice(1,-1),i[i.length-1]+o,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=i.length-1,this.setCursorCol((i[i.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,n){this.historyIndex=-1,n||((Ht(e)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let i=this.state.lines[this.state.cursorLine]||"",s=i.slice(0,this.state.cursorCol),r=i.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=s+e+r,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(e==="@"||e==="#"){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol),c=a[a.length-2];(a.length===1||c===" "||c===" ")&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(a)?this.tryTriggerAutocomplete():a.match(/(?:^|[\s])[@#][^\s]*$/)&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let n=e.replace(/\x1b\[(\d+);5u/g,(a,c)=>{let l=Number(c);return l>=97&&l<=122?String.fromCharCode(l-96):l>=65&&l<=90?String.fromCharCode(l-64):a}),s=this.normalizeText(n).split("").filter(a=>a===`
|
|
53
53
|
`||a.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(s)){let a=this.state.lines[this.state.cursorLine]||"",c=this.state.cursorCol>0?a[this.state.cursorCol-1]:"";c&&/\w/.test(c)&&(s=` ${s}`)}let r=s.split(`
|
|
54
|
-
`),o=s.length;if(r.length>10||o>1e3){this.pasteCounter++;let a=this.pasteCounter;this.pastes.set(a,s);let c=r.length>10?`[paste #${a} +${r.length} lines]`:`[paste #${a} ${o} chars]`;this.insertTextAtCursorInternal(c);return}if(r.length===1){this.insertTextAtCursorInternal(s);return}this.insertTextAtCursorInternal(s)}addNewLine(){this.cancelAutocomplete(),this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",n=e.slice(0,this.state.cursorCol),i=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n,this.state.lines.splice(this.state.cursorLine+1,0,i),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,n){if(this.disableSubmit||!
|
|
54
|
+
`),o=s.length;if(r.length>10||o>1e3){this.pasteCounter++;let a=this.pasteCounter;this.pastes.set(a,s);let c=r.length>10?`[paste #${a} +${r.length} lines]`:`[paste #${a} ${o} chars]`;this.insertTextAtCursorInternal(c);return}if(r.length===1){this.insertTextAtCursorInternal(s);return}this.insertTextAtCursorInternal(s)}addNewLine(){this.cancelAutocomplete(),this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",n=e.slice(0,this.state.cursorCol),i=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n,this.state.lines.splice(this.state.cursorLine+1,0,i),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,n){if(this.disableSubmit||!Ee(e,"enter"))return!1;let i=n.getKeys("tui.input.submit");if(!(i.includes("shift+enter")||i.includes("shift+return")))return!1;let r=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&r[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
|
|
55
55
|
`)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.historyIndex=-1,this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.historyIndex=-1,this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",n=e.slice(0,this.state.cursorCol),i=[...this.segment(n)],s=i[i.length-1],r=s?s.segment.length:1,o=e.slice(0,this.state.cursorCol-r),a=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+a,this.setCursorCol(this.state.cursorCol-r)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",n=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=n+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(n.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(n)?this.tryTriggerAutocomplete():n.match(/(?:^|[\s])[@#][^\s]*$/)&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,n,i){let s=e[n],r=e[i];if(!(s&&r))return;let o;if(this.snappedFromCursorCol!==null){let h=this.findVisualLineAt(e,s.logicalLine,this.snappedFromCursorCol);o=this.snappedFromCursorCol-e[h].startCol}else o=this.state.cursorCol-s.startCol;let c=n===e.length-1||e[n+1]?.logicalLine!==s.logicalLine?s.length:Math.max(0,s.length-1),d=i===e.length-1||e[i+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),u=this.computeVerticalMoveColumn(o,c,d);this.state.cursorLine=r.logicalLine;let p=r.startCol+u,m=this.state.lines[r.logicalLine]||"";this.state.cursorCol=Math.min(p,m.length);let g=[...this.segment(m)];for(let h of g){if(h.index>this.state.cursorCol)break;if(!(h.segment.length<=1)&&this.state.cursorCol<h.index+h.segment.length){let f=h.index<r.startCol,x=i>n;if(f&&x){let y=h.index+h.segment.length,w=i+1;for(;w<e.length&&e[w].logicalLine===r.logicalLine&&e[w].startCol<y;)w++;if(w<e.length){this.moveToVisualLine(e,n,w);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=h.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,n,i){let s=this.preferredVisualCol!==null,r=e<n,o=i<e;if(!s||r)return o?(this.preferredVisualCol=e,i):(this.preferredVisualCol=null,e);let a=i<this.preferredVisualCol;if(o||a)return i;let c=this.preferredVisualCol;return this.preferredVisualCol=null,c}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length)}deleteToStartOfLine(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let n=e.slice(0,this.state.cursorCol);this.killRing.push(n,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
56
56
|
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let n=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=n+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(n.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let n=e.slice(this.state.cursorCol);this.killRing.push(n,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
57
57
|
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let n=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+n,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
@@ -93,7 +93,7 @@ ${n.map(o=>` ${o}`).join(`
|
|
|
93
93
|
`),o=r.length;if(o<=n&&s<=i)return{content:t,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:s,outputLines:o,outputBytes:s,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i};if(Buffer.byteLength(r[0],"utf-8")>i)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:o,totalBytes:s,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:i};let c=[],l=0,d="lines";for(let m=0;m<r.length&&m<n;m++){let g=r[m],h=Buffer.byteLength(g,"utf-8")+(m>0?1:0);if(l+h>i){d="bytes";break}c.push(g),l+=h}c.length>=n&&l<=i&&(d="lines");let u=c.join(`
|
|
94
94
|
`),p=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:d,totalLines:o,totalBytes:s,outputLines:c.length,outputBytes:p,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i}}function vr(t,e={}){let n=e.maxLines??2e3,i=e.maxBytes??51200,s=Buffer.byteLength(t,"utf-8"),r=t.split(`
|
|
95
95
|
`),o=r.length;if(o<=n&&s<=i)return{content:t,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:s,outputLines:o,outputBytes:s,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i};let a=[],c=0,l="lines",d=!1;for(let m=r.length-1;m>=0&&a.length<n;m--){let g=r[m],h=Buffer.byteLength(g,"utf-8")+(a.length>0?1:0);if(c+h>i){if(l="bytes",a.length===0){let f=G5(g,i);a.unshift(f),c=Buffer.byteLength(f,"utf-8"),d=!0}break}a.unshift(g),c+=h}a.length>=n&&c<=i&&(l="lines");let u=a.join(`
|
|
96
|
-
`),p=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:s,outputLines:a.length,outputBytes:p,lastLinePartial:d,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i}}function G5(t,e){let n=Buffer.from(t,"utf-8");if(n.length<=e)return t;let i=n.length-e;for(;i<n.length&&(n[i]&192)===128;)i++;return n.slice(i).toString("utf-8")}function ml(t,e=500){return t.length<=e?{text:t,wasTruncated:!1}:{text:`${t.slice(0,e)}... [truncated]`,wasTruncated:!0}}function Gd(t,e,n){return{role:"branchSummary",summary:t,fromId:e,timestamp:new Date(n).getTime()}}function ga(t,e,n){return{role:"compactionSummary",summary:t,tokensBefore:e,timestamp:new Date(n).getTime()}}function Kd(t,e,n,i,s){return{role:"custom",customType:t,content:e,display:n,details:i,timestamp:new Date(s).getTime()}}import{uuidv7 as K5}from"@earendil-works/pi-agent-core";import{randomUUID as vT}from"crypto";import{appendFileSync as Hd,closeSync as H5,existsSync as wr,mkdirSync as mf,openSync as z5,readdirSync as V5,readFileSync as J5,readSync as Q5,statSync as Y5,writeFileSync as X5}from"fs";import{readdir as hf,readFile as Z5,stat as eU}from"fs/promises";import{join as Is,resolve as wT}from"path";var fa=3;function zd(){return K5()}function En(t){for(let e=0;e<100;e++){let n=vT().slice(0,8);if(!t.has(n))return n}return vT()}function tU(t){let e=new Set,n=null;for(let i of t){if(i.type==="session"){i.version=2;continue}if(i.id=En(e),i.parentId=n,n=i.id,i.type==="compaction"){let s=i;if(typeof s.firstKeptEntryIndex=="number"){let r=t[s.firstKeptEntryIndex];r&&r.type!=="session"&&(s.firstKeptEntryId=r.id),delete s.firstKeptEntryIndex}}}}function nU(t){for(let e of t){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){let n=e;n.message&&n.message.role==="hookMessage"&&(n.message.role="custom")}}}function iU(t){let n=t.find(i=>i.type==="session")?.version??1;return n>=fa?!1:(n<2&&tU(t),n<3&&nU(t),!0)}function gf(t,e,n){if(!n){n=new Map;for(let u of t)n.set(u.id,u)}let i;if(e===null)return{messages:[],thinkingLevel:"off",model:null};if(e&&(i=n.get(e)),i||(i=t[t.length-1]),!i)return{messages:[],thinkingLevel:"off",model:null};let s=[],r=i;for(;r;)s.unshift(r),r=r.parentId?n.get(r.parentId):void 0;let o="off",a=null,c=null;for(let u of s)u.type==="thinking_level_change"?o=u.thinkingLevel:u.type==="model_change"?a={provider:u.provider,modelId:u.modelId}:u.type==="message"&&u.message.role==="assistant"?a={provider:u.message.provider,modelId:u.message.model}:u.type==="compaction"&&(c=u);let l=[],d=u=>{u.type==="message"?l.push(u.message):u.type==="custom_message"?l.push(Kd(u.customType,u.content,u.display,u.details,u.timestamp)):u.type==="branch_summary"&&u.summary&&l.push(Gd(u.summary,u.fromId,u.timestamp))};if(c){l.push(ga(c.summary,c.tokensBefore,c.timestamp));let u=s.findIndex(m=>m.type==="compaction"&&m.id===c.id),p=!1;for(let m=0;m<u;m++){let g=s[m];g.id===c.firstKeptEntryId&&(p=!0),p&&d(g)}for(let m=u+1;m<s.length;m++){let g=s[m];d(g)}}else for(let u of s)d(u);return{messages:l,thinkingLevel:o,model:a}}function hl(t,e=
|
|
96
|
+
`),p=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:s,outputLines:a.length,outputBytes:p,lastLinePartial:d,firstLineExceedsLimit:!1,maxLines:n,maxBytes:i}}function G5(t,e){let n=Buffer.from(t,"utf-8");if(n.length<=e)return t;let i=n.length-e;for(;i<n.length&&(n[i]&192)===128;)i++;return n.slice(i).toString("utf-8")}function ml(t,e=500){return t.length<=e?{text:t,wasTruncated:!1}:{text:`${t.slice(0,e)}... [truncated]`,wasTruncated:!0}}function Gd(t,e,n){return{role:"branchSummary",summary:t,fromId:e,timestamp:new Date(n).getTime()}}function ga(t,e,n){return{role:"compactionSummary",summary:t,tokensBefore:e,timestamp:new Date(n).getTime()}}function Kd(t,e,n,i,s){return{role:"custom",customType:t,content:e,display:n,details:i,timestamp:new Date(s).getTime()}}import{uuidv7 as K5}from"@earendil-works/pi-agent-core";import{randomUUID as vT}from"crypto";import{appendFileSync as Hd,closeSync as H5,existsSync as wr,mkdirSync as mf,openSync as z5,readdirSync as V5,readFileSync as J5,readSync as Q5,statSync as Y5,writeFileSync as X5}from"fs";import{readdir as hf,readFile as Z5,stat as eU}from"fs/promises";import{join as Is,resolve as wT}from"path";var fa=3;function zd(){return K5()}function En(t){for(let e=0;e<100;e++){let n=vT().slice(0,8);if(!t.has(n))return n}return vT()}function tU(t){let e=new Set,n=null;for(let i of t){if(i.type==="session"){i.version=2;continue}if(i.id=En(e),i.parentId=n,n=i.id,i.type==="compaction"){let s=i;if(typeof s.firstKeptEntryIndex=="number"){let r=t[s.firstKeptEntryIndex];r&&r.type!=="session"&&(s.firstKeptEntryId=r.id),delete s.firstKeptEntryIndex}}}}function nU(t){for(let e of t){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){let n=e;n.message&&n.message.role==="hookMessage"&&(n.message.role="custom")}}}function iU(t){let n=t.find(i=>i.type==="session")?.version??1;return n>=fa?!1:(n<2&&tU(t),n<3&&nU(t),!0)}function gf(t,e,n){if(!n){n=new Map;for(let u of t)n.set(u.id,u)}let i;if(e===null)return{messages:[],thinkingLevel:"off",model:null};if(e&&(i=n.get(e)),i||(i=t[t.length-1]),!i)return{messages:[],thinkingLevel:"off",model:null};let s=[],r=i;for(;r;)s.unshift(r),r=r.parentId?n.get(r.parentId):void 0;let o="off",a=null,c=null;for(let u of s)u.type==="thinking_level_change"?o=u.thinkingLevel:u.type==="model_change"?a={provider:u.provider,modelId:u.modelId}:u.type==="message"&&u.message.role==="assistant"?a={provider:u.message.provider,modelId:u.message.model}:u.type==="compaction"&&(c=u);let l=[],d=u=>{u.type==="message"?l.push(u.message):u.type==="custom_message"?l.push(Kd(u.customType,u.content,u.display,u.details,u.timestamp)):u.type==="branch_summary"&&u.summary&&l.push(Gd(u.summary,u.fromId,u.timestamp))};if(c){l.push(ga(c.summary,c.tokensBefore,c.timestamp));let u=s.findIndex(m=>m.type==="compaction"&&m.id===c.id),p=!1;for(let m=0;m<u;m++){let g=s[m];g.id===c.firstKeptEntryId&&(p=!0),p&&d(g)}for(let m=u+1;m<s.length;m++){let g=s[m];d(g)}}else for(let u of s)d(u);return{messages:l,thinkingLevel:o,model:a}}function hl(t,e=_e()){let n=`--${t.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,i=Is(e,"sessions",n);return wr(i)||mf(i,{recursive:!0}),i}function pf(t){if(!wr(t))return[];let e=J5(t,"utf8"),n=[],i=e.trim().split(`
|
|
97
97
|
`);for(let r of i)if(r.trim())try{let o=JSON.parse(r);n.push(o)}catch{}if(n.length===0)return n;let s=n[0];return s.type!=="session"||typeof s.id!="string"?[]:n}function sU(t){try{let e=z5(t,"r"),n=Buffer.alloc(512),i=Q5(e,n,0,512,0);H5(e);let s=n.toString("utf8",0,i).split(`
|
|
98
98
|
`)[0];if(!s)return!1;let r=JSON.parse(s);return r.type==="session"&&typeof r.id=="string"}catch{return!1}}function rU(t){try{return V5(t).filter(n=>n.endsWith(".jsonl")).map(n=>Is(t,n)).filter(sU).map(n=>({path:n,mtime:Y5(n).mtime})).sort((n,i)=>i.mtime.getTime()-n.mtime.getTime())[0]?.path||null}catch{return null}}function ST(t){return typeof t.role=="string"&&"content"in t}function oU(t){let e=t.content;return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(" ")}function aU(t){let e;for(let n of t){if(n.type!=="message")continue;let i=n.message;if(!ST(i)||i.role!=="user"&&i.role!=="assistant")continue;let s=i.timestamp;if(typeof s=="number"){e=Math.max(e??0,s);continue}let r=n.timestamp;if(typeof r=="string"){let o=new Date(r).getTime();Number.isNaN(o)||(e=Math.max(e??0,o))}}return e}function cU(t,e,n){let i=aU(t);if(typeof i=="number"&&i>0)return new Date(i);let s=typeof e.timestamp=="string"?new Date(e.timestamp).getTime():NaN;return Number.isNaN(s)?n:new Date(s)}async function lU(t){try{let e=await Z5(t,"utf8"),n=[],i=e.trim().split(`
|
|
99
99
|
`);for(let m of i)if(m.trim())try{n.push(JSON.parse(m))}catch{}if(n.length===0)return null;let s=n[0];if(s.type!=="session")return null;let r=await eU(t),o=0,a="",c=[],l;for(let m of n){if(m.type==="session_info"&&(l=m.name?.trim()||void 0),m.type!=="message")continue;o++;let g=m.message;if(!ST(g)||g.role!=="user"&&g.role!=="assistant")continue;let h=oU(g);h&&(c.push(h),!a&&g.role==="user"&&(a=h))}let d=typeof s.cwd=="string"?s.cwd:"",u=s.parentSession,p=cU(n,s,r.mtime);return{path:t,id:s.id,cwd:d,name:l,parentSessionPath:u,created:new Date(s.timestamp),modified:p,messageCount:o,firstMessage:a||"(no messages)",allMessagesText:c.join(" ")}}catch{return null}}var uU=10;async function CT(t,e){let n=new Array(t.length).fill(null),i=new Set,s=0,r=()=>{let o=s++,a=t[o];if(!a)return;let c;c=lU(a).then(l=>{n[o]=l}).catch(()=>{n[o]=null}).finally(()=>{i.delete(c),e()}),i.add(c)};for(;s<t.length||i.size>0;){for(;s<t.length&&i.size<uU;)r();i.size>0&&await Promise.race(i)}return n}async function dU(t,e,n=0,i){let s=[];if(!wr(t))return s;try{let o=(await hf(t)).filter(d=>d.endsWith(".jsonl")).map(d=>Is(t,d)),a=i??o.length,c=0,l=await CT(o,()=>{c++,e?.(n+c,a)});for(let d of l)d&&s.push(d)}catch{}return s}var Yn=class t{constructor(e,n,i,s){this.sessionId="";this.flushed=!1;this.fileEntries=[];this.byId=new Map;this.labelsById=new Map;this.labelTimestampsById=new Map;this.leafId=null;this.cwd=e,this.sessionDir=n,this.persist=s,s&&n&&!wr(n)&&mf(n,{recursive:!0}),i?this.setSessionFile(i):this.newSession()}setSessionFile(e){if(this.sessionFile=wT(e),wr(this.sessionFile)){if(this.fileEntries=pf(this.sessionFile),this.fileEntries.length===0){let i=this.sessionFile;this.newSession(),this.sessionFile=i,this._rewriteFile(),this.flushed=!0;return}let n=this.fileEntries.find(i=>i.type==="session");this.sessionId=n?.id??zd(),iU(this.fileEntries)&&this._rewriteFile(),this._buildIndex(),this.flushed=!0}else{let n=this.sessionFile;this.newSession(),this.sessionFile=n}}newSession(e){this.sessionId=e?.id??zd();let n=new Date().toISOString(),i={type:"session",version:fa,id:this.sessionId,timestamp:n,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[i],this.byId.clear(),this.labelsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let s=n.replace(/[:.]/g,"-");this.sessionFile=Is(this.getSessionDir(),`${s}_${this.sessionId}.jsonl`)}return this.sessionFile}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(let e of this.fileEntries)e.type!=="session"&&(this.byId.set(e.id,e),this.leafId=e.id,e.type==="label"&&(e.label?(this.labelsById.set(e.targetId,e.label),this.labelTimestampsById.set(e.targetId,e.timestamp)):(this.labelsById.delete(e.targetId),this.labelTimestampsById.delete(e.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let e=`${this.fileEntries.map(n=>JSON.stringify(n)).join(`
|
|
@@ -281,13 +281,13 @@ ${g.map(f=>l?f:n.fg("toolOutput",$i(f))).join(`
|
|
|
281
281
|
`);if(n)return`
|
|
282
282
|
${e.fg("error",n)}`}function Sp(t,e){let n=e?.operations??AD;return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",promptSnippet:"Create or overwrite files",promptGuidelines:["Use write only for new files or complete rewrites."],parameters:ED,async execute(i,{path:s,content:r},o,a,c){let l=yn(s,t),d=_D(l);return Cr(l,()=>new Promise((u,p)=>{if(o?.aborted){p(new Error("Operation aborted"));return}let m=!1,g=()=>{m=!0,p(new Error("Operation aborted"))};o?.addEventListener("abort",g,{once:!0}),(async()=>{try{if(await n.mkdir(d),m||(await n.writeFile(l,r),m))return;o?.removeEventListener("abort",g),u({content:[{type:"text",text:`Successfully wrote ${r.length} bytes to ${s}`}],details:void 0})}catch(h){o?.removeEventListener("abort",g),m||p(h)}})()}))},renderCall(i,s,r){let o=i,a=Xe(o?.file_path??o?.path),c=Xe(o?.content),l=r.lastComponent??new Jf;return c!==null?l.cache=r.argsComplete?wp(a,c):WD(l.cache,a,c):l.cache=void 0,l.setText(FD(o,{expanded:r.expanded,isPartial:r.isPartial},s,l.cache)),l},renderResult(i,s,r,o){let a=DD({...i,isError:o.isError},r);if(!a){let l=o.lastComponent??new K;return l.clear(),l}let c=o.lastComponent??new A("",0,0);return c.setText(a),c}}}function s0(t,e){return{read:vp(t,e?.read),bash:op(t,e?.bash),edit:lp(t,e?.edit),write:Sp(t,e?.write),grep:pp(t,e?.grep),find:dp(t,e?.find),ls:mp(t,e?.ls)}}function r0(t){let e=t.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}import y0e from"proper-lockfile";import{Type as C}from"typebox";import{Compile as JD}from"typebox/compile";var o0={anthropic:"Anthropic","amazon-bedrock":"Amazon Bedrock","azure-openai-responses":"Azure OpenAI Responses",cerebras:"Cerebras","cloudflare-ai-gateway":"Cloudflare AI Gateway","cloudflare-workers-ai":"Cloudflare Workers AI",deepseek:"DeepSeek",fireworks:"Fireworks",google:"Google Gemini","google-vertex":"Google Vertex AI",groq:"Groq",huggingface:"Hugging Face","kimi-coding":"Kimi For Coding",mistral:"Mistral",minimax:"MiniMax","minimax-cn":"MiniMax (China)",moonshotai:"Moonshot AI","moonshotai-cn":"Moonshot AI (China)",opencode:"OpenCode Zen","opencode-go":"OpenCode Go",openai:"OpenAI",openrouter:"OpenRouter",together:"Together AI","vercel-ai-gateway":"Vercel AI Gateway",xai:"xAI",zai:"ZAI",xiaomi:"Xiaomi MiMo","xiaomi-token-plan-cn":"Xiaomi MiMo Token Plan (China)","xiaomi-token-plan-ams":"Xiaomi MiMo Token Plan (Amsterdam)","xiaomi-token-plan-sgp":"Xiaomi MiMo Token Plan (Singapore)"};var Rk=C.Object({p50:C.Optional(C.Number()),p75:C.Optional(C.Number()),p90:C.Optional(C.Number()),p99:C.Optional(C.Number())}),QD=C.Object({allow_fallbacks:C.Optional(C.Boolean()),require_parameters:C.Optional(C.Boolean()),data_collection:C.Optional(C.Union([C.Literal("deny"),C.Literal("allow")])),zdr:C.Optional(C.Boolean()),enforce_distillable_text:C.Optional(C.Boolean()),order:C.Optional(C.Array(C.String())),only:C.Optional(C.Array(C.String())),ignore:C.Optional(C.Array(C.String())),quantizations:C.Optional(C.Array(C.String())),sort:C.Optional(C.Union([C.String(),C.Object({by:C.Optional(C.String()),partition:C.Optional(C.Union([C.String(),C.Null()]))})])),max_price:C.Optional(C.Object({prompt:C.Optional(C.Union([C.Number(),C.String()])),completion:C.Optional(C.Union([C.Number(),C.String()])),image:C.Optional(C.Union([C.Number(),C.String()])),audio:C.Optional(C.Union([C.Number(),C.String()])),request:C.Optional(C.Union([C.Number(),C.String()]))})),preferred_min_throughput:C.Optional(C.Union([C.Number(),Rk])),preferred_max_latency:C.Optional(C.Union([C.Number(),Rk]))}),YD=C.Object({only:C.Optional(C.Array(C.String())),order:C.Optional(C.Array(C.String()))}),_a=C.Union([C.String(),C.Null()]),Pk=C.Object({off:C.Optional(_a),minimal:C.Optional(_a),low:C.Optional(_a),medium:C.Optional(_a),high:C.Optional(_a),xhigh:C.Optional(_a)}),XD=C.Object({supportsStore:C.Optional(C.Boolean()),supportsDeveloperRole:C.Optional(C.Boolean()),supportsReasoningEffort:C.Optional(C.Boolean()),supportsUsageInStreaming:C.Optional(C.Boolean()),maxTokensField:C.Optional(C.Union([C.Literal("max_completion_tokens"),C.Literal("max_tokens")])),requiresToolResultName:C.Optional(C.Boolean()),requiresAssistantAfterToolResult:C.Optional(C.Boolean()),requiresThinkingAsText:C.Optional(C.Boolean()),requiresReasoningContentOnAssistantMessages:C.Optional(C.Boolean()),thinkingFormat:C.Optional(C.Union([C.Literal("openai"),C.Literal("openrouter"),C.Literal("together"),C.Literal("deepseek"),C.Literal("zai"),C.Literal("qwen"),C.Literal("qwen-chat-template")])),cacheControlFormat:C.Optional(C.Literal("anthropic")),openRouterRouting:C.Optional(QD),vercelGatewayRouting:C.Optional(YD),supportsStrictMode:C.Optional(C.Boolean()),supportsLongCacheRetention:C.Optional(C.Boolean())}),ZD=C.Object({sendSessionIdHeader:C.Optional(C.Boolean()),supportsLongCacheRetention:C.Optional(C.Boolean())}),e4=C.Object({supportsEagerToolInputStreaming:C.Optional(C.Boolean()),supportsLongCacheRetention:C.Optional(C.Boolean())}),a0=C.Union([XD,ZD,e4]),t4=C.Object({id:C.String({minLength:1}),name:C.Optional(C.String({minLength:1})),api:C.Optional(C.String({minLength:1})),baseUrl:C.Optional(C.String({minLength:1})),reasoning:C.Optional(C.Boolean()),thinkingLevelMap:C.Optional(Pk),input:C.Optional(C.Array(C.Union([C.Literal("text"),C.Literal("image")]))),cost:C.Optional(C.Object({input:C.Number(),output:C.Number(),cacheRead:C.Number(),cacheWrite:C.Number()})),contextWindow:C.Optional(C.Number()),maxTokens:C.Optional(C.Number()),headers:C.Optional(C.Record(C.String(),C.String())),compat:C.Optional(a0)}),n4=C.Object({name:C.Optional(C.String({minLength:1})),reasoning:C.Optional(C.Boolean()),thinkingLevelMap:C.Optional(Pk),input:C.Optional(C.Array(C.Union([C.Literal("text"),C.Literal("image")]))),cost:C.Optional(C.Object({input:C.Optional(C.Number()),output:C.Optional(C.Number()),cacheRead:C.Optional(C.Number()),cacheWrite:C.Optional(C.Number())})),contextWindow:C.Optional(C.Number()),maxTokens:C.Optional(C.Number()),headers:C.Optional(C.Record(C.String(),C.String())),compat:C.Optional(a0)}),i4=C.Object({name:C.Optional(C.String({minLength:1})),baseUrl:C.Optional(C.String({minLength:1})),apiKey:C.Optional(C.String({minLength:1})),api:C.Optional(C.String({minLength:1})),headers:C.Optional(C.Record(C.String(),C.String())),compat:C.Optional(a0),authHeader:C.Optional(C.Boolean()),models:C.Optional(C.Array(t4)),modelOverrides:C.Optional(C.Record(C.String(),n4))}),s4=C.Object({providers:C.Record(C.String(),i4)}),F0e=JD(s4);import{createHash as a4}from"node:crypto";import{existsSync as xe,mkdirSync as c0,readdirSync as Aa,readFileSync as Pl,rmSync as Ok,statSync as Rs,writeFileSync as Lk}from"node:fs";import{homedir as c4,tmpdir as l4}from"node:os";import{basename as Ip,dirname as Ln,join as ge,relative as Wn,resolve as hi,sep as u4}from"node:path";import{globSync as d4}from"glob";import _l from"ignore";import{minimatch as Ea}from"minimatch";import _k from"hosted-git-info";function Ek(t){let e=t.match(/^git@([^:]+):(.+)$/);if(e){let c=e[2]??"",l=c.indexOf("@");if(l<0)return{repo:t};let d=c.slice(0,l),u=c.slice(l+1);return!d||!u?{repo:t}:{repo:`git@${e[1]??""}:${d}`,ref:u}}if(t.includes("://"))try{let c=new URL(t),l=c.pathname.replace(/^\/+/,""),d=l.indexOf("@");if(d<0)return{repo:t};let u=l.slice(0,d),p=l.slice(d+1);return!u||!p?{repo:t}:(c.pathname=`/${u}`,{repo:c.toString().replace(/\/$/,""),ref:p})}catch{return{repo:t}}let n=t.indexOf("/");if(n<0)return{repo:t};let i=t.slice(0,n),s=t.slice(n+1),r=s.indexOf("@");if(r<0)return{repo:t};let o=s.slice(0,r),a=s.slice(r+1);return!o||!a?{repo:t}:{repo:`${i}/${o}`,ref:a}}function r4(t){let{repo:e,ref:n}=Ek(t),i=e,s="",r="",o=e.match(/^git@([^:]+):(.+)$/);if(o)s=o[1]??"",r=o[2]??"";else if(e.startsWith("https://")||e.startsWith("http://")||e.startsWith("ssh://")||e.startsWith("git://"))try{let c=new URL(e);s=c.hostname,r=c.pathname.replace(/^\/+/,"")}catch{return null}else{let c=e.indexOf("/");if(c<0||(s=e.slice(0,c),r=e.slice(c+1),!s.includes(".")&&s!=="localhost"))return null;i=`https://${e}`}let a=r.replace(/\.git$/,"").replace(/^\/+/,"");return!s||!a||a.split("/").length<2?null:{type:"git",repo:i,host:s,path:a,ref:n,pinned:!!n}}function Rl(t){let e=t.trim(),n=e.startsWith("git:"),i=n?e.slice(4).trim():e;if(!n&&!/^(https?|ssh|git):\/\//i.test(i))return null;let s=Ek(i),r=[s.ref?`${s.repo}#${s.ref}`:void 0,i].filter(a=>!!a);for(let a of r){let c=_k.fromUrl(a);if(c){if(s.ref&&c.project?.includes("@"))continue;return{type:"git",repo:!s.repo.startsWith("http://")&&!s.repo.startsWith("https://")&&!s.repo.startsWith("ssh://")&&!s.repo.startsWith("git://")&&!s.repo.startsWith("git@")?`https://${s.repo}`:s.repo,host:c.domain||"",path:`${c.user}/${c.project}`.replace(/\.git$/,""),ref:c.committish||s.ref||void 0,pinned:!!(c.committish||s.ref)}}}let o=[s.ref?`https://${s.repo}#${s.ref}`:void 0,`https://${i}`].filter(a=>!!a);for(let a of o){let c=_k.fromUrl(a);if(c){if(s.ref&&c.project?.includes("@"))continue;return{type:"git",repo:`https://${s.repo}`,host:c.domain||"",path:`${c.user}/${c.project}`.replace(/\.git$/,""),ref:c.committish||s.ref||void 0,pinned:!!(c.committish||s.ref)}}}return r4(i)}var o4;function Ak(){return o4!==void 0}function l0(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let t=Pl("/proc/self/environ","utf-8"),e={};for(let n of t.split("\0")){let i=n.indexOf("=");i>0&&(e[n.slice(0,i)]=n.slice(i+1))}return e}catch{return process.env}}var mi=1e4,Wk=4,p4=4;function kr(){let t=process.env.PI_OFFLINE;return t?t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="yes":!1}function Uk(t){return t.origin==="package"?4:(t.scope==="project"?0:2)+(t.source==="local"?0:1)}var Cp=["extensions","skills","prompts","themes"],m4={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},h4=[".gitignore",".ignore",".fdignore"];function kt(t){return t.split(u4).join("/")}function Mr(){return process.env.HOME||c4()}function g4(t,e){let n=t.trim();if(!n||n.startsWith("#")&&!n.startsWith("\\#"))return null;let i=t,s=!1;i.startsWith("!")?(s=!0,i=i.slice(1)):i.startsWith("\\!")&&(i=i.slice(1)),i.startsWith("/")&&(i=i.slice(1));let r=e?`${e}${i}`:i;return s?`!${r}`:r}function El(t,e,n){let i=Wn(n,e),s=i?`${kt(i)}/`:"";for(let r of h4){let o=ge(e,r);if(xe(o))try{let c=Pl(o,"utf-8").split(/\r?\n/).map(l=>g4(l,s)).filter(l=>!!l);c.length>0&&t.add(c)}catch{}}}function f4(t){return t.startsWith("!")||t.startsWith("+")||t.startsWith("-")||t.includes("*")||t.includes("?")}function u0(t){return t.startsWith("!")||t.startsWith("+")||t.startsWith("-")}function b4(t){return t.includes("*")||t.includes("?")}function x4(t){let e=[],n=[];for(let i of t)f4(i)?n.push(i):e.push(i);return{plain:e,patterns:n}}function Bk(t,e,n=!0,i,s){let r=[];if(!xe(t))return r;let o=s??t,a=i??_l();El(a,t,o);try{let c=Aa(t,{withFileTypes:!0});for(let l of c){if(l.name.startsWith(".")||n&&l.name==="node_modules")continue;let d=ge(t,l.name),u=l.isDirectory(),p=l.isFile();if(l.isSymbolicLink())try{let h=Rs(d);u=h.isDirectory(),p=h.isFile()}catch{continue}let m=kt(Wn(o,d)),g=u?`${m}/`:m;a.ignores(g)||(u?r.push(...Bk(d,e,n,a,o)):p&&e.test(l.name)&&r.push(d))}}catch{}return r}function m0(t,e,n,i){let s=[];if(!xe(t))return s;let r=i??t,o=n??_l();El(o,t,r);try{let a=Aa(t,{withFileTypes:!0});for(let c of a){if(c.name!=="SKILL.md")continue;let l=ge(t,c.name),d=c.isFile();if(c.isSymbolicLink())try{d=Rs(l).isFile()}catch{continue}let u=kt(Wn(r,l));if(d&&!o.ignores(u))return s.push(l),s}for(let c of a){if(c.name.startsWith(".")||c.name==="node_modules")continue;let l=ge(t,c.name),d=c.isDirectory(),u=c.isFile();if(c.isSymbolicLink())try{let m=Rs(l);d=m.isDirectory(),u=m.isFile()}catch{continue}let p=kt(Wn(r,l));if(e==="pi"&&t===r&&u&&c.name.endsWith(".md")&&!o.ignores(p)){s.push(l);continue}d&&(o.ignores(`${p}/`)||s.push(...m0(l,e,o,r)))}}catch{}return s}function Tp(t,e){return m0(t,e)}function y4(t){let e=hi(t);for(;;){if(xe(ge(e,".git")))return e;let n=Ln(e);if(n===e)return null;e=n}}function v4(t){let e=[],n=hi(t),i=y4(n),s=n;for(;e.push(ge(s,".agents","skills")),!(i&&s===i);){let r=Ln(s);if(r===s)break;s=r}return e}function Fk(t){let e=[];if(!xe(t))return e;let n=_l();El(n,t,t);try{let i=Aa(t,{withFileTypes:!0});for(let s of i){if(s.name.startsWith(".")||s.name==="node_modules")continue;let r=ge(t,s.name),o=s.isFile();if(s.isSymbolicLink())try{o=Rs(r).isFile()}catch{continue}let a=kt(Wn(t,r));n.ignores(a)||o&&s.name.endsWith(".md")&&e.push(r)}}catch{}return e}function Dk(t){let e=[];if(!xe(t))return e;let n=_l();El(n,t,t);try{let i=Aa(t,{withFileTypes:!0});for(let s of i){if(s.name.startsWith(".")||s.name==="node_modules")continue;let r=ge(t,s.name),o=s.isFile();if(s.isSymbolicLink())try{o=Rs(r).isFile()}catch{continue}let a=kt(Wn(t,r));n.ignores(a)||o&&s.name.endsWith(".json")&&e.push(r)}}catch{}return e}function w4(t){try{let e=Pl(t,"utf-8");return JSON.parse(e).pi??null}catch{return null}}function $k(t){let e=ge(t,"package.json");if(xe(e)){let s=w4(e);if(s?.extensions?.length){let r=[];for(let o of s.extensions){let a=hi(t,o);xe(a)&&r.push(a)}if(r.length>0)return r}}let n=ge(t,"index.ts"),i=ge(t,"index.js");return xe(n)?[n]:xe(i)?[i]:null}function d0(t){let e=[];if(!xe(t))return e;let n=$k(t);if(n)return n;let i=_l();El(i,t,t);try{let s=Aa(t,{withFileTypes:!0});for(let r of s){if(r.name.startsWith(".")||r.name==="node_modules")continue;let o=ge(t,r.name),a=r.isDirectory(),c=r.isFile();if(r.isSymbolicLink())try{let u=Rs(o);a=u.isDirectory(),c=u.isFile()}catch{continue}let l=kt(Wn(t,o)),d=a?`${l}/`:l;if(!i.ignores(d)){if(c&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))e.push(o);else if(a){let u=$k(o);u&&e.push(...u)}}}}catch{}return e}function kp(t,e){return e==="skills"?m0(t,"pi"):e==="extensions"?d0(t):Bk(t,m4[e])}function p0(t,e,n){let i=kt(Wn(n,t)),s=Ip(t),r=kt(t),o=s==="SKILL.md",a=o?Ln(t):void 0,c=o?kt(Wn(n,a)):void 0,l=o?Ip(a):void 0,d=o?kt(a):void 0;return e.some(u=>{let p=kt(u);return Ea(i,p)||Ea(s,p)||Ea(r,p)?!0:o?Ea(c,p)||Ea(l,p)||Ea(d,p):!1})}function S4(t){let e=t.startsWith("./")||t.startsWith(".\\")?t.slice(2):t;return kt(e)}function Rp(t,e,n){if(e.length===0)return!1;let i=kt(Wn(n,t)),s=Ip(t),r=kt(t),o=s==="SKILL.md",a=o?Ln(t):void 0,c=o?kt(Wn(n,a)):void 0,l=o?kt(a):void 0;return e.some(d=>{let u=S4(d);return u===i||u===r?!0:o?u===c||u===l:!1})}function C4(t){return t.filter(e=>e.startsWith("!")||e.startsWith("+")||e.startsWith("-"))}function T4(t,e,n){let i=C4(e),s=i.filter(c=>c.startsWith("!")).map(c=>c.slice(1)),r=i.filter(c=>c.startsWith("+")).map(c=>c.slice(1)),o=i.filter(c=>c.startsWith("-")).map(c=>c.slice(1)),a=!0;return s.length>0&&p0(t,s,n)&&(a=!1),r.length>0&&Rp(t,r,n)&&(a=!0),o.length>0&&Rp(t,o,n)&&(a=!1),a}function Mp(t,e,n){let i=[],s=[],r=[],o=[];for(let c of e)c.startsWith("+")?r.push(c.slice(1)):c.startsWith("-")?o.push(c.slice(1)):c.startsWith("!")?s.push(c.slice(1)):i.push(c);let a;if(i.length===0?a=[...t]:a=t.filter(c=>p0(c,i,n)),s.length>0&&(a=a.filter(c=>!p0(c,s,n))),r.length>0)for(let c of t)!a.includes(c)&&Rp(c,r,n)&&a.push(c);return o.length>0&&(a=a.filter(c=>!Rp(c,o,n))),new Set(a)}var Ni=class{constructor(e){this.cwd=e.cwd,this.agentDir=e.agentDir,this.settingsManager=e.settingsManager}setProgressCallback(e){this.progressCallback=e}addSourceToSettings(e,n){let i=n?.local?"project":"user",r=(i==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],o=this.normalizePackageSourceForSettings(e,i);if(r.some(l=>this.packageSourcesMatch(l,e,i)))return!1;let c=[...r,o];return i==="project"?this.settingsManager.setProjectPackages(c):this.settingsManager.setPackages(c),!0}removeSourceFromSettings(e,n){let i=n?.local?"project":"user",r=(i==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],o=r.filter(c=>!this.packageSourcesMatch(c,e,i));return o.length!==r.length?(i==="project"?this.settingsManager.setProjectPackages(o):this.settingsManager.setPackages(o),!0):!1}getInstalledPath(e,n){let i=this.parseSource(e);if(i.type==="npm"){let s=this.getNpmInstallPath(i,n);return xe(s)?s:void 0}if(i.type==="git"){let s=this.getGitInstallPath(i,n);return xe(s)?s:void 0}if(i.type==="local"){let s=this.getBaseDirForScope(n),r=this.resolvePathFromBase(i.path,s);return xe(r)?r:void 0}}emitProgress(e){this.progressCallback?.(e)}async withProgress(e,n,i,s){this.emitProgress({type:"start",action:e,source:n,message:i});try{await s(),this.emitProgress({type:"complete",action:e,source:n})}catch(r){let o=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:e,source:n,message:o}),r}}async resolve(e){let n=this.createAccumulator(),i=this.settingsManager.getGlobalSettings(),s=this.settingsManager.getProjectSettings(),r=[];for(let l of s.packages??[])r.push({pkg:l,scope:"project"});for(let l of i.packages??[])r.push({pkg:l,scope:"user"});let o=this.dedupePackages(r);await this.resolvePackageSources(o,n,e);let a=this.agentDir,c=ge(this.cwd,St);for(let l of Cp){let d=this.getTargetMap(n,l),u=i[l]??[],p=s[l]??[];this.resolveLocalEntries(p,l,d,{source:"local",scope:"project",origin:"top-level"},c),this.resolveLocalEntries(u,l,d,{source:"local",scope:"user",origin:"top-level"},a)}return this.addAutoDiscoveredResources(n,i,s,a,c),this.toResolvedPaths(n)}async resolveExtensionSources(e,n){let i=this.createAccumulator(),s=n?.temporary?"temporary":n?.local?"project":"user",r=e.map(o=>({pkg:o,scope:s}));return await this.resolvePackageSources(r,i),this.toResolvedPaths(i)}listConfiguredPackages(){let e=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),i=[];for(let s of e.packages??[]){let r=typeof s=="string"?s:s.source;i.push({source:r,scope:"user",filtered:typeof s=="object",installedPath:this.getInstalledPath(r,"user")})}for(let s of n.packages??[]){let r=typeof s=="string"?s:s.source;i.push({source:r,scope:"project",filtered:typeof s=="object",installedPath:this.getInstalledPath(r,"project")})}return i}async install(e,n){let i=this.parseSource(e),s=n?.local?"project":"user";await this.withProgress("install",e,`Installing ${e}...`,async()=>{if(i.type==="npm"){await this.installNpm(i,s,!1);return}if(i.type==="git"){await this.installGit(i,s);return}if(i.type==="local"){let r=this.resolvePath(i.path);if(!xe(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${e}`)})}async installAndPersist(e,n){await this.install(e,n),this.addSourceToSettings(e,n)}async remove(e,n){let i=this.parseSource(e),s=n?.local?"project":"user";await this.withProgress("remove",e,`Removing ${e}...`,async()=>{if(i.type==="npm"){await this.uninstallNpm(i,s);return}if(i.type==="git"){await this.removeGit(i,s);return}if(i.type!=="local")throw new Error(`Unsupported remove source: ${e}`)})}async removeAndPersist(e,n){return await this.remove(e,n),this.removeSourceFromSettings(e,n)}async update(e){let n=this.settingsManager.getGlobalSettings(),i=this.settingsManager.getProjectSettings(),s=e?this.getPackageIdentity(e):void 0,r=!1,o=[];for(let a of n.packages??[]){let c=typeof a=="string"?a:a.source;s&&this.getPackageIdentity(c,"user")!==s||(r=!0,o.push({source:c,scope:"user"}))}for(let a of i.packages??[]){let c=typeof a=="string"?a:a.source;s&&this.getPackageIdentity(c,"project")!==s||(r=!0,o.push({source:c,scope:"project"}))}if(e&&!r)throw new Error(this.buildNoMatchingPackageMessage(e,[...n.packages??[],...i.packages??[]]));await this.updateConfiguredSources(o)}async updateConfiguredSources(e){if(kr()||e.length===0)return;let n=[],i=[];for(let l of e){let d=this.parseSource(l.source);if(!(d.type==="local"||d.pinned)){if(d.type==="npm"){n.push({...l,parsed:d});continue}i.push({...l,parsed:d})}}let s=n.map(l=>async()=>({entry:l,shouldUpdate:await this.shouldUpdateNpmSource(l.parsed,l.scope)})),r=await this.runWithConcurrency(s,Wk),o=[],a=[];for(let l of r)l.shouldUpdate&&(l.entry.scope==="user"?o.push(l.entry):a.push(l.entry));let c=[];if(o.length>0&&c.push(this.updateNpmBatch(o,"user")),a.length>0&&c.push(this.updateNpmBatch(a,"project")),i.length>0){let l=i.map(d=>async()=>this.withProgress("update",d.source,`Updating ${d.source}...`,async()=>{await this.updateGit(d.parsed,d.scope)}));c.push(this.runWithConcurrency(l,p4).then(()=>{}))}await Promise.all(c)}async shouldUpdateNpmSource(e,n){let i=this.getManagedNpmInstallPath(e,n),s=xe(i)?this.getInstalledNpmVersion(i):void 0;if(!s)return!0;try{return await this.getLatestNpmVersion(e.name)!==s}catch{return!0}}async updateNpmBatch(e,n){if(e.length===0)return;let i=e.length===1?e[0].source:`${n} npm packages`,s=e.length===1?`Updating ${e[0].source}...`:`Updating ${n} npm packages...`,r=e.map(o=>`${o.parsed.name}@latest`);await this.withProgress("update",i,s,async()=>{await this.installNpmBatch(r,n)})}async installNpmBatch(e,n){let i=this.getNpmInstallRoot(n,!1);this.ensureNpmProject(i),await this.runNpmCommand(this.getNpmInstallArgs(e,i))}async checkForAvailableUpdates(){if(kr())return[];let e=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),i=[];for(let a of n.packages??[])i.push({pkg:a,scope:"project"});for(let a of e.packages??[])i.push({pkg:a,scope:"user"});let r=this.dedupePackages(i).filter(a=>a.scope!=="temporary").map(a=>async()=>{let c=typeof a.pkg=="string"?a.pkg:a.pkg.source,l=this.parseSource(c);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){let p=this.getNpmInstallPath(l,a.scope);return!xe(p)||!await this.npmHasAvailableUpdate(l,p)?void 0:{source:c,displayName:l.name,type:"npm",scope:a.scope}}let d=this.getGitInstallPath(l,a.scope);if(!(!xe(d)||!await this.gitHasAvailableUpdate(d)))return{source:c,displayName:`${l.host}/${l.path}`,type:"git",scope:a.scope}});return(await this.runWithConcurrency(r,Wk)).filter(a=>a!==void 0)}async resolvePackageSources(e,n,i){for(let{pkg:s,scope:r}of e){let o=typeof s=="string"?s:s.source,a=typeof s=="object"?s:void 0,c=this.parseSource(o),l={source:o,scope:r,origin:"package"};if(c.type==="local"){let u=this.getBaseDirForScope(r);this.resolveLocalExtensionSource(c,n,a,l,u);continue}let d=async()=>{if(kr())return!1;if(!i)return await this.installParsedSource(c,r),!0;let u=await i(o);if(u==="skip")return!1;if(u==="error")throw new Error(`Missing source: ${o}`);return await this.installParsedSource(c,r),!0};if(c.type==="npm"){let u=this.getNpmInstallPath(c,r);if(!xe(u)||c.pinned&&!await this.installedNpmMatchesPinnedVersion(c,u)){if(!await d())continue;u=this.getNpmInstallPath(c,r)}l.baseDir=u,this.collectPackageResources(u,n,a,l);continue}if(c.type==="git"){let u=this.getGitInstallPath(c,r);if(xe(u))r==="temporary"&&!c.pinned&&!kr()&&await this.refreshTemporaryGitSource(c,o);else if(!await d())continue;l.baseDir=u,this.collectPackageResources(u,n,a,l)}}}resolveLocalExtensionSource(e,n,i,s,r){let o=this.resolvePathFromBase(e.path,r);if(xe(o))try{let a=Rs(o);if(a.isFile()){s.baseDir=Ln(o),this.addResource(n.extensions,o,s,!0);return}a.isDirectory()&&(s.baseDir=o,this.collectPackageResources(o,n,i,s)||this.addResource(n.extensions,o,s,!0))}catch{return}}async installParsedSource(e,n){if(e.type==="npm"){await this.installNpm(e,n,n==="temporary");return}if(e.type==="git"){await this.installGit(e,n);return}}getPackageSourceString(e){return typeof e=="string"?e:e.source}getSourceMatchKeyForInput(e){let n=this.parseSource(e);return n.type==="npm"?`npm:${n.name}`:n.type==="git"?`git:${n.host}/${n.path}`:`local:${this.resolvePath(n.path)}`}getSourceMatchKeyForSettings(e,n){let i=this.parseSource(e);if(i.type==="npm")return`npm:${i.name}`;if(i.type==="git")return`git:${i.host}/${i.path}`;let s=this.getBaseDirForScope(n);return`local:${this.resolvePathFromBase(i.path,s)}`}buildNoMatchingPackageMessage(e,n){let i=this.findSuggestedConfiguredSource(e,n);return i?`No matching package found for ${e}. Did you mean ${i}?`:`No matching package found for ${e}`}findSuggestedConfiguredSource(e,n){let i=e.trim(),s=new Set;for(let r of n){let o=this.getPackageSourceString(r),a=this.parseSource(o);if(a.type==="npm"){(i===a.name||i===a.spec)&&s.add(o);continue}if(a.type==="git"){let c=`${a.host}/${a.path}`,l=a.ref?`${c}@${a.ref}`:void 0;(i===c||l&&i===l)&&s.add(o)}}return s.values().next().value}packageSourcesMatch(e,n,i){let s=this.getSourceMatchKeyForSettings(this.getPackageSourceString(e),i),r=this.getSourceMatchKeyForInput(n);return s===r}normalizePackageSourceForSettings(e,n){let i=this.parseSource(e);if(i.type!=="local")return e;let s=this.getBaseDirForScope(n),r=this.resolvePath(i.path);return Wn(s,r)||"."}parseSource(e){if(e.startsWith("npm:")){let i=e.slice(4).trim(),{name:s,version:r}=this.parseNpmSpec(i);return{type:"npm",spec:i,name:s,pinned:!!r}}if(tp(e))return{type:"local",path:e};let n=Rl(e);return n||{type:"local",path:e}}async installedNpmMatchesPinnedVersion(e,n){let i=this.getInstalledNpmVersion(n);if(!i)return!1;let{version:s}=this.parseNpmSpec(e.spec);return s?i===s:!0}async npmHasAvailableUpdate(e,n){if(kr())return!1;let i=this.getInstalledNpmVersion(n);if(!i)return!1;try{return await this.getLatestNpmVersion(e.name)!==i}catch{return!1}}getInstalledNpmVersion(e){let n=ge(e,"package.json");if(xe(n))try{let i=Pl(n,"utf-8");return JSON.parse(i).version}catch{return}}async getLatestNpmVersion(e){let n=this.getNpmCommand(),s=(await this.runCommandCapture(n.command,[...n.args,"view",e,"version","--json"],{cwd:this.cwd,timeoutMs:mi})).trim();if(!s)throw new Error("Empty response from npm view");return JSON.parse(s)}async gitHasAvailableUpdate(e){if(kr())return!1;try{let n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:e,timeoutMs:mi}),i=await this.getRemoteGitHead(e);return n.trim()!==i.trim()}catch{return!1}}async getRemoteGitHead(e){let n=await this.getGitUpstreamRef(e);if(n){let o=(await this.runGitRemoteCommand(e,["ls-remote","origin",n])).match(/^([0-9a-f]{40})\s+/m);if(o?.[1])return o[1]}let s=(await this.runGitRemoteCommand(e,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!s?.[1])throw new Error("Failed to determine remote HEAD");return s[1]}async getLocalGitUpdateTarget(e){try{let i=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:e,timeoutMs:mi})).trim();if(!i.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${i}`);let s=i.slice(7);if(!s)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:e,timeoutMs:mi}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:e}).catch(()=>{});let n=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:e,timeoutMs:mi}),s=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:e,timeoutMs:mi}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return s?{ref:"origin/HEAD",head:n,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`]}:{ref:"origin/HEAD",head:n,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(e){try{let i=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:e,timeoutMs:mi})).trim();if(!i.startsWith("origin/"))return;let s=i.slice(7);return s?`refs/heads/${s}`:void 0}catch{return}}runGitRemoteCommand(e,n){return this.runCommandCapture("git",n,{cwd:e,timeoutMs:mi,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(e,n){if(e.length===0)return[];let i=new Array(e.length),s=0,r=Math.max(1,Math.min(n,e.length)),o=async()=>{for(;;){let a=s;if(s+=1,a>=e.length)return;i[a]=await e[a]()}};return await Promise.all(Array.from({length:r},()=>o())),i}getPackageIdentity(e,n){let i=this.parseSource(e);if(i.type==="npm")return`npm:${i.name}`;if(i.type==="git")return`git:${i.host}/${i.path}`;if(n){let s=this.getBaseDirForScope(n);return`local:${this.resolvePathFromBase(i.path,s)}`}return`local:${this.resolvePath(i.path)}`}dedupePackages(e){let n=new Map;for(let i of e){let s=typeof i.pkg=="string"?i.pkg:i.pkg.source,r=this.getPackageIdentity(s,i.scope),o=n.get(r);o?i.scope==="project"&&o.scope==="user"&&n.set(r,i):n.set(r,i)}return Array.from(n.values())}parseNpmSpec(e){let n=e.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!n)return{name:e};let i=n[1]??e,s=n[2];return{name:i,version:s}}getNpmCommand(){let e=this.settingsManager.getNpmCommand();if(!e||e.length===0)return{command:"npm",args:[]};let[n,...i]=e;if(!n)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:n,args:i}}getPackageManagerName(){let e=this.getNpmCommand(),n=[e.command,...e.args],i=n.lastIndexOf("--"),s=i>=0?n[i+1]:e.command;return s?Ip(s).replace(/\.(cmd|exe)$/i,""):""}async runNpmCommand(e,n){let i=this.getNpmCommand();await this.runCommand(i.command,[...i.args,...e],n)}getGitDependencyInstallArgs(){let e=this.settingsManager.getNpmCommand();return e&&e.length>0?["install"]:["install","--omit=dev"]}runNpmCommandSync(e){let n=this.getNpmCommand();return this.runCommandSync(n.command,[...n.args,...e])}getNpmInstallArgs(e,n){let i=this.getPackageManagerName();return i==="bun"?["install",...e,"--cwd",n]:i==="pnpm"?["install",...e,"--prefix",n,"--config.strict-dep-builds=false"]:["install",...e,"--prefix",n]}async installNpm(e,n,i){let s=this.getNpmInstallRoot(n,i);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs([e.spec],s))}async uninstallNpm(e,n){let i=this.getNpmInstallRoot(n,!1);if(xe(i)){if(this.getPackageManagerName()==="bun"){await this.runNpmCommand(["uninstall",e.name,"--cwd",i]);return}await this.runNpmCommand(["uninstall",e.name,"--prefix",i])}}async installGit(e,n){let i=this.getGitInstallPath(e,n);if(xe(i))return;let s=this.getGitInstallRoot(n);s&&this.ensureGitIgnore(s),c0(Ln(i),{recursive:!0}),await this.runCommand("git",["clone",e.repo,i]),e.ref&&await this.runCommand("git",["checkout",e.ref],{cwd:i});let r=ge(i,"package.json");xe(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:i})}async updateGit(e,n){let i=this.getGitInstallPath(e,n);if(!xe(i)){await this.installGit(e,n);return}let s=await this.getLocalGitUpdateTarget(i);await this.runCommand("git",s.fetchArgs,{cwd:i});let r=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:i,timeoutMs:mi}),o=await this.runCommandCapture("git",["rev-parse",s.ref],{cwd:i,timeoutMs:mi});if(r.trim()===o.trim())return;await this.runCommand("git",["reset","--hard",s.ref],{cwd:i}),await this.runCommand("git",["clean","-fdx"],{cwd:i});let a=ge(i,"package.json");xe(a)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:i})}async refreshTemporaryGitSource(e,n){if(!kr())try{await this.withProgress("pull",n,`Refreshing ${n}...`,async()=>{await this.updateGit(e,"temporary")})}catch{}}async removeGit(e,n){let i=this.getGitInstallPath(e,n);xe(i)&&(Ok(i,{recursive:!0,force:!0}),this.pruneEmptyGitParents(i,this.getGitInstallRoot(n)))}pruneEmptyGitParents(e,n){if(!n)return;let i=hi(n),s=Ln(e);for(;s.startsWith(i)&&s!==i;){if(!xe(s)){s=Ln(s);continue}if(Aa(s).length>0)break;try{Ok(s,{recursive:!0,force:!0})}catch{break}s=Ln(s)}}ensureNpmProject(e){xe(e)||c0(e,{recursive:!0}),JT(e),this.ensureGitIgnore(e);let n=ge(e,"package.json");xe(n)||Lk(n,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(e){xe(e)||c0(e,{recursive:!0});let n=ge(e,".gitignore");xe(n)||Lk(n,`*
|
|
283
283
|
!.gitignore
|
|
284
|
-
`,"utf-8")}getNpmInstallRoot(e,n){return n?this.getTemporaryDir("npm"):e==="project"?ge(this.cwd,St,"npm"):ge(this.agentDir,"npm")}getGlobalNpmRoot(){let e=this.getNpmCommand(),n=[e.command,...e.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===n)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){let i=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=ge(Ln(i),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=n,this.globalNpmRoot}getPnpmGlobalPackagePath(e){if(this.getPackageManagerName()!=="pnpm")return;let n=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),i=JSON.parse(n);for(let s of i){let r=s.dependencies?.[e]?.path;if(r)return r}}getManagedNpmInstallPath(e,n){return n==="temporary"?ge(this.getTemporaryDir("npm"),"node_modules",e.name):n==="project"?ge(this.cwd,St,"npm","node_modules",e.name):ge(this.agentDir,"npm","node_modules",e.name)}getLegacyGlobalNpmInstallPath(e){try{return this.getPnpmGlobalPackagePath(e.name)??ge(this.getGlobalNpmRoot(),e.name)}catch{return}}getNpmInstallPath(e,n){let i=this.getManagedNpmInstallPath(e,n);if(n!=="user"||xe(i))return i;let s=this.getLegacyGlobalNpmInstallPath(e);return s&&xe(s)?s:i}getGitInstallPath(e,n){return n==="temporary"?this.getTemporaryDir(`git-${e.host}`,e.path):n==="project"?ge(this.cwd,St,"git",e.host,e.path):ge(this.agentDir,"git",e.host,e.path)}getGitInstallRoot(e){if(e!=="temporary")return e==="project"?ge(this.cwd,St,"git"):ge(this.agentDir,"git")}getTemporaryDir(e,n){let i=a4("sha256").update(`${e}-${n??""}`).digest("hex").slice(0,8);return ge(l4(),"pi-extensions",e,i,n??"")}getBaseDirForScope(e){return e==="project"?ge(this.cwd,St):e==="user"?this.agentDir:this.cwd}resolvePath(e){let n=e.trim();return n==="~"?Mr():n.startsWith("~/")?ge(Mr(),n.slice(2)):n.startsWith("~")?ge(Mr(),n.slice(1)):hi(this.cwd,n)}resolvePathFromBase(e,n){let i=e.trim();return i==="~"?Mr():i.startsWith("~/")?ge(Mr(),i.slice(2)):i.startsWith("~")?ge(Mr(),i.slice(1)):hi(n,i)}collectPackageResources(e,n,i,s){if(i){for(let a of Cp){let c=i[a],l=this.getTargetMap(n,a);c!==void 0?this.applyPackageFilter(e,c,a,l,s):this.collectDefaultResources(e,a,l,s)}return!0}let r=this.readPiManifest(e);if(r){for(let a of Cp){let c=r[a];this.addManifestEntries(c,e,a,this.getTargetMap(n,a),s)}return!0}let o=!1;for(let a of Cp){let c=ge(e,a);if(xe(c)){let l=kp(c,a);for(let d of l)this.addResource(this.getTargetMap(n,a),d,s,!0);o=!0}}return o}collectDefaultResources(e,n,i,s){let o=this.readPiManifest(e)?.[n];if(o){this.addManifestEntries(o,e,n,i,s);return}let a=ge(e,n);if(xe(a)){let c=kp(a,n);for(let l of c)this.addResource(i,l,s,!0)}}applyPackageFilter(e,n,i,s,r){let{allFiles:o}=this.collectManifestFiles(e,i);if(n.length===0){for(let c of o)this.addResource(s,c,r,!1);return}let a=Mp(o,n,e);for(let c of o){let l=a.has(c);this.addResource(s,c,r,l)}}collectManifestFiles(e,n){let s=this.readPiManifest(e)?.[n];if(s&&s.length>0){let a=this.collectFilesFromManifestEntries(s,e,n),c=s.filter(u0),l=c.length>0?Mp(a,c,e):new Set(a);return{allFiles:Array.from(l),enabledByManifest:l}}let r=ge(e,n);if(!xe(r))return{allFiles:[],enabledByManifest:new Set};let o=kp(r,n);return{allFiles:o,enabledByManifest:new Set(o)}}readPiManifest(e){let n=ge(e,"package.json");if(!xe(n))return null;try{let i=Pl(n,"utf-8");return JSON.parse(i).pi??null}catch{return null}}addManifestEntries(e,n,i,s,r){if(!e)return;let o=this.collectFilesFromManifestEntries(e,n,i),a=e.filter(u0),c=Mp(o,a,n);for(let l of o)c.has(l)&&this.addResource(s,l,r,!0)}collectFilesFromManifestEntries(e,n,i){let r=e.filter(o=>!u0(o)).flatMap(o=>b4(o)?d4(o,{cwd:n,absolute:!0,dot:!1,nodir:!1}).map(a=>hi(a)):[hi(n,o)]);return this.collectFilesFromPaths(r,i)}resolveLocalEntries(e,n,i,s,r){if(e.length===0)return;let{plain:o,patterns:a}=x4(e),c=o.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(c,n),d=Mp(l,a,r);for(let u of l)this.addResource(i,u,s,d.has(u))}addAutoDiscoveredResources(e,n,i,s,r){let o={source:"auto",scope:"user",origin:"top-level",baseDir:s},a={source:"auto",scope:"project",origin:"top-level",baseDir:r},c={extensions:n.extensions??[],skills:n.skills??[],prompts:n.prompts??[],themes:n.themes??[]},l={extensions:i.extensions??[],skills:i.skills??[],prompts:i.prompts??[],themes:i.themes??[]},d={extensions:ge(s,"extensions"),skills:ge(s,"skills"),prompts:ge(s,"prompts"),themes:ge(s,"themes")},u={extensions:ge(r,"extensions"),skills:ge(r,"skills"),prompts:ge(r,"prompts"),themes:ge(r,"themes")},p=ge(Mr(),".agents","skills"),m=v4(this.cwd).filter(x=>hi(x)!==hi(p)),g=(x,y,w,P,_)=>{let R=this.getTargetMap(e,x);for(let L of y){let E=T4(L,P,_);this.addResource(R,L,w,E)}};g("extensions",d0(u.extensions),a,l.extensions,r),g("skills",Tp(u.skills,"pi"),a,l.skills,r);for(let x of m){let y=Ln(x),w={...a,baseDir:y};g("skills",Tp(x,"agents"),w,l.skills,y)}g("prompts",Fk(u.prompts),a,l.prompts,r),g("themes",Dk(u.themes),a,l.themes,r),g("extensions",d0(d.extensions),o,c.extensions,s),g("skills",Tp(d.skills,"pi"),o,c.skills,s);let h=Ln(p),f={...o,baseDir:h};g("skills",Tp(p,"agents"),f,c.skills,h),g("prompts",Fk(d.prompts),o,c.prompts,s),g("themes",Dk(d.themes),o,c.themes,s)}collectFilesFromPaths(e,n){let i=[];for(let s of e)if(xe(s))try{let r=Rs(s);r.isFile()?i.push(s):r.isDirectory()&&i.push(...kp(s,n))}catch{}return i}getTargetMap(e,n){switch(n){case"extensions":return e.extensions;case"skills":return e.skills;case"prompts":return e.prompts;case"themes":return e.themes;default:throw new Error(`Unknown resource type: ${n}`)}}addResource(e,n,i,s){n&&(e.has(n)||e.set(n,{metadata:i,enabled:s}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(e){let n=i=>{let s=Array.from(i.entries()).map(([o,{metadata:a,enabled:c}])=>({path:o,enabled:c,metadata:a}));s.sort((o,a)=>Uk(o.metadata)-Uk(a.metadata));let r=new Set;return s.filter(o=>{let a=ya(o.path);return r.has(a)?!1:(r.add(a),!0)})};return{extensions:n(e.extensions),skills:n(e.skills),prompts:n(e.prompts),themes:n(e.themes)}}spawnCommand(e,n,i){let s=l0();return Qu(e,n,{cwd:i?.cwd,stdio:Ak()?["ignore",2,2]:"inherit",env:s})}spawnCaptureCommand(e,n,i){let s=l0(),r=i?.env?{...s,...i.env}:s;return Qu(e,n,{cwd:i?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(e,n,i){return new Promise((s,r)=>{let o=this.spawnCaptureCommand(e,n,i),a="",c="",l=!1,d=typeof i?.timeoutMs=="number"?setTimeout(()=>{l=!0,o.kill()},i.timeoutMs):void 0;o.stdout?.on("data",u=>{a+=u.toString()}),o.stderr?.on("data",u=>{c+=u.toString()}),o.once("error",u=>{d&&clearTimeout(d),r(u)}),o.once("close",(u,p)=>{if(d&&clearTimeout(d),l){r(new Error(`${e} ${n.join(" ")} timed out after ${i?.timeoutMs}ms`));return}if(u===0){s(a.trim());return}let m=u===null?`signal ${p??"unknown"}`:`code ${u}`;r(new Error(`${e} ${n.join(" ")} failed with ${m}: ${c||a}`))})})}runCommand(e,n,i){return new Promise((s,r)=>{let o=this.spawnCommand(e,n,i);o.on("error",r),o.on("exit",a=>{a===0?s():r(new Error(`${e} ${n.join(" ")} failed with code ${a}`))})})}runCommandSync(e,n){let i=l0(),s=zo(e,n,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:i});if(s.error||s.status!==0)throw new Error(`Failed to run ${e} ${n.join(" ")}: ${s.error?.message||s.stderr||s.stdout}`);return(s.stdout||s.stderr||"").trim()}};import pbe from"chalk";import{existsSync as Nk,mkdirSync as k4,readFileSync as M4,writeFileSync as I4}from"fs";import{homedir as jk}from"os";import{dirname as R4,join as g0}from"path";import P4 from"proper-lockfile";import*as Oa from"undici";var h0=3e5,Pp=[{label:"30 sec",timeoutMs:3e4},{label:"1 min",timeoutMs:6e4},{label:"2 min",timeoutMs:12e4},{label:"5 min",timeoutMs:3e5},{label:"disabled",timeoutMs:0}];function _p(t){if(typeof t=="string"){let e=t.trim();return e.toLowerCase()==="disabled"?0:e.length===0?void 0:_p(Number(e))}if(!(typeof t!="number"||!Number.isFinite(t)||t<0))return Math.floor(t)}function Ep(t){let e=Pp.find(n=>n.timeoutMs===t);return e?e.label:`${t/1e3} sec`}function Al(t=h0){let e=_p(t);if(e===void 0)throw new Error(`Invalid HTTP idle timeout: ${String(t)}`);Oa.setGlobalDispatcher(new Oa.EnvHttpProxyAgent({allowH2:!1,bodyTimeout:e,headersTimeout:e})),Oa.install?.()}function Ol(t,e){let n={...t};for(let i of Object.keys(e)){let s=e[i],r=t[i];s!==void 0&&(typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?n[i]={...r,...s}:n[i]=s)}return n}var f0=class{constructor(e,n){this.globalSettingsPath=g0(n,"settings.json"),this.projectSettingsPath=g0(e,St,"settings.json")}acquireLockSyncWithRetry(e){let s;for(let r=1;r<=10;r++)try{return P4.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;s=o;let c=Date.now();for(;Date.now()-c<20;);}throw s??new Error("Failed to acquire settings lock")}withLock(e,n){let i=e==="global"?this.globalSettingsPath:this.projectSettingsPath,s=R4(i),r;try{let o=Nk(i);o&&(r=this.acquireLockSyncWithRetry(i));let a=o?M4(i,"utf-8"):void 0,c=n(a);c!==void 0&&(Nk(s)||k4(s,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(i)),I4(i,c,"utf-8"))}finally{r&&r()}}},b0=class{withLock(e,n){let i=e==="global"?this.global:this.project,s=n(i);s!==void 0&&(e==="global"?this.global=s:this.project=s)}},gi=class t{constructor(e,n,i,s=null,r=null,o=[]){this.modifiedFields=new Set;this.modifiedNestedFields=new Map;this.modifiedProjectFields=new Set;this.modifiedProjectNestedFields=new Map;this.globalSettingsLoadError=null;this.projectSettingsLoadError=null;this.writeQueue=Promise.resolve();this.storage=e,this.globalSettings=n,this.projectSettings=i,this.globalSettingsLoadError=s,this.projectSettingsLoadError=r,this.errors=[...o],this.settings=Ol(this.globalSettings,this.projectSettings)}static create(e,n=Pe()){let i=new f0(e,n);return t.fromStorage(i)}static fromStorage(e){let n=t.tryLoadFromStorage(e,"global"),i=t.tryLoadFromStorage(e,"project"),s=[];return n.error&&s.push({scope:"global",error:n.error}),i.error&&s.push({scope:"project",error:i.error}),new t(e,n.settings,i.settings,n.error,i.error,s)}static inMemory(e={}){let n=new b0,i=t.migrateSettings(structuredClone(e));return n.withLock("global",()=>JSON.stringify(i,null,2)),t.fromStorage(n)}static loadFromStorage(e,n){let i;if(e.withLock(n,r=>{i=r}),!i)return{};let s=JSON.parse(i);return t.migrateSettings(s)}static tryLoadFromStorage(e,n){try{return{settings:t.loadFromStorage(e,n),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){let n=e.skills;n.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=n.enableSkillCommands),Array.isArray(n.customDirectories)&&n.customDirectories.length>0?e.skills=n.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){let n=e.retry,i=typeof n.provider=="object"&&n.provider!==null?n.provider:void 0;typeof n.maxDelayMs=="number"&&(i?.maxRetryDelayMs===void 0||i?.maxRetryDelayMs===null)&&(n.provider={...i??{},maxRetryDelayMs:n.maxDelayMs}),delete n.maxDelayMs}return e}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let e=t.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let n=t.tryLoadFromStorage(this.storage,"project");n.error?(this.projectSettingsLoadError=n.error,this.recordError("project",n.error)):(this.projectSettings=n.settings,this.projectSettingsLoadError=null),this.settings=Ol(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=Ol(this.settings,e)}markModified(e,n){this.modifiedFields.add(e),n&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(n))}markProjectModified(e,n){this.modifiedProjectFields.add(e),n&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(n))}recordError(e,n){let i=n instanceof Error?n:new Error(String(n));this.errors.push({scope:e,error:i})}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,n){this.writeQueue=this.writeQueue.then(()=>{n(),this.clearModifiedScope(e)}).catch(i=>{this.recordError(e,i)})}cloneModifiedNestedFields(e){let n=new Map;for(let[i,s]of e.entries())n.set(i,new Set(s));return n}persistScopedSettings(e,n,i,s){this.storage.withLock(e,r=>{let o=r?t.migrateSettings(JSON.parse(r)):{},a={...o};for(let c of i){let l=n[c];if(s.has(c)&&typeof l=="object"&&l!==null){let d=s.get(c),u=o[c]??{},p=l,m={...u};for(let g of d)m[g]=p[g];a[c]=m}else a[c]=l}return JSON.stringify(a,null,2)})}save(){if(this.settings=Ol(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let e=structuredClone(this.globalSettings),n=new Set(this.modifiedFields),i=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,n,i)})}saveProjectSettings(e){if(this.projectSettings=structuredClone(e),this.settings=Ol(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let n=structuredClone(this.projectSettings),i=new Set(this.modifiedProjectFields),s=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",n,i,s)})}async flush(){await this.writeQueue}drainErrors(){let e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){let e=this.settings.sessionDir;return e&&(e==="~"?jk():e.startsWith("~/")?g0(jk(),e.slice(2)):e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,n){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=n,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getTheme(){return this.settings.theme}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??3,baseDelayMs:this.settings.retry?.baseDelayMs??2e3}}getHttpIdleTimeoutMs(){let e=this.settings.httpIdleTimeoutMs,n=_p(e);if(n!==void 0)return n;if(e!==void 0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);return h0}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}getShellPath(){return this.settings.shellPath}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){let n=structuredClone(this.projectSettings);n.packages=e,this.markProjectModified("packages"),this.saveProjectSettings(n)}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){let n=structuredClone(this.projectSettings);n.extensions=e,this.markProjectModified("extensions"),this.saveProjectSettings(n)}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){let n=structuredClone(this.projectSettings);n.skills=e,this.markProjectModified("skills"),this.saveProjectSettings(n)}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){let n=structuredClone(this.projectSettings);n.prompts=e,this.markProjectModified("prompts"),this.saveProjectSettings(n)}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){let n=structuredClone(this.projectSettings);n.themes=e,this.markProjectModified("themes"),this.saveProjectSettings(n)}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}};import{Agent as exe}from"@earendil-works/pi-agent-core";import y0 from"chalk";import{minimatch as qk}from"minimatch";import kbe from"chalk";var E4=["off","minimal","low","medium","high","xhigh"];function x0(t){return E4.includes(t)}var w0={"amazon-bedrock":"us.anthropic.claude-opus-4-6-v1",anthropic:"claude-opus-4-7",openai:"gpt-5.4","azure-openai-responses":"gpt-5.4","openai-codex":"gpt-5.5",deepseek:"deepseek-v4-pro",google:"gemini-3.1-pro-preview","google-vertex":"gemini-3.1-pro-preview","github-copilot":"gpt-5.4",openrouter:"moonshotai/kimi-k2.6","vercel-ai-gateway":"zai/glm-5.1",xai:"grok-4.20-0309-reasoning",groq:"openai/gpt-oss-120b",cerebras:"zai-glm-4.7",zai:"glm-5.1",mistral:"devstral-medium-latest",minimax:"MiniMax-M2.7","minimax-cn":"MiniMax-M2.7",moonshotai:"kimi-k2.6","moonshotai-cn":"kimi-k2.6",huggingface:"moonshotai/Kimi-K2.6",fireworks:"accounts/fireworks/models/kimi-k2p6",together:"moonshotai/Kimi-K2.6",opencode:"kimi-k2.6","opencode-go":"kimi-k2.6","kimi-coding":"kimi-for-coding","cloudflare-workers-ai":"@cf/moonshotai/kimi-k2.6","cloudflare-ai-gateway":"workers-ai/@cf/moonshotai/kimi-k2.6",xiaomi:"mimo-v2.5-pro","xiaomi-token-plan-cn":"mimo-v2.5-pro","xiaomi-token-plan-ams":"mimo-v2.5-pro","xiaomi-token-plan-sgp":"mimo-v2.5-pro"};function Gk(t){return t.endsWith("-latest")?!0:!/-\d{8}$/.test(t)}function S0(t,e){let n=t.trim();if(!n)return;let i=n.toLowerCase(),s=e.filter(a=>`${a.provider}/${a.id}`.toLowerCase()===i);if(s.length===1)return s[0];if(s.length>1)return;let r=n.indexOf("/");if(r!==-1){let a=n.substring(0,r).trim(),c=n.substring(r+1).trim();if(a&&c){let l=e.filter(d=>d.provider.toLowerCase()===a.toLowerCase()&&d.id.toLowerCase()===c.toLowerCase());if(l.length===1)return l[0];if(l.length>1)return}}let o=e.filter(a=>a.id.toLowerCase()===i);return o.length===1?o[0]:void 0}function A4(t,e){let n=S0(t,e);if(n)return n;let i=e.filter(o=>o.id.toLowerCase().includes(t.toLowerCase())||o.name?.toLowerCase().includes(t.toLowerCase()));if(i.length===0)return;let s=i.filter(o=>Gk(o.id)),r=i.filter(o=>!Gk(o.id));return s.length>0?(s.sort((o,a)=>a.id.localeCompare(o.id)),s[0]):(r.sort((o,a)=>a.id.localeCompare(o.id)),r[0])}function v0(t,e,n){let i=A4(t,e);if(i)return{model:i,thinkingLevel:void 0,warning:void 0};let s=t.lastIndexOf(":");if(s===-1)return{model:void 0,thinkingLevel:void 0,warning:void 0};let r=t.substring(0,s),o=t.substring(s+1);if(x0(o)){let a=v0(r,e,n);return a.model?{model:a.model,thinkingLevel:a.warning?void 0:o,warning:a.warning}:a}else{if(!(n?.allowInvalidThinkingLevelFallback??!0))return{model:void 0,thinkingLevel:void 0,warning:void 0};let c=v0(r,e,n);return c.model?{model:c.model,thinkingLevel:void 0,warning:`Invalid thinking level "${o}" in pattern "${t}". Using default instead.`}:c}}async function Ap(t,e){let n=await e.getAvailable(),i=[];for(let s of t){if(s.includes("*")||s.includes("?")||s.includes("[")){let c=s.lastIndexOf(":"),l=s,d;if(c!==-1){let p=s.substring(c+1);x0(p)&&(d=p,l=s.substring(0,c))}let u=n.filter(p=>{let m=`${p.provider}/${p.id}`;return qk(m,l,{nocase:!0})||qk(p.id,l,{nocase:!0})});if(u.length===0){console.warn(y0.yellow(`Warning: No models match pattern "${s}"`));continue}for(let p of u)i.find(m=>Kn(m.model,p))||i.push({model:p,thinkingLevel:d});continue}let{model:r,thinkingLevel:o,warning:a}=v0(s,n);if(a&&console.warn(y0.yellow(`Warning: ${a}`)),!r){console.warn(y0.yellow(`Warning: No models match pattern "${s}"`));continue}i.find(c=>Kn(c.model,r))||i.push({model:r,thinkingLevel:o})}return i}function O4(t){return t?t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="yes":!1}function C0(t,e=process.env.PI_TELEMETRY){return e!==void 0?O4(e):t.getEnableInstallTelemetry()}var Wbe=process.env.PI_TIMING==="1";var Ube=Date.now();function L4(t){let e=t.sessionFile?`
|
|
284
|
+
`,"utf-8")}getNpmInstallRoot(e,n){return n?this.getTemporaryDir("npm"):e==="project"?ge(this.cwd,St,"npm"):ge(this.agentDir,"npm")}getGlobalNpmRoot(){let e=this.getNpmCommand(),n=[e.command,...e.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===n)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){let i=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=ge(Ln(i),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=n,this.globalNpmRoot}getPnpmGlobalPackagePath(e){if(this.getPackageManagerName()!=="pnpm")return;let n=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),i=JSON.parse(n);for(let s of i){let r=s.dependencies?.[e]?.path;if(r)return r}}getManagedNpmInstallPath(e,n){return n==="temporary"?ge(this.getTemporaryDir("npm"),"node_modules",e.name):n==="project"?ge(this.cwd,St,"npm","node_modules",e.name):ge(this.agentDir,"npm","node_modules",e.name)}getLegacyGlobalNpmInstallPath(e){try{return this.getPnpmGlobalPackagePath(e.name)??ge(this.getGlobalNpmRoot(),e.name)}catch{return}}getNpmInstallPath(e,n){let i=this.getManagedNpmInstallPath(e,n);if(n!=="user"||xe(i))return i;let s=this.getLegacyGlobalNpmInstallPath(e);return s&&xe(s)?s:i}getGitInstallPath(e,n){return n==="temporary"?this.getTemporaryDir(`git-${e.host}`,e.path):n==="project"?ge(this.cwd,St,"git",e.host,e.path):ge(this.agentDir,"git",e.host,e.path)}getGitInstallRoot(e){if(e!=="temporary")return e==="project"?ge(this.cwd,St,"git"):ge(this.agentDir,"git")}getTemporaryDir(e,n){let i=a4("sha256").update(`${e}-${n??""}`).digest("hex").slice(0,8);return ge(l4(),"pi-extensions",e,i,n??"")}getBaseDirForScope(e){return e==="project"?ge(this.cwd,St):e==="user"?this.agentDir:this.cwd}resolvePath(e){let n=e.trim();return n==="~"?Mr():n.startsWith("~/")?ge(Mr(),n.slice(2)):n.startsWith("~")?ge(Mr(),n.slice(1)):hi(this.cwd,n)}resolvePathFromBase(e,n){let i=e.trim();return i==="~"?Mr():i.startsWith("~/")?ge(Mr(),i.slice(2)):i.startsWith("~")?ge(Mr(),i.slice(1)):hi(n,i)}collectPackageResources(e,n,i,s){if(i){for(let a of Cp){let c=i[a],l=this.getTargetMap(n,a);c!==void 0?this.applyPackageFilter(e,c,a,l,s):this.collectDefaultResources(e,a,l,s)}return!0}let r=this.readPiManifest(e);if(r){for(let a of Cp){let c=r[a];this.addManifestEntries(c,e,a,this.getTargetMap(n,a),s)}return!0}let o=!1;for(let a of Cp){let c=ge(e,a);if(xe(c)){let l=kp(c,a);for(let d of l)this.addResource(this.getTargetMap(n,a),d,s,!0);o=!0}}return o}collectDefaultResources(e,n,i,s){let o=this.readPiManifest(e)?.[n];if(o){this.addManifestEntries(o,e,n,i,s);return}let a=ge(e,n);if(xe(a)){let c=kp(a,n);for(let l of c)this.addResource(i,l,s,!0)}}applyPackageFilter(e,n,i,s,r){let{allFiles:o}=this.collectManifestFiles(e,i);if(n.length===0){for(let c of o)this.addResource(s,c,r,!1);return}let a=Mp(o,n,e);for(let c of o){let l=a.has(c);this.addResource(s,c,r,l)}}collectManifestFiles(e,n){let s=this.readPiManifest(e)?.[n];if(s&&s.length>0){let a=this.collectFilesFromManifestEntries(s,e,n),c=s.filter(u0),l=c.length>0?Mp(a,c,e):new Set(a);return{allFiles:Array.from(l),enabledByManifest:l}}let r=ge(e,n);if(!xe(r))return{allFiles:[],enabledByManifest:new Set};let o=kp(r,n);return{allFiles:o,enabledByManifest:new Set(o)}}readPiManifest(e){let n=ge(e,"package.json");if(!xe(n))return null;try{let i=Pl(n,"utf-8");return JSON.parse(i).pi??null}catch{return null}}addManifestEntries(e,n,i,s,r){if(!e)return;let o=this.collectFilesFromManifestEntries(e,n,i),a=e.filter(u0),c=Mp(o,a,n);for(let l of o)c.has(l)&&this.addResource(s,l,r,!0)}collectFilesFromManifestEntries(e,n,i){let r=e.filter(o=>!u0(o)).flatMap(o=>b4(o)?d4(o,{cwd:n,absolute:!0,dot:!1,nodir:!1}).map(a=>hi(a)):[hi(n,o)]);return this.collectFilesFromPaths(r,i)}resolveLocalEntries(e,n,i,s,r){if(e.length===0)return;let{plain:o,patterns:a}=x4(e),c=o.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(c,n),d=Mp(l,a,r);for(let u of l)this.addResource(i,u,s,d.has(u))}addAutoDiscoveredResources(e,n,i,s,r){let o={source:"auto",scope:"user",origin:"top-level",baseDir:s},a={source:"auto",scope:"project",origin:"top-level",baseDir:r},c={extensions:n.extensions??[],skills:n.skills??[],prompts:n.prompts??[],themes:n.themes??[]},l={extensions:i.extensions??[],skills:i.skills??[],prompts:i.prompts??[],themes:i.themes??[]},d={extensions:ge(s,"extensions"),skills:ge(s,"skills"),prompts:ge(s,"prompts"),themes:ge(s,"themes")},u={extensions:ge(r,"extensions"),skills:ge(r,"skills"),prompts:ge(r,"prompts"),themes:ge(r,"themes")},p=ge(Mr(),".agents","skills"),m=v4(this.cwd).filter(x=>hi(x)!==hi(p)),g=(x,y,w,P,_)=>{let R=this.getTargetMap(e,x);for(let L of y){let E=T4(L,P,_);this.addResource(R,L,w,E)}};g("extensions",d0(u.extensions),a,l.extensions,r),g("skills",Tp(u.skills,"pi"),a,l.skills,r);for(let x of m){let y=Ln(x),w={...a,baseDir:y};g("skills",Tp(x,"agents"),w,l.skills,y)}g("prompts",Fk(u.prompts),a,l.prompts,r),g("themes",Dk(u.themes),a,l.themes,r),g("extensions",d0(d.extensions),o,c.extensions,s),g("skills",Tp(d.skills,"pi"),o,c.skills,s);let h=Ln(p),f={...o,baseDir:h};g("skills",Tp(p,"agents"),f,c.skills,h),g("prompts",Fk(d.prompts),o,c.prompts,s),g("themes",Dk(d.themes),o,c.themes,s)}collectFilesFromPaths(e,n){let i=[];for(let s of e)if(xe(s))try{let r=Rs(s);r.isFile()?i.push(s):r.isDirectory()&&i.push(...kp(s,n))}catch{}return i}getTargetMap(e,n){switch(n){case"extensions":return e.extensions;case"skills":return e.skills;case"prompts":return e.prompts;case"themes":return e.themes;default:throw new Error(`Unknown resource type: ${n}`)}}addResource(e,n,i,s){n&&(e.has(n)||e.set(n,{metadata:i,enabled:s}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(e){let n=i=>{let s=Array.from(i.entries()).map(([o,{metadata:a,enabled:c}])=>({path:o,enabled:c,metadata:a}));s.sort((o,a)=>Uk(o.metadata)-Uk(a.metadata));let r=new Set;return s.filter(o=>{let a=ya(o.path);return r.has(a)?!1:(r.add(a),!0)})};return{extensions:n(e.extensions),skills:n(e.skills),prompts:n(e.prompts),themes:n(e.themes)}}spawnCommand(e,n,i){let s=l0();return Qu(e,n,{cwd:i?.cwd,stdio:Ak()?["ignore",2,2]:"inherit",env:s})}spawnCaptureCommand(e,n,i){let s=l0(),r=i?.env?{...s,...i.env}:s;return Qu(e,n,{cwd:i?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(e,n,i){return new Promise((s,r)=>{let o=this.spawnCaptureCommand(e,n,i),a="",c="",l=!1,d=typeof i?.timeoutMs=="number"?setTimeout(()=>{l=!0,o.kill()},i.timeoutMs):void 0;o.stdout?.on("data",u=>{a+=u.toString()}),o.stderr?.on("data",u=>{c+=u.toString()}),o.once("error",u=>{d&&clearTimeout(d),r(u)}),o.once("close",(u,p)=>{if(d&&clearTimeout(d),l){r(new Error(`${e} ${n.join(" ")} timed out after ${i?.timeoutMs}ms`));return}if(u===0){s(a.trim());return}let m=u===null?`signal ${p??"unknown"}`:`code ${u}`;r(new Error(`${e} ${n.join(" ")} failed with ${m}: ${c||a}`))})})}runCommand(e,n,i){return new Promise((s,r)=>{let o=this.spawnCommand(e,n,i);o.on("error",r),o.on("exit",a=>{a===0?s():r(new Error(`${e} ${n.join(" ")} failed with code ${a}`))})})}runCommandSync(e,n){let i=l0(),s=zo(e,n,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:i});if(s.error||s.status!==0)throw new Error(`Failed to run ${e} ${n.join(" ")}: ${s.error?.message||s.stderr||s.stdout}`);return(s.stdout||s.stderr||"").trim()}};import pbe from"chalk";import{existsSync as Nk,mkdirSync as k4,readFileSync as M4,writeFileSync as I4}from"fs";import{homedir as jk}from"os";import{dirname as R4,join as g0}from"path";import P4 from"proper-lockfile";import*as Oa from"undici";var h0=3e5,Pp=[{label:"30 sec",timeoutMs:3e4},{label:"1 min",timeoutMs:6e4},{label:"2 min",timeoutMs:12e4},{label:"5 min",timeoutMs:3e5},{label:"disabled",timeoutMs:0}];function _p(t){if(typeof t=="string"){let e=t.trim();return e.toLowerCase()==="disabled"?0:e.length===0?void 0:_p(Number(e))}if(!(typeof t!="number"||!Number.isFinite(t)||t<0))return Math.floor(t)}function Ep(t){let e=Pp.find(n=>n.timeoutMs===t);return e?e.label:`${t/1e3} sec`}function Al(t=h0){let e=_p(t);if(e===void 0)throw new Error(`Invalid HTTP idle timeout: ${String(t)}`);Oa.setGlobalDispatcher(new Oa.EnvHttpProxyAgent({allowH2:!1,bodyTimeout:e,headersTimeout:e})),Oa.install?.()}function Ol(t,e){let n={...t};for(let i of Object.keys(e)){let s=e[i],r=t[i];s!==void 0&&(typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?n[i]={...r,...s}:n[i]=s)}return n}var f0=class{constructor(e,n){this.globalSettingsPath=g0(n,"settings.json"),this.projectSettingsPath=g0(e,St,"settings.json")}acquireLockSyncWithRetry(e){let s;for(let r=1;r<=10;r++)try{return P4.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;s=o;let c=Date.now();for(;Date.now()-c<20;);}throw s??new Error("Failed to acquire settings lock")}withLock(e,n){let i=e==="global"?this.globalSettingsPath:this.projectSettingsPath,s=R4(i),r;try{let o=Nk(i);o&&(r=this.acquireLockSyncWithRetry(i));let a=o?M4(i,"utf-8"):void 0,c=n(a);c!==void 0&&(Nk(s)||k4(s,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(i)),I4(i,c,"utf-8"))}finally{r&&r()}}},b0=class{withLock(e,n){let i=e==="global"?this.global:this.project,s=n(i);s!==void 0&&(e==="global"?this.global=s:this.project=s)}},gi=class t{constructor(e,n,i,s=null,r=null,o=[]){this.modifiedFields=new Set;this.modifiedNestedFields=new Map;this.modifiedProjectFields=new Set;this.modifiedProjectNestedFields=new Map;this.globalSettingsLoadError=null;this.projectSettingsLoadError=null;this.writeQueue=Promise.resolve();this.storage=e,this.globalSettings=n,this.projectSettings=i,this.globalSettingsLoadError=s,this.projectSettingsLoadError=r,this.errors=[...o],this.settings=Ol(this.globalSettings,this.projectSettings)}static create(e,n=_e()){let i=new f0(e,n);return t.fromStorage(i)}static fromStorage(e){let n=t.tryLoadFromStorage(e,"global"),i=t.tryLoadFromStorage(e,"project"),s=[];return n.error&&s.push({scope:"global",error:n.error}),i.error&&s.push({scope:"project",error:i.error}),new t(e,n.settings,i.settings,n.error,i.error,s)}static inMemory(e={}){let n=new b0,i=t.migrateSettings(structuredClone(e));return n.withLock("global",()=>JSON.stringify(i,null,2)),t.fromStorage(n)}static loadFromStorage(e,n){let i;if(e.withLock(n,r=>{i=r}),!i)return{};let s=JSON.parse(i);return t.migrateSettings(s)}static tryLoadFromStorage(e,n){try{return{settings:t.loadFromStorage(e,n),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){let n=e.skills;n.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=n.enableSkillCommands),Array.isArray(n.customDirectories)&&n.customDirectories.length>0?e.skills=n.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){let n=e.retry,i=typeof n.provider=="object"&&n.provider!==null?n.provider:void 0;typeof n.maxDelayMs=="number"&&(i?.maxRetryDelayMs===void 0||i?.maxRetryDelayMs===null)&&(n.provider={...i??{},maxRetryDelayMs:n.maxDelayMs}),delete n.maxDelayMs}return e}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let e=t.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let n=t.tryLoadFromStorage(this.storage,"project");n.error?(this.projectSettingsLoadError=n.error,this.recordError("project",n.error)):(this.projectSettings=n.settings,this.projectSettingsLoadError=null),this.settings=Ol(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=Ol(this.settings,e)}markModified(e,n){this.modifiedFields.add(e),n&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(n))}markProjectModified(e,n){this.modifiedProjectFields.add(e),n&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(n))}recordError(e,n){let i=n instanceof Error?n:new Error(String(n));this.errors.push({scope:e,error:i})}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,n){this.writeQueue=this.writeQueue.then(()=>{n(),this.clearModifiedScope(e)}).catch(i=>{this.recordError(e,i)})}cloneModifiedNestedFields(e){let n=new Map;for(let[i,s]of e.entries())n.set(i,new Set(s));return n}persistScopedSettings(e,n,i,s){this.storage.withLock(e,r=>{let o=r?t.migrateSettings(JSON.parse(r)):{},a={...o};for(let c of i){let l=n[c];if(s.has(c)&&typeof l=="object"&&l!==null){let d=s.get(c),u=o[c]??{},p=l,m={...u};for(let g of d)m[g]=p[g];a[c]=m}else a[c]=l}return JSON.stringify(a,null,2)})}save(){if(this.settings=Ol(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let e=structuredClone(this.globalSettings),n=new Set(this.modifiedFields),i=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,n,i)})}saveProjectSettings(e){if(this.projectSettings=structuredClone(e),this.settings=Ol(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let n=structuredClone(this.projectSettings),i=new Set(this.modifiedProjectFields),s=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",n,i,s)})}async flush(){await this.writeQueue}drainErrors(){let e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){let e=this.settings.sessionDir;return e&&(e==="~"?jk():e.startsWith("~/")?g0(jk(),e.slice(2)):e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,n){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=n,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getTheme(){return this.settings.theme}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??3,baseDelayMs:this.settings.retry?.baseDelayMs??2e3}}getHttpIdleTimeoutMs(){let e=this.settings.httpIdleTimeoutMs,n=_p(e);if(n!==void 0)return n;if(e!==void 0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);return h0}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}getShellPath(){return this.settings.shellPath}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){let n=structuredClone(this.projectSettings);n.packages=e,this.markProjectModified("packages"),this.saveProjectSettings(n)}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){let n=structuredClone(this.projectSettings);n.extensions=e,this.markProjectModified("extensions"),this.saveProjectSettings(n)}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){let n=structuredClone(this.projectSettings);n.skills=e,this.markProjectModified("skills"),this.saveProjectSettings(n)}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){let n=structuredClone(this.projectSettings);n.prompts=e,this.markProjectModified("prompts"),this.saveProjectSettings(n)}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){let n=structuredClone(this.projectSettings);n.themes=e,this.markProjectModified("themes"),this.saveProjectSettings(n)}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}};import{Agent as exe}from"@earendil-works/pi-agent-core";import y0 from"chalk";import{minimatch as qk}from"minimatch";import kbe from"chalk";var E4=["off","minimal","low","medium","high","xhigh"];function x0(t){return E4.includes(t)}var w0={"amazon-bedrock":"us.anthropic.claude-opus-4-6-v1",anthropic:"claude-opus-4-7",openai:"gpt-5.4","azure-openai-responses":"gpt-5.4","openai-codex":"gpt-5.5",deepseek:"deepseek-v4-pro",google:"gemini-3.1-pro-preview","google-vertex":"gemini-3.1-pro-preview","github-copilot":"gpt-5.4",openrouter:"moonshotai/kimi-k2.6","vercel-ai-gateway":"zai/glm-5.1",xai:"grok-4.20-0309-reasoning",groq:"openai/gpt-oss-120b",cerebras:"zai-glm-4.7",zai:"glm-5.1",mistral:"devstral-medium-latest",minimax:"MiniMax-M2.7","minimax-cn":"MiniMax-M2.7",moonshotai:"kimi-k2.6","moonshotai-cn":"kimi-k2.6",huggingface:"moonshotai/Kimi-K2.6",fireworks:"accounts/fireworks/models/kimi-k2p6",together:"moonshotai/Kimi-K2.6",opencode:"kimi-k2.6","opencode-go":"kimi-k2.6","kimi-coding":"kimi-for-coding","cloudflare-workers-ai":"@cf/moonshotai/kimi-k2.6","cloudflare-ai-gateway":"workers-ai/@cf/moonshotai/kimi-k2.6",xiaomi:"mimo-v2.5-pro","xiaomi-token-plan-cn":"mimo-v2.5-pro","xiaomi-token-plan-ams":"mimo-v2.5-pro","xiaomi-token-plan-sgp":"mimo-v2.5-pro"};function Gk(t){return t.endsWith("-latest")?!0:!/-\d{8}$/.test(t)}function S0(t,e){let n=t.trim();if(!n)return;let i=n.toLowerCase(),s=e.filter(a=>`${a.provider}/${a.id}`.toLowerCase()===i);if(s.length===1)return s[0];if(s.length>1)return;let r=n.indexOf("/");if(r!==-1){let a=n.substring(0,r).trim(),c=n.substring(r+1).trim();if(a&&c){let l=e.filter(d=>d.provider.toLowerCase()===a.toLowerCase()&&d.id.toLowerCase()===c.toLowerCase());if(l.length===1)return l[0];if(l.length>1)return}}let o=e.filter(a=>a.id.toLowerCase()===i);return o.length===1?o[0]:void 0}function A4(t,e){let n=S0(t,e);if(n)return n;let i=e.filter(o=>o.id.toLowerCase().includes(t.toLowerCase())||o.name?.toLowerCase().includes(t.toLowerCase()));if(i.length===0)return;let s=i.filter(o=>Gk(o.id)),r=i.filter(o=>!Gk(o.id));return s.length>0?(s.sort((o,a)=>a.id.localeCompare(o.id)),s[0]):(r.sort((o,a)=>a.id.localeCompare(o.id)),r[0])}function v0(t,e,n){let i=A4(t,e);if(i)return{model:i,thinkingLevel:void 0,warning:void 0};let s=t.lastIndexOf(":");if(s===-1)return{model:void 0,thinkingLevel:void 0,warning:void 0};let r=t.substring(0,s),o=t.substring(s+1);if(x0(o)){let a=v0(r,e,n);return a.model?{model:a.model,thinkingLevel:a.warning?void 0:o,warning:a.warning}:a}else{if(!(n?.allowInvalidThinkingLevelFallback??!0))return{model:void 0,thinkingLevel:void 0,warning:void 0};let c=v0(r,e,n);return c.model?{model:c.model,thinkingLevel:void 0,warning:`Invalid thinking level "${o}" in pattern "${t}". Using default instead.`}:c}}async function Ap(t,e){let n=await e.getAvailable(),i=[];for(let s of t){if(s.includes("*")||s.includes("?")||s.includes("[")){let c=s.lastIndexOf(":"),l=s,d;if(c!==-1){let p=s.substring(c+1);x0(p)&&(d=p,l=s.substring(0,c))}let u=n.filter(p=>{let m=`${p.provider}/${p.id}`;return qk(m,l,{nocase:!0})||qk(p.id,l,{nocase:!0})});if(u.length===0){console.warn(y0.yellow(`Warning: No models match pattern "${s}"`));continue}for(let p of u)i.find(m=>Kn(m.model,p))||i.push({model:p,thinkingLevel:d});continue}let{model:r,thinkingLevel:o,warning:a}=v0(s,n);if(a&&console.warn(y0.yellow(`Warning: ${a}`)),!r){console.warn(y0.yellow(`Warning: No models match pattern "${s}"`));continue}i.find(c=>Kn(c.model,r))||i.push({model:r,thinkingLevel:o})}return i}function O4(t){return t?t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="yes":!1}function C0(t,e=process.env.PI_TELEMETRY){return e!==void 0?O4(e):t.getEnableInstallTelemetry()}var Wbe=process.env.PI_TIMING==="1";var Ube=Date.now();function L4(t){let e=t.sessionFile?`
|
|
285
285
|
Session file: ${t.sessionFile}`:"";return`Stored session working directory does not exist: ${t.sessionCwd}${e}
|
|
286
286
|
Current working directory: ${t.fallbackCwd}`}function T0(t){return`cwd from session file does not exist
|
|
287
287
|
${t.sessionCwd}
|
|
288
288
|
|
|
289
289
|
continue in current cwd
|
|
290
|
-
${t.fallbackCwd}`}var La=class extends Error{constructor(e){super(L4(e)),this.name="MissingSessionCwdError",this.issue=e}};var Op=class extends Error{constructor(e){super(`File not found: ${e}`),this.name="SessionImportFileNotFoundError",this.filePath=e}};import QCe from"chalk";import yxe from"chalk";import Ixe from"chalk";import{existsSync as B4,readFileSync as N4}from"fs";import{join as j4}from"path";var Qk={...ia,"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:process.platform==="win32"?[]:"ctrl+z",description:"Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.tools.expand":{defaultKeys:"ctrl+o",description:"Toggle tool output"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.session.toggleNamedFilter":{defaultKeys:"ctrl+n",description:"Toggle named session filter"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.followUp":{defaultKeys:"alt+enter",description:"Queue follow-up message"},"app.message.dequeue":{defaultKeys:"alt+up",description:"Restore queued messages"},"app.clipboard.pasteImage":{defaultKeys:process.platform==="win32"?"alt+v":"ctrl+v",description:"Paste image from clipboard"},"app.session.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"},"app.tree.foldOrUp":{defaultKeys:["ctrl+left","alt+left"],description:"Fold tree branch or move up"},"app.tree.unfoldOrDown":{defaultKeys:["ctrl+right","alt+right"],description:"Unfold tree branch or move down"},"app.tree.editLabel":{defaultKeys:"shift+l",description:"Edit tree label"},"app.tree.toggleLabelTimestamp":{defaultKeys:"shift+t",description:"Toggle tree label timestamps"},"app.session.togglePath":{defaultKeys:"ctrl+p",description:"Toggle session path display"},"app.session.toggleSort":{defaultKeys:"ctrl+s",description:"Toggle session sort mode"},"app.session.rename":{defaultKeys:"ctrl+r",description:"Rename session"},"app.session.delete":{defaultKeys:"ctrl+d",description:"Delete session"},"app.session.deleteNoninvasive":{defaultKeys:"ctrl+backspace",description:"Delete session when query is empty"},"app.models.save":{defaultKeys:"ctrl+s",description:"Save model selection"},"app.models.enableAll":{defaultKeys:"ctrl+a",description:"Enable all models"},"app.models.clearAll":{defaultKeys:"ctrl+x",description:"Clear all models"},"app.models.toggleProvider":{defaultKeys:"ctrl+p",description:"Toggle all models for provider"},"app.models.reorderUp":{defaultKeys:"alt+up",description:"Move model up in order"},"app.models.reorderDown":{defaultKeys:"alt+down",description:"Move model down in order"},"app.tree.filter.default":{defaultKeys:"ctrl+d",description:"Tree filter: default view"},"app.tree.filter.noTools":{defaultKeys:"ctrl+t",description:"Tree filter: hide tool results"},"app.tree.filter.userOnly":{defaultKeys:"ctrl+u",description:"Tree filter: user messages only"},"app.tree.filter.labeledOnly":{defaultKeys:"ctrl+l",description:"Tree filter: labeled entries only"},"app.tree.filter.all":{defaultKeys:"ctrl+a",description:"Tree filter: show all entries"},"app.tree.filter.cycleForward":{defaultKeys:"ctrl+o",description:"Tree filter: cycle forward"},"app.tree.filter.cycleBackward":{defaultKeys:"shift+ctrl+o",description:"Tree filter: cycle backward"}},Yk={cursorUp:"tui.editor.cursorUp",cursorDown:"tui.editor.cursorDown",cursorLeft:"tui.editor.cursorLeft",cursorRight:"tui.editor.cursorRight",cursorWordLeft:"tui.editor.cursorWordLeft",cursorWordRight:"tui.editor.cursorWordRight",cursorLineStart:"tui.editor.cursorLineStart",cursorLineEnd:"tui.editor.cursorLineEnd",jumpForward:"tui.editor.jumpForward",jumpBackward:"tui.editor.jumpBackward",pageUp:"tui.editor.pageUp",pageDown:"tui.editor.pageDown",deleteCharBackward:"tui.editor.deleteCharBackward",deleteCharForward:"tui.editor.deleteCharForward",deleteWordBackward:"tui.editor.deleteWordBackward",deleteWordForward:"tui.editor.deleteWordForward",deleteToLineStart:"tui.editor.deleteToLineStart",deleteToLineEnd:"tui.editor.deleteToLineEnd",yank:"tui.editor.yank",yankPop:"tui.editor.yankPop",undo:"tui.editor.undo",newLine:"tui.input.newLine",submit:"tui.input.submit",tab:"tui.input.tab",copy:"tui.input.copy",selectUp:"tui.select.up",selectDown:"tui.select.down",selectPageUp:"tui.select.pageUp",selectPageDown:"tui.select.pageDown",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",toggleSessionNamedFilter:"app.session.toggleNamedFilter",externalEditor:"app.editor.external",followUp:"app.message.followUp",dequeue:"app.message.dequeue",pasteImage:"app.clipboard.pasteImage",newSession:"app.session.new",tree:"app.session.tree",fork:"app.session.fork",resume:"app.session.resume",treeFoldOrUp:"app.tree.foldOrUp",treeUnfoldOrDown:"app.tree.unfoldOrDown",treeEditLabel:"app.tree.editLabel",treeToggleLabelTimestamp:"app.tree.toggleLabelTimestamp",toggleSessionPath:"app.session.togglePath",toggleSessionSort:"app.session.toggleSort",renameSession:"app.session.rename",deleteSession:"app.session.delete",deleteSessionNoninvasive:"app.session.deleteNoninvasive"};function Xk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function q4(t){return t in Yk}function G4(t){if(!Xk(t))return{};let e={};for(let[n,i]of Object.entries(t)){if(typeof i=="string"){e[n]=i;continue}Array.isArray(i)&&i.every(s=>typeof s=="string")&&(e[n]=i)}return e}function Zk(t){let e={},n=!1;for(let[i,s]of Object.entries(t)){let r=q4(i)?Yk[i]:i;if(r!==i&&(n=!0),i!==r&&Object.hasOwn(t,r)){n=!0;continue}e[r]=s}return{config:K4(e),migrated:n}}function K4(t){let e={};for(let i of Object.keys(Qk))Object.hasOwn(t,i)&&(e[i]=t[i]);let n=Object.keys(t).filter(i=>!Object.hasOwn(e,i)).sort();for(let i of n)e[i]=t[i];return e}function H4(t){if(B4(t))try{let e=JSON.parse(N4(t,"utf-8"));return Xk(e)?e:void 0}catch{return}}var Ps=class t extends na{constructor(e={},n){super(Qk,e),this.configPath=n}static create(e=Pe()){let n=j4(e,"keybindings.json"),i=t.loadFromFile(n);return new t(i,n)}reload(){this.configPath&&this.setUserBindings(t.loadFromFile(this.configPath))}getEffectiveConfig(){return this.getResolvedBindings()}static loadFromFile(e){let n=H4(e);return n?G4(Zk(n).config):{}}};import{spawnSync as Q4}from"node:child_process";import{existsSync as Y4}from"node:fs";import{unlink as X4}from"node:fs/promises";import*as s1 from"node:os";var V=class{constructor(e=n=>b.fg("border",n)){this.color=e}invalidate(){}render(e){return[this.color("\u2500".repeat(Math.max(1,e)))]}};function e1(t){return t.toLowerCase().replace(/\s+/g," ").trim()}function z4(t){return`${t.id} ${t.name??""} ${t.allMessagesText} ${t.cwd}`}function M0(t){return!!t.name?.trim()}function V4(t,e){return e==="all"?!0:M0(t)}function J4(t){let e=t.trim();if(!e)return{mode:"tokens",tokens:[],regex:null};if(e.startsWith("re:")){let a=e.slice(3).trim();if(!a)return{mode:"regex",tokens:[],regex:null,error:"Empty regex"};try{return{mode:"regex",tokens:[],regex:new RegExp(a,"i")}}catch(c){let l=c instanceof Error?c.message:String(c);return{mode:"regex",tokens:[],regex:null,error:l}}}let n=[],i="",s=!1,r=!1,o=a=>{let c=i.trim();i="",c&&n.push({kind:a,value:c})};for(let a=0;a<e.length;a++){let c=e[a];if(c==='"'){s?(o("phrase"),s=!1):(o("fuzzy"),s=!0);continue}if(!s&&/\s/.test(c)){o("fuzzy");continue}i+=c}return s&&(r=!0),r?{mode:"tokens",tokens:e.split(/\s+/).map(a=>a.trim()).filter(a=>a.length>0).map(a=>({kind:"fuzzy",value:a})),regex:null}:(o(s?"phrase":"fuzzy"),{mode:"tokens",tokens:n,regex:null})}function t1(t,e){let n=z4(t);if(e.mode==="regex"){if(!e.regex)return{matches:!1,score:0};let r=n.search(e.regex);return r<0?{matches:!1,score:0}:{matches:!0,score:r*.1}}if(e.tokens.length===0)return{matches:!0,score:0};let i=0,s=null;for(let r of e.tokens){if(r.kind==="phrase"){s===null&&(s=e1(n));let a=e1(r.value);if(!a)continue;let c=s.indexOf(a);if(c<0)return{matches:!1,score:0};i+=c*.1;continue}let o=Td(r.value,n);if(!o.matches)return{matches:!1,score:0};i+=o.score}return{matches:!0,score:i}}function n1(t,e,n,i="all"){let s=i==="all"?t:t.filter(c=>V4(c,i));if(!e.trim())return s;let o=J4(e);if(o.error)return[];if(n==="recent"){let c=[];for(let l of s)t1(l,o).matches&&c.push(l);return c}let a=[];for(let c of s){let l=t1(c,o);l.matches&&a.push({session:c,score:l.score})}return a.sort((c,l)=>c.score!==l.score?c.score-l.score:l.session.modified.getTime()-c.session.modified.getTime()),a.map(c=>c.session)}function i1(t){let e=s1.homedir();return t&&(t.startsWith(e)?`~${t.slice(e.length)}`:t)}function Z4(t){let n=new Date().getTime()-t.getTime(),i=Math.floor(n/6e4),s=Math.floor(n/36e5),r=Math.floor(n/864e5);return i<1?"now":i<60?`${i}m`:s<24?`${s}h`:r<7?`${r}d`:r<30?`${Math.floor(r/7)}w`:r<365?`${Math.floor(r/30)}mo`:`${Math.floor(r/365)}y`}function Ll(t){return t&&ya(t)}var I0=class{constructor(e,n,i,s){this.loading=!1;this.loadProgress=null;this.showPath=!1;this.confirmingDeletePath=null;this.statusMessage=null;this.statusTimeout=null;this.showRenameHint=!1;this.scope=e,this.sortMode=n,this.nameFilter=i,this.requestRender=s}setScope(e){this.scope=e}setSortMode(e){this.sortMode=e}setNameFilter(e){this.nameFilter=e}setLoading(e){this.loading=e,this.loadProgress=null}setProgress(e,n){this.loadProgress={loaded:e,total:n}}setShowPath(e){this.showPath=e}setShowRenameHint(e){this.showRenameHint=e}setConfirmingDeletePath(e){this.confirmingDeletePath=e}clearStatusTimeout(){this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null)}setStatusMessage(e,n){this.clearStatusTimeout(),this.statusMessage=e,!(!e||!n)&&(this.statusTimeout=setTimeout(()=>{this.statusMessage=null,this.statusTimeout=null,this.requestRender()},n))}invalidate(){}render(e){let n=this.scope==="current"?"Resume Session (Current Folder)":"Resume Session (All)",i=b.bold(n),s=this.sortMode==="threaded"?"Threaded":this.sortMode==="recent"?"Recent":"Fuzzy",r=b.fg("muted","Sort: ")+b.fg("accent",s),o=this.nameFilter==="all"?"All":"Named",a=b.fg("muted","Name: ")+b.fg("accent",o),c;if(this.loading){let h=this.loadProgress?`${this.loadProgress.loaded}/${this.loadProgress.total}`:"...";c=`${b.fg("muted","\u25CB Current Folder | ")}${b.fg("accent",`Loading ${h}`)}`}else this.scope==="current"?c=`${b.fg("accent","\u25C9 Current Folder")}${b.fg("muted"," | \u25CB All")}`:c=`${b.fg("muted","\u25CB Current Folder | ")}${b.fg("accent","\u25C9 All")}`;let l=X(`${c} ${a} ${r}`,e,""),d=Math.max(0,e-j(l)-1),u=X(i,d,""),p=Math.max(0,e-j(u)-j(l)),m,g;if(this.confirmingDeletePath!==null){let h=`Delete session? ${ce("tui.select.confirm","confirm")} \xB7 ${ce("tui.select.cancel","cancel")}`;m=b.fg("error",X(h,e,"\u2026")),g=""}else if(this.statusMessage){let h=this.statusMessage.type==="error"?"error":"accent";m=b.fg(h,X(this.statusMessage.message,e,"\u2026")),g=""}else{let h=this.showPath?"(on)":"(off)",f=b.fg("muted"," \xB7 "),x=ce("tui.input.tab","scope")+f+b.fg("muted",'re:<pattern> regex \xB7 "phrase" exact'),y=[ce("app.session.toggleSort","sort"),ce("app.session.toggleNamedFilter","named"),ce("app.session.delete","delete"),ce("app.session.togglePath",`path ${h}`)];this.showRenameHint&&y.push(ce("app.session.rename","rename"));let w=y.join(f);m=X(x,e,"\u2026"),g=X(w,e,"\u2026")}return[`${u}${" ".repeat(p)}${l}`,m,g]}};function e$(t){let e=new Map;for(let s of t){let r=Ll(s.path)??s.path;e.set(r,{session:s,children:[]})}let n=[];for(let s of t){let r=Ll(s.path)??s.path,o=e.get(r),a=Ll(s.parentSessionPath);a&&e.has(a)?e.get(a).children.push(o):n.push(o)}let i=s=>{s.sort((r,o)=>o.session.modified.getTime()-r.session.modified.getTime());for(let r of s)i(r.children)};return i(n),n}function t$(t){let e=[],n=(i,s,r,o)=>{e.push({session:i.session,depth:s,isLast:o,ancestorContinues:r});for(let a=0;a<i.children.length;a++){let c=a===i.children.length-1,l=s>0?!o:!1;n(i.children[a],s+1,[...r,l],c)}};for(let i=0;i<t.length;i++)n(t[i],0,[],i===t.length-1);return e}var R0=class{constructor(e,n,i,s,r,o){this.allSessions=[];this.filteredSessions=[];this.selectedIndex=0;this.showCwd=!1;this.sortMode="threaded";this.nameFilter="all";this.showPath=!1;this.confirmingDeletePath=null;this.onExit=()=>{};this.maxVisible=10;this._focused=!1;this.allSessions=e,this.filteredSessions=[],this.searchInput=new Qe,this.showCwd=n,this.sortMode=i,this.nameFilter=s,this.keybindings=r,this.currentSessionCanonicalPath=Ll(o),this.filterSessions(""),this.searchInput.onSubmit=()=>{if(this.filteredSessions[this.selectedIndex]){let a=this.filteredSessions[this.selectedIndex];this.onSelect&&this.onSelect(a.session.path)}}}getSelectedSessionPath(){return this.filteredSessions[this.selectedIndex]?.session.path}get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}setSortMode(e){this.sortMode=e,this.filterSessions(this.searchInput.getValue())}setNameFilter(e){this.nameFilter=e,this.filterSessions(this.searchInput.getValue())}setSessions(e,n){this.allSessions=e,this.showCwd=n,this.filterSessions(this.searchInput.getValue())}filterSessions(e){let n=e.trim(),i=this.nameFilter==="all"?this.allSessions:this.allSessions.filter(s=>M0(s));if(this.sortMode==="threaded"&&!n){let s=e$(i);this.filteredSessions=t$(s)}else{let s=n1(i,e,this.sortMode,"all");this.filteredSessions=s.map(r=>({session:r,depth:0,isLast:!0,ancestorContinues:[]}))}this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredSessions.length-1))}setConfirmingDeletePath(e){this.confirmingDeletePath=e,this.onDeleteConfirmationChange?.(e)}startDeleteConfirmationForSelectedSession(){let e=this.filteredSessions[this.selectedIndex];if(e){if(this.isCurrentSessionPath(e.session.path)){this.onError?.("Cannot delete the currently active session");return}this.setConfirmingDeletePath(e.session.path)}}isCurrentSessionPath(e){return this.currentSessionCanonicalPath?(Ll(e)??e)===this.currentSessionCanonicalPath:!1}invalidate(){}render(e){let n=[];if(n.push(...this.searchInput.render(e)),n.push(""),this.filteredSessions.length===0){let r;if(this.nameFilter==="named"){let o=he("app.session.toggleNamedFilter");this.showCwd?r=` No named sessions found. Press ${o} to show all.`:r=` No named sessions in current folder. Press ${o} to show all, or Tab to view all.`}else this.showCwd?r=" No sessions found":r=" No sessions in current folder. Press Tab to view all.";return n.push(b.fg("muted",X(r,e,"\u2026"))),n}let i=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredSessions.length-this.maxVisible)),s=Math.min(i+this.maxVisible,this.filteredSessions.length);for(let r=i;r<s;r++){let o=this.filteredSessions[r],a=o.session,c=r===this.selectedIndex,l=a.path===this.confirmingDeletePath,d=this.isCurrentSessionPath(a.path),u=this.buildTreePrefix(o),p=!!a.name,g=(a.name??a.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),h=Z4(a.modified),x=`${String(a.messageCount)} ${h}`;this.showCwd&&a.cwd&&(x=`${i1(a.cwd)} ${x}`),this.showPath&&(x=`${i1(a.path)} ${x}`);let y=c?b.fg("accent","\u203A "):" ",w=j(u),P=j(x)+2,_=e-2-w-P,R=X(g,Math.max(10,_),"\u2026"),L=null;l?L="error":d?L="accent":p&&(L="warning");let E=L?b.fg(L,R):R;c&&(E=b.bold(E));let W=y+b.fg("dim",u)+E,M=j(W),I=Math.max(1,e-M-j(x)),O=b.fg(l?"error":"dim",x),F=W+" ".repeat(I)+O;c&&(F=b.bg("selectedBg",F)),n.push(X(F,e))}if(i>0||s<this.filteredSessions.length){let r=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,o=b.fg("muted",X(r,e,""));n.push(o)}return n}buildTreePrefix(e){if(e.depth===0)return"";let n=e.ancestorContinues.map(s=>s?"\u2502 ":" "),i=e.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return n.join("")+i}handleInput(e){let n=ve();if(this.confirmingDeletePath!==null){if(n.matches(e,"tui.select.confirm")){let i=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(i);return}if(n.matches(e,"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(n.matches(e,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(n.matches(e,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(e,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(n.matches(e,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(n.matches(e,"app.session.delete")){this.startDeleteConfirmationForSelectedSession();return}if(n.matches(e,"app.session.rename")){let i=this.filteredSessions[this.selectedIndex];i&&this.onRenameSession?.(i.session.path);return}if(n.matches(e,"app.session.deleteNoninvasive")){if(this.searchInput.getValue().length>0){this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue());return}this.startDeleteConfirmationForSelectedSession();return}if(n.matches(e,"tui.select.up"))this.selectedIndex=Math.max(0,this.selectedIndex-1);else if(n.matches(e,"tui.select.down"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+1);else if(n.matches(e,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisible);else if(n.matches(e,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+this.maxVisible);else if(n.matches(e,"tui.select.confirm")){let i=this.filteredSessions[this.selectedIndex];i&&this.onSelect&&this.onSelect(i.session.path)}else n.matches(e,"tui.select.cancel")?this.onCancel&&this.onCancel():(this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue()))}};async function n$(t){let e=t.startsWith("-")?["--",t]:[t],n=Q4("trash",e,{encoding:"utf-8"}),i=()=>{let s=[];n.error&&s.push(n.error.message);let r=n.stderr?.trim();return r&&s.push(r.split(`
|
|
290
|
+
${t.fallbackCwd}`}var La=class extends Error{constructor(e){super(L4(e)),this.name="MissingSessionCwdError",this.issue=e}};var Op=class extends Error{constructor(e){super(`File not found: ${e}`),this.name="SessionImportFileNotFoundError",this.filePath=e}};import QCe from"chalk";import yxe from"chalk";import Ixe from"chalk";import{existsSync as B4,readFileSync as N4}from"fs";import{join as j4}from"path";var Qk={...ia,"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:process.platform==="win32"?[]:"ctrl+z",description:"Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.tools.expand":{defaultKeys:"ctrl+o",description:"Toggle tool output"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.session.toggleNamedFilter":{defaultKeys:"ctrl+n",description:"Toggle named session filter"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.followUp":{defaultKeys:"alt+enter",description:"Queue follow-up message"},"app.message.dequeue":{defaultKeys:"alt+up",description:"Restore queued messages"},"app.clipboard.pasteImage":{defaultKeys:process.platform==="win32"?"alt+v":"ctrl+v",description:"Paste image from clipboard"},"app.session.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"},"app.tree.foldOrUp":{defaultKeys:["ctrl+left","alt+left"],description:"Fold tree branch or move up"},"app.tree.unfoldOrDown":{defaultKeys:["ctrl+right","alt+right"],description:"Unfold tree branch or move down"},"app.tree.editLabel":{defaultKeys:"shift+l",description:"Edit tree label"},"app.tree.toggleLabelTimestamp":{defaultKeys:"shift+t",description:"Toggle tree label timestamps"},"app.session.togglePath":{defaultKeys:"ctrl+p",description:"Toggle session path display"},"app.session.toggleSort":{defaultKeys:"ctrl+s",description:"Toggle session sort mode"},"app.session.rename":{defaultKeys:"ctrl+r",description:"Rename session"},"app.session.delete":{defaultKeys:"ctrl+d",description:"Delete session"},"app.session.deleteNoninvasive":{defaultKeys:"ctrl+backspace",description:"Delete session when query is empty"},"app.models.save":{defaultKeys:"ctrl+s",description:"Save model selection"},"app.models.enableAll":{defaultKeys:"ctrl+a",description:"Enable all models"},"app.models.clearAll":{defaultKeys:"ctrl+x",description:"Clear all models"},"app.models.toggleProvider":{defaultKeys:"ctrl+p",description:"Toggle all models for provider"},"app.models.reorderUp":{defaultKeys:"alt+up",description:"Move model up in order"},"app.models.reorderDown":{defaultKeys:"alt+down",description:"Move model down in order"},"app.tree.filter.default":{defaultKeys:"ctrl+d",description:"Tree filter: default view"},"app.tree.filter.noTools":{defaultKeys:"ctrl+t",description:"Tree filter: hide tool results"},"app.tree.filter.userOnly":{defaultKeys:"ctrl+u",description:"Tree filter: user messages only"},"app.tree.filter.labeledOnly":{defaultKeys:"ctrl+l",description:"Tree filter: labeled entries only"},"app.tree.filter.all":{defaultKeys:"ctrl+a",description:"Tree filter: show all entries"},"app.tree.filter.cycleForward":{defaultKeys:"ctrl+o",description:"Tree filter: cycle forward"},"app.tree.filter.cycleBackward":{defaultKeys:"shift+ctrl+o",description:"Tree filter: cycle backward"}},Yk={cursorUp:"tui.editor.cursorUp",cursorDown:"tui.editor.cursorDown",cursorLeft:"tui.editor.cursorLeft",cursorRight:"tui.editor.cursorRight",cursorWordLeft:"tui.editor.cursorWordLeft",cursorWordRight:"tui.editor.cursorWordRight",cursorLineStart:"tui.editor.cursorLineStart",cursorLineEnd:"tui.editor.cursorLineEnd",jumpForward:"tui.editor.jumpForward",jumpBackward:"tui.editor.jumpBackward",pageUp:"tui.editor.pageUp",pageDown:"tui.editor.pageDown",deleteCharBackward:"tui.editor.deleteCharBackward",deleteCharForward:"tui.editor.deleteCharForward",deleteWordBackward:"tui.editor.deleteWordBackward",deleteWordForward:"tui.editor.deleteWordForward",deleteToLineStart:"tui.editor.deleteToLineStart",deleteToLineEnd:"tui.editor.deleteToLineEnd",yank:"tui.editor.yank",yankPop:"tui.editor.yankPop",undo:"tui.editor.undo",newLine:"tui.input.newLine",submit:"tui.input.submit",tab:"tui.input.tab",copy:"tui.input.copy",selectUp:"tui.select.up",selectDown:"tui.select.down",selectPageUp:"tui.select.pageUp",selectPageDown:"tui.select.pageDown",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",toggleSessionNamedFilter:"app.session.toggleNamedFilter",externalEditor:"app.editor.external",followUp:"app.message.followUp",dequeue:"app.message.dequeue",pasteImage:"app.clipboard.pasteImage",newSession:"app.session.new",tree:"app.session.tree",fork:"app.session.fork",resume:"app.session.resume",treeFoldOrUp:"app.tree.foldOrUp",treeUnfoldOrDown:"app.tree.unfoldOrDown",treeEditLabel:"app.tree.editLabel",treeToggleLabelTimestamp:"app.tree.toggleLabelTimestamp",toggleSessionPath:"app.session.togglePath",toggleSessionSort:"app.session.toggleSort",renameSession:"app.session.rename",deleteSession:"app.session.delete",deleteSessionNoninvasive:"app.session.deleteNoninvasive"};function Xk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function q4(t){return t in Yk}function G4(t){if(!Xk(t))return{};let e={};for(let[n,i]of Object.entries(t)){if(typeof i=="string"){e[n]=i;continue}Array.isArray(i)&&i.every(s=>typeof s=="string")&&(e[n]=i)}return e}function Zk(t){let e={},n=!1;for(let[i,s]of Object.entries(t)){let r=q4(i)?Yk[i]:i;if(r!==i&&(n=!0),i!==r&&Object.hasOwn(t,r)){n=!0;continue}e[r]=s}return{config:K4(e),migrated:n}}function K4(t){let e={};for(let i of Object.keys(Qk))Object.hasOwn(t,i)&&(e[i]=t[i]);let n=Object.keys(t).filter(i=>!Object.hasOwn(e,i)).sort();for(let i of n)e[i]=t[i];return e}function H4(t){if(B4(t))try{let e=JSON.parse(N4(t,"utf-8"));return Xk(e)?e:void 0}catch{return}}var Ps=class t extends na{constructor(e={},n){super(Qk,e),this.configPath=n}static create(e=_e()){let n=j4(e,"keybindings.json"),i=t.loadFromFile(n);return new t(i,n)}reload(){this.configPath&&this.setUserBindings(t.loadFromFile(this.configPath))}getEffectiveConfig(){return this.getResolvedBindings()}static loadFromFile(e){let n=H4(e);return n?G4(Zk(n).config):{}}};import{spawnSync as Q4}from"node:child_process";import{existsSync as Y4}from"node:fs";import{unlink as X4}from"node:fs/promises";import*as s1 from"node:os";var V=class{constructor(e=n=>b.fg("border",n)){this.color=e}invalidate(){}render(e){return[this.color("\u2500".repeat(Math.max(1,e)))]}};function e1(t){return t.toLowerCase().replace(/\s+/g," ").trim()}function z4(t){return`${t.id} ${t.name??""} ${t.allMessagesText} ${t.cwd}`}function M0(t){return!!t.name?.trim()}function V4(t,e){return e==="all"?!0:M0(t)}function J4(t){let e=t.trim();if(!e)return{mode:"tokens",tokens:[],regex:null};if(e.startsWith("re:")){let a=e.slice(3).trim();if(!a)return{mode:"regex",tokens:[],regex:null,error:"Empty regex"};try{return{mode:"regex",tokens:[],regex:new RegExp(a,"i")}}catch(c){let l=c instanceof Error?c.message:String(c);return{mode:"regex",tokens:[],regex:null,error:l}}}let n=[],i="",s=!1,r=!1,o=a=>{let c=i.trim();i="",c&&n.push({kind:a,value:c})};for(let a=0;a<e.length;a++){let c=e[a];if(c==='"'){s?(o("phrase"),s=!1):(o("fuzzy"),s=!0);continue}if(!s&&/\s/.test(c)){o("fuzzy");continue}i+=c}return s&&(r=!0),r?{mode:"tokens",tokens:e.split(/\s+/).map(a=>a.trim()).filter(a=>a.length>0).map(a=>({kind:"fuzzy",value:a})),regex:null}:(o(s?"phrase":"fuzzy"),{mode:"tokens",tokens:n,regex:null})}function t1(t,e){let n=z4(t);if(e.mode==="regex"){if(!e.regex)return{matches:!1,score:0};let r=n.search(e.regex);return r<0?{matches:!1,score:0}:{matches:!0,score:r*.1}}if(e.tokens.length===0)return{matches:!0,score:0};let i=0,s=null;for(let r of e.tokens){if(r.kind==="phrase"){s===null&&(s=e1(n));let a=e1(r.value);if(!a)continue;let c=s.indexOf(a);if(c<0)return{matches:!1,score:0};i+=c*.1;continue}let o=Td(r.value,n);if(!o.matches)return{matches:!1,score:0};i+=o.score}return{matches:!0,score:i}}function n1(t,e,n,i="all"){let s=i==="all"?t:t.filter(c=>V4(c,i));if(!e.trim())return s;let o=J4(e);if(o.error)return[];if(n==="recent"){let c=[];for(let l of s)t1(l,o).matches&&c.push(l);return c}let a=[];for(let c of s){let l=t1(c,o);l.matches&&a.push({session:c,score:l.score})}return a.sort((c,l)=>c.score!==l.score?c.score-l.score:l.session.modified.getTime()-c.session.modified.getTime()),a.map(c=>c.session)}function i1(t){let e=s1.homedir();return t&&(t.startsWith(e)?`~${t.slice(e.length)}`:t)}function Z4(t){let n=new Date().getTime()-t.getTime(),i=Math.floor(n/6e4),s=Math.floor(n/36e5),r=Math.floor(n/864e5);return i<1?"now":i<60?`${i}m`:s<24?`${s}h`:r<7?`${r}d`:r<30?`${Math.floor(r/7)}w`:r<365?`${Math.floor(r/30)}mo`:`${Math.floor(r/365)}y`}function Ll(t){return t&&ya(t)}var I0=class{constructor(e,n,i,s){this.loading=!1;this.loadProgress=null;this.showPath=!1;this.confirmingDeletePath=null;this.statusMessage=null;this.statusTimeout=null;this.showRenameHint=!1;this.scope=e,this.sortMode=n,this.nameFilter=i,this.requestRender=s}setScope(e){this.scope=e}setSortMode(e){this.sortMode=e}setNameFilter(e){this.nameFilter=e}setLoading(e){this.loading=e,this.loadProgress=null}setProgress(e,n){this.loadProgress={loaded:e,total:n}}setShowPath(e){this.showPath=e}setShowRenameHint(e){this.showRenameHint=e}setConfirmingDeletePath(e){this.confirmingDeletePath=e}clearStatusTimeout(){this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null)}setStatusMessage(e,n){this.clearStatusTimeout(),this.statusMessage=e,!(!e||!n)&&(this.statusTimeout=setTimeout(()=>{this.statusMessage=null,this.statusTimeout=null,this.requestRender()},n))}invalidate(){}render(e){let n=this.scope==="current"?"Resume Session (Current Folder)":"Resume Session (All)",i=b.bold(n),s=this.sortMode==="threaded"?"Threaded":this.sortMode==="recent"?"Recent":"Fuzzy",r=b.fg("muted","Sort: ")+b.fg("accent",s),o=this.nameFilter==="all"?"All":"Named",a=b.fg("muted","Name: ")+b.fg("accent",o),c;if(this.loading){let h=this.loadProgress?`${this.loadProgress.loaded}/${this.loadProgress.total}`:"...";c=`${b.fg("muted","\u25CB Current Folder | ")}${b.fg("accent",`Loading ${h}`)}`}else this.scope==="current"?c=`${b.fg("accent","\u25C9 Current Folder")}${b.fg("muted"," | \u25CB All")}`:c=`${b.fg("muted","\u25CB Current Folder | ")}${b.fg("accent","\u25C9 All")}`;let l=X(`${c} ${a} ${r}`,e,""),d=Math.max(0,e-j(l)-1),u=X(i,d,""),p=Math.max(0,e-j(u)-j(l)),m,g;if(this.confirmingDeletePath!==null){let h=`Delete session? ${ce("tui.select.confirm","confirm")} \xB7 ${ce("tui.select.cancel","cancel")}`;m=b.fg("error",X(h,e,"\u2026")),g=""}else if(this.statusMessage){let h=this.statusMessage.type==="error"?"error":"accent";m=b.fg(h,X(this.statusMessage.message,e,"\u2026")),g=""}else{let h=this.showPath?"(on)":"(off)",f=b.fg("muted"," \xB7 "),x=ce("tui.input.tab","scope")+f+b.fg("muted",'re:<pattern> regex \xB7 "phrase" exact'),y=[ce("app.session.toggleSort","sort"),ce("app.session.toggleNamedFilter","named"),ce("app.session.delete","delete"),ce("app.session.togglePath",`path ${h}`)];this.showRenameHint&&y.push(ce("app.session.rename","rename"));let w=y.join(f);m=X(x,e,"\u2026"),g=X(w,e,"\u2026")}return[`${u}${" ".repeat(p)}${l}`,m,g]}};function e$(t){let e=new Map;for(let s of t){let r=Ll(s.path)??s.path;e.set(r,{session:s,children:[]})}let n=[];for(let s of t){let r=Ll(s.path)??s.path,o=e.get(r),a=Ll(s.parentSessionPath);a&&e.has(a)?e.get(a).children.push(o):n.push(o)}let i=s=>{s.sort((r,o)=>o.session.modified.getTime()-r.session.modified.getTime());for(let r of s)i(r.children)};return i(n),n}function t$(t){let e=[],n=(i,s,r,o)=>{e.push({session:i.session,depth:s,isLast:o,ancestorContinues:r});for(let a=0;a<i.children.length;a++){let c=a===i.children.length-1,l=s>0?!o:!1;n(i.children[a],s+1,[...r,l],c)}};for(let i=0;i<t.length;i++)n(t[i],0,[],i===t.length-1);return e}var R0=class{constructor(e,n,i,s,r,o){this.allSessions=[];this.filteredSessions=[];this.selectedIndex=0;this.showCwd=!1;this.sortMode="threaded";this.nameFilter="all";this.showPath=!1;this.confirmingDeletePath=null;this.onExit=()=>{};this.maxVisible=10;this._focused=!1;this.allSessions=e,this.filteredSessions=[],this.searchInput=new Qe,this.showCwd=n,this.sortMode=i,this.nameFilter=s,this.keybindings=r,this.currentSessionCanonicalPath=Ll(o),this.filterSessions(""),this.searchInput.onSubmit=()=>{if(this.filteredSessions[this.selectedIndex]){let a=this.filteredSessions[this.selectedIndex];this.onSelect&&this.onSelect(a.session.path)}}}getSelectedSessionPath(){return this.filteredSessions[this.selectedIndex]?.session.path}get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}setSortMode(e){this.sortMode=e,this.filterSessions(this.searchInput.getValue())}setNameFilter(e){this.nameFilter=e,this.filterSessions(this.searchInput.getValue())}setSessions(e,n){this.allSessions=e,this.showCwd=n,this.filterSessions(this.searchInput.getValue())}filterSessions(e){let n=e.trim(),i=this.nameFilter==="all"?this.allSessions:this.allSessions.filter(s=>M0(s));if(this.sortMode==="threaded"&&!n){let s=e$(i);this.filteredSessions=t$(s)}else{let s=n1(i,e,this.sortMode,"all");this.filteredSessions=s.map(r=>({session:r,depth:0,isLast:!0,ancestorContinues:[]}))}this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredSessions.length-1))}setConfirmingDeletePath(e){this.confirmingDeletePath=e,this.onDeleteConfirmationChange?.(e)}startDeleteConfirmationForSelectedSession(){let e=this.filteredSessions[this.selectedIndex];if(e){if(this.isCurrentSessionPath(e.session.path)){this.onError?.("Cannot delete the currently active session");return}this.setConfirmingDeletePath(e.session.path)}}isCurrentSessionPath(e){return this.currentSessionCanonicalPath?(Ll(e)??e)===this.currentSessionCanonicalPath:!1}invalidate(){}render(e){let n=[];if(n.push(...this.searchInput.render(e)),n.push(""),this.filteredSessions.length===0){let r;if(this.nameFilter==="named"){let o=he("app.session.toggleNamedFilter");this.showCwd?r=` No named sessions found. Press ${o} to show all.`:r=` No named sessions in current folder. Press ${o} to show all, or Tab to view all.`}else this.showCwd?r=" No sessions found":r=" No sessions in current folder. Press Tab to view all.";return n.push(b.fg("muted",X(r,e,"\u2026"))),n}let i=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredSessions.length-this.maxVisible)),s=Math.min(i+this.maxVisible,this.filteredSessions.length);for(let r=i;r<s;r++){let o=this.filteredSessions[r],a=o.session,c=r===this.selectedIndex,l=a.path===this.confirmingDeletePath,d=this.isCurrentSessionPath(a.path),u=this.buildTreePrefix(o),p=!!a.name,g=(a.name??a.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),h=Z4(a.modified),x=`${String(a.messageCount)} ${h}`;this.showCwd&&a.cwd&&(x=`${i1(a.cwd)} ${x}`),this.showPath&&(x=`${i1(a.path)} ${x}`);let y=c?b.fg("accent","\u203A "):" ",w=j(u),P=j(x)+2,_=e-2-w-P,R=X(g,Math.max(10,_),"\u2026"),L=null;l?L="error":d?L="accent":p&&(L="warning");let E=L?b.fg(L,R):R;c&&(E=b.bold(E));let W=y+b.fg("dim",u)+E,M=j(W),I=Math.max(1,e-M-j(x)),O=b.fg(l?"error":"dim",x),F=W+" ".repeat(I)+O;c&&(F=b.bg("selectedBg",F)),n.push(X(F,e))}if(i>0||s<this.filteredSessions.length){let r=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,o=b.fg("muted",X(r,e,""));n.push(o)}return n}buildTreePrefix(e){if(e.depth===0)return"";let n=e.ancestorContinues.map(s=>s?"\u2502 ":" "),i=e.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return n.join("")+i}handleInput(e){let n=ve();if(this.confirmingDeletePath!==null){if(n.matches(e,"tui.select.confirm")){let i=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(i);return}if(n.matches(e,"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(n.matches(e,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(n.matches(e,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(e,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(n.matches(e,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(n.matches(e,"app.session.delete")){this.startDeleteConfirmationForSelectedSession();return}if(n.matches(e,"app.session.rename")){let i=this.filteredSessions[this.selectedIndex];i&&this.onRenameSession?.(i.session.path);return}if(n.matches(e,"app.session.deleteNoninvasive")){if(this.searchInput.getValue().length>0){this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue());return}this.startDeleteConfirmationForSelectedSession();return}if(n.matches(e,"tui.select.up"))this.selectedIndex=Math.max(0,this.selectedIndex-1);else if(n.matches(e,"tui.select.down"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+1);else if(n.matches(e,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisible);else if(n.matches(e,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+this.maxVisible);else if(n.matches(e,"tui.select.confirm")){let i=this.filteredSessions[this.selectedIndex];i&&this.onSelect&&this.onSelect(i.session.path)}else n.matches(e,"tui.select.cancel")?this.onCancel&&this.onCancel():(this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue()))}};async function n$(t){let e=t.startsWith("-")?["--",t]:[t],n=Q4("trash",e,{encoding:"utf-8"}),i=()=>{let s=[];n.error&&s.push(n.error.message);let r=n.stderr?.trim();return r&&s.push(r.split(`
|
|
291
291
|
`)[0]??r),s.length===0?null:`trash: ${s.join(" \xB7 ").slice(0,200)}`};if(n.status===0||!Y4(t))return{ok:!0,method:"trash"};try{return await X4(t),{ok:!0,method:"unlink"}}catch(s){let r=s instanceof Error?s.message:String(s),o=i();return{ok:!1,method:"unlink",error:o?`${r} (${o})`:r}}}var Ir=class extends K{constructor(n,i,s,r,o,a,c,l){super();this.canRename=!0;this.scope="current";this.sortMode="threaded";this.nameFilter="all";this.currentSessions=null;this.allSessions=null;this.currentLoading=!1;this.allLoading=!1;this.allLoadSeq=0;this.mode="list";this.renameInput=new Qe;this.renameTargetPath=null;this._focused=!1;this.keybindings=c?.keybindings??Ps.create(),this.currentSessionsLoader=n,this.allSessionsLoader=i,this.onCancel=r,this.requestRender=a,this.header=new I0(this.scope,this.sortMode,this.nameFilter,this.requestRender);let d=c?.renameSession;this.renameSession=d,this.canRename=!!d,this.header.setShowRenameHint(c?.showRenameHint??this.canRename),this.sessionList=new R0([],!1,this.sortMode,this.nameFilter,this.keybindings,l),this.buildBaseLayout(this.sessionList),this.renameInput.onSubmit=p=>{this.confirmRename(p)};let u=()=>this.header.setStatusMessage(null);this.sessionList.onSelect=p=>{u(),s(p)},this.sessionList.onCancel=()=>{u(),r()},this.sessionList.onExit=()=>{u(),o()},this.sessionList.onToggleScope=()=>this.toggleScope(),this.sessionList.onToggleSort=()=>this.toggleSortMode(),this.sessionList.onToggleNameFilter=()=>this.toggleNameFilter(),this.sessionList.onRenameSession=p=>{if(!d||this.scope==="current"&&this.currentLoading||this.scope==="all"&&this.allLoading)return;let g=(this.scope==="all"?this.allSessions??[]:this.currentSessions??[]).find(h=>h.path===p);this.enterRenameMode(p,g?.name)},this.sessionList.onTogglePath=p=>{this.header.setShowPath(p),this.requestRender()},this.sessionList.onDeleteConfirmationChange=p=>{this.header.setConfirmingDeletePath(p),this.requestRender()},this.sessionList.onError=p=>{this.header.setStatusMessage({type:"error",message:p},3e3),this.requestRender()},this.sessionList.onDeleteSession=async p=>{let m=await n$(p);if(m.ok){this.currentSessions&&(this.currentSessions=this.currentSessions.filter(x=>x.path!==p)),this.allSessions&&(this.allSessions=this.allSessions.filter(x=>x.path!==p));let g=this.scope==="all"?this.allSessions??[]:this.currentSessions??[],h=this.scope==="all";this.sessionList.setSessions(g,h);let f=m.method==="trash"?"Session moved to trash":"Session deleted";this.header.setStatusMessage({type:"info",message:f},2e3),await this.refreshSessionsAfterMutation()}else{let g=m.error??"Unknown error";this.header.setStatusMessage({type:"error",message:`Failed to delete: ${g}`},3e3)}this.requestRender()},this.loadCurrentSessions()}handleInput(n){if(this.mode==="rename"){if(ve().matches(n,"tui.select.cancel")){this.exitRenameMode();return}this.renameInput.handleInput(n);return}this.sessionList.handleInput(n)}get focused(){return this._focused}set focused(n){this._focused=n,this.sessionList.focused=n,this.renameInput.focused=n,n&&this.mode==="rename"&&(this.renameInput.focused=!0)}buildBaseLayout(n,i){this.clear(),this.addChild(new U(1)),this.addChild(new V(s=>b.fg("accent",s))),this.addChild(new U(1)),(i?.showHeader??!0)&&(this.addChild(this.header),this.addChild(new U(1))),this.addChild(n),this.addChild(new U(1)),this.addChild(new V(s=>b.fg("accent",s)))}loadCurrentSessions(){this.loadScope("current","initial")}enterRenameMode(n,i){this.mode="rename",this.renameTargetPath=n,this.renameInput.setValue(i??""),this.renameInput.focused=!0;let s=new K;s.addChild(new A(b.bold("Rename Session"),1,0)),s.addChild(new U(1)),s.addChild(this.renameInput),s.addChild(new U(1)),s.addChild(new A(b.fg("muted",`${he("tui.select.confirm")} to save \xB7 ${he("tui.select.cancel")} to cancel`),1,0)),this.buildBaseLayout(s,{showHeader:!1}),this.requestRender()}exitRenameMode(){this.mode="list",this.renameTargetPath=null,this.buildBaseLayout(this.sessionList),this.requestRender()}async confirmRename(n){let i=n.trim();if(!i)return;let s=this.renameTargetPath;if(!s){this.exitRenameMode();return}let r=this.renameSession;if(!r){this.exitRenameMode();return}try{await r(s,i),await this.refreshSessionsAfterMutation()}finally{this.exitRenameMode()}}async loadScope(n,i){let s=n==="all";n==="current"?this.currentLoading=!0:this.allLoading=!0;let r=n==="all"?++this.allLoadSeq:void 0;this.header.setScope(n),this.header.setLoading(!0),this.requestRender();let o=(a,c)=>{n===this.scope&&(r!==void 0&&r!==this.allLoadSeq||(this.header.setProgress(a,c),this.requestRender()))};try{let a=await(n==="current"?this.currentSessionsLoader(o):this.allSessionsLoader(o));if(n==="current"?(this.currentSessions=a,this.currentLoading=!1):(this.allSessions=a,this.allLoading=!1),n!==this.scope||r!==void 0&&r!==this.allLoadSeq)return;this.header.setLoading(!1),this.sessionList.setSessions(a,s),this.requestRender(),n==="all"&&a.length===0&&(this.currentSessions?.length??0)===0&&this.onCancel()}catch(a){if(n==="current"?this.currentLoading=!1:this.allLoading=!1,n!==this.scope||r!==void 0&&r!==this.allLoadSeq)return;let c=a instanceof Error?a.message:String(a);this.header.setLoading(!1),this.header.setStatusMessage({type:"error",message:`Failed to load sessions: ${c}`},4e3),i==="initial"&&this.sessionList.setSessions([],s),this.requestRender()}}toggleSortMode(){this.sortMode=this.sortMode==="threaded"?"recent":this.sortMode==="recent"?"relevance":"threaded",this.header.setSortMode(this.sortMode),this.sessionList.setSortMode(this.sortMode),this.requestRender()}toggleNameFilter(){this.nameFilter=this.nameFilter==="all"?"named":"all",this.header.setNameFilter(this.nameFilter),this.sessionList.setNameFilter(this.nameFilter),this.requestRender()}async refreshSessionsAfterMutation(){await this.loadScope(this.scope,"refresh")}toggleScope(){if(this.scope==="current"){if(this.scope="all",this.header.setScope(this.scope),this.allSessions!==null){this.header.setLoading(!1),this.sessionList.setSessions(this.allSessions,!0),this.requestRender();return}this.allLoading||this.loadScope("all","toggle");return}this.scope="current",this.header.setScope(this.scope),this.header.setLoading(this.currentLoading),this.sessionList.setSessions(this.currentSessions??[],!1),this.requestRender()}getSessionList(){return this.sessionList}};import tye from"chalk";import*as L1 from"node:crypto";import*as Xn from"node:fs";import*as ec from"node:os";import*as Ve from"node:path";import{spawn as N0,spawnSync as oB}from"child_process";import{execFile as i$,spawnSync as s$}from"child_process";import{existsSync as Wa,readFileSync as Lp,statSync as r$,unwatchFile as o$,watchFile as a$}from"fs";import{dirname as a1,join as Ua,resolve as r1}from"path";function o1(t){let e=t;for(;;){let n=Ua(e,".git");if(Wa(n))try{let s=r$(n);if(s.isFile()){let r=Lp(n,"utf8").trim();if(r.startsWith("gitdir: ")){let o=r1(e,r.slice(8).trim()),a=Ua(o,"HEAD");if(!Wa(a))return null;let c=Ua(o,"commondir"),l=Wa(c)?r1(o,Lp(c,"utf8").trim()):o;return{repoDir:e,commonGitDir:l,headPath:a}}}else if(s.isDirectory()){let r=Ua(n,"HEAD");return Wa(r)?{repoDir:e,commonGitDir:n,headPath:r}:null}}catch{return null}let i=a1(e);if(i===e)return null;e=i}}function c$(t){let e=s$("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return(e.status===0?e.stdout.trim():"")||null}function l$(t){return new Promise(e=>{i$("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:t,encoding:"utf8"},(n,i)=>{if(n){e(null);return}let s=i.trim();e(s||null)})})}var Wp=class t{constructor(e){this.extensionStatuses=new Map;this.cachedBranch=void 0;this.gitPaths=void 0;this.headWatcher=null;this.reftableWatcher=null;this.reftableTablesListWatcher=null;this.reftableTablesListPath=null;this.branchChangeCallbacks=new Set;this.availableProviderCount=0;this.refreshTimer=null;this.gitWatcherRetryTimer=null;this.refreshInFlight=!1;this.refreshPending=!1;this.disposed=!1;this.cwd=e,this.gitPaths=o1(e),this.setupGitWatcher()}static{this.WATCH_DEBOUNCE_MS=500}getGitBranch(){return this.cachedBranch===void 0&&(this.cachedBranch=this.resolveGitBranchSync()),this.cachedBranch}getExtensionStatuses(){return this.extensionStatuses}onBranchChange(e){return this.branchChangeCallbacks.add(e),()=>this.branchChangeCallbacks.delete(e)}setExtensionStatus(e,n){n===void 0?this.extensionStatuses.delete(e):this.extensionStatuses.set(e,n)}clearExtensionStatuses(){this.extensionStatuses.clear()}getAvailableProviderCount(){return this.availableProviderCount}setAvailableProviderCount(e){this.availableProviderCount=e}setCwd(e){this.cwd!==e&&(this.cwd=e,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.cachedBranch=void 0,this.gitPaths=o1(e),this.setupGitWatcher(),this.notifyBranchChange())}dispose(){this.disposed=!0,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.branchChangeCallbacks.clear()}notifyBranchChange(){for(let e of this.branchChangeCallbacks)e()}scheduleRefresh(){if(!(this.disposed||this.refreshTimer)){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshGitBranchAsync()},t.WATCH_DEBOUNCE_MS)}}async refreshGitBranchAsync(){if(!this.disposed){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshInFlight=!0;try{let e=await this.resolveGitBranchAsync();if(this.disposed)return;if(this.cachedBranch!==void 0&&this.cachedBranch!==e){this.cachedBranch=e,this.notifyBranchChange();return}this.cachedBranch=e}finally{this.refreshInFlight=!1,this.refreshPending&&!this.disposed&&(this.refreshPending=!1,this.scheduleRefresh())}}}resolveGitBranchSync(){try{if(!this.gitPaths)return null;let e=Lp(this.gitPaths.headPath,"utf8").trim();if(e.startsWith("ref: refs/heads/")){let n=e.slice(16);return n===".invalid"?c$(this.gitPaths.repoDir)??"detached":n}return"detached"}catch{return null}}async resolveGitBranchAsync(){try{if(!this.gitPaths)return null;let e=Lp(this.gitPaths.headPath,"utf8").trim();if(e.startsWith("ref: refs/heads/")){let n=e.slice(16);return n===".invalid"?await l$(this.gitPaths.repoDir)??"detached":n}return"detached"}catch{return null}}clearGitWatchers(){mr(this.headWatcher),this.headWatcher=null,mr(this.reftableWatcher),this.reftableWatcher=null,mr(this.reftableTablesListWatcher),this.reftableTablesListWatcher=null,this.reftableTablesListPath&&(o$(this.reftableTablesListPath),this.reftableTablesListPath=null),this.gitWatcherRetryTimer&&(clearTimeout(this.gitWatcherRetryTimer),this.gitWatcherRetryTimer=null)}scheduleGitWatcherRetry(){this.disposed||this.gitWatcherRetryTimer||(this.gitWatcherRetryTimer=setTimeout(()=>{this.gitWatcherRetryTimer=null,this.setupGitWatcher()},YC))}handleGitWatcherError(){this.clearGitWatchers(),this.scheduleGitWatcherRetry()}setupGitWatcher(){if(this.clearGitWatchers(),!this.gitPaths||(this.headWatcher=la(a1(this.gitPaths.headPath),(n,i)=>{(!i||i==="HEAD")&&this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.headWatcher))return;let e=Ua(this.gitPaths.commonGitDir,"reftable");if(Wa(e)){if(this.reftableWatcher=la(e,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableWatcher)return;let n=Ua(e,"tables.list");if(Wa(n)){if(this.reftableTablesListPath=n,this.reftableTablesListWatcher=la(n,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableTablesListWatcher)return;a$(n,{interval:250},(i,s)=>{(i.mtimeMs!==s.mtimeMs||i.ctimeMs!==s.ctimeMs||i.size!==s.size)&&this.scheduleRefresh()})}}}};var P0=[{name:"settings",description:"Open settings menu"},{name:"model",description:"Select model (opens selector UI)"},{name:"scoped-models",description:"Enable/disable models for Ctrl+P cycling"},{name:"export",description:"Export session (HTML default, or specify path: .html/.jsonl)"},{name:"import",description:"Import and resume a session from a JSONL file"},{name:"share",description:"Share session as a secret GitHub gist"},{name:"copy",description:"Copy last agent message to clipboard"},{name:"name",description:"Set session display name"},{name:"session",description:"Show session info and stats"},{name:"changelog",description:"Show changelog entries"},{name:"hotkeys",description:"Show all keyboard shortcuts"},{name:"fork",description:"Create a new fork from a previous user message"},{name:"clone",description:"Duplicate the current session at the current position"},{name:"tree",description:"Navigate session tree (switch branches)"},{name:"login",description:"Configure provider authentication"},{name:"logout",description:"Remove provider authentication"},{name:"new",description:"Start a new session"},{name:"compact",description:"Manually compact the session context"},{name:"resume",description:"Resume a different session"},{name:"reload",description:"Reload keybindings, extensions, skills, prompts, and themes"},{name:"quit",description:`Quit ${Ot}`}];import{existsSync as u$,readFileSync as d$}from"fs";function _0(t){if(!u$(t))return[];try{let n=d$(t,"utf-8").split(`
|
|
292
292
|
`),i=[],s=[],r=null;for(let o of n)if(o.startsWith("## ")){r&&s.length>0&&i.push({...r,content:s.join(`
|
|
293
293
|
`).trim()});let a=o.match(/##\s+\[?(\d+)\.(\d+)\.(\d+)\]?/);a?(r={major:Number.parseInt(a[1],10),minor:Number.parseInt(a[2],10),patch:Number.parseInt(a[3],10)},s=[o]):(r=null,s=[])}else r&&s.push(o);return r&&s.length>0&&i.push({...r,content:s.join(`
|
|
@@ -313,7 +313,7 @@ Pi will resume when the editor exits.
|
|
|
313
313
|
`),await new Promise(c=>{let l=J$(r,[...o,s],{stdio:"inherit",shell:process.platform==="win32"});l.on("error",()=>c(null)),l.on("close",d=>c(d))})===0){let c=Ka.readFileSync(s,"utf-8").replace(/\n$/,"");this.editor.setText(c)}}finally{try{Ka.unlinkSync(s)}catch{}this.tui.start(),this.tui.requestRender(!0)}}};var Ha=class extends K{constructor(n,i,s,r,o){super();this._focused=!1;this.onSubmitCallback=s,this.onCancelCallback=r,this.baseTitle=n,this.addChild(new V),this.addChild(new U(1)),this.titleText=new A(b.fg("accent",n),1,0),this.addChild(this.titleText),this.addChild(new U(1)),o?.timeout&&o.timeout>0&&o.tui&&(this.countdown=new Es(o.timeout,o.tui,a=>this.titleText.setText(b.fg("accent",`${this.baseTitle} (${a}s)`)),()=>this.onCancelCallback())),this.input=new Qe,this.addChild(this.input),this.addChild(new U(1)),this.addChild(new A(`${ce("tui.select.confirm","submit")} ${ce("tui.select.cancel","cancel")}`,1,0)),this.addChild(new U(1)),this.addChild(new V)}get focused(){return this._focused}set focused(n){this._focused=n,this.input.focused=n}handleInput(n){let i=ve();i.matches(n,"tui.select.confirm")||n===`
|
|
314
314
|
`?this.onSubmitCallback(this.input.getValue()):i.matches(n,"tui.select.cancel")?this.onCancelCallback():this.input.handleInput(n)}dispose(){this.countdown?.dispose()}};var Gi=class extends K{constructor(n,i,s,r,o){super();this.selectedIndex=0;this.options=i,this.onSelectCallback=s,this.onCancelCallback=r,this.onToggleToolsExpanded=o?.onToggleToolsExpanded,this.baseTitle=n,this.addChild(new V),this.addChild(new U(1)),this.titleText=new A(b.fg("accent",b.bold(n)),1,0),this.addChild(this.titleText),this.addChild(new U(1)),o?.timeout&&o.timeout>0&&o.tui&&(this.countdown=new Es(o.timeout,o.tui,a=>this.titleText.setText(b.fg("accent",b.bold(`${this.baseTitle} (${a}s)`))),()=>this.onCancelCallback())),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.addChild(new A(pt("\u2191\u2193","navigate")+" "+ce("tui.select.confirm","select")+" "+ce("tui.select.cancel","cancel"),1,0)),this.addChild(new U(1)),this.addChild(new V),this.updateList()}updateList(){this.listContainer.clear();for(let n=0;n<this.options.length;n++){let s=n===this.selectedIndex?b.fg("accent","\u2192 ")+b.fg("accent",this.options[n]):` ${b.fg("text",this.options[n])}`;this.listContainer.addChild(new A(s,1,0))}}handleInput(n){let i=ve();if(i.matches(n,"app.tools.expand"))this.onToggleToolsExpanded?.();else if(i.matches(n,"tui.select.up")||n==="k")this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList();else if(i.matches(n,"tui.select.down")||n==="j")this.selectedIndex=Math.min(this.options.length-1,this.selectedIndex+1),this.updateList();else if(i.matches(n,"tui.select.confirm")||n===`
|
|
315
315
|
`){let s=this.options[this.selectedIndex];s&&this.onSelectCallback(s)}else i.matches(n,"tui.select.cancel")&&this.onCancelCallback()}dispose(){this.countdown?.dispose()}};function Q$(t){return t.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function za(t){return t<1e3?t.toString():t<1e4?`${(t/1e3).toFixed(1)}k`:t<1e6?`${Math.round(t/1e3)}k`:t<1e7?`${(t/1e6).toFixed(1)}M`:`${Math.round(t/1e6)}M`}var Va=class{constructor(e,n){this.autoCompactEnabled=!0;this.session=e,this.footerData=n}setSession(e){this.session=e}setAutoCompactEnabled(e){this.autoCompactEnabled=e}invalidate(){}dispose(){}render(e){let n=this.session.state,i=0,s=0,r=0,o=0,a=0;for(let pe of this.session.sessionManager.getEntries())pe.type==="message"&&pe.message.role==="assistant"&&(i+=pe.message.usage.input,s+=pe.message.usage.output,r+=pe.message.usage.cacheRead,o+=pe.message.usage.cacheWrite,a+=pe.message.usage.cost.total);let c=this.session.getContextUsage(),l=c?.contextWindow??n.model?.contextWindow??0,d=c?.percent??0,u=c?.percent!==null?d.toFixed(1):"?",p=this.session.sessionManager.getCwd(),m=process.env.HOME||process.env.USERPROFILE;m&&p.startsWith(m)&&(p=`~${p.slice(m.length)}`);let g=this.footerData.getGitBranch();g&&(p=`${p} (${g})`);let h=this.session.sessionManager.getSessionName();h&&(p=`${p} \u2022 ${h}`);let f=[];i&&f.push(`\u2191${za(i)}`),s&&f.push(`\u2193${za(s)}`),r&&f.push(`R${za(r)}`),o&&f.push(`W${za(o)}`);let x=n.model?this.session.modelRegistry.isUsingOAuth(n.model):!1;if(a||x){let pe=`$${a.toFixed(3)}${x?" (sub)":""}`;f.push(pe)}let y,w=this.autoCompactEnabled?" (auto)":"",P=u==="?"?`?/${za(l)}${w}`:`${u}%/${za(l)}${w}`;d>90?y=b.fg("error",P):d>70?y=b.fg("warning",P):y=P,f.push(y);let _=f.join(" "),R=n.model?.id||"no-model",L=j(_);L>e&&(_=X(_,e,"..."),L=j(_));let E=2,W=R;if(n.model?.reasoning){let pe=n.thinkingLevel||"off";W=pe==="off"?`${R} \u2022 thinking off`:`${R} \u2022 ${pe}`}let M=W;this.footerData.getAvailableProviderCount()>1&&n.model&&(M=`(${n.model.provider}) ${W}`,L+E+j(M)>e&&(M=W));let I=j(M),O=L+E+I,F;if(O<=e){let pe=" ".repeat(e-L-I);F=_+pe+M}else{let pe=e-L-E;if(pe>0){let Ie=X(M,pe,""),tt=j(Ie),De=" ".repeat(Math.max(0,e-L-tt));F=_+De+Ie}else F=_}let N=b.fg("dim",_),H=F.slice(_.length),G=b.fg("dim",H),de=[X(b.fg("dim",p),e,b.fg("dim","...")),N+G],Te=this.footerData.getExtensionStatuses();if(Te.size>0){let Ie=Array.from(Te.entries()).sort(([tt],[De])=>tt.localeCompare(De)).map(([,tt])=>Q$(tt)).join(" ");de.push(X(Ie,e,b.fg("dim","...")))}return de}};import{exec as Y$}from"child_process";var Os=class extends K{constructor(n,i,s,r,o){super();this.abortController=new AbortController;this._focused=!1;this.tui=n,this.onComplete=s;let a=Af().find(d=>d.id===i),c=r||a?.name||i,l=o??`Login to ${c}`;this.addChild(new V),this.addChild(new A(b.fg("accent",b.bold(l)),1,0)),this.contentContainer=new K,this.addChild(this.contentContainer),this.input=new Qe,this.input.onSubmit=()=>{this.inputResolver&&(this.inputResolver(this.input.getValue()),this.inputResolver=void 0,this.inputRejecter=void 0)},this.input.onEscape=()=>{this.cancel()},this.addChild(new V)}get focused(){return this._focused}set focused(n){this._focused=n,this.input.focused=n}get signal(){return this.abortController.signal}cancel(){this.abortController.abort(),this.inputRejecter&&(this.inputRejecter(new Error("Login cancelled")),this.inputResolver=void 0,this.inputRejecter=void 0),this.onComplete(!1,"Login cancelled")}showAuth(n,i){this.contentContainer.clear(),this.contentContainer.addChild(new U(1));let s=`\x1B]8;;${n}\x07${n}\x1B]8;;\x07`;this.contentContainer.addChild(new A(b.fg("accent",s),1,0));let r=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open",o=`\x1B]8;;${n}\x07${r}\x1B]8;;\x07`;this.contentContainer.addChild(new A(b.fg("dim",o),1,0)),i&&(this.contentContainer.addChild(new U(1)),this.contentContainer.addChild(new A(b.fg("warning",i),1,0)));let a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Y$(`${a} "${n}"`),this.tui.requestRender()}showManualInput(n){return this.contentContainer.addChild(new U(1)),this.contentContainer.addChild(new A(b.fg("dim",n),1,0)),this.contentContainer.addChild(this.input),this.contentContainer.addChild(new A(`(${ce("tui.select.cancel","to cancel")})`,1,0)),this.tui.requestRender(),new Promise((i,s)=>{this.inputResolver=i,this.inputRejecter=s})}showPrompt(n,i){return this.contentContainer.addChild(new U(1)),this.contentContainer.addChild(new A(b.fg("text",n),1,0)),i&&this.contentContainer.addChild(new A(b.fg("dim",`e.g., ${i}`),1,0)),this.contentContainer.addChild(this.input),this.contentContainer.addChild(new A(`(${ce("tui.select.cancel","to cancel,")} ${ce("tui.select.confirm","to submit")})`,1,0)),this.input.setValue(""),this.tui.requestRender(),new Promise((s,r)=>{this.inputResolver=s,this.inputRejecter=r})}showInfo(n){this.contentContainer.clear(),this.contentContainer.addChild(new U(1));for(let i of n)this.contentContainer.addChild(new A(i,1,0));this.contentContainer.addChild(new U(1)),this.contentContainer.addChild(new A(`(${ce("tui.select.cancel","to close")})`,1,0)),this.tui.requestRender()}showWaiting(n){this.contentContainer.addChild(new U(1)),this.contentContainer.addChild(new A(b.fg("dim",n),1,0)),this.contentContainer.addChild(new A(`(${ce("tui.select.cancel","to cancel")})`,1,0)),this.tui.requestRender()}showProgress(n){this.contentContainer.addChild(new A(b.fg("dim",n),1,0)),this.tui.requestRender()}handleInput(n){if(ve().matches(n,"tui.select.cancel")){this.cancel();return}this.input.handleInput(n)}};var Ja=class extends K{constructor(n,i,s,r,o,a,c,l){super();this._focused=!1;this.allModels=[];this.scopedModelItems=[];this.activeModels=[];this.filteredModels=[];this.selectedIndex=0;this.scope="all";if(this.tui=n,this.currentModel=i,this.settingsManager=s,this.modelRegistry=r,this.scopedModels=o,this.scope=o.length>0?"scoped":"all",this.onSelectCallback=a,this.onCancelCallback=c,this.addChild(new V),this.addChild(new U(1)),o.length>0)this.scopeText=new A(this.getScopeText(),0,0),this.addChild(this.scopeText),this.scopeHintText=new A(this.getScopeHintText(),0,0),this.addChild(this.scopeHintText);else{let d="Only showing models from configured providers. Use /login to add providers.";this.addChild(new A(b.fg("warning",d),0,0))}this.addChild(new U(1)),this.searchInput=new Qe,l&&this.searchInput.setValue(l),this.searchInput.onSubmit=()=>{this.filteredModels[this.selectedIndex]&&this.handleSelect(this.filteredModels[this.selectedIndex].model)},this.addChild(this.searchInput),this.addChild(new U(1)),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.addChild(new V),this.loadModels().then(()=>{l?this.filterModels(l):this.updateList(),this.tui.requestRender()})}get focused(){return this._focused}set focused(n){this._focused=n,this.searchInput.focused=n}async loadModels(){let n;this.modelRegistry.refresh();let i=this.modelRegistry.getError();i&&(this.errorMessage=i);try{n=(await this.modelRegistry.getAvailable()).map(o=>({provider:o.provider,id:o.id,model:o}))}catch(r){this.allModels=[],this.scopedModelItems=[],this.activeModels=[],this.filteredModels=[],this.errorMessage=r instanceof Error?r.message:String(r);return}this.allModels=this.sortModels(n),this.scopedModels=this.scopedModels.map(r=>{let o=this.modelRegistry.find(r.model.provider,r.model.id);return o?{...r,model:o}:r}),this.scopedModelItems=this.scopedModels.map(r=>({provider:r.model.provider,id:r.model.id,model:r.model})),this.activeModels=this.scope==="scoped"?this.scopedModelItems:this.allModels,this.filteredModels=this.activeModels;let s=this.filteredModels.findIndex(r=>Kn(this.currentModel,r.model));this.selectedIndex=s>=0?s:Math.min(this.selectedIndex,Math.max(0,this.filteredModels.length-1))}sortModels(n){let i=[...n];return i.sort((s,r)=>{let o=Kn(this.currentModel,s.model),a=Kn(this.currentModel,r.model);return o&&!a?-1:!o&&a?1:s.provider.localeCompare(r.provider)}),i}getScopeText(){let n=this.scope==="all"?b.fg("accent","all"):b.fg("muted","all"),i=this.scope==="scoped"?b.fg("accent","scoped"):b.fg("muted","scoped");return`${b.fg("muted","Scope: ")}${n}${b.fg("muted"," | ")}${i}`}getScopeHintText(){return ce("tui.input.tab","scope")+b.fg("muted"," (all/scoped)")}setScope(n){if(this.scope===n)return;this.scope=n,this.activeModels=this.scope==="scoped"?this.scopedModelItems:this.allModels;let i=this.activeModels.findIndex(s=>Kn(this.currentModel,s.model));this.selectedIndex=i>=0?i:0,this.filterModels(this.searchInput.getValue()),this.scopeText&&this.scopeText.setText(this.getScopeText())}filterModels(n){this.filteredModels=n?Kt(this.activeModels,n,({id:i,provider:s})=>`${i} ${s} ${s}/${i} ${s} ${i}`):this.activeModels,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredModels.length-1)),this.updateList()}updateList(){this.listContainer.clear();let n=10,i=Math.max(0,Math.min(this.selectedIndex-Math.floor(n/2),this.filteredModels.length-n)),s=Math.min(i+n,this.filteredModels.length);for(let r=i;r<s;r++){let o=this.filteredModels[r];if(!o)continue;let a=r===this.selectedIndex,c=Kn(this.currentModel,o.model),l="";if(a){let d=b.fg("accent","\u2192 "),u=`${o.id}`,p=b.fg("muted",`[${o.provider}]`),m=c?b.fg("success"," \u2713"):"";l=`${d+b.fg("accent",u)} ${p}${m}`}else{let d=` ${o.id}`,u=b.fg("muted",`[${o.provider}]`),p=c?b.fg("success"," \u2713"):"";l=`${d} ${u}${p}`}this.listContainer.addChild(new A(l,0,0))}if(i>0||s<this.filteredModels.length){let r=b.fg("muted",` (${this.selectedIndex+1}/${this.filteredModels.length})`);this.listContainer.addChild(new A(r,0,0))}if(this.errorMessage){let r=this.errorMessage.split(`
|
|
316
|
-
`);for(let o of r)this.listContainer.addChild(new A(b.fg("error",o),0,0))}else if(this.filteredModels.length===0)this.listContainer.addChild(new A(b.fg("muted"," No matching models"),0,0));else{let r=this.filteredModels[this.selectedIndex];this.listContainer.addChild(new U(1)),this.listContainer.addChild(new A(b.fg("muted",` Model Name: ${r.model.name}`),0,0))}}handleInput(n){let i=ve();if(i.matches(n,"tui.input.tab")){if(this.scopedModelItems.length>0){let s=this.scope==="all"?"scoped":"all";this.setScope(s),this.scopeHintText&&this.scopeHintText.setText(this.getScopeHintText())}return}if(i.matches(n,"tui.select.up")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredModels.length-1:this.selectedIndex-1,this.updateList()}else if(i.matches(n,"tui.select.down")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredModels.length-1?0:this.selectedIndex+1,this.updateList()}else if(i.matches(n,"tui.select.confirm")){let s=this.filteredModels[this.selectedIndex];s&&this.handleSelect(s.model)}else i.matches(n,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(n),this.filterModels(this.searchInput.getValue()))}handleSelect(n){this.settingsManager.setDefaultModelAndProvider(n.provider,n.id),this.onSelectCallback(n)}getSearchInput(){return this.searchInput}};var Rr=class extends K{constructor(n,i,s,r,o,a){super();this._focused=!1;this.selectedIndex=0;this.mode=n,this.authStorage=i,this.getAuthStatus=a??(l=>this.authStorage.getAuthStatus(l)),this.allProviders=s,this.filteredProviders=s,this.onSelectCallback=r,this.onCancelCallback=o,this.addChild(new V),this.addChild(new U(1));let c=n==="login"?"Select provider to configure:":"Select provider to logout:";this.addChild(new Yt(b.fg("accent",b.bold(c)),1,0)),this.addChild(new U(1)),this.searchInput=new Qe,this.searchInput.onSubmit=()=>{let l=this.filteredProviders[this.selectedIndex];l&&this.onSelectCallback(l.id)},this.addChild(this.searchInput),this.addChild(new U(1)),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.addChild(new V),this.filterProviders("")}get focused(){return this._focused}set focused(n){this._focused=n,this.searchInput.focused=n}filterProviders(n){this.filteredProviders=n?Kt(this.allProviders,n,i=>`${i.name} ${i.id} ${i.authType}`):this.allProviders,this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,Math.max(0,this.filteredProviders.length-1))),this.updateList()}updateList(){this.listContainer.clear();let n=8,i=Math.max(0,Math.min(this.selectedIndex-Math.floor(n/2),this.filteredProviders.length-n)),s=Math.min(i+n,this.filteredProviders.length);for(let r=i;r<s;r++){let o=this.filteredProviders[r];if(!o)continue;let a=r===this.selectedIndex,c=this.formatStatusIndicator(o),l="";if(a){let d=b.fg("accent","\u2192 "),u=b.fg("accent",o.name);l=d+u+c}else l=` ${b.fg("text",o.name)}`+c;this.listContainer.addChild(new Yt(l,1,0))}if(i>0||s<this.filteredProviders.length){let r=b.fg("muted",` (${this.selectedIndex+1}/${this.filteredProviders.length})`);this.listContainer.addChild(new Yt(r,1,0))}if(this.filteredProviders.length===0){let r=this.allProviders.length===0?this.mode==="login"?"No providers available":"No providers logged in. Use /login first.":"No matching providers";this.listContainer.addChild(new Yt(b.fg("muted",` ${r}`),1,0))}}formatStatusIndicator(n){let i=this.authStorage.get(n.id);if(i?.type===n.authType)return b.fg("success"," \u2713 configured");if(i){let r=i.type==="oauth"?"subscription configured":"API key configured";return b.fg("muted"," \u2022 ")+b.fg("warning",r)}if(n.authType!=="api_key")return b.fg("muted"," \u2022 unconfigured");let s=this.getAuthStatus(n.id);switch(s.source){case"environment":return b.fg("success",` \u2713 env: ${s.label??"API key"}`);case"runtime":return b.fg("success"," \u2713 runtime API key");case"fallback":return b.fg("success"," \u2713 custom API key");case"models_json_key":return b.fg("success"," \u2713 key in models.json");case"models_json_command":return b.fg("success"," \u2713 command in models.json");default:return b.fg("muted"," \u2022 unconfigured")}}handleInput(n){let i=ve();if(i.matches(n,"tui.select.up")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList()}else if(i.matches(n,"tui.select.down")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.min(this.filteredProviders.length-1,this.selectedIndex+1),this.updateList()}else if(i.matches(n,"tui.select.confirm")){let s=this.filteredProviders[this.selectedIndex];s&&this.onSelectCallback(s.id)}else i.matches(n,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(n),this.filterProviders(this.searchInput.getValue()))}};function W0(t,e){return t===null||t.includes(e)}function X$(t,e){if(t===null)return[e];let n=t.indexOf(e);return n>=0?[...t.slice(0,n),...t.slice(n+1)]:[...t,e]}function _1(t,e,n){if(t===null)return null;let i=n??e,s=[...t];for(let r of i)s.includes(r)||s.push(r);return s.length===e.length?null:s}function E1(t,e,n){if(t===null)return n?e.filter(s=>!n.includes(s)):[];let i=new Set(n??t);return t.filter(s=>!i.has(s))}function Z$(t,e,n){if(t===null)return null;let i=[...t],s=i.indexOf(e);if(s<0)return i;let r=s+n;if(r<0||r>=i.length)return i;let o=[...i];return[o[s],o[r]]=[o[r],o[s]],o}function eB(t,e){if(t===null)return e;let n=new Set(t);return[...t,...e.filter(i=>!n.has(i))]}var $l=class extends K{constructor(n,i){super();this.modelsById=new Map;this.allIds=[];this.enabledIds=null;this.filteredItems=[];this.selectedIndex=0;this._focused=!1;this.maxVisible=8;this.isDirty=!1;this.callbacks=i;for(let s of n.allModels){let r=`${s.provider}/${s.id}`;this.modelsById.set(r,s),this.allIds.push(r)}this.enabledIds=n.enabledModelIds===null?null:[...n.enabledModelIds],this.filteredItems=this.buildItems(),this.addChild(new V),this.addChild(new U(1)),this.addChild(new A(b.fg("accent",b.bold("Model Configuration")),0,0)),this.addChild(new A(b.fg("muted",`Session-only. ${he("app.models.save")} to save to settings.`),0,0)),this.addChild(new U(1)),this.searchInput=new Qe,this.addChild(this.searchInput),this.addChild(new U(1)),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.footerText=new A(this.getFooterText(),0,0),this.addChild(this.footerText),this.addChild(new V),this.updateList()}get focused(){return this._focused}set focused(n){this._focused=n,this.searchInput.focused=n}buildItems(){return eB(this.enabledIds,this.allIds).filter(n=>this.modelsById.has(n)).map(n=>({fullId:n,model:this.modelsById.get(n),enabled:W0(this.enabledIds,n)}))}getFooterText(){let n=this.enabledIds?.length??this.allIds.length,s=this.enabledIds===null?"all enabled":`${n}/${this.allIds.length} enabled`,r=[`${he("tui.select.confirm")} toggle`,`${he("app.models.enableAll")} all`,`${he("app.models.clearAll")} clear`,`${he("app.models.toggleProvider")} provider`,`${he("app.models.reorderUp")}/${he("app.models.reorderDown")} reorder`,`${he("app.models.save")} save`,s];return this.isDirty?b.fg("dim",` ${r.join(" \xB7 ")} `)+b.fg("warning","(unsaved)"):b.fg("dim",` ${r.join(" \xB7 ")}`)}refresh(){let n=this.searchInput.getValue(),i=this.buildItems();this.filteredItems=n?Kt(i,n,s=>`${s.model.id} ${s.model.provider}`):i,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList(),this.footerText.setText(this.getFooterText())}notifyChange(){this.callbacks.onChange(this.enabledIds===null?null:[...this.enabledIds])}updateList(){if(this.listContainer.clear(),this.filteredItems.length===0){this.listContainer.addChild(new A(b.fg("muted"," No matching models"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),i=Math.min(n+this.maxVisible,this.filteredItems.length),s=this.enabledIds===null;for(let r=n;r<i;r++){let o=this.filteredItems[r],a=r===this.selectedIndex,c=a?b.fg("accent","\u2192 "):" ",l=a?b.fg("accent",o.model.id):o.model.id,d=b.fg("muted",` [${o.model.provider}]`),u=s?"":o.enabled?b.fg("success"," \u2713"):b.fg("dim"," \u2717");this.listContainer.addChild(new A(`${c}${l}${d}${u}`,0,0))}if((n>0||i<this.filteredItems.length)&&this.listContainer.addChild(new A(b.fg("muted",` (${this.selectedIndex+1}/${this.filteredItems.length})`),0,0)),this.filteredItems.length>0){let r=this.filteredItems[this.selectedIndex];this.listContainer.addChild(new U(1)),this.listContainer.addChild(new A(b.fg("muted",` Model Name: ${r.model.name}`),0,0))}}handleInput(n){let i=ve();if(i.matches(n,"tui.select.up")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(i.matches(n,"tui.select.down")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}let s=i.matches(n,"app.models.reorderUp"),r=i.matches(n,"app.models.reorderDown");if(s||r){if(this.enabledIds===null)return;let o=this.filteredItems[this.selectedIndex];if(o&&W0(this.enabledIds,o.fullId)){let a=s?-1:1,l=this.enabledIds.indexOf(o.fullId)+a;l>=0&&l<this.enabledIds.length&&(this.enabledIds=Z$(this.enabledIds,o.fullId,a),this.isDirty=!0,this.selectedIndex+=a,this.refresh(),this.notifyChange())}return}if(i.matches(n,"tui.select.confirm")){let o=this.filteredItems[this.selectedIndex];o&&(this.enabledIds=X$(this.enabledIds,o.fullId),this.isDirty=!0,this.refresh(),this.notifyChange());return}if(i.matches(n,"app.models.enableAll")){let o=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=_1(this.enabledIds,this.allIds,o),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(i.matches(n,"app.models.clearAll")){let o=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=E1(this.enabledIds,this.allIds,o),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(i.matches(n,"app.models.toggleProvider")){let o=this.filteredItems[this.selectedIndex];if(o){let a=o.model.provider,c=this.allIds.filter(d=>this.modelsById.get(d).provider===a),l=c.every(d=>W0(this.enabledIds,d));this.enabledIds=l?E1(this.enabledIds,this.allIds,c):_1(this.enabledIds,this.allIds,c),this.isDirty=!0,this.refresh(),this.notifyChange()}return}if(i.matches(n,"app.models.save")){this.callbacks.onPersist(this.enabledIds===null?null:[...this.enabledIds]),this.isDirty=!1,this.footerText.setText(this.getFooterText());return}if(_e(n,ar.ctrl("c"))){this.searchInput.getValue()?(this.searchInput.setValue(""),this.refresh()):this.callbacks.onCancel();return}if(_e(n,ar.escape)){this.callbacks.onCancel();return}this.searchInput.handleInput(n),this.refresh()}getSearchInput(){return this.searchInput}};var tB={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},nB={off:"No reasoning",minimal:"Very brief reasoning (~1k tokens)",low:"Light reasoning (~2k tokens)",medium:"Moderate reasoning (~8k tokens)",high:"Deep reasoning (~16k tokens)",xhigh:"Maximum reasoning (~32k tokens)"},U0=class extends K{constructor(e,n,i){super(),this.state={...e};let s=[{id:"anthropic-extra-usage",label:"Anthropic extra usage",description:"Warn when Anthropic subscription auth may use paid extra usage",currentValue:this.state.anthropicExtraUsage??!0?"true":"false",values:["true","false"]}];this.settingsList=new ca(s,Math.min(s.length,10),$d(),(r,o)=>{r==="anthropic-extra-usage"&&(this.state={...this.state,anthropicExtraUsage:o==="true"},n({...this.state}))},i),this.addChild(this.settingsList)}handleInput(e){this.settingsList.handleInput(e)}},Bp=class extends K{constructor(e,n,i,s,r,o,a){super(),this.addChild(new A(b.bold(b.fg("accent",e)),0,0)),n&&(this.addChild(new U(1)),this.addChild(new A(b.fg("muted",n),0,0))),this.addChild(new U(1)),this.selectList=new Qt(i,Math.min(i.length,10),yr(),tB);let c=i.findIndex(l=>l.value===s);c!==-1&&this.selectList.setSelectedIndex(c),this.selectList.onSelect=l=>{r(l.value)},this.selectList.onCancel=o,a&&(this.selectList.onSelectionChange=l=>{a(l.value)}),this.addChild(this.selectList),this.addChild(new U(1)),this.addChild(new A(b.fg("dim"," Enter to select \xB7 Esc to go back"),0,0))}handleInput(e){this.selectList.handleInput(e)}},Qa=class extends K{constructor(e,n){super();let i=dt().images,s=xl("app.message.followUp"),r={...e.warnings},o=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:e.autoCompact?"true":"false",values:["true","false"]},{id:"steering-mode",label:"Steering mode",description:"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.",currentValue:e.steeringMode,values:["one-at-a-time","all"]},{id:"follow-up-mode",label:"Follow-up mode",description:`${s} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,currentValue:e.followUpMode,values:["one-at-a-time","all"]},{id:"transport",label:"Transport",description:"Preferred transport for providers that support multiple transports",currentValue:e.transport,values:["sse","websocket","websocket-cached","auto"]},{id:"http-idle-timeout",label:"HTTP idle timeout",description:"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.",currentValue:Ep(e.httpIdleTimeoutMs),values:Pp.map(g=>g.label)},{id:"hide-thinking",label:"Hide thinking",description:"Hide thinking blocks in assistant responses",currentValue:e.hideThinkingBlock?"true":"false",values:["true","false"]},{id:"collapse-changelog",label:"Collapse changelog",description:"Show condensed changelog after updates",currentValue:e.collapseChangelog?"true":"false",values:["true","false"]},{id:"quiet-startup",label:"Quiet startup",description:"Disable verbose printing at startup",currentValue:e.quietStartup?"true":"false",values:["true","false"]},{id:"install-telemetry",label:"Install telemetry",description:"Send an anonymous version/update ping after changelog-detected updates",currentValue:e.enableInstallTelemetry?"true":"false",values:["true","false"]},{id:"double-escape-action",label:"Double-escape action",description:"Action when pressing Escape twice with empty editor",currentValue:e.doubleEscapeAction,values:["tree","fork","none"]},{id:"tree-filter-mode",label:"Tree filter mode",description:"Default filter when opening /tree",currentValue:e.treeFilterMode,values:["default","no-tools","user-only","labeled-only","all"]},{id:"warnings",label:"Warnings",description:"Enable or disable individual warnings",currentValue:"configure",submenu:(g,h)=>new U0(r,f=>{r=f,n.onWarningsChange(f)},()=>h())},{id:"thinking",label:"Thinking level",description:"Reasoning depth for thinking-capable models",currentValue:e.thinkingLevel,submenu:(g,h)=>new Bp("Thinking Level","Select reasoning depth for thinking-capable models",e.availableThinkingLevels.map(f=>({value:f,label:f,description:nB[f]})),g,f=>{n.onThinkingLevelChange(f),h(f)},()=>h())},{id:"theme",label:"Theme",description:"Color theme for the interface",currentValue:e.currentTheme,submenu:(g,h)=>new Bp("Theme","Select color theme",e.availableThemes.map(f=>({value:f,label:f})),g,f=>{n.onThemeChange(f),h(f)},()=>{n.onThemePreview?.(g),h()},f=>{n.onThemePreview?.(f)})}];i&&(o.splice(1,0,{id:"show-images",label:"Show images",description:"Render images inline in terminal",currentValue:e.showImages?"true":"false",values:["true","false"]}),o.splice(2,0,{id:"image-width-cells",label:"Image width",description:"Preferred inline image width in terminal cells",currentValue:String(e.imageWidthCells),values:["60","80","120"]})),o.splice(i?3:1,0,{id:"auto-resize-images",label:"Auto-resize images",description:"Resize large images to 2000x2000 max for better model compatibility",currentValue:e.autoResizeImages?"true":"false",values:["true","false"]});let a=o.findIndex(g=>g.id==="auto-resize-images");o.splice(a+1,0,{id:"block-images",label:"Block images",description:"Prevent images from being sent to LLM providers",currentValue:e.blockImages?"true":"false",values:["true","false"]});let c=o.findIndex(g=>g.id==="block-images");o.splice(c+1,0,{id:"skill-commands",label:"Skill commands",description:"Register skills as /skill:name commands",currentValue:e.enableSkillCommands?"true":"false",values:["true","false"]});let l=o.findIndex(g=>g.id==="skill-commands");o.splice(l+1,0,{id:"show-hardware-cursor",label:"Show hardware cursor",description:"Show the terminal cursor while still positioning it for IME support",currentValue:e.showHardwareCursor?"true":"false",values:["true","false"]});let d=o.findIndex(g=>g.id==="show-hardware-cursor");o.splice(d+1,0,{id:"editor-padding",label:"Editor padding",description:"Horizontal padding for input editor (0-3)",currentValue:String(e.editorPaddingX),values:["0","1","2","3"]});let u=o.findIndex(g=>g.id==="editor-padding");o.splice(u+1,0,{id:"autocomplete-max-visible",label:"Autocomplete max items",description:"Max visible items in autocomplete dropdown (3-20)",currentValue:String(e.autocompleteMaxVisible),values:["3","5","7","10","15","20"]});let p=o.findIndex(g=>g.id==="autocomplete-max-visible");o.splice(p+1,0,{id:"clear-on-shrink",label:"Clear on shrink",description:"Clear empty rows when content shrinks (may cause flicker)",currentValue:e.clearOnShrink?"true":"false",values:["true","false"]});let m=o.findIndex(g=>g.id==="clear-on-shrink");o.splice(m+1,0,{id:"terminal-progress",label:"Terminal progress",description:"Show OSC 9;4 progress indicators in the terminal tab bar",currentValue:e.showTerminalProgress?"true":"false",values:["true","false"]}),this.addChild(new V),this.settingsList=new ca(o,10,$d(),(g,h)=>{switch(g){case"autocompact":n.onAutoCompactChange(h==="true");break;case"show-images":n.onShowImagesChange(h==="true");break;case"image-width-cells":n.onImageWidthCellsChange(parseInt(h,10));break;case"auto-resize-images":n.onAutoResizeImagesChange(h==="true");break;case"block-images":n.onBlockImagesChange(h==="true");break;case"skill-commands":n.onEnableSkillCommandsChange(h==="true");break;case"steering-mode":n.onSteeringModeChange(h);break;case"follow-up-mode":n.onFollowUpModeChange(h);break;case"transport":n.onTransportChange(h);break;case"http-idle-timeout":{let f=Pp.find(x=>x.label===h);f&&n.onHttpIdleTimeoutMsChange(f.timeoutMs);break}case"hide-thinking":n.onHideThinkingBlockChange(h==="true");break;case"collapse-changelog":n.onCollapseChangelogChange(h==="true");break;case"quiet-startup":n.onQuietStartupChange(h==="true");break;case"install-telemetry":n.onEnableInstallTelemetryChange(h==="true");break;case"double-escape-action":n.onDoubleEscapeActionChange(h);break;case"tree-filter-mode":n.onTreeFilterModeChange(h);break;case"show-hardware-cursor":n.onShowHardwareCursorChange(h==="true");break;case"editor-padding":n.onEditorPaddingXChange(parseInt(h,10));break;case"autocomplete-max-visible":n.onAutocompleteMaxVisibleChange(parseInt(h,10));break;case"clear-on-shrink":n.onClearOnShrinkChange(h==="true");break;case"terminal-progress":n.onShowTerminalProgressChange(h==="true");break}},n.onCancel,{enableSearch:!0}),this.addChild(this.settingsList),this.addChild(new V)}getSettingsList(){return this.settingsList}};var Ya=class extends ut{constructor(n,i=Tt()){super(1,1,s=>b.bg("customMessageBg",s));this.expanded=!1;this.skillBlock=n,this.markdownTheme=i,this.updateDisplay()}setExpanded(n){this.expanded=n,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){if(this.clear(),this.expanded){let n=b.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m");this.addChild(new A(n,0,0));let i=`**${this.skillBlock.name}**
|
|
316
|
+
`);for(let o of r)this.listContainer.addChild(new A(b.fg("error",o),0,0))}else if(this.filteredModels.length===0)this.listContainer.addChild(new A(b.fg("muted"," No matching models"),0,0));else{let r=this.filteredModels[this.selectedIndex];this.listContainer.addChild(new U(1)),this.listContainer.addChild(new A(b.fg("muted",` Model Name: ${r.model.name}`),0,0))}}handleInput(n){let i=ve();if(i.matches(n,"tui.input.tab")){if(this.scopedModelItems.length>0){let s=this.scope==="all"?"scoped":"all";this.setScope(s),this.scopeHintText&&this.scopeHintText.setText(this.getScopeHintText())}return}if(i.matches(n,"tui.select.up")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredModels.length-1:this.selectedIndex-1,this.updateList()}else if(i.matches(n,"tui.select.down")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredModels.length-1?0:this.selectedIndex+1,this.updateList()}else if(i.matches(n,"tui.select.confirm")){let s=this.filteredModels[this.selectedIndex];s&&this.handleSelect(s.model)}else i.matches(n,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(n),this.filterModels(this.searchInput.getValue()))}handleSelect(n){this.settingsManager.setDefaultModelAndProvider(n.provider,n.id),this.onSelectCallback(n)}getSearchInput(){return this.searchInput}};var Rr=class extends K{constructor(n,i,s,r,o,a){super();this._focused=!1;this.selectedIndex=0;this.mode=n,this.authStorage=i,this.getAuthStatus=a??(l=>this.authStorage.getAuthStatus(l)),this.allProviders=s,this.filteredProviders=s,this.onSelectCallback=r,this.onCancelCallback=o,this.addChild(new V),this.addChild(new U(1));let c=n==="login"?"Select provider to configure:":"Select provider to logout:";this.addChild(new Yt(b.fg("accent",b.bold(c)),1,0)),this.addChild(new U(1)),this.searchInput=new Qe,this.searchInput.onSubmit=()=>{let l=this.filteredProviders[this.selectedIndex];l&&this.onSelectCallback(l.id)},this.addChild(this.searchInput),this.addChild(new U(1)),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.addChild(new V),this.filterProviders("")}get focused(){return this._focused}set focused(n){this._focused=n,this.searchInput.focused=n}filterProviders(n){this.filteredProviders=n?Kt(this.allProviders,n,i=>`${i.name} ${i.id} ${i.authType}`):this.allProviders,this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,Math.max(0,this.filteredProviders.length-1))),this.updateList()}updateList(){this.listContainer.clear();let n=8,i=Math.max(0,Math.min(this.selectedIndex-Math.floor(n/2),this.filteredProviders.length-n)),s=Math.min(i+n,this.filteredProviders.length);for(let r=i;r<s;r++){let o=this.filteredProviders[r];if(!o)continue;let a=r===this.selectedIndex,c=this.formatStatusIndicator(o),l="";if(a){let d=b.fg("accent","\u2192 "),u=b.fg("accent",o.name);l=d+u+c}else l=` ${b.fg("text",o.name)}`+c;this.listContainer.addChild(new Yt(l,1,0))}if(i>0||s<this.filteredProviders.length){let r=b.fg("muted",` (${this.selectedIndex+1}/${this.filteredProviders.length})`);this.listContainer.addChild(new Yt(r,1,0))}if(this.filteredProviders.length===0){let r=this.allProviders.length===0?this.mode==="login"?"No providers available":"No providers logged in. Use /login first.":"No matching providers";this.listContainer.addChild(new Yt(b.fg("muted",` ${r}`),1,0))}}formatStatusIndicator(n){let i=this.authStorage.get(n.id);if(i?.type===n.authType)return b.fg("success"," \u2713 configured");if(i){let r=i.type==="oauth"?"subscription configured":"API key configured";return b.fg("muted"," \u2022 ")+b.fg("warning",r)}if(n.authType!=="api_key")return b.fg("muted"," \u2022 unconfigured");let s=this.getAuthStatus(n.id);switch(s.source){case"environment":return b.fg("success",` \u2713 env: ${s.label??"API key"}`);case"runtime":return b.fg("success"," \u2713 runtime API key");case"fallback":return b.fg("success"," \u2713 custom API key");case"models_json_key":return b.fg("success"," \u2713 key in models.json");case"models_json_command":return b.fg("success"," \u2713 command in models.json");default:return b.fg("muted"," \u2022 unconfigured")}}handleInput(n){let i=ve();if(i.matches(n,"tui.select.up")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList()}else if(i.matches(n,"tui.select.down")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.min(this.filteredProviders.length-1,this.selectedIndex+1),this.updateList()}else if(i.matches(n,"tui.select.confirm")){let s=this.filteredProviders[this.selectedIndex];s&&this.onSelectCallback(s.id)}else i.matches(n,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(n),this.filterProviders(this.searchInput.getValue()))}};function W0(t,e){return t===null||t.includes(e)}function X$(t,e){if(t===null)return[e];let n=t.indexOf(e);return n>=0?[...t.slice(0,n),...t.slice(n+1)]:[...t,e]}function _1(t,e,n){if(t===null)return null;let i=n??e,s=[...t];for(let r of i)s.includes(r)||s.push(r);return s.length===e.length?null:s}function E1(t,e,n){if(t===null)return n?e.filter(s=>!n.includes(s)):[];let i=new Set(n??t);return t.filter(s=>!i.has(s))}function Z$(t,e,n){if(t===null)return null;let i=[...t],s=i.indexOf(e);if(s<0)return i;let r=s+n;if(r<0||r>=i.length)return i;let o=[...i];return[o[s],o[r]]=[o[r],o[s]],o}function eB(t,e){if(t===null)return e;let n=new Set(t);return[...t,...e.filter(i=>!n.has(i))]}var $l=class extends K{constructor(n,i){super();this.modelsById=new Map;this.allIds=[];this.enabledIds=null;this.filteredItems=[];this.selectedIndex=0;this._focused=!1;this.maxVisible=8;this.isDirty=!1;this.callbacks=i;for(let s of n.allModels){let r=`${s.provider}/${s.id}`;this.modelsById.set(r,s),this.allIds.push(r)}this.enabledIds=n.enabledModelIds===null?null:[...n.enabledModelIds],this.filteredItems=this.buildItems(),this.addChild(new V),this.addChild(new U(1)),this.addChild(new A(b.fg("accent",b.bold("Model Configuration")),0,0)),this.addChild(new A(b.fg("muted",`Session-only. ${he("app.models.save")} to save to settings.`),0,0)),this.addChild(new U(1)),this.searchInput=new Qe,this.addChild(this.searchInput),this.addChild(new U(1)),this.listContainer=new K,this.addChild(this.listContainer),this.addChild(new U(1)),this.footerText=new A(this.getFooterText(),0,0),this.addChild(this.footerText),this.addChild(new V),this.updateList()}get focused(){return this._focused}set focused(n){this._focused=n,this.searchInput.focused=n}buildItems(){return eB(this.enabledIds,this.allIds).filter(n=>this.modelsById.has(n)).map(n=>({fullId:n,model:this.modelsById.get(n),enabled:W0(this.enabledIds,n)}))}getFooterText(){let n=this.enabledIds?.length??this.allIds.length,s=this.enabledIds===null?"all enabled":`${n}/${this.allIds.length} enabled`,r=[`${he("tui.select.confirm")} toggle`,`${he("app.models.enableAll")} all`,`${he("app.models.clearAll")} clear`,`${he("app.models.toggleProvider")} provider`,`${he("app.models.reorderUp")}/${he("app.models.reorderDown")} reorder`,`${he("app.models.save")} save`,s];return this.isDirty?b.fg("dim",` ${r.join(" \xB7 ")} `)+b.fg("warning","(unsaved)"):b.fg("dim",` ${r.join(" \xB7 ")}`)}refresh(){let n=this.searchInput.getValue(),i=this.buildItems();this.filteredItems=n?Kt(i,n,s=>`${s.model.id} ${s.model.provider}`):i,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList(),this.footerText.setText(this.getFooterText())}notifyChange(){this.callbacks.onChange(this.enabledIds===null?null:[...this.enabledIds])}updateList(){if(this.listContainer.clear(),this.filteredItems.length===0){this.listContainer.addChild(new A(b.fg("muted"," No matching models"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),i=Math.min(n+this.maxVisible,this.filteredItems.length),s=this.enabledIds===null;for(let r=n;r<i;r++){let o=this.filteredItems[r],a=r===this.selectedIndex,c=a?b.fg("accent","\u2192 "):" ",l=a?b.fg("accent",o.model.id):o.model.id,d=b.fg("muted",` [${o.model.provider}]`),u=s?"":o.enabled?b.fg("success"," \u2713"):b.fg("dim"," \u2717");this.listContainer.addChild(new A(`${c}${l}${d}${u}`,0,0))}if((n>0||i<this.filteredItems.length)&&this.listContainer.addChild(new A(b.fg("muted",` (${this.selectedIndex+1}/${this.filteredItems.length})`),0,0)),this.filteredItems.length>0){let r=this.filteredItems[this.selectedIndex];this.listContainer.addChild(new U(1)),this.listContainer.addChild(new A(b.fg("muted",` Model Name: ${r.model.name}`),0,0))}}handleInput(n){let i=ve();if(i.matches(n,"tui.select.up")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(i.matches(n,"tui.select.down")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}let s=i.matches(n,"app.models.reorderUp"),r=i.matches(n,"app.models.reorderDown");if(s||r){if(this.enabledIds===null)return;let o=this.filteredItems[this.selectedIndex];if(o&&W0(this.enabledIds,o.fullId)){let a=s?-1:1,l=this.enabledIds.indexOf(o.fullId)+a;l>=0&&l<this.enabledIds.length&&(this.enabledIds=Z$(this.enabledIds,o.fullId,a),this.isDirty=!0,this.selectedIndex+=a,this.refresh(),this.notifyChange())}return}if(i.matches(n,"tui.select.confirm")){let o=this.filteredItems[this.selectedIndex];o&&(this.enabledIds=X$(this.enabledIds,o.fullId),this.isDirty=!0,this.refresh(),this.notifyChange());return}if(i.matches(n,"app.models.enableAll")){let o=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=_1(this.enabledIds,this.allIds,o),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(i.matches(n,"app.models.clearAll")){let o=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=E1(this.enabledIds,this.allIds,o),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(i.matches(n,"app.models.toggleProvider")){let o=this.filteredItems[this.selectedIndex];if(o){let a=o.model.provider,c=this.allIds.filter(d=>this.modelsById.get(d).provider===a),l=c.every(d=>W0(this.enabledIds,d));this.enabledIds=l?E1(this.enabledIds,this.allIds,c):_1(this.enabledIds,this.allIds,c),this.isDirty=!0,this.refresh(),this.notifyChange()}return}if(i.matches(n,"app.models.save")){this.callbacks.onPersist(this.enabledIds===null?null:[...this.enabledIds]),this.isDirty=!1,this.footerText.setText(this.getFooterText());return}if(Ee(n,ar.ctrl("c"))){this.searchInput.getValue()?(this.searchInput.setValue(""),this.refresh()):this.callbacks.onCancel();return}if(Ee(n,ar.escape)){this.callbacks.onCancel();return}this.searchInput.handleInput(n),this.refresh()}getSearchInput(){return this.searchInput}};var tB={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},nB={off:"No reasoning",minimal:"Very brief reasoning (~1k tokens)",low:"Light reasoning (~2k tokens)",medium:"Moderate reasoning (~8k tokens)",high:"Deep reasoning (~16k tokens)",xhigh:"Maximum reasoning (~32k tokens)"},U0=class extends K{constructor(e,n,i){super(),this.state={...e};let s=[{id:"anthropic-extra-usage",label:"Anthropic extra usage",description:"Warn when Anthropic subscription auth may use paid extra usage",currentValue:this.state.anthropicExtraUsage??!0?"true":"false",values:["true","false"]}];this.settingsList=new ca(s,Math.min(s.length,10),$d(),(r,o)=>{r==="anthropic-extra-usage"&&(this.state={...this.state,anthropicExtraUsage:o==="true"},n({...this.state}))},i),this.addChild(this.settingsList)}handleInput(e){this.settingsList.handleInput(e)}},Bp=class extends K{constructor(e,n,i,s,r,o,a){super(),this.addChild(new A(b.bold(b.fg("accent",e)),0,0)),n&&(this.addChild(new U(1)),this.addChild(new A(b.fg("muted",n),0,0))),this.addChild(new U(1)),this.selectList=new Qt(i,Math.min(i.length,10),yr(),tB);let c=i.findIndex(l=>l.value===s);c!==-1&&this.selectList.setSelectedIndex(c),this.selectList.onSelect=l=>{r(l.value)},this.selectList.onCancel=o,a&&(this.selectList.onSelectionChange=l=>{a(l.value)}),this.addChild(this.selectList),this.addChild(new U(1)),this.addChild(new A(b.fg("dim"," Enter to select \xB7 Esc to go back"),0,0))}handleInput(e){this.selectList.handleInput(e)}},Qa=class extends K{constructor(e,n){super();let i=dt().images,s=xl("app.message.followUp"),r={...e.warnings},o=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:e.autoCompact?"true":"false",values:["true","false"]},{id:"steering-mode",label:"Steering mode",description:"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.",currentValue:e.steeringMode,values:["one-at-a-time","all"]},{id:"follow-up-mode",label:"Follow-up mode",description:`${s} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,currentValue:e.followUpMode,values:["one-at-a-time","all"]},{id:"transport",label:"Transport",description:"Preferred transport for providers that support multiple transports",currentValue:e.transport,values:["sse","websocket","websocket-cached","auto"]},{id:"http-idle-timeout",label:"HTTP idle timeout",description:"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.",currentValue:Ep(e.httpIdleTimeoutMs),values:Pp.map(g=>g.label)},{id:"hide-thinking",label:"Hide thinking",description:"Hide thinking blocks in assistant responses",currentValue:e.hideThinkingBlock?"true":"false",values:["true","false"]},{id:"collapse-changelog",label:"Collapse changelog",description:"Show condensed changelog after updates",currentValue:e.collapseChangelog?"true":"false",values:["true","false"]},{id:"quiet-startup",label:"Quiet startup",description:"Disable verbose printing at startup",currentValue:e.quietStartup?"true":"false",values:["true","false"]},{id:"install-telemetry",label:"Install telemetry",description:"Send an anonymous version/update ping after changelog-detected updates",currentValue:e.enableInstallTelemetry?"true":"false",values:["true","false"]},{id:"double-escape-action",label:"Double-escape action",description:"Action when pressing Escape twice with empty editor",currentValue:e.doubleEscapeAction,values:["tree","fork","none"]},{id:"tree-filter-mode",label:"Tree filter mode",description:"Default filter when opening /tree",currentValue:e.treeFilterMode,values:["default","no-tools","user-only","labeled-only","all"]},{id:"warnings",label:"Warnings",description:"Enable or disable individual warnings",currentValue:"configure",submenu:(g,h)=>new U0(r,f=>{r=f,n.onWarningsChange(f)},()=>h())},{id:"thinking",label:"Thinking level",description:"Reasoning depth for thinking-capable models",currentValue:e.thinkingLevel,submenu:(g,h)=>new Bp("Thinking Level","Select reasoning depth for thinking-capable models",e.availableThinkingLevels.map(f=>({value:f,label:f,description:nB[f]})),g,f=>{n.onThinkingLevelChange(f),h(f)},()=>h())},{id:"theme",label:"Theme",description:"Color theme for the interface",currentValue:e.currentTheme,submenu:(g,h)=>new Bp("Theme","Select color theme",e.availableThemes.map(f=>({value:f,label:f})),g,f=>{n.onThemeChange(f),h(f)},()=>{n.onThemePreview?.(g),h()},f=>{n.onThemePreview?.(f)})}];i&&(o.splice(1,0,{id:"show-images",label:"Show images",description:"Render images inline in terminal",currentValue:e.showImages?"true":"false",values:["true","false"]}),o.splice(2,0,{id:"image-width-cells",label:"Image width",description:"Preferred inline image width in terminal cells",currentValue:String(e.imageWidthCells),values:["60","80","120"]})),o.splice(i?3:1,0,{id:"auto-resize-images",label:"Auto-resize images",description:"Resize large images to 2000x2000 max for better model compatibility",currentValue:e.autoResizeImages?"true":"false",values:["true","false"]});let a=o.findIndex(g=>g.id==="auto-resize-images");o.splice(a+1,0,{id:"block-images",label:"Block images",description:"Prevent images from being sent to LLM providers",currentValue:e.blockImages?"true":"false",values:["true","false"]});let c=o.findIndex(g=>g.id==="block-images");o.splice(c+1,0,{id:"skill-commands",label:"Skill commands",description:"Register skills as /skill:name commands",currentValue:e.enableSkillCommands?"true":"false",values:["true","false"]});let l=o.findIndex(g=>g.id==="skill-commands");o.splice(l+1,0,{id:"show-hardware-cursor",label:"Show hardware cursor",description:"Show the terminal cursor while still positioning it for IME support",currentValue:e.showHardwareCursor?"true":"false",values:["true","false"]});let d=o.findIndex(g=>g.id==="show-hardware-cursor");o.splice(d+1,0,{id:"editor-padding",label:"Editor padding",description:"Horizontal padding for input editor (0-3)",currentValue:String(e.editorPaddingX),values:["0","1","2","3"]});let u=o.findIndex(g=>g.id==="editor-padding");o.splice(u+1,0,{id:"autocomplete-max-visible",label:"Autocomplete max items",description:"Max visible items in autocomplete dropdown (3-20)",currentValue:String(e.autocompleteMaxVisible),values:["3","5","7","10","15","20"]});let p=o.findIndex(g=>g.id==="autocomplete-max-visible");o.splice(p+1,0,{id:"clear-on-shrink",label:"Clear on shrink",description:"Clear empty rows when content shrinks (may cause flicker)",currentValue:e.clearOnShrink?"true":"false",values:["true","false"]});let m=o.findIndex(g=>g.id==="clear-on-shrink");o.splice(m+1,0,{id:"terminal-progress",label:"Terminal progress",description:"Show OSC 9;4 progress indicators in the terminal tab bar",currentValue:e.showTerminalProgress?"true":"false",values:["true","false"]}),this.addChild(new V),this.settingsList=new ca(o,10,$d(),(g,h)=>{switch(g){case"autocompact":n.onAutoCompactChange(h==="true");break;case"show-images":n.onShowImagesChange(h==="true");break;case"image-width-cells":n.onImageWidthCellsChange(parseInt(h,10));break;case"auto-resize-images":n.onAutoResizeImagesChange(h==="true");break;case"block-images":n.onBlockImagesChange(h==="true");break;case"skill-commands":n.onEnableSkillCommandsChange(h==="true");break;case"steering-mode":n.onSteeringModeChange(h);break;case"follow-up-mode":n.onFollowUpModeChange(h);break;case"transport":n.onTransportChange(h);break;case"http-idle-timeout":{let f=Pp.find(x=>x.label===h);f&&n.onHttpIdleTimeoutMsChange(f.timeoutMs);break}case"hide-thinking":n.onHideThinkingBlockChange(h==="true");break;case"collapse-changelog":n.onCollapseChangelogChange(h==="true");break;case"quiet-startup":n.onQuietStartupChange(h==="true");break;case"install-telemetry":n.onEnableInstallTelemetryChange(h==="true");break;case"double-escape-action":n.onDoubleEscapeActionChange(h);break;case"tree-filter-mode":n.onTreeFilterModeChange(h);break;case"show-hardware-cursor":n.onShowHardwareCursorChange(h==="true");break;case"editor-padding":n.onEditorPaddingXChange(parseInt(h,10));break;case"autocomplete-max-visible":n.onAutocompleteMaxVisibleChange(parseInt(h,10));break;case"clear-on-shrink":n.onClearOnShrinkChange(h==="true");break;case"terminal-progress":n.onShowTerminalProgressChange(h==="true");break}},n.onCancel,{enableSearch:!0}),this.addChild(this.settingsList),this.addChild(new V)}getSettingsList(){return this.settingsList}};var Ya=class extends ut{constructor(n,i=Tt()){super(1,1,s=>b.bg("customMessageBg",s));this.expanded=!1;this.skillBlock=n,this.markdownTheme=i,this.updateDisplay()}setExpanded(n){this.expanded=n,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){if(this.clear(),this.expanded){let n=b.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m");this.addChild(new A(n,0,0));let i=`**${this.skillBlock.name}**
|
|
317
317
|
|
|
318
318
|
`;this.addChild(new ze(i+this.skillBlock.content,0,0,this.markdownTheme,{color:s=>b.fg("customMessageText",s)}))}else{let n=b.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+b.fg("customMessageText",this.skillBlock.name)+b.fg("dim",` (${he("app.tools.expand")} to expand)`);this.addChild(new A(n,0,0))}}};async function A1(t,e){if(e==="image/png")return{data:t,mimeType:e};let n=await Ia();if(!n)return null;try{let i=new Uint8Array(Buffer.from(t,"base64")),s=n.PhotonImage.new_from_byteslice(i),r=gp(n,s,i);r!==s&&s.free();try{let o=r.get_bytes();return{data:Buffer.from(o).toString("base64"),mimeType:"image/png"}}finally{r.free()}}catch{return null}}var fi=class extends K{constructor(n,i,s,r={},o,a,c){super();this.rendererState={};this.imageComponents=[];this.imageSpacers=[];this.expanded=!1;this.isPartial=!0;this.executionStarted=!1;this.argsComplete=!1;this.convertedImages=new Map;this.hideComponent=!1;this.toolName=n,this.toolCallId=i,this.args=s,this.toolDefinition=o,this.builtInToolDefinition=s0(c)[n],this.showImages=r.showImages??!0,this.imageWidthCells=r.imageWidthCells??60,this.ui=a,this.cwd=c,this.addChild(new U(1)),this.contentBox=new ut(1,1,l=>b.bg("toolPendingBg",l)),this.contentText=new A("",1,1,l=>b.bg("toolPendingBg",l)),this.selfRenderContainer=new K,this.hasRendererDefinition()?this.addChild(this.getRenderShell()==="self"?this.selfRenderContainer:this.contentBox):this.addChild(this.contentText),this.updateDisplay()}getCallRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderCall??this.builtInToolDefinition.renderCall:this.builtInToolDefinition.renderCall:this.toolDefinition?.renderCall}getResultRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderResult??this.builtInToolDefinition.renderResult:this.builtInToolDefinition.renderResult:this.toolDefinition?.renderResult}hasRendererDefinition(){return this.builtInToolDefinition!==void 0||this.toolDefinition!==void 0}getRenderShell(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderShell??this.builtInToolDefinition.renderShell??"default":this.builtInToolDefinition.renderShell??"default":this.toolDefinition?.renderShell??"default"}getRenderContext(n){return{args:this.args,toolCallId:this.toolCallId,invalidate:()=>{this.invalidate(),this.ui.requestRender()},lastComponent:n,state:this.rendererState,cwd:this.cwd,executionStarted:this.executionStarted,argsComplete:this.argsComplete,isPartial:this.isPartial,expanded:this.expanded,showImages:this.showImages,isError:this.result?.isError??!1}}createCallFallback(){return new A(b.fg("toolTitle",b.bold(this.toolName)),0,0)}createResultFallback(){let n=this.getTextOutput();if(n)return new A(b.fg("toolOutput",n),0,0)}updateArgs(n){this.args=n,this.updateDisplay()}markExecutionStarted(){this.executionStarted=!0,this.updateDisplay(),this.ui.requestRender()}setArgsComplete(){this.argsComplete=!0,this.updateDisplay(),this.ui.requestRender()}updateResult(n,i=!1){this.result=n,this.isPartial=i,this.updateDisplay(),this.maybeConvertImagesForKitty()}maybeConvertImagesForKitty(){if(dt().images!=="kitty"||!this.result)return;let i=this.result.content.filter(s=>s.type==="image");for(let s=0;s<i.length;s++){let r=i[s];if(!r.data||!r.mimeType||r.mimeType==="image/png"||this.convertedImages.has(s))continue;let o=s;A1(r.data,r.mimeType).then(a=>{a&&(this.convertedImages.set(o,a),this.updateDisplay(),this.ui.requestRender())})}}setExpanded(n){this.expanded=n,this.updateDisplay()}setShowImages(n){this.showImages=n,this.updateDisplay()}setImageWidthCells(n){this.imageWidthCells=Math.max(1,Math.floor(n)),this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}render(n){return this.hideComponent?[]:super.render(n)}updateDisplay(){let n=this.isPartial?s=>b.bg("toolPendingBg",s):this.result?.isError?s=>b.bg("toolErrorBg",s):s=>b.bg("toolSuccessBg",s),i=!1;if(this.hideComponent=!1,this.hasRendererDefinition()){let s=this.getRenderShell()==="self"?this.selfRenderContainer:this.contentBox;s instanceof ut&&s.setBgFn(n),s.clear();let r=this.getCallRenderer();if(!r)s.addChild(this.createCallFallback()),i=!0;else try{let o=r(this.args,b,this.getRenderContext(this.callRendererComponent));this.callRendererComponent=o,s.addChild(o),i=!0}catch{this.callRendererComponent=void 0,s.addChild(this.createCallFallback()),i=!0}if(this.result){let o=this.getResultRenderer();if(o)try{let a=o({content:this.result.content,details:this.result.details},{expanded:this.expanded,isPartial:this.isPartial},b,this.getRenderContext(this.resultRendererComponent));this.resultRendererComponent=a,s.addChild(a),i=!0}catch{this.resultRendererComponent=void 0;let a=this.createResultFallback();a&&(s.addChild(a),i=!0)}else{let a=this.createResultFallback();a&&(s.addChild(a),i=!0)}}}else this.contentText.setCustomBgFn(n),this.contentText.setText(this.formatToolExecution()),i=!0;for(let s of this.imageComponents)this.removeChild(s);this.imageComponents=[];for(let s of this.imageSpacers)this.removeChild(s);if(this.imageSpacers=[],this.result){let s=this.result.content.filter(o=>o.type==="image"),r=dt();for(let o=0;o<s.length;o++){let a=s[o];if(r.images&&this.showImages&&a.data&&a.mimeType){let c=this.convertedImages.get(o),l=c?.data??a.data,d=c?.mimeType??a.mimeType;if(r.images==="kitty"&&d!=="image/png")continue;let u=new U(1);this.addChild(u),this.imageSpacers.push(u);let p=new dr(l,d,{fallbackColor:m=>b.fg("toolOutput",m)},{maxWidthCells:this.imageWidthCells});this.imageComponents.push(p),this.addChild(p)}}}this.hasRendererDefinition()&&!i&&this.imageComponents.length===0&&(this.hideComponent=!0)}getTextOutput(){return On(this.result,this.showImages)}formatToolExecution(){let n=b.fg("toolTitle",b.bold(this.toolName)),i=JSON.stringify(this.args,null,2);i&&(n+=`
|
|
319
319
|
|
|
@@ -326,7 +326,7 @@ ${o}
|
|
|
326
326
|
${a}`,()=>`${n}
|
|
327
327
|
${s}
|
|
328
328
|
|
|
329
|
-
${a}`,this.getStartupExpansionState(),1,0),this.headerContainer.addChild(new U(1)),this.headerContainer.addChild(this.builtInHeader),this.headerContainer.addChild(new U(1))}else this.builtInHeader=new A("",0,0),this.headerContainer.addChild(this.builtInHeader);this.ui.addChild(this.chatContainer),this.ui.addChild(this.pendingMessagesContainer),this.ui.addChild(this.statusContainer),this.renderWidgets(),this.ui.addChild(this.widgetContainerAbove),this.ui.addChild(this.editorContainer),this.ui.addChild(this.widgetContainerBelow),this.ui.addChild(this.footer),this.ui.setFocus(this.editor),this.setupKeyHandlers(),this.setupEditorSubmitHandler(),this.ui.start(),this.isInitialized=!0,await this.rebindCurrentSession(),this.renderInitialMessages(),mT(()=>{this.ui.invalidate(),this.updateEditorBorderColor(),this.ui.requestRender()}),this.footerDataProvider.onBranchChange(()=>{this.ui.requestRender()}),await this.updateAvailableProviderCount()}updateTerminalTitle(){let e=Ve.basename(this.sessionManager.getCwd()),n=this.sessionManager.getSessionName();n?this.ui.terminal.setTitle(`${rg} - ${n} - ${e}`):this.ui.terminal.setTitle(`${rg} - ${e}`)}async run(){await this.init(),x1(this.version).then(a=>{a&&this.showNewVersionNotification(a)}),this.checkForPackageUpdates().then(a=>{a.length>0&&this.showPackageUpdateNotification(a)}),this.checkTmuxKeyboardSetup().then(a=>{a&&this.showWarning(a)});let{migratedProviders:e,modelFallbackMessage:n,initialMessage:i,initialImages:s,initialMessages:r}=this.options;e&&e.length>0&&this.showWarning(`Migrated credentials to auth.json: ${e.join(", ")}`);let o=this.session.modelRegistry.getError();if(o&&this.showError(`models.json error: ${o}`),n&&this.showWarning(n),this.maybeWarnAboutAnthropicSubscriptionAuth(),i)try{await this.session.prompt(i,{images:s})}catch(a){let c=a instanceof Error?a.message:"Unknown error occurred";this.showError(c)}if(r)for(let a of r)try{await this.session.prompt(a)}catch(c){let l=c instanceof Error?c.message:"Unknown error occurred";this.showError(l)}for(;;){let a=await this.getUserInput();try{await this.session.prompt(a)}catch(c){let l=c instanceof Error?c.message:"Unknown error occurred";this.showError(l)}}}async checkForPackageUpdates(){if(process.env.PI_OFFLINE)return[];try{return(await new Ni({cwd:this.sessionManager.getCwd(),agentDir:
|
|
329
|
+
${a}`,this.getStartupExpansionState(),1,0),this.headerContainer.addChild(new U(1)),this.headerContainer.addChild(this.builtInHeader),this.headerContainer.addChild(new U(1))}else this.builtInHeader=new A("",0,0),this.headerContainer.addChild(this.builtInHeader);this.ui.addChild(this.chatContainer),this.ui.addChild(this.pendingMessagesContainer),this.ui.addChild(this.statusContainer),this.renderWidgets(),this.ui.addChild(this.widgetContainerAbove),this.ui.addChild(this.editorContainer),this.ui.addChild(this.widgetContainerBelow),this.ui.addChild(this.footer),this.ui.setFocus(this.editor),this.setupKeyHandlers(),this.setupEditorSubmitHandler(),this.ui.start(),this.isInitialized=!0,await this.rebindCurrentSession(),this.renderInitialMessages(),mT(()=>{this.ui.invalidate(),this.updateEditorBorderColor(),this.ui.requestRender()}),this.footerDataProvider.onBranchChange(()=>{this.ui.requestRender()}),await this.updateAvailableProviderCount()}updateTerminalTitle(){let e=Ve.basename(this.sessionManager.getCwd()),n=this.sessionManager.getSessionName();n?this.ui.terminal.setTitle(`${rg} - ${n} - ${e}`):this.ui.terminal.setTitle(`${rg} - ${e}`)}async run(){await this.init(),x1(this.version).then(a=>{a&&this.showNewVersionNotification(a)}),this.checkForPackageUpdates().then(a=>{a.length>0&&this.showPackageUpdateNotification(a)}),this.checkTmuxKeyboardSetup().then(a=>{a&&this.showWarning(a)});let{migratedProviders:e,modelFallbackMessage:n,initialMessage:i,initialImages:s,initialMessages:r}=this.options;e&&e.length>0&&this.showWarning(`Migrated credentials to auth.json: ${e.join(", ")}`);let o=this.session.modelRegistry.getError();if(o&&this.showError(`models.json error: ${o}`),n&&this.showWarning(n),this.maybeWarnAboutAnthropicSubscriptionAuth(),i)try{await this.session.prompt(i,{images:s})}catch(a){let c=a instanceof Error?a.message:"Unknown error occurred";this.showError(c)}if(r)for(let a of r)try{await this.session.prompt(a)}catch(c){let l=c instanceof Error?c.message:"Unknown error occurred";this.showError(l)}for(;;){let a=await this.getUserInput();try{await this.session.prompt(a)}catch(c){let l=c instanceof Error?c.message:"Unknown error occurred";this.showError(l)}}}async checkForPackageUpdates(){if(process.env.PI_OFFLINE)return[];try{return(await new Ni({cwd:this.sessionManager.getCwd(),agentDir:_e(),settingsManager:this.settingsManager}).checkForAvailableUpdates()).map(i=>i.displayName)}catch{return[]}}async checkTmuxKeyboardSetup(){if(!process.env.TMUX)return;let e=s=>new Promise(r=>{let o=N0("tmux",["show","-gv",s],{stdio:["ignore","pipe","ignore"]}),a="",c=setTimeout(()=>{o.kill(),r(void 0)},2e3);o.stdout?.on("data",l=>{a+=l.toString()}),o.on("error",()=>{clearTimeout(c),r(void 0)}),o.on("close",l=>{clearTimeout(c),r(l===0?a.trim():void 0)})}),[n,i]=await Promise.all([e("extended-keys"),e("extended-keys-format")]);if(n!==void 0){if(n!=="on"&&n!=="always")return"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.";if(i==="xterm")return"tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux."}}getChangelogForDisplay(){if(this.session.state.messages.length>0)return;let e=this.settingsManager.getLastChangelogVersion(),n=ed(),i=_0(n);if(!e){this.settingsManager.setLastChangelogVersion(Ai),this.reportInstallTelemetry(Ai);return}let s=c1(i,e);if(s.length>0)return this.settingsManager.setLastChangelogVersion(Ai),this.reportInstallTelemetry(Ai),s.map(r=>r.content).join(`
|
|
330
330
|
|
|
331
331
|
`)}reportInstallTelemetry(e){process.env.PI_OFFLINE||C0(this.settingsManager)&&fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(e)}`,{headers:{"User-Agent":Fp(e)},signal:AbortSignal.timeout(5e3)}).then(()=>{}).catch(()=>{})}getMarkdownThemeWithSettings(){return{...Tt(),codeBlockIndent:this.settingsManager.getCodeBlockIndent()}}formatDisplayPath(e){let n=ec.homedir(),i=e;return i.startsWith(n)&&(i=`~${i.slice(n.length)}`),i}formatExtensionDisplayPath(e){let n=this.formatDisplayPath(e);return n=n.replace(/\/index\.ts$/,"").replace(/\/index\.js$/,""),n}formatContextPath(e){let n=Ve.resolve(this.sessionManager.getCwd()),i=Ve.isAbsolute(e)?Ve.resolve(e):Ve.resolve(n,e),s=np(i,n);return s!==void 0?s:this.formatDisplayPath(i)}getStartupExpansionState(){return this.options.verbose||this.toolOutputExpanded}getShortPath(e,n){let i=n?.baseDir;if(i&&this.isPackageSource(n)){let a=Ve.relative(Ve.resolve(i),Ve.resolve(e));if(a&&a!=="."&&!a.startsWith("..")&&!a.startsWith(`..${Ve.sep}`)&&!Ve.isAbsolute(a))return a.replace(/\\/g,"/")}let s=n?.source??"",r=e.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);if(r&&s.startsWith("npm:"))return r[2];let o=e.match(/git\/[^/]+\/[^/]+\/(.*)/);return o&&s.startsWith("git:")?o[1]:this.formatDisplayPath(e)}getCompactPathLabel(e,n){let i=this.getShortPath(e,n),r=i.replace(/\\/g,"/").split("/").filter(o=>o.length>0&&o!=="~");return r.length>0?r[r.length-1]:i}getCompactPackageSourceLabel(e){let n=e?.source??"";if(n.startsWith("npm:"))return n.slice(4)||n;let i=Rl(n);return i&&i.path||n}getCompactExtensionLabel(e,n){if(!this.isPackageSource(n))return this.getCompactPathLabel(e,n);let i=this.getCompactPackageSourceLabel(n);if(!i)return this.getCompactPathLabel(e,n);let s=this.getShortPath(e,n).replace(/\\/g,"/"),r=s.startsWith("extensions/")?s.slice(11):s,o=Ve.posix.parse(r);return o.name==="index"?!o.dir||o.dir==="."?i:`${i}:${o.dir}`:`${i}:${r}`}getCompactDisplayPathSegments(e){return this.formatDisplayPath(e).replace(/\\/g,"/").split("/").filter(n=>n.length>0&&n!=="~")}getCompactNonPackageExtensionLabel(e,n,i){let s=i[n]?.segments;if(!s||s.length===0)return this.getCompactPathLabel(e);for(let r=1;r<=s.length;r+=1){let o=s.slice(-r).join("/");if(i.every((c,l)=>l===n?!0:c.segments.slice(-r).join("/")!==o))return o}return s.join("/")}getCompactExtensionLabels(e){let n=e.map(i=>{let s=this.getCompactDisplayPathSegments(i.path),r=s[s.length-1];return s.length>1&&(r==="index.ts"||r==="index.js")&&s.pop(),{path:i.path,sourceInfo:i.sourceInfo,segments:s}}).filter(i=>!this.isPackageSource(i.sourceInfo));return e.map(i=>{if(this.isPackageSource(i.sourceInfo))return this.getCompactExtensionLabel(i.path,i.sourceInfo);let s=n.findIndex(r=>r.path===i.path);return s===-1?this.getCompactPathLabel(i.path,i.sourceInfo):this.getCompactNonPackageExtensionLabel(i.path,s,n)})}getDisplaySourceInfo(e){let n=e?.source??"local",i=e?.scope??"project";return n==="local"?i==="user"?{label:"user",color:"muted"}:i==="project"?{label:"project",color:"muted"}:i==="temporary"?{label:"path",scopeLabel:"temp",color:"muted"}:{label:"path",color:"muted"}:n==="cli"?{label:"path",scopeLabel:i==="temporary"?"temp":void 0,color:"muted"}:{label:n,scopeLabel:i==="user"?"user":i==="project"?"project":i==="temporary"?"temp":void 0,color:"accent"}}getScopeGroup(e){let n=e?.source??"local",i=e?.scope??"project";return n==="cli"||i==="temporary"?"path":i==="user"?"user":i==="project"?"project":"path"}isPackageSource(e){let n=e?.source??"";return n.startsWith("npm:")||n.startsWith("git:")}buildScopeGroups(e){let n={user:{scope:"user",paths:[],packages:new Map},project:{scope:"project",paths:[],packages:new Map},path:{scope:"path",paths:[],packages:new Map}};for(let i of e){let s=this.getScopeGroup(i.sourceInfo),r=n[s],o=i.sourceInfo?.source??"local";if(this.isPackageSource(i.sourceInfo)){let a=r.packages.get(o)??[];a.push(i),r.packages.set(o,a)}else r.paths.push(i)}return[n.project,n.user,n.path].filter(i=>i.paths.length>0||i.packages.size>0)}formatScopeGroups(e,n){let i=[];for(let s of e){i.push(` ${b.fg("accent",s.scope)}`);let r=[...s.paths].sort((a,c)=>a.path.localeCompare(c.path));for(let a of r)i.push(b.fg("dim",` ${n.formatPath(a)}`));let o=Array.from(s.packages.entries()).sort(([a],[c])=>a.localeCompare(c));for(let[a,c]of o){i.push(` ${b.fg("mdLink",a)}`);let l=[...c].sort((d,u)=>d.path.localeCompare(u.path));for(let d of l)i.push(b.fg("dim",` ${n.formatPackagePath(d,a)}`))}}return i.join(`
|
|
332
332
|
`)}findSourceInfoForPath(e,n){let i=n.get(e);if(i)return i;let s=e;for(;s.includes("/");){s=s.substring(0,s.lastIndexOf("/"));let r=n.get(s);if(r)return r}}formatPathWithSource(e,n){if(n){let i=this.getShortPath(e,n),{label:s,scopeLabel:r}=this.getDisplaySourceInfo(n);return`${r?`${s} (${r})`:s} ${i}`}return this.formatDisplayPath(e)}formatDiagnostics(e,n){let i=[],s=new Map,r=[];for(let o of e)if(o.type==="collision"&&o.collision){let a=s.get(o.collision.name)??[];a.push(o),s.set(o.collision.name,a)}else r.push(o);for(let[o,a]of s){let c=a[0]?.collision;if(c){i.push(b.fg("warning",` "${o}" collision:`)),i.push(b.fg("dim",` ${b.fg("success","\u2713")} ${this.formatPathWithSource(c.winnerPath,this.findSourceInfoForPath(c.winnerPath,n))}`));for(let l of a)l.collision&&i.push(b.fg("dim",` ${b.fg("warning","\u2717")} ${this.formatPathWithSource(l.collision.loserPath,this.findSourceInfoForPath(l.collision.loserPath,n))} (skipped)`))}}for(let o of r)if(o.path){let a=this.formatPathWithSource(o.path,this.findSourceInfoForPath(o.path,n));i.push(b.fg(o.type==="error"?"error":"warning",` ${a}`)),i.push(b.fg(o.type==="error"?"error":"warning",` ${o.message}`))}else i.push(b.fg(o.type==="error"?"error":"warning",` ${o.message}`));return i.join(`
|
|
@@ -337,7 +337,7 @@ ${g}`,this.getStartupExpansionState(),0,0);this.chatContainer.addChild(f),this.c
|
|
|
337
337
|
${w}`,0,0)),this.chatContainer.addChild(new U(1))}let m=c.diagnostics;if(m.length>0){let w=this.formatDiagnostics(m,u);this.chatContainer.addChild(new A(`${b.fg("warning","[Prompt conflicts]")}
|
|
338
338
|
${w}`,0,0)),this.chatContainer.addChild(new U(1))}let g=[],h=this.session.resourceLoader.getExtensions().errors;if(h.length>0)for(let w of h)g.push({type:"error",message:w.error,path:w.path});let f=this.session.extensionRunner.getCommandDiagnostics();g.push(...f),g.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));let x=this.session.extensionRunner.getShortcutDiagnostics();if(g.push(...x),g.length>0){let w=this.formatDiagnostics(g,u);this.chatContainer.addChild(new A(`${b.fg("warning","[Extension issues]")}
|
|
339
339
|
${w}`,0,0)),this.chatContainer.addChild(new U(1))}let y=l.diagnostics;if(y.length>0){let w=this.formatDiagnostics(y,u);this.chatContainer.addChild(new A(`${b.fg("warning","[Theme conflicts]")}
|
|
340
|
-
${w}`,0,0)),this.chatContainer.addChild(new U(1))}}}async bindCurrentSessionExtensions(){let e=this.createExtensionUIContext();await this.session.bindExtensions({uiContext:e,abortHandler:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},commandContextActions:{waitForIdle:()=>this.session.agent.waitForIdle(),newSession:async i=>{this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{let s=await this.runtimeHost.newSession(i);return s.cancelled||(this.renderCurrentSessionState(),this.ui.requestRender()),s}catch(s){return this.handleFatalRuntimeError("Failed to create session",s)}},fork:async(i,s)=>{try{let r=await this.runtimeHost.fork(i,s);return r.cancelled||(this.renderCurrentSessionState(),this.editor.setText(r.selectedText??""),this.showStatus("Forked to new session")),{cancelled:r.cancelled}}catch(r){return this.handleFatalRuntimeError("Failed to fork session",r)}},navigateTree:async(i,s)=>{let r=await this.session.navigateTree(i,{summarize:s?.summarize,customInstructions:s?.customInstructions,replaceInstructions:s?.replaceInstructions,label:s?.label});return r.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),r.editorText&&!this.editor.getText().trim()&&this.editor.setText(r.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1}),{cancelled:!1})},switchSession:async(i,s)=>this.handleResumeSession(i,s),reload:async()=>{await this.handleReloadCommand()}},shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isStreaming||this.shutdown()},onError:i=>{this.showExtensionError(i.extensionPath,i.error,i.stack)}}),Dd(this.session.resourceLoader.getThemes().themes),this.setupAutocompleteProvider();let n=this.session.extensionRunner;this.setupExtensionShortcuts(n),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0}),this.showStartupNoticesIfNeeded()}applyRuntimeSettings(){Al(this.settingsManager.getHttpIdleTimeoutMs()),this.footer.setSession(this.session),this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled),this.footerDataProvider.setCwd(this.sessionManager.getCwd()),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());let e=this.settingsManager.getEditorPaddingX(),n=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(e),this.defaultEditor.setAutocompleteMaxVisible(n),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(e),this.editor.setAutocompleteMaxVisible?.(n))}async rebindCurrentSession(){this.unsubscribe?.(),this.unsubscribe=void 0,this.applyRuntimeSettings(),await this.bindCurrentSessionExtensions(),this.subscribeToAgent(),await this.updateAvailableProviderCount(),this.updateEditorBorderColor(),this.updateTerminalTitle()}async handleFatalRuntimeError(e,n){let i=n instanceof Error?n.message:String(n);this.showError(`${e}: ${i}`),ma(),this.stop(),process.exit(1)}renderCurrentSessionState(){this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.renderInitialMessages()}getRegisteredToolDefinition(e){return this.session.getToolDefinition(e)}setupExtensionShortcuts(e){let n=e.getShortcuts(this.keybindings.getEffectiveConfig());if(n.size===0)return;let i=()=>({ui:this.createExtensionUIContext(),hasUI:!0,cwd:this.sessionManager.getCwd(),sessionManager:this.sessionManager,modelRegistry:this.session.modelRegistry,model:this.session.model,isIdle:()=>!this.session.isStreaming,signal:this.session.agent.signal,abort:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},hasPendingMessages:()=>this.session.pendingMessageCount>0,shutdown:()=>{this.shutdownRequested=!0},getContextUsage:()=>this.session.getContextUsage(),compact:s=>{(async()=>{try{let r=await this.session.compact(s?.customInstructions);s?.onComplete?.(r)}catch(r){let o=r instanceof Error?r:new Error(String(r));s?.onError?.(o)}})()},getSystemPrompt:()=>this.session.systemPrompt});this.defaultEditor.onExtensionShortcut=s=>{for(let[r,o]of n)if(_e(s,r))return Promise.resolve(o.handler(i())).catch(a=>{this.showError(`Shortcut handler error: ${a instanceof Error?a.message:String(a)}`)}),!0;return!1}}setExtensionStatus(e,n){this.footerDataProvider.setExtensionStatus(e,n),this.ui.requestRender()}getWorkingLoaderMessage(){return this.workingMessage??this.defaultWorkingMessage}createWorkingLoader(){return new Jt(this.ui,e=>b.fg("accent",e),e=>b.fg("muted",e),this.getWorkingLoaderMessage(),this.workingIndicatorOptions)}stopWorkingLoader(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear()}setWorkingVisible(e){if(this.workingVisible=e,!e){this.stopWorkingLoader(),this.ui.requestRender();return}this.session.isStreaming&&!this.loadingAnimation&&(this.statusContainer.clear(),this.loadingAnimation=this.createWorkingLoader(),this.statusContainer.addChild(this.loadingAnimation)),this.ui.requestRender()}setWorkingIndicator(e){this.workingIndicatorOptions=e,this.loadingAnimation?.setIndicator(e),this.ui.requestRender()}setHiddenThinkingLabel(e){this.hiddenThinkingLabel=e??this.defaultHiddenThinkingLabel;for(let n of this.chatContainer.children)n instanceof qi&&n.setHiddenThinkingLabel(this.hiddenThinkingLabel);this.streamingComponent&&this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel),this.ui.requestRender()}setExtensionWidget(e,n,i){let s=i?.placement??"aboveEditor",r=c=>{let l=c.get(e);l?.dispose&&l.dispose(),c.delete(e)};if(r(this.extensionWidgetsAbove),r(this.extensionWidgetsBelow),n===void 0){this.renderWidgets();return}let o;if(Array.isArray(n)){let c=new K;for(let l of n.slice(0,t.MAX_WIDGET_LINES))c.addChild(new A(l,1,0));n.length>t.MAX_WIDGET_LINES&&c.addChild(new A(b.fg("muted","... (widget truncated)"),1,0)),o=c}else o=n(this.ui,b);(s==="belowEditor"?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(e,o),this.renderWidgets()}clearExtensionWidgets(){for(let e of this.extensionWidgetsAbove.values())e.dispose?.();for(let e of this.extensionWidgetsBelow.values())e.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){this.extensionSelector&&this.hideExtensionSelector(),this.extensionInput&&this.hideExtensionInput(),this.extensionEditor&&this.hideExtensionEditor(),this.ui.hideOverlay(),this.clearExtensionTerminalInputListeners(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.footer.invalidate(),this.autocompleteProviderWrappers=[],this.setCustomEditorComponent(void 0),this.setupAutocompleteProvider(),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.workingMessage=void 0,this.workingVisible=!0,this.setWorkingIndicator(),this.loadingAnimation&&this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${he("app.interrupt")} to interrupt)`),this.setHiddenThinkingLabel()}static{this.MAX_WIDGET_LINES=10}renderWidgets(){!this.widgetContainerAbove||!this.widgetContainerBelow||(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(e,n,i,s){if(e.clear(),n.size===0){i&&e.addChild(new U(1));return}s&&e.addChild(new U(1));for(let r of n.values())e.addChild(r)}setExtensionFooter(e){this.customFooter?.dispose&&this.customFooter.dispose(),this.customFooter?this.ui.removeChild(this.customFooter):this.ui.removeChild(this.footer),e?(this.customFooter=e(this.ui,b,this.footerDataProvider),this.ui.addChild(this.customFooter)):(this.customFooter=void 0,this.ui.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(e){if(!this.builtInHeader)return;this.customHeader?.dispose&&this.customHeader.dispose();let n=this.customHeader||this.builtInHeader,i=this.headerContainer.children.indexOf(n);e?(this.customHeader=e(this.ui,b),Bl(this.customHeader)&&this.customHeader.setExpanded(this.toolOutputExpanded),i!==-1?this.headerContainer.children[i]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,Bl(this.builtInHeader)&&this.builtInHeader.setExpanded(this.toolOutputExpanded),i!==-1&&(this.headerContainer.children[i]=this.builtInHeader)),this.ui.requestRender()}addExtensionTerminalInputListener(e){let n=this.ui.addInputListener(e);return this.extensionTerminalInputUnsubscribers.add(n),()=>{n(),this.extensionTerminalInputUnsubscribers.delete(n)}}clearExtensionTerminalInputListeners(){for(let e of this.extensionTerminalInputUnsubscribers)e();this.extensionTerminalInputUnsubscribers.clear()}createExtensionUIContext(){return{select:(e,n,i)=>this.showExtensionSelector(e,n,i),confirm:(e,n,i)=>this.showExtensionConfirm(e,n,i),input:(e,n,i)=>this.showExtensionInput(e,n,i),notify:(e,n)=>this.showExtensionNotify(e,n),onTerminalInput:e=>this.addExtensionTerminalInputListener(e),setStatus:(e,n)=>this.setExtensionStatus(e,n),setWorkingMessage:e=>{this.workingMessage=e,this.loadingAnimation&&this.loadingAnimation.setMessage(e??this.defaultWorkingMessage)},setWorkingVisible:e=>this.setWorkingVisible(e),setWorkingIndicator:e=>this.setWorkingIndicator(e),setHiddenThinkingLabel:e=>this.setHiddenThinkingLabel(e),setWidget:(e,n,i)=>this.setExtensionWidget(e,n,i),setFooter:e=>this.setExtensionFooter(e),setHeader:e=>this.setExtensionHeader(e),setTitle:e=>this.ui.terminal.setTitle(e),custom:(e,n)=>this.showExtensionCustom(e,n),pasteToEditor:e=>this.editor.handleInput(`\x1B[200~${e}\x1B[201~`),setEditorText:e=>this.editor.setText(e),getEditorText:()=>this.editor.getExpandedText?.()??this.editor.getText(),editor:(e,n)=>this.showExtensionEditor(e,n),addAutocompleteProvider:e=>{this.autocompleteProviderWrappers.push(e),this.setupAutocompleteProvider()},setEditorComponent:e=>this.setCustomEditorComponent(e),getEditorComponent:()=>this.editorComponentFactory,get theme(){return b},getAllThemes:()=>aT(),getTheme:e=>uT(e),setTheme:e=>{if(e instanceof da)return pT(e),this.ui.requestRender(),{success:!0};let n=ul(e,!0);return n.success&&(this.settingsManager.getTheme()!==e&&this.settingsManager.setTheme(e),this.ui.requestRender()),n},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:e=>this.setToolsExpanded(e)}}showExtensionSelector(e,n,i){return new Promise(s=>{if(i?.signal?.aborted){s(void 0);return}let r=()=>{this.hideExtensionSelector(),s(void 0)};i?.signal?.addEventListener("abort",r,{once:!0}),this.extensionSelector=new Gi(e,n,o=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionSelector(),s(o)},()=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionSelector(),s(void 0)},{tui:this.ui,timeout:i?.timeout,onToggleToolsExpanded:()=>this.toggleToolOutputExpansion()}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionSelector),this.ui.setFocus(this.extensionSelector),this.ui.requestRender()})}hideExtensionSelector(){this.extensionSelector?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionSelector=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}async showExtensionConfirm(e,n,i){return await this.showExtensionSelector(`${e}
|
|
340
|
+
${w}`,0,0)),this.chatContainer.addChild(new U(1))}}}async bindCurrentSessionExtensions(){let e=this.createExtensionUIContext();await this.session.bindExtensions({uiContext:e,abortHandler:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},commandContextActions:{waitForIdle:()=>this.session.agent.waitForIdle(),newSession:async i=>{this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{let s=await this.runtimeHost.newSession(i);return s.cancelled||(this.renderCurrentSessionState(),this.ui.requestRender()),s}catch(s){return this.handleFatalRuntimeError("Failed to create session",s)}},fork:async(i,s)=>{try{let r=await this.runtimeHost.fork(i,s);return r.cancelled||(this.renderCurrentSessionState(),this.editor.setText(r.selectedText??""),this.showStatus("Forked to new session")),{cancelled:r.cancelled}}catch(r){return this.handleFatalRuntimeError("Failed to fork session",r)}},navigateTree:async(i,s)=>{let r=await this.session.navigateTree(i,{summarize:s?.summarize,customInstructions:s?.customInstructions,replaceInstructions:s?.replaceInstructions,label:s?.label});return r.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),r.editorText&&!this.editor.getText().trim()&&this.editor.setText(r.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1}),{cancelled:!1})},switchSession:async(i,s)=>this.handleResumeSession(i,s),reload:async()=>{await this.handleReloadCommand()}},shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isStreaming||this.shutdown()},onError:i=>{this.showExtensionError(i.extensionPath,i.error,i.stack)}}),Dd(this.session.resourceLoader.getThemes().themes),this.setupAutocompleteProvider();let n=this.session.extensionRunner;this.setupExtensionShortcuts(n),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0}),this.showStartupNoticesIfNeeded()}applyRuntimeSettings(){Al(this.settingsManager.getHttpIdleTimeoutMs()),this.footer.setSession(this.session),this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled),this.footerDataProvider.setCwd(this.sessionManager.getCwd()),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());let e=this.settingsManager.getEditorPaddingX(),n=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(e),this.defaultEditor.setAutocompleteMaxVisible(n),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(e),this.editor.setAutocompleteMaxVisible?.(n))}async rebindCurrentSession(){this.unsubscribe?.(),this.unsubscribe=void 0,this.applyRuntimeSettings(),await this.bindCurrentSessionExtensions(),this.subscribeToAgent(),await this.updateAvailableProviderCount(),this.updateEditorBorderColor(),this.updateTerminalTitle()}async handleFatalRuntimeError(e,n){let i=n instanceof Error?n.message:String(n);this.showError(`${e}: ${i}`),ma(),this.stop(),process.exit(1)}renderCurrentSessionState(){this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.renderInitialMessages()}getRegisteredToolDefinition(e){return this.session.getToolDefinition(e)}setupExtensionShortcuts(e){let n=e.getShortcuts(this.keybindings.getEffectiveConfig());if(n.size===0)return;let i=()=>({ui:this.createExtensionUIContext(),hasUI:!0,cwd:this.sessionManager.getCwd(),sessionManager:this.sessionManager,modelRegistry:this.session.modelRegistry,model:this.session.model,isIdle:()=>!this.session.isStreaming,signal:this.session.agent.signal,abort:()=>{this.restoreQueuedMessagesToEditor({abort:!0})},hasPendingMessages:()=>this.session.pendingMessageCount>0,shutdown:()=>{this.shutdownRequested=!0},getContextUsage:()=>this.session.getContextUsage(),compact:s=>{(async()=>{try{let r=await this.session.compact(s?.customInstructions);s?.onComplete?.(r)}catch(r){let o=r instanceof Error?r:new Error(String(r));s?.onError?.(o)}})()},getSystemPrompt:()=>this.session.systemPrompt});this.defaultEditor.onExtensionShortcut=s=>{for(let[r,o]of n)if(Ee(s,r))return Promise.resolve(o.handler(i())).catch(a=>{this.showError(`Shortcut handler error: ${a instanceof Error?a.message:String(a)}`)}),!0;return!1}}setExtensionStatus(e,n){this.footerDataProvider.setExtensionStatus(e,n),this.ui.requestRender()}getWorkingLoaderMessage(){return this.workingMessage??this.defaultWorkingMessage}createWorkingLoader(){return new Jt(this.ui,e=>b.fg("accent",e),e=>b.fg("muted",e),this.getWorkingLoaderMessage(),this.workingIndicatorOptions)}stopWorkingLoader(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear()}setWorkingVisible(e){if(this.workingVisible=e,!e){this.stopWorkingLoader(),this.ui.requestRender();return}this.session.isStreaming&&!this.loadingAnimation&&(this.statusContainer.clear(),this.loadingAnimation=this.createWorkingLoader(),this.statusContainer.addChild(this.loadingAnimation)),this.ui.requestRender()}setWorkingIndicator(e){this.workingIndicatorOptions=e,this.loadingAnimation?.setIndicator(e),this.ui.requestRender()}setHiddenThinkingLabel(e){this.hiddenThinkingLabel=e??this.defaultHiddenThinkingLabel;for(let n of this.chatContainer.children)n instanceof qi&&n.setHiddenThinkingLabel(this.hiddenThinkingLabel);this.streamingComponent&&this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel),this.ui.requestRender()}setExtensionWidget(e,n,i){let s=i?.placement??"aboveEditor",r=c=>{let l=c.get(e);l?.dispose&&l.dispose(),c.delete(e)};if(r(this.extensionWidgetsAbove),r(this.extensionWidgetsBelow),n===void 0){this.renderWidgets();return}let o;if(Array.isArray(n)){let c=new K;for(let l of n.slice(0,t.MAX_WIDGET_LINES))c.addChild(new A(l,1,0));n.length>t.MAX_WIDGET_LINES&&c.addChild(new A(b.fg("muted","... (widget truncated)"),1,0)),o=c}else o=n(this.ui,b);(s==="belowEditor"?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(e,o),this.renderWidgets()}clearExtensionWidgets(){for(let e of this.extensionWidgetsAbove.values())e.dispose?.();for(let e of this.extensionWidgetsBelow.values())e.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){this.extensionSelector&&this.hideExtensionSelector(),this.extensionInput&&this.hideExtensionInput(),this.extensionEditor&&this.hideExtensionEditor(),this.ui.hideOverlay(),this.clearExtensionTerminalInputListeners(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.footer.invalidate(),this.autocompleteProviderWrappers=[],this.setCustomEditorComponent(void 0),this.setupAutocompleteProvider(),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.workingMessage=void 0,this.workingVisible=!0,this.setWorkingIndicator(),this.loadingAnimation&&this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${he("app.interrupt")} to interrupt)`),this.setHiddenThinkingLabel()}static{this.MAX_WIDGET_LINES=10}renderWidgets(){!this.widgetContainerAbove||!this.widgetContainerBelow||(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(e,n,i,s){if(e.clear(),n.size===0){i&&e.addChild(new U(1));return}s&&e.addChild(new U(1));for(let r of n.values())e.addChild(r)}setExtensionFooter(e){this.customFooter?.dispose&&this.customFooter.dispose(),this.customFooter?this.ui.removeChild(this.customFooter):this.ui.removeChild(this.footer),e?(this.customFooter=e(this.ui,b,this.footerDataProvider),this.ui.addChild(this.customFooter)):(this.customFooter=void 0,this.ui.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(e){if(!this.builtInHeader)return;this.customHeader?.dispose&&this.customHeader.dispose();let n=this.customHeader||this.builtInHeader,i=this.headerContainer.children.indexOf(n);e?(this.customHeader=e(this.ui,b),Bl(this.customHeader)&&this.customHeader.setExpanded(this.toolOutputExpanded),i!==-1?this.headerContainer.children[i]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,Bl(this.builtInHeader)&&this.builtInHeader.setExpanded(this.toolOutputExpanded),i!==-1&&(this.headerContainer.children[i]=this.builtInHeader)),this.ui.requestRender()}addExtensionTerminalInputListener(e){let n=this.ui.addInputListener(e);return this.extensionTerminalInputUnsubscribers.add(n),()=>{n(),this.extensionTerminalInputUnsubscribers.delete(n)}}clearExtensionTerminalInputListeners(){for(let e of this.extensionTerminalInputUnsubscribers)e();this.extensionTerminalInputUnsubscribers.clear()}createExtensionUIContext(){return{select:(e,n,i)=>this.showExtensionSelector(e,n,i),confirm:(e,n,i)=>this.showExtensionConfirm(e,n,i),input:(e,n,i)=>this.showExtensionInput(e,n,i),notify:(e,n)=>this.showExtensionNotify(e,n),onTerminalInput:e=>this.addExtensionTerminalInputListener(e),setStatus:(e,n)=>this.setExtensionStatus(e,n),setWorkingMessage:e=>{this.workingMessage=e,this.loadingAnimation&&this.loadingAnimation.setMessage(e??this.defaultWorkingMessage)},setWorkingVisible:e=>this.setWorkingVisible(e),setWorkingIndicator:e=>this.setWorkingIndicator(e),setHiddenThinkingLabel:e=>this.setHiddenThinkingLabel(e),setWidget:(e,n,i)=>this.setExtensionWidget(e,n,i),setFooter:e=>this.setExtensionFooter(e),setHeader:e=>this.setExtensionHeader(e),setTitle:e=>this.ui.terminal.setTitle(e),custom:(e,n)=>this.showExtensionCustom(e,n),pasteToEditor:e=>this.editor.handleInput(`\x1B[200~${e}\x1B[201~`),setEditorText:e=>this.editor.setText(e),getEditorText:()=>this.editor.getExpandedText?.()??this.editor.getText(),editor:(e,n)=>this.showExtensionEditor(e,n),addAutocompleteProvider:e=>{this.autocompleteProviderWrappers.push(e),this.setupAutocompleteProvider()},setEditorComponent:e=>this.setCustomEditorComponent(e),getEditorComponent:()=>this.editorComponentFactory,get theme(){return b},getAllThemes:()=>aT(),getTheme:e=>uT(e),setTheme:e=>{if(e instanceof da)return pT(e),this.ui.requestRender(),{success:!0};let n=ul(e,!0);return n.success&&(this.settingsManager.getTheme()!==e&&this.settingsManager.setTheme(e),this.ui.requestRender()),n},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:e=>this.setToolsExpanded(e)}}showExtensionSelector(e,n,i){return new Promise(s=>{if(i?.signal?.aborted){s(void 0);return}let r=()=>{this.hideExtensionSelector(),s(void 0)};i?.signal?.addEventListener("abort",r,{once:!0}),this.extensionSelector=new Gi(e,n,o=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionSelector(),s(o)},()=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionSelector(),s(void 0)},{tui:this.ui,timeout:i?.timeout,onToggleToolsExpanded:()=>this.toggleToolOutputExpansion()}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionSelector),this.ui.setFocus(this.extensionSelector),this.ui.requestRender()})}hideExtensionSelector(){this.extensionSelector?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionSelector=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}async showExtensionConfirm(e,n,i){return await this.showExtensionSelector(`${e}
|
|
341
341
|
${n}`,["Yes","No"],i)==="Yes"}async promptForMissingSessionCwd(e){return await this.showExtensionConfirm("Session cwd not found",T0(e.issue))?e.issue.fallbackCwd:void 0}showExtensionInput(e,n,i){return new Promise(s=>{if(i?.signal?.aborted){s(void 0);return}let r=()=>{this.hideExtensionInput(),s(void 0)};i?.signal?.addEventListener("abort",r,{once:!0}),this.extensionInput=new Ha(e,n,o=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionInput(),s(o)},()=>{i?.signal?.removeEventListener("abort",r),this.hideExtensionInput(),s(void 0)},{tui:this.ui,timeout:i?.timeout}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionInput),this.ui.setFocus(this.extensionInput),this.ui.requestRender()})}hideExtensionInput(){this.extensionInput?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionInput=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionEditor(e,n){return new Promise(i=>{this.extensionEditor=new Ga(this.ui,this.keybindings,e,n,s=>{this.hideExtensionEditor(),i(s)},()=>{this.hideExtensionEditor(),i(void 0)}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionEditor),this.ui.setFocus(this.extensionEditor),this.ui.requestRender()})}hideExtensionEditor(){this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionEditor=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}setCustomEditorComponent(e){this.editorComponentFactory=e;let n=this.editor.getText();if(this.editorContainer.clear(),e){let i=e(this.ui,dl(),this.keybindings);i.onSubmit=this.defaultEditor.onSubmit,i.onChange=this.defaultEditor.onChange,i.setText(n),i.borderColor!==void 0&&(i.borderColor=this.defaultEditor.borderColor),i.setPaddingX!==void 0&&i.setPaddingX(this.defaultEditor.getPaddingX()),i.setAutocompleteProvider&&this.autocompleteProvider&&i.setAutocompleteProvider(this.autocompleteProvider);let s=i;if("actionHandlers"in s&&s.actionHandlers instanceof Map){s.onEscape||(s.onEscape=()=>this.defaultEditor.onEscape?.()),s.onCtrlD||(s.onCtrlD=()=>this.defaultEditor.onCtrlD?.()),s.onPasteImage||(s.onPasteImage=()=>this.defaultEditor.onPasteImage?.()),s.onExtensionShortcut||(s.onExtensionShortcut=r=>this.defaultEditor.onExtensionShortcut?.(r));for(let[r,o]of this.defaultEditor.actionHandlers)s.actionHandlers.set(r,o)}this.editor=i}else this.defaultEditor.setText(n),this.editor=this.defaultEditor;this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionNotify(e,n){n==="error"?this.showError(e):n==="warning"?this.showWarning(e):this.showStatus(e)}async showExtensionCustom(e,n){let i=this.editor.getText(),s=n?.overlay??!1,r=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.editor.setText(i),this.ui.setFocus(this.editor),this.ui.requestRender()};return new Promise((o,a)=>{let c,l=!1,d=u=>{if(!l){l=!0,s?this.ui.hideOverlay():r(),o(u);try{c?.dispose?.()}catch{}}};Promise.resolve(e(this.ui,b,this.keybindings,d)).then(u=>{if(!l)if(c=u,s){let p=()=>{if(n?.overlayOptions)return typeof n.overlayOptions=="function"?n.overlayOptions():n.overlayOptions;let g=c.width;return g?{width:g}:void 0},m=this.ui.showOverlay(c,p());n?.onHandle?.(m)}else this.editorContainer.clear(),this.editorContainer.addChild(c),this.ui.setFocus(c),this.ui.requestRender()}).catch(u=>{l||(s||r(),a(u))})})}showExtensionError(e,n,i){let s=`Extension "${e}" error: ${n}`,r=new A(b.fg("error",s),1,0);if(this.chatContainer.addChild(r),i){let o=i.split(`
|
|
342
342
|
`).slice(1).map(a=>b.fg("dim",` ${a.trim()}`)).join(`
|
|
343
343
|
`);o&&this.chatContainer.addChild(new A(o,1,0))}this.ui.requestRender()}setupKeyHandlers(){this.defaultEditor.onEscape=()=>{if(this.session.isStreaming)this.restoreQueuedMessagesToEditor({abort:!0});else if(this.session.isBashRunning)this.session.abortBash();else if(this.isBashMode)this.editor.setText(""),this.isBashMode=!1,this.updateEditorBorderColor();else if(!this.editor.getText().trim()){let e=this.settingsManager.getDoubleEscapeAction();if(e!=="none"){let n=Date.now();n-this.lastEscapeTime<500?(e==="tree"?this.showTreeSelector():this.showUserMessageSelector(),this.lastEscapeTime=0):this.lastEscapeTime=n}}},this.defaultEditor.onAction("app.clear",()=>this.handleCtrlC()),this.defaultEditor.onCtrlD=()=>this.handleCtrlD(),this.defaultEditor.onAction("app.suspend",()=>this.handleCtrlZ()),this.defaultEditor.onAction("app.thinking.cycle",()=>this.cycleThinkingLevel()),this.defaultEditor.onAction("app.model.cycleForward",()=>this.cycleModel("forward")),this.defaultEditor.onAction("app.model.cycleBackward",()=>this.cycleModel("backward")),this.ui.onDebug=()=>this.handleDebugCommand(),this.defaultEditor.onAction("app.model.select",()=>this.showModelSelector()),this.defaultEditor.onAction("app.tools.expand",()=>this.toggleToolOutputExpansion()),this.defaultEditor.onAction("app.thinking.toggle",()=>this.toggleThinkingBlockVisibility()),this.defaultEditor.onAction("app.editor.external",()=>this.openExternalEditor()),this.defaultEditor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.defaultEditor.onAction("app.message.dequeue",()=>this.handleDequeue()),this.defaultEditor.onAction("app.session.new",()=>this.handleClearCommand()),this.defaultEditor.onAction("app.session.tree",()=>this.showTreeSelector()),this.defaultEditor.onAction("app.session.fork",()=>this.showUserMessageSelector()),this.defaultEditor.onAction("app.session.resume",()=>this.showSessionSelector()),this.defaultEditor.onChange=e=>{let n=this.isBashMode;this.isBashMode=e.trimStart().startsWith("!"),n!==this.isBashMode&&this.updateEditorBorderColor()},this.defaultEditor.onPasteImage=()=>{this.handleClipboardImagePaste()}}async handleClipboardImagePaste(){try{let e=await m1();if(!e)return;let n=ec.tmpdir(),i=d1(e.mimeType)??"png",s=`pi-clipboard-${L1.randomUUID()}.${i}`,r=Ve.join(n,s);Xn.writeFileSync(r,Buffer.from(e.bytes)),this.editor.insertTextAtCursor?.(r),this.ui.requestRender()}catch{}}setupEditorSubmitHandler(){this.defaultEditor.onSubmit=async e=>{if(e=e.trim(),!!e){if(e==="/settings"){this.showSettingsSelector(),this.editor.setText("");return}if(e==="/scoped-models"){this.editor.setText(""),await this.showModelsSelector();return}if(e==="/model"||e.startsWith("/model ")){let n=e.startsWith("/model ")?e.slice(7).trim():void 0;this.editor.setText(""),await this.handleModelCommand(n);return}if(e==="/export"||e.startsWith("/export ")){await this.handleExportCommand(e),this.editor.setText("");return}if(e==="/import"||e.startsWith("/import ")){await this.handleImportCommand(e),this.editor.setText("");return}if(e==="/share"){await this.handleShareCommand(),this.editor.setText("");return}if(e==="/copy"){await this.handleCopyCommand(),this.editor.setText("");return}if(e==="/name"||e.startsWith("/name ")){this.handleNameCommand(e),this.editor.setText("");return}if(e==="/session"){this.handleSessionCommand(),this.editor.setText("");return}if(e==="/changelog"){this.handleChangelogCommand(),this.editor.setText("");return}if(e==="/hotkeys"){this.handleHotkeysCommand(),this.editor.setText("");return}if(e==="/fork"){this.showUserMessageSelector(),this.editor.setText("");return}if(e==="/clone"){this.editor.setText(""),await this.handleCloneCommand();return}if(e==="/tree"){this.showTreeSelector(),this.editor.setText("");return}if(e==="/login"){this.showOAuthSelector("login"),this.editor.setText("");return}if(e==="/logout"){this.showOAuthSelector("logout"),this.editor.setText("");return}if(e==="/new"){this.editor.setText(""),await this.handleClearCommand();return}if(e==="/compact"||e.startsWith("/compact ")){let n=e.startsWith("/compact ")?e.slice(9).trim():void 0;this.editor.setText(""),await this.handleCompactCommand(n);return}if(e==="/reload"){this.editor.setText(""),await this.handleReloadCommand();return}if(e==="/debug"){this.handleDebugCommand(),this.editor.setText("");return}if(e==="/arminsayshi"){this.handleArminSaysHi(),this.editor.setText("");return}if(e==="/dementedelves"){this.handleDementedDelves(),this.editor.setText("");return}if(e==="/resume"){this.showSessionSelector(),this.editor.setText("");return}if(e==="/quit"){this.editor.setText(""),await this.shutdown();return}if(e.startsWith("!")){let n=e.startsWith("!!"),i=n?e.slice(2).trim():e.slice(1).trim();if(i){if(this.session.isBashRunning){this.showWarning("A bash command is already running. Press Esc to cancel it first."),this.editor.setText(e);return}this.editor.addToHistory?.(e),await this.handleBashCommand(i,n),this.isBashMode=!1,this.updateEditorBorderColor();return}}if(this.session.isCompacting){this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"steer");return}if(this.session.isStreaming){this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"steer"}),this.updatePendingMessagesDisplay(),this.ui.requestRender();return}this.flushPendingBashComponents(),this.onInputCallback&&this.onInputCallback(e),this.editor.addToHistory?.(e)}}}subscribeToAgent(){this.unsubscribe=this.session.subscribe(async e=>{await this.handleEvent(e)})}async handleEvent(e){switch(this.isInitialized||await this.init(),this.footer.invalidate(),e.type){case"agent_start":this.pendingTools.clear(),this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryCountdown&&(this.retryCountdown.dispose(),this.retryCountdown=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0),this.stopWorkingLoader(),this.workingVisible&&(this.loadingAnimation=this.createWorkingLoader(),this.statusContainer.addChild(this.loadingAnimation)),this.ui.requestRender();break;case"queue_update":this.updatePendingMessagesDisplay(),this.ui.requestRender();break;case"session_info_changed":this.updateTerminalTitle(),this.footer.invalidate(),this.ui.requestRender();break;case"thinking_level_changed":this.footer.invalidate(),this.updateEditorBorderColor();break;case"message_start":e.message.role==="custom"?(this.addMessageToChat(e.message),this.ui.requestRender()):e.message.role==="user"?(this.addMessageToChat(e.message),this.updatePendingMessagesDisplay(),this.ui.requestRender()):e.message.role==="assistant"&&(this.streamingComponent=new qi(void 0,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel),this.streamingMessage=e.message,this.chatContainer.addChild(this.streamingComponent),this.streamingComponent.updateContent(this.streamingMessage),this.ui.requestRender());break;case"message_update":if(this.streamingComponent&&e.message.role==="assistant"){this.streamingMessage=e.message,this.streamingComponent.updateContent(this.streamingMessage);for(let n of this.streamingMessage.content)if(n.type==="toolCall")if(this.pendingTools.has(n.id)){let i=this.pendingTools.get(n.id);i&&i.updateArgs(n.arguments)}else{let i=new fi(n.name,n.id,n.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(n.name),this.ui,this.sessionManager.getCwd());i.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(i),this.pendingTools.set(n.id,i)}this.ui.requestRender()}break;case"message_end":if(e.message.role==="user")break;if(this.streamingComponent&&e.message.role==="assistant"){this.streamingMessage=e.message;let n;if(this.streamingMessage.stopReason==="aborted"){let i=this.session.retryAttempt;n=i>0?`Aborted after ${i} retry attempt${i>1?"s":""}`:"Operation aborted",this.streamingMessage.errorMessage=n}if(this.streamingComponent.updateContent(this.streamingMessage),this.streamingMessage.stopReason==="aborted"||this.streamingMessage.stopReason==="error"){n||(n=this.streamingMessage.errorMessage||"Error");for(let[,i]of this.pendingTools.entries())i.updateResult({content:[{type:"text",text:n}],isError:!0});this.pendingTools.clear()}else for(let[,i]of this.pendingTools.entries())i.setArgsComplete();this.streamingComponent=void 0,this.streamingMessage=void 0,this.footer.invalidate()}this.ui.requestRender();break;case"tool_execution_start":{let n=this.pendingTools.get(e.toolCallId);n||(n=new fi(e.toolName,e.toolCallId,e.args,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(e.toolName),this.ui,this.sessionManager.getCwd()),n.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(n),this.pendingTools.set(e.toolCallId,n)),n.markExecutionStarted(),this.ui.requestRender();break}case"tool_execution_update":{let n=this.pendingTools.get(e.toolCallId);n&&(n.updateResult({...e.partialResult,isError:!1},!0),this.ui.requestRender());break}case"tool_execution_end":{let n=this.pendingTools.get(e.toolCallId);n&&(n.updateResult({...e.result,isError:e.isError}),this.pendingTools.delete(e.toolCallId),this.ui.requestRender());break}case"agent_end":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0,this.statusContainer.clear()),this.streamingComponent&&(this.chatContainer.removeChild(this.streamingComponent),this.streamingComponent=void 0,this.streamingMessage=void 0),this.pendingTools.clear(),await this.checkShutdownRequested(),this.ui.requestRender();break;case"compaction_start":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.autoCompactionEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortCompaction()},this.statusContainer.clear();let n=`(${he("app.interrupt")} to cancel)`,i=e.reason==="manual"?`Compacting context... ${n}`:`${e.reason==="overflow"?"Context overflow detected, ":""}Auto-compacting... ${n}`;this.autoCompactionLoader=new Jt(this.ui,s=>b.fg("accent",s),s=>b.fg("muted",s),i),this.statusContainer.addChild(this.autoCompactionLoader),this.ui.requestRender();break}case"compaction_end":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.autoCompactionEscapeHandler&&(this.defaultEditor.onEscape=this.autoCompactionEscapeHandler,this.autoCompactionEscapeHandler=void 0),this.autoCompactionLoader&&(this.autoCompactionLoader.stop(),this.autoCompactionLoader=void 0,this.statusContainer.clear()),e.aborted?e.reason==="manual"?this.showError("Compaction cancelled"):this.showStatus("Auto-compaction cancelled"):e.result?(this.chatContainer.clear(),this.rebuildChatFromMessages(),this.addMessageToChat(ga(e.result.summary,e.result.tokensBefore,new Date().toISOString())),this.footer.invalidate()):e.errorMessage&&(e.reason==="manual"?this.showError(e.errorMessage):(this.chatContainer.addChild(new U(1)),this.chatContainer.addChild(new A(b.fg("error",e.errorMessage),1,0)))),this.flushCompactionQueue({willRetry:e.willRetry}),this.ui.requestRender();break}case"auto_retry_start":{this.retryEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortRetry()},this.statusContainer.clear(),this.retryCountdown?.dispose();let n=i=>`Retrying (${e.attempt}/${e.maxAttempts}) in ${i}s... (${he("app.interrupt")} to cancel)`;this.retryLoader=new Jt(this.ui,i=>b.fg("warning",i),i=>b.fg("muted",i),n(Math.ceil(e.delayMs/1e3))),this.retryCountdown=new Es(e.delayMs,this.ui,i=>{this.retryLoader?.setMessage(n(i))},()=>{this.retryCountdown=void 0}),this.statusContainer.addChild(this.retryLoader),this.ui.requestRender();break}case"auto_retry_end":{this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryCountdown&&(this.retryCountdown.dispose(),this.retryCountdown=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0,this.statusContainer.clear()),e.success||this.showError(`Retry failed after ${e.attempt} attempts: ${e.finalError||"Unknown error"}`),this.ui.requestRender();break}}}getUserMessageText(e){return e.role!=="user"?"":(typeof e.content=="string"?[{type:"text",text:e.content}]:e.content.filter(i=>i.type==="text")).map(i=>i.text).join("")}showStatus(e){let n=this.chatContainer.children,i=n.length>0?n[n.length-1]:void 0,s=n.length>1?n[n.length-2]:void 0;if(i&&s&&i===this.lastStatusText&&s===this.lastStatusSpacer){this.lastStatusText.setText(b.fg("dim",e)),this.ui.requestRender();return}let r=new U(1),o=new A(b.fg("dim",e),1,0);this.chatContainer.addChild(r),this.chatContainer.addChild(o),this.lastStatusSpacer=r,this.lastStatusText=o,this.ui.requestRender()}addMessageToChat(e,n){switch(e.role){case"bashExecution":{let i=new _s(e.command,this.ui,e.excludeFromContext);e.output&&i.appendOutput(e.output),i.setComplete(e.exitCode,e.cancelled,e.truncated?{truncated:!0}:void 0,e.fullOutputPath),this.chatContainer.addChild(i);break}case"custom":{if(e.display){let i=this.session.extensionRunner.getMessageRenderer(e.customType),s=new qa(e,i,this.getMarkdownThemeWithSettings());s.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(s)}break}case"compactionSummary":{this.chatContainer.addChild(new U(1));let i=new ja(e,this.getMarkdownThemeWithSettings());i.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(i);break}case"branchSummary":{this.chatContainer.addChild(new U(1));let i=new Na(e,this.getMarkdownThemeWithSettings());i.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(i);break}case"user":{let i=this.getUserMessageText(e);if(i){this.chatContainer.children.length>0&&this.chatContainer.addChild(new U(1));let s=r0(i);if(s){let r=new Ya(s,this.getMarkdownThemeWithSettings());if(r.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(r),s.userMessage){let o=new Pr(s.userMessage,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(o)}}else{let r=new Pr(i,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(r)}n?.populateHistory&&this.editor.addToHistory?.(i)}break}case"assistant":{let i=new qi(e,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel);this.chatContainer.addChild(i);break}case"toolResult":break;default:{let i=e}}}renderSessionContext(e,n={}){this.pendingTools.clear();let i=new Map;n.updateFooter&&(this.footer.invalidate(),this.updateEditorBorderColor());for(let s of e.messages)if(s.role==="assistant"){this.addMessageToChat(s);for(let r of s.content)if(r.type==="toolCall"){let o=new fi(r.name,r.id,r.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(r.name),this.ui,this.sessionManager.getCwd());if(o.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(o),s.stopReason==="aborted"||s.stopReason==="error"){let a;if(s.stopReason==="aborted"){let c=this.session.retryAttempt;a=c>0?`Aborted after ${c} retry attempt${c>1?"s":""}`:"Operation aborted"}else a=s.errorMessage||"Error";o.updateResult({content:[{type:"text",text:a}],isError:!0})}else i.set(r.id,o)}}else if(s.role==="toolResult"){let r=i.get(s.toolCallId);r&&(r.updateResult(s),i.delete(s.toolCallId))}else this.addMessageToChat(s,n);for(let[s,r]of i)this.pendingTools.set(s,r);this.ui.requestRender()}renderInitialMessages(){let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e,{updateFooter:!0,populateHistory:!0});let i=this.sessionManager.getEntries().filter(s=>s.type==="compaction").length;if(i>0){let s=i===1?"1 time":`${i} times`;this.showStatus(`Session compacted ${s}`)}}async getUserInput(){return new Promise(e=>{this.onInputCallback=n=>{this.onInputCallback=void 0,e(n)}})}rebuildChatFromMessages(){this.chatContainer.clear();let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e)}handleCtrlC(){let e=Date.now();e-this.lastSigintTime<500?this.shutdown():(this.clearEditor(),this.lastSigintTime=e)}handleCtrlD(){this.shutdown()}async shutdown(){this.isShuttingDown||(this.isShuttingDown=!0,this.unregisterSignalHandlers(),await this.ui.terminal.drainInput(1e3),this.stop(),await this.runtimeHost.dispose(),process.exit(0))}emergencyTerminalExit(){this.isShuttingDown=!0,this.unregisterSignalHandlers(),ha(),process.exit(129)}uncaughtCrash(e){this.isShuttingDown&&process.exit(1),this.isShuttingDown=!0;try{this.unregisterSignalHandlers()}catch{}try{ha()}catch{}try{this.ui.stop()}catch{}console.error("pi exiting due to uncaughtException:"),console.error(e),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(let s of e){let r=()=>{s==="SIGHUP"&&this.emergencyTerminalExit(),ha(),this.shutdown()};process.prependListener(s,r),this.signalCleanupHandlers.push(()=>process.off(s,r))}let n=s=>{throw cB(s)&&this.emergencyTerminalExit(),s};process.stdout.on("error",n),process.stderr.on("error",n),this.signalCleanupHandlers.push(()=>process.stdout.off("error",n)),this.signalCleanupHandlers.push(()=>process.stderr.off("error",n));let i=s=>this.uncaughtCrash(s);process.prependListener("uncaughtException",i),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",i))}unregisterSignalHandlers(){for(let e of this.signalCleanupHandlers)e();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let e=setInterval(()=>{},2**30),n=()=>{};process.on("SIGINT",n),process.once("SIGCONT",()=>{clearInterval(e),process.removeListener("SIGINT",n),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(i){throw clearInterval(e),process.removeListener("SIGINT",n),i}}async handleFollowUp(){let e=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(e){if(this.session.isCompacting){this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):this.editor.onSubmit&&(this.editor.setText(""),this.editor.onSubmit(e))}}handleDequeue(){let e=this.restoreQueuedMessagesToEditor();e===0?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${e} queued message${e>1?"s":""} to editor`)}updateEditorBorderColor(){if(this.isBashMode)this.editor.borderColor=b.getBashModeBorderColor();else{let e=this.session.thinkingLevel||"off";this.editor.borderColor=b.getThinkingBorderColor(e)}this.ui.requestRender()}cycleThinkingLevel(){let e=this.session.cycleThinkingLevel();e===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${e}`))}async cycleModel(e){try{let n=await this.session.cycleModel(e);if(n===void 0){let i=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(i)}else{this.footer.invalidate(),this.updateEditorBorderColor();let i=n.model.reasoning&&n.thinkingLevel!=="off"?` (thinking: ${n.thinkingLevel})`:"";this.showStatus(`Switched to ${n.model.name||n.model.id}${i}`),this.maybeWarnAboutAnthropicSubscriptionAuth(n.model)}}catch(n){this.showError(n instanceof Error?n.message:String(n))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(e){this.toolOutputExpanded=e;let n=this.customHeader??this.builtInHeader;Bl(n)&&n.setExpanded(e);for(let i of this.chatContainer.children)Bl(i)&&i.setExpanded(e);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.chatContainer.clear(),this.rebuildChatFromMessages(),this.streamingComponent&&this.streamingMessage&&(this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock),this.streamingComponent.updateContent(this.streamingMessage),this.chatContainer.addChild(this.streamingComponent)),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}async openExternalEditor(){let e=process.env.VISUAL||process.env.EDITOR;if(!e){this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");return}let n=this.editor.getExpandedText?.()??this.editor.getText(),i=Ve.join(ec.tmpdir(),`pi-editor-${Date.now()}.pi.md`);try{Xn.writeFileSync(i,n,"utf-8"),this.ui.stop();let[s,...r]=e.split(" ");if(process.stdout.write(`Launching external editor: ${e}
|
|
@@ -437,11 +437,11 @@ ${b.fg("muted",s)}`,1,1)),this.ui.requestRender()}handleArminSaysHi(){this.chatC
|
|
|
437
437
|
|
|
438
438
|
Log file: ${Ki}
|
|
439
439
|
|
|
440
|
-
`;Ls.writeFileSync(Ki,r)}}catch(t){console.warn("[Slingshot Analytics] Could not initialize file logging:",t)}}function
|
|
440
|
+
`;Ls.writeFileSync(Ki,r)}}catch(t){console.warn("[Slingshot Analytics] Could not initialize file logging:",t)}}function Pe(t){if(!(!Ki||!Ls||!jl))try{let n=`[${new Date().toISOString()}] ${t}
|
|
441
441
|
`;Ls.appendFileSync(Ki,n)}catch{}}function Je(t,e){if(!(!Ki||!Ls||!jl))try{let i=`[${new Date().toISOString()}] ${t}:
|
|
442
442
|
${JSON.stringify(e,null,2)}
|
|
443
443
|
|
|
444
|
-
`;Ls.appendFileSync(Ki,i)}catch{}}var Ws=null;function $1(t){if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")}var we=class t{static{this.BASE_URL="base_url"}static{this.ANALYTICS_DOMAIN="analytics_domain"}static{this.CLIENT_ID="client_id"}static{this.PROJECT_ID="project_id"}static{this.WORKSPACE_ID="workspace_id"}static{this.defaultValues={[t.BASE_URL]:"https://sapientaiproducts.com",[t.ANALYTICS_DOMAIN]:"https://slingshot.sapientaiproducts.com",[t.CLIENT_ID]:"b97fbef7-cad9-4e56-9850-39e86c8fdf61",[t.PROJECT_ID]:"fa8121c4-e2fc-48f1-9478-8949c04e13cc",[t.WORKSPACE_ID]:"6e5756eb-d7e2-4d80-ad07-9d7a51600d85"}}static{this.LOGIN_PATH="/web/v1/studio-auth/login"}static{this.EXCHANGE_PATH="/api/v1/studio-auth/auth/desktop/exchange"}static{this.REFRESH_PATH="/api/v3/auth/refreshtoken"}static{this.REFRESH_CLIENT_NAME="machine"}static{this.API_BASE_PATH="/api/v1/llm"}static{this.SAGE_EVENTS_PATH="/api/v1/ai-portal/sage_events"}static{this.APP_TOKEN_PATH="/api/v3/auth/app-token"}static{this.CONFIG_SERVICE_PATH="/api/v2/configservice/client"}static{this.APP_TOKEN_REFRESH_BUFFER_MS=60*1e3}static{this.SLINGSHOT_APP_TOKEN_ENV="SLINGSHOT_APP_TOKEN_HEADER"}static{this.TOKEN_EXPIRY_BUFFER_MS=300*1e3}static{this.SAPI="/save/api/v1"}static{this.CLIENT_NAME="desktop"}static defaults(e){return this.defaultValues[e]}static getSettingsPath(){let e=Gl.resolve(process.cwd(),".sling","sling.settings.json");if(Hi.existsSync(e))return e;let n=Pe();return Gl.resolve(n,"sling.settings.json")}static getSettings(){if(!Ws){let i=this.getSettingsPath();try{if(Hi.existsSync(i)){let s=Hi.readFileSync(i,"utf-8"),r=JSON.parse(s)||{};Ws={...this.defaultValues,...r}}else{let s=Gl.dirname(i);Hi.existsSync(s)||Hi.mkdirSync(s,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ws={...this.defaultValues}}}catch(s){Je("Error reading/writing sling.settings.json: ",s),Ws={...this.defaultValues}}}let e=$1(process.env.SLINGSHOT_API_DOMAIN),n=$1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ws,[t.BASE_URL]:e||Ws[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ws[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=Pe(),i=Gl.resolve(n,"sling.settings.json");try{let r={...this.getSettings()||{},...e},o=Gl.dirname(i);Hi.existsSync(o)||Hi.mkdirSync(o,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(r,null,2),"utf-8"),Ws=r}catch(s){Je("Error updating sling.settings.json: ",s)}}static getLoginUrl(e){let n=this.getSettings(),i=new URLSearchParams({client:this.CLIENT_NAME,port:String(e.port),localState:e.localState});return e.clientId&&i.set("clientId",e.clientId),`${n[t.BASE_URL]}${this.LOGIN_PATH}?${i.toString()}`}static getExchangeUrl(){return`${this.getSettings()[t.BASE_URL]}${this.EXCHANGE_PATH}`}static getRefreshUrl(){let e=this.getSettings(),n=new URLSearchParams({client:this.REFRESH_CLIENT_NAME});return`${e[t.BASE_URL]}${this.REFRESH_PATH}?${n.toString()}`}static getApiBaseUrl(){return`${this.getSettings()[t.BASE_URL]}${this.API_BASE_PATH}`}static getSageEventsUrl(){return`${this.getSettings()[t.ANALYTICS_DOMAIN]}${this.SAGE_EVENTS_PATH}`}static getTokenExpiryBuffer(){return this.TOKEN_EXPIRY_BUFFER_MS}static getDefaultProjectId(){let e=this.getSettings();return process.env.SLINGSHOT_PROJECT_ID||e[t.PROJECT_ID]}static getDefaultWorkspaceId(){let e=this.getSettings();return process.env.SLINGSHOT_WORKSPACE_ID||e[t.WORKSPACE_ID]}static getDefaultClientId(){let e=this.getSettings();return process.env.CLIENT_ID||e[t.CLIENT_ID]}static getUserActivityUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users/activity`}static getUserUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users`}static getAppTokenUrl(){return`${this.getSettings()[t.BASE_URL]}${this.APP_TOKEN_PATH}`}static getConfigServiceUrl(e){let n=this.getSettings(),i=this.getDefaultClientId(),s=new URLSearchParams({keys:e});return`${n[t.BASE_URL]}${this.CONFIG_SERVICE_PATH}/${i}?${s.toString()}`}static getAppTokenRefreshBuffer(){return this.APP_TOKEN_REFRESH_BUFFER_MS}};function Kl(t){try{let e=t.split(".");if(e.length!==3)return 0;let n=JSON.parse(atob(e[1]));return n.exp?n.exp*1e3:0}catch{return 0}}function jp(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function B1(){return`user_${jp()}`}var q0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",kB=BigInt(q0.length);function MB(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=q0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*kB+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===q0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var G0=new Map,qp=new Map;async function IB(t,e){let n=we.getConfigServiceUrl(t);We(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?o=String(a.message):a.error&&(o=String(a.error))}catch{}throw new Error(`Config service request failed: ${o}`)}let r=(await i.json())?.data?.config;if(!r||typeof r!="object")throw new Error("Config service response missing data.config");return r}async function N1(t,e){let n=G0.get(t);if(n)return n;let i=qp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=IB(t,e).then(r=>(G0.set(t,r),r)).finally(()=>{qp.delete(t)});return qp.set(t,s),s}var tc=class{static async getSlingcliConfig(e){let n=await N1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw Je("sling-config: missing slingcli block",n),new Error("Config service did not return slingcli.app_id / slingcli.app_key for this client");return{app_id:i.app_id,app_key:MB(i.app_key)}}static async getRemoteConfig(e,n){return N1(e,n)}static clearCache(){G0.clear(),qp=new Map}};import j1 from"node:path";import Us from"node:fs";var RB="sling.app-creds.json";function K0(){return j1.resolve(Pe(),RB)}function q1(){let t=K0();if(!Us.existsSync(t))return null;try{let e=Us.readFileSync(t,"utf-8"),n=JSON.parse(e);return typeof n.app_id!="string"||typeof n.app_key!="string"||!n.app_id||!n.app_key?(Je("app-creds-store: invalid creds file, ignoring",n),null):{app_id:n.app_id,app_key:n.app_key}}catch(e){return Je("app-creds-store: failed to read creds file",e),null}}function H0(t){let e=K0(),n=j1.dirname(e);try{Us.existsSync(n)||Us.mkdirSync(n,{recursive:!0});let i={...t,savedAt:Date.now()};Us.writeFileSync(e,JSON.stringify(i,null,2),{encoding:"utf-8",mode:384});try{Us.chmodSync(e,384)}catch{}We(`app-creds-store: persisted to ${e}`)}catch(i){Je("app-creds-store: failed to persist creds",i)}}function G1(){let t=K0();try{Us.existsSync(t)&&(Us.unlinkSync(t),We(`app-creds-store: cleared ${t}`))}catch(e){Je("app-creds-store: failed to clear creds file",e)}}var Kp=class extends Error{constructor(n,i){super(i);this.status=n;this.name="AppTokenHttpError"}},Hl=null,zl=null,Gp=null,nc=null;function K1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function PB(t){nc&&(clearTimeout(nc),nc=null);let e=t.expiresAt-Date.now();e<=0||(nc=setTimeout(()=>{nc=null,zi().catch(n=>{Je("app-token: scheduled refresh failed",n)})},e),nc.unref?.())}async function H1(t){let e=Buffer.from(`${t.app_id}:${t.app_key}`).toString("base64"),n=we.getAppTokenUrl();We(`app-token: minting from ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${e}`}})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach app-token service: ${c}`)}if(!i.ok){let a=`${i.status} ${i.statusText}`;try{let c=await i.text()||"";c&&(a=c)}catch{}throw new Kp(i.status,`App token request failed: ${a}`)}let s=await i.json();if(!s.app_token||typeof s.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let r=we.getAppTokenRefreshBuffer(),o=Date.now()+s.expires_in*1e3-r;return We(`app-token: minted, expires at ${new Date(o).toISOString()}`),{token:s.app_token,expiresAt:o}}async function _B(){let t=q1();if(t)return{creds:t,fromDisk:!0};if(!zl)throw new Error("Cannot mint app token: no on-disk app credentials and no Slingshot user token available (please /login slingshot first)");let e=await tc.getSlingcliConfig(zl);return H0(e),{creds:e,fromDisk:!1}}async function EB(){let{creds:t,fromDisk:e}=await _B();try{return await H1(t)}catch(n){let i=n instanceof Kp&&(n.status===401||n.status===403);if(!e||!i)throw n;if(Je("app-token: disk creds rejected (likely rotated), refetching from config service",{status:n.status}),G1(),!zl)throw new Error("Cannot rotate app credentials: on-disk creds rejected and no Slingshot user token available (please /login slingshot)");let s=await tc.getSlingcliConfig(zl);return H0(s),await H1(s)}}async function zi(t){if(t&&(zl=t),Hl&&Hl.expiresAt>Date.now())return K1(Hl.token),Hl.token;if(Gp)return(await Gp).token;let e=EB().then(i=>(Hl=i,K1(i.token),PB(i),i)).finally(()=>{Gp=null});return Gp=e,(await e).token}var Vl=null,z0=null;typeof process<"u"&&process.versions?.node&&(z0=import("node:http").then(t=>{Vl=t.createServer}));async function AB(){if(Vl||(z0&&await z0,Vl))return Vl;throw new Error("Slingshot OAuth requires Node.js")}async function V0(t){let e=await AB(),n,i,s,r=!1,o=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!r){r=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),m=p.searchParams.get("code"),g=p.searchParams.get("state"),h=p.searchParams.get("clientId"),f=p.searchParams.get("error"),x=p.searchParams.get("error_description");if(f){u.writeHead(400,{"Content-Type":"text/html"}),u.end(`<html><body><h1>Login Failed</h1><p>${x||f}</p><p>You can close this window.</p></body></html>`),a(()=>s(new Error(`Login failed: ${x||f}`)));return}if(!m||!g){u.writeHead(400,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Failed</h1><p>Missing code or state in callback.</p><p>You can close this window.</p></body></html>"),a(()=>s(new Error("Missing code or state in callback")));return}u.writeHead(200,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Successful</h1><p>You can close this window and return to your terminal.</p><script>setTimeout(()=>window.close(),3000)</script></body></html>"),a(()=>i({code:m,state:g,clientId:h||""}))}),n.on("error",d=>{a(()=>s(d))});let c=setTimeout(()=>{a(()=>s(new Error("Login timeout - no callback received within 5 minutes")))},300*1e3);return n.on("close",()=>clearTimeout(c)),t&&t.addEventListener("abort",()=>{a(()=>s(new Error("Login cancelled")))}),{port:await new Promise((d,u)=>{n.once("error",u),n.listen(0,"127.0.0.1",()=>{let p=n.address();p&&typeof p=="object"?d(p.port):u(new Error("Failed to obtain loopback server port"))})}),result:o}}async function J0(t,e){if(!t)throw new Error("Missing exchange code");if(!e)throw new Error("Missing clientId for exchange");let n=we.getExchangeUrl(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify({code:t,clientId:e})})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach Studio Auth: ${o}`)}if(!i.ok){let r,o=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.error?.code,a.error?.message?o=a.error.message:a.message?o=a.message:r&&(o=r)}catch{}throw r==="INVALID_CALLBACK"?new Error("Login failed: exchange code is expired, already used, or bound to a different tenant. Please log in again."):new Error(`Code exchange failed: ${o}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function LB(){return OB(16).toString("hex")}function WB(t){let e=new URL(t),n=e.searchParams.get("code"),i=e.searchParams.get("state"),s=e.searchParams.get("clientId");if(!n||!i)throw new Error("Pasted URL is missing code or state");return{code:n,state:i,clientId:s||""}}async function Q0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Kl(e);return console.log("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await zi(e),{refresh:"",access:e,expires:d>0?d-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:process.env.SLINGSHOT_PROJECT_ID,workspaceId:process.env.SLINGSHOT_WORKSPACE_ID}}let{port:n,result:i}=await V0(t.signal),s=LB(),r=we.getDefaultClientId(),o=we.getLoginUrl({port:n,localState:s,clientId:r||void 0});t.onAuth({url:o});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(WB);a=await Promise.race([i,d])}else a=await i;if(a.state!==s)throw new Error("CSRF check failed - state does not match localState");if(!a.clientId)throw new Error("Login callback did not include clientId");let c=await J0(a.code,a.clientId),l=Kl(c.accessToken);return await zi(c.accessToken),{refresh:c.refreshToken,access:c.accessToken,expires:l>0?l-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:void 0,workspaceId:void 0}}import{randomUUID as UB}from"node:crypto";async function Hp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await zi()}catch(a){throw Je("auth/refresh: app token unavailable for refresh call",a),new Error(`Cannot refresh Slingshot token: app token unavailable (${a instanceof Error?a.message:String(a)}). Please /login slingshot.`)}let n=UB(),i={accept:"application/json",rt:t.refresh,"trace-id":n,Authorization:`Bearer ${e}`},s;try{let a=we.getRefreshUrl();s=await fetch(a,{headers:i})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach Slingshot server: ${c}`)}if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();c.message?a=String(c.message):c.error&&(a=String(c.error))}catch{}throw new Error(`Token refresh failed: ${a}`)}let r=await s.json();if(!r.accessToken)throw new Error("No access token in refresh response");let o=Kl(r.accessToken);try{await zi(r.accessToken)}catch(a){throw Je("auth/refresh: app token refresh failed",a),a}return{refresh:r.refreshToken||t.refresh,access:r.accessToken,expires:o>0?o-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var z1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-4.1",name:"GPT-4.1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768,provider:"slingshot",api:"openai-completions"},{id:"gpt-5",name:"GPT-5",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-mini",name:"GPT-5 Mini",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-nano",name:"GPT-5 Nano",reasoning:!0,input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.1",name:"GPT-5.1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.2",name:"GPT-5.2",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.4",name:"GPT-5.4",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.5",name:"GPT-5.5",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"claude-opus-4@20250514",name:"Claude Opus 4",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4@20250514",name:"Claude Sonnet 4",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-5@20250929",name:"Claude Sonnet 4.5",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-opus-4-6",name:"Claude Opus 4.6",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"o3",name:"O3",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o3-mini",name:"o3-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o4-mini",name:"o4-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536,provider:"slingshot",api:"openai-completions"}];var _r={name:"slingshot.cli",private:!0,type:"module",workspaces:["packages/*","packages/web-ui/example","packages/coding-agent/examples/extensions/with-deps","packages/coding-agent/examples/extensions/custom-provider-anthropic","packages/coding-agent/examples/extensions/custom-provider-gitlab-duo"],scripts:{clean:"npm run clean --workspaces",build:"cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build && cd ../web-ui && npm run build",dev:'concurrently --names "ai,agent,coding-agent,web-ui,tui" --prefix-colors "cyan,yellow,red,white,green,magenta" "cd packages/ai && npm run dev" "cd packages/agent && npm run dev" "cd packages/coding-agent && npm run dev" "cd packages/web-ui && npm run dev" "cd packages/tui && npm run dev"',"dev:tsc":'concurrently --names "ai,web-ui" --prefix-colors "cyan,green" "cd packages/ai && npm run dev:tsc" "cd packages/web-ui && npm run dev:tsc"',check:"","check:browser-smoke":"","profile:tui":"node scripts/profile-coding-agent-node.mjs --mode tui","profile:rpc":"node scripts/profile-coding-agent-node.mjs --mode rpc",test:"npm run test --workspaces --if-present","version:patch":"npm version patch -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:minor":"npm version minor -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:major":"npm version major -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:set":"npm version -ws",prepublishOnly:"npm run clean && npm run build && npm run check",publish:"npm run prepublishOnly && npm publish -ws --access public","publish:dry":"npm run prepublishOnly && npm publish -ws --access public --dry-run","release:patch":"node scripts/release.mjs patch","release:minor":"node scripts/release.mjs minor","release:major":"node scripts/release.mjs major",prepare:"husky"},devDependencies:{"@anthropic-ai/sandbox-runtime":"0.0.26","@biomejs/biome":"2.3.5","@types/node":"22.19.19","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"0.28.0",husky:"9.1.7",jiti:"2.7.0",shx:"0.4.0",tsx:"4.22.1",typescript:"5.9.3"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260523-2",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@mozilla/readability":"^0.6.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0",linkedom:"^0.18.12",turndown:"^7.2.4",unpdf:"^1.6.2"}};var j1e=we.getRefreshUrl(),q1e=we.getApiBaseUrl(),G1e=we.getSageEventsUrl(),K1e=we.getTokenExpiryBuffer(),V1=we.getDefaultProjectId(),J1=we.getDefaultWorkspaceId(),Q1=we.getDefaultClientId();async function zp(t,e,n){let i=B1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){We("ERROR: No API key found");return}let r=s.startsWith("Bearer ")?s:`Bearer ${s}`,o=process.env.SLINGSHOT_PROJECT_ID||V1,a=process.env.SLINGSHOT_WORKSPACE_ID||J1,c=process.env.CLIENT_ID||Q1,l={"Content-Type":"application/json",accept:"application/json","access-token":r,"x-project-id":o,"x-workspace-id":a,"x-client-id":c,"sage-trace-id":i,"User-Agent":"pi-slingshot/1.0.0"},d=parseFloat(process.env.SLINGSHOT_TEMPERATURE||"0.2"),u=parseFloat(process.env.SLINGSHOT_TOP_P||"0.8"),p={source:_r.name||"sling",ai_model_info:{ai_provider_name:e.model?.provider||"slingshot",sage_modl_name:e.model?.id||"unknown",sage_modl_option:{temperature:String(d),max_token_size:String(e.model?.maxTokens||16834),top_p:String(u)}},rag_info:{type:null,account_name:"dummy",project_names:[],repository_names:[],programming_language:null},tab_data:{tab_count:"1"},tags:null,slingshot_version:_r.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Vp(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};We(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let r=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(r.ok){let o=await r.json().catch(()=>{});if(o.error_code)throw new Error(`Analytics API error: ${o.error_code} - ${o.error_message||"No message"}`);We(`'SUCCESS: Event sent: ${t}`),We(`Response: ${JSON.stringify(o)}`),We("\u2500".repeat(66))}else{let o=await r.text().catch(()=>""),a={status:r.status,statusText:r.statusText,responseBody:o,requestHeaders:e};throw We(`ERROR: ${r.status} ${r.statusText}`),Je("Error Details",a),Je("Failed Request Body",s),new Error(`Analytics API error: ${r.status} ${r.statusText}`)}}catch(r){let o=r instanceof Error?r.message:String(r);console.warn("[Slingshot Analytics] Request that caused error:",o),We(`EXCEPTION: ${o}`),r instanceof Error&&r.stack&&We(`Stack trace: ${r.stack}`),Je("Request that caused exception",s)}}import Jl from"chalk";function Y1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
|
|
444
|
+
`;Ls.appendFileSync(Ki,i)}catch{}}var Ws=null;function $1(t){if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")}var we=class t{static{this.BASE_URL="base_url"}static{this.ANALYTICS_DOMAIN="analytics_domain"}static{this.CLIENT_ID="client_id"}static{this.PROJECT_ID="project_id"}static{this.WORKSPACE_ID="workspace_id"}static{this.defaultValues={[t.BASE_URL]:"https://sapientaiproducts.com",[t.ANALYTICS_DOMAIN]:"https://slingshot.sapientaiproducts.com",[t.CLIENT_ID]:"b97fbef7-cad9-4e56-9850-39e86c8fdf61",[t.PROJECT_ID]:"fa8121c4-e2fc-48f1-9478-8949c04e13cc",[t.WORKSPACE_ID]:"6e5756eb-d7e2-4d80-ad07-9d7a51600d85"}}static{this.LOGIN_PATH="/web/v1/studio-auth/login"}static{this.EXCHANGE_PATH="/api/v1/studio-auth/auth/desktop/exchange"}static{this.REFRESH_PATH="/api/v3/auth/refreshtoken"}static{this.REFRESH_CLIENT_NAME="machine"}static{this.API_BASE_PATH="/api/v1/llm"}static{this.SAGE_EVENTS_PATH="/api/v1/ai-portal/sage_events"}static{this.APP_TOKEN_PATH="/api/v3/auth/app-token"}static{this.CONFIG_SERVICE_PATH="/api/v2/configservice/client"}static{this.APP_TOKEN_REFRESH_BUFFER_MS=60*1e3}static{this.SLINGSHOT_APP_TOKEN_ENV="SLINGSHOT_APP_TOKEN_HEADER"}static{this.TOKEN_EXPIRY_BUFFER_MS=300*1e3}static{this.SAPI="/save/api/v1"}static{this.CLIENT_NAME="desktop"}static defaults(e){return this.defaultValues[e]}static getSettingsPath(){let e=Gl.resolve(process.cwd(),".sling","sling.settings.json");if(Hi.existsSync(e))return e;let n=_e();return Gl.resolve(n,"sling.settings.json")}static getSettings(){if(!Ws){let i=this.getSettingsPath();try{if(Hi.existsSync(i)){let s=Hi.readFileSync(i,"utf-8"),r=JSON.parse(s)||{};Ws={...this.defaultValues,...r}}else{let s=Gl.dirname(i);Hi.existsSync(s)||Hi.mkdirSync(s,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ws={...this.defaultValues}}}catch(s){Je("Error reading/writing sling.settings.json: ",s),Ws={...this.defaultValues}}}let e=$1(process.env.SLINGSHOT_API_DOMAIN),n=$1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ws,[t.BASE_URL]:e||Ws[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ws[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=_e(),i=Gl.resolve(n,"sling.settings.json");try{let r={...this.getSettings()||{},...e},o=Gl.dirname(i);Hi.existsSync(o)||Hi.mkdirSync(o,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(r,null,2),"utf-8"),Ws=r}catch(s){Je("Error updating sling.settings.json: ",s)}}static getLoginUrl(e){let n=this.getSettings(),i=new URLSearchParams({client:this.CLIENT_NAME,port:String(e.port),localState:e.localState});return e.clientId&&i.set("clientId",e.clientId),`${n[t.BASE_URL]}${this.LOGIN_PATH}?${i.toString()}`}static getExchangeUrl(){return`${this.getSettings()[t.BASE_URL]}${this.EXCHANGE_PATH}`}static getRefreshUrl(){let e=this.getSettings(),n=new URLSearchParams({client:this.REFRESH_CLIENT_NAME});return`${e[t.BASE_URL]}${this.REFRESH_PATH}?${n.toString()}`}static getApiBaseUrl(){return`${this.getSettings()[t.BASE_URL]}${this.API_BASE_PATH}`}static getSageEventsUrl(){return`${this.getSettings()[t.ANALYTICS_DOMAIN]}${this.SAGE_EVENTS_PATH}`}static getTokenExpiryBuffer(){return this.TOKEN_EXPIRY_BUFFER_MS}static getDefaultProjectId(){let e=this.getSettings();return process.env.SLINGSHOT_PROJECT_ID||e[t.PROJECT_ID]}static getDefaultWorkspaceId(){let e=this.getSettings();return process.env.SLINGSHOT_WORKSPACE_ID||e[t.WORKSPACE_ID]}static getDefaultClientId(){let e=this.getSettings();return process.env.CLIENT_ID||e[t.CLIENT_ID]}static getUserActivityUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users/activity`}static getUserUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users`}static getAppTokenUrl(){return`${this.getSettings()[t.BASE_URL]}${this.APP_TOKEN_PATH}`}static getConfigServiceUrl(e){let n=this.getSettings(),i=this.getDefaultClientId(),s=new URLSearchParams({keys:e});return`${n[t.BASE_URL]}${this.CONFIG_SERVICE_PATH}/${i}?${s.toString()}`}static getAppTokenRefreshBuffer(){return this.APP_TOKEN_REFRESH_BUFFER_MS}};function Kl(t){try{let e=t.split(".");if(e.length!==3)return 0;let n=JSON.parse(atob(e[1]));return n.exp?n.exp*1e3:0}catch{return 0}}function jp(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function B1(){return`user_${jp()}`}var q0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",kB=BigInt(q0.length);function MB(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=q0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*kB+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===q0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var G0=new Map,qp=new Map;async function IB(t,e){let n=we.getConfigServiceUrl(t);Pe(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?o=String(a.message):a.error&&(o=String(a.error))}catch{}throw new Error(`Config service request failed: ${o}`)}let r=(await i.json())?.data?.config;if(!r||typeof r!="object")throw new Error("Config service response missing data.config");return r}async function N1(t,e){let n=G0.get(t);if(n)return n;let i=qp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=IB(t,e).then(r=>(G0.set(t,r),r)).finally(()=>{qp.delete(t)});return qp.set(t,s),s}var tc=class{static async getSlingcliConfig(e){let n=await N1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw Je("sling-config: missing slingcli block",n),new Error("Config service did not return slingcli.app_id / slingcli.app_key for this client");return{app_id:i.app_id,app_key:MB(i.app_key)}}static async getRemoteConfig(e,n){return N1(e,n)}static clearCache(){G0.clear(),qp=new Map}};import j1 from"node:path";import Us from"node:fs";var RB="sling.app-creds.json";function K0(){return j1.resolve(_e(),RB)}function q1(){let t=K0();if(!Us.existsSync(t))return null;try{let e=Us.readFileSync(t,"utf-8"),n=JSON.parse(e);return typeof n.app_id!="string"||typeof n.app_key!="string"||!n.app_id||!n.app_key?(Je("app-creds-store: invalid creds file, ignoring",n),null):{app_id:n.app_id,app_key:n.app_key}}catch(e){return Je("app-creds-store: failed to read creds file",e),null}}function H0(t){let e=K0(),n=j1.dirname(e);try{Us.existsSync(n)||Us.mkdirSync(n,{recursive:!0});let i={...t,savedAt:Date.now()};Us.writeFileSync(e,JSON.stringify(i,null,2),{encoding:"utf-8",mode:384});try{Us.chmodSync(e,384)}catch{}Pe(`app-creds-store: persisted to ${e}`)}catch(i){Je("app-creds-store: failed to persist creds",i)}}function G1(){let t=K0();try{Us.existsSync(t)&&(Us.unlinkSync(t),Pe(`app-creds-store: cleared ${t}`))}catch(e){Je("app-creds-store: failed to clear creds file",e)}}var Kp=class extends Error{constructor(n,i){super(i);this.status=n;this.name="AppTokenHttpError"}},Hl=null,zl=null,Gp=null,nc=null;function K1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function PB(t){nc&&(clearTimeout(nc),nc=null);let e=t.expiresAt-Date.now();e<=0||(nc=setTimeout(()=>{nc=null,zi().catch(n=>{Je("app-token: scheduled refresh failed",n)})},e),nc.unref?.())}async function H1(t){let e=Buffer.from(`${t.app_id}:${t.app_key}`).toString("base64"),n=we.getAppTokenUrl();Pe(`app-token: minting from ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${e}`}})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach app-token service: ${c}`)}if(!i.ok){let a=`${i.status} ${i.statusText}`;try{let c=await i.text()||"";c&&(a=c)}catch{}throw new Kp(i.status,`App token request failed: ${a}`)}let s=await i.json();if(!s.app_token||typeof s.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let r=we.getAppTokenRefreshBuffer(),o=Date.now()+s.expires_in*1e3-r;return Pe(`app-token: minted, expires at ${new Date(o).toISOString()}`),{token:s.app_token,expiresAt:o}}async function _B(){let t=q1();if(t)return{creds:t,fromDisk:!0};if(!zl)throw new Error("Cannot mint app token: no on-disk app credentials and no Slingshot user token available (please /login slingshot first)");let e=await tc.getSlingcliConfig(zl);return H0(e),{creds:e,fromDisk:!1}}async function EB(){let{creds:t,fromDisk:e}=await _B();try{return await H1(t)}catch(n){let i=n instanceof Kp&&(n.status===401||n.status===403);if(!e||!i)throw n;if(Je("app-token: disk creds rejected (likely rotated), refetching from config service",{status:n.status}),G1(),!zl)throw new Error("Cannot rotate app credentials: on-disk creds rejected and no Slingshot user token available (please /login slingshot)");let s=await tc.getSlingcliConfig(zl);return H0(s),await H1(s)}}async function zi(t){if(t&&(zl=t),Hl&&Hl.expiresAt>Date.now())return K1(Hl.token),Hl.token;if(Gp)return(await Gp).token;let e=EB().then(i=>(Hl=i,K1(i.token),PB(i),i)).finally(()=>{Gp=null});return Gp=e,(await e).token}var Vl=null,z0=null;typeof process<"u"&&process.versions?.node&&(z0=import("node:http").then(t=>{Vl=t.createServer}));async function AB(){if(Vl||(z0&&await z0,Vl))return Vl;throw new Error("Slingshot OAuth requires Node.js")}async function V0(t){let e=await AB(),n,i,s,r=!1,o=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!r){r=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),m=p.searchParams.get("code"),g=p.searchParams.get("state"),h=p.searchParams.get("clientId"),f=p.searchParams.get("error"),x=p.searchParams.get("error_description");if(f){u.writeHead(400,{"Content-Type":"text/html"}),u.end(`<html><body><h1>Login Failed</h1><p>${x||f}</p><p>You can close this window.</p></body></html>`),a(()=>s(new Error(`Login failed: ${x||f}`)));return}if(!m||!g){u.writeHead(400,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Failed</h1><p>Missing code or state in callback.</p><p>You can close this window.</p></body></html>"),a(()=>s(new Error("Missing code or state in callback")));return}u.writeHead(200,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Successful</h1><p>You can close this window and return to your terminal.</p><script>setTimeout(()=>window.close(),3000)</script></body></html>"),a(()=>i({code:m,state:g,clientId:h||""}))}),n.on("error",d=>{a(()=>s(d))});let c=setTimeout(()=>{a(()=>s(new Error("Login timeout - no callback received within 5 minutes")))},300*1e3);return n.on("close",()=>clearTimeout(c)),t&&t.addEventListener("abort",()=>{a(()=>s(new Error("Login cancelled")))}),{port:await new Promise((d,u)=>{n.once("error",u),n.listen(0,"127.0.0.1",()=>{let p=n.address();p&&typeof p=="object"?d(p.port):u(new Error("Failed to obtain loopback server port"))})}),result:o}}async function J0(t,e){if(!t)throw new Error("Missing exchange code");if(!e)throw new Error("Missing clientId for exchange");let n=we.getExchangeUrl(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify({code:t,clientId:e})})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach Studio Auth: ${o}`)}if(!i.ok){let r,o=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.error?.code,a.error?.message?o=a.error.message:a.message?o=a.message:r&&(o=r)}catch{}throw r==="INVALID_CALLBACK"?new Error("Login failed: exchange code is expired, already used, or bound to a different tenant. Please log in again."):new Error(`Code exchange failed: ${o}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function LB(){return OB(16).toString("hex")}function WB(t){let e=new URL(t),n=e.searchParams.get("code"),i=e.searchParams.get("state"),s=e.searchParams.get("clientId");if(!n||!i)throw new Error("Pasted URL is missing code or state");return{code:n,state:i,clientId:s||""}}async function Q0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Kl(e);return Pe("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await zi(e),{refresh:"",access:e,expires:d>0?d-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:process.env.SLINGSHOT_PROJECT_ID,workspaceId:process.env.SLINGSHOT_WORKSPACE_ID}}let{port:n,result:i}=await V0(t.signal),s=LB(),r=we.getDefaultClientId(),o=we.getLoginUrl({port:n,localState:s,clientId:r||void 0});t.onAuth({url:o});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(WB);a=await Promise.race([i,d])}else a=await i;if(a.state!==s)throw new Error("CSRF check failed - state does not match localState");if(!a.clientId)throw new Error("Login callback did not include clientId");let c=await J0(a.code,a.clientId),l=Kl(c.accessToken);return await zi(c.accessToken),{refresh:c.refreshToken,access:c.accessToken,expires:l>0?l-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:void 0,workspaceId:void 0}}import{randomUUID as UB}from"node:crypto";async function Hp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await zi()}catch(a){throw Je("auth/refresh: app token unavailable for refresh call",a),new Error(`Cannot refresh Slingshot token: app token unavailable (${a instanceof Error?a.message:String(a)}). Please /login slingshot.`)}let n=UB(),i={accept:"application/json",rt:t.refresh,"trace-id":n,Authorization:`Bearer ${e}`},s;try{let a=we.getRefreshUrl();s=await fetch(a,{headers:i})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach Slingshot server: ${c}`)}if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();c.message?a=String(c.message):c.error&&(a=String(c.error))}catch{}throw new Error(`Token refresh failed: ${a}`)}let r=await s.json();if(!r.accessToken)throw new Error("No access token in refresh response");let o=Kl(r.accessToken);try{await zi(r.accessToken)}catch(a){throw Je("auth/refresh: app token refresh failed",a),a}return{refresh:r.refreshToken||t.refresh,access:r.accessToken,expires:o>0?o-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var z1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-4.1",name:"GPT-4.1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768,provider:"slingshot",api:"openai-completions"},{id:"gpt-5",name:"GPT-5",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-mini",name:"GPT-5 Mini",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-nano",name:"GPT-5 Nano",reasoning:!0,input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.1",name:"GPT-5.1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.2",name:"GPT-5.2",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.4",name:"GPT-5.4",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.5",name:"GPT-5.5",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"claude-opus-4@20250514",name:"Claude Opus 4",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4@20250514",name:"Claude Sonnet 4",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-5@20250929",name:"Claude Sonnet 4.5",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-opus-4-6",name:"Claude Opus 4.6",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"o3",name:"O3",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o3-mini",name:"o3-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o4-mini",name:"o4-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536,provider:"slingshot",api:"openai-completions"}];var _r={name:"slingshot.cli",private:!0,type:"module",workspaces:["packages/*","packages/web-ui/example","packages/coding-agent/examples/extensions/with-deps","packages/coding-agent/examples/extensions/custom-provider-anthropic","packages/coding-agent/examples/extensions/custom-provider-gitlab-duo"],scripts:{clean:"npm run clean --workspaces",build:"cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build && cd ../web-ui && npm run build",dev:'concurrently --names "ai,agent,coding-agent,web-ui,tui" --prefix-colors "cyan,yellow,red,white,green,magenta" "cd packages/ai && npm run dev" "cd packages/agent && npm run dev" "cd packages/coding-agent && npm run dev" "cd packages/web-ui && npm run dev" "cd packages/tui && npm run dev"',"dev:tsc":'concurrently --names "ai,web-ui" --prefix-colors "cyan,green" "cd packages/ai && npm run dev:tsc" "cd packages/web-ui && npm run dev:tsc"',check:"","check:browser-smoke":"","profile:tui":"node scripts/profile-coding-agent-node.mjs --mode tui","profile:rpc":"node scripts/profile-coding-agent-node.mjs --mode rpc",test:"npm run test --workspaces --if-present","version:patch":"npm version patch -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:minor":"npm version minor -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:major":"npm version major -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:set":"npm version -ws",prepublishOnly:"npm run clean && npm run build && npm run check",publish:"npm run prepublishOnly && npm publish -ws --access public","publish:dry":"npm run prepublishOnly && npm publish -ws --access public --dry-run","release:patch":"node scripts/release.mjs patch","release:minor":"node scripts/release.mjs minor","release:major":"node scripts/release.mjs major",prepare:"husky"},devDependencies:{"@anthropic-ai/sandbox-runtime":"0.0.26","@biomejs/biome":"2.3.5","@types/node":"22.19.19","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"0.28.0",husky:"9.1.7",jiti:"2.7.0",shx:"0.4.0",tsx:"4.22.1",typescript:"5.9.3"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260523-3",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@mozilla/readability":"^0.6.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0",linkedom:"^0.18.12",turndown:"^7.2.4",unpdf:"^1.6.2"}};var q1e=we.getRefreshUrl(),G1e=we.getApiBaseUrl(),K1e=we.getSageEventsUrl(),H1e=we.getTokenExpiryBuffer(),V1=we.getDefaultProjectId(),J1=we.getDefaultWorkspaceId(),Q1=we.getDefaultClientId();async function zp(t,e,n){let i=B1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){Pe("ERROR: No API key found");return}let r=s.startsWith("Bearer ")?s:`Bearer ${s}`,o=process.env.SLINGSHOT_PROJECT_ID||V1,a=process.env.SLINGSHOT_WORKSPACE_ID||J1,c=process.env.CLIENT_ID||Q1,l={"Content-Type":"application/json",accept:"application/json","access-token":r,"x-project-id":o,"x-workspace-id":a,"x-client-id":c,"sage-trace-id":i,"User-Agent":"pi-slingshot/1.0.0"},d=parseFloat(process.env.SLINGSHOT_TEMPERATURE||"0.2"),u=parseFloat(process.env.SLINGSHOT_TOP_P||"0.8"),p={source:_r.name||"sling",ai_model_info:{ai_provider_name:e.model?.provider||"slingshot",sage_modl_name:e.model?.id||"unknown",sage_modl_option:{temperature:String(d),max_token_size:String(e.model?.maxTokens||16834),top_p:String(u)}},rag_info:{type:null,account_name:"dummy",project_names:[],repository_names:[],programming_language:null},tab_data:{tab_count:"1"},tags:null,slingshot_version:_r.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Vp(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};Pe(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let r=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(r.ok){let o=await r.json().catch(()=>{});if(o.error_code)throw new Error(`Analytics API error: ${o.error_code} - ${o.error_message||"No message"}`);Pe(`'SUCCESS: Event sent: ${t}`),Pe(`Response: ${JSON.stringify(o)}`),Pe("\u2500".repeat(66))}else{let o=await r.text().catch(()=>""),a={status:r.status,statusText:r.statusText,responseBody:o,requestHeaders:e};throw Pe(`ERROR: ${r.status} ${r.statusText}`),Je("Error Details",a),Je("Failed Request Body",s),new Error(`Analytics API error: ${r.status} ${r.statusText}`)}}catch(r){let o=r instanceof Error?r.message:String(r);console.warn("[Slingshot Analytics] Request that caused error:",o),Pe(`EXCEPTION: ${o}`),r instanceof Error&&r.stack&&Pe(`Stack trace: ${r.stack}`),Je("Request that caused exception",s)}}import Jl from"chalk";function Y1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
|
|
445
445
|
\u274D \xB7 \u274D / || | | | | \\ | | / _____|
|
|
446
446
|
\u2726 \u26AC \u2726 | (----\`| | | | | \\| | | | __
|
|
447
447
|
\u26AC \xB7 \u26AC \u26AC \xB7 \u26AC \\ \\ | | | | | . \` | | | |_ |
|
|
@@ -452,12 +452,12 @@ ${JSON.stringify(e,null,2)}
|
|
|
452
452
|
`))i.startsWith("+++ ")||i.startsWith("--- ")||i.startsWith("@@")||(i.startsWith("+")?e++:i.startsWith("-")&&n++);return{added:e,removed:n}}function zB(t,e){return`(+${t}/-${e})`}function VB(t,e){let n=e.match(/^\+(\d+)\/\-(\d+)$/);if(!n)return t.fg("muted",e);let i=Number(n[1]),s=Number(n[2]),r=i===0?t.fg("text",`+${i}`):t.fg("success",`+${i}`),o=s===0?t.fg("text",`-${s}`):t.fg("error",`-${s}`);return r+t.fg("text","/")+o}function JB(t,e){if(t.size===0)return;let n=0,i=0;for(let s of t.values())s.kind==="new"?i++:n++;return e?e.fg("muted",`\u0394 ${n} + ${i}`):`\u0394 ${n} + ${i}`}function tM(t,e){if(t.size===0)return;let n=[...t.values()].sort((r,o)=>o.updatedAt-r.updatedAt),i=8,s=[];for(let r of n.slice(0,i)){let o=r.kind==="new"?"+":"\u0394";if(!e){s.push(`${o} ${r.displayPath} ${zB(r.added,r.removed)}`);continue}let a=e.fg("muted",`${o} `)+e.fg("muted",`${r.displayPath} `),c,l=r.added===0?e.fg("text",`+${r.added}`):e.fg("success",`+${r.added}`),d=r.removed===0?e.fg("text",`-${r.removed}`):e.fg("error",`-${r.removed}`);c=e.fg("text","(")+l+e.fg("text","/")+d+e.fg("text",")"),s.push(a+c)}return n.length>i&&s.push(e?e.fg("dim",`\u2026and ${n.length-i} more`):`\u2026and ${n.length-i} more`),s}function ib(t,e,n){return DB(t,t,e??"",n,"","",{context:3})}async function QB(t){await jB(qB(t),{recursive:!0})}function nM(t){let e=new Map,n=new Map,i=new Map;function s(u){u?.hasUI&&(u.ui.setStatus("filechanges",JB(n,u.ui.theme)),u.ui.setWidget("filechanges",tM(n,u.ui.theme)))}async function r(u,p){let m=e.get(p);if(!m)return;let g=await tb(m.absPath);if(m.originalContent===null){if(g===null){n.delete(p);return}let w=m.path,P=ib(w,null,g),{added:_,removed:R}=nb(P);n.set(p,{path:m.path,absPath:m.absPath,displayPath:w,originalContent:null,currentContent:g,diff:P,added:_,removed:R,kind:"new",updatedAt:Date.now()});return}if(g===null){let w=m.path,P=ib(w,m.originalContent,""),{added:_,removed:R}=nb(P);n.set(p,{path:m.path,absPath:m.absPath,displayPath:w,originalContent:m.originalContent,currentContent:"",diff:P,added:_,removed:R,kind:"edited",updatedAt:Date.now()});return}if(g===m.originalContent){n.delete(p);return}let h=m.path,f=ib(h,m.originalContent,g),{added:x,removed:y}=nb(f);n.set(p,{path:m.path,absPath:m.absPath,displayPath:h,originalContent:m.originalContent,currentContent:g,diff:f,added:x,removed:y,kind:"edited",updatedAt:Date.now()})}async function o(u,p){e.clear(),n.clear(),i.clear(),t.appendEntry(Z1,{timestamp:Date.now(),reason:p}),s(u)}async function a(u){if(await u.waitForIdle(),n.size===0){u.hasUI&&u.ui.notify("filechanges: nothing to decline.","info");return}let p=u.args?.includes("force")??!1;if(u.hasUI&&!p){if(!await u.ui.confirm("Decline sling changes?","This will revert ALL currently logged sling changes (overwrite files / delete created files)."))return}else if(!u.hasUI&&!p)throw new Error("Decline requires confirmation. Run: /s:filechanges-decline force");let m=[...n.values()].sort((f,x)=>x.updatedAt-f.updatedAt),g=0,h=[];for(let f of m)try{f.originalContent===null?await NB(f.absPath,{force:!0}):(await QB(f.absPath),await BB(f.absPath,f.originalContent,"utf-8")),g++}catch(x){h.push(`${f.displayPath}: ${x?.message??String(x)}`)}await o(u,"decline"),u.hasUI&&(h.length===0?u.ui.notify(`filechanges: declined changes for ${g} file(s).`,"info"):(u.ui.notify(`filechanges: declined with ${h.length} error(s). Run /s:filechanges to inspect; see console for details.`,"warning"),console.warn(`[filechanges] decline errors:
|
|
453
453
|
`+h.join(`
|
|
454
454
|
`))))}async function c(u){if(await u.waitForIdle(),n.size===0){u.hasUI&&u.ui.notify("filechanges: nothing to accept.","info");return}let p=u.args?.includes("force")??!1;if(u.hasUI&&!p){if(!await u.ui.confirm("Accept sling changes?","This will keep current files as-is and clear the modification log."))return}else if(!u.hasUI&&!p)throw new Error("Accept requires confirmation. Run: /filechanges-accept force");let m=n.size;await o(u,"accept"),u.hasUI&&u.ui.notify(`filechanges: accepted changes for ${m} file(s).`,"info")}function l(u){return u?u.split(/\s+/g).map(p=>p.trim()).filter(Boolean):[]}t.registerCommand("s:filechanges",{description:"Show files changed by sling and inspect diffs",handler:async(u,p)=>{if(p.args=l(u),await p.waitForIdle(),s(p),!p.hasUI){if([...n.values()].sort((h,f)=>f.updatedAt-h.updatedAt).length===0){console.log("filechanges: no sling made modifications recorded.");return}let g=tM(n)??[];console.log(g.join(`
|
|
455
|
-
`));return}for(;;){await p.waitForIdle(),s(p);let m=[...n.values()].sort((y,w)=>w.updatedAt-y.updatedAt);if(m.length===0){p.ui.notify("filechanges: no sling made modifications recorded.","info");return}let g=[{value:"__accept__",label:"Accept changes (clear log)",description:"Keep current files"},{value:"__decline__",label:"Undo changes (revert)",description:"Restore original contents"},{value:"__sep__",label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",description:""},...m.map(y=>({value:y.path,label:`${y.kind==="new"?"+":"\u0394"} ${y.displayPath}`,description:`+${y.added}/-${y.removed}`}))],h=await p.ui.custom((y,w,P,_)=>{let R=new K;R.addChild(new V(E=>w.fg("accent",E))),R.addChild(new A(w.fg("accent",w.bold("File changes")),1,0));let L=new Qt(g,Math.min(14,g.length),{selectedPrefix:E=>w.fg("accent",E),selectedText:E=>w.fg("accent",E),description:E=>VB(w,E),scrollInfo:E=>w.fg("dim",E),noMatch:E=>w.fg("warning",E)});return L.onSelect=E=>{E.value!=="__sep__"&&_(E.value)},L.onCancel=()=>_(null),R.addChild(L),R.addChild(new A(w.fg("dim","\u2191\u2193 navigate \u2022 enter select \u2022 esc close"),1,0)),R.addChild(new V(E=>w.fg("accent",E))),{render:E=>R.render(E),invalidate:()=>R.invalidate(),handleInput:E=>{L.handleInput(E),y.requestRender()}}},{overlay:!0});if(!h)return;if(h==="__accept__"){await c(p);return}if(h==="__decline__"){await a(p);return}let f=n.get(h);if(!f){p.ui.notify("filechanges: entry not found (maybe log was cleared).","warning");continue}let x="```diff\n"+(f.diff.trimEnd()||"(no diff)")+"\n```";await p.ui.custom((y,w,P,_)=>{let R=new K;return R.addChild(new V(L=>w.fg("accent",L))),R.addChild(new A(w.fg("accent",w.bold(f.displayPath)),1,0)),R.addChild(new ze(x,1,0,Tt())),R.addChild(new A(w.fg("dim","esc to go back"),1,0)),R.addChild(new V(L=>w.fg("accent",L))),{render:L=>R.render(L),invalidate:()=>R.invalidate(),handleInput:L=>{
|
|
455
|
+
`));return}for(;;){await p.waitForIdle(),s(p);let m=[...n.values()].sort((y,w)=>w.updatedAt-y.updatedAt);if(m.length===0){p.ui.notify("filechanges: no sling made modifications recorded.","info");return}let g=[{value:"__accept__",label:"Accept changes (clear log)",description:"Keep current files"},{value:"__decline__",label:"Undo changes (revert)",description:"Restore original contents"},{value:"__sep__",label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",description:""},...m.map(y=>({value:y.path,label:`${y.kind==="new"?"+":"\u0394"} ${y.displayPath}`,description:`+${y.added}/-${y.removed}`}))],h=await p.ui.custom((y,w,P,_)=>{let R=new K;R.addChild(new V(E=>w.fg("accent",E))),R.addChild(new A(w.fg("accent",w.bold("File changes")),1,0));let L=new Qt(g,Math.min(14,g.length),{selectedPrefix:E=>w.fg("accent",E),selectedText:E=>w.fg("accent",E),description:E=>VB(w,E),scrollInfo:E=>w.fg("dim",E),noMatch:E=>w.fg("warning",E)});return L.onSelect=E=>{E.value!=="__sep__"&&_(E.value)},L.onCancel=()=>_(null),R.addChild(L),R.addChild(new A(w.fg("dim","\u2191\u2193 navigate \u2022 enter select \u2022 esc close"),1,0)),R.addChild(new V(E=>w.fg("accent",E))),{render:E=>R.render(E),invalidate:()=>R.invalidate(),handleInput:E=>{L.handleInput(E),y.requestRender()}}},{overlay:!0});if(!h)return;if(h==="__accept__"){await c(p);return}if(h==="__decline__"){await a(p);return}let f=n.get(h);if(!f){p.ui.notify("filechanges: entry not found (maybe log was cleared).","warning");continue}let x="```diff\n"+(f.diff.trimEnd()||"(no diff)")+"\n```";await p.ui.custom((y,w,P,_)=>{let R=new K;return R.addChild(new V(L=>w.fg("accent",L))),R.addChild(new A(w.fg("accent",w.bold(f.displayPath)),1,0)),R.addChild(new ze(x,1,0,Tt())),R.addChild(new A(w.fg("dim","esc to go back"),1,0)),R.addChild(new V(L=>w.fg("accent",L))),{render:L=>R.render(L),invalidate:()=>R.invalidate(),handleInput:L=>{Ee(L,ar.escape)||Ee(L,ar.ctrl("c"))?_():y.requestRender()}}},{overlay:!0})}}}),t.registerCommand("s:filechanges-accept",{description:"Accept sling made changes (keeps files, clears log)",handler:async(u,p)=>{p.args=l(u),await c(p)}}),t.registerCommand("s:filechanges-decline",{description:"Decline sling made changes (reverts files, clears log)",handler:async(u,p)=>{p.args=l(u),await a(p)}});async function d(u){e.clear(),n.clear(),i.clear();for(let p of u.sessionManager.getBranch())if(p.type==="custom"){if(p.customType===Z1){e.clear(),n.clear();continue}if(p.customType===X1){let m=p.data;if(!m?.path)continue;let{absPath:g,relPath:h}=eb(u.cwd,m.path);e.set(h,{path:h,absPath:g,originalContent:typeof m.originalContent=="string"?m.originalContent:null,createdAt:typeof m.timestamp=="number"?m.timestamp:Date.now()});continue}if(p.customType===eM){let m=p.data;if(!m?.path)continue;let{relPath:g}=eb(u.cwd,m.path);e.delete(g),n.delete(g);continue}}for(let p of e.keys())await r(u,p);s(u)}t.on("session_start",async(u,p)=>{await d(p)}),t.on("session_before_switch",async(u,p)=>{await d(p)}),t.on("session_tree",async(u,p)=>{await d(p)}),t.on("session_before_fork",async(u,p)=>{await d(p)}),t.on("tool_call",async(u,p)=>{if(fl("edit",u)||fl("write",u)){let{absPath:m,relPath:g}=eb(p.cwd,u.input.path),h=await tb(m);i.set(u.toolCallId,{path:g,absPath:m,before:h})}}),t.on("tool_result",async(u,p)=>{if(u.isError){i.delete(u.toolCallId);return}if(!Zd(u)&&!ep(u))return;let m=i.get(u.toolCallId);if(i.delete(u.toolCallId),!m)return;e.has(m.path)||(e.set(m.path,{path:m.path,absPath:m.absPath,originalContent:m.before,createdAt:Date.now()}),t.appendEntry(X1,{path:m.path,originalContent:m.before,timestamp:Date.now()})),await r(p,m.path);let g=e.get(m.path),h=await tb(m.absPath);g&&(g.originalContent!==null&&h===g.originalContent||g.originalContent===null&&h===null)&&(e.delete(m.path),n.delete(m.path),t.appendEntry(eM,{path:m.path,timestamp:Date.now()})),s(p)})}import{readFileSync as lu,writeFileSync as FI,existsSync as uc,mkdirSync as DI,readdirSync as W8}from"node:fs";import{join as Ji,dirname as $I}from"node:path";import{homedir as uu}from"node:os";function YB(t){return Buffer.byteLength(t,"utf8")}function XB(t){let e=[];for(let n of t){let i=n.replace(/\r/g,"");if(i.length===0){e.push("");continue}e.push(...i.split(`
|
|
456
456
|
`))}return e}var Ql=class{constructor(e){this.commands=[];this.commandIndex=new Map;this.totalLines=0;this.totalBytes=0;this.truncatedCommands=0;this.settings=e}startCommand(e,n,i){let s={id:e,command:n,cwdAtStart:i,startedAt:Date.now(),output:[],outputBytes:0,exitCode:null,finishedAt:null,truncated:!1};return this.commands.push(s),this.commandIndex.set(e,s),this.enforceLimits(),s}appendOutput(e,n){let i=this.commandIndex.get(e);if(!i||!n)return;let s=XB([n]);if(s.length===0)return;i.output.push(...s);let r=s.reduce((o,a)=>o+YB(a)+1,0);i.outputBytes+=r,this.totalLines+=s.length,this.totalBytes+=r,this.enforceLimits()}finishCommand(e,n){let i=this.commandIndex.get(e);i&&(i.exitCode=n,i.finishedAt=Date.now())}clear(){this.commands=[],this.commandIndex.clear(),this.totalLines=0,this.totalBytes=0,this.truncatedCommands=0}getSnapshot(){return{commands:this.commands.map(e=>({...e,output:[...e.output]})),totalLines:this.totalLines,totalBytes:this.totalBytes,truncatedCommands:this.truncatedCommands}}enforceLimits(){for(;this.commands.length>1&&(this.totalLines>this.settings.transcriptMaxLines||this.totalBytes>this.settings.transcriptMaxBytes);){let e=this.commands.shift();if(!e)break;this.commandIndex.delete(e.id),this.totalLines=Math.max(0,this.totalLines-e.output.length),this.totalBytes=Math.max(0,this.totalBytes-e.outputBytes),this.truncatedCommands+=1,e.truncated=!0}}};import{readdirSync as lN}from"node:fs";import{spawnSync as uN}from"node:child_process";import{basename as dN,dirname as pN,isAbsolute as mN,join as hN,resolve as gN}from"node:path";import{existsSync as Jp,mkdirSync as ZB,readFileSync as Qp,writeFileSync as eN}from"node:fs";import{dirname as tN,join as Yl}from"node:path";import{homedir as nN}from"node:os";function iM(){return process.env.HOME||process.env.USERPROFILE||nN()}function iN(){return Yl(iM(),".pi","agent","powerline-footer","bash-history")}function sN(t){return t.replace(/^[/\\]+|[/\\]+$/g,"").replace(/[\\/]+/g,"-")||"root"}function sM(t){return Yl(iN(),`${sN(t)}.json`)}function rN(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(typeof n!="object"||n===null||Array.isArray(n))continue;let i=typeof n.command=="string"?n.command.trim():"",s=typeof n.cwd=="string"?n.cwd.trim():"",r=typeof n.timestamp=="number"&&Number.isFinite(n.timestamp)?n.timestamp:0;!i||!s||!r||e.push({command:i,cwd:s,timestamp:r})}return e}function Xl(t){let e=sM(t);if(!Jp(e))return[];try{let n=JSON.parse(Qp(e,"utf8"));return typeof n!="object"||n===null||Array.isArray(n)?[]:rN(n.entries).sort((i,s)=>s.timestamp-i.timestamp)}catch(n){return console.debug(`[powerline-footer] Failed to read bash project history from ${e}:`,n),[]}}function rM(t,e,n){let i=e.trim();if(!i)return;let s=Xl(t),r=[{command:i,cwd:n,timestamp:Date.now()},...s.filter(a=>a.command!==i)].slice(0,500),o=sM(t);try{ZB(tN(o),{recursive:!0}),eN(o,JSON.stringify({version:1,entries:r},null,2)+`
|
|
457
457
|
`)}catch(a){console.debug(`[powerline-footer] Failed to persist bash project history to ${o}:`,a)}}function oN(t){let e=t.trim();if(!e)return null;if(!e.startsWith(":"))return e;let n=e.split(";");return n.length<2?null:n.slice(1).join(";").trim()||null}function aN(t){return t.map(e=>e.trim()).filter(Boolean)}function cN(t){let e=t.matchAll(/^\s*-\s*cmd:\s*(.+)$/gm),n=[];for(let i of e){let s=i[1]?.trim();s&&n.push(s)}return n}function Zl(t){let e=t.split("/").pop()?.toLowerCase()??"",n=iM();try{if(e.includes("zsh")){let s=process.env.HISTFILE||Yl(n,".zsh_history");return Jp(s)?Qp(s,"utf8").split(`
|
|
458
458
|
`).map(oN).filter(r=>!!r).reverse():[]}if(e.includes("fish")){let s=Yl(n,".local","share","fish","fish_history");return Jp(s)?cN(Qp(s,"utf8")).reverse():[]}let i=process.env.HISTFILE||Yl(n,".bash_history");return Jp(i)?aN(Qp(i,"utf8").split(`
|
|
459
459
|
`)).reverse():[]}catch(i){return console.debug(`[powerline-footer] Failed to read global shell history for ${e}:`,i),[]}}function Er(t,e,n){let i=e.trim(),s=new Set,r=[];for(let o of t){let a=o?.trim();if(!(!a||s.has(a))&&!(i&&!a.startsWith(i))&&(s.add(a),r.push(a),r.length>=n))break}return r}var fN=["add","bisect","branch","checkout","cherry-pick","clean","clone","commit","diff","fetch","grep","init","log","merge","mv","pull","push","rebase","reset","restore","revert","rm","show","stash","status","switch","tag","worktree"];function lM(t){let e=[],n="",i=null,s=!1;for(let r of t){if(s){n+=r,s=!1;continue}if(r==="\\"){s=!0,n+=r;continue}if(i){n+=r,r===i&&(i=null);continue}if(r==="'"||r==='"'){i=r,n+=r;continue}if(/\s/.test(r)){n&&(e.push(n),n="");continue}n+=r}return n&&e.push(n),e}function bN(t,e){let n=t.slice(0,e),i=t.slice(e),s=lM(n),r=0;for(let a=n.length-1;a>=0;a-=1){let c=n[a];if(c&&/\s/.test(c)){r=a+1;break}}let o=e;for(let a=e;a<t.length;a+=1){let c=t[a];if(c&&/\s/.test(c))break;o=a+1}return{line:t,cursorCol:e,beforeCursor:n,afterCursor:i,token:t.slice(r,o),tokenStart:r,tokenEnd:o,tokenIndex:Math.max(0,s.length-1),previousTokens:s}}function nu(t){return t.startsWith("!!")?{prefix:"!!",command:t.slice(2),offset:2}:t.startsWith("!")?{prefix:"!",command:t.slice(1),offset:1}:null}function eu(t){return"shouldTriggerFileCompletion"in t&&typeof t.shouldTriggerFileCompletion=="function"}function uM(t){return"replacement"in t&&typeof t.replacement=="string"&&"startCol"in t&&typeof t.startCol=="number"&&"endCol"in t&&typeof t.endCol=="number"}function oM(t){let e=new Map;for(let n of t){let i=`${n.startCol}:${n.endCol}:${n.replacement}`,s=e.get(i);(!s||n.score>s.score)&&e.set(i,n)}return[...e.values()].sort((n,i)=>i.score-n.score||n.label.localeCompare(i.label))}function xN(t,e){let n=t.startsWith("~/")?hN(process.env.HOME||"",t.slice(2)):t;if(!n.includes("/"))return{dir:e,prefix:n,displayPrefix:""};let s=n.endsWith("/")?n.slice(0,-1):pN(n),r=mN(s)?s:gN(e,s),o=n.endsWith("/")?"":dN(n),a=t.endsWith("/")?t:t.slice(0,Math.max(0,t.length-o.length));return{dir:r,prefix:o,displayPrefix:a}}function yN(t){return t.replace(/([\\\s"'`$&|;<>()[\]{}?!*])/g,"\\$1")}function vN(t,e){if(!t)return[];let{dir:n,prefix:i,displayPrefix:s}=xN(t,e);try{return lN(n,{withFileTypes:!0}).filter(o=>i.length===0||o.name.startsWith(i)).slice(0,100).map(o=>{let a=o.isDirectory()?"/":"",c=`${s}${o.name}${a}`,l=`${s}${yN(o.name)}${a}`;return{value:l,label:c,replacement:l,startCol:0,endCol:0,source:"path",score:40+(o.isDirectory()?4:0)}})}catch{return[]}}function aM(t,e){try{let n=uN("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return n.status!==0||!n.stdout?[]:n.stdout.split(`
|
|
460
|
-
`).map(i=>i.trim()).filter(Boolean)}catch{return[]}}function wN(t,e){let n=t.previousTokens;if(n[0]!=="git")return[];if(t.tokenIndex<=1)return fN.filter(r=>r.startsWith(t.token)).map(r=>({value:r,label:r,replacement:r,startCol:0,endCol:0,source:"git",score:52}));let i=n[1]??"";if(!["checkout","switch","merge","rebase","branch","show","diff"].includes(i))return[];let s=[...aM(["branch","--format=%(refname:short)"],e),...aM(["tag","--list"],e)];return[...new Set(s)].filter(r=>r.startsWith(t.token)).slice(0,100).map(r=>({value:r,label:r,replacement:r,startCol:0,endCol:0,source:"git",score:50}))}function SN(t){return t.cursorCol===t.line.length&&t.line.trim().length>0}function cM(t,e,n){return t.map(i=>({...i,startCol:e,endCol:n}))}function dM(t,e){return t.slice(0,e.startCol)+e.replacement+t.slice(e.endCol)}function CN(t){return lM(t.trim())[0]??""}function TN(t,e,n){for(let i of t){let s=i.trim();if(!(!s||!s.startsWith(e))&&CN(s)===n)return s}return null}function kN(t){let e=t.trim();return e?"cd".startsWith(e)?{value:"cd ..",source:"path"}:"git".startsWith(e)?{value:"git status",source:"git"}:null:null}function MN(t){let e=t.trim();return e.length>=2&&"git".startsWith(e)}function IN(t,e,n){if(e.length===0||n.length===0)return e;let i=new Map;for(let[s,r]of n.entries())i.set(r,Math.max(1,4-s));return e.map(s=>{let r=i.get(dM(t,s));return r?{...s,score:s.score+r}:s})}var tu=class{async getGhostSuggestion(e,n,i,s){let r=Xl(n);if(e.trim().length===0){let u=e,p=Er(r.map(m=>m.command),e,1);return p.length>0?{value:`${u}${p[0]}`,source:"project-history"}:null}let o=bN(e,e.length);if(!SN(o))return null;let a=Er(r.map(u=>u.command),e,10);if(a.length>0)return{value:a[0],source:"project-history"};if(o.tokenIndex===0)return this.getCommandPositionGhostSuggestion(e,Zl(i));let c=this.getDeterministicInlineSuggestions(o,n),l=Er(Zl(i),e,5),d=IN(e,oM(c),l);for(let u of d){let p=this.buildInlineSuggestionValue(e,u);if(p)return{value:p,source:u.source}}return null}getCommandPositionGhostSuggestion(e,n){if(MN(e)){let i=TN(n,e,"git");if(i)return{value:i,source:"global-history"}}return kN(e)}getDeterministicInlineSuggestions(e,n){let i=[];return i.push(...cM(wN(e,n),e.tokenStart,e.tokenEnd)),i.push(...cM(vN(e.token,n),e.tokenStart,e.tokenEnd)),oM(i)}buildInlineSuggestionValue(e,n){let i=dM(e,n);return!i.startsWith(e)||i===e?null:i}},Yp=class{getSuggestions(){return null}applyCompletion(e,n,i,s){if(!uM(s))throw new Error("Expected an extended completion item for bash autocomplete");return pM(e,n,s)}shouldTriggerFileCompletion(){return!1}};function pM(t,e,n){let i=t[e]||"",s=Math.max(0,Math.min(n.startCol,i.length)),r=Math.max(s,Math.min(n.endCol,i.length)),o=i.slice(0,s)+n.replacement+i.slice(r),a=[...t];return a[e]=o,{lines:a,cursorLine:e,cursorCol:s+n.replacement.length}}var Xp=class{getSuggestions(){return null}applyCompletion(e,n,i,s){if(!uM(s))throw new Error("Expected an extended completion item for one-off bash autocomplete");return pM(e,n,s)}shouldTriggerFileCompletion(e,n,i){let s=n===0?nu(e[0]||""):null;return s!==null&&i>=s.offset}},Zp=class{constructor(e,n,i,s){this.defaultProvider=e,this.bashProvider=n,this.oneOffBashProvider=i,this.isBashModeActive=s}getSuggestions(e,n,i,s){return this.isBashModeActive()?this.bashProvider.getSuggestions(e,n,i,s):eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?this.oneOffBashProvider.getSuggestions(e,n,i,s):this.defaultProvider?.getSuggestions(e,n,i,s)??null}applyCompletion(e,n,i,s,r){return this.isBashModeActive()?this.bashProvider.applyCompletion(e,n,i,s,r):eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?this.oneOffBashProvider.applyCompletion(e,n,i,s,r):this.defaultProvider?this.defaultProvider.applyCompletion(e,n,i,s,r):{lines:e,cursorLine:n,cursorCol:i}}shouldTriggerFileCompletion(e,n,i){return this.isBashModeActive()?eu(this.bashProvider)?this.bashProvider.shouldTriggerFileCompletion(e,n,i):!0:eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?!0:!this.defaultProvider||!eu(this.defaultProvider)?!1:this.defaultProvider.shouldTriggerFileCompletion(e,n,i)}};import{fileURLToPath as RN}from"node:url";var mM=new Map([["super+up",/^\x1b\[(?:1;9(?::[12])?[AH]|574(?:19|23);9(?::[12])?u|7;9(?::[12])?~|27;9;65~)$/],["super+down",/^\x1b\[(?:1;9(?::[12])?[BF]|574(?:20|24);9(?::[12])?u|8;9(?::[12])?~|27;9;66~)$/],["super+home",/^\x1b\[(?:1;9(?::[12])?H|57423;9(?::[12])?u|7;9(?::[12])?~)$/],["super+end",/^\x1b\[(?:1;9(?::[12])?F|57424;9(?::[12])?u|8;9(?::[12])?~)$/],["super+pageup",/^\x1b\[(?:5;9(?::[12])?~|57421;9(?::[12])?u)$/],["super+pagedown",/^\x1b\[(?:6;9(?::[12])?~|57422;9(?::[12])?u)$/],["super+shift+up",/^\x1b\[(?:1;10(?::[12])?[AH]|574(?:19|23);10(?::[12])?u|7;10(?::[12])?~|27;10;65~)$/],["super+shift+down",/^\x1b\[(?:1;10(?::[12])?[BF]|574(?:20|24);10(?::[12])?u|8;10(?::[12])?~|27;10;66~)$/],["super+shift+home",/^\x1b\[(?:1;10(?::[12])?H|57423;10(?::[12])?u|7;10(?::[12])?~)$/],["super+shift+end",/^\x1b\[(?:1;10(?::[12])?F|57424;10(?::[12])?u|8;10(?::[12])?~)$/]]);function sb(t){return t.toLowerCase().split("+").slice(0,-1).includes("super")}function hM(t){return mM.has(t.toLowerCase())}function gM(t){switch(t.toLowerCase()){case"super+home":return"super+up";case"super+end":return"super+down";case"super+shift+home":return"super+shift+up";case"super+shift+end":return"super+shift+down";default:return t}}function Un(t,e){let n=e.toLowerCase();return sb(n)?mM.get(n)?.test(t)??!1:_e(t,e)}var PN={start:"super+shift+up",end:"super+shift+down"};function _N(t){return t.length===1&&t.charCodeAt(0)>=32}function EN(t){return t==="\x1B[122;9u"||t==="\x1B[122;9:1u"||t==="\x1B[122;9:2u"||t==="\x1B[27;9;122~"}function AN(t){let e="\x1B[200~",n="\x1B[201~";if(t.indexOf(e)!==0)return null;let s=t.indexOf(n,e.length);return s===-1||s+n.length!==t.length?null:t.slice(e.length,s)}function ON(t){let e=t.split(/\r?\n|\s+/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"));if(e.length===0||e.some(n=>!n.startsWith("file://")))return null;try{return e.map(n=>RN(n)).join(" ")}catch{return null}}function LN(t){let n=AN(t)??t,i=ON(n);if(i)return i;let s=n.replace(/^[\r\n]+|[\r\n]+$/g,"");return s.length<=1||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(s)?null:/^(?:\/|~\/|\.\.?\/)/.test(s)&&!/[\r\n]/.test(s)?s:null}var em=class extends As{constructor(n,i,s,r){super(n,i,s);this.wrappedProviderInstalled=!1;this.shellHistoryIndex=-1;this.shellHistoryItems=[];this.shellHistoryDraft="";this.ghost=null;this.ghostAbort=null;this.ghostToken=0;this.keybindingsRef=s,this.optionsRef=r}installAutocompleteProvider(n){this.setAutocompleteProvider(n),this.wrappedProviderInstalled=!0}hasWrappedProvider(){return this.wrappedProviderInstalled}getGhostSuggestion(){return this.isShellCompletionContext()?this.ghost:null}refreshGhostSuggestion(){this.scheduleGhostUpdate()}clearGhostSuggestion(){this.ghostAbort?.abort(),this.ghostAbort=null,this.ghost=null}dismissBashModeUi(){this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.clearGhostSuggestion(),"cancelAutocomplete"in this&&typeof this.cancelAutocomplete=="function"&&this.cancelAutocomplete(),this.tui.requestRender()}handleInput(n){let i=LN(n);if(i!==null){this.insertTextAtCursor(i),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.isShellCompletionContext()?this.scheduleGhostUpdate():this.clearGhostSuggestion();return}let s=n.includes("\x1B[200~")||Reflect.get(this,"isInPaste")===!0;if(s){if(super.handleInput(n),Reflect.get(this,"isInPaste")===!0)return}else{let r=this.optionsRef.isBashModeActive(),o=!r&&this.isOneOffBashCommandContext();if(EN(n)){this.undo(),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.isShellCompletionContext()?this.scheduleGhostUpdate():this.clearGhostSuggestion();return}if(r&&this.keybindingsRef.matches(n,"app.interrupt")){this.optionsRef.onExitBashMode();return}if(r&&this.keybindingsRef.matches(n,"app.clear")&&this.optionsRef.isShellRunning()){this.optionsRef.onInterrupt();return}if(r&&this.keybindingsRef.matches(n,"tui.editor.cursorUp")){this.navigateShellHistory(-1);return}if(r&&this.keybindingsRef.matches(n,"tui.editor.cursorDown")){this.navigateShellHistory(1);return}let a=this.optionsRef.editorBoundaryShortcuts??PN;if(!Vn(n)&&Un(n,a.start)){this.moveCursorToEditorBoundary("start");return}if(!Vn(n)&&Un(n,a.end)){this.moveCursorToEditorBoundary("end");return}if((r||o)&&this.keybindingsRef.matches(n,"tui.input.tab")){this.acceptGhostSuggestion();return}if((r||o)&&this.keybindingsRef.matches(n,"tui.editor.cursorRight")&&this.acceptGhostSuggestion())return;if(r&&this.keybindingsRef.matches(n,"tui.input.submit")&&!this.keybindingsRef.matches(n,"tui.input.newLine")){if(this.optionsRef.isShellRunning()){this.optionsRef.onNotify("Shell command already running","warning");return}let c=this.getExpandedText().trim();if(!c)return;this.clearGhostSuggestion(),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.optionsRef.onEditorSubmit?.(),this.optionsRef.onSubmitCommand(c),this.setText(""),this.refreshGhostSuggestion();return}super.handleInput(n)}if(!this.isShellCompletionContext()){this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.clearGhostSuggestion();return}(s||_N(n)||this.keybindingsRef.matches(n,"tui.editor.deleteCharBackward")||this.keybindingsRef.matches(n,"tui.editor.deleteCharForward")||this.keybindingsRef.matches(n,"tui.editor.deleteWordBackward")||this.keybindingsRef.matches(n,"tui.editor.deleteWordForward")||this.keybindingsRef.matches(n,"tui.editor.deleteToLineStart")||this.keybindingsRef.matches(n,"tui.editor.deleteToLineEnd")||this.keybindingsRef.matches(n,"tui.input.newLine")||this.keybindingsRef.matches(n,"tui.editor.cursorLeft")||this.keybindingsRef.matches(n,"tui.editor.cursorRight"))&&(this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.scheduleGhostUpdate())}render(n){let i=super.render(n);if(!this.isShellCompletionContext()||!this.ghost)return i;let s=this.getText();if(s.includes(`
|
|
460
|
+
`).map(i=>i.trim()).filter(Boolean)}catch{return[]}}function wN(t,e){let n=t.previousTokens;if(n[0]!=="git")return[];if(t.tokenIndex<=1)return fN.filter(r=>r.startsWith(t.token)).map(r=>({value:r,label:r,replacement:r,startCol:0,endCol:0,source:"git",score:52}));let i=n[1]??"";if(!["checkout","switch","merge","rebase","branch","show","diff"].includes(i))return[];let s=[...aM(["branch","--format=%(refname:short)"],e),...aM(["tag","--list"],e)];return[...new Set(s)].filter(r=>r.startsWith(t.token)).slice(0,100).map(r=>({value:r,label:r,replacement:r,startCol:0,endCol:0,source:"git",score:50}))}function SN(t){return t.cursorCol===t.line.length&&t.line.trim().length>0}function cM(t,e,n){return t.map(i=>({...i,startCol:e,endCol:n}))}function dM(t,e){return t.slice(0,e.startCol)+e.replacement+t.slice(e.endCol)}function CN(t){return lM(t.trim())[0]??""}function TN(t,e,n){for(let i of t){let s=i.trim();if(!(!s||!s.startsWith(e))&&CN(s)===n)return s}return null}function kN(t){let e=t.trim();return e?"cd".startsWith(e)?{value:"cd ..",source:"path"}:"git".startsWith(e)?{value:"git status",source:"git"}:null:null}function MN(t){let e=t.trim();return e.length>=2&&"git".startsWith(e)}function IN(t,e,n){if(e.length===0||n.length===0)return e;let i=new Map;for(let[s,r]of n.entries())i.set(r,Math.max(1,4-s));return e.map(s=>{let r=i.get(dM(t,s));return r?{...s,score:s.score+r}:s})}var tu=class{async getGhostSuggestion(e,n,i,s){let r=Xl(n);if(e.trim().length===0){let u=e,p=Er(r.map(m=>m.command),e,1);return p.length>0?{value:`${u}${p[0]}`,source:"project-history"}:null}let o=bN(e,e.length);if(!SN(o))return null;let a=Er(r.map(u=>u.command),e,10);if(a.length>0)return{value:a[0],source:"project-history"};if(o.tokenIndex===0)return this.getCommandPositionGhostSuggestion(e,Zl(i));let c=this.getDeterministicInlineSuggestions(o,n),l=Er(Zl(i),e,5),d=IN(e,oM(c),l);for(let u of d){let p=this.buildInlineSuggestionValue(e,u);if(p)return{value:p,source:u.source}}return null}getCommandPositionGhostSuggestion(e,n){if(MN(e)){let i=TN(n,e,"git");if(i)return{value:i,source:"global-history"}}return kN(e)}getDeterministicInlineSuggestions(e,n){let i=[];return i.push(...cM(wN(e,n),e.tokenStart,e.tokenEnd)),i.push(...cM(vN(e.token,n),e.tokenStart,e.tokenEnd)),oM(i)}buildInlineSuggestionValue(e,n){let i=dM(e,n);return!i.startsWith(e)||i===e?null:i}},Yp=class{getSuggestions(){return null}applyCompletion(e,n,i,s){if(!uM(s))throw new Error("Expected an extended completion item for bash autocomplete");return pM(e,n,s)}shouldTriggerFileCompletion(){return!1}};function pM(t,e,n){let i=t[e]||"",s=Math.max(0,Math.min(n.startCol,i.length)),r=Math.max(s,Math.min(n.endCol,i.length)),o=i.slice(0,s)+n.replacement+i.slice(r),a=[...t];return a[e]=o,{lines:a,cursorLine:e,cursorCol:s+n.replacement.length}}var Xp=class{getSuggestions(){return null}applyCompletion(e,n,i,s){if(!uM(s))throw new Error("Expected an extended completion item for one-off bash autocomplete");return pM(e,n,s)}shouldTriggerFileCompletion(e,n,i){let s=n===0?nu(e[0]||""):null;return s!==null&&i>=s.offset}},Zp=class{constructor(e,n,i,s){this.defaultProvider=e,this.bashProvider=n,this.oneOffBashProvider=i,this.isBashModeActive=s}getSuggestions(e,n,i,s){return this.isBashModeActive()?this.bashProvider.getSuggestions(e,n,i,s):eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?this.oneOffBashProvider.getSuggestions(e,n,i,s):this.defaultProvider?.getSuggestions(e,n,i,s)??null}applyCompletion(e,n,i,s,r){return this.isBashModeActive()?this.bashProvider.applyCompletion(e,n,i,s,r):eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?this.oneOffBashProvider.applyCompletion(e,n,i,s,r):this.defaultProvider?this.defaultProvider.applyCompletion(e,n,i,s,r):{lines:e,cursorLine:n,cursorCol:i}}shouldTriggerFileCompletion(e,n,i){return this.isBashModeActive()?eu(this.bashProvider)?this.bashProvider.shouldTriggerFileCompletion(e,n,i):!0:eu(this.oneOffBashProvider)&&this.oneOffBashProvider.shouldTriggerFileCompletion(e,n,i)?!0:!this.defaultProvider||!eu(this.defaultProvider)?!1:this.defaultProvider.shouldTriggerFileCompletion(e,n,i)}};import{fileURLToPath as RN}from"node:url";var mM=new Map([["super+up",/^\x1b\[(?:1;9(?::[12])?[AH]|574(?:19|23);9(?::[12])?u|7;9(?::[12])?~|27;9;65~)$/],["super+down",/^\x1b\[(?:1;9(?::[12])?[BF]|574(?:20|24);9(?::[12])?u|8;9(?::[12])?~|27;9;66~)$/],["super+home",/^\x1b\[(?:1;9(?::[12])?H|57423;9(?::[12])?u|7;9(?::[12])?~)$/],["super+end",/^\x1b\[(?:1;9(?::[12])?F|57424;9(?::[12])?u|8;9(?::[12])?~)$/],["super+pageup",/^\x1b\[(?:5;9(?::[12])?~|57421;9(?::[12])?u)$/],["super+pagedown",/^\x1b\[(?:6;9(?::[12])?~|57422;9(?::[12])?u)$/],["super+shift+up",/^\x1b\[(?:1;10(?::[12])?[AH]|574(?:19|23);10(?::[12])?u|7;10(?::[12])?~|27;10;65~)$/],["super+shift+down",/^\x1b\[(?:1;10(?::[12])?[BF]|574(?:20|24);10(?::[12])?u|8;10(?::[12])?~|27;10;66~)$/],["super+shift+home",/^\x1b\[(?:1;10(?::[12])?H|57423;10(?::[12])?u|7;10(?::[12])?~)$/],["super+shift+end",/^\x1b\[(?:1;10(?::[12])?F|57424;10(?::[12])?u|8;10(?::[12])?~)$/]]);function sb(t){return t.toLowerCase().split("+").slice(0,-1).includes("super")}function hM(t){return mM.has(t.toLowerCase())}function gM(t){switch(t.toLowerCase()){case"super+home":return"super+up";case"super+end":return"super+down";case"super+shift+home":return"super+shift+up";case"super+shift+end":return"super+shift+down";default:return t}}function Un(t,e){let n=e.toLowerCase();return sb(n)?mM.get(n)?.test(t)??!1:Ee(t,e)}var PN={start:"super+shift+up",end:"super+shift+down"};function _N(t){return t.length===1&&t.charCodeAt(0)>=32}function EN(t){return t==="\x1B[122;9u"||t==="\x1B[122;9:1u"||t==="\x1B[122;9:2u"||t==="\x1B[27;9;122~"}function AN(t){let e="\x1B[200~",n="\x1B[201~";if(t.indexOf(e)!==0)return null;let s=t.indexOf(n,e.length);return s===-1||s+n.length!==t.length?null:t.slice(e.length,s)}function ON(t){let e=t.split(/\r?\n|\s+/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"));if(e.length===0||e.some(n=>!n.startsWith("file://")))return null;try{return e.map(n=>RN(n)).join(" ")}catch{return null}}function LN(t){let n=AN(t)??t,i=ON(n);if(i)return i;let s=n.replace(/^[\r\n]+|[\r\n]+$/g,"");return s.length<=1||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(s)?null:/^(?:\/|~\/|\.\.?\/)/.test(s)&&!/[\r\n]/.test(s)?s:null}var em=class extends As{constructor(n,i,s,r){super(n,i,s);this.wrappedProviderInstalled=!1;this.shellHistoryIndex=-1;this.shellHistoryItems=[];this.shellHistoryDraft="";this.ghost=null;this.ghostAbort=null;this.ghostToken=0;this.keybindingsRef=s,this.optionsRef=r}installAutocompleteProvider(n){this.setAutocompleteProvider(n),this.wrappedProviderInstalled=!0}hasWrappedProvider(){return this.wrappedProviderInstalled}getGhostSuggestion(){return this.isShellCompletionContext()?this.ghost:null}refreshGhostSuggestion(){this.scheduleGhostUpdate()}clearGhostSuggestion(){this.ghostAbort?.abort(),this.ghostAbort=null,this.ghost=null}dismissBashModeUi(){this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.clearGhostSuggestion(),"cancelAutocomplete"in this&&typeof this.cancelAutocomplete=="function"&&this.cancelAutocomplete(),this.tui.requestRender()}handleInput(n){let i=LN(n);if(i!==null){this.insertTextAtCursor(i),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.isShellCompletionContext()?this.scheduleGhostUpdate():this.clearGhostSuggestion();return}let s=n.includes("\x1B[200~")||Reflect.get(this,"isInPaste")===!0;if(s){if(super.handleInput(n),Reflect.get(this,"isInPaste")===!0)return}else{let r=this.optionsRef.isBashModeActive(),o=!r&&this.isOneOffBashCommandContext();if(EN(n)){this.undo(),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.isShellCompletionContext()?this.scheduleGhostUpdate():this.clearGhostSuggestion();return}if(r&&this.keybindingsRef.matches(n,"app.interrupt")){this.optionsRef.onExitBashMode();return}if(r&&this.keybindingsRef.matches(n,"app.clear")&&this.optionsRef.isShellRunning()){this.optionsRef.onInterrupt();return}if(r&&this.keybindingsRef.matches(n,"tui.editor.cursorUp")){this.navigateShellHistory(-1);return}if(r&&this.keybindingsRef.matches(n,"tui.editor.cursorDown")){this.navigateShellHistory(1);return}let a=this.optionsRef.editorBoundaryShortcuts??PN;if(!Vn(n)&&Un(n,a.start)){this.moveCursorToEditorBoundary("start");return}if(!Vn(n)&&Un(n,a.end)){this.moveCursorToEditorBoundary("end");return}if((r||o)&&this.keybindingsRef.matches(n,"tui.input.tab")){this.acceptGhostSuggestion();return}if((r||o)&&this.keybindingsRef.matches(n,"tui.editor.cursorRight")&&this.acceptGhostSuggestion())return;if(r&&this.keybindingsRef.matches(n,"tui.input.submit")&&!this.keybindingsRef.matches(n,"tui.input.newLine")){if(this.optionsRef.isShellRunning()){this.optionsRef.onNotify("Shell command already running","warning");return}let c=this.getExpandedText().trim();if(!c)return;this.clearGhostSuggestion(),this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.optionsRef.onEditorSubmit?.(),this.optionsRef.onSubmitCommand(c),this.setText(""),this.refreshGhostSuggestion();return}super.handleInput(n)}if(!this.isShellCompletionContext()){this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.clearGhostSuggestion();return}(s||_N(n)||this.keybindingsRef.matches(n,"tui.editor.deleteCharBackward")||this.keybindingsRef.matches(n,"tui.editor.deleteCharForward")||this.keybindingsRef.matches(n,"tui.editor.deleteWordBackward")||this.keybindingsRef.matches(n,"tui.editor.deleteWordForward")||this.keybindingsRef.matches(n,"tui.editor.deleteToLineStart")||this.keybindingsRef.matches(n,"tui.editor.deleteToLineEnd")||this.keybindingsRef.matches(n,"tui.input.newLine")||this.keybindingsRef.matches(n,"tui.editor.cursorLeft")||this.keybindingsRef.matches(n,"tui.editor.cursorRight"))&&(this.shellHistoryIndex=-1,this.shellHistoryItems=[],this.shellHistoryDraft="",this.scheduleGhostUpdate())}render(n){let i=super.render(n);if(!this.isShellCompletionContext()||!this.ghost)return i;let s=this.getText();if(s.includes(`
|
|
461
461
|
`))return i;let r=this.getCursor();if(r.line!==0||r.col!==s.length||!this.ghost.value.startsWith(s)||this.ghost.value===s||i.length<3)return i;let o=this.ghost.value.slice(s.length),a=1,c="\x1B[7m \x1B[0m",l=Math.max(0,n-j(s)-1);if(l===0)return i;let d=X(o,l,"",!0);if(!d)return i;let u=" ".repeat(Math.max(0,n-j(s)-1-j(d))),p=`\x1B[38;5;244m${d}\x1B[0m`;return i[a]=`${s}${c}${p}${u}`,i}isShellCompletionContext(){return this.optionsRef.isBashModeActive()||this.isOneOffBashCommandContext()}isOneOffBashCommandContext(){return nu(this.getExpandedText())!==null}moveCursorToEditorBoundary(n){let i=Reflect.get(this,"state"),s=i&&typeof i=="object"?Reflect.get(i,"lines"):null;if(!Array.isArray(s))throw new Error("Editor cursor state is unavailable");if(n==="start")Reflect.set(i,"cursorLine",0),Reflect.set(i,"cursorCol",0);else{let r=Math.max(0,s.length-1);Reflect.set(i,"cursorLine",r),Reflect.set(i,"cursorCol",typeof s[r]=="string"?s[r].length:0)}Reflect.set(this,"lastAction",null),Reflect.set(this,"preferredVisualCol",null),Reflect.set(this,"snappedFromCursorCol",null),this.tui.requestRender()}acceptGhostSuggestion(){if(!this.ghost)return!1;let n=this.getExpandedText();if(n.includes(`
|
|
462
462
|
`))return!1;let i=this.getCursor();return i.line!==0||i.col!==n.length||!this.ghost.value.startsWith(n)||this.ghost.value===n?!1:(this.setText(this.ghost.value),this.clearGhostSuggestion(),!0)}navigateShellHistory(n){let i=this.shellHistoryDraft||this.getExpandedText();if(this.shellHistoryIndex===-1&&(this.shellHistoryDraft=i,this.shellHistoryItems=this.optionsRef.getHistoryEntries(i)),this.shellHistoryItems.length===0){this.optionsRef.onNotify("No shell history matches","info");return}if(n<0){this.shellHistoryIndex=Math.min(this.shellHistoryItems.length-1,this.shellHistoryIndex+1),this.setText(this.shellHistoryItems[this.shellHistoryIndex]??this.shellHistoryDraft),this.clearGhostSuggestion();return}if(this.shellHistoryIndex-=1,this.shellHistoryIndex<0){this.shellHistoryIndex=-1,this.setText(this.shellHistoryDraft),this.scheduleGhostUpdate();return}this.setText(this.shellHistoryItems[this.shellHistoryIndex]??this.shellHistoryDraft),this.clearGhostSuggestion()}scheduleGhostUpdate(){let n=this.getExpandedText(),i=++this.ghostToken;this.ghostAbort?.abort();let s=new AbortController;this.ghostAbort=s,this.optionsRef.resolveGhostSuggestion(n,s.signal).then(r=>{s.signal.aborted||i!==this.ghostToken||(this.ghost=r,this.tui.requestRender())}).catch(r=>{r instanceof Error&&r.message==="aborted"||console.debug("[powerline-footer] Failed to resolve bash ghost suggestion:",r)})}};import{mkdtempSync as WN,writeFileSync as UN}from"node:fs";import{tmpdir as FN}from"node:os";import{basename as DN,join as fM}from"node:path";import{spawn as $N}from"node:child_process";var iu="__PI_READY__",tm="__PI_CMD_START__",nm="__PI_CMD_DONE__";function BN(t){return t.replace(/\x1B\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\x1B\][^\u0007]*(?:\u0007|\x1b\\)/g,"").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")}function bM(t){return`'${t.replace(/'/g,`'"'"'`)}'`}function NN(t,e){return typeof t=="number"?t:e==="SIGINT"?130:e==="SIGTERM"?143:e==="SIGKILL"?137:1}function jN(t){return t.includes("fish")?`
|
|
463
463
|
function __pi_eval
|
|
@@ -501,32 +501,32 @@ print -r -- "${iu}:$PWD"
|
|
|
501
501
|
`,"utf8"),this.currentCommandId=n,this.state.running=!0,this.transcript.startCommand(n,e,this.state.cwd),this.onStateChange(),this.sendRaw(`__pi_eval ${bM(n)} ${bM(s)}
|
|
502
502
|
`)}interrupt(){if(!(!this.process||!this.state.running))try{process.kill(-this.process.pid,"SIGINT")}catch{this.process.kill("SIGINT")}}dispose(){if(this.disposed=!0,this.readyPromise=null,this.readyResolve=null,this.readyReject=null,!!this.process){try{process.kill(-this.process.pid,"SIGKILL")}catch{this.process.kill("SIGKILL")}this.process=null}}sendRaw(e){this.process&&this.process.stdin.write(e)}handleChunk(e){let n=BN(e).replace(/\r/g,"");if(!n)return;this.buffer+=n;let i=this.buffer.split(`
|
|
503
503
|
`);this.buffer=i.pop()??"";for(let s of i){let r=s.trimEnd();if(!this.state.ready){r.startsWith(`${iu}:`)&&(this.state.ready=!0,this.state.cwd=r.slice(iu.length+1)||this.state.cwd,this.readyResolve?.(),this.readyResolve=null,this.readyReject=null,this.onStateChange());continue}if(r.startsWith(`${tm}:`)){let[,o,a]=r.split(":");a&&(this.state.cwd=a),this.currentCommandId=o??this.currentCommandId,this.onStateChange();continue}if(r.startsWith(`${nm}:`)){let[,o,a,c]=r.split(":"),l=Number.parseInt(a??"1",10);if(this.state.running=!1,this.state.lastExitCode=Number.isFinite(l)?l:1,c&&(this.state.cwd=c),o){this.transcript.finishCommand(o,this.state.lastExitCode);let u=this.transcript.getSnapshot().commands.find(p=>p.id===o);u&&this.state.lastExitCode===0&&this.onCommandSuccess(u.command,this.state.cwd)}this.currentCommandId=null,this.onStateChange();continue}this.currentCommandId&&(this.transcript.appendOutput(this.currentCommandId,r),this.onStateChange())}}};import{existsSync as qN,readFileSync as GN}from"node:fs";import{join as KN,dirname as HN}from"node:path";import{fileURLToPath as zN}from"node:url";var ob={model:"#d787af",shellMode:"accent",path:"#00afaf",gitDirty:"warning",gitClean:"success",thinking:"thinkingOff",thinkingMinimal:"thinkingMinimal",thinkingLow:"thinkingLow",thinkingMedium:"thinkingMedium",context:"dim",contextWarn:"warning",contextError:"error",cost:"text",tokens:"muted",separator:"dim",border:"borderMuted"},xM=["#b281d6","#d787af","#febc38","#e4c00f","#89d281","#00afaf","#178fb9","#b281d6"],sm=null,yM=0,ic=null,rb=0,vM=5e3,rm=new Set;function wM(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function VN(t){if(!wM(t))return{};let e={};for(let[n,i]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(ob,n)||typeof i!="string")continue;let s=i.trim();s&&(e[n]=s)}return e}function JN(){let t=HN(zN(import.meta.url));return KN(t,"theme.json")}function ab(){let t=Date.now();if(ic&&t-rb<vM)return ic;let e=JN();try{if(qN(e)){let n=GN(e,"utf-8"),i=JSON.parse(n);return ic=wM(i)?i:{},rb=t,ic}}catch(n){console.debug(`[powerline-theme] Failed to load ${e}:`,n)}return ic={},rb=t,ic}function QN(){let t=Date.now();return sm&&t-yM<vM||(sm=VN(ab().colors),yM=t),sm}function YN(t,e){return QN()[t]??e?.[t]??ob[t]}function XN(t){return typeof t=="string"&&/^#[0-9a-fA-F]{6}$/.test(t)}function SM(t){let e=t.replace("#",""),n=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),s=parseInt(e.slice(4,6),16);return`\x1B[38;2;${n};${i};${s}m`}function sc(t,e,n){if(XN(e))return`${SM(e)}${n}\x1B[0m`;try{return t.fg(e,n)}catch(i){let s=String(e);return rm.has(s)||(rm.add(s),rm.size>200&&rm.clear(),console.debug(`[powerline-theme] Invalid theme color "${s}"; falling back to "text".`,i)),t.fg("text",n)}}function CM(t,e,n,i){let s=YN(e,i);return sc(t,s,n)}function TM(t){let e="",n=0;for(let i of t)i===" "||i===":"?e+=i:(e+=SM(xM[n%xM.length])+i,n++);return e+"\x1B[0m"}function om(){return{...ob}}var rc=om(),kM={...rc,model:"text",path:"text",gitClean:"dim"},ZN={...rc,model:"accent",path:"success",tokens:"muted",cost:"warning"},oc={default:{leftSegments:["model","thinking","shell_mode","path","git","context_pct","cache_read","cost"],rightSegments:[],secondarySegments:["extension_statuses"],separator:"powerline-thin",colors:rc,segmentOptions:{model:{showThinkingLevel:!1},path:{mode:"basename"},git:{showBranch:!0,showStaged:!0,showUnstaged:!0,showUntracked:!0}}},minimal:{leftSegments:["shell_mode","path","git"],rightSegments:["context_pct"],separator:"slash",colors:kM,segmentOptions:{path:{mode:"basename"},git:{showBranch:!0,showStaged:!1,showUnstaged:!1,showUntracked:!1}}},compact:{leftSegments:["model","shell_mode","git"],rightSegments:["cost","context_pct"],separator:"powerline-thin",colors:rc,segmentOptions:{model:{showThinkingLevel:!1},git:{showBranch:!0,showStaged:!0,showUnstaged:!0,showUntracked:!1}}},full:{leftSegments:["hostname","model","thinking","shell_mode","path","git","subagents"],rightSegments:["token_in","token_out","cache_read","cost","context_pct","time_spent","time","extension_statuses"],separator:"powerline",colors:rc,segmentOptions:{model:{showThinkingLevel:!1},path:{mode:"abbreviated",maxLength:50},git:{showBranch:!0,showStaged:!0,showUnstaged:!0,showUntracked:!0},time:{format:"24h",showSeconds:!1}}},nerd:{leftSegments:["hostname","model","thinking","shell_mode","path","git","session","subagents"],rightSegments:["token_in","token_out","cache_read","cache_write","cost","context_pct","context_total","time_spent","time","extension_statuses"],separator:"powerline",colors:ZN,segmentOptions:{model:{showThinkingLevel:!1},path:{mode:"abbreviated",maxLength:60},git:{showBranch:!0,showStaged:!0,showUnstaged:!0,showUntracked:!0},time:{format:"24h",showSeconds:!0}}},ascii:{leftSegments:["model","shell_mode","path","git"],rightSegments:["token_total","cost","context_pct"],separator:"ascii",colors:kM,segmentOptions:{model:{showThinkingLevel:!0},path:{mode:"abbreviated",maxLength:40},git:{showBranch:!0,showStaged:!0,showUnstaged:!0,showUntracked:!0}}},custom:{leftSegments:["model","shell_mode","path","git"],rightSegments:["token_total","cost","context_pct"],separator:"powerline-thin",colors:rc,segmentOptions:{}}};function cb(t){return oc[t]??oc.default}function su(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function MM(t,e){if(typeof t!="string")return null;let n=t.trim().toLowerCase();return e.includes(n)?n:null}function e6(t){if(typeof t!="string")return null;let e=t.trim();return e&&/^[a-zA-Z0-9_-]+$/.test(e)?e:null}function t6(t){return t==="left"||t==="right"||t==="secondary"?t:"right"}function n6(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function i6(t){if(typeof t!="string")return;let e=t.trim();return e||void 0}function IM(t,e){if(!su(t))return null;let n=e6(e??t.id);if(!n)return null;let i=typeof t.statusKey=="string"&&t.statusKey.trim()?t.statusKey.trim():n;return{id:n,statusKey:i,position:t6(t.position),color:n6(t.color),prefix:i6(t.prefix),hideWhenMissing:t.hideWhenMissing!==!1,excludeFromExtensionStatuses:t.excludeFromExtensionStatuses!==!1}}function s6(t){let e=[];if(Array.isArray(t))for(let i of t){let s=IM(i);s&&e.push(s)}else if(su(t))for(let[i,s]of Object.entries(t)){let r=IM(s,i);r&&e.push(r)}let n=new Map;for(let i of e)n.set(i.id,i);return[...n.values()]}function lb(t,e){let n={preset:"default",customItems:[],mouseScroll:!0,fixedEditor:!0},i=MM(t,e);return i?{...n,preset:i}:su(t)?{preset:MM(t.preset,e)??n.preset,customItems:s6(t.customItems),mouseScroll:t.mouseScroll!==!1,fixedEditor:t.fixedEditor!==!1}:n}function RM(t,e){let n=[...t.leftSegments],i=[...t.rightSegments],s=[...t.secondarySegments??[]];for(let r of e){let o=`custom:${r.id}`;r.position==="left"?n.push(o):r.position==="secondary"?s.push(o):i.push(o)}return{leftSegments:n,rightSegments:i,secondarySegments:s}}function PM(t,e){return su(t)?{...t,preset:e}:e}function _M(t,e,n){return su(t)?{...t,...e}:{preset:n,...e}}function ub(t){let e=new Set;for(let n of t)n.excludeFromExtensionStatuses&&e.add(n.statusKey);return e}function EM(t){return t.trimStart().startsWith("[")}function AM(t,e){let n=[];for(let[i,s]of t.entries())e.has(i)||!s||!EM(s)||n.push(s);return n}function db(t){if(!t||j(t)<=0)return null;let e=t.replace(/(\x1b\[[0-9;]*m|\s|·|[|])+$/,"");return j(e)>0?e:null}function OM(t){return EM(t)?null:db(t)}var ru=" \xB7 ",r6={minimal:"[min]",low:"[low]",medium:"[med]",high:"[high]",xhigh:"[xhi]"},o6={minimal:"\uF0E7 min",low:"\uF10C low",medium:"\uF192 med",high:"\uF111 high",xhigh:"\uF06D xhi"};function LM(t){return pb()?o6[t]:r6[t]}var WM={pi:"\uE22C",model:"\uEC19",folder:"\uF115",branch:"\uF126",git:"\uF1D3",tokens:"\uE26B",context:"\uE70F",cost:"\uF155",time:"\uF017",agents:"\uF0C0",cache:"\uF1C0",input:"\uF090",output:"\uF08B",host:"\uF109",session:"\uF550",auto:"\u{F0068}",warning:"\uF071"},a6={pi:"\u2B55\uFE0F",model:"\u{1F9E0}",folder:"\u{1F5C2}\uFE0F",branch:"\u2387",git:"\u2387",tokens:"\u229B",context:"\u25EB",cost:"$",time:"\u25F7",agents:"AG",cache:"cache",input:"in:",output:"out:",host:"host",session:"id",auto:"AC",warning:"!"};function c6(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={},n=Object.keys(WM);for(let i of n){let s=t[i];typeof s=="string"&&(e[i]=s)}return e}var l6={powerlineLeft:"\uE0B0",powerlineRight:"\uE0B2",powerlineThinLeft:"\uE0B1",powerlineThinRight:"\uE0B3",slash:"/",pipe:"|",block:"\u2588",space:" ",asciiLeft:">",asciiRight:"<",dot:"\xB7"},u6={powerlineLeft:">",powerlineRight:"<",powerlineThinLeft:"|",powerlineThinRight:"|",slash:"/",pipe:"|",block:"#",space:" ",asciiLeft:">",asciiRight:"<",dot:"."};function pb(){if(process.env.POWERLINE_NERD_FONTS==="1")return!0;if(process.env.POWERLINE_NERD_FONTS==="0")return!1;if(process.env.GHOSTTY_RESOURCES_DIR)return!0;let t=(process.env.TERM_PROGRAM||"").toLowerCase();return["iterm","wezterm","kitty","ghostty","alacritty"].some(n=>t.includes(n))}function Wt(){return{...pb()?WM:a6,...c6(ab().icons)}}function UM(){return pb()?l6:u6}function am(t){let e=UM();switch(t){case"powerline":return{left:e.powerlineLeft,right:e.powerlineRight,endCaps:{left:e.powerlineRight,right:e.powerlineLeft,useBgAsFg:!0}};case"powerline-thin":return{left:e.powerlineThinLeft,right:e.powerlineThinRight,endCaps:{left:e.powerlineRight,right:e.powerlineLeft,useBgAsFg:!0}};case"slash":return{left:` ${e.slash} `,right:` ${e.slash} `};case"pipe":return{left:` ${e.pipe} `,right:` ${e.pipe} `};case"block":return{left:e.block,right:e.block};case"none":return{left:e.space,right:e.space};case"ascii":return{left:e.asciiLeft,right:e.asciiRight};case"dot":return{left:e.dot,right:e.dot};case"chevron":return{left:"\u203A",right:"\u2039"};case"star":return{left:"\u2726",right:"\u2726"};default:return am("powerline-thin")}}import{hostname as d6}from"node:os";import{basename as FM}from"node:path";function mt(t,e,n){return CM(t.theme,e,n,t.colors)}function en(t,e){return t?`${t} ${e}`:e}function Ar(t){return t<1e3?t.toString():t<1e4?`${(t/1e3).toFixed(1)}k`:t<1e6?`${Math.round(t/1e3)}k`:t<1e7?`${(t/1e6).toFixed(1)}M`:`${Math.round(t/1e6)}M`}function p6(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),i=Math.floor(n/60);return i>0?`${i}h${n%60}m`:n>0?`${n}m${e%60}s`:`${e}s`}var m6={id:"model",render(t){let e=Wt(),n=t.options.model??{},i=t.model?.name||t.model?.id||"no-model";i.startsWith("Claude ")&&(i=i.slice(7));let s=en(e.model,i);if(n.showThinkingLevel!==!1&&t.model?.reasoning){let r=t.thinkingLevel||"off";if(r!=="off"){let o=LM(r);o&&(s+=`${ru}${o}`)}}return{content:mt(t,"model",s),visible:!0}}},h6={id:"shell_mode",render(t){if(!t.shellModeActive)return{content:"",visible:!1};let e=t.shellName??"shell",n=t.shellRunning?"run":"idle",i=t.shellCwd?FM(t.shellCwd):null,s=[e,n];return i&&s.push(i),{content:mt(t,"shellMode",s.join(ru)),visible:!0}}},g6={id:"path",render(t){let e=Wt(),n=t.options.path??{},i=n.mode??"basename",s=t.shellModeActive&&t.shellCwd?t.shellCwd:t.cwd??process.cwd(),r=process.env.HOME||process.env.USERPROFILE;if(i==="basename")s=FM(s)||s;else if(r&&s.startsWith(r)&&(s=`~${s.slice(r.length)}`),s.startsWith("/work/")&&(s=s.slice(6)),i==="abbreviated"){let a=n.maxLength??40;s.length>a&&(s=`\u2026${s.slice(-(a-1))}`)}let o=en(e.folder,s);return{content:mt(t,"path",o),visible:!0}}},f6={id:"git",render(t){let e=Wt(),n=t.options.git??{},{branch:i,staged:s,unstaged:r,untracked:o}=t.git,a=s>0||r>0||o>0?{staged:s,unstaged:r,untracked:o}:null;if(!i&&!a)return{content:"",visible:!1};let c=a&&(a.staged>0||a.unstaged>0||a.untracked>0),l=n.showBranch!==!1,d=c?"gitDirty":"gitClean",u="";if(l&&i&&(u=mt(t,d,en(e.branch,i))),a){let p=[];if(n.showUnstaged!==!1&&a.unstaged>0&&p.push(sc(t.theme,"warning",`*${a.unstaged}`)),n.showStaged!==!1&&a.staged>0&&p.push(sc(t.theme,"success",`+${a.staged}`)),n.showUntracked!==!1&&a.untracked>0&&p.push(sc(t.theme,"muted",`?${a.untracked}`)),p.length>0){let m=p.join(" ");!u&&l===!1?u=mt(t,d,e.git?`${e.git} `:"")+m:u+=u?` ${m}`:m}}return u?{content:u,visible:!0}:{content:"",visible:!1}}},b6={id:"thinking",render(t){let e=t.thinkingLevel||"off",s=`think:${{off:"off",minimal:"min",low:"low",medium:"med",high:"high",xhigh:"xhigh"}[e]||e}`;return e==="high"||e==="xhigh"?{content:TM(s),visible:!0}:e==="minimal"?{content:mt(t,"thinkingMinimal",s),visible:!0}:e==="low"?{content:mt(t,"thinkingLow",s),visible:!0}:e==="medium"?{content:mt(t,"thinkingMedium",s),visible:!0}:{content:mt(t,"thinking",s),visible:!0}}},x6={id:"subagents",render(){return{content:"",visible:!1}}},y6={id:"token_in",render(t){let e=Wt(),{input:n}=t.usageStats;if(!n)return{content:"",visible:!1};let i=en(e.input,Ar(n));return{content:mt(t,"tokens",i),visible:!0}}},v6={id:"token_out",render(t){let e=Wt(),{output:n}=t.usageStats;if(!n)return{content:"",visible:!1};let i=en(e.output,Ar(n));return{content:mt(t,"tokens",i),visible:!0}}},w6={id:"token_total",render(t){let e=Wt(),{input:n,output:i,cacheRead:s,cacheWrite:r}=t.usageStats,o=n+i+s+r;if(!o)return{content:"",visible:!1};let a=en(e.tokens,Ar(o));return{content:mt(t,"tokens",a),visible:!0}}},S6={id:"cost",render(t){let{cost:e}=t.usageStats,n=t.usingSubscription;if(!e&&!n)return{content:"",visible:!1};let i=n?"(sub)":`$${e.toFixed(2)}`;return{content:mt(t,"cost",i),visible:!0}}},C6={id:"context_pct",render(t){if(t.customCompactionEnabled)return{content:"",visible:!1};let e=Wt(),n=t.contextPercent,i=t.contextWindow,s=t.autoCompactEnabled&&e.auto?` ${e.auto}`:"",r=`${n.toFixed(1)}%/${Ar(i)}${s}`,o;return n>90?o=en(e.context,mt(t,"contextError",r)):n>70?o=en(e.context,mt(t,"contextWarn",r)):o=en(e.context,mt(t,"context",r)),{content:o,visible:!0}}},T6={id:"context_total",render(t){if(t.customCompactionEnabled)return{content:"",visible:!1};let e=Wt(),n=t.contextWindow;return n?{content:mt(t,"context",en(e.context,Ar(n))),visible:!0}:{content:"",visible:!1}}},k6={id:"time_spent",render(t){let e=Wt(),n=Date.now()-t.sessionStartTime;return n<1e3?{content:"",visible:!1}:{content:en(e.time,p6(n)),visible:!0}}},M6={id:"time",render(t){let e=Wt(),n=t.options.time??{},i=new Date,s=i.getHours(),r="";n.format==="12h"&&(r=s>=12?"pm":"am",s=s%12||12);let o=i.getMinutes().toString().padStart(2,"0"),a=`${s}:${o}`;return n.showSeconds&&(a+=`:${i.getSeconds().toString().padStart(2,"0")}`),a+=r,{content:en(e.time,a),visible:!0}}},I6={id:"session",render(t){let e=Wt(),i=t.sessionId?.slice(0,8)||"new";return{content:en(e.session,i),visible:!0}}},R6={id:"hostname",render(){let t=Wt(),e=d6().split(".")[0];return{content:en(t.host,e),visible:!0}}},P6={id:"cache_read",render(t){let e=Wt(),{cacheRead:n}=t.usageStats;if(!n)return{content:"",visible:!1};let s=[e.cache,e.input,Ar(n)].filter(Boolean).join(" ");return{content:mt(t,"tokens",s),visible:!0}}},_6={id:"cache_write",render(t){let e=Wt(),{cacheWrite:n}=t.usageStats;if(!n)return{content:"",visible:!1};let s=[e.cache,e.output,Ar(n)].filter(Boolean).join(" ");return{content:mt(t,"tokens",s),visible:!0}}},E6={id:"extension_statuses",render(t){let e=t.extensionStatuses;if(!e||e.size===0)return{content:"",visible:!1};let n=[];for(let[s,r]of e.entries()){if(t.hiddenExtensionStatusKeys.has(s))continue;let o=r?OM(r):null;o&&n.push(o)}return n.length===0?{content:"",visible:!1}:{content:n.join(` ${ru} `),visible:!0}}},A6={model:m6,shell_mode:h6,path:g6,git:f6,thinking:b6,subagents:x6,token_in:y6,token_out:v6,token_total:w6,cost:S6,context_pct:C6,context_total:T6,time_spent:k6,time:M6,session:I6,hostname:R6,cache_read:P6,cache_write:_6,extension_statuses:E6};function O6(t,e){let n=t.slice(7),i=e.customItemsById.get(n);if(!i)return{content:"",visible:!1};let s=e.extensionStatuses.get(i.statusKey),r=s?db(s):null;if(!r)return i.hideWhenMissing?{content:"",visible:!1}:{content:i.prefix??i.id,visible:!0};let o=r;return i.prefix&&(o=`${i.prefix}${ru}${o}`),i.color&&(o=sc(e.theme,i.color,o)),{content:o,visible:!0}}function DM(t,e){if(t.startsWith("custom:"))return O6(t,e);let n=A6[t];return n?n.render(e):{content:"",visible:!1}}import{spawn as L6}from"node:child_process";var W6=1e3,U6=500,Zn=null,Or=null,mb=null,hb=null,gb=0,fb=0;function F6(t){let e=0,n=0,i=0;for(let s of t.split(`
|
|
504
|
-
`)){if(!s)continue;let r=s[0],o=s[1];if(r==="?"&&o==="?"){i++;continue}r&&r!==" "&&r!=="?"&&e++,o&&o!==" "&&n++}return{staged:e,unstaged:n,untracked:i}}function bb(t,e=200){return new Promise(n=>{let i=L6("git",t,{stdio:["ignore","pipe","pipe"]}),s="",r=!1,o=c=>{r||(r=!0,clearTimeout(a),n(c))};i.stdout.on("data",c=>{s+=c.toString()}),i.on("close",c=>{o(c===0?s.trim():null)}),i.on("error",()=>{o(null)});let a=setTimeout(()=>{i.kill(),o(null)},e)})}async function D6(){let t=await bb(["branch","--show-current"]);if(t===null)return null;if(t)return t;let e=await bb(["rev-parse","--short","HEAD"]);return e?`${e} (detached)`:"detached"}async function $6(){let t=await bb(["status","--porcelain"],500);return t===null?null:F6(t)}function B6(t){let e=Date.now();if(Or&&e-Or.timestamp<U6)return Or.branch;if(!hb){let n=fb;hb=D6().then(i=>{n===fb&&(Or={branch:i,timestamp:Date.now()}),hb=null})}return Or?Or.branch:t}function $M(t){let e=Date.now(),n=B6(t);if(Zn&&e-Zn.timestamp<W6)return{branch:n,staged:Zn.staged,unstaged:Zn.unstaged,untracked:Zn.untracked};if(!mb){let i=gb;mb=$6().then(s=>{i===gb&&(Zn=s?{staged:s.staged,unstaged:s.unstaged,untracked:s.untracked,timestamp:Date.now()}:{staged:0,unstaged:0,untracked:0,timestamp:Date.now()}),mb=null})}return Zn?{branch:n,staged:Zn.staged,unstaged:Zn.unstaged,untracked:Zn.untracked}:{branch:n,staged:0,unstaged:0,untracked:0}}function cm(){Zn=null,gb++}function xb(){Or=null,fb++}var wn={getBgAnsi:(t,e,n)=>`\x1B[48;2;${t};${e};${n}m`,getFgAnsi:(t,e,n)=>`\x1B[38;2;${t};${e};${n}m`,getFgAnsi256:t=>`\x1B[38;5;${t}m`,reset:"\x1B[0m"};function N6(t){let e=t.replace("#","");return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}var j6={sep:244,model:"#d787af",path:"#00afaf",gitClean:"#5faf5f",accent:"#febc38"};function BM(t){let e=j6[t];if(e===void 0||e==="")return"";if(typeof e=="number")return wn.getFgAnsi256(e);if(typeof e=="string"&&e.startsWith("#")){let[n,i,s]=N6(e);return wn.getFgAnsi(n,i,s)}return""}function ei(t,e){let n=BM(t);return n?`${n}${e}`:e}function Lr(t){return BM(t)}import{readdirSync as dm,existsSync as bi,statSync as pm,readFileSync as q6}from"node:fs";import{join as $e,basename as vb}from"node:path";import{homedir as jM}from"node:os";var G6=[" xxxxxxxxxxxxxx "," xxxxxxxxxxxxxxxxxxxxx "," xxxxxxx;:+xxxxxxx+:;xxxxxxx "," xxxxxxxx .xxxxxxx. xxxxxxxx "," xxxxxxxxxxxxxx+;+xxxxxxxxxxxxxxx "," xxxxxxxxxxxxxxx+ +xxxxxxxxxxxxxxx "," xxxx..xxx+ xx+ +xx. +xxx:.xxxxx","xxxx; +xx+ .xxx xxx: +xx+ ;xxxx","xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx","xxxxxxxx+ ;xx; +xx+ +xxxxxxxx","xxxxxxxx+ ;xx+ ;xx; ;xxxxxxxx","xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx","xxxx; +xx+ .xxx xxx: +xx+ ;xxxx"," xxxx.:xxx+ xx+ xxx +xxx. xxxxx"," xxxxxxxxxxx+xxx+ +xxx+xxxxxxxxxxx "," xxxxxxxxxxxxxxx+:+xxxxxxxxxxxxxxx "," xxxxxxxx .xxxxxxx. xxxxxxxx "," xxxxxxx;:+xxxxxxx+:;xxxxxxx "," xxxxxxxxxxxxxxxxxxxxx "," xxxxxxxxxxxxxx "],yb=["\x1B[0;38;5;196;49m","\x1B[0;38;5;196;49m","\x1B[0;38;5;197;49m","\x1B[0;38;5;198;49m","\x1B[0;38;5;197;49m","\x1B[0;38;5;196;49m","\x1B[0;38;5;196;49m"];function mm(t){return`\x1B[1m${t}\x1B[22m`}function Ze(t){return Lr("sep")+t+wn.reset}function K6(t){let e=wn.reset,n="",i=0,s=Math.max(1,Math.floor(t.length/yb.length));for(let r=0;r<t.length;r++){r>0&&r%s===0&&i<yb.length-1&&i++;let o=t[r];o!==" "?n+=yb[i]+o+e:n+=o}return n}function lm(t,e){let n=j(t);if(n>e)return X(t,e,"\u2026");if(n===e)return t;let i=Math.floor((e-n)/2),s=e-n-i;return" ".repeat(i)+t+" ".repeat(s)}function NM(t,e){let n=j(t);return n>e?X(t,e,"\u2026"):t+" ".repeat(e-n)}function H6(t,e){let n=G6.map(i=>K6(i));return["",lm(mm("Welcome back!"),e),"",...n.map(i=>lm(i,e)),"",lm(ei("model",t.modelName),e),lm(Ze(t.providerName),e)]}function z6(t,e){let i=` ${Ze("\u2500".repeat(e-2))}`,s=[];if(t.recentSessions.length===0)s.push(` ${Ze("No recent sessions")}`);else for(let u of t.recentSessions.slice(0,3))s.push(` ${Ze("\u2022 ")}${ei("path",u.name)}${Ze(` (${u.timeAgo})`)}`);let r=[],{contextFiles:o,extensions:a,skills:c,promptTemplates:l}=t.loadedCounts,d=Ze("- ");return o>0||a>0||c>0||l>0?(o>0&&r.push(` ${d}${ei("gitClean",`${o}`)} context file${o!==1?"s":""}`),a>0&&r.push(` ${d}${ei("gitClean",`${a}`)} extension${a!==1?"s":""}`),c>0&&r.push(` ${d}${ei("gitClean",`${c}`)} skill${c!==1?"s":""}`),l>0&&r.push(` ${d}${ei("gitClean",`${l}`)} prompt template${l!==1?"s":""}`)):r.push(` ${Ze("No extensions loaded")}`),[` ${mm(ei("accent","Tips"))}`,` ${Ze("/")} for commands`,` ${Ze("!")} to run bash`,` ${Ze("Shift+Tab")} cycle thinking`,i,` ${mm(ei("accent","Loaded"))}`,...r,i,` ${mm(ei("accent","Recent sessions"))}`,...s,""]}function qM(t,e,n){if(e<58)return[];let o=Math.min(e,Math.max(76,Math.min(e-2,96))),a=40,c=Math.max(1,o-a-3),l="\u2500",d=Ze("\u2502"),u=Ze("\u2554"),p=Ze("\u2557"),m=Ze("\u255A"),g=Ze("\u255D"),h=H6(t,a),f=z6(t,c),x=[],y=" sling - Slingshot agent ",P=Ze(l.repeat(1))+ei("model",y),_=1+j(y),R=o-2-_,L=R>0?Ze(l.repeat(R)):"";x.push(u+P+L+p);let E=Math.max(h.length,f.length);for(let W=0;W<E;W++){let M=NM(h[W]??"",a),I=NM(f[W]??"",c);x.push(d+M+d+I+d)}return x.push(m+n+g),x}var hm=class{constructor(e,n,i=[],s={contextFiles:0,extensions:0,skills:0,promptTemplates:0}){this.countdown=10;this.data={modelName:e,providerName:n,recentSessions:i,loadedCounts:s}}setCountdown(e){this.countdown=e}invalidate(){}render(e){if(e<44)return[];let r=Math.min(e,Math.max(76,Math.min(e-2,96))),o=` Press any key to continue (${this.countdown}s) `,a=Ze(o),c=r-2,l=j(o),d=Math.floor((c-l)/2),u=c-l-d,p="\u2500",m=Ze(p.repeat(Math.max(0,d)))+a+Ze(p.repeat(Math.max(0,u)));return qM(this.data,e,m)}},gm=class{constructor(e,n,i=[],s={contextFiles:0,extensions:0,skills:0,promptTemplates:0}){this.data={modelName:e,providerName:n,recentSessions:i,loadedCounts:s}}invalidate(){}render(e){if(e<44)return[];let r=Math.min(e,Math.max(76,Math.min(e-2,96))),o="\u2500",a=26,c=Math.max(1,r-a-3),l=Ze(o.repeat(a))+Ze("\u2534")+Ze(o.repeat(c)),d=qM(this.data,e,l);return d.length>0&&d.push(""),d}},um=new Set;function Vi(t,e){let n=e instanceof Error?e.message:String(e),i=`${t}:${n}`;um.has(i)||(um.add(i),um.size>500&&um.clear(),console.debug(`[powerline-welcome] ${t}:`,e))}function wb(){let t=process.env.HOME||process.env.USERPROFILE||jM(),e=process.cwd(),n=0,i=0,s=0,r=0,o=[$e(t,".pi","agent","AGENTS.md"),$e(t,".claude","AGENTS.md"),$e(e,"AGENTS.md"),$e(e,".pi","AGENTS.md"),$e(e,".claude","AGENTS.md")];for(let h of o)bi(h)&&n++;let a=[$e(t,".pi","agent","extensions"),$e(e,"extensions"),$e(e,".pi","extensions")],c=new Set,l=[$e(t,".pi","agent","settings.json"),$e(e,".pi","settings.json")];for(let h of l)if(bi(h))try{let f=JSON.parse(q6(h,"utf-8")),x=null;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&(x=f.packages),Array.isArray(x))for(let y of x){let w=null,P=null;if(typeof y=="string"?w=y:typeof y=="object"&&y!==null&&!Array.isArray(y)&&(w=y.source,P=y.extensions),typeof w!="string")continue;let _=w.trim();if(!_.startsWith("npm:")||Array.isArray(P)&&P.length===0)continue;let R=_.slice(4),L=R.lastIndexOf("@"),E=L>0?R.slice(0,L):R;!E||c.has(E)||(c.add(E),i++)}}catch(f){Vi(`Failed to read settings at ${h}`,f)}for(let h of a)if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{if(pm(y).isDirectory())(bi($e(y,"index.ts"))||bi($e(y,"index.js"))||bi($e(y,"package.json")))&&(c.has(x)||(c.add(x),i++));else if((x.endsWith(".ts")||x.endsWith(".js"))&&!x.startsWith(".")){let P=x.endsWith(".ts")?".ts":".js",_=vb(x,P);c.has(_)||(c.add(_),i++)}}catch(w){Vi(`Failed to inspect extension entry ${y}`,w)}}}catch(f){Vi(`Failed to scan extensions dir ${h}`,f)}let d=[$e(t,".pi","agent","skills"),$e(e,".pi","skills"),$e(e,"skills")],u=new Set;for(let h of d)if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{pm(y).isDirectory()&&bi($e(y,"SKILL.md"))&&(u.has(x)||(u.add(x),s++))}catch(w){Vi(`Failed to inspect skill entry ${y}`,w)}}}catch(f){Vi(`Failed to scan skills dir ${h}`,f)}let p=[$e(t,".pi","agent","commands"),$e(t,".claude","commands"),$e(e,".pi","commands"),$e(e,".claude","commands")],m=new Set;function g(h){if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{if(pm(y).isDirectory())g(y);else if(x.endsWith(".md")){let P=vb(x,".md");m.has(P)||(m.add(P),r++)}}catch(w){Vi(`Failed to inspect prompt template entry ${y}`,w)}}}catch(f){Vi(`Failed to scan prompt template dir ${h}`,f)}}for(let h of p)g(h);return{contextFiles:n,extensions:i,skills:s,promptTemplates:r}}function Sb(t=3){let e=process.env.HOME||process.env.USERPROFILE||jM(),n=[$e(e,".pi","agent","sessions"),$e(e,".pi","sessions")],i=[];function s(c){if(bi(c))try{let l=dm(c);for(let d of l){let u=$e(c,d);try{let p=pm(u);if(p.isDirectory())s(u);else if(d.endsWith(".jsonl")){let m=vb(c),g=m;if(m.startsWith("--")){let h=m.split("-").filter(f=>f);g=h[h.length-1]||m}i.push({name:g,mtime:p.mtimeMs})}}catch(p){Vi(`Failed to inspect session entry ${u}`,p)}}}catch(l){Vi(`Failed to scan sessions dir ${c}`,l)}}for(let c of n)s(c);if(i.length===0)return[];i.sort((c,l)=>l.mtime-c.mtime);let r=new Set,o=[];for(let c of i)r.has(c.name)||(r.add(c.name),o.push(c));let a=Date.now();return o.slice(0,t).map(c=>({name:c.name.length>20?c.name.slice(0,17)+"\u2026":c.name,timeAgo:V6(a-c.mtime)}))}function V6(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),i=Math.floor(n/60),s=Math.floor(i/24);return s>0?`${s}d ago`:i>0?`${i}h ago`:n>0?`${n}m ago`:"just now"}function GM(t){let e=null;return{schedule(n){if(e)return;let i=t.getGeneration();e=setTimeout(()=>{e=null,!(!t.isEnabled()||i!==t.getGeneration())&&t.dismiss(n)},0)},cancel(){e&&(clearTimeout(e),e=null)}}}function KM(t,e){let n=null;return{schedule(i=e){n||(n=setTimeout(()=>{n=null,t()},i))},cancel(){n&&(clearTimeout(n),n=null)}}}function HM(t){return typeof t=="object"&&t!==null}function zM(t){if(!HM(t)||typeof t.getContextUsage!="function")return null;let e=t.getContextUsage();if(!HM(e))return null;let n=e.tokens,i=e.contextWindow;if(typeof n!="number"||!Number.isFinite(n)||typeof i!="number"||!Number.isFinite(i)||i<=0)return null;let s=e.percent;return{contextTokens:n,contextWindow:i,contextPercent:typeof s=="number"&&Number.isFinite(s)?s:n/i*100}}var Cb="\x1B_pi:c\x07";function ac(t,e){return!t||e<=0?[]:t.filter(n=>n!=null).map(n=>j(n)>e?X(n,e,"",!0):n)}function ou(t,e){return e<=0?[]:t.length<=e?t:t.slice(t.length-e)}function J6(t,e){if(e<=0)return[];if(t.length<=e)return t;let n=t.findIndex(r=>r.includes(Cb));if(n!==-1){let r=Math.max(0,Math.min(n-e+1,t.length-e));return t.slice(r,r+e)}let i=t.findIndex(r=>r.replace(/\x1b\[[0-9;]*m/g,"").trimStart().startsWith("\u2192 "));if(i===-1)return t.slice(0,e);let s=Math.max(0,Math.min(i-Math.floor(e/2),t.length-e));return t.slice(s,s+e)}function Q6(t){let e=null;return{lines:t.map((i,s)=>{let r=i.indexOf(Cb);return r===-1?i:(e||(e={row:s,col:j(i.slice(0,r))}),i.slice(0,r)+i.slice(r+Cb.length))}),cursor:e}}function VM(t){let e=Math.max(1,t.width),n=Math.max(1,t.terminalRows-1),i=ac(t.statusLines,e),s=ac(t.topLines,e),r=ac(t.editorLines,e),o=ac(t.secondaryLines,e),a=ac(t.transcriptLines,e),c=ac(t.lastPromptLines,e),l=J6(r,n),d=n-l.length,u=ou(s,d);d-=u.length;let p=ou(o,d);d-=p.length;let m=ou(c,d);d-=m.length;let g=ou(i,d);d-=g.length;let h=ou(a,d);return Q6([...g,...u,...l,...p,...h,...m])}var Y6=1200,X6=5e3,JM=100,Z6=500,nI={up:"super+up",down:"super+down"};function Fs(){return"\x1B[?2026h"}function Ds(){return"\x1B[?2026l"}function QM(t,e){return`\x1B[${t};${e}r`}function Ib(){return"\x1B[r"}function bm(t,e){return`\x1B[${t};${e}H`}function iI(){return"\x1B[2K"}function e8(){return"\x1B[?25l"}function t8(){return"\x1B[?25h"}function n8(){return"\x1B[?1049h"}function sI(){return"\x1B[?1049l"}function rI(){return"\x1B[?1007h"}function i8(){return"\x1B[?1007l"}function YM(){return"\x1B[?1002h\x1B[?1006h"}function Mb(){return"\x1B[?1006l\x1B[?1002l\x1B[?1000l"}function XM(t){return t==="kitty"?"\x1B[>7u":"\x1B[>4;2m"}function s8(t){return t==="kitty"?"\x1B[<u":"\x1B[>4;0m"}function oI(){return"\x1B[<999u\x1B[>4;0m"}function aI(){return Fs()+Ib()+Mb()+rI()+sI()+oI()+Ds()}function r8(t,e=nI){return Vn(t)?0:Un(t,e.up)||_e(t,"pageUp")||_e(t,"ctrl+shift+up")||/^\x1b\[(?:5;9(?::[12])?~|1;6(?::[12])?A|57421;9(?::[12])?u|57419;6(?::[12])?u)$/.test(t)?10:Un(t,e.down)||_e(t,"pageDown")||_e(t,"ctrl+shift+down")||/^\x1b\[(?:6;9(?::[12])?~|1;6(?::[12])?B|57422;9(?::[12])?u|57420;6(?::[12])?u)$/.test(t)?-10:0}function o8(t){let e=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,n=[],i=0;for(let s of t.matchAll(e)){if(s.index!==i)return null;i=s.index+s[0].length,n.push({code:Number(s[1]),col:Number(s[2]),row:Number(s[3]),final:s[4]})}return n.length>0&&i===t.length?n:null}function ym(t){return t&-61}function a8(t){if(t.final!=="M")return 0;let e=ym(t.code);return e===64?3:e===65?-3:0}function c8(t){return t.final==="M"&&ym(t.code)===0&&(t.code&32)===0}function ZM(t){return t.final==="M"&&ym(t.code)===0&&(t.code&32)!==0}function l8(t){return t.final==="M"&&ym(t.code)===2&&(t.code&32)===0}function u8(t){return t.final==="m"}function cI(t){return t.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g,"")}function Tb(t){return cI(t).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"")}var d8=new Intl.Segmenter(void 0,{granularity:"grapheme"});function fm(t,e,n){let i=0,s="";for(let{segment:r}of d8.segment(t)){let o=Math.max(0,j(r));i>=e&&i<n&&(s+=r),i+=o}return s}function eI(t,e){return t.line===e.line?t.col-e.col:t.line-e.line}function p8(t){let e=t;for(;e;){let n=Object.getOwnPropertyDescriptor(e,"rows");if(n)return n;e=Object.getPrototypeOf(e)}}function m8(t,e){if(e?.get){let i=e.get.call(t);return typeof i=="number"&&Number.isFinite(i)?i:24}let n=Reflect.get(t,"rows");return typeof n=="number"&&Number.isFinite(n)?n:24}function Rb(t,e){return j(t)>e?X(t,e,"",!0):t}function h8(t,e){return Rb(cI(t),e)}function tI(t){return t.includes(" ")?t.replace(/\t/g," "):t}function kb(t,e,n,i){if(t.lines.length===0)return"";let s=Math.max(1,e-t.lines.length+1),r=Ib();for(let o=0;o<t.lines.length;o++)r+=bm(s+o,1),r+=iI(),r+=Rb(t.lines[o]??"",n);return t.cursor&&i?(r+=bm(s+t.cursor.row,Math.max(1,t.cursor.col+1)),r+=t8()):r+=e8(),r}var xm=class{constructor(e){this.extendedKeyboardMode=null;this.originalCompositeLineAt=null;this.patchedRenders=[];this.removeInputListener=null;this.emergencyCleanup=null;this.mouseReportingResumeTimer=null;this.clipboardRestoreTimer=null;this.installed=!1;this.disposed=!1;this.writing=!1;this.renderPassActive=!1;this.renderPassCluster=null;this.renderingCluster=!1;this.renderingScrollableRoot=!1;this.checkingOverlay=!1;this.scrollOffset=0;this.maxScrollOffset=0;this.lastRootLineCount=0;this.rootLines=[];this.visibleRootStart=0;this.visibleScrollableRows=0;this.visibleRootLines=[];this.visibleClusterLines=[];this.selectionArea=null;this.selectionAnchor=null;this.selectionFocus=null;this.selectionDragging=!1;this.preserveSelectionFocusOnRelease=!1;this.lastLeftPress=null;this.tui=e.tui,this.terminal=e.terminal,this.renderCluster=e.renderCluster,this.getShowHardwareCursor=e.getShowHardwareCursor??(()=>!1),this.mouseScroll=e.mouseScroll!==!1,this.keyboardScrollShortcuts=e.keyboardScrollShortcuts??nI,this.onCopySelection=e.onCopySelection??null,this.rowsDescriptor=p8(e.terminal),this.originalWrite=e.terminal.write.bind(e.terminal),this.originalDoRender=typeof e.tui.doRender=="function"?e.tui.doRender.bind(e.tui):null,this.originalRender=typeof e.tui.render=="function"?e.tui.render.bind(e.tui):null}install(){if(!this.installed){if(typeof this.terminal.write!="function")throw new Error("[powerline-footer] Fixed editor compositor expected terminal.write(data) to exist");this.originalWrite(Fs()+n8()+this.enableAlternateScreenKeyboardMode()+i8()+(this.mouseScroll?YM():"")+Ds()),this.emergencyCleanup=()=>{this.disposed||this.restoreTerminalStateForExit()},process.once("exit",this.emergencyCleanup),Object.defineProperty(this.terminal,"rows",{configurable:!0,get:()=>this.getScrollableRows()}),this.originalRender&&(this.tui.render=e=>this.renderScrollableRoot(e)),typeof this.tui.addInputListener=="function"&&(this.removeInputListener=this.tui.addInputListener(e=>this.handleInput(e))),this.terminal.write=e=>this.write(e),this.originalDoRender&&(this.tui.doRender=()=>{this.renderPassActive=!0,this.renderPassCluster=null;try{this.originalDoRender?.(),this.requestRepaint()}finally{this.renderPassActive=!1,this.renderPassCluster=null}}),typeof this.tui.compositeLineAt=="function"&&(this.originalCompositeLineAt=this.tui.compositeLineAt.bind(this.tui),this.tui.compositeLineAt=(e,n,i,s,r)=>this.originalCompositeLineAt?.(tI(e),tI(n),i,s,r)??""),this.installed=!0}}hideRenderable(e){if(this.patchedRenders.some(i=>i.target===e))return;let n=e.render.bind(e);this.patchedRenders.push({target:e,originalRender:n}),e.render=()=>[]}renderHidden(e,n){return(this.patchedRenders.find(r=>r.target===e)?.originalRender??e.render.bind(e))(n)}jumpToPreviousRootTarget(e){return this.jumpToRootTarget(e,"previous")}jumpToNextRootTarget(e){return this.jumpToRootTarget(e,"next")}jumpToRootBottom(){return this.disposed||this.hasVisibleOverlay()||this.scrollOffset===0?!1:(this.clearSelection(),this.lastLeftPress=null,this.scrollOffset=0,this.requestRender(),!0)}jumpToRootTarget(e,n){if(this.disposed||e.length===0||this.hasVisibleOverlay())return!1;let i=this.visibleRootStart,s=n==="previous"?e.filter(r=>r<i).sort((r,o)=>o-r):e.filter(r=>r>i).sort((r,o)=>r-o);for(let r of s){let o=Math.max(0,Math.min(this.lastRootLineCount-Math.max(1,this.visibleScrollableRows)-r,this.maxScrollOffset));if(o!==this.scrollOffset)return this.clearSelection(),this.lastLeftPress=null,this.scrollOffset=o,this.requestRender(),!0}return!1}requestRepaint(){if(this.disposed||this.hasVisibleOverlay())return;let e=this.getRawRows(),n=Math.max(1,this.terminal.columns||80),i=this.getCluster(n,e);i.lines.length!==0&&this.originalWrite(Fs()+kb(this.decorateCluster(i),e,n,this.getShowHardwareCursor())+Ds())}dispose(e={}){if(!this.disposed){this.disposed=!0;for(let n of this.patchedRenders.splice(0))n.target.render=n.originalRender;this.removeInputListener?.(),this.removeInputListener=null,this.emergencyCleanup&&(process.removeListener("exit",this.emergencyCleanup),this.emergencyCleanup=null),this.mouseReportingResumeTimer&&(clearTimeout(this.mouseReportingResumeTimer),this.mouseReportingResumeTimer=null),this.clipboardRestoreTimer&&(clearTimeout(this.clipboardRestoreTimer),this.clipboardRestoreTimer=null),this.terminal.write=this.originalWrite,this.originalDoRender&&(this.tui.doRender=this.originalDoRender),this.originalRender&&(this.tui.render=this.originalRender),this.originalCompositeLineAt&&(this.tui.compositeLineAt=this.originalCompositeLineAt,this.originalCompositeLineAt=null),this.rowsDescriptor?Object.defineProperty(this.terminal,"rows",this.rowsDescriptor):Reflect.deleteProperty(this.terminal,"rows"),this.restoreTerminalState(e)}}getRawRows(){return Math.max(2,m8(this.terminal,this.rowsDescriptor))}getScrollableRows(){if(this.disposed||this.writing||this.renderingCluster||this.checkingOverlay||this.hasVisibleOverlay())return this.getRawRows();let e=this.getRawRows(),n=Math.max(1,this.terminal.columns||80),i=this.getCluster(n,e);return Math.max(1,e-i.lines.length)}renderScrollableRoot(e){if(!this.originalRender||this.disposed||this.renderingScrollableRoot)return this.originalRender?.(e)??[];if(this.hasVisibleOverlay())return this.originalRender(e).map(n=>h8(n,Math.max(1,e)));this.renderingScrollableRoot=!0;try{let n=this.refreshRootWindow(e);return this.visibleRootLines.map((i,s)=>this.renderSelectionHighlight(i,n+s,"root"))}finally{this.renderingScrollableRoot=!1}}refreshRootWindow(e){if(!this.originalRender)return this.updateVisibleRootWindow();let n=this.getRawRows(),i=Math.max(1,e),s=this.getCluster(i,n),r=Math.max(1,n-s.lines.length),o=this.originalRender(i);return this.rootLines=o,this.scrollOffset>0&&this.lastRootLineCount>0&&o.length>this.lastRootLineCount&&(this.scrollOffset+=o.length-this.lastRootLineCount),this.lastRootLineCount=o.length,this.maxScrollOffset=Math.max(0,o.length-r),this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,this.maxScrollOffset)),this.updateVisibleRootWindow(r)}handleInput(e){if(this.disposed||this.hasVisibleOverlay())return;let n=this.mouseScroll?o8(e):null;if(n){for(let s of n)this.handleMousePacket(s);return{consume:!0}}let i=r8(e,this.keyboardScrollShortcuts);if(i!==0)return this.scrollBy(i),{consume:!0}}handleMousePacket(e){let n=a8(e);if(n!==0){this.selectionDragging=!1,this.scrollBy(n);return}let i=this.selectionLocationForPacket(e);if(l8(e)){this.selectionDragging=!1,this.preserveSelectionFocusOnRelease=!1;let s=this.isLocationInsideSelection(i)?this.getSelectedText():"";if(s){this.onCopySelection?.(s),this.lastLeftPress=null,this.pauseMouseReportingForContextMenu(s);return}this.clearSelection(),this.lastLeftPress=null,this.pauseMouseReportingForContextMenu();return}if(!this.scrollSelectionAtViewportEdge(e)){if(this.selectionDragging&&u8(e)){this.finishSelection(e,i);return}if(i){if(c8(e)){this.startSelection(i);return}if(this.selectionDragging&&ZM(e)&&i.area===this.selectionArea){this.lastLeftPress=null,this.preserveSelectionFocusOnRelease=!1,this.selectionFocus=i.point,this.requestRender();return}}}}updateVisibleRootWindow(e=this.visibleScrollableRows){let n=Math.max(1,e),i=Math.max(0,this.rootLines.length-n-this.scrollOffset),s=this.rootLines.slice(i,i+n);for(;s.length<n;)s.push("");return this.visibleRootStart=i,this.visibleScrollableRows=n,this.visibleRootLines=s,i}finishSelection(e,n){this.preserveSelectionFocusOnRelease||(this.selectionFocus=n?.area===this.selectionArea?n.point:this.clampedSelectionPointForPacket(e,this.selectionArea)),this.preserveSelectionFocusOnRelease=!1,this.selectionDragging=!1;let i=this.getSelectedText();i?(this.lastLeftPress=null,this.onCopySelection?.(i)):this.clearSelection(),this.requestRender()}startSelection(e){let n=Date.now(),i=e.point.line;if(this.lastLeftPress&&this.lastLeftPress.area===e.area&&this.lastLeftPress.line===i&&n-this.lastLeftPress.at<=Z6){this.selectionArea=e.area,this.selectionAnchor={line:i,col:0},this.selectionFocus={line:i,col:this.selectionLineWidth(e.area,i)},this.selectionDragging=!0,this.preserveSelectionFocusOnRelease=!0,this.lastLeftPress=null,this.requestRender();return}this.selectionArea=e.area,this.selectionAnchor=e.point,this.selectionFocus=e.point,this.selectionDragging=!0,this.preserveSelectionFocusOnRelease=!1,this.lastLeftPress={area:e.area,line:i,at:n},this.requestRender()}selectionLocationForPacket(e){if(e.row<1)return null;let n=Math.max(0,e.col-1);if(e.row<=this.visibleScrollableRows)return{area:"root",point:{line:this.visibleRootStart+e.row-1,col:n}};let i=e.row-this.visibleScrollableRows-1;return i>=this.visibleClusterLines.length?null:{area:"cluster",point:{line:i,col:n}}}scrollSelectionAtViewportEdge(e){if(!this.selectionDragging||this.selectionArea!=="root"||!ZM(e))return!1;let n=e.row<=1?1:e.row>=this.visibleScrollableRows?-1:0;if(n===0)return!1;let i=Math.max(0,Math.min(this.scrollOffset+n,this.maxScrollOffset));if(i===this.scrollOffset)return!1;this.lastLeftPress=null,this.preserveSelectionFocusOnRelease=!0,this.scrollOffset=i;let s=this.updateVisibleRootWindow(),r=n>0?s:s+Math.max(0,this.visibleScrollableRows-1);return this.selectionFocus={line:r,col:Math.max(0,e.col-1)},this.requestRender(),!0}clampedSelectionPointForPacket(e,n){if(n==="cluster")return{line:Math.max(0,Math.min(e.row-this.visibleScrollableRows-1,this.visibleClusterLines.length-1)),col:Math.max(0,e.col-1)};let i=Math.max(1,Math.min(e.row,this.visibleScrollableRows));return{line:this.visibleRootStart+i-1,col:Math.max(0,e.col-1)}}renderSelectionHighlight(e,n,i){let s=this.getSelectionRangeForLine(n,i);if(!s)return e;let r=Tb(e),o=Math.max(0,Math.min(s.startCol,j(r))),a=Math.max(o,Math.min(s.endCol,j(r)));if(o===a)return e;let c=fm(r,0,o),l=fm(r,o,a),d=fm(r,a,Number.POSITIVE_INFINITY);return`${c}\x1B[7m${l}\x1B[27m${d}`}selectionLineWidth(e,n){let i=e==="root"?this.visibleRootLines:this.visibleClusterLines,s=e==="root"?this.visibleRootStart:0;return j(Tb(i[n-s]??""))}getSelectedText(){if(!this.selectionArea||!this.selectionAnchor||!this.selectionFocus)return"";let e=eI(this.selectionAnchor,this.selectionFocus)<=0?this.selectionAnchor:this.selectionFocus,n=e===this.selectionAnchor?this.selectionFocus:this.selectionAnchor;if(e.line===n.line&&e.col===n.col)return"";let i=this.selectionArea==="root"?this.rootLines:this.visibleClusterLines,s=[];for(let r=e.line;r<=n.line;r++){let o=Tb(i[r]??""),a=r===e.line?e.col:0,c=r===n.line?n.col:Number.POSITIVE_INFINITY;s.push(fm(o,a,c))}return s.join(`
|
|
504
|
+
`)){if(!s)continue;let r=s[0],o=s[1];if(r==="?"&&o==="?"){i++;continue}r&&r!==" "&&r!=="?"&&e++,o&&o!==" "&&n++}return{staged:e,unstaged:n,untracked:i}}function bb(t,e=200){return new Promise(n=>{let i=L6("git",t,{stdio:["ignore","pipe","pipe"]}),s="",r=!1,o=c=>{r||(r=!0,clearTimeout(a),n(c))};i.stdout.on("data",c=>{s+=c.toString()}),i.on("close",c=>{o(c===0?s.trim():null)}),i.on("error",()=>{o(null)});let a=setTimeout(()=>{i.kill(),o(null)},e)})}async function D6(){let t=await bb(["branch","--show-current"]);if(t===null)return null;if(t)return t;let e=await bb(["rev-parse","--short","HEAD"]);return e?`${e} (detached)`:"detached"}async function $6(){let t=await bb(["status","--porcelain"],500);return t===null?null:F6(t)}function B6(t){let e=Date.now();if(Or&&e-Or.timestamp<U6)return Or.branch;if(!hb){let n=fb;hb=D6().then(i=>{n===fb&&(Or={branch:i,timestamp:Date.now()}),hb=null})}return Or?Or.branch:t}function $M(t){let e=Date.now(),n=B6(t);if(Zn&&e-Zn.timestamp<W6)return{branch:n,staged:Zn.staged,unstaged:Zn.unstaged,untracked:Zn.untracked};if(!mb){let i=gb;mb=$6().then(s=>{i===gb&&(Zn=s?{staged:s.staged,unstaged:s.unstaged,untracked:s.untracked,timestamp:Date.now()}:{staged:0,unstaged:0,untracked:0,timestamp:Date.now()}),mb=null})}return Zn?{branch:n,staged:Zn.staged,unstaged:Zn.unstaged,untracked:Zn.untracked}:{branch:n,staged:0,unstaged:0,untracked:0}}function cm(){Zn=null,gb++}function xb(){Or=null,fb++}var wn={getBgAnsi:(t,e,n)=>`\x1B[48;2;${t};${e};${n}m`,getFgAnsi:(t,e,n)=>`\x1B[38;2;${t};${e};${n}m`,getFgAnsi256:t=>`\x1B[38;5;${t}m`,reset:"\x1B[0m"};function N6(t){let e=t.replace("#","");return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}var j6={sep:244,model:"#d787af",path:"#00afaf",gitClean:"#5faf5f",accent:"#febc38"};function BM(t){let e=j6[t];if(e===void 0||e==="")return"";if(typeof e=="number")return wn.getFgAnsi256(e);if(typeof e=="string"&&e.startsWith("#")){let[n,i,s]=N6(e);return wn.getFgAnsi(n,i,s)}return""}function ei(t,e){let n=BM(t);return n?`${n}${e}`:e}function Lr(t){return BM(t)}import{readdirSync as dm,existsSync as bi,statSync as pm,readFileSync as q6}from"node:fs";import{join as $e,basename as vb}from"node:path";import{homedir as jM}from"node:os";var G6=[" xxxxxxxxxxxxxx "," xxxxxxxxxxxxxxxxxxxxx "," xxxxxxx;:+xxxxxxx+:;xxxxxxx "," xxxxxxxx .xxxxxxx. xxxxxxxx "," xxxxxxxxxxxxxx+;+xxxxxxxxxxxxxxx "," xxxxxxxxxxxxxxx+ +xxxxxxxxxxxxxxx "," xxxx..xxx+ xx+ +xx. +xxx:.xxxxx","xxxx; +xx+ .xxx xxx: +xx+ ;xxxx","xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx","xxxxxxxx+ ;xx; +xx+ +xxxxxxxx","xxxxxxxx+ ;xx+ ;xx; ;xxxxxxxx","xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx","xxxx; +xx+ .xxx xxx: +xx+ ;xxxx"," xxxx.:xxx+ xx+ xxx +xxx. xxxxx"," xxxxxxxxxxx+xxx+ +xxx+xxxxxxxxxxx "," xxxxxxxxxxxxxxx+:+xxxxxxxxxxxxxxx "," xxxxxxxx .xxxxxxx. xxxxxxxx "," xxxxxxx;:+xxxxxxx+:;xxxxxxx "," xxxxxxxxxxxxxxxxxxxxx "," xxxxxxxxxxxxxx "],yb=["\x1B[0;38;5;196;49m","\x1B[0;38;5;196;49m","\x1B[0;38;5;197;49m","\x1B[0;38;5;198;49m","\x1B[0;38;5;197;49m","\x1B[0;38;5;196;49m","\x1B[0;38;5;196;49m"];function mm(t){return`\x1B[1m${t}\x1B[22m`}function Ze(t){return Lr("sep")+t+wn.reset}function K6(t){let e=wn.reset,n="",i=0,s=Math.max(1,Math.floor(t.length/yb.length));for(let r=0;r<t.length;r++){r>0&&r%s===0&&i<yb.length-1&&i++;let o=t[r];o!==" "?n+=yb[i]+o+e:n+=o}return n}function lm(t,e){let n=j(t);if(n>e)return X(t,e,"\u2026");if(n===e)return t;let i=Math.floor((e-n)/2),s=e-n-i;return" ".repeat(i)+t+" ".repeat(s)}function NM(t,e){let n=j(t);return n>e?X(t,e,"\u2026"):t+" ".repeat(e-n)}function H6(t,e){let n=G6.map(i=>K6(i));return["",lm(mm("Welcome back!"),e),"",...n.map(i=>lm(i,e)),"",lm(ei("model",t.modelName),e),lm(Ze(t.providerName),e)]}function z6(t,e){let i=` ${Ze("\u2500".repeat(e-2))}`,s=[];if(t.recentSessions.length===0)s.push(` ${Ze("No recent sessions")}`);else for(let u of t.recentSessions.slice(0,3))s.push(` ${Ze("\u2022 ")}${ei("path",u.name)}${Ze(` (${u.timeAgo})`)}`);let r=[],{contextFiles:o,extensions:a,skills:c,promptTemplates:l}=t.loadedCounts,d=Ze("- ");return o>0||a>0||c>0||l>0?(o>0&&r.push(` ${d}${ei("gitClean",`${o}`)} context file${o!==1?"s":""}`),a>0&&r.push(` ${d}${ei("gitClean",`${a}`)} extension${a!==1?"s":""}`),c>0&&r.push(` ${d}${ei("gitClean",`${c}`)} skill${c!==1?"s":""}`),l>0&&r.push(` ${d}${ei("gitClean",`${l}`)} prompt template${l!==1?"s":""}`)):r.push(` ${Ze("No extensions loaded")}`),[` ${mm(ei("accent","Tips"))}`,` ${Ze("/")} for commands`,` ${Ze("!")} to run bash`,` ${Ze("Shift+Tab")} cycle thinking`,i,` ${mm(ei("accent","Loaded"))}`,...r,i,` ${mm(ei("accent","Recent sessions"))}`,...s,""]}function qM(t,e,n){if(e<58)return[];let o=Math.min(e,Math.max(76,Math.min(e-2,96))),a=40,c=Math.max(1,o-a-3),l="\u2500",d=Ze("\u2502"),u=Ze("\u2554"),p=Ze("\u2557"),m=Ze("\u255A"),g=Ze("\u255D"),h=H6(t,a),f=z6(t,c),x=[],y=" sling - Slingshot agent ",P=Ze(l.repeat(1))+ei("model",y),_=1+j(y),R=o-2-_,L=R>0?Ze(l.repeat(R)):"";x.push(u+P+L+p);let E=Math.max(h.length,f.length);for(let W=0;W<E;W++){let M=NM(h[W]??"",a),I=NM(f[W]??"",c);x.push(d+M+d+I+d)}return x.push(m+n+g),x}var hm=class{constructor(e,n,i=[],s={contextFiles:0,extensions:0,skills:0,promptTemplates:0}){this.countdown=10;this.data={modelName:e,providerName:n,recentSessions:i,loadedCounts:s}}setCountdown(e){this.countdown=e}invalidate(){}render(e){if(e<44)return[];let r=Math.min(e,Math.max(76,Math.min(e-2,96))),o=` Press any key to continue (${this.countdown}s) `,a=Ze(o),c=r-2,l=j(o),d=Math.floor((c-l)/2),u=c-l-d,p="\u2500",m=Ze(p.repeat(Math.max(0,d)))+a+Ze(p.repeat(Math.max(0,u)));return qM(this.data,e,m)}},gm=class{constructor(e,n,i=[],s={contextFiles:0,extensions:0,skills:0,promptTemplates:0}){this.data={modelName:e,providerName:n,recentSessions:i,loadedCounts:s}}invalidate(){}render(e){if(e<44)return[];let r=Math.min(e,Math.max(76,Math.min(e-2,96))),o="\u2500",a=26,c=Math.max(1,r-a-3),l=Ze(o.repeat(a))+Ze("\u2534")+Ze(o.repeat(c)),d=qM(this.data,e,l);return d.length>0&&d.push(""),d}},um=new Set;function Vi(t,e){let n=e instanceof Error?e.message:String(e),i=`${t}:${n}`;um.has(i)||(um.add(i),um.size>500&&um.clear(),console.debug(`[powerline-welcome] ${t}:`,e))}function wb(){let t=process.env.HOME||process.env.USERPROFILE||jM(),e=process.cwd(),n=0,i=0,s=0,r=0,o=[$e(t,".pi","agent","AGENTS.md"),$e(t,".claude","AGENTS.md"),$e(e,"AGENTS.md"),$e(e,".pi","AGENTS.md"),$e(e,".claude","AGENTS.md")];for(let h of o)bi(h)&&n++;let a=[$e(t,".pi","agent","extensions"),$e(e,"extensions"),$e(e,".pi","extensions")],c=new Set,l=[$e(t,".pi","agent","settings.json"),$e(e,".pi","settings.json")];for(let h of l)if(bi(h))try{let f=JSON.parse(q6(h,"utf-8")),x=null;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&(x=f.packages),Array.isArray(x))for(let y of x){let w=null,P=null;if(typeof y=="string"?w=y:typeof y=="object"&&y!==null&&!Array.isArray(y)&&(w=y.source,P=y.extensions),typeof w!="string")continue;let _=w.trim();if(!_.startsWith("npm:")||Array.isArray(P)&&P.length===0)continue;let R=_.slice(4),L=R.lastIndexOf("@"),E=L>0?R.slice(0,L):R;!E||c.has(E)||(c.add(E),i++)}}catch(f){Vi(`Failed to read settings at ${h}`,f)}for(let h of a)if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{if(pm(y).isDirectory())(bi($e(y,"index.ts"))||bi($e(y,"index.js"))||bi($e(y,"package.json")))&&(c.has(x)||(c.add(x),i++));else if((x.endsWith(".ts")||x.endsWith(".js"))&&!x.startsWith(".")){let P=x.endsWith(".ts")?".ts":".js",_=vb(x,P);c.has(_)||(c.add(_),i++)}}catch(w){Vi(`Failed to inspect extension entry ${y}`,w)}}}catch(f){Vi(`Failed to scan extensions dir ${h}`,f)}let d=[$e(t,".pi","agent","skills"),$e(e,".pi","skills"),$e(e,"skills")],u=new Set;for(let h of d)if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{pm(y).isDirectory()&&bi($e(y,"SKILL.md"))&&(u.has(x)||(u.add(x),s++))}catch(w){Vi(`Failed to inspect skill entry ${y}`,w)}}}catch(f){Vi(`Failed to scan skills dir ${h}`,f)}let p=[$e(t,".pi","agent","commands"),$e(t,".claude","commands"),$e(e,".pi","commands"),$e(e,".claude","commands")],m=new Set;function g(h){if(bi(h))try{let f=dm(h);for(let x of f){let y=$e(h,x);try{if(pm(y).isDirectory())g(y);else if(x.endsWith(".md")){let P=vb(x,".md");m.has(P)||(m.add(P),r++)}}catch(w){Vi(`Failed to inspect prompt template entry ${y}`,w)}}}catch(f){Vi(`Failed to scan prompt template dir ${h}`,f)}}for(let h of p)g(h);return{contextFiles:n,extensions:i,skills:s,promptTemplates:r}}function Sb(t=3){let e=process.env.HOME||process.env.USERPROFILE||jM(),n=[$e(e,".pi","agent","sessions"),$e(e,".pi","sessions")],i=[];function s(c){if(bi(c))try{let l=dm(c);for(let d of l){let u=$e(c,d);try{let p=pm(u);if(p.isDirectory())s(u);else if(d.endsWith(".jsonl")){let m=vb(c),g=m;if(m.startsWith("--")){let h=m.split("-").filter(f=>f);g=h[h.length-1]||m}i.push({name:g,mtime:p.mtimeMs})}}catch(p){Vi(`Failed to inspect session entry ${u}`,p)}}}catch(l){Vi(`Failed to scan sessions dir ${c}`,l)}}for(let c of n)s(c);if(i.length===0)return[];i.sort((c,l)=>l.mtime-c.mtime);let r=new Set,o=[];for(let c of i)r.has(c.name)||(r.add(c.name),o.push(c));let a=Date.now();return o.slice(0,t).map(c=>({name:c.name.length>20?c.name.slice(0,17)+"\u2026":c.name,timeAgo:V6(a-c.mtime)}))}function V6(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),i=Math.floor(n/60),s=Math.floor(i/24);return s>0?`${s}d ago`:i>0?`${i}h ago`:n>0?`${n}m ago`:"just now"}function GM(t){let e=null;return{schedule(n){if(e)return;let i=t.getGeneration();e=setTimeout(()=>{e=null,!(!t.isEnabled()||i!==t.getGeneration())&&t.dismiss(n)},0)},cancel(){e&&(clearTimeout(e),e=null)}}}function KM(t,e){let n=null;return{schedule(i=e){n||(n=setTimeout(()=>{n=null,t()},i))},cancel(){n&&(clearTimeout(n),n=null)}}}function HM(t){return typeof t=="object"&&t!==null}function zM(t){if(!HM(t)||typeof t.getContextUsage!="function")return null;let e=t.getContextUsage();if(!HM(e))return null;let n=e.tokens,i=e.contextWindow;if(typeof n!="number"||!Number.isFinite(n)||typeof i!="number"||!Number.isFinite(i)||i<=0)return null;let s=e.percent;return{contextTokens:n,contextWindow:i,contextPercent:typeof s=="number"&&Number.isFinite(s)?s:n/i*100}}var Cb="\x1B_pi:c\x07";function ac(t,e){return!t||e<=0?[]:t.filter(n=>n!=null).map(n=>j(n)>e?X(n,e,"",!0):n)}function ou(t,e){return e<=0?[]:t.length<=e?t:t.slice(t.length-e)}function J6(t,e){if(e<=0)return[];if(t.length<=e)return t;let n=t.findIndex(r=>r.includes(Cb));if(n!==-1){let r=Math.max(0,Math.min(n-e+1,t.length-e));return t.slice(r,r+e)}let i=t.findIndex(r=>r.replace(/\x1b\[[0-9;]*m/g,"").trimStart().startsWith("\u2192 "));if(i===-1)return t.slice(0,e);let s=Math.max(0,Math.min(i-Math.floor(e/2),t.length-e));return t.slice(s,s+e)}function Q6(t){let e=null;return{lines:t.map((i,s)=>{let r=i.indexOf(Cb);return r===-1?i:(e||(e={row:s,col:j(i.slice(0,r))}),i.slice(0,r)+i.slice(r+Cb.length))}),cursor:e}}function VM(t){let e=Math.max(1,t.width),n=Math.max(1,t.terminalRows-1),i=ac(t.statusLines,e),s=ac(t.topLines,e),r=ac(t.editorLines,e),o=ac(t.secondaryLines,e),a=ac(t.transcriptLines,e),c=ac(t.lastPromptLines,e),l=J6(r,n),d=n-l.length,u=ou(s,d);d-=u.length;let p=ou(o,d);d-=p.length;let m=ou(c,d);d-=m.length;let g=ou(i,d);d-=g.length;let h=ou(a,d);return Q6([...g,...u,...l,...p,...h,...m])}var Y6=1200,X6=5e3,JM=100,Z6=500,nI={up:"super+up",down:"super+down"};function Fs(){return"\x1B[?2026h"}function Ds(){return"\x1B[?2026l"}function QM(t,e){return`\x1B[${t};${e}r`}function Ib(){return"\x1B[r"}function bm(t,e){return`\x1B[${t};${e}H`}function iI(){return"\x1B[2K"}function e8(){return"\x1B[?25l"}function t8(){return"\x1B[?25h"}function n8(){return"\x1B[?1049h"}function sI(){return"\x1B[?1049l"}function rI(){return"\x1B[?1007h"}function i8(){return"\x1B[?1007l"}function YM(){return"\x1B[?1002h\x1B[?1006h"}function Mb(){return"\x1B[?1006l\x1B[?1002l\x1B[?1000l"}function XM(t){return t==="kitty"?"\x1B[>7u":"\x1B[>4;2m"}function s8(t){return t==="kitty"?"\x1B[<u":"\x1B[>4;0m"}function oI(){return"\x1B[<999u\x1B[>4;0m"}function aI(){return Fs()+Ib()+Mb()+rI()+sI()+oI()+Ds()}function r8(t,e=nI){return Vn(t)?0:Un(t,e.up)||Ee(t,"pageUp")||Ee(t,"ctrl+shift+up")||/^\x1b\[(?:5;9(?::[12])?~|1;6(?::[12])?A|57421;9(?::[12])?u|57419;6(?::[12])?u)$/.test(t)?10:Un(t,e.down)||Ee(t,"pageDown")||Ee(t,"ctrl+shift+down")||/^\x1b\[(?:6;9(?::[12])?~|1;6(?::[12])?B|57422;9(?::[12])?u|57420;6(?::[12])?u)$/.test(t)?-10:0}function o8(t){let e=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,n=[],i=0;for(let s of t.matchAll(e)){if(s.index!==i)return null;i=s.index+s[0].length,n.push({code:Number(s[1]),col:Number(s[2]),row:Number(s[3]),final:s[4]})}return n.length>0&&i===t.length?n:null}function ym(t){return t&-61}function a8(t){if(t.final!=="M")return 0;let e=ym(t.code);return e===64?3:e===65?-3:0}function c8(t){return t.final==="M"&&ym(t.code)===0&&(t.code&32)===0}function ZM(t){return t.final==="M"&&ym(t.code)===0&&(t.code&32)!==0}function l8(t){return t.final==="M"&&ym(t.code)===2&&(t.code&32)===0}function u8(t){return t.final==="m"}function cI(t){return t.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g,"")}function Tb(t){return cI(t).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"")}var d8=new Intl.Segmenter(void 0,{granularity:"grapheme"});function fm(t,e,n){let i=0,s="";for(let{segment:r}of d8.segment(t)){let o=Math.max(0,j(r));i>=e&&i<n&&(s+=r),i+=o}return s}function eI(t,e){return t.line===e.line?t.col-e.col:t.line-e.line}function p8(t){let e=t;for(;e;){let n=Object.getOwnPropertyDescriptor(e,"rows");if(n)return n;e=Object.getPrototypeOf(e)}}function m8(t,e){if(e?.get){let i=e.get.call(t);return typeof i=="number"&&Number.isFinite(i)?i:24}let n=Reflect.get(t,"rows");return typeof n=="number"&&Number.isFinite(n)?n:24}function Rb(t,e){return j(t)>e?X(t,e,"",!0):t}function h8(t,e){return Rb(cI(t),e)}function tI(t){return t.includes(" ")?t.replace(/\t/g," "):t}function kb(t,e,n,i){if(t.lines.length===0)return"";let s=Math.max(1,e-t.lines.length+1),r=Ib();for(let o=0;o<t.lines.length;o++)r+=bm(s+o,1),r+=iI(),r+=Rb(t.lines[o]??"",n);return t.cursor&&i?(r+=bm(s+t.cursor.row,Math.max(1,t.cursor.col+1)),r+=t8()):r+=e8(),r}var xm=class{constructor(e){this.extendedKeyboardMode=null;this.originalCompositeLineAt=null;this.patchedRenders=[];this.removeInputListener=null;this.emergencyCleanup=null;this.mouseReportingResumeTimer=null;this.clipboardRestoreTimer=null;this.installed=!1;this.disposed=!1;this.writing=!1;this.renderPassActive=!1;this.renderPassCluster=null;this.renderingCluster=!1;this.renderingScrollableRoot=!1;this.checkingOverlay=!1;this.scrollOffset=0;this.maxScrollOffset=0;this.lastRootLineCount=0;this.rootLines=[];this.visibleRootStart=0;this.visibleScrollableRows=0;this.visibleRootLines=[];this.visibleClusterLines=[];this.selectionArea=null;this.selectionAnchor=null;this.selectionFocus=null;this.selectionDragging=!1;this.preserveSelectionFocusOnRelease=!1;this.lastLeftPress=null;this.tui=e.tui,this.terminal=e.terminal,this.renderCluster=e.renderCluster,this.getShowHardwareCursor=e.getShowHardwareCursor??(()=>!1),this.mouseScroll=e.mouseScroll!==!1,this.keyboardScrollShortcuts=e.keyboardScrollShortcuts??nI,this.onCopySelection=e.onCopySelection??null,this.rowsDescriptor=p8(e.terminal),this.originalWrite=e.terminal.write.bind(e.terminal),this.originalDoRender=typeof e.tui.doRender=="function"?e.tui.doRender.bind(e.tui):null,this.originalRender=typeof e.tui.render=="function"?e.tui.render.bind(e.tui):null}install(){if(!this.installed){if(typeof this.terminal.write!="function")throw new Error("[powerline-footer] Fixed editor compositor expected terminal.write(data) to exist");this.originalWrite(Fs()+n8()+this.enableAlternateScreenKeyboardMode()+i8()+(this.mouseScroll?YM():"")+Ds()),this.emergencyCleanup=()=>{this.disposed||this.restoreTerminalStateForExit()},process.once("exit",this.emergencyCleanup),Object.defineProperty(this.terminal,"rows",{configurable:!0,get:()=>this.getScrollableRows()}),this.originalRender&&(this.tui.render=e=>this.renderScrollableRoot(e)),typeof this.tui.addInputListener=="function"&&(this.removeInputListener=this.tui.addInputListener(e=>this.handleInput(e))),this.terminal.write=e=>this.write(e),this.originalDoRender&&(this.tui.doRender=()=>{this.renderPassActive=!0,this.renderPassCluster=null;try{this.originalDoRender?.(),this.requestRepaint()}finally{this.renderPassActive=!1,this.renderPassCluster=null}}),typeof this.tui.compositeLineAt=="function"&&(this.originalCompositeLineAt=this.tui.compositeLineAt.bind(this.tui),this.tui.compositeLineAt=(e,n,i,s,r)=>this.originalCompositeLineAt?.(tI(e),tI(n),i,s,r)??""),this.installed=!0}}hideRenderable(e){if(this.patchedRenders.some(i=>i.target===e))return;let n=e.render.bind(e);this.patchedRenders.push({target:e,originalRender:n}),e.render=()=>[]}renderHidden(e,n){return(this.patchedRenders.find(r=>r.target===e)?.originalRender??e.render.bind(e))(n)}jumpToPreviousRootTarget(e){return this.jumpToRootTarget(e,"previous")}jumpToNextRootTarget(e){return this.jumpToRootTarget(e,"next")}jumpToRootBottom(){return this.disposed||this.hasVisibleOverlay()||this.scrollOffset===0?!1:(this.clearSelection(),this.lastLeftPress=null,this.scrollOffset=0,this.requestRender(),!0)}jumpToRootTarget(e,n){if(this.disposed||e.length===0||this.hasVisibleOverlay())return!1;let i=this.visibleRootStart,s=n==="previous"?e.filter(r=>r<i).sort((r,o)=>o-r):e.filter(r=>r>i).sort((r,o)=>r-o);for(let r of s){let o=Math.max(0,Math.min(this.lastRootLineCount-Math.max(1,this.visibleScrollableRows)-r,this.maxScrollOffset));if(o!==this.scrollOffset)return this.clearSelection(),this.lastLeftPress=null,this.scrollOffset=o,this.requestRender(),!0}return!1}requestRepaint(){if(this.disposed||this.hasVisibleOverlay())return;let e=this.getRawRows(),n=Math.max(1,this.terminal.columns||80),i=this.getCluster(n,e);i.lines.length!==0&&this.originalWrite(Fs()+kb(this.decorateCluster(i),e,n,this.getShowHardwareCursor())+Ds())}dispose(e={}){if(!this.disposed){this.disposed=!0;for(let n of this.patchedRenders.splice(0))n.target.render=n.originalRender;this.removeInputListener?.(),this.removeInputListener=null,this.emergencyCleanup&&(process.removeListener("exit",this.emergencyCleanup),this.emergencyCleanup=null),this.mouseReportingResumeTimer&&(clearTimeout(this.mouseReportingResumeTimer),this.mouseReportingResumeTimer=null),this.clipboardRestoreTimer&&(clearTimeout(this.clipboardRestoreTimer),this.clipboardRestoreTimer=null),this.terminal.write=this.originalWrite,this.originalDoRender&&(this.tui.doRender=this.originalDoRender),this.originalRender&&(this.tui.render=this.originalRender),this.originalCompositeLineAt&&(this.tui.compositeLineAt=this.originalCompositeLineAt,this.originalCompositeLineAt=null),this.rowsDescriptor?Object.defineProperty(this.terminal,"rows",this.rowsDescriptor):Reflect.deleteProperty(this.terminal,"rows"),this.restoreTerminalState(e)}}getRawRows(){return Math.max(2,m8(this.terminal,this.rowsDescriptor))}getScrollableRows(){if(this.disposed||this.writing||this.renderingCluster||this.checkingOverlay||this.hasVisibleOverlay())return this.getRawRows();let e=this.getRawRows(),n=Math.max(1,this.terminal.columns||80),i=this.getCluster(n,e);return Math.max(1,e-i.lines.length)}renderScrollableRoot(e){if(!this.originalRender||this.disposed||this.renderingScrollableRoot)return this.originalRender?.(e)??[];if(this.hasVisibleOverlay())return this.originalRender(e).map(n=>h8(n,Math.max(1,e)));this.renderingScrollableRoot=!0;try{let n=this.refreshRootWindow(e);return this.visibleRootLines.map((i,s)=>this.renderSelectionHighlight(i,n+s,"root"))}finally{this.renderingScrollableRoot=!1}}refreshRootWindow(e){if(!this.originalRender)return this.updateVisibleRootWindow();let n=this.getRawRows(),i=Math.max(1,e),s=this.getCluster(i,n),r=Math.max(1,n-s.lines.length),o=this.originalRender(i);return this.rootLines=o,this.scrollOffset>0&&this.lastRootLineCount>0&&o.length>this.lastRootLineCount&&(this.scrollOffset+=o.length-this.lastRootLineCount),this.lastRootLineCount=o.length,this.maxScrollOffset=Math.max(0,o.length-r),this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,this.maxScrollOffset)),this.updateVisibleRootWindow(r)}handleInput(e){if(this.disposed||this.hasVisibleOverlay())return;let n=this.mouseScroll?o8(e):null;if(n){for(let s of n)this.handleMousePacket(s);return{consume:!0}}let i=r8(e,this.keyboardScrollShortcuts);if(i!==0)return this.scrollBy(i),{consume:!0}}handleMousePacket(e){let n=a8(e);if(n!==0){this.selectionDragging=!1,this.scrollBy(n);return}let i=this.selectionLocationForPacket(e);if(l8(e)){this.selectionDragging=!1,this.preserveSelectionFocusOnRelease=!1;let s=this.isLocationInsideSelection(i)?this.getSelectedText():"";if(s){this.onCopySelection?.(s),this.lastLeftPress=null,this.pauseMouseReportingForContextMenu(s);return}this.clearSelection(),this.lastLeftPress=null,this.pauseMouseReportingForContextMenu();return}if(!this.scrollSelectionAtViewportEdge(e)){if(this.selectionDragging&&u8(e)){this.finishSelection(e,i);return}if(i){if(c8(e)){this.startSelection(i);return}if(this.selectionDragging&&ZM(e)&&i.area===this.selectionArea){this.lastLeftPress=null,this.preserveSelectionFocusOnRelease=!1,this.selectionFocus=i.point,this.requestRender();return}}}}updateVisibleRootWindow(e=this.visibleScrollableRows){let n=Math.max(1,e),i=Math.max(0,this.rootLines.length-n-this.scrollOffset),s=this.rootLines.slice(i,i+n);for(;s.length<n;)s.push("");return this.visibleRootStart=i,this.visibleScrollableRows=n,this.visibleRootLines=s,i}finishSelection(e,n){this.preserveSelectionFocusOnRelease||(this.selectionFocus=n?.area===this.selectionArea?n.point:this.clampedSelectionPointForPacket(e,this.selectionArea)),this.preserveSelectionFocusOnRelease=!1,this.selectionDragging=!1;let i=this.getSelectedText();i?(this.lastLeftPress=null,this.onCopySelection?.(i)):this.clearSelection(),this.requestRender()}startSelection(e){let n=Date.now(),i=e.point.line;if(this.lastLeftPress&&this.lastLeftPress.area===e.area&&this.lastLeftPress.line===i&&n-this.lastLeftPress.at<=Z6){this.selectionArea=e.area,this.selectionAnchor={line:i,col:0},this.selectionFocus={line:i,col:this.selectionLineWidth(e.area,i)},this.selectionDragging=!0,this.preserveSelectionFocusOnRelease=!0,this.lastLeftPress=null,this.requestRender();return}this.selectionArea=e.area,this.selectionAnchor=e.point,this.selectionFocus=e.point,this.selectionDragging=!0,this.preserveSelectionFocusOnRelease=!1,this.lastLeftPress={area:e.area,line:i,at:n},this.requestRender()}selectionLocationForPacket(e){if(e.row<1)return null;let n=Math.max(0,e.col-1);if(e.row<=this.visibleScrollableRows)return{area:"root",point:{line:this.visibleRootStart+e.row-1,col:n}};let i=e.row-this.visibleScrollableRows-1;return i>=this.visibleClusterLines.length?null:{area:"cluster",point:{line:i,col:n}}}scrollSelectionAtViewportEdge(e){if(!this.selectionDragging||this.selectionArea!=="root"||!ZM(e))return!1;let n=e.row<=1?1:e.row>=this.visibleScrollableRows?-1:0;if(n===0)return!1;let i=Math.max(0,Math.min(this.scrollOffset+n,this.maxScrollOffset));if(i===this.scrollOffset)return!1;this.lastLeftPress=null,this.preserveSelectionFocusOnRelease=!0,this.scrollOffset=i;let s=this.updateVisibleRootWindow(),r=n>0?s:s+Math.max(0,this.visibleScrollableRows-1);return this.selectionFocus={line:r,col:Math.max(0,e.col-1)},this.requestRender(),!0}clampedSelectionPointForPacket(e,n){if(n==="cluster")return{line:Math.max(0,Math.min(e.row-this.visibleScrollableRows-1,this.visibleClusterLines.length-1)),col:Math.max(0,e.col-1)};let i=Math.max(1,Math.min(e.row,this.visibleScrollableRows));return{line:this.visibleRootStart+i-1,col:Math.max(0,e.col-1)}}renderSelectionHighlight(e,n,i){let s=this.getSelectionRangeForLine(n,i);if(!s)return e;let r=Tb(e),o=Math.max(0,Math.min(s.startCol,j(r))),a=Math.max(o,Math.min(s.endCol,j(r)));if(o===a)return e;let c=fm(r,0,o),l=fm(r,o,a),d=fm(r,a,Number.POSITIVE_INFINITY);return`${c}\x1B[7m${l}\x1B[27m${d}`}selectionLineWidth(e,n){let i=e==="root"?this.visibleRootLines:this.visibleClusterLines,s=e==="root"?this.visibleRootStart:0;return j(Tb(i[n-s]??""))}getSelectedText(){if(!this.selectionArea||!this.selectionAnchor||!this.selectionFocus)return"";let e=eI(this.selectionAnchor,this.selectionFocus)<=0?this.selectionAnchor:this.selectionFocus,n=e===this.selectionAnchor?this.selectionFocus:this.selectionAnchor;if(e.line===n.line&&e.col===n.col)return"";let i=this.selectionArea==="root"?this.rootLines:this.visibleClusterLines,s=[];for(let r=e.line;r<=n.line;r++){let o=Tb(i[r]??""),a=r===e.line?e.col:0,c=r===n.line?n.col:Number.POSITIVE_INFINITY;s.push(fm(o,a,c))}return s.join(`
|
|
505
505
|
`).replace(/[ \t]+$/gm,"").trimEnd()}getSelectionRangeForLine(e,n){if(this.selectionArea!==n||!this.selectionAnchor||!this.selectionFocus)return null;let i=eI(this.selectionAnchor,this.selectionFocus)<=0?this.selectionAnchor:this.selectionFocus,s=i===this.selectionAnchor?this.selectionFocus:this.selectionAnchor;return e<i.line||e>s.line?null:{startCol:e===i.line?i.col:0,endCol:e===s.line?s.col:Number.POSITIVE_INFINITY}}isLocationInsideSelection(e){if(!e||e.area!==this.selectionArea)return!1;let n=this.getSelectionRangeForLine(e.point.line,e.area);return!!(n&&e.point.col>=n.startCol&&e.point.col<n.endCol)}scrollBy(e){let n=Math.max(1,this.terminal.columns||80);this.refreshRootWindow(n);let i=Math.max(0,Math.min(this.scrollOffset+e,this.maxScrollOffset));i!==this.scrollOffset&&(this.clearSelection(),this.lastLeftPress=null,this.scrollOffset=i,this.repaintScrollableViewport(n),this.requestRender())}requestRender(){typeof this.tui.requestRender=="function"&&this.tui.requestRender()}repaintScrollableViewport(e){if(this.disposed||this.writing||this.hasVisibleOverlay())return;let n=this.getRawRows(),i=this.getCluster(e,n),s=Math.max(1,n-i.lines.length),r=this.updateVisibleRootWindow(s),o=Fs()+QM(1,s)+bm(1,1);for(let a=0;a<s;a++)a>0&&(o+=`\r
|
|
506
|
-
`),o+=iI(),o+=Rb(this.renderSelectionHighlight(this.visibleRootLines[a]??"",r+a,"root"),e);o+=kb(this.decorateCluster(i),n,e,this.getShowHardwareCursor()),o+=Ds(),this.originalWrite(o)}pauseMouseReportingForContextMenu(e=null){this.mouseReportingResumeTimer&&clearTimeout(this.mouseReportingResumeTimer),this.clipboardRestoreTimer&&(clearTimeout(this.clipboardRestoreTimer),this.clipboardRestoreTimer=null),this.originalWrite(Fs()+Mb()+Ds()),this.mouseReportingResumeTimer=setTimeout(()=>{this.mouseReportingResumeTimer=null,this.disposed||this.originalWrite(Fs()+YM()+Ds())},Y6),typeof this.mouseReportingResumeTimer=="object"&&"unref"in this.mouseReportingResumeTimer&&this.mouseReportingResumeTimer.unref();let n=this.onCopySelection;if(!e||!n)return;let i=Math.ceil(X6/JM),s=()=>{this.clipboardRestoreTimer=setTimeout(()=>{this.clipboardRestoreTimer=null,!this.disposed&&(i-=1,this.getSelectedText()===e&&(n(e),i>0&&s()))},JM),typeof this.clipboardRestoreTimer=="object"&&"unref"in this.clipboardRestoreTimer&&this.clipboardRestoreTimer.unref()};s()}clearSelection(){this.selectionArea=null,this.selectionAnchor=null,this.selectionFocus=null,this.selectionDragging=!1,this.preserveSelectionFocusOnRelease=!1}activeExtendedKeyboardMode(){return this.terminal.kittyProtocolActive===!0?"kitty":Reflect.get(this.terminal,"_modifyOtherKeysActive")===!0?"modifyOtherKeys":null}enableAlternateScreenKeyboardMode(){return this.extendedKeyboardMode=this.activeExtendedKeyboardMode(),this.extendedKeyboardMode?XM(this.extendedKeyboardMode):""}restoreTerminalState(e={}){let n=this.extendedKeyboardMode??this.activeExtendedKeyboardMode(),i=!e.resetExtendedKeyboardModes&&this.extendedKeyboardMode===null&&n!==null;this.originalWrite(Fs()+Ib()+(this.mouseScroll?Mb():"")+(n?s8(n):"")+rI()+sI()+(i&&n?XM(n):"")+(e.resetExtendedKeyboardModes?oI():"")+Ds())}restoreTerminalStateForExit(){try{this.restoreTerminalState({resetExtendedKeyboardModes:!0})}catch{}}write(e){if(this.disposed||this.writing||this.hasVisibleOverlay()){this.originalWrite(e);return}this.writing=!0;try{let n=this.getRawRows(),i=Math.max(1,this.terminal.columns||80),s=this.getCluster(i,n),r=s.lines.length;if(r===0||n<=2){this.originalWrite(e);return}let o=Math.max(1,n-r),a=typeof this.tui.hardwareCursorRow=="number"?this.tui.hardwareCursorRow:typeof this.tui.cursorRow=="number"?this.tui.cursorRow:0,c=typeof this.tui.previousViewportTop=="number"?this.tui.previousViewportTop:0,l=Math.max(1,Math.min(o,a-c+1)),d=Fs()+QM(1,o)+bm(l,1)+e+kb(this.decorateCluster(s),n,i,this.getShowHardwareCursor())+Ds();this.originalWrite(d)}finally{this.writing=!1}}getCluster(e,n){if(this.renderPassActive&&this.renderPassCluster?.width===e&&this.renderPassCluster.terminalRows===n)return this.renderPassCluster.cluster;let i=this.withClusterRender(()=>this.renderCluster(e,n));return this.visibleClusterLines=i.lines,this.renderPassActive&&(this.renderPassCluster={width:e,terminalRows:n,cluster:i}),i}decorateCluster(e){return this.selectionArea!=="cluster"?e:{...e,lines:e.lines.map((n,i)=>this.renderSelectionHighlight(n,i,"cluster"))}}withClusterRender(e){let n=this.renderingCluster;this.renderingCluster=!0;try{return e()}finally{this.renderingCluster=n}}hasVisibleOverlay(){if(this.checkingOverlay)return!1;this.checkingOverlay=!0;try{if(typeof this.tui.hasOverlay=="function"&&this.tui.hasOverlay())return!0;let e=Reflect.get(this.tui,"overlayStack");return Array.isArray(e)?e.some(n=>n&&n.hidden!==!0):!1}finally{this.checkingOverlay=!1}}};import{existsSync as dI,readFileSync as pI,writeFileSync as
|
|
506
|
+
`),o+=iI(),o+=Rb(this.renderSelectionHighlight(this.visibleRootLines[a]??"",r+a,"root"),e);o+=kb(this.decorateCluster(i),n,e,this.getShowHardwareCursor()),o+=Ds(),this.originalWrite(o)}pauseMouseReportingForContextMenu(e=null){this.mouseReportingResumeTimer&&clearTimeout(this.mouseReportingResumeTimer),this.clipboardRestoreTimer&&(clearTimeout(this.clipboardRestoreTimer),this.clipboardRestoreTimer=null),this.originalWrite(Fs()+Mb()+Ds()),this.mouseReportingResumeTimer=setTimeout(()=>{this.mouseReportingResumeTimer=null,this.disposed||this.originalWrite(Fs()+YM()+Ds())},Y6),typeof this.mouseReportingResumeTimer=="object"&&"unref"in this.mouseReportingResumeTimer&&this.mouseReportingResumeTimer.unref();let n=this.onCopySelection;if(!e||!n)return;let i=Math.ceil(X6/JM),s=()=>{this.clipboardRestoreTimer=setTimeout(()=>{this.clipboardRestoreTimer=null,!this.disposed&&(i-=1,this.getSelectedText()===e&&(n(e),i>0&&s()))},JM),typeof this.clipboardRestoreTimer=="object"&&"unref"in this.clipboardRestoreTimer&&this.clipboardRestoreTimer.unref()};s()}clearSelection(){this.selectionArea=null,this.selectionAnchor=null,this.selectionFocus=null,this.selectionDragging=!1,this.preserveSelectionFocusOnRelease=!1}activeExtendedKeyboardMode(){return this.terminal.kittyProtocolActive===!0?"kitty":Reflect.get(this.terminal,"_modifyOtherKeysActive")===!0?"modifyOtherKeys":null}enableAlternateScreenKeyboardMode(){return this.extendedKeyboardMode=this.activeExtendedKeyboardMode(),this.extendedKeyboardMode?XM(this.extendedKeyboardMode):""}restoreTerminalState(e={}){let n=this.extendedKeyboardMode??this.activeExtendedKeyboardMode(),i=!e.resetExtendedKeyboardModes&&this.extendedKeyboardMode===null&&n!==null;this.originalWrite(Fs()+Ib()+(this.mouseScroll?Mb():"")+(n?s8(n):"")+rI()+sI()+(i&&n?XM(n):"")+(e.resetExtendedKeyboardModes?oI():"")+Ds())}restoreTerminalStateForExit(){try{this.restoreTerminalState({resetExtendedKeyboardModes:!0})}catch{}}write(e){if(this.disposed||this.writing||this.hasVisibleOverlay()){this.originalWrite(e);return}this.writing=!0;try{let n=this.getRawRows(),i=Math.max(1,this.terminal.columns||80),s=this.getCluster(i,n),r=s.lines.length;if(r===0||n<=2){this.originalWrite(e);return}let o=Math.max(1,n-r),a=typeof this.tui.hardwareCursorRow=="number"?this.tui.hardwareCursorRow:typeof this.tui.cursorRow=="number"?this.tui.cursorRow:0,c=typeof this.tui.previousViewportTop=="number"?this.tui.previousViewportTop:0,l=Math.max(1,Math.min(o,a-c+1)),d=Fs()+QM(1,o)+bm(l,1)+e+kb(this.decorateCluster(s),n,i,this.getShowHardwareCursor())+Ds();this.originalWrite(d)}finally{this.writing=!1}}getCluster(e,n){if(this.renderPassActive&&this.renderPassCluster?.width===e&&this.renderPassCluster.terminalRows===n)return this.renderPassCluster.cluster;let i=this.withClusterRender(()=>this.renderCluster(e,n));return this.visibleClusterLines=i.lines,this.renderPassActive&&(this.renderPassCluster={width:e,terminalRows:n,cluster:i}),i}decorateCluster(e){return this.selectionArea!=="cluster"?e:{...e,lines:e.lines.map((n,i)=>this.renderSelectionHighlight(n,i,"cluster"))}}withClusterRender(e){let n=this.renderingCluster;this.renderingCluster=!0;try{return e()}finally{this.renderingCluster=n}}hasVisibleOverlay(){if(this.checkingOverlay)return!1;this.checkingOverlay=!0;try{if(typeof this.tui.hasOverlay=="function"&&this.tui.hasOverlay())return!0;let e=Reflect.get(this.tui,"overlayStack");return Array.isArray(e)?e.some(n=>n&&n.hidden!==!0):!1}finally{this.checkingOverlay=!1}}};import{existsSync as dI,readFileSync as pI,writeFileSync as SIe,mkdirSync as CIe}from"node:fs";import{join as Ob,dirname as kIe}from"node:path";import{homedir as mI}from"node:os";var g8="openai-codex/gpt-5.4-mini",f8=`Generate a 2-4 word "{theme}" themed loading message ending in "...".
|
|
507
507
|
|
|
508
508
|
Task: {task}
|
|
509
509
|
|
|
510
510
|
Be creative and unexpected. Avoid obvious/clich\xE9d phrases for this theme.
|
|
511
511
|
The message should hint at the task using theme vocabulary.
|
|
512
512
|
{exclude}
|
|
513
|
-
Output only the message, nothing else.`;var b8="You generate short themed loading messages and reply with the requested text only.",
|
|
514
|
-
`).map(i=>i.trim()).filter(i=>i.length>0&&i.endsWith("..."))}catch(n){return console.debug(`[working-vibes] Failed to load vibe file ${e}:`,n),[]}}function M8(t){return function(){let e=t+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function I8(t,e,n){if(t.length===0)return`${
|
|
515
|
-
`)[0].trim();return n=n.replace(/^["']|["']$/g,""),n.endsWith("...")||(n=n.replace(/\.+$/,"")+"..."),n.length>
|
|
513
|
+
Output only the message, nothing else.`;var b8="You generate short themed loading messages and reply with the requested text only.",We=hI(),cc=null,Eb=null,wm=!1,Ab=0,Pb=[],lI=null,uI=Date.now(),_b=0,x8=5,vm=[];function y8(){let t=process.env.HOME||process.env.USERPROFILE||mI();return Ob(t,".pi","agent","settings.json")}function v8(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function w8(){let t=y8();try{if(!dI(t))return{};let e=JSON.parse(pI(t,"utf-8"));return v8(e)?e:(console.debug(`[working-vibes] Ignoring non-object settings at ${t}`),{})}catch(e){return console.debug(`[working-vibes] Failed to load settings from ${t}:`,e),{}}}function hI(){let t=w8(),e=typeof t.workingVibe=="string"?t.workingVibe:null,n=e?.toLowerCase()==="off"?null:e,i=t.workingVibeMode,s=i==="file"||i==="generate"?i:"generate",r=typeof t.workingVibeRefreshInterval=="number"&&Number.isFinite(t.workingVibeRefreshInterval)?Math.max(0,t.workingVibeRefreshInterval):30,o=typeof t.workingVibeMaxLength=="number"&&Number.isFinite(t.workingVibeMaxLength)?Math.max(4,Math.floor(t.workingVibeMaxLength)):65;return{theme:n,mode:s,modelSpec:typeof t.workingVibeModel=="string"?t.workingVibeModel:g8,fallback:typeof t.workingVibeFallback=="string"?t.workingVibeFallback:"Working",timeout:3e3,refreshInterval:r*1e3,promptTemplate:typeof t.workingVibePrompt=="string"?t.workingVibePrompt:f8,maxLength:o}}function S8(){let t=process.env.HOME||process.env.USERPROFILE||mI();return Ob(t,".pi","agent","vibes")}function C8(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"")||"theme"}function T8(t){let e=`${C8(t)}.txt`;return Ob(S8(),e)}function k8(t){let e=T8(t);if(!dI(e))return[];try{return pI(e,"utf-8").split(`
|
|
514
|
+
`).map(i=>i.trim()).filter(i=>i.length>0&&i.endsWith("..."))}catch(n){return console.debug(`[working-vibes] Failed to load vibe file ${e}:`,n),[]}}function M8(t){return function(){let e=t+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function I8(t,e,n){if(t.length===0)return`${We.fallback}...`;let i=e%t.length,s=M8(n),r=Array.from({length:t.length},(o,a)=>a);for(let o=r.length-1;o>0;o--){let a=Math.floor(s()*(o+1));[r[o],r[a]]=[r[a],r[o]]}return t[r[i]]}function R8(){if(!We.theme)return`${We.fallback}...`;if(lI!==We.theme&&(Pb=k8(We.theme),lI=We.theme,uI=Date.now(),_b=0),Pb.length===0)return`${We.fallback}...`;let t=I8(Pb,_b,uI);return _b++,t}function P8(t){let e=t.userPrompt.slice(0,100),n=vm.length>0?`Don't use: ${vm.join(", ")}`:"";return We.promptTemplate.replace(/\{theme\}/g,t.theme).replace(/\{task\}/g,e).replace(/\{exclude\}/g,n)}function _8(t,e){if(!t)return`${e}...`;let n=t.trim().split(`
|
|
515
|
+
`)[0].trim();return n=n.replace(/^["']|["']$/g,""),n.endsWith("...")||(n=n.replace(/\.+$/,"")+"..."),n.length>We.maxLength&&(n=n.slice(0,We.maxLength-3)+"..."),!n||n==="..."?`${e}...`:n}function E8(t){return{systemPrompt:b8,messages:[{role:"user",content:[{type:"text",text:t}],timestamp:Date.now()}]}}async function A8(t,e){if(!cc)return`${We.fallback}...`;let n=We.modelSpec.indexOf("/");if(n===-1)return`${We.fallback}...`;let i=We.modelSpec.slice(0,n),s=We.modelSpec.slice(n+1);if(!i||!s)return`${We.fallback}...`;let r=cc.modelRegistry.find(i,s);if(!r)return console.debug(`[working-vibes] Model not found: ${We.modelSpec}`),`${We.fallback}...`;let o=await cc.modelRegistry.getApiKeyAndHeaders(r);if(!o.ok)return console.debug(`[working-vibes] Auth failed for ${i}: ${o.error}`),`${We.fallback}...`;let a=E8(P8(t)),c=await mC(r,a,{apiKey:o.apiKey,headers:o.headers,signal:e}),l=c.content.find(d=>d.type==="text");return!l?.text&&c.stopReason==="error"&&c.errorMessage&&console.debug(`[working-vibes] Vibe generation failed for ${We.modelSpec}: ${c.errorMessage}`),_8(l?.text||"",We.fallback)}function O8(t){t!==`${We.fallback}...`&&(vm=[t,...vm.filter(e=>e!==t)].slice(0,x8))}function L8(t){t(R8())}async function gI(t,e){if(We.mode==="file"){L8(e);return}let n=new AbortController;Eb?.abort(),Eb=n;let i=AbortSignal.timeout(We.timeout),s=AbortSignal.any([n.signal,i]);try{let r=await A8({theme:We.theme,userPrompt:t},s);wm&&!n.signal.aborted&&(O8(r),e(r))}catch(r){r instanceof Error&&r.name==="AbortError"?console.debug("[working-vibes] Generation aborted"):console.debug("[working-vibes] Generation failed:",r)}}function fI(t){cc=t,We=hI()}function bI(t,e){!We.theme||!cc||(e(`Channeling ${We.theme}...`),Ab=Date.now(),gI(t,e))}function xI(){wm=!0}function yI(t,e,n,i){if(!We.theme||!cc||!wm)return;let s=Date.now();if(s-Ab<We.refreshInterval)return;let r;i&&i.length>10?r=i.slice(0,150):(r=`using ${t} tool`,t==="read"&&e.path?r=`reading file: ${e.path}`:t==="write"&&e.path?r=`writing file: ${e.path}`:t==="edit"&&e.path?r=`editing file: ${e.path}`:t==="bash"&&e.command&&(r=`running command: ${String(e.command).slice(0,40)}`)),Ab=s,gI(r,n)}function vI(t){wm=!1,Eb?.abort(),t(void 0)}var qe={preset:"default",customItems:[],mouseScroll:!0,fixedEditor:!0},U8="compact-policy",wI=!1,Tm=12,F8=50,SI=72,Ub={stashHistory:"ctrl+alt+h",copyEditor:"ctrl+alt+c",cutEditor:"ctrl+alt+x",jumpPreviousUserMessage:"ctrl+shift+u",jumpNextUserMessage:"ctrl+shift+i",jumpPreviousLlmMessage:"ctrl+alt+,",jumpNextLlmMessage:"ctrl+alt+.",jumpChatBottom:"ctrl+shift+g",scrollChatUp:"super+up",scrollChatDown:"super+down",editorStart:"super+shift+up",editorEnd:"super+shift+down"},Lb={toggleShortcut:"ctrl+shift+b",transcriptMaxLines:2e3,transcriptMaxBytes:512*1024},CI=[{shortcutKey:"jumpPreviousUserMessage",description:"Jump to previous user message",action:{kind:"message",role:"user",direction:"previous"}},{shortcutKey:"jumpNextUserMessage",description:"Jump to next user message",action:{kind:"message",role:"user",direction:"next"}},{shortcutKey:"jumpPreviousLlmMessage",description:"Jump to previous LLM message",action:{kind:"message",role:"assistant",direction:"previous"}},{shortcutKey:"jumpNextLlmMessage",description:"Jump to next LLM message",action:{kind:"message",role:"assistant",direction:"next"}},{shortcutKey:"jumpChatBottom",description:"Jump chat to bottom",action:{kind:"bottom"}}],Fb=["stashHistory","copyEditor","cutEditor","jumpPreviousUserMessage","jumpNextUserMessage","jumpPreviousLlmMessage","jumpNextLlmMessage","jumpChatBottom","scrollChatUp","scrollChatDown","editorStart","editorEnd"],D8=["escape","ctrl+c","ctrl+d","ctrl+z","shift+tab","ctrl+p","shift+ctrl+p","ctrl+l","ctrl+o","shift+ctrl+o","ctrl+t","ctrl+n","ctrl+g","alt+enter","alt+up","alt+down","ctrl+v","alt+v","shift+l","shift+t","ctrl+s","ctrl+r","ctrl+backspace","ctrl+a","ctrl+x","ctrl+u"],$8=["alt+s"],BI=["ctrl","alt","super","shift"],B8=new Set(BI),N8=new Set(["escape","esc","enter","return","tab","space","backspace","delete","insert","clear","home","end","pageup","pagedown","up","down","left","right"]),NI=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","|","~","{","}",":","<",">","?"]),j8=100,q8=250,G8=1e3,K8=33,H8=250,Sm=150,TI=Symbol.for("powerlinePromptHistoryTracked"),kI=Symbol.for("powerlinePromptHistoryState");function Cm(t){return("totalTokens"in t&&typeof t.totalTokens=="number"?t.totalTokens:0)||t.input+t.output+t.cacheRead+t.cacheWrite}function z8(t){return!bt(t)||typeof t.input!="number"||typeof t.output!="number"||typeof t.cacheRead!="number"||typeof t.cacheWrite!="number"?!1:bt(t.cost)&&typeof t.cost.total=="number"}function Wb(t){return bt(t)&&t.role==="assistant"&&z8(t.usage)&&(t.stopReason===void 0||typeof t.stopReason=="string")}function V8(t){return bt(t)&&Array.isArray(t.savedPromptHistory)&&t.savedPromptHistory.every(e=>typeof e=="string")}function Db(){let t=Reflect.get(globalThis,kI);if(V8(t))return t;let e={savedPromptHistory:[]};return Reflect.set(globalThis,kI,e),e}function J8(t){let e=t?.history;if(!Array.isArray(e))return[];let n=[];for(let i of e){if(typeof i!="string")continue;let s=i.trim();if(s&&!(n.length>0&&n[n.length-1]===s)&&(n.push(s),n.length>=j8))break}return n}function cu(t){let e=J8(t);e.length>0&&(Db().savedPromptHistory=[...e])}function Q8(t){let{savedPromptHistory:e}=Db();if(!(!e.length||typeof t?.addToHistory!="function"))for(let n=e.length-1;n>=0;n--)t.addToHistory(e[n])}function Y8(t){if(!t||typeof t.addToHistory!="function")return;if(t[TI]){cu(t);return}let e=t.addToHistory.bind(t);t.addToHistory=n=>{e(n),cu(t)},t[TI]=!0,cu(t)}function jI(){let t=process.env.HOME||process.env.USERPROFILE||uu();return Ji(t,".pi","agent","settings.json")}function qI(t){return Ji(t,".pi","settings.json")}function X8(){let t=process.env.HOME||process.env.USERPROFILE||uu();return Ji(t,".pi","agent","compaction-policy.json")}function Z8(){let t=process.env.HOME||process.env.USERPROFILE||uu();return Ji(t,".pi","agent","extensions","pi-custom-compaction")}function GI(t,e){let n={...t};for(let[i,s]of Object.entries(e)){let r=n[i];n[i]=bt(r)&&bt(s)?GI(r,s):s}return n}function MI(t){try{if(!uc(t))return{};let e=JSON.parse(lu(t,"utf-8"));return bt(e)?e:(console.debug(`[sling-footer] Ignoring non-object settings at ${t}`),{})}catch(e){return console.debug(`[sling-footer] Failed to read settings from ${t}:`,e),{}}}function II(t){if(!uc(t))return{};try{let e=JSON.parse(lu(t,"utf-8"));return bt(e)?e:(console.debug(`[sling-footer] Refusing to write settings to non-object file at ${t}`),null)}catch(e){return console.debug(`[sling-footer] Failed to parse settings at ${t}:`,e),null}}function RI(t){if(uc(t))try{let e=JSON.parse(lu(t,"utf-8"));return!bt(e)||typeof e.enabled!="boolean"?!1:e.enabled}catch(e){return console.debug(`[sling-footer] Failed to read compaction policy from ${t}:`,e),!1}}function ej(t){if(!uc(Z8()))return!1;let e=RI(Ji(t,".pi","compaction-policy.json"));return e!==void 0?e:RI(X8())??!1}function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function KI(){let t=process.env.HOME||process.env.USERPROFILE||uu();return Ji(t,".sling","agent","sling-footer","stash-history.json")}function tj(){let t=process.env.HOME||process.env.USERPROFILE||uu();return Ji(t,".sling","agent","sling-footer","sessions")}function nj(t){let e=t.replace(/^[/\\]+|[/\\]+$/g,"").replace(/[\\/]+/g,"-");return Ji(tj(),`--${e}--`)}function ij(t){if(typeof t=="string")return t.replace(/\s+/g," ").trim();if(!Array.isArray(t))return"";let e=[];for(let n of t)!bt(n)||n.type!=="text"||typeof n.text!="string"||e.push(n.text);return e.join(`
|
|
516
516
|
`).replace(/\s+/g," ").trim()}function sj(t,e){let n=nj(t);if(!uc(n))return[];let i=[],s=W8(n).filter(a=>a.endsWith(".jsonl"));for(let a of s){let c=Ji(n,a),l=lu(c,"utf-8").split(`
|
|
517
517
|
`);for(let d=l.length-1;d>=0;d--){let u=l[d];if(!u||!u.includes('"type":"message"')||!u.includes('"role":"user"'))continue;let p;try{p=JSON.parse(u)}catch(h){let f=h instanceof Error?h.message:String(h);throw new Error(`Failed to parse session file ${c}: ${f}`,{cause:h})}if(!bt(p)||p.type!=="message"||!bt(p.message)||p.message.role!=="user")continue;let m=ij(p.message.content);if(!$s(m))continue;let g=typeof p.message.timestamp=="number"?p.message.timestamp:typeof p.timestamp=="string"?Date.parse(p.timestamp):0;i.push({text:m,timestamp:Number.isFinite(g)?g:0})}}i.sort((a,c)=>c.timestamp-a.timestamp);let r=[],o=new Set;for(let a of i)if(!o.has(a.text)&&(o.add(a.text),r.push(a.text),r.length>=e))return r;return r}function rj(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(typeof n=="string"&&$s(n)&&e[e.length-1]!==n&&(e.push(n),e.length>=Tm))break;return e}function PI(){let t=KI();try{if(!uc(t))return[];let e=JSON.parse(lu(t,"utf-8"));return bt(e)?rj(e.history):(console.debug(`[sling-footer] Ignoring invalid stash history at ${t}`),[])}catch(e){return console.debug(`[sling-footer] Failed to read stash history from ${t}:`,e),[]}}function oj(t){let e=KI(),n={version:1,history:t.slice(0,Tm)};try{DI($I(e),{recursive:!0}),FI(e,JSON.stringify(n,null,2)+`
|
|
518
518
|
`)}catch(i){console.debug(`[sling-footer] Failed to persist stash history to ${e}:`,i)}}function _I(t=process.cwd()){return GI(MI(jI()),MI(qI(t)))}function HI(t,e){let n=jI(),i=qI(t),s=II(n),r=II(i);if(s===null||r===null)return!1;let o=Object.prototype.hasOwnProperty.call(r,"powerline"),a=o?i:n,c=o?r:s;c.powerline=e(c.powerline);try{return DI($I(a),{recursive:!0}),FI(a,JSON.stringify(c,null,2)+`
|
|
519
|
-
`),!0}catch(l){return console.debug(`[sling-footer] Failed to persist powerline setting to ${a}:`,l),!1}}function aj(t,e=process.cwd()){return HI(e,n=>PM(n,t))}function EI(t,e,n){return HI(t,i=>_M(i,e,n))}var AI=Object.keys(oc);function cj(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(oc,t)}function lj(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return cj(e)?e:null}function $s(t){return t.trim().length>0}function au(t,e){return e?.getExpandedText?.()??t.ui.getEditorText()}function OI(t,e){let n=t.replace(/\s+/g," ").trim();return n?X(n,e,"\u2026"):"(empty)"}function uj(t,e){return!$s(e)||t[0]===e?!1:(t.unshift(e),t.length>Tm&&(t.length=Tm),!0)}function km(t){let e=t.trim().toLowerCase().split("+");if(e.length<=1)return e[0]??"";let n=new Map(BI.map((s,r)=>[s,r]));return[...e.slice(0,-1).sort((s,r)=>(n.get(s)??99)-(n.get(r)??99)),e[e.length-1]].join("+")}function zI(){let t=new Set([...$8,...D8].map(km));for(let e of Object.values(ia)){let n=e.defaultKeys,i=n===void 0?[]:Array.isArray(n)?n:[n];for(let s of i)t.add(km(s))}return t}function dj(t){let e=t.toLowerCase();return/^[a-z0-9]$/i.test(t)||/^f([1-9]|1[0-2])$/i.test(t)||N8.has(e)?!0:NI.has(t)}function VI(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/\s/.test(e))return null;let n=e.split("+");if(n.some(a=>a.length===0))return null;let i=n.slice(0,-1).map(a=>{let c=a.toLowerCase();return c==="cmd"||c==="command"?"super":c});if(new Set(i).size!==i.length)return null;for(let a of i)if(!B8.has(a))return null;let s=n[n.length-1];if(!dj(s))return null;let r=NI.has(s)?s:s.toLowerCase(),o=km([...i,r].join("+"));return sb(o)&&!hM(o)?null:o}function lc(t){return gM(km(t))}function pj(t,e){let n=Ub[t];if(!e.has(lc(n)))return n;for(let i of Fb){let s=Ub[i];if(!e.has(lc(s)))return s}return null}function LI(t){let e={...Ub},n=t.powerlineShortcuts;if(bt(n))for(let s of Fb){let r=VI(n[s]);r&&(e[s]=r)}let i=new Set(Array.from(zI(),lc));for(let s of Fb){let r=e[s],o=lc(r);if(!i.has(o)){i.add(o);continue}let a=pj(s,i);if(!a){console.debug(`[sling-footer] Shortcut conflict for ${s}: "${r}" is already in use`);continue}console.debug(`[sling-footer] Shortcut conflict for ${s}: "${r}" replaced with "${a}"`),e[s]=a,i.add(lc(a))}return e}function WI(t){let e=bt(t.bashMode)?t.bashMode:{},n=VI(e.toggleShortcut),i=n&&!zI().has(lc(n))?n:Lb.toggleShortcut;n&&i!==n&&console.debug(`[sling-footer] Bash mode shortcut conflict: "${n}" replaced with "${i}"`);let s=typeof e.transcriptMaxLines=="number"&&Number.isFinite(e.transcriptMaxLines)?Math.max(100,Math.floor(e.transcriptMaxLines)):Lb.transcriptMaxLines,r=typeof e.transcriptMaxBytes=="number"&&Number.isFinite(e.transcriptMaxBytes)?Math.max(16*1024,Math.floor(e.transcriptMaxBytes)):Lb.transcriptMaxBytes;return{toggleShortcut:i,transcriptMaxLines:s,transcriptMaxBytes:r}}function mj(t,e){let n=DM(t,e);return!n.visible||!n.content?{content:"",width:0,visible:!1}:{content:n.content,width:j(n.content),visible:!0}}function UI(t,e){if(t.length===0)return"";let n=am(e.separator),i=Lr("sep"),s=n.left;return" "+t.join(` ${i}${s}${wn.reset} `)+wn.reset+" "}function hj(t,e,n){let i=am(e.separator),s=j(i.left)+2,r=RM(e,qe.customItems),o=[...r.leftSegments,...r.rightSegments],a=r.secondarySegments,c=[...o,...a],l=[];for(let x of c){let{content:y,width:w,visible:P}=mj(x,t);P&&l.push({content:y,width:w})}if(l.length===0)return{topContent:"",secondaryContent:""};let d=2,u=d,p=[],m=[],g=!1;for(let x of l){let y=x.width+(p.length>0?s:0);!g&&u+y<=n?(p.push(x.content),u+=y):(g=!0,m.push(x))}let h=d,f=[];for(let x of m){let y=x.width+(f.length>0?s:0);if(h+y<=n)f.push(x.content),h+=y;else break}return{topContent:UI(p,e),secondaryContent:UI(f,e)}}function $b(t){let e=_I();qe=lb(e.powerline,AI);let n=LI(e),i=WI(e),s=!0,r=Date.now(),o=0,a=null,c=null,l=null,d=null,u=null,p=!1,m=null,g=null,h=null,f=null,x=null,y=null,w=null,P=null,_=null,R=!1,L=!1,E="",W=!0,M=null,I=PI(),O=null,F=!1,N=new Ql(i),H=new tu,G=null,Z=0,de=null,Te=0,pe=!0,Ie=!1,tt=0,De=()=>process.env.SHELL||"/bin/sh",ri=()=>G?.state.cwd??a?.cwd??process.cwd(),jt=GM({dismiss:v=>Gu(v),getGeneration:()=>o,isEnabled:()=>s}),ne=KM(()=>{let v=Date.now()-tt;if(pe&&!Ie&&v<Sm){ne.schedule(Math.max(0,Sm-v));return}m?.requestRender()},K8),be=()=>{de=null,pe=!0},ye=v=>{pe=!0,ne.schedule(v)},nt=(v={})=>{if(pe=!0,v.deferDuringTyping!==!1&&Date.now()-tt<Sm){ne.schedule();return}Ie=!0,ne.cancel(),ne.schedule(0)},At=v=>{g?.(),g=null;let S=v;if(typeof S.setExtensionStatus!="function")return;let D=S.setExtensionStatus,q=S.clearExtensionStatuses,te=function(He,Ee){D.call(this,He,Ee),nt()};S.setExtensionStatus=te;let J=null;typeof q=="function"&&(J=function(){q.call(this),nt()},S.clearExtensionStatuses=J),g=()=>{S.setExtensionStatus===te&&(S.setExtensionStatus=D),J&&S.clearExtensionStatuses===J&&(S.clearExtensionStatuses=q)}},Ii=v=>{let S=Er(Xl(a?.cwd??process.cwd()).map(q=>q.command),v,50),D=Er(Zl(De()),v,50);return[...new Set([...S,...D])]},qt=async()=>(G||(G=new im(De(),a?.cwd??process.cwd(),N,ye,(v,S)=>rM(a?.cwd??process.cwd(),v,S))),await G.ensureReady(),G),Tn=async(v,S)=>{try{await(await qt()).runCommand(v),ye()}catch(D){let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to run shell command: ${q}`,"error")}},Ri=async(v,S)=>{if(v!==F){if(!v&&G?.state.running){S.ui.notify("Wait for the current shell command to finish before leaving bash mode","warning");return}if(v){try{let D=await qt();F=!0,O?.dismissBashModeUi?.(),O?.refreshGhostSuggestion?.(),ye(),S.ui.notify(`Bash mode enabled (${D.state.shellName})`,"info")}catch(D){G?.dispose(),G=null,F=!1,ye();let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to start shell session: ${q}`,"error")}return}F=v,O?.dismissBashModeUi?.(),ye(),S.ui.notify("Bash mode disabled","info")}};function Lc(v){return{selectedPrefix:S=>v.fg("accent",S),selectedText:S=>v.fg("accent",S),description:S=>v.fg("muted",S),scrollInfo:S=>v.fg("dim",S),noMatch:S=>v.fg("warning",S)}}async function er(v,S,D,q,te){return v.ui.custom((J,Y,He,Ee)=>{let lt=new Qt(q,te,Lc(Y)),rt=ue=>Y.fg("dim",ue),kn=(ue,Re)=>`${rt("\u2502")}${X(ue,Re,"\u2026",!0)}${rt("\u2502")}`;return lt.onSelect=ue=>Ee(ue),lt.onCancel=()=>Ee(null),{render:ue=>{let Re=Math.max(1,ue-2),Ge=[];Ge.push(rt(`\u256D${"\u2500".repeat(Re)}\u256E`)),Ge.push(kn(Y.fg("accent",Y.bold(S)),Re)),Ge.push(rt(`\u251C${"\u2500".repeat(Re)}\u2524`));for(let It of lt.render(Re))Ge.push(kn(It,Re));return Ge.push(rt(`\u251C${"\u2500".repeat(Re)}\u2524`)),Ge.push(kn(Y.fg("dim",D),Re)),Ge.push(rt(`\u2570${"\u2500".repeat(Re)}\u256F`)),Ge},invalidate:()=>lt.invalidate(),handleInput:ue=>{lt.handleInput(ue),J.requestRender()}}},{overlay:!0,overlayOptions:()=>({verticalAlign:"center",horizontalAlign:"center"})})}t.on("session_start",async(v,S)=>{G?.dispose(),G=null,o++,r=Date.now(),a=S,wI=ej(S.cwd),E="",p=!1,u=null,M=null;let D=_I(S.cwd);i=WI(D),n=LI(D),W=D.showLastPrompt!==!1,qe=lb(D.powerline,AI),I=PI(),F=!1,N=new Ql(i),H=new tu,l=typeof S.getThinkingLevel=="function"?()=>S.getThinkingLevel():null,d=l?.()??null,S.hasUI&&S.ui.setStatus("stash",void 0),fI(S),s&&S.hasUI&&(zu(S),v.reason==="startup"?D.quietStartup===!0?fO(S):bO(S):Gu(S))}),t.on("session_shutdown",async()=>{o++,_?.(),_=null,R=!1,L=!1,jt.cancel(),ne.cancel(),g?.(),g=null,Hu({resetExtendedKeyboardModes:!0}),P?.(),P=null,G?.dispose(),G=null,F=!1,a=null,c=null,l=null,d=null,u=null,m=null,O=null,be()});let Wc=v=>[/\bgit\s+(checkout|switch|branch\s+-[dDmM]|merge|rebase|pull|reset|worktree)/,/\bgit\s+stash\s+(pop|apply)/].some(D=>D.test(v));t.on("tool_result",async v=>{if((v.toolName==="write"||v.toolName==="edit")&&cm(),v.toolName==="bash"&&v.input?.command){let S=String(v.input.command);Wc(S)&&(cm(),xb(),setTimeout(()=>ye(),100))}}),t.on("user_bash",async v=>{Wc(v.command)&&(cm(),xb(),setTimeout(()=>ye(),100),setTimeout(()=>ye(),300),setTimeout(()=>ye(),500))}),t.on("model_select",async(v,S)=>{a=S,ye()}),t.on("thinking_level_select",async(v,S)=>{a=S,d=l?.()??(typeof v.level=="string"?v.level:null),nt({deferDuringTyping:!1})}),t.on("session_tree",async(v,S)=>{a=S,d=null,u=null,nt({deferDuringTyping:!1})}),t.on("before_agent_start",async(v,S)=>{E=v.prompt,S.hasUI&&bI(v.prompt,S.ui.setWorkingMessage)}),t.on("agent_start",async(v,S)=>{p=!0,u=null,xI(),Gu(S),a=S}),t.on("message_update",async(v,S)=>{Wb(v.message)&&v.message.stopReason!=="error"&&v.message.stopReason!=="aborted"&&Cm(v.message.usage)>0&&(u=v.message.usage,a=S,pe=!0,ne.schedule(H8))}),t.on("message_end",async(v,S)=>{a=S,Wb(v.message)&&(v.message.stopReason==="error"||v.message.stopReason==="aborted"?u=null:Cm(v.message.usage)>0&&(u=v.message.usage)),nt({deferDuringTyping:!1})}),t.on("turn_end",async(v,S)=>{a=S,nt({deferDuringTyping:!1})}),t.on("tool_call",async(v,S)=>{if(Gu(S),S.hasUI){let D=Hh(S);yI(v.toolName,v.input,S.ui.setWorkingMessage,D)}});function Hh(v){let S=v.sessionManager?.getBranch?.()??[];for(let D=S.length-1;D>=0;D--){let q=S[D];if(q.type==="message"&&q.message?.role==="assistant"){let te=q.message.content;if(!Array.isArray(te))continue;for(let J of te)if(J.type==="text"&&J.text){let Y=J.text.trim();if(Y.length>0)return Y.slice(0,200)}}}}function Gu(v){jt.cancel(),_?(_(),_=null):L=!0,R&&(R=!1,v.ui.setHeader(void 0))}function Uc(v){!_&&L&&!R||jt.schedule(v)}function tO(v){uj(I,v)&&oj(I)}function Ku(v,S,D){Ul(S),D&&v.ui.notify(D,"info")}function zh(v){let S=au(v,O);return $s(S)?S:(v.ui.notify("Editor is empty","info"),null)}async function nO(v){let S=[...I],D=S.map((J,Y)=>({value:String(Y),label:`#${Y+1} ${OI(J,SI)}`})),q=await er(v,"Stash history","\u2191\u2193 navigate \u2022 enter insert \u2022 esc cancel",D,Math.min(D.length,10));if(!q)return null;let te=Number.parseInt(q.value,10);return S[te]??null}async function iO(v,S){let D=S.map((J,Y)=>({value:String(Y),label:`#${Y+1} ${OI(J,SI)}`})),q=await er(v,"Recent project prompts","\u2191\u2193 navigate \u2022 enter insert \u2022 esc cancel",D,Math.min(D.length,10));if(!q)return null;let te=Number.parseInt(q.value,10);return S[te]??null}async function sO(v,S,D){let q=[];if(S>0&&q.push({value:"stash",label:"Stashed prompts",description:`${S} saved`}),D>0&&q.push({value:"project",label:"Recent project prompts",description:`${D} recent`}),q.length===0)return null;if(q.length===1)return q[0]?.value==="project"?"project":"stash";let te=await er(v,"Prompt history","\u2191\u2193 navigate \u2022 enter open \u2022 esc cancel",q,q.length);return te?te.value==="project"?"project":"stash":null}async function rO(v,S){let D=au(v,O);if(!$s(D)){v.ui.setEditorText(S),v.ui.notify("Inserted prompt","info");return}let q=await v.ui.select("Insert prompt",["Replace","Append","Cancel"]);if(q==="Replace"){v.ui.setEditorText(S),v.ui.notify("Replaced editor with prompt","info");return}if(q==="Append"){let te=D.endsWith(`
|
|
519
|
+
`),!0}catch(l){return console.debug(`[sling-footer] Failed to persist powerline setting to ${a}:`,l),!1}}function aj(t,e=process.cwd()){return HI(e,n=>PM(n,t))}function EI(t,e,n){return HI(t,i=>_M(i,e,n))}var AI=Object.keys(oc);function cj(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(oc,t)}function lj(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return cj(e)?e:null}function $s(t){return t.trim().length>0}function au(t,e){return e?.getExpandedText?.()??t.ui.getEditorText()}function OI(t,e){let n=t.replace(/\s+/g," ").trim();return n?X(n,e,"\u2026"):"(empty)"}function uj(t,e){return!$s(e)||t[0]===e?!1:(t.unshift(e),t.length>Tm&&(t.length=Tm),!0)}function km(t){let e=t.trim().toLowerCase().split("+");if(e.length<=1)return e[0]??"";let n=new Map(BI.map((s,r)=>[s,r]));return[...e.slice(0,-1).sort((s,r)=>(n.get(s)??99)-(n.get(r)??99)),e[e.length-1]].join("+")}function zI(){let t=new Set([...$8,...D8].map(km));for(let e of Object.values(ia)){let n=e.defaultKeys,i=n===void 0?[]:Array.isArray(n)?n:[n];for(let s of i)t.add(km(s))}return t}function dj(t){let e=t.toLowerCase();return/^[a-z0-9]$/i.test(t)||/^f([1-9]|1[0-2])$/i.test(t)||N8.has(e)?!0:NI.has(t)}function VI(t){if(typeof t!="string")return null;let e=t.trim();if(!e||/\s/.test(e))return null;let n=e.split("+");if(n.some(a=>a.length===0))return null;let i=n.slice(0,-1).map(a=>{let c=a.toLowerCase();return c==="cmd"||c==="command"?"super":c});if(new Set(i).size!==i.length)return null;for(let a of i)if(!B8.has(a))return null;let s=n[n.length-1];if(!dj(s))return null;let r=NI.has(s)?s:s.toLowerCase(),o=km([...i,r].join("+"));return sb(o)&&!hM(o)?null:o}function lc(t){return gM(km(t))}function pj(t,e){let n=Ub[t];if(!e.has(lc(n)))return n;for(let i of Fb){let s=Ub[i];if(!e.has(lc(s)))return s}return null}function LI(t){let e={...Ub},n=t.powerlineShortcuts;if(bt(n))for(let s of Fb){let r=VI(n[s]);r&&(e[s]=r)}let i=new Set(Array.from(zI(),lc));for(let s of Fb){let r=e[s],o=lc(r);if(!i.has(o)){i.add(o);continue}let a=pj(s,i);if(!a){console.debug(`[sling-footer] Shortcut conflict for ${s}: "${r}" is already in use`);continue}console.debug(`[sling-footer] Shortcut conflict for ${s}: "${r}" replaced with "${a}"`),e[s]=a,i.add(lc(a))}return e}function WI(t){let e=bt(t.bashMode)?t.bashMode:{},n=VI(e.toggleShortcut),i=n&&!zI().has(lc(n))?n:Lb.toggleShortcut;n&&i!==n&&console.debug(`[sling-footer] Bash mode shortcut conflict: "${n}" replaced with "${i}"`);let s=typeof e.transcriptMaxLines=="number"&&Number.isFinite(e.transcriptMaxLines)?Math.max(100,Math.floor(e.transcriptMaxLines)):Lb.transcriptMaxLines,r=typeof e.transcriptMaxBytes=="number"&&Number.isFinite(e.transcriptMaxBytes)?Math.max(16*1024,Math.floor(e.transcriptMaxBytes)):Lb.transcriptMaxBytes;return{toggleShortcut:i,transcriptMaxLines:s,transcriptMaxBytes:r}}function mj(t,e){let n=DM(t,e);return!n.visible||!n.content?{content:"",width:0,visible:!1}:{content:n.content,width:j(n.content),visible:!0}}function UI(t,e){if(t.length===0)return"";let n=am(e.separator),i=Lr("sep"),s=n.left;return" "+t.join(` ${i}${s}${wn.reset} `)+wn.reset+" "}function hj(t,e,n){let i=am(e.separator),s=j(i.left)+2,r=RM(e,qe.customItems),o=[...r.leftSegments,...r.rightSegments],a=r.secondarySegments,c=[...o,...a],l=[];for(let x of c){let{content:y,width:w,visible:P}=mj(x,t);P&&l.push({content:y,width:w})}if(l.length===0)return{topContent:"",secondaryContent:""};let d=2,u=d,p=[],m=[],g=!1;for(let x of l){let y=x.width+(p.length>0?s:0);!g&&u+y<=n?(p.push(x.content),u+=y):(g=!0,m.push(x))}let h=d,f=[];for(let x of m){let y=x.width+(f.length>0?s:0);if(h+y<=n)f.push(x.content),h+=y;else break}return{topContent:UI(p,e),secondaryContent:UI(f,e)}}function $b(t){let e=_I();qe=lb(e.powerline,AI);let n=LI(e),i=WI(e),s=!0,r=Date.now(),o=0,a=null,c=null,l=null,d=null,u=null,p=!1,m=null,g=null,h=null,f=null,x=null,y=null,w=null,P=null,_=null,R=!1,L=!1,E="",W=!0,M=null,I=PI(),O=null,F=!1,N=new Ql(i),H=new tu,G=null,Z=0,de=null,Te=0,pe=!0,Ie=!1,tt=0,De=()=>process.env.SHELL||"/bin/sh",ri=()=>G?.state.cwd??a?.cwd??process.cwd(),jt=GM({dismiss:v=>Gu(v),getGeneration:()=>o,isEnabled:()=>s}),ne=KM(()=>{let v=Date.now()-tt;if(pe&&!Ie&&v<Sm){ne.schedule(Math.max(0,Sm-v));return}m?.requestRender()},K8),be=()=>{de=null,pe=!0},ye=v=>{pe=!0,ne.schedule(v)},nt=(v={})=>{if(pe=!0,v.deferDuringTyping!==!1&&Date.now()-tt<Sm){ne.schedule();return}Ie=!0,ne.cancel(),ne.schedule(0)},At=v=>{g?.(),g=null;let S=v;if(typeof S.setExtensionStatus!="function")return;let D=S.setExtensionStatus,q=S.clearExtensionStatuses,te=function(He,Ae){D.call(this,He,Ae),nt()};S.setExtensionStatus=te;let J=null;typeof q=="function"&&(J=function(){q.call(this),nt()},S.clearExtensionStatuses=J),g=()=>{S.setExtensionStatus===te&&(S.setExtensionStatus=D),J&&S.clearExtensionStatuses===J&&(S.clearExtensionStatuses=q)}},Ii=v=>{let S=Er(Xl(a?.cwd??process.cwd()).map(q=>q.command),v,50),D=Er(Zl(De()),v,50);return[...new Set([...S,...D])]},qt=async()=>(G||(G=new im(De(),a?.cwd??process.cwd(),N,ye,(v,S)=>rM(a?.cwd??process.cwd(),v,S))),await G.ensureReady(),G),Tn=async(v,S)=>{try{await(await qt()).runCommand(v),ye()}catch(D){let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to run shell command: ${q}`,"error")}},Ri=async(v,S)=>{if(v!==F){if(!v&&G?.state.running){S.ui.notify("Wait for the current shell command to finish before leaving bash mode","warning");return}if(v){try{let D=await qt();F=!0,O?.dismissBashModeUi?.(),O?.refreshGhostSuggestion?.(),ye(),S.ui.notify(`Bash mode enabled (${D.state.shellName})`,"info")}catch(D){G?.dispose(),G=null,F=!1,ye();let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to start shell session: ${q}`,"error")}return}F=v,O?.dismissBashModeUi?.(),ye(),S.ui.notify("Bash mode disabled","info")}};function Lc(v){return{selectedPrefix:S=>v.fg("accent",S),selectedText:S=>v.fg("accent",S),description:S=>v.fg("muted",S),scrollInfo:S=>v.fg("dim",S),noMatch:S=>v.fg("warning",S)}}async function er(v,S,D,q,te){return v.ui.custom((J,Y,He,Ae)=>{let lt=new Qt(q,te,Lc(Y)),rt=ue=>Y.fg("dim",ue),kn=(ue,Re)=>`${rt("\u2502")}${X(ue,Re,"\u2026",!0)}${rt("\u2502")}`;return lt.onSelect=ue=>Ae(ue),lt.onCancel=()=>Ae(null),{render:ue=>{let Re=Math.max(1,ue-2),Ge=[];Ge.push(rt(`\u256D${"\u2500".repeat(Re)}\u256E`)),Ge.push(kn(Y.fg("accent",Y.bold(S)),Re)),Ge.push(rt(`\u251C${"\u2500".repeat(Re)}\u2524`));for(let It of lt.render(Re))Ge.push(kn(It,Re));return Ge.push(rt(`\u251C${"\u2500".repeat(Re)}\u2524`)),Ge.push(kn(Y.fg("dim",D),Re)),Ge.push(rt(`\u2570${"\u2500".repeat(Re)}\u256F`)),Ge},invalidate:()=>lt.invalidate(),handleInput:ue=>{lt.handleInput(ue),J.requestRender()}}},{overlay:!0,overlayOptions:()=>({verticalAlign:"center",horizontalAlign:"center"})})}t.on("session_start",async(v,S)=>{G?.dispose(),G=null,o++,r=Date.now(),a=S,wI=ej(S.cwd),E="",p=!1,u=null,M=null;let D=_I(S.cwd);i=WI(D),n=LI(D),W=D.showLastPrompt!==!1,qe=lb(D.powerline,AI),I=PI(),F=!1,N=new Ql(i),H=new tu,l=typeof S.getThinkingLevel=="function"?()=>S.getThinkingLevel():null,d=l?.()??null,S.hasUI&&S.ui.setStatus("stash",void 0),fI(S),s&&S.hasUI&&(zu(S),v.reason==="startup"?D.quietStartup===!0?fO(S):bO(S):Gu(S))}),t.on("session_shutdown",async(v,S)=>{o++,_?.(),_=null,R=!1,L=!1,jt.cancel(),ne.cancel(),g?.(),g=null,Hu({resetExtendedKeyboardModes:S.hasUI}),P?.(),P=null,G?.dispose(),G=null,F=!1,a=null,c=null,l=null,d=null,u=null,m=null,O=null,be()});let Wc=v=>[/\bgit\s+(checkout|switch|branch\s+-[dDmM]|merge|rebase|pull|reset|worktree)/,/\bgit\s+stash\s+(pop|apply)/].some(D=>D.test(v));t.on("tool_result",async v=>{if((v.toolName==="write"||v.toolName==="edit")&&cm(),v.toolName==="bash"&&v.input?.command){let S=String(v.input.command);Wc(S)&&(cm(),xb(),setTimeout(()=>ye(),100))}}),t.on("user_bash",async v=>{Wc(v.command)&&(cm(),xb(),setTimeout(()=>ye(),100),setTimeout(()=>ye(),300),setTimeout(()=>ye(),500))}),t.on("model_select",async(v,S)=>{a=S,ye()}),t.on("thinking_level_select",async(v,S)=>{a=S,d=l?.()??(typeof v.level=="string"?v.level:null),nt({deferDuringTyping:!1})}),t.on("session_tree",async(v,S)=>{a=S,d=null,u=null,nt({deferDuringTyping:!1})}),t.on("before_agent_start",async(v,S)=>{E=v.prompt,S.hasUI&&bI(v.prompt,S.ui.setWorkingMessage)}),t.on("agent_start",async(v,S)=>{p=!0,u=null,xI(),Gu(S),a=S}),t.on("message_update",async(v,S)=>{Wb(v.message)&&v.message.stopReason!=="error"&&v.message.stopReason!=="aborted"&&Cm(v.message.usage)>0&&(u=v.message.usage,a=S,pe=!0,ne.schedule(H8))}),t.on("message_end",async(v,S)=>{a=S,Wb(v.message)&&(v.message.stopReason==="error"||v.message.stopReason==="aborted"?u=null:Cm(v.message.usage)>0&&(u=v.message.usage)),nt({deferDuringTyping:!1})}),t.on("turn_end",async(v,S)=>{a=S,nt({deferDuringTyping:!1})}),t.on("tool_call",async(v,S)=>{if(Gu(S),S.hasUI){let D=Hh(S);yI(v.toolName,v.input,S.ui.setWorkingMessage,D)}});function Hh(v){let S=v.sessionManager?.getBranch?.()??[];for(let D=S.length-1;D>=0;D--){let q=S[D];if(q.type==="message"&&q.message?.role==="assistant"){let te=q.message.content;if(!Array.isArray(te))continue;for(let J of te)if(J.type==="text"&&J.text){let Y=J.text.trim();if(Y.length>0)return Y.slice(0,200)}}}}function Gu(v){jt.cancel(),_?(_(),_=null):L=!0,R&&(R=!1,v.ui.setHeader(void 0))}function Uc(v){!_&&L&&!R||jt.schedule(v)}function tO(v){uj(I,v)&&oj(I)}function Ku(v,S,D){Ul(S),D&&v.ui.notify(D,"info")}function zh(v){let S=au(v,O);return $s(S)?S:(v.ui.notify("Editor is empty","info"),null)}async function nO(v){let S=[...I],D=S.map((J,Y)=>({value:String(Y),label:`#${Y+1} ${OI(J,SI)}`})),q=await er(v,"Stash history","\u2191\u2193 navigate \u2022 enter insert \u2022 esc cancel",D,Math.min(D.length,10));if(!q)return null;let te=Number.parseInt(q.value,10);return S[te]??null}async function iO(v,S){let D=S.map((J,Y)=>({value:String(Y),label:`#${Y+1} ${OI(J,SI)}`})),q=await er(v,"Recent project prompts","\u2191\u2193 navigate \u2022 enter insert \u2022 esc cancel",D,Math.min(D.length,10));if(!q)return null;let te=Number.parseInt(q.value,10);return S[te]??null}async function sO(v,S,D){let q=[];if(S>0&&q.push({value:"stash",label:"Stashed prompts",description:`${S} saved`}),D>0&&q.push({value:"project",label:"Recent project prompts",description:`${D} recent`}),q.length===0)return null;if(q.length===1)return q[0]?.value==="project"?"project":"stash";let te=await er(v,"Prompt history","\u2191\u2193 navigate \u2022 enter open \u2022 esc cancel",q,q.length);return te?te.value==="project"?"project":"stash":null}async function rO(v,S){let D=au(v,O);if(!$s(D)){v.ui.setEditorText(S),v.ui.notify("Inserted prompt","info");return}let q=await v.ui.select("Insert prompt",["Replace","Append","Cancel"]);if(q==="Replace"){v.ui.setEditorText(S),v.ui.notify("Replaced editor with prompt","info");return}if(q==="Append"){let te=D.endsWith(`
|
|
520
520
|
`)||S.startsWith(`
|
|
521
521
|
`)?"":`
|
|
522
|
-
`;v.ui.setEditorText(`${D}${te}${S}`),v.ui.notify("Appended prompt","info")}}function rw(v){return Vn(v)?!1:v==="\xDF"||v==="\x1Bs"||v==="\x1BS"||/^\x1b\[(?:83|115)(?::\d*)?(?::\d*)?;3(?::\d+)?u$/.test(v)||v==="\x1B[27;3;115~"||v==="\x1B[27;3;83~"||_e(v,"alt+s")}function oO(v){return CI.find(({shortcutKey:S})=>Un(v,n[S]))?.action??null}function aO(v){return Un(v,n.stashHistory)||n.stashHistory==="ctrl+alt+h"&&(/^\x1b\[104(?::\d*)?(?::\d*)?;7(?::\d+)?u$/.test(v)||v==="\x1B[27;7;104~"||v==="\x1B[27;7;72~")}function ow(v){if(Vn(v))return null;if(aO(v))return{kind:"stashHistory"};if(Un(v,n.copyEditor))return{kind:"copyEditor"};if(Un(v,n.cutEditor))return{kind:"cutEditor"};if(Un(v,i.toggleShortcut))return{kind:"bashMode"};let S=oO(v);return S?{kind:"chat",action:S}:null}function Vh(v,S){if(S.kind==="stashHistory"){Qh(v);return}if(S.kind==="copyEditor"||S.kind==="cutEditor"){let D=zh(v);if(!D)return;Ku(v,D,S.kind==="copyEditor"?"Copied editor text":void 0),S.kind==="cutEditor"&&(v.ui.setEditorText(""),v.ui.notify("Cut editor text","info"));return}if(S.kind==="bashMode"){Ri(!F,v);return}if(S.action.kind==="bottom"){hO(v);return}mO(v,S.action.role,S.action.direction)}function Jh(v){let S=au(v,O),D=M!==null;if(!$s(S)){if(!D){v.ui.notify("Nothing to stash","info");return}v.ui.setEditorText(M),M=null,v.ui.setStatus("stash",void 0),v.ui.notify("Stash restored","info");return}M=S,tO(S),v.ui.setEditorText(""),v.ui.setStatus("stash","stash"),v.ui.notify(D?"Stash updated":"Text stashed","info")}async function Qh(v){let S=[];try{S=sj(v.cwd,F8)}catch(te){let J=te instanceof Error?te.message:String(te);v.ui.notify(`Failed to load project prompts: ${J}`,"warning")}if(I.length===0&&S.length===0){v.ui.notify("No prompt history yet","info");return}let D=await sO(v,I.length,S.length);if(!D)return;let q=D==="project"?await iO(v,S):await nO(v);q&&await rO(v,q)}t.on("agent_end",async(v,S)=>{p=!1,u=null,a=S,S.hasUI&&(vI(S.ui.setWorkingMessage),M!==null&&(S.ui.getEditorText().trim()===""?(S.ui.setEditorText(M),M=null,S.ui.setStatus("stash",void 0),S.ui.notify("Stash restored","info")):S.ui.notify("Stash preserved \u2014 clear editor then Alt+S to restore","info"))),ye()}),t.registerCommand("s:footer",{description:"Configure sling footer status (toggle, preset)",handler:async(v,S)=>{if(a=S,!v?.trim()){s=!s,s?(zu(S),S.ui.notify("sling footer enabled","info")):(G?.dispose(),G=null,N.clear(),F=!1,_?.(),_=null,R=!1,L=!1,jt.cancel(),Db().savedPromptHistory=[],M=null,S.ui.setStatus("stash",void 0),g?.(),g=null,Hu(),P?.(),P=null,S.ui.setEditorComponent(void 0),S.ui.setFooter(void 0),S.ui.setHeader(void 0),S.ui.setWidget("powerline-top",void 0),S.ui.setWidget("powerline-secondary",void 0),S.ui.setWidget("powerline-bash-transcript",void 0),S.ui.setWidget("powerline-status",void 0),S.ui.setWidget("powerline-last-prompt",void 0),c=null,m=null,O=null,ne.cancel(),be(),S.ui.notify("sling footer disabled","info"));return}let D=v.trim().toLowerCase(),q=/^mouse-scroll(?:\s+(on|off|toggle))?$/.exec(D);if(q){let He=q[1]??"toggle";qe.mouseScroll=He==="toggle"?!qe.mouseScroll:He==="on",s&&S.hasUI&&qe.fixedEditor&&m&&O&&Yh(S,m),EI(S.cwd,{mouseScroll:qe.mouseScroll},qe.preset)?S.ui.notify(`sling mouse scroll ${qe.mouseScroll?"enabled":"disabled"}`,"info"):S.ui.notify(`sling mouse scroll ${qe.mouseScroll?"enabled":"disabled"} (not persisted; check settings.json)`,"warning");return}let te=/^fixed-editor(?:\s+(on|off|toggle))?$/.exec(D);if(te){let He=te[1]??"toggle";qe.fixedEditor=He==="toggle"?!qe.fixedEditor:He==="on",s&&S.hasUI&&zu(S),EI(S.cwd,{fixedEditor:qe.fixedEditor},qe.preset)?S.ui.notify(`sling fixed editor ${qe.fixedEditor?"enabled":"disabled"}`,"info"):S.ui.notify(`sling fixed editor ${qe.fixedEditor?"enabled":"disabled"} (not persisted; check settings.json)`,"warning");return}let J=lj(v);if(J){qe.preset=J,be(),s&&zu(S),aj(J,S.cwd)?S.ui.notify(`Preset set to: ${J}`,"info"):S.ui.notify(`Preset set to: ${J} (not persisted; check settings.json)`,"warning");return}let Y=Object.keys(oc).join(", ");S.ui.notify(`Available presets: ${Y}`,"info")}}),t.registerCommand("s:stash-history",{description:"Open prompt history picker",handler:async(v,S)=>{if(S.hasUI){if(!s){S.ui.notify("sling footer is disabled","info");return}await Qh(S)}}}),t.registerCommand("s:bash-mode",{description:"Toggle sticky bash mode (on, off, toggle)",handler:async(v,S)=>{let D=v?.trim().toLowerCase()||"toggle";if(D==="on"){await Ri(!0,S);return}if(D==="off"){await Ri(!1,S);return}if(D==="toggle"){await Ri(!F,S);return}S.ui.notify("Usage: /bash-mode [on|off|toggle]","warning")}}),t.registerCommand("s:bash-reset",{description:"Reset the managed bash session",handler:async(v,S)=>{if(G?.dispose(),G=null,N.clear(),F)try{await qt()}catch(D){F=!1;let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to restart shell session: ${q}`,"error"),ye();return}ye(),S.ui.notify("Bash session reset","info")}}),t.registerShortcut(i.toggleShortcut,{description:"Toggle bash mode",handler:async v=>{!s||!v.hasUI||await Ri(!F,v)}}),t.registerShortcut("alt+s",{description:"Stash/restore editor text",handler:async v=>{!s||!v.hasUI||Jh(v)}}),t.registerShortcut(n.stashHistory,{description:"Open prompt history picker",handler:async v=>{!s||!v.hasUI||await Qh(v)}}),t.registerShortcut(n.copyEditor,{description:"Copy full editor text",handler:async v=>{if(!s||!v.hasUI)return;let S=zh(v);S&&Ku(v,S,"Copied editor text")}}),t.registerShortcut(n.cutEditor,{description:"Cut full editor text",handler:async v=>{if(!s||!v.hasUI)return;let S=zh(v);S&&(Ku(v,S),v.ui.setEditorText(""),v.ui.notify("Cut editor text","info"))}});for(let{shortcutKey:v,description:S,action:D}of CI)t.registerShortcut(n[v],{description:S,handler:async q=>{!s||!q.hasUI||Vh(q,{kind:"chat",action:D})}});function cO(v,S){let D=cb(qe.preset),q=D.colors??om(),te=0,J=0,Y=0,He=0,Ee=0,lt,rt=null,kn=v.sessionManager?.getBranch?.()??[];for(let oi of kn){if(!bt(oi)||(oi.type==="thinking_level_change"&&typeof oi.thinkingLevel=="string"&&(rt=oi.thinkingLevel),oi.type!=="message"||!Wb(oi.message)))continue;let _i=oi.message;_i.stopReason==="error"||_i.stopReason==="aborted"||(te+=_i.usage.input,J+=_i.usage.output,Y+=_i.usage.cacheRead,He+=_i.usage.cacheWrite,Ee+=_i.usage.cost.total,Cm(_i.usage)>0&&(lt=_i))}let ue=p?u??lt?.usage:lt?.usage,Re=p&&u?null:zM(v),Ge=Re?.contextTokens??(ue?Cm(ue):0),It=Re?.contextWindow??v.model?.contextWindow??0,Pi=Re?.contextPercent??(It>0?Ge/It*100:0),Fc=c?.getGitBranch()??null,Vu=$M(Fc),qn=c?.getExtensionStatuses()??new Map,Ko=new Map(qe.customItems.map(oi=>[oi.id,oi])),xs=ub(qe.customItems),wt=v.model?v.modelRegistry?.isUsingOAuth?.(v.model)??!1:!1,Ho=d??rt??l?.()??"off";return{model:v.model,thinkingLevel:Ho,sessionId:v.sessionManager?.getSessionId?.(),cwd:v.cwd,usageStats:{input:te,output:J,cacheRead:Y,cacheWrite:He,cost:Ee},contextPercent:Pi,contextWindow:It,autoCompactEnabled:v.settingsManager?.getCompactionSettings?.()?.enabled??!0,customCompactionEnabled:wI||qn.has(U8),usingSubscription:wt,sessionStartTime:r,shellModeActive:F,shellRunning:G?.state.running??!1,shellName:G?.state.shellName??null,shellCwd:G?.state.cwd??null,git:Vu,extensionStatuses:qn,hiddenExtensionStatusKeys:xs,customItemsById:Ko,options:D.segmentOptions??{},theme:S,colors:q}}function aw(v,S){let D=Date.now(),q=p?G8:q8;if(de&&Z===v){let He=D-tt<Sm;if(!Ie&&He&&(pe||D-Te>=q)||!pe&&D-Te<q)return de}let te=cb(qe.preset),J=cO(a,S);return Z=v,de=hj(J,te,v),Te=D,pe=!1,Ie=!1,de}function cw(v){if(!a||!c)return[];let S=c.getExtensionStatuses();if(!S||S.size===0)return[];let D=ub(qe.customItems),q=[];for(let te of AM(S,D)){let J=` ${te}`;j(J)<=v&&q.push(J)}return q}function lw(v,S){if(!a)return[];let D=aw(v,S);return D.topContent?[D.topContent]:[]}function uw(v,S){if(!a)return[];let D=aw(v,S);return D.secondaryContent?[D.secondaryContent]:[]}function dw(v,S){if(!F)return[];let D=N.getSnapshot();if(D.commands.length===0)return[];let q=[];D.truncatedCommands>0&&q.push(` ${S.fg("dim",`\u2026 ${D.truncatedCommands} earlier command${D.truncatedCommands===1?"":"s"} truncated`)}`);let te=D.commands.slice(-4);for(let J of te){let Y=(G?.state.shellName??"shell")==="fish"?">":"$",He=J.exitCode===null?S.fg("accent","running"):J.exitCode===0?S.fg("success","ok"):S.fg("error",`exit ${J.exitCode}`),Ee=X(J.command.replace(/\s+/g," ").trim(),Math.max(8,v-8),"\u2026");q.push(` ${S.fg("accent",Y)} ${Ee} ${S.fg("dim","(")}${He}${S.fg("dim",")")}`);let lt=J.output.slice(-6);for(let rt of lt)q.push(` ${X(rt,Math.max(1,v-3),"\u2026")}`)}return q.slice(-16)}function pw(v){if(F||!W||!E)return[];let S=` ${Lr("sep")}\u21B3${wn.reset} `,D=v-j(S);if(D<10)return[];let q=E.replace(/\s+/g," ").trim();if(!q)return[];q=X(q,D,"\u2026");let te=`${Lr("sep")}${q}${wn.reset}`,J=`${S}${te}`;return[X(J,v,"\u2026")]}function Hu(v){let S=h!==null;if(h?.dispose(v),!S&&v?.resetExtendedKeyboardModes)try{process.stdout.write(aI())}catch{}h=null,f=null,x=null,y=null,w=null}function lO(v,S){let D=Array.isArray(v?.children)?v.children:[],q=D.findIndex(te=>Array.isArray(te?.children)&&te.children.includes(S));return q===-1?null:{container:D[q],index:q}}function Yh(v,S){if(Hu(),!v.hasUI||!qe.fixedEditor)return;if(!S?.terminal||typeof S.terminal.write!="function")throw new Error("[sling-footer] Fixed editor compositor could not find tui.terminal.write()");if(!O)throw new Error("[sling-footer] Fixed editor compositor expected the custom editor to be installed first");let D=lO(S,O);if(!D)throw new Error("[sling-footer] Fixed editor compositor could not find the editor container in TUI children");let q=Array.isArray(S.children)?S.children:[];x=D.container;let te=q[D.index-2]??null;f=te&&typeof te.render=="function"?te:null,y=q[D.index-1]??null,w=q[D.index+1]??null;let J;J=new xm({tui:S,terminal:S.terminal,mouseScroll:qe.mouseScroll,keyboardScrollShortcuts:{up:n.scrollChatUp,down:n.scrollChatDown},onCopySelection:Y=>Ku(v,Y),getShowHardwareCursor:()=>typeof S.getShowHardwareCursor=="function"&&S.getShowHardwareCursor(),renderCluster:(Y,He)=>{let Ee=a?.ui?.theme??v.ui.theme,lt=f?J.renderHidden(f,Y).filter(ue=>j(ue)>0):[],rt=y?J.renderHidden(y,Y):[],kn=w?J.renderHidden(w,Y):[];return VM({width:Y,terminalRows:He,statusLines:[...rt,...cw(Y),...lt],topLines:lw(Y,Ee),editorLines:x?J.renderHidden(x,Y):[],secondaryLines:[...uw(Y,Ee),...kn],transcriptLines:dw(Y,Ee),lastPromptLines:pw(Y)})}}),h=J,f?.render&&J.hideRenderable(f),y?.render&&J.hideRenderable(y),J.hideRenderable(x),w?.render&&J.hideRenderable(w),J.install(),S.requestRender(!0)}function uO(v,S){let D=typeof v=="object"&&v!==null?v.constructor?.name:void 0;return S==="assistant"?D==="AssistantMessageComponent":D==="UserMessageComponent"||D==="SkillInvocationMessageComponent"}function dO(v,S){if(typeof v!="object"||v===null)return 0;let D=Reflect.get(v,"render");if(typeof D!="function")return 0;let q=D.call(v,S);return Array.isArray(q)?q.length:0}function mw(v,S,D,q){let te=dO(v,S);if(uO(v,D))return{targets:[q],lineCount:te};let J=typeof v=="object"&&v!==null?Reflect.get(v,"children"):null;if(!Array.isArray(J)||J.length===0)return{targets:[],lineCount:te};let Y=[],He=q,Ee=0;for(let lt of J){let rt=mw(lt,S,D,He);Y.push(...rt.targets),He+=rt.lineCount,Ee+=rt.lineCount}return{targets:Y,lineCount:Math.max(te,Ee)}}function pO(v){let S=Array.isArray(m?.children)?m.children:[],D=Math.max(1,m?.terminal?.columns??80),q=[],te=0;for(let J of S){let Y=mw(J,D,v,te);q.push(...Y.targets),te+=Y.lineCount}return[...new Set(q)].sort((J,Y)=>J-Y)}function mO(v,S,D){if(!h){v.ui.notify("Chat message jumps require /s:footer fixed-editor on","warning");return}let q=pO(S),te=S==="assistant"?"LLM":"user";if(q.length===0){v.ui.notify(`No ${te} messages found`,"info");return}(D==="previous"?h.jumpToPreviousRootTarget(q):h.jumpToNextRootTarget(q))||v.ui.notify(`No ${D} ${te} message`,"info")}function hO(v){if(!h){v.ui.notify("Chat bottom jump requires /s:footer fixed-editor on","warning");return}h.jumpToRootBottom()}function Xh(){h?.jumpToRootBottom()}function gO(v){v.ui.setWidget("powerline-status",()=>({dispose(){},invalidate(){ye()},render(S){return cw(S)}}),{placement:"aboveEditor"}),v.ui.setWidget("powerline-top",(S,D)=>({dispose(){},invalidate(){be()},render(q){return lw(q,D)}}),{placement:"aboveEditor"}),v.ui.setWidget("powerline-secondary",(S,D)=>({dispose(){},invalidate(){be()},render(q){return uw(q,D)}}),{placement:"belowEditor"}),v.ui.setWidget("powerline-bash-transcript",(S,D)=>({dispose(){},invalidate(){},render(q){return dw(q,D)}}),{placement:"belowEditor"}),v.ui.setWidget("powerline-last-prompt",()=>({dispose(){},invalidate(){},render(S){return pw(S)}}),{placement:"belowEditor"})}function zu(v){if(cu(O),!s)return;P?.(),P=typeof v.ui.onTerminalInput=="function"?v.ui.onTerminalInput(q=>{if(!s||!v.hasUI||m?.hasOverlay?.())return;if(rw(q))return Jh(v),Uc(v),m?.requestRender(),{consume:!0};let te=ow(q);if(te)return Vh(v,te),Uc(v),m?.requestRender(),{consume:!0}}):null,Hu(),v.ui.setWidget("powerline-top",void 0),v.ui.setWidget("powerline-secondary",void 0),v.ui.setWidget("powerline-bash-transcript",void 0),v.ui.setWidget("powerline-status",void 0),v.ui.setWidget("powerline-last-prompt",void 0);let S=!1,D=(q,te,J)=>{let Y=new em(q,te,J,{keybindings:J,isBashModeActive:()=>F,isShellRunning:()=>G?.state.running??!1,onExitBashMode:()=>{Ri(!1,v)},onSubmitCommand:ue=>{Tn(ue,v)},onEditorSubmit:()=>Xh(),editorBoundaryShortcuts:{start:n.editorStart,end:n.editorEnd},onInterrupt:()=>{G?.interrupt(),v.ui.notify("Sent interrupt to shell","info")},onNotify:(ue,Re="info")=>v.ui.notify(ue,Re),getHistoryEntries:ue=>Ii(ue),resolveGhostSuggestion:async(ue,Re)=>{let Ge=nu(ue);if(Ge){let It=await H.getGhostSuggestion(Ge.command,ri(),De(),Re);return It?{...It,value:`${Ge.prefix}${It.value}`}:null}return H.getGhostSuggestion(ue,ri(),De(),Re)}}),He=()=>{let ue=Reflect.get(Y,"autocompleteProvider");if(!(!ue||typeof ue!="object")&&typeof Reflect.get(ue,"getSuggestions")=="function"&&typeof Reflect.get(ue,"applyCompletion")=="function")return ue},Ee=()=>{if(Y.hasWrappedProvider())return!0;let ue=He();if(!ue)return!1;let Re=new Yp,Ge=new Xp;return Y.installAutocompleteProvider(new Zp(ue,Re,Ge,()=>F)),!0},lt;Object.defineProperty(Y,"onSubmit",{configurable:!0,get:()=>lt,set(ue){lt=typeof ue=="function"?Re=>{Xh(),ue(Re)}:ue}}),O=Y,Y8(Y),Q8(Y),Ee();let rt=Y.handleInput.bind(Y);Y.handleInput=ue=>{if(tt=Date.now(),rw(ue)){Jh(v),Uc(v);return}let Re=ow(ue);if(Re){Vh(v,Re),Uc(v);return}if(!S&&!He()){S=!0,cu(Y),v.ui.setEditorComponent(D),qe.fixedEditor&&Yh(v,q),O?.handleInput(ue);return}Ee();let Ge=J.matches(ue,"app.message.followUp")?au(v,Y):"";Uc(v),rt(ue),$s(Ge)&&!$s(au(v,Y))&&Xh()};let kn=Y.render.bind(Y);return Y.render=ue=>{if(ue<10)return kn(ue);let Re=wt=>`${Lr("sep")}${wt}${wn.reset}`,Ge=F?"$":">",Pi=` ${`${wn.getFgAnsi(200,200,200)}${Ge}${wn.reset}`} `,Fc=" ",Vu=Math.max(1,ue-3),qn=kn(Vu);if(qn.length===0)return qn;let Ko=qn.length-1;for(let wt=qn.length-1;wt>=1;wt--){let Ho=qn[wt]?.replace(/\x1b\[[0-9;]*m/g,"")||"";if(Ho.length>0&&/^─{3,}/.test(Ho)){Ko=wt;break}}let xs=[];xs.push(" "+Re("\u2500".repeat(ue-2)));for(let wt=1;wt<Ko;wt++){let Ho=wt===1?Pi:Fc;xs.push(`${Ho}${qn[wt]||""}`)}Ko===1&&xs.push(`${Pi}${" ".repeat(Vu)}`),xs.push(" "+Re("\u2500".repeat(ue-2)));for(let wt=Ko+1;wt<qn.length;wt++)xs.push(qn[wt]||"");return xs},Y};v.ui.setEditorComponent(D),v.ui.setFooter((q,te,J)=>{c=J,m=q,At(J);let Y=J.onBranchChange(()=>ye());return{dispose(){Y(),g?.(),g=null},invalidate(){ye()},render(){return[]}}}),qe.fixedEditor?m&&Yh(v,m):gO(v)}function fO(v){let S=v.model?.name||v.model?.id||"No model",D=v.model?.provider||"Unknown",q=wb(),te=Sb(3),J=new gm(S,D,te,q);R=!0,v.ui.setHeader(()=>({render(Y){return J.render(Y)},invalidate(){J.invalidate()}}))}function bO(v){let S=v.model?.name||v.model?.id||"No model",D=v.model?.provider||"Unknown",q=wb(),te=Sb(3),J=o;setTimeout(()=>{if(!s||L||p||J!==o){L=!1;return}(v.sessionManager?.getBranch?.()??[]).some(Ee=>bt(Ee)?Ee.type==="tool_call"||Ee.type==="tool_result"?!0:Ee.type==="message"&&bt(Ee.message)&&Ee.message.role==="assistant":!1)||v.ui.custom((Ee,lt,rt,kn)=>{let ue=new hm(S,D,te,q),Re=10,Ge=!1,It=null,Pi=()=>{Ge||(Ge=!0,It&&clearInterval(It),_=null,kn())};return It=setInterval(()=>{Ge||(Re--,ue.setCountdown(Re),Ee.requestRender(),Re<=0&&Pi())},1e3),_=Pi,L&&(L=!1,Pi()),{focused:!1,invalidate:()=>ue.invalidate(),render:Fc=>ue.render(Fc),handleInput:()=>Pi(),dispose:()=>{Ge=!0,It&&clearInterval(It)}}},{overlay:!0,overlayOptions:()=>({verticalAlign:"center",horizontalAlign:"center"})}).catch(Ee=>{console.debug("[sling-footer] Welcome overlay failed:",Ee)})},100)}}function JI(t,e){let n=0,i=0,s=async()=>{try{return i=(await(await fetch(we.getUserUrl(),{headers:{Authorization:`Bearer ${e()?.access||""}`,Accept:"application/json",projectId:e()?.projectId||"",workspaceId:e()?.workspaceId||""}})).json()).remainingCredits||0,We("Fetched user data for credits: "+i),i}catch(r){Je("Error fetching user data for credits",r)}return 0};t.on("session_start",async(r,o)=>{o.hasUI&&o.ui.setStatus("ss-credit","0")}),t.on("before_agent_start",async(r,o)=>{let a=await s();o.hasUI&&o.ui.setStatus("ss-credit",`${a.toFixed(2)}`)}),t.on("agent_end",async(r,o)=>{let a=await s();o.hasUI&&o.ui.setStatus("ss-credit",`${a.toFixed(2)}`)})}var Nt=TO(jA(),1);var Ac=t=>t==null?"N/A":t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?Math.round(t/1e3)+"k":t.toString();var Xre=["context_tag","context_log","context_checkout"],jh=null,mn=null,qh=t=>Xre.includes(t),qA=(t,e)=>{if(e.toLowerCase()==="root"){let i=t.getTree();return i.length>0?i[0].entry.id:e}if(/^[0-9a-f]{8,}$/i.test(e))return e;let n=[...t.getTree()];for(;n.length>0;){let i=n.pop();if(t.getLabel(i.entry.id)===e)return i.entry.id;i.children?.length&&n.push(...i.children)}return e},Zre=Nt.Type.Object({limit:Nt.Type.Optional(Nt.Type.Number({description:"History limit for visible entries (default: 50)."})),verbose:Nt.Type.Optional(Nt.Type.Boolean({description:"If true, show ALL messages. If false (default), collapses intermediate AI steps and only shows 'milestones': User messages, Tags, Branch Points, and Summaries."}))}),eoe=Nt.Type.Object({target:Nt.Type.String({description:"Where to jump/squash to. Can be a tag name (e.g., 'task-start'), a commit ID, or 'root'. This is the base for your new branch."}),message:Nt.Type.String({description:"The 'Carryover Message' for the new branch. A summary of your *current* progress/lessons that you want to bring with you to the new state. This ensures you don't lose key information when switching contexts. Good summary message: '[Status] + [Reason] + [Important Changes] + [Carryover Data]'"}),backupTag:Nt.Type.Optional(Nt.Type.String({description:"Optional tag name to apply to the CURRENT state before checking out. Use this to create an automatic backup of the history you are about to leave/squash."}))}),toe=Nt.Type.Object({name:Nt.Type.String({description:"The tag/milestone name. Use meaningful names."}),target:Nt.Type.Optional(Nt.Type.String({description:"The commit ID to tag. Defaults to HEAD (current state)."}))});function GA(t){t.registerCommand("s:acm",{description:"Enable agentic context management for the current session",handler:async(n,i)=>{jh=i,i.ui.notify("Agentic Context Management enabled.","info"),t.sendMessage({customType:"ss-context",content:"use context-management skill",display:!1},{deliverAs:"followUp"}),n&&t.sendUserMessage(n)}});let e=(n,i,s)=>{let r=[...i].reverse();for(;r.length>0;){let o=r.pop();if(n.getLabel(o.entry.id)===s)return o.entry.id;if(o.children?.length)for(let a=o.children.length-1;a>=0;a--)r.push(o.children[a])}return null};t.registerTool({name:"context_tag",label:"Context Tag",description:"Creates a 'Save Point' (Bookmark) in the history. Use this before trying risky changes or when a feature is stable. 'Untagged progress is risky'.",parameters:toe,async execute(n,i,s,r,o){let a=o.sessionManager,c=e(a,a.getTree(),i.name);if(c)return{content:[{type:"text",text:`Error: Tag '${i.name}' already exists at ${c}. Tag names must be unique. Use a different name or delete the existing tag first.`}],details:{}};let l=i.target?qA(a,i.target):void 0;if(!l){let d=a.getBranch();for(let u=d.length-1;u>=0;u--){let p=d[u];if(p.type==="message"&&p.message.role==="toolResult"){let m=p.message;if(qh(m.toolName))continue;l=p.id;break}if(p.type==="message"&&p.message.role==="assistant"&&!p.message.content.some(h=>h.type==="toolCall"&&qh(h.name))){l=p.id;break}l=p.id;break}l||(l=a.getLeafId()??"")}return t.setLabel(l,i.name),{content:[{type:"text",text:`Created tag '${i.name}' at ${l}`}],details:{}}}}),t.registerTool({name:"context_log",label:"Context Log",description:"Show the entire history structure (status, message, tags, milestones). Analogous to 'git log --graph --oneline --decorate'",parameters:Zre,async execute(n,i,s,r,o){let a=o.sessionManager,c=a.getBranch(),l=a.getLeafId(),d=i.verbose??!1,u=i.limit??50,p=new Set(c.map(W=>W.id)),m=[];c.forEach(W=>{m.push(W),a.getChildren(W.id).forEach(I=>{(I.type==="branch_summary"||I.type==="compaction")&&!p.has(I.id)&&m.push(I)})});let g=W=>{if(W.type==="branch_summary"||W.type==="compaction")return W.summary||"[No summary provided]";if(W.type==="label")return`tag: ${W.label}`;if(W.type==="message"){let M=W.message;if(M.role==="toolResult"){let I=M;if(!d&&qh(I.toolName))return"";let F=(H=>H.map(G=>G.type==="text"?G.text:"").join(" ").trim())(I.content),N=I.details;return(I.toolName==="read"||I.toolName==="edit")&&N&&"path"in N&&typeof N.path=="string"&&(F=`${N.path}: ${F}`),`(${I.toolName}) ${F}`}if(M.role==="bashExecution")return`[Bash] ${M.command}`;if(M.role==="user"||M.role==="assistant"){let I="";typeof M.content=="string"?I=M.content:Array.isArray(M.content)&&(I=M.content.map(F=>typeof F=="object"&&F!==null&&"text"in F?F.text:"").join(" ").trim());let O="";return M.role==="assistant"&&(O=M.content.filter(N=>N.type==="toolCall").filter(N=>d||!qh(N.name)).map(N=>`call: ${N.name}(${JSON.stringify(N.arguments)})`).join("; ")),[I,O].filter(Boolean).join(" ")}}return""},h=W=>W.id===l||c.length>0&&W.id===c[0].id||a.getLabel(W.id)?!0:W.type==="label"?!1:W.type==="branch_summary"||W.type==="compaction"||a.getChildren(W.id).length>1||W.type==="message"&&W.message.role==="user",f=new Set;m.forEach(W=>{(d||h(W))&&f.add(W.id)});let x=m.filter(W=>f.has(W.id));if(x.length>u){let W=new Set(x.slice(-u).map(M=>M.id));f.clear(),W.forEach(M=>f.add(M))}let y=[],w=0;m.forEach(W=>{if(!f.has(W.id)){w++;return}w>0&&(y.push(` : ... (${w} hidden messages) ...`),w=0);let M=W.id===l,I=a.getLabel(W.id),O=g(W).replace(/\s+/g," "),F=W.type.toUpperCase();if(W.type==="message"){let Te=W.message;F=Te.role==="assistant"?"AI":Te.role==="user"?"USER":Te.role==="bashExecution"?"BASH":"TOOL"}else(W.type==="branch_summary"||W.type==="compaction")&&(F="SUMMARY");if(F==="CUSTOM_MESSAGE")return;let N=W.id,G=[c.length>0&&W.id===c[0].id?"ROOT":null,M?"HEAD":null,I?`tag: ${I}`:null].filter(Boolean).join(", "),Z=O.length>100?O.slice(0,100)+"...":O,de=M?"*":F==="USER"?"\u2022":"|";y.push(`${de} ${N}${G?` (${G})`:""} [${F}] ${Z}`)}),w>0&&y.push(` : ... (${w} hidden messages) ...`);let P=await o.getContextUsage(),_="Unknown";P&&(_=`${P.percent.toFixed(1)}% (${Ac(P.tokens)}/${Ac(P.contextWindow)})`);let R=0,L="None";for(let W=c.length-1;W>=0;W--){let M=c[W].id,I=a.getLabel(M);if(I){L=I;break}R++}return{content:[{type:"text",text:["[Context Dashboard]",`\u2022 Context Usage: ${_}`,`\u2022 Segment Size: ${R} steps since last tag '${L}'`,"---------------------------------------------------"].join(`
|
|
522
|
+
`;v.ui.setEditorText(`${D}${te}${S}`),v.ui.notify("Appended prompt","info")}}function rw(v){return Vn(v)?!1:v==="\xDF"||v==="\x1Bs"||v==="\x1BS"||/^\x1b\[(?:83|115)(?::\d*)?(?::\d*)?;3(?::\d+)?u$/.test(v)||v==="\x1B[27;3;115~"||v==="\x1B[27;3;83~"||Ee(v,"alt+s")}function oO(v){return CI.find(({shortcutKey:S})=>Un(v,n[S]))?.action??null}function aO(v){return Un(v,n.stashHistory)||n.stashHistory==="ctrl+alt+h"&&(/^\x1b\[104(?::\d*)?(?::\d*)?;7(?::\d+)?u$/.test(v)||v==="\x1B[27;7;104~"||v==="\x1B[27;7;72~")}function ow(v){if(Vn(v))return null;if(aO(v))return{kind:"stashHistory"};if(Un(v,n.copyEditor))return{kind:"copyEditor"};if(Un(v,n.cutEditor))return{kind:"cutEditor"};if(Un(v,i.toggleShortcut))return{kind:"bashMode"};let S=oO(v);return S?{kind:"chat",action:S}:null}function Vh(v,S){if(S.kind==="stashHistory"){Qh(v);return}if(S.kind==="copyEditor"||S.kind==="cutEditor"){let D=zh(v);if(!D)return;Ku(v,D,S.kind==="copyEditor"?"Copied editor text":void 0),S.kind==="cutEditor"&&(v.ui.setEditorText(""),v.ui.notify("Cut editor text","info"));return}if(S.kind==="bashMode"){Ri(!F,v);return}if(S.action.kind==="bottom"){hO(v);return}mO(v,S.action.role,S.action.direction)}function Jh(v){let S=au(v,O),D=M!==null;if(!$s(S)){if(!D){v.ui.notify("Nothing to stash","info");return}v.ui.setEditorText(M),M=null,v.ui.setStatus("stash",void 0),v.ui.notify("Stash restored","info");return}M=S,tO(S),v.ui.setEditorText(""),v.ui.setStatus("stash","stash"),v.ui.notify(D?"Stash updated":"Text stashed","info")}async function Qh(v){let S=[];try{S=sj(v.cwd,F8)}catch(te){let J=te instanceof Error?te.message:String(te);v.ui.notify(`Failed to load project prompts: ${J}`,"warning")}if(I.length===0&&S.length===0){v.ui.notify("No prompt history yet","info");return}let D=await sO(v,I.length,S.length);if(!D)return;let q=D==="project"?await iO(v,S):await nO(v);q&&await rO(v,q)}t.on("agent_end",async(v,S)=>{p=!1,u=null,a=S,S.hasUI&&(vI(S.ui.setWorkingMessage),M!==null&&(S.ui.getEditorText().trim()===""?(S.ui.setEditorText(M),M=null,S.ui.setStatus("stash",void 0),S.ui.notify("Stash restored","info")):S.ui.notify("Stash preserved \u2014 clear editor then Alt+S to restore","info"))),ye()}),t.registerCommand("s:footer",{description:"Configure sling footer status (toggle, preset)",handler:async(v,S)=>{if(a=S,!v?.trim()){s=!s,s?(zu(S),S.ui.notify("sling footer enabled","info")):(G?.dispose(),G=null,N.clear(),F=!1,_?.(),_=null,R=!1,L=!1,jt.cancel(),Db().savedPromptHistory=[],M=null,S.ui.setStatus("stash",void 0),g?.(),g=null,Hu(),P?.(),P=null,S.ui.setEditorComponent(void 0),S.ui.setFooter(void 0),S.ui.setHeader(void 0),S.ui.setWidget("powerline-top",void 0),S.ui.setWidget("powerline-secondary",void 0),S.ui.setWidget("powerline-bash-transcript",void 0),S.ui.setWidget("powerline-status",void 0),S.ui.setWidget("powerline-last-prompt",void 0),c=null,m=null,O=null,ne.cancel(),be(),S.ui.notify("sling footer disabled","info"));return}let D=v.trim().toLowerCase(),q=/^mouse-scroll(?:\s+(on|off|toggle))?$/.exec(D);if(q){let He=q[1]??"toggle";qe.mouseScroll=He==="toggle"?!qe.mouseScroll:He==="on",s&&S.hasUI&&qe.fixedEditor&&m&&O&&Yh(S,m),EI(S.cwd,{mouseScroll:qe.mouseScroll},qe.preset)?S.ui.notify(`sling mouse scroll ${qe.mouseScroll?"enabled":"disabled"}`,"info"):S.ui.notify(`sling mouse scroll ${qe.mouseScroll?"enabled":"disabled"} (not persisted; check settings.json)`,"warning");return}let te=/^fixed-editor(?:\s+(on|off|toggle))?$/.exec(D);if(te){let He=te[1]??"toggle";qe.fixedEditor=He==="toggle"?!qe.fixedEditor:He==="on",s&&S.hasUI&&zu(S),EI(S.cwd,{fixedEditor:qe.fixedEditor},qe.preset)?S.ui.notify(`sling fixed editor ${qe.fixedEditor?"enabled":"disabled"}`,"info"):S.ui.notify(`sling fixed editor ${qe.fixedEditor?"enabled":"disabled"} (not persisted; check settings.json)`,"warning");return}let J=lj(v);if(J){qe.preset=J,be(),s&&zu(S),aj(J,S.cwd)?S.ui.notify(`Preset set to: ${J}`,"info"):S.ui.notify(`Preset set to: ${J} (not persisted; check settings.json)`,"warning");return}let Y=Object.keys(oc).join(", ");S.ui.notify(`Available presets: ${Y}`,"info")}}),t.registerCommand("s:stash-history",{description:"Open prompt history picker",handler:async(v,S)=>{if(S.hasUI){if(!s){S.ui.notify("sling footer is disabled","info");return}await Qh(S)}}}),t.registerCommand("s:bash-mode",{description:"Toggle sticky bash mode (on, off, toggle)",handler:async(v,S)=>{let D=v?.trim().toLowerCase()||"toggle";if(D==="on"){await Ri(!0,S);return}if(D==="off"){await Ri(!1,S);return}if(D==="toggle"){await Ri(!F,S);return}S.ui.notify("Usage: /bash-mode [on|off|toggle]","warning")}}),t.registerCommand("s:bash-reset",{description:"Reset the managed bash session",handler:async(v,S)=>{if(G?.dispose(),G=null,N.clear(),F)try{await qt()}catch(D){F=!1;let q=D instanceof Error?D.message:String(D);S.ui.notify(`Failed to restart shell session: ${q}`,"error"),ye();return}ye(),S.ui.notify("Bash session reset","info")}}),t.registerShortcut(i.toggleShortcut,{description:"Toggle bash mode",handler:async v=>{!s||!v.hasUI||await Ri(!F,v)}}),t.registerShortcut("alt+s",{description:"Stash/restore editor text",handler:async v=>{!s||!v.hasUI||Jh(v)}}),t.registerShortcut(n.stashHistory,{description:"Open prompt history picker",handler:async v=>{!s||!v.hasUI||await Qh(v)}}),t.registerShortcut(n.copyEditor,{description:"Copy full editor text",handler:async v=>{if(!s||!v.hasUI)return;let S=zh(v);S&&Ku(v,S,"Copied editor text")}}),t.registerShortcut(n.cutEditor,{description:"Cut full editor text",handler:async v=>{if(!s||!v.hasUI)return;let S=zh(v);S&&(Ku(v,S),v.ui.setEditorText(""),v.ui.notify("Cut editor text","info"))}});for(let{shortcutKey:v,description:S,action:D}of CI)t.registerShortcut(n[v],{description:S,handler:async q=>{!s||!q.hasUI||Vh(q,{kind:"chat",action:D})}});function cO(v,S){let D=cb(qe.preset),q=D.colors??om(),te=0,J=0,Y=0,He=0,Ae=0,lt,rt=null,kn=v.sessionManager?.getBranch?.()??[];for(let oi of kn){if(!bt(oi)||(oi.type==="thinking_level_change"&&typeof oi.thinkingLevel=="string"&&(rt=oi.thinkingLevel),oi.type!=="message"||!Wb(oi.message)))continue;let _i=oi.message;_i.stopReason==="error"||_i.stopReason==="aborted"||(te+=_i.usage.input,J+=_i.usage.output,Y+=_i.usage.cacheRead,He+=_i.usage.cacheWrite,Ae+=_i.usage.cost.total,Cm(_i.usage)>0&&(lt=_i))}let ue=p?u??lt?.usage:lt?.usage,Re=p&&u?null:zM(v),Ge=Re?.contextTokens??(ue?Cm(ue):0),It=Re?.contextWindow??v.model?.contextWindow??0,Pi=Re?.contextPercent??(It>0?Ge/It*100:0),Fc=c?.getGitBranch()??null,Vu=$M(Fc),qn=c?.getExtensionStatuses()??new Map,Ko=new Map(qe.customItems.map(oi=>[oi.id,oi])),xs=ub(qe.customItems),wt=v.model?v.modelRegistry?.isUsingOAuth?.(v.model)??!1:!1,Ho=d??rt??l?.()??"off";return{model:v.model,thinkingLevel:Ho,sessionId:v.sessionManager?.getSessionId?.(),cwd:v.cwd,usageStats:{input:te,output:J,cacheRead:Y,cacheWrite:He,cost:Ae},contextPercent:Pi,contextWindow:It,autoCompactEnabled:v.settingsManager?.getCompactionSettings?.()?.enabled??!0,customCompactionEnabled:wI||qn.has(U8),usingSubscription:wt,sessionStartTime:r,shellModeActive:F,shellRunning:G?.state.running??!1,shellName:G?.state.shellName??null,shellCwd:G?.state.cwd??null,git:Vu,extensionStatuses:qn,hiddenExtensionStatusKeys:xs,customItemsById:Ko,options:D.segmentOptions??{},theme:S,colors:q}}function aw(v,S){let D=Date.now(),q=p?G8:q8;if(de&&Z===v){let He=D-tt<Sm;if(!Ie&&He&&(pe||D-Te>=q)||!pe&&D-Te<q)return de}let te=cb(qe.preset),J=cO(a,S);return Z=v,de=hj(J,te,v),Te=D,pe=!1,Ie=!1,de}function cw(v){if(!a||!c)return[];let S=c.getExtensionStatuses();if(!S||S.size===0)return[];let D=ub(qe.customItems),q=[];for(let te of AM(S,D)){let J=` ${te}`;j(J)<=v&&q.push(J)}return q}function lw(v,S){if(!a)return[];let D=aw(v,S);return D.topContent?[D.topContent]:[]}function uw(v,S){if(!a)return[];let D=aw(v,S);return D.secondaryContent?[D.secondaryContent]:[]}function dw(v,S){if(!F)return[];let D=N.getSnapshot();if(D.commands.length===0)return[];let q=[];D.truncatedCommands>0&&q.push(` ${S.fg("dim",`\u2026 ${D.truncatedCommands} earlier command${D.truncatedCommands===1?"":"s"} truncated`)}`);let te=D.commands.slice(-4);for(let J of te){let Y=(G?.state.shellName??"shell")==="fish"?">":"$",He=J.exitCode===null?S.fg("accent","running"):J.exitCode===0?S.fg("success","ok"):S.fg("error",`exit ${J.exitCode}`),Ae=X(J.command.replace(/\s+/g," ").trim(),Math.max(8,v-8),"\u2026");q.push(` ${S.fg("accent",Y)} ${Ae} ${S.fg("dim","(")}${He}${S.fg("dim",")")}`);let lt=J.output.slice(-6);for(let rt of lt)q.push(` ${X(rt,Math.max(1,v-3),"\u2026")}`)}return q.slice(-16)}function pw(v){if(F||!W||!E)return[];let S=` ${Lr("sep")}\u21B3${wn.reset} `,D=v-j(S);if(D<10)return[];let q=E.replace(/\s+/g," ").trim();if(!q)return[];q=X(q,D,"\u2026");let te=`${Lr("sep")}${q}${wn.reset}`,J=`${S}${te}`;return[X(J,v,"\u2026")]}function Hu(v){let S=h!==null;if(h?.dispose(v),!S&&v?.resetExtendedKeyboardModes)try{process.stdout.write(aI())}catch{}h=null,f=null,x=null,y=null,w=null}function lO(v,S){let D=Array.isArray(v?.children)?v.children:[],q=D.findIndex(te=>Array.isArray(te?.children)&&te.children.includes(S));return q===-1?null:{container:D[q],index:q}}function Yh(v,S){if(Hu(),!v.hasUI||!qe.fixedEditor)return;if(!S?.terminal||typeof S.terminal.write!="function")throw new Error("[sling-footer] Fixed editor compositor could not find tui.terminal.write()");if(!O)throw new Error("[sling-footer] Fixed editor compositor expected the custom editor to be installed first");let D=lO(S,O);if(!D)throw new Error("[sling-footer] Fixed editor compositor could not find the editor container in TUI children");let q=Array.isArray(S.children)?S.children:[];x=D.container;let te=q[D.index-2]??null;f=te&&typeof te.render=="function"?te:null,y=q[D.index-1]??null,w=q[D.index+1]??null;let J;J=new xm({tui:S,terminal:S.terminal,mouseScroll:qe.mouseScroll,keyboardScrollShortcuts:{up:n.scrollChatUp,down:n.scrollChatDown},onCopySelection:Y=>Ku(v,Y),getShowHardwareCursor:()=>typeof S.getShowHardwareCursor=="function"&&S.getShowHardwareCursor(),renderCluster:(Y,He)=>{let Ae=a?.ui?.theme??v.ui.theme,lt=f?J.renderHidden(f,Y).filter(ue=>j(ue)>0):[],rt=y?J.renderHidden(y,Y):[],kn=w?J.renderHidden(w,Y):[];return VM({width:Y,terminalRows:He,statusLines:[...rt,...cw(Y),...lt],topLines:lw(Y,Ae),editorLines:x?J.renderHidden(x,Y):[],secondaryLines:[...uw(Y,Ae),...kn],transcriptLines:dw(Y,Ae),lastPromptLines:pw(Y)})}}),h=J,f?.render&&J.hideRenderable(f),y?.render&&J.hideRenderable(y),J.hideRenderable(x),w?.render&&J.hideRenderable(w),J.install(),S.requestRender(!0)}function uO(v,S){let D=typeof v=="object"&&v!==null?v.constructor?.name:void 0;return S==="assistant"?D==="AssistantMessageComponent":D==="UserMessageComponent"||D==="SkillInvocationMessageComponent"}function dO(v,S){if(typeof v!="object"||v===null)return 0;let D=Reflect.get(v,"render");if(typeof D!="function")return 0;let q=D.call(v,S);return Array.isArray(q)?q.length:0}function mw(v,S,D,q){let te=dO(v,S);if(uO(v,D))return{targets:[q],lineCount:te};let J=typeof v=="object"&&v!==null?Reflect.get(v,"children"):null;if(!Array.isArray(J)||J.length===0)return{targets:[],lineCount:te};let Y=[],He=q,Ae=0;for(let lt of J){let rt=mw(lt,S,D,He);Y.push(...rt.targets),He+=rt.lineCount,Ae+=rt.lineCount}return{targets:Y,lineCount:Math.max(te,Ae)}}function pO(v){let S=Array.isArray(m?.children)?m.children:[],D=Math.max(1,m?.terminal?.columns??80),q=[],te=0;for(let J of S){let Y=mw(J,D,v,te);q.push(...Y.targets),te+=Y.lineCount}return[...new Set(q)].sort((J,Y)=>J-Y)}function mO(v,S,D){if(!h){v.ui.notify("Chat message jumps require /s:footer fixed-editor on","warning");return}let q=pO(S),te=S==="assistant"?"LLM":"user";if(q.length===0){v.ui.notify(`No ${te} messages found`,"info");return}(D==="previous"?h.jumpToPreviousRootTarget(q):h.jumpToNextRootTarget(q))||v.ui.notify(`No ${D} ${te} message`,"info")}function hO(v){if(!h){v.ui.notify("Chat bottom jump requires /s:footer fixed-editor on","warning");return}h.jumpToRootBottom()}function Xh(){h?.jumpToRootBottom()}function gO(v){v.ui.setWidget("powerline-status",()=>({dispose(){},invalidate(){ye()},render(S){return cw(S)}}),{placement:"aboveEditor"}),v.ui.setWidget("powerline-top",(S,D)=>({dispose(){},invalidate(){be()},render(q){return lw(q,D)}}),{placement:"aboveEditor"}),v.ui.setWidget("powerline-secondary",(S,D)=>({dispose(){},invalidate(){be()},render(q){return uw(q,D)}}),{placement:"belowEditor"}),v.ui.setWidget("powerline-bash-transcript",(S,D)=>({dispose(){},invalidate(){},render(q){return dw(q,D)}}),{placement:"belowEditor"}),v.ui.setWidget("powerline-last-prompt",()=>({dispose(){},invalidate(){},render(S){return pw(S)}}),{placement:"belowEditor"})}function zu(v){if(cu(O),!s)return;P?.(),P=typeof v.ui.onTerminalInput=="function"?v.ui.onTerminalInput(q=>{if(!s||!v.hasUI||m?.hasOverlay?.())return;if(rw(q))return Jh(v),Uc(v),m?.requestRender(),{consume:!0};let te=ow(q);if(te)return Vh(v,te),Uc(v),m?.requestRender(),{consume:!0}}):null,Hu(),v.ui.setWidget("powerline-top",void 0),v.ui.setWidget("powerline-secondary",void 0),v.ui.setWidget("powerline-bash-transcript",void 0),v.ui.setWidget("powerline-status",void 0),v.ui.setWidget("powerline-last-prompt",void 0);let S=!1,D=(q,te,J)=>{let Y=new em(q,te,J,{keybindings:J,isBashModeActive:()=>F,isShellRunning:()=>G?.state.running??!1,onExitBashMode:()=>{Ri(!1,v)},onSubmitCommand:ue=>{Tn(ue,v)},onEditorSubmit:()=>Xh(),editorBoundaryShortcuts:{start:n.editorStart,end:n.editorEnd},onInterrupt:()=>{G?.interrupt(),v.ui.notify("Sent interrupt to shell","info")},onNotify:(ue,Re="info")=>v.ui.notify(ue,Re),getHistoryEntries:ue=>Ii(ue),resolveGhostSuggestion:async(ue,Re)=>{let Ge=nu(ue);if(Ge){let It=await H.getGhostSuggestion(Ge.command,ri(),De(),Re);return It?{...It,value:`${Ge.prefix}${It.value}`}:null}return H.getGhostSuggestion(ue,ri(),De(),Re)}}),He=()=>{let ue=Reflect.get(Y,"autocompleteProvider");if(!(!ue||typeof ue!="object")&&typeof Reflect.get(ue,"getSuggestions")=="function"&&typeof Reflect.get(ue,"applyCompletion")=="function")return ue},Ae=()=>{if(Y.hasWrappedProvider())return!0;let ue=He();if(!ue)return!1;let Re=new Yp,Ge=new Xp;return Y.installAutocompleteProvider(new Zp(ue,Re,Ge,()=>F)),!0},lt;Object.defineProperty(Y,"onSubmit",{configurable:!0,get:()=>lt,set(ue){lt=typeof ue=="function"?Re=>{Xh(),ue(Re)}:ue}}),O=Y,Y8(Y),Q8(Y),Ae();let rt=Y.handleInput.bind(Y);Y.handleInput=ue=>{if(tt=Date.now(),rw(ue)){Jh(v),Uc(v);return}let Re=ow(ue);if(Re){Vh(v,Re),Uc(v);return}if(!S&&!He()){S=!0,cu(Y),v.ui.setEditorComponent(D),qe.fixedEditor&&Yh(v,q),O?.handleInput(ue);return}Ae();let Ge=J.matches(ue,"app.message.followUp")?au(v,Y):"";Uc(v),rt(ue),$s(Ge)&&!$s(au(v,Y))&&Xh()};let kn=Y.render.bind(Y);return Y.render=ue=>{if(ue<10)return kn(ue);let Re=wt=>`${Lr("sep")}${wt}${wn.reset}`,Ge=F?"$":">",Pi=` ${`${wn.getFgAnsi(200,200,200)}${Ge}${wn.reset}`} `,Fc=" ",Vu=Math.max(1,ue-3),qn=kn(Vu);if(qn.length===0)return qn;let Ko=qn.length-1;for(let wt=qn.length-1;wt>=1;wt--){let Ho=qn[wt]?.replace(/\x1b\[[0-9;]*m/g,"")||"";if(Ho.length>0&&/^─{3,}/.test(Ho)){Ko=wt;break}}let xs=[];xs.push(" "+Re("\u2500".repeat(ue-2)));for(let wt=1;wt<Ko;wt++){let Ho=wt===1?Pi:Fc;xs.push(`${Ho}${qn[wt]||""}`)}Ko===1&&xs.push(`${Pi}${" ".repeat(Vu)}`),xs.push(" "+Re("\u2500".repeat(ue-2)));for(let wt=Ko+1;wt<qn.length;wt++)xs.push(qn[wt]||"");return xs},Y};v.ui.setEditorComponent(D),v.ui.setFooter((q,te,J)=>{c=J,m=q,At(J);let Y=J.onBranchChange(()=>ye());return{dispose(){Y(),g?.(),g=null},invalidate(){ye()},render(){return[]}}}),qe.fixedEditor?m&&Yh(v,m):gO(v)}function fO(v){let S=v.model?.name||v.model?.id||"No model",D=v.model?.provider||"Unknown",q=wb(),te=Sb(3),J=new gm(S,D,te,q);R=!0,v.ui.setHeader(()=>({render(Y){return J.render(Y)},invalidate(){J.invalidate()}}))}function bO(v){let S=v.model?.name||v.model?.id||"No model",D=v.model?.provider||"Unknown",q=wb(),te=Sb(3),J=o;setTimeout(()=>{if(!s||L||p||J!==o){L=!1;return}(v.sessionManager?.getBranch?.()??[]).some(Ae=>bt(Ae)?Ae.type==="tool_call"||Ae.type==="tool_result"?!0:Ae.type==="message"&&bt(Ae.message)&&Ae.message.role==="assistant":!1)||v.ui.custom((Ae,lt,rt,kn)=>{let ue=new hm(S,D,te,q),Re=10,Ge=!1,It=null,Pi=()=>{Ge||(Ge=!0,It&&clearInterval(It),_=null,kn())};return It=setInterval(()=>{Ge||(Re--,ue.setCountdown(Re),Ae.requestRender(),Re<=0&&Pi())},1e3),_=Pi,L&&(L=!1,Pi()),{focused:!1,invalidate:()=>ue.invalidate(),render:Fc=>ue.render(Fc),handleInput:()=>Pi(),dispose:()=>{Ge=!0,It&&clearInterval(It)}}},{overlay:!0,overlayOptions:()=>({verticalAlign:"center",horizontalAlign:"center"})}).catch(Ae=>{console.debug("[sling-footer] Welcome overlay failed:",Ae)})},100)}}function JI(t,e){let n=0,i=0,s=async()=>{try{return i=(await(await fetch(we.getUserUrl(),{headers:{Authorization:`Bearer ${e()?.access||""}`,Accept:"application/json",projectId:e()?.projectId||"",workspaceId:e()?.workspaceId||""}})).json()).remainingCredits||0,Pe("Fetched user data for credits: "+i),i}catch(r){Je("Error fetching user data for credits",r)}return 0};t.on("session_start",async(r,o)=>{o.hasUI&&o.ui.setStatus("ss-credit","0")}),t.on("before_agent_start",async(r,o)=>{let a=await s();o.hasUI&&o.ui.setStatus("ss-credit",`${a.toFixed(2)}`)}),t.on("agent_end",async(r,o)=>{let a=await s();o.hasUI&&o.ui.setStatus("ss-credit",`${a.toFixed(2)}`)})}var Nt=TO(jA(),1);var Ac=t=>t==null?"N/A":t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?Math.round(t/1e3)+"k":t.toString();var Xre=["context_tag","context_log","context_checkout"],jh=null,mn=null,qh=t=>Xre.includes(t),qA=(t,e)=>{if(e.toLowerCase()==="root"){let i=t.getTree();return i.length>0?i[0].entry.id:e}if(/^[0-9a-f]{8,}$/i.test(e))return e;let n=[...t.getTree()];for(;n.length>0;){let i=n.pop();if(t.getLabel(i.entry.id)===e)return i.entry.id;i.children?.length&&n.push(...i.children)}return e},Zre=Nt.Type.Object({limit:Nt.Type.Optional(Nt.Type.Number({description:"History limit for visible entries (default: 50)."})),verbose:Nt.Type.Optional(Nt.Type.Boolean({description:"If true, show ALL messages. If false (default), collapses intermediate AI steps and only shows 'milestones': User messages, Tags, Branch Points, and Summaries."}))}),eoe=Nt.Type.Object({target:Nt.Type.String({description:"Where to jump/squash to. Can be a tag name (e.g., 'task-start'), a commit ID, or 'root'. This is the base for your new branch."}),message:Nt.Type.String({description:"The 'Carryover Message' for the new branch. A summary of your *current* progress/lessons that you want to bring with you to the new state. This ensures you don't lose key information when switching contexts. Good summary message: '[Status] + [Reason] + [Important Changes] + [Carryover Data]'"}),backupTag:Nt.Type.Optional(Nt.Type.String({description:"Optional tag name to apply to the CURRENT state before checking out. Use this to create an automatic backup of the history you are about to leave/squash."}))}),toe=Nt.Type.Object({name:Nt.Type.String({description:"The tag/milestone name. Use meaningful names."}),target:Nt.Type.Optional(Nt.Type.String({description:"The commit ID to tag. Defaults to HEAD (current state)."}))});function GA(t){t.registerCommand("s:acm",{description:"Enable agentic context management for the current session",handler:async(n,i)=>{jh=i,i.ui.notify("Agentic Context Management enabled.","info"),t.sendMessage({customType:"ss-context",content:"use context-management skill",display:!1},{deliverAs:"followUp"}),n&&t.sendUserMessage(n)}});let e=(n,i,s)=>{let r=[...i].reverse();for(;r.length>0;){let o=r.pop();if(n.getLabel(o.entry.id)===s)return o.entry.id;if(o.children?.length)for(let a=o.children.length-1;a>=0;a--)r.push(o.children[a])}return null};t.registerTool({name:"context_tag",label:"Context Tag",description:"Creates a 'Save Point' (Bookmark) in the history. Use this before trying risky changes or when a feature is stable. 'Untagged progress is risky'.",parameters:toe,async execute(n,i,s,r,o){let a=o.sessionManager,c=e(a,a.getTree(),i.name);if(c)return{content:[{type:"text",text:`Error: Tag '${i.name}' already exists at ${c}. Tag names must be unique. Use a different name or delete the existing tag first.`}],details:{}};let l=i.target?qA(a,i.target):void 0;if(!l){let d=a.getBranch();for(let u=d.length-1;u>=0;u--){let p=d[u];if(p.type==="message"&&p.message.role==="toolResult"){let m=p.message;if(qh(m.toolName))continue;l=p.id;break}if(p.type==="message"&&p.message.role==="assistant"&&!p.message.content.some(h=>h.type==="toolCall"&&qh(h.name))){l=p.id;break}l=p.id;break}l||(l=a.getLeafId()??"")}return t.setLabel(l,i.name),{content:[{type:"text",text:`Created tag '${i.name}' at ${l}`}],details:{}}}}),t.registerTool({name:"context_log",label:"Context Log",description:"Show the entire history structure (status, message, tags, milestones). Analogous to 'git log --graph --oneline --decorate'",parameters:Zre,async execute(n,i,s,r,o){let a=o.sessionManager,c=a.getBranch(),l=a.getLeafId(),d=i.verbose??!1,u=i.limit??50,p=new Set(c.map(W=>W.id)),m=[];c.forEach(W=>{m.push(W),a.getChildren(W.id).forEach(I=>{(I.type==="branch_summary"||I.type==="compaction")&&!p.has(I.id)&&m.push(I)})});let g=W=>{if(W.type==="branch_summary"||W.type==="compaction")return W.summary||"[No summary provided]";if(W.type==="label")return`tag: ${W.label}`;if(W.type==="message"){let M=W.message;if(M.role==="toolResult"){let I=M;if(!d&&qh(I.toolName))return"";let F=(H=>H.map(G=>G.type==="text"?G.text:"").join(" ").trim())(I.content),N=I.details;return(I.toolName==="read"||I.toolName==="edit")&&N&&"path"in N&&typeof N.path=="string"&&(F=`${N.path}: ${F}`),`(${I.toolName}) ${F}`}if(M.role==="bashExecution")return`[Bash] ${M.command}`;if(M.role==="user"||M.role==="assistant"){let I="";typeof M.content=="string"?I=M.content:Array.isArray(M.content)&&(I=M.content.map(F=>typeof F=="object"&&F!==null&&"text"in F?F.text:"").join(" ").trim());let O="";return M.role==="assistant"&&(O=M.content.filter(N=>N.type==="toolCall").filter(N=>d||!qh(N.name)).map(N=>`call: ${N.name}(${JSON.stringify(N.arguments)})`).join("; ")),[I,O].filter(Boolean).join(" ")}}return""},h=W=>W.id===l||c.length>0&&W.id===c[0].id||a.getLabel(W.id)?!0:W.type==="label"?!1:W.type==="branch_summary"||W.type==="compaction"||a.getChildren(W.id).length>1||W.type==="message"&&W.message.role==="user",f=new Set;m.forEach(W=>{(d||h(W))&&f.add(W.id)});let x=m.filter(W=>f.has(W.id));if(x.length>u){let W=new Set(x.slice(-u).map(M=>M.id));f.clear(),W.forEach(M=>f.add(M))}let y=[],w=0;m.forEach(W=>{if(!f.has(W.id)){w++;return}w>0&&(y.push(` : ... (${w} hidden messages) ...`),w=0);let M=W.id===l,I=a.getLabel(W.id),O=g(W).replace(/\s+/g," "),F=W.type.toUpperCase();if(W.type==="message"){let Te=W.message;F=Te.role==="assistant"?"AI":Te.role==="user"?"USER":Te.role==="bashExecution"?"BASH":"TOOL"}else(W.type==="branch_summary"||W.type==="compaction")&&(F="SUMMARY");if(F==="CUSTOM_MESSAGE")return;let N=W.id,G=[c.length>0&&W.id===c[0].id?"ROOT":null,M?"HEAD":null,I?`tag: ${I}`:null].filter(Boolean).join(", "),Z=O.length>100?O.slice(0,100)+"...":O,de=M?"*":F==="USER"?"\u2022":"|";y.push(`${de} ${N}${G?` (${G})`:""} [${F}] ${Z}`)}),w>0&&y.push(` : ... (${w} hidden messages) ...`);let P=await o.getContextUsage(),_="Unknown";P&&(_=`${P.percent.toFixed(1)}% (${Ac(P.tokens)}/${Ac(P.contextWindow)})`);let R=0,L="None";for(let W=c.length-1;W>=0;W--){let M=c[W].id,I=a.getLabel(M);if(I){L=I;break}R++}return{content:[{type:"text",text:["[Context Dashboard]",`\u2022 Context Usage: ${_}`,`\u2022 Segment Size: ${R} steps since last tag '${L}'`,"---------------------------------------------------"].join(`
|
|
523
523
|
`)+`
|
|
524
524
|
`+(y.join(`
|
|
525
525
|
`)||"(Root Path Only)")}],details:{}}}}),t.registerTool({name:"context_checkout",label:"Context Checkout",description:"Navigate to ANY point in the conversation history. This checkout only resets *conversation history*, NOT disk files. ALWAYS provide a detailed 'message' to bridge context.",parameters:eoe,async execute(n,i,s,r,o){if(!jh)return o.ui.setEditorText(`/acm ${o.ui.getEditorText()||"continue"}`),{content:[{type:"text",text:"Agentic context management is not enabled. Ask the user to run `/acm` in the pi to enable it, then retry."}],details:{}};let a=o.sessionManager,c=qA(a,i.target),l=a.getLeafId();if(l===c)return{content:[{type:"text",text:`Already at target ${c}`}],details:{}};i.backupTag&&l&&t.setLabel(l,i.backupTag);let d=l?a.getLabel(l):void 0,p=`(summary from ${d?`tag: ${d}`:l||"unknown"})
|
|
526
526
|
${i.message}`,m=await a.branchWithSummary(c,p);return mn=i,mn.nid=m,mn.tid=c,mn.enrichedMessage=p,{content:[{type:"text",text:"checkout start"}],details:{}}}}),t.on("turn_end",async(n,i)=>{mn&&i.abort()}),t.on("agent_end",async(n,i)=>{mn&&jh&&(await jh.navigateTree(mn.nid,{summarize:!1}),i.ui.notify(`Checked out ${mn.target}${mn.target===mn.tid?"":`(${mn.tid})`}
|
|
527
527
|
Backup tag created: ${mn.backupTag||"none"}
|
|
528
|
-
message: ${mn.enrichedMessage}`,"info"),mn=null,t.sendMessage({customType:"ss-context",content:"context_checkout complete. A summary of your previous branch was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",display:!1},{triggerTurn:!0}))})}function KA(t){t.registerCommand("s:context",{description:"Show context usage visualization",handler:async(e,n)=>{let i=await n.getContextUsage();if(!i){n.ui.notify("Context usage info not available.","warning");return}let r=n.sessionManager.getBranch(),o=n.getSystemPrompt(),a=t.getActiveTools(),l=t.getAllTools().filter(W=>a.includes(W.name)),d=W=>Math.ceil(W.length/4),u=0,p=0,m=0;for(let W of r)if(W.type==="message"){let M=W.message;if(M.role==="user"){if(typeof M.content=="string")u+=d(M.content);else if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(u+=d(I.text))}else if(M.role==="assistant"){if(typeof M.content=="string")u+=d(M.content);else if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(u+=d(I.text)),I.type==="toolCall"&&(p+=d(JSON.stringify(I)))}else if(M.role==="toolResult"){if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(m+=d(I.text))}else M.role==="bashExecution"&&(p+=d(M.command||""))}else(W.type==="branch_summary"||W.type==="compaction")&&(u+=d(W.summary||""));let g=d(o),h=d(JSON.stringify(l)),f=i.tokens,x=i.contextWindow;if(f==null||x==null||i.percent==null){n.ui.notify("Context usage info not available.","warning");return}let y=g+h+u+p+m,w=y>0?f/y:1,P=Math.round(g*w),_=Math.round(h*w),R=Math.round(u*w),L=Math.round(p*w),E=Math.round(m*w);await n.ui.custom((W,M,I,O)=>{let F=new K;F.addChild(new V(ne=>M.fg("accent",ne))),F.addChild(new A(M.fg("accent",M.bold(" Context Usage")),1,0)),F.addChild(new U(1));let N=[{label:"System Prompt",value:P,color:"muted"},{label:"System Tools",value:_,color:"dim"},{label:"Tool Call",value:L+E,color:"success"},{label:"Messages",value:R,color:"accent"}],H=Math.max(0,f-(P+_+R+L+E));H>10&&N.push({label:"Other",value:H,color:"dim"}),N.push({label:"Available",value:Math.max(0,x-f),color:"borderMuted"});let G=10,Z=5,de=G*Z,Te=[];for(N.forEach(ne=>{if(ne.label==="Available")return;let be=Math.round(ne.value/x*de);be===0&&ne.value>0&&(be=1);for(let ye=0;ye<be&&Te.length<de;ye++)Te.push({color:ne.color,filled:!0})});Te.length<de;)Te.push({color:"borderMuted",filled:!1});let pe=[];for(let ne=0;ne<Z;ne++){let be="";for(let ye=0;ye<G;ye++){let nt=Te[ne*G+ye];be+=M.fg(nt.color,nt.filled?"\u25A0 ":"\u25A1 ")}pe.push(be.trimEnd())}let Ie=`${M.fg("text",M.bold("Total Usage".padEnd(16)))} ${M.fg("text",M.bold(Ac(f).padStart(7)))} ${M.fg("text",M.bold(`(${i.percent.toFixed(1).padStart(5)}%)`))}`,tt=N.map(ne=>{let be=ne.label.padEnd(14),ye=Ac(ne.value).padStart(7),nt=(ne.value/x*100).toFixed(1).padStart(5),At=ne.label==="Available"?"\u25A1":"\u25A0";return`${M.fg(ne.color,At)} ${M.fg("text",be)} ${M.fg("accent",ye)} (${nt}%)`}),De=[Ie,"",...tt],ri=20,jt=Math.max(pe.length,De.length);for(let ne=0;ne<jt;ne++){let be=(pe[ne]||"").padEnd(ri),ye=De[ne]||"";F.addChild(new A(` ${be} ${ye}`,1,0))}return F.addChild(new U(1)),F.addChild(new A(M.fg("dim"," Press any key to close"),1,0)),F.addChild(new V(ne=>M.fg("accent",ne))),{render:ne=>F.render(ne),invalidate:()=>F.invalidate(),handleInput:ne=>O(void 0)}},{overlay:!0})}})}import{basename as HA,dirname as VA,join as noe,relative as JA}from"node:path";var Xv=["by-source","a-z","active-first"],ioe={"by-source":"By source","a-z":"A\u2013Z","active-first":"Active first"};function soe(t){let e=Xv.indexOf(t);return Xv[(e+1)%Xv.length]??"by-source"}function roe(t){return t.origin==="package"?`${t.source} (${t.scope})`:t.source==="auto"?t.scope==="user"?"User (~/.sling/agent/)":"Project (.sling/)":t.scope==="user"?"User settings":"Project settings"}function ooe(t){let e=new Map;for(let i of t){let{path:s,enabled:r,metadata:o}=i,a=`${o.origin}:${o.scope}:${o.source}`;e.has(a)||e.set(a,{key:a,label:roe(o),scope:o.scope,origin:o.origin,source:o.source,items:[]});let c=HA(s),l=HA(VA(s)),d=c==="SKILL.md"?l:c.endsWith(".md")?c.replace(/\.md$/,""):c;e.get(a)?.items.push({path:s,enabled:r,metadata:o,displayName:d,groupKey:a})}let n=Array.from(e.values());n.sort((i,s)=>i.origin!==s.origin?i.origin==="package"?-1:1:i.scope!==s.scope?i.scope==="user"?-1:1:i.source.localeCompare(s.source));for(let i of n)i.items.sort((s,r)=>s.displayName.localeCompare(r.displayName));return n}function aoe(t){let e=[];for(let n of t){e.push({type:"group",group:n});for(let i of n.items)e.push({type:"item",item:i})}return e}function coe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function loe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.enabled!==i.enabled?n.enabled?-1:1:n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function zA(t,e){switch(e){case"by-source":return aoe(t);case"a-z":return coe(t);case"active-first":return loe(t)}}function uoe(t){let e=t.trim();if(e.length===0)return;if(e.startsWith("/")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.path.toLowerCase().includes(i)}if(e.startsWith("@")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.metadata.source.toLowerCase().includes(i)}let n=e.toLowerCase();return i=>i.displayName.toLowerCase().includes(n)}function doe(t,e){let n=
|
|
529
|
-
`),"info");return}let u=0;if(await n.ui.custom((p,m,g,h)=>{let f="by-source",x=zA(l,f),y=[...x],w=y.findIndex(F=>F.type==="item");w<0&&(w=0);let P=new Qe;function _(F,N){let H=F+N;for(;H>=0&&H<y.length;){if(y[H]?.type==="item")return H;H+=N}return F}function R(F){let N=uoe(F);if(!N){y=[...x],E();return}let H=new Set,G=new Set;for(let Z of x)Z.type==="item"&&N(Z.item)&&H.add(Z.item);for(let Z of l)for(let de of Z.items)H.has(de)&&G.add(Z);y=[];for(let Z of x)(Z.type==="group"&&G.has(Z.group)||Z.type==="item"&&H.has(Z.item))&&y.push(Z);E()}function L(){x=zA(l,f),R(P.getValue())}function E(){let F=y.findIndex(N=>N.type==="item");w=F>=0?F:0}let W={invalidate(){},render(F){let N=m.bold("Skill Configuration"),H=m.fg("muted"," \xB7 "),G=pt("space","toggle")+H+pt("tab","view")+H+pt("esc","close"),Z=j(G),de=j(N),Te=Math.max(1,F-de-Z);return[X(`${N}${" ".repeat(Te)}${G}`,F,""),m.fg("muted","Filter: name \xB7 /path \xB7 @source")]}},M=15,I={invalidate(){},render(F){let N=[];if(N.push(...P.render(F)),N.push(""),y.length===0)return N.push(m.fg("muted"," No skills found")),N;let H=Math.max(0,Math.min(w-Math.floor(M/2),y.length-M)),G=Math.min(H+M,y.length);for(let pe=H;pe<G;pe++){let Ie=y[pe];if(!Ie)continue;let tt=pe===w;if(Ie.type==="group"){let De=m.fg("accent",m.bold(Ie.group.label));N.push(X(` ${De}`,F,""))}else{let De=tt?"> ":" ",ri=Ie.item.enabled?m.fg("success","[x]"):m.fg("dim","[ ]"),jt=tt?m.bold(Ie.item.displayName):Ie.item.displayName;N.push(X(`${De} ${ri} ${jt}`,F,"..."))}}let Z=y.filter(pe=>pe.type==="item").length,de=y[w]?.type==="item"?y.slice(0,w+1).filter(pe=>pe.type==="item").length:0,Te=ioe[f];return H>0||G<y.length?N.push(m.fg("dim",` ${de}/${Z} ${Te}`)):N.push(m.fg("dim",` ${Te}`)),N}},O=new K;return O.addChild(new U(1)),O.addChild(new V),O.addChild(new U(1)),O.addChild(W),O.addChild(new U(1)),O.addChild(I),O.addChild(new U(1)),O.addChild(new V),{render(F){return O.render(F)},invalidate(){O.invalidate()},handleInput(F){let N=ve();if(N.matches(F,"tui.select.up")){w=_(w,-1),p.requestRender();return}if(N.matches(F,"tui.select.down")){w=_(w,1),p.requestRender();return}if(N.matches(F,"tui.select.pageUp")){let H=Math.max(0,w-M);for(;H<y.length&&y[H]?.type!=="item";)H++;H<y.length&&(w=H),p.requestRender();return}if(N.matches(F,"tui.select.pageDown")){let H=Math.min(y.length-1,w+M);for(;H>=0&&y[H]?.type!=="item";)H--;H>=0&&(w=H),p.requestRender();return}if(N.matches(F,"tui.select.cancel")){h(void 0);return}if(
|
|
528
|
+
message: ${mn.enrichedMessage}`,"info"),mn=null,t.sendMessage({customType:"ss-context",content:"context_checkout complete. A summary of your previous branch was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",display:!1},{triggerTurn:!0}))})}function KA(t){t.registerCommand("s:context",{description:"Show context usage visualization",handler:async(e,n)=>{let i=await n.getContextUsage();if(!i){n.ui.notify("Context usage info not available.","warning");return}let r=n.sessionManager.getBranch(),o=n.getSystemPrompt(),a=t.getActiveTools(),l=t.getAllTools().filter(W=>a.includes(W.name)),d=W=>Math.ceil(W.length/4),u=0,p=0,m=0;for(let W of r)if(W.type==="message"){let M=W.message;if(M.role==="user"){if(typeof M.content=="string")u+=d(M.content);else if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(u+=d(I.text))}else if(M.role==="assistant"){if(typeof M.content=="string")u+=d(M.content);else if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(u+=d(I.text)),I.type==="toolCall"&&(p+=d(JSON.stringify(I)))}else if(M.role==="toolResult"){if(Array.isArray(M.content))for(let I of M.content)I.type==="text"&&(m+=d(I.text))}else M.role==="bashExecution"&&(p+=d(M.command||""))}else(W.type==="branch_summary"||W.type==="compaction")&&(u+=d(W.summary||""));let g=d(o),h=d(JSON.stringify(l)),f=i.tokens,x=i.contextWindow;if(f==null||x==null||i.percent==null){n.ui.notify("Context usage info not available.","warning");return}let y=g+h+u+p+m,w=y>0?f/y:1,P=Math.round(g*w),_=Math.round(h*w),R=Math.round(u*w),L=Math.round(p*w),E=Math.round(m*w);await n.ui.custom((W,M,I,O)=>{let F=new K;F.addChild(new V(ne=>M.fg("accent",ne))),F.addChild(new A(M.fg("accent",M.bold(" Context Usage")),1,0)),F.addChild(new U(1));let N=[{label:"System Prompt",value:P,color:"muted"},{label:"System Tools",value:_,color:"dim"},{label:"Tool Call",value:L+E,color:"success"},{label:"Messages",value:R,color:"accent"}],H=Math.max(0,f-(P+_+R+L+E));H>10&&N.push({label:"Other",value:H,color:"dim"}),N.push({label:"Available",value:Math.max(0,x-f),color:"borderMuted"});let G=10,Z=5,de=G*Z,Te=[];for(N.forEach(ne=>{if(ne.label==="Available")return;let be=Math.round(ne.value/x*de);be===0&&ne.value>0&&(be=1);for(let ye=0;ye<be&&Te.length<de;ye++)Te.push({color:ne.color,filled:!0})});Te.length<de;)Te.push({color:"borderMuted",filled:!1});let pe=[];for(let ne=0;ne<Z;ne++){let be="";for(let ye=0;ye<G;ye++){let nt=Te[ne*G+ye];be+=M.fg(nt.color,nt.filled?"\u25A0 ":"\u25A1 ")}pe.push(be.trimEnd())}let Ie=`${M.fg("text",M.bold("Total Usage".padEnd(16)))} ${M.fg("text",M.bold(Ac(f).padStart(7)))} ${M.fg("text",M.bold(`(${i.percent.toFixed(1).padStart(5)}%)`))}`,tt=N.map(ne=>{let be=ne.label.padEnd(14),ye=Ac(ne.value).padStart(7),nt=(ne.value/x*100).toFixed(1).padStart(5),At=ne.label==="Available"?"\u25A1":"\u25A0";return`${M.fg(ne.color,At)} ${M.fg("text",be)} ${M.fg("accent",ye)} (${nt}%)`}),De=[Ie,"",...tt],ri=20,jt=Math.max(pe.length,De.length);for(let ne=0;ne<jt;ne++){let be=(pe[ne]||"").padEnd(ri),ye=De[ne]||"";F.addChild(new A(` ${be} ${ye}`,1,0))}return F.addChild(new U(1)),F.addChild(new A(M.fg("dim"," Press any key to close"),1,0)),F.addChild(new V(ne=>M.fg("accent",ne))),{render:ne=>F.render(ne),invalidate:()=>F.invalidate(),handleInput:ne=>O(void 0)}},{overlay:!0})}})}import{basename as HA,dirname as VA,join as noe,relative as JA}from"node:path";var Xv=["by-source","a-z","active-first"],ioe={"by-source":"By source","a-z":"A\u2013Z","active-first":"Active first"};function soe(t){let e=Xv.indexOf(t);return Xv[(e+1)%Xv.length]??"by-source"}function roe(t){return t.origin==="package"?`${t.source} (${t.scope})`:t.source==="auto"?t.scope==="user"?"User (~/.sling/agent/)":"Project (.sling/)":t.scope==="user"?"User settings":"Project settings"}function ooe(t){let e=new Map;for(let i of t){let{path:s,enabled:r,metadata:o}=i,a=`${o.origin}:${o.scope}:${o.source}`;e.has(a)||e.set(a,{key:a,label:roe(o),scope:o.scope,origin:o.origin,source:o.source,items:[]});let c=HA(s),l=HA(VA(s)),d=c==="SKILL.md"?l:c.endsWith(".md")?c.replace(/\.md$/,""):c;e.get(a)?.items.push({path:s,enabled:r,metadata:o,displayName:d,groupKey:a})}let n=Array.from(e.values());n.sort((i,s)=>i.origin!==s.origin?i.origin==="package"?-1:1:i.scope!==s.scope?i.scope==="user"?-1:1:i.source.localeCompare(s.source));for(let i of n)i.items.sort((s,r)=>s.displayName.localeCompare(r.displayName));return n}function aoe(t){let e=[];for(let n of t){e.push({type:"group",group:n});for(let i of n.items)e.push({type:"item",item:i})}return e}function coe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function loe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.enabled!==i.enabled?n.enabled?-1:1:n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function zA(t,e){switch(e){case"by-source":return aoe(t);case"a-z":return coe(t);case"active-first":return loe(t)}}function uoe(t){let e=t.trim();if(e.length===0)return;if(e.startsWith("/")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.path.toLowerCase().includes(i)}if(e.startsWith("@")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.metadata.source.toLowerCase().includes(i)}let n=e.toLowerCase();return i=>i.displayName.toLowerCase().includes(n)}function doe(t,e){let n=_e(),i=noe(e,".sling"),s=t.metadata.scope==="project"?i:n;return JA(s,t.path)}function poe(t){let e=t.metadata.baseDir??VA(t.path);return JA(e,t.path)}function QA(t){return t.startsWith("!")||t.startsWith("+")||t.startsWith("-")?t.slice(1):t}function moe(t,e,n,i){let s=t.metadata.scope,o=[...(s==="project"?n.getProjectSettings():n.getGlobalSettings()).skills??[]],a=doe(t,i),c=o.filter(l=>QA(l)!==a);c.push(e?`+${a}`:`-${a}`),s==="project"?n.setProjectSkillPaths(c):n.setSkillPaths(c)}function hoe(t,e,n){let i=t.metadata.scope,r=[...(i==="project"?n.getProjectSettings():n.getGlobalSettings()).packages??[]],o=r.findIndex(p=>(typeof p=="string"?p:p.source)===t.metadata.source);if(o===-1)return;let a=r[o];if(a===void 0)return;typeof a=="string"&&(a={source:a},r[o]=a);let c=[...a.skills??[]],l=poe(t),d=c.filter(p=>QA(p)!==l);d.push(e?`+${l}`:`-${l}`),d.length>0?a.skills=d:delete a.skills,a.extensions!==void 0||a.skills!==void 0||a.prompts!==void 0||a.themes!==void 0||(r[o]=a.source),i==="project"?n.setProjectPackages(r):n.setPackages(r)}function goe(t,e,n,i){t.metadata.origin==="top-level"?moe(t,e,n,i):hoe(t,e,n)}function Zv(t){t.registerCommand("s:skills-manager",{description:"Enable/disable skills",getArgumentCompletions:e=>{let n=[{value:"list",description:"List skills with enabled/disabled state"}],i=(e??"").toLowerCase(),s=n.filter(r=>r.value.startsWith(i)||r.description.toLowerCase().includes(i));return s.length>0?s.map(r=>({value:r.value,label:`${r.value} - ${r.description}`})):null},handler:async(e,n)=>{let i=n.cwd,s=_e(),r=gi.create(i,s),c=(await new Ni({cwd:i,agentDir:s,settingsManager:r}).resolve()).skills;if(c.length===0){n.ui.notify("No skills found.","info");return}let l=ooe(c);if(e.trim().toLowerCase()==="list"||!n.hasUI){let p=[];for(let m of l){p.push(`${m.label}`);for(let g of m.items){let h=g.enabled?"[x]":"[ ]";p.push(` ${h} ${g.displayName}`)}}n.ui.notify(p.join(`
|
|
529
|
+
`),"info");return}let u=0;if(await n.ui.custom((p,m,g,h)=>{let f="by-source",x=zA(l,f),y=[...x],w=y.findIndex(F=>F.type==="item");w<0&&(w=0);let P=new Qe;function _(F,N){let H=F+N;for(;H>=0&&H<y.length;){if(y[H]?.type==="item")return H;H+=N}return F}function R(F){let N=uoe(F);if(!N){y=[...x],E();return}let H=new Set,G=new Set;for(let Z of x)Z.type==="item"&&N(Z.item)&&H.add(Z.item);for(let Z of l)for(let de of Z.items)H.has(de)&&G.add(Z);y=[];for(let Z of x)(Z.type==="group"&&G.has(Z.group)||Z.type==="item"&&H.has(Z.item))&&y.push(Z);E()}function L(){x=zA(l,f),R(P.getValue())}function E(){let F=y.findIndex(N=>N.type==="item");w=F>=0?F:0}let W={invalidate(){},render(F){let N=m.bold("Skill Configuration"),H=m.fg("muted"," \xB7 "),G=pt("space","toggle")+H+pt("tab","view")+H+pt("esc","close"),Z=j(G),de=j(N),Te=Math.max(1,F-de-Z);return[X(`${N}${" ".repeat(Te)}${G}`,F,""),m.fg("muted","Filter: name \xB7 /path \xB7 @source")]}},M=15,I={invalidate(){},render(F){let N=[];if(N.push(...P.render(F)),N.push(""),y.length===0)return N.push(m.fg("muted"," No skills found")),N;let H=Math.max(0,Math.min(w-Math.floor(M/2),y.length-M)),G=Math.min(H+M,y.length);for(let pe=H;pe<G;pe++){let Ie=y[pe];if(!Ie)continue;let tt=pe===w;if(Ie.type==="group"){let De=m.fg("accent",m.bold(Ie.group.label));N.push(X(` ${De}`,F,""))}else{let De=tt?"> ":" ",ri=Ie.item.enabled?m.fg("success","[x]"):m.fg("dim","[ ]"),jt=tt?m.bold(Ie.item.displayName):Ie.item.displayName;N.push(X(`${De} ${ri} ${jt}`,F,"..."))}}let Z=y.filter(pe=>pe.type==="item").length,de=y[w]?.type==="item"?y.slice(0,w+1).filter(pe=>pe.type==="item").length:0,Te=ioe[f];return H>0||G<y.length?N.push(m.fg("dim",` ${de}/${Z} ${Te}`)):N.push(m.fg("dim",` ${Te}`)),N}},O=new K;return O.addChild(new U(1)),O.addChild(new V),O.addChild(new U(1)),O.addChild(W),O.addChild(new U(1)),O.addChild(I),O.addChild(new U(1)),O.addChild(new V),{render(F){return O.render(F)},invalidate(){O.invalidate()},handleInput(F){let N=ve();if(N.matches(F,"tui.select.up")){w=_(w,-1),p.requestRender();return}if(N.matches(F,"tui.select.down")){w=_(w,1),p.requestRender();return}if(N.matches(F,"tui.select.pageUp")){let H=Math.max(0,w-M);for(;H<y.length&&y[H]?.type!=="item";)H++;H<y.length&&(w=H),p.requestRender();return}if(N.matches(F,"tui.select.pageDown")){let H=Math.min(y.length-1,w+M);for(;H>=0&&y[H]?.type!=="item";)H--;H>=0&&(w=H),p.requestRender();return}if(N.matches(F,"tui.select.cancel")){h(void 0);return}if(Ee(F,"ctrl+c")){h(void 0);return}if(Ee(F,"tab")){f=soe(f),L(),p.requestRender();return}if(F===" "||N.matches(F,"tui.select.confirm")){let H=y[w];if(H?.type==="item"){let G=!H.item.enabled;goe(H.item,G,r,i),H.item.enabled=G;for(let Z of l){let de=Z.items.find(Te=>Te.path===H.item.path);de&&(de.enabled=G)}u++,f==="active-first"&&L()}p.requestRender();return}P.handleInput(F),R(P.getValue()),p.requestRender()}}}),u>0){if(await n.ui.confirm("Reload Required",`${u} skill change(s) saved. Reload pi now?`)){await n.reload();return}n.ui.notify("Changes saved to settings. Use /reload to apply.","info")}}})}async function ew(t,e){let n=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot"),i=new Date;return fetch(`${we.getUserActivityUrl()}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||""}`,Accept:"application/json"},body:JSON.stringify({...t,activity_entity_type:"slingcli",activity_entity_id:_r.slingVersion||"dev",activity_startdate:t.activity_startdate?.toISOString()||i.toISOString(),activity_enddate:t.activity_enddate?.toISOString()||i.toISOString(),metadata:t.metadata||{}})}).then(s=>s.json()).then(s=>{Pe("User activity posted successfully, credits used: "+s.credits_used+"/"+s.remainingCredits)}).catch(s=>{Je("Error posting user activity:",s)}),{}}import XA from"node:path";var Gh=null,tw=0,YA=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function nw(t){let e=XA.basename(process.cwd());return t?`\u2B55\uFE0F - ${t} - ${e}`:`\u2B55\uFE0F - ${e}`}function iw(t){Gh&&(clearInterval(Gh),Gh=null),tw=0;let e=t.sessionManager.getSessionName();t.ui.setTitle(nw(e))}function ZA(t){iw(t),Gh=setInterval(()=>{let e=YA[tw%YA.length],n=XA.basename(process.cwd()),i=t.sessionManager.getSessionName(),s=i?`${e} ${nw(i)}`:`${e} ${nw()}`;t.ui.setTitle(s),tw++},80)}var Kh=null;function Go(t){t.hasUI&&t.ui.setWorkingMessage(foe.magenta(Y0[Math.floor(Math.random()*Y0.length)]+"..."))}function boe(t){j0(),nM(t),JI(t,()=>Kh),Zv(t),$b(t),GA(t),KA(t),t.on("resources_discover",async r=>{let o=Oc.join(eO(),".pi","agent"),a=Oc.join(eO(),".agents"),l=[Oc.join(r.cwd,".sling","agent"),a,o],d=[],u=[],p=[];for(let m of l){let g=Oc.join(m,"skills");sw(g)&&d.push(g);let h=Oc.join(m,"prompts");sw(h)&&u.push(h);let f=Oc.join(m,"themes");sw(f)&&p.push(f)}return{skillPaths:d,promptPaths:u,themePaths:p}});let e=new WeakSet;t.on("session_start",async(r,o)=>{o.hasUI&&o.ui.setStatus("ss-credit","0");let a=o.modelRegistry.authStorage;if(!e.has(a)){let c=a.getOAuthProviders.bind(a);a.getOAuthProviders=()=>c().filter(l=>l.id==="slingshot"),e.add(a)}o.hasUI&&o.ui.setHeader(Y1);try{let c=await o.modelRegistry.getApiKeyForProvider("slingshot");c?await zi(c):Pe("session_start: no Slingshot token found in modelRegistry")}catch(c){Pe(`session_start: app-token fetch failed: ${c instanceof Error?c.message:String(c)}`)}});let n=!1;t.registerProvider("slingshot",{baseUrl:we.getApiBaseUrl(),api:"openai-completions",apiKey:"SLINGSHOT_API_KEY",models:z1,headers:{"X-App-Authorization":we.SLINGSHOT_APP_TOKEN_ENV},oauth:{name:"Slingshot",login:Q0,refreshToken:Hp,getApiKey:r=>(Kh=r,t.appendEntry("slingshot_credentials",r),r.access)}}),t.registerCommand("s:settings",{description:"slingshot specific settings",handler:async(r,o)=>{let a=we.getSettings();t.sendMessage({customType:"slingshot-settings",content:JSON.stringify(a,null,2),display:!0})}}),t.registerCommand("s:debug",{description:"Toggle Slingshot debug logging",handler:async(r,o)=>{let a=!ql();if(F1(a),a){let c="Slingshot Debug: ENABLED \u2705",l=D1();l&&(c+=`
|
|
530
530
|
|
|
531
531
|
Log file:
|
|
532
532
|
${l}`),t.sendMessage({customType:"slingshot-debug-status",content:c,display:!0})}else t.sendMessage({customType:"slingshot-debug-status",content:"Slingshot Debug: DISABLED \u274C",display:!0})}}),t.registerCommand("refresh-token",{description:"Manually refresh Slingshot OAuth token",handler:async(r,o)=>{try{let a=o.modelRegistry.authStorage,c=a.get("slingshot");if(!c||c.type!=="oauth"){o.hasUI&&o.ui.notify("No Slingshot OAuth credentials found. Please use /login slingshot first.","error");return}o.hasUI&&o.ui.setStatus("refresh","Refreshing Slingshot token...");let l=await Hp(c);a.set("slingshot",{type:"oauth",...l}),Kh=l,o.hasUI&&(o.ui.setStatus("refresh",void 0),o.ui.notify("Slingshot token refreshed successfully!","info"))}catch(a){if(o.hasUI){o.ui.setStatus("refresh",void 0);let c=a instanceof Error?a.message:String(a);o.ui.notify(`Failed to refresh token: ${c}`,"error")}}}});let i=jp(),s=new Date;t.on("before_agent_start",async(r,o)=>{try{s=new Date,ZA(o),Go(o),Z0(o,"random");let a=await zp(r,o);if(!a?.headers||!a.sageCommonData)return;i=jp(),Vp("agentExecutionStatus",a.headers,a.sageCommonData,{agent_id:i,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Started",agent_correlation_id:i,agent_type:"Temp"});let c=r.systemPrompt;return c.includes("<pi-intercom>")||(c=r.systemPrompt+`
|
|
@@ -539,7 +539,7 @@ Coordinate with other local sling sessions on related codebases. Use \`/skill:pi
|
|
|
539
539
|
**Not when:** Unrelated codebases, trivial questions, or when you can proceed independently.
|
|
540
540
|
|
|
541
541
|
**Principle:** Prefer \`send\` for notifications; \`ask\` only when blocked waiting for input.
|
|
542
|
-
</pi-intercom>`),{systemPrompt:c}}catch(a){ql()&&(
|
|
542
|
+
</pi-intercom>`),{systemPrompt:c}}catch(a){ql()&&(Pe(`CRITICAL ERROR in event handler: ${a?.message||a}`),a?.stack&&Pe(a.stack))}}),t.on("agent_end",async(r,o)=>{try{iw(o);let a=0,c=0,l=0,d=0,u=0;for(let m of o.sessionManager.getEntries())m.type==="message"&&m.message.role==="assistant"&&(a+=m.message.usage.input,c+=m.message.usage.output,l+=m.message.usage.cacheRead,d+=m.message.usage.cacheWrite,u+=m.message.usage.cost.total);ew({activity_type:"slingcli:agent:execute",activity_entity_id:i,activity_entity_type:"coding_agent",total_tokens:a+c,activity_startdate:s,activity_enddate:new Date,credits_used:0,metadata:{correlation_id:i,cost:u}},o).then(m=>{o.hasUI&&(m.credits_used&&o.ui.notify(`Credits used: ${m.credits_used.toFixed(4)}`,"info"),m.remainingCredits&&o.ui.setStatus("ss-credit",`${m.remainingCredits.toFixed(2)}`))});let p=await zp(r,o);if(!p?.headers||!p.sageCommonData)return;Vp("agentExecutionStatus",p.headers,p.sageCommonData,{agent_id:i,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Success",agent_correlation_id:i,agent_type:"Temp",tools_list:[]})}catch(a){t.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),ql()&&(Pe(`CRITICAL ERROR in event handler: ${a?.message||a}`),a?.stack&&Pe(a.stack))}}),t.on("tool_execution_start",async(r,o)=>{Go(o)}),t.on("tool_result",async(r,o)=>{if(Go(o),r.toolName==="write"||r.toolName==="edit")try{let a=await zp(r,o,Kh);if(!a?.headers||!a.sageCommonData||r.isError)return;let c=r.input.path+"",d=c.split(".").pop()||"",u="";r.toolName==="write"?u=r.input.content+"":r.toolName==="edit"&&(u=(r.details?.diff+"").split(`
|
|
543
543
|
`).filter(p=>p.startsWith("+")||p.startsWith("-")).join(`
|
|
544
544
|
`)),Vp(`${r.toolName==="edit"?"insertCode":"createNewFile"}`,a.headers,a.sageCommonData,{programming_language:d,number_of_lines:u.split(`
|
|
545
|
-
`).length+"",message_id:o.sessionManager.getSessionId()+"-"+i,code_block_id:o.sessionManager.getSessionId()+"-"+c})}catch(a){t.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),ql()&&(
|
|
545
|
+
`).length+"",message_id:o.sessionManager.getSessionId()+"-"+i,code_block_id:o.sessionManager.getSessionId()+"-"+c})}catch(a){t.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),ql()&&(Pe(`CRITICAL ERROR in event handler: ${a?.message||a}`),a?.stack&&Pe(a.stack))}}),t.on("tool_execution_end",async(r,o)=>{Go(o)}),t.on("message_start",async(r,o)=>{Go(o)}),t.on("message_update",async(r,o)=>{Go(o)}),t.on("message_end",async(r,o)=>{Go(o)})}export{boe as default};
|