@hyperpuncher/pi-ui 0.42.0 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4334,7 +4334,7 @@ ${n.slice(-Fyr).join(`
4334
4334
  `)}function LF(e){return e.replace(Ski,"")}function FSe(e){if(Cr(e))return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Fyr=4,wki=7,kki,Ski;var tmt=m(()=>{jk();kki=new Set(["fd","find","grep","ls","rg","tree"]);Ski=new RegExp(String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`,"g")});class nmt{load(e,t){let n=new Map,r=e.session.sessionManager.getBranch(),a=e.session.settingsManager?.getShowCacheMissNotices()?Wbr(r,e.session.modelRuntime):void 0;t.replaceMessages(r.flatMap((i)=>{let o=i.type==="message"&&i.message.role==="assistant"?a?.get(i.message):void 0;return this.entry(i,n,o?ISe(o):void 0)}))}entry(e,t,n){let r=new Date(e.timestamp);if(e.type==="message"){if(e.message.role==="assistant")for(let i of Pki(e.message.content))t.set(i.id,{name:i.name,args:i.arguments});if(e.message.role==="toolResult"){let i=t.get(e.message.toolCallId);return t.delete(e.message.toolCallId),[$yr(e.message,r,i)]}let a=this.message(e.message,r);if(n)a.push({role:"notice",...n,timestamp:r});return a}if(e.type==="custom_message"&&e.display)return[{role:"system",text:m7(e.content),timestamp:r}];if(e.type==="compaction")return[{role:"compaction",text:e.summary,timestamp:r,meta:`compacted from ${e.tokensBefore.toLocaleString()} tokens`}];if(e.type==="branch_summary")return[{role:"summary",text:e.summary,timestamp:r}];return[]}message(e,t,n={}){switch(e.role){case"user":{let r=Tki(e.content),{prompt:a,paths:i}=BSe(r);return Bki(a,t,Dki(i,e.content))}case"assistant":{let r=Nki(e.content,t);if(n.includeAssistantError!==!1&&e.stopReason==="error")r.push({role:"system",text:uce(e.errorMessage),timestamp:t,state:"error"});return r}case"toolResult":return[$yr(e,t)];case"bashExecution":return[{role:"tool",text:NSe(e.output),timestamp:t,title:`$ ${e.command}`,titleParts:[{text:`$ ${e.command}`}],meta:e.exitCode===void 0?"cancelled":`exit ${e.exitCode}`,state:e.exitCode===0?"success":"error",format:"output"}];case"custom":return e.display?[{role:"system",text:m7(e.content),timestamp:t}]:[];case"branchSummary":return[{role:"summary",text:e.summary,timestamp:t}];case"compactionSummary":return[{role:"compaction",text:e.summary,timestamp:t,meta:`compacted from ${e.tokensBefore.toLocaleString()} tokens`}]}}}function Bki(e,t,n){let r=c$(e);if(!r){let i={role:"user",text:e,timestamp:t};if(n?.length)i.attachments=n;return[i]}let a=[{role:"skill",text:r.content,timestamp:t,meta:r.name}];if(r.userMessage||n?.length)a.push({role:"user",text:r.userMessage??"",timestamp:t,attachments:n});return a}function Tki(e){return Array.isArray(e)?e.flatMap((t)=>Ra(t)&&t.type==="text"&&Cr(t.text)?[LF(t.text)]:[]).join(`
4335
4335
  `):m7(e)}function Dki(e,t){let n=Array.isArray(t)?t.flatMap((i)=>Ra(i)&&i.type==="image"&&Cr(i.data)&&Cr(i.mimeType)&&/^image\/[a-z0-9.+-]+$/i.test(i.mimeType)?[{data:i.data,mimeType:i.mimeType}]:[]):[],r=0,a=e.map((i)=>{let o=TSe(i),s=Rki(o)?n[r++]:void 0,c={name:o,path:i,mimeType:s?.mimeType??Mki(o)};if(s)c.image=s;return c});for(;r<n.length;r+=1)a.push({name:`Image ${r+1}`,mimeType:n[r].mimeType,image:n[r]});return a.length>0?a:void 0}function Rki(e){return/\.(?:jpe?g|png|gif|webp|bmp)$/i.test(e)}function Mki(e){let t=e.split(".").at(-1)?.toLowerCase(),n=new Map(Object.entries({txt:"text/plain",md:"text/markdown",json:"application/json",pdf:"application/pdf",ogg:"audio/ogg",mp3:"audio/mpeg",wav:"audio/wav"}));return t?n.get(t):void 0}function $yr(e,t,n){let r=Ine(e.toolName,e,{args:n?.args,isError:e.isError});return{role:"tool",text:r.text,timestamp:t,title:n?vne(e.isError?"error":"success",n.name,n.args):e.toolName,titleParts:n?Ene(n.name,n.args):void 0,state:e.isError?"error":"success",format:r.format}}function Pki(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>Ra(t)&&t.type==="toolCall"&&Cr(t.id)&&Cr(t.name)?[{id:t.id,name:t.name,arguments:t.arguments}]:[])}function Nki(e,t){if(!Array.isArray(e))return[{role:"assistant",text:m7(e),timestamp:t}];let n=[],r="",a="";for(let i of e)if(Ra(i)&&i.type==="thinking"&&Cr(i.thinking))a+=`${a?`
4336
4336
 
4337
- `:""}${i.thinking}`;else if(Ra(i)&&i.type==="text"&&Cr(i.text))r+=i.text;if(a.trim())n.push({role:"thought",text:a,timestamp:t});if(r.trim())n.push({role:"assistant",text:LF(r),timestamp:t});return n}var jyr=m(()=>{rF();Qpt();dce();tmt()});class rmt{getRuntime;state;onNavigated;getOwnerToken;navigations=new Map;constructor(e,t,n=()=>{},r=()=>e().session){this.getRuntime=e;this.state=t;this.onNavigated=n;this.getOwnerToken=r}open(){this.cancelNavigation(),this.load()}load(){let e=this.getRuntime().session.sessionManager;this.state.setTreeEntries(Fki(e.getTree(),e.getLeafId(),new Set(e.getBranch().map((t)=>t.id))))}async navigate(e,t={}){let n=this.getRuntime().session,r=this.getOwnerToken();if(this.navigations.has(r))return{status:"busy"};if(!e.trim())return{status:"cancelled"};let a={session:n};if(this.navigations.set(r,a),t.summarize)this.state.setActivityText?.("Summarizing branch...");try{let i=await n.navigateTree(e,{summarize:t.summarize??!1,customInstructions:t.customInstructions});if(i.cancelled||this.getOwnerToken()!==r)return{status:"cancelled"};return this.onNavigated(),this.load(),{status:"success",editorText:i.editorText}}finally{if(this.navigations.get(r)===a){if(t.summarize)this.state.setActivityText?.(void 0);this.navigations.delete(r)}}}cancelNavigation(){this.navigations.get(this.getOwnerToken())?.session.abortBranchSummary()}}function Fki(e,t,n){let r=[],a=Oki(e),i=new Map,o=(l)=>{let d=l.entry.id===t||l.children.some(o);return i.set(l,d),d};e.forEach(o);let s=e.length>1,u=Uyr(e,i).toReversed().map((l,d)=>({node:l,indent:s?1:0,justBranched:s,showConnector:s,isLast:d===0,gutters:[]}));while(u.length>0){let{node:l,indent:d,justBranched:p,showConnector:g,isLast:A,gutters:f}=u.pop();if(Qki(l,t))r.push({id:l.entry.id,parentId:l.entry.parentId,prefix:Lki(d,g,A,f),label:l.label,active:l.entry.id===t,inPath:n.has(l.entry.id),...$ki(l,a)});let h=Uyr(l.children,i),b=h.length>1,y=b?d+1:p&&d>0?d+1:d,w=[...f];if(g&&d>0)w[d-1]=!A;for(let _=h.length-1;_>=0;_-=1)u.push({node:h[_],indent:y,justBranched:b,showConnector:b,isLast:_===h.length-1,gutters:w})}return r}function Uyr(e,t){return[...e].sort((n,r)=>Number(t.get(r))-Number(t.get(n)))}function Lki(e,t,n,r){if(e===0&&!t)return"";let a=[];for(let i=0;i<e;i+=1)if(i===e-1&&t)a.push(n?"\u2514\u2500 ":"\u251C\u2500 ");else a.push(r[i]?"\u2502 ":" ");return a.join("")}function Oki(e){let t=new Map,n=[...e];while(n.length>0){let r=n.pop();if(n.push(...r.children),r.entry.type!=="message")continue;let a=r.entry.message;if(a.role!=="assistant"||!Array.isArray(a.content))continue;for(let i of a.content){if(!Ra(i)||i.type!=="toolCall")continue;if(!Cr(i.id)||!Cr(i.name))continue;t.set(i.id,{name:i.name,arguments:Ra(i.arguments)?i.arguments:{}})}}return t}function Qki(e,t){let n=e.entry;if(n.type==="label"||n.type==="custom"||n.type==="model_change"||n.type==="thinking_level_change"||n.type==="session_info")return!1;if(n.type==="message"&&n.message.role==="assistant"&&n.id!==t&&!g7(LSe(n.message.content))&&(n.message.stopReason==="stop"||n.message.stopReason==="toolUse"||!n.message.stopReason))return!1;return!0}function $ki(e,t){let n=e.entry,r=new Date(n.timestamp),a={meta:NR(r),metaTimestamp:r.toISOString()};if(n.type==="message"){let i=n.message;if(i.role==="user")return{kind:"user",role:"user",text:g7(LSe(i.content)),...a};if(i.role==="assistant"){let o=g7(LSe(i.content)),s=i.stopReason==="aborted"?"(aborted)":i.errorMessage||"(no content)";return{kind:"assistant",role:"assistant",text:o||s,...a}}if(i.role==="toolResult"){let o=t.get(i.toolCallId);return{kind:"tool",role:o?.name??i.toolName??"tool",text:o?jki(o.name,o.arguments):"",...a}}if(i.role==="bashExecution")return{kind:"tool",role:"bash",text:g7(i.command),...a};return{kind:"other",role:i.role,text:"",...a}}if(n.type==="custom_message")return{kind:"other",role:n.customType,text:g7(LSe(n.content)),...a};if(n.type==="compaction")return{kind:"other",role:"compaction",text:`${Math.round(n.tokensBefore/1000)}k tokens`,...a};if(n.type==="branch_summary")return{kind:"summary",role:"summary",text:g7(n.summary),...a};if(n.type==="model_change")return{kind:"other",role:"model",text:n.modelId,...a};if(n.type==="thinking_level_change")return{kind:"other",role:"thinking",text:n.thinkingLevel,...a};if(n.type==="custom")return{kind:"other",role:"custom",text:n.customType,...a};if(n.type==="label")return{kind:"other",role:"label",text:n.label??"(cleared)",...a};return{kind:"other",role:"title",text:n.name??"(empty)",...a}}function jki(e,t){let n=String(t.path||t.file_path||"");switch(e){case"read":{let r=kf(t.offset)?t.offset:void 0,a=kf(t.limit)?t.limit:void 0,i=r!==void 0||a!==void 0?`:${r??1}${a!==void 0?`-${(r??1)+a-1}`:""}`:"";return`${n}${i}`}case"write":case"edit":return n;case"bash":{let r=String(t.command||"").replace(/[\n\t]+/g," ").trim();return`${r.slice(0,80)}${r.length>80?"...":""}`}case"grep":return`/${String(t.pattern||"")}/ in ${n||"."}`;case"find":return`${String(t.pattern||"")} in ${n||"."}`;case"ls":return n||".";default:{let r=JSON.stringify(t);return`${r.slice(0,60)}${r.length>60?"...":""}`}}}function LSe(e){if(Cr(e))return e;if(!Array.isArray(e))return"";return e.filter((t)=>Ra(t)&&t.type==="text"&&Cr(t.text)).map((t)=>t.text).join(" ")}function g7(e){return e.replace(/[\n\t]+/g," ").replace(/\s+/g," ").trim().slice(0,240)}var Gyr=m(()=>{yG()});function OSe(e,t){return s7(e.modelRuntime,()=>Gki(e,t))}async function Gki(e,t){let n=e.model;if(!n)return;let r=await e.modelRuntime.getAuth(n);if(!r)return;let a=new Headers;for(let[s,c]of Object.entries(r.auth.headers??{}))if(c!==null)a.set(s,c);if(!a.has("authorization")){if(!r.auth.apiKey)return;a.set("Authorization",`Bearer ${r.auth.apiKey}`)}if(!a.has("user-agent"))a.set("User-Agent","pi-ui");let i=new AbortController,o=setTimeout(()=>i.abort(),Uki);try{let s=await fetch(t,{headers:a,signal:i.signal});return s.ok?await s.json():void 0}finally{clearTimeout(o)}}var Uki=15000,amt=60000;var QSe=m(()=>{vSe()});function $Se(e){let t=Math.min(100,Math.max(0,e));return Math.round(100-t)}function jSe(e){if(!e)return"?";let t=Math.max(0,e-Date.now())/60000;if(t<60)return`${Math.round(t)}m`;let n=t/60;if(n<24)return`${qyr(n)}h`;return`${qyr(n/24)}d`}function qyr(e){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}function smt(e){return e?.provider===qki}async function Wyr(e){let t=await OSe(e,Hki);return t===void 0?void 0:Kki(t)}function Kyr(e){let t=[];if(e.primary)t.push(Hyr(e.primary,"5 hours"));if(e.secondary)t.push(Hyr(e.secondary,"Weekly"));return t}function Hyr(e,t){return{label:Yki(e.windowSeconds)??t,usedPercent:e.usedPercent,remainingPercent:$Se(e.usedPercent),resetText:jSe(e.resetsAt===void 0?void 0:e.resetsAt*1000)}}function Kki(e){if(!omt.Check(e))return;let t=e.rate_limit;if(!omt.Check(t))return;let n=zyr(t.primary_window),r=zyr(t.secondary_window);return n||r?{primary:n,secondary:r}:void 0}function zyr(e){if(!omt.Check(e))return;let t=imt(e.used_percent);if(t===void 0)return;return{usedPercent:t,windowSeconds:imt(e.limit_window_seconds),resetsAt:imt(e.reset_at)}}function imt(e){if(!Wki.Check(e))return;return Vki(e)}function Vki(e){let t=Number(e);return Number.isFinite(t)?t:void 0}function Yki(e){if(!e||e<=0)return;if(e===604800)return"Weekly";if(e>=2419200&&e<=2678400)return"Monthly";if(e===86400)return"Daily";if(e%3600===0){let t=e/3600;return`${t} ${t===1?"hour":"hours"}`}if(e%60===0){let t=e/60;return`${t} ${t===1?"minute":"minutes"}`}return}var qki="openai-codex",Hki="https://chatgpt.com/backend-api/wham/usage",zki,Wki,omt;var Vyr=m(()=>{hk();Sk();HOe();QSe();zki=Jt.Union([Jt.Number(),Jt.String({pattern:"\\S"})]),Wki=Gc(zki),omt=Gc(jle)});function pmt(e){return e?.provider===Zki}async function Yyr(e){let t=await OSe(e,Jki);return t===void 0?void 0:a_i(t)}function a_i(e){if(!n_i.Check(e))return;let t={rolling:lmt(e.usage.rolling),weekly:lmt(e.usage.weekly),monthly:lmt(e.usage.monthly)};return t.rolling||t.weekly||t.monthly?t:void 0}function Zyr(e){let t=[];if(e.rolling)t.push(umt(e.rolling,"5 hours"));if(e.weekly)t.push(umt(e.weekly,"Weekly"));if(e.monthly)t.push(umt(e.monthly,"Monthly"));return t}function lmt(e){if(!e)return;let t=i_i(e.percent);if(t===void 0)return;return{usedPercent:t,resetsAt:o_i(e.resetsAt)}}function umt(e,t){return{label:t,usedPercent:e.usedPercent,remainingPercent:$Se(e.usedPercent),resetText:jSe(e.resetsAt)}}function i_i(e){let t=Number(e);return Number.isFinite(t)?t:void 0}function o_i(e){if(e===void 0)return;if(r_i.Check(e)){let t=Date.parse(e);return Number.isFinite(t)?t:void 0}return e<10000000000?e*1000:e}var Zki="opencode-go",Jki="https://opencode.ai/zen/go/v1/usage",dmt,Xki,e_i,cmt,t_i,n_i,r_i;var Jyr=m(()=>{hk();Sk();QSe();dmt=Jt.String({pattern:"\\S"}),Xki=Jt.Union([Jt.Number(),dmt]),e_i=Jt.Union([Jt.Number(),dmt]),cmt=Jt.Object({percent:Xki,resetsAt:Jt.Optional(e_i)}),t_i=Jt.Object({usage:Jt.Object({rolling:Jt.Optional(cmt),weekly:Jt.Optional(cmt),monthly:Jt.Optional(cmt)})}),n_i=Gc(t_i),r_i=Gc(dmt)});function s_i(e,t){return e.generation===t.generation&&e.runtime===t.runtime&&e.session===t.session&&e.provider===t.model?.provider&&e.modelId===t.model?.id}class mmt{generation=0;active;begin(e,t,n){this.generation+=1;let r={generation:this.generation,runtime:e,session:t,provider:n?.provider,modelId:n?.id};return this.active=r,r}invalidate(){this.generation+=1,this.active=void 0}owns(e,t,n,r){return this.active===e&&s_i(e,{generation:this.generation,runtime:t,session:n,model:r})}release(e,t,n,r){if(!this.owns(e,t,n,r))return!1;return this.active=void 0,!0}get loading(){return this.active!==void 0}}class gmt{getRuntime;state;fetchCodex;fetchOpenCodeGo;codexStatus="";codexUsage;codexFetchedAt=0;opencodeGoStatus="";opencodeGoUsage;opencodeGoFetchedAt=0;requests=new mmt;timer;constructor(e,t,n=Wyr,r=Yyr){this.getRuntime=e;this.state=t;this.fetchCodex=n;this.fetchOpenCodeGo=r}sync(){let e=this.getRuntime().session,t=smt(e.model),n=pmt(e.model),r=e.getSessionStats();this.state.setUsage(c_i(r,{cacheHitPercent:l_i(r),limits:t?Xyr("Codex limits",this.codexStatus,this.codexUsage?Kyr(this.codexUsage):void 0):n?Xyr("OpenCode Go usage",this.opencodeGoStatus,this.opencodeGoUsage?Zyr(this.opencodeGoUsage):void 0):void 0}))}suspend(){this.invalidate()}refresh(e=!1){let t=this.getRuntime(),n=t.session,r=u_i(n.model);if(!r){this.suspend(),this.sync();return}if(this.requests.loading||!e&&Date.now()-this.fetchedAt(r)<amt)return;let a=this.requests.begin(t,n,n.model);if(!this.hasUsageState(r))this.setUsageStatus(r,"loading"),this.sync();this.fetchProviderUsage(r,n).then((i)=>{if(!this.owns(a))return;this.setUsageResult(i,i.usage?"":"unavailable"),this.sync()}).catch((i)=>{if(!this.owns(a))return;console.warn(`Failed to fetch ${r} usage`,i),this.setUsageResult({provider:r,usage:void 0},"unavailable"),this.sync()}).finally(()=>{let i=this.getRuntime();if(!this.requests.release(a,i,i.session,i.session.model))return;this.schedule()})}dispose(){this.suspend()}fetchProviderUsage(e,t){return e==="codex"?this.fetchCodex(t).then((n)=>({provider:e,usage:n})):this.fetchOpenCodeGo(t).then((n)=>({provider:e,usage:n}))}hasUsageState(e){return e==="codex"?this.codexFetchedAt>0||!!this.codexStatus:this.opencodeGoFetchedAt>0||!!this.opencodeGoStatus}fetchedAt(e){return e==="codex"?this.codexFetchedAt:this.opencodeGoFetchedAt}setUsageStatus(e,t){if(e==="codex")this.codexStatus=t;else this.opencodeGoStatus=t}setUsageResult(e,t){if(e.provider==="codex"){this.codexStatus=t,this.codexUsage=e.usage,this.codexFetchedAt=Date.now();return}this.opencodeGoStatus=t,this.opencodeGoUsage=e.usage,this.opencodeGoFetchedAt=Date.now()}owns(e){let t=this.getRuntime();return this.requests.owns(e,t,t.session,t.session.model)}invalidate(){if(this.requests.invalidate(),this.timer)clearTimeout(this.timer);this.timer=void 0}schedule(){if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=void 0,this.refresh(!0)},amt),this.timer.unref?.()}}function c_i(e,t={}){let n=d_i(e.cost);if(e.contextUsage)return{text:`${n} \u2022 ${p_i(e.contextUsage.percent)}/${MS(e.contextUsage.contextWindow)}`,costText:n,contextPercent:e.contextUsage.percent??void 0,contextTokens:e.contextUsage.tokens??void 0,contextWindow:e.contextUsage.contextWindow,cacheHitPercent:t.cacheHitPercent,limits:t.limits};return{text:`${n} \u2022 ${MS(e.tokens.total)} tokens`,costText:n,cacheHitPercent:t.cacheHitPercent,limits:t.limits}}function l_i(e){let{input:t,cacheRead:n,cacheWrite:r}=e.tokens,a=t+n+r;return a>0?n/a*100:void 0}function Xyr(e,t,n){if(!t&&!n?.length)return;return{label:e,status:n?.length?void 0:t,windows:n??[]}}function u_i(e){if(smt(e))return"codex";if(pmt(e))return"opencode-go";return}function d_i(e){if(e<1)return`$${e.toFixed(3)}`;if(e<100)return`$${e.toFixed(1)}`;return`$${Math.round(e)}`}function p_i(e){return e===null?"?":`${e.toFixed(1)}%`}var e0r=m(()=>{Vyr();Jyr();QSe()});class A7{runtime;state;runtimeFactory;preparedSessions;activationOptions;unsubscribe;tools=vyr();prompts;auth;transitionController;backgroundSessions=new Opt;catalog;llama;models;usage;extensionUi;transcript=new nmt;tree;foregroundGeneration;foregroundObservedRunning;sharing=!1;resetChatOnInvalidation=!1;disposal;initialCatalogLoad;lastForcedModelRefreshAt;dependencies;autoTitlesInFlight=new Set;constructor(e,t,n,r,a){this.runtime=e;this.state=t;this.runtimeFactory=n;this.preparedSessions=r;this.activationOptions=a;this.dependencies=a.dependencies??t0r,this.extensionUi=new $pt(t),this.foregroundGeneration=this.backgroundSessions.allocateGeneration(),this.foregroundObservedRunning=e.session.isStreaming,this.models=new qpt(()=>this.runtime,t,()=>this.afterModelChange()),this.llama=new Upt(()=>this.runtime,t,()=>this.syncModels()),this.usage=new gmt(()=>this.runtime,t),this.tree=new rmt(()=>this.runtime,t,()=>this.loadCurrentSessionMessages(),()=>this.foregroundGeneration),this.catalog=new Cne(t,{agentDir:this.dependencies.getAgentDir(),backgroundStatuses:()=>new Map([...this.backgroundSessions.entries()].map(([i,o])=>[i,o.status])),watch:this.dependencies.watchSessionCatalog}),this.prompts=new Hpt((i)=>{if(i===this.runtime)return this.state;for(let o of this.backgroundSessions.values())if(o.runtime===i)return o.state}),this.auth=new Lpt(()=>this.runtime,t,()=>this.models.sync()),this.transitionController=a.transitionController??new cU((i)=>t.setSessionTransition(i))}static async create(e,t=OG(),n={}){let r=await A7.prepare(e,t,n);return r.activate(),r}static async prepare(e,t=OG(),n={}){let r=n.dependencies??t0r,a=r.prepareSessions(),i=async({cwd:s,sessionManager:c,sessionStartEvent:u})=>{let l=await oi.measure("runtimeServicesCreate",()=>kF({cwd:s,resourceLoaderOptions:{extensionFactories:m_i}}));Lbr(l.modelRuntime,l.settingsManager.getGlobalSettings().httpProxy);let d=await s7(l.modelRuntime,()=>l.modelRuntime.getAvailable()),p=oi.measureSync("scopedModelResolution",()=>oyr(l.settingsManager.getEnabledModels()??[],d)),g=l.resourceLoader.getExtensions().extensions.some((f)=>f.tools.has("read"));return{...await oi.measure("runtimeSessionCreate",()=>_F({services:l,sessionManager:c,sessionStartEvent:u,scopedModels:p,customTools:g?void 0:[dyr(s)]})),services:l,diagnostics:l.diagnostics}},o=await r.createRuntime(i,{cwd:t,agentDir:r.getAgentDir(),sessionManager:r.createSessionManager(t)});try{let s=new A7(o,e,i,a,n);return s.bindRuntimeCallbacks(o),await s.bindSessionExtensions(),s}catch(s){throw await o.dispose(),s}}activate(){this.bindSessionState({syncSessions:!1}),this.initialCatalogLoad=this.loadInitialCatalog(),this.catalog.activate()}async prompt(e,t={}){let n=e.trim();if(!n)return!1;if(n==="/tree")return this.openTree(),!0;if(n==="/login"||n.startsWith("/login "))return this.openLogin(n.startsWith("/login ")?n.slice(7).trim():void 0),!0;if(n==="/logout")return this.openLogout(),!0;if(n==="/llama")return this.openLlama(),!0;if(n==="/compact"||n.startsWith("/compact ")){let a=n.startsWith("/compact ")?n.slice(9).trim():void 0;return this.compact(a),!0}if(n==="/share")return this.share(),!0;if(n==="/reload")return this.reload(),!0;let r=this.runtime;if(r.session.isCompacting)return this.prompts.queueAfterCompaction(r,n,t.streamingBehavior??"steer",t.images),!0;return await this.prompts.submit(r,n,t)}async abort(){this.tree.cancelNavigation(),await this.runtime.session.abort(),this.prompts.clear(this.runtime),this.foregroundObservedRunning=!1,this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),this.loadCurrentSessionMessages(),this.usage.sync();let e=this.runtime.session.sessionManager.getSessionFile();if(e)await this.catalog.refreshPath(e)}async abortBackgroundSession(e){let t=this.backgroundSessions.get(e);if(t?.status!=="running")return!1;return await t.runtime.session.abort(),t.status="completed",t.observedRunning=!1,this.catalog.mergeCurrentStatuses(),await this.catalog.refreshPath(e),!0}restoreQueuedMessages(){return this.prompts.restore(this.runtime)}async removeQueuedMessage(e,t){return await this.prompts.remove(this.runtime,e,t)}async newSession(){return await this.transitionController.run("New session",()=>this.createNewSession(),{overlay:!1})}async createNewSession(){let e=this.runtime.session,t=e.sessionManager.isPersisted();if(this.isCurrentRuntimeActive()||!t){let r=e.sessionManager.getCwd();await this.leaveCurrentRuntimeForReplacement(),this.state.resetChat();let a=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:r,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createSessionManager(r),sessionStartEvent:{type:"session_start",reason:"new"}});this.adoptRuntime(a)}else{this.resetChatOnInvalidation=!0;let r;try{r=await this.runtime.newSession()}finally{this.resetChatOnInvalidation=!1}if(r.cancelled)return!1;this.adoptRuntime(this.runtime)}return await this.bindSession({refreshSessions:!0}),!0}async newTemporarySession(){return await this.transitionController.run("New temporary session",()=>this.createNewTemporarySession(),{overlay:!1})}async createNewTemporarySession(){let e=this.runtime.session.sessionManager.getSessionFile(),t=this.runtime.session.sessionManager.getCwd();await this.leaveCurrentRuntimeForReplacement(),this.state.resetChat();let n=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:t,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createMemorySessionManager(t),sessionStartEvent:{type:"session_start",reason:"new",previousSessionFile:e}});return this.adoptRuntime(n),await this.bindSession(),!0}async listSessions(){await this.initialCatalogLoad,this.usage.sync()}async renameSession(e,t){let n=t.replace(/[\r\n]+/g," ").trim();if(!n)return!1;try{let r=this.dependencies.openSessionManager(e),a=r.getSessionFile();if(!a)return!1;let i=this.runtime.session;if(i.sessionManager.getSessionFile()===a)i.setSessionName(n);else{let o=this.backgroundSessions.get(a);if(o)o.runtime.session.setSessionName(n);else r.appendSessionInfo(n)}return await this.catalog.refreshPath(a),!0}catch(r){return this.state.appendMessage("system",`Failed to rename session: ${im(r)}`),!1}}async deleteSession(e){let t=this.dependencies.openSessionManager(e).getSessionFile();if(!t)return!1;let n=t===this.runtime.session.sessionManager.getSessionFile();if(n&&this.isCurrentRuntimeActive())return this.state.appendMessage("system","Cannot delete the current session while it is running."),!1;if(this.backgroundSessions.get(t)?.status==="running")return this.state.appendMessage("system","Cannot delete a running background session."),!1;try{if(n){if((await this.transitionController.run("Delete current session",()=>this.createNewSession())).status!=="success")return!1}await this.dependencies.moveToTrash(t);let r=this.backgroundSessions.get(t);if(r)this.unsubscribeBackgroundSession(r),await r.runtime.dispose(),this.backgroundSessions.delete(t);return this.state.removeSession(t),await this.refreshSessions(),!0}catch(r){return this.state.appendMessage("system",`Failed to delete session: ${im(r)}`),!1}}getWorkspacePath(){return this.runtime.session.sessionManager.getCwd()}async openWorkspace(e){if(e===this.getWorkspacePath())return!0;let t=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:e,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createSessionManager(e)});try{await t.session.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(()=>t===this.runtime)})}catch(r){throw await t.dispose(),r}let n=this.currentRuntimeLeaveAction();try{await this.leaveCurrentRuntimeForReplacement(n)}catch(r){if(n!=="dispose")throw r;console.error("Failed to dispose previous workspace runtime",r)}return this.adoptRuntime(t),this.state.resetChat({preserveEmptyHint:!0}),this.bindSessionState(),!0}async forkSessionToWorkspace(e){let t=this.runtime.session.sessionManager.getSessionFile();if(!t)return this.state.appendMessage("notice","Temporary sessions cannot be forked to another workspace."),{status:"cancelled"};return await this.transitionController.run(`Fork to ${Fh(e)}`,async()=>{let n=this.dependencies.forkSessionManager(t,e).getSessionFile();return n?await this.resumeSessionTransition(n):!1},{overlay:!1})}async resumeSession(e){if(e===this.runtime.session.sessionManager.getSessionFile())return{status:"success"};return await this.transitionController.run(e,async(t)=>{let n=oi.startSessionTransition(t);try{let r=await oi.runInTransition(n,()=>this.resumeSessionTransition(e,n));if(r)oi.markSessionTransitionComplete(n);else oi.cancelSessionTransition(n);return r}catch(r){throw oi.cancelSessionTransition(n),r}},{overlay:!1})}async resumeSessionTransition(e,t){let n=this.runtime.session.isStreaming,r=this.runtime.session.sessionManager.isPersisted();oi.recordOwnershipDiagnostics({sourceGeneration:this.foregroundGeneration,sourceSdkStreaming:n,sourceObservedRunning:this.foregroundObservedRunning,sourcePersisted:r,sourceLocationBefore:"foreground",ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t);let a=await Dyr(e,{state:()=>({streaming:n,observedRunning:this.foregroundObservedRunning,persisted:r}),findBackground:(i)=>{let o=this.backgroundSessions.get(i);return oi.recordOwnershipDiagnostics({targetBackgroundLookup:o?"hit":"miss",targetLocationBefore:o?o.status==="running"?"background-running":"background-completed":"disposed"},t),o},activateBackground:async(i,o)=>{let s=this.backgroundSessions.beginActivation(i);if(!s||s.runtime!==o)throw new c7;let c=this.currentRuntimeLeaveAction();oi.recordOwnershipDiagnostics({leaveAction:c},t);try{await oi.measure("backgroundActivation",()=>this.activateRuntime(o),t),s.commit(),oi.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(c),targetLocationAfter:"foreground"},t)}catch(u){throw s.rollback(),u}},openSession:(i)=>{let o=oi.measureSync("sessionManagerOpen",()=>this.dependencies.openSessionManager(i),t);return oi.recordSessionOpen(t),o},replaceRuntime:async(i,o)=>{oi.recordOwnershipDiagnostics({leaveAction:o},t),await this.leaveCurrentRuntimeForReplacement(o);let s=await oi.measure("runtimeSwitchCreate",()=>this.dependencies.createRuntime(this.runtimeFactory,{cwd:i.getCwd(),agentDir:this.dependencies.getAgentDir(),sessionManager:i}),t);this.adoptRuntime(s),await oi.measure("runtimeRebind",()=>this.bindSession(),t),this.loadCurrentSessionMessages(),oi.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(o),targetLocationAfter:"foreground"},t)},switchSession:async(i)=>{oi.recordOwnershipDiagnostics({leaveAction:"dispose"},t);let o=await oi.measure("runtimeSwitchCreate",()=>this.runtime.switchSession(i),t);if(!o.cancelled)oi.recordSessionOpen(t),this.adoptRuntime(this.runtime),oi.recordOwnershipDiagnostics({sourceLocationAfter:"disposed",targetLocationAfter:"foreground"},t);return o}});return oi.recordOwnershipDiagnostics({ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t),a}openTree(){return this.tree.open(),this.state.openTreeDialog(),!0}async navigateTree(e,t={}){return await this.tree.navigate(e,t)}async setThinkingLevel(e){return this.models.setThinking(e)}cycleThinkingLevel(e="forward"){return this.models.cycleThinking(e)}toggleThinkingBlockVisibility(){let e=this.runtime.session.settingsManager;if(!e)return!1;let t=!e.getHideThinkingBlock();return e.setHideThinkingBlock(t),this.state.setThinkingHidden(t),!0}async compact(e){try{return await this.runtime.session.compact(e),this.loadCurrentSessionMessages(),!0}catch{return!1}}async reload(){let e=this.runtime,t=e.session;if(t.isStreaming)return this.state.appendMessage("notice","Wait for the current response to finish before reloading."),!1;if(t.isCompacting)return this.state.appendMessage("notice","Wait for compaction to finish before reloading."),!1;this.state.setActivityText("Reloading...");try{if(await t.reload(),e!==this.runtime)return!1;return this.unbindSession(),this.bindSessionState(),this.loadCurrentSessionMessages(),this.state.appendMessage("system","Reloaded extensions, skills, prompts, and context files."),!0}catch(n){if(e===this.runtime)this.state.appendMessage("notice",`Reload failed: ${im(n)}`);return!1}finally{if(e===this.runtime)this.state.setActivityText(void 0)}}async share(){if(this.sharing){this.state.appendMessage("notice","A session share is already in progress.");return}this.sharing=!0;let e=this.foregroundGeneration;this.state.setActivityText("Creating share...");try{let t=await this.dependencies.shareSession(this.runtime.session);if(e!==this.foregroundGeneration)return;this.state.appendMessage("system",`Share URL: ${t.shareUrl}
4337
+ `:""}${i.thinking}`;else if(Ra(i)&&i.type==="text"&&Cr(i.text))r+=i.text;if(a.trim())n.push({role:"thought",text:a,timestamp:t});if(r.trim())n.push({role:"assistant",text:LF(r),timestamp:t});return n}var jyr=m(()=>{rF();Qpt();dce();tmt()});class rmt{getRuntime;state;onNavigated;getOwnerToken;navigations=new Map;constructor(e,t,n=()=>{},r=()=>e().session){this.getRuntime=e;this.state=t;this.onNavigated=n;this.getOwnerToken=r}open(){this.cancelNavigation(),this.load()}load(){let e=this.getRuntime().session.sessionManager;this.state.setTreeEntries(Fki(e.getTree(),e.getLeafId(),new Set(e.getBranch().map((t)=>t.id))))}async navigate(e,t={}){let n=this.getRuntime().session,r=this.getOwnerToken();if(this.navigations.has(r))return{status:"busy"};if(!e.trim())return{status:"cancelled"};let a={session:n};if(this.navigations.set(r,a),t.summarize)this.state.setActivityText?.("Summarizing branch...");try{let i=await n.navigateTree(e,{summarize:t.summarize??!1,customInstructions:t.customInstructions});if(i.cancelled||this.getOwnerToken()!==r)return{status:"cancelled"};return this.onNavigated(),this.load(),{status:"success",editorText:i.editorText}}finally{if(this.navigations.get(r)===a){if(t.summarize)this.state.setActivityText?.(void 0);this.navigations.delete(r)}}}cancelNavigation(){this.navigations.get(this.getOwnerToken())?.session.abortBranchSummary()}}function Fki(e,t,n){let r=[],a=Oki(e),i=new Map,o=(l)=>{let d=l.entry.id===t||l.children.some(o);return i.set(l,d),d};e.forEach(o);let s=e.length>1,u=Uyr(e,i).toReversed().map((l,d)=>({node:l,indent:s?1:0,justBranched:s,showConnector:s,isLast:d===0,gutters:[]}));while(u.length>0){let{node:l,indent:d,justBranched:p,showConnector:g,isLast:A,gutters:f}=u.pop();if(Qki(l,t))r.push({id:l.entry.id,parentId:l.entry.parentId,prefix:Lki(d,g,A,f),label:l.label,active:l.entry.id===t,inPath:n.has(l.entry.id),...$ki(l,a)});let h=Uyr(l.children,i),b=h.length>1,y=b?d+1:p&&d>0?d+1:d,w=[...f];if(g&&d>0)w[d-1]=!A;for(let _=h.length-1;_>=0;_-=1)u.push({node:h[_],indent:y,justBranched:b,showConnector:b,isLast:_===h.length-1,gutters:w})}return r}function Uyr(e,t){return[...e].sort((n,r)=>Number(t.get(r))-Number(t.get(n)))}function Lki(e,t,n,r){if(e===0&&!t)return"";let a=[];for(let i=0;i<e;i+=1)if(i===e-1&&t)a.push(n?"\u2514\u2500 ":"\u251C\u2500 ");else a.push(r[i]?"\u2502 ":" ");return a.join("")}function Oki(e){let t=new Map,n=[...e];while(n.length>0){let r=n.pop();if(n.push(...r.children),r.entry.type!=="message")continue;let a=r.entry.message;if(a.role!=="assistant"||!Array.isArray(a.content))continue;for(let i of a.content){if(!Ra(i)||i.type!=="toolCall")continue;if(!Cr(i.id)||!Cr(i.name))continue;t.set(i.id,{name:i.name,arguments:Ra(i.arguments)?i.arguments:{}})}}return t}function Qki(e,t){let n=e.entry;if(n.type==="label"||n.type==="custom"||n.type==="model_change"||n.type==="thinking_level_change"||n.type==="session_info")return!1;if(n.type==="message"&&n.message.role==="assistant"&&n.id!==t&&!g7(LSe(n.message.content))&&(n.message.stopReason==="stop"||n.message.stopReason==="toolUse"||!n.message.stopReason))return!1;return!0}function $ki(e,t){let n=e.entry,r=new Date(n.timestamp),a={meta:NR(r),metaTimestamp:r.toISOString()};if(n.type==="message"){let i=n.message;if(i.role==="user")return{kind:"user",role:"user",text:g7(LSe(i.content)),...a};if(i.role==="assistant"){let o=g7(LSe(i.content)),s=i.stopReason==="aborted"?"(aborted)":i.errorMessage||"(no content)";return{kind:"assistant",role:"assistant",text:o||s,...a}}if(i.role==="toolResult"){let o=t.get(i.toolCallId);return{kind:"tool",role:o?.name??i.toolName??"tool",text:o?jki(o.name,o.arguments):"",...a}}if(i.role==="bashExecution")return{kind:"tool",role:"bash",text:g7(i.command),...a};return{kind:"other",role:i.role,text:"",...a}}if(n.type==="custom_message")return{kind:"other",role:n.customType,text:g7(LSe(n.content)),...a};if(n.type==="compaction")return{kind:"other",role:"compaction",text:`${Math.round(n.tokensBefore/1000)}k tokens`,...a};if(n.type==="branch_summary")return{kind:"summary",role:"summary",text:g7(n.summary),...a};if(n.type==="model_change")return{kind:"other",role:"model",text:n.modelId,...a};if(n.type==="thinking_level_change")return{kind:"other",role:"thinking",text:n.thinkingLevel,...a};if(n.type==="custom")return{kind:"other",role:"custom",text:n.customType,...a};if(n.type==="label")return{kind:"other",role:"label",text:n.label??"(cleared)",...a};return{kind:"other",role:"title",text:n.name??"(empty)",...a}}function jki(e,t){let n=String(t.path||t.file_path||"");switch(e){case"read":{let r=kf(t.offset)?t.offset:void 0,a=kf(t.limit)?t.limit:void 0,i=r!==void 0||a!==void 0?`:${r??1}${a!==void 0?`-${(r??1)+a-1}`:""}`:"";return`${n}${i}`}case"write":case"edit":return n;case"bash":{let r=String(t.command||"").replace(/[\n\t]+/g," ").trim();return`${r.slice(0,80)}${r.length>80?"...":""}`}case"grep":return`/${String(t.pattern||"")}/ in ${n||"."}`;case"find":return`${String(t.pattern||"")} in ${n||"."}`;case"ls":return n||".";default:{let r=JSON.stringify(t);return`${r.slice(0,60)}${r.length>60?"...":""}`}}}function LSe(e){if(Cr(e))return e;if(!Array.isArray(e))return"";return e.filter((t)=>Ra(t)&&t.type==="text"&&Cr(t.text)).map((t)=>t.text).join(" ")}function g7(e){return e.replace(/[\n\t]+/g," ").replace(/\s+/g," ").trim().slice(0,240)}var Gyr=m(()=>{yG()});function OSe(e,t){return s7(e.modelRuntime,()=>Gki(e,t))}async function Gki(e,t){let n=e.model;if(!n)return;let r=await e.modelRuntime.getAuth(n);if(!r)return;let a=new Headers;for(let[s,c]of Object.entries(r.auth.headers??{}))if(c!==null)a.set(s,c);if(!a.has("authorization")){if(!r.auth.apiKey)return;a.set("Authorization",`Bearer ${r.auth.apiKey}`)}if(!a.has("user-agent"))a.set("User-Agent","pi-ui");let i=new AbortController,o=setTimeout(()=>i.abort(),Uki);try{let s=await fetch(t,{headers:a,signal:i.signal});return s.ok?await s.json():void 0}finally{clearTimeout(o)}}var Uki=15000,amt=60000;var QSe=m(()=>{vSe()});function $Se(e){let t=Math.min(100,Math.max(0,e));return Math.round(100-t)}function jSe(e){if(!e)return"?";let t=Math.max(0,e-Date.now())/60000;if(t<60)return`${Math.round(t)}m`;let n=t/60;if(n<24)return`${qyr(n)}h`;return`${qyr(n/24)}d`}function qyr(e){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}function smt(e){return e?.provider===qki}async function Wyr(e){let t=await OSe(e,Hki);return t===void 0?void 0:Kki(t)}function Kyr(e){let t=[];if(e.primary)t.push(Hyr(e.primary,"5 hours"));if(e.secondary)t.push(Hyr(e.secondary,"Weekly"));return t}function Hyr(e,t){return{label:Yki(e.windowSeconds)??t,usedPercent:e.usedPercent,remainingPercent:$Se(e.usedPercent),resetText:jSe(e.resetsAt===void 0?void 0:e.resetsAt*1000)}}function Kki(e){if(!omt.Check(e))return;let t=e.rate_limit;if(!omt.Check(t))return;let n=zyr(t.primary_window),r=zyr(t.secondary_window);return n||r?{primary:n,secondary:r}:void 0}function zyr(e){if(!omt.Check(e))return;let t=imt(e.used_percent);if(t===void 0)return;return{usedPercent:t,windowSeconds:imt(e.limit_window_seconds),resetsAt:imt(e.reset_at)}}function imt(e){if(!Wki.Check(e))return;return Vki(e)}function Vki(e){let t=Number(e);return Number.isFinite(t)?t:void 0}function Yki(e){if(!e||e<=0)return;if(e===604800)return"Weekly";if(e>=2419200&&e<=2678400)return"Monthly";if(e===86400)return"Daily";if(e%3600===0){let t=e/3600;return`${t} ${t===1?"hour":"hours"}`}if(e%60===0){let t=e/60;return`${t} ${t===1?"minute":"minutes"}`}return}var qki="openai-codex",Hki="https://chatgpt.com/backend-api/wham/usage",zki,Wki,omt;var Vyr=m(()=>{hk();Sk();HOe();QSe();zki=Jt.Union([Jt.Number(),Jt.String({pattern:"\\S"})]),Wki=Gc(zki),omt=Gc(jle)});function pmt(e){return e?.provider===Zki}async function Yyr(e){let t=await OSe(e,Jki);return t===void 0?void 0:a_i(t)}function a_i(e){if(!n_i.Check(e))return;let t={rolling:lmt(e.usage.rolling),weekly:lmt(e.usage.weekly),monthly:lmt(e.usage.monthly)};return t.rolling||t.weekly||t.monthly?t:void 0}function Zyr(e){let t=[];if(e.rolling)t.push(umt(e.rolling,"5 hours"));if(e.weekly)t.push(umt(e.weekly,"Weekly"));if(e.monthly)t.push(umt(e.monthly,"Monthly"));return t}function lmt(e){if(!e)return;let t=i_i(e.percent);if(t===void 0)return;return{usedPercent:t,resetsAt:o_i(e.resetsAt)}}function umt(e,t){return{label:t,usedPercent:e.usedPercent,remainingPercent:$Se(e.usedPercent),resetText:jSe(e.resetsAt)}}function i_i(e){let t=Number(e);return Number.isFinite(t)?t:void 0}function o_i(e){if(e===void 0)return;if(r_i.Check(e)){let t=Date.parse(e);return Number.isFinite(t)?t:void 0}return e<10000000000?e*1000:e}var Zki="opencode-go",Jki="https://opencode.ai/zen/go/v1/usage",dmt,Xki,e_i,cmt,t_i,n_i,r_i;var Jyr=m(()=>{hk();Sk();QSe();dmt=Jt.String({pattern:"\\S"}),Xki=Jt.Union([Jt.Number(),dmt]),e_i=Jt.Union([Jt.Number(),dmt]),cmt=Jt.Object({percent:Xki,resetsAt:Jt.Optional(e_i)}),t_i=Jt.Object({usage:Jt.Object({rolling:Jt.Optional(cmt),weekly:Jt.Optional(cmt),monthly:Jt.Optional(cmt)})}),n_i=Gc(t_i),r_i=Gc(dmt)});function s_i(e,t){return e.generation===t.generation&&e.runtime===t.runtime&&e.session===t.session&&e.provider===t.model?.provider&&e.modelId===t.model?.id}class mmt{generation=0;active;begin(e,t,n){this.generation+=1;let r={generation:this.generation,runtime:e,session:t,provider:n?.provider,modelId:n?.id};return this.active=r,r}invalidate(){this.generation+=1,this.active=void 0}owns(e,t,n,r){return this.active===e&&s_i(e,{generation:this.generation,runtime:t,session:n,model:r})}release(e,t,n,r){if(!this.owns(e,t,n,r))return!1;return this.active=void 0,!0}get loading(){return this.active!==void 0}}class gmt{getRuntime;state;fetchCodex;fetchOpenCodeGo;codexStatus="";codexUsage;codexFetchedAt=0;opencodeGoStatus="";opencodeGoUsage;opencodeGoFetchedAt=0;requests=new mmt;timer;constructor(e,t,n=Wyr,r=Yyr){this.getRuntime=e;this.state=t;this.fetchCodex=n;this.fetchOpenCodeGo=r}sync(){let e=this.getRuntime().session,t=smt(e.model),n=pmt(e.model),r=e.getSessionStats();this.state.setUsage(c_i(r,{cacheHitPercent:l_i(r),limits:t?Xyr("Codex limits",this.codexStatus,this.codexUsage?Kyr(this.codexUsage):void 0):n?Xyr("OpenCode Go usage",this.opencodeGoStatus,this.opencodeGoUsage?Zyr(this.opencodeGoUsage):void 0):void 0}))}suspend(){this.invalidate()}refresh(e=!1){let t=this.getRuntime(),n=t.session,r=u_i(n.model);if(!r){this.suspend(),this.sync();return}if(this.requests.loading||!e&&Date.now()-this.fetchedAt(r)<amt)return;let a=this.requests.begin(t,n,n.model);if(!this.hasUsageState(r))this.setUsageStatus(r,"loading"),this.sync();this.fetchProviderUsage(r,n).then((i)=>{if(!this.owns(a))return;this.setUsageResult(i,i.usage?"":"unavailable"),this.sync()}).catch((i)=>{if(!this.owns(a))return;console.warn(`Failed to fetch ${r} usage`,i),this.setUsageResult({provider:r,usage:void 0},"unavailable"),this.sync()}).finally(()=>{let i=this.getRuntime();if(!this.requests.release(a,i,i.session,i.session.model))return;this.schedule()})}dispose(){this.suspend()}fetchProviderUsage(e,t){return e==="codex"?this.fetchCodex(t).then((n)=>({provider:e,usage:n})):this.fetchOpenCodeGo(t).then((n)=>({provider:e,usage:n}))}hasUsageState(e){return e==="codex"?this.codexFetchedAt>0||!!this.codexStatus:this.opencodeGoFetchedAt>0||!!this.opencodeGoStatus}fetchedAt(e){return e==="codex"?this.codexFetchedAt:this.opencodeGoFetchedAt}setUsageStatus(e,t){if(e==="codex")this.codexStatus=t;else this.opencodeGoStatus=t}setUsageResult(e,t){if(e.provider==="codex"){this.codexStatus=t,this.codexUsage=e.usage,this.codexFetchedAt=Date.now();return}this.opencodeGoStatus=t,this.opencodeGoUsage=e.usage,this.opencodeGoFetchedAt=Date.now()}owns(e){let t=this.getRuntime();return this.requests.owns(e,t,t.session,t.session.model)}invalidate(){if(this.requests.invalidate(),this.timer)clearTimeout(this.timer);this.timer=void 0}schedule(){if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=void 0,this.refresh(!0)},amt),this.timer.unref?.()}}function c_i(e,t={}){let n=d_i(e.cost);if(e.contextUsage)return{text:`${n} \u2022 ${p_i(e.contextUsage.percent)}/${MS(e.contextUsage.contextWindow)}`,costText:n,contextPercent:e.contextUsage.percent??void 0,contextTokens:e.contextUsage.tokens??void 0,contextWindow:e.contextUsage.contextWindow,cacheHitPercent:t.cacheHitPercent,limits:t.limits};return{text:`${n} \u2022 ${MS(e.tokens.total)} tokens`,costText:n,cacheHitPercent:t.cacheHitPercent,limits:t.limits}}function l_i(e){let{input:t,cacheRead:n,cacheWrite:r}=e.tokens,a=t+n+r;return a>0?n/a*100:void 0}function Xyr(e,t,n){if(!t&&!n?.length)return;return{label:e,status:n?.length?void 0:t,windows:n??[]}}function u_i(e){if(smt(e))return"codex";if(pmt(e))return"opencode-go";return}function d_i(e){if(e<1)return`$${e.toFixed(3)}`;if(e<100)return`$${e.toFixed(1)}`;return`$${Math.round(e)}`}function p_i(e){return e===null?"?":`${e.toFixed(1)}%`}var e0r=m(()=>{Vyr();Jyr();QSe()});class A7{runtime;state;runtimeFactory;preparedSessions;activationOptions;unsubscribe;tools=vyr();prompts;auth;transitionController;backgroundSessions=new Opt;catalog;llama;models;usage;extensionUi;transcript=new nmt;tree;foregroundGeneration;foregroundObservedRunning;sharing=!1;resetChatOnInvalidation=!1;disposal;initialCatalogLoad;lastForcedModelRefreshAt;dependencies;autoTitlesInFlight=new Set;constructor(e,t,n,r,a){this.runtime=e;this.state=t;this.runtimeFactory=n;this.preparedSessions=r;this.activationOptions=a;this.dependencies=a.dependencies??t0r,this.extensionUi=new $pt(t),this.foregroundGeneration=this.backgroundSessions.allocateGeneration(),this.foregroundObservedRunning=e.session.isStreaming,this.models=new qpt(()=>this.runtime,t,()=>this.afterModelChange()),this.llama=new Upt(()=>this.runtime,t,()=>this.syncModels()),this.usage=new gmt(()=>this.runtime,t),this.tree=new rmt(()=>this.runtime,t,()=>this.loadCurrentSessionMessages(),()=>this.foregroundGeneration),this.catalog=new Cne(t,{agentDir:this.dependencies.getAgentDir(),backgroundStatuses:()=>new Map([...this.backgroundSessions.entries()].map(([i,o])=>[i,o.status])),watch:this.dependencies.watchSessionCatalog}),this.prompts=new Hpt((i)=>{if(i===this.runtime)return this.state;for(let o of this.backgroundSessions.values())if(o.runtime===i)return o.state}),this.auth=new Lpt(()=>this.runtime,t,()=>this.models.sync()),this.transitionController=a.transitionController??new cU((i)=>t.setSessionTransition(i))}static async create(e,t=OG(),n={}){let r=await A7.prepare(e,t,n);return r.activate(),r}static async prepare(e,t=OG(),n={}){let r=n.dependencies??t0r,a=r.prepareSessions(),i=async({cwd:s,sessionManager:c,sessionStartEvent:u})=>{let l=await oi.measure("runtimeServicesCreate",()=>kF({cwd:s,resourceLoaderOptions:{extensionFactories:m_i}}));Lbr(l.modelRuntime,l.settingsManager.getGlobalSettings().httpProxy);let d=await s7(l.modelRuntime,()=>l.modelRuntime.getAvailable()),p=oi.measureSync("scopedModelResolution",()=>oyr(l.settingsManager.getEnabledModels()??[],d)),g=l.resourceLoader.getExtensions().extensions.some((f)=>f.tools.has("read"));return{...await oi.measure("runtimeSessionCreate",()=>_F({services:l,sessionManager:c,sessionStartEvent:u,scopedModels:p,customTools:g?void 0:[dyr(s)]})),services:l,diagnostics:l.diagnostics}},o=await r.createRuntime(i,{cwd:t,agentDir:r.getAgentDir(),sessionManager:r.createSessionManager(t)});try{let s=new A7(o,e,i,a,n);return s.bindRuntimeCallbacks(o),await s.bindSessionExtensions(),s}catch(s){throw await o.dispose(),s}}activate(){this.bindSessionState({syncSessions:!1}),this.initialCatalogLoad=this.loadInitialCatalog(),this.catalog.activate()}async prompt(e,t={}){let n=e.trim();if(!n)return!1;if(n==="/tree")return this.openTree(),!0;if(n==="/login"||n.startsWith("/login "))return this.openLogin(n.startsWith("/login ")?n.slice(7).trim():void 0),!0;if(n==="/logout")return this.openLogout(),!0;if(n==="/llama")return this.openLlama(),!0;if(n==="/compact"||n.startsWith("/compact ")){let a=n.startsWith("/compact ")?n.slice(9).trim():void 0;return this.compact(a),!0}if(n==="/share")return this.share(),!0;if(n==="/reload")return this.reload(),!0;let r=this.runtime;if(r.session.isCompacting)return this.prompts.queueAfterCompaction(r,n,t.streamingBehavior??"steer",t.images),!0;return await this.prompts.submit(r,n,t)}async abort(){this.tree.cancelNavigation(),await this.runtime.session.abort(),this.prompts.clear(this.runtime),this.foregroundObservedRunning=!1,this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),this.usage.sync();let e=this.runtime.session.sessionManager.getSessionFile();if(e)await this.catalog.refreshPath(e)}async abortBackgroundSession(e){let t=this.backgroundSessions.get(e);if(t?.status!=="running")return!1;return await t.runtime.session.abort(),t.status="completed",t.observedRunning=!1,this.catalog.mergeCurrentStatuses(),await this.catalog.refreshPath(e),!0}restoreQueuedMessages(){return this.prompts.restore(this.runtime)}async removeQueuedMessage(e,t){return await this.prompts.remove(this.runtime,e,t)}async newSession(){return await this.transitionController.run("New session",()=>this.createNewSession(),{overlay:!1})}async createNewSession(){let e=this.runtime.session,t=e.sessionManager.isPersisted();if(this.isCurrentRuntimeActive()||!t){let r=e.sessionManager.getCwd();await this.leaveCurrentRuntimeForReplacement(),this.state.resetChat();let a=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:r,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createSessionManager(r),sessionStartEvent:{type:"session_start",reason:"new"}});this.adoptRuntime(a)}else{this.resetChatOnInvalidation=!0;let r;try{r=await this.runtime.newSession()}finally{this.resetChatOnInvalidation=!1}if(r.cancelled)return!1;this.adoptRuntime(this.runtime)}return await this.bindSession({refreshSessions:!0}),!0}async newTemporarySession(){return await this.transitionController.run("New temporary session",()=>this.createNewTemporarySession(),{overlay:!1})}async createNewTemporarySession(){let e=this.runtime.session.sessionManager.getSessionFile(),t=this.runtime.session.sessionManager.getCwd();await this.leaveCurrentRuntimeForReplacement(),this.state.resetChat();let n=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:t,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createMemorySessionManager(t),sessionStartEvent:{type:"session_start",reason:"new",previousSessionFile:e}});return this.adoptRuntime(n),await this.bindSession(),!0}async listSessions(){await this.initialCatalogLoad,this.usage.sync()}async renameSession(e,t){let n=t.replace(/[\r\n]+/g," ").trim();if(!n)return!1;try{let r=this.dependencies.openSessionManager(e),a=r.getSessionFile();if(!a)return!1;let i=this.runtime.session;if(i.sessionManager.getSessionFile()===a)i.setSessionName(n);else{let o=this.backgroundSessions.get(a);if(o)o.runtime.session.setSessionName(n);else r.appendSessionInfo(n)}return await this.catalog.refreshPath(a),!0}catch(r){return this.state.appendMessage("system",`Failed to rename session: ${im(r)}`),!1}}async deleteSession(e){let t=this.dependencies.openSessionManager(e).getSessionFile();if(!t)return!1;let n=t===this.runtime.session.sessionManager.getSessionFile();if(n&&this.isCurrentRuntimeActive())return this.state.appendMessage("system","Cannot delete the current session while it is running."),!1;if(this.backgroundSessions.get(t)?.status==="running")return this.state.appendMessage("system","Cannot delete a running background session."),!1;try{if(n){if((await this.transitionController.run("Delete current session",()=>this.createNewSession())).status!=="success")return!1}await this.dependencies.moveToTrash(t);let r=this.backgroundSessions.get(t);if(r)this.unsubscribeBackgroundSession(r),await r.runtime.dispose(),this.backgroundSessions.delete(t);return this.state.removeSession(t),await this.refreshSessions(),!0}catch(r){return this.state.appendMessage("system",`Failed to delete session: ${im(r)}`),!1}}getWorkspacePath(){return this.runtime.session.sessionManager.getCwd()}async openWorkspace(e){if(e===this.getWorkspacePath())return!0;let t=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:e,agentDir:this.dependencies.getAgentDir(),sessionManager:this.dependencies.createSessionManager(e)});try{await t.session.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(()=>t===this.runtime)})}catch(r){throw await t.dispose(),r}let n=this.currentRuntimeLeaveAction();try{await this.leaveCurrentRuntimeForReplacement(n)}catch(r){if(n!=="dispose")throw r;console.error("Failed to dispose previous workspace runtime",r)}return this.adoptRuntime(t),this.state.resetChat({preserveEmptyHint:!0}),this.bindSessionState(),!0}async forkSessionToWorkspace(e){let t=this.runtime.session.sessionManager.getSessionFile();if(!t)return this.state.appendMessage("notice","Temporary sessions cannot be forked to another workspace."),{status:"cancelled"};return await this.transitionController.run(`Fork to ${Fh(e)}`,async()=>{let n=this.dependencies.forkSessionManager(t,e).getSessionFile();return n?await this.resumeSessionTransition(n):!1},{overlay:!1})}async resumeSession(e){if(e===this.runtime.session.sessionManager.getSessionFile())return{status:"success"};return await this.transitionController.run(e,async(t)=>{let n=oi.startSessionTransition(t);try{let r=await oi.runInTransition(n,()=>this.resumeSessionTransition(e,n));if(r)oi.markSessionTransitionComplete(n);else oi.cancelSessionTransition(n);return r}catch(r){throw oi.cancelSessionTransition(n),r}},{overlay:!1})}async resumeSessionTransition(e,t){let n=this.runtime.session.isStreaming,r=this.runtime.session.sessionManager.isPersisted();oi.recordOwnershipDiagnostics({sourceGeneration:this.foregroundGeneration,sourceSdkStreaming:n,sourceObservedRunning:this.foregroundObservedRunning,sourcePersisted:r,sourceLocationBefore:"foreground",ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t);let a=await Dyr(e,{state:()=>({streaming:n,observedRunning:this.foregroundObservedRunning,persisted:r}),findBackground:(i)=>{let o=this.backgroundSessions.get(i);return oi.recordOwnershipDiagnostics({targetBackgroundLookup:o?"hit":"miss",targetLocationBefore:o?o.status==="running"?"background-running":"background-completed":"disposed"},t),o},activateBackground:async(i,o)=>{let s=this.backgroundSessions.beginActivation(i);if(!s||s.runtime!==o)throw new c7;let c=this.currentRuntimeLeaveAction();oi.recordOwnershipDiagnostics({leaveAction:c},t);try{await oi.measure("backgroundActivation",()=>this.activateRuntime(o),t),s.commit(),oi.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(c),targetLocationAfter:"foreground"},t)}catch(u){throw s.rollback(),u}},openSession:(i)=>{let o=oi.measureSync("sessionManagerOpen",()=>this.dependencies.openSessionManager(i),t);return oi.recordSessionOpen(t),o},replaceRuntime:async(i,o)=>{oi.recordOwnershipDiagnostics({leaveAction:o},t),await this.leaveCurrentRuntimeForReplacement(o);let s=await oi.measure("runtimeSwitchCreate",()=>this.dependencies.createRuntime(this.runtimeFactory,{cwd:i.getCwd(),agentDir:this.dependencies.getAgentDir(),sessionManager:i}),t);this.adoptRuntime(s),await oi.measure("runtimeRebind",()=>this.bindSession(),t),this.loadCurrentSessionMessages(),oi.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(o),targetLocationAfter:"foreground"},t)},switchSession:async(i)=>{oi.recordOwnershipDiagnostics({leaveAction:"dispose"},t);let o=await oi.measure("runtimeSwitchCreate",()=>this.runtime.switchSession(i),t);if(!o.cancelled)oi.recordSessionOpen(t),this.adoptRuntime(this.runtime),oi.recordOwnershipDiagnostics({sourceLocationAfter:"disposed",targetLocationAfter:"foreground"},t);return o}});return oi.recordOwnershipDiagnostics({ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t),a}openTree(){return this.tree.open(),this.state.openTreeDialog(),!0}async navigateTree(e,t={}){return await this.tree.navigate(e,t)}async setThinkingLevel(e){return this.models.setThinking(e)}cycleThinkingLevel(e="forward"){return this.models.cycleThinking(e)}toggleThinkingBlockVisibility(){let e=this.runtime.session.settingsManager;if(!e)return!1;let t=!e.getHideThinkingBlock();return e.setHideThinkingBlock(t),this.state.setThinkingHidden(t),!0}async compact(e){try{return await this.runtime.session.compact(e),this.loadCurrentSessionMessages(),!0}catch{return!1}}async reload(){let e=this.runtime,t=e.session;if(t.isStreaming)return this.state.appendMessage("notice","Wait for the current response to finish before reloading."),!1;if(t.isCompacting)return this.state.appendMessage("notice","Wait for compaction to finish before reloading."),!1;this.state.setActivityText("Reloading...");try{if(await t.reload(),e!==this.runtime)return!1;return this.unbindSession(),this.bindSessionState(),this.loadCurrentSessionMessages(),this.state.appendMessage("system","Reloaded extensions, skills, prompts, and context files."),!0}catch(n){if(e===this.runtime)this.state.appendMessage("notice",`Reload failed: ${im(n)}`);return!1}finally{if(e===this.runtime)this.state.setActivityText(void 0)}}async share(){if(this.sharing){this.state.appendMessage("notice","A session share is already in progress.");return}this.sharing=!0;let e=this.foregroundGeneration;this.state.setActivityText("Creating share...");try{let t=await this.dependencies.shareSession(this.runtime.session);if(e!==this.foregroundGeneration)return;this.state.appendMessage("system",`Share URL: ${t.shareUrl}
4338
4338
  Gist: ${t.gistUrl}`)}catch(t){if(e===this.foregroundGeneration)this.state.appendMessage("notice",`Failed to share session: ${im(t)}`)}finally{if(this.sharing=!1,e===this.foregroundGeneration)this.state.setActivityText(void 0)}}openLogin(e){this.auth.openLogin(e)}openLogout(){this.auth.openLogout()}startLogin(e,t){return this.auth.startLogin(e,t)}submitAuthInput(e){return this.auth.submitInput(e)}logout(e){return this.auth.logout(e)}closeAuth(){this.auth.close()}openLlama(){this.llama.open()}toggleLlamaModel(e){return this.llama.toggle(e)}closeLlama(){this.llama.close()}respondExtensionUi(e,t,n){return this.extensionUi.respond(e,t,n)}async refreshModels(e){let t=Date.now(),n=this.lastForcedModelRefreshAt===void 0||t-this.lastForcedModelRefreshAt>=g_i;if(n)this.lastForcedModelRefreshAt=t;await this.models.refresh({force:n,signal:e})}async setModel(e){return await this.models.set(e)}async cycleModel(e="forward"){return await this.models.cycle(e)}async toggleScopedModel(e){return await this.models.toggleScoped(e)}dispose(){return this.disposal??=this.disposeOwnedRuntimes(),this.disposal}async disposeOwnedRuntimes(){this.extensionUi.cancelAll(),this.unsubscribe?.(),this.unsubscribe=void 0,this.catalog.dispose(),this.auth.dispose(),this.llama.dispose(),this.usage.dispose();let e=[this.runtime];for(let r of this.backgroundSessions.values())this.unsubscribeBackgroundSession(r),e.push(r.runtime);this.backgroundSessions.clear(),this.prompts.dispose();let n=(await Promise.allSettled(e.map((r)=>Promise.resolve().then(()=>r.dispose())))).flatMap((r)=>r.status==="rejected"?[r.reason]:[]);if(n.length>0)throw AggregateError(n,"Failed to dispose owned runtimes")}isCurrentRuntimeActive(){return this.runtime.session.isStreaming||this.runtime.session.isCompacting||this.foregroundObservedRunning||this.prompts.hasPending(this.runtime)}currentRuntimeLeaveAction(){if(!this.isCurrentRuntimeActive())return"dispose";return this.runtime.session.sessionManager.isPersisted()?"background":"discard"}leaveActionLocation(e){if(e==="background")return"background-running";if(e==="keep")return"foreground";return"disposed"}adoptRuntime(e,t){this.runtime=e,this.foregroundGeneration=t?.generation??this.backgroundSessions.allocateGeneration(),this.foregroundObservedRunning=t?.observedRunning??e.session.isStreaming,this.bindRuntimeCallbacks(e)}ownedLiveRuntimeCount(){return this.backgroundSessions.liveCount(this.isCurrentRuntimeActive())}unsubscribeBackgroundSession(e){let t=e.unsubscribe;e.unsubscribe=()=>{},t()}bindRuntimeCallbacks(e){let t=this.foregroundGeneration,n=()=>Hbr(this.runtime,this.foregroundGeneration,e,t);e.setBeforeSessionInvalidate(()=>{if(!n())return;if(this.unbindSession(),this.resetChatOnInvalidation)this.state.resetChat()}),e.setRebindSession(async()=>{if(!n())return;await oi.measure("runtimeRebind",async()=>{if(!n())return;if(await this.bindSessionExtensions(),!n())return;this.bindSessionState(),this.loadCurrentSessionMessages()})})}async leaveCurrentRuntimeForReplacement(e=this.currentRuntimeLeaveAction()){if(e==="background")this.backgroundCurrentRuntime();else if(e==="discard")await this.discardTemporaryRuntime();else this.unbindSession(),await this.runtime.dispose()}async discardTemporaryRuntime(){let e=this.runtime;this.prompts.clear(e),this.unbindSession();try{await e.session.abort()}catch(t){this.state.appendMessage("system",`Failed to abort temporary session: ${im(t)}`)}await e.dispose(),this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),Jpt(this.tools)}backgroundCurrentRuntime(){let e=this.runtime.session.sessionManager.getSessionFile();if(!e)return;if(this.backgroundSessions.has(e))throw new c7;let t=this.state.snapshotChat(),n=this.foregroundGeneration,r=this.foregroundObservedRunning;this.foregroundGeneration=this.backgroundSessions.allocateGeneration(),this.foregroundObservedRunning=!1,this.unbindSession(),this.state.setQueuedMessages([],[]);let a=new xne(t.emptyChatHint);a.restore(t);let i={runtime:this.runtime,state:a,status:"running",generation:n,observedRunning:r,tools:Iyr(this.tools),unsubscribe:()=>{}};i.unsubscribe=this.runtime.session.subscribe((o)=>this.handleBackgroundEvent(i,o)),this.backgroundSessions.register(e,i),this.state.setCurrentSessionPath(void 0),this.catalog.mergeCurrentStatuses(),this.catalog.refreshPath(e)}handleBackgroundEvent(e,t){if(t.type==="agent_start")e.observedRunning=!0;if(t.type==="agent_settled")e.observedRunning=!1;let n=this.reduceEvent(t,e.state,e.tools);if(this.updateSessionCatalogFromEvent(t,e.runtime),this.scheduleAutoTitleAfterUserMessage(e.runtime,t),t.type==="queue_update")this.prompts.sync(e.runtime);if(t.type==="compaction_end")this.prompts.flushCompactionQueue(e.runtime);if(n.agentCompleted){this.unsubscribeBackgroundSession(e),e.status="completed",this.catalog.mergeCurrentStatuses(),this.notifyRuntimeDone(e.runtime,!0);let r=e.runtime.session.sessionManager.getSessionFile();if(r)this.catalog.agentCompleted(r),this.catalog.refreshPath(r);return}}notifyRuntimeDone(e,t){this.notifyRuntimeDoneWhenAppropriate({workspace:Fh(e.session.sessionManager.getCwd()),sessionPath:e.session.sessionManager.getSessionFile()},t)}async notifyRuntimeDoneWhenAppropriate(e,t){if(!t&&await(this.activationOptions.isApplicationFocused?.()??!0))return;await(this.activationOptions.notifySessionDone??this.dependencies.notifySessionDone)(e)}async activateRuntime(e){await this.leaveCurrentRuntimeForReplacement(),this.unsubscribeBackgroundSession(e),this.adoptRuntime(e.runtime,e),Syr(this.tools,e.tools),this.bindSessionState({resetToolState:!1,syncSessions:!1}),this.state.restoreChat(e.state.snapshot()),this.catalog.mergeCurrentStatuses()}async bindSession(e={}){this.unbindSession(),await this.bindSessionExtensions(),this.bindSessionState(e)}unbindSession(){this.extensionUi.cancelAll(),this.unsubscribe?.(),this.unsubscribe=void 0,this.usage.suspend()}bindSessionState(e={}){this.state.update(()=>{let t=this.runtime.session,n=e.resetToolState??!0;if(this.state.setWorkspacePath(t.sessionManager.getCwd()),this.state.setCurrentSessionPath(t.sessionManager.getSessionFile()),this.state.setTemporarySession(!t.sessionManager.isPersisted()),n)Jpt(this.tools);if(this.unsubscribe=t.subscribe((r)=>this.handleEvent(r)),this.state.setActivityText(t.isStreaming||this.foregroundObservedRunning?"Working...":void 0),this.syncModels(),this.models.syncThinking(),this.state.setThinkingHidden(t.settingsManager?.getHideThinkingBlock()??!1),this.syncSlashCommands(),this.usage.sync(),this.usage.refresh(!0),e.syncSessions!==!1)this.catalog.mergeCurrentStatuses();if(e.refreshSessions===!0)this.refreshSessions()})}async bindSessionExtensions(){let e=this.runtime,t=this.foregroundGeneration,n=e.session;await oi.measure("extensionBind",()=>n.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(()=>e===this.runtime&&t===this.foregroundGeneration),commandContextActions:{waitForIdle:()=>n.waitForIdle(),newSession:(r)=>e.newSession(r),fork:async(r,a)=>({cancelled:(await e.fork(r,a)).cancelled}),navigateTree:async(r,a)=>{let i=await n.navigateTree(r,a);if(!i.cancelled&&e===this.runtime)this.loadCurrentSessionMessages();return{cancelled:i.cancelled}},switchSession:(r,a)=>e.switchSession(r,a),reload:async()=>{await this.reload()}}}))}async loadInitialCatalog(){await this.catalog.refresh(()=>this.preparedSessions,{refreshWorkspaces:this.activationOptions.refreshWorkspaces})}async refreshSessions(){await this.initialCatalogLoad,await this.catalog.refresh(this.dependencies.prepareSessions,{showLoading:!1})}updateSessionCatalogFromEvent(e,t){let n=t.session.sessionManager,r=n.getSessionFile();if(r)this.catalog.handleEvent(r,e,n.getCwd())}afterModelChange(){this.usage.suspend(),this.models.sync(),this.models.syncThinking(),this.usage.sync(),this.usage.refresh(!0)}syncModels(){this.models.sync()}handleEvent(e){if(e.type==="agent_start")this.foregroundObservedRunning=!0;if(e.type==="agent_settled")this.foregroundObservedRunning=!1;if(this.state.update(()=>{let t=this.reduceEvent(e,this.state,this.tools,()=>this.usage.sync());if(this.updateSessionCatalogFromEvent(e,this.runtime),this.scheduleAutoTitleAfterUserMessage(this.runtime,e),this.foregroundObservedRunning&&!this.state.activityText)this.state.setActivityText("Working...");if(t.agentCompleted){let n=this.runtime.session.sessionManager.getSessionFile();if(n)this.catalog.agentCompleted(n);if(this.usage.sync(),this.usage.refresh(!0),this.notifyRuntimeDone(this.runtime,!1),n)this.catalog.refreshPath(n)}},{commit:!1}),e.type==="queue_update")this.prompts.sync(this.runtime);if(e.type==="compaction_end")this.prompts.flushCompactionQueue(this.runtime)}scheduleAutoTitleAfterUserMessage(e,t){if(t.type!=="message_end"||t.message.role!=="user")return;queueMicrotask(()=>this.maybeGenerateAutoTitle(e))}maybeGenerateAutoTitle(e){let t=this.activationOptions.autoTitle,n=e.session.sessionManager.getSessionFile();if(!t?.enabled||!n||e.session.sessionManager.getSessionName()||this.autoTitlesInFlight.has(n))return;this.autoTitlesInFlight.add(n),Sbr(e,t).then((r)=>{if(!r||e.session.sessionManager.getSessionName())return;e.session.setSessionName(r),this.catalog.rename(n,r)}).catch((r)=>console.warn("Failed to generate session title",r)).finally(()=>this.autoTitlesInFlight.delete(n))}reduceEvent(e,t,n,r){return Byr(e,{state:t,tools:n,convertMessage:(a,i)=>this.transcript.message(a,i,{includeAssistantError:!1}),formatToolStart:(a)=>this.formatRunningTool(a.toolName,a.args),formatToolPreview:(a,i)=>this.formatRunningTool(a,i,!1),formatToolUpdate:(a)=>{let i=Ine(a.toolName,a.partialResult,{args:a.args});return{text:i.text,meta:emt(a.toolName,a.args),format:i.format}},formatToolEnd:(a,i,o)=>{let s=Ine(a.toolName,a.result,{args:i,isError:a.isError});return{text:s.text,options:{title:vne(a.isError?"error":"success",a.toolName,i),meta:Lyr(o),state:a.isError?"error":"success",titleParts:Ene(a.toolName,i),format:s.format}}},cacheMissNotice:(a)=>{if(!this.runtime.session.settingsManager?.getShowCacheMissNotices())return;let i=Kbr(this.runtime.session.sessionManager.getEntries(),a,this.runtime.session.modelRuntime);return i?ISe(i):void 0},syncUsage:r})}formatRunningTool(e,t,n=!0){let r=Qyr(e,t);return{text:n?r.text:"",options:{title:vne("running",e,t),titleParts:Ene(e,t),meta:emt(e,t),state:"running",format:r.format}}}syncSlashCommands(){let e=this.runtime.session,t=e.promptTemplates.map((a)=>({name:a.name,description:a.description,argumentHint:a.argumentHint,source:"prompt"})),n=e.extensionRunner.getRegisteredCommands().filter((a)=>!A_i.has(a.name)).map((a)=>({name:a.invocationName,description:a.description??"",source:"extension"})),r=e.resourceLoader.getSkills().skills.map((a)=>({name:`skill:${a.name}`,description:a.description,source:"skill"}));this.state.setSlashCommands([...n0r,...t,...n,...r])}loadCurrentSessionMessages(){this.transcript.load(this.runtime,this.state),this.usage.sync()}}var m_i,g_i=1800000,n0r,A_i,t0r;var r0r=m(()=>{rF();jR();Pbr();vSe();Qbr();jk();qbr();Rpt();zbr();Qpt();Zbr();tyr();iyr();syr();pyr();Ayr();Eyr();Tyr();Ryr();Nyr();lU();tmt();jyr();Gyr();e0r();m_i=[ayr],n0r=[{name:"login",description:"Log in with a subscription or API key",source:"system",argumentHint:"[provider]"},{name:"logout",description:"Remove stored provider credentials",source:"system"},{name:"tree",description:"Navigate and branch within the current session",source:"system"},{name:"llama",description:"Load or unload llama.cpp models",source:"system"},{name:"compact",description:"Manually compact the session context",source:"system",argumentHint:"[instructions]"},{name:"share",description:"Share session as a secret GitHub gist",source:"system"},{name:"reload",description:"Reload extensions, skills, prompts, and context files",source:"system"}],A_i=new Set(n0r.map((e)=>e.name)),t0r={createRuntime:v$,prepareSessions:Cne.prepare,createSessionManager:Mi.create,createMemorySessionManager:Mi.inMemory,forkSessionManager:Mi.forkFrom,openSessionManager:Mi.open,moveToTrash:Obr,shareSession:Pyr,getAgentDir:pa,notifySessionDone:Mbr,watchSessionCatalog:gyr}});function Amt(){return i0r[Math.floor(Math.random()*i0r.length)]}function f_i(){return process.env.PI_UI_DEBUG==="1"}function h_i(){return process.env.PI_UI_INSPECTOR==="1"}function b_i(e){let t=[];for(let n of e)if(n&&!t.includes(n))t.push(n);return t}class fmt{transcript=new xne(Amt());presentation;debugUi=f_i();datastarInspector=h_i();documentTitle="pi-ui";promptEditorText="";models=[];sessionCatalogLoading=!0;sessionCatalog=[];sessionLimit=a0r;treeEntries=[];slashCommands=[];authDialog;extensionDialog;extensionStatuses=[];extensionWidgets=[];extensionWorkingIndicator;extensionWorkingMessage;extensionWorkingVisible=!0;llamaDialog;currentModel;currentSessionPath;isTemporarySession=!1;thinkingLevel="off";thinkingLevels=["off"];thinkingHidden=!1;usage={text:"$0.000 \u2022 0 tokens",costText:"$0.000"};workspacePath=OG();workspaceFilesRevision=0;workspaceTreeRevision=0;workspaceReview=VRe;workspaceReviewPreferences={};recentWorkspaces=[];workspacePathListener;sessionTransition={status:"idle",generation:0};attachPresentation(e){if(this.presentation)throw Error("AppStore presentation already attached");this.presentation=e}listenForWorkspacePath(e){if(this.workspacePathListener)throw Error("AppStore workspace path listener already attached");this.workspacePathListener=e}get messages(){return this.transcript.messages}get sessions(){return this.sessionCatalog.slice(0,this.sessionLimit)}get sessionsHasMore(){return!this.sessionCatalogLoading&&this.sessionLimit<this.sessionCatalog.length}get hasOlderMessages(){return this.transcript.hasOlderMessages}get promptHistory(){let e=[],t=this.transcript.allMessages;for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.role!=="user")continue;let a=r.text.trim();if(!a||e.at(-1)===a)continue;if(e.push(a),e.length===100)break}return e}get emptyChatHint(){return this.transcript.emptyChatHint}get activityText(){return this.transcript.activityText}get queuedSteeringMessages(){return[...this.transcript.queuedSteeringMessages]}get queuedFollowUpMessages(){return[...this.transcript.queuedFollowUpMessages]}snapshot(){let e=this.sessionCatalog;return Object.freeze({messages:this.messages.map((t)=>({...t})),models:this.models.map((t)=>({...t})),sessions:e.slice(0,this.sessionLimit).map((t)=>({...t})),sessionsHasMore:this.sessionsHasMore,sessionCatalogLoading:this.sessionCatalogLoading,treeEntries:this.treeEntries.map((t)=>({...t})),slashCommands:this.slashCommands.map((t)=>({...t})),authDialog:this.authDialog?structuredClone(this.authDialog):void 0,extensionDialog:this.extensionDialog?structuredClone(this.extensionDialog):void 0,extensionStatuses:this.extensionStatuses.map((t)=>({...t})),extensionWidgets:this.extensionWidgets.map((t)=>({...t,lines:[...t.lines]})),extensionWorkingIndicator:this.extensionWorkingIndicator,extensionWorkingMessage:this.extensionWorkingMessage,extensionWorkingVisible:this.extensionWorkingVisible,llamaDialog:this.llamaDialog?structuredClone(this.llamaDialog):void 0,currentModel:this.currentModel,currentSessionPath:this.currentSessionPath,isTemporarySession:this.isTemporarySession,thinkingLevel:this.thinkingLevel,thinkingLevels:[...this.thinkingLevels],thinkingHidden:this.thinkingHidden,usage:{...this.usage},activityText:this.activityText,queuedSteeringMessages:[...this.queuedSteeringMessages],queuedFollowUpMessages:[...this.queuedFollowUpMessages],workspacePath:this.workspacePath,workspaceFilesRevision:this.workspaceFilesRevision,workspaceTreeRevision:this.workspaceTreeRevision,workspaceReview:structuredClone(this.workspaceReview),workspaceReviewPreferences:{...this.workspaceReviewPreferences},recentWorkspaces:[...this.recentWorkspaces],sessionTransition:{...this.sessionTransition},debugUi:this.debugUi,datastarInspector:this.datastarInspector,documentTitle:this.documentTitle,hasOlderMessages:this.hasOlderMessages,promptHistory:[...this.promptHistory],promptEditorText:this.promptEditorText,emptyChatHint:{...this.emptyChatHint}})}update(e,t={}){this.presentation?.beginUpdate();try{return e()}finally{this.presentation?.endUpdate(t.commit!==!1,t.flush===!0)}}flush(){this.presentation?.flush()}commit(e){this.presentation?.requestCommit(e)}appendMessage(e,t,n={}){let r=this.transcript.appendMessage(e,t,n);return this.presentation?.messageAppended(r),r}updateMessage(e,t){if(!this.transcript.updateMessage(e,t))return;this.presentation?.messageUpdated(e)}appendThoughtDelta(e){let t=this.transcript.activeThoughtMessageId,n=this.transcript.appendThoughtDelta(e);if(!t)this.presentation?.streamingMessageStarted(n);else this.presentation?.streamingMessageChanged()}appendAssistantDelta(e){let t=this.transcript.activeAssistantMessageId,n=this.transcript.appendAssistantDelta(e);if(!t)this.presentation?.streamingMessageStarted(n);else this.presentation?.streamingMessageChanged()}finishAssistant(){let e=this.transcript.finishAssistant();this.presentation?.assistantFinished(e)}snapshotChat(){return this.transcript.snapshot()}restoreChat(e){let t=oi.startSpan("transcriptProjection");this.presentation?.transcriptReplacing(),this.transcript.restore(e),t(),oi.markTranscriptProjected(),this.presentation?.transcriptReplaced([e.activeThoughtId,e.activeAssistantId],this.transcript.messages.map((n)=>n.id)),this.commit()}resetChat(e={}){if(this.presentation?.transcriptReplacing(),this.transcript.reset(e.preserveEmptyHint?void 0:Amt()),this.presentation?.transcriptReplaced([],[]),e.broadcast!==!1)this.commit()}replaceMessages(e){let t=oi.startSpan("transcriptProjection");this.presentation?.transcriptReplacing(),this.transcript.replaceMessages(e,e.length===0?Amt():void 0),t(),oi.markTranscriptProjected(),this.presentation?.transcriptReplaced([],this.transcript.messages.map((n)=>n.id)),this.commit()}showRecentMessages(){if(!this.transcript.showRecentMessages())return;this.presentation?.transcriptReplacing(),this.presentation?.transcriptReplaced([],this.transcript.messages.map((e)=>e.id)),this.commit({type:"scroll-transcript-bottom"})}loadOlderMessages(){return this.transcript.loadOlderMessages()}trimOldMessages(){return this.transcript.trimOldMessages()}setModels(e,t,n={}){this.models=e,this.currentModel=t,this.presentation?.pickersChanged(),this.commit(n.restorePicker?{type:"restore-model-picker"}:void 0)}setThinking(e,t){this.thinkingLevel=e,this.thinkingLevels=t.length>0?t:["off"],this.presentation?.pickersChanged(),this.commit()}setThinkingHidden(e){if(this.thinkingHidden===e)return;this.thinkingHidden=e,this.commit()}setSessionCatalogLoading(e){if(this.sessionCatalogLoading===e)return;this.sessionCatalogLoading=e,this.presentation?.sessionsChanged(),this.commit()}setSessionCatalog(e){this.sessionCatalog=e,this.presentation?.sessionsChanged(),this.commit()}loadMoreSessions(){this.sessionLimit=Math.min(this.sessionLimit+a0r,this.getSessionCatalog().length),this.presentation?.sessionsChanged(),this.commit()}getSessionCatalog(){return this.sessionCatalog}promoteSession(e,t={}){let n=this.getSessionCatalog(),r=n.find((a)=>a.path===e);if(!r)return!1;if(n[0]?.path===e){if(t.regroup)this.presentation?.sessionsChanged(),this.commit();return!1}return this.sessionCatalog=[r,...n.filter((a)=>a.path!==e)],this.presentation?.sessionsChanged(),this.commit(),!0}updateSessionSummary(e,t,n={}){let r=this.getSessionCatalog(),a=r.findIndex((i)=>i.path===e);if(a<0)return!1;if(this.sessionCatalog=r.map((i,o)=>o===a?t(i):i),n.sidebarOnly)this.presentation?.sessionSidebarChanged();else this.presentation?.sessionsChanged();return this.commit(),!0}searchSessions(e){let t=e.trim().toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return[...this.sessions];return this.getSessionCatalog().filter((n)=>{let r=`${n.title} ${_4(n.messageCount)} ${n.cwd} ${n.path}`.toLowerCase();return t.every((a)=>r.includes(a))}).slice(0,this.sessionLimit)}removeSession(e){this.setSessionCatalog(this.getSessionCatalog().filter((t)=>t.path!==e))}setRecentWorkspaces(e){this.recentWorkspaces=b_i([this.workspacePath,...e,...this.recentWorkspaces]),this.presentation?.pickersChanged(),this.commit()}setSlashCommands(e){this.slashCommands=e,this.presentation?.pickersChanged(),this.commit()}setAuthDialog(e,t={}){if(this.authDialog=e,this.presentation?.pickersChanged(),this.presentation?.requestCommit({type:"dialog",id:"auth-dialog",open:Boolean(e)}),t.resetInput)this.presentation?.requestCommit({type:"signal-overrides",values:{authInput:""}})}setExtensionDialog(e){if(this.extensionDialog=e,this.presentation?.pickersChanged(),this.presentation?.requestCommit({type:"dialog",id:"extension-dialog",open:Boolean(e)}),e)this.presentation?.requestCommit({type:"signal-overrides",values:{extensionRequestId:e.id,extensionResponse:e.kind==="input"||e.kind==="editor"?e.prefill??"":""}})}setExtensionStatuses(e){this.extensionStatuses=e.map((t)=>({...t})),this.commit()}setExtensionWidgets(e){this.extensionWidgets=e.map((t)=>({...t,lines:[...t.lines]})),this.commit()}setExtensionWorking(e){this.extensionWorkingMessage=e.message,this.extensionWorkingVisible=e.visible,this.extensionWorkingIndicator=e.indicator,this.commit()}setDocumentTitle(e){this.documentTitle=e,this.presentation?.requestCommit({type:"document-title",title:e})}setPromptEditorText(e,t={}){if(this.promptEditorText=e,t.broadcast!==!1)this.presentation?.requestCommit({type:"signal-overrides",values:{prompt:e}})}setLlamaDialog(e){this.llamaDialog=e,this.presentation?.pickersChanged(),this.presentation?.requestCommit({type:"dialog",id:"llama-dialog",open:Boolean(e)})}setTreeEntries(e){this.treeEntries=e,this.presentation?.pickersChanged(),this.commit()}openTreeDialog(){this.presentation?.pickersChanged(),this.commit({type:"dialog",id:"tree-dialog",open:!0})}setUsage(e){this.usage=e,this.commit()}setActivityText(e){this.transcript.setActivityText(e),this.presentation?.sessionsChanged(),this.commit()}setQueuedMessages(e,t){this.transcript.setQueuedMessages(e,t),this.commit()}setCurrentSessionPath(e){this.currentSessionPath=e,this.presentation?.sessionsChanged(),this.commit()}setTemporarySession(e){this.isTemporarySession=e,this.commit()}setWorkspacePath(e){if(this.workspacePath===e)return;this.workspacePath=e,this.workspaceFilesRevision=0,this.workspaceTreeRevision=0,this.workspaceReview=VRe,this.presentation?.pickersChanged(),this.presentation?.workspaceReviewChanged(),this.commit(),this.workspacePathListener?.(e)}workspaceFilesChanged(e=!0){if(this.workspaceFilesRevision+=1,e)this.workspaceTreeRevision+=1;this.presentation?.workspaceReviewChanged(),this.commit()}setWorkspaceReview(e){if(this.workspaceReview.revision===e.revision)return;this.workspaceReview=e,this.presentation?.workspaceReviewChanged(),this.commit()}setWorkspaceReviewPreferences(e){this.workspaceReviewPreferences=e,this.presentation?.workspaceReviewChanged(),this.commit()}setSessionTransition(e){let t=this.sessionTransition.status==="loading"&&e.status==="idle";this.flush(),this.sessionTransition=e,this.presentation?.sessionTransitionChanged(t)}}var a0r=30,i0r;var o0r=m(()=>{lMe();jR();pS();jk();cR();i0r=[...Foe.filter((e)=>e.shortcut).map((e)=>({keys:uU(e.shortcut),description:e.description})),{keys:"alt T",description:"Cycle thinking level."},{keys:"@",description:"Attach a file path."},{keys:"/",description:"Open slash commands and skills."}]});class hmt{clients=new Map;get clientCount(){return this.clients.size}get targetHz(){let e;for(let t of this.clients.values())if(e===void 0||t.hz>e)e=t.hz;return e??WOe}connect(e){let t=this.clients.get(e);if(t){t.connections+=1;return}this.clients.set(e,{connections:1,hz:WOe})}disconnect(e){let t=this.clients.get(e);if(!t)return;if(t.connections-=1,t.connections===0)this.clients.delete(e)}setHz(e,t){let n=this.clients.get(e);if(!n)return!1;return n.hz=t,!0}}var s0r=m(()=>{Gle()});class bmt{concurrency;pending=[];active=new Map;sequence=0;constructor(e=2){this.concurrency=e;if(!Number.isInteger(e)||e<1)throw Error("Enhancement concurrency must be a positive integer")}enqueue(e){this.pending.push({...e,sequence:this.sequence++}),this.pending.sort((t,n)=>n.priority-t.priority||t.sequence-n.sequence),this.drain()}cancelAll(){for(let e of this.pending.splice(0))e.onCancel?.();for(let[e,t]of this.active)t.abort(),e.onCancel?.()}drain(){while(this.active.size<this.concurrency){let e=this.pending.shift();if(!e)return;let t=new AbortController;this.active.set(e,t),e.run(t.signal).catch((n)=>{if(!t.signal.aborted)e.onError?.(n)}).finally(()=>{this.active.delete(e),this.drain()})}}}function Sne(e){return y_i.has(e)}function c0r(e){if(Sne(e.role)&&e.role!=="skill"&&e.role!=="compaction"&&e.role!=="summary")return"markdown";if(e.role!=="tool")return;if(e.format==="diff")return"diff";if(e.format==="code")return"code"}function l0r(e){return[...new Set(e.filter((t)=>t!==void 0))]}function w_i(e){let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}class ymt{store;patchMessage;deferEnhancement;presentation=new Map;imageUrls=new Map;queue;streaming;pendingStreamingIds=new Set;generation=0;renderMarkdownEnhancement;renderCodeEnhancement;renderDiffEnhancement;registerImage;clearImages;constructor(e,t,n,r={}){this.store=e;this.patchMessage=t;this.deferEnhancement=n;this.queue=new bmt(r.enhancementConcurrency??2),this.renderMarkdownEnhancement=r.renderMarkdownFinal??i9t,this.renderCodeEnhancement=r.renderCode??((a,i)=>Zce(a,i,{disableLineNumbers:!0})),this.renderDiffEnhancement=r.renderDiff??Z5t,this.registerImage=r.registerImage,this.clearImages=r.clearImages,this.streaming=new KOe((a)=>{for(let i of a)this.pendingStreamingIds.delete(i);for(let i of a)this.patchScheduledMessage(i)})}projectMessages(e){return e.map((t)=>this.project(t))}renderMessagesElement(){return v4(this.projectMessages(this.store.messages),this.store.emptyChatHint,this.store.hasOlderMessages,this.store.sessions,this.store.models.some((e)=>e.configured),this.store.sessionCatalogLoading)}renderMessageElement(e){let t=this.store.transcript.getMessage(e);if(!t)return;return UG(this.project(t))}renderOlderMessagesPatch(e){return v9t(this.projectMessages(e))}renderOlderMessagesTrigger(){return I9t(this.store.hasOlderMessages)}messageAppended(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(this.presentation.set(e,{renderedHtml:Sne(t.role)&&t.text.trim()?RS(t.text,{cacheKey:e}):void 0,presentationState:Sne(t.role)?"streaming":"plain",presentationVersion:0}),t.role==="tool"&&t.state!=="running")this.enqueueEnhancement(e)}messageUpdated(e){if(!this.store.transcript.getMessage(e))return;QR(e);let n=this.ensure(e);n.renderedHtml=void 0,n.presentationState="plain",n.presentationVersion+=1,this.scheduleMessages([e])}codeThemeChanged(){let e=new Set(this.streamingIds());this.clearScheduledMessages(),this.generation+=1,this.queue.cancelAll();for(let t of this.presentation.keys())QR(t);this.presentation.clear();for(let t of this.store.messages)if(this.messageAppended(t.id),c0r(t)==="markdown"&&!e.has(t.id))this.deferEnhancement(t.id)}streamingMessageStarted(e){this.initializeStreaming(e)}streamingMessageChanged(){let e=this.streamingIds();for(let t of e)this.ensure(t).presentationVersion+=1;this.scheduleMessages(e)}assistantFinished(e){let t=l0r([e.thoughtId,e.assistantId]);this.flushMessages(t);for(let n of t)this.deferEnhancement(n)}transcriptReplacing(){this.clearScheduledMessages(),this.generation+=1,this.queue.cancelAll();for(let e of this.store.transcript.allMessages)QR(e.id);this.presentation.clear(),this.imageUrls.clear(),this.clearImages?.()}transcriptReplaced(e,t){for(let n of e)if(n)this.initializeStreaming(n);for(let n of t.toReversed())this.deferEnhancement(n)}setDisplayRefreshHz(e){return this.streaming.setDisplayHz(e)}enqueueEnhancement(e){let t=this.store.transcript.getMessage(e),n=t?this.project(t):void 0,r=n?c0r(n):void 0,a=t?this.ensure(e):void 0;if(!t||!r||!a||r==="markdown"&&this.streamingIds().includes(e)||!t.text.trim()||a.presentationState==="enhancing"||a.presentationState==="final")return;let i=this.generation,o=t.text,s=t.format,c=a.presentationVersion;a.presentationState="enhancing",this.queue.enqueue({key:`${i}:${e}:${c}:${r}`,priority:this.store.transcript.getMessageIndex(e)??0,run:async(u)=>{let l=await this.renderEnhancement(r,o);if(u.aborted)return;let d=this.store.transcript.getMessage(e),p=this.ensure(e);if(i!==this.generation||!d||d.text!==o||d.format!==s||p.presentationVersion!==c)return;p.renderedHtml=l,p.presentationState="final",QR(e),this.broadcast(d)},onCancel:()=>QR(e),onError:(u)=>{let l=this.store.transcript.getMessage(e),d=this.ensure(e);if(i===this.generation&&l?.text===o&&l.format===s&&d.presentationVersion===c)d.presentationState="plain",QR(e);console.warn(`Failed to enhance message ${e}`,u)}})}streamingIds(){return l0r([this.store.transcript.activeThoughtMessageId,this.store.transcript.activeAssistantMessageId])}scheduleMessages(e){for(let t of e)this.pendingStreamingIds.add(t);this.streaming.schedule([...this.pendingStreamingIds])}flushMessages(e){for(let t of e)this.pendingStreamingIds.add(t);this.streaming.flush([...this.pendingStreamingIds])}clearScheduledMessages(){this.pendingStreamingIds.clear(),this.streaming.clear()}initializeStreaming(e){let t=this.store.transcript.getMessage(e);if(!t)return;this.presentation.set(e,{renderedHtml:t.text.trim()?RS(t.text,{cacheKey:e}):void 0,presentationState:"streaming",presentationVersion:0})}patchScheduledMessage(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(Sne(t.role)&&t.text.trim()){let n=this.ensure(e);n.renderedHtml=RS(t.text,{cacheKey:e}),n.presentationState="streaming"}if(this.broadcast(t),t.role==="tool"&&t.state!=="running")this.enqueueEnhancement(e)}project(e){let t=this.ensure(e.id),n=this.activitySummary(e);if(Sne(e.role)&&e.text.trim()&&t.renderedHtml===void 0)t.renderedHtml=RS(e.text);return{...e,activitySummary:n,attachments:e.attachments?.map((r,a)=>{let i=r.image;if(!i?.data||!this.registerImage)return r;let o=`${e.id}:${a}`,s=this.imageUrls.get(o);if(!s||s.data!==i.data)s={data:i.data,url:this.registerImage({data:i.data,mimeType:i.mimeType})},this.imageUrls.set(o,s);return{...r,image:{mimeType:i.mimeType,url:s.url}}}),...t}}activitySummary(e){if(e.role!=="assistant")return;let t=this.store.transcript.allMessages,n=this.store.transcript.getMessageIndex(e.id);if(n===void 0)return;let r=n;while(r>0&&["thought","tool"].includes(t[r-1].role))r-=1;let a=t.slice(r,n),i=a.filter((o)=>o.role==="tool").length;if(i===0)return;return{stepCount:i,duration:w_i(e.timestamp.getTime()-a[0].timestamp.getTime())}}broadcast(e){this.patchMessage(UG(this.project(e)),`[data-message-id="${e.id}"]`)}ensure(e){let t=this.presentation.get(e);if(!t)t={presentationState:"plain",presentationVersion:0},this.presentation.set(e,t);return t}async renderEnhancement(e,t){if(e==="markdown")return await oi.measure("markdownEnhancement",()=>this.renderMarkdownEnhancement(t));let n=oi.startSpan("toolEnhancement");try{if(e==="diff")return await this.renderDiffEnhancement(t)??await s9t(t,"diff",{chrome:!1});return await this.renderCodeEnhancement(t,"bash")}finally{n()}}}var y_i;var u0r=m(()=>{jR();Gle();Jce();K4e();ile();y_i=new Set(["assistant","thought","compaction","summary","skill"])});class wmt{store;hub;messages;displayClients=new hmt;updateDepth=0;commitPending=!1;commitScheduled=!1;pendingEffects=[];pendingEnhancements=new Set;pickersDirty=!1;sessionsDirty=!1;sessionSidebarDirty=!1;workspaceReviewDirty=!1;replaceTranscriptOnCommit=!1;constructor(e,t,n={}){this.store=e;this.hub=t;this.messages=new ymt(e,(r,a)=>t.patchElement(r,a),(r)=>this.pendingEnhancements.add(r),n),e.attachPresentation(this)}createStream(e,t=crypto.randomUUID()){this.flush(),this.displayClients.connect(t),this.messages.setDisplayRefreshHz(this.displayClients.targetHz);let n=()=>{if(this.displayClients.disconnect(t),this.messages.setDisplayRefreshHz(this.displayClients.targetHz),this.hub.clientCount===0)this.pendingEnhancements.clear(),this.messages.transcriptReplacing()};try{return this.hub.createStream(e,()=>{if(this.hub.clientCount===1)this.messages.transcriptReplaced([this.store.transcript.activeThoughtMessageId,this.store.transcript.activeAssistantMessageId],[]);let r=this.store.snapshot(),a=this.renderView({},this.projectState(r));if(this.hub.clientCount===1)queueMicrotask(()=>{if(this.hub.clientCount===0)return;for(let i of r.messages.toReversed())this.messages.enqueueEnhancement(i.id)});return a},{onDisconnect:n})}catch(r){throw n(),r}}beginUpdate(){this.updateDepth+=1}endUpdate(e,t){if(this.updateDepth-=1,e)this.requestCommit();if(this.updateDepth===0&&this.commitPending)this.requestCommit();if(t)this.flush()}requestCommit(e){if(this.commitPending=!0,e)this.pendingEffects.push(e);if(this.updateDepth>0||this.commitScheduled)return;this.commitScheduled=!0,queueMicrotask(()=>{if(!this.commitScheduled)return;this.commitScheduled=!1,this.flush()})}flush(){if(this.updateDepth>0||!this.commitPending)return;this.commitPending=!1,this.commitScheduled=!1;let e=this.pendingEffects;this.pendingEffects=[];let t=[...this.pendingEnhancements];this.pendingEnhancements.clear();let n={pickers:this.pickersDirty,sessions:this.sessionsDirty,sessionSidebar:this.sessionSidebarDirty,workspaceReview:this.workspaceReviewDirty};if(this.pickersDirty=!1,this.sessionsDirty=!1,this.sessionSidebarDirty=!1,this.workspaceReviewDirty=!1,this.hub.clientCount>0){let r=this.store.snapshot();if(this.replaceTranscriptOnCommit)this.hub.replaceElement(this.renderTranscript(this.projectState(r)),"#messages");this.hub.patchView(this.replaceTranscriptOnCommit?"":this.renderAppElements(r),this.renderSignals(r,this.effectSignalOverrides(e)),this.mainEffectScripts(e)),this.patchDirtyRegions(r,e,n)}if(this.replaceTranscriptOnCommit=!1,this.hub.clientCount>0)for(let r of t)this.messages.enqueueEnhancement(r)}patchDirtyRegions(e,t,n){if(n.pickers)this.hub.patchView(this.renderPickerElements(e),"{}",this.pickerEffectScripts(t));if(n.sessions)this.hub.patchView(S4(e)+zG(e)+(e.messages.length===0?this.renderTranscript(this.projectState(e)):""),"{}",[]);else if(n.sessionSidebar)this.hub.patchView(zG(e),"{}",[]);if(n.workspaceReview)this.hub.patchView(UOe(e.workspacePath,e.workspaceFilesRevision,e.workspaceTreeRevision,e.workspaceReview,e.workspaceReviewPreferences),"{}",[])}messageAppended(e){if(this.hub.clientCount===0)return;this.messages.messageAppended(e),this.appendMessage(e)}messagesRemoved(e){if(e<=0)return;this.hub.patchElement("",`#message-list > [data-message-id]:nth-last-child(n + ${this.store.messages.length+1})`,{mode:"remove"})}appendMessage(e){if(this.store.messages.length===1){this.hub.patchElement(this.messages.renderMessagesElement(),"#messages");return}let t=this.messages.renderMessageElement(e);if(t)this.hub.patchElement(t,"#message-list",{mode:"append",scripts:["window.piUi.messageScroll.trimOldMessages()"]})}messageUpdated(e){if(this.hub.clientCount===0)return;this.messages.messageUpdated(e)}pickersChanged(){this.pickersDirty=!0}sessionsChanged(){this.sessionsDirty=!0}sessionSidebarChanged(){this.sessionSidebarDirty=!0}workspaceReviewChanged(){this.workspaceReviewDirty=!0}codeThemeChanged(){if(this.hub.clientCount>0)this.messages.codeThemeChanged();else this.messages.transcriptReplacing();this.replaceTranscriptOnCommit=!0,this.requestCommit()}fontsChanged(){this.requestCommit()}streamingMessageStarted(e){if(this.hub.clientCount===0)return;this.messages.streamingMessageStarted(e),this.appendMessage(e)}streamingMessageChanged(){if(this.hub.clientCount===0)return;this.messages.streamingMessageChanged()}sessionTransitionChanged(e){if(this.hub.clientCount===0)return;this.hub.patchView("",this.renderSignals(this.store.snapshot()),e?["window.piUi.messageScroll.scrollBottom()"]:[])}assistantFinished(e){if(this.hub.clientCount===0)return;this.messages.assistantFinished(e)}transcriptReplacing(){this.replaceTranscriptOnCommit=!0,this.messages.transcriptReplacing()}transcriptReplaced(e,t){if(this.hub.clientCount>0)this.messages.transcriptReplaced(e,t)}patchOlderMessages(e){if(this.hub.clientCount===0)return;this.hub.patchElement(this.messages.renderOlderMessagesPatch(e),"#older-messages-trigger",{mode:"after",scripts:["window.piUi.messageScroll.restoreAnchor()"]}),this.hub.patchElement(this.messages.renderOlderMessagesTrigger(),"#older-messages-trigger");for(let t of e.toReversed())this.messages.enqueueEnhancement(t.id)}setDisplayRefreshHz(e,t){if(!this.displayClients.setHz(e,t))return!1;return this.messages.setDisplayRefreshHz(this.displayClients.targetHz),!0}projectState(e){return{...e,messages:this.messages.projectMessages(e.messages)}}renderElements(e){return this.renderTranscript(e)+this.renderAppElements(e)}renderTranscript(e){return v4(e.messages,e.emptyChatHint,e.hasOlderMessages,e.sessions,e.models.some((t)=>t.configured),e.sessionCatalogLoading)}renderAppElements(e){return fle(e)+fOe(e)+kle(e)+lle(e)+B4(e,"aboveEditor")+B4(e,"belowEditor")+hle(e)+rle(e)+Loe(e)}renderPickerElements(e){return oMe(e.authDialog)+dMe(e.extensionDialog)+hMe(e.llamaDialog)+gle(e)+yle(e)+ble(e)+mle(e)+Sle(e)}renderSignals(e,t={}){return JSON.stringify({...Roe(e),...t})}renderView(e={},t=this.projectState(this.store.snapshot())){return{elements:this.renderElements(t)+this.renderPickerElements(t)+S4(t)+zG(t)+UOe(t.workspacePath,t.workspaceFilesRevision,t.workspaceTreeRevision,t.workspaceReview,t.workspaceReviewPreferences),signals:this.renderSignals(t,e),scripts:this.initialDialogScripts(t)}}effectSignalOverrides(e){return Object.assign({},...e.filter((t)=>t.type==="signal-overrides").map((t)=>t.values))}mainEffectScripts(e){let t=[];for(let n of e){if(n.type==="document-title")t.push(`document.title = ${JSON.stringify(n.title)}`);if(n.type==="scroll-transcript-bottom")t.push("window.piUi.messageScroll.scrollBottom()")}return t}pickerEffectScripts(e){let t=[];for(let n of e){if(n.type==="restore-model-picker")t.push("requestAnimationFrame(() => document.getElementById('model-select-input')?.focus())");if(n.type==="dialog")if(n.open&&n.id==="tree-dialog")t.push("window.piUi.dialogs.openTree()");else t.push(n.open?`{ const dialog = document.getElementById('${n.id}'); if (dialog && !dialog.open) dialog.showModal(); }`:`{ const dialog = document.getElementById('${n.id}'); if (dialog?.open) dialog.close(); }`)}return[...new Set(t)]}initialDialogScripts(e){return[["auth-dialog",e.authDialog],["extension-dialog",e.extensionDialog],["llama-dialog",e.llamaDialog]].filter((t)=>Boolean(t[1])).map(([t])=>`{ const dialog = document.getElementById('${t}'); if (dialog && !dialog.open) dialog.showModal(); }`)}}var d0r=m(()=>{sMe();cMe();uMe();s0r();mMe();dOe();bMe();u0r();ile();GR();pOe();hOe();gOe();ule();AOe();ple();E4();kOe();GOe()});class kmt{streamFactory;recordPerformance;clients=new Map;disconnectCallbacks=new Map;constructor(e=y2e,t=!0){this.streamFactory=e;this.recordPerformance=t}get clientCount(){return this.clients.size}createStream(e,t,n={}){let r=crypto.randomUUID();return this.streamFactory((a)=>{if(this.clients.set(r,a),n.onDisconnect)this.disconnectCallbacks.set(r,n.onDisconnect);try{let i=t();this.patchClient(a,i.elements,i.signals,i.scripts??[])}catch{this.disconnect(r,a);return}e.addEventListener("abort",()=>this.disconnect(r,a),{once:!0})},{keepalive:!0,onAbort:()=>this.disconnectById(r)})}patchView(e,t,n){for(let[r,a]of this.clients)try{this.patchClient(a,e,t,n)}catch{this.disconnect(r,a)}}patchElement(e,t,n={}){for(let[r,a]of this.clients)try{a.patchElements(e,{selector:t,mode:n.mode??"outer"});for(let i of n.scripts??[])a.executeScript(i);if(this.recordPerformance)oi.recordTargetedMessagePatch(e)}catch{this.disconnect(r,a)}}replaceElement(e,t){for(let[n,r]of this.clients)try{if(r.patchElements(e,{selector:t,mode:"replace"}),this.recordPerformance)oi.recordFatMorph(e),oi.markFirstTranscriptPatch()}catch{this.disconnect(n,r)}}patchSignals(e){for(let[t,n]of this.clients)try{n.patchSignals(e)}catch{this.disconnect(t,n)}}patchClient(e,t,n,r){if(t){if(e.patchElements(t),this.recordPerformance){if(oi.recordFatMorph(t),t.includes('id="messages"'))oi.markFirstTranscriptPatch()}}if(e.patchSignals(n),r.length>0)e.executeScript(r.join(";"))}disconnectById(e){let t=this.clients.get(e);if(t)this.disconnect(e,t)}disconnect(e,t){if(!this.clients.delete(e))return;let n=this.disconnectCallbacks.get(e);this.disconnectCallbacks.delete(e),n?.();try{t.close()}catch{}}}var p0r=m(()=>{jR();em()});import{readdir as k_i,readFile as __i,stat as x_i}from"fs/promises";import{extname as C_i,relative as m0r,resolve as USe,sep as E_i}from"path";async function g0r(e){let t=await S_i(e),n=`/static/${t}/`;return{version:t,serve:async(r)=>{let a=new URL(r.url),i=a.pathname.startsWith(n),o=i?`/${a.pathname.slice(n.length)}`:a.pathname,s=v_i(e,o);if(!s)return new Response("Not found",{status:404});try{if(!(await x_i(s)).isFile())return new Response("Not found",{status:404})}catch{return new Response("Not found",{status:404})}return new Response(Bun.file(s),{headers:{"cache-control":i?"public, max-age=31536000, immutable":"no-cache, must-revalidate","content-type":I_i(s)}})}}}function v_i(e,t){let n;try{n=decodeURIComponent(t)}catch{return}let r=USe(e,`.${n}`),a=m0r(e,r);if(a.startsWith(`..${E_i}`)||a==="..")return;return r}function I_i(e){return{".css":"text/css; charset=utf-8",".gif":"image/gif",".html":"text/html; charset=utf-8",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".wasm":"application/wasm",".webmanifest":"application/manifest+json; charset=utf-8",".webp":"image/webp"}[C_i(e).toLowerCase()]??"application/octet-stream"}async function S_i(e){let t=await B_i(e),n=new Bun.CryptoHasher("sha256");for(let r of t)n.update(`${m0r(e,r)}\x00`),n.update(await __i(r));return n.digest("hex").slice(0,16)}async function B_i(e){let t=[],n=async(r)=>{for(let a of await k_i(r,{withFileTypes:!0})){let i=USe(r,a.name);if(a.isDirectory()){if(i===USe(e,"build/chunks")||i===USe(e,"build/assets"))continue;await n(i)}else if(a.isFile()&&!a.name.includes("_test."))t.push(i)}};return await n(e),t.sort()}var A0r=()=>{};import{watch as T_i}from"fs";import D_i from"os";import*as Bne from"path";class _mt{store;generation=0;timer;watchers=[];constructor(e){this.store=e;e.listenForWorkspacePath((t)=>this.open(t))}open(e){let t=++this.generation;this.stopWatcher(),this.watch(e,t).catch((n)=>{if(t===this.generation)console.error("Failed to watch workspace",n)})}dispose(){this.generation++,this.stopWatcher()}async watch(e,t){let n=!1,r=!1,a=!1,i={},o=()=>t===this.generation,s=async()=>{if(n){r=!0;return}n=!0;try{do{r=!1;let g=await dhr(e,a?void 0:(A)=>{if(o())this.store.setWorkspaceReview(A)},i);if(o())this.store.setWorkspaceReview(g),a=!0}while(r&&o())}finally{n=!1}};if(await s(),!o())return;let c=await uhr(e);if(!o())return;i={};let u=new Set,l=!1,d=async()=>{if(!o())return;let g=u;if(u=new Set,this.store.workspaceFilesChanged(l),l=!1,g&&c?.[0]&&await lhr(c[0],[...g]))return;if(o())await s()},p=(g,A,f)=>{if(!o())return;let h=f?.replaceAll("\\","/");if(c&&h){let b=g===c[0]?".git/":"",y=h.startsWith(b)?h.slice(b.length):"";if(y.startsWith("objects/")||y.startsWith("logs/")||y.endsWith(".lock"))return}if(A!=="change"||!f)l=!0;if(A==="change"&&f&&h&&g===c?.[0]&&h!==".git"&&!h.startsWith(".git/")&&h.split("/").at(-1)!==".gitignore")u?.add(f);else u=void 0,i={};if(this.timer!==void 0)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=void 0,d()},R_i)};this.watchers=(c??[e]).map((g)=>T_i(g,{recursive:c!==void 0||M_i(e)},(A,f)=>p(g,A,f)))}stopWatcher(){if(this.timer!==void 0)clearTimeout(this.timer);this.timer=void 0;for(let e of this.watchers)e.close();this.watchers=[]}}function M_i(e){let t=Bne.resolve(e),n=D_i.homedir();return t!==Bne.parse(t).root&&(!n||t!==Bne.resolve(n))}var R_i=200;var f0r=m(()=>{hSe()});var h0r={};Fe(h0r,{createApp:()=>F_i});import{realpath as P_i,stat as N_i}from"fs/promises";async function F_i(){let e=vI("fd",({message:w})=>console.error(w)),t=await g0r(Mpt),n=await X7t(),r=yTt(n.codeTheme)??wTt(),a=nTt(n.fonts)??eTt(),i=Ibr(n.autoTitle),o=Soe(n.gitView);yoe(r),hoe(a);let s=k4("bash"),c=new fmt;c.setWorkspaceReviewPreferences(o);let u=new ipt,l=new wmt(c,new kmt,{registerImage:(w)=>u.register(w),clearImages:()=>u.clear()}),d=new cU((w)=>c.setSessionTransition(w)),p=await A7.create(c,void 0,{autoTitle:i,transitionController:d}).catch((w)=>{console.error("Failed to start pi SDK runtime",w);return});if(!await s)console.error("Failed to preload shell highlighter");let g=new _mt(c);g.open(c.workspacePath);let A=await e,f={host:p,sessionImages:u,fdPath:A},h=await pSe.create(),b={store:c,renderer:l,resources:f,transferredFiles:h,appVersion:t.version,keybindHints:n.keybindHints!==!1,minimalMode:n.minimalMode===!0,toolOutputHidden:n.toolOutputHidden===!0,themeLab:process.env.PI_UI_THEME_LAB==="1",serveStatic:(w)=>t.serve(w),openWorkspace:(w)=>L_i(w,c,f,d,i)},y;return{context:b,dispose:()=>(y??=(async()=>{g.dispose(),await Promise.allSettled([h.dispose(),f.host?.dispose()])})(),y)}}async function L_i(e,t,n,r,a){let i=e.trim();return(await r.run(i,async()=>{let s=await P_i($R(i));if(!(await N_i(s)).isDirectory())throw Error("Not a directory");if(!n.host)return n.host=await A7.create(t,s,{autoTitle:a,refreshWorkspaces:!1,transitionController:r}),!0;return await n.host.openWorkspace(s)},{overlay:!1})).status==="success"}var b0r=m(()=>{lte();Rpt();r0r();lU();Noe();zL();Ux();o0r();Jce();d0r();jk();cR();YR();p0r();A0r();Ppt();mSe();f0r()});var _0r={};Fe(_0r,{compressResponse:()=>z_i,compressSseResponse:()=>y0r,preferredResponseEncoding:()=>xmt});import{Readable as O_i}from"stream";import{constants as GSe,createBrotliCompress as Q_i,createGzip as $_i,createZstdCompress as j_i}from"zlib";function z_i(e,t){if(!t.body||t.headers.has("content-encoding"))return t;let n=t.headers.get("content-type")?.split(";",1)[0].trim().toLowerCase();if(n==="text/event-stream")return y0r(e,t);if(e.method==="HEAD"||t.status===206||t.headers.has("content-range")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||!n||!K_i(n))return t;let r=t.headers.get("content-length");if(r&&Number(r)<q_i)return t;let a=new Headers(t.headers);a.set("vary",k0r(a.get("vary"),"Accept-Encoding"));let i=xmt(e.headers.get("accept-encoding"));if(!i)return W_i(t,a);return w0r(t,a,i)}function y0r(e,t){if(!t.body||t.headers.has("content-encoding")||t.headers.get("content-type")?.split(";",1)[0].trim().toLowerCase()!=="text/event-stream")return t;let n=xmt(e.headers.get("accept-encoding"));if(!n)return t;let r=new Headers(t.headers);return r.set("vary",k0r(r.get("vary"),"Accept-Encoding")),w0r(t,r,n,n)}function xmt(e){if(!e)return;let t=new Map;for(let i of e.split(",")){let[o,...s]=i.trim().split(";"),c=o.toLowerCase();if(!c)continue;let u=1;for(let l of s){let[d,p]=l.split("=",2).map((g)=>g.trim());if(d.toLowerCase()!=="q")continue;u=/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(p)?Number(p):0;break}t.set(c,Math.max(t.get(c)??0,u))}let n=t.get("*")??0,r,a=0;for(let i of U_i){let o=t.get(i)??n;if(o>a)r=i,a=o}return r}function w0r(e,t,n,r){let a=e.body;if(!a)return e;let i=V_i(n);Y_i(a.getReader(),i,r),t.set("content-encoding",n),t.delete("content-length");let o=O_i.toWeb(i);return new Response(o,{status:e.status,statusText:e.statusText,headers:t})}function W_i(e,t){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function K_i(e){return e.startsWith("text/")||e==="image/svg+xml"||H_i.has(e)||e.endsWith("+json")||e.endsWith("+xml")}function V_i(e){switch(e){case"zstd":return j_i();case"br":return Q_i({params:{[GSe.BROTLI_PARAM_QUALITY]:6}});case"gzip":return $_i()}}async function Y_i(e,t,n){let r=!1,a=()=>{if(!r)e.cancel().catch(()=>{})};t.once("close",a);try{while(!0){let{done:i,value:o}=await e.read();if(i){r=!0;break}let s=n==="br"?G_i:o.length;for(let c=0;c<o.length;c+=s)if(await Z_i(t,o.subarray(c,c+s)),n)await J_i(t,n)}if(!t.destroyed)await X_i(t)}catch(i){if(await e.cancel(i).catch(()=>{}),!t.destroyed)t.destroy(i instanceof Error?i:Error(String(i)))}finally{t.off("close",a),e.releaseLock()}}function Z_i(e,t){return new Promise((n,r)=>{e.write(t,(a)=>a?r(a):n())})}function J_i(e,t){let n={zstd:GSe.ZSTD_e_flush,br:GSe.BROTLI_OPERATION_FLUSH,gzip:GSe.Z_SYNC_FLUSH}[t];return new Promise((r)=>e.flush(n,r))}function X_i(e){return new Promise((t)=>e.end(t))}function k0r(e,t){if(!e)return t;let n=e.split(",").map((r)=>r.trim().toLowerCase());return n.includes("*")||n.includes(t.toLowerCase())?e:`${e}, ${t}`}var U_i,G_i=4096,q_i=1024,H_i;var x0r=m(()=>{U_i=["zstd","br","gzip"],H_i=new Set(["application/javascript","application/json","application/manifest+json","application/xhtml+xml","application/xml"])});var v0r={};Fe(v0r,{disposeApp:()=>nxi,fallback:()=>txi,routes:()=>exi});async function txi(e){let t=await E0r(),n=e.method==="GET"?await t.app.context.serveStatic(e):ov(404,"Not found.");return t.compressResponse(e,n)}async function nxi(){await(await C0r?.catch(()=>{return}))?.app.dispose()}function rxi(e){return async(t)=>{let n=await E0r();return n.compressResponse(t,await WBt(t,n.app.context,e))}}function E0r(){return C0r??=axi()}async function axi(){let[{registerBunOAuthFlows:e},{createApp:t},{compressResponse:n}]=await Promise.all([Promise.resolve().then(() => (vbr(),Ebr)),Promise.resolve().then(() => (b0r(),h0r)),Promise.resolve().then(() => (x0r(),_0r))]);return e(),{app:await t(),compressResponse:n}}var C0r,exi;var I0r=m(()=>{em();Vm();Ihr();exi=Object.fromEntries(Object.entries(vhr).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([n,r])=>[n,rxi(r)]))]))});import{userInfo as swr}from"os";var cwr="printf '\\0'; command env -0; printf '\\0'";async function Vmt(e={}){let t=e.environment??process.env,n=e.platform??process.platform,r=e.isTerminal??Boolean(process.stdin.isTTY);if(n==="win32"||r)return;let a=t.SHELL??swr().shell;if(!a)return;let i=await(e.readOutput??lwr)(a,t);if(i!==void 0)Object.assign(t,uwr(i))}async function lwr(e,t){try{let n=Bun.spawn([e,"-ilc",cwr],{env:t,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:5000}),[r,a]=await Promise.all([n.exited,new Response(n.stdout).text()]);return r===0?a:void 0}catch{return}}function uwr(e){let t=e.indexOf("\x00"),n=e.indexOf("\x00\x00",t+1);if(t<0||n<0)return{};let r={};for(let a of e.slice(t+1,n).split("\x00")){let i=a.indexOf("=");if(i<=0)continue;r[a.slice(0,i)]=a.slice(i+1)}return r}iv();import{mkdir as dwr}from"fs/promises";import{homedir as pwr}from"os";import{dirname as mwr}from"path";var qF="pi-ui",y7="pi-ui-server",a2e="dev.pi.ui",Ymt="dev.pi.ui.server",Zmt="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";function Jmt(e=xp,t=kwr()){if(e!=="linux"&&e!=="darwin"&&e!=="windows")throw Error(`server autostart is not supported on ${e}`);let n=pwr();if(!n)throw Error("could not determine the user home directory");let r=t.standalone?void 0:t.script;if(!t.standalone&&!r)throw Error("could not determine the pi-ui server script");return{platform:e,executable:t.executable,args:r?[r]:[],home:n,uid:e==="darwin"?process.getuid?.():void 0,transient:r?_wr(r):!1}}async function Xmt(e=Jmt()){if(e.transient)throw Error("bunx cannot install the background service. install pi-ui first with: bun i -g @hyperpuncher/pi-ui");switch(e.platform){case"linux":await hwr(e);break;case"darwin":await bwr(e);break;case"windows":await ywr(e);break}}async function egt(e=Jmt()){switch(e.platform){case"linux":await e2e(e,qF),await e2e(e,y7),await yh("systemctl",["--user","daemon-reload"]);break;case"darwin":await t2e(e,a2e),await t2e(e,Ymt);break;case"windows":await wwr(e);break}}function gwr(e){return`[Unit]
4339
4339
  Description=pi-ui server
4340
4340
  After=graphical-session.target
@@ -4378,4 +4378,4 @@ options:
4378
4378
  --host <hostname> listen hostname (default: 127.0.0.1; env: PI_UI_HOST)
4379
4379
  --port <port> listen port (default: 31415; env: PI_UI_PORT)
4380
4380
  --version show the version
4381
- -h, --help show this help`;function o2e(e,t){let n=e?.trim();if(!n)throw Error(`${t} requires a non-empty hostname`);return n}function s2e(e,t){if(!e||!/^\d+$/.test(e))throw Error(`${t} must be an integer from 1 to 65535`);let n=Number(e);if(n<1||n>65535)throw Error(`${t} must be an integer from 1 to 65535`);return n}var lgt={name:"@hyperpuncher/pi-ui",version:"0.42.0",description:"keyboard-first minimal gui for pi",homepage:"https://pi-ui.app",bugs:"https://github.com/hyperpuncher/pi-ui/issues",license:"MIT",repository:{type:"git",url:"git+https://github.com/hyperpuncher/pi-ui.git"},bin:{"pi-ui":"dist/npm/server-main.js"},files:["dist/npm","static"],type:"module",imports:{"#testing/assertions":"./src/testing/assertions.ts","#testing/files":"./src/testing/files.ts","#testing/temp":"./src/testing/temp.ts"},publishConfig:{access:"public"},scripts:{dev:"bun run assets:build && bun src/server-main.ts","assets:build":"bun scripts/build-assets.ts",build:"bun run assets:build && bun scripts/build.ts","npm:build":"bun run assets:build && bun scripts/build-npm.ts",prepack:"bun run npm:build",run:"./dist/pi-ui",release:"bun scripts/release.ts","schema:build":"bun scripts/generate-config-schema.ts","schema:check":"bun scripts/generate-config-schema.ts --check",fmt:"bun run schema:build && ~/projects/dsfmt/target/release/dsfmt --write . && bunx oxfmt",lint:"bunx oxlint && bun run lint:css","lint:css":'bunx stylelint "src/**/*.css"',"lint:fix":"bunx oxlint --fix && bun run lint:css --fix",check:"bun run schema:check && bunx tsc --noEmit",test:"bun test",audit:"bunx fallow audit"},devDependencies:{"@earendil-works/pi-ai":"^0.85.1","@earendil-works/pi-coding-agent":"^0.85.1","@earendil-works/pi-tui":"^0.85.1","@iconify-json/lucide":"^1.2.129","@kitajs/html":"5.0.0-next.1","@oxlint/plugins":"1.81.0","@pierre/diffs":"^1.4.1","@pierre/trees":"^1.0.0-beta.6","@starfederation/datastar-sdk":"^1.0.0","@types/bun":"^1.4.0","open-props":"^1.7.23",oxfmt:"^0.66.0",oxlint:"1.81.0",stylelint:"^17.15.0","stylelint-config-standard":"^40.0.0",typebox:"^1.3.27",typescript:"^7.0.2"},engines:{bun:">=1.4.0"},packageManager:"bun@1.4.0"};function ugt(e){return e.length===1&&e[0]==="--version"}var dgt=lgt.version;async function ixi(){let e=process.argv.slice(2);if(ugt(e))console.log(dgt);else if(e[0]==="service"||e[0]==="autostart"){let t=e[0]==="service"?"install":"enable",n=e[0]==="service"?"uninstall":"disable";if(e.length!==2||e[1]!==t&&e[1]!==n)throw Error("usage: pi-ui service install|uninstall");if(e[1]===t)await Xmt(),console.log("pi-ui service installed and started");else await egt(),console.log("pi-ui service stopped and uninstalled")}else{await Vmt();let t=sgt(e,{host:process.env.PI_UI_HOST,port:process.env.PI_UI_PORT});if(t.help)console.log(cgt);else{let{disposeApp:n,fallback:r,routes:a}=await Promise.resolve().then(() => (I0r(),v0r)),i=Bun.serve({hostname:t.hostname,port:t.port,idleTimeout:0,routes:a,fetch:r}),o=!1,s=async()=>{if(o)return;o=!0,await i.stop(),await n()};process.once("SIGINT",()=>void s()),process.once("SIGTERM",()=>void s()),console.log(`pi-ui listening on ${i.url}`)}}}process.on("unhandledRejection",(e)=>{console.error("Unhandled rejection",e)});process.on("uncaughtException",(e)=>{console.error("Unhandled error",e)});ixi().catch((e)=>{console.error(e),process.exitCode=1});
4381
+ -h, --help show this help`;function o2e(e,t){let n=e?.trim();if(!n)throw Error(`${t} requires a non-empty hostname`);return n}function s2e(e,t){if(!e||!/^\d+$/.test(e))throw Error(`${t} must be an integer from 1 to 65535`);let n=Number(e);if(n<1||n>65535)throw Error(`${t} must be an integer from 1 to 65535`);return n}var lgt={name:"@hyperpuncher/pi-ui",version:"0.42.1",description:"keyboard-first minimal gui for pi",homepage:"https://pi-ui.app",bugs:"https://github.com/hyperpuncher/pi-ui/issues",license:"MIT",repository:{type:"git",url:"git+https://github.com/hyperpuncher/pi-ui.git"},bin:{"pi-ui":"dist/npm/server-main.js"},files:["dist/npm","static"],type:"module",imports:{"#testing/assertions":"./src/testing/assertions.ts","#testing/files":"./src/testing/files.ts","#testing/temp":"./src/testing/temp.ts"},publishConfig:{access:"public"},scripts:{dev:"bun run assets:build && bun src/server-main.ts","assets:build":"bun scripts/build-assets.ts",build:"bun run assets:build && bun scripts/build.ts","npm:build":"bun run assets:build && bun scripts/build-npm.ts",prepack:"bun run npm:build",run:"./dist/pi-ui",release:"bun scripts/release.ts","schema:build":"bun scripts/generate-config-schema.ts","schema:check":"bun scripts/generate-config-schema.ts --check",fmt:"bun run schema:build && ~/projects/dsfmt/target/release/dsfmt --write . && bunx oxfmt",lint:"bunx oxlint && bun run lint:css","lint:css":'bunx stylelint "src/**/*.css"',"lint:fix":"bunx oxlint --fix && bun run lint:css --fix",check:"bun run schema:check && bunx tsc --noEmit",test:"bun test",audit:"bunx fallow audit"},devDependencies:{"@earendil-works/pi-ai":"^0.85.1","@earendil-works/pi-coding-agent":"^0.85.1","@earendil-works/pi-tui":"^0.85.1","@iconify-json/lucide":"^1.2.129","@kitajs/html":"5.0.0-next.1","@oxlint/plugins":"1.81.0","@pierre/diffs":"^1.4.1","@pierre/trees":"^1.0.0-beta.6","@starfederation/datastar-sdk":"^1.0.0","@types/bun":"^1.4.0","open-props":"^1.7.23",oxfmt:"^0.66.0",oxlint:"1.81.0",stylelint:"^17.15.0","stylelint-config-standard":"^40.0.0",typebox:"^1.3.27",typescript:"^7.0.2"},engines:{bun:">=1.4.0"},packageManager:"bun@1.4.0"};function ugt(e){return e.length===1&&e[0]==="--version"}var dgt=lgt.version;async function ixi(){let e=process.argv.slice(2);if(ugt(e))console.log(dgt);else if(e[0]==="service"||e[0]==="autostart"){let t=e[0]==="service"?"install":"enable",n=e[0]==="service"?"uninstall":"disable";if(e.length!==2||e[1]!==t&&e[1]!==n)throw Error("usage: pi-ui service install|uninstall");if(e[1]===t)await Xmt(),console.log("pi-ui service installed and started");else await egt(),console.log("pi-ui service stopped and uninstalled")}else{await Vmt();let t=sgt(e,{host:process.env.PI_UI_HOST,port:process.env.PI_UI_PORT});if(t.help)console.log(cgt);else{let{disposeApp:n,fallback:r,routes:a}=await Promise.resolve().then(() => (I0r(),v0r)),i=Bun.serve({hostname:t.hostname,port:t.port,idleTimeout:0,routes:a,fetch:r}),o=!1,s=async()=>{if(o)return;o=!0,await i.stop(),await n()};process.once("SIGINT",()=>void s()),process.once("SIGTERM",()=>void s()),console.log(`pi-ui listening on ${i.url}`)}}}process.on("unhandledRejection",(e)=>{console.error("Unhandled rejection",e)});process.on("uncaughtException",(e)=>{console.error("Unhandled error",e)});ixi().catch((e)=>{console.error(e),process.exitCode=1});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperpuncher/pi-ui",
3
- "version": "0.42.0",
3
+ "version": "0.42.1",
4
4
  "description": "keyboard-first minimal gui for pi",
5
5
  "homepage": "https://pi-ui.app",
6
6
  "bugs": "https://github.com/hyperpuncher/pi-ui/issues",