@hyperpuncher/pi-ui 0.63.1 → 0.64.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/npm/server-main.js +5 -5
- package/package.json +1 -1
- package/static/build/main.js +4 -4
package/dist/npm/server-main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var n6n=Object.create;var{getPrototypeOf:r6n,defineProperty:l4,getOwnPropertyNames:Pet,getOwnPropertyDescriptor:a6n}=Object,nke=Object.prototype.hasOwnProperty;function Net(e){return this[e]}var i6n,o6n,mn=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var a=t?i6n??=new WeakMap:o6n??=new WeakMap,i=a.get(e);if(i)return i}n=e!=null?n6n(r6n(e)):{};let o=t||!e||!e.__esModule||!nke.call(e,"default")?l4(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Pet(e))if(!nke.call(o,s))l4(o,s,{get:Net.bind(e,s),enumerable:!0})}if(r)a.set(e,o);return o},s6n=(e)=>{var t=(Let??=new WeakMap).get(e),n;if(t)return t;if(t=l4({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var r of Pet(e))if(!nke.call(t,r))l4(t,r,{get:Net.bind(e,r),enumerable:!(n=a6n(e,r))||n.enumerable})}return Let.set(e,t),t},Let,yt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var c6n=(e)=>e;function l6n(e,t){this[e]=c6n.bind(null,t)}var Ke=(e,t)=>{for(var n in t)l4(e,n,{get:t[n],enumerable:!0,configurable:!0,set:l6n.bind(t,n)})};var I=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var An=import.meta.require;async function I0(e,t={}){let n=Bun.spawn([e,...t.args??[]],{cwd:t.cwd,env:{...process.env,...t.env},stdin:t.stdin??"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0,signal:t.signal,timeout:t.timeout}),[r,a,i]=await Promise.all([new Response(n.stdout).bytes(),new Response(n.stderr).bytes(),n.exited]);return{code:i,stdout:r,stderr:a,success:i===0,timedOut:t.timeout!==void 0&&n.signalCode==="SIGTERM"&&!t.signal?.aborted}}function QY(e,t){return Error.isError(e)&&"code"in e&&e.code===t}function SY(e){return QY(e,"EEXIST")}function hc(e){return QY(e,"ENOENT")}function rke(e){return QY(e,"EACCES")||QY(e,"EPERM")}var DY,Md;var Uv=I(()=>{DY=globalThis.navigator?.platform??globalThis.process?.platform,Md=DY==="win32"||DY?.startsWith("Win")?"windows":DY==="darwin"||DY?.startsWith("Mac")?"darwin":"linux"});var ttt;var ett=I(()=>{ttt={name:"@hyperpuncher/pi-ui",version:"0.
|
|
3
|
+
var n6n=Object.create;var{getPrototypeOf:r6n,defineProperty:l4,getOwnPropertyNames:Pet,getOwnPropertyDescriptor:a6n}=Object,nke=Object.prototype.hasOwnProperty;function Net(e){return this[e]}var i6n,o6n,mn=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var a=t?i6n??=new WeakMap:o6n??=new WeakMap,i=a.get(e);if(i)return i}n=e!=null?n6n(r6n(e)):{};let o=t||!e||!e.__esModule||!nke.call(e,"default")?l4(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Pet(e))if(!nke.call(o,s))l4(o,s,{get:Net.bind(e,s),enumerable:!0})}if(r)a.set(e,o);return o},s6n=(e)=>{var t=(Let??=new WeakMap).get(e),n;if(t)return t;if(t=l4({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var r of Pet(e))if(!nke.call(t,r))l4(t,r,{get:Net.bind(e,r),enumerable:!(n=a6n(e,r))||n.enumerable})}return Let.set(e,t),t},Let,yt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var c6n=(e)=>e;function l6n(e,t){this[e]=c6n.bind(null,t)}var Ke=(e,t)=>{for(var n in t)l4(e,n,{get:t[n],enumerable:!0,configurable:!0,set:l6n.bind(t,n)})};var I=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var An=import.meta.require;async function I0(e,t={}){let n=Bun.spawn([e,...t.args??[]],{cwd:t.cwd,env:{...process.env,...t.env},stdin:t.stdin??"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0,signal:t.signal,timeout:t.timeout}),[r,a,i]=await Promise.all([new Response(n.stdout).bytes(),new Response(n.stderr).bytes(),n.exited]);return{code:i,stdout:r,stderr:a,success:i===0,timedOut:t.timeout!==void 0&&n.signalCode==="SIGTERM"&&!t.signal?.aborted}}function QY(e,t){return Error.isError(e)&&"code"in e&&e.code===t}function SY(e){return QY(e,"EEXIST")}function hc(e){return QY(e,"ENOENT")}function rke(e){return QY(e,"EACCES")||QY(e,"EPERM")}var DY,Md;var Uv=I(()=>{DY=globalThis.navigator?.platform??globalThis.process?.platform,Md=DY==="win32"||DY?.startsWith("Win")?"windows":DY==="darwin"||DY?.startsWith("Mac")?"darwin":"linux"});var ttt;var ett=I(()=>{ttt={name:"@hyperpuncher/pi-ui",version:"0.64.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","!static/app"],type:"module",imports:{"#src/*":"./src/*","#static/*":"./static/*","#tests/*":"./tests/*","#testing/*":"./tests/src/testing/*","#tools/*":"./tools/*","#package":"./package.json","#testing/assertions":"./tests/src/testing/assertions.ts","#testing/temp":"./tests/src/testing/temp.ts"},publishConfig:{access:"public"},scripts:{dev:"bun run assets:build && bun src/server-main.ts","assets:build":"bun scripts/generate-icons.ts && 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 && dsfmt --write . && bun fmt","fmt:check":"bun run schema:check && bun fmt --no-script --check",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 && bun check",test:"bun test --parallel=8",audit:"bunx fallow audit"},devDependencies:{"@earendil-works/pi-ai":"^1.5.0","@earendil-works/pi-coding-agent":"^1.5.0","@earendil-works/pi-schema":"^1.5.0","@earendil-works/pi-tui":"^1.5.0","@iconify-json/lucide":"^1.2.151","@kitajs/html":"5.0.0-next.1","@oxlint/plugins":"1.91.0","@pierre/diffs":"^1.6.4","@pierre/highlights":"0.4.0","@pierre/trees":"^1.0.0-beta.6","@starfederation/datastar-sdk":"^1.0.0","@types/bun":"^1.4.4","open-props":"^1.7.23",oxlint:"1.91.0",pele:"1.13.0",stylelint:"^18.0.0","stylelint-config-standard":"^41.0.0",typescript:"^7.0.2"},engines:{bun:">=1.4.4"},packageManager:"bun@1.4.4",patchedDependencies:{"@earendil-works/pi-coding-agent@1.5.0":"patches/@earendil-works%2Fpi-coding-agent@1.5.0.patch"}}});function ntt(e){return e.length===1&&e[0]==="--version"}var TY;var pke=I(()=>{ett();TY=ttt.version});var rtt=1000,att=!1,itt=!1,Ake="selector",MY="mode",mke="elements",d4="namespace",ott="useViewTransition",gke="signals",stt="onlyIfMissing",fke,hke,ctt="outer",ltt="html";var bke=I(()=>{fke=["outer","inner","replace","prepend","append","before","after","remove"],hke=["html","svg","mathml"]});var utt,yke;var wke=I(()=>{bke();utt={"Cache-Control":"no-cache",Connection:"keep-alive","Content-Type":"text/event-stream"},yke={[MY]:ctt,[d4]:ltt,[ott]:att,[stt]:itt}});class Eke{constructor(){}validateElementPatchMode(e){if(!fke.includes(e))throw Error(`Invalid ElementPatchMode: "${e}". Valid modes are: ${fke.join(", ")}`)}validateNamespace(e){if(!hke.includes(e))throw Error(`Invalid namespace: "${e}". Valid namespaces are: ${hke.join(", ")}`)}validateRequired(e,t){if(!e||e.trim()==="")throw Error(`${t} is required and cannot be empty`)}send(e,t,n){let{eventId:r,retryDuration:a}=n||{},i=[`event: ${e}
|
|
4
4
|
`],o=r?[`id: ${r}
|
|
5
5
|
`]:[],s=!a||a===1000?[]:[`retry: ${a??rtt}
|
|
6
6
|
`];return i.concat(o,s,t.map((c)=>`data: ${c}
|
|
@@ -40,7 +40,7 @@ var n6n=Object.create;var{getPrototypeOf:r6n,defineProperty:l4,getOwnPropertyNam
|
|
|
40
40
|
});
|
|
41
41
|
}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}function H9n(e){return an(Kr.jsxDEV(Kr.Fragment,{children:[Kr.jsxDEV("header",{children:[Kr.jsxDEV("h2",{id:"auth-dialog-title",children:e.error?"Authentication failed":"Authentication updated"},void 0,!1,void 0,this),Kr.jsxDEV("p",{class:[e.error&&"error-foreground"],safe:!0,children:e.error??e.status},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Kr.jsxDEV("footer",{children:Kr.jsxDEV("button",{type:"button",class:"btn",commandfor:"auth-dialog",command:"close",children:"Done"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}var Kr,snt=`window.piUi.copyText(el.dataset.code).then((copied) => {
|
|
42
42
|
$_authCopyStatus = copied ? 'Code copied.' : 'Copy the code shown above.';
|
|
43
|
-
});`;var tBe=I(()=>{yi();Kr=mn(ur(),1)});function ei(e={}){return{type:"string",...e}}function fi(e={}){return{type:"number",...e}}function Qb(e={}){return{type:"integer",...e}}function Oi(e={}){return{type:"boolean",...e}}function YR(e={}){return{type:"null",...e}}function R0(e,t={}){return{enum:e,...t}}function Lc(e,t={}){return{anyOf:e,...t}}function iZ(e,t={}){return{anyOf:[e,{type:"null"}],...t}}function jd(e,t={}){return{type:"array",items:e,...t}}class oZ{schema;constructor(e){this.schema=e}}function In(e){return new oZ(e)}function wp(e,t={}){let{open:n,...r}=t,a={},i=[];for(let[o,s]of Object.entries(e))if(s instanceof oZ)a[o]=s.schema;else a[o]=s,i.push(o);return{type:"object",properties:a,...i.length>0?{required:i}:{},...n===!0?{}:{additionalProperties:!1},...r}}class nBe{draft;rootBase;baseOf=new Map;dynamicAnchors=new Map;root;options;registry=new Map;rejectUnresolved;unresolved=new Set;resources=new Map;anchors=new Map;indexed=!1;constructor(e,t){this.draft=t.draft==="7"?"7":"2020-12",this.root=e,this.options=t,this.rejectUnresolved=t.unresolvedRefs==="reject",this.rootBase=ua(e)?this.baseFor(e,"https://json-schema.invalid/root.json"):"https://json-schema.invalid/root.json"}baseFor(e,t){let n=this.baseOf.get(e);if(n!==void 0)return n;let r=e.$id;if(typeof r!=="string")return t;if(this.draft==="7"&&(typeof e.$ref==="string"||r.startsWith("#")))return t;return kC(EC(r,t))}ensureIndexed(){if(this.indexed)return;this.indexed=!0;for(let[e,t]of Object.entries(this.options.schemas??{}))this.registry.set(kC(EC(e,"https://json-schema.invalid/root.json")),t);this.resources.set("https://json-schema.invalid/root.json",this.root),this.index(this.root,"https://json-schema.invalid/root.json")}resolve(e,t){if(this.ensureIndexed(),!this.rejectUnresolved)return this.find(e,t);try{return this.find(e,t)}catch{return this.unresolved.add(EC(e,t)),{node:!1,base:t}}}isUnresolved(e,t){return this.unresolved.has(EC(e,t))}find(e,t){let n=EC(e,t),r=kC(n),a=n.length>r.length?decodeURIComponent(n.slice(r.length+1)):"",i=this.resources.has(r)?this.resources.get(r):this.load(r);if(i===void 0)throw Error(`Unresolved $ref ${e} (no schema registered for ${r})`);if(a==="")return{node:i,base:r};if(a.startsWith("/"))return this.pointer(i,r,a);let o=this.anchors.get(`${r}#${a}`);if(o===void 0)throw Error(`Unresolved $ref ${e} (no anchor ${a} in ${r})`);return{node:o,base:this.baseOf.get(o)??r}}isResource(e,t){return this.ensureIndexed(),this.resources.get(t)===e}index(e,t){if(!ua(e)||this.baseOf.has(e))return;let n=t,r=this.draft==="7"&&typeof e.$ref==="string";if(!r&&typeof e.$id==="string")if(this.draft==="7"&&e.$id.startsWith("#"))this.anchors.set(kC(n)+e.$id,e);else{let a=EC(e.$id,n);if(n=kC(a),this.resources.set(n,e),a.length>n.length+1)this.anchors.set(a,e)}if(this.baseOf.set(e,n),r)return;if(this.draft!=="7"){if(typeof e.$anchor==="string")this.anchors.set(`${n}#${e.$anchor}`,e);if(typeof e.$dynamicAnchor==="string")this.anchors.set(`${n}#${e.$dynamicAnchor}`,e),this.dynamicAnchors.set(`${n}#${e.$dynamicAnchor}`,e)}for(let a of W9n)this.index(e[a],n);for(let a of z9n){let i=e[a];if(ua(i))for(let o of Object.keys(i))this.index(i[o],n)}for(let a of J9n){let i=e[a];if(Array.isArray(i))for(let o of i)this.index(o,n)}}load(e){let t=this.registry.get(e);if(t===void 0)return;return this.resources.set(e,t),this.index(t,e),t}pointer(e,t,n){let r=e,a=t;for(let i of n.split("/").slice(1)){let o=i.replace(/~1/g,"/").replace(/~0/g,"~");if(r=typeof r==="object"&&r!==null&&Object.hasOwn(r,o)?r[o]:void 0,r===void 0)throw Error(`Unresolved $ref #${n} in ${t}`);if(typeof r==="object"&&r!==null)a=this.baseOf.get(r)??a}return{node:r,base:a}}}function ua(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function EC(e,t){try{return new URL(e,t).href}catch{return e.startsWith("#")?kC(t)+e:e}}function kC(e){let t=e.indexOf("#");return t<0?e:e.slice(0,t)}var W9n,z9n,J9n;var sZ=I(()=>{W9n=["additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems","additionalItems","contentSchema","items"],z9n=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"],J9n=["allOf","anyOf","oneOf","prefixItems","items"]});function Sb(e){let t=cZ.get(e)?.deref();if(t!==void 0)return t;let n;try{n=new RegExp(e,"u")}catch{n=new RegExp(e)}return cZ.set(e,new WeakRef(n)),K9n.register(n,e),n}var cZ,K9n;var lZ=I(()=>{cZ=new Map,K9n=new FinalizationRegistry((e)=>{if(cZ.get(e)?.deref()===void 0)cZ.delete(e)})});class aBe{c;schema;entered=[];cuts=0;memo=void 0;constructor(e,t){this.c=e,this.schema=t}coerce(e){let t=this.c.r.rootBase,n=this.dropOptionalNulls(e,this.schema,t);return this.coerceTypes(this.convertOnly(n),this.schema,t)}convertOnly(e){try{return this.convert(this.schema,this.c.r.rootBase,e)}finally{this.memo=void 0,this.cuts=0}}reenter(e,t,n,r){let a=this.entered;for(let c=0;c<a.length;c+=2)if(a[c]===e&&Object.is(a[c+1],n))return this.cuts++,n;let i=r?this.memo?.get(e):void 0;if(i?.has(n))return i.get(n);let o=this.cuts;a.push(e,n);let s;try{s=this.convert(e,t,n)}finally{a.length-=2}if(r&&this.cuts===o){this.memo??=new Map;let c=this.memo.get(e);if(c===void 0)c=new Map,this.memo.set(e,c);c.set(n,s)}return s}passes(e,t,n){try{return this.c.check(e,this.baseOf(e,t))(n)}catch{return}}baseOf(e,t){return ua(e)?this.c.r.baseOf.get(e)??t:t}dropOptionalNulls(e,t,n){if(!ua(t))return e;let r=this.baseOf(t,n);if(Array.isArray(e))return uZ(e,(l,d)=>{let p=cnt(t,d);return p===void 0?l:this.dropOptionalNulls(l,p,r)});if(!pZ(e))return e;let a=ua(t.properties)?t.properties:{},i=ua(t.patternProperties)?Object.entries(t.patternProperties).map(([l,d])=>[Sb(l),d]):[],o=ua(t.additionalProperties)?t.additionalProperties:void 0;if(i.length===0&&o===void 0&&!ua(t.properties))return e;let s=new Set(Array.isArray(t.required)?t.required:[]),c,u=(l,d)=>{if(d===(c??e)[l])return;c??={...e},c[l]=d};for(let[l,d]of Object.entries(a)){if(!Object.hasOwn(e,l))continue;let p=ua(d)&&typeof d.$ref==="string";if(e[l]===null&&!s.has(l)&&!p&&this.passes(d,r,null)===!1){c??={...e},delete c[l];continue}u(l,this.dropOptionalNulls(e[l],d,r))}if(i.length>0||o!==void 0)for(let l of Object.keys(e)){let d=Object.hasOwn(a,l);for(let[p,A]of i){if(!p.test(l))continue;d=!0,u(l,this.dropOptionalNulls((c??e)[l],A,r))}if(!d&&o!==void 0)u(l,this.dropOptionalNulls(e[l],o,r))}return c??e}convert(e,t,n){if(!ua(e))return n;let r=this.baseOf(e,t);if(typeof e.$ref==="string"){let a;try{a=this.c.r.resolve(e.$ref,r)}catch{return n}return ua(a.node)?this.reenter(a.node,a.base,n,!0):n}return this.convertNode(e,r,n)}convertNode(e,t,n){if(Object.hasOwn(e,"const"))return lnt(e.const,n);if(Array.isArray(e.enum))return this.convertEnum(e,e.enum,t,n);if(Array.isArray(e.anyOf))return this.convertUnion(e,e.anyOf,t,n);if(Array.isArray(e.oneOf))return this.convertUnion(e,e.oneOf,t,n);if(Array.isArray(e.allOf)){let r=n;for(let a of e.allOf)r=this.convert(a,t,r);return this.convertMembers(e,t,r)}switch(e.type){case"string":return dZ(pnt(n),n);case"number":return dZ(rBe(n),n);case"integer":{let r=rBe(n);return r===void 0?n:Math.trunc(r.value)}case"boolean":return dZ(Ant(n),n);case"null":return dZ(Z9n(n),n);case"array":return this.convertArray(e,t,n);case"object":return this.convertObject(e,t,n);case void 0:if(e.properties!==void 0||e.patternProperties!==void 0)return this.convertObject(e,t,n);if(e.items!==void 0||e.prefixItems!==void 0)return this.convertArray(e,t,n);return n;default:return n}}convertEnum(e,t,n,r){if(t.some((a)=>a===r))return r;for(let a of t){let i=lnt(a,r);if(i!==r&&this.passes(e,n,i)===!0)return i}return r}convertUnion(e,t,n,r){if(t.some((a)=>this.passes(a,n,r)===!0))return this.convertMembers(e,n,r);for(let a of t){let i=this.convertMembers(e,n,this.convert(a,n,r));if(this.passes(e,n,i)===!0)return i}return this.convertMembers(e,n,r)}convertMembers(e,t,n){return e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0?this.convertObject(e,t,n):n}convertArray(e,t,n){let r=Array.isArray(e.items)?e.items:Array.isArray(e.prefixItems)?e.prefixItems:void 0;if(r!==void 0){if(!Array.isArray(n))return n;let i=Array.isArray(e.items)?void 0:e.items;return uZ(n,(o,s)=>{let c=s<r.length?r[s]:i;return c===void 0?o:this.convert(c,t,o)})}if(Array.isArray(n))return e.items===void 0?n:uZ(n,(i)=>this.convert(e.items,t,i));let a=e.items;return[ua(a)?this.reenter(a,t,n,!1):n]}convertObject(e,t,n){if(!pZ(n))return n;let r=ua(e.properties)?e.properties:{},a=ua(e.patternProperties)?Object.entries(e.patternProperties).map(([s,c])=>[Sb(s),c]):[],i=ua(e.additionalProperties)?e.additionalProperties:void 0,o;for(let s of Object.keys(n)){if(n[s]===void 0)continue;let c=n[s],u=Object.hasOwn(r,s);if(u)c=this.convert(r[s],t,c);for(let[l,d]of a){if(!l.test(s))continue;u=!0,c=this.convert(d,t,c)}if(!u&&i!==void 0)c=this.convert(i,t,c);if(c!==n[s])o??={...n},o[s]=c}return o??n}coerceTypes(e,t,n){if(!ua(t))return e;let r=this.baseOf(t,n),a=e;if(Array.isArray(t.allOf))for(let s of t.allOf)a=this.coerceTypes(a,s,r);if(Array.isArray(t.anyOf))a=this.coerceUnion(a,t.anyOf,r);if(Array.isArray(t.oneOf))a=this.coerceUnion(a,t.oneOf,r);let i=V9n(t),o=i.length>1&&i.some((s)=>X9n(a,s));if(i.length>0&&!o)for(let s of i){let c=e$n(a,s);if(c!==a){a=c;break}}if(i.includes("object")&&pZ(a))a=this.coerceProperties(a,t,r);if(i.includes("array")&&Array.isArray(a))a=this.coerceItems(a,t,r);return a}coerceUnion(e,t,n){for(let r of t)if(this.passes(r,n,e)===!0)return e;for(let r of t){let a=this.coerceTypes(e,r,n);if(this.passes(r,n,a)===!0)return a}return e}coerceProperties(e,t,n){let r=ua(t.properties)?t.properties:{},a=ua(t.patternProperties)?Object.entries(t.patternProperties).map(([c,u])=>[Sb(c),u]):[],i=ua(t.additionalProperties)?t.additionalProperties:void 0,o,s=(c,u)=>{if(u===(o??e)[c])return;o??={...e},o[c]=u};for(let[c,u]of Object.entries(r))if(c in e)s(c,this.coerceTypes(e[c],u,n));for(let c of Object.keys(e)){let u=Object.hasOwn(r,c);for(let[l,d]of a){if(!l.test(c))continue;u=!0,s(c,this.coerceTypes((o??e)[c],d,n))}if(!u&&i!==void 0)s(c,this.coerceTypes(e[c],i,n))}return o??e}coerceItems(e,t,n){return uZ(e,(r,a)=>{let i=cnt(t,a);return ua(i)?this.coerceTypes(r,i,n):r})}}function cnt(e,t){if(Array.isArray(e.items))return e.items[t];if(Array.isArray(e.prefixItems)&&t<e.prefixItems.length)return e.prefixItems[t];return e.items}function uZ(e,t){let n;for(let r=0;r<e.length;r++){let a=t(e[r],r);if(a===e[r])continue;n??=e.slice(),n[r]=a}return n??e}function dZ(e,t){return e===void 0?t:e.value}function lnt(e,t){if(e===t)return t;let n=typeof e==="string"?pnt(t):typeof e==="number"?rBe(t):typeof e==="boolean"?Ant(t):void 0;return n!==void 0&&n.value===e?n.value:t}function pnt(e){if(typeof e==="bigint"||typeof e==="boolean"||AZ(e))return{value:String(e)};if(e===null)return{value:"null"};if(typeof e==="string")return{value:e};if(e===void 0)return{value:""};return}function rBe(e){if(typeof e==="bigint")return e<=unt&&e>=dnt?{value:Number(e)}:void 0;if(typeof e==="boolean")return{value:e?1:0};if(AZ(e))return{value:e};if(e===null||e===void 0)return{value:0};if(typeof e!=="string")return;let t=+e;if(Number.isFinite(t))return{value:t};let n=e.toLowerCase();if(n==="false")return{value:0};if(n==="true")return{value:1};let r=Y9n(e);return r!==void 0&&r<=unt&&r>=dnt?{value:Number(r)}:void 0}function Y9n(e){if(/^-?(0|[1-9]\d*)n$/.test(e))return BigInt(e.slice(0,-1));if(/^-?(0|[1-9]\d*)\.\d+$/.test(e))return BigInt(e.split(".")[0]);if(/^-?(0|[1-9]\d*)$/.test(e))return BigInt(e);return}function Ant(e){if(typeof e==="bigint")return e===0n?{value:!1}:e===1n?{value:!0}:void 0;if(typeof e==="boolean")return{value:e};if(AZ(e))return e===0?{value:!1}:e===1?{value:!0}:void 0;if(e===null||e===void 0)return{value:!1};if(typeof e!=="string")return;let t=e.toLowerCase();if(t==="false"||e==="0")return{value:!1};if(t==="true"||e==="1")return{value:!0};return}function Z9n(e){if(typeof e==="bigint")return e===0n?{value:null}:void 0;if(typeof e==="boolean")return e===!1?{value:null}:void 0;if(AZ(e))return e===0?{value:null}:void 0;if(e===null||e===void 0)return{value:null};if(typeof e!=="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:null}:void 0}function AZ(e){return typeof e==="number"&&Number.isFinite(e)}function V9n(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((t)=>typeof t==="string");return[]}function X9n(e,t){switch(t){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return pZ(e);default:return!1}}function e$n(e,t){switch(t){case"number":case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let n=Number(e);if(t==="number"?Number.isFinite(n):Number.isInteger(n))return n}if(typeof e==="boolean")return e?1:0;return e}case"boolean":if(e===null)return!1;if(e==="true"||e===1)return!0;if(e==="false"||e===0)return!1;return e;case"string":if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e;case"null":return e===""||e===0||e===!1?null:e;default:return e}}function pZ(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var unt,dnt;var mnt=I(()=>{sZ();lZ();unt=BigInt(Number.MAX_SAFE_INTEGER),dnt=BigInt(Number.MIN_SAFE_INTEGER)});function aA(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function lBe(e,t){switch(e){case 1:return typeof t==="string";case 2:return typeof t==="number";case 3:return Number.isInteger(t);case 4:return typeof t==="boolean";case 5:return t===null;default:return!0}}function I4(e){switch(e.length){case 0:return Jv;case 1:return e[0];case 2:{let[t,n]=e;return(r)=>t(r)&&n(r)}case 3:{let[t,n,r]=e;return(a)=>t(a)&&n(a)&&r(a)}default:return(t)=>{for(let n=0;n<e.length;n++)if(!e[n](t))return!1;return!0}}}function knt(e){return(t)=>e.check(t)}function pBe(e,t,n){return(r)=>{e.push(t);let a=n(r);return e.pop(),a}}function Bnt(e){let t=e.map((n)=>(typeof n==="string"?x4.get(n):void 0)??C4);if(t.length===1)return t[0];return(n)=>{for(let r=0;r<t.length;r++)if(t[r](n))return!0;return!1}}function Cnt(e,t){return(n)=>n instanceof Uint8Array&&n.length>=e&&n.length<=t}function mZ(e){let t=0;for(let n=0;n<e.length;n++,t++){let r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);if(a>=56320&&a<=57343)n++}}return t}function iBe(e,t,n){let r=e.length;if(r<t)return!1;if(r<2*t&&mZ(e)<t)return!1;return r<=n||mZ(e)<=n}function xnt(e,t,n,r,a){if(r!==void 0&&t===0&&n===Number.POSITIVE_INFINITY&&a===void 0)return e?(i)=>typeof i==="string"&&r.test(i):(i)=>typeof i!=="string"||r.test(i);if(r===void 0&&a===void 0)return e?(i)=>typeof i==="string"&&iBe(i,t,n):(i)=>typeof i!=="string"||iBe(i,t,n);return(i)=>{if(typeof i!=="string")return!e;return iBe(i,t,n)&&(r===void 0||r.test(i))&&(a===void 0||a(i))}}function _nt(e,t,n,r,a,i){return(o)=>{if(typeof o!=="number")return e===0;if(e===2&&!Number.isInteger(o))return!1;return o>=t&&o<=n&&o>r&&o<a&&(i===void 0||ABe(o,i))}}function ABe(e,t){let n=e/t;if(Number.isInteger(n))return!0;if(!Number.isFinite(n))return e%t===0;let[r,a]=gnt(e),[i,o]=gnt(t);return a>=o?r*10n**BigInt(a-o)%i===0n:r%(i*10n**BigInt(o-a))===0n}function gnt(e){let[t,n="0"]=Math.abs(e).toString().split("e"),r=t.indexOf("."),a=r<0?0:t.length-r-1;return[BigInt(t.replace(".","")),Number(n)-a]}function Int(e,t){return t?(n)=>aA(n)&&e(n):(n)=>!aA(n)||e(n)}function vnt(e,t){return t?(n)=>Array.isArray(n)&&e(n):(n)=>!Array.isArray(n)||e(n)}function Qnt(e,t,n,r){let a=e.length;return(i)=>{if(r!==_4&&!aA(i))return r===ZR;let o=i,s=0;for(let c in o){let u=0;while(u<a&&e[u]!==c)u+=3;if(u===a){if(n)return!1;continue}let l=o[c];if(l===void 0)continue;let d=e[u+2],p=d&Ent;if(p!==0?!lBe(p,l):!e[u+1](l))return!1;if(d&gZ)s++}return s===t}}function Snt(e,t,n,r,a,i){let o=r.length>0||a!==void 0?new Set(t):void 0;return(s)=>{if(i!==_4&&!aA(s))return i===ZR;let c=s;for(let u=0;u<e.length;u+=3){let l=e[u],d=c[l],p=e[u+2];if(d===void 0||p&dBe&&!Object.hasOwn(c,l)){if(p&gZ)return!1;continue}let A=p&Ent;if(A!==0?!lBe(A,d):!e[u+1](d))return!1}for(let u=0;u<n.length;u++)if(!Object.hasOwn(c,n[u]))return!1;if(o===void 0)return!0;for(let u of Object.keys(c)){let l=o.has(u);for(let d=0;d<r.length;d++)if(r[d][0].test(u)){if(l=!0,!r[d][1](c[u]))return!1}if(!l&&a!==void 0&&!a(c[u]))return!1}return!0}}function Dnt(e){return(t)=>{for(let n in t)if(!e(n))return!1;return!0}}function Rnt(e,t){return(n)=>{let r=0;for(let a in n)r++;return r>=e&&r<=t}}function Tnt(e){return(t)=>{let n=t;for(let[r,a]of e)if(Object.hasOwn(n,r)){for(let i of a)if(!Object.hasOwn(n,i))return!1}return!0}}function Mnt(e){return(t)=>{for(let[n,r]of e)if(Object.hasOwn(t,n)&&!r(t))return!1;return!0}}function mBe(e,t,n,r,a){let i=r.length,o=a===void 0?0:cBe.get(a)??0;return(s)=>{if(!Array.isArray(s))return e===ZR;let c=s.length;if(c<t||c>n)return!1;let u=c<i?c:i;for(let l=0;l<u;l++)if(!r[l](s[l]))return!1;if(a===void 0)return!0;if(o!==0){for(let l=i;l<c;l++)if(!lBe(o,s[l]))return!1;return!0}for(let l=i;l<c;l++)if(!a(s[l]))return!1;return!0}}function Fnt(e,t){return mBe(_4,0,Number.POSITIVE_INFINITY,e,t)}function jnt(e,t){return(n)=>n.length>=e&&n.length<=t}function fZ(e,t,n){return(r)=>{let a=r,i=0;for(let o=0;o<a.length;o++)if(e(a[o])&&++i>n)return!1;return i>=t}}function hZ(e){let t=e;for(let n=1;n<t.length;n++)for(let r=0;r<n;r++)if(B4(t[n],t[r]))return!1;return!0}function v4(e){let t=e.filter((a)=>typeof a!=="object"||a===null);if(t.length===e.length&&t.length<=8)return(a)=>{for(let i=0;i<t.length;i++)if(t[i]===a)return!0;return!1};let n=new Set(t),r=e.filter((a)=>typeof a==="object"&&a!==null);return(a)=>n.has(a)||typeof a==="object"&&r.some((i)=>B4(a,i))}function bZ(e){if(typeof e!=="object"||e===null)return(t)=>t===e;return(t)=>B4(t,e)}function Lnt(e){return(t)=>{for(let n=0;n<e.length;n++)if(e[n](t))return!0;return!1}}function Pnt(e){return(t)=>{let n=0;for(let r=0;r<e.length;r++)if(e[r](t)&&++n>1)return!1;return n===1}}function Nnt(e){return(t)=>!e(t)}function $nt(e,t,n){return(r)=>e(r)?t(r):n(r)}function Ont(e,t,n){return(r)=>{if(!aA(r))return!1;let a=r[e];for(let i=0;i<t.length;i++)if(t[i]===a)return n[i](r);return!1}}function B4(e,t){if(e===t)return!0;if(typeof e!=="object"||typeof t!=="object"||e===null||t===null)return!1;let n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){let o=e,s=t;if(o.length!==s.length)return!1;for(let c=0;c<o.length;c++)if(!B4(o[c],s[c]))return!1;return!0}let r=e,a=t,i=Object.keys(r);if(i.length!==Object.keys(a).length)return!1;for(let o of i)if(!Object.hasOwn(a,o)||!B4(r[o],a[o]))return!1;return!0}var Jv=()=>!0,C4=()=>!1,fnt=(e)=>typeof e==="string",hnt=(e)=>typeof e==="number",bnt=(e)=>Number.isInteger(e),ynt=(e)=>typeof e==="boolean",wnt=(e)=>e===null,oBe=(e)=>Array.isArray(e),t$n=(e)=>e instanceof Uint8Array,sBe=(e)=>aA(e),x4,cBe,_4=0,uBe=1,ZR=2,Ent=7,gZ=8,dBe=16;var yZ=I(()=>{x4=new Map([["string",fnt],["number",hnt],["integer",bnt],["boolean",ynt],["null",wnt],["array",oBe],["object",sBe],["bytes",t$n]]),cBe=new Map([[fnt,1],[hnt,2],[bnt,3],[ynt,4],[wnt,5],[Jv,6]])});function VR(){return{props:null,allProps:!1,items:0,allItems:!1,indexes:null}}function gBe(e,t){if(t.props!==null)for(let n of t.props)Gnt(e,n);if(e.allProps||=t.allProps,t.items>e.items)e.items=t.items;if(e.allItems||=t.allItems,t.indexes!==null)for(let n of t.indexes)Unt(e,n)}function Gnt(e,t){if(e.props===null)e.props=new Set;e.props.add(t)}function Unt(e,t){if(e.indexes===null)e.indexes=new Set;e.indexes.add(t)}function Wnt(e){return(t,n)=>e.check(t,n)}function znt(e){return(t)=>e(t)}function Jnt(e){return(t)=>e(t,VR())}function fBe(e,t,n){return(r,a)=>{e.push(t);let i=n(r,a);return e.pop(),i}}function Knt(e){return(t,n)=>{let r=VR();if(!e(t,r))return!1;return gBe(n,r),!0}}function Ynt(e,t){return(n,r)=>{if(!e(n))return!1;for(let a=0;a<t.length;a++)if(!t[a](n,r))return!1;return!0}}function Znt(e,t,n){let r=new Set(e.map(([a])=>a));return(a,i)=>{if(!aA(a))return!0;let o=[];for(let[s,c]of e){if(!Object.hasOwn(a,s))continue;if(!c(a[s]))return!1;o.push(s)}for(let s of Object.keys(a)){let c=r.has(s);for(let[u,l]of t)if(u.test(s)){if(!l(a[s]))return!1;c=!0,o.push(s)}if(!c&&n!==void 0){if(!n(a[s]))return!1;o.push(s)}}for(let s of o)Gnt(i,s);return!0}}function Vnt(e,t,n,r,a){return(i,o)=>{if(!Array.isArray(i))return!0;let s=Math.min(i.length,e.length);for(let c=0;c<s;c++)if(!e[c](i[c]))return!1;if(t!==void 0){for(let c=e.length;c<i.length;c++)if(!t(i[c]))return!1;o.allItems=!0}if(s>o.items)o.items=s;if(n!==void 0){let c=0;for(let u=0;u<i.length;u++)if(n(i[u]))c++,Unt(o,u);if(c<r||c>a)return!1}return!0}}function hBe(e,t){return(n,r)=>{let a=0;for(let i of e){let o=VR();if(i(n,o))a++,gBe(r,o)}return t?a===1:a>0}}function Xnt(e,t,n){return(r,a)=>{let i=VR();if(e(r,i))return gBe(a,i),t===void 0||t(r,a);return n===void 0||n(r,a)}}function ert(e,t){return(n,r)=>!aA(n)||!Object.hasOwn(n,e)||t(n,r)}function trt(e){return(t,n)=>{if(!aA(t)||n.allProps)return!0;for(let r of Object.keys(t))if(!(n.props?.has(r)??!1)&&!e(t[r]))return!1;return n.allProps=!0,!0}}function nrt(e){return(t,n)=>{if(!Array.isArray(t)||n.allItems)return!0;for(let r=n.items;r<t.length;r++)if(!(n.indexes?.has(r)??!1)&&!e(t[r]))return!1;return n.allItems=!0,!0}}var qnt=()=>!0,Hnt=()=>!1;var bBe=I(()=>{yZ()});class wZ{r;draft;formats;dynamic;schema;scope;cache=new Map;annotatingCache=new Map;constructor(e,t,n){this.schema=e,this.r=new nBe(e,t),this.draft=this.r.draft,this.formats=t.formats,this.dynamic=n,this.scope=[]}root(){return this.check(this.schema,this.r.rootBase)}check(e,t){if(e===!0)return Jv;if(e===!1)return C4;if(!ua(e))throw Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let n=this.cache.get(e);if(n!==void 0)return n;let r=this.bareType(e);if(r!==void 0)return r;let a={check:void 0};this.cache.set(e,knt(a));let i=this.build(e,this.r.baseFor(e,t));return a.check=i,this.cache.set(e,i),i}build(e,t){if(this.draft==="7"&&typeof e.$ref==="string")return this.ref(e.$ref,t);if(this.draft!=="7"&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))return Jnt(this.annotating(e,t));let n=this.plain(e,t);return this.dynamic&&this.r.isResource(e,t)?pBe(this.scope,t,n):n}bareType(e){let t;for(let n in e)if(n==="type")t=e.type;else if(!rrt.has(n))return;if(t===void 0)return Jv;return typeof t==="string"?x4.get(t):void 0}plain(e,t){let n=[],r=e.type===void 0?void 0:Array.isArray(e.type)?e.type:[e.type],a=r?.length===1?r[0]:void 0,i=!1;if(a==="bytes")n.push(Cnt(Ld(e.minLength)??0,Ld(e.maxLength)??Number.POSITIVE_INFINITY)),i=!0;else{let o=this.stringGroup(e,a==="string");if(o!==void 0)n.push(o);let s=a==="number"||a==="integer",c=this.numberGroup(e,a==="number"?1:a==="integer"?2:0);if(c!==void 0)n.push(c);let u=this.objectGroup(e,t,a==="object");if(u!==void 0)n.push(u);let l=this.arrayGroup(e,t,a==="array");if(l!==void 0)n.push(l);i=a==="string"&&o!==void 0||s&&c!==void 0||a==="object"&&u!==void 0||a==="array"&&l!==void 0}if(r!==void 0&&!i)n.unshift(Bnt(r));return this.inPlace(e,t,n),I4(n)}inPlace(e,t,n){if(Array.isArray(e.enum))n.push(v4(e.enum));if(Object.hasOwn(e,"const"))n.push(bZ(e.const));if(Array.isArray(e.allOf))n.push(I4(e.allOf.map((r)=>this.check(r,t))));if(Array.isArray(e.anyOf))n.push(this.union(e.anyOf,t,!1));if(Array.isArray(e.oneOf))n.push(this.union(e.oneOf,t,!0));if(e.not!==void 0)n.push(Nnt(this.check(e.not,t)));if(e.if!==void 0&&(e.then!==void 0||e.else!==void 0)){let r=e.then===void 0?Jv:this.check(e.then,t),a=e.else===void 0?Jv:this.check(e.else,t);n.push($nt(this.check(e.if,t),r,a))}if(typeof e.$ref==="string")n.push(this.ref(e.$ref,t));if(this.draft!=="7"&&typeof e.$dynamicRef==="string")n.push(this.dynamicRef(e.$dynamicRef,t))}union(e,t,n){let r=()=>e.map((a)=>this.check(a,t));return a$n(e,n)??this.tagged(e,t)??(n?Pnt(r()):Lnt(r()))}ref(e,t){let n=this.r.resolve(e,t),r=this.check(n.node,n.base);return this.dynamic&&n.base!==t?pBe(this.scope,n.base,r):r}dynamicRef(e,t){let n=this.bookended(e,t);if(n===void 0)return this.ref(e,t);let{initial:r,name:a}=n,i=this.check(r.node,r.base),o=this.dynamicLookup(a,(c,u)=>this.check(c,u)),s=this.scope;return(c)=>{for(let u=0;u<s.length;u++){let l=o(s[u]);if(l!==null)return l(c)}return i(c)}}bookended(e,t){let n=this.r.resolve(e,t),r=EC(e,t),a=r.slice(kC(r).length+1),i=ua(n.node)&&n.node.$dynamicAnchor===a;if(a===""||a.startsWith("/")||!i)return;if(!this.dynamic)throw yBe;return{initial:n,name:a}}dynamicLookup(e,t){let n=new Map;return(r)=>{let a=`${r}#${e}`,i=n.get(a);if(i===void 0){let o=this.r.dynamicAnchors.get(a);i=o===void 0?null:t(o,this.r.baseOf.get(o)??r),n.set(a,i)}return i}}tagged(e,t){if(e.length<2)return;let n=[];for(let a of e){if(!ua(a))return;let i=typeof a.$ref==="string"&&Object.keys(a).length===1?a.$ref:void 0,o=i===void 0?a:this.r.resolve(i,this.r.baseFor(a,t)).node;if(!ua(o))return;n.push(o)}let r=n[0].properties;if(!ua(r))return;for(let a of Object.keys(r)){let i=n.map((o)=>i$n(o,a));if(i.some((o)=>o===void 0)||new Set(i).size!==i.length)continue;return Ont(a,i,e.map((o)=>this.check(o,t)))}return}stringGroup(e,t){let n=Ld(e.minLength)??0,r=Ld(e.maxLength)??Number.POSITIVE_INFINITY,a=typeof e.pattern==="string"?Sb(e.pattern):void 0,i=this.formats!==void 0&&typeof e.format==="string"&&Object.hasOwn(this.formats,e.format)?this.formats[e.format]:void 0;if(n===0&&r===Number.POSITIVE_INFINITY&&a===void 0&&i===void 0)return;return xnt(t,n,r,a,i)}numberGroup(e,t){let n=Ld(e.minimum),r=Ld(e.maximum),a=Ld(e.exclusiveMinimum),i=Ld(e.exclusiveMaximum),o=Ld(e.multipleOf);if([n,r,a,i,o].every((c)=>c===void 0))return;let s=Number.POSITIVE_INFINITY;return _nt(t,n??-s,r??s,a??-s,i??s,o)}objectGroup(e,t,n){let r=n$n.every((l)=>e[l]===void 0),a=this.objectCore(e,t,r?n?uBe:ZR:_4);if(a!==void 0&&r)return a;let i=a===void 0?[]:[a];if(e.propertyNames!==void 0)i.push(Dnt(this.check(e.propertyNames,t)));let o=Ld(e.minProperties),s=Ld(e.maxProperties);if(o!==void 0||s!==void 0)i.push(Rnt(o??0,s??Number.POSITIVE_INFINITY));let c=[],u=[];if(this.draft!=="7"){for(let[l,d]of XR(e.dependentRequired))if(Array.isArray(d))c.push([l,d]);for(let[l,d]of XR(e.dependentSchemas))u.push([l,this.check(d,t)])}for(let[l,d]of XR(e.dependencies))if(Array.isArray(d))c.push([l,d]);else u.push([l,this.check(d,t)]);if(c.length>0)i.push(Tnt(c));if(u.length>0)i.push(Mnt(u));if(i.length===0)return n?sBe:void 0;return Int(I4(i),n)}objectCore(e,t,n){let r=ua(e.properties)?e.properties:{},a=Array.isArray(e.required)?e.required.filter((A)=>typeof A==="string"):[],i=ua(e.patternProperties)?e.patternProperties:{},o=e.additionalProperties,s=Object.keys(r),c=Object.keys(i);if(s.length+a.length+c.length===0&&(o===void 0||o===!0))return;let u=[];for(let A of s){let m=this.check(r[A],t),h=(cBe.get(m)??0)|(a.includes(A)?gZ:0)|(A in Object.prototype?dBe:0);u.push(A,m,h)}let l=a.filter((A)=>!Object.hasOwn(r,A)),d=c.map((A)=>[Sb(A),this.check(i[A],t)]),p=o===void 0||o===!0?void 0:this.check(o,t);if(d.length===0&&l.length===0&&(p===void 0||o===!1)){let A=s.filter((m)=>a.includes(m)).length;return Qnt(u,A,o===!1,n)}return Snt(u,s,l,d,p,n)}arrayGroup(e,t,n){let r=[],a;if(Array.isArray(e.items))r=e.items,a=e.additionalItems;else{if(this.draft!=="7"&&Array.isArray(e.prefixItems))r=e.prefixItems;a=e.items}let i=r.map((l)=>this.check(l,t)),o=a===void 0||a===!0?void 0:this.check(a,t),s=Ld(e.minItems),c=Ld(e.maxItems);if(e.contains===void 0&&e.uniqueItems!==!0&&(i.length>0||o!==void 0))return mBe(n?uBe:ZR,s??0,c??Number.POSITIVE_INFINITY,i,o);let u=[];if(i.length>0||o!==void 0)u.push(Fnt(i,o));if(s!==void 0||c!==void 0)u.push(jnt(s??0,c??Number.POSITIVE_INFINITY));if(e.contains!==void 0){let l=this.draft==="7"?1:Ld(e.minContains)??1,d=this.draft==="7"?Number.POSITIVE_INFINITY:Ld(e.maxContains)??Number.POSITIVE_INFINITY;u.push(fZ(this.check(e.contains,t),l,d))}if(e.uniqueItems===!0)u.push(hZ);if(u.length===0)return n?oBe:void 0;return vnt(I4(u),n)}annotating(e,t){if(e===!0)return qnt;if(e===!1)return Hnt;if(!ua(e))throw Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let n=this.annotatingCache.get(e);if(n!==void 0)return n;let r={check:void 0};this.annotatingCache.set(e,Wnt(r));let a=this.buildAnnotating(e,this.r.baseFor(e,t));return r.check=a,this.annotatingCache.set(e,a),a}buildAnnotating(e,t){let n={},r=!1;for(let c of Object.keys(e))if(r$n.has(c))r=!0;else n[c]=e[c];let a=this.plain(n,t),i=[];if(r)this.annotatingParts(e,t,i);let o=i.length===0?znt(a):Ynt(a,i),s=e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0?Knt(o):o;return this.dynamic&&this.r.isResource(e,t)?fBe(this.scope,t,s):s}annotatingParts(e,t,n){if(e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0){let r=XR(e.properties).map(([o,s])=>[o,this.check(s,t)]),a=XR(e.patternProperties).map(([o,s])=>[Sb(o),this.check(s,t)]),i=e.additionalProperties===void 0?void 0:this.check(e.additionalProperties,t);n.push(Znt(r,a,i))}if(e.prefixItems!==void 0||e.items!==void 0||e.contains!==void 0){let r=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[],a=Array.isArray(e.items)?e.additionalItems:e.items;n.push(Vnt(r.map((i)=>this.check(i,t)),a===void 0?void 0:this.check(a,t),e.contains===void 0?void 0:this.check(e.contains,t),Ld(e.minContains)??1,Ld(e.maxContains)??Number.POSITIVE_INFINITY))}if(Array.isArray(e.allOf))for(let r of e.allOf)n.push(this.annotating(r,t));if(Array.isArray(e.anyOf))n.push(hBe(e.anyOf.map((r)=>this.annotating(r,t)),!1));if(Array.isArray(e.oneOf))n.push(hBe(e.oneOf.map((r)=>this.annotating(r,t)),!0));if(e.if!==void 0){let r=e.then===void 0?void 0:this.annotating(e.then,t),a=e.else===void 0?void 0:this.annotating(e.else,t);n.push(Xnt(this.annotating(e.if,t),r,a))}if(typeof e.$ref==="string")n.push(this.annotatingRef(e.$ref,t));if(typeof e.$dynamicRef==="string")n.push(this.annotatingDynamicRef(e.$dynamicRef,t));for(let[r,a]of XR(e.dependentSchemas))n.push(ert(r,this.annotating(a,t)));if(e.unevaluatedProperties!==void 0)n.push(trt(this.check(e.unevaluatedProperties,t)));if(e.unevaluatedItems!==void 0)n.push(nrt(this.check(e.unevaluatedItems,t)))}annotatingRef(e,t){let n=this.r.resolve(e,t),r=this.annotating(n.node,n.base);return this.dynamic&&n.base!==t?fBe(this.scope,n.base,r):r}annotatingDynamicRef(e,t){let n=this.bookended(e,t);if(n===void 0)return this.annotatingRef(e,t);let{initial:r,name:a}=n,i=this.annotating(r.node,r.base),o=this.dynamicLookup(a,(c,u)=>this.annotating(c,u)),s=this.scope;return(c,u)=>{for(let l=0;l<s.length;l++){let d=o(s[l]);if(d!==null)return d(c,u)}return i(c,u)}}}function a$n(e,t){let n=[];for(let r of e){if(!ua(r)||!Object.hasOwn(r,"const"))return;for(let a of Object.keys(r))if(a!=="const"&&!rrt.has(a))return;if(typeof r.const==="object"&&r.const!==null)return;if(t&&n.includes(r.const))return;n.push(r.const)}return v4(n)}function i$n(e,t){let n=e.properties;if(e.type!=="object"||!Array.isArray(e.required)||!e.required.includes(t))return;let r=ua(n)?n[t]:void 0;if(!ua(r)||!Object.hasOwn(r,"const"))return;return typeof r.const==="object"&&r.const!==null?void 0:r.const}function Ld(e){return typeof e==="number"?e:void 0}function XR(e){return ua(e)?Object.entries(e):[]}var yBe,rrt,n$n,r$n;var art=I(()=>{bBe();yZ();sZ();lZ();yBe=Symbol("restart");rrt=new Set(["$schema","$comment","title","description","default","examples","deprecated","readOnly","writeOnly","$defs","definitions","contentEncoding","contentMediaType","minContains","maxContains","$vocabulary"]),n$n=["propertyNames","minProperties","maxProperties","dependentRequired","dependentSchemas","dependencies"],r$n=new Set(["properties","patternProperties","additionalProperties","prefixItems","items","additionalItems","contains","minContains","maxContains","allOf","anyOf","oneOf","if","then","else","$ref","$dynamicRef","dependentSchemas","unevaluatedProperties","unevaluatedItems"])});class EBe{c;schema;memo=void 0;constructor(e,t){this.c=e,this.schema=t,e.root()}errors(e){let t=[];try{this.walk(this.schema,this.c.r.rootBase,e,"",t)}finally{this.memo=void 0}if(t.length===0)t.push({path:"",keyword:"schema",message:"invalid"});return t}ok(e,t,n){return this.c.check(e,t)(n)}walk(e,t,n,r,a){if(e===!0)return;if(e===!1){a.push({path:r,keyword:"false",message:"no value is allowed here"});return}if(!ua(e))return;let i=this.c.r.baseFor(e,t);if(this.ok(e,i,n))return;let o=a.length,s=(c,u,l=r)=>{a.push({path:l,keyword:c,message:u})};if(this.c.draft==="7"&&typeof e.$ref==="string"){this.walkRef(e.$ref,i,n,r,a);return}if(e.type!==void 0){let c=Array.isArray(e.type)?e.type:[e.type];if(!c.map((l)=>(typeof l==="string"?x4.get(l):void 0)??C4).some((l)=>l(n))){s("type",`expected ${c.join(" or ")}, got ${s$n(n)}`);return}}if(Array.isArray(e.enum)&&!v4(e.enum)(n))s("enum",`expected one of ${irt(e.enum)}`);if(Object.hasOwn(e,"const")&&!bZ(e.const)(n))s("const",`expected ${JSON.stringify(e.const)}`);if(typeof n==="string"&&e.type!=="bytes")this.walkString(e,n,s);if(n instanceof Uint8Array&&e.type==="bytes")this.walkBytes(e,n,s);if(typeof n==="number")this.walkNumber(e,n,s);if(aA(n))this.walkObject(e,i,n,r,a,s);if(Array.isArray(n))this.walkArray(e,i,n,r,a,s);if(Array.isArray(e.allOf))for(let c of e.allOf)this.walk(c,i,n,r,a);if(Array.isArray(e.anyOf))this.walkUnion(e.anyOf,i,n,r,a,!1);if(Array.isArray(e.oneOf))this.walkUnion(e.oneOf,i,n,r,a,!0);if(e.not!==void 0&&this.ok(e.not,i,n))s("not","must not match the schema in not");if(e.if!==void 0){let c=this.ok(e.if,i,n)?e.then:e.else;if(c!==void 0)this.walk(c,i,n,r,a)}if(typeof e.$ref==="string")this.walkRef(e.$ref,i,n,r,a);if(a.length===o&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))this.walkUnevaluated(e,i,n,r,a);if(a.length===o&&typeof e.$dynamicRef==="string")s("$dynamicRef","does not match the dynamically referenced schema")}walkRef(e,t,n,r,a){let i=this.c.r.resolve(e,t);if(i.node===!1&&this.c.r.isUnresolved(e,t)){a.push({path:r,keyword:"$ref",message:`unresolved reference ${e}`});return}if(!ua(i.node)||typeof n!=="object"||n===null){this.walk(i.node,i.base,n,r,a);return}this.memo??=new Map;let o=this.memo.get(i.node),s=o?.get(n);if(s!==void 0&&s.path===r){a.push(...s.errors);return}let c=[];if(this.walk(i.node,i.base,n,r,c),o===void 0)o=new Map,this.memo.set(i.node,o);o.set(n,{path:r,errors:c}),a.push(...c)}walkString(e,t,n){let r=mZ(t);if(typeof e.minLength==="number"&&r<e.minLength)n("minLength",`expected at least ${e.minLength} characters`);if(typeof e.maxLength==="number"&&r>e.maxLength)n("maxLength",`expected at most ${e.maxLength} characters`);if(typeof e.pattern==="string"&&!Sb(e.pattern).test(t))n("pattern",`expected to match ${e.pattern}`);let a=this.c.formats,i=a!==void 0&&typeof e.format==="string"&&Object.hasOwn(a,e.format)?a[e.format]:void 0;if(i!==void 0&&!i(t))n("format",`expected format ${e.format}`)}walkBytes(e,t,n){if(typeof e.minLength==="number"&&t.length<e.minLength)n("minLength",`expected at least ${e.minLength} bytes`);if(typeof e.maxLength==="number"&&t.length>e.maxLength)n("maxLength",`expected at most ${e.maxLength} bytes`)}walkNumber(e,t,n){if(typeof e.minimum==="number"&&t<e.minimum)n("minimum",`expected >= ${e.minimum}`);if(typeof e.maximum==="number"&&t>e.maximum)n("maximum",`expected <= ${e.maximum}`);if(typeof e.exclusiveMinimum==="number"&&t<=e.exclusiveMinimum)n("exclusiveMinimum",`expected > ${e.exclusiveMinimum}`);if(typeof e.exclusiveMaximum==="number"&&t>=e.exclusiveMaximum)n("exclusiveMaximum",`expected < ${e.exclusiveMaximum}`);if(typeof e.multipleOf==="number"&&!ABe(t,e.multipleOf))n("multipleOf",`expected a multiple of ${e.multipleOf}`)}walkObject(e,t,n,r,a,i){let o=ua(e.properties)?e.properties:{},s=Array.isArray(e.required)?e.required:[];for(let d of s)if(typeof d==="string"&&(!Object.hasOwn(n,d)||n[d]===void 0))i("required","missing",T0(r,d));for(let d of Object.keys(o))if(Object.hasOwn(n,d)&&n[d]!==void 0)this.walk(o[d],t,n[d],T0(r,d),a);let c=ua(e.patternProperties)?Object.entries(e.patternProperties):[];for(let d of Object.keys(n)){let p=Object.hasOwn(o,d);for(let[A,m]of c)if(Sb(A).test(d))p=!0,this.walk(m,t,n[d],T0(r,d),a);if(!p&&e.additionalProperties!==void 0)if(e.additionalProperties===!1)i("additionalProperties","unknown field",T0(r,d));else this.walk(e.additionalProperties,t,n[d],T0(r,d),a);if(e.propertyNames!==void 0&&!this.ok(e.propertyNames,t,d))i("propertyNames","invalid property name",T0(r,d))}let u=Object.keys(n).length;if(typeof e.minProperties==="number"&&u<e.minProperties)i("minProperties",`expected at least ${e.minProperties} properties`);if(typeof e.maxProperties==="number"&&u>e.maxProperties)i("maxProperties",`expected at most ${e.maxProperties} properties`);let l={...this.c.draft==="7"||!ua(e.dependentRequired)?{}:e.dependentRequired,...ua(e.dependencies)?e.dependencies:{}};for(let[d,p]of Object.entries(l)){if(!Object.hasOwn(n,d))continue;if(!Array.isArray(p))this.walk(p,t,n,r,a);else for(let A of p)if(!Object.hasOwn(n,A))i("dependentRequired",`required when ${d} is present`,T0(r,A))}if(this.c.draft!=="7"&&ua(e.dependentSchemas)){for(let[d,p]of Object.entries(e.dependentSchemas))if(Object.hasOwn(n,d))this.walk(p,t,n,r,a)}}walkArray(e,t,n,r,a,i){let o=[],s;if(Array.isArray(e.items))o=e.items,s=e.additionalItems;else{if(this.c.draft!=="7"&&Array.isArray(e.prefixItems))o=e.prefixItems;s=e.items}for(let c=0;c<n.length;c++){let u=c<o.length?o[c]:s;if(u!==void 0)this.walk(u,t,n[c],`${r}/${c}`,a)}if(typeof e.minItems==="number"&&n.length<e.minItems)i("minItems",`expected at least ${e.minItems} items`);if(typeof e.maxItems==="number"&&n.length>e.maxItems)i("maxItems",`expected at most ${e.maxItems} items`);if(e.uniqueItems===!0&&!hZ(n))i("uniqueItems","expected unique items");if(e.contains!==void 0){let c=this.c.draft==="7",u=c||typeof e.minContains!=="number"?1:e.minContains,l=c||typeof e.maxContains!=="number"?Number.POSITIVE_INFINITY:e.maxContains;if(!fZ(this.c.check(e.contains,t),u,l)(n))i("contains",o$n(u,l))}}walkUnion(e,t,n,r,a,i){let o=e.filter((l)=>this.ok(l,t,n)).length;if(o===1||!i&&o>0)return;let s=i?"oneOf":"anyOf";if(o>1){a.push({path:r,keyword:s,message:"matches more than one alternative"});return}let c=this.tagOf(e,t);if(c!==void 0&&aA(n)){let l=c.values.indexOf(n[c.key]);if(l<0)a.push({path:T0(r,c.key),keyword:s,message:`expected one of ${irt(c.values)}`});else this.walk(e[l],t,n,r,a);return}let u;for(let l of e){let d=[];if(this.walk(l,t,n,r,d),d.length===0)continue;let p=aA(n)?this.declaredKeys(l,t,n):0;if(u===void 0||p>u.declared||p===u.declared&&d[0].path.length>u.errors[0].path.length)u={errors:d,declared:p}}a.push(...u?.errors??[{path:r,keyword:s,message:"matches no alternative"}])}declaredKeys(e,t,n){let r=ua(e)&&typeof e.$ref==="string"?this.c.r.resolve(e.$ref,t).node:e,a=ua(r)&&ua(r.properties)?r.properties:{};return Object.keys(n).filter((i)=>Object.hasOwn(a,i)).length}tagOf(e,t){let n=e.map((a)=>ua(a)&&typeof a.$ref==="string"?this.c.r.resolve(a.$ref,t).node:a),r=n[0];if(!ua(r)||!ua(r.properties))return;for(let a of Object.keys(r.properties)){let i=n.map((s)=>{let c=ua(s)&&ua(s.properties)?s.properties[a]:void 0;return ua(c)?c.const:void 0});if(i.every((s)=>s!==void 0&&(typeof s!=="object"||s===null))&&new Set(i).size===i.length)return{key:a,values:i}}return}walkUnevaluated(e,t,n,r,a){let{unevaluatedProperties:i,unevaluatedItems:o,...s}=e,c=VR();if(this.c.annotating(s,t)(n,c),aA(n)&&i!==void 0&&!c.allProps)for(let u of Object.keys(n)){if(c.props?.has(u))continue;if(i===!1)a.push({path:T0(r,u),keyword:"unevaluatedProperties",message:"unknown field"});else this.walk(i,t,n[u],T0(r,u),a)}if(Array.isArray(n)&&o!==void 0&&!c.allItems)for(let u=c.items;u<n.length;u++){if(c.indexes?.has(u))continue;if(o===!1)a.push({path:`${r}/${u}`,keyword:"unevaluatedItems",message:"unexpected item"});else this.walk(o,t,n[u],`${r}/${u}`,a)}}}function irt(e){if(e.length<=wBe)return JSON.stringify(e);return`${JSON.stringify(e.slice(0,wBe)).slice(0,-1)}, ... and ${e.length-wBe} more]`}function o$n(e,t){if(t===Number.POSITIVE_INFINITY)return`expected at least ${e} matching ${e===1?"item":"items"}`;if(e===0)return`expected at most ${t} matching ${t===1?"item":"items"}`;return`expected between ${e} and ${t} matching items`}function T0(e,t){return`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`}function s$n(e){if(e===null)return"null";if(Array.isArray(e))return"array";if(e instanceof Uint8Array)return"bytes";if(typeof e==="number"&&Number.isInteger(e))return"integer";return typeof e}var wBe=20;var ort=I(()=>{bBe();yZ();sZ();lZ()});function fg(e,t=c$n){let n=l$n(e,t);return t.coerce===!0?new kBe(e,t,n):new EZ(e,t,n)}class EZ{check;schema;options;explainer=void 0;constructor(e,t,n){this.check=n,this.schema=e,this.options=t}errors(e){if(this.check(e))return[];return this.explainer??=new EBe(BBe(this.schema,this.options),this.schema),this.explainer.errors(e)}}function l$n(e,t){return BBe(e,t).root()}function BBe(e,t){let n=new wZ(e,t,!1);try{return n.root(),n}catch(r){if(r!==yBe)throw r;return new wZ(e,t,!0)}}var c$n,kBe;var srt=I(()=>{mnt();art();ort();c$n=Object.freeze({});kBe=class kBe extends EZ{coercer=void 0;coerce(e){return this.coercer??=new aBe(BBe(this.schema,this.options),this.schema),this.coercer.coerce(e)}parse(e){let t=this.coerce(e);return this.check(t)?{ok:!0,value:t}:{ok:!1,errors:this.errors(t)}}}});var NE=I(()=>{srt()});function SZ(e){let t=0,n=0,r=!1;for(let a of e)if(t+=a.additions,n+=a.deletions,a.status!=="untracked")r=!0;return{additions:t,deletions:n,tracked:r}}function D4(e){if(!$r(e))return{};let t={changesRatio:CBe(e.changesRatio,vZ,QZ),gitPaneRatio:CBe(e.gitPaneRatio,kZ,BZ),layout:e.layout==="split"||e.layout==="unified"?e.layout:void 0,mode:e.mode==="all"||e.mode==="selected"?e.mode:void 0,reviewSidebarWidth:CBe(e.reviewSidebarWidth,xZ,_Z),tab:e.tab==="files"||e.tab==="git"?e.tab:void 0,wrap:jE(e.wrap)?e.wrap:void 0};return Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))}function CBe(e,t,n){return Gl(e)?Math.min(Math.max(e,t),n):void 0}var Q4=50,S4=0.5,kZ=0.35,BZ=0.65,CZ=272,xZ=224,_Z=480,IZ=0.5,vZ=0.3,QZ=0.7,xBe,_Be,crt,IBe,u$n,d$n,k6a,B6a,C6a;var BC=I(()=>{NE();xBe={branch:null,changes:[],commits:[],isGitRepository:!1,changeCount:0,revision:"non-git"},_Be={...xBe,revision:"git-unloaded"},crt=wp({additions:fi(),deletions:fi(),path:ei(),status:R0(["added","deleted","modified","renamed","untracked"])},{open:!0}),IBe=wp({author:ei(),authoredAt:ei(),hash:ei(),pushed:iZ(Oi()),shortHash:ei(),subject:ei(),tags:jd(ei())},{open:!0}),u$n=wp({changes:jd(crt),commit:IBe,patch:ei()},{open:!0}),d$n=wp({branch:iZ(ei()),changes:jd(crt),commits:jd(IBe),isGitRepository:Oi(),changeCount:fi(),revision:ei()},{open:!0}),k6a=fg(u$n),B6a=fg(jd(IBe)),C6a=fg(d$n)});function DZ(e){let t=el,n=WR(),r=SZ(e.workspaceReview.changes);return{_modelsRevision:e.modelsRevision,_codeThemeDark:t.dark,_codeThemeLight:t.light,_fontMono:n.mono,_fontSans:n.sans,_promptHistory:e.promptHistory,_thinkingHidden:e.thinkingHidden,_theme:e.theme,_keybindHints:e.keybindHints,_minimalMode:e.minimalMode,_toolOutputHidden:e.toolOutputHidden,_toolbarHidden:e.toolbarHidden,_temporarySession:e.isTemporarySession,_sessionTransitionGeneration:e.sessionTransition.generation,_sessionTransitionStatus:e.sessionTransition.status,_sessionTransitionVisible:LY(e.sessionTransition),_workspaceReviewAdditions:r.additions,_workspaceReviewBranch:e.workspaceReview.branch??"",_workspaceReviewDeletions:r.deletions,_workspaceReviewGitAvailable:e.workspaceReview.isGitRepository,_workspaceReviewChangeCount:e.workspaceReview.changeCount,_workspaceReviewStatsKnown:r.tracked}}var vBe=I(()=>{f4();zR();vb();BC()});function g$n(e){return e.split("-").map((t)=>m$n.get(t)??`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function urt(e,t){return{appearance:t,label:g$n(e),name:e}}function TZ(e){return e==="light"?drt:prt}function RZ(e,t){return zn(t)?TZ(e).find((n)=>n.name===t):void 0}function Art(e){if(!$r(e))return;let t=RZ("light",e.light)?.name,n=RZ("dark",e.dark)?.name;return t&&n?{dark:n,light:t}:void 0}function mrt(){return{...Xke}}var lrt="// syntax preview\nconst greet = (name: string) => {\n return `hello, ${name}!`;\n};",p$n,A$n,m$n,drt,prt,T6a;var MZ=I(()=>{vb();p$n=["pierre-light","pierre-light-soft","pierre-light-vibrant","pierre-light-protanopia-deuteranopia","pierre-light-tritanopia","ayu-light","catppuccin-latte","everforest-light","github-light","github-light-default","github-light-high-contrast","gruvbox-light-hard","gruvbox-light-medium","gruvbox-light-soft","horizon-bright","kanagawa-lotus","light-plus","material-theme-lighter","min-light","night-owl-light","one-light","rose-pine-dawn","slack-ochin","snazzy-light","solarized-light","vitesse-light"],A$n=["pierre-dark","pierre-dark-soft","pierre-dark-vibrant","pierre-dark-protanopia-deuteranopia","pierre-dark-tritanopia","ayu-dark","ayu-mirage","catppuccin-frappe","catppuccin-macchiato","catppuccin-mocha","everforest-dark","github-dark","github-dark-default","github-dark-dimmed","github-dark-high-contrast","gruvbox-dark-hard","gruvbox-dark-medium","gruvbox-dark-soft","horizon","kanagawa-wave","kanagawa-dragon","dark-plus","material-theme","material-theme-darker","material-theme-ocean","material-theme-palenight","min-dark","night-owl","one-dark-pro","rose-pine","rose-pine-moon","slack-dark","andromeeda","solarized-dark","vitesse-dark","vitesse-black","aurora-x","dracula","dracula-soft","houston","laserwave","monokai","nord","plastic","poimandres","red","synthwave-84","tokyo-night","vesper"],m$n=new Map(Object.entries({ayu:"Ayu",cvd:"CVD",github:"GitHub",min:"Min",pierre:"Pierre",vscode:"VS Code"}));drt=p$n.map((e)=>urt(e,"light")).toSorted((e,t)=>e.label.localeCompare(t.label)),prt=A$n.map((e)=>urt(e,"dark")).toSorted((e,t)=>e.label.localeCompare(t.label)),T6a=[...drt,...prt]});function grt(){let e=el,t=Object.fromEntries(["light","dark"].map((n)=>[n,TZ(n).map((r)=>r.label.toLowerCase())]));return an(yl.jsxDEV("dialog",{id:"code-theme-dialog",class:"dialog code-theme-dialog","aria-labelledby":"code-theme-title","data-signals__ifmissing":JSON.stringify({_codeThemeAppearance:"light",_codeThemeSearch:"",_codeThemeStatus:""}),"data-on:pi-ui-open-code-theme__window":`
|
|
43
|
+
});`;var tBe=I(()=>{yi();Kr=mn(ur(),1)});function ei(e={}){return{type:"string",...e}}function fi(e={}){return{type:"number",...e}}function Qb(e={}){return{type:"integer",...e}}function Oi(e={}){return{type:"boolean",...e}}function YR(e={}){return{type:"null",...e}}function R0(e,t={}){return{enum:e,...t}}function Lc(e,t={}){return{anyOf:e,...t}}function iZ(e,t={}){return{anyOf:[e,{type:"null"}],...t}}function jd(e,t={}){return{type:"array",items:e,...t}}class oZ{schema;constructor(e){this.schema=e}}function In(e){return new oZ(e)}function wp(e,t={}){let{open:n,...r}=t,a={},i=[];for(let[o,s]of Object.entries(e))if(s instanceof oZ)a[o]=s.schema;else a[o]=s,i.push(o);return{type:"object",properties:a,...i.length>0?{required:i}:{},...n===!0?{}:{additionalProperties:!1},...r}}class nBe{draft;rootBase;baseOf=new Map;dynamicAnchors=new Map;root;options;registry=new Map;rejectUnresolved;unresolved=new Set;resources=new Map;anchors=new Map;indexed=!1;constructor(e,t){this.draft=t.draft==="7"?"7":"2020-12",this.root=e,this.options=t,this.rejectUnresolved=t.unresolvedRefs==="reject",this.rootBase=ua(e)?this.baseFor(e,"https://json-schema.invalid/root.json"):"https://json-schema.invalid/root.json"}baseFor(e,t){let n=this.baseOf.get(e);if(n!==void 0)return n;let r=e.$id;if(typeof r!=="string")return t;if(this.draft==="7"&&(typeof e.$ref==="string"||r.startsWith("#")))return t;return kC(EC(r,t))}ensureIndexed(){if(this.indexed)return;this.indexed=!0;for(let[e,t]of Object.entries(this.options.schemas??{}))this.registry.set(kC(EC(e,"https://json-schema.invalid/root.json")),t);this.resources.set("https://json-schema.invalid/root.json",this.root),this.index(this.root,"https://json-schema.invalid/root.json")}resolve(e,t){if(this.ensureIndexed(),!this.rejectUnresolved)return this.find(e,t);try{return this.find(e,t)}catch{return this.unresolved.add(EC(e,t)),{node:!1,base:t}}}isUnresolved(e,t){return this.unresolved.has(EC(e,t))}find(e,t){let n=EC(e,t),r=kC(n),a=n.length>r.length?decodeURIComponent(n.slice(r.length+1)):"",i=this.resources.has(r)?this.resources.get(r):this.load(r);if(i===void 0)throw Error(`Unresolved $ref ${e} (no schema registered for ${r})`);if(a==="")return{node:i,base:r};if(a.startsWith("/"))return this.pointer(i,r,a);let o=this.anchors.get(`${r}#${a}`);if(o===void 0)throw Error(`Unresolved $ref ${e} (no anchor ${a} in ${r})`);return{node:o,base:this.baseOf.get(o)??r}}isResource(e,t){return this.ensureIndexed(),this.resources.get(t)===e}index(e,t){if(!ua(e)||this.baseOf.has(e))return;let n=t,r=this.draft==="7"&&typeof e.$ref==="string";if(!r&&typeof e.$id==="string")if(this.draft==="7"&&e.$id.startsWith("#"))this.anchors.set(kC(n)+e.$id,e);else{let a=EC(e.$id,n);if(n=kC(a),this.resources.set(n,e),a.length>n.length+1)this.anchors.set(a,e)}if(this.baseOf.set(e,n),r)return;if(this.draft!=="7"){if(typeof e.$anchor==="string")this.anchors.set(`${n}#${e.$anchor}`,e);if(typeof e.$dynamicAnchor==="string")this.anchors.set(`${n}#${e.$dynamicAnchor}`,e),this.dynamicAnchors.set(`${n}#${e.$dynamicAnchor}`,e)}for(let a of W9n)this.index(e[a],n);for(let a of z9n){let i=e[a];if(ua(i))for(let o of Object.keys(i))this.index(i[o],n)}for(let a of J9n){let i=e[a];if(Array.isArray(i))for(let o of i)this.index(o,n)}}load(e){let t=this.registry.get(e);if(t===void 0)return;return this.resources.set(e,t),this.index(t,e),t}pointer(e,t,n){let r=e,a=t;for(let i of n.split("/").slice(1)){let o=i.replace(/~1/g,"/").replace(/~0/g,"~");if(r=typeof r==="object"&&r!==null&&Object.hasOwn(r,o)?r[o]:void 0,r===void 0)throw Error(`Unresolved $ref #${n} in ${t}`);if(typeof r==="object"&&r!==null)a=this.baseOf.get(r)??a}return{node:r,base:a}}}function ua(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function EC(e,t){try{return new URL(e,t).href}catch{return e.startsWith("#")?kC(t)+e:e}}function kC(e){let t=e.indexOf("#");return t<0?e:e.slice(0,t)}var W9n,z9n,J9n;var sZ=I(()=>{W9n=["additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems","additionalItems","contentSchema","items"],z9n=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"],J9n=["allOf","anyOf","oneOf","prefixItems","items"]});function Sb(e){let t=cZ.get(e)?.deref();if(t!==void 0)return t;let n;try{n=new RegExp(e,"u")}catch{n=new RegExp(e)}return cZ.set(e,new WeakRef(n)),K9n.register(n,e),n}var cZ,K9n;var lZ=I(()=>{cZ=new Map,K9n=new FinalizationRegistry((e)=>{if(cZ.get(e)?.deref()===void 0)cZ.delete(e)})});class aBe{c;schema;entered=[];cuts=0;memo=void 0;constructor(e,t){this.c=e,this.schema=t}coerce(e){let t=this.c.r.rootBase,n=this.dropOptionalNulls(e,this.schema,t);return this.coerceTypes(this.convertOnly(n),this.schema,t)}convertOnly(e){try{return this.convert(this.schema,this.c.r.rootBase,e)}finally{this.memo=void 0,this.cuts=0}}reenter(e,t,n,r){let a=this.entered;for(let c=0;c<a.length;c+=2)if(a[c]===e&&Object.is(a[c+1],n))return this.cuts++,n;let i=r?this.memo?.get(e):void 0;if(i?.has(n))return i.get(n);let o=this.cuts;a.push(e,n);let s;try{s=this.convert(e,t,n)}finally{a.length-=2}if(r&&this.cuts===o){this.memo??=new Map;let c=this.memo.get(e);if(c===void 0)c=new Map,this.memo.set(e,c);c.set(n,s)}return s}passes(e,t,n){try{return this.c.check(e,this.baseOf(e,t))(n)}catch{return}}baseOf(e,t){return ua(e)?this.c.r.baseOf.get(e)??t:t}dropOptionalNulls(e,t,n){if(!ua(t))return e;let r=this.baseOf(t,n);if(Array.isArray(e))return uZ(e,(l,d)=>{let p=cnt(t,d);return p===void 0?l:this.dropOptionalNulls(l,p,r)});if(!pZ(e))return e;let a=ua(t.properties)?t.properties:{},i=ua(t.patternProperties)?Object.entries(t.patternProperties).map(([l,d])=>[Sb(l),d]):[],o=ua(t.additionalProperties)?t.additionalProperties:void 0;if(i.length===0&&o===void 0&&!ua(t.properties))return e;let s=new Set(Array.isArray(t.required)?t.required:[]),c,u=(l,d)=>{if(d===(c??e)[l])return;c??={...e},c[l]=d};for(let[l,d]of Object.entries(a)){if(!Object.hasOwn(e,l))continue;let p=ua(d)&&typeof d.$ref==="string";if(e[l]===null&&!s.has(l)&&!p&&this.passes(d,r,null)===!1){c??={...e},delete c[l];continue}u(l,this.dropOptionalNulls(e[l],d,r))}if(i.length>0||o!==void 0)for(let l of Object.keys(e)){let d=Object.hasOwn(a,l);for(let[p,A]of i){if(!p.test(l))continue;d=!0,u(l,this.dropOptionalNulls((c??e)[l],A,r))}if(!d&&o!==void 0)u(l,this.dropOptionalNulls(e[l],o,r))}return c??e}convert(e,t,n){if(!ua(e))return n;let r=this.baseOf(e,t);if(typeof e.$ref==="string"){let a;try{a=this.c.r.resolve(e.$ref,r)}catch{return n}return ua(a.node)?this.reenter(a.node,a.base,n,!0):n}return this.convertNode(e,r,n)}convertNode(e,t,n){if(Object.hasOwn(e,"const"))return lnt(e.const,n);if(Array.isArray(e.enum))return this.convertEnum(e,e.enum,t,n);if(Array.isArray(e.anyOf))return this.convertUnion(e,e.anyOf,t,n);if(Array.isArray(e.oneOf))return this.convertUnion(e,e.oneOf,t,n);if(Array.isArray(e.allOf)){let r=n;for(let a of e.allOf)r=this.convert(a,t,r);return this.convertMembers(e,t,r)}switch(e.type){case"string":return dZ(pnt(n),n);case"number":return dZ(rBe(n),n);case"integer":{let r=rBe(n);return r===void 0?n:Math.trunc(r.value)}case"boolean":return dZ(Ant(n),n);case"null":return dZ(Z9n(n),n);case"array":return this.convertArray(e,t,n);case"object":return this.convertObject(e,t,n);case void 0:if(e.properties!==void 0||e.patternProperties!==void 0)return this.convertObject(e,t,n);if(e.items!==void 0||e.prefixItems!==void 0)return this.convertArray(e,t,n);return n;default:return n}}convertEnum(e,t,n,r){if(t.some((a)=>a===r))return r;for(let a of t){let i=lnt(a,r);if(i!==r&&this.passes(e,n,i)===!0)return i}return r}convertUnion(e,t,n,r){if(t.some((a)=>this.passes(a,n,r)===!0))return this.convertMembers(e,n,r);for(let a of t){let i=this.convertMembers(e,n,this.convert(a,n,r));if(this.passes(e,n,i)===!0)return i}return this.convertMembers(e,n,r)}convertMembers(e,t,n){return e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0?this.convertObject(e,t,n):n}convertArray(e,t,n){let r=Array.isArray(e.items)?e.items:Array.isArray(e.prefixItems)?e.prefixItems:void 0;if(r!==void 0){if(!Array.isArray(n))return n;let i=Array.isArray(e.items)?void 0:e.items;return uZ(n,(o,s)=>{let c=s<r.length?r[s]:i;return c===void 0?o:this.convert(c,t,o)})}if(Array.isArray(n))return e.items===void 0?n:uZ(n,(i)=>this.convert(e.items,t,i));let a=e.items;return[ua(a)?this.reenter(a,t,n,!1):n]}convertObject(e,t,n){if(!pZ(n))return n;let r=ua(e.properties)?e.properties:{},a=ua(e.patternProperties)?Object.entries(e.patternProperties).map(([s,c])=>[Sb(s),c]):[],i=ua(e.additionalProperties)?e.additionalProperties:void 0,o;for(let s of Object.keys(n)){if(n[s]===void 0)continue;let c=n[s],u=Object.hasOwn(r,s);if(u)c=this.convert(r[s],t,c);for(let[l,d]of a){if(!l.test(s))continue;u=!0,c=this.convert(d,t,c)}if(!u&&i!==void 0)c=this.convert(i,t,c);if(c!==n[s])o??={...n},o[s]=c}return o??n}coerceTypes(e,t,n){if(!ua(t))return e;let r=this.baseOf(t,n),a=e;if(Array.isArray(t.allOf))for(let s of t.allOf)a=this.coerceTypes(a,s,r);if(Array.isArray(t.anyOf))a=this.coerceUnion(a,t.anyOf,r);if(Array.isArray(t.oneOf))a=this.coerceUnion(a,t.oneOf,r);let i=V9n(t),o=i.length>1&&i.some((s)=>X9n(a,s));if(i.length>0&&!o)for(let s of i){let c=e$n(a,s);if(c!==a){a=c;break}}if(i.includes("object")&&pZ(a))a=this.coerceProperties(a,t,r);if(i.includes("array")&&Array.isArray(a))a=this.coerceItems(a,t,r);return a}coerceUnion(e,t,n){for(let r of t)if(this.passes(r,n,e)===!0)return e;for(let r of t){let a=this.coerceTypes(e,r,n);if(this.passes(r,n,a)===!0)return a}return e}coerceProperties(e,t,n){let r=ua(t.properties)?t.properties:{},a=ua(t.patternProperties)?Object.entries(t.patternProperties).map(([c,u])=>[Sb(c),u]):[],i=ua(t.additionalProperties)?t.additionalProperties:void 0,o,s=(c,u)=>{if(u===(o??e)[c])return;o??={...e},o[c]=u};for(let[c,u]of Object.entries(r))if(c in e)s(c,this.coerceTypes(e[c],u,n));for(let c of Object.keys(e)){let u=Object.hasOwn(r,c);for(let[l,d]of a){if(!l.test(c))continue;u=!0,s(c,this.coerceTypes((o??e)[c],d,n))}if(!u&&i!==void 0)s(c,this.coerceTypes(e[c],i,n))}return o??e}coerceItems(e,t,n){return uZ(e,(r,a)=>{let i=cnt(t,a);return ua(i)?this.coerceTypes(r,i,n):r})}}function cnt(e,t){if(Array.isArray(e.items))return e.items[t];if(Array.isArray(e.prefixItems)&&t<e.prefixItems.length)return e.prefixItems[t];return e.items}function uZ(e,t){let n;for(let r=0;r<e.length;r++){let a=t(e[r],r);if(a===e[r])continue;n??=e.slice(),n[r]=a}return n??e}function dZ(e,t){return e===void 0?t:e.value}function lnt(e,t){if(e===t)return t;let n=typeof e==="string"?pnt(t):typeof e==="number"?rBe(t):typeof e==="boolean"?Ant(t):void 0;return n!==void 0&&n.value===e?n.value:t}function pnt(e){if(typeof e==="bigint"||typeof e==="boolean"||AZ(e))return{value:String(e)};if(e===null)return{value:"null"};if(typeof e==="string")return{value:e};if(e===void 0)return{value:""};return}function rBe(e){if(typeof e==="bigint")return e<=unt&&e>=dnt?{value:Number(e)}:void 0;if(typeof e==="boolean")return{value:e?1:0};if(AZ(e))return{value:e};if(e===null||e===void 0)return{value:0};if(typeof e!=="string")return;let t=+e;if(Number.isFinite(t))return{value:t};let n=e.toLowerCase();if(n==="false")return{value:0};if(n==="true")return{value:1};let r=Y9n(e);return r!==void 0&&r<=unt&&r>=dnt?{value:Number(r)}:void 0}function Y9n(e){if(/^-?(0|[1-9]\d*)n$/.test(e))return BigInt(e.slice(0,-1));if(/^-?(0|[1-9]\d*)\.\d+$/.test(e))return BigInt(e.split(".")[0]);if(/^-?(0|[1-9]\d*)$/.test(e))return BigInt(e);return}function Ant(e){if(typeof e==="bigint")return e===0n?{value:!1}:e===1n?{value:!0}:void 0;if(typeof e==="boolean")return{value:e};if(AZ(e))return e===0?{value:!1}:e===1?{value:!0}:void 0;if(e===null||e===void 0)return{value:!1};if(typeof e!=="string")return;let t=e.toLowerCase();if(t==="false"||e==="0")return{value:!1};if(t==="true"||e==="1")return{value:!0};return}function Z9n(e){if(typeof e==="bigint")return e===0n?{value:null}:void 0;if(typeof e==="boolean")return e===!1?{value:null}:void 0;if(AZ(e))return e===0?{value:null}:void 0;if(e===null||e===void 0)return{value:null};if(typeof e!=="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:null}:void 0}function AZ(e){return typeof e==="number"&&Number.isFinite(e)}function V9n(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((t)=>typeof t==="string");return[]}function X9n(e,t){switch(t){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return pZ(e);default:return!1}}function e$n(e,t){switch(t){case"number":case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let n=Number(e);if(t==="number"?Number.isFinite(n):Number.isInteger(n))return n}if(typeof e==="boolean")return e?1:0;return e}case"boolean":if(e===null)return!1;if(e==="true"||e===1)return!0;if(e==="false"||e===0)return!1;return e;case"string":if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e;case"null":return e===""||e===0||e===!1?null:e;default:return e}}function pZ(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var unt,dnt;var mnt=I(()=>{sZ();lZ();unt=BigInt(Number.MAX_SAFE_INTEGER),dnt=BigInt(Number.MIN_SAFE_INTEGER)});function aA(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function lBe(e,t){switch(e){case 1:return typeof t==="string";case 2:return typeof t==="number";case 3:return Number.isInteger(t);case 4:return typeof t==="boolean";case 5:return t===null;default:return!0}}function I4(e){switch(e.length){case 0:return Jv;case 1:return e[0];case 2:{let[t,n]=e;return(r)=>t(r)&&n(r)}case 3:{let[t,n,r]=e;return(a)=>t(a)&&n(a)&&r(a)}default:return(t)=>{for(let n=0;n<e.length;n++)if(!e[n](t))return!1;return!0}}}function knt(e){return(t)=>e.check(t)}function pBe(e,t,n){return(r)=>{e.push(t);let a=n(r);return e.pop(),a}}function Bnt(e){let t=e.map((n)=>(typeof n==="string"?x4.get(n):void 0)??C4);if(t.length===1)return t[0];return(n)=>{for(let r=0;r<t.length;r++)if(t[r](n))return!0;return!1}}function Cnt(e,t){return(n)=>n instanceof Uint8Array&&n.length>=e&&n.length<=t}function mZ(e){let t=0;for(let n=0;n<e.length;n++,t++){let r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);if(a>=56320&&a<=57343)n++}}return t}function iBe(e,t,n){let r=e.length;if(r<t)return!1;if(r<2*t&&mZ(e)<t)return!1;return r<=n||mZ(e)<=n}function xnt(e,t,n,r,a){if(r!==void 0&&t===0&&n===Number.POSITIVE_INFINITY&&a===void 0)return e?(i)=>typeof i==="string"&&r.test(i):(i)=>typeof i!=="string"||r.test(i);if(r===void 0&&a===void 0)return e?(i)=>typeof i==="string"&&iBe(i,t,n):(i)=>typeof i!=="string"||iBe(i,t,n);return(i)=>{if(typeof i!=="string")return!e;return iBe(i,t,n)&&(r===void 0||r.test(i))&&(a===void 0||a(i))}}function _nt(e,t,n,r,a,i){return(o)=>{if(typeof o!=="number")return e===0;if(e===2&&!Number.isInteger(o))return!1;return o>=t&&o<=n&&o>r&&o<a&&(i===void 0||ABe(o,i))}}function ABe(e,t){let n=e/t;if(Number.isInteger(n))return!0;if(!Number.isFinite(n))return e%t===0;let[r,a]=gnt(e),[i,o]=gnt(t);return a>=o?r*10n**BigInt(a-o)%i===0n:r%(i*10n**BigInt(o-a))===0n}function gnt(e){let[t,n="0"]=Math.abs(e).toString().split("e"),r=t.indexOf("."),a=r<0?0:t.length-r-1;return[BigInt(t.replace(".","")),Number(n)-a]}function Int(e,t){return t?(n)=>aA(n)&&e(n):(n)=>!aA(n)||e(n)}function vnt(e,t){return t?(n)=>Array.isArray(n)&&e(n):(n)=>!Array.isArray(n)||e(n)}function Qnt(e,t,n,r){let a=e.length;return(i)=>{if(r!==_4&&!aA(i))return r===ZR;let o=i,s=0;for(let c in o){let u=0;while(u<a&&e[u]!==c)u+=3;if(u===a){if(n)return!1;continue}let l=o[c];if(l===void 0)continue;let d=e[u+2],p=d&Ent;if(p!==0?!lBe(p,l):!e[u+1](l))return!1;if(d&gZ)s++}return s===t}}function Snt(e,t,n,r,a,i){let o=r.length>0||a!==void 0?new Set(t):void 0;return(s)=>{if(i!==_4&&!aA(s))return i===ZR;let c=s;for(let u=0;u<e.length;u+=3){let l=e[u],d=c[l],p=e[u+2];if(d===void 0||p&dBe&&!Object.hasOwn(c,l)){if(p&gZ)return!1;continue}let A=p&Ent;if(A!==0?!lBe(A,d):!e[u+1](d))return!1}for(let u=0;u<n.length;u++)if(!Object.hasOwn(c,n[u]))return!1;if(o===void 0)return!0;for(let u of Object.keys(c)){let l=o.has(u);for(let d=0;d<r.length;d++)if(r[d][0].test(u)){if(l=!0,!r[d][1](c[u]))return!1}if(!l&&a!==void 0&&!a(c[u]))return!1}return!0}}function Dnt(e){return(t)=>{for(let n in t)if(!e(n))return!1;return!0}}function Rnt(e,t){return(n)=>{let r=0;for(let a in n)r++;return r>=e&&r<=t}}function Tnt(e){return(t)=>{let n=t;for(let[r,a]of e)if(Object.hasOwn(n,r)){for(let i of a)if(!Object.hasOwn(n,i))return!1}return!0}}function Mnt(e){return(t)=>{for(let[n,r]of e)if(Object.hasOwn(t,n)&&!r(t))return!1;return!0}}function mBe(e,t,n,r,a){let i=r.length,o=a===void 0?0:cBe.get(a)??0;return(s)=>{if(!Array.isArray(s))return e===ZR;let c=s.length;if(c<t||c>n)return!1;let u=c<i?c:i;for(let l=0;l<u;l++)if(!r[l](s[l]))return!1;if(a===void 0)return!0;if(o!==0){for(let l=i;l<c;l++)if(!lBe(o,s[l]))return!1;return!0}for(let l=i;l<c;l++)if(!a(s[l]))return!1;return!0}}function Fnt(e,t){return mBe(_4,0,Number.POSITIVE_INFINITY,e,t)}function jnt(e,t){return(n)=>n.length>=e&&n.length<=t}function fZ(e,t,n){return(r)=>{let a=r,i=0;for(let o=0;o<a.length;o++)if(e(a[o])&&++i>n)return!1;return i>=t}}function hZ(e){let t=e;for(let n=1;n<t.length;n++)for(let r=0;r<n;r++)if(B4(t[n],t[r]))return!1;return!0}function v4(e){let t=e.filter((a)=>typeof a!=="object"||a===null);if(t.length===e.length&&t.length<=8)return(a)=>{for(let i=0;i<t.length;i++)if(t[i]===a)return!0;return!1};let n=new Set(t),r=e.filter((a)=>typeof a==="object"&&a!==null);return(a)=>n.has(a)||typeof a==="object"&&r.some((i)=>B4(a,i))}function bZ(e){if(typeof e!=="object"||e===null)return(t)=>t===e;return(t)=>B4(t,e)}function Lnt(e){return(t)=>{for(let n=0;n<e.length;n++)if(e[n](t))return!0;return!1}}function Pnt(e){return(t)=>{let n=0;for(let r=0;r<e.length;r++)if(e[r](t)&&++n>1)return!1;return n===1}}function Nnt(e){return(t)=>!e(t)}function $nt(e,t,n){return(r)=>e(r)?t(r):n(r)}function Ont(e,t,n){return(r)=>{if(!aA(r))return!1;let a=r[e];for(let i=0;i<t.length;i++)if(t[i]===a)return n[i](r);return!1}}function B4(e,t){if(e===t)return!0;if(typeof e!=="object"||typeof t!=="object"||e===null||t===null)return!1;let n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){let o=e,s=t;if(o.length!==s.length)return!1;for(let c=0;c<o.length;c++)if(!B4(o[c],s[c]))return!1;return!0}let r=e,a=t,i=Object.keys(r);if(i.length!==Object.keys(a).length)return!1;for(let o of i)if(!Object.hasOwn(a,o)||!B4(r[o],a[o]))return!1;return!0}var Jv=()=>!0,C4=()=>!1,fnt=(e)=>typeof e==="string",hnt=(e)=>typeof e==="number",bnt=(e)=>Number.isInteger(e),ynt=(e)=>typeof e==="boolean",wnt=(e)=>e===null,oBe=(e)=>Array.isArray(e),t$n=(e)=>e instanceof Uint8Array,sBe=(e)=>aA(e),x4,cBe,_4=0,uBe=1,ZR=2,Ent=7,gZ=8,dBe=16;var yZ=I(()=>{x4=new Map([["string",fnt],["number",hnt],["integer",bnt],["boolean",ynt],["null",wnt],["array",oBe],["object",sBe],["bytes",t$n]]),cBe=new Map([[fnt,1],[hnt,2],[bnt,3],[ynt,4],[wnt,5],[Jv,6]])});function VR(){return{props:null,allProps:!1,items:0,allItems:!1,indexes:null}}function gBe(e,t){if(t.props!==null)for(let n of t.props)Gnt(e,n);if(e.allProps||=t.allProps,t.items>e.items)e.items=t.items;if(e.allItems||=t.allItems,t.indexes!==null)for(let n of t.indexes)Unt(e,n)}function Gnt(e,t){if(e.props===null)e.props=new Set;e.props.add(t)}function Unt(e,t){if(e.indexes===null)e.indexes=new Set;e.indexes.add(t)}function Wnt(e){return(t,n)=>e.check(t,n)}function znt(e){return(t)=>e(t)}function Jnt(e){return(t)=>e(t,VR())}function fBe(e,t,n){return(r,a)=>{e.push(t);let i=n(r,a);return e.pop(),i}}function Knt(e){return(t,n)=>{let r=VR();if(!e(t,r))return!1;return gBe(n,r),!0}}function Ynt(e,t){return(n,r)=>{if(!e(n))return!1;for(let a=0;a<t.length;a++)if(!t[a](n,r))return!1;return!0}}function Znt(e,t,n){let r=new Set(e.map(([a])=>a));return(a,i)=>{if(!aA(a))return!0;let o=[];for(let[s,c]of e){if(!Object.hasOwn(a,s))continue;if(!c(a[s]))return!1;o.push(s)}for(let s of Object.keys(a)){let c=r.has(s);for(let[u,l]of t)if(u.test(s)){if(!l(a[s]))return!1;c=!0,o.push(s)}if(!c&&n!==void 0){if(!n(a[s]))return!1;o.push(s)}}for(let s of o)Gnt(i,s);return!0}}function Vnt(e,t,n,r,a){return(i,o)=>{if(!Array.isArray(i))return!0;let s=Math.min(i.length,e.length);for(let c=0;c<s;c++)if(!e[c](i[c]))return!1;if(t!==void 0){for(let c=e.length;c<i.length;c++)if(!t(i[c]))return!1;o.allItems=!0}if(s>o.items)o.items=s;if(n!==void 0){let c=0;for(let u=0;u<i.length;u++)if(n(i[u]))c++,Unt(o,u);if(c<r||c>a)return!1}return!0}}function hBe(e,t){return(n,r)=>{let a=0;for(let i of e){let o=VR();if(i(n,o))a++,gBe(r,o)}return t?a===1:a>0}}function Xnt(e,t,n){return(r,a)=>{let i=VR();if(e(r,i))return gBe(a,i),t===void 0||t(r,a);return n===void 0||n(r,a)}}function ert(e,t){return(n,r)=>!aA(n)||!Object.hasOwn(n,e)||t(n,r)}function trt(e){return(t,n)=>{if(!aA(t)||n.allProps)return!0;for(let r of Object.keys(t))if(!(n.props?.has(r)??!1)&&!e(t[r]))return!1;return n.allProps=!0,!0}}function nrt(e){return(t,n)=>{if(!Array.isArray(t)||n.allItems)return!0;for(let r=n.items;r<t.length;r++)if(!(n.indexes?.has(r)??!1)&&!e(t[r]))return!1;return n.allItems=!0,!0}}var qnt=()=>!0,Hnt=()=>!1;var bBe=I(()=>{yZ()});class wZ{r;draft;formats;dynamic;schema;scope;cache=new Map;annotatingCache=new Map;constructor(e,t,n){this.schema=e,this.r=new nBe(e,t),this.draft=this.r.draft,this.formats=t.formats,this.dynamic=n,this.scope=[]}root(){return this.check(this.schema,this.r.rootBase)}check(e,t){if(e===!0)return Jv;if(e===!1)return C4;if(!ua(e))throw Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let n=this.cache.get(e);if(n!==void 0)return n;let r=this.bareType(e);if(r!==void 0)return r;let a={check:void 0};this.cache.set(e,knt(a));let i=this.build(e,this.r.baseFor(e,t));return a.check=i,this.cache.set(e,i),i}build(e,t){if(this.draft==="7"&&typeof e.$ref==="string")return this.ref(e.$ref,t);if(this.draft!=="7"&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))return Jnt(this.annotating(e,t));let n=this.plain(e,t);return this.dynamic&&this.r.isResource(e,t)?pBe(this.scope,t,n):n}bareType(e){let t;for(let n in e)if(n==="type")t=e.type;else if(!rrt.has(n))return;if(t===void 0)return Jv;return typeof t==="string"?x4.get(t):void 0}plain(e,t){let n=[],r=e.type===void 0?void 0:Array.isArray(e.type)?e.type:[e.type],a=r?.length===1?r[0]:void 0,i=!1;if(a==="bytes")n.push(Cnt(Ld(e.minLength)??0,Ld(e.maxLength)??Number.POSITIVE_INFINITY)),i=!0;else{let o=this.stringGroup(e,a==="string");if(o!==void 0)n.push(o);let s=a==="number"||a==="integer",c=this.numberGroup(e,a==="number"?1:a==="integer"?2:0);if(c!==void 0)n.push(c);let u=this.objectGroup(e,t,a==="object");if(u!==void 0)n.push(u);let l=this.arrayGroup(e,t,a==="array");if(l!==void 0)n.push(l);i=a==="string"&&o!==void 0||s&&c!==void 0||a==="object"&&u!==void 0||a==="array"&&l!==void 0}if(r!==void 0&&!i)n.unshift(Bnt(r));return this.inPlace(e,t,n),I4(n)}inPlace(e,t,n){if(Array.isArray(e.enum))n.push(v4(e.enum));if(Object.hasOwn(e,"const"))n.push(bZ(e.const));if(Array.isArray(e.allOf))n.push(I4(e.allOf.map((r)=>this.check(r,t))));if(Array.isArray(e.anyOf))n.push(this.union(e.anyOf,t,!1));if(Array.isArray(e.oneOf))n.push(this.union(e.oneOf,t,!0));if(e.not!==void 0)n.push(Nnt(this.check(e.not,t)));if(e.if!==void 0&&(e.then!==void 0||e.else!==void 0)){let r=e.then===void 0?Jv:this.check(e.then,t),a=e.else===void 0?Jv:this.check(e.else,t);n.push($nt(this.check(e.if,t),r,a))}if(typeof e.$ref==="string")n.push(this.ref(e.$ref,t));if(this.draft!=="7"&&typeof e.$dynamicRef==="string")n.push(this.dynamicRef(e.$dynamicRef,t))}union(e,t,n){let r=()=>e.map((a)=>this.check(a,t));return a$n(e,n)??this.tagged(e,t)??(n?Pnt(r()):Lnt(r()))}ref(e,t){let n=this.r.resolve(e,t),r=this.check(n.node,n.base);return this.dynamic&&n.base!==t?pBe(this.scope,n.base,r):r}dynamicRef(e,t){let n=this.bookended(e,t);if(n===void 0)return this.ref(e,t);let{initial:r,name:a}=n,i=this.check(r.node,r.base),o=this.dynamicLookup(a,(c,u)=>this.check(c,u)),s=this.scope;return(c)=>{for(let u=0;u<s.length;u++){let l=o(s[u]);if(l!==null)return l(c)}return i(c)}}bookended(e,t){let n=this.r.resolve(e,t),r=EC(e,t),a=r.slice(kC(r).length+1),i=ua(n.node)&&n.node.$dynamicAnchor===a;if(a===""||a.startsWith("/")||!i)return;if(!this.dynamic)throw yBe;return{initial:n,name:a}}dynamicLookup(e,t){let n=new Map;return(r)=>{let a=`${r}#${e}`,i=n.get(a);if(i===void 0){let o=this.r.dynamicAnchors.get(a);i=o===void 0?null:t(o,this.r.baseOf.get(o)??r),n.set(a,i)}return i}}tagged(e,t){if(e.length<2)return;let n=[];for(let a of e){if(!ua(a))return;let i=typeof a.$ref==="string"&&Object.keys(a).length===1?a.$ref:void 0,o=i===void 0?a:this.r.resolve(i,this.r.baseFor(a,t)).node;if(!ua(o))return;n.push(o)}let r=n[0].properties;if(!ua(r))return;for(let a of Object.keys(r)){let i=n.map((o)=>i$n(o,a));if(i.some((o)=>o===void 0)||new Set(i).size!==i.length)continue;return Ont(a,i,e.map((o)=>this.check(o,t)))}return}stringGroup(e,t){let n=Ld(e.minLength)??0,r=Ld(e.maxLength)??Number.POSITIVE_INFINITY,a=typeof e.pattern==="string"?Sb(e.pattern):void 0,i=this.formats!==void 0&&typeof e.format==="string"&&Object.hasOwn(this.formats,e.format)?this.formats[e.format]:void 0;if(n===0&&r===Number.POSITIVE_INFINITY&&a===void 0&&i===void 0)return;return xnt(t,n,r,a,i)}numberGroup(e,t){let n=Ld(e.minimum),r=Ld(e.maximum),a=Ld(e.exclusiveMinimum),i=Ld(e.exclusiveMaximum),o=Ld(e.multipleOf);if([n,r,a,i,o].every((c)=>c===void 0))return;let s=Number.POSITIVE_INFINITY;return _nt(t,n??-s,r??s,a??-s,i??s,o)}objectGroup(e,t,n){let r=n$n.every((l)=>e[l]===void 0),a=this.objectCore(e,t,r?n?uBe:ZR:_4);if(a!==void 0&&r)return a;let i=a===void 0?[]:[a];if(e.propertyNames!==void 0)i.push(Dnt(this.check(e.propertyNames,t)));let o=Ld(e.minProperties),s=Ld(e.maxProperties);if(o!==void 0||s!==void 0)i.push(Rnt(o??0,s??Number.POSITIVE_INFINITY));let c=[],u=[];if(this.draft!=="7"){for(let[l,d]of XR(e.dependentRequired))if(Array.isArray(d))c.push([l,d]);for(let[l,d]of XR(e.dependentSchemas))u.push([l,this.check(d,t)])}for(let[l,d]of XR(e.dependencies))if(Array.isArray(d))c.push([l,d]);else u.push([l,this.check(d,t)]);if(c.length>0)i.push(Tnt(c));if(u.length>0)i.push(Mnt(u));if(i.length===0)return n?sBe:void 0;return Int(I4(i),n)}objectCore(e,t,n){let r=ua(e.properties)?e.properties:{},a=Array.isArray(e.required)?e.required.filter((A)=>typeof A==="string"):[],i=ua(e.patternProperties)?e.patternProperties:{},o=e.additionalProperties,s=Object.keys(r),c=Object.keys(i);if(s.length+a.length+c.length===0&&(o===void 0||o===!0))return;let u=[];for(let A of s){let m=this.check(r[A],t),h=(cBe.get(m)??0)|(a.includes(A)?gZ:0)|(A in Object.prototype?dBe:0);u.push(A,m,h)}let l=a.filter((A)=>!Object.hasOwn(r,A)),d=c.map((A)=>[Sb(A),this.check(i[A],t)]),p=o===void 0||o===!0?void 0:this.check(o,t);if(d.length===0&&l.length===0&&(p===void 0||o===!1)){let A=s.filter((m)=>a.includes(m)).length;return Qnt(u,A,o===!1,n)}return Snt(u,s,l,d,p,n)}arrayGroup(e,t,n){let r=[],a;if(Array.isArray(e.items))r=e.items,a=e.additionalItems;else{if(this.draft!=="7"&&Array.isArray(e.prefixItems))r=e.prefixItems;a=e.items}let i=r.map((l)=>this.check(l,t)),o=a===void 0||a===!0?void 0:this.check(a,t),s=Ld(e.minItems),c=Ld(e.maxItems);if(e.contains===void 0&&e.uniqueItems!==!0&&(i.length>0||o!==void 0))return mBe(n?uBe:ZR,s??0,c??Number.POSITIVE_INFINITY,i,o);let u=[];if(i.length>0||o!==void 0)u.push(Fnt(i,o));if(s!==void 0||c!==void 0)u.push(jnt(s??0,c??Number.POSITIVE_INFINITY));if(e.contains!==void 0){let l=this.draft==="7"?1:Ld(e.minContains)??1,d=this.draft==="7"?Number.POSITIVE_INFINITY:Ld(e.maxContains)??Number.POSITIVE_INFINITY;u.push(fZ(this.check(e.contains,t),l,d))}if(e.uniqueItems===!0)u.push(hZ);if(u.length===0)return n?oBe:void 0;return vnt(I4(u),n)}annotating(e,t){if(e===!0)return qnt;if(e===!1)return Hnt;if(!ua(e))throw Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let n=this.annotatingCache.get(e);if(n!==void 0)return n;let r={check:void 0};this.annotatingCache.set(e,Wnt(r));let a=this.buildAnnotating(e,this.r.baseFor(e,t));return r.check=a,this.annotatingCache.set(e,a),a}buildAnnotating(e,t){let n={},r=!1;for(let c of Object.keys(e))if(r$n.has(c))r=!0;else n[c]=e[c];let a=this.plain(n,t),i=[];if(r)this.annotatingParts(e,t,i);let o=i.length===0?znt(a):Ynt(a,i),s=e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0?Knt(o):o;return this.dynamic&&this.r.isResource(e,t)?fBe(this.scope,t,s):s}annotatingParts(e,t,n){if(e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0){let r=XR(e.properties).map(([o,s])=>[o,this.check(s,t)]),a=XR(e.patternProperties).map(([o,s])=>[Sb(o),this.check(s,t)]),i=e.additionalProperties===void 0?void 0:this.check(e.additionalProperties,t);n.push(Znt(r,a,i))}if(e.prefixItems!==void 0||e.items!==void 0||e.contains!==void 0){let r=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[],a=Array.isArray(e.items)?e.additionalItems:e.items;n.push(Vnt(r.map((i)=>this.check(i,t)),a===void 0?void 0:this.check(a,t),e.contains===void 0?void 0:this.check(e.contains,t),Ld(e.minContains)??1,Ld(e.maxContains)??Number.POSITIVE_INFINITY))}if(Array.isArray(e.allOf))for(let r of e.allOf)n.push(this.annotating(r,t));if(Array.isArray(e.anyOf))n.push(hBe(e.anyOf.map((r)=>this.annotating(r,t)),!1));if(Array.isArray(e.oneOf))n.push(hBe(e.oneOf.map((r)=>this.annotating(r,t)),!0));if(e.if!==void 0){let r=e.then===void 0?void 0:this.annotating(e.then,t),a=e.else===void 0?void 0:this.annotating(e.else,t);n.push(Xnt(this.annotating(e.if,t),r,a))}if(typeof e.$ref==="string")n.push(this.annotatingRef(e.$ref,t));if(typeof e.$dynamicRef==="string")n.push(this.annotatingDynamicRef(e.$dynamicRef,t));for(let[r,a]of XR(e.dependentSchemas))n.push(ert(r,this.annotating(a,t)));if(e.unevaluatedProperties!==void 0)n.push(trt(this.check(e.unevaluatedProperties,t)));if(e.unevaluatedItems!==void 0)n.push(nrt(this.check(e.unevaluatedItems,t)))}annotatingRef(e,t){let n=this.r.resolve(e,t),r=this.annotating(n.node,n.base);return this.dynamic&&n.base!==t?fBe(this.scope,n.base,r):r}annotatingDynamicRef(e,t){let n=this.bookended(e,t);if(n===void 0)return this.annotatingRef(e,t);let{initial:r,name:a}=n,i=this.annotating(r.node,r.base),o=this.dynamicLookup(a,(c,u)=>this.annotating(c,u)),s=this.scope;return(c,u)=>{for(let l=0;l<s.length;l++){let d=o(s[l]);if(d!==null)return d(c,u)}return i(c,u)}}}function a$n(e,t){let n=[];for(let r of e){if(!ua(r)||!Object.hasOwn(r,"const"))return;for(let a of Object.keys(r))if(a!=="const"&&!rrt.has(a))return;if(typeof r.const==="object"&&r.const!==null)return;if(t&&n.includes(r.const))return;n.push(r.const)}return v4(n)}function i$n(e,t){let n=e.properties;if(e.type!=="object"||!Array.isArray(e.required)||!e.required.includes(t))return;let r=ua(n)?n[t]:void 0;if(!ua(r)||!Object.hasOwn(r,"const"))return;return typeof r.const==="object"&&r.const!==null?void 0:r.const}function Ld(e){return typeof e==="number"?e:void 0}function XR(e){return ua(e)?Object.entries(e):[]}var yBe,rrt,n$n,r$n;var art=I(()=>{bBe();yZ();sZ();lZ();yBe=Symbol("restart");rrt=new Set(["$schema","$comment","title","description","default","examples","deprecated","readOnly","writeOnly","$defs","definitions","contentEncoding","contentMediaType","minContains","maxContains","$vocabulary"]),n$n=["propertyNames","minProperties","maxProperties","dependentRequired","dependentSchemas","dependencies"],r$n=new Set(["properties","patternProperties","additionalProperties","prefixItems","items","additionalItems","contains","minContains","maxContains","allOf","anyOf","oneOf","if","then","else","$ref","$dynamicRef","dependentSchemas","unevaluatedProperties","unevaluatedItems"])});class EBe{c;schema;memo=void 0;constructor(e,t){this.c=e,this.schema=t,e.root()}errors(e){let t=[];try{this.walk(this.schema,this.c.r.rootBase,e,"",t)}finally{this.memo=void 0}if(t.length===0)t.push({path:"",keyword:"schema",message:"invalid"});return t}ok(e,t,n){return this.c.check(e,t)(n)}walk(e,t,n,r,a){if(e===!0)return;if(e===!1){a.push({path:r,keyword:"false",message:"no value is allowed here"});return}if(!ua(e))return;let i=this.c.r.baseFor(e,t);if(this.ok(e,i,n))return;let o=a.length,s=(c,u,l=r)=>{a.push({path:l,keyword:c,message:u})};if(this.c.draft==="7"&&typeof e.$ref==="string"){this.walkRef(e.$ref,i,n,r,a);return}if(e.type!==void 0){let c=Array.isArray(e.type)?e.type:[e.type];if(!c.map((l)=>(typeof l==="string"?x4.get(l):void 0)??C4).some((l)=>l(n))){s("type",`expected ${c.join(" or ")}, got ${s$n(n)}`);return}}if(Array.isArray(e.enum)&&!v4(e.enum)(n))s("enum",`expected one of ${irt(e.enum)}`);if(Object.hasOwn(e,"const")&&!bZ(e.const)(n))s("const",`expected ${JSON.stringify(e.const)}`);if(typeof n==="string"&&e.type!=="bytes")this.walkString(e,n,s);if(n instanceof Uint8Array&&e.type==="bytes")this.walkBytes(e,n,s);if(typeof n==="number")this.walkNumber(e,n,s);if(aA(n))this.walkObject(e,i,n,r,a,s);if(Array.isArray(n))this.walkArray(e,i,n,r,a,s);if(Array.isArray(e.allOf))for(let c of e.allOf)this.walk(c,i,n,r,a);if(Array.isArray(e.anyOf))this.walkUnion(e.anyOf,i,n,r,a,!1);if(Array.isArray(e.oneOf))this.walkUnion(e.oneOf,i,n,r,a,!0);if(e.not!==void 0&&this.ok(e.not,i,n))s("not","must not match the schema in not");if(e.if!==void 0){let c=this.ok(e.if,i,n)?e.then:e.else;if(c!==void 0)this.walk(c,i,n,r,a)}if(typeof e.$ref==="string")this.walkRef(e.$ref,i,n,r,a);if(a.length===o&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))this.walkUnevaluated(e,i,n,r,a);if(a.length===o&&typeof e.$dynamicRef==="string")s("$dynamicRef","does not match the dynamically referenced schema")}walkRef(e,t,n,r,a){let i=this.c.r.resolve(e,t);if(i.node===!1&&this.c.r.isUnresolved(e,t)){a.push({path:r,keyword:"$ref",message:`unresolved reference ${e}`});return}if(!ua(i.node)||typeof n!=="object"||n===null){this.walk(i.node,i.base,n,r,a);return}this.memo??=new Map;let o=this.memo.get(i.node),s=o?.get(n);if(s!==void 0&&s.path===r){a.push(...s.errors);return}let c=[];if(this.walk(i.node,i.base,n,r,c),o===void 0)o=new Map,this.memo.set(i.node,o);o.set(n,{path:r,errors:c}),a.push(...c)}walkString(e,t,n){let r=mZ(t);if(typeof e.minLength==="number"&&r<e.minLength)n("minLength",`expected at least ${e.minLength} characters`);if(typeof e.maxLength==="number"&&r>e.maxLength)n("maxLength",`expected at most ${e.maxLength} characters`);if(typeof e.pattern==="string"&&!Sb(e.pattern).test(t))n("pattern",`expected to match ${e.pattern}`);let a=this.c.formats,i=a!==void 0&&typeof e.format==="string"&&Object.hasOwn(a,e.format)?a[e.format]:void 0;if(i!==void 0&&!i(t))n("format",`expected format ${e.format}`)}walkBytes(e,t,n){if(typeof e.minLength==="number"&&t.length<e.minLength)n("minLength",`expected at least ${e.minLength} bytes`);if(typeof e.maxLength==="number"&&t.length>e.maxLength)n("maxLength",`expected at most ${e.maxLength} bytes`)}walkNumber(e,t,n){if(typeof e.minimum==="number"&&t<e.minimum)n("minimum",`expected >= ${e.minimum}`);if(typeof e.maximum==="number"&&t>e.maximum)n("maximum",`expected <= ${e.maximum}`);if(typeof e.exclusiveMinimum==="number"&&t<=e.exclusiveMinimum)n("exclusiveMinimum",`expected > ${e.exclusiveMinimum}`);if(typeof e.exclusiveMaximum==="number"&&t>=e.exclusiveMaximum)n("exclusiveMaximum",`expected < ${e.exclusiveMaximum}`);if(typeof e.multipleOf==="number"&&!ABe(t,e.multipleOf))n("multipleOf",`expected a multiple of ${e.multipleOf}`)}walkObject(e,t,n,r,a,i){let o=ua(e.properties)?e.properties:{},s=Array.isArray(e.required)?e.required:[];for(let d of s)if(typeof d==="string"&&(!Object.hasOwn(n,d)||n[d]===void 0))i("required","missing",T0(r,d));for(let d of Object.keys(o))if(Object.hasOwn(n,d)&&n[d]!==void 0)this.walk(o[d],t,n[d],T0(r,d),a);let c=ua(e.patternProperties)?Object.entries(e.patternProperties):[];for(let d of Object.keys(n)){let p=Object.hasOwn(o,d);for(let[A,m]of c)if(Sb(A).test(d))p=!0,this.walk(m,t,n[d],T0(r,d),a);if(!p&&e.additionalProperties!==void 0)if(e.additionalProperties===!1)i("additionalProperties","unknown field",T0(r,d));else this.walk(e.additionalProperties,t,n[d],T0(r,d),a);if(e.propertyNames!==void 0&&!this.ok(e.propertyNames,t,d))i("propertyNames","invalid property name",T0(r,d))}let u=Object.keys(n).length;if(typeof e.minProperties==="number"&&u<e.minProperties)i("minProperties",`expected at least ${e.minProperties} properties`);if(typeof e.maxProperties==="number"&&u>e.maxProperties)i("maxProperties",`expected at most ${e.maxProperties} properties`);let l={...this.c.draft==="7"||!ua(e.dependentRequired)?{}:e.dependentRequired,...ua(e.dependencies)?e.dependencies:{}};for(let[d,p]of Object.entries(l)){if(!Object.hasOwn(n,d))continue;if(!Array.isArray(p))this.walk(p,t,n,r,a);else for(let A of p)if(!Object.hasOwn(n,A))i("dependentRequired",`required when ${d} is present`,T0(r,A))}if(this.c.draft!=="7"&&ua(e.dependentSchemas)){for(let[d,p]of Object.entries(e.dependentSchemas))if(Object.hasOwn(n,d))this.walk(p,t,n,r,a)}}walkArray(e,t,n,r,a,i){let o=[],s;if(Array.isArray(e.items))o=e.items,s=e.additionalItems;else{if(this.c.draft!=="7"&&Array.isArray(e.prefixItems))o=e.prefixItems;s=e.items}for(let c=0;c<n.length;c++){let u=c<o.length?o[c]:s;if(u!==void 0)this.walk(u,t,n[c],`${r}/${c}`,a)}if(typeof e.minItems==="number"&&n.length<e.minItems)i("minItems",`expected at least ${e.minItems} items`);if(typeof e.maxItems==="number"&&n.length>e.maxItems)i("maxItems",`expected at most ${e.maxItems} items`);if(e.uniqueItems===!0&&!hZ(n))i("uniqueItems","expected unique items");if(e.contains!==void 0){let c=this.c.draft==="7",u=c||typeof e.minContains!=="number"?1:e.minContains,l=c||typeof e.maxContains!=="number"?Number.POSITIVE_INFINITY:e.maxContains;if(!fZ(this.c.check(e.contains,t),u,l)(n))i("contains",o$n(u,l))}}walkUnion(e,t,n,r,a,i){let o=e.filter((l)=>this.ok(l,t,n)).length;if(o===1||!i&&o>0)return;let s=i?"oneOf":"anyOf";if(o>1){a.push({path:r,keyword:s,message:"matches more than one alternative"});return}let c=this.tagOf(e,t);if(c!==void 0&&aA(n)){let l=c.values.indexOf(n[c.key]);if(l<0)a.push({path:T0(r,c.key),keyword:s,message:`expected one of ${irt(c.values)}`});else this.walk(e[l],t,n,r,a);return}let u;for(let l of e){let d=[];if(this.walk(l,t,n,r,d),d.length===0)continue;let p=aA(n)?this.declaredKeys(l,t,n):0;if(u===void 0||p>u.declared||p===u.declared&&d[0].path.length>u.errors[0].path.length)u={errors:d,declared:p}}a.push(...u?.errors??[{path:r,keyword:s,message:"matches no alternative"}])}declaredKeys(e,t,n){let r=ua(e)&&typeof e.$ref==="string"?this.c.r.resolve(e.$ref,t).node:e,a=ua(r)&&ua(r.properties)?r.properties:{};return Object.keys(n).filter((i)=>Object.hasOwn(a,i)).length}tagOf(e,t){let n=e.map((a)=>ua(a)&&typeof a.$ref==="string"?this.c.r.resolve(a.$ref,t).node:a),r=n[0];if(!ua(r)||!ua(r.properties))return;for(let a of Object.keys(r.properties)){let i=n.map((s)=>{let c=ua(s)&&ua(s.properties)?s.properties[a]:void 0;return ua(c)?c.const:void 0});if(i.every((s)=>s!==void 0&&(typeof s!=="object"||s===null))&&new Set(i).size===i.length)return{key:a,values:i}}return}walkUnevaluated(e,t,n,r,a){let{unevaluatedProperties:i,unevaluatedItems:o,...s}=e,c=VR();if(this.c.annotating(s,t)(n,c),aA(n)&&i!==void 0&&!c.allProps)for(let u of Object.keys(n)){if(c.props?.has(u))continue;if(i===!1)a.push({path:T0(r,u),keyword:"unevaluatedProperties",message:"unknown field"});else this.walk(i,t,n[u],T0(r,u),a)}if(Array.isArray(n)&&o!==void 0&&!c.allItems)for(let u=c.items;u<n.length;u++){if(c.indexes?.has(u))continue;if(o===!1)a.push({path:`${r}/${u}`,keyword:"unevaluatedItems",message:"unexpected item"});else this.walk(o,t,n[u],`${r}/${u}`,a)}}}function irt(e){if(e.length<=wBe)return JSON.stringify(e);return`${JSON.stringify(e.slice(0,wBe)).slice(0,-1)}, ... and ${e.length-wBe} more]`}function o$n(e,t){if(t===Number.POSITIVE_INFINITY)return`expected at least ${e} matching ${e===1?"item":"items"}`;if(e===0)return`expected at most ${t} matching ${t===1?"item":"items"}`;return`expected between ${e} and ${t} matching items`}function T0(e,t){return`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`}function s$n(e){if(e===null)return"null";if(Array.isArray(e))return"array";if(e instanceof Uint8Array)return"bytes";if(typeof e==="number"&&Number.isInteger(e))return"integer";return typeof e}var wBe=20;var ort=I(()=>{bBe();yZ();sZ();lZ()});function fg(e,t=c$n){let n=l$n(e,t);return t.coerce===!0?new kBe(e,t,n):new EZ(e,t,n)}class EZ{check;schema;options;explainer=void 0;constructor(e,t,n){this.check=n,this.schema=e,this.options=t}errors(e){if(this.check(e))return[];return this.explainer??=new EBe(BBe(this.schema,this.options),this.schema),this.explainer.errors(e)}}function l$n(e,t){return BBe(e,t).root()}function BBe(e,t){let n=new wZ(e,t,!1);try{return n.root(),n}catch(r){if(r!==yBe)throw r;return new wZ(e,t,!0)}}var c$n,kBe;var srt=I(()=>{mnt();art();ort();c$n=Object.freeze({});kBe=class kBe extends EZ{coercer=void 0;coerce(e){return this.coercer??=new aBe(BBe(this.schema,this.options),this.schema),this.coercer.coerce(e)}parse(e){let t=this.coerce(e);return this.check(t)?{ok:!0,value:t}:{ok:!1,errors:this.errors(t)}}}});var NE=I(()=>{srt()});function SZ(e){let t=0,n=0,r=!1;for(let a of e)if(t+=a.additions,n+=a.deletions,a.status!=="untracked")r=!0;return{additions:t,deletions:n,tracked:r}}function D4(e){if(!$r(e))return{};let t={changesRatio:CBe(e.changesRatio,vZ,QZ),gitPaneRatio:CBe(e.gitPaneRatio,kZ,BZ),layout:e.layout==="split"||e.layout==="unified"?e.layout:void 0,mode:e.mode==="all"||e.mode==="selected"?e.mode:void 0,reviewSidebarWidth:CBe(e.reviewSidebarWidth,xZ,_Z),tab:e.tab==="files"||e.tab==="git"?e.tab:void 0,wrap:jE(e.wrap)?e.wrap:void 0};return Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))}function CBe(e,t,n){return Gl(e)?Math.min(Math.max(e,t),n):void 0}var Q4=50,S4=0.5,kZ=0.35,BZ=0.65,CZ=272,xZ=224,_Z=480,IZ=0.5,vZ=0.3,QZ=0.7,xBe,_Be,crt,IBe,u$n,d$n,k6a,B6a,C6a;var BC=I(()=>{NE();xBe={branch:null,changes:[],commits:[],isGitRepository:!1,changeCount:0,revision:"non-git"},_Be={...xBe,revision:"git-unloaded"},crt=wp({additions:fi(),deletions:fi(),path:ei(),status:R0(["added","deleted","modified","renamed","untracked"])},{open:!0}),IBe=wp({author:ei(),authoredAt:ei(),hash:ei(),pushed:iZ(Oi()),shortHash:ei(),subject:ei(),tags:jd(ei())},{open:!0}),u$n=wp({changes:jd(crt),commit:IBe,patch:ei()},{open:!0}),d$n=wp({branch:iZ(ei()),changes:jd(crt),commits:jd(IBe),isGitRepository:Oi(),changeCount:fi(),revision:ei()},{open:!0}),k6a=fg(u$n),B6a=fg(jd(IBe)),C6a=fg(d$n)});function DZ(e){let t=el,n=WR(),r=SZ(e.workspaceReview.changes);return{_modelsRevision:e.modelsRevision,_codeThemeDark:t.dark,_codeThemeLight:t.light,_fontMono:n.mono,_fontSans:n.sans,_promptHistory:e.promptHistory,_promptSessionKey:e.promptSessionKey,_thinkingHidden:e.thinkingHidden,_theme:e.theme,_keybindHints:e.keybindHints,_minimalMode:e.minimalMode,_toolOutputHidden:e.toolOutputHidden,_toolbarHidden:e.toolbarHidden,_temporarySession:e.isTemporarySession,_sessionTransitionGeneration:e.sessionTransition.generation,_sessionTransitionStatus:e.sessionTransition.status,_sessionTransitionVisible:LY(e.sessionTransition),_workspaceReviewAdditions:r.additions,_workspaceReviewBranch:e.workspaceReview.branch??"",_workspaceReviewDeletions:r.deletions,_workspaceReviewGitAvailable:e.workspaceReview.isGitRepository,_workspaceReviewChangeCount:e.workspaceReview.changeCount,_workspaceReviewStatsKnown:r.tracked}}var vBe=I(()=>{f4();zR();vb();BC()});function g$n(e){return e.split("-").map((t)=>m$n.get(t)??`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function urt(e,t){return{appearance:t,label:g$n(e),name:e}}function TZ(e){return e==="light"?drt:prt}function RZ(e,t){return zn(t)?TZ(e).find((n)=>n.name===t):void 0}function Art(e){if(!$r(e))return;let t=RZ("light",e.light)?.name,n=RZ("dark",e.dark)?.name;return t&&n?{dark:n,light:t}:void 0}function mrt(){return{...Xke}}var lrt="// syntax preview\nconst greet = (name: string) => {\n return `hello, ${name}!`;\n};",p$n,A$n,m$n,drt,prt,T6a;var MZ=I(()=>{vb();p$n=["pierre-light","pierre-light-soft","pierre-light-vibrant","pierre-light-protanopia-deuteranopia","pierre-light-tritanopia","ayu-light","catppuccin-latte","everforest-light","github-light","github-light-default","github-light-high-contrast","gruvbox-light-hard","gruvbox-light-medium","gruvbox-light-soft","horizon-bright","kanagawa-lotus","light-plus","material-theme-lighter","min-light","night-owl-light","one-light","rose-pine-dawn","slack-ochin","snazzy-light","solarized-light","vitesse-light"],A$n=["pierre-dark","pierre-dark-soft","pierre-dark-vibrant","pierre-dark-protanopia-deuteranopia","pierre-dark-tritanopia","ayu-dark","ayu-mirage","catppuccin-frappe","catppuccin-macchiato","catppuccin-mocha","everforest-dark","github-dark","github-dark-default","github-dark-dimmed","github-dark-high-contrast","gruvbox-dark-hard","gruvbox-dark-medium","gruvbox-dark-soft","horizon","kanagawa-wave","kanagawa-dragon","dark-plus","material-theme","material-theme-darker","material-theme-ocean","material-theme-palenight","min-dark","night-owl","one-dark-pro","rose-pine","rose-pine-moon","slack-dark","andromeeda","solarized-dark","vitesse-dark","vitesse-black","aurora-x","dracula","dracula-soft","houston","laserwave","monokai","nord","plastic","poimandres","red","synthwave-84","tokyo-night","vesper"],m$n=new Map(Object.entries({ayu:"Ayu",cvd:"CVD",github:"GitHub",min:"Min",pierre:"Pierre",vscode:"VS Code"}));drt=p$n.map((e)=>urt(e,"light")).toSorted((e,t)=>e.label.localeCompare(t.label)),prt=A$n.map((e)=>urt(e,"dark")).toSorted((e,t)=>e.label.localeCompare(t.label)),T6a=[...drt,...prt]});function grt(){let e=el,t=Object.fromEntries(["light","dark"].map((n)=>[n,TZ(n).map((r)=>r.label.toLowerCase())]));return an(yl.jsxDEV("dialog",{id:"code-theme-dialog",class:"dialog code-theme-dialog","aria-labelledby":"code-theme-title","data-signals__ifmissing":JSON.stringify({_codeThemeAppearance:"light",_codeThemeSearch:"",_codeThemeStatus:""}),"data-on:pi-ui-open-code-theme__window":`
|
|
44
44
|
$_codeThemeAppearance = window.piUiTheme.currentMode();
|
|
45
45
|
$_codeThemeSearch = '';
|
|
46
46
|
$_codeThemeStatus = '';
|
|
@@ -728,7 +728,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
728
728
|
`);_k.mkdirSync(jQ.dirname(T),{recursive:!0}),_k.writeFileSync(T,O),this.stop();let q=[`Rendered line ${_} exceeds terminal width (${Xt(v)} > ${e}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${T}`].join(`
|
|
729
729
|
`);throw Error(q)}y.append(v)}let x=k;if(this.previousLines.length>u.length){if(k<u.length-1){let v=u.length-1-k;y.append(`\x1B[${v}B`),x=u.length-1}let _=this.previousLines.length-u.length;for(let v=u.length;v<this.previousLines.length;v++)y.append(`\r
|
|
730
730
|
\x1B[2K`);y.append(`\x1B[${_}A`)}if(y.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){_k.mkdirSync("/tmp/tui",{recursive:!0});let v=jQ.join("/tmp/tui",`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),U=[`firstChanged: ${m}`,`viewportTop: ${o}`,`cursorRow: ${this.cursorRow}`,`height: ${t}`,`lineDiff: ${B}`,`hardwareCursorRow: ${s}`,`renderEnd: ${k}`,`finalCursorRow: ${x}`,`cursorPos: ${JSON.stringify(l)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${y.length} chars written in bounded chunks]`].join(`
|
|
731
|
-
`);_k.writeFileSync(v,U)}y.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=x,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(i,x-t+1),this.positionHardwareCursor(l,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let n=Math.max(0,Math.min(e.row,t-1)),r=Math.max(0,e.col),a=n-this.hardwareCursorRow,i="";if(a>0)i+=`\x1B[${a}B`;else if(a<0)i+=`\x1B[${-a}A`;if(i+=`\x1B[${r+1}G`,i)this.terminal.write(i);if(this.hardwareCursorRow=n,this.getShowHardwareCursor())this.terminal.showCursor();else this.terminal.hideCursor()}}});var h5={};Ke(h5,{Box:()=>Cu,CURSOR_MARKER:()=>Fg,CancellableLoader:()=>r5,CombinedAutocompleteProvider:()=>yQ,Container:()=>pn,Editor:()=>_Q,HStack:()=>P2e,Image:()=>QQ,Input:()=>Eo,Key:()=>BQ,KeybindingsManager:()=>oF,Loader:()=>Xb,Markdown:()=>kc,Marked:()=>mQ,MouseRegion:()=>jg,ProcessTerminal:()=>xk,ScrollView:()=>MQ,SelectList:()=>ud,SettingsList:()=>FQ,Spacer:()=>Mt,StdinBuffer:()=>A5,TUI_KEYBINDINGS:()=>kk,Text:()=>Tt,TruncatedText:()=>mA,TuiAltScreen:()=>ym,TuiMainScreen:()=>Zf,VStack:()=>pF,allocateImageId:()=>Lre,backgroundAnsi:()=>uw,calculateImageRows:()=>q2t,colorToHex:()=>zM,colorToOkhsl:()=>Rre,colorToOklch:()=>lw,colorToRgb:()=>Wf,compositeTuiLine:()=>dw,decodeKittyPrintable:()=>Z$,deleteAllKittyImages:()=>Pre,deleteKittyImage:()=>rF,detectCapabilities:()=>X$,encodeITerm2:()=>k2e,encodeKitty:()=>w2e,foregroundAnsi:()=>hm,formatProgramStatus:()=>AF,fuzzyFilter:()=>ds,fuzzyMatch:()=>gQ,getCapabilities:()=>Ec,getCellDimensions:()=>V$,getGifDimensions:()=>_2e,getImageDimensions:()=>aF,getJpegDimensions:()=>x2e,getKeybindings:()=>na,getNativeClipboard:()=>_x,getOsc8LinkAtColumn:()=>xre,getPngDimensions:()=>t5,getSelectPageIndex:()=>Ip,getTerminalColorMode:()=>CQ,getWebpDimensions:()=>I2e,hyperlink:()=>ld,imageFallback:()=>xQ,indexedColor:()=>wQ,isAppleTerminalSession:()=>m5,isFocusable:()=>Ure,isKeyRelease:()=>ZM,isKeyRepeat:()=>v2t,isKittyProtocolActive:()=>_2t,isViewportTUI:()=>n5,matchesKey:()=>cd,mixColors:()=>JM,okhslColor:()=>EQ,oklabToOkhslLightness:()=>qM,oklchColor:()=>WM,parseColor:()=>Vb,parseKey:()=>D2t,parseTerminalColorSchemeReport:()=>Fre,renderFakeCursor:()=>Cx,renderImage:()=>$re,renderLatex:()=>d5,replaceControlCharacters:()=>hk,resetCapabilitiesCache:()=>P2t,rgbColor:()=>Gd,setCapabilities:()=>e5,setCapabilityOverrides:()=>wk,setCellDimensions:()=>jre,setImageTranscoder:()=>Kre,setKeybindings:()=>xx,setKittyProtocolActive:()=>YM,sliceByColumn:()=>Ds,stripTerminalSequences:()=>fQ,styleText:()=>E2t,styleTextWithAnsi:()=>W$,truncateToWidth:()=>sr,visibleWidth:()=>Xt,wrapTextWithAnsi:()=>AA});var Zn=I(()=>{a2e();d2t();k2t();J2t();Z2t();uDt();pDt();ADt();Yre();T2e();vDt();QDt();W2e();F2e();SDt();R2e();DDt();RDt();Bk();kx();U2e();nae();f2e();J2e();K2e();YDt();b2e();Bx();Kf();dRt();fRt();$c()});class b5{messageSeq=0;activeAssistantId;activeThoughtId;transcriptMessages=[];messageIndexById=new Map;visibleMessageStart=0;emptyChatHint;activityText;queuedSteeringMessages=[];queuedFollowUpMessages=[];constructor(e){this.emptyChatHint={...e}}get hasOlderMessages(){return this.visibleMessageStart>0}get activeAssistantMessageId(){return this.activeAssistantId}get activeThoughtMessageId(){return this.activeThoughtId}get messages(){return this.transcriptMessages.slice(this.visibleMessageStart)}get allMessages(){return this.transcriptMessages}getMessage(e){let t=this.messageIndexById.get(e);return t===void 0?void 0:this.transcriptMessages[t]}getMessageIndex(e){return this.messageIndexById.get(e)}isMessageVisible(e){let t=this.messageIndexById.get(e);return t!==void 0&&t>=this.visibleMessageStart}appendMessage(e,t,n={}){this.messageSeq+=1;let r=`m-${this.messageSeq}`;if(this.transcriptMessages.push({id:r,role:e,text:t,timestamp:new Date,...n}),this.messageIndexById.set(r,this.transcriptMessages.length-1),e==="assistant")this.activeAssistantId=r;if(e==="thought")this.activeThoughtId=r;return r}updateMessage(e,t){let n=this.getMessage(e);if(!n)return!1;return Object.assign(n,t),!0}appendThoughtDelta(e){let t=this.activeThoughtId?this.getMessage(this.activeThoughtId):void 0;if(!t)return this.appendMessage("thought",e);return t.text+=e,t.id}appendAssistantDelta(e){this.activeThoughtId=void 0;let t=this.activeAssistantId?this.getMessage(this.activeAssistantId):void 0;if(!t)return this.appendMessage("assistant",e);return t.text+=e,t.id}finishAssistant(){let e={assistantId:this.activeAssistantId,thoughtId:this.activeThoughtId};return this.activeAssistantId=void 0,this.activeThoughtId=void 0,e}setActivityText(e){this.activityText=e}setQueuedMessages(e,t){this.queuedSteeringMessages=[...e],this.queuedFollowUpMessages=[...t]}snapshot(){return{messageSeq:this.messageSeq,activeAssistantId:this.activeAssistantId,activeThoughtId:this.activeThoughtId,transcriptMessages:this.transcriptMessages.map(hRt),visibleMessageStart:this.visibleMessageStart,emptyChatHint:{...this.emptyChatHint},activityText:this.activityText,queuedSteeringMessages:[...this.queuedSteeringMessages],queuedFollowUpMessages:[...this.queuedFollowUpMessages]}}restore(e){this.messageSeq=e.messageSeq,this.activeAssistantId=e.activeAssistantId,this.activeThoughtId=e.activeThoughtId,this.transcriptMessages=e.transcriptMessages.map(hRt),this.rebuildMessageIndex(),this.visibleMessageStart=e.visibleMessageStart,this.emptyChatHint={...e.emptyChatHint},this.activityText=e.activityText,this.queuedSteeringMessages=[...e.queuedSteeringMessages],this.queuedFollowUpMessages=[...e.queuedFollowUpMessages]}reset(e){if(this.transcriptMessages=[],this.messageIndexById.clear(),this.visibleMessageStart=0,this.activeAssistantId=void 0,this.activeThoughtId=void 0,e)this.emptyChatHint={...e}}replaceMessages(e,t){let n=this.transcriptMessages.length,r=this.visibleMessageStart;if(this.activeAssistantId=void 0,this.activeThoughtId=void 0,t)this.emptyChatHint={...t};this.transcriptMessages=e.map((a)=>(this.messageSeq+=1,{...a,id:`m-${this.messageSeq}`})),this.rebuildMessageIndex(),this.visibleMessageStart=n===0?Math.max(0,this.transcriptMessages.length-30):Math.min(r,this.transcriptMessages.length)}showRecentMessages(){let e=Math.max(0,this.transcriptMessages.length-30);if(e<=this.visibleMessageStart)return!1;return this.visibleMessageStart=e,!0}loadOlderMessages(){if(!this.hasOlderMessages)return[];let e=this.visibleMessageStart;return this.visibleMessageStart=Math.max(0,e-30),this.transcriptMessages.slice(this.visibleMessageStart,e)}trimOldMessages(e,t){if(this.transcriptMessages[this.visibleMessageStart]?.id!==e)return[];let n=this.messageIndexById.get(t);if(n===void 0||n<this.visibleMessageStart||n>=this.transcriptMessages.length-100)return[];let r=this.transcriptMessages.slice(this.visibleMessageStart,n+1).map(({id:a})=>a);return this.visibleMessageStart=n+1,r}rebuildMessageIndex(){this.messageIndexById=new Map(this.transcriptMessages.map((e,t)=>[e.id,t]))}}function hRt(e){return{...e,attachments:e.attachments?.map((t)=>({...t,image:t.image?{...t.image}:void 0})),nestedCalls:e.nestedCalls?structuredClone(e.nestedCalls):void 0,timestamp:new Date(e.timestamp),titleParts:e.titleParts?.map((t)=>({...t}))}}function fF(e,t){if(e.path===t.currentSessionPath)return t.activityText?"running":void 0;return e.backgroundStatus}function qkr(){return[...JR.flatMap((t)=>{let n=jc(t.id);return n?[{keys:y4(n),description:t.description}]:[]}),{keys:"@",description:"Attach a file path."},{keys:"/",description:"Open slash commands and skills."}]}function sDe(){let e=qkr();return e[Math.floor(Math.random()*e.length)]}function Hkr(){return process.env.PI_UI_DEBUG==="1"}function Wkr(){return process.env.PI_UI_INSPECTOR==="1"}function zkr(e){let t=new Set(e);return t.delete(""),[...t]}class cDe{transcript=new b5(sDe());presentation;debugUi=Hkr();datastarInspector=Wkr();documentTitle="pi-ui";updateAvailable;promptEditorText="";models=[];modelsRevision=0;sessionCatalogLoading=!0;sessionCatalog=[];sessionLimit=bRt;treeEntries=[];slashCommands=[];authDialog;extensionDialog;extensionStatuses=[];extensionWidgets=[];extensionWorkingIndicator;extensionWorkingMessage;extensionWorkingVisible=!0;llamaDialog;currentModel;currentSessionPath;previousSessionPath;isTemporarySession=!1;thinkingLevel="off";thinkingLevels=["off"];thinkingHidden=!1;theme="system";keybindHints=!0;minimalMode=!1;toolOutputHidden=!1;toolbarHidden=!1;sessionSidebarOpen=!0;sessionSidebarWidth=D0;sessionSidebarArchive=!0;sessionSidebarArchiveAfterDays=nZ;usage={text:"$0.000 \u2022 0 tokens",costText:"$0.000"};workspacePath=a9();projectRoot=this.workspacePath;workspaceFilesRevision=0;workspaceTreeRevision=0;workspaceReview=_Be;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.orderedSessions.slice(0,this.sessionLimit)}get orderedSessions(){let e=[],t=[],n=[];for(let r of this.sessionCatalog){let a=fF(r,this);if(a==="running")e.push(r);else if(a==="completed")t.push(r);else n.push(r)}return t.concat(e,n)}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(){return Object.freeze({messages:this.messages.map((e)=>({...e})),models:this.models.map((e)=>({...e})),modelsRevision:this.modelsRevision,sessions:this.sessions.map((e)=>({...e})),sessionsHasMore:this.sessionsHasMore,sessionCatalogLoading:this.sessionCatalogLoading,treeEntries:this.treeEntries.map((e)=>({...e})),slashCommands:this.slashCommands.map((e)=>({...e})),authDialog:this.authDialog?structuredClone(this.authDialog):void 0,extensionDialog:this.extensionDialog?structuredClone(this.extensionDialog):void 0,extensionStatuses:this.extensionStatuses.map((e)=>({...e})),extensionWidgets:this.extensionWidgets.map((e)=>({...e,lines:[...e.lines]})),extensionWorkingIndicator:this.extensionWorkingIndicator,extensionWorkingMessage:this.extensionWorkingMessage,extensionWorkingVisible:this.extensionWorkingVisible,llamaDialog:this.llamaDialog?structuredClone(this.llamaDialog):void 0,currentModel:this.currentModel,currentSessionPath:this.currentSessionPath,previousSessionPath:this.previousSessionPath,isTemporarySession:this.isTemporarySession,thinkingLevel:this.thinkingLevel,thinkingLevels:[...this.thinkingLevels],thinkingHidden:this.thinkingHidden,theme:this.theme,keybindHints:this.keybindHints,minimalMode:this.minimalMode,toolOutputHidden:this.toolOutputHidden,toolbarHidden:this.toolbarHidden,sessionSidebarArchive:this.sessionSidebarArchive,sessionSidebarArchiveAfterDays:this.sessionSidebarArchiveAfterDays,usage:{...this.usage},activityText:this.activityText,queuedSteeringMessages:this.queuedSteeringMessages,queuedFollowUpMessages:this.queuedFollowUpMessages,workspacePath:this.workspacePath,projectRoot:this.projectRoot,workspaceFilesRevision:this.workspaceFilesRevision,workspaceTreeRevision:this.workspaceTreeRevision,workspaceReview:this.workspaceReview,workspaceReviewPreferences:{...this.workspaceReviewPreferences},recentWorkspaces:[...this.recentWorkspaces],sessionTransition:{...this.sessionTransition},debugUi:this.debugUi,datastarInspector:this.datastarInspector,documentTitle:this.documentTitle,updateAvailable:this.updateAvailable,hasOlderMessages:this.hasOlderMessages,promptHistory:this.promptHistory,promptEditorText:this.promptEditorText,emptyChatHint:{...this.emptyChatHint}})}update(e,t={}){try{return e()}finally{if(t.commit!==!1)this.commit()}}commit(e){this.presentation?.requestCommit(e)}commitView(){this.presentation?.viewChanged()}appendMessage(e,t,n={}){let r=this.transcript.appendMessage(e,t,n);return this.presentation?.messageAppended(r),r}getMessage(e){return this.transcript.getMessage(e)}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=Jr.startSpan("transcriptInstall");this.presentation?.transcriptReplacing(),this.transcript.restore(e),t(),Jr.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:sDe()),this.presentation?.transcriptReplaced([],[]),e.broadcast!==!1)this.commit()}replaceMessages(e){let t=Jr.startSpan("transcriptInstall");this.presentation?.transcriptReplacing(),this.transcript.replaceMessages(e,e.length===0?sDe():void 0),t(),Jr.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(e,t){let n=this.transcript.trimOldMessages(e,t);if(n.length>0)this.presentation?.messagesRemoved(n)}setModels(e,t){this.models=e,this.currentModel=t,this.modelsRevision+=1,this.commitView()}setThinking(e,t){this.thinkingLevel=e,this.thinkingLevels=t.length>0?t:["off"],this.commitView()}setThinkingHidden(e){if(this.thinkingHidden===e)return;this.thinkingHidden=e,this.commit()}setSessionCatalogLoading(e){if(this.sessionCatalogLoading===e)return;this.sessionCatalogLoading=e,this.commitView()}setSessionCatalog(e){this.sessionCatalog=e,this.commitView()}loadMoreSessions(){this.sessionLimit=Math.min(this.sessionLimit+bRt,this.getSessionCatalog().length),this.commitView()}getSessionCatalog(){return this.sessionCatalog}promoteSession(e,t={}){let n=this.getSessionCatalog(),r=n.findIndex((a)=>a.path===e);if(r<0)return!1;if(r===0){if(t.regroup)this.commitView();return!1}return this.sessionCatalog=[n[r],...n.toSpliced(r,1)],this.commitView(),!0}updateSessionSummary(e,t){let n=this.getSessionCatalog(),r=n.findIndex((a)=>a.path===e);if(r<0)return!1;return this.sessionCatalog=n.with(r,t(n[r])),this.commitView(),!0}searchSessions(e){let t=e.trim().toLowerCase();if(!t)return[...this.sessions];let n=t.split(/\s+/);return this.orderedSessions.values().filter((r)=>{let a=`${r.title} ${dre(r.messageCount)} ${r.cwd} ${r.path}`.toLowerCase();return n.every((i)=>a.includes(i))}).take(this.sessionLimit).toArray()}removeSession(e){this.setSessionCatalog(this.getSessionCatalog().filter((t)=>t.path!==e))}setRecentWorkspaces(e){this.recentWorkspaces=zkr([...e.filter((t)=>!LT(t)),...this.recentWorkspaces]),this.commitView()}setSlashCommands(e){this.slashCommands=e,this.commitView()}setAuthDialog(e){this.authDialog=e,this.commitView()}setExtensionDialog(e){this.extensionDialog=e,this.commitView()}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.commit()}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.commitView()}setTreeEntries(e){this.treeEntries=e,this.commitView()}openTreeDialog(){this.commitView(),this.commit({type:"open-tree-dialog"})}setUsage(e){this.usage=e,this.commit()}setActivityText(e){if(this.activityText===e)return;this.transcript.setActivityText(e),this.commit()}setQueuedMessages(e,t){this.transcript.setQueuedMessages(e,t),this.commit()}setCurrentSessionPath(e){if(e&&e!==this.currentSessionPath&&this.currentSessionPath)this.previousSessionPath=this.currentSessionPath;this.currentSessionPath=e,this.commitView()}setPreviousSessionPath(e){if(this.previousSessionPath===e)return;this.previousSessionPath=e,this.commit()}setTemporarySession(e){this.isTemporarySession=e,this.commit()}setUpdateAvailable(e){this.updateAvailable=e,this.commit()}setWorkspacePath(e){if(this.workspacePath===e)return;this.workspacePath=e,this.workspaceFilesRevision=0,this.workspaceTreeRevision=0,this.workspaceReview=_Be,this.commitView(),this.workspacePathListener?.(e)}setProjectRoot(e){if(this.projectRoot===e)return;this.projectRoot=e,this.commitView()}workspaceFilesChanged(e=!0){if(this.workspaceFilesRevision+=1,e)this.workspaceTreeRevision+=1;this.commitView()}setWorkspaceReview(e){if(this.workspaceReview.revision===e.revision)return;this.workspaceReview=e,this.commitView()}setWorkspaceReviewPreferences(e){this.workspaceReviewPreferences=e,this.commitView()}setSessionTransition(e){let t=this.sessionTransition.status==="loading"&&e.status==="idle";this.sessionTransition=e,this.presentation?.sessionTransitionChanged(t)}}var bRt=30;var lae=I(()=>{VY();Ib();bC();KR();w4();Tf();BC()});function lDe(e){return an(Ik.jsxDEV("ul",{id:e.id,"aria-label":e.label,role:e.role??"listbox",class:e.class??"picker-list",children:e.children},void 0,!1,void 0,this))}function yRt(e){return an(Ik.jsxDEV("li",{id:`file-option-${encodeURIComponent(e.value)}`,role:"option","data-picker-kind":e.kind,"data-picker-value":e.value,class:"picker-row","aria-selected":e.selected?"true":"false","data-file-row":!0,children:Ik.jsxDEV("div",{class:"picker-row-button",children:[Ik.jsxDEV("span",{class:"picker-row-content",children:[Ik.jsxDEV("span",{class:"picker-row-title",safe:!0,children:e.label},void 0,!1,void 0,this),Ik.jsxDEV("span",{class:"picker-row-description",safe:!0,children:e.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ik.jsxDEV(uDe,{text:e.metadata},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this))}function uDe(e){return an(Ik.jsxDEV("span",{class:"badge","data-variant":"secondary",safe:!0,children:e.text},void 0,!1,void 0,this))}var Ik;var wRt=I(()=>{Ik=mn(ur(),1)});function Jkr(e){return`
|
|
731
|
+
`);_k.writeFileSync(v,U)}y.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=x,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(i,x-t+1),this.positionHardwareCursor(l,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let n=Math.max(0,Math.min(e.row,t-1)),r=Math.max(0,e.col),a=n-this.hardwareCursorRow,i="";if(a>0)i+=`\x1B[${a}B`;else if(a<0)i+=`\x1B[${-a}A`;if(i+=`\x1B[${r+1}G`,i)this.terminal.write(i);if(this.hardwareCursorRow=n,this.getShowHardwareCursor())this.terminal.showCursor();else this.terminal.hideCursor()}}});var h5={};Ke(h5,{Box:()=>Cu,CURSOR_MARKER:()=>Fg,CancellableLoader:()=>r5,CombinedAutocompleteProvider:()=>yQ,Container:()=>pn,Editor:()=>_Q,HStack:()=>P2e,Image:()=>QQ,Input:()=>Eo,Key:()=>BQ,KeybindingsManager:()=>oF,Loader:()=>Xb,Markdown:()=>kc,Marked:()=>mQ,MouseRegion:()=>jg,ProcessTerminal:()=>xk,ScrollView:()=>MQ,SelectList:()=>ud,SettingsList:()=>FQ,Spacer:()=>Mt,StdinBuffer:()=>A5,TUI_KEYBINDINGS:()=>kk,Text:()=>Tt,TruncatedText:()=>mA,TuiAltScreen:()=>ym,TuiMainScreen:()=>Zf,VStack:()=>pF,allocateImageId:()=>Lre,backgroundAnsi:()=>uw,calculateImageRows:()=>q2t,colorToHex:()=>zM,colorToOkhsl:()=>Rre,colorToOklch:()=>lw,colorToRgb:()=>Wf,compositeTuiLine:()=>dw,decodeKittyPrintable:()=>Z$,deleteAllKittyImages:()=>Pre,deleteKittyImage:()=>rF,detectCapabilities:()=>X$,encodeITerm2:()=>k2e,encodeKitty:()=>w2e,foregroundAnsi:()=>hm,formatProgramStatus:()=>AF,fuzzyFilter:()=>ds,fuzzyMatch:()=>gQ,getCapabilities:()=>Ec,getCellDimensions:()=>V$,getGifDimensions:()=>_2e,getImageDimensions:()=>aF,getJpegDimensions:()=>x2e,getKeybindings:()=>na,getNativeClipboard:()=>_x,getOsc8LinkAtColumn:()=>xre,getPngDimensions:()=>t5,getSelectPageIndex:()=>Ip,getTerminalColorMode:()=>CQ,getWebpDimensions:()=>I2e,hyperlink:()=>ld,imageFallback:()=>xQ,indexedColor:()=>wQ,isAppleTerminalSession:()=>m5,isFocusable:()=>Ure,isKeyRelease:()=>ZM,isKeyRepeat:()=>v2t,isKittyProtocolActive:()=>_2t,isViewportTUI:()=>n5,matchesKey:()=>cd,mixColors:()=>JM,okhslColor:()=>EQ,oklabToOkhslLightness:()=>qM,oklchColor:()=>WM,parseColor:()=>Vb,parseKey:()=>D2t,parseTerminalColorSchemeReport:()=>Fre,renderFakeCursor:()=>Cx,renderImage:()=>$re,renderLatex:()=>d5,replaceControlCharacters:()=>hk,resetCapabilitiesCache:()=>P2t,rgbColor:()=>Gd,setCapabilities:()=>e5,setCapabilityOverrides:()=>wk,setCellDimensions:()=>jre,setImageTranscoder:()=>Kre,setKeybindings:()=>xx,setKittyProtocolActive:()=>YM,sliceByColumn:()=>Ds,stripTerminalSequences:()=>fQ,styleText:()=>E2t,styleTextWithAnsi:()=>W$,truncateToWidth:()=>sr,visibleWidth:()=>Xt,wrapTextWithAnsi:()=>AA});var Zn=I(()=>{a2e();d2t();k2t();J2t();Z2t();uDt();pDt();ADt();Yre();T2e();vDt();QDt();W2e();F2e();SDt();R2e();DDt();RDt();Bk();kx();U2e();nae();f2e();J2e();K2e();YDt();b2e();Bx();Kf();dRt();fRt();$c()});class b5{messageSeq=0;activeAssistantId;activeThoughtId;transcriptMessages=[];messageIndexById=new Map;visibleMessageStart=0;emptyChatHint;activityText;queuedSteeringMessages=[];queuedFollowUpMessages=[];constructor(e){this.emptyChatHint={...e}}get hasOlderMessages(){return this.visibleMessageStart>0}get activeAssistantMessageId(){return this.activeAssistantId}get activeThoughtMessageId(){return this.activeThoughtId}get messages(){return this.transcriptMessages.slice(this.visibleMessageStart)}get allMessages(){return this.transcriptMessages}getMessage(e){let t=this.messageIndexById.get(e);return t===void 0?void 0:this.transcriptMessages[t]}getMessageIndex(e){return this.messageIndexById.get(e)}isMessageVisible(e){let t=this.messageIndexById.get(e);return t!==void 0&&t>=this.visibleMessageStart}appendMessage(e,t,n={}){this.messageSeq+=1;let r=`m-${this.messageSeq}`;if(this.transcriptMessages.push({id:r,role:e,text:t,timestamp:new Date,...n}),this.messageIndexById.set(r,this.transcriptMessages.length-1),e==="assistant")this.activeAssistantId=r;if(e==="thought")this.activeThoughtId=r;return r}updateMessage(e,t){let n=this.getMessage(e);if(!n)return!1;return Object.assign(n,t),!0}appendThoughtDelta(e){let t=this.activeThoughtId?this.getMessage(this.activeThoughtId):void 0;if(!t)return this.appendMessage("thought",e);return t.text+=e,t.id}appendAssistantDelta(e){this.activeThoughtId=void 0;let t=this.activeAssistantId?this.getMessage(this.activeAssistantId):void 0;if(!t)return this.appendMessage("assistant",e);return t.text+=e,t.id}finishAssistant(){let e={assistantId:this.activeAssistantId,thoughtId:this.activeThoughtId};return this.activeAssistantId=void 0,this.activeThoughtId=void 0,e}setActivityText(e){this.activityText=e}setQueuedMessages(e,t){this.queuedSteeringMessages=[...e],this.queuedFollowUpMessages=[...t]}snapshot(){return{messageSeq:this.messageSeq,activeAssistantId:this.activeAssistantId,activeThoughtId:this.activeThoughtId,transcriptMessages:this.transcriptMessages.map(hRt),visibleMessageStart:this.visibleMessageStart,emptyChatHint:{...this.emptyChatHint},activityText:this.activityText,queuedSteeringMessages:[...this.queuedSteeringMessages],queuedFollowUpMessages:[...this.queuedFollowUpMessages]}}restore(e){this.messageSeq=e.messageSeq,this.activeAssistantId=e.activeAssistantId,this.activeThoughtId=e.activeThoughtId,this.transcriptMessages=e.transcriptMessages.map(hRt),this.rebuildMessageIndex(),this.visibleMessageStart=e.visibleMessageStart,this.emptyChatHint={...e.emptyChatHint},this.activityText=e.activityText,this.queuedSteeringMessages=[...e.queuedSteeringMessages],this.queuedFollowUpMessages=[...e.queuedFollowUpMessages]}reset(e){if(this.transcriptMessages=[],this.messageIndexById.clear(),this.visibleMessageStart=0,this.activeAssistantId=void 0,this.activeThoughtId=void 0,e)this.emptyChatHint={...e}}replaceMessages(e,t){let n=this.transcriptMessages.length,r=this.visibleMessageStart;if(this.activeAssistantId=void 0,this.activeThoughtId=void 0,t)this.emptyChatHint={...t};this.transcriptMessages=e.map((a)=>(this.messageSeq+=1,{...a,id:`m-${this.messageSeq}`})),this.rebuildMessageIndex(),this.visibleMessageStart=n===0?Math.max(0,this.transcriptMessages.length-30):Math.min(r,this.transcriptMessages.length)}showRecentMessages(){let e=Math.max(0,this.transcriptMessages.length-30);if(e<=this.visibleMessageStart)return!1;return this.visibleMessageStart=e,!0}loadOlderMessages(){if(!this.hasOlderMessages)return[];let e=this.visibleMessageStart;return this.visibleMessageStart=Math.max(0,e-30),this.transcriptMessages.slice(this.visibleMessageStart,e)}trimOldMessages(e,t){if(this.transcriptMessages[this.visibleMessageStart]?.id!==e)return[];let n=this.messageIndexById.get(t);if(n===void 0||n<this.visibleMessageStart||n>=this.transcriptMessages.length-100)return[];let r=this.transcriptMessages.slice(this.visibleMessageStart,n+1).map(({id:a})=>a);return this.visibleMessageStart=n+1,r}rebuildMessageIndex(){this.messageIndexById=new Map(this.transcriptMessages.map((e,t)=>[e.id,t]))}}function hRt(e){return{...e,attachments:e.attachments?.map((t)=>({...t,image:t.image?{...t.image}:void 0})),nestedCalls:e.nestedCalls?structuredClone(e.nestedCalls):void 0,timestamp:new Date(e.timestamp),titleParts:e.titleParts?.map((t)=>({...t}))}}function fF(e,t){if(e.path===t.currentSessionPath)return t.activityText?"running":void 0;return e.backgroundStatus}function qkr(){return[...JR.flatMap((t)=>{let n=jc(t.id);return n?[{keys:y4(n),description:t.description}]:[]}),{keys:"@",description:"Attach a file path."},{keys:"/",description:"Open slash commands and skills."}]}function sDe(){let e=qkr();return e[Math.floor(Math.random()*e.length)]}function Hkr(){return process.env.PI_UI_DEBUG==="1"}function Wkr(){return process.env.PI_UI_INSPECTOR==="1"}function zkr(e){let t=new Set(e);return t.delete(""),[...t]}class cDe{transcript=new b5(sDe());presentation;debugUi=Hkr();datastarInspector=Wkr();documentTitle="pi-ui";updateAvailable;promptEditorText="";promptSessionKey="";models=[];modelsRevision=0;sessionCatalogLoading=!0;sessionCatalog=[];sessionLimit=bRt;treeEntries=[];slashCommands=[];authDialog;extensionDialog;extensionStatuses=[];extensionWidgets=[];extensionWorkingIndicator;extensionWorkingMessage;extensionWorkingVisible=!0;llamaDialog;currentModel;currentSessionPath;previousSessionPath;isTemporarySession=!1;thinkingLevel="off";thinkingLevels=["off"];thinkingHidden=!1;theme="system";keybindHints=!0;minimalMode=!1;toolOutputHidden=!1;toolbarHidden=!1;sessionSidebarOpen=!0;sessionSidebarWidth=D0;sessionSidebarArchive=!0;sessionSidebarArchiveAfterDays=nZ;usage={text:"$0.000 \u2022 0 tokens",costText:"$0.000"};workspacePath=a9();projectRoot=this.workspacePath;workspaceFilesRevision=0;workspaceTreeRevision=0;workspaceReview=_Be;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.orderedSessions.slice(0,this.sessionLimit)}get orderedSessions(){let e=[],t=[],n=[];for(let r of this.sessionCatalog){let a=fF(r,this);if(a==="running")e.push(r);else if(a==="completed")t.push(r);else n.push(r)}return t.concat(e,n)}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(){return Object.freeze({messages:this.messages.map((e)=>({...e})),models:this.models.map((e)=>({...e})),modelsRevision:this.modelsRevision,sessions:this.sessions.map((e)=>({...e})),sessionsHasMore:this.sessionsHasMore,sessionCatalogLoading:this.sessionCatalogLoading,treeEntries:this.treeEntries.map((e)=>({...e})),slashCommands:this.slashCommands.map((e)=>({...e})),authDialog:this.authDialog?structuredClone(this.authDialog):void 0,extensionDialog:this.extensionDialog?structuredClone(this.extensionDialog):void 0,extensionStatuses:this.extensionStatuses.map((e)=>({...e})),extensionWidgets:this.extensionWidgets.map((e)=>({...e,lines:[...e.lines]})),extensionWorkingIndicator:this.extensionWorkingIndicator,extensionWorkingMessage:this.extensionWorkingMessage,extensionWorkingVisible:this.extensionWorkingVisible,llamaDialog:this.llamaDialog?structuredClone(this.llamaDialog):void 0,currentModel:this.currentModel,currentSessionPath:this.currentSessionPath,previousSessionPath:this.previousSessionPath,isTemporarySession:this.isTemporarySession,thinkingLevel:this.thinkingLevel,thinkingLevels:[...this.thinkingLevels],thinkingHidden:this.thinkingHidden,theme:this.theme,keybindHints:this.keybindHints,minimalMode:this.minimalMode,toolOutputHidden:this.toolOutputHidden,toolbarHidden:this.toolbarHidden,sessionSidebarArchive:this.sessionSidebarArchive,sessionSidebarArchiveAfterDays:this.sessionSidebarArchiveAfterDays,usage:{...this.usage},activityText:this.activityText,queuedSteeringMessages:this.queuedSteeringMessages,queuedFollowUpMessages:this.queuedFollowUpMessages,workspacePath:this.workspacePath,projectRoot:this.projectRoot,workspaceFilesRevision:this.workspaceFilesRevision,workspaceTreeRevision:this.workspaceTreeRevision,workspaceReview:this.workspaceReview,workspaceReviewPreferences:{...this.workspaceReviewPreferences},recentWorkspaces:[...this.recentWorkspaces],sessionTransition:{...this.sessionTransition},debugUi:this.debugUi,datastarInspector:this.datastarInspector,documentTitle:this.documentTitle,updateAvailable:this.updateAvailable,hasOlderMessages:this.hasOlderMessages,promptHistory:this.promptHistory,promptEditorText:this.promptEditorText,promptSessionKey:this.promptSessionKey,emptyChatHint:{...this.emptyChatHint}})}update(e,t={}){try{return e()}finally{if(t.commit!==!1)this.commit()}}commit(e){this.presentation?.requestCommit(e)}commitView(){this.presentation?.viewChanged()}appendMessage(e,t,n={}){let r=this.transcript.appendMessage(e,t,n);return this.presentation?.messageAppended(r),r}getMessage(e){return this.transcript.getMessage(e)}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=Jr.startSpan("transcriptInstall");this.presentation?.transcriptReplacing(),this.transcript.restore(e),t(),Jr.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:sDe()),this.presentation?.transcriptReplaced([],[]),e.broadcast!==!1)this.commit()}replaceMessages(e){let t=Jr.startSpan("transcriptInstall");this.presentation?.transcriptReplacing(),this.transcript.replaceMessages(e,e.length===0?sDe():void 0),t(),Jr.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(e,t){let n=this.transcript.trimOldMessages(e,t);if(n.length>0)this.presentation?.messagesRemoved(n)}setModels(e,t){this.models=e,this.currentModel=t,this.modelsRevision+=1,this.commitView()}setThinking(e,t){this.thinkingLevel=e,this.thinkingLevels=t.length>0?t:["off"],this.commitView()}setThinkingHidden(e){if(this.thinkingHidden===e)return;this.thinkingHidden=e,this.commit()}setSessionCatalogLoading(e){if(this.sessionCatalogLoading===e)return;this.sessionCatalogLoading=e,this.commitView()}setSessionCatalog(e){this.sessionCatalog=e,this.commitView()}loadMoreSessions(){this.sessionLimit=Math.min(this.sessionLimit+bRt,this.getSessionCatalog().length),this.commitView()}getSessionCatalog(){return this.sessionCatalog}promoteSession(e,t={}){let n=this.getSessionCatalog(),r=n.findIndex((a)=>a.path===e);if(r<0)return!1;if(r===0){if(t.regroup)this.commitView();return!1}return this.sessionCatalog=[n[r],...n.toSpliced(r,1)],this.commitView(),!0}updateSessionSummary(e,t){let n=this.getSessionCatalog(),r=n.findIndex((a)=>a.path===e);if(r<0)return!1;return this.sessionCatalog=n.with(r,t(n[r])),this.commitView(),!0}searchSessions(e){let t=e.trim().toLowerCase();if(!t)return[...this.sessions];let n=t.split(/\s+/);return this.orderedSessions.values().filter((r)=>{let a=`${r.title} ${dre(r.messageCount)} ${r.cwd} ${r.path}`.toLowerCase();return n.every((i)=>a.includes(i))}).take(this.sessionLimit).toArray()}removeSession(e){this.setSessionCatalog(this.getSessionCatalog().filter((t)=>t.path!==e))}setRecentWorkspaces(e){this.recentWorkspaces=zkr([...e.filter((t)=>!LT(t)),...this.recentWorkspaces]),this.commitView()}setSlashCommands(e){this.slashCommands=e,this.commitView()}setAuthDialog(e){this.authDialog=e,this.commitView()}setExtensionDialog(e){this.extensionDialog=e,this.commitView()}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.commit()}setPromptSessionKey(e){if(e===this.promptSessionKey)return;this.promptSessionKey=e,this.setPromptEditorText("",{broadcast:!1})}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.commitView()}setTreeEntries(e){this.treeEntries=e,this.commitView()}openTreeDialog(){this.commitView(),this.commit({type:"open-tree-dialog"})}setUsage(e){this.usage=e,this.commit()}setActivityText(e){if(this.activityText===e)return;this.transcript.setActivityText(e),this.commit()}setQueuedMessages(e,t){this.transcript.setQueuedMessages(e,t),this.commit()}setCurrentSessionPath(e){if(e&&e!==this.currentSessionPath&&this.currentSessionPath)this.previousSessionPath=this.currentSessionPath;this.currentSessionPath=e,this.commitView()}setPreviousSessionPath(e){if(this.previousSessionPath===e)return;this.previousSessionPath=e,this.commit()}setTemporarySession(e){this.isTemporarySession=e,this.commit()}setUpdateAvailable(e){this.updateAvailable=e,this.commit()}setWorkspacePath(e){if(this.workspacePath===e)return;this.workspacePath=e,this.workspaceFilesRevision=0,this.workspaceTreeRevision=0,this.workspaceReview=_Be,this.commitView(),this.workspacePathListener?.(e)}setProjectRoot(e){if(this.projectRoot===e)return;this.projectRoot=e,this.commitView()}workspaceFilesChanged(e=!0){if(this.workspaceFilesRevision+=1,e)this.workspaceTreeRevision+=1;this.commitView()}setWorkspaceReview(e){if(this.workspaceReview.revision===e.revision)return;this.workspaceReview=e,this.commitView()}setWorkspaceReviewPreferences(e){this.workspaceReviewPreferences=e,this.commitView()}setSessionTransition(e){let t=this.sessionTransition.status==="loading"&&e.status==="idle";this.sessionTransition=e,this.presentation?.sessionTransitionChanged(t)}}var bRt=30;var lae=I(()=>{VY();Ib();bC();KR();w4();Tf();BC()});function lDe(e){return an(Ik.jsxDEV("ul",{id:e.id,"aria-label":e.label,role:e.role??"listbox",class:e.class??"picker-list",children:e.children},void 0,!1,void 0,this))}function yRt(e){return an(Ik.jsxDEV("li",{id:`file-option-${encodeURIComponent(e.value)}`,role:"option","data-picker-kind":e.kind,"data-picker-value":e.value,class:"picker-row","aria-selected":e.selected?"true":"false","data-file-row":!0,children:Ik.jsxDEV("div",{class:"picker-row-button",children:[Ik.jsxDEV("span",{class:"picker-row-content",children:[Ik.jsxDEV("span",{class:"picker-row-title",safe:!0,children:e.label},void 0,!1,void 0,this),Ik.jsxDEV("span",{class:"picker-row-description",safe:!0,children:e.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ik.jsxDEV(uDe,{text:e.metadata},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this))}function uDe(e){return an(Ik.jsxDEV("span",{class:"badge","data-variant":"secondary",safe:!0,children:e.text},void 0,!1,void 0,this))}var Ik;var wRt=I(()=>{Ik=mn(ur(),1)});function Jkr(e){return`
|
|
732
732
|
const title = evt.currentTarget;
|
|
733
733
|
$sessionRenamePath = ${JSON.stringify(e.path)};
|
|
734
734
|
$sessionRenameTitle = ${JSON.stringify(e.title)};
|
|
@@ -959,7 +959,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
959
959
|
payload: { model: row.dataset.modelValue },
|
|
960
960
|
});
|
|
961
961
|
requestAnimationFrame(() => document.getElementById('prompt-input')?.focus());
|
|
962
|
-
`,children:Rr.jsxDEV("div",{role:"group","aria-labelledby":"model-select-heading",children:[Rr.jsxDEV("div",{id:"model-select-heading",class:"picker-heading",children:[Rr.jsxDEV("span",{children:"Models"},void 0,!1,void 0,this),Rr.jsxDEV(wl,{shortcut:jc("switch-model")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("svg",{width:"0",height:"0",style:"position:absolute","aria-hidden":"true",children:Rr.jsxDEV("defs",{children:Rr.jsxDEV("symbol",{id:"model-scope-star",viewBox:"0 0 24 24",children:$Y.star.replace('fill="none"','fill="inherit"')},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),Rr.jsxDEV("div",{id:"model-select-options","data-ignore-morph":!0},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Rr.jsxDEV("p",{class:"command-empty",role:"status",children:"No models found."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this))}function NRt(e,t){return an(Rr.jsxDEV(Rr.Fragment,{children:e.map((n,r)=>{let a=`${n.provider}/${n.id}`,i=n.configured?"":" \u2022 no auth";return Rr.jsxDEV("div",{id:`model-row-${encodeURIComponent(a)}`,class:"model-option","data-model-value":a,"data-command-row":!0,children:[Rr.jsxDEV("button",{type:"button",id:`model-option-${encodeURIComponent(a)}`,role:"option",tabindex:"-1",class:["model-choice",r===0&&"active"],commandfor:"model-select-popover",command:"hide-popover","data-preserve-attr":"class","aria-selected":a===t?"true":"false",children:[Rr.jsxDEV("span",{class:"picker-option-text",children:[Rr.jsxDEV("span",{class:"picker-option-title",safe:!0,children:n.id},void 0,!1,void 0,this),Rr.jsxDEV("span",{class:"picker-option-description",safe:!0,children:[n.provider,i]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("span",{class:"selection-dot model-current-indicator",hidden:a!==t,"aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("button",{type:"button",class:"btn model-scope-button","data-variant":n.scoped?"secondary":"ghost","data-size":"icon-sm","aria-pressed":n.scoped?"true":"false","aria-label":`Toggle scoped model ${a}`,children:Rr.jsxDEV("svg",{class:"icon",fill:"none","aria-hidden":"true",children:Rr.jsxDEV("use",{href:"#model-scope-star"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})},void 0,!1,void 0,this))}function gBr(e){return e.id.slice(e.id.lastIndexOf("/")+1)}var Rr;var w5=I(()=>{qR();Ib();yi();Zu();Lke();xf();Tf();Rr=mn(ur(),1)});function $Rt(e){return an(dd.jsxDEV("button",{id:"update-badge",type:"button",class:"btn prompt-context-button update-badge","data-variant":"ghost","data-size":"sm",popovertarget:"update-popover","aria-haspopup":"dialog","aria-label":`Update pi-ui to ${e.latestVersion}`,"data-tooltip":"Update available","data-tooltip-delay":!0,children:[dd.jsxDEV(Dr,{name:"arrow-up"},void 0,!1,void 0,this),dd.jsxDEV("span",{class:"prompt-context-label",children:"Update"},void 0,!1,void 0,this),dd.jsxDEV(Ep,{label:"Update available"},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}function ORt(e){return an(dd.jsxDEV("div",{id:"update-popover",popover:"auto","data-popover":!0,"data-side":"top","data-align":"start",class:"update-popover",role:"dialog","aria-label":"Update available",children:[dd.jsxDEV("div",{class:"update-popover-heading",children:[dd.jsxDEV("strong",{class:"update-popover-title",children:"Update available"},void 0,!1,void 0,this),dd.jsxDEV("span",{class:"update-popover-versions",children:[dd.jsxDEV("span",{children:e.currentVersion},void 0,!1,void 0,this),dd.jsxDEV("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this),dd.jsxDEV("strong",{children:e.latestVersion},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),dd.jsxDEV("div",{class:"update-command","data-code-block":!0,"data-code-source":e.upgradeCommand,children:[dd.jsxDEV("code",{children:e.upgradeCommand},void 0,!1,void 0,this),dd.jsxDEV("button",{class:"btn code-copy-button","data-variant":"ghost","data-size":"icon-xs",type:"button","data-copy-code":!0,autofocus:!0,"aria-label":"Copy upgrade command",children:[dd.jsxDEV(Dr,{name:"copy"},void 0,!1,void 0,this),dd.jsxDEV(Dr,{name:"check"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),dd.jsxDEV("a",{class:"update-release-link",href:e.releaseUrl,target:"_blank",rel:"noreferrer noopener",children:"Release notes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}var dd;var GRt=I(()=>{Zu();xf();dd=mn(ur(),1)});function xae(e){let t=e.updateAvailable;return an(BDe.jsxDEV("div",{id:"prompt-start",class:"prompt-start",children:[LRt(e),PRt(e),t&&BDe.jsxDEV("span",{class:"update-anchor",children:[$Rt(t),ORt(t)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this))}var BDe;var CDe=I(()=>{w5();GRt();BDe=mn(ur(),1)});function URt(e){return an(Po.jsxDEV("div",{id:"prompt-box",class:"prompt-box","data-signals__ifmissing":JSON.stringify({prompt:e.promptEditorText,_filePickerOpen:!1,_fileSearchController:"",_slashPickerOpen:!1,_promptSubmitting:!1,fileQuery:"",slashSearch:""}),"data-on:pointerdown__outside":"window.piUi.pickers.close()","data-effect":"$_filePickerOpen; $_slashPickerOpen; $slashSearch = $prompt.startsWith('/') && !$prompt.includes(' ') ? $prompt.slice(1) : ''; window.piUi.pickers.sync(true);","data-on:pi-ui-prompt-submit-finished":"$_promptSubmitting = false",children:[Po.jsxDEV("div",{class:"prompt-popovers",children:[fBr(),yae(e),Po.jsxDEV("div",{id:"prompt-file-popover",class:"prompt-picker-popover",style:"display: none;","data-show":"$_filePickerOpen",children:Po.jsxDEV("div",{id:"file-picker-results","aria-live":"polite"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),xDe(e),Po.jsxDEV("div",{id:"prompt-attachments",class:"prompt-attachments","data-style:filter":"$_promptSubmitting ? 'brightness(0.75)' : ''","aria-label":"Attachments","data-attr:inert":"$_promptSubmitting","data-attr:aria-busy":"$_promptSubmitting ? 'true' : 'false'","data-ignore-morph":!0,hidden:!0},void 0,!1,void 0,this),Po.jsxDEV("div",{class:"input-group raised-surface prompt-surface","data-orientation":"vertical","data-prompt-initial":!0,"data-init":"el.removeAttribute('data-prompt-initial')",children:[bF(e,"aboveEditor"),Po.jsxDEV("div",{class:"prompt-editor-row",children:[Po.jsxDEV("textarea",{id:"prompt-input",class:"prompt-input",placeholder:e.isTemporarySession?"Temporary chat":"Ask pi anything...","data-attr:placeholder":"$_temporarySession ? 'Temporary chat' : 'Ask pi anything...'","aria-label":"Message","aria-autocomplete":"list","aria-haspopup":"listbox","data-preserve-attr":"aria-controls aria-activedescendant","aria-keyshortcuts":yp("focus-prompt"),rows:"1","data-bind:prompt":!0,attrs:{"data-on:input__debounce.150ms":`@post('${Dt.extensionUiEditor}', { payload: { prompt: $prompt } })`,"data-on:pi-ui-file-query__debounce.20ms":`
|
|
962
|
+
`,children:Rr.jsxDEV("div",{role:"group","aria-labelledby":"model-select-heading",children:[Rr.jsxDEV("div",{id:"model-select-heading",class:"picker-heading",children:[Rr.jsxDEV("span",{children:"Models"},void 0,!1,void 0,this),Rr.jsxDEV(wl,{shortcut:jc("switch-model")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("svg",{width:"0",height:"0",style:"position:absolute","aria-hidden":"true",children:Rr.jsxDEV("defs",{children:Rr.jsxDEV("symbol",{id:"model-scope-star",viewBox:"0 0 24 24",children:$Y.star.replace('fill="none"','fill="inherit"')},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),Rr.jsxDEV("div",{id:"model-select-options","data-ignore-morph":!0},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Rr.jsxDEV("p",{class:"command-empty",role:"status",children:"No models found."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this))}function NRt(e,t){return an(Rr.jsxDEV(Rr.Fragment,{children:e.map((n,r)=>{let a=`${n.provider}/${n.id}`,i=n.configured?"":" \u2022 no auth";return Rr.jsxDEV("div",{id:`model-row-${encodeURIComponent(a)}`,class:"model-option","data-model-value":a,"data-command-row":!0,children:[Rr.jsxDEV("button",{type:"button",id:`model-option-${encodeURIComponent(a)}`,role:"option",tabindex:"-1",class:["model-choice",r===0&&"active"],commandfor:"model-select-popover",command:"hide-popover","data-preserve-attr":"class","aria-selected":a===t?"true":"false",children:[Rr.jsxDEV("span",{class:"picker-option-text",children:[Rr.jsxDEV("span",{class:"picker-option-title",safe:!0,children:n.id},void 0,!1,void 0,this),Rr.jsxDEV("span",{class:"picker-option-description",safe:!0,children:[n.provider,i]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("span",{class:"selection-dot model-current-indicator",hidden:a!==t,"aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Rr.jsxDEV("button",{type:"button",class:"btn model-scope-button","data-variant":n.scoped?"secondary":"ghost","data-size":"icon-sm","aria-pressed":n.scoped?"true":"false","aria-label":`Toggle scoped model ${a}`,children:Rr.jsxDEV("svg",{class:"icon",fill:"none","aria-hidden":"true",children:Rr.jsxDEV("use",{href:"#model-scope-star"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})},void 0,!1,void 0,this))}function gBr(e){return e.id.slice(e.id.lastIndexOf("/")+1)}var Rr;var w5=I(()=>{qR();Ib();yi();Zu();Lke();xf();Tf();Rr=mn(ur(),1)});function $Rt(e){return an(dd.jsxDEV("button",{id:"update-badge",type:"button",class:"btn prompt-context-button update-badge","data-variant":"ghost","data-size":"sm",popovertarget:"update-popover","aria-haspopup":"dialog","aria-label":`Update pi-ui to ${e.latestVersion}`,"data-tooltip":"Update available","data-tooltip-delay":!0,children:[dd.jsxDEV(Dr,{name:"arrow-up"},void 0,!1,void 0,this),dd.jsxDEV("span",{class:"prompt-context-label",children:"Update"},void 0,!1,void 0,this),dd.jsxDEV(Ep,{label:"Update available"},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}function ORt(e){return an(dd.jsxDEV("div",{id:"update-popover",popover:"auto","data-popover":!0,"data-side":"top","data-align":"start",class:"update-popover",role:"dialog","aria-label":"Update available",children:[dd.jsxDEV("div",{class:"update-popover-heading",children:[dd.jsxDEV("strong",{class:"update-popover-title",children:"Update available"},void 0,!1,void 0,this),dd.jsxDEV("span",{class:"update-popover-versions",children:[dd.jsxDEV("span",{children:e.currentVersion},void 0,!1,void 0,this),dd.jsxDEV("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this),dd.jsxDEV("strong",{children:e.latestVersion},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),dd.jsxDEV("div",{class:"update-command","data-code-block":!0,"data-code-source":e.upgradeCommand,children:[dd.jsxDEV("code",{children:e.upgradeCommand},void 0,!1,void 0,this),dd.jsxDEV("button",{class:"btn code-copy-button","data-variant":"ghost","data-size":"icon-xs",type:"button","data-copy-code":!0,autofocus:!0,"aria-label":"Copy upgrade command",children:[dd.jsxDEV(Dr,{name:"copy"},void 0,!1,void 0,this),dd.jsxDEV(Dr,{name:"check"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),dd.jsxDEV("a",{class:"update-release-link",href:e.releaseUrl,target:"_blank",rel:"noreferrer noopener",children:"Release notes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this))}var dd;var GRt=I(()=>{Zu();xf();dd=mn(ur(),1)});function xae(e){let t=e.updateAvailable;return an(BDe.jsxDEV("div",{id:"prompt-start",class:"prompt-start",children:[LRt(e),PRt(e),t&&BDe.jsxDEV("span",{class:"update-anchor",children:[$Rt(t),ORt(t)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this))}var BDe;var CDe=I(()=>{w5();GRt();BDe=mn(ur(),1)});function URt(e){return an(Po.jsxDEV("div",{id:"prompt-box",class:"prompt-box","data-signals__ifmissing":JSON.stringify({prompt:e.promptEditorText,_filePickerOpen:!1,_fileSearchController:"",_slashPickerOpen:!1,_promptSubmitting:!1,fileQuery:"",slashSearch:""}),"data-on:pointerdown__outside":"window.piUi.pickers.close()","data-effect":"const draft = window.piUi.promptDrafts.sync($_promptSessionKey, $prompt); if (draft !== null) window.piUi.prompt.setValue(draft); $_filePickerOpen; $_slashPickerOpen; $slashSearch = $prompt.startsWith('/') && !$prompt.includes(' ') ? $prompt.slice(1) : ''; window.piUi.pickers.sync(true);","data-on:pi-ui-prompt-submit-finished":"$_promptSubmitting = false",children:[Po.jsxDEV("div",{class:"prompt-popovers",children:[fBr(),yae(e),Po.jsxDEV("div",{id:"prompt-file-popover",class:"prompt-picker-popover",style:"display: none;","data-show":"$_filePickerOpen",children:Po.jsxDEV("div",{id:"file-picker-results","aria-live":"polite"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),xDe(e),Po.jsxDEV("div",{id:"prompt-attachments",class:"prompt-attachments","data-style:filter":"$_promptSubmitting ? 'brightness(0.75)' : ''","aria-label":"Attachments","data-attr:inert":"$_promptSubmitting","data-attr:aria-busy":"$_promptSubmitting ? 'true' : 'false'","data-ignore-morph":!0,hidden:!0},void 0,!1,void 0,this),Po.jsxDEV("div",{class:"input-group raised-surface prompt-surface","data-orientation":"vertical","data-prompt-initial":!0,"data-init":"el.removeAttribute('data-prompt-initial')",children:[bF(e,"aboveEditor"),Po.jsxDEV("div",{class:"prompt-editor-row",children:[Po.jsxDEV("textarea",{id:"prompt-input",class:"prompt-input",placeholder:e.isTemporarySession?"Temporary chat":"Ask pi anything...","data-attr:placeholder":"$_temporarySession ? 'Temporary chat' : 'Ask pi anything...'","aria-label":"Message","aria-autocomplete":"list","aria-haspopup":"listbox","data-preserve-attr":"aria-controls aria-activedescendant","aria-keyshortcuts":yp("focus-prompt"),rows:"1","data-bind:prompt":!0,attrs:{"data-on:input__debounce.150ms":`@post('${Dt.extensionUiEditor}', { payload: { prompt: $prompt } })`,"data-on:pi-ui-file-query__debounce.20ms":`
|
|
963
963
|
if (typeof evt.detail?.query === 'string') {
|
|
964
964
|
$_fileSearchController?.abort?.();
|
|
965
965
|
$_fileSearchController = new AbortController();
|
|
@@ -3749,7 +3749,7 @@ ${s}`;return o},gJ(r)}function lNn(e,t,n){let r=e.get(t);if(r)r.push(n);else e.s
|
|
|
3749
3749
|
`:""}${i.thinking}`;else if($r(i)&&i.type==="text"&&zn(i.text))r+=i.text;if(a.trim())n.push({role:"thought",text:a,timestamp:t});if(r.trim())n.push({role:"assistant",text:dm(r),timestamp:t});return n}var LNn=I(()=>{ZD();LXe();mee();c9()});class VXe{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(R8a(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 R8a(e,t,n){let r=[],a=M8a(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=PNn(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:A,isLast:m,gutters:h}=u.pop();if(F8a(l,t))r.push({id:l.entry.id,parentId:l.entry.parentId,prefix:T8a(d,A,m,h),label:l.label,active:l.entry.id===t,inPath:n.has(l.entry.id),...j8a(l,a)});let f=PNn(l.children,i),g=f.length>1,b=g?d+1:p&&d>0?d+1:d,y=[...h];if(A&&d>0)y[d-1]=!m;for(let w=f.length-1;w>=0;w-=1)u.push({node:f[w],indent:b,justBranched:g,showConnector:g,isLast:w===f.length-1,gutters:y})}return r}function PNn(e,t){return e.toSorted((n,r)=>Number(t.get(r))-Number(t.get(n)))}function T8a(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 M8a(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(!$r(i)||i.type!=="toolCall")continue;if(!zn(i.id)||!zn(i.name))continue;t.set(i.id,{name:i.name,arguments:$r(i.arguments)?i.arguments:{}})}}return t}function F8a(e,t){let n=e.entry;if(n.type==="label"||n.type==="custom"||n.type==="context_edit"||n.type==="model_change"||n.type==="thinking_level_change"||n.type==="session_info"||n.type==="usage")return!1;if(n.type==="message"&&n.message.role==="assistant"&&n.id!==t&&!i4(NEe(n.message.content))&&(n.message.stopReason==="stop"||n.message.stopReason==="toolUse"||!n.message.stopReason))return!1;return!0}function j8a(e,t){let n=e.entry,r=new Date(n.timestamp),a={meta:S1(r),metaTimestamp:r.toISOString()};if(n.type==="message"){let i=n.message;if(i.role==="user")return{kind:"user",role:"user",text:i4(NEe(i.content)),...a};if(i.role==="assistant"){let o=i4(NEe(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?L8a(o.name,o.arguments):"",...a}}if(i.role==="bashExecution")return{kind:"tool",role:"bash",text:i4(i.command),...a};return{kind:"other",role:i.role,text:"",...a}}if(n.type==="custom_message")return{kind:"other",role:n.customType,text:i4(NEe(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:i4(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};if(n.type==="usage")return{kind:"other",role:"usage",text:n.note??n.kind,...a};if(n.type==="context_edit")return{kind:"other",role:"context",text:`${n.replacement===null?"omit":"replace"} ${n.targetId}`,...a};return{kind:"other",role:"title",text:n.name??"(empty)",...a}}function L8a(e,t){let n=String(t.path||t.file_path||"");switch(e){case"read":{let r=Gl(t.offset)?t.offset:void 0,a=Gl(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 NEe(e){if(zn(e))return e;if(!Array.isArray(e))return"";return e.filter((t)=>$r(t)&&t.type==="text"&&zn(t.text)).map((t)=>t.text).join(" ")}function i4(e){return e.replace(/[\n\t]+/g," ").replace(/\s+/g," ").trim().slice(0,240)}var NNn=I(()=>{d9()});function $Ee(e,t,n){return r4(e.modelRuntime,()=>N8a(e,t,n))}async function N8a(e,t,n){let r=e.model;if(!r)return;let a=n?await e.modelRuntime.getAuth(n):await e.modelRuntime.getAuth(r);if(!a)return;let i=new Headers;for(let[s,c]of Object.entries(a.auth.headers??{}))if(c!==null)i.set(s,c);if(!i.has("authorization")){if(!a.auth.apiKey)return;i.set("Authorization",`Bearer ${a.auth.apiKey}`)}if(!i.has("user-agent"))i.set("User-Agent","pi-ui");let o=await fetch(t,{headers:i,signal:AbortSignal.timeout(P8a)});if(!o.ok)throw Error(`Usage request failed (HTTP ${o.status})${o.status===401?`; sign in to ${n??r.provider} again`:""}`);return await o.json()}var P8a=15000,XXe=60000;var OEe=I(()=>{SEe()});function GEe(e){return Math.round(100-wC(e,0,100))}function UEe(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`${$Nn(n)}h`;return`${$Nn(n/24)}d`}function $Nn(e){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}var eet=()=>{};function net(e){return e?.provider===UNn||e?.provider==="openai"}async function qNn(e){let t=await $Ee(e,$8a,UNn);return t===void 0?void 0:O8a(t)}function HNn(e){let t=[];if(e.primary)t.push(ONn(e.primary,"5 hours"));if(e.secondary)t.push(ONn(e.secondary,"Weekly"));return t}function ONn(e,t){return{label:G8a(e.windowSeconds)??t,usedPercent:e.usedPercent,remainingPercent:GEe(e.usedPercent),resetText:UEe(e.resetsAt===void 0?void 0:e.resetsAt*1000)}}function O8a(e){if(!$R(e))return;let t=e.rate_limit;if(!$R(t))return;let n=GNn(t.primary_window),r=GNn(t.secondary_window);return n||r?{primary:n,secondary:r}:void 0}function GNn(e){if(!$R(e))return;let t=tet(e.used_percent);if(t===void 0)return;return{usedPercent:t,windowSeconds:tet(e.limit_window_seconds),resetsAt:tet(e.reset_at)}}function tet(e){if(!Gl(e)&&(!zn(e)||e.trim()===""))return;let t=Number(e);return Number.isFinite(t)?t:void 0}function G8a(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 UNn="openai-codex",$8a="https://chatgpt.com/backend-api/wham/usage";var WNn=I(()=>{OEe();eet()});function oet(e){return e?.provider===U8a}async function JNn(e){let t=await $Ee(e,q8a);return t===void 0?void 0:z8a(t)}function z8a(e){if(!W8a.check(e))return;let t={rolling:aet(e.usage.rolling),weekly:aet(e.usage.weekly),monthly:aet(e.usage.monthly)};return t.rolling||t.weekly||t.monthly?t:void 0}function KNn(e){let t=[];if(e.rolling)t.push(iet(e.rolling,"5 hours"));if(e.weekly)t.push(iet(e.weekly,"Weekly"));if(e.monthly)t.push(iet(e.monthly,"Monthly"));return t}function aet(e){if(!e)return;let t=Number(e.percent);if(!Number.isFinite(t))return;return{usedPercent:t,resetsAt:J8a(e.resetsAt)}}function iet(e,t){return{label:t,usedPercent:e.usedPercent,remainingPercent:GEe(e.usedPercent),resetText:UEe(e.resetsAt)}}function J8a(e){if(e===void 0)return;if(zn(e)){let t=Date.parse(e);return Number.isFinite(t)?t:void 0}return e<10000000000?e*1000:e}var U8a="opencode-go",q8a="https://opencode.ai/zen/go/v1/usage",zNn,ret,H8a,W8a;var YNn=I(()=>{NE();OEe();eet();zNn=Lc([fi(),ei({pattern:"\\S"})]),ret=wp({percent:zNn,resetsAt:In(zNn)},{open:!0}),H8a=wp({usage:wp({rolling:In(ret),weekly:In(ret),monthly:In(ret)},{open:!0})},{open:!0}),W8a=fg(H8a)});class set{active;begin(e,t,n){let r={runtime:e,session:t,provider:n?.provider,modelId:n?.id};return this.active=r,r}invalidate(){this.active=void 0}owns(e,t,n,r){return this.active===e&&e.runtime===t&&e.session===n&&e.provider===r?.provider&&e.modelId===r?.id}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 cet{getRuntime;state;fetchCodex;fetchOpenCodeGo;codexStatus="";codexUsage;codexFetchedAt=0;opencodeGoStatus="";opencodeGoUsage;opencodeGoFetchedAt=0;requests=new set;timer;constructor(e,t,n=qNn,r=JNn){this.getRuntime=e;this.state=t;this.fetchCodex=n;this.fetchOpenCodeGo=r}sync(){let e=this.getRuntime().session,t=net(e.model),n=oet(e.model),r=e.getSessionStats();this.state.setUsage(K8a(r,{cacheHitPercent:Y8a(r),limits:t?ZNn("Codex limits",this.codexStatus,this.codexUsage?HNn(this.codexUsage):void 0):n?ZNn("OpenCode Go usage",this.opencodeGoStatus,this.opencodeGoUsage?KNn(this.opencodeGoUsage):void 0):void 0}))}suspend(){this.invalidate()}refresh(e=!1){let t=this.getRuntime(),n=t.session,r=Z8a(n.model);if(!r){this.suspend(),this.sync();return}if(this.requests.loading||!e&&Date.now()-this.fetchedAt(r)<XXe)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;if(i instanceof DOMException&&(i.name==="AbortError"||i.name==="TimeoutError"))console.warn(`${r} usage request timed out`);else 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.codexUsage,this.codexFetchedAt=Date.now();return}this.opencodeGoStatus=t,this.opencodeGoUsage=e.usage??this.opencodeGoUsage,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)},XXe),this.timer.unref?.()}}function K8a(e,t={}){let n=V8a(e.cost);if(e.contextUsage)return{text:`${n} \u2022 ${X8a(e.contextUsage.percent)}/${fx(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 ${fx(e.tokens.total)} tokens`,costText:n,cacheHitPercent:t.cacheHitPercent,limits:t.limits}}function Y8a(e){let{input:t,cacheRead:n,cacheWrite:r}=e.tokens,a=t+n+r;return a>0?n/a*100:void 0}function ZNn(e,t,n){if(!t&&!n?.length)return;return{label:e,status:t&&n?.length?"stale (refresh unavailable)":t||void 0,windows:n??[]}}function Z8a(e){if(net(e))return"codex";if(oet(e))return"opencode-go";return}function V8a(e){if(e<1)return`$${e.toFixed(3)}`;if(e<100)return`$${e.toFixed(1)}`;return`$${Math.round(e)}`}function X8a(e){return e===null?"?":`${e.toFixed(1)}%`}var VNn=I(()=>{WNn();YNn();OEe()});async function XNn(e){let t=e3a(e);try{let n=await I0(t.command,{args:t.args});if(!n.success){let r=new TextDecoder().decode(n.stderr).trim();throw Error(r||`Trash command failed with code ${n.code}`)}}catch(n){if(hc(n)){await Bun.file(e).delete();return}throw n}}function e3a(e){if(Md==="darwin")return{command:"osascript",args:["-e",`tell application "Finder" to delete POSIX file ${JSON.stringify(e)}`]};if(Md==="windows")return{command:"powershell",args:["-NoProfile","-Command",`Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile(${JSON.stringify(e)}, 'OnlyErrorDialogs', 'SendToRecycleBin')`]};return{command:"trash",args:[e]}}var e4n=I(()=>{Uv()});import{realpath as t3a}from"fs/promises";import{sep as n3a}from"path";class o4{runtime;state;runtimeFactory;preparedSessions;activationOptions;unsubscribe;tools=vNn();prompts;auth;transitionController;backgroundSessions=new jXe;completedBackgroundPaths=new Set;catalog;llama;models;usage;extensionUi;transcript=new ZXe;projectedSessionId;tree;foregroundGeneration;foregroundObservedRunning;sharing=!1;resetChatOnInvalidation=!1;disposal;initialCatalogLoad;lastForcedModelRefreshAt;dependencies;sessionDir;autoTitlesInFlight=new Set;constructor(e,t,n,r,a,i){this.runtime=e;this.state=t;this.runtimeFactory=n;this.preparedSessions=r;this.activationOptions=i;this.dependencies=i.dependencies??t4n,this.sessionDir=a,this.extensionUi=new PXe(t),this.foregroundGeneration=this.backgroundSessions.allocateGeneration(),this.foregroundObservedRunning=e.session.isStreaming,this.models=new $Xe(()=>this.runtime,t,()=>this.afterModelChange()),this.llama=new NXe(()=>this.runtime,t,()=>this.models.sync()),this.usage=new cet(()=>this.runtime,t),this.tree=new VXe(()=>this.runtime,t,()=>this.loadCurrentSessionMessages(),()=>this.foregroundGeneration),this.catalog=new hY(t,{sessionDir:REe(this.dependencies.getAgentDir()),backgroundStatuses:()=>this.backgroundStatuses(),watch:this.dependencies.watchSessionCatalog}),this.prompts=new OXe((o)=>{if(o===this.runtime)return this.state;for(let s of this.backgroundSessions.values())if(s.runtime===o)return s.state}),this.auth=new FXe(()=>this.runtime,t,()=>this.models.sync()),this.transitionController=i.transitionController??new g4((o)=>t.setSessionTransition(o))}static async create(e,t=a9(),n={}){let r=await o4.prepare(e,t,n);return r.activate(),r}static async prepare(e,t=a9(),n={}){let r=n.dependencies??t4n,a=r.prepareSessions(),i=async({cwd:c,sessionManager:u,sessionStartEvent:l})=>{let d=await Jr.measure("runtimeServicesCreate",()=>dR({cwd:c,resourceLoaderOptions:{extensionFactories:r3a}}));d.settingsManager.getImageAutoResize=()=>!1,q3n(d.modelRuntime,d.settingsManager.getGlobalSettings().httpProxy);let{scopedModels:p}=await Jr.measure("scopedModelResolution",()=>r4(d.modelRuntime,()=>OJ(d.settingsManager.getEnabledModels()??[],d.modelRuntime))),A=d.resourceLoader.getExtensions().extensions.some((h)=>h.tools.has("read"));return{...await Jr.measure("runtimeSessionCreate",()=>pR({services:d,sessionManager:u,sessionStartEvent:l,scopedModels:p,customTools:A?void 0:[dNn(c)]})),services:d,diagnostics:d.diagnostics}},o=GXe(),s=await r.createRuntime(i,{cwd:t,agentDir:r.getAgentDir(),sessionManager:r.createSessionManager(t,o)});try{let c=new o4(s,e,i,a,o,n);return c.bindRuntimeCallbacks(s),await c.bindSessionExtensions(),c}catch(c){throw await s.dispose(),c}}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();let e=this.prompts.restore(this.runtime),t=this.state.promptEditorText;this.foregroundObservedRunning=!1,this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),this.usage.sync();let n=this.runtime.session.sessionManager.getSessionFile();if(n)await this.catalog.refreshPath(n);if(e)this.state.setPromptEditorText([e,t].filter((r)=>r.trim()).join(`
|
|
3750
3750
|
|
|
3751
3751
|
`))}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),this.releaseBackgroundSession(t),!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.replaceRuntime(r,this.dependencies.createSessionManager(r,this.sessionDir),{type:"session_start",reason:"new"})}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();return await this.replaceRuntime(t,this.dependencies.createMemorySessionManager(t),{type:"session_start",reason:"new",previousSessionFile:e}),await this.bindSession(),!0}async replaceRuntime(e,t,n){await this.leaveCurrentRuntimeForReplacement(),this.state.resetChat();let r=await this.dependencies.createRuntime(this.runtimeFactory,{cwd:e,agentDir:this.dependencies.getAgentDir(),sessionManager:t,sessionStartEvent:n});this.adoptRuntime(r)}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,this.sessionDir),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: ${fu(r)}`),!1}}async deleteSession(e){let t=this.dependencies.openSessionManager(e,this.sessionDir).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}if(await this.dependencies.moveToTrash(t),this.state.previousSessionPath===t)this.state.setPreviousSessionPath(void 0);let r=this.backgroundSessions.get(t);if(r)this.unsubscribeBackgroundSession(r),await r.runtime.dispose(),this.backgroundSessions.delete(t),this.completedBackgroundPaths.delete(t);return this.state.removeSession(t),await this.refreshSessions(),!0}catch(r){return this.state.appendMessage("system",`Failed to delete session: ${fu(r)}`),!1}}getWorkspacePath(){return this.runtime.session.sessionManager.getCwd()}async hasRunningSessionInWorktree(e){let t=[];if(this.isCurrentRuntimeActive())t.push(this.getWorkspacePath());for(let n of this.backgroundSessions.values())if(n.status==="running")t.push(n.runtime.session.sessionManager.getCwd());for(let n of t){let r=await t3a(n).catch(()=>n);if(r===e||r.startsWith(`${e}${n3a}`))return!0}return!1}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,this.sessionDir)});try{await t.session.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(()=>t===this.runtime),onError:(r)=>{if(t===this.runtime)this.state.appendMessage("notice",`Extension ${r.extensionPath}: ${r.error}`)}})}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 ${Rf(e)}`,async()=>{let n=this.dependencies.forkSessionManager(t,e,this.sessionDir).getSessionFile();return n?await this.resumeSessionTransition(n):!1},{overlay:!1})}async resumeSession(e){if(e===this.runtime.session.sessionManager.getSessionFile())return{status:"success"};let t,n=await this.transitionController.run(e,(r)=>(t=Jr.startSessionTransition(r),Jr.runInTransition(t,()=>this.resumeSessionTransition(e,t))),{overlay:!1});if(t!==void 0)if(n.status==="success")Jr.markSessionTransitionComplete(t);else Jr.cancelSessionTransition(t);return n}async resumeSessionTransition(e,t){if(!e.trim())return!1;let n=this.runtime.session.sessionManager.isPersisted();Jr.recordOwnershipDiagnostics({sourceGeneration:this.foregroundGeneration,sourceSdkStreaming:this.runtime.session.isStreaming,sourceObservedRunning:this.foregroundObservedRunning,sourcePersisted:n,sourceLocationBefore:"foreground",ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t);let r=Jn(e),a=this.backgroundSessions.get(r);Jr.recordOwnershipDiagnostics({targetBackgroundLookup:a?"hit":"miss",targetLocationBefore:a?a.status==="running"?"background-running":"background-completed":"disposed"},t);let i=!0;if(a){a.activating=!0;let o=this.currentRuntimeLeaveAction();Jr.recordOwnershipDiagnostics({leaveAction:o},t);try{await Jr.measure("backgroundActivation",()=>this.activateRuntime(a),t),this.backgroundSessions.release(r,a),Jr.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(o),targetLocationAfter:"foreground"},t)}catch(s){if(a.status==="completed")this.releaseBackgroundSession(a);throw s}finally{a.activating=!1}}else if(!this.isCurrentRuntimeActive()&&n){if(Jr.recordOwnershipDiagnostics({leaveAction:"dispose"},t),i=!(await Jr.measure("runtimeSwitchCreate",()=>this.runtime.switchSession(e),t)).cancelled,i)Jr.recordSessionOpen(t),this.adoptRuntime(this.runtime),Jr.recordOwnershipDiagnostics({sourceLocationAfter:"disposed",targetLocationAfter:"foreground"},t)}else{let o=Jr.measureSync("sessionManagerOpen",()=>this.dependencies.openSessionManager(e,this.sessionDir),t);Jr.recordSessionOpen(t);let s=this.currentRuntimeLeaveAction();Jr.recordOwnershipDiagnostics({leaveAction:s},t),await this.leaveCurrentRuntimeForReplacement(s);let c=await Jr.measure("runtimeSwitchCreate",()=>this.dependencies.createRuntime(this.runtimeFactory,{cwd:o.getCwd(),agentDir:this.dependencies.getAgentDir(),sessionManager:o}),t);this.adoptRuntime(c),await Jr.measure("runtimeRebind",()=>this.bindSession(),t),this.state.resetChat({broadcast:!1}),this.loadCurrentSessionMessages(),Jr.recordOwnershipDiagnostics({sourceLocationAfter:this.leaveActionLocation(s),targetLocationAfter:"foreground"},t)}return Jr.recordOwnershipDiagnostics({ownedLiveRuntimeCount:this.ownedLiveRuntimeCount(),duplicateKeyInvariantFailures:this.backgroundSessions.invariantFailureCount},t),i}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){let t=this.runtime,n=t.session;try{if(await n.compact(e),this.runtime===t&&t.session===n)this.loadCurrentSessionMessages();return!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({beforeSessionStart:()=>this.unbindSession()}),e!==this.runtime)return!1;return 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: ${fu(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}
|
|
3752
|
-
Gist: ${t.gistUrl}`)}catch(t){if(e===this.foregroundGeneration)this.state.appendMessage("notice",`Failed to share session: ${fu(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>=a3a;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.completedBackgroundPaths.clear(),this.prompts.dispose();let n=(await Promise.allSettled(e.map((r)=>Promise.try(()=>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=()=>z3n(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 Jr.measure("runtimeRebind",async()=>{if(!n())return;if(await this.bindSessionExtensions(),!n())return;this.bindSessionState(),this.loadCurrentSessionMessages()})})}rememberCurrentSession(){let e=this.runtime.session.sessionManager.getSessionFile();if(e)this.state.setPreviousSessionPath(e)}async leaveCurrentRuntimeForReplacement(e=this.currentRuntimeLeaveAction()){if(this.rememberCurrentSession(),e==="background")this.backgroundCurrentRuntime();else if(e==="discard")await this.discardTemporaryRuntime();else{this.unbindSession();let t=Jr.startSpan("runtimeDispose");try{await this.runtime.dispose()}finally{t()}}}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: ${fu(t)}`)}await e.dispose(),this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),YXe(this.tools)}backgroundCurrentRuntime(){let e=this.runtime.session.sessionManager.getSessionFile();if(!e)return;if(this.backgroundSessions.has(e))throw new gY;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 b5(t.emptyChatHint);a.restore(t);let i={runtime:this.runtime,state:a,status:"running",generation:n,observedRunning:r,tools:QNn(this.tools),unsubscribe:()=>{},activating:!1};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).then(()=>{let r=e.runtime,a=r.session.sessionManager.getSessionFile();if(t.reason!=="manual"||!a||this.backgroundSessions.get(a)!==e||r.session.isCompacting||r.session.isStreaming||e.observedRunning||this.prompts.hasPending(r))return;this.completeBackgroundSession(e)});if(n.agentCompleted)this.completeBackgroundSession(e)}completeBackgroundSession(e){if(e.status==="completed")return;this.unsubscribeBackgroundSession(e),e.status="completed",this.catalog.mergeCurrentStatuses(),this.notifyRuntimeDone(e.runtime);let t=e.runtime.session.sessionManager.getSessionFile();if(t)this.catalog.agentCompleted(t),this.catalog.refreshPath(t);this.releaseBackgroundSession(e)}releaseBackgroundSession(e){let t=e.runtime.session.sessionManager.getSessionFile();if(!t)return;queueMicrotask(()=>{if(e.activating)return;if(this.backgroundSessions.get(t)!==e)return;this.backgroundSessions.delete(t),this.completedBackgroundPaths.add(t),this.catalog.mergeCurrentStatuses(),Promise.try(()=>e.runtime.dispose()).catch((n)=>console.error("Failed to dispose background runtime",n))})}backgroundStatuses(){let e=new Map([...this.backgroundSessions.entries()].map(([t,n])=>[t,n.status]));for(let t of this.completedBackgroundPaths)if(!e.has(t))e.set(t,"completed");return e}notifyRuntimeDone(e){let t=e.session.sessionManager.getCwd(),n=LT(t);this.activationOptions.notifySessionDone?.({workspace:n?`${n.project}/${n.branch}`:qC(t),sessionPath:e.session.sessionManager.getSessionFile()})}async activateRuntime(e){await this.leaveCurrentRuntimeForReplacement(),this.unsubscribeBackgroundSession(e),this.adoptRuntime(e.runtime,e),SNn(this.tools,e.tools),this.bindSessionState({resetToolState:!1,syncSessions:!1}),this.state.restoreChat(e.state.snapshot()),await this.bindSessionExtensions(),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;this.state.setWorkspacePath(t.sessionManager.getCwd());let r=t.sessionManager.getSessionFile();if(this.state.setCurrentSessionPath(r),r)this.completedBackgroundPaths.delete(r);if(this.state.setTemporarySession(!t.sessionManager.isPersisted()),n)YXe(this.tools);if(this.unsubscribe=t.subscribe((a)=>this.handleEvent(a)),this.state.setActivityText(t.isStreaming||this.foregroundObservedRunning?"Working...":void 0),this.models.sync(),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=e.session,n=()=>e===this.runtime&&t===e.session;await Jr.measure("extensionBind",()=>t.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(n),onError:(r)=>{if(n())this.state.appendMessage("notice",`Extension ${r.extensionPath}: ${r.error}`)},commandContextActions:{waitForIdle:()=>t.waitForIdle(),newSession:(r)=>e.newSession(r),fork:async(r,a)=>({cancelled:(await e.fork(r,a)).cancelled}),navigateTree:async(r,a)=>{let i=await t.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)}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),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),N3n(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 DNn(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=s9(a.toolName,a.partialResult,{args:a.args});return{text:i.text,meta:ZIe(a.toolName,a.args),format:i.format}},formatToolEnd:(a,i)=>{let o=s9(a.toolName,a.result,{args:i,isError:a.isError}),s=hee(a.result);return{text:o.text,options:{title:o9(a.isError?"error":"success",a.toolName,i),meta:fee(a.durationMs),state:a.isError?"error":"success",titleParts:Q1(a.toolName,i),format:o.format,attachments:s.length?s:void 0}}},cacheMissNotice:(a)=>{if(!this.runtime.session.settingsManager?.getShowCacheMissNotices())return;let i=PK(this.runtime.session.sessionManager.getEntries(),a,this.runtime.session.modelRuntime);return i?DEe(i):void 0},syncUsage:r})}formatRunningTool(e,t,n=!0){let r=zkt(e,t);return{text:n?r.text:"",options:{title:o9("running",e,t),titleParts:Q1(e,t),meta:ZIe(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)=>!i3a.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([...n4n,...t,...n,...r])}loadCurrentSessionMessages(){let e=this.runtime.session.sessionManager.getSessionId();if(this.projectedSessionId!==void 0&&this.projectedSessionId!==e)this.state.resetChat();this.projectedSessionId=e,Jr.measureSync("transcriptProjection",()=>this.transcript.load(this.runtime,this.state)),this.usage.sync()}}var r3a,a3a=1800000,n4n,i3a,t4n;var r4n=I(()=>{ZD();W3n();TXe();J3n();LXe();K3n();V3n();eNn();nNn();iNn();No();sNn();pNn();mNn();INn();UXe();RNn();FNn();f4();c9();LNn();NNn();VNn();bC();qv();SEe();e4n();Tf();r3a=[X3n,tNn,{name:"codemode",factory:mK(),builtin:!0,replaceable:!0},{name:"tool-search",factory:DK(),builtin:!0,replaceable:!0},{name:"mcp",factory:SK(),builtin:!0,replaceable:!0}],n4n=[{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"}],i3a=new Set(n4n.map((e)=>e.name)),t4n={createRuntime:Z3,prepareSessions:hY.prepare,createSessionManager:$a.create,createMemorySessionManager:$a.inMemory,forkSessionManager:$a.forkFrom,openSessionManager:$a.open,moveToTrash:XNn,shareSession:MNn,getAgentDir:kr,watchSessionCatalog:ANn}});function a4n(e,t){let n=JSON.stringify(t).replaceAll("<","\\u003c");e.executeOnOneClient(`window.piUi.notifications.show(${n})`)}class qEe{streamFactory;recordPerformance;clients=new Map;constructor(e=Cke,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)=>{let i=()=>{if(!this.clients.delete(r))return;e.removeEventListener("abort",i),a.close(),n.onDisconnect?.()};if(this.clients.set(r,{stream:a,disconnect:i}),e.addEventListener("abort",i,{once:!0}),e.aborted){i();return}try{let o=t();if(this.recordPerformance&&Jr.enabled&&o.elements)Jr.recordPatch("initial",o.elements,1);this.patchClient(a,o.elements,o.signals,o.scripts??[])}catch{i()}},{keepalive:!0,onAbort:()=>this.clients.get(r)?.disconnect()})}patchView(e,t,n){if(this.clientCount===0)return;let r=e();if(this.recordPerformance&&Jr.enabled&&r)Jr.recordPatch("view",r,this.clientCount);this.broadcast((a)=>this.patchClient(a,r,t,n))}executeScript(e){this.broadcast((t)=>t.executeScript(e))}patchElement(e,t,n={}){let{scripts:r=[],...a}=n,i=this.recordPerformance&&Jr.enabled,o=t==="#messages",s=i&&o?Jr.transcriptPatchScript():void 0;if(i&&this.clientCount>0){let c=o?"transcript":t.startsWith("#message-")?"message":t==="#session-sidebar-content"?"sidebar":"other";Jr.recordPatch(c,e,this.clientCount)}if(this.broadcast((c)=>{c.patchElements(e,{...a,selector:t});for(let u of r)c.executeScript(u);if(s)c.executeScript(s)}),i&&o&&this.clientCount>0)Jr.markFirstTranscriptPatch()}executeOnOneClient(e){for(let{stream:t,disconnect:n}of this.clients.values())try{t.executeScript(e);return}catch{n()}}broadcast(e){for(let{stream:t,disconnect:n}of this.clients.values())try{e(t)}catch{n()}}patchClient(e,t,n,r){if(t)e.patchElements(t);if(n&&n!=="{}")e.patchSignals(n);if(r.length>0)e.executeScript(r.join(";"))}}var i4n=I(()=>{bC();gu()});import{readdir as o3a,readFile as s3a}from"fs/promises";import{relative as o4n,resolve as HEe,sep as c3a}from"path";async function s4n(e){let t=await u3a(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=l3a(e,o);if(!s)return new Response("Not found",{status:404});let c=Bun.file(s);if(!await c.exists())return new Response("Not found",{status:404});return new Response(c,{headers:{"cache-control":i?"public, max-age=31536000, immutable":"no-cache, must-revalidate"}})}}}function l3a(e,t){let n;try{n=decodeURIComponent(t)}catch{return}let r=HEe(e,`.${n}`),a=o4n(e,r);if(a.startsWith(`..${c3a}`)||a==="..")return;return r}async function u3a(e){let t=await d3a(e),n=new Bun.CryptoHasher("sha256");for(let r of t)n.update(`${o4n(e,r)}\x00`),n.update(await s3a(r));return n.digest("hex").slice(0,16)}async function d3a(e){let t=[],n=async(r)=>{for(let a of await o3a(r,{withFileTypes:!0})){let i=HEe(r,a.name);if(a.isDirectory()){if(i===HEe(e,"build/chunks")||i===HEe(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 c4n=()=>{};import{join as p3a}from"path";import{fileURLToPath as A3a}from"url";var l4n;var u4n=I(()=>{l4n=Bun.isStandaloneExecutable?p3a(import.meta.dir,"static"):A3a(new URL("../../static",import.meta.url))});import{watch as m3a}from"fs";import g3a from"os";import*as bY from"path";class uet{store;generation=0;timer;watchers=[];constructor(e){this.store=e;e.listenForWorkspacePath((t)=>this.open(t))}open(e){let t=++this.generation;return 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={},i=()=>t===this.generation,o=async()=>{if(n){r=!0;return}n=!0;try{do{r=!1;let p=await KPn(e,a);if(i())this.store.setWorkspaceReview(p)}while(r&&i())}finally{n=!1}};if(await Promise.all([o(),NMt(e).then((p)=>{if(i())this.store.setProjectRoot(p??e)})]),!i())return;let s=await JPn(e);if(!i())return;a={};let c=new Set,u=!1,l=async()=>{if(!i())return;let p=c;if(c=new Set,this.store.workspaceFilesChanged(u),u=!1,p&&s?.[0]&&await zPn(s[0],[...p]))return;if(i())await o()},d=(p,A,m)=>{if(!i())return;let h=m?.replaceAll("\\","/");if(s&&h){let f=p===s[0]?".git/":"",g=h.startsWith(f)?h.slice(f.length):"";if(g.startsWith("objects/")||g.startsWith("logs/")||g.endsWith(".lock"))return}if(A!=="change"||!m)u=!0;if(A==="change"&&m&&h&&p===s?.[0]&&h!==".git"&&!h.startsWith(".git/")&&h.split("/").at(-1)!==".gitignore")c?.add(m);else c=void 0,a={};if(this.timer!==void 0)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=void 0,l()},f3a)};this.watchers=(s??[e]).map((p)=>m3a(p,{recursive:s!==void 0||h3a(e)},(A,m)=>d(p,A,m)))}stopWatcher(){if(this.timer!==void 0)clearTimeout(this.timer);this.timer=void 0;for(let e of this.watchers)e.close();this.watchers=[]}}function h3a(e){let t=bY.resolve(e),n=g3a.homedir();return t!==bY.parse(t).root&&(!n||t!==bY.resolve(n))}var f3a=200;var d4n=I(()=>{zae();BEe()});class yY{render;clock;schedulingToleranceMs;latest;dirty=!1;rendering=!1;flushAfterRender=!1;timer;nextDeadline;intervalMs=33.333333333333336;constructor(e,t=b3a,n=0.5){this.render=e;this.clock=t;this.schedulingToleranceMs=n}schedule(e){if(this.latest=e,this.dirty=!0,!this.rendering)this.scheduleTimer()}flush(e){if(e!==void 0)this.latest=e,this.dirty=!0;if(this.cancelTimer(),this.rendering){this.flushAfterRender=!0;return}this.commitLatest()}clear(){this.cancelTimer(),this.latest=void 0,this.dirty=!1,this.flushAfterRender=!1,this.nextDeadline=void 0}scheduleTimer(){if(this.timer!==void 0||!this.dirty)return;let e=this.clock.now();if(this.nextDeadline===void 0)this.nextDeadline=e+this.intervalMs;if(this.nextDeadline<=e){let r=Math.floor((e-this.nextDeadline)/this.intervalMs)+1;this.nextDeadline+=r*this.intervalMs}let t=this.nextDeadline,n=Math.max(0,t-e-this.schedulingToleranceMs);this.timer=this.clock.setTimer(()=>{this.timer=void 0,this.nextDeadline=t+this.intervalMs,this.commitLatest()},n)}commitLatest(){if(!this.dirty||this.latest===void 0||this.rendering)return;let e=this.latest;this.dirty=!1,this.rendering=!0;try{this.render(e)}finally{this.rendering=!1}if(this.dirty&&this.flushAfterRender){this.flushAfterRender=!1,this.commitLatest();return}if(this.dirty)this.scheduleTimer()}cancelTimer(){if(this.timer===void 0)return;this.clock.clearTimer(this.timer),this.timer=void 0}}var b3a;var det=I(()=>{b3a={now:()=>performance.now(),setTimer:(e,t)=>Number(setTimeout(e,t)),clearTimer:(e)=>clearTimeout(e)}});class pet{concurrency;pending=[];active=new Map;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),this.pending.sort((t,n)=>n.priority-t.priority),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 p4n(e){let t;try{t=Buffer.from(e.slice(0,5464),"base64")}catch{return}if(t.length<10)return;if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){if(t.length<24)return;let n=new DataView(t.buffer,t.byteOffset);return{width:n.getUint32(16),height:n.getUint32(20)}}if(t[0]===255&&t[1]===216)return y3a(t);if(t[0]===71&&t[1]===73&&t[2]===70){let n=new DataView(t.buffer,t.byteOffset);return{width:n.getUint16(6,!0),height:n.getUint16(8,!0)}}if(t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80)return w3a(t);return}function y3a(e){let t=new DataView(e.buffer,e.byteOffset),n=2;while(n+9<e.length){if(e[n]!==255)return;let r=e[n+1];if(r>=192&&r<=207&&r!==196&&r!==200)return{height:t.getUint16(n+5),width:t.getUint16(n+7)};n+=2+t.getUint16(n+2)}return}function w3a(e){let t=new DataView(e.buffer,e.byteOffset),n=String.fromCharCode(e[12],e[13],e[14],e[15]);if(n==="VP8 "){if(e.length<30)return;return{width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383}}if(n==="VP8L"){if(e.length<25)return;let[r,a,i,o]=[e[21],e[22],e[23],e[24]];return{width:(r|(a&63)<<8)+1,height:((a>>6|i<<2|(o&15)<<10)&16383)+1}}if(n==="VP8X"){if(e.length<30)return;return{width:(e[24]|e[25]<<8|e[26]<<16)+1,height:(e[27]|e[28]<<8|e[29]<<16)+1}}return}function wY(e){return E3a.has(e)}function WEe(e){if(wY(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";if(e.titleParts?.some((t)=>t.highlight==="javascript"||t.highlight==="bash"&&nve(t.text)))return"title"}function A4n(e){return[...new Set(e.filter((t)=>t!==void 0))]}function k3a(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 Aet{store;patchMessage;deferEnhancement;presentation=new Map;imageUrls=new Map;queue;streaming;pendingStreamingIds=new Set;renderMarkdownEnhancement;renderCodeEnhancement;renderDiffEnhancement;registerImage;clearImages;constructor(e,t,n,r={}){this.store=e;this.patchMessage=t;this.deferEnhancement=n;this.queue=new pet(r.enhancementConcurrency??2),this.renderMarkdownEnhancement=r.renderMarkdownFinal??sre,this.renderCodeEnhancement=r.renderCode??((a,i)=>kee(a,i,{disableLineNumbers:!0})),this.renderDiffEnhancement=r.renderDiff??wBt,this.registerImage=r.registerImage,this.clearImages=r.clearImages,this.streaming=new yY((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))}get compactTools(){return this.store.minimalMode||this.store.toolOutputHidden}renderTranscript(e){return mre(this.projectMessages(e.messages),e.emptyChatHint,e.hasOlderMessages,e.sessions,e.models.some((t)=>t.configured),e.sessionCatalogLoading,e.minimalMode||e.toolOutputHidden)}renderMessageElement(e){let t=this.store.transcript.getMessage(e);if(!t)return;return fre(this.project(t),this.compactTools)}messageAppended(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(this.presentation.set(e,{renderedHtml:wY(t.role)&&t.text.trim()?mx(t.text,{cacheKey:e}):void 0,presentationState:wY(t.role)?"streaming":"plain",presentationVersion:0}),t.role==="tool"&&(t.state!=="running"||WEe(t)==="title"))this.enqueueEnhancement(e)}messageUpdated(e){if(!this.store.transcript.getMessage(e))return;gx(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.queue.cancelAll();for(let t of this.presentation.keys())gx(t);this.presentation.clear();for(let t of this.store.messages)if(this.messageAppended(t.id),WEe(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=A4n([e.thoughtId,e.assistantId]);this.flushMessages(t);for(let n of t)this.deferEnhancement(n)}transcriptReplacing(){this.clearScheduledMessages(),this.queue.cancelAll();for(let e of this.store.transcript.allMessages)gx(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)}dropMessages(e){for(let t of e)this.presentation.delete(t),gx(t),bee(this.imageUrls,`${t}:`)}enqueueEnhancement(e){if(!this.store.transcript.isMessageVisible(e))return;let t=this.store.transcript.getMessage(e),n=t?this.project(t):void 0,r=n?WEe(n):void 0,a=t?this.ensure(e):void 0;if(!t||!r||!a||r==="markdown"&&this.streamingIds().includes(e)||r!=="title"&&!t.text.trim()||a.presentationState==="enhancing"||a.presentationState==="final")return;let{text:i,format:o}=t,s=a.presentationVersion;a.presentationState="enhancing",this.queue.enqueue({priority:this.store.transcript.getMessageIndex(e)??0,run:async(c)=>{if(await zC("bash"),c.aborted)return;if(!this.store.transcript.isMessageVisible(e))return;let u=await this.renderEnhancement(r,i,e);if(c.aborted)return;let l=this.store.transcript.getMessage(e);if(!l||l.text!==i||l.format!==o||!this.store.transcript.isMessageVisible(e))return;let d=this.ensure(e);if(d.presentationVersion!==s)return;let p=r==="markdown"&&d.renderedHtml===u;if(d.renderedHtml=u,d.presentationState="final",gx(e),!p)this.broadcast(l)},onCancel:()=>gx(e),onError:(c)=>{if(!this.store.transcript.isMessageVisible(e))return;let u=this.store.transcript.getMessage(e),l=this.ensure(e);if(u?.text===i&&u.format===o&&l.presentationVersion===s)l.presentationState="plain",gx(e);console.warn(`Failed to enhance message ${e}`,c)}})}streamingIds(){return A4n([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()?mx(t.text,{cacheKey:e}):void 0,presentationState:"streaming",presentationVersion:0})}patchScheduledMessage(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(wY(t.role)&&t.text.trim()){let n=this.ensure(e);n.renderedHtml=mx(t.text,{cacheKey:e}),n.presentationState="streaming"}if(this.broadcast(t),t.role==="tool"&&(t.state!=="running"||WEe(t)==="title"))this.enqueueEnhancement(e)}project(e){let t=this.ensure(e.id),n=this.activitySummary(e);if(wY(e.role)&&e.text.trim()&&t.renderedHtml===void 0)t.renderedHtml=mx(e.text,{cacheKey:e.id});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}),...p4n(i.data)},this.imageUrls.set(o,s);let c={mimeType:i.mimeType,url:s.url};if(s.width!==void 0&&s.height!==void 0)c.width=s.width,c.height=s.height;return{...r,image:c}}),...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,a=0;while(r>0){let i=t[r-1];if(i.role!=="thought"&&i.role!=="tool")break;if(r-=1,i.role==="tool")a+=1}if(a===0)return;return{stepCount:a,duration:k3a(e.timestamp.getTime()-t[r].timestamp.getTime())}}broadcast(e){this.patchMessage(fre(this.project(e),this.compactTools),`#message-${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,n){if(e==="title")return;if(e==="markdown")return await Jr.measure("markdownEnhancement",()=>this.renderMarkdownEnhancement(t,{cacheKey:n}));let r=Jr.startSpan("toolEnhancement");try{if(e==="diff")return await this.renderDiffEnhancement(t)??await qQt(t,"diff",{chrome:!1});return await this.renderCodeEnhancement(t,"bash")}finally{r()}}}var E3a;var m4n=I(()=>{bC();det();ave();Bee();ure();hre();E3a=new Set(["assistant","thought","compaction","summary","skill"])});class met{store;hub;messages;view={sessionQuery:"",slashQuery:"",workspaceSearch:{query:"",results:[]}};commits=new yY(()=>this.flush());fullViewPending=!1;pendingEffects=[];pendingEnhancements=new Set;transcriptPending=!1;compactTools;sidebarLayout="";constructor(e,t,n={}){this.store=e;this.hub=t;this.messages=new Aet(e,(r,a)=>{if(!this.transcriptPending)t.patchElement(r,a)},(r)=>this.pendingEnhancements.add(r),n),this.compactTools=this.messages.compactTools,e.attachPresentation(this)}createStream(e,t="",n="",r=""){this.commits.flush();let a=this.view;a.sessionQuery=t,a.slashQuery=r,a.workspaceSearch={query:n,results:[]};let i=()=>{if(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 o=this.store.snapshot();this.sidebarLayout=mDe(o);let s=this.messages.renderTranscript(o)+this.renderView(o,a)+hae(o);if(n.trim())queueMicrotask(()=>{this.setWorkspaceSearch(n)});if(this.hub.clientCount===1)queueMicrotask(()=>{if(this.hub.clientCount===0)return;for(let c of o.messages.toReversed())this.messages.enqueueEnhancement(c.id)});return{elements:s,signals:this.renderSignals(o)}},{onDisconnect:i})}catch(o){throw i(),o}}setSessionSearch(e){if(this.view.sessionQuery===e)return;this.view.sessionQuery=e,this.viewChanged()}setSlashSearch(e){if(this.view.slashQuery===e)return;this.view.slashQuery=e,this.viewChanged()}async setWorkspaceSearch(e){let t={query:e,results:[]};this.view.workspaceSearch=t;let n=await m8n(this.store.workspacePath,e);if(this.view.workspaceSearch!==t)return;t.results=n,this.viewChanged()}viewChanged(){this.fullViewPending=!0,this.requestCommit()}requestCommit(e){if(e?.type==="render-transcript")this.transcriptPending=!0;else if(e)this.pendingEffects.push(e);this.commits.schedule(!0)}flush(){let e=this.pendingEffects;this.pendingEffects=[];let t=this.fullViewPending;this.fullViewPending=!1;let n=[...this.pendingEnhancements];this.pendingEnhancements.clear();let r=this.compactTools!==this.messages.compactTools;if(this.compactTools=this.messages.compactTools,this.hub.clientCount>0){let a=Jr.measureSync("stateSnapshot",()=>this.store.snapshot());if(this.transcriptPending||r||t&&a.messages.length===0)this.hub.patchElement(Jr.measureSync("transcriptRender",()=>this.messages.renderTranscript(a)),"#messages",{scripts:["window.piUi.messageScroll.checkOlder()"]});let i=mDe(a),o=i!==this.sidebarLayout;if(t||o)this.sidebarLayout=i,this.hub.patchElement(Jr.measureSync("sidebarRender",()=>hae(a)),"#session-sidebar-content",{useViewTransition:o,viewTransitionSelector:"#session-sidebar-viewport"});this.hub.patchView(()=>Jr.measureSync("viewRender",()=>t?this.renderView(a,this.view):this.renderAppElements(a)),Jr.measureSync("signalRender",()=>this.renderSignals(a,this.effectSignalOverrides(e))),this.effectScripts(e))}if(this.transcriptPending=!1,this.hub.clientCount>0)for(let a of n)this.messages.enqueueEnhancement(a)}messageAppended(e){if(this.hub.clientCount===0)return;this.messages.messageAppended(e),this.requestCommit({type:"render-transcript"})}messagesRemoved(e){this.messages.dropMessages(e),this.hub.patchElement("",`#message-list > :nth-child(-n+${e.length} of .message[id])`,{mode:"remove"}),this.hub.patchElement(gre(this.store.hasOlderMessages),"#older-messages-trigger")}messageUpdated(e){if(this.hub.clientCount===0)return;this.messages.messageUpdated(e)}codeThemeChanged(){if(this.hub.clientCount>0)this.messages.codeThemeChanged();else this.messages.transcriptReplacing();this.transcriptPending=!0,this.requestCommit()}streamingMessageStarted(e){if(this.hub.clientCount===0)return;this.messages.streamingMessageStarted(e),this.requestCommit({type:"render-transcript"})}streamingMessageChanged(){if(this.hub.clientCount===0)return;this.messages.streamingMessageChanged()}sessionTransitionChanged(e){this.requestCommit(e?{type:"scroll-transcript-bottom"}:void 0),this.commits.flush()}assistantFinished(e){if(this.hub.clientCount===0)return;this.messages.assistantFinished(e)}transcriptReplacing(){this.transcriptPending=!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;if(e.length>0)this.hub.executeScript("window.piUi.messageScroll.beforeOlder()"),this.hub.patchElement(e.map(({id:t})=>this.messages.renderMessageElement(t)).join(""),"#older-messages-trigger",{mode:"after",scripts:["window.piUi.messageScroll.afterOlder()"]});if(!this.store.hasOlderMessages)this.hub.patchElement(gre(!1),"#older-messages-trigger");for(let t of e.toReversed())this.messages.enqueueEnhancement(t.id)}projectState(e){return{...e,messages:this.messages.projectMessages(e.messages)}}renderAppElements(e){return`<title id="document-title">${Bun.escapeHTML(e.documentTitle)}</title>`+kae(e)+xDe(e)+Dae(e)+Aae(e)+bF(e,"aboveEditor")+bF(e,"belowEditor")+xae(e)+HY(e)+FZ(e)}renderPickerElements(e,t){return aZ(e.authDialog)+jZ(e.extensionDialog)+LZ(e.llamaDialog)+Cae(e)+Bae(e)+yae(e,t?.slashQuery)+Tae(e)}renderSignals(e,t={}){return JSON.stringify({...DZ(e),...t})}renderView(e,t){let n=t?.sessionQuery??"";return this.renderAppElements(e)+this.renderPickerElements(e,t)+wae(e,t?.workspaceSearch.query,t?.workspaceSearch.results)+yDe(n.trim()?{...e,sessions:this.store.searchSessions(n),sessionsHasMore:!1}:e,n)+jMt(e.workspacePath,e.workspaceFilesRevision,e.workspaceTreeRevision,e.workspaceReview,e.workspaceReviewPreferences)}effectSignalOverrides(e){let t={};for(let n of e)if(n.type==="signal-overrides")Object.assign(t,n.values);return t}effectScripts(e){let t=new Set;for(let n of e){if(n.type==="scroll-transcript-bottom")t.add("window.piUi.messageScroll.scrollBottom()");if(n.type==="open-tree-dialog")t.add("{ const dialog = document.getElementById('tree-dialog'); if (dialog && !dialog.open) dialog.showModal(); }")}return[...t]}}var g4n=I(()=>{bC();sXe();det();tBe();vBe();QBe();DBe();wDe();RBe();m4n();hre();hF();EDe();_De();w5();CDe();gae();bae();Wv();QDe();DDe();VDe()});import{existsSync as B3a}from"fs";async function h4n(e=fetch,t=TY){let n=await I3a(e);if(!n)return;if(_Ze(n,t)!==1)return;return{currentVersion:t,latestVersion:n,releaseUrl:`${x3a}${n}`,upgradeCommand:v3a()}}async function I3a(e){try{let t=await e(C3a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(_3a)});if(!t.ok)return;let n=await t.json(),r=rm(n)?.version;return zn(r)?r:void 0}catch{return}}function v3a(e=process.platform,t=process.execPath,n=process.argv[1]??"",r=B3a("/etc/arch-release")){if(e==="win32")return"irm https://pi-ui.app/install.ps1 | iex";if(Q3a(t))return"brew upgrade hyperpuncher/tap/pi-ui";if(f4n(t)||f4n(n))return"bun i -g @hyperpuncher/pi-ui";if(e==="linux"&&r)return"paru -S pi-ui-bin";return"curl -fsSL https://pi-ui.app/install | sh"}function Q3a(e){return/[\\/](?:Cellar|homebrew)[\\/]/i.test(e)}function f4n(e){return/[\\/]node_modules[\\/]|[\\/]\.bun[\\/]install[\\/]/i.test(e)}var C3a="https://registry.npmjs.org/@hyperpuncher/pi-ui/latest",x3a="https://github.com/hyperpuncher/pi-ui/releases/tag/v",_3a=3000;var b4n=I(()=>{vwe();pke()});var y4n={};Ke(y4n,{createApp:()=>R3a});import{realpath as S3a,stat as D3a}from"fs/promises";async function R3a(){let e=ZB("fd",({message:k})=>console.error(k)),t=await s4n(l4n),n=await iFt();nnt(tnt(n.keybinds));let r=Art(n.codeTheme)??mrt(),a=Ytt(n.fonts)??Jtt(),i=P3n(n.autoTitle),o=D4(n.gitView),s=rZ(n.sessionSidebar);eZ(r),ZY(a);let c=zC("bash"),u=new cDe;if(u.theme=n.theme==="light"||n.theme==="dark"?n.theme:"system",u.keybindHints=n.keybindHints!==!1,u.minimalMode=n.minimalMode===!0,u.toolOutputHidden=n.toolOutputHidden===!0,u.toolbarHidden=n.toolbarHidden===!0,u.sessionSidebarOpen=s.open!==!1,u.sessionSidebarWidth=s.width??D0,u.sessionSidebarArchive=s.archive!==!1,u.sessionSidebarArchiveAfterDays=s.archiveAfterDays??nZ,n.updateCheck!==!1&&process.env.PI_UI_NO_UPDATE_CHECK!=="1")h4n().then((k)=>{if(k)u.setUpdateAvailable(k)});u.setWorkspaceReviewPreferences(o);let l=new tXe,d=new qEe,p=new qEe,A=(k)=>a4n(p,k),m=new met(u,d,{registerImage:(k)=>l.register(k),clearImages:()=>l.clear()}),h=new g4((k)=>u.setSessionTransition(k)),f=await o4.create(u,void 0,{autoTitle:i,notifySessionDone:A,transitionController:h}).catch((k)=>{console.error("Failed to start pi SDK runtime",k);return});if(!await c)console.error("Failed to preload tool highlighter");let g=new uet(u);g.open(u.workspacePath);let b=await e,y={host:f,sessionImages:l,fdPath:b},w=await bEe.create(),E={store:u,renderer:m,notificationClients:p,resources:y,transferredFiles:w,appVersion:t.version,themeLab:process.env.PI_UI_THEME_LAB==="1",serveStatic:(k)=>t.serve(k),openWorkspace:(k)=>T3a(k,u,y,h,i,A)},B;return{context:E,dispose:()=>(B??=(async()=>{g.dispose(),await Promise.allSettled([w.dispose(),y.host?.dispose()])})(),B)}}async function T3a(e,t,n,r,a,i){let o=e.trim();return(await r.run(o,async()=>{let c=await S3a(ak(o));if(!(await D3a(c)).isDirectory())throw Error("Not a directory");if(!n.host)return n.host=await o4.create(t,c,{autoTitle:a,notifySessionDone:i,refreshWorkspaces:!1,transitionController:r}),!0;return await n.host.openWorkspace(c)},{overlay:!1})).status==="success"}var w4n=I(()=>{DJ();TXe();r4n();f4();MZ();zR();Ib();vb();Mx();i4n();c4n();u4n();yEe();d4n();KR();lae();Bee();g4n();b4n();Tf();BC()});var C4n={};Ke(C4n,{compressResponse:()=>G3a});import{Readable as M3a}from"stream";import{constants as zEe,createBrotliCompress as F3a,createGzip as j3a,createZstdCompress as L3a}from"zlib";function G3a(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 U3a(e,t);if(e.method==="HEAD"||e.headers.has("range")||t.status===206||t.headers.has("content-range")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||!n||!H3a(n))return t;let r=t.headers.get("content-length");if(r&&Number(r)<$3a)return t;let a=new Headers(t.headers);a.set("vary",B4n(a.get("vary"),"Accept-Encoding"));let i=E4n(e.headers.get("accept-encoding"));if(!i)return q3a(t,a);return k4n(t,a,i)}function U3a(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=E4n(e.headers.get("accept-encoding"));if(!n)return t;let r=new Headers(t.headers);return r.set("vary",B4n(r.get("vary"),"Accept-Encoding")),k4n(t,r,n,n)}function E4n(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((A)=>A.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 P3a){let o=t.get(i)??n;if(o>a)r=i,a=o}return r}function k4n(e,t,n,r){let a=e.body;if(!a)return e;let i=W3a(n);z3a(a.getReader(),i,r),t.set("content-encoding",n),t.delete("content-length");let o=M3a.toWeb(i);return new Response(o,{status:e.status,statusText:e.statusText,headers:t})}function q3a(e,t){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function H3a(e){return e.startsWith("text/")||e==="image/svg+xml"||O3a.has(e)||e.endsWith("+json")||e.endsWith("+xml")}function W3a(e){switch(e){case"zstd":return L3a();case"br":return F3a({params:{[zEe.BROTLI_PARAM_QUALITY]:6}});case"gzip":return j3a()}}async function z3a(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"?N3a:o.length;for(let c=0;c<o.length;c+=s)if(await J3a(t,o.subarray(c,c+s)),n)await K3a(t,n)}if(!t.destroyed)await Y3a(t)}catch(i){if(await e.cancel(i).catch(()=>{}),!t.destroyed)t.destroy(Error.isError(i)?i:Error(String(i)))}finally{t.off("close",a),e.releaseLock()}}function J3a(e,t){return new Promise((n,r)=>{e.write(t,(a)=>a?r(a):n())})}function K3a(e,t){let n={zstd:zEe.ZSTD_e_flush,br:zEe.BROTLI_OPERATION_FLUSH,gzip:zEe.Z_SYNC_FLUSH}[t];return new Promise((r)=>e.flush(n,r))}function Y3a(e){return new Promise((t)=>e.end(t))}function B4n(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 P3a,N3a=4096,$3a=1024,O3a;var x4n=I(()=>{P3a=["zstd","br","gzip"],O3a=new Set(["application/javascript","application/json","application/manifest+json","application/xhtml+xml","application/xml"])});async function v4n(e){let t=await S4n(),n=e.method==="GET"?await t.app.context.serveStatic(e):FE(404,"Not found.");return t.compressResponse(e,n)}async function Q4n(){await(await _4n?.catch(()=>{return}))?.app.dispose()}function Z3a(e){return async(t,n)=>{let r=await S4n();return r.compressResponse(t,await ktt(t,{...r.app.context,clientAddress:n.requestIP(t)?.address},e))}}function S4n(){return _4n??=V3a()}async function V3a(){let[{registerBunOAuthFlows:e},{createApp:t},{compressResponse:n}]=await Promise.all([Promise.resolve().then(() => (L3n(),j3n)),Promise.resolve().then(() => (w4n(),y4n)),Promise.resolve().then(() => (x4n(),C4n))]);return e(),{app:await t(),compressResponse:n}}var _4n,I4n;var D4n=I(()=>{gu();bp();B8n();I4n=Object.fromEntries(Object.entries(k8n).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([n,r])=>[n,Z3a(r)]))]))});import{userInfo as u6n}from"os";var d6n="printf '\\0'; command env -0; printf '\\0'";async function $et(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??u6n().shell;if(!a)return;let i=await(e.readOutput??p6n)(a,t);if(i!==void 0)Object.assign(t,A6n(i))}async function p6n(e,t){try{let n=Bun.spawn([e,"-ilc",d6n],{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 A6n(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}Uv();import{mkdir as m6n}from"fs/promises";import{homedir as g6n}from"os";import{dirname as f6n}from"path";var PR="pi-ui",u4="pi-ui-server",cke="dev.pi.ui",Oet="dev.pi.ui.server",Get="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";function Uet(e=Md,t=C6n()){if(e!=="linux"&&e!=="darwin"&&e!=="windows")throw Error(`server autostart is not supported on ${e}`);let n=g6n();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?x6n(r):!1}}async function qet(e=Uet()){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 w6n(e);break;case"darwin":await E6n(e);break;case"windows":await k6n(e);break}}async function Het(e=Uet()){switch(e.platform){case"linux":await ake(e,PR),await ake(e,u4),await nm("systemctl",["--user","daemon-reload"]);break;case"darwin":await ike(e,cke),await ike(e,Oet);break;case"windows":await B6n(e);break}}function h6n(e){return`[Unit]
|
|
3752
|
+
Gist: ${t.gistUrl}`)}catch(t){if(e===this.foregroundGeneration)this.state.appendMessage("notice",`Failed to share session: ${fu(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>=a3a;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.completedBackgroundPaths.clear(),this.prompts.dispose();let n=(await Promise.allSettled(e.map((r)=>Promise.try(()=>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=()=>z3n(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 Jr.measure("runtimeRebind",async()=>{if(!n())return;if(await this.bindSessionExtensions(),!n())return;this.bindSessionState(),this.loadCurrentSessionMessages()})})}rememberCurrentSession(){let e=this.runtime.session.sessionManager.getSessionFile();if(e)this.state.setPreviousSessionPath(e)}async leaveCurrentRuntimeForReplacement(e=this.currentRuntimeLeaveAction()){if(this.rememberCurrentSession(),e==="background")this.backgroundCurrentRuntime();else if(e==="discard")await this.discardTemporaryRuntime();else{this.unbindSession();let t=Jr.startSpan("runtimeDispose");try{await this.runtime.dispose()}finally{t()}}}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: ${fu(t)}`)}await e.dispose(),this.state.setActivityText(void 0),this.state.setQueuedMessages([],[]),YXe(this.tools)}backgroundCurrentRuntime(){let e=this.runtime.session.sessionManager.getSessionFile();if(!e)return;if(this.backgroundSessions.has(e))throw new gY;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 b5(t.emptyChatHint);a.restore(t);let i={runtime:this.runtime,state:a,status:"running",generation:n,observedRunning:r,tools:QNn(this.tools),unsubscribe:()=>{},activating:!1};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).then(()=>{let r=e.runtime,a=r.session.sessionManager.getSessionFile();if(t.reason!=="manual"||!a||this.backgroundSessions.get(a)!==e||r.session.isCompacting||r.session.isStreaming||e.observedRunning||this.prompts.hasPending(r))return;this.completeBackgroundSession(e)});if(n.agentCompleted)this.completeBackgroundSession(e)}completeBackgroundSession(e){if(e.status==="completed")return;this.unsubscribeBackgroundSession(e),e.status="completed",this.catalog.mergeCurrentStatuses(),this.notifyRuntimeDone(e.runtime);let t=e.runtime.session.sessionManager.getSessionFile();if(t)this.catalog.agentCompleted(t),this.catalog.refreshPath(t);this.releaseBackgroundSession(e)}releaseBackgroundSession(e){let t=e.runtime.session.sessionManager.getSessionFile();if(!t)return;queueMicrotask(()=>{if(e.activating)return;if(this.backgroundSessions.get(t)!==e)return;this.backgroundSessions.delete(t),this.completedBackgroundPaths.add(t),this.catalog.mergeCurrentStatuses(),Promise.try(()=>e.runtime.dispose()).catch((n)=>console.error("Failed to dispose background runtime",n))})}backgroundStatuses(){let e=new Map([...this.backgroundSessions.entries()].map(([t,n])=>[t,n.status]));for(let t of this.completedBackgroundPaths)if(!e.has(t))e.set(t,"completed");return e}notifyRuntimeDone(e){let t=e.session.sessionManager.getCwd(),n=LT(t);this.activationOptions.notifySessionDone?.({workspace:n?`${n.project}/${n.branch}`:qC(t),sessionPath:e.session.sessionManager.getSessionFile()})}async activateRuntime(e){await this.leaveCurrentRuntimeForReplacement(),this.unsubscribeBackgroundSession(e),this.adoptRuntime(e.runtime,e),SNn(this.tools,e.tools),this.bindSessionState({resetToolState:!1,syncSessions:!1}),this.state.restoreChat(e.state.snapshot()),await this.bindSessionExtensions(),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;this.state.setWorkspacePath(t.sessionManager.getCwd());let r=t.sessionManager.getSessionFile();if(this.state.setPromptSessionKey(r??t.sessionManager.getSessionId()),this.state.setCurrentSessionPath(r),r)this.completedBackgroundPaths.delete(r);if(this.state.setTemporarySession(!t.sessionManager.isPersisted()),n)YXe(this.tools);if(this.unsubscribe=t.subscribe((a)=>this.handleEvent(a)),this.state.setActivityText(t.isStreaming||this.foregroundObservedRunning?"Working...":void 0),this.models.sync(),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=e.session,n=()=>e===this.runtime&&t===e.session;await Jr.measure("extensionBind",()=>t.bindExtensions({mode:"rpc",uiContext:this.extensionUi.context(n),onError:(r)=>{if(n())this.state.appendMessage("notice",`Extension ${r.extensionPath}: ${r.error}`)},commandContextActions:{waitForIdle:()=>t.waitForIdle(),newSession:(r)=>e.newSession(r),fork:async(r,a)=>({cancelled:(await e.fork(r,a)).cancelled}),navigateTree:async(r,a)=>{let i=await t.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)}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),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),N3n(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 DNn(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=s9(a.toolName,a.partialResult,{args:a.args});return{text:i.text,meta:ZIe(a.toolName,a.args),format:i.format}},formatToolEnd:(a,i)=>{let o=s9(a.toolName,a.result,{args:i,isError:a.isError}),s=hee(a.result);return{text:o.text,options:{title:o9(a.isError?"error":"success",a.toolName,i),meta:fee(a.durationMs),state:a.isError?"error":"success",titleParts:Q1(a.toolName,i),format:o.format,attachments:s.length?s:void 0}}},cacheMissNotice:(a)=>{if(!this.runtime.session.settingsManager?.getShowCacheMissNotices())return;let i=PK(this.runtime.session.sessionManager.getEntries(),a,this.runtime.session.modelRuntime);return i?DEe(i):void 0},syncUsage:r})}formatRunningTool(e,t,n=!0){let r=zkt(e,t);return{text:n?r.text:"",options:{title:o9("running",e,t),titleParts:Q1(e,t),meta:ZIe(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)=>!i3a.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([...n4n,...t,...n,...r])}loadCurrentSessionMessages(){let e=this.runtime.session.sessionManager.getSessionId();if(this.projectedSessionId!==void 0&&this.projectedSessionId!==e)this.state.resetChat();this.projectedSessionId=e,Jr.measureSync("transcriptProjection",()=>this.transcript.load(this.runtime,this.state)),this.usage.sync()}}var r3a,a3a=1800000,n4n,i3a,t4n;var r4n=I(()=>{ZD();W3n();TXe();J3n();LXe();K3n();V3n();eNn();nNn();iNn();No();sNn();pNn();mNn();INn();UXe();RNn();FNn();f4();c9();LNn();NNn();VNn();bC();qv();SEe();e4n();Tf();r3a=[X3n,tNn,{name:"codemode",factory:mK(),builtin:!0,replaceable:!0},{name:"tool-search",factory:DK(),builtin:!0,replaceable:!0},{name:"mcp",factory:SK(),builtin:!0,replaceable:!0}],n4n=[{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"}],i3a=new Set(n4n.map((e)=>e.name)),t4n={createRuntime:Z3,prepareSessions:hY.prepare,createSessionManager:$a.create,createMemorySessionManager:$a.inMemory,forkSessionManager:$a.forkFrom,openSessionManager:$a.open,moveToTrash:XNn,shareSession:MNn,getAgentDir:kr,watchSessionCatalog:ANn}});function a4n(e,t){let n=JSON.stringify(t).replaceAll("<","\\u003c");e.executeOnOneClient(`window.piUi.notifications.show(${n})`)}class qEe{streamFactory;recordPerformance;clients=new Map;constructor(e=Cke,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)=>{let i=()=>{if(!this.clients.delete(r))return;e.removeEventListener("abort",i),a.close(),n.onDisconnect?.()};if(this.clients.set(r,{stream:a,disconnect:i}),e.addEventListener("abort",i,{once:!0}),e.aborted){i();return}try{let o=t();if(this.recordPerformance&&Jr.enabled&&o.elements)Jr.recordPatch("initial",o.elements,1);this.patchClient(a,o.elements,o.signals,o.scripts??[])}catch{i()}},{keepalive:!0,onAbort:()=>this.clients.get(r)?.disconnect()})}patchView(e,t,n){if(this.clientCount===0)return;let r=e();if(this.recordPerformance&&Jr.enabled&&r)Jr.recordPatch("view",r,this.clientCount);this.broadcast((a)=>this.patchClient(a,r,t,n))}executeScript(e){this.broadcast((t)=>t.executeScript(e))}patchElement(e,t,n={}){let{scripts:r=[],...a}=n,i=this.recordPerformance&&Jr.enabled,o=t==="#messages",s=i&&o?Jr.transcriptPatchScript():void 0;if(i&&this.clientCount>0){let c=o?"transcript":t.startsWith("#message-")?"message":t==="#session-sidebar-content"?"sidebar":"other";Jr.recordPatch(c,e,this.clientCount)}if(this.broadcast((c)=>{c.patchElements(e,{...a,selector:t});for(let u of r)c.executeScript(u);if(s)c.executeScript(s)}),i&&o&&this.clientCount>0)Jr.markFirstTranscriptPatch()}executeOnOneClient(e){for(let{stream:t,disconnect:n}of this.clients.values())try{t.executeScript(e);return}catch{n()}}broadcast(e){for(let{stream:t,disconnect:n}of this.clients.values())try{e(t)}catch{n()}}patchClient(e,t,n,r){if(t)e.patchElements(t);if(n&&n!=="{}")e.patchSignals(n);if(r.length>0)e.executeScript(r.join(";"))}}var i4n=I(()=>{bC();gu()});import{readdir as o3a,readFile as s3a}from"fs/promises";import{relative as o4n,resolve as HEe,sep as c3a}from"path";async function s4n(e){let t=await u3a(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=l3a(e,o);if(!s)return new Response("Not found",{status:404});let c=Bun.file(s);if(!await c.exists())return new Response("Not found",{status:404});return new Response(c,{headers:{"cache-control":i?"public, max-age=31536000, immutable":"no-cache, must-revalidate"}})}}}function l3a(e,t){let n;try{n=decodeURIComponent(t)}catch{return}let r=HEe(e,`.${n}`),a=o4n(e,r);if(a.startsWith(`..${c3a}`)||a==="..")return;return r}async function u3a(e){let t=await d3a(e),n=new Bun.CryptoHasher("sha256");for(let r of t)n.update(`${o4n(e,r)}\x00`),n.update(await s3a(r));return n.digest("hex").slice(0,16)}async function d3a(e){let t=[],n=async(r)=>{for(let a of await o3a(r,{withFileTypes:!0})){let i=HEe(r,a.name);if(a.isDirectory()){if(i===HEe(e,"build/chunks")||i===HEe(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 c4n=()=>{};import{join as p3a}from"path";import{fileURLToPath as A3a}from"url";var l4n;var u4n=I(()=>{l4n=Bun.isStandaloneExecutable?p3a(import.meta.dir,"static"):A3a(new URL("../../static",import.meta.url))});import{watch as m3a}from"fs";import g3a from"os";import*as bY from"path";class uet{store;generation=0;timer;watchers=[];constructor(e){this.store=e;e.listenForWorkspacePath((t)=>this.open(t))}open(e){let t=++this.generation;return 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={},i=()=>t===this.generation,o=async()=>{if(n){r=!0;return}n=!0;try{do{r=!1;let p=await KPn(e,a);if(i())this.store.setWorkspaceReview(p)}while(r&&i())}finally{n=!1}};if(await Promise.all([o(),NMt(e).then((p)=>{if(i())this.store.setProjectRoot(p??e)})]),!i())return;let s=await JPn(e);if(!i())return;a={};let c=new Set,u=!1,l=async()=>{if(!i())return;let p=c;if(c=new Set,this.store.workspaceFilesChanged(u),u=!1,p&&s?.[0]&&await zPn(s[0],[...p]))return;if(i())await o()},d=(p,A,m)=>{if(!i())return;let h=m?.replaceAll("\\","/");if(s&&h){let f=p===s[0]?".git/":"",g=h.startsWith(f)?h.slice(f.length):"";if(g.startsWith("objects/")||g.startsWith("logs/")||g.endsWith(".lock"))return}if(A!=="change"||!m)u=!0;if(A==="change"&&m&&h&&p===s?.[0]&&h!==".git"&&!h.startsWith(".git/")&&h.split("/").at(-1)!==".gitignore")c?.add(m);else c=void 0,a={};if(this.timer!==void 0)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=void 0,l()},f3a)};this.watchers=(s??[e]).map((p)=>m3a(p,{recursive:s!==void 0||h3a(e)},(A,m)=>d(p,A,m)))}stopWatcher(){if(this.timer!==void 0)clearTimeout(this.timer);this.timer=void 0;for(let e of this.watchers)e.close();this.watchers=[]}}function h3a(e){let t=bY.resolve(e),n=g3a.homedir();return t!==bY.parse(t).root&&(!n||t!==bY.resolve(n))}var f3a=200;var d4n=I(()=>{zae();BEe()});class yY{render;clock;schedulingToleranceMs;latest;dirty=!1;rendering=!1;flushAfterRender=!1;timer;nextDeadline;intervalMs=33.333333333333336;constructor(e,t=b3a,n=0.5){this.render=e;this.clock=t;this.schedulingToleranceMs=n}schedule(e){if(this.latest=e,this.dirty=!0,!this.rendering)this.scheduleTimer()}flush(e){if(e!==void 0)this.latest=e,this.dirty=!0;if(this.cancelTimer(),this.rendering){this.flushAfterRender=!0;return}this.commitLatest()}clear(){this.cancelTimer(),this.latest=void 0,this.dirty=!1,this.flushAfterRender=!1,this.nextDeadline=void 0}scheduleTimer(){if(this.timer!==void 0||!this.dirty)return;let e=this.clock.now();if(this.nextDeadline===void 0)this.nextDeadline=e+this.intervalMs;if(this.nextDeadline<=e){let r=Math.floor((e-this.nextDeadline)/this.intervalMs)+1;this.nextDeadline+=r*this.intervalMs}let t=this.nextDeadline,n=Math.max(0,t-e-this.schedulingToleranceMs);this.timer=this.clock.setTimer(()=>{this.timer=void 0,this.nextDeadline=t+this.intervalMs,this.commitLatest()},n)}commitLatest(){if(!this.dirty||this.latest===void 0||this.rendering)return;let e=this.latest;this.dirty=!1,this.rendering=!0;try{this.render(e)}finally{this.rendering=!1}if(this.dirty&&this.flushAfterRender){this.flushAfterRender=!1,this.commitLatest();return}if(this.dirty)this.scheduleTimer()}cancelTimer(){if(this.timer===void 0)return;this.clock.clearTimer(this.timer),this.timer=void 0}}var b3a;var det=I(()=>{b3a={now:()=>performance.now(),setTimer:(e,t)=>Number(setTimeout(e,t)),clearTimer:(e)=>clearTimeout(e)}});class pet{concurrency;pending=[];active=new Map;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),this.pending.sort((t,n)=>n.priority-t.priority),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 p4n(e){let t;try{t=Buffer.from(e.slice(0,5464),"base64")}catch{return}if(t.length<10)return;if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){if(t.length<24)return;let n=new DataView(t.buffer,t.byteOffset);return{width:n.getUint32(16),height:n.getUint32(20)}}if(t[0]===255&&t[1]===216)return y3a(t);if(t[0]===71&&t[1]===73&&t[2]===70){let n=new DataView(t.buffer,t.byteOffset);return{width:n.getUint16(6,!0),height:n.getUint16(8,!0)}}if(t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80)return w3a(t);return}function y3a(e){let t=new DataView(e.buffer,e.byteOffset),n=2;while(n+9<e.length){if(e[n]!==255)return;let r=e[n+1];if(r>=192&&r<=207&&r!==196&&r!==200)return{height:t.getUint16(n+5),width:t.getUint16(n+7)};n+=2+t.getUint16(n+2)}return}function w3a(e){let t=new DataView(e.buffer,e.byteOffset),n=String.fromCharCode(e[12],e[13],e[14],e[15]);if(n==="VP8 "){if(e.length<30)return;return{width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383}}if(n==="VP8L"){if(e.length<25)return;let[r,a,i,o]=[e[21],e[22],e[23],e[24]];return{width:(r|(a&63)<<8)+1,height:((a>>6|i<<2|(o&15)<<10)&16383)+1}}if(n==="VP8X"){if(e.length<30)return;return{width:(e[24]|e[25]<<8|e[26]<<16)+1,height:(e[27]|e[28]<<8|e[29]<<16)+1}}return}function wY(e){return E3a.has(e)}function WEe(e){if(wY(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";if(e.titleParts?.some((t)=>t.highlight==="javascript"||t.highlight==="bash"&&nve(t.text)))return"title"}function A4n(e){return[...new Set(e.filter((t)=>t!==void 0))]}function k3a(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 Aet{store;patchMessage;deferEnhancement;presentation=new Map;imageUrls=new Map;queue;streaming;pendingStreamingIds=new Set;renderMarkdownEnhancement;renderCodeEnhancement;renderDiffEnhancement;registerImage;clearImages;constructor(e,t,n,r={}){this.store=e;this.patchMessage=t;this.deferEnhancement=n;this.queue=new pet(r.enhancementConcurrency??2),this.renderMarkdownEnhancement=r.renderMarkdownFinal??sre,this.renderCodeEnhancement=r.renderCode??((a,i)=>kee(a,i,{disableLineNumbers:!0})),this.renderDiffEnhancement=r.renderDiff??wBt,this.registerImage=r.registerImage,this.clearImages=r.clearImages,this.streaming=new yY((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))}get compactTools(){return this.store.minimalMode||this.store.toolOutputHidden}renderTranscript(e){return mre(this.projectMessages(e.messages),e.emptyChatHint,e.hasOlderMessages,e.sessions,e.models.some((t)=>t.configured),e.sessionCatalogLoading,e.minimalMode||e.toolOutputHidden)}renderMessageElement(e){let t=this.store.transcript.getMessage(e);if(!t)return;return fre(this.project(t),this.compactTools)}messageAppended(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(this.presentation.set(e,{renderedHtml:wY(t.role)&&t.text.trim()?mx(t.text,{cacheKey:e}):void 0,presentationState:wY(t.role)?"streaming":"plain",presentationVersion:0}),t.role==="tool"&&(t.state!=="running"||WEe(t)==="title"))this.enqueueEnhancement(e)}messageUpdated(e){if(!this.store.transcript.getMessage(e))return;gx(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.queue.cancelAll();for(let t of this.presentation.keys())gx(t);this.presentation.clear();for(let t of this.store.messages)if(this.messageAppended(t.id),WEe(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=A4n([e.thoughtId,e.assistantId]);this.flushMessages(t);for(let n of t)this.deferEnhancement(n)}transcriptReplacing(){this.clearScheduledMessages(),this.queue.cancelAll();for(let e of this.store.transcript.allMessages)gx(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)}dropMessages(e){for(let t of e)this.presentation.delete(t),gx(t),bee(this.imageUrls,`${t}:`)}enqueueEnhancement(e){if(!this.store.transcript.isMessageVisible(e))return;let t=this.store.transcript.getMessage(e),n=t?this.project(t):void 0,r=n?WEe(n):void 0,a=t?this.ensure(e):void 0;if(!t||!r||!a||r==="markdown"&&this.streamingIds().includes(e)||r!=="title"&&!t.text.trim()||a.presentationState==="enhancing"||a.presentationState==="final")return;let{text:i,format:o}=t,s=a.presentationVersion;a.presentationState="enhancing",this.queue.enqueue({priority:this.store.transcript.getMessageIndex(e)??0,run:async(c)=>{if(await zC("bash"),c.aborted)return;if(!this.store.transcript.isMessageVisible(e))return;let u=await this.renderEnhancement(r,i,e);if(c.aborted)return;let l=this.store.transcript.getMessage(e);if(!l||l.text!==i||l.format!==o||!this.store.transcript.isMessageVisible(e))return;let d=this.ensure(e);if(d.presentationVersion!==s)return;let p=r==="markdown"&&d.renderedHtml===u;if(d.renderedHtml=u,d.presentationState="final",gx(e),!p)this.broadcast(l)},onCancel:()=>gx(e),onError:(c)=>{if(!this.store.transcript.isMessageVisible(e))return;let u=this.store.transcript.getMessage(e),l=this.ensure(e);if(u?.text===i&&u.format===o&&l.presentationVersion===s)l.presentationState="plain",gx(e);console.warn(`Failed to enhance message ${e}`,c)}})}streamingIds(){return A4n([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()?mx(t.text,{cacheKey:e}):void 0,presentationState:"streaming",presentationVersion:0})}patchScheduledMessage(e){let t=this.store.transcript.getMessage(e);if(!t)return;if(wY(t.role)&&t.text.trim()){let n=this.ensure(e);n.renderedHtml=mx(t.text,{cacheKey:e}),n.presentationState="streaming"}if(this.broadcast(t),t.role==="tool"&&(t.state!=="running"||WEe(t)==="title"))this.enqueueEnhancement(e)}project(e){let t=this.ensure(e.id),n=this.activitySummary(e);if(wY(e.role)&&e.text.trim()&&t.renderedHtml===void 0)t.renderedHtml=mx(e.text,{cacheKey:e.id});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}),...p4n(i.data)},this.imageUrls.set(o,s);let c={mimeType:i.mimeType,url:s.url};if(s.width!==void 0&&s.height!==void 0)c.width=s.width,c.height=s.height;return{...r,image:c}}),...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,a=0;while(r>0){let i=t[r-1];if(i.role!=="thought"&&i.role!=="tool")break;if(r-=1,i.role==="tool")a+=1}if(a===0)return;return{stepCount:a,duration:k3a(e.timestamp.getTime()-t[r].timestamp.getTime())}}broadcast(e){this.patchMessage(fre(this.project(e),this.compactTools),`#message-${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,n){if(e==="title")return;if(e==="markdown")return await Jr.measure("markdownEnhancement",()=>this.renderMarkdownEnhancement(t,{cacheKey:n}));let r=Jr.startSpan("toolEnhancement");try{if(e==="diff")return await this.renderDiffEnhancement(t)??await qQt(t,"diff",{chrome:!1});return await this.renderCodeEnhancement(t,"bash")}finally{r()}}}var E3a;var m4n=I(()=>{bC();det();ave();Bee();ure();hre();E3a=new Set(["assistant","thought","compaction","summary","skill"])});class met{store;hub;messages;view={sessionQuery:"",slashQuery:"",workspaceSearch:{query:"",results:[]}};commits=new yY(()=>this.flush());fullViewPending=!1;pendingEffects=[];pendingEnhancements=new Set;transcriptPending=!1;compactTools;sidebarLayout="";constructor(e,t,n={}){this.store=e;this.hub=t;this.messages=new Aet(e,(r,a)=>{if(!this.transcriptPending)t.patchElement(r,a)},(r)=>this.pendingEnhancements.add(r),n),this.compactTools=this.messages.compactTools,e.attachPresentation(this)}createStream(e,t="",n="",r=""){this.commits.flush();let a=this.view;a.sessionQuery=t,a.slashQuery=r,a.workspaceSearch={query:n,results:[]};let i=()=>{if(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 o=this.store.snapshot();this.sidebarLayout=mDe(o);let s=this.messages.renderTranscript(o)+this.renderView(o,a)+hae(o);if(n.trim())queueMicrotask(()=>{this.setWorkspaceSearch(n)});if(this.hub.clientCount===1)queueMicrotask(()=>{if(this.hub.clientCount===0)return;for(let c of o.messages.toReversed())this.messages.enqueueEnhancement(c.id)});return{elements:s,signals:this.renderSignals(o)}},{onDisconnect:i})}catch(o){throw i(),o}}setSessionSearch(e){if(this.view.sessionQuery===e)return;this.view.sessionQuery=e,this.viewChanged()}setSlashSearch(e){if(this.view.slashQuery===e)return;this.view.slashQuery=e,this.viewChanged()}async setWorkspaceSearch(e){let t={query:e,results:[]};this.view.workspaceSearch=t;let n=await m8n(this.store.workspacePath,e);if(this.view.workspaceSearch!==t)return;t.results=n,this.viewChanged()}viewChanged(){this.fullViewPending=!0,this.requestCommit()}requestCommit(e){if(e?.type==="render-transcript")this.transcriptPending=!0;else if(e)this.pendingEffects.push(e);this.commits.schedule(!0)}flush(){let e=this.pendingEffects;this.pendingEffects=[];let t=this.fullViewPending;this.fullViewPending=!1;let n=[...this.pendingEnhancements];this.pendingEnhancements.clear();let r=this.compactTools!==this.messages.compactTools;if(this.compactTools=this.messages.compactTools,this.hub.clientCount>0){let a=Jr.measureSync("stateSnapshot",()=>this.store.snapshot());if(this.transcriptPending||r||t&&a.messages.length===0)this.hub.patchElement(Jr.measureSync("transcriptRender",()=>this.messages.renderTranscript(a)),"#messages",{scripts:["window.piUi.messageScroll.checkOlder()"]});let i=mDe(a),o=i!==this.sidebarLayout;if(t||o)this.sidebarLayout=i,this.hub.patchElement(Jr.measureSync("sidebarRender",()=>hae(a)),"#session-sidebar-content",{useViewTransition:o,viewTransitionSelector:"#session-sidebar-viewport"});this.hub.patchView(()=>Jr.measureSync("viewRender",()=>t?this.renderView(a,this.view):this.renderAppElements(a)),Jr.measureSync("signalRender",()=>this.renderSignals(a,this.effectSignalOverrides(e))),this.effectScripts(e))}if(this.transcriptPending=!1,this.hub.clientCount>0)for(let a of n)this.messages.enqueueEnhancement(a)}messageAppended(e){if(this.hub.clientCount===0)return;this.messages.messageAppended(e),this.requestCommit({type:"render-transcript"})}messagesRemoved(e){this.messages.dropMessages(e),this.hub.patchElement("",`#message-list > :nth-child(-n+${e.length} of .message[id])`,{mode:"remove"}),this.hub.patchElement(gre(this.store.hasOlderMessages),"#older-messages-trigger")}messageUpdated(e){if(this.hub.clientCount===0)return;this.messages.messageUpdated(e)}codeThemeChanged(){if(this.hub.clientCount>0)this.messages.codeThemeChanged();else this.messages.transcriptReplacing();this.transcriptPending=!0,this.requestCommit()}streamingMessageStarted(e){if(this.hub.clientCount===0)return;this.messages.streamingMessageStarted(e),this.requestCommit({type:"render-transcript"})}streamingMessageChanged(){if(this.hub.clientCount===0)return;this.messages.streamingMessageChanged()}sessionTransitionChanged(e){this.requestCommit(e?{type:"scroll-transcript-bottom"}:void 0),this.commits.flush()}assistantFinished(e){if(this.hub.clientCount===0)return;this.messages.assistantFinished(e)}transcriptReplacing(){this.transcriptPending=!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;if(e.length>0)this.hub.executeScript("window.piUi.messageScroll.beforeOlder()"),this.hub.patchElement(e.map(({id:t})=>this.messages.renderMessageElement(t)).join(""),"#older-messages-trigger",{mode:"after",scripts:["window.piUi.messageScroll.afterOlder()"]});if(!this.store.hasOlderMessages)this.hub.patchElement(gre(!1),"#older-messages-trigger");for(let t of e.toReversed())this.messages.enqueueEnhancement(t.id)}projectState(e){return{...e,messages:this.messages.projectMessages(e.messages)}}renderAppElements(e){return`<title id="document-title">${Bun.escapeHTML(e.documentTitle)}</title>`+kae(e)+xDe(e)+Dae(e)+Aae(e)+bF(e,"aboveEditor")+bF(e,"belowEditor")+xae(e)+HY(e)+FZ(e)}renderPickerElements(e,t){return aZ(e.authDialog)+jZ(e.extensionDialog)+LZ(e.llamaDialog)+Cae(e)+Bae(e)+yae(e,t?.slashQuery)+Tae(e)}renderSignals(e,t={}){return JSON.stringify({...DZ(e),...t})}renderView(e,t){let n=t?.sessionQuery??"";return this.renderAppElements(e)+this.renderPickerElements(e,t)+wae(e,t?.workspaceSearch.query,t?.workspaceSearch.results)+yDe(n.trim()?{...e,sessions:this.store.searchSessions(n),sessionsHasMore:!1}:e,n)+jMt(e.workspacePath,e.workspaceFilesRevision,e.workspaceTreeRevision,e.workspaceReview,e.workspaceReviewPreferences)}effectSignalOverrides(e){let t={};for(let n of e)if(n.type==="signal-overrides")Object.assign(t,n.values);return t}effectScripts(e){let t=new Set;for(let n of e){if(n.type==="scroll-transcript-bottom")t.add("window.piUi.messageScroll.scrollBottom()");if(n.type==="open-tree-dialog")t.add("{ const dialog = document.getElementById('tree-dialog'); if (dialog && !dialog.open) dialog.showModal(); }")}return[...t]}}var g4n=I(()=>{bC();sXe();det();tBe();vBe();QBe();DBe();wDe();RBe();m4n();hre();hF();EDe();_De();w5();CDe();gae();bae();Wv();QDe();DDe();VDe()});import{existsSync as B3a}from"fs";async function h4n(e=fetch,t=TY){let n=await I3a(e);if(!n)return;if(_Ze(n,t)!==1)return;return{currentVersion:t,latestVersion:n,releaseUrl:`${x3a}${n}`,upgradeCommand:v3a()}}async function I3a(e){try{let t=await e(C3a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(_3a)});if(!t.ok)return;let n=await t.json(),r=rm(n)?.version;return zn(r)?r:void 0}catch{return}}function v3a(e=process.platform,t=process.execPath,n=process.argv[1]??"",r=B3a("/etc/arch-release")){if(e==="win32")return"irm https://pi-ui.app/install.ps1 | iex";if(Q3a(t))return"brew upgrade hyperpuncher/tap/pi-ui";if(f4n(t)||f4n(n))return"bun i -g @hyperpuncher/pi-ui";if(e==="linux"&&r)return"paru -S pi-ui-bin";return"curl -fsSL https://pi-ui.app/install | sh"}function Q3a(e){return/[\\/](?:Cellar|homebrew)[\\/]/i.test(e)}function f4n(e){return/[\\/]node_modules[\\/]|[\\/]\.bun[\\/]install[\\/]/i.test(e)}var C3a="https://registry.npmjs.org/@hyperpuncher/pi-ui/latest",x3a="https://github.com/hyperpuncher/pi-ui/releases/tag/v",_3a=3000;var b4n=I(()=>{vwe();pke()});var y4n={};Ke(y4n,{createApp:()=>R3a});import{realpath as S3a,stat as D3a}from"fs/promises";async function R3a(){let e=ZB("fd",({message:k})=>console.error(k)),t=await s4n(l4n),n=await iFt();nnt(tnt(n.keybinds));let r=Art(n.codeTheme)??mrt(),a=Ytt(n.fonts)??Jtt(),i=P3n(n.autoTitle),o=D4(n.gitView),s=rZ(n.sessionSidebar);eZ(r),ZY(a);let c=zC("bash"),u=new cDe;if(u.theme=n.theme==="light"||n.theme==="dark"?n.theme:"system",u.keybindHints=n.keybindHints!==!1,u.minimalMode=n.minimalMode===!0,u.toolOutputHidden=n.toolOutputHidden===!0,u.toolbarHidden=n.toolbarHidden===!0,u.sessionSidebarOpen=s.open!==!1,u.sessionSidebarWidth=s.width??D0,u.sessionSidebarArchive=s.archive!==!1,u.sessionSidebarArchiveAfterDays=s.archiveAfterDays??nZ,n.updateCheck!==!1&&process.env.PI_UI_NO_UPDATE_CHECK!=="1")h4n().then((k)=>{if(k)u.setUpdateAvailable(k)});u.setWorkspaceReviewPreferences(o);let l=new tXe,d=new qEe,p=new qEe,A=(k)=>a4n(p,k),m=new met(u,d,{registerImage:(k)=>l.register(k),clearImages:()=>l.clear()}),h=new g4((k)=>u.setSessionTransition(k)),f=await o4.create(u,void 0,{autoTitle:i,notifySessionDone:A,transitionController:h}).catch((k)=>{console.error("Failed to start pi SDK runtime",k);return});if(!await c)console.error("Failed to preload tool highlighter");let g=new uet(u);g.open(u.workspacePath);let b=await e,y={host:f,sessionImages:l,fdPath:b},w=await bEe.create(),E={store:u,renderer:m,notificationClients:p,resources:y,transferredFiles:w,appVersion:t.version,themeLab:process.env.PI_UI_THEME_LAB==="1",serveStatic:(k)=>t.serve(k),openWorkspace:(k)=>T3a(k,u,y,h,i,A)},B;return{context:E,dispose:()=>(B??=(async()=>{g.dispose(),await Promise.allSettled([w.dispose(),y.host?.dispose()])})(),B)}}async function T3a(e,t,n,r,a,i){let o=e.trim();return(await r.run(o,async()=>{let c=await S3a(ak(o));if(!(await D3a(c)).isDirectory())throw Error("Not a directory");if(!n.host)return n.host=await o4.create(t,c,{autoTitle:a,notifySessionDone:i,refreshWorkspaces:!1,transitionController:r}),!0;return await n.host.openWorkspace(c)},{overlay:!1})).status==="success"}var w4n=I(()=>{DJ();TXe();r4n();f4();MZ();zR();Ib();vb();Mx();i4n();c4n();u4n();yEe();d4n();KR();lae();Bee();g4n();b4n();Tf();BC()});var C4n={};Ke(C4n,{compressResponse:()=>G3a});import{Readable as M3a}from"stream";import{constants as zEe,createBrotliCompress as F3a,createGzip as j3a,createZstdCompress as L3a}from"zlib";function G3a(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 U3a(e,t);if(e.method==="HEAD"||e.headers.has("range")||t.status===206||t.headers.has("content-range")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||!n||!H3a(n))return t;let r=t.headers.get("content-length");if(r&&Number(r)<$3a)return t;let a=new Headers(t.headers);a.set("vary",B4n(a.get("vary"),"Accept-Encoding"));let i=E4n(e.headers.get("accept-encoding"));if(!i)return q3a(t,a);return k4n(t,a,i)}function U3a(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=E4n(e.headers.get("accept-encoding"));if(!n)return t;let r=new Headers(t.headers);return r.set("vary",B4n(r.get("vary"),"Accept-Encoding")),k4n(t,r,n,n)}function E4n(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((A)=>A.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 P3a){let o=t.get(i)??n;if(o>a)r=i,a=o}return r}function k4n(e,t,n,r){let a=e.body;if(!a)return e;let i=W3a(n);z3a(a.getReader(),i,r),t.set("content-encoding",n),t.delete("content-length");let o=M3a.toWeb(i);return new Response(o,{status:e.status,statusText:e.statusText,headers:t})}function q3a(e,t){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function H3a(e){return e.startsWith("text/")||e==="image/svg+xml"||O3a.has(e)||e.endsWith("+json")||e.endsWith("+xml")}function W3a(e){switch(e){case"zstd":return L3a();case"br":return F3a({params:{[zEe.BROTLI_PARAM_QUALITY]:6}});case"gzip":return j3a()}}async function z3a(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"?N3a:o.length;for(let c=0;c<o.length;c+=s)if(await J3a(t,o.subarray(c,c+s)),n)await K3a(t,n)}if(!t.destroyed)await Y3a(t)}catch(i){if(await e.cancel(i).catch(()=>{}),!t.destroyed)t.destroy(Error.isError(i)?i:Error(String(i)))}finally{t.off("close",a),e.releaseLock()}}function J3a(e,t){return new Promise((n,r)=>{e.write(t,(a)=>a?r(a):n())})}function K3a(e,t){let n={zstd:zEe.ZSTD_e_flush,br:zEe.BROTLI_OPERATION_FLUSH,gzip:zEe.Z_SYNC_FLUSH}[t];return new Promise((r)=>e.flush(n,r))}function Y3a(e){return new Promise((t)=>e.end(t))}function B4n(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 P3a,N3a=4096,$3a=1024,O3a;var x4n=I(()=>{P3a=["zstd","br","gzip"],O3a=new Set(["application/javascript","application/json","application/manifest+json","application/xhtml+xml","application/xml"])});async function v4n(e){let t=await S4n(),n=e.method==="GET"?await t.app.context.serveStatic(e):FE(404,"Not found.");return t.compressResponse(e,n)}async function Q4n(){await(await _4n?.catch(()=>{return}))?.app.dispose()}function Z3a(e){return async(t,n)=>{let r=await S4n();return r.compressResponse(t,await ktt(t,{...r.app.context,clientAddress:n.requestIP(t)?.address},e))}}function S4n(){return _4n??=V3a()}async function V3a(){let[{registerBunOAuthFlows:e},{createApp:t},{compressResponse:n}]=await Promise.all([Promise.resolve().then(() => (L3n(),j3n)),Promise.resolve().then(() => (w4n(),y4n)),Promise.resolve().then(() => (x4n(),C4n))]);return e(),{app:await t(),compressResponse:n}}var _4n,I4n;var D4n=I(()=>{gu();bp();B8n();I4n=Object.fromEntries(Object.entries(k8n).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([n,r])=>[n,Z3a(r)]))]))});import{userInfo as u6n}from"os";var d6n="printf '\\0'; command env -0; printf '\\0'";async function $et(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??u6n().shell;if(!a)return;let i=await(e.readOutput??p6n)(a,t);if(i!==void 0)Object.assign(t,A6n(i))}async function p6n(e,t){try{let n=Bun.spawn([e,"-ilc",d6n],{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 A6n(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}Uv();import{mkdir as m6n}from"fs/promises";import{homedir as g6n}from"os";import{dirname as f6n}from"path";var PR="pi-ui",u4="pi-ui-server",cke="dev.pi.ui",Oet="dev.pi.ui.server",Get="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";function Uet(e=Md,t=C6n()){if(e!=="linux"&&e!=="darwin"&&e!=="windows")throw Error(`server autostart is not supported on ${e}`);let n=g6n();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?x6n(r):!1}}async function qet(e=Uet()){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 w6n(e);break;case"darwin":await E6n(e);break;case"windows":await k6n(e);break}}async function Het(e=Uet()){switch(e.platform){case"linux":await ake(e,PR),await ake(e,u4),await nm("systemctl",["--user","daemon-reload"]);break;case"darwin":await ike(e,cke),await ike(e,Oet);break;case"windows":await B6n(e);break}}function h6n(e){return`[Unit]
|
|
3753
3753
|
Description=pi-ui server
|
|
3754
3754
|
After=graphical-session.target
|
|
3755
3755
|
PartOf=graphical-session.target
|
package/package.json
CHANGED
package/static/build/main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{ee,e,de,H,x,u,y}from"./chunks/main-tan9pwk6.js";de(import.meta.url,["
|
|
2
|
-
var he={};ee(he,{canSubmit:()=>ue,composePrompt:()=>Je,convertAvifToJpeg:()=>Ge,enterDrag:()=>tn,extractTransferredFilePaths:()=>Ve,fileWithDetectedMimeType:()=>We,formatFileReferences:()=>_e,hasAttachments:()=>Ke,hasFiles:()=>Qt,insert:()=>$e,isAvifImageFile:()=>fe,isHeicImageFile:()=>me,jpegFileName:()=>ze,leaveDrag:()=>nn,pick:()=>en,resetDrag:()=>on,submit:()=>rn});async function X(t){try{return await navigator.clipboard.writeText(t),!0}catch{return!1}}function xe(){document.addEventListener("click",xt)}async function xt(t){let n=t.target;if(!(n instanceof Element))return;let o=n.closest("[data-copy-code]");if(!(o instanceof HTMLButtonElement))return;let r=o.closest("[data-code-block]"),i=r?.querySelector("code"),s=r?.getAttribute("data-code-source")||i?.textContent;if(!s)return;if(!await X(s)){o.setAttribute("aria-label","Copy failed");return}o.dataset.copyState="copied",o.setAttribute("aria-label","Copied"),setTimeout(()=>{delete o.dataset.copyState,o.setAttribute("aria-label","Copy code")},1200)}var Te=new Set(["ArrowDown","ArrowUp","Home","End"]),Tt=new Set(["ArrowDown","ArrowUp"]);function Ae(){document.addEventListener("keydown",kt),document.addEventListener("mousemove",Ct),document.addEventListener("click",It),Z()}function Z(t=document){for(let n of At(t,".command"))St(n)}function At(t,n){let o=[];if(!t)return o;if(t instanceof Element&&t.matches(n))o.push(t);for(let r of t.querySelectorAll?.(n)??[])o.push(r);return o}function Q(t){return{input:t.querySelector("search input"),menu:t.querySelector('[role="listbox"], [role="menu"]')}}function Mt(t){return[...t.querySelectorAll('[role="option"], [role="menuitem"]')].filter((n)=>n instanceof HTMLElement&&!Se(n))}function te(t){let{menu:n}=Q(t);if(!(n instanceof HTMLElement))return[];return Mt(n).filter((o)=>!o.hidden)}function St(t){let{input:n,menu:o}=Q(t);if(!(n instanceof HTMLInputElement)||!(o instanceof HTMLElement))return;o.scrollTop=0,P(t,te(t)[0])}function P(t,n){let{input:o,menu:r}=Q(t);if(!(o instanceof HTMLInputElement)||!(r instanceof HTMLElement))return;for(let i of r.querySelectorAll('[role="option"].active, [role="menuitem"].active'))i.classList.remove("active");if(n instanceof HTMLElement)if(n.classList.add("active"),n.id)o.setAttribute("aria-activedescendant",n.id);else o.removeAttribute("aria-activedescendant");else o.removeAttribute("aria-activedescendant")}function Lt(t,n){let o=te(t);if(o.length===0)return;let r=o.findIndex((a)=>a.classList.contains("active")),i=r;if(n==="ArrowDown")i=Math.min(r+1,o.length-1);if(n==="ArrowUp")i=Math.max(r<0?0:r-1,0);if(n==="Home")i=0;if(n==="End")i=o.length-1;let s=o[i];P(t,s),s?.scrollIntoView({block:"nearest"})}function Me(t){return[...t.querySelectorAll('[role^="menuitem"]')].filter((n)=>n instanceof HTMLElement&&!Se(n))}function Pt(t,n){let o=Me(t);if(o.length===0)return;let r=o.indexOf(document.activeElement),i=r;if(n==="ArrowDown")i=Math.min(r+1,o.length-1);if(n==="ArrowUp")i=r<0?o.length-1:Math.max(r-1,0);if(n==="Home")i=0;if(n==="End")i=o.length-1;o[i]?.focus({preventScroll:!0})}function kt(t){if(!(t.target instanceof Element))return;let n=t.target.closest(".command");if(n instanceof HTMLElement&&t.target.matches("search input")){if(t.isComposing)return;if(t.key==="Enter"){let i=te(n).find((s)=>s.classList.contains("active"));if(i)t.preventDefault(),i.click();return}if(Te.has(t.key)){t.preventDefault(),Lt(n,t.key);return}}let o=t.target.closest("[popover][role='menu']");if(o instanceof HTMLElement){if(t.key==="Tab")o.hidePopover();if(Te.has(t.key))t.preventDefault(),Pt(o,t.key);return}if(!(t.target instanceof HTMLButtonElement))return;let r=t.target.popoverTargetElement;if(r?.matches("[popover][role='menu']")&&Tt.has(t.key)){t.preventDefault(),t.target.click();let i=Me(r);(t.key==="ArrowUp"?i.at(-1):i[0])?.focus({preventScroll:!0})}}function Ct(t){if(!(t.target instanceof Element))return;let n=t.target.closest('[role="option"], [role="menuitem"]')??t.target.closest("[data-command-row]")?.querySelector('[role="option"], [role="menuitem"]'),o=n?.closest(".command");if(o instanceof HTMLElement&&n instanceof HTMLElement){if(!n.hidden&&!n.classList.contains("active"))P(o,n);return}let r=t.target.closest('[role="option"]');if(r instanceof HTMLElement&&r.getAttribute("aria-selected")!=="true")Ft(r)}function Ft(t){let n=t.closest('[role="listbox"]');if(!(n instanceof HTMLElement))return;for(let r of n.querySelectorAll('[role="option"][aria-selected="true"]'))r.setAttribute("aria-selected","false");t.setAttribute("aria-selected","true"),document.querySelector(`[aria-controls="${CSS.escape(n.id)}"]`)?.setAttribute("aria-activedescendant",t.id)}function It(t){if(!(t.target instanceof Element))return;let n=t.target.closest('.command [role="option"], .command [role="menuitem"]');if(n instanceof HTMLElement&&!n.hasAttribute("commandfor")&&!n.hasAttribute("data-keep-command-open"))n.closest("dialog")?.close()}function Se(t){return t.hasAttribute("disabled")||t.getAttribute("aria-disabled")==="true"||t.getAttribute("data-disabled")==="true"}function Le(t){let n=new Date(t.dateTime);if(Number.isNaN(n.getTime()))return;t.textContent=H(n),t.title=x(n)}function Ht(){let t,n,o=[];return{reset(){t=void 0,n=void 0,o=[]},add(r){if(t===void 0){t=n=r;return}o.push(r-t),t=r;let i=r-n;if(i<1000)return;let s=o.sort((c,p)=>c-p),a=Math.floor(s.length/2),l={rate:o.length*1000/i,median:(s[a]+s[Math.floor((s.length-1)/2)])/2,p95:s[Math.ceil(s.length*0.95)-1],max:s.at(-1)};return o=[],n=r,l}}}function Pe(){let t=document.getElementById("debug-frame-rate");if(!t)return;let n=document.getElementById("debug-frame-median"),o=document.getElementById("debug-frame-p95"),r=document.getElementById("debug-frame-max"),i=Ht(),s;function a(c){let p=i.add(c);if(p)t.textContent=String(Math.round(p.rate)),n.textContent=p.median.toFixed(1),o.textContent=p.p95.toFixed(1),r.textContent=p.max.toFixed(1);s=requestAnimationFrame(a)}function l(){if(s!==void 0)cancelAnimationFrame(s);if(i.reset(),t.textContent=n.textContent=o.textContent=r.textContent="—",!document.hidden)s=requestAnimationFrame(a)}document.addEventListener("visibilitychange",l),l()}function k(t){try{let n=new URL(t);if(n.protocol!=="file:")return;let o=decodeURIComponent(n.pathname);if(n.hostname&&n.hostname.toLowerCase()!=="localhost")return`//${n.hostname}${o}`;if(/^\/[A-Za-z]:(?:\/|$)/.test(o))return o.slice(1);return o}catch{return}}function ke(){document.addEventListener("click",(t)=>{if(t.button!==0)return;let n=t.target instanceof Element?t.target.closest("a[href]"):null;if(!(n instanceof HTMLAnchorElement))return;let o=n.getAttribute("data-pi-file-link")??"",r=o?k(o):void 0,i=r===void 0?n.href:o;if((r??k(i))===void 0)return;t.preventDefault(),Bt(i)},{capture:!0})}async function Bt(t){let n=document.body.dataset.filesOpenEndpoint;if(!n)return;try{let o=await fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({uri:t})});if(!o.ok)throw Error(await y(o,"Could not open the file."));let r=await o.json();if(r.opened)return;let{openLinkedWorkspaceFile:i}=await (e("sc4yfzz9"),import("./chunks/workspace-review-sc4yfzz9.js"));await i(r.path,r.workspacePath)}catch(o){alert(Error.isError(o)?o.message:"Could not open the file.")}}var ne={archive:{paths:["M13.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v11.5","M14 2v5a1 1 0 0 0 1 1h5M8 12v-1m0 7v-2m0-9V6"],circle:{cx:8,cy:20,r:2}},audio:{paths:["M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3","M14 2v4a2 2 0 0 0 2 2h4M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0"]},code:{paths:["M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4","M14 2v4a2 2 0 0 0 2 2h4M5 12l-3 3l3 3m4 0l3-3l-3-3"]},file:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5"]},pdf:{paths:["M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4","M14 2v4a2 2 0 0 0 2 2h4M2 13v-1h6v1m-3-1v6m-1 0h2"]},text:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5M10 9H8m8 4H8m8 4H8"]},video:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5m-4.967 5.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56v-4.704a.645.645 0 0 1 .967-.56z"]}},qt=new Set(["aac","flac","m4a","mp3","ogg","wav"]),Dt=new Set(["avi","m4v","mkv","mov","mp4","webm"]),Ot=new Set(["7z","bz2","gz","rar","tar","xz","zip"]),Rt=new Set(["c","cpp","css","go","h","html","java","js","json","jsx","py","rs","sh","sql","toml","ts","tsx","xml","yaml","yml"]),Ut=new Set(["csv","log","md","rst","txt"]);function Ce(t){return Ie(t).slice(0,4)}function Fe(t,n){let o=Ie(t);if(n==="application/pdf"||o==="pdf")return"pdf";if(n?.startsWith("audio/")||qt.has(o))return"audio";if(n?.startsWith("video/")||Dt.has(o))return"video";if(n?.includes("zip")||Ot.has(o))return"archive";if(Rt.has(o)||n==="application/json"||n?.includes("javascript")||n?.includes("xml"))return"code";if(n?.startsWith("text/")||Ut.has(o))return"text";return"file"}function Ie(t){return t.match(/\.([^.]+)$/)?.[1].toLowerCase()??""}function m(){let t=document.getElementById("prompt-input");return t instanceof HTMLTextAreaElement?t:void 0}function M(t){let n=m();if(!n)return;n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}))}function oe(){if(!window.matchMedia("(hover: hover) and (pointer: fine)").matches)return;re()}function re(){let t=m();if(!t)return;t.focus({preventScroll:!0}),t.selectionStart=t.value.length,t.selectionEnd=t.value.length}var A,R=!1;function Nt(t,n){let o=t.slice(0,n),r=/(?:^|[\s"'=])(@(?:"[^"]*|[^\s"'=]*))$/.exec(o)?.[1];if(!r)return;return{start:n-r.length,end:n,query:r.slice(1)}}function $t(t,n,o){let r=o.endsWith("/")||o.endsWith('/"'),i=r?"":" ",s=t.slice(n.end),a=n.query.startsWith('"')&&o.endsWith('"')&&s.startsWith('"')?s.slice(1):s,l=`${t.slice(0,n.start)}${o}${i}${a}`,c=r&&o.endsWith('"')?1:0;return{text:l,cursor:n.start+o.length+i.length-c}}function C(){return De("prompt-file-popover")}function U(){return C()||qe()}function He(){document.addEventListener("input",Kt),document.addEventListener("click",Vt),document.addEventListener("keydown",jt),document.addEventListener("mousedown",(t)=>{if(t.button===0&&t.target instanceof Element&&t.target.closest("[data-picker-kind]"))t.preventDefault()}),document.addEventListener("focusout",(t)=>{if(t.target===m())v(!0)})}function Kt(t){if(t.target!==m()||t.isComposing)return;R=!1,ie(t.target)}function ie(t){if(R||document.activeElement!==t)return;let n=Nt(t.value,t.selectionStart);if(!n){se();return}if(A?.start===n.start&&A.end===n.end&&A.query===n.query)return;A=n,t.dispatchEvent(new CustomEvent("pi-ui-file-query",{bubbles:!0,detail:{query:n.query}}))}function Vt(t){let n=t.target;if(!(n instanceof Element))return;let o=n.closest('[data-picker-kind="slash"]'),r=n.closest('[data-picker-kind="file"]');if(n.closest("[data-file-trigger]"))t.preventDefault(),Wt();else if(n.closest("[data-send-trigger]")||o instanceof HTMLElement)v(!0);else if(r instanceof HTMLElement)t.preventDefault(),zt(r.dataset.pickerValue??"")}function jt(t){if(t.target!==m()||t.isComposing||t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||!U())return;if(t.code==="Escape"){t.preventDefault(),v(!0);return}let n=C()?"[data-file-row]":"[data-slash-row]";if(t.code==="ArrowDown"||t.code==="ArrowUp")t.preventDefault(),_t(n,t.code==="ArrowDown"?1:-1);else if(t.code==="Enter"||t.code==="Tab")t.preventDefault(),Oe(n)?.click()}function zt(t){let n=m();if(!n||!A)return;let o=$t(n.value,A,t);if(n.value=o.text,n.selectionStart=o.cursor,n.selectionEnd=o.cursor,n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus(),t.endsWith("/")||t.endsWith('/"'))ie(n);else se()}function Be(t){M(`/${t} `),re(),v()}function Wt(){let t=m();if(!t)return;R=!1;let n=t.selectionStart,r=`${n>0&&!/\s/.test(t.value[n-1]??"")?" ":""}@`;t.setRangeText(r,n,t.selectionEnd,"end"),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus(),ie(t)}function v(t=!1){se(t),m()?.dispatchEvent(new CustomEvent("pi-ui-picker-close",{bubbles:!0}))}function se(t=!1){if(t)R=!0;A=void 0;let n=m();n?.dispatchEvent(new CustomEvent("pi-ui-file-query",{bubbles:!0})),n?.dispatchEvent(new CustomEvent("pi-ui-file-close",{bubbles:!0}))}function qe(){return De("prompt-slash-popover")}function De(t){let n=document.getElementById(t);return n instanceof HTMLElement&&n.checkVisibility()}function ae(t){return document.querySelectorAll(t).values().filter((n)=>n instanceof HTMLElement&&n.checkVisibility()).toArray()}function Oe(t){let n=ae(t);return n.find((o)=>o.getAttribute("aria-selected")==="true")??n[0]}function Gt(t,n,o){if(t<=0)return-1;if(n===-1)return 0;return Math.max(0,Math.min(t-1,n-o))}function _t(t,n){let o=ae(t);if(o.length===0)return;let r=o.findIndex((s)=>s.getAttribute("aria-selected")==="true"),i=Gt(o.length,r,n);for(let s of o)s.setAttribute("aria-selected","false");o[i]?.setAttribute("aria-selected","true"),o[i]?.scrollIntoView({block:"nearest",behavior:"instant"}),ce()}function ce(t=!1){queueMicrotask(()=>{let n=m();if(!n)return;let o=C()?"file-picker-list":qe()?"slash-picker-list":void 0;if(t&&o){document.getElementById(o).scrollTop=0;for(let[i,s]of ae(`#${o} [role="option"]`).entries())s.setAttribute("aria-selected",i===0?"true":"false")}let r=o&&Oe(`#${o} [role="option"]`);if(r&&document.activeElement===n)r.setAttribute("aria-selected","true"),n.setAttribute("aria-controls",o),n.setAttribute("aria-activedescendant",r.id);else n.removeAttribute("aria-controls"),n.removeAttribute("aria-activedescendant")})}var Jt=["text/uri-list","x-special/gnome-copied-files","text/plain"],Re=10,Yt=20971520,Xt=52428800,Zt=0.85,F=0,le=!1,g=[];function Qt(t){if(!t)return!1;if(t.files?.length)return!0;return t.types.includes("Files")||t.types.includes("text/uri-list")}function en(){h("");let t=document.createElement("input");t.type="file",t.multiple=!0,t.addEventListener("change",()=>{if(t.files?.length)$e(t.files)},{once:!0}),t.click()}function tn(){return F+=1,!0}function nn(){return F=Math.max(0,F-1),F>0}function on(){F=0}async function $e(t){if(!t)return;h("");let n=je(t),o=n.some((c)=>fe(c)||me(c)),r=Ve(t);if(r.length>0&&!o){let c=an(r);if(c){h(c);return}un(r);return}if(n.length===0)return;let i=Ue(n);if(i){h(i);return}let s;try{s=await sn(n)}catch(c){console.error(c),h(c?.message||"Could not prepare the selected images.");return}let a=Ue(s);if(a){h(a);return}let l=await ln(s);for(let c=0;c<l.length;c+=1)Ye({path:l[c].path,file:We(s[c],l[c].mimeType)})}function Ke(){return g.length>0}function ue(t){return!le&&(t.trim()!==""||Ke())}async function rn(t,n,o){if(!ue(n))return!1;let r=[...g],i=Je(n,r.map(({path:a})=>a)),s=new FormData;if(s.set("prompt",i),o)s.set("streamingBehavior",o);for(let{file:a}of r)if(a?.type.startsWith("image/"))s.append("image",a,a.name||"pasted-image");le=!0;try{let a=await fetch(t,{method:"POST",body:s});if(await a.text(),!a.ok)throw Error(`Prompt was not accepted (${a.status}).`);return fn(r),h(""),!0}catch(a){return dn(n),h(a?.message||"Could not send the prompt."),!1}finally{le=!1,document.getElementById("prompt-box")?.dispatchEvent(new CustomEvent("pi-ui-prompt-submit-finished",{bubbles:!0})),pe()}}function Ve(t){let n="getData"in t?Jt.flatMap((r)=>t.getData(r).split(/\r?\n/)):[];for(let r of je(t))n.push(r.path??"",r.webkitRelativePath??"");let o=new Set(n.map(cn));return o.delete(void 0),[...o]}function je(t){if(t.files)return[...t.files];return Array.from(t)}function fe(t){return t.type?.toLowerCase()==="image/avif"||/\.avif$/i.test(t.name??"")}function me(t){return/^(?:image\/)?hei[cf]$/i.test(t.type??"")||/\.hei[cf]$/i.test(t.name??"")}function ze(t){return/\.avif$/i.test(t)?t.replace(/\.avif$/i,".jpg"):`${t||"image"}.jpg`}function We(t,n){if(n===void 0||t.type===n)return t;return new File([t],t.name,{type:n??"",lastModified:t.lastModified})}function sn(t){return Array.fromAsync(t,(n)=>{if(me(n))throw Error("HEIC and HEIF images are not supported. Convert them to JPEG or PNG first.");return fe(n)?Ge(n):n})}async function Ge(t){let n;try{n=await createImageBitmap(t);let o=document.createElement("canvas");o.width=n.width,o.height=n.height;let r=o.getContext("2d");if(!r)throw Error("Canvas image conversion is unavailable.");r.fillStyle="white",r.fillRect(0,0,o.width,o.height),r.drawImage(n,0,0,o.width,o.height);let i=await new Promise((s,a)=>{o.toBlob((l)=>l?s(l):a(Error("JPEG encoding failed.")),"image/jpeg",Zt)});return new File([i],ze(t.name),{type:"image/jpeg",lastModified:t.lastModified})}catch(o){throw Error(`Could not convert ${t.name||"the AVIF image"} to JPEG.`,{cause:o})}finally{n?.close()}}function an(t){if(t.some((n)=>/\.hei[cf]$/i.test(n)))return"HEIC and HEIF images are not supported. Convert them to JPEG or PNG first.";if(t.some((n)=>/\.avif$/i.test(n)))return"AVIF images must be dropped, pasted, or selected with the browser file picker so they can be converted."}function cn(t){let n=t.trim();if(!n||n.startsWith("#")||n==="copy"||n==="cut")return;let o=k(n);if(o)return o;if(n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n))return n;return}function Ue(t){if(t.length>Re)return`Attach at most ${Re} files at a time.`;let n=0;for(let o of t){if(o.size>Yt)return"Dropped or pasted files must be 20 MiB or smaller; use the Files button for larger files.";n+=o.size}if(n>Xt)return"Dropped or pasted files must total 50 MiB or less."}async function ln(t){let n=new FormData;for(let o of t)n.append("file",o,o.name||"pasted-file");try{let o=document.body.dataset.filesImportEndpoint,r=await fetch(o,{method:"POST",body:n}),i=await r.json().catch(()=>({}));if(!r.ok)return h(u(i.message)?i.message:"Could not transfer the selected files."),[];return h(""),Array.isArray(i.imports)?i.imports:[]}catch{return h("Could not transfer the selected files."),[]}}function h(t){let n=m();if(!n)return;let o=document.getElementById("file-transfer-error");if(!(o instanceof HTMLParagraphElement))o=document.createElement("p"),o.id="file-transfer-error",o.className="file-transfer-error",o.setAttribute("role","alert"),o.setAttribute("aria-live","polite"),n.before(o);o.textContent=t,o.hidden=!t}function _e(t){return`${t.map((n)=>`@${n}`).join(`
|
|
1
|
+
import{ee,e,de,H,x,u,y}from"./chunks/main-tan9pwk6.js";de(import.meta.url,["50w124px","sc4yfzz9","q8ytkktk","vm8gqreq","tan9pwk6","1njw3bhj","jnny2wvt","kp2q2m10","y3pra3sz","tpb91x6n","j043hr0y","jxxcae4s","qk7a6yqw","zdncvbbq","ksscxt51","8fcm1mvt","9nxespbm","93n0yege","06e2nv03","gxb5srgm","5barcpw8","8x83g358","6gb86a0d","7fwrfh74","3em138qf","wp500gq1","nknyxfxy","eb2am5x1","z3j5w6rx","5jadr7kg","9r0ckba5","7ce95fs8","5xx43938","rcrka58h","ywjxksww","jt18dkfd","fjafvtft","ay9qb384","wrbv1ehn","ys1cr5m1","e1vq84p1","p0xtkjcq","1s5w6vg5","9kdrynsa","5mtfg3dp","015c376k","5588d3zy","enf70ntg","ppgd3znr","nxvznjva","mbgxwth0","tqt2pskq","18jh4rmk","t2j0qk96","knt9ds0k","vgqbqnpv","914016cj","9t6b705s","sdv10jrj","cy4jx512","m8at7yx7","4fc9ntns","5q94k618","d1yfc7p8","8cd74ewt","mm6673p6","mq5awb4z","kt7rv59v","mv0k79bd","ghd075yb","v3ystkk5","vzvzpezs","znmj0d2m","p8aygbzx","f8vwt6tn","f5skm0s6","dvs8g9s9","hg031v40","hcqns3mt","kfyv50pr","4f2kgqvy","s9tqbsvc","x4vh9x60","wg0jqvm9","4mgfqqv0","w7sqrdqg","xbst0r6r","bte48x46","xc0vwsv5","kmbwnbg0","k9hmefys","qbe60h0e","ykgm42k6","s2tjqac1","chfr1dky","nn8msg3q","626rys45","b1zh65yc","fyjsk51f","tacx30ck","tj3b94mt","a5znxv0j","4jt80rb3","30ehh77t","bk3cvzvs","h102ytjk","3a5asyhw","sbmr4d39","0p37dqhe","8003tffz","th51yc2v","xyfaz8my","ckwy3eca","vhqnt3mv","8q0xtee6","nhqrbrbc","8x3dzepx","q3pe707k","t39papy0","3skg33fz","75v2e0z7","pbfh6xmb","shk74frp","hs8bjf78","1zp201y9","5r4ghtv4","djkvncyh","4dm5z5gz","5fv3834p","xwa8jjky","fs9vxzcr","e78k91wj","27pzh9h4","bzh90507","v2dc377y","y1c4jvva","ebx8qzp1","p7mfec7n","3d3j7q8a","h7ytmqc1","ny5zfg3e","9212jnfg","5v8f6wjy","r11td6rr","9ncba8pj","6xym75kt","bn1j7t5a","kbpz0qam","1bjn4cgw","yt916yx8","jte12g1m","q0yvybq5","9c66kxde","wv0n2pm7","dtyyn81w","p076c381","kr23demp","yrwp6405","ezf6pef0","ncea79rq","wz3vyvnp","0g1trpbb","x66a8fp4"],[["./main.js",4],["./chunks/workspace-review-sc4yfzz9.js",6,4],["./chunks/fonts-q8ytkktk.js"],["./chunks/code-theme-vm8gqreq.js",6],["./chunks/main-tan9pwk6.js"],["./chunks/index-1njw3bhj.js",6,7,4],["./chunks/main-jnny2wvt.js",4],["./chunks/main-kp2q2m10.js"],["./chunks/themes-y3pra3sz.js",6,4],["./chunks/highlights-tpb91x6n.js",6,87],["./chunks/shiki-j043hr0y.js",6,87,7],["./chunks/loader-jxxcae4s.js",4],["./chunks/solarized-dark-qk7a6yqw.js"],["./chunks/solarized-light-zdncvbbq.js"],["./chunks/synthwave-84-ksscxt51.js"],["./chunks/tokyo-night-8fcm1mvt.js"],["./chunks/vesper-9nxespbm.js"],["./chunks/vitesse-black-93n0yege.js"],["./chunks/vitesse-dark-06e2nv03.js"],["./chunks/vitesse-light-gxb5srgm.js"],["./chunks/poimandres-5barcpw8.js"],["./chunks/red-8x83g358.js"],["./chunks/rose-pine-6gb86a0d.js"],["./chunks/rose-pine-dawn-7fwrfh74.js"],["./chunks/rose-pine-moon-3em138qf.js"],["./chunks/slack-dark-wp500gq1.js"],["./chunks/slack-ochin-nknyxfxy.js"],["./chunks/snazzy-light-eb2am5x1.js"],["./chunks/min-light-z3j5w6rx.js"],["./chunks/monokai-5jadr7kg.js"],["./chunks/night-owl-9r0ckba5.js"],["./chunks/night-owl-light-7ce95fs8.js"],["./chunks/nord-5xx43938.js"],["./chunks/one-dark-pro-rcrka58h.js"],["./chunks/one-light-ywjxksww.js"],["./chunks/plastic-jt18dkfd.js"],["./chunks/laserwave-fjafvtft.js"],["./chunks/light-plus-ay9qb384.js"],["./chunks/material-theme-wrbv1ehn.js"],["./chunks/material-theme-darker-ys1cr5m1.js"],["./chunks/material-theme-lighter-e1vq84p1.js"],["./chunks/material-theme-ocean-p0xtkjcq.js"],["./chunks/material-theme-palenight-1s5w6vg5.js"],["./chunks/min-dark-9kdrynsa.js"],["./chunks/gruvbox-light-medium-5mtfg3dp.js"],["./chunks/gruvbox-light-soft-015c376k.js"],["./chunks/horizon-5588d3zy.js"],["./chunks/horizon-bright-enf70ntg.js"],["./chunks/houston-ppgd3znr.js"],["./chunks/kanagawa-dragon-nxvznjva.js"],["./chunks/kanagawa-lotus-mbgxwth0.js"],["./chunks/kanagawa-wave-tqt2pskq.js"],["./chunks/github-dark-high-contrast-18jh4rmk.js"],["./chunks/github-light-t2j0qk96.js"],["./chunks/github-light-default-knt9ds0k.js"],["./chunks/github-light-high-contrast-vgqbqnpv.js"],["./chunks/gruvbox-dark-hard-914016cj.js"],["./chunks/gruvbox-dark-medium-9t6b705s.js"],["./chunks/gruvbox-dark-soft-sdv10jrj.js"],["./chunks/gruvbox-light-hard-cy4jx512.js"],["./chunks/dark-plus-m8at7yx7.js"],["./chunks/dracula-4fc9ntns.js"],["./chunks/dracula-soft-5q94k618.js"],["./chunks/everforest-dark-d1yfc7p8.js"],["./chunks/everforest-light-8cd74ewt.js"],["./chunks/github-dark-mm6673p6.js"],["./chunks/github-dark-default-mq5awb4z.js"],["./chunks/github-dark-dimmed-kt7rv59v.js"],["./chunks/aurora-x-mv0k79bd.js"],["./chunks/ayu-dark-ghd075yb.js"],["./chunks/ayu-light-v3ystkk5.js"],["./chunks/ayu-mirage-vzvzpezs.js"],["./chunks/catppuccin-frappe-znmj0d2m.js"],["./chunks/catppuccin-latte-p8aygbzx.js"],["./chunks/catppuccin-macchiato-f8vwt6tn.js"],["./chunks/catppuccin-mocha-f5skm0s6.js"],["./chunks/pierre-dark-protanopia-deuteranopia-dvs8g9s9.js"],["./chunks/pierre-dark-tritanopia-hg031v40.js"],["./chunks/pierre-light-hcqns3mt.js"],["./chunks/pierre-light-soft-kfyv50pr.js"],["./chunks/pierre-light-vibrant-4f2kgqvy.js"],["./chunks/pierre-light-protanopia-deuteranopia-s9tqbsvc.js"],["./chunks/pierre-light-tritanopia-x4vh9x60.js"],["./chunks/andromeeda-wg0jqvm9.js"],["./chunks/pierre-dark-4mgfqqv0.js"],["./chunks/pierre-dark-soft-w7sqrdqg.js"],["./chunks/pierre-dark-vibrant-xbst0r6r.js"],["./chunks/main-bte48x46.js",6],["./chunks/vesper-xc0vwsv5.js"],["./chunks/vitesse-black-kmbwnbg0.js"],["./chunks/vitesse-dark-k9hmefys.js"],["./chunks/vitesse-light-qbe60h0e.js"],["./chunks/rose-pine-moon-ykgm42k6.js"],["./chunks/slack-dark-s2tjqac1.js"],["./chunks/slack-ochin-chfr1dky.js"],["./chunks/snazzy-light-nn8msg3q.js"],["./chunks/solarized-dark-626rys45.js"],["./chunks/solarized-light-b1zh65yc.js"],["./chunks/synthwave-84-fyjsk51f.js"],["./chunks/tokyo-night-tacx30ck.js"],["./chunks/pierre-light-soft-tj3b94mt.js"],["./chunks/pierre-light-tritanopia-a5znxv0j.js"],["./chunks/pierre-light-vibrant-4jt80rb3.js"],["./chunks/plastic-30ehh77t.js"],["./chunks/poimandres-bk3cvzvs.js"],["./chunks/red-h102ytjk.js"],["./chunks/rose-pine-3a5asyhw.js"],["./chunks/rose-pine-dawn-sbmr4d39.js"],["./chunks/one-light-0p37dqhe.js"],["./chunks/pierre-dark-8003tffz.js"],["./chunks/pierre-dark-protanopia-deuteranopia-th51yc2v.js"],["./chunks/pierre-dark-soft-xyfaz8my.js"],["./chunks/pierre-dark-tritanopia-ckwy3eca.js"],["./chunks/pierre-dark-vibrant-vhqnt3mv.js"],["./chunks/pierre-light-8q0xtee6.js"],["./chunks/pierre-light-protanopia-deuteranopia-nhqrbrbc.js"],["./chunks/material-theme-palenight-8x3dzepx.js"],["./chunks/min-dark-q3pe707k.js"],["./chunks/min-light-t39papy0.js"],["./chunks/monokai-3skg33fz.js"],["./chunks/night-owl-75v2e0z7.js"],["./chunks/night-owl-light-pbfh6xmb.js"],["./chunks/nord-shk74frp.js"],["./chunks/one-dark-pro-hs8bjf78.js"],["./chunks/kanagawa-lotus-1zp201y9.js"],["./chunks/kanagawa-wave-5r4ghtv4.js"],["./chunks/laserwave-djkvncyh.js"],["./chunks/light-plus-4dm5z5gz.js"],["./chunks/material-theme-5fv3834p.js"],["./chunks/material-theme-darker-xwa8jjky.js"],["./chunks/material-theme-lighter-fs9vxzcr.js"],["./chunks/material-theme-ocean-e78k91wj.js"],["./chunks/gruvbox-dark-soft-27pzh9h4.js"],["./chunks/gruvbox-light-hard-bzh90507.js"],["./chunks/gruvbox-light-medium-v2dc377y.js"],["./chunks/gruvbox-light-soft-y1c4jvva.js"],["./chunks/horizon-ebx8qzp1.js"],["./chunks/horizon-bright-p7mfec7n.js"],["./chunks/houston-3d3j7q8a.js"],["./chunks/kanagawa-dragon-h7ytmqc1.js"],["./chunks/github-dark-default-ny5zfg3e.js"],["./chunks/github-dark-dimmed-9212jnfg.js"],["./chunks/github-dark-high-contrast-5v8f6wjy.js"],["./chunks/github-light-r11td6rr.js"],["./chunks/github-light-default-9ncba8pj.js"],["./chunks/github-light-high-contrast-6xym75kt.js"],["./chunks/gruvbox-dark-hard-bn1j7t5a.js"],["./chunks/gruvbox-dark-medium-kbpz0qam.js"],["./chunks/catppuccin-macchiato-1bjn4cgw.js"],["./chunks/catppuccin-mocha-yt916yx8.js"],["./chunks/dark-plus-jte12g1m.js"],["./chunks/dracula-q0yvybq5.js"],["./chunks/dracula-soft-9c66kxde.js"],["./chunks/everforest-dark-wv0n2pm7.js"],["./chunks/everforest-light-dtyyn81w.js"],["./chunks/github-dark-p076c381.js"],["./chunks/andromeeda-kr23demp.js"],["./chunks/aurora-x-yrwp6405.js"],["./chunks/ayu-dark-ezf6pef0.js"],["./chunks/ayu-light-ncea79rq.js"],["./chunks/ayu-mirage-wz3vyvnp.js"],["./chunks/catppuccin-frappe-0g1trpbb.js"],["./chunks/catppuccin-latte-x66a8fp4.js"]],0);
|
|
2
|
+
var he={};ee(he,{canSubmit:()=>ue,composePrompt:()=>Ye,convertAvifToJpeg:()=>_e,enterDrag:()=>nn,extractTransferredFilePaths:()=>je,fileWithDetectedMimeType:()=>Ge,formatFileReferences:()=>Je,hasAttachments:()=>Ve,hasFiles:()=>en,insert:()=>Ke,isAvifImageFile:()=>fe,isHeicImageFile:()=>me,jpegFileName:()=>We,leaveDrag:()=>on,pick:()=>tn,resetDrag:()=>rn,submit:()=>sn});async function X(t){try{return await navigator.clipboard.writeText(t),!0}catch{return!1}}function Te(){document.addEventListener("click",Tt)}async function Tt(t){let n=t.target;if(!(n instanceof Element))return;let o=n.closest("[data-copy-code]");if(!(o instanceof HTMLButtonElement))return;let r=o.closest("[data-code-block]"),i=r?.querySelector("code"),s=r?.getAttribute("data-code-source")||i?.textContent;if(!s)return;if(!await X(s)){o.setAttribute("aria-label","Copy failed");return}o.dataset.copyState="copied",o.setAttribute("aria-label","Copied"),setTimeout(()=>{delete o.dataset.copyState,o.setAttribute("aria-label","Copy code")},1200)}var Ae=new Set(["ArrowDown","ArrowUp","Home","End"]),At=new Set(["ArrowDown","ArrowUp"]);function Me(){document.addEventListener("keydown",kt),document.addEventListener("mousemove",Ft),document.addEventListener("click",Ht),Z()}function Z(t=document){for(let n of Mt(t,".command"))Lt(n)}function Mt(t,n){let o=[];if(!t)return o;if(t instanceof Element&&t.matches(n))o.push(t);for(let r of t.querySelectorAll?.(n)??[])o.push(r);return o}function Q(t){return{input:t.querySelector("search input"),menu:t.querySelector('[role="listbox"], [role="menu"]')}}function St(t){return[...t.querySelectorAll('[role="option"], [role="menuitem"]')].filter((n)=>n instanceof HTMLElement&&!Le(n))}function te(t){let{menu:n}=Q(t);if(!(n instanceof HTMLElement))return[];return St(n).filter((o)=>!o.hidden)}function Lt(t){let{input:n,menu:o}=Q(t);if(!(n instanceof HTMLInputElement)||!(o instanceof HTMLElement))return;o.scrollTop=0,P(t,te(t)[0])}function P(t,n){let{input:o,menu:r}=Q(t);if(!(o instanceof HTMLInputElement)||!(r instanceof HTMLElement))return;for(let i of r.querySelectorAll('[role="option"].active, [role="menuitem"].active'))i.classList.remove("active");if(n instanceof HTMLElement)if(n.classList.add("active"),n.id)o.setAttribute("aria-activedescendant",n.id);else o.removeAttribute("aria-activedescendant");else o.removeAttribute("aria-activedescendant")}function Pt(t,n){let o=te(t);if(o.length===0)return;let r=o.findIndex((a)=>a.classList.contains("active")),i=r;if(n==="ArrowDown")i=Math.min(r+1,o.length-1);if(n==="ArrowUp")i=Math.max(r<0?0:r-1,0);if(n==="Home")i=0;if(n==="End")i=o.length-1;let s=o[i];P(t,s),s?.scrollIntoView({block:"nearest"})}function Se(t){return[...t.querySelectorAll('[role^="menuitem"]')].filter((n)=>n instanceof HTMLElement&&!Le(n))}function Ct(t,n){let o=Se(t);if(o.length===0)return;let r=o.indexOf(document.activeElement),i=r;if(n==="ArrowDown")i=Math.min(r+1,o.length-1);if(n==="ArrowUp")i=r<0?o.length-1:Math.max(r-1,0);if(n==="Home")i=0;if(n==="End")i=o.length-1;o[i]?.focus({preventScroll:!0})}function kt(t){if(!(t.target instanceof Element))return;let n=t.target.closest(".command");if(n instanceof HTMLElement&&t.target.matches("search input")){if(t.isComposing)return;if(t.key==="Enter"){let i=te(n).find((s)=>s.classList.contains("active"));if(i)t.preventDefault(),i.click();return}if(Ae.has(t.key)){t.preventDefault(),Pt(n,t.key);return}}let o=t.target.closest("[popover][role='menu']");if(o instanceof HTMLElement){if(t.key==="Tab")o.hidePopover();if(Ae.has(t.key))t.preventDefault(),Ct(o,t.key);return}if(!(t.target instanceof HTMLButtonElement))return;let r=t.target.popoverTargetElement;if(r?.matches("[popover][role='menu']")&&At.has(t.key)){t.preventDefault(),t.target.click();let i=Se(r);(t.key==="ArrowUp"?i.at(-1):i[0])?.focus({preventScroll:!0})}}function Ft(t){if(!(t.target instanceof Element))return;let n=t.target.closest('[role="option"], [role="menuitem"]')??t.target.closest("[data-command-row]")?.querySelector('[role="option"], [role="menuitem"]'),o=n?.closest(".command");if(o instanceof HTMLElement&&n instanceof HTMLElement){if(!n.hidden&&!n.classList.contains("active"))P(o,n);return}let r=t.target.closest('[role="option"]');if(r instanceof HTMLElement&&r.getAttribute("aria-selected")!=="true")It(r)}function It(t){let n=t.closest('[role="listbox"]');if(!(n instanceof HTMLElement))return;for(let r of n.querySelectorAll('[role="option"][aria-selected="true"]'))r.setAttribute("aria-selected","false");t.setAttribute("aria-selected","true"),document.querySelector(`[aria-controls="${CSS.escape(n.id)}"]`)?.setAttribute("aria-activedescendant",t.id)}function Ht(t){if(!(t.target instanceof Element))return;let n=t.target.closest('.command [role="option"], .command [role="menuitem"]');if(n instanceof HTMLElement&&!n.hasAttribute("commandfor")&&!n.hasAttribute("data-keep-command-open"))n.closest("dialog")?.close()}function Le(t){return t.hasAttribute("disabled")||t.getAttribute("aria-disabled")==="true"||t.getAttribute("data-disabled")==="true"}function Pe(t){let n=new Date(t.dateTime);if(Number.isNaN(n.getTime()))return;t.textContent=H(n),t.title=x(n)}function Bt(){let t,n,o=[];return{reset(){t=void 0,n=void 0,o=[]},add(r){if(t===void 0){t=n=r;return}o.push(r-t),t=r;let i=r-n;if(i<1000)return;let s=o.sort((c,p)=>c-p),a=Math.floor(s.length/2),l={rate:o.length*1000/i,median:(s[a]+s[Math.floor((s.length-1)/2)])/2,p95:s[Math.ceil(s.length*0.95)-1],max:s.at(-1)};return o=[],n=r,l}}}function Ce(){let t=document.getElementById("debug-frame-rate");if(!t)return;let n=document.getElementById("debug-frame-median"),o=document.getElementById("debug-frame-p95"),r=document.getElementById("debug-frame-max"),i=Bt(),s;function a(c){let p=i.add(c);if(p)t.textContent=String(Math.round(p.rate)),n.textContent=p.median.toFixed(1),o.textContent=p.p95.toFixed(1),r.textContent=p.max.toFixed(1);s=requestAnimationFrame(a)}function l(){if(s!==void 0)cancelAnimationFrame(s);if(i.reset(),t.textContent=n.textContent=o.textContent=r.textContent="—",!document.hidden)s=requestAnimationFrame(a)}document.addEventListener("visibilitychange",l),l()}function C(t){try{let n=new URL(t);if(n.protocol!=="file:")return;let o=decodeURIComponent(n.pathname);if(n.hostname&&n.hostname.toLowerCase()!=="localhost")return`//${n.hostname}${o}`;if(/^\/[A-Za-z]:(?:\/|$)/.test(o))return o.slice(1);return o}catch{return}}function ke(){document.addEventListener("click",(t)=>{if(t.button!==0)return;let n=t.target instanceof Element?t.target.closest("a[href]"):null;if(!(n instanceof HTMLAnchorElement))return;let o=n.getAttribute("data-pi-file-link")??"",r=o?C(o):void 0,i=r===void 0?n.href:o;if((r??C(i))===void 0)return;t.preventDefault(),Dt(i)},{capture:!0})}async function Dt(t){let n=document.body.dataset.filesOpenEndpoint;if(!n)return;try{let o=await fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({uri:t})});if(!o.ok)throw Error(await y(o,"Could not open the file."));let r=await o.json();if(r.opened)return;let{openLinkedWorkspaceFile:i}=await (e("sc4yfzz9"),import("./chunks/workspace-review-sc4yfzz9.js"));await i(r.path,r.workspacePath)}catch(o){alert(Error.isError(o)?o.message:"Could not open the file.")}}var ne={archive:{paths:["M13.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v11.5","M14 2v5a1 1 0 0 0 1 1h5M8 12v-1m0 7v-2m0-9V6"],circle:{cx:8,cy:20,r:2}},audio:{paths:["M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3","M14 2v4a2 2 0 0 0 2 2h4M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0"]},code:{paths:["M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4","M14 2v4a2 2 0 0 0 2 2h4M5 12l-3 3l3 3m4 0l3-3l-3-3"]},file:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5"]},pdf:{paths:["M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4","M14 2v4a2 2 0 0 0 2 2h4M2 13v-1h6v1m-3-1v6m-1 0h2"]},text:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5M10 9H8m8 4H8m8 4H8"]},video:{paths:["M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z","M14 2v5a1 1 0 0 0 1 1h5m-4.967 5.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56v-4.704a.645.645 0 0 1 .967-.56z"]}},qt=new Set(["aac","flac","m4a","mp3","ogg","wav"]),Ot=new Set(["avi","m4v","mkv","mov","mp4","webm"]),Rt=new Set(["7z","bz2","gz","rar","tar","xz","zip"]),Ut=new Set(["c","cpp","css","go","h","html","java","js","json","jsx","py","rs","sh","sql","toml","ts","tsx","xml","yaml","yml"]),Nt=new Set(["csv","log","md","rst","txt"]);function Fe(t){return He(t).slice(0,4)}function Ie(t,n){let o=He(t);if(n==="application/pdf"||o==="pdf")return"pdf";if(n?.startsWith("audio/")||qt.has(o))return"audio";if(n?.startsWith("video/")||Ot.has(o))return"video";if(n?.includes("zip")||Rt.has(o))return"archive";if(Ut.has(o)||n==="application/json"||n?.includes("javascript")||n?.includes("xml"))return"code";if(n?.startsWith("text/")||Nt.has(o))return"text";return"file"}function He(t){return t.match(/\.([^.]+)$/)?.[1].toLowerCase()??""}function m(){let t=document.getElementById("prompt-input");return t instanceof HTMLTextAreaElement?t:void 0}function A(t){let n=m();if(!n)return;n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}))}function oe(){if(!window.matchMedia("(hover: hover) and (pointer: fine)").matches)return;re()}function re(){let t=m();if(!t)return;t.focus({preventScroll:!0}),t.selectionStart=t.value.length,t.selectionEnd=t.value.length}var M,R=!1;function $t(t,n){let o=t.slice(0,n),r=/(?:^|[\s"'=])(@(?:"[^"]*|[^\s"'=]*))$/.exec(o)?.[1];if(!r)return;return{start:n-r.length,end:n,query:r.slice(1)}}function Kt(t,n,o){let r=o.endsWith("/")||o.endsWith('/"'),i=r?"":" ",s=t.slice(n.end),a=n.query.startsWith('"')&&o.endsWith('"')&&s.startsWith('"')?s.slice(1):s,l=`${t.slice(0,n.start)}${o}${i}${a}`,c=r&&o.endsWith('"')?1:0;return{text:l,cursor:n.start+o.length+i.length-c}}function k(){return Oe("prompt-file-popover")}function U(){return k()||qe()}function Be(){document.addEventListener("input",Vt),document.addEventListener("click",jt),document.addEventListener("keydown",zt),document.addEventListener("mousedown",(t)=>{if(t.button===0&&t.target instanceof Element&&t.target.closest("[data-picker-kind]"))t.preventDefault()}),document.addEventListener("focusout",(t)=>{if(t.target===m())v(!0)})}function Vt(t){if(t.target!==m()||t.isComposing)return;R=!1,ie(t.target)}function ie(t){if(R||document.activeElement!==t)return;let n=$t(t.value,t.selectionStart);if(!n){se();return}if(M?.start===n.start&&M.end===n.end&&M.query===n.query)return;M=n,t.dispatchEvent(new CustomEvent("pi-ui-file-query",{bubbles:!0,detail:{query:n.query}}))}function jt(t){let n=t.target;if(!(n instanceof Element))return;let o=n.closest('[data-picker-kind="slash"]'),r=n.closest('[data-picker-kind="file"]');if(n.closest("[data-file-trigger]"))t.preventDefault(),Gt();else if(n.closest("[data-send-trigger]")||o instanceof HTMLElement)v(!0);else if(r instanceof HTMLElement)t.preventDefault(),Wt(r.dataset.pickerValue??"")}function zt(t){if(t.target!==m()||t.isComposing||t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||!U())return;if(t.code==="Escape"){t.preventDefault(),v(!0);return}let n=k()?"[data-file-row]":"[data-slash-row]";if(t.code==="ArrowDown"||t.code==="ArrowUp")t.preventDefault(),Jt(n,t.code==="ArrowDown"?1:-1);else if(t.code==="Enter"||t.code==="Tab")t.preventDefault(),Re(n)?.click()}function Wt(t){let n=m();if(!n||!M)return;let o=Kt(n.value,M,t);if(n.value=o.text,n.selectionStart=o.cursor,n.selectionEnd=o.cursor,n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus(),t.endsWith("/")||t.endsWith('/"'))ie(n);else se()}function De(t){A(`/${t} `),re(),v()}function Gt(){let t=m();if(!t)return;R=!1;let n=t.selectionStart,r=`${n>0&&!/\s/.test(t.value[n-1]??"")?" ":""}@`;t.setRangeText(r,n,t.selectionEnd,"end"),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus(),ie(t)}function v(t=!1){se(t),m()?.dispatchEvent(new CustomEvent("pi-ui-picker-close",{bubbles:!0}))}function se(t=!1){if(t)R=!0;M=void 0;let n=m();n?.dispatchEvent(new CustomEvent("pi-ui-file-query",{bubbles:!0})),n?.dispatchEvent(new CustomEvent("pi-ui-file-close",{bubbles:!0}))}function qe(){return Oe("prompt-slash-popover")}function Oe(t){let n=document.getElementById(t);return n instanceof HTMLElement&&n.checkVisibility()}function ae(t){return document.querySelectorAll(t).values().filter((n)=>n instanceof HTMLElement&&n.checkVisibility()).toArray()}function Re(t){let n=ae(t);return n.find((o)=>o.getAttribute("aria-selected")==="true")??n[0]}function _t(t,n,o){if(t<=0)return-1;if(n===-1)return 0;return Math.max(0,Math.min(t-1,n-o))}function Jt(t,n){let o=ae(t);if(o.length===0)return;let r=o.findIndex((s)=>s.getAttribute("aria-selected")==="true"),i=_t(o.length,r,n);for(let s of o)s.setAttribute("aria-selected","false");o[i]?.setAttribute("aria-selected","true"),o[i]?.scrollIntoView({block:"nearest",behavior:"instant"}),ce()}function ce(t=!1){queueMicrotask(()=>{let n=m();if(!n)return;let o=k()?"file-picker-list":qe()?"slash-picker-list":void 0;if(t&&o){document.getElementById(o).scrollTop=0;for(let[i,s]of ae(`#${o} [role="option"]`).entries())s.setAttribute("aria-selected",i===0?"true":"false")}let r=o&&Re(`#${o} [role="option"]`);if(r&&document.activeElement===n)r.setAttribute("aria-selected","true"),n.setAttribute("aria-controls",o),n.setAttribute("aria-activedescendant",r.id);else n.removeAttribute("aria-controls"),n.removeAttribute("aria-activedescendant")})}var Yt=["text/uri-list","x-special/gnome-copied-files","text/plain"],Ue=10,Xt=20971520,Zt=52428800,Qt=0.85,F=0,le=!1,g=[];function en(t){if(!t)return!1;if(t.files?.length)return!0;return t.types.includes("Files")||t.types.includes("text/uri-list")}function tn(){h("");let t=document.createElement("input");t.type="file",t.multiple=!0,t.addEventListener("change",()=>{if(t.files?.length)Ke(t.files)},{once:!0}),t.click()}function nn(){return F+=1,!0}function on(){return F=Math.max(0,F-1),F>0}function rn(){F=0}async function Ke(t){if(!t)return;h("");let n=ze(t),o=n.some((c)=>fe(c)||me(c)),r=je(t);if(r.length>0&&!o){let c=cn(r);if(c){h(c);return}dn(r);return}if(n.length===0)return;let i=Ne(n);if(i){h(i);return}let s;try{s=await an(n)}catch(c){console.error(c),h(c?.message||"Could not prepare the selected images.");return}let a=Ne(s);if(a){h(a);return}let l=await un(s);for(let c=0;c<l.length;c+=1)Xe({path:l[c].path,file:Ge(s[c],l[c].mimeType)})}function Ve(){return g.length>0}function ue(t){return!le&&(t.trim()!==""||Ve())}async function sn(t,n,o){if(!ue(n))return!1;let r=[...g],i=Ye(n,r.map(({path:a})=>a)),s=new FormData;if(s.set("prompt",i),o)s.set("streamingBehavior",o);for(let{file:a}of r)if(a?.type.startsWith("image/"))s.append("image",a,a.name||"pasted-image");le=!0;try{let a=await fetch(t,{method:"POST",body:s});if(await a.text(),!a.ok)throw Error(`Prompt was not accepted (${a.status}).`);return mn(r),h(""),!0}catch(a){return fn(n),h(a?.message||"Could not send the prompt."),!1}finally{le=!1,document.getElementById("prompt-box")?.dispatchEvent(new CustomEvent("pi-ui-prompt-submit-finished",{bubbles:!0})),pe()}}function je(t){let n="getData"in t?Yt.flatMap((r)=>t.getData(r).split(/\r?\n/)):[];for(let r of ze(t))n.push(r.path??"",r.webkitRelativePath??"");let o=new Set(n.map(ln));return o.delete(void 0),[...o]}function ze(t){if(t.files)return[...t.files];return Array.from(t)}function fe(t){return t.type?.toLowerCase()==="image/avif"||/\.avif$/i.test(t.name??"")}function me(t){return/^(?:image\/)?hei[cf]$/i.test(t.type??"")||/\.hei[cf]$/i.test(t.name??"")}function We(t){return/\.avif$/i.test(t)?t.replace(/\.avif$/i,".jpg"):`${t||"image"}.jpg`}function Ge(t,n){if(n===void 0||t.type===n)return t;return new File([t],t.name,{type:n??"",lastModified:t.lastModified})}function an(t){return Array.fromAsync(t,(n)=>{if(me(n))throw Error("HEIC and HEIF images are not supported. Convert them to JPEG or PNG first.");return fe(n)?_e(n):n})}async function _e(t){let n;try{n=await createImageBitmap(t);let o=document.createElement("canvas");o.width=n.width,o.height=n.height;let r=o.getContext("2d");if(!r)throw Error("Canvas image conversion is unavailable.");r.fillStyle="white",r.fillRect(0,0,o.width,o.height),r.drawImage(n,0,0,o.width,o.height);let i=await new Promise((s,a)=>{o.toBlob((l)=>l?s(l):a(Error("JPEG encoding failed.")),"image/jpeg",Qt)});return new File([i],We(t.name),{type:"image/jpeg",lastModified:t.lastModified})}catch(o){throw Error(`Could not convert ${t.name||"the AVIF image"} to JPEG.`,{cause:o})}finally{n?.close()}}function cn(t){if(t.some((n)=>/\.hei[cf]$/i.test(n)))return"HEIC and HEIF images are not supported. Convert them to JPEG or PNG first.";if(t.some((n)=>/\.avif$/i.test(n)))return"AVIF images must be dropped, pasted, or selected with the browser file picker so they can be converted."}function ln(t){let n=t.trim();if(!n||n.startsWith("#")||n==="copy"||n==="cut")return;let o=C(n);if(o)return o;if(n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n))return n;return}function Ne(t){if(t.length>Ue)return`Attach at most ${Ue} files at a time.`;let n=0;for(let o of t){if(o.size>Xt)return"Dropped or pasted files must be 20 MiB or smaller; use the Files button for larger files.";n+=o.size}if(n>Zt)return"Dropped or pasted files must total 50 MiB or less."}async function un(t){let n=new FormData;for(let o of t)n.append("file",o,o.name||"pasted-file");try{let o=document.body.dataset.filesImportEndpoint,r=await fetch(o,{method:"POST",body:n}),i=await r.json().catch(()=>({}));if(!r.ok)return h(u(i.message)?i.message:"Could not transfer the selected files."),[];return h(""),Array.isArray(i.imports)?i.imports:[]}catch{return h("Could not transfer the selected files."),[]}}function h(t){let n=m();if(!n)return;let o=document.getElementById("file-transfer-error");if(!(o instanceof HTMLParagraphElement))o=document.createElement("p"),o.id="file-transfer-error",o.className="file-transfer-error",o.setAttribute("role","alert"),o.setAttribute("aria-live","polite"),n.before(o);o.textContent=t,o.hidden=!t}function Je(t){return`${t.map((n)=>`@${n}`).join(`
|
|
3
3
|
`)}
|
|
4
|
-
`}function Je(t,n){let o=_e(n);return t.trim()?`${o}${t}`:o.trimEnd()}function un(t){for(let n of t)Ye({path:n})}function Ye({path:t,file:n}){if(!t||g.some((o)=>o.path===t))return;g.push({path:t,file:n,previewUrl:n?.type.startsWith("image/")?URL.createObjectURL(n):void 0}),pe(),m()?.focus(),v(!0)}function dn(t){let n=m();if(!n||n.value!==""||!t)return;n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}))}function fn(t){for(let n of t){let o=g.indexOf(n);if(o<0)continue;if(g.splice(o,1),n.previewUrl)URL.revokeObjectURL(n.previewUrl)}}function mn(t){let n=g.findIndex((r)=>r.path===t);if(n<0)return;let[o]=g.splice(n,1);if(o.previewUrl)URL.revokeObjectURL(o.previewUrl);pe()}function pe(){let t=document.getElementById("prompt-attachments");if(!(t instanceof HTMLElement))return;t.replaceChildren(...g.map(pn)),t.hidden=g.length===0;let n=document.querySelector("[data-send-trigger]");if(n instanceof HTMLButtonElement)n.disabled=!ue(m()?.value??"")}function pn(t){let n=t.file?.name||hn(t.path),o=document.createElement("button");if(o.type="button",o.className=`prompt-attachment prompt-attachment-${t.previewUrl?"image":"file"}`,o.setAttribute("aria-label",`Remove ${n}`),o.addEventListener("click",()=>mn(t.path)),t.previewUrl){let p=document.createElement("span");p.className="prompt-attachment-preview";let w=document.createElement("img");return w.className="prompt-attachment-image-content",w.src=t.previewUrl,w.alt=n,p.append(w),o.append(p,Ne()),o}let r=Ce(n),i=Fe(n,t.file?.type),s=document.createElement("span");if(s.className="prompt-attachment-file-icon",s.dataset.fileKind=i,s.append(gn(i)),r){let p=document.createElement("span");p.className="prompt-attachment-extension",p.textContent=r,s.append(p)}o.append(s);let a=document.createElement("span");a.className="prompt-attachment-details";let l=document.createElement("span");l.className="prompt-attachment-name",l.textContent=n,a.append(l);let c=document.createElement("span");return c.className="prompt-attachment-meta",c.textContent=t.file?En(t.file.size):"local file",a.append(c),o.append(a,Ne()),o}function Ne(){let t=document.createElement("span");return t.className="prompt-attachment-remove",t.textContent="×",t.setAttribute("aria-hidden","true"),t}function hn(t){return t.split(/[\\/]/).filter(Boolean).at(-1)||t}function gn(t){let o=ne[t]??ne.file,r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttribute("class","prompt-attachment-file-type-icon"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("stroke-width","2"),r.setAttribute("aria-hidden","true");for(let i of o.paths){let s=document.createElementNS("http://www.w3.org/2000/svg","path");s.setAttribute("d",i),r.append(s)}if(o.circle){let i=document.createElementNS("http://www.w3.org/2000/svg","circle");for(let[s,a]of Object.entries(o.circle))i.setAttribute(s,String(a));r.append(i)}return r}function En(t){if(t<1024)return`${t} B`;if(t<1048576)return`${(t/1024).toFixed(1)} KiB`;return`${(t/1048576).toFixed(1)} MiB`}var d={middleScrolling:!1,pinnedToBottom:!0,pointerScrolling:!1,scrollTop:0},Xe,Ze,I,S,K,T,B=0,ge,q,Qe=!1;function Ee(){if(T!==void 0)cancelAnimationFrame(T);T=void 0}function et(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function tt(t,n){if(B=n,T!==void 0||document.hidden)return;if(q??=window.matchMedia("(prefers-reduced-motion: reduce)"),q.matches){t.scrollTop=n,d.scrollTop=t.scrollTop;return}let o=performance.now(),r=t.scrollTop,i=(s)=>{if(T=void 0,!d.pinnedToBottom||document.hidden||!t.isConnected)return;let a=1-Math.exp(-Math.max(0,s-o)/60);if(r+=(B-r)*a,q.matches||B-r<=1)r=B;if(t.scrollTo({top:Math.round(r),behavior:"instant"}),d.scrollTop=t.scrollTop,o=s,r!==B)T=requestAnimationFrame(i);else V()};T=requestAnimationFrame(i)}function nt(){let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;E(),t.style.overflowAnchor="none";let n=t.getBoundingClientRect().top,o=[...t.querySelectorAll("#message-list > .message[id]")].find((r)=>{let i=r.getBoundingClientRect();return i.height>0&&i.bottom>n});K=o&&{messages:t,row:o,top:o.getBoundingClientRect().top}}function ot(){let t=K;K=void 0;let n=document.getElementById("messages");if(!(n instanceof HTMLElement))return;if(t?.messages===n&&n.contains(t.row))n.scrollTop+=t.row.getBoundingClientRect().top-t.top,d.scrollTop=n.scrollTop;D(n,d.pinnedToBottom),be()}function D(t,n){if(n)t.style.overflowAnchor="none";else t.style.removeProperty("overflow-anchor")}function be(){if(T!==void 0||ge!==void 0)return;ge=setTimeout(()=>{ge=void 0;let t=document.getElementById("messages"),n=document.getElementById("older-messages-trigger");if(!(t instanceof HTMLElement)||!n?.hasAttribute("data-active"))return;if(t.scrollTop>2*t.clientHeight)return;n.dispatchEvent(new CustomEvent("pi-ui-older"))},0)}function V(){if(!d.pinnedToBottom||K)return;let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;let n=[...t.querySelectorAll("#message-list > .message[id]")],o=n.length-100;if(o<=0||t.scrollTop<=2*t.clientHeight)return;let r=t.getBoundingClientRect().top-2*t.clientHeight;for(let i of n.slice(0,o)){let s=i.getBoundingClientRect();if(s.height>0&&s.bottom>=r)return}t.dispatchEvent(new CustomEvent("pi-ui-trim",{detail:{firstId:n[0].id.slice(8),throughId:n[o-1].id.slice(8)}}))}function rt(){document.addEventListener("scroll",(n)=>{let o=document.getElementById("messages");if(!(o instanceof HTMLElement)||n.target!==o)return;if((d.middleScrolling||d.pointerScrolling)&&o.scrollTop<d.scrollTop)E();if(!d.pinnedToBottom&&yn(d.scrollTop,o.scrollTop,o.scrollHeight-o.scrollTop-o.clientHeight))d.pinnedToBottom=!0,D(o,!0),o.scrollTop=o.scrollHeight,V();d.scrollTop=o.scrollTop,j()},!0);let t=(n)=>{if(n.button===1)d.middleScrolling=!0,E();else if(n.button===0&&N(n.target)){d.middleScrolling=!1,d.pointerScrolling=!0,S={x:n.clientX,y:n.clientY};let o=document.getElementById("messages");if(o instanceof HTMLElement)d.scrollTop=o.scrollTop}};document.addEventListener("pointerdown",t,{capture:!0,passive:!0}),document.addEventListener("pointermove",(n)=>{if(d.pointerScrolling&&S&&bn(S.x,S.y,n.clientX,n.clientY))S=void 0,E()},{capture:!0,passive:!0});for(let n of["pointerup","pointercancel"])document.addEventListener(n,()=>{d.middleScrolling=!1,d.pointerScrolling=!1,S=void 0},{capture:!0,passive:!0});document.addEventListener("wheel",(n)=>{if(!N(n.target))return;if(d.middleScrolling=!1,n.deltaY<0)E()},{capture:!0,passive:!0}),document.addEventListener("touchmove",(n)=>{if(N(n.target))E()},{capture:!0,passive:!0}),document.addEventListener("keydown",(n)=>{if(wn(n)&&N(n.target))E()},!0),document.addEventListener("visibilitychange",()=>{Ee();let n=document.getElementById("messages");if(!document.hidden&&d.pinnedToBottom&&n instanceof HTMLElement)tt(n,et(n))}),ye(),O()}function bn(t,n,o,r){return Math.hypot(o-t,r-n)>=8}function yn(t,n,o){return n>t&&o<=8}function O(t="auto"){Ee(),d.middleScrolling=!1,d.pinnedToBottom=!0,d.pointerScrolling=!1;let n=document.getElementById("messages");if(!(n instanceof HTMLElement))return;D(n,!0),q??=window.matchMedia("(prefers-reduced-motion: reduce)"),n.scrollTo({top:n.scrollHeight,behavior:q.matches?"instant":t}),j(),V()}function E(){Ee(),d.pinnedToBottom=!1;let t=document.getElementById("messages");if(t instanceof HTMLElement)t.scrollTo({top:t.scrollTop,behavior:"instant"}),D(t,!1);j()}function N(t){let n=document.getElementById("messages");return n instanceof HTMLElement&&t instanceof Node&&n.contains(t)}function wn(t){return t.key==="ArrowUp"||t.key==="PageUp"||t.key==="Home"||t.key===" "&&t.shiftKey}function ye(){let t=document.querySelector("#messages > .messages-stack"),n=document.getElementById("prompt-box"),o=document.getElementById("messages");if(!t||!n||!o)return;if(t===Xe&&n===Ze)return;I??=new ResizeObserver(()=>{vn();let r=document.getElementById("messages");if(r instanceof HTMLElement&&d.pinnedToBottom)D(r,!0),tt(r,et(r));j(),V()}),I.disconnect(),Xe=t,Ze=n,I.observe(t),I.observe(n),I.observe(o)}function vn(){let t=document.getElementById("prompt-box"),n=document.getElementById("messages-prompt-spacer");if(!(t instanceof HTMLElement)||!(n instanceof HTMLElement))return;let o=`${t.offsetHeight+48}px`;if(n.style.height!==o)n.style.height=o}function j(){let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;let n=!d.pinnedToBottom&&t.scrollHeight-t.scrollTop-t.clientHeight>=48;if(n===Qe)return;Qe=n,document.dispatchEvent(new CustomEvent("pi-ui-latest-changed",{detail:n}))}function it(t){if(!(t instanceof HTMLElement))return;let n=t.querySelector('template[shadowrootmode="open"]');if(!(n instanceof HTMLTemplateElement))return;(t.shadowRoot??t.attachShadow({mode:"open"})).replaceChildren(n.content.cloneNode(!0)),n.remove()}var st=!1;function at(){if(st||!("Notification"in window)||!window.isSecureContext)return;if(Notification.permission!=="default")return;st=!0;try{if(localStorage.getItem("pi-ui-notifications-requested"))return;localStorage.setItem("pi-ui-notifications-requested","true")}catch{}Notification.requestPermission().catch(()=>{})}function ct({workspace:t,sessionPath:n}){if(!("Notification"in window)||Notification.permission!=="granted")return;if(document.hasFocus())return;try{let o=new Notification(`${t} finished`,{icon:document.querySelector('link[rel="icon"]')?.href,tag:n||t});o.onclick=()=>{window.focus(),o.close()}}catch{}}class lt{#t=[];#e=-1;#n="";#o="";sync(t){let n=JSON.stringify(t);if(n===this.#o)return;this.#o=n,this.#t=t,this.reset()}get browsing(){return this.#e>=0}reset(){this.#e=-1,this.#n=""}navigate(t,n){if(n==="up"){if(!this.browsing){if(t!==""||this.#t.length===0)return;this.#n=t,this.#e=0}else if(this.#e<this.#t.length-1)this.#e+=1;return{value:this.#t[this.#e],cursor:"start"}}if(!this.browsing)return;if(this.#e>0)return this.#e-=1,{value:this.#t[this.#e],cursor:"end"};let o=this.#n;return this.reset(),{value:o,cursor:"end"}}}function ut(){let t=new lt,n=!1;function o(i,s){if(i.isComposing||i.defaultPrevented||i.altKey||i.ctrlKey||i.metaKey||i.shiftKey||i.code!=="ArrowUp"&&i.code!=="ArrowDown")return!1;let a=m();if(i.target!==a||window.piUi.pickers.isOpen())return!1;if(t.sync(Array.isArray(s)?s:[]),t.browsing&&!xn(a,i.code))return!1;let l=t.navigate(a.value,i.code==="ArrowUp"?"up":"down");if(!l)return!1;i.preventDefault(),n=!0,M(l.value),n=!1;let c=l.cursor==="start"?0:a.value.length;return a.selectionStart=c,a.selectionEnd=c,!0}function r(){if(!n)t.reset()}return{handleInput:r,handleKeydown:o}}function xn(t,n){if(t.selectionStart!==t.selectionEnd)return!1;if(n==="ArrowUp"){let r=t.value.indexOf(`
|
|
4
|
+
`}function Ye(t,n){let o=Je(n);return t.trim()?`${o}${t}`:o.trimEnd()}function dn(t){for(let n of t)Xe({path:n})}function Xe({path:t,file:n}){if(!t||g.some((o)=>o.path===t))return;g.push({path:t,file:n,previewUrl:n?.type.startsWith("image/")?URL.createObjectURL(n):void 0}),pe(),m()?.focus(),v(!0)}function fn(t){let n=m();if(!n||n.value!==""||!t)return;n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}))}function mn(t){for(let n of t){let o=g.indexOf(n);if(o<0)continue;if(g.splice(o,1),n.previewUrl)URL.revokeObjectURL(n.previewUrl)}}function pn(t){let n=g.findIndex((r)=>r.path===t);if(n<0)return;let[o]=g.splice(n,1);if(o.previewUrl)URL.revokeObjectURL(o.previewUrl);pe()}function pe(){let t=document.getElementById("prompt-attachments");if(!(t instanceof HTMLElement))return;t.replaceChildren(...g.map(hn)),t.hidden=g.length===0;let n=document.querySelector("[data-send-trigger]");if(n instanceof HTMLButtonElement)n.disabled=!ue(m()?.value??"")}function hn(t){let n=t.file?.name||gn(t.path),o=document.createElement("button");if(o.type="button",o.className=`prompt-attachment prompt-attachment-${t.previewUrl?"image":"file"}`,o.setAttribute("aria-label",`Remove ${n}`),o.addEventListener("click",()=>pn(t.path)),t.previewUrl){let p=document.createElement("span");p.className="prompt-attachment-preview";let w=document.createElement("img");return w.className="prompt-attachment-image-content",w.src=t.previewUrl,w.alt=n,p.append(w),o.append(p,$e()),o}let r=Fe(n),i=Ie(n,t.file?.type),s=document.createElement("span");if(s.className="prompt-attachment-file-icon",s.dataset.fileKind=i,s.append(En(i)),r){let p=document.createElement("span");p.className="prompt-attachment-extension",p.textContent=r,s.append(p)}o.append(s);let a=document.createElement("span");a.className="prompt-attachment-details";let l=document.createElement("span");l.className="prompt-attachment-name",l.textContent=n,a.append(l);let c=document.createElement("span");return c.className="prompt-attachment-meta",c.textContent=t.file?bn(t.file.size):"local file",a.append(c),o.append(a,$e()),o}function $e(){let t=document.createElement("span");return t.className="prompt-attachment-remove",t.textContent="×",t.setAttribute("aria-hidden","true"),t}function gn(t){return t.split(/[\\/]/).filter(Boolean).at(-1)||t}function En(t){let o=ne[t]??ne.file,r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttribute("class","prompt-attachment-file-type-icon"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("stroke-width","2"),r.setAttribute("aria-hidden","true");for(let i of o.paths){let s=document.createElementNS("http://www.w3.org/2000/svg","path");s.setAttribute("d",i),r.append(s)}if(o.circle){let i=document.createElementNS("http://www.w3.org/2000/svg","circle");for(let[s,a]of Object.entries(o.circle))i.setAttribute(s,String(a));r.append(i)}return r}function bn(t){if(t<1024)return`${t} B`;if(t<1048576)return`${(t/1024).toFixed(1)} KiB`;return`${(t/1048576).toFixed(1)} MiB`}var d={middleScrolling:!1,pinnedToBottom:!0,pointerScrolling:!1,scrollTop:0},Ze,Qe,I,S,K,T,B=0,ge,D,et=!1;function Ee(){if(T!==void 0)cancelAnimationFrame(T);T=void 0}function tt(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function nt(t,n){if(B=n,T!==void 0||document.hidden)return;if(D??=window.matchMedia("(prefers-reduced-motion: reduce)"),D.matches){t.scrollTop=n,d.scrollTop=t.scrollTop;return}let o=performance.now(),r=t.scrollTop,i=(s)=>{if(T=void 0,!d.pinnedToBottom||document.hidden||!t.isConnected)return;let a=1-Math.exp(-Math.max(0,s-o)/60);if(r+=(B-r)*a,D.matches||B-r<=1)r=B;if(t.scrollTo({top:Math.round(r),behavior:"instant"}),d.scrollTop=t.scrollTop,o=s,r!==B)T=requestAnimationFrame(i);else V()};T=requestAnimationFrame(i)}function ot(){let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;E(),t.style.overflowAnchor="none";let n=t.getBoundingClientRect().top,o=[...t.querySelectorAll("#message-list > .message[id]")].find((r)=>{let i=r.getBoundingClientRect();return i.height>0&&i.bottom>n});K=o&&{messages:t,row:o,top:o.getBoundingClientRect().top}}function rt(){let t=K;K=void 0;let n=document.getElementById("messages");if(!(n instanceof HTMLElement))return;if(t?.messages===n&&n.contains(t.row))n.scrollTop+=t.row.getBoundingClientRect().top-t.top,d.scrollTop=n.scrollTop;q(n,d.pinnedToBottom),be()}function q(t,n){if(n)t.style.overflowAnchor="none";else t.style.removeProperty("overflow-anchor")}function be(){if(T!==void 0||ge!==void 0)return;ge=setTimeout(()=>{ge=void 0;let t=document.getElementById("messages"),n=document.getElementById("older-messages-trigger");if(!(t instanceof HTMLElement)||!n?.hasAttribute("data-active"))return;if(t.scrollTop>2*t.clientHeight)return;n.dispatchEvent(new CustomEvent("pi-ui-older"))},0)}function V(){if(!d.pinnedToBottom||K)return;let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;let n=[...t.querySelectorAll("#message-list > .message[id]")],o=n.length-100;if(o<=0||t.scrollTop<=2*t.clientHeight)return;let r=t.getBoundingClientRect().top-2*t.clientHeight;for(let i of n.slice(0,o)){let s=i.getBoundingClientRect();if(s.height>0&&s.bottom>=r)return}t.dispatchEvent(new CustomEvent("pi-ui-trim",{detail:{firstId:n[0].id.slice(8),throughId:n[o-1].id.slice(8)}}))}function it(){document.addEventListener("scroll",(n)=>{let o=document.getElementById("messages");if(!(o instanceof HTMLElement)||n.target!==o)return;if((d.middleScrolling||d.pointerScrolling)&&o.scrollTop<d.scrollTop)E();if(!d.pinnedToBottom&&wn(d.scrollTop,o.scrollTop,o.scrollHeight-o.scrollTop-o.clientHeight))d.pinnedToBottom=!0,q(o,!0),o.scrollTop=o.scrollHeight,V();d.scrollTop=o.scrollTop,j()},!0);let t=(n)=>{if(n.button===1)d.middleScrolling=!0,E();else if(n.button===0&&N(n.target)){d.middleScrolling=!1,d.pointerScrolling=!0,S={x:n.clientX,y:n.clientY};let o=document.getElementById("messages");if(o instanceof HTMLElement)d.scrollTop=o.scrollTop}};document.addEventListener("pointerdown",t,{capture:!0,passive:!0}),document.addEventListener("pointermove",(n)=>{if(d.pointerScrolling&&S&&yn(S.x,S.y,n.clientX,n.clientY))S=void 0,E()},{capture:!0,passive:!0});for(let n of["pointerup","pointercancel"])document.addEventListener(n,()=>{d.middleScrolling=!1,d.pointerScrolling=!1,S=void 0},{capture:!0,passive:!0});document.addEventListener("wheel",(n)=>{if(!N(n.target))return;if(d.middleScrolling=!1,n.deltaY<0)E()},{capture:!0,passive:!0}),document.addEventListener("touchmove",(n)=>{if(N(n.target))E()},{capture:!0,passive:!0}),document.addEventListener("keydown",(n)=>{if(vn(n)&&N(n.target))E()},!0),document.addEventListener("visibilitychange",()=>{Ee();let n=document.getElementById("messages");if(!document.hidden&&d.pinnedToBottom&&n instanceof HTMLElement)nt(n,tt(n))}),ye(),O()}function yn(t,n,o,r){return Math.hypot(o-t,r-n)>=8}function wn(t,n,o){return n>t&&o<=8}function O(t="auto"){Ee(),d.middleScrolling=!1,d.pinnedToBottom=!0,d.pointerScrolling=!1;let n=document.getElementById("messages");if(!(n instanceof HTMLElement))return;q(n,!0),D??=window.matchMedia("(prefers-reduced-motion: reduce)"),n.scrollTo({top:n.scrollHeight,behavior:D.matches?"instant":t}),j(),V()}function E(){Ee(),d.pinnedToBottom=!1;let t=document.getElementById("messages");if(t instanceof HTMLElement)t.scrollTo({top:t.scrollTop,behavior:"instant"}),q(t,!1);j()}function N(t){let n=document.getElementById("messages");return n instanceof HTMLElement&&t instanceof Node&&n.contains(t)}function vn(t){return t.key==="ArrowUp"||t.key==="PageUp"||t.key==="Home"||t.key===" "&&t.shiftKey}function ye(){let t=document.querySelector("#messages > .messages-stack"),n=document.getElementById("prompt-box"),o=document.getElementById("messages");if(!t||!n||!o)return;if(t===Ze&&n===Qe)return;I??=new ResizeObserver(()=>{xn();let r=document.getElementById("messages");if(r instanceof HTMLElement&&d.pinnedToBottom)q(r,!0),nt(r,tt(r));j(),V()}),I.disconnect(),Ze=t,Qe=n,I.observe(t),I.observe(n),I.observe(o)}function xn(){let t=document.getElementById("prompt-box"),n=document.getElementById("messages-prompt-spacer");if(!(t instanceof HTMLElement)||!(n instanceof HTMLElement))return;let o=`${t.offsetHeight+48}px`;if(n.style.height!==o)n.style.height=o}function j(){let t=document.getElementById("messages");if(!(t instanceof HTMLElement))return;let n=!d.pinnedToBottom&&t.scrollHeight-t.scrollTop-t.clientHeight>=48;if(n===et)return;et=n,document.dispatchEvent(new CustomEvent("pi-ui-latest-changed",{detail:n}))}function st(t){if(!(t instanceof HTMLElement))return;let n=t.querySelector('template[shadowrootmode="open"]');if(!(n instanceof HTMLTemplateElement))return;(t.shadowRoot??t.attachShadow({mode:"open"})).replaceChildren(n.content.cloneNode(!0)),n.remove()}var at=!1;function ct(){if(at||!("Notification"in window)||!window.isSecureContext)return;if(Notification.permission!=="default")return;at=!0;try{if(localStorage.getItem("pi-ui-notifications-requested"))return;localStorage.setItem("pi-ui-notifications-requested","true")}catch{}Notification.requestPermission().catch(()=>{})}function lt({workspace:t,sessionPath:n}){if(!("Notification"in window)||Notification.permission!=="granted")return;if(document.hasFocus())return;try{let o=new Notification(`${t} finished`,{icon:document.querySelector('link[rel="icon"]')?.href,tag:n||t});o.onclick=()=>{window.focus(),o.close()}}catch{}}class we{#t=new Map;#e;sync(t,n){if(this.#e===void 0)return this.#e=t,null;if(t===this.#e)return null;return this.#t.set(this.#e,n),this.#e=t,this.#t.get(t)??""}}class ut{#t=[];#e=-1;#n="";#o="";sync(t){let n=JSON.stringify(t);if(n===this.#o)return;this.#o=n,this.#t=t,this.reset()}get browsing(){return this.#e>=0}reset(){this.#e=-1,this.#n=""}navigate(t,n){if(n==="up"){if(!this.browsing){if(t!==""||this.#t.length===0)return;this.#n=t,this.#e=0}else if(this.#e<this.#t.length-1)this.#e+=1;return{value:this.#t[this.#e],cursor:"start"}}if(!this.browsing)return;if(this.#e>0)return this.#e-=1,{value:this.#t[this.#e],cursor:"end"};let o=this.#n;return this.reset(),{value:o,cursor:"end"}}}function dt(){let t=new ut,n=!1;function o(i,s){if(i.isComposing||i.defaultPrevented||i.altKey||i.ctrlKey||i.metaKey||i.shiftKey||i.code!=="ArrowUp"&&i.code!=="ArrowDown")return!1;let a=m();if(i.target!==a||window.piUi.pickers.isOpen())return!1;if(t.sync(Array.isArray(s)?s:[]),t.browsing&&!Tn(a,i.code))return!1;let l=t.navigate(a.value,i.code==="ArrowUp"?"up":"down");if(!l)return!1;i.preventDefault(),n=!0,A(l.value),n=!1;let c=l.cursor==="start"?0:a.value.length;return a.selectionStart=c,a.selectionEnd=c,!0}function r(){if(!n)t.reset()}return{handleInput:r,handleKeydown:o}}function Tn(t,n){if(t.selectionStart!==t.selectionEnd)return!1;if(n==="ArrowUp"){let r=t.value.indexOf(`
|
|
5
5
|
`);return r<0||t.selectionStart<=r}let o=t.value.lastIndexOf(`
|
|
6
|
-
`)+1;return t.selectionEnd>=o}var
|
|
6
|
+
`)+1;return t.selectionEnd>=o}var An,f;function ft(){if(!z())return;f={startedAt:performance.now(),origin:"command"}}function z(){return document.getElementById("session-transition")?.hasAttribute("data-session-performance-enabled")}function mt(t,n){if(!z())return;if(t==="loading"){if(!f||f.generation!==void 0&&f.generation!==Number(n))f={startedAt:performance.now(),origin:"observer"};f.generation=Number(n),f.loadingObservedMs??=performance.now()-f.startedAt;return}if(t==="error"){f=void 0;return}if(t!=="idle"||f?.generation!==Number(n)||f.readyObservedMs!==void 0)return;let o=f;o.readyObservedMs=performance.now()-o.startedAt,ht(o,"readyFrameMs")}function pt(t,n){if(!z()||!f||f.generation!==Number(t)||f.firstTranscriptPatchMs!==void 0)return;let o=f;o.runId=n,o.firstTranscriptPatchMs=performance.now()-o.startedAt,ht(o,"firstTranscriptFrameMs")}function ht(t,n){requestAnimationFrame(()=>requestAnimationFrame(()=>{if(f!==t||document.hidden)return;if(t[n]=performance.now()-t.startedAt,t.firstTranscriptFrameMs===void 0||t.readyFrameMs===void 0)return;f=void 0;let{startedAt:o,...r}=t;document.body.dispatchEvent(new CustomEvent("pi-ui-session-performance",{detail:{pageId:An??=crypto.getRandomValues(new Uint32Array(4)).join("-"),...r}}))}))}if(z())document.addEventListener("visibilitychange",()=>{if(document.hidden)f=void 0});function bt(){if(!("popover"in HTMLElement.prototype))return;let t;document.addEventListener("pointerover",(n)=>{if(n.pointerType==="touch")return;gt(n.target)}),document.addEventListener("pointerout",(n)=>{Et(n.target,n.relatedTarget)}),document.addEventListener("focusin",(n)=>{let o=ve(n.target);if(!o)return;if(!o.matches(":focus-visible")&&!Mn(o))return;cancelAnimationFrame(t),t=requestAnimationFrame(()=>{if(o.matches(":focus-within"))gt(o)})}),document.addEventListener("focusout",(n)=>{Et(n.target,n.relatedTarget)}),document.addEventListener("keydown",(n)=>{if(n.key==="Escape")cancelAnimationFrame(t),Sn()})}function ve(t){return t instanceof Element?t.closest("[data-tooltip]")??void 0:void 0}function xe(t){let n=t?.querySelector('[data-slot="tooltip-content"]');return n instanceof HTMLElement?n:void 0}function Mn(t){return xe(t)?.classList.contains("usage-tooltip")===!0}function gt(t){let n=ve(t),o=xe(n);if(!o||o.matches(":popover-open"))return;o.showPopover({source:n})}function Et(t,n){let o=xe(ve(t));if(!o?.matches(":popover-open"))return;if(n instanceof Node&&o.contains(n))return;o.hidePopover()}function Sn(){for(let t of document.querySelectorAll('[data-slot="tooltip-content"]:popover-open'))if(t instanceof HTMLElement)t.hidePopover()}var J=100,Ln=120,Pn=17,Cn=33.333333333333336,b,W=0,L=0,Y=!1,G=0,_=0;function wt(){let t=!1;document.addEventListener("keydown",(n)=>{if(n.defaultPrevented||n.ctrlKey||n.metaKey||n.altKey||kn(n)){t=!1;return}if(document.querySelector(":modal"))return;if(t){if(t=!1,n.code==="KeyG"&&!n.shiftKey){n.preventDefault(),yt("top");return}}if(n.code==="KeyG"&&!n.shiftKey)n.preventDefault(),t=!0;else if(n.code==="KeyG"&&n.shiftKey)n.preventDefault(),yt("bottom");else if(n.code==="KeyJ"||n.code==="KeyK")n.preventDefault(),In(n.code==="KeyJ"?J:-J)}),document.addEventListener("keyup",(n)=>{if(n.code==="KeyJ"||n.code==="KeyK")Y=!1})}function kn(t){return Fn(t.composedPath()[0])}function Fn(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLElement&&t.isContentEditable}function In(t){let n=Math.sign(t);if(!b||L!==n)L=n,G=0,_=0,W=0;Y=!0,Hn(),E()}function yt(t){if(b)cancelAnimationFrame(b);if(b=void 0,L=0,Y=!1,t==="bottom"){O();return}let n=document.getElementById("messages");if(!(n instanceof HTMLElement))return;E(),n.scrollTop=0}function Hn(){if(b)return;let t=(n)=>{let o=document.getElementById("messages");if(!(o instanceof HTMLElement)||!L){b=void 0;return}let r=W?Math.min(Math.max(n-W,0),Cn):Pn;W=n;let i=o.scrollHeight-o.clientHeight,s=L*(J*r/Ln)+_,a=o.scrollTop,l=Math.max(0,Math.min(a+s,i));o.scrollTop=l;let c=l-a;if(_=s-c,G+=Math.abs(c),l===0||l===i||!Y&&G>=J){L=0,G=0,_=0,b=void 0;return}b=requestAnimationFrame(t)};b=requestAnimationFrame(t)}function Bn(t={}){let n=t.activeElement??(()=>document.activeElement),o=t.body??(()=>document.body),r=t.requestFrame??((c)=>requestAnimationFrame(c)),i,s=0;function a(){s+=1;let c=n();if(!vt(c)||c===o()){i=void 0;return}i=c,c.blur()}function l(){let c=i;if(i=void 0,!vt(c)||!c.isConnected)return;let p=s;r(()=>{if(s!==p||!c.isConnected)return;let w=n();if(w===c)return;if(w&&w!==o())return;c.focus({preventScroll:!0})})}return{restore:l,suspend:a}}function vt(t){return Boolean(t&&t.blur instanceof Function&&t.focus instanceof Function)}var xt=Bn();var Dn=dt(),qn=new we;window.piUi={copyText:X,controls:{refresh:Z,activate:P},codeTheme:{loadPreviews(){}},dateTime:{hydrate:Pe},fonts:{apply(){}},fileTransfer:he,messageScroll:{afterOlder:rt,beforeOlder:ot,bindResize:ye,checkOlder:be,hydratePierreDiff:st,scrollBottom:O},notifications:{requestPermission:ct,show:lt},pickers:{close:v,complete:De,isFileOpen:k,isOpen:U,sync:ce},prompt:{autofocus:oe,clear:()=>A(""),setValue:A},promptHistory:Dn,promptDrafts:qn,sessionPerformance:{observe:mt,start:ft,transcriptPatched:pt},windowFocus:xt,workspaceReview:{applyOpen:()=>{}},shouldAbortOnEscape(t){return!t.defaultPrevented&&!On()}};function On(){if(U()||document.querySelector(":modal"))return!0;return Boolean(document.querySelector("[popover]:popover-open:not([data-slot='tooltip-content'])"))}ke();window.addEventListener("DOMContentLoaded",async()=>{Me(),oe(),Be(),it(),Te(),bt(),wt(),Ce(),await Promise.all([(e("q8ytkktk"),import("./chunks/fonts-q8ytkktk.js")),(e("vm8gqreq"),import("./chunks/code-theme-vm8gqreq.js")),(e("sc4yfzz9"),import("./chunks/workspace-review-sc4yfzz9.js"))])});
|