pi-webapp 0.1.58-alpha.5 → 0.1.58

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/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- var B0=Object.defineProperty;var w=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}};var Hn=(t,e)=>{for(var i in e)B0(t,i,{get:e[i],enumerable:!0})};var bu={};Hn(bu,{listMacApps:()=>HS,openMacApp:()=>GS});import{execFile as LS}from"node:child_process";import{lstat as US}from"node:fs/promises";import{isAbsolute as qS}from"node:path/posix";import{promisify as jS}from"node:util";async function yu(t,e,i){let r=["-l","JavaScript","-e",BS,"--",t,e];i!==void 0&&r.push(i);let{stdout:n}=await hu("/usr/bin/osascript",r,{timeout:5e3,maxBuffer:640*1024});return JSON.parse(n)}async function Dr(t){try{return await US(t)}catch(e){if(e.code!=="ENOENT"&&e.code!=="ENOTDIR")throw e}}function fu(t,e){return e&&t.dev===e.dev&&t.ino===e.ino&&t.mode===e.mode}async function HS(t,e){if(process.platform!=="darwin"||!oo(t)||e!=="file"&&e!=="directory")return[];let i=await Dr(t);return(e==="directory"?i?.isDirectory():i?.isFile())?yu(t,e):[]}async function GS(t,e){if(process.platform!=="darwin"||!oo(t)||!oo(e)||!/\.app$/i.test(e))throw new Error("Invalid macOS Open With request");let[i,r]=await Promise.all([Dr(t),Dr(e)]),n=i?.isDirectory()?"directory":i?.isFile()?"file":void 0;if(!n||!r?.isDirectory()||await yu(t,n,e)!==!0)throw new Error("Document or associated macOS app unavailable");let[s,a]=await Promise.all([Dr(t),Dr(e)]);if(!fu(i,s)||!fu(r,a))throw new Error("Document or macOS app changed before opening");await hu("/usr/bin/open",["-a",e,"--",t],{timeout:5e3})}var hu,gu,FS,oo,BS,_u=w(()=>{"use strict";hu=jS(LS),gu=16,FS=16*1024,oo=t=>typeof t=="string"&&qS(t)&&!t.includes("\0"),BS=`
1
+ var G0=Object.defineProperty;var w=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}};var Hn=(t,e)=>{for(var i in e)G0(t,i,{get:e[i],enumerable:!0})};var vu={};Hn(vu,{listMacApps:()=>$S,openMacApp:()=>VS});import{execFile as jS}from"node:child_process";import{lstat as FS}from"node:fs/promises";import{isAbsolute as BS}from"node:path/posix";import{promisify as HS}from"node:util";async function _u(t,e,i){let r=["-l","JavaScript","-e",GS,"--",t,e];i!==void 0&&r.push(i);let{stdout:n}=await bu("/usr/bin/osascript",r,{timeout:5e3,maxBuffer:640*1024});return JSON.parse(n)}async function Dr(t){try{return await FS(t)}catch(e){if(e.code!=="ENOENT"&&e.code!=="ENOTDIR")throw e}}function yu(t,e){return e&&t.dev===e.dev&&t.ino===e.ino&&t.mode===e.mode}async function $S(t,e){if(process.platform!=="darwin"||!lo(t)||e!=="file"&&e!=="directory")return[];let i=await Dr(t);return(e==="directory"?i?.isDirectory():i?.isFile())?_u(t,e):[]}async function VS(t,e){if(process.platform!=="darwin"||!lo(t)||!lo(e)||!/\.app$/i.test(e))throw new Error("Invalid macOS Open With request");let[i,r]=await Promise.all([Dr(t),Dr(e)]),n=i?.isDirectory()?"directory":i?.isFile()?"file":void 0;if(!n||!r?.isDirectory()||await _u(t,n,e)!==!0)throw new Error("Document or associated macOS app unavailable");let[s,a]=await Promise.all([Dr(t),Dr(e)]);if(!yu(i,s)||!yu(r,a))throw new Error("Document or macOS app changed before opening");await bu("/usr/bin/open",["-a",e,"--",t],{timeout:5e3})}var bu,hu,WS,lo,GS,wu=w(()=>{"use strict";bu=HS(jS),hu=16,WS=16*1024,lo=t=>typeof t=="string"&&BS(t)&&!t.includes("\0"),GS=`
2
2
  ObjC.import("AppKit");
3
3
 
4
4
  function localPath(url) {
@@ -20,7 +20,7 @@ function pngIcon(workspace, path) {
20
20
  }
21
21
  if (!(bitmap.pixelsWide <= 64 && bitmap.pixelsHigh <= 64)) return;
22
22
  const png = bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $.NSDictionary.dictionary);
23
- if (png.length > 0 && png.length <= ${FS}) {
23
+ if (png.length > 0 && png.length <= ${WS}) {
24
24
  return "data:image/png;base64," + ObjC.unwrap(png.base64EncodedStringWithOptions(0));
25
25
  }
26
26
  }
@@ -43,7 +43,7 @@ function run(argv) {
43
43
  const bundleIds = new Set();
44
44
  const entries = [];
45
45
  // Visit the default first even when Launch Services orders the array differently.
46
- for (let i = -1; i < handlers.count && entries.length < ${gu}; i++) {
46
+ for (let i = -1; i < handlers.count && entries.length < ${hu}; i++) {
47
47
  const url = i === -1 ? primary : handlers.objectAtIndex(i);
48
48
  const id = localPath(url);
49
49
  if (!id || !/^\\/.*\\.app$/is.test(id) || seen.has(id) || !installedRoots.some(root => id.startsWith(root))) continue;
@@ -59,7 +59,7 @@ function run(argv) {
59
59
  bundleIds.add(bundleId);
60
60
  if (selected) {
61
61
  if (id === selected) return "true";
62
- if (bundleIds.size === ${gu}) return "false";
62
+ if (bundleIds.size === ${hu}) return "false";
63
63
  continue;
64
64
  }
65
65
  const displayName = ObjC.unwrap(files.displayNameAtPath(id));
@@ -74,7 +74,7 @@ function run(argv) {
74
74
  }
75
75
  return selected ? "false" : JSON.stringify(entries);
76
76
  }
77
- `});var Tu={};Hn(Tu,{createWindowsOpenWith:()=>ku,listWindowsApps:()=>YS,openWindowsApp:()=>QS});import{execFile as WS}from"node:child_process";import{win32 as vu}from"node:path";function lo(t){if(typeof t!="string"||t.length>4096||!/^[a-z]:[\\/]/i.test(t))return;let e=t.slice(3).replaceAll("/","\\");if(!e)return t.slice(0,2)+"\\";let i=e.replace(/\\$/,"");if(!i.split("\\").some(r=>!r||/[<>:"|?*\x00-\x1f]|[. ]$|\.\{[0-9a-f-]+\}$/i.test(r)||$S.test(r)))return t.slice(0,2)+"\\"+i}function ku({platform:t=process.platform,systemRoot:e=process.env.SystemRoot,exec:i=WS}={}){let r=lo(e),n=r&&vu.join(r,"System32"),s=n&&vu.join(n,"WindowsPowerShell","v1.0","powershell.exe");async function a(o){if(!(t!=="win32"||!s))try{let l=await new Promise((c,p)=>{let d=i(s,KS,{cwd:n,shell:!1,windowsHide:!0,timeout:1e4,maxBuffer:524288},(m,g)=>m?p(m):c(g));d.stdin.on("error",p),d.stdin.end(JSON.stringify(o),"utf8")});return JSON.parse(l)}catch{}}return{async listWindowsApps(o,l){if(o=lo(o),!o||l!=="file"&&l!=="directory")return[];let c=await a({op:"list",path:o,kind:l});if(!Array.isArray(c))return[];let p=new Map;for(let d of c){if(typeof d?.id!="string"||!wu.test(d.id)||p.has(d.id)||typeof d.name!="string"||!d.name.trim()||d.name.length>256)continue;let m=typeof d.icon=="string"&&d.icon.length<=24e3&&/^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(d.icon)?d.icon:void 0;if(p.set(d.id,{id:d.id,name:d.name,...m&&{icon:m},...d.isDefault===!0?{isDefault:!0}:{}}),p.size===Su)break}return[...p.values()]},async openWindowsApp(o,l){return o=lo(o),!o||typeof l!="string"||!wu.test(l)?!1:await a({op:"open",path:o,appId:l})===!0}}}async function YS(t,e){return Eu.listWindowsApps(t,e)}async function QS(t,e){return Eu.openWindowsApp(t,e)}var Su,wu,$S,VS,zS,KS,Eu,Iu=w(()=>{"use strict";Su=16,wu=/^win:[a-f0-9]{64}$/,$S=/^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9¹²³]|LPT[0-9¹²³]) *(?:\.|$)/i;VS=String.raw`
77
+ `});var Au={};Hn(Au,{createWindowsOpenWith:()=>Tu,listWindowsApps:()=>XS,openWindowsApp:()=>ZS});import{execFile as zS}from"node:child_process";import{win32 as Su}from"node:path";function co(t){if(typeof t!="string"||t.length>4096||!/^[a-z]:[\\/]/i.test(t))return;let e=t.slice(3).replaceAll("/","\\");if(!e)return t.slice(0,2)+"\\";let i=e.replace(/\\$/,"");if(!i.split("\\").some(r=>!r||/[<>:"|?*\x00-\x1f]|[. ]$|\.\{[0-9a-f-]+\}$/i.test(r)||KS.test(r)))return t.slice(0,2)+"\\"+i}function Tu({platform:t=process.platform,systemRoot:e=process.env.SystemRoot,exec:i=zS}={}){let r=co(e),n=r&&Su.join(r,"System32"),s=n&&Su.join(n,"WindowsPowerShell","v1.0","powershell.exe");async function a(o){if(!(t!=="win32"||!s))try{let l=await new Promise((c,p)=>{let d=i(s,JS,{cwd:n,shell:!1,windowsHide:!0,timeout:1e4,maxBuffer:524288},(m,g)=>m?p(m):c(g));d.stdin.on("error",p),d.stdin.end(JSON.stringify(o),"utf8")});return JSON.parse(l)}catch{}}return{async listWindowsApps(o,l){if(o=co(o),!o||l!=="file"&&l!=="directory")return[];let c=await a({op:"list",path:o,kind:l});if(!Array.isArray(c))return[];let p=new Map;for(let d of c){if(typeof d?.id!="string"||!ku.test(d.id)||p.has(d.id)||typeof d.name!="string"||!d.name.trim()||d.name.length>256)continue;let m=typeof d.icon=="string"&&d.icon.length<=24e3&&/^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(d.icon)?d.icon:void 0;if(p.set(d.id,{id:d.id,name:d.name,...m&&{icon:m},...d.isDefault===!0?{isDefault:!0}:{}}),p.size===Eu)break}return[...p.values()]},async openWindowsApp(o,l){return o=co(o),!o||typeof l!="string"||!ku.test(l)?!1:await a({op:"open",path:o,appId:l})===!0}}}async function XS(t,e){return Iu.listWindowsApps(t,e)}async function ZS(t,e){return Iu.openWindowsApp(t,e)}var Eu,ku,KS,YS,QS,JS,Iu,xu=w(()=>{"use strict";Eu=16,ku=/^win:[a-f0-9]{64}$/,KS=/^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9¹²³]|LPT[0-9¹²³]) *(?:\.|$)/i;YS=String.raw`
78
78
  $ErrorActionPreference = 'Stop'
79
79
  [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
80
80
  [Console]::OutputEncoding = [Console]::InputEncoding
@@ -302,23 +302,23 @@ public static class OpenWithWindows {
302
302
  }
303
303
  '@
304
304
  if ($request.op -eq 'list') {
305
- $apps = [OpenWithWindows]::List($request.path, $request.kind, ${Su})
305
+ $apps = [OpenWithWindows]::List($request.path, $request.kind, ${Eu})
306
306
  [Console]::WriteLine((ConvertTo-Json -InputObject $apps -Compress))
307
307
  } elseif ($request.op -eq 'open') {
308
308
  $ok = [OpenWithWindows]::Open($request.path, $request.appId)
309
309
  [Console]::WriteLine((ConvertTo-Json -InputObject $ok -Compress))
310
310
  }
311
- `,zS=Buffer.from(VS.replace(/^ +/gm,""),"utf16le").toString("base64"),KS=["-NoLogo","-NoProfile","-NonInteractive","-STA","-EncodedCommand",zS];Eu=ku()});var xm,Om=w(()=>{xm=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var B,Re=w(()=>{B=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var Y,st=w(()=>{Y=globalThis});var Rt,ss=w(()=>{Rt="11.15.0"});function _e(){return $e(Y),Y}function $e(t){let e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||"11.15.0",e[Rt]=e["11.15.0"]||{}}function bt(t,e,i=Y){let r=i.__SENTRY__=i.__SENTRY__||{},n=r[Rt]=r["11.15.0"]||{};return n[t]||(n[t]=e())}var at=w(()=>{ss();st()});function ot(t){if(!("console"in Y))return t();let e=Y.console,i={},r=Object.keys(ho);r.forEach(n=>{let s=ho[n];i[n]=e[n],e[n]=s});try{return t()}finally{r.forEach(n=>{e[n]=i[n]})}}function TE(){bo().enabled=!0}function IE(){bo().enabled=!1}function Rm(){return bo().enabled}function AE(...t){yo("log",...t)}function xE(...t){yo("warn",...t)}function OE(...t){yo("error",...t)}function yo(t,...e){B&&Rm()&&ot(()=>{Y.console[t](`${EE}[${t}]:`,...e)})}function bo(){return B?bt("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var EE,ho,q,Ne=w(()=>{at();Re();st();EE="Sentry Logger ",ho={};q={enable:TE,disable:IE,isEnabled:Rm,log:AE,warn:xE,error:OE}});function vo(...t){let e=t.sort((i,r)=>i[0]-r[0]).map(i=>i[1]);return(i,r=0,n=0)=>{let s=[],a=i.split(`
312
- `);for(let o=r;o<a.length;o++){let l=a[o];l.length>1024&&(l=l.slice(0,1024));let c=Nm.test(l)?l.replace(Nm,"$1"):l;if(!c.includes("Error: ")){for(let p of e){let d=p(c);if(d){s.push(d);break}}if(s.length>=50+n)break}}return Cm(s.slice(n))}}function Cm(t){if(!t.length)return[];let e=Array.from(t);return/sentryWrapped/.test(as(e).function||"")&&e.pop(),e.reverse(),Pm.test(as(e).function||"")&&(e.pop(),Pm.test(as(e).function||"")&&e.pop()),e.slice(0,50).map(i=>({...i,filename:i.filename||as(e).filename,function:i.function||"?"}))}function as(t){return t[t.length-1]||{}}function wo(t){try{return!t||typeof t!="function"?_o:t.name||_o}catch{return _o}}function Dm(t){let e=t?.startsWith("file://")?t.slice(7):t;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var Nm,Pm,_o,os=w(()=>{Nm=/\(error: (.*)\)/,Pm=/captureMessage|captureException/;_o="<anonymous>"});function lt(t){switch(Mm.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return jm(t,Error)}}function ls(t,e){return Mm.call(t)===`[object ${e}]`}function Lm(t){return ls(t,"ErrorEvent")}function Lr(t){return ls(t,"String")}function Ur(t){return typeof t=="object"&&t!==null&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function _t(t){return t===null||Ur(t)||typeof t!="object"&&typeof t!="function"}function gi(t){return ls(t,"Object")}function qr(t){return typeof t=="object"&&t!==null}function Um(t){return typeof Event<"u"&&jm(t,Event)}function qm(t){return ls(t,"RegExp")}function Nt(t){return!!(t?.then&&typeof t.then=="function")}function jm(t,e){try{return t instanceof e}catch{return!1}}var Mm,qe=w(()=>{Mm=Object.prototype.toString});function cs(t,e,i){try{Object.defineProperty(t,e,{value:i,writable:!0,configurable:!0})}catch{B&&q.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}function So(t){if(lt(t))return{message:t.message,name:t.name,stack:t.stack,...Fm(t)};if(Um(t)){let{type:e,target:i,currentTarget:r,detail:n}=t;return{type:e,target:i,currentTarget:r,...n?{detail:n}:{},...Fm(t)}}return t}function Fm(t){return qr(t)?Object.fromEntries(Object.entries(t)):{}}function Bm(t){let e=Object.keys(So(t));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var jr=w(()=>{Re();Ne();qe()});function Gt(t){if($i!==void 0)return $i?$i(t):t();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),i=Y;return e in i&&typeof i[e]=="function"?($i=i[e],$i(t)):($i=null,t())}function Xe(){return Gt(()=>Math.random())}function Pe(){return Gt(()=>Date.now())}var $i,ct=w(()=>{st()});function Hm(t){return!!t[RE]}function Gm(t){let e=t[NE];return typeof e=="number"?e:void 0}var RE,NE,Wm=w(()=>{RE=Symbol.for("sentry.skipNormalization"),NE=Symbol.for("sentry.overrideNormalizationDepth")});function pt(t,e=100,i=1/0){try{return ko("",t,e,i)}catch(r){return{ERROR:`**non-serializable** (${Vm(r)})`}}}function Vm(t){try{return String(t)}catch{return"unknown error"}}function Eo(t,e=3,i=102400){let r=pt(t,e);return DE(r)>i?Eo(t,e-1,i):r}function ko(t,e,i=1/0,r=1/0,n=ME()){let[s,a]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let o=To(t,e);if(!o.startsWith("[object "))return o;if(Hm(e))return e;let l=Gm(e),c=l!==void 0?l:i;if(c===0)return o.replace("object ","");if(s(e))return"[Circular ~]";let p=e;if(p&&typeof p.toJSON=="function")try{return ko("",p.toJSON(),c-1,r,n)}catch{}let d=Array.isArray(e)?[]:{},m=0,g=So(e);for(let h in g){if(!Object.prototype.hasOwnProperty.call(g,h))continue;if(m>=r){d[h]="[MaxProperties ~]";break}let f=g[h];d[h]=ko(h,f,c-1,r,n),m++}return a(e),d}function To(t,e){try{if($m){let i=$m(e);if(i)return i}return typeof global<"u"&&e===global?"[Global]":typeof e=="number"&&!Number.isFinite(e)?`[${e}]`:typeof e=="function"?`[Function: ${wo(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${PE(e)}]`}catch(i){return`**non-serializable** (${Vm(i)})`}}function PE(t){let e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function CE(t){return~-encodeURI(t).split(/%..|./).length}function DE(t){return CE(JSON.stringify(t))}function ME(){let t=new WeakSet;function e(r){return t.has(r)?!0:(t.add(r),!1)}function i(r){t.delete(r)}return[e,i]}var $m,ps=w(()=>{Wm();jr();os()});function Io(t){return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var zm=w(()=>{});function Km(t,e="[unserializable]"){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return typeof e=="function"?e(t):e}}function Fr(t,e=0){return typeof t!="string"||e===0||t.length<=e?t:`${t.slice(0,e)}...`}function Br(t,e,i=!1){return Lr(t)?qm(e)?e.test(t):Lr(e)?i?t===e:t.includes(e):typeof e=="function"?e(t):!1:!1}var Hr=w(()=>{qe()});function LE(){let t=Y;return t.crypto||t.msCrypto}function UE(){return Xe()*16}function we(t=LE()){try{if(t?.randomUUID)return Gt(()=>t.randomUUID()).replace(/-/g,"")}catch{}return Ao||(Ao="10000000100040008000100000000000"),Ao.replace(/[018]/g,e=>(e^(UE()&15)>>e/4).toString(16))}function qE(t){return t.exception?.values?.[0]}function Oo(t,e,i){let r=t.exception=t.exception||{},n=r.values=r.values||[],s=n[0]=n[0]||{};s.value||(s.value=e||""),s.type||(s.type=i||"Error")}function ds(t,e){let i=qE(t);i&&Qm(i,e)}function Ym(t,e){let i=t.exception?.values,r=i?.find(n=>n.mechanism?.exception_id===0)??i?.[0];r&&Qm(r,e)}function Qm(t,e){let i={type:"generic",handled:!0},r=t.mechanism;t.mechanism={...i,...r,...e},e&&"data"in e&&(t.mechanism.data={...r?.data,...e.data})}function xo(t){return parseInt(t||"",10)}function Ro(t){let e=t.match(jE)||[],i=xo(e[1]),r=xo(e[2]),n=xo(e[3]);return{buildmetadata:e[5],major:isNaN(i)?void 0:i,minor:isNaN(r)?void 0:r,patch:isNaN(n)?void 0:n,prerelease:e[4]}}function us(t){if(Jm(t))return!0;try{cs(t,"__sentry_captured__",!0)}catch{}return!1}function Jm(t){try{return t.__sentry_captured__}catch{}}var Ao,jE,Pt=w(()=>{jr();ct();st();jE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/});function fi(){return Pe()/Zm}function HE(){let{performance:t}=Y;if(!t?.now||!t.timeOrigin)return t?.now&&(Vi=[{from:0,origin:Pe()-Gt(()=>t.now())}]),fi;let e=t.timeOrigin;Vi=[{from:0,origin:e}];let i=!0,r=0;return()=>Gt(()=>{let n=t.now(),s=Date.now();return Math.abs(e+n-s)>FE&&(e=s-n,i?Vi=[{from:0,origin:e}]:(Vi.push({from:r,origin:e}),Vi.length>BE&&Vi.splice(1,1))),i=!1,r=n,(e+n)/Zm})}function ms(){return(Xm??(Xm=HE()))()}var Zm,FE,BE,Vi,Xm,zi=w(()=>{ct();st();Zm=1e3,FE=1e3,BE=100;Vi=[]});function Gr(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),!t.did&&!e.did&&(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||ms(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=e.sid.length===32?e.sid:we()),e.init!==void 0&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),typeof e.started=="number"&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if(typeof e.duration=="number")t.duration=e.duration;else{let i=t.timestamp-t.started;t.duration=i>=0?i:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),typeof e.errors=="number"&&(t.errors=e.errors),e.status&&(t.status=e.status)}var No=w(()=>{Pt();zi()});function Wt(t,e,i=2){if(!e||typeof e!="object"||i<=0)return e;if(t&&Object.keys(e).length===0)return t;let r={...t};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Wt(r[n],e[n],i-1));return r}var gs=w(()=>{});function hi(){return we()}function Wr(){return we().substring(16)}var $r=w(()=>{Pt()});var GE,Ve,Ki=w(()=>{Re();No();Ne();qe();jr();gs();Pt();$r();ct();Hr();zi();GE=100,Ve=class Po{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},cs(this,"refs",{}),this._propagationContext={traceId:hi(),sampleRand:Xe()}}clone(){let e=new Po;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._attributes={...this._attributes},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,e._conversationId=this._conversationId,e.refs={...this.refs},e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Gr(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,i){return this.setTags({[e]:i})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,i){return this.setAttributes({[e]:i})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,i){return this._extra={...this._extra,[e]:i},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,i){return i===null?delete this._contexts[e]:this._contexts[e]=i,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;let i=typeof e=="function"?e(this):e,{tags:r,attributes:n,extra:s,user:a,contexts:o,level:l,fingerprint:c=[],propagationContext:p,conversationId:d}=(i instanceof Po?i.getScopeData():gi(i)?e:void 0)||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...n},this._extra={...this._extra,...s},this._contexts={...this._contexts,...o},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),c.length&&(this._fingerprint=c),p&&(this._propagationContext=p),d&&(this._conversationId=d),this}addBreadcrumb(e,i){let r=typeof i=="number"?i:GE;if(r<=0)return this;let n={timestamp:fi(),...e,message:e.message?Fr(e.message,2048):e.message};return this._breadcrumbs.push(n),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r)),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Wt(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,i){let r=i?.event_id||we();if(!this._client)return B&&q.warn("No client configured on scope - will not capture exception!"),r;let n=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:n,...i,event_id:r},this),r}captureMessage(e,i,r){let n=r?.event_id||we();if(!this._client)return B&&q.warn("No client configured on scope - will not capture message!"),n;let s=r?.syntheticException??new Error(e);return this._client.captureMessage(e,i,{originalException:e,syntheticException:s,...r,event_id:n},this),n}captureEvent(e,i){let r=e.event_id||i?.event_id||we();return this._client?(this._client.captureEvent(e,{...i,event_id:r},this),r):(B&&q.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}});function yi(){return bt("defaultCurrentScope",()=>new Ve)}function bi(){return bt("defaultIsolationScope",()=>new Ve)}var Co=w(()=>{at();Ki()});var Do,eg=w(()=>{Do="__SENTRY_SUPPRESS_TRACING__"});var tg,ig,rg,WE,ng=w(()=>{tg=t=>t instanceof Promise&&!t[ig],ig=Symbol("chained PromiseLike"),rg=(t,e,i)=>{let r=t.then(n=>(e(n),n),n=>{throw i(n),n});return tg(r)&&tg(t)?r:WE(t,r)},WE=(t,e)=>{if(!e)return t;let i=!1;for(let r in t){if(r in e)continue;i=!0;let n=t[r];typeof n=="function"?Object.defineProperty(e,r,{value:(...s)=>n.apply(t,s),enumerable:!0,configurable:!0,writable:!0}):e[r]=n}return i&&Object.assign(e,{[ig]:!0}),e}});function Yi(){let t=_e(),e=$e(t);return e.stack=e.stack||new $E(yi(),bi())}function ag(t){return Yi().withScope(t)}function VE(t,e){let i=Yi();return i.withScope(()=>(i.getStackTop().scope=t,e(t)))}function sg(t){return Yi().withScope(()=>t(Yi().getIsolationScope()))}function og(){return{suppressTracing:zE,withIsolationScope:sg,withScope:ag,withSetScope:VE,withSetIsolationScope:(t,e)=>sg(e),getCurrentScope:()=>Yi().getScope(),getIsolationScope:()=>Yi().getIsolationScope()}}function zE(t){return ag(e=>{e.setSDKProcessingMetadata({[Do]:!0});let i=t();return e.setSDKProcessingMetadata({[Do]:void 0}),i})}var $E,lg=w(()=>{Co();Ki();eg();ng();qe();at();$E=class{constructor(t,e){let i;t?i=t:i=new Ve;let r;e?r=e:r=new Ve,this._stack=[{scope:i}],this._isolationScope=r}withScope(t){let e=this._pushScope(),i;try{i=t(e)}catch(r){throw this._popScope(),r}return Nt(i)?rg(i,()=>this._popScope(),()=>this._popScope()):(this._popScope(),i)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}});function Vr(t){let e=_e(),i=$e(e);i.acs=t}function dt(t){let e=$e(t);return e.acs?e.acs:og()}var fs=w(()=>{at();lg()});function KE(t){return typeof t=="object"&&t!=null&&!Array.isArray(t)&&Object.keys(t).includes("value")}function YE(t,e){let{value:i,unit:r}=KE(t)?t:{value:t,unit:void 0},n=QE(i),s=r&&typeof r=="string"?{unit:r}:{};if(n)return{...n,...s};if(!e||e==="skip-undefined"&&i===void 0)return;let a="";try{a=JSON.stringify(i)??""}catch{}return{value:a,type:"string",...s}}function Mo(t,e=!1){let i={};for(let[r,n]of Object.entries(t??{})){let s=YE(n,e);s&&(i[r]=s)}return i}function Lo(t){if(!t)return 0;let e=0;for(let[i,r]of Object.entries(t)){e+=i.length*2,e+=r.type.length*2,e+=(r.unit?.length??0)*2;let n=r.value;Array.isArray(n)?e+=cg(n[0])*n.length:_t(n)?e+=cg(n):e+=100}return e}function cg(t){return typeof t=="string"?t.length*2:typeof t=="boolean"?4:typeof t=="number"?8:0}function QE(t){if(Array.isArray(t))return{value:t,type:"array"};let e=typeof t=="string"?"string":typeof t=="boolean"?"boolean":typeof t=="number"&&!Number.isNaN(t)?Number.isInteger(t)?"integer":"double":null;if(e)return{value:t,type:e}}var Uo=w(()=>{qe()});function hs(){return $e(_e()).externalPropagationContextProvider?.()}function Ct(){let t=_e();return dt(t).getCurrentScope()}function _i(){let t=_e();return dt(t).getIsolationScope()}function qo(){return bt("globalScope",()=>new Ve)}function ys(...t){let e=_e(),i=dt(e);if(t.length===2){let[r,n]=t;return r?i.withSetScope(r,n):i.withScope(n)}return i.withScope(t[0])}function vt(){return Ct().getClient()}function vi(t){let e=hs();if(e)return{trace_id:e.traceId,span_id:e.spanId};let{traceId:i,parentSpanId:r,propagationSpanId:n}=t.getPropagationContext(),s={trace_id:i,span_id:n||Wr()};return r&&(s.parent_span_id=r),s}var ut=w(()=>{fs();at();Ki();$r()});var pg,dg=w(()=>{pg="sentry.custom_span_name"});var ug,mg=w(()=>{ug=["ok","deadline_exceeded","unauthenticated","permission_denied","not_found","resource_exhausted","invalid_argument","unimplemented","unavailable","internal_error","unknown_error","cancelled","already_exists","failed_precondition","aborted","out_of_range","data_loss"]});var gg,fg,hg,yg,bg,_g,vg,jo,wg,Sg,kg,zr,Eg,Tg,Ig,Ag,xg,Kr,Fo,Og,Rg,bs,Ng,Pg,Cg,Dg,Mg,Lg,wt=w(()=>{gg="angular.version",fg="culture.locale",hg="culture.timezone",yg="http.response.body.size",bg="http.response.status_code",_g="react.version",vg="sentry.environment",jo="sentry.exclusive_time",wg="sentry.op",Sg="sentry.origin",kg="sentry.profiler_id",zr="sentry.profile_id",Eg="sentry.release",Tg="sentry.sdk.integrations",Ig="sentry.sdk.name",Ag="sentry.sdk.version",xg="sentry.segment.id",Kr="sentry.segment.name",Fo="sentry.segment.name.source",Og="sentry.status.message",Rg="sentry.trace_lifecycle",bs="server.address",Ng="state.type",Pg="url.path",Cg="user.email",Dg="user.id",Mg="user.ip_address",Lg="user.name"});function Ug(t){return t!=="ok"&&ug.includes(t)}var qg=w(()=>{mg()});function Qi(t){try{let e=Y.WeakRef;if(typeof e=="function")return new e(t)}catch{}return t}function wi(t){if(t){if(typeof t=="object"&&"deref"in t&&typeof t.deref=="function")try{return t.deref()}catch{return}return t}}var _s=w(()=>{st()});function $t(t){let e=t;return{scope:e[JE],isolationScope:wi(e[XE])}}var JE,XE,vs=w(()=>{_s();JE="_sentryScope",XE="_sentryIsolationScope"});function Yr(t){let e=Fg(t);if(!e)return;let i=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith("sentry-")){let a=n.slice(7);r[a]=s}return r},{});if(Object.keys(i).length>0)return i}function Fg(t){if(!(!t||!Lr(t)&&!Array.isArray(t)))return Array.isArray(t)?t.reduce((e,i)=>{let r=jg(i);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):jg(t)}function jg(t){return t.split(",").map(e=>{let i=e.indexOf("=");return i===-1?[]:[e.slice(0,i),e.slice(i+1)].map(r=>{try{return decodeURIComponent(r.trim())}catch{return}})}).reduce((e,[i,r])=>(i&&r&&(e[i]=r),e),{})}var Bo=w(()=>{qe()});function tT(t){return t==="http"||t==="https"}function ze(t,e=!1){let{host:i,path:r,pass:n,port:s,projectId:a,protocol:o,publicKey:l}=t;return`${o}://${l}${e&&n?`:${n}`:""}@${i}${s?`:${s}`:""}/${r&&`${r}/`}${a}`}function iT(t){let e=eT.exec(t);if(!e){ot(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});return}let[i,r,n="",s="",a="",o=""]=e.slice(1),l="",c=o,p=c.split("/");if(p.length>1&&(l=p.slice(0,-1).join("/"),c=p.pop()),c){let d=c.match(/^\d+/);d&&(c=d[0])}return Bg({host:s,pass:n,path:l,projectId:c,port:a,protocol:i,publicKey:r})}function Bg(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function rT(t){if(!B)return!0;let{port:e,projectId:i,protocol:r}=t;return["protocol","publicKey","host","projectId"].find(n=>t[n]?!1:(q.error(`Invalid Sentry Dsn: ${n} missing`),!0))?!1:i.match(/^\d+$/)?tT(r)?e&&isNaN(parseInt(e,10))?(q.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(q.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(q.error(`Invalid Sentry Dsn: Invalid projectId ${i}`),!1)}function nT(t){return t.match(ZE)?.[1]}function Hg(t){let e=t.getOptions(),{host:i}=t.getDsn()||{},r;return e.orgId?r=String(e.orgId):i&&(r=nT(i)),r}function Qr(t){let e=typeof t=="string"?iT(t):Bg(t);if(!(!e||!rT(e)))return e}var ZE,eT,Vt=w(()=>{Re();Ne();ZE=/^o(\d+)\./,eT=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function Gg(t){if(typeof t=="boolean")return Number(t);let e=typeof t=="string"?parseFloat(t):t;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}var Wg=w(()=>{});function Jr(t){return!!t.parentSpanId||!!t.dsc}var $g=w(()=>{});function ws(t,e){e?t.refs[Ho]=Qi(e):delete t.refs[Ho]}function Vg(t){return wi(t.refs[Ho])}var Ho,Go=w(()=>{_s();Ho="span"});function ks(t){let{spanId:e,traceId:i,isRemote:r}=t.spanContext(),n=r?e:Ji(t).parent_span_id,s=$t(t).scope;return{parent_span_id:n,span_id:r?s?.getPropagationContext().propagationSpanId||Wr():e,trace_id:i}}function sT(t){if(t&&t.length>0)return t.map(({context:{spanId:e,traceId:i,traceFlags:r,...n},attributes:s})=>({span_id:e,trace_id:i,sampled:r===1,attributes:s,...n}))}function aT(t){if(t?.length)return t.map(({context:{spanId:e,traceId:i,traceFlags:r},attributes:n})=>({span_id:e,trace_id:i,sampled:r===1,attributes:n}))}function Ss(t){return typeof t=="number"?zg(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?zg(t.getTime()):ms()}function zg(t){return t>9999999999?t/1e3:t}function Ji(t){if(Jg(t))return t.getStaticSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(Qg(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{span_id:e,trace_id:i,data:r,description:s,parent_span_id:Yg(t),start_timestamp:Ss(n),timestamp:Ss(a)||void 0,status:oT(o),op:r[wg],origin:r[Sg],links:sT(l)}}return{span_id:e,trace_id:i,start_timestamp:0,status:"ok",data:{}}}function Xr(t){if(Jg(t))return t.getSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(Qg(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{name:s,span_id:e,trace_id:i,parent_span_id:Yg(t),start_timestamp:Ss(n),end_timestamp:Ss(a)||void 0,is_segment:Kg(t),status:Xg(o),attributes:lT(r,o),links:aT(l)}}return{span_id:e,trace_id:i,start_timestamp:0,name:"",status:"ok",is_segment:Kg(t),attributes:{}}}function Yg(t){return"parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0}function Es(t){return{...t,end_timestamp:t.end_timestamp??t.start_timestamp,attributes:Mo(t.attributes),links:t.links?.map(e=>({...e,attributes:Mo(e.attributes)}))}}function Qg(t){let e=t;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function Jg(t){return typeof t.getSpanJSON=="function"}function Ts(t){let{traceFlags:e}=t.spanContext();return e===1}function oT(t){return!t||t.code===0||t.code===1?"ok":t.message&&Ug(t.message)?t.message:"internal_error"}function Xg(t){return!t||t.code===1||t.code===0||t.message==="cancelled"?"ok":"error"}function lT(t,e){let i=Xg(e)==="error"?e?.message:void 0;return{...i&&{[Og]:i},...t}}function As(t){return t[cT]||t}function Kg(t){return t===As(t)}function Zr(t){let e=_e(),i=dt(e);return i.getActiveSpan?i.getActiveSpan(t):Vg(t||Ct())}var cT,Is,Dt=w(()=>{fs();Uo();at();ut();qg();vs();$r();zi();Go();wt();cT="_sentryRootSpan",Is=As});function Wo(t){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=t||vt()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var Zg=w(()=>{ut()});function ef(t){q.log(`Ignoring span ${t.op} - ${t.description} because it matches \`ignoreSpans\`.`)}function $o(t,e){if(!e?.length)return!1;for(let i of e){if(dT(i)){if(t.description&&Br(t.description,i))return B&&ef(t),!0;continue}let r=!!i.attributes&&Object.keys(i.attributes).length>0;if(!i.name&&!i.op&&!r)continue;let n=i.name?t.description&&Br(t.description,i.name):!0,s=i.op?t.op&&Br(t.op,i.op):!0,a=i.attributes?Object.entries(i.attributes).every(([o,l])=>pT(t.attributes?.[o],l)):!0;if(n&&s&&a)return B&&ef(t),!0}return!1}function pT(t,e){return typeof t=="string"&&(typeof e=="string"||e instanceof RegExp)?Br(t,e):Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((i,r)=>i===e[r]):t===e}function tf(t,e){let i=e.parent_span_id,r=e.span_id;if(i)for(let n of t)n.parent_span_id===r&&(n.parent_span_id=i)}function dT(t){return typeof t=="string"||t instanceof RegExp}var rf=w(()=>{Re();Ne();Hr()});function sf(t,e){let i={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(t)}),e.forEach(r=>{r&&zo(t,r,i)}),i}function Vo(t,e){for(let i of e)i?.afterAllSetup&&i.afterAllSetup(t)}function zo(t,e,i){if(i[e.name]){B&&q.log(`Integration skipped because it was already installed: ${e.name}`);return}if(i[e.name]=e,!nf.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),nf.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(t),typeof e.preprocessEvent=="function"){let r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(n,s)=>r(n,s,t))}if(typeof e.processEvent=="function"){let r=e.processEvent.bind(e),n=Object.assign((s,a)=>r(s,a,t),{id:e.name});t.addEventProcessor(n)}["processSpan","processSegmentSpan"].forEach(r=>{let n=e[r];typeof n=="function"&&t.on(r,s=>n.call(e,s,t))}),B&&q.log(`Integration installed: ${e.name}`)}var nf,af=w(()=>{Re();Ne();nf=[]});var of,lf=w(()=>{of="production"});function cf(t){return!!t&&t[uT]===!0}var uT,pf=w(()=>{uT=Symbol.for("sentry.nonRecordingSpan")});function Ko(t,e){let i=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:i.environment||"production",release:i.release,public_key:r,trace_id:t,org_id:Hg(e)};return e.emit("createDsc",n),n}function Xi(t,e){if(hs())return;let i=e.getPropagationContext();return i.dsc||Ko(i.traceId,t)}function Mt(t){let e=vt();if(!e)return{};let i=Is(t),r=Ji(i),n=r.data,s=i.spanContext().traceState,a=s?.get("sentry.sample_rate")??n["sentry.sample_rate"]??n["sentry.previous_trace_sample_rate"];function o(b){return(typeof a=="number"||typeof a=="string")&&(b.sample_rate=`${a}`),b}let l=i[mT];if(l)return o(l);let c=cf(i),p=c&&i.dropReason==="ignored";if(c&&(!Wo(e.getOptions())||p)){let b=$t(i).scope,S=b&&Xi(e,b);if(S){let E={...S};return p&&(E.sampled="false"),o(E)}}let d=s?.get("sentry.dsc"),m=d&&Yr(d);if(m)return o(m);let g=Ko(t.spanContext().traceId,e),h=n[Fo],f=r.description;return h!=="url"&&f&&(g.transaction=f),Wo()&&(g.sampled=String(Ts(i)),g.sample_rand=s?.get("sentry.sample_rand")??$t(i).scope?.getPropagationContext().sampleRand.toString()),o(g),e.emit("createDsc",g,i),g}var mT,Zi=w(()=>{ut();Bo();Vt();Zg();Dt();pf();vs();wt();mT="_frozenDsc"});function mf(t,e){let{fingerprint:i,breadcrumbs:r,sdkProcessingMetadata:n}=e;gT(t,e),yT(t,i),fT(t,r),hT(t,n)}function uf(t,e){let{extra:i,tags:r,attributes:n,user:s,contexts:a,level:o,sdkProcessingMetadata:l,breadcrumbs:c,fingerprint:p,eventProcessors:d,attachments:m,propagationContext:g,transactionName:h}=e;en(t,"extra",i),en(t,"tags",r),en(t,"attributes",n),en(t,"user",s),en(t,"contexts",a),t.sdkProcessingMetadata=Wt(t.sdkProcessingMetadata,l,2),o&&(t.level=o),h&&(t.transactionName=h),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),p.length&&(t.fingerprint=[...t.fingerprint,...p]),d.length&&(t.eventProcessors=[...t.eventProcessors,...d]),m.length&&(t.attachments=[...t.attachments,...m]),t.propagationContext={...t.propagationContext,...g}}function en(t,e,i){t[e]=Wt(t[e],i,1)}function xs(t,e){let i=qo().getScopeData();return t&&uf(i,t.getScopeData()),e&&uf(i,e.getScopeData()),i}function gT(t,e){let{extra:i,tags:r,user:n,contexts:s,level:a,transactionName:o}=e;Object.keys(i).length&&(t.extra={...i,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(n).length&&(t.user={...n,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),a&&(t.level=a),o&&t.type!=="transaction"&&(t.transaction=o)}function fT(t,e){let i=[...t.breadcrumbs||[],...e];t.breadcrumbs=i.length?i:void 0}function hT(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function gf(t,e){t.contexts={trace:ks(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:Mt(e),...t.sdkProcessingMetadata};let i=Is(e),r=Ji(i).description;r&&!t.transaction&&t.type==="transaction"&&(t.transaction=r)}function yT(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}var Yo=w(()=>{ut();Zi();gs();Dt()});function Si(t,e,i){let r;try{r=e()}catch(n){return ff(t,n,i)}return Nt(r)?r.then(void 0,n=>ff(t,n,i)):r}function ff(t,e,i){return B&&q.error(t,e),i(e)}var Os=w(()=>{Re();Ne();qe()});function tn(t){return!!t&&typeof t=="function"&&"_static"in t&&!!t._static}function rn(t,e){return Si(B?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(t),()=>t)||t}var Qo=w(()=>{Re();Os()});function hf(t){let e={trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,name:t.description||"",start_timestamp:t.start_timestamp,end_timestamp:t.timestamp,status:!t.status||t.status==="ok"||t.status==="cancelled"?"ok":"error",is_segment:!1,attributes:{...t.data},links:t.links};return Es(e)}var yf=w(()=>{Dt()});function bf(t){let e={},{response:i,profile:r,cloud_resource:n,culture:s,state:a}=t;if(i&&(i.status_code!=null&&(e[bg]=i.status_code),i.body_size!=null&&(e[yg]=i.body_size)),r&&(r.profile_id&&(e[zr]=r.profile_id),r.profiler_id&&(e[kg]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e[fg]=s.locale),s.timezone&&(e[hg]=s.timezone)),a?.state&&typeof a.state.type=="string"&&(e[Ng]=a.state.type);let o=t.angular;if(o){let c=o.version;(typeof c=="string"||typeof c=="number")&&(e[gg]=c)}let l=t.react;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e[_g]=c)}return e}var _f=w(()=>{wt()});function vf(t,e){let i=Xr(t);i.attributes&&delete i.attributes[pg];let r=As(t),n=Xr(r),{isolationScope:s,scope:a}=$t(t),o=xs(s,a);wT(i,n,e,o),e.emit("preprocessSpan",i),i.is_segment&&(bT(i,o),_T(i,e),e.emit("processSegmentSpan",i)),e.emit("processSpan",i);let{beforeSendSpan:l,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&l&&!tn(l)?rn(i,l):i;return{...Es(p),_segmentSpan:r,_segmentNameAtCapture:n.name}}function bT(t,e){Jo(t,bf(e.contexts))}function Jo(t,e){let i=t.attributes??(t.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in i)&&(i[r]=n)})}function _T(t,e){let i=e.getIntegrationNames();i.length&&Jo(t,{[Tg]:i})}function vT(t,e,i,r=!0){let n=e.getSdkMetadata(),{release:s,environment:a}=e.getOptions();return{[Rg]:"stream",[Kr]:t.name,[xg]:t.span_id,[Ig]:n?.sdk?.name,[Ag]:n?.sdk?.version,[Eg]:s,[vg]:a||"production",[Dg]:i.user?.id,[Cg]:i.user?.email,[Mg]:i.user?.ip_address,[Lg]:i.user?.username,...r?i.attributes:void 0}}function wT(t,e,i,r){Jo(t,vT(e,i,r))}var wf=w(()=>{dg();Yo();Dt();vs();Qo();_f();wt()});function Rs(t){return t.getOptions().traceLifecycle==="stream"}var Xo=w(()=>{});function er(t){return typeof t=="object"&&typeof t.unref=="function"&&t.unref(),t}var Ns=w(()=>{});function mt(t,e=[]){return[t,e]}function el(t,e){let[i,r]=t;return[i,[...r,e]]}function Ps(t,e){let i=t[1];for(let r of i){let n=r[0].type;if(e(r,n))return!0}return!1}function Sf(t,e){return Ps(t,(i,r)=>e.includes(r))}function Zo(t){let e=$e(Y);return e.encodePolyfill?e.encodePolyfill(t):new TextEncoder().encode(t)}function kf(t){let[e,i]=t,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[Zo(r),s]:r.push(typeof s=="string"?Zo(s):s)}for(let s of i){let[a,o]=s;if(n(`
311
+ `,QS=Buffer.from(YS.replace(/^ +/gm,""),"utf16le").toString("base64"),JS=["-NoLogo","-NoProfile","-NonInteractive","-STA","-EncodedCommand",QS];Iu=Tu()});var Rm,Nm=w(()=>{Rm=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var B,Re=w(()=>{B=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var Y,st=w(()=>{Y=globalThis});var Rt,ss=w(()=>{Rt="11.15.0"});function _e(){return $e(Y),Y}function $e(t){let e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||"11.15.0",e[Rt]=e["11.15.0"]||{}}function yt(t,e,i=Y){let r=i.__SENTRY__=i.__SENTRY__||{},n=r[Rt]=r["11.15.0"]||{};return n[t]||(n[t]=e())}var at=w(()=>{ss();st()});function ot(t){if(!("console"in Y))return t();let e=Y.console,i={},r=Object.keys(yo);r.forEach(n=>{let s=yo[n];i[n]=e[n],e[n]=s});try{return t()}finally{r.forEach(n=>{e[n]=i[n]})}}function xE(){_o().enabled=!0}function OE(){_o().enabled=!1}function Pm(){return _o().enabled}function RE(...t){bo("log",...t)}function NE(...t){bo("warn",...t)}function PE(...t){bo("error",...t)}function bo(t,...e){B&&Pm()&&ot(()=>{Y.console[t](`${AE}[${t}]:`,...e)})}function _o(){return B?yt("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var AE,yo,q,Ne=w(()=>{at();Re();st();AE="Sentry Logger ",yo={};q={enable:xE,disable:OE,isEnabled:Pm,log:RE,warn:NE,error:PE}});function wo(...t){let e=t.sort((i,r)=>i[0]-r[0]).map(i=>i[1]);return(i,r=0,n=0)=>{let s=[],a=i.split(`
312
+ `);for(let o=r;o<a.length;o++){let l=a[o];l.length>1024&&(l=l.slice(0,1024));let c=Cm.test(l)?l.replace(Cm,"$1"):l;if(!c.includes("Error: ")){for(let p of e){let d=p(c);if(d){s.push(d);break}}if(s.length>=50+n)break}}return Mm(s.slice(n))}}function Mm(t){if(!t.length)return[];let e=Array.from(t);return/sentryWrapped/.test(as(e).function||"")&&e.pop(),e.reverse(),Dm.test(as(e).function||"")&&(e.pop(),Dm.test(as(e).function||"")&&e.pop()),e.slice(0,50).map(i=>({...i,filename:i.filename||as(e).filename,function:i.function||"?"}))}function as(t){return t[t.length-1]||{}}function So(t){try{return!t||typeof t!="function"?vo:t.name||vo}catch{return vo}}function Lm(t){let e=t?.startsWith("file://")?t.slice(7):t;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var Cm,Dm,vo,os=w(()=>{Cm=/\(error: (.*)\)/,Dm=/captureMessage|captureException/;vo="<anonymous>"});function lt(t){switch(Um.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Bm(t,Error)}}function ls(t,e){return Um.call(t)===`[object ${e}]`}function qm(t){return ls(t,"ErrorEvent")}function Lr(t){return ls(t,"String")}function Ur(t){return typeof t=="object"&&t!==null&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function bt(t){return t===null||Ur(t)||typeof t!="object"&&typeof t!="function"}function gi(t){return ls(t,"Object")}function qr(t){return typeof t=="object"&&t!==null}function jm(t){return typeof Event<"u"&&Bm(t,Event)}function Fm(t){return ls(t,"RegExp")}function Nt(t){return!!(t?.then&&typeof t.then=="function")}function Bm(t,e){try{return t instanceof e}catch{return!1}}var Um,qe=w(()=>{Um=Object.prototype.toString});function cs(t,e,i){try{Object.defineProperty(t,e,{value:i,writable:!0,configurable:!0})}catch{B&&q.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}function ko(t){if(lt(t))return{message:t.message,name:t.name,stack:t.stack,...Hm(t)};if(jm(t)){let{type:e,target:i,currentTarget:r,detail:n}=t;return{type:e,target:i,currentTarget:r,...n?{detail:n}:{},...Hm(t)}}return t}function Hm(t){return qr(t)?Object.fromEntries(Object.entries(t)):{}}function Wm(t){let e=Object.keys(ko(t));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var jr=w(()=>{Re();Ne();qe()});function Wt(t){if($i!==void 0)return $i?$i(t):t();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),i=Y;return e in i&&typeof i[e]=="function"?($i=i[e],$i(t)):($i=null,t())}function Xe(){return Wt(()=>Math.random())}function Pe(){return Wt(()=>Date.now())}var $i,ct=w(()=>{st()});function Gm(t){return!!t[CE]}function $m(t){let e=t[DE];return typeof e=="number"?e:void 0}var CE,DE,Vm=w(()=>{CE=Symbol.for("sentry.skipNormalization"),DE=Symbol.for("sentry.overrideNormalizationDepth")});function pt(t,e=100,i=1/0){try{return Eo("",t,e,i)}catch(r){return{ERROR:`**non-serializable** (${Km(r)})`}}}function Km(t){try{return String(t)}catch{return"unknown error"}}function To(t,e=3,i=102400){let r=pt(t,e);return UE(r)>i?To(t,e-1,i):r}function Eo(t,e,i=1/0,r=1/0,n=qE()){let[s,a]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let o=Io(t,e);if(!o.startsWith("[object "))return o;if(Gm(e))return e;let l=$m(e),c=l!==void 0?l:i;if(c===0)return o.replace("object ","");if(s(e))return"[Circular ~]";let p=e;if(p&&typeof p.toJSON=="function")try{return Eo("",p.toJSON(),c-1,r,n)}catch{}let d=Array.isArray(e)?[]:{},m=0,g=ko(e);for(let h in g){if(!Object.prototype.hasOwnProperty.call(g,h))continue;if(m>=r){d[h]="[MaxProperties ~]";break}let f=g[h];d[h]=Eo(h,f,c-1,r,n),m++}return a(e),d}function Io(t,e){try{if(zm){let i=zm(e);if(i)return i}return typeof global<"u"&&e===global?"[Global]":typeof e=="number"&&!Number.isFinite(e)?`[${e}]`:typeof e=="function"?`[Function: ${So(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${ME(e)}]`}catch(i){return`**non-serializable** (${Km(i)})`}}function ME(t){let e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function LE(t){return~-encodeURI(t).split(/%..|./).length}function UE(t){return LE(JSON.stringify(t))}function qE(){let t=new WeakSet;function e(r){return t.has(r)?!0:(t.add(r),!1)}function i(r){t.delete(r)}return[e,i]}var zm,ps=w(()=>{Vm();jr();os()});function Ao(t){return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var Ym=w(()=>{});function Qm(t,e="[unserializable]"){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return typeof e=="function"?e(t):e}}function Fr(t,e=0){return typeof t!="string"||e===0||t.length<=e?t:`${t.slice(0,e)}...`}function Br(t,e,i=!1){return Lr(t)?Fm(e)?e.test(t):Lr(e)?i?t===e:t.includes(e):typeof e=="function"?e(t):!1:!1}var Hr=w(()=>{qe()});function jE(){let t=Y;return t.crypto||t.msCrypto}function FE(){return Xe()*16}function we(t=jE()){try{if(t?.randomUUID)return Wt(()=>t.randomUUID()).replace(/-/g,"")}catch{}return xo||(xo="10000000100040008000100000000000"),xo.replace(/[018]/g,e=>(e^(FE()&15)>>e/4).toString(16))}function BE(t){return t.exception?.values?.[0]}function Ro(t,e,i){let r=t.exception=t.exception||{},n=r.values=r.values||[],s=n[0]=n[0]||{};s.value||(s.value=e||""),s.type||(s.type=i||"Error")}function ds(t,e){let i=BE(t);i&&Xm(i,e)}function Jm(t,e){let i=t.exception?.values,r=i?.find(n=>n.mechanism?.exception_id===0)??i?.[0];r&&Xm(r,e)}function Xm(t,e){let i={type:"generic",handled:!0},r=t.mechanism;t.mechanism={...i,...r,...e},e&&"data"in e&&(t.mechanism.data={...r?.data,...e.data})}function Oo(t){return parseInt(t||"",10)}function No(t){let e=t.match(HE)||[],i=Oo(e[1]),r=Oo(e[2]),n=Oo(e[3]);return{buildmetadata:e[5],major:isNaN(i)?void 0:i,minor:isNaN(r)?void 0:r,patch:isNaN(n)?void 0:n,prerelease:e[4]}}function us(t){if(Zm(t))return!0;try{cs(t,"__sentry_captured__",!0)}catch{}return!1}function Zm(t){try{return t.__sentry_captured__}catch{}}var xo,HE,Pt=w(()=>{jr();ct();st();HE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/});function fi(){return Pe()/tg}function $E(){let{performance:t}=Y;if(!t?.now||!t.timeOrigin)return t?.now&&(Vi=[{from:0,origin:Pe()-Wt(()=>t.now())}]),fi;let e=t.timeOrigin;Vi=[{from:0,origin:e}];let i=!0,r=0;return()=>Wt(()=>{let n=t.now(),s=Date.now();return Math.abs(e+n-s)>WE&&(e=s-n,i?Vi=[{from:0,origin:e}]:(Vi.push({from:r,origin:e}),Vi.length>GE&&Vi.splice(1,1))),i=!1,r=n,(e+n)/tg})}function ms(){return(eg??(eg=$E()))()}var tg,WE,GE,Vi,eg,zi=w(()=>{ct();st();tg=1e3,WE=1e3,GE=100;Vi=[]});function Wr(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),!t.did&&!e.did&&(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||ms(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=e.sid.length===32?e.sid:we()),e.init!==void 0&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),typeof e.started=="number"&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if(typeof e.duration=="number")t.duration=e.duration;else{let i=t.timestamp-t.started;t.duration=i>=0?i:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),typeof e.errors=="number"&&(t.errors=e.errors),e.status&&(t.status=e.status)}var Po=w(()=>{Pt();zi()});function Gt(t,e,i=2){if(!e||typeof e!="object"||i<=0)return e;if(t&&Object.keys(e).length===0)return t;let r={...t};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Gt(r[n],e[n],i-1));return r}var gs=w(()=>{});function hi(){return we()}function Gr(){return we().substring(16)}var $r=w(()=>{Pt()});var VE,Ve,Ki=w(()=>{Re();Po();Ne();qe();jr();gs();Pt();$r();ct();Hr();zi();VE=100,Ve=class Co{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},cs(this,"refs",{}),this._propagationContext={traceId:hi(),sampleRand:Xe()}}clone(){let e=new Co;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._attributes={...this._attributes},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,e._conversationId=this._conversationId,e.refs={...this.refs},e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Wr(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,i){return this.setTags({[e]:i})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,i){return this.setAttributes({[e]:i})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,i){return this._extra={...this._extra,[e]:i},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,i){return i===null?delete this._contexts[e]:this._contexts[e]=i,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;let i=typeof e=="function"?e(this):e,{tags:r,attributes:n,extra:s,user:a,contexts:o,level:l,fingerprint:c=[],propagationContext:p,conversationId:d}=(i instanceof Co?i.getScopeData():gi(i)?e:void 0)||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...n},this._extra={...this._extra,...s},this._contexts={...this._contexts,...o},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),c.length&&(this._fingerprint=c),p&&(this._propagationContext=p),d&&(this._conversationId=d),this}addBreadcrumb(e,i){let r=typeof i=="number"?i:VE;if(r<=0)return this;let n={timestamp:fi(),...e,message:e.message?Fr(e.message,2048):e.message};return this._breadcrumbs.push(n),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r)),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Gt(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,i){let r=i?.event_id||we();if(!this._client)return B&&q.warn("No client configured on scope - will not capture exception!"),r;let n=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:n,...i,event_id:r},this),r}captureMessage(e,i,r){let n=r?.event_id||we();if(!this._client)return B&&q.warn("No client configured on scope - will not capture message!"),n;let s=r?.syntheticException??new Error(e);return this._client.captureMessage(e,i,{originalException:e,syntheticException:s,...r,event_id:n},this),n}captureEvent(e,i){let r=e.event_id||i?.event_id||we();return this._client?(this._client.captureEvent(e,{...i,event_id:r},this),r):(B&&q.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}});function yi(){return yt("defaultCurrentScope",()=>new Ve)}function bi(){return yt("defaultIsolationScope",()=>new Ve)}var Do=w(()=>{at();Ki()});var Mo,ig=w(()=>{Mo="__SENTRY_SUPPRESS_TRACING__"});var rg,ng,sg,zE,ag=w(()=>{rg=t=>t instanceof Promise&&!t[ng],ng=Symbol("chained PromiseLike"),sg=(t,e,i)=>{let r=t.then(n=>(e(n),n),n=>{throw i(n),n});return rg(r)&&rg(t)?r:zE(t,r)},zE=(t,e)=>{if(!e)return t;let i=!1;for(let r in t){if(r in e)continue;i=!0;let n=t[r];typeof n=="function"?Object.defineProperty(e,r,{value:(...s)=>n.apply(t,s),enumerable:!0,configurable:!0,writable:!0}):e[r]=n}return i&&Object.assign(e,{[ng]:!0}),e}});function Yi(){let t=_e(),e=$e(t);return e.stack=e.stack||new KE(yi(),bi())}function lg(t){return Yi().withScope(t)}function YE(t,e){let i=Yi();return i.withScope(()=>(i.getStackTop().scope=t,e(t)))}function og(t){return Yi().withScope(()=>t(Yi().getIsolationScope()))}function cg(){return{suppressTracing:QE,withIsolationScope:og,withScope:lg,withSetScope:YE,withSetIsolationScope:(t,e)=>og(e),getCurrentScope:()=>Yi().getScope(),getIsolationScope:()=>Yi().getIsolationScope()}}function QE(t){return lg(e=>{e.setSDKProcessingMetadata({[Mo]:!0});let i=t();return e.setSDKProcessingMetadata({[Mo]:void 0}),i})}var KE,pg=w(()=>{Do();Ki();ig();ag();qe();at();KE=class{constructor(t,e){let i;t?i=t:i=new Ve;let r;e?r=e:r=new Ve,this._stack=[{scope:i}],this._isolationScope=r}withScope(t){let e=this._pushScope(),i;try{i=t(e)}catch(r){throw this._popScope(),r}return Nt(i)?sg(i,()=>this._popScope(),()=>this._popScope()):(this._popScope(),i)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}});function Vr(t){let e=_e(),i=$e(e);i.acs=t}function dt(t){let e=$e(t);return e.acs?e.acs:cg()}var fs=w(()=>{at();pg()});function JE(t){return typeof t=="object"&&t!=null&&!Array.isArray(t)&&Object.keys(t).includes("value")}function XE(t,e){let{value:i,unit:r}=JE(t)?t:{value:t,unit:void 0},n=ZE(i),s=r&&typeof r=="string"?{unit:r}:{};if(n)return{...n,...s};if(!e||e==="skip-undefined"&&i===void 0)return;let a="";try{a=JSON.stringify(i)??""}catch{}return{value:a,type:"string",...s}}function Lo(t,e=!1){let i={};for(let[r,n]of Object.entries(t??{})){let s=XE(n,e);s&&(i[r]=s)}return i}function Uo(t){if(!t)return 0;let e=0;for(let[i,r]of Object.entries(t)){e+=i.length*2,e+=r.type.length*2,e+=(r.unit?.length??0)*2;let n=r.value;Array.isArray(n)?e+=dg(n[0])*n.length:bt(n)?e+=dg(n):e+=100}return e}function dg(t){return typeof t=="string"?t.length*2:typeof t=="boolean"?4:typeof t=="number"?8:0}function ZE(t){if(Array.isArray(t))return{value:t,type:"array"};let e=typeof t=="string"?"string":typeof t=="boolean"?"boolean":typeof t=="number"&&!Number.isNaN(t)?Number.isInteger(t)?"integer":"double":null;if(e)return{value:t,type:e}}var qo=w(()=>{qe()});function hs(){return $e(_e()).externalPropagationContextProvider?.()}function Ct(){let t=_e();return dt(t).getCurrentScope()}function _i(){let t=_e();return dt(t).getIsolationScope()}function jo(){return yt("globalScope",()=>new Ve)}function ys(...t){let e=_e(),i=dt(e);if(t.length===2){let[r,n]=t;return r?i.withSetScope(r,n):i.withScope(n)}return i.withScope(t[0])}function _t(){return Ct().getClient()}function vi(t){let e=hs();if(e)return{trace_id:e.traceId,span_id:e.spanId};let{traceId:i,parentSpanId:r,propagationSpanId:n}=t.getPropagationContext(),s={trace_id:i,span_id:n||Gr()};return r&&(s.parent_span_id=r),s}var ut=w(()=>{fs();at();Ki();$r()});var ug,mg=w(()=>{ug="sentry.custom_span_name"});var gg,fg=w(()=>{gg=["ok","deadline_exceeded","unauthenticated","permission_denied","not_found","resource_exhausted","invalid_argument","unimplemented","unavailable","internal_error","unknown_error","cancelled","already_exists","failed_precondition","aborted","out_of_range","data_loss"]});var hg,yg,bg,_g,vg,wg,Sg,Fo,kg,Eg,Tg,zr,Ig,Ag,xg,Og,Rg,Kr,Bo,Ng,Pg,bs,Cg,Dg,Mg,Lg,Ug,qg,vt=w(()=>{hg="angular.version",yg="culture.locale",bg="culture.timezone",_g="http.response.body.size",vg="http.response.status_code",wg="react.version",Sg="sentry.environment",Fo="sentry.exclusive_time",kg="sentry.op",Eg="sentry.origin",Tg="sentry.profiler_id",zr="sentry.profile_id",Ig="sentry.release",Ag="sentry.sdk.integrations",xg="sentry.sdk.name",Og="sentry.sdk.version",Rg="sentry.segment.id",Kr="sentry.segment.name",Bo="sentry.segment.name.source",Ng="sentry.status.message",Pg="sentry.trace_lifecycle",bs="server.address",Cg="state.type",Dg="url.path",Mg="user.email",Lg="user.id",Ug="user.ip_address",qg="user.name"});function jg(t){return t!=="ok"&&gg.includes(t)}var Fg=w(()=>{fg()});function Qi(t){try{let e=Y.WeakRef;if(typeof e=="function")return new e(t)}catch{}return t}function wi(t){if(t){if(typeof t=="object"&&"deref"in t&&typeof t.deref=="function")try{return t.deref()}catch{return}return t}}var _s=w(()=>{st()});function $t(t){let e=t;return{scope:e[eT],isolationScope:wi(e[tT])}}var eT,tT,vs=w(()=>{_s();eT="_sentryScope",tT="_sentryIsolationScope"});function Yr(t){let e=Hg(t);if(!e)return;let i=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith("sentry-")){let a=n.slice(7);r[a]=s}return r},{});if(Object.keys(i).length>0)return i}function Hg(t){if(!(!t||!Lr(t)&&!Array.isArray(t)))return Array.isArray(t)?t.reduce((e,i)=>{let r=Bg(i);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):Bg(t)}function Bg(t){return t.split(",").map(e=>{let i=e.indexOf("=");return i===-1?[]:[e.slice(0,i),e.slice(i+1)].map(r=>{try{return decodeURIComponent(r.trim())}catch{return}})}).reduce((e,[i,r])=>(i&&r&&(e[i]=r),e),{})}var Ho=w(()=>{qe()});function nT(t){return t==="http"||t==="https"}function ze(t,e=!1){let{host:i,path:r,pass:n,port:s,projectId:a,protocol:o,publicKey:l}=t;return`${o}://${l}${e&&n?`:${n}`:""}@${i}${s?`:${s}`:""}/${r&&`${r}/`}${a}`}function sT(t){let e=rT.exec(t);if(!e){ot(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});return}let[i,r,n="",s="",a="",o=""]=e.slice(1),l="",c=o,p=c.split("/");if(p.length>1&&(l=p.slice(0,-1).join("/"),c=p.pop()),c){let d=c.match(/^\d+/);d&&(c=d[0])}return Wg({host:s,pass:n,path:l,projectId:c,port:a,protocol:i,publicKey:r})}function Wg(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function aT(t){if(!B)return!0;let{port:e,projectId:i,protocol:r}=t;return["protocol","publicKey","host","projectId"].find(n=>t[n]?!1:(q.error(`Invalid Sentry Dsn: ${n} missing`),!0))?!1:i.match(/^\d+$/)?nT(r)?e&&isNaN(parseInt(e,10))?(q.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(q.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(q.error(`Invalid Sentry Dsn: Invalid projectId ${i}`),!1)}function oT(t){return t.match(iT)?.[1]}function Gg(t){let e=t.getOptions(),{host:i}=t.getDsn()||{},r;return e.orgId?r=String(e.orgId):i&&(r=oT(i)),r}function Qr(t){let e=typeof t=="string"?sT(t):Wg(t);if(!(!e||!aT(e)))return e}var iT,rT,Vt=w(()=>{Re();Ne();iT=/^o(\d+)\./,rT=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function $g(t){if(typeof t=="boolean")return Number(t);let e=typeof t=="string"?parseFloat(t):t;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}var Vg=w(()=>{});function Jr(t){return!!t.parentSpanId||!!t.dsc}var zg=w(()=>{});function ws(t,e){e?t.refs[Wo]=Qi(e):delete t.refs[Wo]}function Kg(t){return wi(t.refs[Wo])}var Wo,Go=w(()=>{_s();Wo="span"});function ks(t){let{spanId:e,traceId:i,isRemote:r}=t.spanContext(),n=r?e:Ji(t).parent_span_id,s=$t(t).scope;return{parent_span_id:n,span_id:r?s?.getPropagationContext().propagationSpanId||Gr():e,trace_id:i}}function lT(t){if(t&&t.length>0)return t.map(({context:{spanId:e,traceId:i,traceFlags:r,...n},attributes:s})=>({span_id:e,trace_id:i,sampled:r===1,attributes:s,...n}))}function cT(t){if(t?.length)return t.map(({context:{spanId:e,traceId:i,traceFlags:r},attributes:n})=>({span_id:e,trace_id:i,sampled:r===1,attributes:n}))}function Ss(t){return typeof t=="number"?Yg(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?Yg(t.getTime()):ms()}function Yg(t){return t>9999999999?t/1e3:t}function Ji(t){if(Zg(t))return t.getStaticSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(Xg(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{span_id:e,trace_id:i,data:r,description:s,parent_span_id:Jg(t),start_timestamp:Ss(n),timestamp:Ss(a)||void 0,status:pT(o),op:r[kg],origin:r[Eg],links:lT(l)}}return{span_id:e,trace_id:i,start_timestamp:0,status:"ok",data:{}}}function Xr(t){if(Zg(t))return t.getSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(Xg(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{name:s,span_id:e,trace_id:i,parent_span_id:Jg(t),start_timestamp:Ss(n),end_timestamp:Ss(a)||void 0,is_segment:Qg(t),status:ef(o),attributes:dT(r,o),links:cT(l)}}return{span_id:e,trace_id:i,start_timestamp:0,name:"",status:"ok",is_segment:Qg(t),attributes:{}}}function Jg(t){return"parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0}function Es(t){return{...t,end_timestamp:t.end_timestamp??t.start_timestamp,attributes:Lo(t.attributes),links:t.links?.map(e=>({...e,attributes:Lo(e.attributes)}))}}function Xg(t){let e=t;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function Zg(t){return typeof t.getSpanJSON=="function"}function Ts(t){let{traceFlags:e}=t.spanContext();return e===1}function pT(t){return!t||t.code===0||t.code===1?"ok":t.message&&jg(t.message)?t.message:"internal_error"}function ef(t){return!t||t.code===1||t.code===0||t.message==="cancelled"?"ok":"error"}function dT(t,e){let i=ef(e)==="error"?e?.message:void 0;return{...i&&{[Ng]:i},...t}}function As(t){return t[uT]||t}function Qg(t){return t===As(t)}function Zr(t){let e=_e(),i=dt(e);return i.getActiveSpan?i.getActiveSpan(t):Kg(t||Ct())}var uT,Is,Dt=w(()=>{fs();qo();at();ut();Fg();vs();$r();zi();Go();vt();uT="_sentryRootSpan",Is=As});function $o(t){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=t||_t()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var tf=w(()=>{ut()});function rf(t){q.log(`Ignoring span ${t.op} - ${t.description} because it matches \`ignoreSpans\`.`)}function Vo(t,e){if(!e?.length)return!1;for(let i of e){if(gT(i)){if(t.description&&Br(t.description,i))return B&&rf(t),!0;continue}let r=!!i.attributes&&Object.keys(i.attributes).length>0;if(!i.name&&!i.op&&!r)continue;let n=i.name?t.description&&Br(t.description,i.name):!0,s=i.op?t.op&&Br(t.op,i.op):!0,a=i.attributes?Object.entries(i.attributes).every(([o,l])=>mT(t.attributes?.[o],l)):!0;if(n&&s&&a)return B&&rf(t),!0}return!1}function mT(t,e){return typeof t=="string"&&(typeof e=="string"||e instanceof RegExp)?Br(t,e):Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((i,r)=>i===e[r]):t===e}function nf(t,e){let i=e.parent_span_id,r=e.span_id;if(i)for(let n of t)n.parent_span_id===r&&(n.parent_span_id=i)}function gT(t){return typeof t=="string"||t instanceof RegExp}var sf=w(()=>{Re();Ne();Hr()});function of(t,e){let i={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(t)}),e.forEach(r=>{r&&Ko(t,r,i)}),i}function zo(t,e){for(let i of e)i?.afterAllSetup&&i.afterAllSetup(t)}function Ko(t,e,i){if(i[e.name]){B&&q.log(`Integration skipped because it was already installed: ${e.name}`);return}if(i[e.name]=e,!af.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),af.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(t),typeof e.preprocessEvent=="function"){let r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(n,s)=>r(n,s,t))}if(typeof e.processEvent=="function"){let r=e.processEvent.bind(e),n=Object.assign((s,a)=>r(s,a,t),{id:e.name});t.addEventProcessor(n)}["processSpan","processSegmentSpan"].forEach(r=>{let n=e[r];typeof n=="function"&&t.on(r,s=>n.call(e,s,t))}),B&&q.log(`Integration installed: ${e.name}`)}var af,lf=w(()=>{Re();Ne();af=[]});var cf,pf=w(()=>{cf="production"});function df(t){return!!t&&t[fT]===!0}var fT,uf=w(()=>{fT=Symbol.for("sentry.nonRecordingSpan")});function Yo(t,e){let i=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:i.environment||"production",release:i.release,public_key:r,trace_id:t,org_id:Gg(e)};return e.emit("createDsc",n),n}function Xi(t,e){if(hs())return;let i=e.getPropagationContext();return i.dsc||Yo(i.traceId,t)}function Mt(t){let e=_t();if(!e)return{};let i=Is(t),r=Ji(i),n=r.data,s=i.spanContext().traceState,a=s?.get("sentry.sample_rate")??n["sentry.sample_rate"]??n["sentry.previous_trace_sample_rate"];function o(b){return(typeof a=="number"||typeof a=="string")&&(b.sample_rate=`${a}`),b}let l=i[hT];if(l)return o(l);let c=df(i),p=c&&i.dropReason==="ignored";if(c&&(!$o(e.getOptions())||p)){let b=$t(i).scope,S=b&&Xi(e,b);if(S){let E={...S};return p&&(E.sampled="false"),o(E)}}let d=s?.get("sentry.dsc"),m=d&&Yr(d);if(m)return o(m);let g=Yo(t.spanContext().traceId,e),h=n[Bo],f=r.description;return h!=="url"&&f&&(g.transaction=f),$o()&&(g.sampled=String(Ts(i)),g.sample_rand=s?.get("sentry.sample_rand")??$t(i).scope?.getPropagationContext().sampleRand.toString()),o(g),e.emit("createDsc",g,i),g}var hT,Zi=w(()=>{ut();Ho();Vt();tf();Dt();uf();vs();vt();hT="_frozenDsc"});function ff(t,e){let{fingerprint:i,breadcrumbs:r,sdkProcessingMetadata:n}=e;yT(t,e),vT(t,i),bT(t,r),_T(t,n)}function gf(t,e){let{extra:i,tags:r,attributes:n,user:s,contexts:a,level:o,sdkProcessingMetadata:l,breadcrumbs:c,fingerprint:p,eventProcessors:d,attachments:m,propagationContext:g,transactionName:h}=e;en(t,"extra",i),en(t,"tags",r),en(t,"attributes",n),en(t,"user",s),en(t,"contexts",a),t.sdkProcessingMetadata=Gt(t.sdkProcessingMetadata,l,2),o&&(t.level=o),h&&(t.transactionName=h),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),p.length&&(t.fingerprint=[...t.fingerprint,...p]),d.length&&(t.eventProcessors=[...t.eventProcessors,...d]),m.length&&(t.attachments=[...t.attachments,...m]),t.propagationContext={...t.propagationContext,...g}}function en(t,e,i){t[e]=Gt(t[e],i,1)}function xs(t,e){let i=jo().getScopeData();return t&&gf(i,t.getScopeData()),e&&gf(i,e.getScopeData()),i}function yT(t,e){let{extra:i,tags:r,user:n,contexts:s,level:a,transactionName:o}=e;Object.keys(i).length&&(t.extra={...i,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(n).length&&(t.user={...n,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),a&&(t.level=a),o&&t.type!=="transaction"&&(t.transaction=o)}function bT(t,e){let i=[...t.breadcrumbs||[],...e];t.breadcrumbs=i.length?i:void 0}function _T(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function hf(t,e){t.contexts={trace:ks(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:Mt(e),...t.sdkProcessingMetadata};let i=Is(e),r=Ji(i).description;r&&!t.transaction&&t.type==="transaction"&&(t.transaction=r)}function vT(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}var Qo=w(()=>{ut();Zi();gs();Dt()});function Si(t,e,i){let r;try{r=e()}catch(n){return yf(t,n,i)}return Nt(r)?r.then(void 0,n=>yf(t,n,i)):r}function yf(t,e,i){return B&&q.error(t,e),i(e)}var Os=w(()=>{Re();Ne();qe()});function tn(t){return!!t&&typeof t=="function"&&"_static"in t&&!!t._static}function rn(t,e){return Si(B?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(t),()=>t)||t}var Jo=w(()=>{Re();Os()});function bf(t){let e={trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,name:t.description||"",start_timestamp:t.start_timestamp,end_timestamp:t.timestamp,status:!t.status||t.status==="ok"||t.status==="cancelled"?"ok":"error",is_segment:!1,attributes:{...t.data},links:t.links};return Es(e)}var _f=w(()=>{Dt()});function vf(t){let e={},{response:i,profile:r,cloud_resource:n,culture:s,state:a}=t;if(i&&(i.status_code!=null&&(e[vg]=i.status_code),i.body_size!=null&&(e[_g]=i.body_size)),r&&(r.profile_id&&(e[zr]=r.profile_id),r.profiler_id&&(e[Tg]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e[yg]=s.locale),s.timezone&&(e[bg]=s.timezone)),a?.state&&typeof a.state.type=="string"&&(e[Cg]=a.state.type);let o=t.angular;if(o){let c=o.version;(typeof c=="string"||typeof c=="number")&&(e[hg]=c)}let l=t.react;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e[wg]=c)}return e}var wf=w(()=>{vt()});function Sf(t,e){let i=Xr(t);i.attributes&&delete i.attributes[ug];let r=As(t),n=Xr(r),{isolationScope:s,scope:a}=$t(t),o=xs(s,a);ET(i,n,e,o),e.emit("preprocessSpan",i),i.is_segment&&(wT(i,o),ST(i,e),e.emit("processSegmentSpan",i)),e.emit("processSpan",i);let{beforeSendSpan:l,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&l&&!tn(l)?rn(i,l):i;return{...Es(p),_segmentSpan:r,_segmentNameAtCapture:n.name}}function wT(t,e){Xo(t,vf(e.contexts))}function Xo(t,e){let i=t.attributes??(t.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in i)&&(i[r]=n)})}function ST(t,e){let i=e.getIntegrationNames();i.length&&Xo(t,{[Ag]:i})}function kT(t,e,i,r=!0){let n=e.getSdkMetadata(),{release:s,environment:a}=e.getOptions();return{[Pg]:"stream",[Kr]:t.name,[Rg]:t.span_id,[xg]:n?.sdk?.name,[Og]:n?.sdk?.version,[Ig]:s,[Sg]:a||"production",[Lg]:i.user?.id,[Mg]:i.user?.email,[Ug]:i.user?.ip_address,[qg]:i.user?.username,...r?i.attributes:void 0}}function ET(t,e,i,r){Xo(t,kT(e,i,r))}var kf=w(()=>{mg();Qo();Dt();vs();Jo();wf();vt()});function Rs(t){return t.getOptions().traceLifecycle==="stream"}var Zo=w(()=>{});function er(t){return typeof t=="object"&&typeof t.unref=="function"&&t.unref(),t}var Ns=w(()=>{});function mt(t,e=[]){return[t,e]}function tl(t,e){let[i,r]=t;return[i,[...r,e]]}function Ps(t,e){let i=t[1];for(let r of i){let n=r[0].type;if(e(r,n))return!0}return!1}function Ef(t,e){return Ps(t,(i,r)=>e.includes(r))}function el(t){let e=$e(Y);return e.encodePolyfill?e.encodePolyfill(t):new TextEncoder().encode(t)}function Tf(t){let[e,i]=t,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[el(r),s]:r.push(typeof s=="string"?el(s):s)}for(let s of i){let[a,o]=s;if(n(`
313
313
  ${JSON.stringify(a)}
314
- `),typeof o=="string"||o instanceof Uint8Array)n(o);else{let l;try{l=JSON.stringify(o)}catch{l=JSON.stringify(pt(o))}n(l)}}return typeof r=="string"?r:ST(r)}function ST(t){let e=t.reduce((n,s)=>n+s.length,0),i=new Uint8Array(e),r=0;for(let n of t)i.set(n,r),r+=n.length;return i}function Ef(t){let e=typeof t.data=="string"?Zo(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}function kT(t){return t in Tf}function tl(t){return kT(t)?Tf[t]:t}function nn(t){if(!t?.sdk)return;let{name:e,version:i}=t.sdk;return{name:e,version:i}}function If(t,e,i,r){let n=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(Pe()).toISOString(),...e&&{sdk:e},...!!i&&r&&{dsn:ze(r)},...n&&{trace:n}}}function sn(t){return t==="replay_event"?"replay":t||"error"}var Tf,zt=w(()=>{at();Vt();ps();ct();st();Tf={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",metric:"trace_metric"}});function Af(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var xf=w(()=>{});function Of(){return!Af()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var Rf=w(()=>{xf()});function Nf(){return typeof window<"u"&&(!Of()||ET())}function ET(){return Y.process?.type==="renderer"}var Pf=w(()=>{Rf();st()});function Cf(t,e,i){let r=i.getOptions(),n=i.getDsn(),s=r.tunnel,a=nn(r._metadata),o={sent_at:new Date(Pe()).toISOString(),...TT(e)&&{trace:e},...a&&{sdk:a},...!!s&&n&&{dsn:ze(n)}};return mt(o,[il(t,i)])}function il(t,e){let i=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:t.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,ingest_settings:Nf()?{infer_ip:i,infer_user_agent:i}:void 0,items:t}]}function TT(t){return!!t.trace_id&&!!t.public_key}var rl=w(()=>{Vt();zt();Pf();ct()});function Df(t){let e=156;if(e+=t.name.length*2,e+=Lo(t.attributes),t.links&&t.links.length>0){let i=t.links[0]?.attributes,r=100+(i?Lo(i):0);e+=r*t.links.length}return e}var Mf=w(()=>{Uo()});function AT(t,e,i){let r=t.attributes[Kr];if(e===void 0||r?.value!==e)return;let n=i();n!==e&&(t.attributes[Kr]={...r,value:n})}var Lf,IT,Uf,qf=w(()=>{Re();Ne();Dt();Ns();Zi();rl();Mf();wt();Lf=1e3,IT=5e6,Uf=class{constructor(t,e){this._traceBuckets=new Map,this._client=t;let{maxSpanLimit:i,flushInterval:r,maxTraceWeightInBytes:n}=e??{};this._maxSpanLimit=i&&i>0&&i<=Lf?i:Lf,this._flushInterval=r&&r>0?r:5e3,this._maxTraceWeight=n&&n>0?n:IT,this._client.on("flush",()=>{this.drain()}),this._client.on("close",()=>{this._traceBuckets.forEach(s=>{clearTimeout(s.timeout)}),this._traceBuckets.clear()})}add(t){let e=t.trace_id,i=this._traceBuckets.get(e);i||(i={spans:new Set,size:0,timeout:er(setTimeout(()=>{this.flush(e)},this._flushInterval))},this._traceBuckets.set(e,i)),i.spans.add(t),i.size+=Df(t),(i.spans.size>=this._maxSpanLimit||i.size>=this._maxTraceWeight)&&this.flush(e)}drain(){this._traceBuckets.size&&(B&&q.log(`Flushing span tree map with ${this._traceBuckets.size} traces`),this._traceBuckets.forEach((t,e)=>{this.flush(e)}))}flush(t){let e=this._traceBuckets.get(t);if(!e)return;if(!e.spans.size){this._removeTrace(t);return}let i=Array.from(e.spans),r=i[0]?._segmentSpan;if(!r){B&&q.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(t);return}let n=Mt(r),s=new Map,a=c=>{let p=s.get(c);return p===void 0&&(p=Xr(c).name,s.set(c,p)),p},o=i.map(c=>{let{_segmentSpan:p,_segmentNameAtCapture:d,...m}=c;return AT(m,d,()=>a(p)),m}),l=Cf(o,n,this._client);B&&q.log(`Sending span envelope for trace ${t} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,c=>{B&&q.error("Error while sending streamed span envelope:",c)}),this._removeTrace(t)}_removeTrace(t){let e=this._traceBuckets.get(t);e&&clearTimeout(e.timeout),this._traceBuckets.delete(t)}}});var xT,jf,Ff=w(()=>{Re();wf();Xo();qf();Ne();Dt();Ns();xT="SpanStreaming",jf=(t={})=>{let e=t.flushOnSegmentEnd??!0;return{name:xT,setup(i){if(!Rs(i)){B&&q.log('[SpanStreaming] `traceLifecycle` is "static", skipping setup.');return}let r=new Uf(i);i.on("afterSpanEnd",n=>{Ts(n)&&r.add(vf(n,i))}),i.on("flushTraceSpans",n=>{r.flush(n)}),e&&i.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;er(setTimeout(()=>{r.flush(s)},500))})}}}});function RT(t){return _t(t)?void 0:t}function Bf(t,e,i){let r=RT(e.originalException),n=r&&OT.get(r);if(!n)return;let s=t.contexts?.trace;(s?.trace_id??(i&&vi(i).trace_id))===n.trace_id&&(t.contexts={...t.contexts,trace:{...s,...n}})}var OT,Hf=w(()=>{ut();qe();OT=new WeakMap});function Gf(t){$e(_e()).segmentSpanCaptureStrategy=t}function Wf(){return $e(_e()).segmentSpanCaptureStrategy}var $f=w(()=>{at()});function Vf(t,e,i){let r,n,s,a=i?.maxWait?Math.max(i.maxWait,e):0,o=i?.setTimeoutImpl||setTimeout;function l(){return c(),r=t(),r}function c(){n!==void 0&&clearTimeout(n),s!==void 0&&clearTimeout(s),n=s=void 0}function p(){return n!==void 0||s!==void 0?l():r}function d(){return n&&clearTimeout(n),n=o(l,e),a&&s===void 0&&(s=o(l,a)),r}return d.cancel=c,d.flush=p,d}var zf=w(()=>{});function nl(t){if(Wf()||Gf(NT),Ds.has(t))return;let e=new Set,i=Vf(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});t.on("flush",()=>{i.flush()}),Ds.set(t,r=>{e.add(r),i()})}var Cs,Kf,Yf,Ds,NT,Qf=w(()=>{zf();$f();Cs=new WeakSet,Kf=t=>Cs.has(t),Yf=t=>{Cs.add(t)},Ds=new WeakMap;NT={onSegmentSpanEnded(t,e){let i=e.getClient(),r=i&&Ds.get(i);if(!r){let n=t();n&&i?.captureEvent(n);return}r(()=>{let n=t({isSpanAlreadyCaptured:Kf,onSpanCaptured:Yf});n&&i.captureEvent(n)})},onChildSpanEnded(t,e,i,r){if(Cs.has(t)||!Cs.has(e))return;let n=r.getClient(),s=n&&Ds.get(n),a=()=>{let o=i({isSpanAlreadyCaptured:Kf,onSpanCaptured:Yf});o?.contexts?.trace?.data&&(o.contexts.trace.data["sentry.parent_span_already_sent"]=!0),o&&n?.captureEvent(o)};s?s(a):a()}}});function PT(t,e){if(!e)return t;let i=t.sdk||{};return t.sdk={...i,name:i.name||e.name,version:i.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0},t}function Jf(t,e,i,r){let n=nn(i),s={sent_at:new Date(Pe()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:ze(e)}},a="aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()];return mt(s,[a])}function Xf(t,e,i,r){let n=nn(i),s=t.type&&t.type!=="replay_event"?t.type:"event";PT(t,i?.sdk);let a=If(t,n,r,e);return delete t.sdkProcessingMetadata,mt(a,[[{type:s},t]])}var Zf=w(()=>{Vt();zt();ct()});function Lt(t){return new ih(e=>{e(t)})}function tr(t){return new ih((e,i)=>{i(t)})}var sl,eh,th,ih,ir=w(()=>{qe();sl=0,eh=1,th=2;ih=class al{constructor(e){this._state=sl,this._handlers=[],this._runExecutor(e)}then(e,i){return new al((r,n)=>{this._handlers.push([!1,s=>{if(!e)r(s);else try{r(e(s))}catch(a){n(a)}},s=>{if(!i)n(s);else try{r(i(s))}catch(a){n(a)}}]),this._executeHandlers()})}catch(e){return this.then(i=>i,e)}finally(e){return new al((i,r)=>{let n,s;return this.then(a=>{s=!1,n=a,e&&e()},a=>{s=!0,n=a,e&&e()}).then(()=>{if(s){r(n);return}i(n)})})}_executeHandlers(){if(this._state===sl)return;let e=this._handlers.slice();this._handlers=[],e.forEach(i=>{i[0]||(this._state===eh&&i[1](this._value),this._state===th&&i[2](this._value),i[0]=!0)})}_runExecutor(e){let i=(s,a)=>{if(this._state===sl){if(Nt(a)){a.then(r,n);return}this._state=s,this._value=a,this._executeHandlers()}},r=s=>{i(eh,s)},n=s=>{i(th,s)};try{e(r,n)}catch(s){n(s)}}}});function rh(t,e,i,r=0,n){try{let s=ol(e,i,t,r,n);return Nt(s)?s:Lt(s)}catch(s){return tr(s)}}function ol(t,e,i,r,n){let s=i[r];if(!t||!s)return t;let a=`Event processor "${s.id||"?"}"`,o=!1,l=Si(B?`${a} threw an error, dropping event:`:"",()=>s({...t},e),()=>(o=!0,null));return B&&l===null&&q.log(`${a} dropped event`),Nt(l)?l.then(c=>c?ol(c,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)):l?ol(l,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)}var nh=w(()=>{Re();Ne();qe();Os();ir()});function oh(t){let e=Y._sentryDebugIds,i=Y._debugIds;if(!e&&!i)return{};let r=e?Object.keys(e):[],n=i?Object.keys(i):[];if(Kt&&r.length===sh&&n.length===ah)return Kt;sh=r.length,ah=n.length,Kt={},ki||(ki={});let s=(a,o)=>{for(let l of a){let c=o[l],p=ki?.[l];if(p&&Kt&&c)Kt[p[0]]=c,ki&&(ki[l]=[p[0],c]);else if(c){let d=t(l);for(let m=d.length-1;m>=0;m--){let g=d[m]?.filename;if(g&&Kt&&ki){Kt[g]=c,ki[l]=[g,c];break}}}}};return e&&s(r,e),i&&s(n,i),Kt}var ki,sh,ah,Kt,lh=w(()=>{st()});function an(t){return t.data?.__sentry__===!0}function ch(t){let e=[];t.message&&e.push(t.message);try{let i=t.exception.values[t.exception.values.length-1];i?.value&&(e.push(i.value),i.type&&e.push(`${i.type}: ${i.value}`))}catch{}return e}var ll=w(()=>{});function ph(t,e,i,r,n,s){let{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=t,l={...e,event_id:e.event_id||i.event_id||we(),timestamp:e.timestamp||fi()},c=i.integrations||t.integrations.map(E=>E.name);CT(l,t),LT(l,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&DT(l,t.stackParser);let p=qT(r,i.captureContext);i.mechanism&&Ym(l,i.mechanism);let d=n?n.getEventProcessors():[],m=xs(s,p),g=[...i.attachments||[],...m.attachments];g.length&&(i.attachments=g),mf(l,m);let h=Zr(p);h&&gf(l,h),Bf(l,i,p);let f=[...d,...m.eventProcessors],b=e.type==="transaction",S=e.spans?.length||0;return(an(i)?Lt(l):rh(f,l,i,0,E=>{n&&(n.recordDroppedEvent(E,sn(e.type)),b&&n.recordDroppedEvent(E,"span",1+S))})).then(E=>{if(!E)return null;if(b&&n){let A=S-(E.spans?.length||0);A>0&&n.recordDroppedEvent("event_processor","span",A)}return MT(E),typeof a=="number"&&a>0?UT(E,a,o):E})}function CT(t,e){let{environment:i,release:r,dist:n,maxValueLength:s}=e;t.environment=t.environment||i||"production",!t.release&&r&&(t.release=r),!t.dist&&n&&(t.dist=n);let a=t.request;a?.url&&s&&(a.url=Fr(a.url,s)),s&&t.exception?.values?.forEach(o=>{o.value&&(o.value=Fr(o.value,s))})}function DT(t,e){let i=oh(e);t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=i[n.filename])})})}function MT(t){let e={};if(t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.debug_id&&(n.abs_path?e[n.abs_path]=n.debug_id:n.filename&&(e[n.filename]=n.debug_id),delete n.debug_id)})}),Object.keys(e).length===0)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];let i=t.debug_meta.images;Object.entries(e).forEach(([r,n])=>{i.push({type:"sourcemap",code_file:r,debug_id:n})})}function LT(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function UT(t,e,i){if(!t)return null;let r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(n=>({...n,...n.data&&{data:pt(n.data,e,i)}}))},...t.user&&{user:pt(t.user,e,i)},...t.contexts&&{contexts:pt(t.contexts,e,i)},...t.extra&&{extra:pt(t.extra,e,i)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=pt(t.contexts.trace.data,e,i))),t.spans&&(r.spans=t.spans.map(n=>({...n,...n.data&&{data:pt(n.data,e,i)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=pt(t.contexts.flags,3,i)),r}function qT(t,e){if(!e)return t;let i=t?t.clone():new Ve;return i.update(e),i}var dh=w(()=>{nh();Ki();lh();zt();Hf();ll();Pt();ps();Yo();Dt();Hr();ir();zi()});function jT(t){let e=t.protocol?`${t.protocol}:`:"",i=t.port?`:${t.port}`:"";return`${e}//${t.host}${i}${t.path?`/${t.path}`:""}/api/`}function FT(t){return`${jT(t)}${t.projectId}/envelope/`}function BT(t,e){let i={sentry_version:"7"};return t.publicKey&&(i.sentry_key=t.publicKey),e&&(i.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(i).toString()}function uh(t,e,i){return e||`${FT(t)}?${BT(t,i)}`}var mh=w(()=>{});function gh(t,e){if(t.type!=="transaction"||!t.spans?.length||!t.sdkProcessingMetadata?.hasGenAiSpans||Rs(e))return;let i=[],r=[];for(let n of t.spans)n.op?.startsWith("gen_ai.")?i.push(hf(n)):r.push(n);if(i.length!==0)return t.spans=r,il(i,e)}var fh=w(()=>{rl();Xo();yf()});function rr(t=100){let e=new Set;function i(){return e.size<t}function r(a){e.delete(a)}function n(a){if(!i())return tr(on);let o=a();return e.add(o),o.then(()=>r(o),()=>r(o)),o}function s(a){if(!e.size)return Lt(!0);let o=Promise.allSettled(Array.from(e)).then(()=>!0);if(!a)return o;let l=[o,new Promise(c=>er(setTimeout(()=>c(!1),a)))];return Promise.race(l)}return{get $(){return Array.from(e)},add:n,drain:s}}var on,Ms=w(()=>{ir();Ns();on=Symbol.for("SentryBufferFullError")});function GT(t,e=Pe()){let i=parseInt(`${t}`,10);if(!isNaN(i))return i*1e3;let r=Date.parse(`${t}`);return isNaN(r)?HT:r-e}function WT(t,e){return t[e]||t.all||0}function hh(t,e,i=Pe()){return WT(t,e)>i}function yh(t,e,i=Pe()){let r={...t};return $T(e,i,(n,s)=>{r[n]=Math.max(r[n]||0,s)}),r}function $T({statusCode:t,headers:e},i,r){let n=e?.["x-sentry-rate-limits"],s=e?.["retry-after"];if(n)for(let a of n.trim().split(",")){let[o,l,,,c]=a.split(":",5),p=parseInt(o,10),d=(isNaN(p)?60:p)*1e3;if(!l)r("all",i+d);else for(let m of l.split(";"))m==="metric_bucket"?(!c||c.split(";").includes("custom"))&&r(m,i+d):r(m,i+d)}else s?r("all",i+GT(s,i)):t===429&&r("all",i+6e4)}var HT,bh=w(()=>{ct();HT=6e4});function cl(t,e,i=rr(t.bufferSize||64)){let r={},n=o=>i.drain(o);function s(o,[l,c],p){let d=tl(p);p==="transaction"&&t.recordDroppedEvent(o,"span",(c.spans?.length??0)+1),t.recordDroppedEvent(o,d,typeof l.item_count=="number"?l.item_count:1)}function a(o){let l=[];if(Ps(o,(m,g)=>{hh(r,tl(g))?s("ratelimit_backoff",m,g):l.push(m)}),l.length===0)return Promise.resolve({});let c=mt(o[0],l),p=m=>{if(Sf(c,["client_report"])){B&&q.warn(`Dropping client report. Will not send outcomes (reason: ${m}).`);return}Ps(c,(g,h)=>{s(m,g,h)})},d=()=>e({body:kf(c)}).then(m=>m.statusCode===413?(B&&q.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),p("send_error"),m):(B&&m.statusCode!==void 0&&(m.statusCode<200||m.statusCode>=300)&&q.warn(`Sentry responded with status code ${m.statusCode} to sent event.`),r=yh(r,m),m),m=>{throw p("network_error"),B&&q.error("Encountered error running transport request:",m),m});return i.add(d).then(m=>m,m=>{if(m===on)return B&&q.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw m})}return{send:a,flush:n}}var _h=w(()=>{Re();Ne();zt();Ms();bh()});function vh(t,e,i){let r=[{type:"client_report"},{timestamp:i||fi(),discarded_events:t}];return mt(e?{dsn:e}:{},[r])}var wh=w(()=>{zt();zi()});function Sh(t){let{trace_id:e,parent_span_id:i,span_id:r,status:n,origin:s,data:a,op:o,links:l}=t.contexts?.trace??{};return{data:a??{},description:t.transaction,op:o,parent_span_id:i,span_id:r??"",start_timestamp:t.start_timestamp??0,status:n??"ok",timestamp:t.timestamp,trace_id:e??"",origin:s,links:l,profile_id:a?.[zr],exclusive_time:a?.[jo],measurements:t.measurements,is_segment:!0}}function kh(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,links:t.links,data:{...t.data,...t.profile_id&&{[zr]:t.profile_id},...t.exclusive_time&&{[jo]:t.exclusive_time}}}},measurements:t.measurements}}var Eh=w(()=>{wt()});function Th(t){t.traceLifecycle!=="stream"||!(t.beforeSendTransaction||t.ignoreTransactions?.length)||ot(()=>{console.warn("[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.")})}var Ih=w(()=>{Ne()});function VT(t){return typeof t=="boolean"||"allow"in t||"deny"in t}function zT(t){return t===void 0?{...Ie.httpHeaders}:VT(t)?{request:t,response:t}:{request:t.request??Ie.httpHeaders.request,response:t.response??Ie.httpHeaders.response}}function Ah(t){let e=t.dataCollection??{};return{userInfo:e.userInfo??Ie.userInfo,cookies:e.cookies??Ie.cookies,httpHeaders:zT(e.httpHeaders),httpBodies:e.httpBodies??Ie.httpBodies,urlQueryParams:e.urlQueryParams??Ie.urlQueryParams,graphQL:{document:e.graphQL?.document??Ie.graphQL.document,variables:e.graphQL?.variables??Ie.graphQL.variables},genAI:{inputs:e.genAI?.inputs??Ie.genAI.inputs,outputs:e.genAI?.outputs??Ie.genAI.outputs},mcp:{inputs:e.mcp?.inputs??Ie.mcp.inputs,outputs:e.mcp?.outputs??Ie.mcp.outputs},databaseQueryData:e.databaseQueryData??Ie.databaseQueryData,queues:e.queues??Ie.queues,stackFrameVariables:e.stackFrameVariables??Ie.stackFrameVariables,frameContextLines:e.frameContextLines??Ie.frameContextLines}}var Ie,xh=w(()=>{Ie={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},mcp:{inputs:!0,outputs:!0},databaseQueryData:!0,queues:!0,stackFrameVariables:!0,frameContextLines:5}});function Nh(t){return{message:t,[Mh]:!0}}function pl(t){return{message:t,[Lh]:!0}}function Ph(t){return pl(`Discarding event because it's not included in the random sample (sampling rate = ${t})`)}function Ch(t){return qr(t)&&Mh in t}function Dh(t){return qr(t)&&Lh in t}function YT(t,e,i,r,n){let{beforeSend:s,ignoreSpans:a,beforeSendTransaction:o}=t,l=tn(t.beforeSendSpan)&&t.beforeSendSpan,c=e;if(dl(c)&&s){let p=c;return Si(B?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,i),()=>(r("callback_error"),null))}if(qh(c)){if(l||a){let p=Sh(c);if(a?.length&&$o({description:p.description,op:p.op,attributes:p.data},a))return r("ignored"),null;if(l){let d=rn(p,l);c=Wt(e,kh(d))}if(c.spans){let d=[],m=c.spans;for(let g of m){if(a?.length&&$o({description:g.description,op:g.op,attributes:g.data},a)){tf(m,g);continue}l?d.push(rn(g,l)):d.push(g)}n(m.length-d.length),c.spans=d}}if(o)return Si(B?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>o(c,i),()=>(r("callback_error"),null))}return c}function dl(t){return t.type===void 0}function qh(t){return t.type==="transaction"}var Oh,Rh,Mh,Lh,KT,Uh,jh=w(()=>{mh();lf();ut();Re();Zf();af();No();Zi();Qo();fh();wh();Ne();Vt();zt();ll();qe();gs();Pt();Wg();dh();Ms();ct();Os();rf();ir();Eh();Ih();xh();Oh="Not capturing exception because it's already been captured.",Rh="Discarded session because of missing or non-string release",Mh=Symbol.for("SentryInternalError"),Lh=Symbol.for("SentryDoNotSendEventError"),KT=Symbol.for("SentryClosedClient");Uh=class{constructor(t){this._options={attachStacktrace:!0,...t,traceLifecycle:t.traceLifecycle==="static"?"static":"stream"},this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=rr(t.transportOptions?.bufferSize??64),this._dataCollection=Ah(t),this._unhandledSessionStatus="crashed",this._attachStacktraceIsDefault=t.attachStacktrace===void 0,t.dsn?this._dsn=Qr(t.dsn):B&&q.warn("No DSN provided, client will not send events.");let{beforeSendSpan:e,traceLifecycle:i}=this._options;if(B&&e&&tn(e)!==(i==="static")&&ot(()=>{console.warn(`Ignoring \`beforeSendSpan\`: ${i==="static"?"wrap it with":"remove"} \`Sentry.withStaticSpan\` to use it with \`traceLifecycle: "${i}"\`.`)}),this._dsn){let r=uh(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:r})}}captureException(t,e,i){let r=we();if(us(t))return B&&q.log(Oh),r;let n={event_id:r,...e};return this._process(()=>this.eventFromException(t,n).then(s=>this._captureEvent(s,n,i)).then(s=>s),"error"),n.event_id}captureMessage(t,e,i,r){let n={event_id:we(),...i},s=Ur(t)?t:String(t),a=_t(t),o=a?this.eventFromMessage(s,e,n).then(l=>(l.exception&&this._attachStacktraceIsDefault&&(l.sdkProcessingMetadata={...l.sdkProcessingMetadata,hasDefaultSyntheticStacktrace:!0}),l)):this.eventFromException(t,n);return this._process(()=>o.then(l=>this._captureEvent(l,n,r)),a?"unknown":"error"),n.event_id}captureEvent(t,e,i){let r=we();if(e?.originalException&&us(e.originalException))return B&&q.log(Oh),r;let n={event_id:r,...e},s=t.sdkProcessingMetadata||{},a=s.capturedSpanScope,o=s.capturedSpanIsolationScope,l=sn(t.type);return this._process(()=>this._captureEvent(t,n,a||i,o),l),n.event_id}captureSession(t){this.sendSession(t),Gr(t,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(t){let e=this._transport;if(this.emit("flush"),!e)return!0;let i=await this._isClientDoneProcessing(t),r=await e.flush(t);return i&&r}async close(t){Object.defineProperty(this,KT,{value:!0});let e=await this.flush(t);return this.getOptions().enabled=!1,this.emit("close"),e}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&(this._setupIntegrations(),Th(this._options))}getIntegrationByName(t){return this._integrations[t]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(t){let e=this._integrations[t.name];!e&&t.beforeSetup&&t.beforeSetup(this),zo(this,t,this._integrations),e||Vo(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);let i=gh(t,this),r=Xf(t,this._dsn,this._options._metadata,this._options.tunnel);if(!an(e))for(let n of e.attachments||[])r=el(r,Ef(n));i&&(r=el(r,i)),this.sendEnvelope(r).then(n=>this.emit("afterSendEvent",t,n))}sendSession(t){let{release:e,environment:i=of}=this._options;if("aggregates"in t){let n=t.attrs||{};if(!n.release&&!e){B&&q.warn(Rh);return}n.release=n.release||e,n.environment=n.environment||i,t.attrs=n}else{if(!t.release&&!e){B&&q.warn(Rh);return}t.release=t.release||e,t.environment=t.environment||i}this.emit("beforeSendSession",t);let r=Jf(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(t,e,i=1){if(this._options.sendClientReports){let r=`${t}:${e}`;B&&q.log(`Recording outcome: "${r}"${i>1?` (${i} times)`:""}`),this._outcomes[r]=(this._outcomes[r]||0)+i}}on(t,e){let i=this._hooks[t]=this._hooks[t]||new Set,r=(...n)=>e(...n);return i.add(r),()=>{i.delete(r)}}emit(t,...e){let i=this._hooks[t];i&&i.forEach(r=>r(...e))}async sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)try{let e=await this._transport.send(t);return this.emit("afterEnvelope",t),e}catch(e){return B&&q.error("Error while sending envelope:",e),{}}return B&&q.error("Transport disabled"),{}}registerCleanup(t){}dispose(){}_setupIntegrations(){let{integrations:t}=this._options;this._integrations=sf(this,t),Vo(this,t)}_updateSessionFromEvent(t,e){let i=e.level==="fatal",r=!1,n=e.exception?.values;if(n){r=!0,i=!1;for(let a of n)if(a.mechanism?.handled===!1){i=!0;break}}let s=t.status==="ok";(s&&t.errors===0||s&&i)&&(Gr(t,{...i&&{status:this._unhandledSessionStatus},errors:t.errors||Number(r||i)}),this.captureSession(t))}async _isClientDoneProcessing(t){let e=0;for(;!t||e<t;){if(await new Promise(i=>setTimeout(i,1)),!this._numProcessing)return!0;e++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(t,e,i,r){let n=this.getOptions(),s=this.getIntegrationNames();return!e.integrations&&s.length&&(e.integrations=s),this.emit("preprocessEvent",t,e),t.type||r.setLastEventId(t.event_id||e.event_id),ph(n,t,e,i,this,r).then(a=>(a===null||(this.emit("postprocessEvent",a,e),a.contexts={trace:{...a.contexts?.trace,...vi(i)},...a.contexts},a.sdkProcessingMetadata={dynamicSamplingContext:Xi(this,i),...a.sdkProcessingMetadata}),a))}_captureEvent(t,e={},i=Ct(),r=_i()){return B&&dl(t)&&q.log(`Captured error event \`${ch(t)[0]||"<unknown>"}\``),this._processEvent(t,e,i,r).then(n=>n.event_id,n=>{B&&(Dh(n)?q.log(n.message):Ch(n)?q.warn(n.message):q.warn(n))})}_processEvent(t,e,i,r){let n=this.getOptions(),{sampleRate:s}=n,a=qh(t),o=dl(t),l=`before send for type \`${t.type||"error"}\``,c="before_send",p=0,d=typeof s>"u"?void 0:Gg(s),m=o&&typeof d=="number"&&Xe()>d,g=sn(t.type),h=0,f=i.getSession()||r.getSession();return m&&f?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),tr(Ph(s))):this._prepareEvent(t,e,i,r).then(b=>{if(b===null)throw pl("An event processor returned `null`, will not send event.");return h=b.spans?.length||0,an(e)?b:YT(n,b,e,S=>{c=S},S=>{p=S})}).then(b=>{if(p&&this.recordDroppedEvent("ignored","span",p),!gi(b)||b===null)throw this.recordDroppedEvent(c,g),a&&this.recordDroppedEvent(c,"span",1+h-p),b!==null?Nh(`${l} must return \`null\` or a valid event.`):pl(`${c==="ignored"?"Transaction matched `ignoreSpans`":`${l} ${c==="callback_error"?"threw an error":"returned `null`"}`}, will not send event.`);if(o&&f&&this._updateSessionFromEvent(f,b),m)throw this.recordDroppedEvent("sample_rate","error"),Ph(s);if(a){let E=h-p-(b.spans?.length||0);E>0&&this.recordDroppedEvent("before_send","span",E)}let S=b.transaction_info;if(a&&S&&b.transaction!==t.transaction){let E="custom";b.transaction_info={...S,source:E}}return this.sendEvent(b,e),b}).then(null,b=>{throw Dh(b)||Ch(b)?b:(this.captureException(b,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:b}),Nh(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
315
- Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t).then(i=>(this._numProcessing--,i),i=>(this._numProcessing--,i===on&&this.recordDroppedEvent("queue_overflow",e),i))}_clearOutcomes(){let t=this._outcomes;return this._outcomes={},Object.entries(t).map(([e,i])=>{let[r,n]=e.split(":");return{reason:r,category:n,quantity:i}})}_flushOutcomes(){B&&q.log("Flushing outcomes...");let t=this._clearOutcomes();if(t.length===0){B&&q.log("No outcomes to send");return}if(!this._dsn){B&&q.log("No dsn provided, will not send outcomes");return}B&&q.log("Sending outcomes:",t);let e=vh(t,this._options.tunnel&&ze(this._dsn));this.sendEnvelope(e)}}});function ul(){QT.clear(),B&&q.log("Cleared AI provider skip registrations")}var QT,Fh=w(()=>{Re();Ne();QT=new Set});function Bh(t,e,i,r,n){let s={sent_at:new Date(Pe()).toISOString()};i?.sdk&&(s.sdk={name:i.sdk.name,version:i.sdk.version}),r&&n&&(s.dsn=ze(n)),e&&(s.trace=e);let a=JT(t);return mt(s,[a])}function JT(t){return[{type:"check_in"},t]}var Hh=w(()=>{Vt();zt();ct()});function Gh(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0).toString(36)}var Wh=w(()=>{});function ml(){return bt("tunnelStore",()=>({clients:new WeakMap}))}function Ls(t){return ml().clients.get(t)}function Us(t,e){let{clients:i}=ml();i.set(t,{...i.get(t),...e})}function $h(){return ml().defaults}var gl=w(()=>{at()});function Vh(t,e,i){let r=eI(e.allowedDsns,t.getDsn()),n={paths:ZT(e,r),basePath:e.basePath,allowedDsns:r,forward:i,intercept:e.intercept!==!1};return Us(t,{served:n}),n}function XT(t){let e=t?Qr(t):vt()?.getDsn();return e?`/${Gh(ze(e))}`:void 0}function ZT(t,e){let i=t.path?.replace(/\/$/,"");if(i)return[i];let r=e.map(n=>XT(n));return[...new Set(r.filter(n=>!!n))]}function zh(t,e){if(!e.length)return[];let i=`${Io(fl(t.basePath))}(?:${e.map(Io).join("|")})/?`;return[{attributes:{[Pg]:new RegExp(`^${i}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${i}(?:[?#].*)?$`)}}]}function fl(t){let e=(t?.startsWith("./")?t.slice(1):t??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function eI(t,e){let i=new Set;for(let r of[...(t??[]).map(n=>Qr(n)),e])r&&i.add(ze(r));return[...i]}var Kh=w(()=>{ut();zm();Vt();Wh();gl();wt()});function hl(t,e,i=[e],r="npm"){let n=(t._metadata=t._metadata||{}).sdk=t._metadata.sdk||{};n.name||(n.name=`sentry.javascript.${e}`,n.packages=i.map(s=>({name:`${r}:@sentry/${s}`,version:Rt})),n.version=Rt)}var Yh=w(()=>{ss()});function yl(t){return Array.from(new Set(t))}var Qh=w(()=>{});function Jh(t,e,i,r,n,s){if(!n.exception?.values||!s||!lt(s.originalException))return;let a=n.exception.values.length>0?n.exception.values[n.exception.values.length-1]:void 0;a&&(n.exception.values=qs(t,e,r,s.originalException,i,n.exception.values,a,0))}function qs(t,e,i,r,n,s,a,o){if(s.length>=i+1)return s;let l=[...s];if(lt(r[n])){bl(a,o,r);let c=t(e,r[n]),p=l.length;_l(c,n,p,o),l=qs(t,e,i,r[n],n,[c,...l],c,p)}return Xh(r)&&r.errors.forEach((c,p)=>{if(l.length<i+1&&lt(c)){bl(a,o,r);let d=t(e,c),m=l.length;_l(d,`errors[${p}]`,m,o),l=qs(t,e,i,c,n,[d,...l],d,m)}}),tI(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(l.length<i+1&&lt(p)){bl(a,o,r);let d=t(e,p),m=l.length;_l(d,c,m,o),l=qs(t,e,i,p,n,[d,...l],d,m)}}),l}function Xh(t){return Array.isArray(t.errors)}function tI(t){return"error"in t&&"suppressed"in t}function bl(t,e,i){t.mechanism={handled:!0,type:"auto.core.linked_errors",...Xh(i)&&{is_exception_group:!0},...t.mechanism,exception_id:e}}function _l(t,e,i,r){t.mechanism={handled:!0,...t.mechanism,type:"chained",source:e,exception_id:i,parent_id:r}}var Zh=w(()=>{qe()});function ey(t,e){return t(e.stack||"",1)}function iI(t){return lt(t)&&"__sentry_fetch_url_host__"in t&&typeof t.__sentry_fetch_url_host__=="string"}function rI(t){let e=nI(t.message);return iI(t)?`${e} (${t.__sentry_fetch_url_host__})`:e}function nI(t){if(typeof t=="string")return t;if(t==null)return"";if(_t(t))return String(t);if(gi(t)||Array.isArray(t)){let e=Km(t,"");if(e)return e}return To(void 0,t)}function vl(t,e){let i={type:e.name||e.constructor.name,value:rI(e)},r=ey(t,e);return r.length&&(i.stacktrace={frames:r}),i}function sI(t){for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let i=t[e];if(lt(i))return i}}function aI(t){if("name"in t&&typeof t.name=="string"){let r=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(r+=` with message '${t.message}'`),r}else if("message"in t&&typeof t.message=="string")return t.message;let e=Bm(t);if(Lm(t))return`Event \`ErrorEvent\` captured as exception with message \`${t.message}\``;let i=oI(t);return`${i&&i!=="Object"?`'${i}'`:"Object"} captured as exception with keys: ${e}`}function oI(t){try{let e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function lI(t,e,i,r){if(lt(i))return[i,void 0];if(e.synthetic=!0,gi(i)){let s=t?.getOptions().normalizeDepth,a={__serialized__:Eo(i,s)},o=sI(i);if(o)return[o,a];let l=aI(i),c=r?.syntheticException||new Error(l);return c.message=l,[c,a]}let n=r?.syntheticException||new Error(i);return n.message=`${i}`,[n,void 0]}function ty(t,e,i,r){let n=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[s,a]=lI(t,n,i,r),o={exception:{values:[vl(e,s)]}};return a&&(o.extra=a),Oo(o,void 0,void 0),ds(o,n),{...o,event_id:r?.event_id}}function iy(t,e,i="info",r,n){let s={event_id:r?.event_id,level:i};if(n&&r?.syntheticException){let a=ey(t,r.syntheticException);a.length&&(s.exception={values:[{value:e,stacktrace:{frames:a}}]},ds(s,{synthetic:!0}))}if(Ur(e)){let{__sentry_template_string__:a,__sentry_template_values__:o}=e;return s.logentry={message:a,params:o},s}return s.message=e,s}var wl=w(()=>{qe();Pt();ps();jr();Hr()});var cI,pI,dI,uI,Sl,ry=w(()=>{Zh();wl();cI="cause",pI=5,dI="LinkedErrors",uI=((t={})=>{let e=t.limit||pI,i=t.key||cI;return{name:dI,preprocessEvent(r,n,s){let a=s.getOptions();Jh(vl,a.stackParser,i,e,r,n)}}}),Sl=uI});function ny(t,e){return e?ys(e,()=>{let i=Zr(),r=i?ks(i):vi(e);return[i?Mt(i):Xi(t,e),r]}):[void 0,void 0]}var sy=w(()=>{ut();Zi();Dt()});function gI(t){let e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,i=mI.exec(e);return i?i.slice(1):[]}function kl(t){let e=gI(t),i=e[0]||"",r=e[1];return!i&&!r?".":(r&&(r=r.slice(0,r.length-1)),i+r)}var mI,ay=w(()=>{mI=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var St=w(()=>{ut();Co();fs();at();Ki();_h();Fh();Zi();Go();Yh();Qf();Qh();_s();ry();st();Ne();Pt();ay();os();$g();Bo();$r();ss();ct()});function oy(t){let e=t._metadata?.sdk,i=e?.name&&e?.version?`${e?.name}/${e?.version}`:void 0;t.transportOptions={...t.transportOptions,headers:{...i&&{"user-agent":i},...t.transportOptions?.headers}}}var ly=w(()=>{});function cy(t){let e=$h(),i=t?.getOptions(),r=i?._managedTunnel??e?.tunnel,n=t&&(Ls(t)?.forward??e?.forward);if(!t||!i||!r||!n)return;let s=fl(e?.basePath),a=r.basePath===void 0&&!r.path&&s?{...r,basePath:s}:r;i._managedTunnel=a;let{paths:o}=Vh(t,a,n),l=Ls(t)?.spanFilters??[],c=zh(a,o);i.ignoreSpans=[...(i.ignoreSpans??[]).filter(p=>!l.includes(p)),...c],Us(t,{spanFilters:c})}var py=w(()=>{gl();Kh()});function dy(t){let e=_i().getScopeData().sdkProcessingMetadata.requestSession;if(e){let i=t?.mechanism?.handled??!0;i&&e.status!=="crashed"?e.status="errored":i||(e.status="crashed")}}var El,uy=w(()=>{Hh();jh();ut();Re();Ff();ly();Ne();wl();Pt();Ms();ir();sy();py();wt();El=class extends Uh{constructor(t){oy(t),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&t.traceLifecycle!=="static"&&!t.integrations.some(e=>e.name==="SpanStreaming")&&t.integrations.push(jf()),super(t),this._disposeCallbacks=[],cy(this),this._setUpMetricsProcessing()}eventFromException(t,e){let i=ty(this,this._options.stackParser,t,e);return i.level="error",Lt(i)}eventFromMessage(t,e="info",i){return Lt(iy(this._options.stackParser,t,e,i,this._options.attachStacktrace))}captureException(t,e,i){return dy(e),super.captureException(t,e,i)}captureEvent(t,e,i){return!t.type&&t.exception?.values&&t.exception.values.length>0&&dy(e),super.captureEvent(t,e,i)}captureCheckIn(t,e,i){let r="checkInId"in t&&t.checkInId?t.checkInId:we();if(!this._isEnabled())return B&&q.warn("SDK not enabled, will not capture check-in."),r;let{release:n,environment:s,tunnel:a}=this.getOptions(),o={check_in_id:r,monitor_slug:t.monitorSlug,status:t.status,release:n,environment:s};"duration"in t&&(o.duration=t.duration),e&&(o.monitor_config={schedule:e.schedule,checkin_margin:e.checkinMargin,max_runtime:e.maxRuntime,timezone:e.timezone,failure_issue_threshold:e.failureIssueThreshold,recovery_threshold:e.recoveryThreshold});let[l,c]=ny(this,i);c&&(o.contexts={trace:c});let p=Bh(o,l,this.getSdkMetadata(),a,this.getDsn());return B&&q.log("Sending checkin:",t.monitorSlug,t.status),this.sendEnvelope(p),r}registerCleanup(t){this._disposeCallbacks.push(t)}dispose(){B&&q.log("Disposing client...");for(let t of this._disposeCallbacks)try{t()}catch{}this._disposeCallbacks.length=0;for(let t of Object.keys(this._hooks))this._hooks[t]?.clear();this._hooks={},this._eventProcessors.length=0,this._integrations={},this._outcomes={},this._transport=void 0,this._promiseBuffer=rr(64)}_prepareEvent(t,e,i,r){return this._options.platform&&(t.platform=t.platform||this._options.platform),this._options.runtime&&(t.contexts={...t.contexts,runtime:t.contexts?.runtime||this._options.runtime}),this._options.serverName&&(t.server_name=t.server_name||this._options.serverName),super._prepareEvent(t,e,i,r)}_setUpMetricsProcessing(){this.on("processMetric",t=>{this._options.serverName&&(t.attributes={[bs]:this._options.serverName,...t.attributes})})}}});function gy(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function fy(t){let e=/^\s*[-]{4,}$/,i=/at (?:async )?(?:(?=.*\)\s*$)(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,r=/at (?:async )?(.+?) \(data:(.*?),/;return n=>{let s=n.match(r);if(s)return{filename:`<data:${s[2]}>`,function:s[1]};let a=n.match(i);if(a){let o,l,c,p,d;if(a[1]){c=a[1];let f=c.lastIndexOf(".");if(c[f-1]==="."&&f--,f>0){o=c.slice(0,f),l=c.slice(f+1);let b=o.indexOf(".Module");b>0&&(c=c.slice(b+1),o=o.slice(0,b))}p=void 0}l&&(p=o,d=l),l==="<anonymous>"&&(d=void 0,c=void 0),c===void 0&&(d=d||"?",c=p?`${p}.${d}`:d);let m=Dm(a[2]),g=a[5]==="native";!m&&a[5]&&!g&&(m=a[5]);let h=m?yI(m):void 0;return{filename:h??m,module:h&&t?.(h),function:c,lineno:my(a[3]),colno:my(a[4]),in_app:gy(m||"",g)}}if(n.match(e))return{filename:n}}}function Tl(t){return[90,fy(t)]}function my(t){return parseInt(t||"",10)||void 0}function yI(t){try{return decodeURI(t)}catch{return}}var hy=w(()=>{os()});var Il=w(()=>{uy();hy()});var Yt,Al=w(()=>{Yt="1.10.0"});function bI(t){let e=new Set([t]),i=new Set,r=t.match(yy);if(!r)return()=>!1;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(l){return l===t};function s(o){return i.add(o),!1}function a(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(i.has(l))return!1;let c=l.match(yy);if(!c)return s(l);let p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||n.major!==p.major?s(l):n.major===0?n.minor===p.minor&&n.patch<=p.patch?a(l):s(l):n.minor<=p.minor?a(l):s(l)}}var yy,by,_y=w(()=>{Al();yy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;by=bI(Yt)});function vI(){return Object.defineProperty({},"version",{value:Yt,enumerable:!0,writable:!1,configurable:!1})}function nr(t,e,i,r=!1){var n;let s=Fs[js]=(n=Fs[js])!==null&&n!==void 0?n:vI();if(!r&&s[t]){let a=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return i.error(a.stack||a.message),!1}if(s.version!=="1.10.0"){let a=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${Yt}`);return i.error(a.stack||a.message),!1}return s[t]=e,i.debug(`@opentelemetry/api: Registered a global for ${t} v${Yt}.`),!0}function Ut(t){let e=Fs[js];if(e!=null){if(e!==vy){if(!e.version||!by(e.version))return;vy=e}return e[t]}}function sr(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Yt}.`);let i=Fs[js];i&&delete i[t]}var _I,js,Fs,vy,ln=w(()=>{Al();_y();_I=Yt.split(".")[0],js=Symbol.for(`opentelemetry.js.api.${_I}`),Fs=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function cn(t,e,i){let r=Ut("diag");if(r)return r[t](e,...i)}var wy,Sy=w(()=>{ln();wy=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return cn("debug",this._namespace,t)}error(...t){return cn("error",this._namespace,t)}info(...t){return cn("info",this._namespace,t)}warn(...t){return cn("warn",this._namespace,t)}verbose(...t){return cn("verbose",this._namespace,t)}}});function ky(t,e){t<0?t=0:t>9999&&(t=9999),e=e||{};function i(r,n){let s=e[r];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:i("error",30),warn:i("warn",50),info:i("info",60),debug:i("debug",70),verbose:i("verbose",80)}}var Ey=w(()=>{});var wI,Ei,xl=w(()=>{ln();Sy();Ey();wI="diag",Ei=class Ty{static instance(){return this._instance||(this._instance=new Ty),this._instance}constructor(){function e(n){return function(...s){let a=Ut("diag");if(a)return a[n](...s)}}let i=this,r=(n,s={logLevel:60})=>{var a;if(n===i){var o;let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return i.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof s=="number"&&(s={logLevel:s});let l=Ut("diag"),c=ky((a=s.logLevel)!==null&&a!==void 0?a:60,n);if(l&&!s.suppressOverrideMessage){var p;let d=(p=new Error().stack)!==null&&p!==void 0?p:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${d}`),c.warn(`Current logger will overwrite one already registered from ${d}`)}return nr("diag",c,i,!0)};i.setLogger=r,i.disable=()=>{sr(wI,i)},i.createComponentLogger=n=>new wy(n),i.verbose=e("verbose"),i.debug=e("debug"),i.info=e("info"),i.warn=e("warn"),i.error=e("error")}}});function qt(t){return Symbol.for(t)}var pn,Bs=w(()=>{pn=new class Ol{constructor(e){let i=this;i._currentContext=e?new Map(e):new Map,i.getValue=r=>i._currentContext.get(r),i.setValue=(r,n)=>{let s=new Ol(i._currentContext);return s._currentContext.set(r,n),s},i.deleteValue=r=>{let n=new Ol(i._currentContext);return n._currentContext.delete(r),n}}}});var Rl,Iy=w(()=>{Rl=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var SI,kI,Ay,xy=w(()=>{SI="0000000000000000",kI="00000000000000000000000000000000",Ay={traceId:kI,spanId:SI,traceFlags:0}});var Qt,Hs=w(()=>{xy();Qt=class{constructor(t=Ay){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,e){return this}setAttributes(t){return this}addEvent(t,e){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,e){}}});function Oy(t,e){if(typeof t!="string"||t.length!==e)return!1;let i=0;for(let r=0;r<t.length;r+=4)i+=(Gs[t.charCodeAt(r)]|0)+(Gs[t.charCodeAt(r+1)]|0)+(Gs[t.charCodeAt(r+2)]|0)+(Gs[t.charCodeAt(r+3)]|0);return i===e}function Ry(t){return Oy(t,32)&&t!=="00000000000000000000000000000000"}function Ny(t){return Oy(t,16)&&t!=="0000000000000000"}function Ti(t){return Ry(t.traceId)&&Ny(t.spanId)}function Py(t){return new Qt(t)}var Gs,Ws=w(()=>{Hs();Gs=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});var Cy,Dy=w(()=>{Bs();Cy=class{active(){return pn}with(t,e,i,...r){return e.call(i,...r)}bind(t,e){return e}enable(){return this}disable(){return this}attach(t){return{dispose(){}}}}});var Nl,EI,TI,ar,$s=w(()=>{ln();xl();Dy();Nl="context",EI=new Cy,TI=Object.freeze({dispose:()=>{}}),ar=class My{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new My),this._instance}setGlobalContextManager(e){return nr(Nl,e,Ei.instance())}active(){return this._getContextManager().active()}with(e,i,r,...n){return this._getContextManager().with(e,i,r,...n)}bind(e,i){return this._getContextManager().bind(e,i)}attach(e){let i=this._getContextManager();return i.attach?i.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,Ei.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),TI)}_getContextManager(){return Ut(Nl)||EI}disable(){this._getContextManager().disable(),sr(Nl,Ei.instance())}}});function Vs(t){return t.getValue(Pl)||void 0}function Ly(){return Vs(ar.getInstance().active())}function dn(t,e){return t.setValue(Pl,e)}function Uy(t){return t.deleteValue(Pl)}function qy(t,e){return dn(t,new Qt(e))}function zs(t){var e;return(e=Vs(t))===null||e===void 0?void 0:e.spanContext()}var Pl,Cl=w(()=>{Bs();$s();Hs();Pl=qt("OpenTelemetry Context Key SPAN")});function II(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var Dl,Ks,Ml=w(()=>{$s();Hs();Cl();Ws();Dl=ar.getInstance(),Ks=class{startSpan(t,e,i=Dl.active()){if(e?.root)return new Qt;let r=i&&zs(i);return II(r)&&Ti(r)?new Qt(r):new Qt}startActiveSpan(t,e,i,r){var n;let s,a,o;if(arguments.length<2)return;arguments.length===2?o=e:arguments.length===3?(s=e,o=i):(s=e,a=i,o=r);let l=(n=a)!==null&&n!==void 0?n:Dl.active(),c=this.startSpan(t,s,l),p=dn(l,c);return Dl.with(p,o,void 0,c)}}});var AI,jy,Fy=w(()=>{Ml();AI=new Ks,jy=class{constructor(t,e,i,r){this._provider=t,this.name=e,this.version=i,this.options=r}startSpan(t,e,i){return this._getTracer().startSpan(t,e,i)}startActiveSpan(t,e,i,r){let n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)}_getTracer(){if(this._delegate)return this._delegate;let t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):AI}}});var By,Hy=w(()=>{Ml();By=class{getTracer(t,e,i){return new Ks}}});var xI,Ll,Gy=w(()=>{Fy();Hy();xI=new By,Ll=class{getTracer(t,e,i){var r;return(r=this.getDelegateTracer(t,e,i))!==null&&r!==void 0?r:new jy(this,t,e,i)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:xI}setDelegate(t){this._delegate=t}getDelegateTracer(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,e,i)}}});var Ce,Wy=w(()=>{$s();Ce=ar.getInstance()});var Ul,$y,zy=w(()=>{ln();xl();Cl();Ws();Gy();Ul="trace",$y=class Vy{constructor(){this._proxyTracerProvider=new Ll,this.wrapSpanContext=Py,this.isSpanContextValid=Ti,this.deleteSpan=Uy,this.getSpan=Vs,this.getActiveSpan=Ly,this.getSpanContext=zs,this.setSpan=dn,this.setSpanContext=qy}static getInstance(){return this._instance||(this._instance=new Vy),this._instance}setGlobalTracerProvider(e){let i=nr(Ul,this._proxyTracerProvider,Ei.instance());return i&&this._proxyTracerProvider.setDelegate(e),i}getTracerProvider(){return Ut(Ul)||this._proxyTracerProvider}getTracer(e,i){return this.getTracerProvider().getTracer(e,i)}disable(){sr(Ul,Ei.instance()),this._proxyTracerProvider=new Ll}}});var Jt,Ky=w(()=>{zy();Jt=$y.getInstance()});var Ys=w(()=>{Bs();Iy();Ws();Wy();Ky()});import{AsyncLocalStorage as RI}from"node:async_hooks";function ql(){let t=dt(_e()).getTracingChannelBinding?.()?.asyncLocalStorage??new RI;function e(){let a=t.getStore();return a||{scope:yi(),isolationScope:bi()}}function i(a){let o=e().scope.clone(),l=e().isolationScope;return t.run({scope:o,isolationScope:l},()=>a(o))}function r(a,o){let l=e().isolationScope;return t.run({scope:a,isolationScope:l},()=>o(a))}function n(a){let o=e().scope.clone(),l=e().isolationScope.clone();return Jr(o.getPropagationContext())||o.setPropagationContext({traceId:hi(),sampleRand:Xe()}),t.run({scope:o,isolationScope:l},()=>a(l))}function s(a,o){let l=e().scope.clone();return t.run({scope:l,isolationScope:a},()=>o(a))}return Vr({withScope:i,withSetScope:r,withIsolationScope:n,withSetIsolationScope:s,getCurrentScope:()=>e().scope,getIsolationScope:()=>e().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:t})}),t}var Yy=w(()=>{St()});function M(t){return[...new Set(t.map(e=>e.module.name))]}var $=w(()=>{});var Qy,or,Qs,jl,GB,Jy=w(()=>{$();Qy={name:"@earendil-works/pi-ai",versionRange:">=0.80.0 <2.0.0"},or=(t,e,i)=>({channelName:e,module:{...Qy,filePath:"dist/models.js"},functionQuery:{className:"ModelsImpl",methodName:t,kind:i}}),Qs=(t,e,i)=>({channelName:e,module:{...Qy,filePath:"dist/compat.js"},functionQuery:{functionName:t,kind:i}}),jl=[or("stream","stream","Sync"),or("streamSimple","stream","Sync"),Qs("stream","stream","Sync"),Qs("streamSimple","stream","Sync"),or("complete","complete","Async"),or("completeSimple","complete","Async"),Qs("complete","complete","Async"),Qs("completeSimple","complete","Async"),or("streamDeferred","stream","Sync"),or("fetchDeferred","complete","Async")],GB=M(jl)});var Fl,VB,Xy=w(()=>{$();Fl=[{channelName:"send",module:{name:"@smithy/core",versionRange:">=3.24.0 <4",filePath:"dist-cjs/submodules/client/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@smithy/smithy-client",versionRange:">=1.0.3 <5",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@aws-sdk/smithy-client",versionRange:"^3.1.0",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}}],VB=M(Fl)});var gt,Bl,YB,Zy=w(()=>{$();gt={name:"amqplib",versionRange:">=0.5.5 <3"},Bl=[...["lib/channel_model.js","lib/callback_model.js"].flatMap(t=>[{channelName:"publish",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"publish",kind:"Sync"}},{channelName:"confirmPublish",module:{...gt,filePath:t},functionQuery:{className:"ConfirmChannel",methodName:"publish",kind:"Callback"}},{channelName:"consume",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"consume",kind:"Sync"}},{channelName:"ack",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"ack",kind:"Sync"}},{channelName:"nack",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"nack",kind:"Sync"}},{channelName:"reject",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"reject",kind:"Sync"}},{channelName:"ackAll",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"ackAll",kind:"Sync"}},{channelName:"nackAll",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"nackAll",kind:"Sync"}}]),{channelName:"registerConsumer",module:{...gt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"registerConsumer",kind:"Sync"}},{channelName:"dispatch",module:{...gt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"dispatchMessage",kind:"Sync"}},{channelName:"connect",module:{...gt,filePath:"lib/connect.js"},functionQuery:{functionName:"connect",kind:"Callback"}}],YB=M(Bl)});var Hl,XB,eb=w(()=>{$();Hl=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/completions.js","resources/completions.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"messages-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"stream",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.63.0 <2",filePath:t},functionQuery:{className:"Messages",methodName:"toolRunner",kind:"Sync"}})),...["lib/tools/SessionToolRunner.js","lib/tools/SessionToolRunner.mjs"].map(t=>({channelName:"session-tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.97.0 <2",filePath:t},functionQuery:{className:"SessionToolRunner"}})),...["lib/BetaMessageStream.js","lib/BetaMessageStream.mjs"].map(t=>({channelName:"thread-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=1.2.0 <2",filePath:t},functionQuery:{className:"BetaMessageStream",methodName:"_start",kind:"Sync"}}))],XB=M(Hl)});var Gl,t3,tb=w(()=>{$();Gl=[{channelName:"cronJobConstructor",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob"}},{channelName:"cronJobSetTime",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob",methodName:"setTime",kind:"Sync"}}],t3=M(Gl)});var lr,ib,rb=w(()=>{lr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},ib=[{channelName:"construct",module:lr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:lr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:lr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:lr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:lr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:lr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var Wl,s3,nb=w(()=>{$();Wl=[{channelName:"handle",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/layer.js"},functionQuery:{expressionName:"handle_request",kind:"Callback"}},{channelName:"handle",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"lib/layer.js"},functionQuery:{expressionName:"handleRequest",kind:"Callback"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"use",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"use",kind:"Sync"}}],s3=M(Wl)});var NI,PI,CI,DI,MI,$l,l3,sb=w(()=>{$();NI=">=3.0.0 <5",PI=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,CI=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],DI=">=6.0.0 <7",MI=[{file:"lib/v2/providers/https.js",functionName:"onRequest",channelName:"http-request"},{file:"lib/v2/providers/https.js",functionName:"onCall",channelName:"http-call"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreated",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreatedWithAuthContext",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdated",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdatedWithAuthContext",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeleted",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeletedWithAuthContext",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWritten",channelName:"firestore-written"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWrittenWithAuthContext",channelName:"firestore-written"},{file:"lib/v2/providers/scheduler.js",functionName:"onSchedule",channelName:"scheduler"},{file:"lib/v2/providers/storage.js",functionName:"onObjectFinalized",channelName:"storage-finalized"},{file:"lib/v2/providers/storage.js",functionName:"onObjectArchived",channelName:"storage-archived"},{file:"lib/v2/providers/storage.js",functionName:"onObjectDeleted",channelName:"storage-deleted"},{file:"lib/v2/providers/storage.js",functionName:"onObjectMetadataUpdated",channelName:"storage-metadata-updated"}],$l=[...CI.map(({functionName:t,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:NI,filePath:PI},functionQuery:{functionName:t,kind:"Auto"}})),...MI.map(({file:t,functionName:e,channelName:i})=>({channelName:i,module:{name:"firebase-functions",versionRange:DI,filePath:t},functionQuery:{functionName:e,kind:"Sync"}}))],l3=M($l)});var Vl,d3,ab=w(()=>{$();Vl=[{channelName:"acquire",module:{name:"generic-pool",versionRange:">=3.0.0 <4",filePath:"lib/Pool.js"},functionQuery:{className:"Pool",methodName:"acquire",kind:"Auto"}},{channelName:"acquire",module:{name:"generic-pool",versionRange:">=2.4.0 <3",filePath:"lib/generic-pool.js"},functionQuery:{expressionName:"acquire",kind:"Callback"}}],d3=M(Vl)});var Js,zl,g3,ob=w(()=>{$();Js=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],zl=[...Js.flatMap(t=>["generateContent","generateContentStream"].map(e=>({channelName:"generate-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{expressionName:e,kind:"Auto"}}))),...Js.map(t=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...Js.flatMap(t=>["sendMessage","sendMessageStream"].map(e=>({channelName:"chat",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Chat",methodName:e,kind:"Auto"}}))),...Js.map(t=>({channelName:"decide",module:{name:"@google/genai",versionRange:">=3.2.0 <4",filePath:t},functionQuery:{className:"GeminiNextGenDecisions",methodName:"create",kind:"Async"}}))],g3=M(zl)});var Kl,y3,lb=w(()=>{$();Kl=[...["language/parser.js","language/parser.mjs"].map(t=>({channelName:"parse",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"parse",kind:"Sync"}})),...["validation/validate.js","validation/validate.mjs"].map(t=>({channelName:"validate",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"validate",kind:"Sync"}})),...["execution/execute.js","execution/execute.mjs"].map(t=>({channelName:"execute",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"execute",kind:"Auto"}}))],y3=M(Kl)});function un(t,e={chat:"Completions",embeddings:"Embeddings"}){return[...["resources/chat/completions.js","resources/chat/completions.mjs"].map(i=>({channelName:"chat",module:{...t,filePath:i},functionQuery:{className:e.chat,methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(i=>({channelName:"embeddings",module:{...t,filePath:i},functionQuery:{className:e.embeddings,methodName:"create",kind:"Sync"}}))]}var Yl=w(()=>{});var Ql,S3,cb=w(()=>{$();Yl();Ql=un({name:"groq-sdk",versionRange:">=0.3.0 <2"}),S3=M(Ql)});var Jl,T3,pb=w(()=>{$();Jl=[{channelName:"route",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"route",kind:"Sync"}},{channelName:"ext",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"ext",kind:"Sync"}},{channelName:"start",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"start",kind:"Sync"}},{channelName:"initialize",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"initialize",kind:"Sync"}}],T3=M(Jl)});var Xl,x3,db=w(()=>{$();Xl=[{channelName:"context",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?context\.js$/},functionQuery:{className:"Context"}},{channelName:"request",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?hono-base\.js$/},astQuery:"PropertyDefinition[key.name='request'] > ArrowFunctionExpression",functionQuery:{kind:"Auto"}}],x3=M(Xl)});function De(t){return{channelName:"module-registration",module:t,astQuery:"Program",transform:LI}}var LI,jt=w(()=>{LI="sentryModuleRegistration"});var Zl,C3,ub=w(()=>{$();jt();Zl=[De({name:"ioredis",versionRange:">=5.11.0",filePath:"built/Redis.js"}),...["lib/redis.js","built/redis.js","built/redis/index.js"].flatMap(t=>[{channelName:"command",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"connect",kind:"Async"}}]),{channelName:"command",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"connect",kind:"Async"}}],C3=M(Zl)});var ec,L3,mb=w(()=>{$();ec=[{channelName:"send_batch",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/producer/messageProducer.js"},functionQuery:{expressionName:"sendBatch",kind:"Async"}},{channelName:"consumer_run",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/consumer/index.js"},functionQuery:{expressionName:"run",kind:"Async"}}],L3=M(ec)});function FI(t,e){return{channelName:"query",module:{name:gb,versionRange:e,filePath:t},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function BI(t,e,i){return{channelName:t,module:{name:gb,versionRange:i,filePath:e},functionQuery:{className:"Client",methodName:t,kind:"Sync"}}}var gb,UI,qI,jI,fb,hb=w(()=>{gb="knex",UI=[{filePath:"lib/execution/runner.js",versionRange:">=0.22.0 <4"},{filePath:"lib/runner.js",versionRange:">=0.10.0 <0.22.0"},{filePath:"src/runner.js",versionRange:">=0.18.0 <0.19.0"}],qI=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],jI=["queryBuilder","schemaBuilder","raw"];fb=[...UI.map(({filePath:t,versionRange:e})=>FI(t,e)),...qI.flatMap(({filePath:t,versionRange:e})=>jI.map(i=>BI(i,t,e)))]});var tc,F3,yb=w(()=>{$();tc=[{channelName:"use",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"use",kind:"Sync"}},{channelName:"callback",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"callback",kind:"Sync"}}],F3=M(tc)});var HI,ic,Xs,bb,GI,WI,rc,G3,W3,_b=w(()=>{$();HI=["dist/language_models/chat_models.cjs","dist/language_models/chat_models.js"].flatMap(t=>{let e={name:"@langchain/core",versionRange:">=0.1.0 <2.0.0",filePath:t};return[{channelName:"chatModelInvoke",module:e,functionQuery:{className:"BaseChatModel",methodName:"invoke",kind:"Async"}},{channelName:"chatModelStream",module:e,functionQuery:{className:"BaseChatModel",methodName:"_streamIterator",kind:"Async"}}]}),ic="embedQuery",Xs="embedDocuments",bb=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[ic,Xs]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[ic,Xs]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[ic,Xs]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Xs]}],GI=bb.flatMap(({name:t,versionRange:e,methods:i})=>["dist/embeddings.cjs","dist/embeddings.js"].flatMap(r=>i.map(n=>({channelName:n,module:{name:t,versionRange:e,filePath:r},functionQuery:{methodName:n,kind:"Async"}})))),WI=["dist/classifier.cjs","dist/classifier.js"].map(t=>({channelName:"typesafeClassifierInvoke",module:{name:"@langchain/typesafe",versionRange:">=0.0.1 <1.0.0",filePath:t},functionQuery:{className:"TypeSafeClassifier",methodName:"invoke",kind:"Async"}})),rc=[...HI,...GI,...WI],G3=bb.flatMap(({name:t,methods:e})=>e.map(i=>`orchestrion:${t}:${i}`)),W3=M(rc)});var vb,$I,VI,nc,z3,wb=w(()=>{$();vb=t=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:t}),$I=["dist/graph/state.cjs","dist/graph/state.js"].map(t=>({channelName:"stateGraphCompile",module:vb(t),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),VI=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(t=>({channelName:"createReactAgent",module:vb(t),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),nc=[...$I,...VI],z3=M(nc)});var sc,Q3,Sb=w(()=>{$();sc=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],Q3=M(sc)});var kb,Eb=w(()=>{jt();kb=[De({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var zI,KI,YI,ac,tH,Tb=w(()=>{$();zI=[{channelName:"mastraConstructor",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/(?:[\w.-]+\/)?mastra[\w.-]*\.(?:cjs|mjs|js)$/},functionQuery:{className:"Mastra"}}],KI=["executeWithContext","executeWithContextSync"].map(t=>({channelName:"mastraExecuteWithContext",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/observability\/context-storage\.(?:cjs|mjs|js)$/},functionQuery:{functionName:t,kind:"Auto"}})),YI=[{channelName:"mastraClassifierEvaluate",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/classifier\/index\.(?:cjs|mjs|js)$/},functionQuery:{className:"Classifier",methodName:"evaluate",kind:"Async"}}],ac=[...zI,...KI,...YI],tH=M(ac)});var Ib,oc,nH,Ab=w(()=>{$();Ib={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},oc=[{channelName:"harnessOpen",module:{...Ib,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([t,e])=>({channelName:"codingTool",module:{...Ib,filePath:`dist/tools/${t}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],nH=M(oc)});var QI,JI,lc,oH,xb=w(()=>{$();QI=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],JI=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],lc=[...QI,...JI],oH=M(lc)});var cc,Zs,Ob,pc,pH,Rb=w(()=>{$();cc={name:"@mistralai/mistralai",versionRange:">=2.0.0 <4"},Zs={...cc,filePath:"esm/sdk/chat.js"},Ob={...cc,filePath:"esm/sdk/agents.js"},pc=[{channelName:"chat",module:Zs,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:Zs,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:Zs,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:Zs,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...cc,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:Ob,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:Ob,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],pH=M(pc)});var Ii,dc,mH,Nb=w(()=>{$();Ii={name:"mongodb"},dc=[{channelName:"command",module:{...Ii,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...Ii,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...Ii,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection_pool.js"},functionQuery:{methodName:"checkOut",kind:"Callback"}},...["insert","update","remove"].map(t=>({channelName:`v3_${t}`,module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:t,kind:"Callback"}})),{channelName:"v3_command",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],mH=M(dc)});var Xt,Pb,uc,yH,bH,Cb=w(()=>{$();jt();Xt={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},Pb=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],uc=[De({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Xt,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Xt,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...Pb.map(t=>({channelName:`ctx_${t}`,module:{...Xt,filePath:"lib/query.js"},functionQuery:{expressionName:t,kind:"Sync"}}))],yH=M(uc),bH=Pb.map(t=>`orchestrion:mongoose:ctx_${t}`)});var mc,SH,Db=w(()=>{$();jt();mc=[De({name:"mysql2",versionRange:">=3.20.0",filePath:"lib/base/connection.js"}),{channelName:"query",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"execute",kind:"Callback"}},{channelName:"query",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"execute",kind:"Callback"}}],SH=M(mc)});var gc,TH,Mb=w(()=>{$();gc=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],TH=M(gc)});var fc,hc,xH,Lb=w(()=>{$();fc={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},hc=[{channelName:"query",module:fc,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:fc,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:fc,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],xH=M(hc)});var Ub,qb=w(()=>{Ub=[{channelName:"nestFactoryCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"nest-factory.js"},functionQuery:{className:"NestFactoryStatic",methodName:"create",kind:"Async"}},{channelName:"routerExecutionContextCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"router/router-execution-context.js"},functionQuery:{className:"RouterExecutionContext",methodName:"create",kind:"Sync"}},{channelName:"injectableDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/injectable.decorator.js"},astQuery:'FunctionDeclaration[id.name="Injectable"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"catchDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/catch.decorator.js"},astQuery:'FunctionDeclaration[id.name="Catch"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"cronDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/cron.decorator.js"},functionQuery:{functionName:"Cron",kind:"Sync"}},{channelName:"intervalDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/interval.decorator.js"},functionQuery:{functionName:"Interval",kind:"Sync"}},{channelName:"timeoutDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/timeout.decorator.js"},functionQuery:{functionName:"Timeout",kind:"Sync"}},{channelName:"scheduleExplorerWrap",module:{name:"@nestjs/schedule",versionRange:">=6.0.0",filePath:"dist/schedule.explorer.js"},functionQuery:{className:"ScheduleExplorer",methodName:"wrapFunctionInTryCatchBlocks",kind:"Sync"}},{channelName:"onEventDecorator",module:{name:"@nestjs/event-emitter",versionRange:">=2.0.0",filePath:"dist/decorators/on-event.decorator.js"},functionQuery:{expressionName:"OnEvent",kind:"Sync"}},{channelName:"processorDecorator",module:{name:"@nestjs/bullmq",versionRange:">=10.0.0",filePath:"dist/decorators/processor.decorator.js"},functionQuery:{functionName:"Processor",kind:"Sync"}}]});var jb,Fb=w(()=>{jt();jb=[De({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var Ai,yc,DH,Bb=w(()=>{$();Ai={functionName:"createTask",kind:"Sync"},yc=[{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.cjs"},functionQuery:Ai},{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.3.0 <4.6.0",filePath:"dist/node-cron.cjs"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.6.0",filePath:"dist/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/cjs/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/esm/node-cron.js"},functionQuery:Ai},{channelName:"v3_createTask",module:{name:"node-cron",versionRange:">=3.0.0 <4",filePath:"src/node-cron.js"},functionQuery:Ai}],DH=M(yc)});var Hb,bc,UH,Gb=w(()=>{$();Hb={channelName:"schedule",astQuery:"AssignmentExpression[left.object.property.name='prototype'][left.property.name='schedule'] > FunctionExpression",functionQuery:{methodName:"schedule",kind:"Sync"}},bc=[{...Hb,module:{name:"node-schedule",versionRange:">=1.3.0 <2",filePath:"lib/schedule.js"}},{...Hb,module:{name:"node-schedule",versionRange:">=2.0.0 <3",filePath:"lib/Job.js"}}],UH=M(bc)});var _c,FH,Wb=w(()=>{$();_c=[...["resources/chat/completions/completions.js","resources/chat/completions/completions.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/responses/responses.js","resources/responses/responses.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Responses",methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(t=>({channelName:"embeddings",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Embeddings",methodName:"create",kind:"Sync"}})),...["resources/conversations/conversations.js","resources/conversations/conversations.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Conversations",methodName:"create",kind:"Sync"}})),...["resources/decisions.js","resources/decisions.mjs"].map(t=>({channelName:"decide",module:{name:"openai",versionRange:">=7.30.0 <8",filePath:t},functionQuery:{className:"Decisions",methodName:"create",kind:"Sync"}}))],FH=M(_c)});var vc,GH,$b=w(()=>{$();vc=[{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"connect",kind:"Auto"}},{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"connect",kind:"Auto"}},{channelName:"connect",module:{name:"pg-pool",versionRange:">=2.0.0 <4",filePath:"index.js"},functionQuery:{className:"Pool",methodName:"connect",kind:"Auto"}}],GH=M(vc)});var XI,wc,zH,Vb=w(()=>{$();jt();XI=t=>[{channelName:"handle",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/query.js`},functionQuery:{className:"Query",methodName:"handle",kind:"Async"}},{channelName:"connection",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"Connection",kind:"Sync"}},{channelName:"execute",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"execute",kind:"Sync"}},{channelName:"connect",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{methodName:"connect",kind:"Sync"}}],wc=[De({name:"postgres",versionRange:">=4.0.0",filePath:"src/query.js"}),...["src","cjs/src"].flatMap(XI)],zH=M(wc)});function zb(t,e){return{channelName:t,module:{name:ZI,versionRange:tA,filePath:eA},functionQuery:{className:"CollectionBase",methodName:t,kind:e}}}var ZI,eA,tA,iA,rA,Sc,QH,Kb=w(()=>{$();ZI="@prisma/orm-family-sql",eA="dist/orm-client.mjs",tA=">=8.0.0-rc.15 <9",iA=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],rA=["all","createAll","updateAll","deleteAll"];Sc=[...iA.map(t=>zb(t,"Async")),...rA.map(t=>zb(t,"Sync"))],QH=M(Sc)});var kc,e5,Yb=w(()=>{$();jt();kc=[De({name:"@redis/client",versionRange:">=5.12.0",filePath:"dist/lib/client/index.js"}),{channelName:"command",module:{name:"redis",versionRange:">=2.6.0 <4",filePath:"index.js"},functionQuery:{expressionName:"internal_send_command",kind:"Sync"}},{channelName:"executor",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"commandsExecutor",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"multi",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executeMulti",kind:"Async"}},{channelName:"pipeline",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executePipeline",kind:"Async"}},{channelName:"batch",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"multiExecutor",kind:"Async"}}],e5=M(kc)});var nA,Qb,Jb=w(()=>{nA=t=>[{channelName:"requestHandler",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/server.js`},astQuery:'FunctionExpression[id.name="requestHandler"]',functionQuery:{kind:"Async"}},{channelName:"matchServerRoutes",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/routeMatching.js`},functionQuery:{functionName:"matchServerRoutes",kind:"Sync"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoader",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteAction",kind:"Async"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoaderRR",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteActionRR",kind:"Async"}}],Qb=["dist","dist/esm"].flatMap(nA)});var Xb,Zb=w(()=>{Xb=[{channelName:"createRouter",module:{name:"@remix-run/fetch-router",versionRange:">=0.21.0 <2",filePath:"dist/lib/router.js"},functionQuery:{functionName:"createRouter",kind:"Sync"}},{channelName:"createAssetServer",module:{name:"@remix-run/assets",versionRange:">=0.6.0 <2",filePath:"dist/lib/asset-server.js"},functionQuery:{functionName:"createAssetServer",kind:"Sync"}},{channelName:"createRequestListener",module:{name:"@remix-run/node-fetch-server",versionRange:">=0.14.0 <2",filePath:"dist/lib/request-listener.js"},functionQuery:{functionName:"createRequestListener",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/ui",versionRange:">=0.8.0 <1",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/component",versionRange:">=1.0.0 <2",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}}]});var sA,aA,oA,Ec,s5,e_=w(()=>{$();sA="tedious",aA="lib/connection.js",oA=">=1.11.0 <21",Ec=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"].map(t=>({channelName:t,module:{name:sA,versionRange:oA,filePath:aA},functionQuery:{className:"Connection",methodName:t,kind:"Sync"}})),s5=M(Ec)});var Tc,c5,t_=w(()=>{$();Yl();Tc=[...un({name:"together-ai",versionRange:">=0.6.0 <1"}),...un({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],c5=M(Tc)});var Ic,u5,i_=w(()=>{$();Ic=["dist/index.mjs","dist/index.cjs"].map(t=>({channelName:"system-one",module:{name:"@typesafe-ai/sdk",versionRange:">=0.5.0 <1",filePath:t},functionQuery:{className:"TypeSafeClient",methodName:"systemOne",kind:"Sync"}})),u5=M(Ic)});function Zt(t,e,i,r){return["dist/index.js","dist/index.mjs"].map(n=>({channelName:e,module:{name:"ai",versionRange:t,filePath:n},functionQuery:{functionName:i,kind:r}}))}var Ac,h5,r_=w(()=>{$();jt();Ac=[...["dist/index.js","dist/index.mjs"].map(t=>De({name:"ai",versionRange:">=7.0.0",filePath:t})),...Zt(">=4.0.0 <7.0.0","generateText","generateText","Async"),...Zt(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...Zt(">=4.0.0 <7.0.0","streamObject","streamObject","Sync"),...Zt(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...Zt(">=4.0.0 <7.0.0","embed","embed","Async"),...Zt(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...Zt(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...Zt(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];h5=M(Ac)});function lA(t=[]){return[...yl([...n_,...t].map(e=>e.module.name)),"@remix-run/node"]}var n_,mn,gG,s_=w(()=>{Xy();Zy();eb();tb();rb();nb();sb();ab();ob();lb();cb();pb();db();ub();mb();hb();yb();_b();wb();Sb();Eb();Tb();Jy();Ab();xb();Rb();Nb();Cb();Db();Mb();Lb();qb();Fb();Bb();Gb();Wb();$b();Vb();Kb();Yb();Jb();Zb();e_();t_();i_();r_();St();n_=[...Bl,...Hl,...Fl,...Gl,...ib,...Wl,...$l,...Vl,...zl,...Kl,...Ql,...Jl,...Xl,...Zl,...ec,...fb,...tc,...rc,...nc,...sc,...kb,...ac,...lc,...pc,...dc,...uc,...mc,...gc,...hc,...Ub,...jb,...yc,...bc,..._c,...vc,...jl,...oc,...wc,...Sc,...kc,...Qb,...Xb,...Ec,...Tc,...Ic,...Ac],mn=n_.filter(t=>!t.transform);gG=lA()});var a_=w(()=>{Yy()});import{posix as cA,sep as pA}from"node:path";function o_(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function l_(t=process.argv[1]?kl(process.argv[1]):process.cwd(),e=pA==="\\"){let i=e?o_(t):t;return r=>{if(!r)return;let n=e?o_(r):r,{dir:s,base:a,ext:o}=cA.parse(n);(o===".js"||o===".mjs"||o===".cjs")&&(a=a.slice(0,o.length*-1));let l=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${l}`;if(s.startsWith(i)){let p=s.slice(i.length+1).replace(/\//g,".");return p?`${p}:${l}`:l}return l}}var c_=w(()=>{St()});var xc,p_=w(()=>{c_();St();Il();xc=vo(Tl(l_()))});import{AsyncLocalStorage as dA}from"node:async_hooks";function m_(t){return t.getValue(Dc)}function mA(t,e){return t.setValue(Dc,e)}function gA(t,e){t.refs[u_]=Qi(e)}function Mc(t){return wi(t.refs[u_])}function fA(t,e){let i=t?Jt.setSpan(Ce.active(),t):Jt.deleteSpan(Ce.active());return Ce.with(i,()=>{let r=Ct();return ws(r,t??void 0),e(r)})}function hA(t){let e=t?yA(t):Jt.getActiveSpan();return e&&Ti(e.spanContext())?e:void 0}function yA(t){let e=Mc(t);return e?Jt.getSpan(e):void 0}function bA(t){let e=m_(t),i=e?.scope||Ct(),r=e?.isolationScope||_i(),n=t.getValue(Nc)===!0,s=t.getValue(Pc),a=t.getValue(Cc),o=s||i.clone(),l=mA(t,{scope:o,isolationScope:a||(n?r.clone():r)}).deleteValue(Nc).deleteValue(Pc).deleteValue(Cc);return(!s||!Mc(s))&&gA(o,l),l}function wA(t){if(typeof t!="object"||!t)return!1;let e=t;return typeof e.on=="function"&&typeof e.emit=="function"}function Oc(t,e){let i=t[e];return typeof i=="function"?i:void 0}function Rc(t,e,i){try{t[e]=i}catch{}}function g_(){let t=dt(_e()).getTracingChannelBinding?.()?.asyncLocalStorage??new dA;function e(){let p=m_(Ce.active());return p||{scope:yi(),isolationScope:bi()}}function i(p){let d=Ce.active();return Ce.with(d,()=>p(a()))}function r(p,d){let m=Mc(p)||Ce.active();return Ce.with(m.setValue(Pc,p),()=>d(p))}function n(p){let d=Ce.active();return Ce.with(d.setValue(Nc,!0),()=>{let m=a();return Jr(m.getPropagationContext())||m.setPropagationContext({traceId:hi(),sampleRand:Xe()}),p(o())})}function s(p,d){let m=Ce.active();return Ce.with(m.setValue(Cc,p),()=>d(o()))}function a(){return e().scope}function o(){return e().isolationScope}function l(){return{asyncLocalStorage:t}}Vr({withScope:i,withSetScope:r,withSetIsolationScope:s,withIsolationScope:n,getCurrentScope:a,getIsolationScope:o,getActiveSpan:hA,withActiveSpan:fA,getTracingChannelBinding:l});let c=new vA(t);return Ce.setGlobalContextManager(c),c.getAsyncLocalStorageLookup()}function SA(t){let{traceFlags:e,traceState:i}=t,r=i?i.get(uA)==="1":!1;if(e===Rl.SAMPLED)return!0;if(r)return!1;let n=i?i.get(d_):void 0,s=n?Yr(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function f_(t){t.on("prepareSpanScope",e=>{let{scope:i,parentSpan:r}=e;if(!r?.spanContext().isRemote)return;let{spanId:n,traceId:s,traceState:a}=r.spanContext(),o=Mt(r),l=typeof o.sample_rand=="string"?Number(o.sample_rand):void 0,c=!!a?.get(d_),p=i.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:SA(r.spanContext()),dsc:c?o:void 0,sampleRand:typeof l=="number"&&!Number.isNaN(l)?l:Xe()}),ws(p,void 0),e.scope=p,e.parentSpan=void 0})}var d_,uA,Dc,Nc,Pc,Cc,u_,FG,_A,vA,h_=w(()=>{St();Ys();Ys();d_="sentry.dsc",uA="sentry.sampled_not_recording",Dc=qt("sentry_scopes"),Nc=qt("sentry_fork_isolation_scope"),Pc=qt("sentry_fork_set_scope"),Cc=qt("sentry_fork_set_isolation_scope"),u_="context";FG=qt("OpenTelemetry SDK Context Key SUPPRESS_TRACING");_A=["addListener","on","once","prependListener","prependOnceListener"],vA=class{constructor(t){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=t}active(){return this._asyncLocalStorage.getStore()??pn}with(t,e,i,...r){let n=bA(t),s=i==null?e:e.bind(i);return this._asyncLocalStorage.run(n,s,...r)}enable(){return this}disable(){try{this._asyncLocalStorage.disable()}catch{}return this}bind(t,e){return wA(e)?this._bindEventEmitter(t,e):typeof e=="function"?this._bindFunction(t,e):e}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:Dc}}_bindFunction(t,e){let i=this.with.bind(this),r=function(...n){return i(t,()=>e.apply(this,n))};return Object.defineProperty(r,"length",{enumerable:!1,configurable:!0,writable:!1,value:e.length}),r}_bindEventEmitter(t,e){if(this._getPatchMap(e)!==void 0||this._createPatchMap(e)===void 0)return e;for(let r of _A){let n=Oc(e,r);n&&Rc(e,r,this._patchAddListener(e,n,t))}for(let r of["removeListener","off"]){let n=Oc(e,r);n&&Rc(e,r,this._patchRemoveListener(e,n))}let i=Oc(e,"removeAllListeners");return i&&Rc(e,"removeAllListeners",this._patchRemoveAllListeners(e,i)),e}_patchRemoveListener(t,e){let i=this;return function(r,n){let s=i._getPatchMap(t)?.[r];if(s===void 0)return e.call(this,r,n);let a=s.get(n);return e.call(this,r,a||n)}}_patchRemoveAllListeners(t,e){let i=this;return function(r){let n=i._getPatchMap(t);return n!==void 0&&(arguments.length===0?i._createPatchMap(t):r!==void 0&&n[r]!==void 0&&delete n[r]),e.apply(this,arguments)}}_patchAddListener(t,e,i){let r=this;return function(n,s){if(r._wrapped)return e.call(this,n,s);let a=r._getPatchMap(t)??r._createPatchMap(t);if(a===void 0)return e.call(this,n,s);let o=a[n];o===void 0&&(o=new WeakMap,a[n]=o);let l=r.bind(i,s);o.set(s,l),r._wrapped=!0;try{return e.call(this,n,l)}finally{r._wrapped=!1}}}_createPatchMap(t){let e=Object.create(null);try{t[this._kOtListeners]=e}catch{return}return this._getPatchMap(t)===e?e:void 0}_getPatchMap(t){return t[this._kOtListeners]}}});var kA,gn,EA,TA,IA,Lc,je,de,y_,b_,cr,__,ge=w(()=>{kA=Object.create,gn=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,TA=Object.getOwnPropertyNames,IA=Object.getPrototypeOf,Lc=Object.prototype.hasOwnProperty,je=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}},de=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e,e.exports),t=null),e.exports),y_=(t,e)=>{let i=Object.setPrototypeOf({},null);for(var r in t)gn(i,r,{get:t[r],enumerable:!0});return e&1||gn(i,Symbol.toStringTag,{value:"Module"}),e&2?i:Object.preventExtensions(i)},b_=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var n=TA(e),s=0,a=n.length,o;s<a;s++)o=n[s],!Lc.call(t,o)&&o!==i&&gn(t,o,{get:(l=>e[l]).bind(null,o),enumerable:!(r=EA(e,o))||r.enumerable});return t},cr=(t,e,i)=>(i=t!=null?kA(IA(t)):{},b_(e||!t||!t.__esModule||!Lc.call(t,"default")?gn(i,"default",{value:t,enumerable:!0}):i,t)),__=t=>Lc.call(t,"module.exports")?t["module.exports"]:b_(gn({},"__esModule",{value:!0}),t)});function ea(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}var AA,Uc=w(()=>{ge();AA=je((()=>{}));AA()});function Ze(t,e,i){ea(t,e),e.set(t,i)}var fn,qc=w(()=>{ge();Uc();fn=je((()=>{}));fn()});function ft(t,e,i){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var xA,ta=w(()=>{ge();xA=je((()=>{}));xA()});function ht(t,e,i){return t.set(ft(t,e),i),i}var hn,jc=w(()=>{ge();ta();hn=je((()=>{}));hn()});function he(t,e){return t.get(ft(t,e))}var yn,Fc=w(()=>{ge();ta();yn=je((()=>{}));yn()});var Bc,aW,v_=w(()=>{ge();Bc=de(((t,e)=>{e.exports=i;function i(m,g){let[h]=p(m,"");for(let f of s(g))if(r(f,h))return!0;return!1}function r(m,g){for(let[h,f]of m)if(!d(g,f,h))return!1;return!0}function n(m){return m==="latest"&&(m=">=0"),m.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function s(m){let g=[],h=[],f=m.trim().split(/\s+/);for(let b=0;b<f.length;b++){let S=f[b];if(S==="-")continue;if(S==="||"){g.push(h),h=[];continue}if(/^[<>=~v^]+$/.test(S)&&b+1<f.length){f[b+1]=S+f[b+1];continue}let E=n(S),A=E[1]||"=";A.endsWith("v")&&(A=A.slice(0,-1));let[C,N]=p(E[2],A);if(b+2<f.length&&f[b+1]==="-"){let R=n(f[b+2]);f[b+2]="<="+(R[2].indexOf("-")===-1?R[2]+".*.*":R[2]),N=">="}if(N[0]==="~"){let R=E[2].split("-")[0].split(".").length;h.push([">=",C]),h.push(["<",R===1?a(C,0):a(C,1)])}else if(N[0]==="^"){let R=C[0]!==0?0:C[1]!==0?1:2;h.push([">=",C]),h.push(["<",R===0?a(C,0):R===1?a(C,1):a(C,2)])}else h.push([N.replace("~","").replace("^",""),C])}return h.length&&g.push(h),g}function a(m,g){let h=m.slice(0);if(m[g]===-1)return h;for(h[g++]++;g<3;g++)h[g]=0;return h}function o(m){return m==="x"||m==="X"||m==="*"||m==="latest"?-1:Number(m)}function l(m){return/^\d+$/.test(m)?Number(m):m}function c(m,g,h){return h===-1?m!=="<":m==="="?g===h:m===">"?g>h:m===">="?g>=h:m==="<"?g<h:m==="<="?g<=h:!1}function p(m,g){m=m.split("+")[0];let[h,f]=m.split("-"),b=h.split(".").map(o).slice(0,3),S=Math.max(b.length-1,0);return g===">"?(g=">=",b.push(0,0,0),b[S]++):g===""?b.push(0,0,0):b.push(-1,-1,-1),f?[b.slice(0,3).concat(f.split(".").map(l)),g]:[b.slice(0,3),g]}function d(m,g,h){if(!c("=",m[0],g[0]))return c(h,m[0],g[0]);if(!c("=",m[1],g[1]))return c(h,m[1],g[1]);if(!c("=",m[2],g[2])||m.length===3&&g.length===3)return c(h,m[2],g[2]);if(h[0]==="<"&&(g.length===3||m.length===3))return!1;if(h[0]===">"){if(m.length===3)return!0;if(g.length===3)return!1}for(let f=3;f<Math.max(m.length,g.length);f++)if(c(h,m[f]||"",g[f]||""))return!0;return!1}})),aW=Bc()});function w_(t,e){ea(t,e),e.add(t)}var Hc,S_=w(()=>{ge();Uc();Hc=je((()=>{}));Hc()});var ia,Gc=w(()=>{ia={}});var ra,Wc=w(()=>{ra={}});var k_,E_=w(()=>{k_={}});var $c,yW,T_=w(()=>{ge();Gc();Wc();$c=de(((t,e)=>{let i=ia.v??{},{parse:r}=ra.v??{},n=I=>I.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",s=/[^\w]/g,a=I=>`tr_ch_apm$${I.replace(s,"_")}`;e.exports={tracingChannelImport({dcModule:I,moduleType:x},L){if(L.body.some(n))return;let U={module:x==="esm"},k=L.body.findIndex(F=>F.directive==="use strict"),v=x==="esm"?`import tr_ch_apm_dc from "${I}"`:`const tr_ch_apm_dc = require("${I}")`;L.body.splice(k+1,0,r(v,U).body[0],r("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",U).body[0],r(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
314
+ `),typeof o=="string"||o instanceof Uint8Array)n(o);else{let l;try{l=JSON.stringify(o)}catch{l=JSON.stringify(pt(o))}n(l)}}return typeof r=="string"?r:TT(r)}function TT(t){let e=t.reduce((n,s)=>n+s.length,0),i=new Uint8Array(e),r=0;for(let n of t)i.set(n,r),r+=n.length;return i}function If(t){let e=typeof t.data=="string"?el(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}function IT(t){return t in Af}function il(t){return IT(t)?Af[t]:t}function nn(t){if(!t?.sdk)return;let{name:e,version:i}=t.sdk;return{name:e,version:i}}function xf(t,e,i,r){let n=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(Pe()).toISOString(),...e&&{sdk:e},...!!i&&r&&{dsn:ze(r)},...n&&{trace:n}}}function sn(t){return t==="replay_event"?"replay":t||"error"}var Af,zt=w(()=>{at();Vt();ps();ct();st();Af={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",metric:"trace_metric"}});function Of(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var Rf=w(()=>{});function Nf(){return!Of()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var Pf=w(()=>{Rf()});function Cf(){return typeof window<"u"&&(!Nf()||AT())}function AT(){return Y.process?.type==="renderer"}var Df=w(()=>{Pf();st()});function Mf(t,e,i){let r=i.getOptions(),n=i.getDsn(),s=r.tunnel,a=nn(r._metadata),o={sent_at:new Date(Pe()).toISOString(),...xT(e)&&{trace:e},...a&&{sdk:a},...!!s&&n&&{dsn:ze(n)}};return mt(o,[rl(t,i)])}function rl(t,e){let i=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:t.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,ingest_settings:Cf()?{infer_ip:i,infer_user_agent:i}:void 0,items:t}]}function xT(t){return!!t.trace_id&&!!t.public_key}var nl=w(()=>{Vt();zt();Df();ct()});function Lf(t){let e=156;if(e+=t.name.length*2,e+=Uo(t.attributes),t.links&&t.links.length>0){let i=t.links[0]?.attributes,r=100+(i?Uo(i):0);e+=r*t.links.length}return e}var Uf=w(()=>{qo()});function RT(t,e,i){let r=t.attributes[Kr];if(e===void 0||r?.value!==e)return;let n=i();n!==e&&(t.attributes[Kr]={...r,value:n})}var qf,OT,jf,Ff=w(()=>{Re();Ne();Dt();Ns();Zi();nl();Uf();vt();qf=1e3,OT=5e6,jf=class{constructor(t,e){this._traceBuckets=new Map,this._client=t;let{maxSpanLimit:i,flushInterval:r,maxTraceWeightInBytes:n}=e??{};this._maxSpanLimit=i&&i>0&&i<=qf?i:qf,this._flushInterval=r&&r>0?r:5e3,this._maxTraceWeight=n&&n>0?n:OT,this._client.on("flush",()=>{this.drain()}),this._client.on("close",()=>{this._traceBuckets.forEach(s=>{clearTimeout(s.timeout)}),this._traceBuckets.clear()})}add(t){let e=t.trace_id,i=this._traceBuckets.get(e);i||(i={spans:new Set,size:0,timeout:er(setTimeout(()=>{this.flush(e)},this._flushInterval))},this._traceBuckets.set(e,i)),i.spans.add(t),i.size+=Lf(t),(i.spans.size>=this._maxSpanLimit||i.size>=this._maxTraceWeight)&&this.flush(e)}drain(){this._traceBuckets.size&&(B&&q.log(`Flushing span tree map with ${this._traceBuckets.size} traces`),this._traceBuckets.forEach((t,e)=>{this.flush(e)}))}flush(t){let e=this._traceBuckets.get(t);if(!e)return;if(!e.spans.size){this._removeTrace(t);return}let i=Array.from(e.spans),r=i[0]?._segmentSpan;if(!r){B&&q.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(t);return}let n=Mt(r),s=new Map,a=c=>{let p=s.get(c);return p===void 0&&(p=Xr(c).name,s.set(c,p)),p},o=i.map(c=>{let{_segmentSpan:p,_segmentNameAtCapture:d,...m}=c;return RT(m,d,()=>a(p)),m}),l=Mf(o,n,this._client);B&&q.log(`Sending span envelope for trace ${t} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,c=>{B&&q.error("Error while sending streamed span envelope:",c)}),this._removeTrace(t)}_removeTrace(t){let e=this._traceBuckets.get(t);e&&clearTimeout(e.timeout),this._traceBuckets.delete(t)}}});var NT,Bf,Hf=w(()=>{Re();kf();Zo();Ff();Ne();Dt();Ns();NT="SpanStreaming",Bf=(t={})=>{let e=t.flushOnSegmentEnd??!0;return{name:NT,setup(i){if(!Rs(i)){B&&q.log('[SpanStreaming] `traceLifecycle` is "static", skipping setup.');return}let r=new jf(i);i.on("afterSpanEnd",n=>{Ts(n)&&r.add(Sf(n,i))}),i.on("flushTraceSpans",n=>{r.flush(n)}),e&&i.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;er(setTimeout(()=>{r.flush(s)},500))})}}}});function CT(t){return bt(t)?void 0:t}function Wf(t,e,i){let r=CT(e.originalException),n=r&&PT.get(r);if(!n)return;let s=t.contexts?.trace;(s?.trace_id??(i&&vi(i).trace_id))===n.trace_id&&(t.contexts={...t.contexts,trace:{...s,...n}})}var PT,Gf=w(()=>{ut();qe();PT=new WeakMap});function $f(t){$e(_e()).segmentSpanCaptureStrategy=t}function Vf(){return $e(_e()).segmentSpanCaptureStrategy}var zf=w(()=>{at()});function Kf(t,e,i){let r,n,s,a=i?.maxWait?Math.max(i.maxWait,e):0,o=i?.setTimeoutImpl||setTimeout;function l(){return c(),r=t(),r}function c(){n!==void 0&&clearTimeout(n),s!==void 0&&clearTimeout(s),n=s=void 0}function p(){return n!==void 0||s!==void 0?l():r}function d(){return n&&clearTimeout(n),n=o(l,e),a&&s===void 0&&(s=o(l,a)),r}return d.cancel=c,d.flush=p,d}var Yf=w(()=>{});function sl(t){if(Vf()||$f(DT),Ds.has(t))return;let e=new Set,i=Kf(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});t.on("flush",()=>{i.flush()}),Ds.set(t,r=>{e.add(r),i()})}var Cs,Qf,Jf,Ds,DT,Xf=w(()=>{Yf();zf();Cs=new WeakSet,Qf=t=>Cs.has(t),Jf=t=>{Cs.add(t)},Ds=new WeakMap;DT={onSegmentSpanEnded(t,e){let i=e.getClient(),r=i&&Ds.get(i);if(!r){let n=t();n&&i?.captureEvent(n);return}r(()=>{let n=t({isSpanAlreadyCaptured:Qf,onSpanCaptured:Jf});n&&i.captureEvent(n)})},onChildSpanEnded(t,e,i,r){if(Cs.has(t)||!Cs.has(e))return;let n=r.getClient(),s=n&&Ds.get(n),a=()=>{let o=i({isSpanAlreadyCaptured:Qf,onSpanCaptured:Jf});o?.contexts?.trace?.data&&(o.contexts.trace.data["sentry.parent_span_already_sent"]=!0),o&&n?.captureEvent(o)};s?s(a):a()}}});function MT(t,e){if(!e)return t;let i=t.sdk||{};return t.sdk={...i,name:i.name||e.name,version:i.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0},t}function Zf(t,e,i,r){let n=nn(i),s={sent_at:new Date(Pe()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:ze(e)}},a="aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()];return mt(s,[a])}function eh(t,e,i,r){let n=nn(i),s=t.type&&t.type!=="replay_event"?t.type:"event";MT(t,i?.sdk);let a=xf(t,n,r,e);return delete t.sdkProcessingMetadata,mt(a,[[{type:s},t]])}var th=w(()=>{Vt();zt();ct()});function Lt(t){return new nh(e=>{e(t)})}function tr(t){return new nh((e,i)=>{i(t)})}var al,ih,rh,nh,ir=w(()=>{qe();al=0,ih=1,rh=2;nh=class ol{constructor(e){this._state=al,this._handlers=[],this._runExecutor(e)}then(e,i){return new ol((r,n)=>{this._handlers.push([!1,s=>{if(!e)r(s);else try{r(e(s))}catch(a){n(a)}},s=>{if(!i)n(s);else try{r(i(s))}catch(a){n(a)}}]),this._executeHandlers()})}catch(e){return this.then(i=>i,e)}finally(e){return new ol((i,r)=>{let n,s;return this.then(a=>{s=!1,n=a,e&&e()},a=>{s=!0,n=a,e&&e()}).then(()=>{if(s){r(n);return}i(n)})})}_executeHandlers(){if(this._state===al)return;let e=this._handlers.slice();this._handlers=[],e.forEach(i=>{i[0]||(this._state===ih&&i[1](this._value),this._state===rh&&i[2](this._value),i[0]=!0)})}_runExecutor(e){let i=(s,a)=>{if(this._state===al){if(Nt(a)){a.then(r,n);return}this._state=s,this._value=a,this._executeHandlers()}},r=s=>{i(ih,s)},n=s=>{i(rh,s)};try{e(r,n)}catch(s){n(s)}}}});function sh(t,e,i,r=0,n){try{let s=ll(e,i,t,r,n);return Nt(s)?s:Lt(s)}catch(s){return tr(s)}}function ll(t,e,i,r,n){let s=i[r];if(!t||!s)return t;let a=`Event processor "${s.id||"?"}"`,o=!1,l=Si(B?`${a} threw an error, dropping event:`:"",()=>s({...t},e),()=>(o=!0,null));return B&&l===null&&q.log(`${a} dropped event`),Nt(l)?l.then(c=>c?ll(c,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)):l?ll(l,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)}var ah=w(()=>{Re();Ne();qe();Os();ir()});function ch(t){let e=Y._sentryDebugIds,i=Y._debugIds;if(!e&&!i)return{};let r=e?Object.keys(e):[],n=i?Object.keys(i):[];if(Kt&&r.length===oh&&n.length===lh)return Kt;oh=r.length,lh=n.length,Kt={},ki||(ki={});let s=(a,o)=>{for(let l of a){let c=o[l],p=ki?.[l];if(p&&Kt&&c)Kt[p[0]]=c,ki&&(ki[l]=[p[0],c]);else if(c){let d=t(l);for(let m=d.length-1;m>=0;m--){let g=d[m]?.filename;if(g&&Kt&&ki){Kt[g]=c,ki[l]=[g,c];break}}}}};return e&&s(r,e),i&&s(n,i),Kt}var ki,oh,lh,Kt,ph=w(()=>{st()});function an(t){return t.data?.__sentry__===!0}function dh(t){let e=[];t.message&&e.push(t.message);try{let i=t.exception.values[t.exception.values.length-1];i?.value&&(e.push(i.value),i.type&&e.push(`${i.type}: ${i.value}`))}catch{}return e}var cl=w(()=>{});function uh(t,e,i,r,n,s){let{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=t,l={...e,event_id:e.event_id||i.event_id||we(),timestamp:e.timestamp||fi()},c=i.integrations||t.integrations.map(E=>E.name);LT(l,t),jT(l,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&UT(l,t.stackParser);let p=BT(r,i.captureContext);i.mechanism&&Jm(l,i.mechanism);let d=n?n.getEventProcessors():[],m=xs(s,p),g=[...i.attachments||[],...m.attachments];g.length&&(i.attachments=g),ff(l,m);let h=Zr(p);h&&hf(l,h),Wf(l,i,p);let f=[...d,...m.eventProcessors],b=e.type==="transaction",S=e.spans?.length||0;return(an(i)?Lt(l):sh(f,l,i,0,E=>{n&&(n.recordDroppedEvent(E,sn(e.type)),b&&n.recordDroppedEvent(E,"span",1+S))})).then(E=>{if(!E)return null;if(b&&n){let A=S-(E.spans?.length||0);A>0&&n.recordDroppedEvent("event_processor","span",A)}return qT(E),typeof a=="number"&&a>0?FT(E,a,o):E})}function LT(t,e){let{environment:i,release:r,dist:n,maxValueLength:s}=e;t.environment=t.environment||i||"production",!t.release&&r&&(t.release=r),!t.dist&&n&&(t.dist=n);let a=t.request;a?.url&&s&&(a.url=Fr(a.url,s)),s&&t.exception?.values?.forEach(o=>{o.value&&(o.value=Fr(o.value,s))})}function UT(t,e){let i=ch(e);t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=i[n.filename])})})}function qT(t){let e={};if(t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.debug_id&&(n.abs_path?e[n.abs_path]=n.debug_id:n.filename&&(e[n.filename]=n.debug_id),delete n.debug_id)})}),Object.keys(e).length===0)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];let i=t.debug_meta.images;Object.entries(e).forEach(([r,n])=>{i.push({type:"sourcemap",code_file:r,debug_id:n})})}function jT(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function FT(t,e,i){if(!t)return null;let r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(n=>({...n,...n.data&&{data:pt(n.data,e,i)}}))},...t.user&&{user:pt(t.user,e,i)},...t.contexts&&{contexts:pt(t.contexts,e,i)},...t.extra&&{extra:pt(t.extra,e,i)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=pt(t.contexts.trace.data,e,i))),t.spans&&(r.spans=t.spans.map(n=>({...n,...n.data&&{data:pt(n.data,e,i)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=pt(t.contexts.flags,3,i)),r}function BT(t,e){if(!e)return t;let i=t?t.clone():new Ve;return i.update(e),i}var mh=w(()=>{ah();Ki();ph();zt();Gf();cl();Pt();ps();Qo();Dt();Hr();ir();zi()});function HT(t){let e=t.protocol?`${t.protocol}:`:"",i=t.port?`:${t.port}`:"";return`${e}//${t.host}${i}${t.path?`/${t.path}`:""}/api/`}function WT(t){return`${HT(t)}${t.projectId}/envelope/`}function GT(t,e){let i={sentry_version:"7"};return t.publicKey&&(i.sentry_key=t.publicKey),e&&(i.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(i).toString()}function gh(t,e,i){return e||`${WT(t)}?${GT(t,i)}`}var fh=w(()=>{});function hh(t,e){if(t.type!=="transaction"||!t.spans?.length||!t.sdkProcessingMetadata?.hasGenAiSpans||Rs(e))return;let i=[],r=[];for(let n of t.spans)n.op?.startsWith("gen_ai.")?i.push(bf(n)):r.push(n);if(i.length!==0)return t.spans=r,rl(i,e)}var yh=w(()=>{nl();Zo();_f()});function rr(t=100){let e=new Set;function i(){return e.size<t}function r(a){e.delete(a)}function n(a){if(!i())return tr(on);let o=a();return e.add(o),o.then(()=>r(o),()=>r(o)),o}function s(a){if(!e.size)return Lt(!0);let o=Promise.allSettled(Array.from(e)).then(()=>!0);if(!a)return o;let l=[o,new Promise(c=>er(setTimeout(()=>c(!1),a)))];return Promise.race(l)}return{get $(){return Array.from(e)},add:n,drain:s}}var on,Ms=w(()=>{ir();Ns();on=Symbol.for("SentryBufferFullError")});function VT(t,e=Pe()){let i=parseInt(`${t}`,10);if(!isNaN(i))return i*1e3;let r=Date.parse(`${t}`);return isNaN(r)?$T:r-e}function zT(t,e){return t[e]||t.all||0}function bh(t,e,i=Pe()){return zT(t,e)>i}function _h(t,e,i=Pe()){let r={...t};return KT(e,i,(n,s)=>{r[n]=Math.max(r[n]||0,s)}),r}function KT({statusCode:t,headers:e},i,r){let n=e?.["x-sentry-rate-limits"],s=e?.["retry-after"];if(n)for(let a of n.trim().split(",")){let[o,l,,,c]=a.split(":",5),p=parseInt(o,10),d=(isNaN(p)?60:p)*1e3;if(!l)r("all",i+d);else for(let m of l.split(";"))m==="metric_bucket"?(!c||c.split(";").includes("custom"))&&r(m,i+d):r(m,i+d)}else s?r("all",i+VT(s,i)):t===429&&r("all",i+6e4)}var $T,vh=w(()=>{ct();$T=6e4});function pl(t,e,i=rr(t.bufferSize||64)){let r={},n=o=>i.drain(o);function s(o,[l,c],p){let d=il(p);p==="transaction"&&t.recordDroppedEvent(o,"span",(c.spans?.length??0)+1),t.recordDroppedEvent(o,d,typeof l.item_count=="number"?l.item_count:1)}function a(o){let l=[];if(Ps(o,(m,g)=>{bh(r,il(g))?s("ratelimit_backoff",m,g):l.push(m)}),l.length===0)return Promise.resolve({});let c=mt(o[0],l),p=m=>{if(Ef(c,["client_report"])){B&&q.warn(`Dropping client report. Will not send outcomes (reason: ${m}).`);return}Ps(c,(g,h)=>{s(m,g,h)})},d=()=>e({body:Tf(c)}).then(m=>m.statusCode===413?(B&&q.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),p("send_error"),m):(B&&m.statusCode!==void 0&&(m.statusCode<200||m.statusCode>=300)&&q.warn(`Sentry responded with status code ${m.statusCode} to sent event.`),r=_h(r,m),m),m=>{throw p("network_error"),B&&q.error("Encountered error running transport request:",m),m});return i.add(d).then(m=>m,m=>{if(m===on)return B&&q.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw m})}return{send:a,flush:n}}var wh=w(()=>{Re();Ne();zt();Ms();vh()});function Sh(t,e,i){let r=[{type:"client_report"},{timestamp:i||fi(),discarded_events:t}];return mt(e?{dsn:e}:{},[r])}var kh=w(()=>{zt();zi()});function Eh(t){let{trace_id:e,parent_span_id:i,span_id:r,status:n,origin:s,data:a,op:o,links:l}=t.contexts?.trace??{};return{data:a??{},description:t.transaction,op:o,parent_span_id:i,span_id:r??"",start_timestamp:t.start_timestamp??0,status:n??"ok",timestamp:t.timestamp,trace_id:e??"",origin:s,links:l,profile_id:a?.[zr],exclusive_time:a?.[Fo],measurements:t.measurements,is_segment:!0}}function Th(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,links:t.links,data:{...t.data,...t.profile_id&&{[zr]:t.profile_id},...t.exclusive_time&&{[Fo]:t.exclusive_time}}}},measurements:t.measurements}}var Ih=w(()=>{vt()});function Ah(t){t.traceLifecycle!=="stream"||!(t.beforeSendTransaction||t.ignoreTransactions?.length)||ot(()=>{console.warn("[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.")})}var xh=w(()=>{Ne()});function YT(t){return typeof t=="boolean"||"allow"in t||"deny"in t}function QT(t){return t===void 0?{...Ie.httpHeaders}:YT(t)?{request:t,response:t}:{request:t.request??Ie.httpHeaders.request,response:t.response??Ie.httpHeaders.response}}function Oh(t){let e=t.dataCollection??{};return{userInfo:e.userInfo??Ie.userInfo,cookies:e.cookies??Ie.cookies,httpHeaders:QT(e.httpHeaders),httpBodies:e.httpBodies??Ie.httpBodies,urlQueryParams:e.urlQueryParams??Ie.urlQueryParams,graphQL:{document:e.graphQL?.document??Ie.graphQL.document,variables:e.graphQL?.variables??Ie.graphQL.variables},genAI:{inputs:e.genAI?.inputs??Ie.genAI.inputs,outputs:e.genAI?.outputs??Ie.genAI.outputs},mcp:{inputs:e.mcp?.inputs??Ie.mcp.inputs,outputs:e.mcp?.outputs??Ie.mcp.outputs},databaseQueryData:e.databaseQueryData??Ie.databaseQueryData,queues:e.queues??Ie.queues,stackFrameVariables:e.stackFrameVariables??Ie.stackFrameVariables,frameContextLines:e.frameContextLines??Ie.frameContextLines}}var Ie,Rh=w(()=>{Ie={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},mcp:{inputs:!0,outputs:!0},databaseQueryData:!0,queues:!0,stackFrameVariables:!0,frameContextLines:5}});function Ch(t){return{message:t,[Uh]:!0}}function dl(t){return{message:t,[qh]:!0}}function Dh(t){return dl(`Discarding event because it's not included in the random sample (sampling rate = ${t})`)}function Mh(t){return qr(t)&&Uh in t}function Lh(t){return qr(t)&&qh in t}function XT(t,e,i,r,n){let{beforeSend:s,ignoreSpans:a,beforeSendTransaction:o}=t,l=tn(t.beforeSendSpan)&&t.beforeSendSpan,c=e;if(ul(c)&&s){let p=c;return Si(B?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,i),()=>(r("callback_error"),null))}if(Fh(c)){if(l||a){let p=Eh(c);if(a?.length&&Vo({description:p.description,op:p.op,attributes:p.data},a))return r("ignored"),null;if(l){let d=rn(p,l);c=Gt(e,Th(d))}if(c.spans){let d=[],m=c.spans;for(let g of m){if(a?.length&&Vo({description:g.description,op:g.op,attributes:g.data},a)){nf(m,g);continue}l?d.push(rn(g,l)):d.push(g)}n(m.length-d.length),c.spans=d}}if(o)return Si(B?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>o(c,i),()=>(r("callback_error"),null))}return c}function ul(t){return t.type===void 0}function Fh(t){return t.type==="transaction"}var Nh,Ph,Uh,qh,JT,jh,Bh=w(()=>{fh();pf();ut();Re();th();lf();Po();Zi();Jo();yh();kh();Ne();Vt();zt();cl();qe();gs();Pt();Vg();mh();Ms();ct();Os();sf();ir();Ih();xh();Rh();Nh="Not capturing exception because it's already been captured.",Ph="Discarded session because of missing or non-string release",Uh=Symbol.for("SentryInternalError"),qh=Symbol.for("SentryDoNotSendEventError"),JT=Symbol.for("SentryClosedClient");jh=class{constructor(t){this._options={attachStacktrace:!0,...t,traceLifecycle:t.traceLifecycle==="static"?"static":"stream"},this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=rr(t.transportOptions?.bufferSize??64),this._dataCollection=Oh(t),this._unhandledSessionStatus="crashed",this._attachStacktraceIsDefault=t.attachStacktrace===void 0,t.dsn?this._dsn=Qr(t.dsn):B&&q.warn("No DSN provided, client will not send events.");let{beforeSendSpan:e,traceLifecycle:i}=this._options;if(B&&e&&tn(e)!==(i==="static")&&ot(()=>{console.warn(`Ignoring \`beforeSendSpan\`: ${i==="static"?"wrap it with":"remove"} \`Sentry.withStaticSpan\` to use it with \`traceLifecycle: "${i}"\`.`)}),this._dsn){let r=gh(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:r})}}captureException(t,e,i){let r=we();if(us(t))return B&&q.log(Nh),r;let n={event_id:r,...e};return this._process(()=>this.eventFromException(t,n).then(s=>this._captureEvent(s,n,i)).then(s=>s),"error"),n.event_id}captureMessage(t,e,i,r){let n={event_id:we(),...i},s=Ur(t)?t:String(t),a=bt(t),o=a?this.eventFromMessage(s,e,n).then(l=>(l.exception&&this._attachStacktraceIsDefault&&(l.sdkProcessingMetadata={...l.sdkProcessingMetadata,hasDefaultSyntheticStacktrace:!0}),l)):this.eventFromException(t,n);return this._process(()=>o.then(l=>this._captureEvent(l,n,r)),a?"unknown":"error"),n.event_id}captureEvent(t,e,i){let r=we();if(e?.originalException&&us(e.originalException))return B&&q.log(Nh),r;let n={event_id:r,...e},s=t.sdkProcessingMetadata||{},a=s.capturedSpanScope,o=s.capturedSpanIsolationScope,l=sn(t.type);return this._process(()=>this._captureEvent(t,n,a||i,o),l),n.event_id}captureSession(t){this.sendSession(t),Wr(t,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(t){let e=this._transport;if(this.emit("flush"),!e)return!0;let i=await this._isClientDoneProcessing(t),r=await e.flush(t);return i&&r}async close(t){Object.defineProperty(this,JT,{value:!0});let e=await this.flush(t);return this.getOptions().enabled=!1,this.emit("close"),e}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&(this._setupIntegrations(),Ah(this._options))}getIntegrationByName(t){return this._integrations[t]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(t){let e=this._integrations[t.name];!e&&t.beforeSetup&&t.beforeSetup(this),Ko(this,t,this._integrations),e||zo(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);let i=hh(t,this),r=eh(t,this._dsn,this._options._metadata,this._options.tunnel);if(!an(e))for(let n of e.attachments||[])r=tl(r,If(n));i&&(r=tl(r,i)),this.sendEnvelope(r).then(n=>this.emit("afterSendEvent",t,n))}sendSession(t){let{release:e,environment:i=cf}=this._options;if("aggregates"in t){let n=t.attrs||{};if(!n.release&&!e){B&&q.warn(Ph);return}n.release=n.release||e,n.environment=n.environment||i,t.attrs=n}else{if(!t.release&&!e){B&&q.warn(Ph);return}t.release=t.release||e,t.environment=t.environment||i}this.emit("beforeSendSession",t);let r=Zf(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(t,e,i=1){if(this._options.sendClientReports){let r=`${t}:${e}`;B&&q.log(`Recording outcome: "${r}"${i>1?` (${i} times)`:""}`),this._outcomes[r]=(this._outcomes[r]||0)+i}}on(t,e){let i=this._hooks[t]=this._hooks[t]||new Set,r=(...n)=>e(...n);return i.add(r),()=>{i.delete(r)}}emit(t,...e){let i=this._hooks[t];i&&i.forEach(r=>r(...e))}async sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)try{let e=await this._transport.send(t);return this.emit("afterEnvelope",t),e}catch(e){return B&&q.error("Error while sending envelope:",e),{}}return B&&q.error("Transport disabled"),{}}registerCleanup(t){}dispose(){}_setupIntegrations(){let{integrations:t}=this._options;this._integrations=of(this,t),zo(this,t)}_updateSessionFromEvent(t,e){let i=e.level==="fatal",r=!1,n=e.exception?.values;if(n){r=!0,i=!1;for(let a of n)if(a.mechanism?.handled===!1){i=!0;break}}let s=t.status==="ok";(s&&t.errors===0||s&&i)&&(Wr(t,{...i&&{status:this._unhandledSessionStatus},errors:t.errors||Number(r||i)}),this.captureSession(t))}async _isClientDoneProcessing(t){let e=0;for(;!t||e<t;){if(await new Promise(i=>setTimeout(i,1)),!this._numProcessing)return!0;e++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(t,e,i,r){let n=this.getOptions(),s=this.getIntegrationNames();return!e.integrations&&s.length&&(e.integrations=s),this.emit("preprocessEvent",t,e),t.type||r.setLastEventId(t.event_id||e.event_id),uh(n,t,e,i,this,r).then(a=>(a===null||(this.emit("postprocessEvent",a,e),a.contexts={trace:{...a.contexts?.trace,...vi(i)},...a.contexts},a.sdkProcessingMetadata={dynamicSamplingContext:Xi(this,i),...a.sdkProcessingMetadata}),a))}_captureEvent(t,e={},i=Ct(),r=_i()){return B&&ul(t)&&q.log(`Captured error event \`${dh(t)[0]||"<unknown>"}\``),this._processEvent(t,e,i,r).then(n=>n.event_id,n=>{B&&(Lh(n)?q.log(n.message):Mh(n)?q.warn(n.message):q.warn(n))})}_processEvent(t,e,i,r){let n=this.getOptions(),{sampleRate:s}=n,a=Fh(t),o=ul(t),l=`before send for type \`${t.type||"error"}\``,c="before_send",p=0,d=typeof s>"u"?void 0:$g(s),m=o&&typeof d=="number"&&Xe()>d,g=sn(t.type),h=0,f=i.getSession()||r.getSession();return m&&f?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),tr(Dh(s))):this._prepareEvent(t,e,i,r).then(b=>{if(b===null)throw dl("An event processor returned `null`, will not send event.");return h=b.spans?.length||0,an(e)?b:XT(n,b,e,S=>{c=S},S=>{p=S})}).then(b=>{if(p&&this.recordDroppedEvent("ignored","span",p),!gi(b)||b===null)throw this.recordDroppedEvent(c,g),a&&this.recordDroppedEvent(c,"span",1+h-p),b!==null?Ch(`${l} must return \`null\` or a valid event.`):dl(`${c==="ignored"?"Transaction matched `ignoreSpans`":`${l} ${c==="callback_error"?"threw an error":"returned `null`"}`}, will not send event.`);if(o&&f&&this._updateSessionFromEvent(f,b),m)throw this.recordDroppedEvent("sample_rate","error"),Dh(s);if(a){let E=h-p-(b.spans?.length||0);E>0&&this.recordDroppedEvent("before_send","span",E)}let S=b.transaction_info;if(a&&S&&b.transaction!==t.transaction){let E="custom";b.transaction_info={...S,source:E}}return this.sendEvent(b,e),b}).then(null,b=>{throw Lh(b)||Mh(b)?b:(this.captureException(b,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:b}),Ch(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
315
+ Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t).then(i=>(this._numProcessing--,i),i=>(this._numProcessing--,i===on&&this.recordDroppedEvent("queue_overflow",e),i))}_clearOutcomes(){let t=this._outcomes;return this._outcomes={},Object.entries(t).map(([e,i])=>{let[r,n]=e.split(":");return{reason:r,category:n,quantity:i}})}_flushOutcomes(){B&&q.log("Flushing outcomes...");let t=this._clearOutcomes();if(t.length===0){B&&q.log("No outcomes to send");return}if(!this._dsn){B&&q.log("No dsn provided, will not send outcomes");return}B&&q.log("Sending outcomes:",t);let e=Sh(t,this._options.tunnel&&ze(this._dsn));this.sendEnvelope(e)}}});function ml(){ZT.clear(),B&&q.log("Cleared AI provider skip registrations")}var ZT,Hh=w(()=>{Re();Ne();ZT=new Set});function Wh(t,e,i,r,n){let s={sent_at:new Date(Pe()).toISOString()};i?.sdk&&(s.sdk={name:i.sdk.name,version:i.sdk.version}),r&&n&&(s.dsn=ze(n)),e&&(s.trace=e);let a=eI(t);return mt(s,[a])}function eI(t){return[{type:"check_in"},t]}var Gh=w(()=>{Vt();zt();ct()});function $h(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0).toString(36)}var Vh=w(()=>{});function gl(){return yt("tunnelStore",()=>({clients:new WeakMap}))}function Ls(t){return gl().clients.get(t)}function Us(t,e){let{clients:i}=gl();i.set(t,{...i.get(t),...e})}function zh(){return gl().defaults}var fl=w(()=>{at()});function Kh(t,e,i){let r=rI(e.allowedDsns,t.getDsn()),n={paths:iI(e,r),basePath:e.basePath,allowedDsns:r,forward:i,intercept:e.intercept!==!1};return Us(t,{served:n}),n}function tI(t){let e=t?Qr(t):_t()?.getDsn();return e?`/${$h(ze(e))}`:void 0}function iI(t,e){let i=t.path?.replace(/\/$/,"");if(i)return[i];let r=e.map(n=>tI(n));return[...new Set(r.filter(n=>!!n))]}function Yh(t,e){if(!e.length)return[];let i=`${Ao(hl(t.basePath))}(?:${e.map(Ao).join("|")})/?`;return[{attributes:{[Dg]:new RegExp(`^${i}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${i}(?:[?#].*)?$`)}}]}function hl(t){let e=(t?.startsWith("./")?t.slice(1):t??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function rI(t,e){let i=new Set;for(let r of[...(t??[]).map(n=>Qr(n)),e])r&&i.add(ze(r));return[...i]}var Qh=w(()=>{ut();Ym();Vt();Vh();fl();vt()});function yl(t,e,i=[e],r="npm"){let n=(t._metadata=t._metadata||{}).sdk=t._metadata.sdk||{};n.name||(n.name=`sentry.javascript.${e}`,n.packages=i.map(s=>({name:`${r}:@sentry/${s}`,version:Rt})),n.version=Rt)}var Jh=w(()=>{ss()});function bl(t){return Array.from(new Set(t))}var Xh=w(()=>{});function Zh(t,e,i,r,n,s){if(!n.exception?.values||!s||!lt(s.originalException))return;let a=n.exception.values.length>0?n.exception.values[n.exception.values.length-1]:void 0;a&&(n.exception.values=qs(t,e,r,s.originalException,i,n.exception.values,a,0))}function qs(t,e,i,r,n,s,a,o){if(s.length>=i+1)return s;let l=[...s];if(lt(r[n])){_l(a,o,r);let c=t(e,r[n]),p=l.length;vl(c,n,p,o),l=qs(t,e,i,r[n],n,[c,...l],c,p)}return ey(r)&&r.errors.forEach((c,p)=>{if(l.length<i+1&&lt(c)){_l(a,o,r);let d=t(e,c),m=l.length;vl(d,`errors[${p}]`,m,o),l=qs(t,e,i,c,n,[d,...l],d,m)}}),nI(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(l.length<i+1&&lt(p)){_l(a,o,r);let d=t(e,p),m=l.length;vl(d,c,m,o),l=qs(t,e,i,p,n,[d,...l],d,m)}}),l}function ey(t){return Array.isArray(t.errors)}function nI(t){return"error"in t&&"suppressed"in t}function _l(t,e,i){t.mechanism={handled:!0,type:"auto.core.linked_errors",...ey(i)&&{is_exception_group:!0},...t.mechanism,exception_id:e}}function vl(t,e,i,r){t.mechanism={handled:!0,...t.mechanism,type:"chained",source:e,exception_id:i,parent_id:r}}var ty=w(()=>{qe()});function iy(t,e){return t(e.stack||"",1)}function sI(t){return lt(t)&&"__sentry_fetch_url_host__"in t&&typeof t.__sentry_fetch_url_host__=="string"}function aI(t){let e=oI(t.message);return sI(t)?`${e} (${t.__sentry_fetch_url_host__})`:e}function oI(t){if(typeof t=="string")return t;if(t==null)return"";if(bt(t))return String(t);if(gi(t)||Array.isArray(t)){let e=Qm(t,"");if(e)return e}return Io(void 0,t)}function wl(t,e){let i={type:e.name||e.constructor.name,value:aI(e)},r=iy(t,e);return r.length&&(i.stacktrace={frames:r}),i}function lI(t){for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let i=t[e];if(lt(i))return i}}function cI(t){if("name"in t&&typeof t.name=="string"){let r=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(r+=` with message '${t.message}'`),r}else if("message"in t&&typeof t.message=="string")return t.message;let e=Wm(t);if(qm(t))return`Event \`ErrorEvent\` captured as exception with message \`${t.message}\``;let i=pI(t);return`${i&&i!=="Object"?`'${i}'`:"Object"} captured as exception with keys: ${e}`}function pI(t){try{let e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function dI(t,e,i,r){if(lt(i))return[i,void 0];if(e.synthetic=!0,gi(i)){let s=t?.getOptions().normalizeDepth,a={__serialized__:To(i,s)},o=lI(i);if(o)return[o,a];let l=cI(i),c=r?.syntheticException||new Error(l);return c.message=l,[c,a]}let n=r?.syntheticException||new Error(i);return n.message=`${i}`,[n,void 0]}function ry(t,e,i,r){let n=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[s,a]=dI(t,n,i,r),o={exception:{values:[wl(e,s)]}};return a&&(o.extra=a),Ro(o,void 0,void 0),ds(o,n),{...o,event_id:r?.event_id}}function ny(t,e,i="info",r,n){let s={event_id:r?.event_id,level:i};if(n&&r?.syntheticException){let a=iy(t,r.syntheticException);a.length&&(s.exception={values:[{value:e,stacktrace:{frames:a}}]},ds(s,{synthetic:!0}))}if(Ur(e)){let{__sentry_template_string__:a,__sentry_template_values__:o}=e;return s.logentry={message:a,params:o},s}return s.message=e,s}var Sl=w(()=>{qe();Pt();ps();jr();Hr()});var uI,mI,gI,fI,kl,sy=w(()=>{ty();Sl();uI="cause",mI=5,gI="LinkedErrors",fI=((t={})=>{let e=t.limit||mI,i=t.key||uI;return{name:gI,preprocessEvent(r,n,s){let a=s.getOptions();Zh(wl,a.stackParser,i,e,r,n)}}}),kl=fI});function ay(t,e){return e?ys(e,()=>{let i=Zr(),r=i?ks(i):vi(e);return[i?Mt(i):Xi(t,e),r]}):[void 0,void 0]}var oy=w(()=>{ut();Zi();Dt()});function yI(t){let e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,i=hI.exec(e);return i?i.slice(1):[]}function El(t){let e=yI(t),i=e[0]||"",r=e[1];return!i&&!r?".":(r&&(r=r.slice(0,r.length-1)),i+r)}var hI,ly=w(()=>{hI=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var wt=w(()=>{ut();Do();fs();at();Ki();wh();Hh();Zi();Go();Jh();Xf();Xh();_s();sy();st();Ne();Pt();ly();os();zg();Ho();$r();ss();ct()});function cy(t){let e=t._metadata?.sdk,i=e?.name&&e?.version?`${e?.name}/${e?.version}`:void 0;t.transportOptions={...t.transportOptions,headers:{...i&&{"user-agent":i},...t.transportOptions?.headers}}}var py=w(()=>{});function dy(t){let e=zh(),i=t?.getOptions(),r=i?._managedTunnel??e?.tunnel,n=t&&(Ls(t)?.forward??e?.forward);if(!t||!i||!r||!n)return;let s=hl(e?.basePath),a=r.basePath===void 0&&!r.path&&s?{...r,basePath:s}:r;i._managedTunnel=a;let{paths:o}=Kh(t,a,n),l=Ls(t)?.spanFilters??[],c=Yh(a,o);i.ignoreSpans=[...(i.ignoreSpans??[]).filter(p=>!l.includes(p)),...c],Us(t,{spanFilters:c})}var uy=w(()=>{fl();Qh()});function my(t){let e=_i().getScopeData().sdkProcessingMetadata.requestSession;if(e){let i=t?.mechanism?.handled??!0;i&&e.status!=="crashed"?e.status="errored":i||(e.status="crashed")}}var Tl,gy=w(()=>{Gh();Bh();ut();Re();Hf();py();Ne();Sl();Pt();Ms();ir();oy();uy();vt();Tl=class extends jh{constructor(t){cy(t),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&t.traceLifecycle!=="static"&&!t.integrations.some(e=>e.name==="SpanStreaming")&&t.integrations.push(Bf()),super(t),this._disposeCallbacks=[],dy(this),this._setUpMetricsProcessing()}eventFromException(t,e){let i=ry(this,this._options.stackParser,t,e);return i.level="error",Lt(i)}eventFromMessage(t,e="info",i){return Lt(ny(this._options.stackParser,t,e,i,this._options.attachStacktrace))}captureException(t,e,i){return my(e),super.captureException(t,e,i)}captureEvent(t,e,i){return!t.type&&t.exception?.values&&t.exception.values.length>0&&my(e),super.captureEvent(t,e,i)}captureCheckIn(t,e,i){let r="checkInId"in t&&t.checkInId?t.checkInId:we();if(!this._isEnabled())return B&&q.warn("SDK not enabled, will not capture check-in."),r;let{release:n,environment:s,tunnel:a}=this.getOptions(),o={check_in_id:r,monitor_slug:t.monitorSlug,status:t.status,release:n,environment:s};"duration"in t&&(o.duration=t.duration),e&&(o.monitor_config={schedule:e.schedule,checkin_margin:e.checkinMargin,max_runtime:e.maxRuntime,timezone:e.timezone,failure_issue_threshold:e.failureIssueThreshold,recovery_threshold:e.recoveryThreshold});let[l,c]=ay(this,i);c&&(o.contexts={trace:c});let p=Wh(o,l,this.getSdkMetadata(),a,this.getDsn());return B&&q.log("Sending checkin:",t.monitorSlug,t.status),this.sendEnvelope(p),r}registerCleanup(t){this._disposeCallbacks.push(t)}dispose(){B&&q.log("Disposing client...");for(let t of this._disposeCallbacks)try{t()}catch{}this._disposeCallbacks.length=0;for(let t of Object.keys(this._hooks))this._hooks[t]?.clear();this._hooks={},this._eventProcessors.length=0,this._integrations={},this._outcomes={},this._transport=void 0,this._promiseBuffer=rr(64)}_prepareEvent(t,e,i,r){return this._options.platform&&(t.platform=t.platform||this._options.platform),this._options.runtime&&(t.contexts={...t.contexts,runtime:t.contexts?.runtime||this._options.runtime}),this._options.serverName&&(t.server_name=t.server_name||this._options.serverName),super._prepareEvent(t,e,i,r)}_setUpMetricsProcessing(){this.on("processMetric",t=>{this._options.serverName&&(t.attributes={[bs]:this._options.serverName,...t.attributes})})}}});function hy(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function yy(t){let e=/^\s*[-]{4,}$/,i=/at (?:async )?(?:(?=.*\)\s*$)(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,r=/at (?:async )?(.+?) \(data:(.*?),/;return n=>{let s=n.match(r);if(s)return{filename:`<data:${s[2]}>`,function:s[1]};let a=n.match(i);if(a){let o,l,c,p,d;if(a[1]){c=a[1];let f=c.lastIndexOf(".");if(c[f-1]==="."&&f--,f>0){o=c.slice(0,f),l=c.slice(f+1);let b=o.indexOf(".Module");b>0&&(c=c.slice(b+1),o=o.slice(0,b))}p=void 0}l&&(p=o,d=l),l==="<anonymous>"&&(d=void 0,c=void 0),c===void 0&&(d=d||"?",c=p?`${p}.${d}`:d);let m=Lm(a[2]),g=a[5]==="native";!m&&a[5]&&!g&&(m=a[5]);let h=m?vI(m):void 0;return{filename:h??m,module:h&&t?.(h),function:c,lineno:fy(a[3]),colno:fy(a[4]),in_app:hy(m||"",g)}}if(n.match(e))return{filename:n}}}function Il(t){return[90,yy(t)]}function fy(t){return parseInt(t||"",10)||void 0}function vI(t){try{return decodeURI(t)}catch{return}}var by=w(()=>{os()});var Al=w(()=>{gy();by()});var Yt,xl=w(()=>{Yt="1.10.0"});function wI(t){let e=new Set([t]),i=new Set,r=t.match(_y);if(!r)return()=>!1;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(l){return l===t};function s(o){return i.add(o),!1}function a(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(i.has(l))return!1;let c=l.match(_y);if(!c)return s(l);let p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||n.major!==p.major?s(l):n.major===0?n.minor===p.minor&&n.patch<=p.patch?a(l):s(l):n.minor<=p.minor?a(l):s(l)}}var _y,vy,wy=w(()=>{xl();_y=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;vy=wI(Yt)});function kI(){return Object.defineProperty({},"version",{value:Yt,enumerable:!0,writable:!1,configurable:!1})}function nr(t,e,i,r=!1){var n;let s=Fs[js]=(n=Fs[js])!==null&&n!==void 0?n:kI();if(!r&&s[t]){let a=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return i.error(a.stack||a.message),!1}if(s.version!=="1.10.0"){let a=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${Yt}`);return i.error(a.stack||a.message),!1}return s[t]=e,i.debug(`@opentelemetry/api: Registered a global for ${t} v${Yt}.`),!0}function Ut(t){let e=Fs[js];if(e!=null){if(e!==Sy){if(!e.version||!vy(e.version))return;Sy=e}return e[t]}}function sr(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Yt}.`);let i=Fs[js];i&&delete i[t]}var SI,js,Fs,Sy,ln=w(()=>{xl();wy();SI=Yt.split(".")[0],js=Symbol.for(`opentelemetry.js.api.${SI}`),Fs=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function cn(t,e,i){let r=Ut("diag");if(r)return r[t](e,...i)}var ky,Ey=w(()=>{ln();ky=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return cn("debug",this._namespace,t)}error(...t){return cn("error",this._namespace,t)}info(...t){return cn("info",this._namespace,t)}warn(...t){return cn("warn",this._namespace,t)}verbose(...t){return cn("verbose",this._namespace,t)}}});function Ty(t,e){t<0?t=0:t>9999&&(t=9999),e=e||{};function i(r,n){let s=e[r];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:i("error",30),warn:i("warn",50),info:i("info",60),debug:i("debug",70),verbose:i("verbose",80)}}var Iy=w(()=>{});var EI,Ei,Ol=w(()=>{ln();Ey();Iy();EI="diag",Ei=class Ay{static instance(){return this._instance||(this._instance=new Ay),this._instance}constructor(){function e(n){return function(...s){let a=Ut("diag");if(a)return a[n](...s)}}let i=this,r=(n,s={logLevel:60})=>{var a;if(n===i){var o;let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return i.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof s=="number"&&(s={logLevel:s});let l=Ut("diag"),c=Ty((a=s.logLevel)!==null&&a!==void 0?a:60,n);if(l&&!s.suppressOverrideMessage){var p;let d=(p=new Error().stack)!==null&&p!==void 0?p:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${d}`),c.warn(`Current logger will overwrite one already registered from ${d}`)}return nr("diag",c,i,!0)};i.setLogger=r,i.disable=()=>{sr(EI,i)},i.createComponentLogger=n=>new ky(n),i.verbose=e("verbose"),i.debug=e("debug"),i.info=e("info"),i.warn=e("warn"),i.error=e("error")}}});function qt(t){return Symbol.for(t)}var pn,Bs=w(()=>{pn=new class Rl{constructor(e){let i=this;i._currentContext=e?new Map(e):new Map,i.getValue=r=>i._currentContext.get(r),i.setValue=(r,n)=>{let s=new Rl(i._currentContext);return s._currentContext.set(r,n),s},i.deleteValue=r=>{let n=new Rl(i._currentContext);return n._currentContext.delete(r),n}}}});var Nl,xy=w(()=>{Nl=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var TI,II,Oy,Ry=w(()=>{TI="0000000000000000",II="00000000000000000000000000000000",Oy={traceId:II,spanId:TI,traceFlags:0}});var Qt,Hs=w(()=>{Ry();Qt=class{constructor(t=Oy){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,e){return this}setAttributes(t){return this}addEvent(t,e){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,e){}}});function Ny(t,e){if(typeof t!="string"||t.length!==e)return!1;let i=0;for(let r=0;r<t.length;r+=4)i+=(Ws[t.charCodeAt(r)]|0)+(Ws[t.charCodeAt(r+1)]|0)+(Ws[t.charCodeAt(r+2)]|0)+(Ws[t.charCodeAt(r+3)]|0);return i===e}function Py(t){return Ny(t,32)&&t!=="00000000000000000000000000000000"}function Cy(t){return Ny(t,16)&&t!=="0000000000000000"}function Ti(t){return Py(t.traceId)&&Cy(t.spanId)}function Dy(t){return new Qt(t)}var Ws,Gs=w(()=>{Hs();Ws=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});var My,Ly=w(()=>{Bs();My=class{active(){return pn}with(t,e,i,...r){return e.call(i,...r)}bind(t,e){return e}enable(){return this}disable(){return this}attach(t){return{dispose(){}}}}});var Pl,AI,xI,ar,$s=w(()=>{ln();Ol();Ly();Pl="context",AI=new My,xI=Object.freeze({dispose:()=>{}}),ar=class Uy{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new Uy),this._instance}setGlobalContextManager(e){return nr(Pl,e,Ei.instance())}active(){return this._getContextManager().active()}with(e,i,r,...n){return this._getContextManager().with(e,i,r,...n)}bind(e,i){return this._getContextManager().bind(e,i)}attach(e){let i=this._getContextManager();return i.attach?i.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,Ei.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),xI)}_getContextManager(){return Ut(Pl)||AI}disable(){this._getContextManager().disable(),sr(Pl,Ei.instance())}}});function Vs(t){return t.getValue(Cl)||void 0}function qy(){return Vs(ar.getInstance().active())}function dn(t,e){return t.setValue(Cl,e)}function jy(t){return t.deleteValue(Cl)}function Fy(t,e){return dn(t,new Qt(e))}function zs(t){var e;return(e=Vs(t))===null||e===void 0?void 0:e.spanContext()}var Cl,Dl=w(()=>{Bs();$s();Hs();Cl=qt("OpenTelemetry Context Key SPAN")});function OI(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var Ml,Ks,Ll=w(()=>{$s();Hs();Dl();Gs();Ml=ar.getInstance(),Ks=class{startSpan(t,e,i=Ml.active()){if(e?.root)return new Qt;let r=i&&zs(i);return OI(r)&&Ti(r)?new Qt(r):new Qt}startActiveSpan(t,e,i,r){var n;let s,a,o;if(arguments.length<2)return;arguments.length===2?o=e:arguments.length===3?(s=e,o=i):(s=e,a=i,o=r);let l=(n=a)!==null&&n!==void 0?n:Ml.active(),c=this.startSpan(t,s,l),p=dn(l,c);return Ml.with(p,o,void 0,c)}}});var RI,By,Hy=w(()=>{Ll();RI=new Ks,By=class{constructor(t,e,i,r){this._provider=t,this.name=e,this.version=i,this.options=r}startSpan(t,e,i){return this._getTracer().startSpan(t,e,i)}startActiveSpan(t,e,i,r){let n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)}_getTracer(){if(this._delegate)return this._delegate;let t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):RI}}});var Wy,Gy=w(()=>{Ll();Wy=class{getTracer(t,e,i){return new Ks}}});var NI,Ul,$y=w(()=>{Hy();Gy();NI=new Wy,Ul=class{getTracer(t,e,i){var r;return(r=this.getDelegateTracer(t,e,i))!==null&&r!==void 0?r:new By(this,t,e,i)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:NI}setDelegate(t){this._delegate=t}getDelegateTracer(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,e,i)}}});var Ce,Vy=w(()=>{$s();Ce=ar.getInstance()});var ql,zy,Yy=w(()=>{ln();Ol();Dl();Gs();$y();ql="trace",zy=class Ky{constructor(){this._proxyTracerProvider=new Ul,this.wrapSpanContext=Dy,this.isSpanContextValid=Ti,this.deleteSpan=jy,this.getSpan=Vs,this.getActiveSpan=qy,this.getSpanContext=zs,this.setSpan=dn,this.setSpanContext=Fy}static getInstance(){return this._instance||(this._instance=new Ky),this._instance}setGlobalTracerProvider(e){let i=nr(ql,this._proxyTracerProvider,Ei.instance());return i&&this._proxyTracerProvider.setDelegate(e),i}getTracerProvider(){return Ut(ql)||this._proxyTracerProvider}getTracer(e,i){return this.getTracerProvider().getTracer(e,i)}disable(){sr(ql,Ei.instance()),this._proxyTracerProvider=new Ul}}});var Jt,Qy=w(()=>{Yy();Jt=zy.getInstance()});var Ys=w(()=>{Bs();xy();Gs();Vy();Qy()});import{AsyncLocalStorage as CI}from"node:async_hooks";function jl(){let t=dt(_e()).getTracingChannelBinding?.()?.asyncLocalStorage??new CI;function e(){let a=t.getStore();return a||{scope:yi(),isolationScope:bi()}}function i(a){let o=e().scope.clone(),l=e().isolationScope;return t.run({scope:o,isolationScope:l},()=>a(o))}function r(a,o){let l=e().isolationScope;return t.run({scope:a,isolationScope:l},()=>o(a))}function n(a){let o=e().scope.clone(),l=e().isolationScope.clone();return Jr(o.getPropagationContext())||o.setPropagationContext({traceId:hi(),sampleRand:Xe()}),t.run({scope:o,isolationScope:l},()=>a(l))}function s(a,o){let l=e().scope.clone();return t.run({scope:l,isolationScope:a},()=>o(a))}return Vr({withScope:i,withSetScope:r,withIsolationScope:n,withSetIsolationScope:s,getCurrentScope:()=>e().scope,getIsolationScope:()=>e().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:t})}),t}var Jy=w(()=>{wt()});function M(t){return[...new Set(t.map(e=>e.module.name))]}var $=w(()=>{});var Xy,or,Qs,Fl,VB,Zy=w(()=>{$();Xy={name:"@earendil-works/pi-ai",versionRange:">=0.80.0 <2.0.0"},or=(t,e,i)=>({channelName:e,module:{...Xy,filePath:"dist/models.js"},functionQuery:{className:"ModelsImpl",methodName:t,kind:i}}),Qs=(t,e,i)=>({channelName:e,module:{...Xy,filePath:"dist/compat.js"},functionQuery:{functionName:t,kind:i}}),Fl=[or("stream","stream","Sync"),or("streamSimple","stream","Sync"),Qs("stream","stream","Sync"),Qs("streamSimple","stream","Sync"),or("complete","complete","Async"),or("completeSimple","complete","Async"),Qs("complete","complete","Async"),Qs("completeSimple","complete","Async"),or("streamDeferred","stream","Sync"),or("fetchDeferred","complete","Async")],VB=M(Fl)});var Bl,YB,eb=w(()=>{$();Bl=[{channelName:"send",module:{name:"@smithy/core",versionRange:">=3.24.0 <4",filePath:"dist-cjs/submodules/client/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@smithy/smithy-client",versionRange:">=1.0.3 <5",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@aws-sdk/smithy-client",versionRange:"^3.1.0",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}}],YB=M(Bl)});var gt,Hl,XB,tb=w(()=>{$();gt={name:"amqplib",versionRange:">=0.5.5 <3"},Hl=[...["lib/channel_model.js","lib/callback_model.js"].flatMap(t=>[{channelName:"publish",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"publish",kind:"Sync"}},{channelName:"confirmPublish",module:{...gt,filePath:t},functionQuery:{className:"ConfirmChannel",methodName:"publish",kind:"Callback"}},{channelName:"consume",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"consume",kind:"Sync"}},{channelName:"ack",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"ack",kind:"Sync"}},{channelName:"nack",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"nack",kind:"Sync"}},{channelName:"reject",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"reject",kind:"Sync"}},{channelName:"ackAll",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"ackAll",kind:"Sync"}},{channelName:"nackAll",module:{...gt,filePath:t},functionQuery:{className:"Channel",methodName:"nackAll",kind:"Sync"}}]),{channelName:"registerConsumer",module:{...gt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"registerConsumer",kind:"Sync"}},{channelName:"dispatch",module:{...gt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"dispatchMessage",kind:"Sync"}},{channelName:"connect",module:{...gt,filePath:"lib/connect.js"},functionQuery:{functionName:"connect",kind:"Callback"}}],XB=M(Hl)});var Wl,t3,ib=w(()=>{$();Wl=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/completions.js","resources/completions.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"messages-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"stream",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.63.0 <2",filePath:t},functionQuery:{className:"Messages",methodName:"toolRunner",kind:"Sync"}})),...["lib/tools/SessionToolRunner.js","lib/tools/SessionToolRunner.mjs"].map(t=>({channelName:"session-tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.97.0 <2",filePath:t},functionQuery:{className:"SessionToolRunner"}})),...["lib/BetaMessageStream.js","lib/BetaMessageStream.mjs"].map(t=>({channelName:"thread-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=1.2.0 <2",filePath:t},functionQuery:{className:"BetaMessageStream",methodName:"_start",kind:"Sync"}}))],t3=M(Wl)});var Gl,n3,rb=w(()=>{$();Gl=[{channelName:"cronJobConstructor",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob"}},{channelName:"cronJobSetTime",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob",methodName:"setTime",kind:"Sync"}}],n3=M(Gl)});var lr,nb,sb=w(()=>{lr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},nb=[{channelName:"construct",module:lr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:lr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:lr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:lr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:lr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:lr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var $l,l3,ab=w(()=>{$();$l=[{channelName:"handle",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/layer.js"},functionQuery:{expressionName:"handle_request",kind:"Callback"}},{channelName:"handle",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"lib/layer.js"},functionQuery:{expressionName:"handleRequest",kind:"Callback"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"use",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"use",kind:"Sync"}}],l3=M($l)});var DI,MI,LI,UI,qI,Vl,d3,ob=w(()=>{$();DI=">=3.0.0 <5",MI=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,LI=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],UI=">=6.0.0 <7",qI=[{file:"lib/v2/providers/https.js",functionName:"onRequest",channelName:"http-request"},{file:"lib/v2/providers/https.js",functionName:"onCall",channelName:"http-call"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreated",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreatedWithAuthContext",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdated",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdatedWithAuthContext",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeleted",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeletedWithAuthContext",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWritten",channelName:"firestore-written"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWrittenWithAuthContext",channelName:"firestore-written"},{file:"lib/v2/providers/scheduler.js",functionName:"onSchedule",channelName:"scheduler"},{file:"lib/v2/providers/storage.js",functionName:"onObjectFinalized",channelName:"storage-finalized"},{file:"lib/v2/providers/storage.js",functionName:"onObjectArchived",channelName:"storage-archived"},{file:"lib/v2/providers/storage.js",functionName:"onObjectDeleted",channelName:"storage-deleted"},{file:"lib/v2/providers/storage.js",functionName:"onObjectMetadataUpdated",channelName:"storage-metadata-updated"}],Vl=[...LI.map(({functionName:t,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:DI,filePath:MI},functionQuery:{functionName:t,kind:"Auto"}})),...qI.map(({file:t,functionName:e,channelName:i})=>({channelName:i,module:{name:"firebase-functions",versionRange:UI,filePath:t},functionQuery:{functionName:e,kind:"Sync"}}))],d3=M(Vl)});var zl,g3,lb=w(()=>{$();zl=[{channelName:"acquire",module:{name:"generic-pool",versionRange:">=3.0.0 <4",filePath:"lib/Pool.js"},functionQuery:{className:"Pool",methodName:"acquire",kind:"Auto"}},{channelName:"acquire",module:{name:"generic-pool",versionRange:">=2.4.0 <3",filePath:"lib/generic-pool.js"},functionQuery:{expressionName:"acquire",kind:"Callback"}}],g3=M(zl)});var Js,Kl,y3,cb=w(()=>{$();Js=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],Kl=[...Js.flatMap(t=>["generateContent","generateContentStream"].map(e=>({channelName:"generate-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{expressionName:e,kind:"Auto"}}))),...Js.map(t=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...Js.flatMap(t=>["sendMessage","sendMessageStream"].map(e=>({channelName:"chat",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Chat",methodName:e,kind:"Auto"}}))),...Js.map(t=>({channelName:"decide",module:{name:"@google/genai",versionRange:">=3.2.0 <4",filePath:t},functionQuery:{className:"GeminiNextGenDecisions",methodName:"create",kind:"Async"}}))],y3=M(Kl)});var Yl,v3,pb=w(()=>{$();Yl=[...["language/parser.js","language/parser.mjs"].map(t=>({channelName:"parse",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"parse",kind:"Sync"}})),...["validation/validate.js","validation/validate.mjs"].map(t=>({channelName:"validate",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"validate",kind:"Sync"}})),...["execution/execute.js","execution/execute.mjs"].map(t=>({channelName:"execute",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"execute",kind:"Auto"}}))],v3=M(Yl)});function un(t,e={chat:"Completions",embeddings:"Embeddings"}){return[...["resources/chat/completions.js","resources/chat/completions.mjs"].map(i=>({channelName:"chat",module:{...t,filePath:i},functionQuery:{className:e.chat,methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(i=>({channelName:"embeddings",module:{...t,filePath:i},functionQuery:{className:e.embeddings,methodName:"create",kind:"Sync"}}))]}var Ql=w(()=>{});var Jl,T3,db=w(()=>{$();Ql();Jl=un({name:"groq-sdk",versionRange:">=0.3.0 <2"}),T3=M(Jl)});var Xl,x3,ub=w(()=>{$();Xl=[{channelName:"route",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"route",kind:"Sync"}},{channelName:"ext",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"ext",kind:"Sync"}},{channelName:"start",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"start",kind:"Sync"}},{channelName:"initialize",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"initialize",kind:"Sync"}}],x3=M(Xl)});var Zl,N3,mb=w(()=>{$();Zl=[{channelName:"context",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?context\.js$/},functionQuery:{className:"Context"}},{channelName:"request",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?hono-base\.js$/},astQuery:"PropertyDefinition[key.name='request'] > ArrowFunctionExpression",functionQuery:{kind:"Auto"}}],N3=M(Zl)});function De(t){return{channelName:"module-registration",module:t,astQuery:"Program",transform:jI}}var jI,jt=w(()=>{jI="sentryModuleRegistration"});var ec,L3,gb=w(()=>{$();jt();ec=[De({name:"ioredis",versionRange:">=5.11.0",filePath:"built/Redis.js"}),...["lib/redis.js","built/redis.js","built/redis/index.js"].flatMap(t=>[{channelName:"command",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"connect",kind:"Async"}}]),{channelName:"command",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"connect",kind:"Async"}}],L3=M(ec)});var tc,j3,fb=w(()=>{$();tc=[{channelName:"send_batch",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/producer/messageProducer.js"},functionQuery:{expressionName:"sendBatch",kind:"Async"}},{channelName:"consumer_run",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/consumer/index.js"},functionQuery:{expressionName:"run",kind:"Async"}}],j3=M(tc)});function WI(t,e){return{channelName:"query",module:{name:hb,versionRange:e,filePath:t},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function GI(t,e,i){return{channelName:t,module:{name:hb,versionRange:i,filePath:e},functionQuery:{className:"Client",methodName:t,kind:"Sync"}}}var hb,FI,BI,HI,yb,bb=w(()=>{hb="knex",FI=[{filePath:"lib/execution/runner.js",versionRange:">=0.22.0 <4"},{filePath:"lib/runner.js",versionRange:">=0.10.0 <0.22.0"},{filePath:"src/runner.js",versionRange:">=0.18.0 <0.19.0"}],BI=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],HI=["queryBuilder","schemaBuilder","raw"];yb=[...FI.map(({filePath:t,versionRange:e})=>WI(t,e)),...BI.flatMap(({filePath:t,versionRange:e})=>HI.map(i=>GI(i,t,e)))]});var ic,W3,_b=w(()=>{$();ic=[{channelName:"use",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"use",kind:"Sync"}},{channelName:"callback",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"callback",kind:"Sync"}}],W3=M(ic)});var $I,rc,Xs,vb,VI,zI,nc,V3,z3,wb=w(()=>{$();$I=["dist/language_models/chat_models.cjs","dist/language_models/chat_models.js"].flatMap(t=>{let e={name:"@langchain/core",versionRange:">=0.1.0 <2.0.0",filePath:t};return[{channelName:"chatModelInvoke",module:e,functionQuery:{className:"BaseChatModel",methodName:"invoke",kind:"Async"}},{channelName:"chatModelStream",module:e,functionQuery:{className:"BaseChatModel",methodName:"_streamIterator",kind:"Async"}}]}),rc="embedQuery",Xs="embedDocuments",vb=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[rc,Xs]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[rc,Xs]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[rc,Xs]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Xs]}],VI=vb.flatMap(({name:t,versionRange:e,methods:i})=>["dist/embeddings.cjs","dist/embeddings.js"].flatMap(r=>i.map(n=>({channelName:n,module:{name:t,versionRange:e,filePath:r},functionQuery:{methodName:n,kind:"Async"}})))),zI=["dist/classifier.cjs","dist/classifier.js"].map(t=>({channelName:"typesafeClassifierInvoke",module:{name:"@langchain/typesafe",versionRange:">=0.0.1 <1.0.0",filePath:t},functionQuery:{className:"TypeSafeClassifier",methodName:"invoke",kind:"Async"}})),nc=[...$I,...VI,...zI],V3=vb.flatMap(({name:t,methods:e})=>e.map(i=>`orchestrion:${t}:${i}`)),z3=M(nc)});var Sb,KI,YI,sc,Q3,kb=w(()=>{$();Sb=t=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:t}),KI=["dist/graph/state.cjs","dist/graph/state.js"].map(t=>({channelName:"stateGraphCompile",module:Sb(t),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),YI=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(t=>({channelName:"createReactAgent",module:Sb(t),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),sc=[...KI,...YI],Q3=M(sc)});var ac,Z3,Eb=w(()=>{$();ac=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],Z3=M(ac)});var Tb,Ib=w(()=>{jt();Tb=[De({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var QI,JI,XI,oc,nH,Ab=w(()=>{$();QI=[{channelName:"mastraConstructor",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/(?:[\w.-]+\/)?mastra[\w.-]*\.(?:cjs|mjs|js)$/},functionQuery:{className:"Mastra"}}],JI=["executeWithContext","executeWithContextSync"].map(t=>({channelName:"mastraExecuteWithContext",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/observability\/context-storage\.(?:cjs|mjs|js)$/},functionQuery:{functionName:t,kind:"Auto"}})),XI=[{channelName:"mastraClassifierEvaluate",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/classifier\/index\.(?:cjs|mjs|js)$/},functionQuery:{className:"Classifier",methodName:"evaluate",kind:"Async"}}],oc=[...QI,...JI,...XI],nH=M(oc)});var xb,lc,oH,Ob=w(()=>{$();xb={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},lc=[{channelName:"harnessOpen",module:{...xb,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([t,e])=>({channelName:"codingTool",module:{...xb,filePath:`dist/tools/${t}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],oH=M(lc)});var ZI,eA,cc,pH,Rb=w(()=>{$();ZI=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],eA=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],cc=[...ZI,...eA],pH=M(cc)});var pc,Zs,Nb,dc,mH,Pb=w(()=>{$();pc={name:"@mistralai/mistralai",versionRange:">=2.0.0 <4"},Zs={...pc,filePath:"esm/sdk/chat.js"},Nb={...pc,filePath:"esm/sdk/agents.js"},dc=[{channelName:"chat",module:Zs,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:Zs,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:Zs,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:Zs,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...pc,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:Nb,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:Nb,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],mH=M(dc)});var Ii,uc,hH,Cb=w(()=>{$();Ii={name:"mongodb"},uc=[{channelName:"command",module:{...Ii,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...Ii,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...Ii,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection_pool.js"},functionQuery:{methodName:"checkOut",kind:"Callback"}},...["insert","update","remove"].map(t=>({channelName:`v3_${t}`,module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:t,kind:"Callback"}})),{channelName:"v3_command",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...Ii,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],hH=M(uc)});var Xt,Db,mc,vH,wH,Mb=w(()=>{$();jt();Xt={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},Db=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],mc=[De({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Xt,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Xt,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Xt,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...Db.map(t=>({channelName:`ctx_${t}`,module:{...Xt,filePath:"lib/query.js"},functionQuery:{expressionName:t,kind:"Sync"}}))],vH=M(mc),wH=Db.map(t=>`orchestrion:mongoose:ctx_${t}`)});var gc,TH,Lb=w(()=>{$();jt();gc=[De({name:"mysql2",versionRange:">=3.20.0",filePath:"lib/base/connection.js"}),{channelName:"query",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"execute",kind:"Callback"}},{channelName:"query",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"execute",kind:"Callback"}}],TH=M(gc)});var fc,xH,Ub=w(()=>{$();fc=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],xH=M(fc)});var hc,yc,NH,qb=w(()=>{$();hc={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},yc=[{channelName:"query",module:hc,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:hc,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:hc,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],NH=M(yc)});var jb,Fb=w(()=>{jb=[{channelName:"nestFactoryCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"nest-factory.js"},functionQuery:{className:"NestFactoryStatic",methodName:"create",kind:"Async"}},{channelName:"routerExecutionContextCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"router/router-execution-context.js"},functionQuery:{className:"RouterExecutionContext",methodName:"create",kind:"Sync"}},{channelName:"injectableDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/injectable.decorator.js"},astQuery:'FunctionDeclaration[id.name="Injectable"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"catchDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/catch.decorator.js"},astQuery:'FunctionDeclaration[id.name="Catch"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"cronDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/cron.decorator.js"},functionQuery:{functionName:"Cron",kind:"Sync"}},{channelName:"intervalDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/interval.decorator.js"},functionQuery:{functionName:"Interval",kind:"Sync"}},{channelName:"timeoutDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/timeout.decorator.js"},functionQuery:{functionName:"Timeout",kind:"Sync"}},{channelName:"scheduleExplorerWrap",module:{name:"@nestjs/schedule",versionRange:">=6.0.0",filePath:"dist/schedule.explorer.js"},functionQuery:{className:"ScheduleExplorer",methodName:"wrapFunctionInTryCatchBlocks",kind:"Sync"}},{channelName:"onEventDecorator",module:{name:"@nestjs/event-emitter",versionRange:">=2.0.0",filePath:"dist/decorators/on-event.decorator.js"},functionQuery:{expressionName:"OnEvent",kind:"Sync"}},{channelName:"processorDecorator",module:{name:"@nestjs/bullmq",versionRange:">=10.0.0",filePath:"dist/decorators/processor.decorator.js"},functionQuery:{functionName:"Processor",kind:"Sync"}}]});var Bb,Hb=w(()=>{jt();Bb=[De({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var Ai,bc,UH,Wb=w(()=>{$();Ai={functionName:"createTask",kind:"Sync"},bc=[{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.cjs"},functionQuery:Ai},{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.3.0 <4.6.0",filePath:"dist/node-cron.cjs"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.6.0",filePath:"dist/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/cjs/node-cron.js"},functionQuery:Ai},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/esm/node-cron.js"},functionQuery:Ai},{channelName:"v3_createTask",module:{name:"node-cron",versionRange:">=3.0.0 <4",filePath:"src/node-cron.js"},functionQuery:Ai}],UH=M(bc)});var Gb,_c,FH,$b=w(()=>{$();Gb={channelName:"schedule",astQuery:"AssignmentExpression[left.object.property.name='prototype'][left.property.name='schedule'] > FunctionExpression",functionQuery:{methodName:"schedule",kind:"Sync"}},_c=[{...Gb,module:{name:"node-schedule",versionRange:">=1.3.0 <2",filePath:"lib/schedule.js"}},{...Gb,module:{name:"node-schedule",versionRange:">=2.0.0 <3",filePath:"lib/Job.js"}}],FH=M(_c)});var vc,WH,Vb=w(()=>{$();vc=[...["resources/chat/completions/completions.js","resources/chat/completions/completions.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/responses/responses.js","resources/responses/responses.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Responses",methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(t=>({channelName:"embeddings",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Embeddings",methodName:"create",kind:"Sync"}})),...["resources/conversations/conversations.js","resources/conversations/conversations.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Conversations",methodName:"create",kind:"Sync"}})),...["resources/decisions.js","resources/decisions.mjs"].map(t=>({channelName:"decide",module:{name:"openai",versionRange:">=7.30.0 <8",filePath:t},functionQuery:{className:"Decisions",methodName:"create",kind:"Sync"}}))],WH=M(vc)});var wc,VH,zb=w(()=>{$();wc=[{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"connect",kind:"Auto"}},{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"connect",kind:"Auto"}},{channelName:"connect",module:{name:"pg-pool",versionRange:">=2.0.0 <4",filePath:"index.js"},functionQuery:{className:"Pool",methodName:"connect",kind:"Auto"}}],VH=M(wc)});var tA,Sc,QH,Kb=w(()=>{$();jt();tA=t=>[{channelName:"handle",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/query.js`},functionQuery:{className:"Query",methodName:"handle",kind:"Async"}},{channelName:"connection",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"Connection",kind:"Sync"}},{channelName:"execute",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"execute",kind:"Sync"}},{channelName:"connect",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{methodName:"connect",kind:"Sync"}}],Sc=[De({name:"postgres",versionRange:">=4.0.0",filePath:"src/query.js"}),...["src","cjs/src"].flatMap(tA)],QH=M(Sc)});function Yb(t,e){return{channelName:t,module:{name:iA,versionRange:nA,filePath:rA},functionQuery:{className:"CollectionBase",methodName:t,kind:e}}}var iA,rA,nA,sA,aA,kc,ZH,Qb=w(()=>{$();iA="@prisma/orm-family-sql",rA="dist/orm-client.mjs",nA=">=8.0.0-rc.15 <9",sA=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],aA=["all","createAll","updateAll","deleteAll"];kc=[...sA.map(t=>Yb(t,"Async")),...aA.map(t=>Yb(t,"Sync"))],ZH=M(kc)});var Ec,rW,Jb=w(()=>{$();jt();Ec=[De({name:"@redis/client",versionRange:">=5.12.0",filePath:"dist/lib/client/index.js"}),{channelName:"command",module:{name:"redis",versionRange:">=2.6.0 <4",filePath:"index.js"},functionQuery:{expressionName:"internal_send_command",kind:"Sync"}},{channelName:"executor",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"commandsExecutor",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"multi",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executeMulti",kind:"Async"}},{channelName:"pipeline",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executePipeline",kind:"Async"}},{channelName:"batch",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"multiExecutor",kind:"Async"}}],rW=M(Ec)});var oA,Xb,Zb=w(()=>{oA=t=>[{channelName:"requestHandler",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/server.js`},astQuery:'FunctionExpression[id.name="requestHandler"]',functionQuery:{kind:"Async"}},{channelName:"matchServerRoutes",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/routeMatching.js`},functionQuery:{functionName:"matchServerRoutes",kind:"Sync"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoader",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteAction",kind:"Async"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoaderRR",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteActionRR",kind:"Async"}}],Xb=["dist","dist/esm"].flatMap(oA)});var e_,t_=w(()=>{e_=[{channelName:"createRouter",module:{name:"@remix-run/fetch-router",versionRange:">=0.21.0 <2",filePath:"dist/lib/router.js"},functionQuery:{functionName:"createRouter",kind:"Sync"}},{channelName:"createAssetServer",module:{name:"@remix-run/assets",versionRange:">=0.6.0 <2",filePath:"dist/lib/asset-server.js"},functionQuery:{functionName:"createAssetServer",kind:"Sync"}},{channelName:"createRequestListener",module:{name:"@remix-run/node-fetch-server",versionRange:">=0.14.0 <2",filePath:"dist/lib/request-listener.js"},functionQuery:{functionName:"createRequestListener",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/ui",versionRange:">=0.8.0 <1",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/component",versionRange:">=1.0.0 <2",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}}]});var lA,cA,pA,Tc,lW,i_=w(()=>{$();lA="tedious",cA="lib/connection.js",pA=">=1.11.0 <21",Tc=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"].map(t=>({channelName:t,module:{name:lA,versionRange:pA,filePath:cA},functionQuery:{className:"Connection",methodName:t,kind:"Sync"}})),lW=M(Tc)});var Ic,uW,r_=w(()=>{$();Ql();Ic=[...un({name:"together-ai",versionRange:">=0.6.0 <1"}),...un({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],uW=M(Ic)});var Ac,fW,n_=w(()=>{$();Ac=["dist/index.mjs","dist/index.cjs"].map(t=>({channelName:"system-one",module:{name:"@typesafe-ai/sdk",versionRange:">=0.5.0 <1",filePath:t},functionQuery:{className:"TypeSafeClient",methodName:"systemOne",kind:"Sync"}})),fW=M(Ac)});function Zt(t,e,i,r){return["dist/index.js","dist/index.mjs"].map(n=>({channelName:e,module:{name:"ai",versionRange:t,filePath:n},functionQuery:{functionName:i,kind:r}}))}var xc,_W,s_=w(()=>{$();jt();xc=[...["dist/index.js","dist/index.mjs"].map(t=>De({name:"ai",versionRange:">=7.0.0",filePath:t})),...Zt(">=4.0.0 <7.0.0","generateText","generateText","Async"),...Zt(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...Zt(">=4.0.0 <7.0.0","streamObject","streamObject","Sync"),...Zt(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...Zt(">=4.0.0 <7.0.0","embed","embed","Async"),...Zt(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...Zt(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...Zt(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];_W=M(xc)});function dA(t=[]){return[...bl([...a_,...t].map(e=>e.module.name)),"@remix-run/node"]}var a_,mn,yG,o_=w(()=>{eb();tb();ib();rb();sb();ab();ob();lb();cb();pb();db();ub();mb();gb();fb();bb();_b();wb();kb();Eb();Ib();Ab();Zy();Ob();Rb();Pb();Cb();Mb();Lb();Ub();qb();Fb();Hb();Wb();$b();Vb();zb();Kb();Qb();Jb();Zb();t_();i_();r_();n_();s_();wt();a_=[...Hl,...Wl,...Bl,...Gl,...nb,...$l,...Vl,...zl,...Kl,...Yl,...Jl,...Xl,...Zl,...ec,...tc,...yb,...ic,...nc,...sc,...ac,...Tb,...oc,...cc,...dc,...uc,...mc,...gc,...fc,...yc,...jb,...Bb,...bc,..._c,...vc,...wc,...Fl,...lc,...Sc,...kc,...Ec,...Xb,...e_,...Tc,...Ic,...Ac,...xc],mn=a_.filter(t=>!t.transform);yG=dA()});var l_=w(()=>{Jy()});import{posix as uA,sep as mA}from"node:path";function c_(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function p_(t=process.argv[1]?El(process.argv[1]):process.cwd(),e=mA==="\\"){let i=e?c_(t):t;return r=>{if(!r)return;let n=e?c_(r):r,{dir:s,base:a,ext:o}=uA.parse(n);(o===".js"||o===".mjs"||o===".cjs")&&(a=a.slice(0,o.length*-1));let l=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${l}`;if(s.startsWith(i)){let p=s.slice(i.length+1).replace(/\//g,".");return p?`${p}:${l}`:l}return l}}var d_=w(()=>{wt()});var Oc,u_=w(()=>{d_();wt();Al();Oc=wo(Il(p_()))});import{AsyncLocalStorage as gA}from"node:async_hooks";function f_(t){return t.getValue(Mc)}function hA(t,e){return t.setValue(Mc,e)}function yA(t,e){t.refs[g_]=Qi(e)}function Lc(t){return wi(t.refs[g_])}function bA(t,e){let i=t?Jt.setSpan(Ce.active(),t):Jt.deleteSpan(Ce.active());return Ce.with(i,()=>{let r=Ct();return ws(r,t??void 0),e(r)})}function _A(t){let e=t?vA(t):Jt.getActiveSpan();return e&&Ti(e.spanContext())?e:void 0}function vA(t){let e=Lc(t);return e?Jt.getSpan(e):void 0}function wA(t){let e=f_(t),i=e?.scope||Ct(),r=e?.isolationScope||_i(),n=t.getValue(Pc)===!0,s=t.getValue(Cc),a=t.getValue(Dc),o=s||i.clone(),l=hA(t,{scope:o,isolationScope:a||(n?r.clone():r)}).deleteValue(Pc).deleteValue(Cc).deleteValue(Dc);return(!s||!Lc(s))&&yA(o,l),l}function EA(t){if(typeof t!="object"||!t)return!1;let e=t;return typeof e.on=="function"&&typeof e.emit=="function"}function Rc(t,e){let i=t[e];return typeof i=="function"?i:void 0}function Nc(t,e,i){try{t[e]=i}catch{}}function h_(){let t=dt(_e()).getTracingChannelBinding?.()?.asyncLocalStorage??new gA;function e(){let p=f_(Ce.active());return p||{scope:yi(),isolationScope:bi()}}function i(p){let d=Ce.active();return Ce.with(d,()=>p(a()))}function r(p,d){let m=Lc(p)||Ce.active();return Ce.with(m.setValue(Cc,p),()=>d(p))}function n(p){let d=Ce.active();return Ce.with(d.setValue(Pc,!0),()=>{let m=a();return Jr(m.getPropagationContext())||m.setPropagationContext({traceId:hi(),sampleRand:Xe()}),p(o())})}function s(p,d){let m=Ce.active();return Ce.with(m.setValue(Dc,p),()=>d(o()))}function a(){return e().scope}function o(){return e().isolationScope}function l(){return{asyncLocalStorage:t}}Vr({withScope:i,withSetScope:r,withSetIsolationScope:s,withIsolationScope:n,getCurrentScope:a,getIsolationScope:o,getActiveSpan:_A,withActiveSpan:bA,getTracingChannelBinding:l});let c=new kA(t);return Ce.setGlobalContextManager(c),c.getAsyncLocalStorageLookup()}function TA(t){let{traceFlags:e,traceState:i}=t,r=i?i.get(fA)==="1":!1;if(e===Nl.SAMPLED)return!0;if(r)return!1;let n=i?i.get(m_):void 0,s=n?Yr(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function y_(t){t.on("prepareSpanScope",e=>{let{scope:i,parentSpan:r}=e;if(!r?.spanContext().isRemote)return;let{spanId:n,traceId:s,traceState:a}=r.spanContext(),o=Mt(r),l=typeof o.sample_rand=="string"?Number(o.sample_rand):void 0,c=!!a?.get(m_),p=i.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:TA(r.spanContext()),dsc:c?o:void 0,sampleRand:typeof l=="number"&&!Number.isNaN(l)?l:Xe()}),ws(p,void 0),e.scope=p,e.parentSpan=void 0})}var m_,fA,Mc,Pc,Cc,Dc,g_,WG,SA,kA,b_=w(()=>{wt();Ys();Ys();m_="sentry.dsc",fA="sentry.sampled_not_recording",Mc=qt("sentry_scopes"),Pc=qt("sentry_fork_isolation_scope"),Cc=qt("sentry_fork_set_scope"),Dc=qt("sentry_fork_set_isolation_scope"),g_="context";WG=qt("OpenTelemetry SDK Context Key SUPPRESS_TRACING");SA=["addListener","on","once","prependListener","prependOnceListener"],kA=class{constructor(t){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=t}active(){return this._asyncLocalStorage.getStore()??pn}with(t,e,i,...r){let n=wA(t),s=i==null?e:e.bind(i);return this._asyncLocalStorage.run(n,s,...r)}enable(){return this}disable(){try{this._asyncLocalStorage.disable()}catch{}return this}bind(t,e){return EA(e)?this._bindEventEmitter(t,e):typeof e=="function"?this._bindFunction(t,e):e}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:Mc}}_bindFunction(t,e){let i=this.with.bind(this),r=function(...n){return i(t,()=>e.apply(this,n))};return Object.defineProperty(r,"length",{enumerable:!1,configurable:!0,writable:!1,value:e.length}),r}_bindEventEmitter(t,e){if(this._getPatchMap(e)!==void 0||this._createPatchMap(e)===void 0)return e;for(let r of SA){let n=Rc(e,r);n&&Nc(e,r,this._patchAddListener(e,n,t))}for(let r of["removeListener","off"]){let n=Rc(e,r);n&&Nc(e,r,this._patchRemoveListener(e,n))}let i=Rc(e,"removeAllListeners");return i&&Nc(e,"removeAllListeners",this._patchRemoveAllListeners(e,i)),e}_patchRemoveListener(t,e){let i=this;return function(r,n){let s=i._getPatchMap(t)?.[r];if(s===void 0)return e.call(this,r,n);let a=s.get(n);return e.call(this,r,a||n)}}_patchRemoveAllListeners(t,e){let i=this;return function(r){let n=i._getPatchMap(t);return n!==void 0&&(arguments.length===0?i._createPatchMap(t):r!==void 0&&n[r]!==void 0&&delete n[r]),e.apply(this,arguments)}}_patchAddListener(t,e,i){let r=this;return function(n,s){if(r._wrapped)return e.call(this,n,s);let a=r._getPatchMap(t)??r._createPatchMap(t);if(a===void 0)return e.call(this,n,s);let o=a[n];o===void 0&&(o=new WeakMap,a[n]=o);let l=r.bind(i,s);o.set(s,l),r._wrapped=!0;try{return e.call(this,n,l)}finally{r._wrapped=!1}}}_createPatchMap(t){let e=Object.create(null);try{t[this._kOtListeners]=e}catch{return}return this._getPatchMap(t)===e?e:void 0}_getPatchMap(t){return t[this._kOtListeners]}}});var IA,gn,AA,xA,OA,Uc,je,ue,__,v_,cr,w_,fe=w(()=>{IA=Object.create,gn=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,xA=Object.getOwnPropertyNames,OA=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty,je=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}},ue=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e,e.exports),t=null),e.exports),__=(t,e)=>{let i=Object.setPrototypeOf({},null);for(var r in t)gn(i,r,{get:t[r],enumerable:!0});return e&1||gn(i,Symbol.toStringTag,{value:"Module"}),e&2?i:Object.preventExtensions(i)},v_=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var n=xA(e),s=0,a=n.length,o;s<a;s++)o=n[s],!Uc.call(t,o)&&o!==i&&gn(t,o,{get:(l=>e[l]).bind(null,o),enumerable:!(r=AA(e,o))||r.enumerable});return t},cr=(t,e,i)=>(i=t!=null?IA(OA(t)):{},v_(e||!t||!t.__esModule||!Uc.call(t,"default")?gn(i,"default",{value:t,enumerable:!0}):i,t)),w_=t=>Uc.call(t,"module.exports")?t["module.exports"]:v_(gn({},"__esModule",{value:!0}),t)});function ea(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}var RA,qc=w(()=>{fe();RA=je((()=>{}));RA()});function Ze(t,e,i){ea(t,e),e.set(t,i)}var fn,jc=w(()=>{fe();qc();fn=je((()=>{}));fn()});function ft(t,e,i){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var NA,ta=w(()=>{fe();NA=je((()=>{}));NA()});function ht(t,e,i){return t.set(ft(t,e),i),i}var hn,Fc=w(()=>{fe();ta();hn=je((()=>{}));hn()});function he(t,e){return t.get(ft(t,e))}var yn,Bc=w(()=>{fe();ta();yn=je((()=>{}));yn()});var Hc,c5,S_=w(()=>{fe();Hc=ue(((t,e)=>{e.exports=i;function i(m,g){let[h]=p(m,"");for(let f of s(g))if(r(f,h))return!0;return!1}function r(m,g){for(let[h,f]of m)if(!d(g,f,h))return!1;return!0}function n(m){return m==="latest"&&(m=">=0"),m.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function s(m){let g=[],h=[],f=m.trim().split(/\s+/);for(let b=0;b<f.length;b++){let S=f[b];if(S==="-")continue;if(S==="||"){g.push(h),h=[];continue}if(/^[<>=~v^]+$/.test(S)&&b+1<f.length){f[b+1]=S+f[b+1];continue}let E=n(S),A=E[1]||"=";A.endsWith("v")&&(A=A.slice(0,-1));let[C,N]=p(E[2],A);if(b+2<f.length&&f[b+1]==="-"){let R=n(f[b+2]);f[b+2]="<="+(R[2].indexOf("-")===-1?R[2]+".*.*":R[2]),N=">="}if(N[0]==="~"){let R=E[2].split("-")[0].split(".").length;h.push([">=",C]),h.push(["<",R===1?a(C,0):a(C,1)])}else if(N[0]==="^"){let R=C[0]!==0?0:C[1]!==0?1:2;h.push([">=",C]),h.push(["<",R===0?a(C,0):R===1?a(C,1):a(C,2)])}else h.push([N.replace("~","").replace("^",""),C])}return h.length&&g.push(h),g}function a(m,g){let h=m.slice(0);if(m[g]===-1)return h;for(h[g++]++;g<3;g++)h[g]=0;return h}function o(m){return m==="x"||m==="X"||m==="*"||m==="latest"?-1:Number(m)}function l(m){return/^\d+$/.test(m)?Number(m):m}function c(m,g,h){return h===-1?m!=="<":m==="="?g===h:m===">"?g>h:m===">="?g>=h:m==="<"?g<h:m==="<="?g<=h:!1}function p(m,g){m=m.split("+")[0];let[h,f]=m.split("-"),b=h.split(".").map(o).slice(0,3),S=Math.max(b.length-1,0);return g===">"?(g=">=",b.push(0,0,0),b[S]++):g===""?b.push(0,0,0):b.push(-1,-1,-1),f?[b.slice(0,3).concat(f.split(".").map(l)),g]:[b.slice(0,3),g]}function d(m,g,h){if(!c("=",m[0],g[0]))return c(h,m[0],g[0]);if(!c("=",m[1],g[1]))return c(h,m[1],g[1]);if(!c("=",m[2],g[2])||m.length===3&&g.length===3)return c(h,m[2],g[2]);if(h[0]==="<"&&(g.length===3||m.length===3))return!1;if(h[0]===">"){if(m.length===3)return!0;if(g.length===3)return!1}for(let f=3;f<Math.max(m.length,g.length);f++)if(c(h,m[f]||"",g[f]||""))return!0;return!1}})),c5=Hc()});function k_(t,e){ea(t,e),e.add(t)}var Wc,E_=w(()=>{fe();qc();Wc=je((()=>{}));Wc()});var ia,Gc=w(()=>{ia={}});var ra,$c=w(()=>{ra={}});var T_,I_=w(()=>{T_={}});var Vc,v5,A_=w(()=>{fe();Gc();$c();Vc=ue(((t,e)=>{let i=ia.v??{},{parse:r}=ra.v??{},n=I=>I.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",s=/[^\w]/g,a=I=>`tr_ch_apm$${I.replace(s,"_")}`;e.exports={tracingChannelImport({dcModule:I,moduleType:x},L){if(L.body.some(n))return;let U={module:x==="esm"},k=L.body.findIndex(F=>F.directive==="use strict"),v=x==="esm"?`import tr_ch_apm_dc from "${I}"`:`const tr_ch_apm_dc = require("${I}")`;L.body.splice(k+1,0,r(v,U).body[0],r("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",U).body[0],r(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
316
316
  || ch.end.hasSubscribers
317
317
  || ch.asyncStart.hasSubscribers
318
318
  || ch.asyncEnd.hasSubscribers
319
- || ch.error.hasSubscribers`,U).body[0])},tracingChannelDeclaration(I,x){let{channelName:L,module:{name:U}}=I,k=a(L);if(x.body.some(W=>W.declarations?.[0]?.id?.name===k))return;I.transforms.tracingChannelImport(I,x);let v=x.body.findIndex(n),F=`
319
+ || ch.error.hasSubscribers`,U).body[0])},tracingChannelDeclaration(I,x){let{channelName:L,module:{name:U}}=I,k=a(L);if(x.body.some(G=>G.declarations?.[0]?.id?.name===k))return;I.transforms.tracingChannelImport(I,x);let v=x.body.findIndex(n),F=`
320
320
  const ${k} = tr_ch_apm_tracingChannel("orchestrion:${U}:${L}")
321
- `;x.body.splice(v+1,0,r(F).body[0])},traceCallback:l,tracePromise:l,traceSync:l,traceAuto:l};function o(I){return[...(I||[]).filter(x=>x.type!=="RestElement"&&x.type!=="AssignmentPattern").map((x,L)=>({type:"Identifier",name:`__apm$arg${L}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function l(I,x,L,U){let k=U[U.length-1];x.type==="ClassDeclaration"||x.type==="ClassExpression"?h(I,x,k):g(I,x,k)}function c(I,x){if(I.type!=="ReturnStatement")return!1;let L=I.argument?.type==="CallExpression"?I.argument.callee:null;return L?.type==="MemberExpression"&&L.property?.name==="runStores"&&L.object?.type==="MemberExpression"&&L.object.property?.name==="start"&&L.object.object?.type==="Identifier"&&L.object.object.name===x}function p(I){let x=(k,v)=>k?.find(F=>F.type==="VariableDeclaration"&&F.declarations.some(W=>W.id?.name===v))?.declarations.find(F=>F.id?.name===v)?.init??null,L=x(x(I,"__apm$traced")?.body?.body,"__apm$wrapped"),U=L?.type;return U==="FunctionExpression"||U==="ArrowFunctionExpression"||U==="FunctionDeclaration"?L:null}function d(I,x){let L=new Set,U=I;for(;U&&!L.has(U);){L.add(U);let k=U.body?.body;if(!Array.isArray(k))return!1;if(k.some(v=>c(v,x)))return!0;U=p(k)}return!1}function m(I,x){let L=I?.value?.body?.body;return Array.isArray(L)?L.some(U=>U.type==="VariableDeclaration"&&U.declarations.some(k=>k.id?.name===x)):!1}function g(I,x,L){if(d(x,a(I.channelName)))return;I.transforms.tracingChannelDeclaration(I,L);let{functionQuery:{methodName:U,privateMethodName:k,functionName:v,expressionName:F,propertyName:W}}=I,K=U==="constructor"||!U&&!k&&!v&&!F&&!W,J=K?"ArrowFunctionExpression":x.type,O=x.params,oe=`${a(I.channelName)}$self`;I.selfBinding=K&&S(x,oe)?oe:null,x.body=f(I,{type:J,params:O,body:x.body,async:x.async,expression:!1,generator:x.generator},L),x.params=o(O),x.generator=!1,x.async=!1,J!=="ArrowFunctionExpression"&&E(I,x)}function h(I,x,L){let{functionQuery:U,operator:k,channelName:v}=I,{methodName:F}=U;if(!F)return;let W=x.body;if(W.body.some(({key:se})=>se?.name===F))return;let K=W.body.find(({kind:se})=>se==="constructor"),J=`${a(v)}$${F}`;if(K&&m(K,J))return;I.transforms.tracingChannelDeclaration(I,L),K||(K=r(x.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],W.body.unshift(K));let O=r(`
321
+ `;x.body.splice(v+1,0,r(F).body[0])},traceCallback:l,tracePromise:l,traceSync:l,traceAuto:l};function o(I){return[...(I||[]).filter(x=>x.type!=="RestElement"&&x.type!=="AssignmentPattern").map((x,L)=>({type:"Identifier",name:`__apm$arg${L}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function l(I,x,L,U){let k=U[U.length-1];x.type==="ClassDeclaration"||x.type==="ClassExpression"?h(I,x,k):g(I,x,k)}function c(I,x){if(I.type!=="ReturnStatement")return!1;let L=I.argument?.type==="CallExpression"?I.argument.callee:null;return L?.type==="MemberExpression"&&L.property?.name==="runStores"&&L.object?.type==="MemberExpression"&&L.object.property?.name==="start"&&L.object.object?.type==="Identifier"&&L.object.object.name===x}function p(I){let x=(k,v)=>k?.find(F=>F.type==="VariableDeclaration"&&F.declarations.some(G=>G.id?.name===v))?.declarations.find(F=>F.id?.name===v)?.init??null,L=x(x(I,"__apm$traced")?.body?.body,"__apm$wrapped"),U=L?.type;return U==="FunctionExpression"||U==="ArrowFunctionExpression"||U==="FunctionDeclaration"?L:null}function d(I,x){let L=new Set,U=I;for(;U&&!L.has(U);){L.add(U);let k=U.body?.body;if(!Array.isArray(k))return!1;if(k.some(v=>c(v,x)))return!0;U=p(k)}return!1}function m(I,x){let L=I?.value?.body?.body;return Array.isArray(L)?L.some(U=>U.type==="VariableDeclaration"&&U.declarations.some(k=>k.id?.name===x)):!1}function g(I,x,L){if(d(x,a(I.channelName)))return;I.transforms.tracingChannelDeclaration(I,L);let{functionQuery:{methodName:U,privateMethodName:k,functionName:v,expressionName:F,propertyName:G}}=I,K=U==="constructor"||!U&&!k&&!v&&!F&&!G,J=K?"ArrowFunctionExpression":x.type,O=x.params,oe=`${a(I.channelName)}$self`;I.selfBinding=K&&S(x,oe)?oe:null,x.body=f(I,{type:J,params:O,body:x.body,async:x.async,expression:!1,generator:x.generator},L),x.params=o(O),x.generator=!1,x.async=!1,J!=="ArrowFunctionExpression"&&E(I,x)}function h(I,x,L){let{functionQuery:U,operator:k,channelName:v}=I,{methodName:F}=U;if(!F)return;let G=x.body;if(G.body.some(({key:se})=>se?.name===F))return;let K=G.body.find(({kind:se})=>se==="constructor"),J=`${a(v)}$${F}`;if(K&&m(K,J))return;I.transforms.tracingChannelDeclaration(I,L),K||(K=r(x.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],G.body.unshift(K));let O=r(`
322
322
  const ${J} = this["${F}"]
323
323
  this["${F}"] = function () {}
324
324
  if (typeof ${J} === 'function') {
@@ -327,7 +327,7 @@ Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t)
327
327
  configurable: true
328
328
  })
329
329
  }
330
- `).body,oe=O[1].expression.right;oe.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],oe.async=k==="tracePromise",I.selfBinding=null,oe.body=f(I,{type:"Identifier",name:J},L),E(I,oe),K.value.body.body.push(...O)}function f(I,x,L){let{operator:U,moduleVersion:k,selfBinding:v}=I,{returnKind:F}=I.functionQuery,W=F?P(I,F,L):"",K;U==="traceCallback"&&(K=C(I,x,W)),U==="tracePromise"&&(K=N(I,x,W)),U==="traceSync"&&(K=R(I,x,W)),U==="traceAuto"&&(K=A(I,x,W));let J=(x.params||[]).filter(ce=>ce.type!=="RestElement"&&ce.type!=="AssignmentPattern").map((ce,It)=>`__apm$arg${It}`).concat("...__apm$args").join(", "),O=K.body[0].body,oe=v?`let ${v};`:"",se=r(oe+(x.type==="ArrowFunctionExpression"?`
330
+ `).body,oe=O[1].expression.right;oe.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],oe.async=k==="tracePromise",I.selfBinding=null,oe.body=f(I,{type:"Identifier",name:J},L),E(I,oe),K.value.body.body.push(...O)}function f(I,x,L){let{operator:U,moduleVersion:k,selfBinding:v}=I,{returnKind:F}=I.functionQuery,G=F?P(I,F,L):"",K;U==="traceCallback"&&(K=C(I,x,G)),U==="tracePromise"&&(K=N(I,x,G)),U==="traceSync"&&(K=R(I,x,G)),U==="traceAuto"&&(K=A(I,x,G));let J=(x.params||[]).filter(pe=>pe.type!=="RestElement"&&pe.type!=="AssignmentPattern").map((pe,It)=>`__apm$arg${It}`).concat("...__apm$args").join(", "),O=K.body[0].body,oe=v?`let ${v};`:"",se=r(oe+(x.type==="ArrowFunctionExpression"?`
331
331
  const __apm$arguments = [${J}];
332
332
  const __apm$ctx = {
333
333
  arguments: __apm$arguments,
@@ -348,13 +348,13 @@ Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t)
348
348
  const __apm$wrapped = () => {};
349
349
  return __apm$wrapped.apply(this, __apm$arguments);
350
350
  };
351
- `)).body;return O.body.unshift(...se),i.query(O,"[id.name=__apm$wrapped]")[0].init=x,O}let b=({selfBinding:I})=>I||"this";function S(I,x){let L=!1,U=(k,v)=>{let F=k[v];if(!(F===null||typeof F!="object")){if(Array.isArray(F)){for(let W=0;W<F.length;W++)U(F,W);return}if(typeof F.type=="string"&&!(F.type==="ClassBody"||F.type==="FunctionExpression"||F.type==="FunctionDeclaration")){if(F.type==="CallExpression"&&F.callee.type==="Super"){let W=r(`(0, ${x} = this)`).body[0].expression;W.expressions[0]=F,k[v]=W,L=!0;return}for(let W of Object.keys(F))U(F,W)}}};return U(I,"body"),L}function E(I,x){let L=new Set;i.traverse(x.body,i.parse("[object.type=Super]"),(U,k)=>{let{name:v}=U.property,F;if(k.callee){let{expression:W}=r(`__apm$super['${v}'].call(this)`).body[0];k.callee=F=W.callee,k.arguments.unshift(...W.arguments)}else k.expression=F=r(`__apm$super['${v}']`).body[0];F.computed=k.callee.computed,F.optional=k.callee.optional,L.add(v)});for(let U of L){let k=r(`
351
+ `)).body;return O.body.unshift(...se),i.query(O,"[id.name=__apm$wrapped]")[0].init=x,O}let b=({selfBinding:I})=>I||"this";function S(I,x){let L=!1,U=(k,v)=>{let F=k[v];if(!(F===null||typeof F!="object")){if(Array.isArray(F)){for(let G=0;G<F.length;G++)U(F,G);return}if(typeof F.type=="string"&&!(F.type==="ClassBody"||F.type==="FunctionExpression"||F.type==="FunctionDeclaration")){if(F.type==="CallExpression"&&F.callee.type==="Super"){let G=r(`(0, ${x} = this)`).body[0].expression;G.expressions[0]=F,k[v]=G,L=!0;return}for(let G of Object.keys(F))U(F,G)}}};return U(I,"body"),L}function E(I,x){let L=new Set;i.traverse(x.body,i.parse("[object.type=Super]"),(U,k)=>{let{name:v}=U.property,F;if(k.callee){let{expression:G}=r(`__apm$super['${v}'].call(this)`).body[0];k.callee=F=G.callee,k.arguments.unshift(...G.arguments)}else k.expression=F=r(`__apm$super['${v}']`).body[0];F.computed=k.callee.computed,F.optional=k.callee.optional,L.add(v)});for(let U of L){let k=r(`
352
352
  class Wrapper {
353
353
  wrapper () {
354
354
  __apm$super['${U}'] = super['${U}']
355
355
  }
356
356
  }
357
- `).body[0].body.body[0].value.body.body[0];x.body.body.unshift(k)}L.size>0&&x.body.body.unshift(r("const __apm$super = {}").body[0])}function A(I,x,L=""){let U=C(I,x,L),k=N(I,x,L),[v,F,W,K,J,O]=U.body[0].body.body,oe={type:"IfStatement",test:K.test,consequent:{type:"BlockStatement",body:k.body[0].body.body},alternate:null};return U.body[0].body.body=[v,oe,F,W,J,O],U}function C(I,x,L=""){let{channelName:U,functionQuery:{callbackIndex:k=-1}}=I,v=a(U);return r(`
357
+ `).body[0].body.body[0].value.body.body[0];x.body.body.unshift(k)}L.size>0&&x.body.body.unshift(r("const __apm$super = {}").body[0])}function A(I,x,L=""){let U=C(I,x,L),k=N(I,x,L),[v,F,G,K,J,O]=U.body[0].body.body,oe={type:"IfStatement",test:K.test,consequent:{type:"BlockStatement",body:k.body[0].body.body},alternate:null};return U.body[0].body.body=[v,oe,F,G,J,O],U}function C(I,x,L=""){let{channelName:U,functionQuery:{callbackIndex:k=-1}}=I,v=a(U);return r(`
358
358
  function wrapper () {
359
359
  const __apm$cb = Array.prototype.at.call(__apm$arguments, ${k});
360
360
 
@@ -478,7 +478,7 @@ Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t)
478
478
  return __apm$ctx.result;
479
479
  });
480
480
  }
481
- `)}function G(I,x){let{channelName:L,module:{name:U}}=I,k=a(L+":next");if(x.body.some(K=>K.declarations?.[0]?.id?.name===k))return;let v=a(L),F=x.body.findIndex(K=>K.declarations?.[0]?.id?.name===v),W=`const ${k} = tr_ch_apm_tracingChannel("orchestrion:${U}:${L}:next")`;x.body.splice(F+1,0,r(W).body[0])}function P(I,x,L){let{channelName:U}=I,k=x==="Iterator"?"traceSync":"tracePromise",v=a(U+":next");return G(I,L),`
481
+ `)}function W(I,x){let{channelName:L,module:{name:U}}=I,k=a(L+":next");if(x.body.some(K=>K.declarations?.[0]?.id?.name===k))return;let v=a(L),F=x.body.findIndex(K=>K.declarations?.[0]?.id?.name===v),G=`const ${k} = tr_ch_apm_tracingChannel("orchestrion:${U}:${L}:next")`;x.body.splice(F+1,0,r(G).body[0])}function P(I,x,L){let{channelName:U}=I,k=x==="Iterator"?"traceSync":"tracePromise",v=a(U+":next");return W(I,L),`
482
482
  const __apm$iter = __apm$ctx.result;
483
483
  if (__apm$iter != null && typeof __apm$iter.next === 'function') {
484
484
  const __apm$patchIter = function (method) {
@@ -496,64 +496,61 @@ Reason: ${b}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t)
496
496
  __apm$patchIter('throw');
497
497
  __apm$patchIter('return');
498
498
  }
499
- `}})),yW=$c()});var Vc,I_=w(()=>{Vc={}});var zc,NW,A_=w(()=>{ge();S_();qc();jc();Fc();ta();Gc();Wc();E_();T_();I_();zc=de(((t,e)=>{Hc(),fn(),hn(),yn();let i=ia.v??{},{parse:r}=ra.v??{},{generate:n}=k_.v??{},s=$c(),a,o;var l=new WeakMap,c=new WeakMap,p=new WeakMap,d=new WeakMap,m=new WeakMap,g=new WeakMap,h=new WeakSet,f=class{constructor(N,R,G,P,I,x={}){w_(this,h),Ze(this,l,null),Ze(this,c,null),Ze(this,p,null),Ze(this,d,[]),Ze(this,m,null),Ze(this,g,{}),ht(l,this,N),ht(c,this,R),ht(p,this,G),ht(d,this,P),ht(m,this,I),ht(g,this,x)}free(){}get moduleName(){return he(l,this)}get filePath(){return he(p,this)}transform(N,R,G,P){let I=P?.sourceFile||`${he(l,this)}/${he(p,this)}`;if(Buffer.isBuffer(N)&&(N=N.toString()),!N)return{code:N};let x,L={},U=0,k={...s,...he(g,this),defaults:{...s}};for(let v of he(d,this)){let{astQuery:F,functionQuery:W={}}=v;if(!x){let oe={loc:!0,ranges:!0,raw:!0,module:R==="esm"};try{x=r(N,oe)}catch{x=r(N,{...oe,module:!oe.module})}R==="esm"&&(L=ft(h,this,E).call(this,x))}let K=ft(h,this,A).call(this,W,L),J=F||ft(h,this,C).call(this,K),O={...v,dcModule:he(m,this),moduleType:R,moduleVersion:he(c,this),functionQuery:K,transforms:k};O.operator=ft(h,this,S).call(this,O),i.traverse(x,i.parse(J),(...oe)=>{U++,ft(h,this,b).call(this,O,...oe)})}if(U===0&&he(d,this).length>0){let v=he(d,this).map(({astQuery:F,functionQuery:W={}})=>{if(F)return F;let K=ft(h,this,A).call(this,W,L),O=(ce=>ce.methodName||ce.privateMethodName||ce.functionName||ce.expressionName||"constructor")(W),oe=W.className||W.functionName||W.expressionName,se=K.className||K.functionName||K.expressionName;return oe&&oe!==se?`${oe} (local name: ${se})`:O});throw new Error(`Failed to find injection points for: ${JSON.stringify(v)}`)}if(x){a??(a=(Vc.v??{}).SourceMapConsumer),o??(o=(Vc.v??{}).SourceMapGenerator);let v=new o({file:I});v.setSourceContent(I,N);let F=n(x,{sourceMap:v});return G&&v.applySourceMap(new a(G),I),{code:F,map:v.toString()}}return{code:N}}};function b(N,...R){let G=typeof N.transform=="function"?N.transform:N.transforms[N.operator],{index:P=0}=N.functionQuery,[I]=R,x=I.init?.type||I.type;x!=="ClassDeclaration"&&x!=="ClassExpression"&&(I.type==="VariableDeclarator"||(N.functionIndex=++N.functionIndex||0,P!==null&&P!==N.functionIndex))||G(N,...R)}function S({transform:N,functionQuery:{kind:R}}){if(typeof N=="string")return N;switch(R){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}}function E(N){let R={};for(let G of N.body)if(G.type==="ExportNamedDeclaration"&&!G.source){for(let P of G.specifiers)if(P.exported&&P.local){let I=P.exported.name??P.exported.value,x=P.local.name??P.local.value;I&&x&&(R[I]=x)}}return R}function A(N,R){if(!N.isExportAlias)return N;let{functionName:G,expressionName:P,className:I}=N;return G&&R[G]?{...N,functionName:R[G]}:P&&R[P]?{...N,expressionName:R[P]}:I&&R[I]?{...N,className:R[I]}:N}function C(N){let{functionName:R,expressionName:G,className:P,objectName:I,propertyName:x}=N,L=N.privateMethodName?"PrivateIdentifier":"Identifier",U=[],k=N.methodName||N.privateMethodName;if(P?(k??(k="constructor"),U.push(`[id.name="${P}"]`,`[id.name="${P}"] > ClassExpression`,`[id.name="${P}"] > ClassBody > [key.name="${k}"][key.type=${L}] > [async]`,`[id.name="${P}"] > ClassExpression > ClassBody > [key.name="${k}"][key.type=${L}] > [async]`)):k&&U.push(`ClassBody > [key.name="${k}"][key.type=${L}] > [async]`,`Property[key.name="${k}"][key.type=${L}] > [async]`),R?U.push(`FunctionDeclaration[id.name="${R}"][async]`):G&&U.push(`FunctionExpression[id.name="${G}"][async]`,`ArrowFunctionExpression[id.name="${G}"][async]`,`VariableDeclarator[id.name="${G}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > ArrowFunctionExpression[async]`),I||x){if(!I||!x)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${I}, propertyName=${x})`);let v=I==="this"?"left.object.type=ThisExpression":`left.object.name="${I}"`;U.push(`AssignmentExpression[${v}][left.property.name="${x}"] > [async]`)}return U.join(", ")}e.exports={Transformer:f}})),NW=zc()});var Kc,FW,x_=w(()=>{ge();qc();jc();Fc();v_();A_();Kc=de(((t,e)=>{fn(),hn(),yn();let i=Bc(),{Transformer:r}=zc();var n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=class{constructor(c,p){Ze(this,n,[]),Ze(this,s,null),Ze(this,a,{}),Ze(this,o,{}),ht(n,this,c),ht(s,this,p||"diagnostics_channel")}free(){ht(a,this,{})}addTransform(c,p){he(o,this)[c]=p}getTransformer(c,p,d){d=d.replace(/\\/g,"/");let m=`${c}/${d}@${p}`;if(he(a,this)[m])return he(a,this)[m];let g=he(n,this).filter(({module:h})=>h.name===c&&(typeof h.filePath=="string"?h.filePath===d:h.filePath.test(d))&&i(p,h.versionRange));if(g.length!==0)return he(a,this)[m]=new r(c,p,d,g,he(s,this),he(o,this)),he(a,this)[m]}};e.exports={InstrumentationMatcher:l}})),FW=Kc()});var Yc,$W,O_=w(()=>{ge();x_();Yc=de(((t,e)=>{let{InstrumentationMatcher:i}=Kc();function r(n,s){return new i(n,s)}e.exports={create:r}})),$W=Yc()});var bn,YW,Qc=w(()=>{ge();O_();bn=de(((t,e)=>{e.exports=Yc()})),YW=bn()});import OA from"node:path";var _n,ZW,Jc=w(()=>{ge();_n=de(((t,e)=>{var i=OA.sep;e.exports=function(r){var n=r.split(i),s=n.lastIndexOf("node_modules");if(s!==-1&&n[s+1]){for(var a=n[s+1][0]==="@",o=a?n[s+1]+"/"+n[s+2]:n[s+1],l=a?3:2,c="",p=s+l-1,d=0;d<=p;d++)d===p?c+=n[d]:c+=n[d]+i;for(var m="",g=n.length-1,h=s+l;h<=g;h++)h===g?m+=n[h]:m+=n[h]+i;return{name:o,basedir:c,path:m}}}})),ZW=_n()});import RA from"node:fs";import NA from"node:path";var vn,n$,Xc=w(()=>{ge();vn=de(((t,e)=>{let{readFileSync:i}=RA,{join:r}=NA,n=new Map;function s(a){if(n.has(a))return n.get(a);try{let o=r(a,"package.json"),l=i(o),{version:c}=JSON.parse(l);return n.set(a,c),c}catch{return process.version.slice(1)}}e.exports=s})),n$=vn()});var xi,o$,na=w(()=>{ge();xi=de(((t,e)=>{let i;function r(s){i=s}function n(s){i&&i(s)}e.exports={setDiagnosticsHook:r,emitDiagnostics:n}})),o$=xi()});import{format as PA}from"node:util";function CA(t){return(...e)=>{q.isEnabled()&&q.log(`[${t}]`,PA(...e))}}var R_,Zc,N_=w(()=>{ge();St();R_=y_({default:()=>CA});Zc=je((()=>{}));Zc()});var wn,f$,ep=w(()=>{ge();N_();wn=de(((t,e)=>{e.exports=(Zc(),__(R_)).default})),f$=wn()});import DA from"node:module";import MA from"node:url";import LA from"node:os";import UA from"node:path";import qA from"node:fs";var tp,x$,P_=w(()=>{ge();Qc();Jc();Xc();na();ep();tp=de(((t,e)=>{let{create:i}=bn(),r=DA,n=_n(),{pathToFileURL:s}=MA,a=vn(),{emitDiagnostics:o}=xi(),l=wn()("@apm-js-collab/tracing-hooks:module-patch");var c=class{constructor({instrumentations:d=[]}={}){this.packages=new Set(d.map(m=>m.module.name)),this.instrumentator=i(d),this.compile=r.prototype._compile}patch(){let d=this;r.prototype._compile=function(...g){let[h,f]=g,b=n(f);if(b&&d.packages.has(b.name)){l("found resolved module, checking if there is a transformer %s",f);let S=a(b.basedir,b.name),E=d.instrumentator.getTransformer(b.name,S,b.path);if(E){l("transforming file %s",f);try{g[0]=E.transform(h,"cjs")?.code,o({url:s(f).href,moduleName:E.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&p(g[0],f)}catch(A){l("Error transforming module %s: %o",f,A),o({url:s(f).href,moduleName:E.moduleName,error:A})}finally{E.free()}}}return d.compile.apply(this,g)}}unpatch(){r.prototype._compile=this.compile}};function p(d,m){let g=LA,h=UA,f=qA,b=process.env.TRACING_DUMP_DIR??g.tmpdir(),S=h.dirname(m),E=h.basename(m),A=h.join(b,S.slice(h.parse(S).root.length)),C=h.join(A,E);l("Dumping patched code to: %s",C),f.mkdirSync(A,{recursive:!0}),f.writeFileSync(C,d)}e.exports=c})),x$=tp()});import{readFileSync as C_}from"node:fs";import{dirname as D_,join as jA}from"node:path";import{fileURLToPath as M_}from"node:url";import{MessageChannel as FA}from"node:worker_threads";function q_(){let{port1:t,port2:e}=new FA;return t.on("message",sp.emitDiagnostics),t.unref(),e}function j_(t={}){let e=t?.instrumentations||[];U_=(0,HA.create)(e),L_=new Set(e.map(i=>i.module.name)),Sn=new Map,np=t?.diagnosticsPort?$A(t.diagnosticsPort):sp.emitDiagnostics}function $A(t){return e=>{try{let i=e.error===void 0||e.error instanceof Error?e.error:new Error(String(e.error));t.postMessage({...e,error:i})}catch(i){rp("failed to post diagnostics for %s: %o",e.url,i)}}}function VA(t){if(!t.url.startsWith("file:"))return t;let e=(0,GA.default)(M_(t.url));if(e&&L_.has(e.name)){let i=e.basedir,r=(0,WA.default)(i),n=U_.getTransformer(e.name,r,e.path);n&&Sn.set(t.url,n)}return t}function F_(t,e,i){return VA(i(t,e))}function ap(t,e,i){let r=i(t,e);if(Sn.has(t)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??t);r.source??(r.source=C_(n))}return zA(t,r)}function zA(t,e){let i=e.source;if(i){let r=Sn.get(t);if(YA(t,e.format))return rp("skipping json module %s",t),r.free(),Sn.delete(t),e;try{let n=typeof i=="string"?i:Buffer.from(i).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":JA(t,n);e.source=r.transform(n,s)?.code,e.shortCircuit=!0,np({url:t,moduleName:r.moduleName})}catch(n){rp("Error transforming module %s: %o",t,n),np({url:t,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function YA(t,e){return e==="json"||KA.test(t)}function JA(t,e){return XA(t)??(QA.test(e)?"esm":"cjs")}function XA(t){let e;try{e=M_(t)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let i=B_(D_(e));return i==="module"?"esm":i==="commonjs"?"cjs":void 0}function B_(t){if(ip.has(t))return ip.get(t);let e;try{e=JSON.parse(C_(jA(t,"package.json"),"utf8")).type}catch{let i=D_(t);i!==t&&(e=B_(i))}return ip.set(t,e),e}var BA,HA,GA,WA,sp,rp,Sn,L_,U_,np,KA,QA,ip,H_=w(()=>{ge();ep();Qc();Jc();Xc();na();BA=cr(wn(),1),HA=bn(),GA=cr(_n(),1),WA=cr(vn(),1),sp=xi(),rp=(0,BA.default)("@apm-js-collab/tracing-hooks:esm-hook"),Sn=null,L_=null,U_=null,np=sp.emitDiagnostics;KA=/\.json([?#]|$)/;QA=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;ip=new Map});import{createHash as G_}from"node:crypto";import{existsSync as z_,readFileSync as ZA}from"node:fs";import*as ex from"node:module";import{dirname as sa,join as K_}from"node:path";import{fileURLToPath as cp,pathToFileURL as op}from"node:url";function rx(t){if(t)return!0;let{major:e=0,minor:i=0}=Ro(process.versions.node??"0.0.0");return e>25||e===25&&i>=1||e===24&&i>=13}function Y_(t){if(lp.has(t))return lp.get(t);let e,i=K_(t,"package.json");if(z_(i))try{e=JSON.parse(ZA(i,"utf8")).type}catch{e=void 0}else sa(t)!==t&&(e=Y_(sa(t)));return lp.set(t,e),e}function nx(t){if(t.endsWith(".json"))return"json";if(t.endsWith(".mjs")||t.startsWith("file:")&&t.endsWith(".js")&&Y_(sa(cp(t)))==="module")return"module"}function sx(t){return(e,i,r)=>t(e,i,(n,s)=>{let a=r(n,s);if(a&&a.format==null){let o=nx(n);o&&(a.format=o)}return a})}function Q_(t){ot(()=>{console.warn(`[Sentry] ${t}`)})}function J_(t){Q_(`${t} See ${ix}`)}function ax(t,e){let i=e instanceof Error?e.message:String(e),r=/^[\w$]+ is not a function$/.test(i),n=i==="transform is not a function",s=(Y.__SENTRY_ORCHESTRION__?.runtime?.length??0)===0;if(!(r&&!n&&s)){if(V_.has(t))return;V_.add(t),Q_(`Could not instrument \`${t}\` (${i}). Other instrumented dependencies are unaffected, so this is not a bundling problem. If \`${t}\` should be traced, please report it.`);return}$_||($_=!0,J_(`\`@sentry/server-runtime-injection\` was bundled into your application, so \`${t}\` and any other instrumented dependency load uninstrumented (${i}). Keep \`@sentry/server-runtime-injection\` external in your server bundle, or use the Sentry bundler plugin for build-time instrumentation.`))}function ox(){(0,tx.setDiagnosticsHook)(({url:t,moduleName:e,error:i})=>{if(i)i instanceof TypeError&&ax(e,i),q.warn(`[instrumentation] failed to inject diagnostics-channel into ${e}:`,i);else{var r;Y.__SENTRY_ORCHESTRION__=Y.__SENTRY_ORCHESTRION__||{},Y.__SENTRY_ORCHESTRION__.runtime=Y.__SENTRY_ORCHESTRION__.runtime||[],Y.__SENTRY_ORCHESTRION__.runtime.push(e),((r=Y.__SENTRY_ORCHESTRION__).runtimeFiles??(r.runtimeFiles={}))[e]=t,vt()?.emit("orchestrion.module-injected",e)}})}function X_(){let t=Y.__SENTRY_ORCHESTRION__??(Y.__SENTRY_ORCHESTRION__={});if(t.runtime||t.runtimeUnavailable)return;let e=globalThis,i=rx(!!e.Deno),r=ex;ox();try{if(typeof r.registerHooks=="function"&&i){j_({instrumentations:mn});let n=new Map,s=e.Deno?sx(ap):ap;r.registerHooks({resolve:F_,load:(c,p,d)=>{let m=s(c,p,d),g=m?.format??p.format;if((g==null||g==="commonjs")&&m?.shortCircuit===!0&&m?.source!=null&&c.startsWith("file:")){let h=G_("sha256").update(m.source).digest("hex");n.set(op(cp(c)).href,h)}return m}});let a=r.Module.prototype,o=a._compile;new W_.default({instrumentations:mn}).patch();let l=a._compile;a._compile=function(c,p,...d){let m=op(p).href,g=n.get(m);return n.delete(m),(g!==void 0&&g===G_("sha256").update(c).digest("hex")?o:l).call(this,c,p,...d)},q.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof r.register=="function"&&!e.Bun&&!e.Deno){let n=q_(),s;s=import.meta.url;let a;a=K_(sa(cp(import.meta.url)),"hook.js");let o=z_(a);o||q.warn(`No orchestrion loader hook at ${a}; falling back to the package specifier.`);let l=o?op(a).href:"@sentry/server-runtime-injection/hook";r.register(l,{parentURL:s,data:{instrumentations:mn,diagnosticsPort:n},transferList:[n]}),new W_.default({instrumentations:mn}).patch(),q.log("Registered diagnostics-channel injection via Module.register()")}else{t.runtimeUnavailable=!0,q.warn("No available Node API to register diagnostics-channel injection hooks; skipping.");return}}catch(n){t.runtimeUnavailable=!0;let s=n instanceof Error?n.message:String(n);J_(n?.code==="ERR_MODULE_NOT_FOUND"?`Channel-based integrations will not record spans: your deployment is missing a file from \`@sentry/server-runtime-injection\` (${s}). Your build's file tracing left it out. Deploy the whole \`@sentry/server-runtime-injection\` package directory with your server.`:`Failed to register diagnostics-channel injection hooks (${s}), so channel-based integrations will not record spans.`),q.warn("Diagnostics-channel injection registration error:",n);return}t.runtime=t.runtime||[]}var W_,tx,ix,lp,$_,V_,Z_=w(()=>{ge();P_();H_();na();St();s_();W_=cr(tp()),tx=xi(),ix="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";lp=new Map;$_=!1,V_=new Set});import*as ev from"node:os";import{isMainThread as lx,threadId as cx}from"worker_threads";var px,pp,tv=w(()=>{Om();wt();St();Il();Ys();a_();h_();Z_();px=6e4,pp=class extends El{constructor(t){let e=t.includeServerName===!1?void 0:t.serverName||global.process.env.SENTRY_NAME||ev.hostname(),i={...t,platform:"node",runtime:t.runtime||{name:"node",version:global.process.version},serverName:e};hl(i,"node"),q.log(`Initializing Sentry: process: ${process.pid}, thread: ${lx?"main":`worker-${cx}`}.`),super(i),this._onExitFlushListener=()=>{this.emit("flush")},e&&this.on("beforeCaptureLog",r=>{r.attributes={...r.attributes,[bs]:e}}),process.on("beforeExit",this._onExitFlushListener),nl(this),f_(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&t.enableRuntimeChannelInjection!==!1&&X_()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=g_():this.asyncLocalStorageLookup={asyncLocalStorage:ql()},super.init()}get tracer(){if(this._tracer)return this._tracer;let t="@sentry/node",e=Rt,i=Jt.getTracer(t,e);return this._tracer=i,i}async flush(t){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(t)}async close(t){this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._onExitFlushListener&&process.off("beforeExit",this._onExitFlushListener);let e=await super.close(t);return this.traceProvider&&await this.traceProvider.shutdown(),e}startClientReportTracking(){let t=this.getOptions();t.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{xm&&q.log("Flushing client reports based on interval."),this._flushOutcomes()},t.clientReportFlushInterval??px).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){ul(),super._setupIntegrations()}}});var iv=w(()=>{p_();tv()});var rv={};Hn(rv,{NodeClient:()=>pp,Scope:()=>Ve,createTransport:()=>cl,defaultStackParser:()=>xc,linkedErrorsIntegration:()=>Sl});var nv=w(()=>{"use strict";iv();St()});var _v={};Hn(_v,{localFileKey:()=>ua,localFileLaunchUrl:()=>Mx,localFilePlatform:()=>da,matchesLocalFileGrant:()=>fp});import{createHmac as wx,randomBytes as fv,timingSafeEqual as Sx}from"node:crypto";import{constants as mp,statSync as kx}from"node:fs";import{link as Ex,mkdir as Tx,open as Ix,rm as Ax,writeFile as xx}from"node:fs/promises";import{get as Ox}from"node:http";import{homedir as hv}from"node:os";import{join as gp,resolve as Rx}from"node:path";function da(t=process.platform,e=process.env,i=()=>kx("/dev/console").uid,r=process.getuid?.()){if(!(e.SSH_CONNECTION||e.SSH_CLIENT||e.SSH_TTY||e.PI_WEBAPP_LISTEN_HOST==="0.0.0.0")){if(t==="win32"&&/^(?:Console|RDP-Tcp#\d+)$/i.test(e.SESSIONNAME??""))return t;if(t==="darwin"&&r)try{if(r===i())return t}catch{}}}async function yv(t){let e=process.platform!=="win32",i=await Ix(t,mp.O_RDONLY|(e?mp.O_NOFOLLOW|mp.O_NONBLOCK:0));try{let r=await i.stat();if(!r.isFile()||r.size!==32||e&&((r.mode&63)!==0||r.uid!==process.getuid?.()))return;let n=Buffer.alloc(33);if((await i.read(n)).bytesRead===32)return n.subarray(0,32)}finally{await i.close()}}async function ua(t,e=!1){let i=gp(t,"pi-web"),r=gp(i,Nx);try{return await yv(r)}catch(s){if(!e||s?.code!=="ENOENT")return}let n=`${r}.${fv(12).toString("hex")}`;try{await Tx(i,{recursive:!0,mode:448}),await xx(n,fv(32),{flag:"wx",mode:384});try{await Ex(n,r)}catch(s){if(s?.code!=="EEXIST")throw s}return await yv(r)}catch{}finally{await Ax(n,{force:!0}).catch(()=>{})}}function bv(t,e){return wx("sha256",t).update(`pi-web/native-files/v1\0${e}`).digest("base64url")}function fp(t,e,i){return!!t&&typeof i=="string"&&Cx.test(i)&&Sx(Buffer.from(i),Buffer.from(bv(t,e)))}function Dx(t,e,i,r){return new Promise(n=>{Ox(new URL("/api/local-file-actions",t),{agent:!1,signal:AbortSignal.timeout(1500),headers:{Authorization:`Bearer ${e}`,"X-Pi-Local-Files":i}},a=>{if(a.statusCode!==200){a.destroy(),n(!1);return}let o="";a.setEncoding("utf8"),a.on("data",l=>{o+=l,o.length>256&&(a.destroy(),n(!1))}),a.once("end",()=>{try{n(JSON.parse(o)?.platform===r)}catch{n(!1)}}),a.once("error",()=>n(!1))}).once("error",()=>n(!1))})}async function Mx(t,e=process.platform,i=process.env,r=Rx((i.PI_CODING_AGENT_DIR??gp(hv(),".pi","agent")).replace(/^~(?=$|[\\/])/,hv()))){if(!da(e,i))return t;try{let n=new URL(t),s=n.hash.slice(1);if(n.protocol!=="http:"||n.hostname!=="127.0.0.1"||!n.port||n.username||n.password||n.pathname!=="/"||n.search||!Px.test(s))return t;let a=await ua(r);if(!a)return t;let o=bv(a,s);return await Dx(n,s,o,e)?(n.hash=`${s}.${o}`,n.href):t}catch{return t}}var Nx,Px,Cx,ma=w(()=>{"use strict";Nx="native-files.key",Px=/^[A-Za-z0-9_-]{32}$/,Cx=/^[A-Za-z0-9_-]{43}$/});(function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="392fc95c-8b1a-47c8-ae18-972e14ee10b2",t._sentryDebugIdIdentifier="sentry-dbid-392fc95c-8b1a-47c8-ae18-972e14ee10b2")}catch{}})();import{delimiter as gP,dirname as fP,join as Er,resolve as Ir}from"node:path";import{readFileSync as hP,realpathSync as bd,watch as yP}from"node:fs";import{fileURLToPath as bP}from"node:url";import{DefaultPackageManager as U0,getAgentDir as Ae,ModelRuntime as _P,SessionManager as Bn,SettingsManager as vP,VERSION as _d}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as wP}from"@earendil-works/pi-ai";import{randomBytes as Sv,randomUUID as hp,timingSafeEqual as Ux}from"node:crypto";import{readFile as qx,readdir as jx}from"node:fs/promises";import{createServer as Fx}from"node:http";import{join as yp}from"node:path";import{getAgentDir as Bx}from"@earendil-works/pi-coding-agent";import{isAbsolute as vS,relative as wS}from"node:path";var He={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Id={id:He.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as H0}from"node:child_process";import{realpath as G0}from"node:fs/promises";import{isAbsolute as Ad,relative as W0,sep as $0,win32 as V0}from"node:path";var H=class extends Error{status;reason;constructor(e,i=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=i,this.reason=r}};function ee(t,e,i=2*1024*1024,r={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,a)=>{let o,l=H0("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:t,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:i,windowsHide:!0},(c,p,d)=>{if(!c){if(o){a(new H("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let g=c.killed||c.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(d)?"index_locked":/already exists/i.test(d)?"branch_exists":/already checked out|used by worktree/i.test(d)?"branch_in_use":/would be overwritten|local changes/i.test(d)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(d)?"identity_missing":"git_failed";a(new H("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let m=c.code;m==="ENOENT"?a(new H("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):m==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?a(new H("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(d)?a(new H("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):a(new H(c.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});l.stdin?.on("error",c=>{o=c}),r.input!==void 0&&l.stdin?.end(r.input)})}async function Ge(t){let e=await G0(t),i;try{i=(await ee(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof H&&n.status===404)return{kind:"not-repository"};if(n instanceof H&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let r=W0(i,e).split($0).join("/");if(r===".."||r.startsWith("../")||Ad(r))throw new H("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:i,scope:r?`${r}/`:""}}function ui(t){if(typeof t!="string"||!t||t.length>4096||t.includes("\0")||t.includes("\\")||Ad(t)||V0.isAbsolute(t)||t.split("/").some(e=>!e||e==="."||e===".."))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as sS}from"node:crypto";import{lstat as io,realpath as Bd}from"node:fs/promises";import{dirname as Fd,isAbsolute as aS,relative as oS,resolve as Nr}from"node:path";import{lstat as iS}from"node:fs/promises";import{resolve as rS}from"node:path";import{createHash as z0}from"node:crypto";import{constants as At}from"node:fs";import{open as Za,opendir as K0,realpath as xd,stat as Gn}from"node:fs/promises";import{isAbsolute as Rd,relative as Y0,resolve as Q0,sep as J0,win32 as X0}from"node:path";var Z0=1e3,eS={bytes:512*1024,lines:1e4},eo={bytes:5*1024*1024,lines:2e5},Nd=8*1024*1024,tS=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Xa=t=>z0("sha256").update(t).digest("hex"),X=class extends Error{status;reason;constructor(e,i=400,r){super(e),this.name="WorkspaceFileError",this.status=i,this.reason=r}};function Od(t,e){let i=Y0(t,e);return i!==".."&&!i.startsWith(`..${J0}`)&&!Rd(i)}async function Or(t,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Rd(e)||X0.isAbsolute(e))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let i=await xd(t),r=Q0(i,e);if(!Od(i,r))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await xd(r);if(!Od(i,n))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function Wn(t){try{return await t()}catch(e){if(e instanceof X)throw e;let i=e.code;throw i==="ENOENT"||i==="ENOTDIR"?new X("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):i==="EACCES"||i==="EPERM"?new X("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function Pd(t,e){return Wn(async()=>{let i=await Or(t,e),r=[],n=!1;for await(let s of await K0(i)){if(s.name===".git")continue;if(r.length===Z0){n=!0;break}let a=e?`${e}/${s.name}`:s.name,o=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await Gn(await Or(t,a));o=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}r.push({name:s.name,path:a,kind:o})}return r.sort((s,a)=>+(a.kind==="directory")-+(s.kind==="directory")||tS.compare(s.name,a.name)||s.name.localeCompare(a.name)),{path:e,entries:r,truncated:n}})}function Cd(t){if(t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(t.subarray(0,6).toString("ascii")))return"image/gif";if(t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Rr(t,e,i=eS){return Wn(async()=>{let r=await Or(t,e);if(!(await Gn(r)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Za(r,At.O_RDONLY|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let a={path:e,size:s.size},o=Buffer.alloc(16);await n.read(o,0,o.length,0);let l=Cd(o),c=l?Nd:i.bytes;if(s.size>c)return{...a,kind:"too-large",limit:c,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,c+1)),d=0;for(;d<p.length;){let{bytesRead:h}=await n.read(p,d,p.length-d,d);if(!h)break;d+=h}if(d>s.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let m=p.subarray(0,d);if(l)return{...a,kind:"image",mimeType:l,data:m.toString("base64")};if(m.some(h=>h===0||h<32&&![9,10,12,13,27].includes(h)))return{...a,kind:"unsupported"};let g=1;for(let h=0;h<m.length-1;h++)if(m[h]===10&&++g>i.lines)return{...a,kind:"too-large",limit:i.lines,unit:"lines"};try{return{...a,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(m),version:Xa(m)}}catch{return{...a,kind:"unsupported"}}}finally{await n.close()}})}async function Dd(t,e){return Wn(async()=>{let i=await Or(t,e);if(!(await Gn(i)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Za(i,At.O_RDONLY|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>Nd)throw new X("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(n.size+1),a=0;for(;a<s.length;){let{bytesRead:c}=await r.read(s,a,s.length-a,a);if(!c)break;a+=c}if(a>n.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let o=s.subarray(0,a),l=Cd(o);if(!l)throw new X("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:l,bytes:o}}finally{await r.close()}})}async function Md(t,e,i,r){if(typeof i!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new X("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(i,"utf8"),{bytes:s,lines:a}=eo;if(n.length>s)throw new X(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let o=1;for(let l of n)if(l===10&&++o>a+1)throw new X(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${a} \u884C`,413);return Wn(async()=>{let l=await Or(t,e);if(!(await Gn(l)).isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Za(l,At.O_RDWR|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let d=Buffer.alloc(p.size+1),m=0;for(;m<d.length;){let{bytesRead:h}=await c.read(d,m,d.length-m,m);if(!h)break;m+=h}if(m>p.size||Xa(d.subarray(0,m))!==r)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await c.truncate(0);let g=0;for(;g<n.length;)g+=(await c.write(n,g,n.length-g,g)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Xa(n)}}finally{await c.close()}})}var nS=1e3,Ld=512*1024,Ud=1e4;function qd(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}async function Hi(t){let e=await Ge(t);if(e.kind!=="repository")return e;let{root:i,scope:r}=e,n=await ee(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:i,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},a=n.split("\0");for(let o=0;o<a.length;o++){let l=a[o];if(l.startsWith("# branch.oid ")){let S=l.slice(13);s.head=S==="(initial)"?null:S;continue}if(l.startsWith("# branch.head ")){let S=l.slice(14);s.branch=S==="(detached)"?null:S;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let S=l.match(/\+(\d+) -(\d+)/);S&&(s.ahead=Number(S[1]),s.behind=Number(S[2]));continue}let c=l[0];if(!["1","2","u","?"].includes(c??""))continue;let p=c==="?"?1:c==="1"?8:c==="2"?9:10,d=0;for(let S=0;S<p;S++)d=l.indexOf(" ",d)+1;let m=qd(r,l.slice(d)),g=c==="2"?a[++o]:void 0;if(!m)continue;if(s.entries.length===nS){s.truncated=!0;continue}let h=l.slice(0,d).split(" "),f={path:m,index:c==="?"?"?":h[1][0],worktree:c==="?"?"?":h[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&h[2]!=="N..."},b=g===void 0?void 0:qd(r,g);b&&(f.originalPath=b),s.entries.push(f)}return s}async function jd(t,e,i){if(ui(e),!["staged","unstaged","untracked"].includes(i))throw new H("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await Hi(t);if(r.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:i},s=r.entries.find(o=>o.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(i==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await iS(rS(t,e))).isFile())return{...n,kind:"unsupported"};let o=await Rr(t,e);if(o.kind==="too-large")return{...n,kind:"too-large"};if(o.kind!=="text")return{...n,kind:"binary"};if(!o.text)return{...n,kind:"empty"};let l=o.text.split(`
499
+ `}})),v5=Vc()});var zc,x_=w(()=>{zc={}});var Kc,D5,O_=w(()=>{fe();E_();jc();Fc();Bc();ta();Gc();$c();I_();A_();x_();Kc=ue(((t,e)=>{Wc(),fn(),hn(),yn();let i=ia.v??{},{parse:r}=ra.v??{},{generate:n}=T_.v??{},s=Vc(),a,o;var l=new WeakMap,c=new WeakMap,p=new WeakMap,d=new WeakMap,m=new WeakMap,g=new WeakMap,h=new WeakSet,f=class{constructor(N,R,W,P,I,x={}){k_(this,h),Ze(this,l,null),Ze(this,c,null),Ze(this,p,null),Ze(this,d,[]),Ze(this,m,null),Ze(this,g,{}),ht(l,this,N),ht(c,this,R),ht(p,this,W),ht(d,this,P),ht(m,this,I),ht(g,this,x)}free(){}get moduleName(){return he(l,this)}get filePath(){return he(p,this)}transform(N,R,W,P){let I=P?.sourceFile||`${he(l,this)}/${he(p,this)}`;if(Buffer.isBuffer(N)&&(N=N.toString()),!N)return{code:N};let x,L={},U=0,k={...s,...he(g,this),defaults:{...s}};for(let v of he(d,this)){let{astQuery:F,functionQuery:G={}}=v;if(!x){let oe={loc:!0,ranges:!0,raw:!0,module:R==="esm"};try{x=r(N,oe)}catch{x=r(N,{...oe,module:!oe.module})}R==="esm"&&(L=ft(h,this,E).call(this,x))}let K=ft(h,this,A).call(this,G,L),J=F||ft(h,this,C).call(this,K),O={...v,dcModule:he(m,this),moduleType:R,moduleVersion:he(c,this),functionQuery:K,transforms:k};O.operator=ft(h,this,S).call(this,O),i.traverse(x,i.parse(J),(...oe)=>{U++,ft(h,this,b).call(this,O,...oe)})}if(U===0&&he(d,this).length>0){let v=he(d,this).map(({astQuery:F,functionQuery:G={}})=>{if(F)return F;let K=ft(h,this,A).call(this,G,L),O=(pe=>pe.methodName||pe.privateMethodName||pe.functionName||pe.expressionName||"constructor")(G),oe=G.className||G.functionName||G.expressionName,se=K.className||K.functionName||K.expressionName;return oe&&oe!==se?`${oe} (local name: ${se})`:O});throw new Error(`Failed to find injection points for: ${JSON.stringify(v)}`)}if(x){a??(a=(zc.v??{}).SourceMapConsumer),o??(o=(zc.v??{}).SourceMapGenerator);let v=new o({file:I});v.setSourceContent(I,N);let F=n(x,{sourceMap:v});return W&&v.applySourceMap(new a(W),I),{code:F,map:v.toString()}}return{code:N}}};function b(N,...R){let W=typeof N.transform=="function"?N.transform:N.transforms[N.operator],{index:P=0}=N.functionQuery,[I]=R,x=I.init?.type||I.type;x!=="ClassDeclaration"&&x!=="ClassExpression"&&(I.type==="VariableDeclarator"||(N.functionIndex=++N.functionIndex||0,P!==null&&P!==N.functionIndex))||W(N,...R)}function S({transform:N,functionQuery:{kind:R}}){if(typeof N=="string")return N;switch(R){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}}function E(N){let R={};for(let W of N.body)if(W.type==="ExportNamedDeclaration"&&!W.source){for(let P of W.specifiers)if(P.exported&&P.local){let I=P.exported.name??P.exported.value,x=P.local.name??P.local.value;I&&x&&(R[I]=x)}}return R}function A(N,R){if(!N.isExportAlias)return N;let{functionName:W,expressionName:P,className:I}=N;return W&&R[W]?{...N,functionName:R[W]}:P&&R[P]?{...N,expressionName:R[P]}:I&&R[I]?{...N,className:R[I]}:N}function C(N){let{functionName:R,expressionName:W,className:P,objectName:I,propertyName:x}=N,L=N.privateMethodName?"PrivateIdentifier":"Identifier",U=[],k=N.methodName||N.privateMethodName;if(P?(k??(k="constructor"),U.push(`[id.name="${P}"]`,`[id.name="${P}"] > ClassExpression`,`[id.name="${P}"] > ClassBody > [key.name="${k}"][key.type=${L}] > [async]`,`[id.name="${P}"] > ClassExpression > ClassBody > [key.name="${k}"][key.type=${L}] > [async]`)):k&&U.push(`ClassBody > [key.name="${k}"][key.type=${L}] > [async]`,`Property[key.name="${k}"][key.type=${L}] > [async]`),R?U.push(`FunctionDeclaration[id.name="${R}"][async]`):W&&U.push(`FunctionExpression[id.name="${W}"][async]`,`ArrowFunctionExpression[id.name="${W}"][async]`,`VariableDeclarator[id.name="${W}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${W}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${W}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${W}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${W}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${W}"] > ArrowFunctionExpression[async]`),I||x){if(!I||!x)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${I}, propertyName=${x})`);let v=I==="this"?"left.object.type=ThisExpression":`left.object.name="${I}"`;U.push(`AssignmentExpression[${v}][left.property.name="${x}"] > [async]`)}return U.join(", ")}e.exports={Transformer:f}})),D5=Kc()});var Yc,W5,R_=w(()=>{fe();jc();Fc();Bc();S_();O_();Yc=ue(((t,e)=>{fn(),hn(),yn();let i=Hc(),{Transformer:r}=Kc();var n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=class{constructor(c,p){Ze(this,n,[]),Ze(this,s,null),Ze(this,a,{}),Ze(this,o,{}),ht(n,this,c),ht(s,this,p||"diagnostics_channel")}free(){ht(a,this,{})}addTransform(c,p){he(o,this)[c]=p}getTransformer(c,p,d){d=d.replace(/\\/g,"/");let m=`${c}/${d}@${p}`;if(he(a,this)[m])return he(a,this)[m];let g=he(n,this).filter(({module:h})=>h.name===c&&(typeof h.filePath=="string"?h.filePath===d:h.filePath.test(d))&&i(p,h.versionRange));if(g.length!==0)return he(a,this)[m]=new r(c,p,d,g,he(s,this),he(o,this)),he(a,this)[m]}};e.exports={InstrumentationMatcher:l}})),W5=Yc()});var Qc,K5,N_=w(()=>{fe();R_();Qc=ue(((t,e)=>{let{InstrumentationMatcher:i}=Yc();function r(n,s){return new i(n,s)}e.exports={create:r}})),K5=Qc()});var bn,X5,Jc=w(()=>{fe();N_();bn=ue(((t,e)=>{e.exports=Qc()})),X5=bn()});import PA from"node:path";var _n,i$,Xc=w(()=>{fe();_n=ue(((t,e)=>{var i=PA.sep;e.exports=function(r){var n=r.split(i),s=n.lastIndexOf("node_modules");if(s!==-1&&n[s+1]){for(var a=n[s+1][0]==="@",o=a?n[s+1]+"/"+n[s+2]:n[s+1],l=a?3:2,c="",p=s+l-1,d=0;d<=p;d++)d===p?c+=n[d]:c+=n[d]+i;for(var m="",g=n.length-1,h=s+l;h<=g;h++)h===g?m+=n[h]:m+=n[h]+i;return{name:o,basedir:c,path:m}}}})),i$=_n()});import CA from"node:fs";import DA from"node:path";var vn,o$,Zc=w(()=>{fe();vn=ue(((t,e)=>{let{readFileSync:i}=CA,{join:r}=DA,n=new Map;function s(a){if(n.has(a))return n.get(a);try{let o=r(a,"package.json"),l=i(o),{version:c}=JSON.parse(l);return n.set(a,c),c}catch{return process.version.slice(1)}}e.exports=s})),o$=vn()});var xi,p$,na=w(()=>{fe();xi=ue(((t,e)=>{let i;function r(s){i=s}function n(s){i&&i(s)}e.exports={setDiagnosticsHook:r,emitDiagnostics:n}})),p$=xi()});import{format as MA}from"node:util";function LA(t){return(...e)=>{q.isEnabled()&&q.log(`[${t}]`,MA(...e))}}var P_,ep,C_=w(()=>{fe();wt();P_=__({default:()=>LA});ep=je((()=>{}));ep()});var wn,b$,tp=w(()=>{fe();C_();wn=ue(((t,e)=>{e.exports=(ep(),w_(P_)).default})),b$=wn()});import UA from"node:module";import qA from"node:url";import jA from"node:os";import FA from"node:path";import BA from"node:fs";var ip,N$,D_=w(()=>{fe();Jc();Xc();Zc();na();tp();ip=ue(((t,e)=>{let{create:i}=bn(),r=UA,n=_n(),{pathToFileURL:s}=qA,a=vn(),{emitDiagnostics:o}=xi(),l=wn()("@apm-js-collab/tracing-hooks:module-patch");var c=class{constructor({instrumentations:d=[]}={}){this.packages=new Set(d.map(m=>m.module.name)),this.instrumentator=i(d),this.compile=r.prototype._compile}patch(){let d=this;r.prototype._compile=function(...g){let[h,f]=g,b=n(f);if(b&&d.packages.has(b.name)){l("found resolved module, checking if there is a transformer %s",f);let S=a(b.basedir,b.name),E=d.instrumentator.getTransformer(b.name,S,b.path);if(E){l("transforming file %s",f);try{g[0]=E.transform(h,"cjs")?.code,o({url:s(f).href,moduleName:E.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&p(g[0],f)}catch(A){l("Error transforming module %s: %o",f,A),o({url:s(f).href,moduleName:E.moduleName,error:A})}finally{E.free()}}}return d.compile.apply(this,g)}}unpatch(){r.prototype._compile=this.compile}};function p(d,m){let g=jA,h=FA,f=BA,b=process.env.TRACING_DUMP_DIR??g.tmpdir(),S=h.dirname(m),E=h.basename(m),A=h.join(b,S.slice(h.parse(S).root.length)),C=h.join(A,E);l("Dumping patched code to: %s",C),f.mkdirSync(A,{recursive:!0}),f.writeFileSync(C,d)}e.exports=c})),N$=ip()});import{readFileSync as M_}from"node:fs";import{dirname as L_,join as HA}from"node:path";import{fileURLToPath as U_}from"node:url";import{MessageChannel as WA}from"node:worker_threads";function F_(){let{port1:t,port2:e}=new WA;return t.on("message",ap.emitDiagnostics),t.unref(),e}function B_(t={}){let e=t?.instrumentations||[];j_=(0,$A.create)(e),q_=new Set(e.map(i=>i.module.name)),Sn=new Map,sp=t?.diagnosticsPort?KA(t.diagnosticsPort):ap.emitDiagnostics}function KA(t){return e=>{try{let i=e.error===void 0||e.error instanceof Error?e.error:new Error(String(e.error));t.postMessage({...e,error:i})}catch(i){np("failed to post diagnostics for %s: %o",e.url,i)}}}function YA(t){if(!t.url.startsWith("file:"))return t;let e=(0,VA.default)(U_(t.url));if(e&&q_.has(e.name)){let i=e.basedir,r=(0,zA.default)(i),n=j_.getTransformer(e.name,r,e.path);n&&Sn.set(t.url,n)}return t}function H_(t,e,i){return YA(i(t,e))}function op(t,e,i){let r=i(t,e);if(Sn.has(t)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??t);r.source??(r.source=M_(n))}return QA(t,r)}function QA(t,e){let i=e.source;if(i){let r=Sn.get(t);if(XA(t,e.format))return np("skipping json module %s",t),r.free(),Sn.delete(t),e;try{let n=typeof i=="string"?i:Buffer.from(i).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":ex(t,n);e.source=r.transform(n,s)?.code,e.shortCircuit=!0,sp({url:t,moduleName:r.moduleName})}catch(n){np("Error transforming module %s: %o",t,n),sp({url:t,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function XA(t,e){return e==="json"||JA.test(t)}function ex(t,e){return tx(t)??(ZA.test(e)?"esm":"cjs")}function tx(t){let e;try{e=U_(t)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let i=W_(L_(e));return i==="module"?"esm":i==="commonjs"?"cjs":void 0}function W_(t){if(rp.has(t))return rp.get(t);let e;try{e=JSON.parse(M_(HA(t,"package.json"),"utf8")).type}catch{let i=L_(t);i!==t&&(e=W_(i))}return rp.set(t,e),e}var GA,$A,VA,zA,ap,np,Sn,q_,j_,sp,JA,ZA,rp,G_=w(()=>{fe();tp();Jc();Xc();Zc();na();GA=cr(wn(),1),$A=bn(),VA=cr(_n(),1),zA=cr(vn(),1),ap=xi(),np=(0,GA.default)("@apm-js-collab/tracing-hooks:esm-hook"),Sn=null,q_=null,j_=null,sp=ap.emitDiagnostics;JA=/\.json([?#]|$)/;ZA=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;rp=new Map});import{createHash as $_}from"node:crypto";import{existsSync as Y_,readFileSync as ix}from"node:fs";import*as rx from"node:module";import{dirname as sa,join as Q_}from"node:path";import{fileURLToPath as pp,pathToFileURL as lp}from"node:url";function ax(t){if(t)return!0;let{major:e=0,minor:i=0}=No(process.versions.node??"0.0.0");return e>25||e===25&&i>=1||e===24&&i>=13}function J_(t){if(cp.has(t))return cp.get(t);let e,i=Q_(t,"package.json");if(Y_(i))try{e=JSON.parse(ix(i,"utf8")).type}catch{e=void 0}else sa(t)!==t&&(e=J_(sa(t)));return cp.set(t,e),e}function ox(t){if(t.endsWith(".json"))return"json";if(t.endsWith(".mjs")||t.startsWith("file:")&&t.endsWith(".js")&&J_(sa(pp(t)))==="module")return"module"}function lx(t){return(e,i,r)=>t(e,i,(n,s)=>{let a=r(n,s);if(a&&a.format==null){let o=ox(n);o&&(a.format=o)}return a})}function X_(t){ot(()=>{console.warn(`[Sentry] ${t}`)})}function Z_(t){X_(`${t} See ${sx}`)}function cx(t,e){let i=e instanceof Error?e.message:String(e),r=/^[\w$]+ is not a function$/.test(i),n=i==="transform is not a function",s=(Y.__SENTRY_ORCHESTRION__?.runtime?.length??0)===0;if(!(r&&!n&&s)){if(K_.has(t))return;K_.add(t),X_(`Could not instrument \`${t}\` (${i}). Other instrumented dependencies are unaffected, so this is not a bundling problem. If \`${t}\` should be traced, please report it.`);return}z_||(z_=!0,Z_(`\`@sentry/server-runtime-injection\` was bundled into your application, so \`${t}\` and any other instrumented dependency load uninstrumented (${i}). Keep \`@sentry/server-runtime-injection\` external in your server bundle, or use the Sentry bundler plugin for build-time instrumentation.`))}function px(){(0,nx.setDiagnosticsHook)(({url:t,moduleName:e,error:i})=>{if(i)i instanceof TypeError&&cx(e,i),q.warn(`[instrumentation] failed to inject diagnostics-channel into ${e}:`,i);else{var r;Y.__SENTRY_ORCHESTRION__=Y.__SENTRY_ORCHESTRION__||{},Y.__SENTRY_ORCHESTRION__.runtime=Y.__SENTRY_ORCHESTRION__.runtime||[],Y.__SENTRY_ORCHESTRION__.runtime.push(e),((r=Y.__SENTRY_ORCHESTRION__).runtimeFiles??(r.runtimeFiles={}))[e]=t,_t()?.emit("orchestrion.module-injected",e)}})}function ev(){let t=Y.__SENTRY_ORCHESTRION__??(Y.__SENTRY_ORCHESTRION__={});if(t.runtime||t.runtimeUnavailable)return;let e=globalThis,i=ax(!!e.Deno),r=rx;px();try{if(typeof r.registerHooks=="function"&&i){B_({instrumentations:mn});let n=new Map,s=e.Deno?lx(op):op;r.registerHooks({resolve:H_,load:(c,p,d)=>{let m=s(c,p,d),g=m?.format??p.format;if((g==null||g==="commonjs")&&m?.shortCircuit===!0&&m?.source!=null&&c.startsWith("file:")){let h=$_("sha256").update(m.source).digest("hex");n.set(lp(pp(c)).href,h)}return m}});let a=r.Module.prototype,o=a._compile;new V_.default({instrumentations:mn}).patch();let l=a._compile;a._compile=function(c,p,...d){let m=lp(p).href,g=n.get(m);return n.delete(m),(g!==void 0&&g===$_("sha256").update(c).digest("hex")?o:l).call(this,c,p,...d)},q.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof r.register=="function"&&!e.Bun&&!e.Deno){let n=F_(),s;s=import.meta.url;let a;a=Q_(sa(pp(import.meta.url)),"hook.js");let o=Y_(a);o||q.warn(`No orchestrion loader hook at ${a}; falling back to the package specifier.`);let l=o?lp(a).href:"@sentry/server-runtime-injection/hook";r.register(l,{parentURL:s,data:{instrumentations:mn,diagnosticsPort:n},transferList:[n]}),new V_.default({instrumentations:mn}).patch(),q.log("Registered diagnostics-channel injection via Module.register()")}else{t.runtimeUnavailable=!0,q.warn("No available Node API to register diagnostics-channel injection hooks; skipping.");return}}catch(n){t.runtimeUnavailable=!0;let s=n instanceof Error?n.message:String(n);Z_(n?.code==="ERR_MODULE_NOT_FOUND"?`Channel-based integrations will not record spans: your deployment is missing a file from \`@sentry/server-runtime-injection\` (${s}). Your build's file tracing left it out. Deploy the whole \`@sentry/server-runtime-injection\` package directory with your server.`:`Failed to register diagnostics-channel injection hooks (${s}), so channel-based integrations will not record spans.`),q.warn("Diagnostics-channel injection registration error:",n);return}t.runtime=t.runtime||[]}var V_,nx,sx,cp,z_,K_,tv=w(()=>{fe();D_();G_();na();wt();o_();V_=cr(ip()),nx=xi(),sx="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";cp=new Map;z_=!1,K_=new Set});import*as iv from"node:os";import{isMainThread as dx,threadId as ux}from"worker_threads";var mx,dp,rv=w(()=>{Nm();vt();wt();Al();Ys();l_();b_();tv();mx=6e4,dp=class extends Tl{constructor(t){let e=t.includeServerName===!1?void 0:t.serverName||global.process.env.SENTRY_NAME||iv.hostname(),i={...t,platform:"node",runtime:t.runtime||{name:"node",version:global.process.version},serverName:e};yl(i,"node"),q.log(`Initializing Sentry: process: ${process.pid}, thread: ${dx?"main":`worker-${ux}`}.`),super(i),this._onExitFlushListener=()=>{this.emit("flush")},e&&this.on("beforeCaptureLog",r=>{r.attributes={...r.attributes,[bs]:e}}),process.on("beforeExit",this._onExitFlushListener),sl(this),y_(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&t.enableRuntimeChannelInjection!==!1&&ev()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=h_():this.asyncLocalStorageLookup={asyncLocalStorage:jl()},super.init()}get tracer(){if(this._tracer)return this._tracer;let t="@sentry/node",e=Rt,i=Jt.getTracer(t,e);return this._tracer=i,i}async flush(t){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(t)}async close(t){this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._onExitFlushListener&&process.off("beforeExit",this._onExitFlushListener);let e=await super.close(t);return this.traceProvider&&await this.traceProvider.shutdown(),e}startClientReportTracking(){let t=this.getOptions();t.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{Rm&&q.log("Flushing client reports based on interval."),this._flushOutcomes()},t.clientReportFlushInterval??mx).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){ml(),super._setupIntegrations()}}});var nv=w(()=>{u_();rv()});var sv={};Hn(sv,{NodeClient:()=>dp,Scope:()=>Ve,createTransport:()=>pl,defaultStackParser:()=>Oc,linkedErrorsIntegration:()=>kl});var av=w(()=>{"use strict";nv();wt()});var wv={};Hn(wv,{localFileKey:()=>ma,localFileLaunchUrl:()=>qx,localFilePlatform:()=>ua,matchesLocalFileGrant:()=>yp});import{createHmac as Ex,randomBytes as yv,timingSafeEqual as Tx}from"node:crypto";import{constants as fp,statSync as Ix}from"node:fs";import{link as Ax,mkdir as xx,open as Ox,rm as Rx,writeFile as Nx}from"node:fs/promises";import{get as Px}from"node:http";import{homedir as bv}from"node:os";import{join as hp,resolve as Cx}from"node:path";function ua(t=process.platform,e=process.env,i=()=>Ix("/dev/console").uid,r=process.getuid?.()){if(!(e.SSH_CONNECTION||e.SSH_CLIENT||e.SSH_TTY||e.PI_WEBAPP_LISTEN_HOST==="0.0.0.0")){if(t==="win32"&&/^(?:Console|RDP-Tcp#\d+)$/i.test(e.SESSIONNAME??""))return t;if(t==="darwin"&&r)try{if(r===i())return t}catch{}}}async function _v(t){let e=process.platform!=="win32",i=await Ox(t,fp.O_RDONLY|(e?fp.O_NOFOLLOW|fp.O_NONBLOCK:0));try{let r=await i.stat();if(!r.isFile()||r.size!==32||e&&((r.mode&63)!==0||r.uid!==process.getuid?.()))return;let n=Buffer.alloc(33);if((await i.read(n)).bytesRead===32)return n.subarray(0,32)}finally{await i.close()}}async function ma(t,e=!1){let i=hp(t,"pi-web"),r=hp(i,Dx);try{return await _v(r)}catch(s){if(!e||s?.code!=="ENOENT")return}let n=`${r}.${yv(12).toString("hex")}`;try{await xx(i,{recursive:!0,mode:448}),await Nx(n,yv(32),{flag:"wx",mode:384});try{await Ax(n,r)}catch(s){if(s?.code!=="EEXIST")throw s}return await _v(r)}catch{}finally{await Rx(n,{force:!0}).catch(()=>{})}}function vv(t,e){return Ex("sha256",t).update(`pi-web/native-files/v1\0${e}`).digest("base64url")}function yp(t,e,i){return!!t&&typeof i=="string"&&Lx.test(i)&&Tx(Buffer.from(i),Buffer.from(vv(t,e)))}function Ux(t,e,i,r){return new Promise(n=>{Px(new URL("/api/local-file-actions",t),{agent:!1,signal:AbortSignal.timeout(1500),headers:{Authorization:`Bearer ${e}`,"X-Pi-Local-Files":i}},a=>{if(a.statusCode!==200){a.destroy(),n(!1);return}let o="";a.setEncoding("utf8"),a.on("data",l=>{o+=l,o.length>256&&(a.destroy(),n(!1))}),a.once("end",()=>{try{n(JSON.parse(o)?.platform===r)}catch{n(!1)}}),a.once("error",()=>n(!1))}).once("error",()=>n(!1))})}async function qx(t,e=process.platform,i=process.env,r=Cx((i.PI_CODING_AGENT_DIR??hp(bv(),".pi","agent")).replace(/^~(?=$|[\\/])/,bv()))){if(!ua(e,i))return t;try{let n=new URL(t),s=n.hash.slice(1);if(n.protocol!=="http:"||n.hostname!=="127.0.0.1"||!n.port||n.username||n.password||n.pathname!=="/"||n.search||!Mx.test(s))return t;let a=await ma(r);if(!a)return t;let o=vv(a,s);return await Ux(n,s,o,e)?(n.hash=`${s}.${o}`,n.href):t}catch{return t}}var Dx,Mx,Lx,ga=w(()=>{"use strict";Dx="native-files.key",Mx=/^[A-Za-z0-9_-]{32}$/,Lx=/^[A-Za-z0-9_-]{43}$/});(function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="d6f7f3e4-0a03-4e7d-bd6c-922fb146710d",t._sentryDebugIdIdentifier="sentry-dbid-d6f7f3e4-0a03-4e7d-bd6c-922fb146710d")}catch{}})();import{delimiter as yP,dirname as bP,join as Er,resolve as Ir}from"node:path";import{readFileSync as _P,realpathSync as vd,watch as vP}from"node:fs";import{fileURLToPath as wP}from"node:url";import{DefaultPackageManager as F0,getAgentDir as Ae,ModelRuntime as SP,SessionManager as Bn,SettingsManager as kP,VERSION as wd}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as EP}from"@earendil-works/pi-ai";import{randomBytes as Ev,randomUUID as bp,timingSafeEqual as Fx}from"node:crypto";import{readFile as Bx,readdir as Hx}from"node:fs/promises";import{createServer as Wx}from"node:http";import{join as _p}from"node:path";import{getAgentDir as Gx}from"@earendil-works/pi-coding-agent";import{isAbsolute as kS,relative as ES}from"node:path";var He={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var xd={id:He.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as $0}from"node:child_process";import{realpath as V0}from"node:fs/promises";import{isAbsolute as Od,relative as z0,sep as K0,win32 as Y0}from"node:path";var H=class extends Error{status;reason;constructor(e,i=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=i,this.reason=r}};function ee(t,e,i=2*1024*1024,r={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,a)=>{let o,l=$0("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:t,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:i,windowsHide:!0},(c,p,d)=>{if(!c){if(o){a(new H("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let g=c.killed||c.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(d)?"index_locked":/already exists/i.test(d)?"branch_exists":/already checked out|used by worktree/i.test(d)?"branch_in_use":/would be overwritten|local changes/i.test(d)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(d)?"identity_missing":"git_failed";a(new H("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let m=c.code;m==="ENOENT"?a(new H("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):m==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?a(new H("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(d)?a(new H("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):a(new H(c.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});l.stdin?.on("error",c=>{o=c}),r.input!==void 0&&l.stdin?.end(r.input)})}async function We(t){let e=await V0(t),i;try{i=(await ee(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof H&&n.status===404)return{kind:"not-repository"};if(n instanceof H&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let r=z0(i,e).split(K0).join("/");if(r===".."||r.startsWith("../")||Od(r))throw new H("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:i,scope:r?`${r}/`:""}}function ui(t){if(typeof t!="string"||!t||t.length>4096||t.includes("\0")||t.includes("\\")||Od(t)||Y0.isAbsolute(t)||t.split("/").some(e=>!e||e==="."||e===".."))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as lS}from"node:crypto";import{lstat as ro,realpath as Wd}from"node:fs/promises";import{dirname as Hd,isAbsolute as cS,relative as pS,resolve as Nr}from"node:path";import{lstat as sS}from"node:fs/promises";import{resolve as aS}from"node:path";import{createHash as Q0}from"node:crypto";import{constants as At}from"node:fs";import{open as eo,opendir as J0,realpath as Rd,stat as Wn}from"node:fs/promises";import{isAbsolute as Pd,relative as X0,resolve as Z0,sep as eS,win32 as tS}from"node:path";var iS=1e3,rS={bytes:512*1024,lines:1e4},to={bytes:5*1024*1024,lines:2e5},Cd=8*1024*1024,nS=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Za=t=>Q0("sha256").update(t).digest("hex"),X=class extends Error{status;reason;constructor(e,i=400,r){super(e),this.name="WorkspaceFileError",this.status=i,this.reason=r}};function Nd(t,e){let i=X0(t,e);return i!==".."&&!i.startsWith(`..${eS}`)&&!Pd(i)}async function Or(t,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Pd(e)||tS.isAbsolute(e))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let i=await Rd(t),r=Z0(i,e);if(!Nd(i,r))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await Rd(r);if(!Nd(i,n))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function Gn(t){try{return await t()}catch(e){if(e instanceof X)throw e;let i=e.code;throw i==="ENOENT"||i==="ENOTDIR"?new X("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):i==="EACCES"||i==="EPERM"?new X("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function Dd(t,e){return Gn(async()=>{let i=await Or(t,e),r=[],n=!1;for await(let s of await J0(i)){if(s.name===".git")continue;if(r.length===iS){n=!0;break}let a=e?`${e}/${s.name}`:s.name,o=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await Wn(await Or(t,a));o=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}r.push({name:s.name,path:a,kind:o})}return r.sort((s,a)=>+(a.kind==="directory")-+(s.kind==="directory")||nS.compare(s.name,a.name)||s.name.localeCompare(a.name)),{path:e,entries:r,truncated:n}})}function Md(t){if(t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(t.subarray(0,6).toString("ascii")))return"image/gif";if(t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Rr(t,e,i=rS){return Gn(async()=>{let r=await Or(t,e);if(!(await Wn(r)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await eo(r,At.O_RDONLY|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let a={path:e,size:s.size},o=Buffer.alloc(16);await n.read(o,0,o.length,0);let l=Md(o),c=l?Cd:i.bytes;if(s.size>c)return{...a,kind:"too-large",limit:c,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,c+1)),d=0;for(;d<p.length;){let{bytesRead:h}=await n.read(p,d,p.length-d,d);if(!h)break;d+=h}if(d>s.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let m=p.subarray(0,d);if(l)return{...a,kind:"image",mimeType:l,data:m.toString("base64")};if(m.some(h=>h===0||h<32&&![9,10,12,13,27].includes(h)))return{...a,kind:"unsupported"};let g=1;for(let h=0;h<m.length-1;h++)if(m[h]===10&&++g>i.lines)return{...a,kind:"too-large",limit:i.lines,unit:"lines"};try{return{...a,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(m),version:Za(m)}}catch{return{...a,kind:"unsupported"}}}finally{await n.close()}})}async function Ld(t,e){return Gn(async()=>{let i=await Or(t,e);if(!(await Wn(i)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await eo(i,At.O_RDONLY|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>Cd)throw new X("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(n.size+1),a=0;for(;a<s.length;){let{bytesRead:c}=await r.read(s,a,s.length-a,a);if(!c)break;a+=c}if(a>n.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let o=s.subarray(0,a),l=Md(o);if(!l)throw new X("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:l,bytes:o}}finally{await r.close()}})}async function Ud(t,e,i,r){if(typeof i!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new X("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(i,"utf8"),{bytes:s,lines:a}=to;if(n.length>s)throw new X(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let o=1;for(let l of n)if(l===10&&++o>a+1)throw new X(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${a} \u884C`,413);return Gn(async()=>{let l=await Or(t,e);if(!(await Wn(l)).isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await eo(l,At.O_RDWR|At.O_NONBLOCK|(At.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let d=Buffer.alloc(p.size+1),m=0;for(;m<d.length;){let{bytesRead:h}=await c.read(d,m,d.length-m,m);if(!h)break;m+=h}if(m>p.size||Za(d.subarray(0,m))!==r)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await c.truncate(0);let g=0;for(;g<n.length;)g+=(await c.write(n,g,n.length-g,g)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Za(n)}}finally{await c.close()}})}var oS=1e3,qd=512*1024,jd=1e4;function Fd(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}async function Hi(t){let e=await We(t);if(e.kind!=="repository")return e;let{root:i,scope:r}=e,n=await ee(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:i,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},a=n.split("\0");for(let o=0;o<a.length;o++){let l=a[o];if(l.startsWith("# branch.oid ")){let S=l.slice(13);s.head=S==="(initial)"?null:S;continue}if(l.startsWith("# branch.head ")){let S=l.slice(14);s.branch=S==="(detached)"?null:S;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let S=l.match(/\+(\d+) -(\d+)/);S&&(s.ahead=Number(S[1]),s.behind=Number(S[2]));continue}let c=l[0];if(!["1","2","u","?"].includes(c??""))continue;let p=c==="?"?1:c==="1"?8:c==="2"?9:10,d=0;for(let S=0;S<p;S++)d=l.indexOf(" ",d)+1;let m=Fd(r,l.slice(d)),g=c==="2"?a[++o]:void 0;if(!m)continue;if(s.entries.length===oS){s.truncated=!0;continue}let h=l.slice(0,d).split(" "),f={path:m,index:c==="?"?"?":h[1][0],worktree:c==="?"?"?":h[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&h[2]!=="N..."},b=g===void 0?void 0:Fd(r,g);b&&(f.originalPath=b),s.entries.push(f)}return s}async function Bd(t,e,i){if(ui(e),!["staged","unstaged","untracked"].includes(i))throw new H("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await Hi(t);if(r.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:i},s=r.entries.find(o=>o.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(i==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await sS(aS(t,e))).isFile())return{...n,kind:"unsupported"};let o=await Rr(t,e);if(o.kind==="too-large")return{...n,kind:"too-large"};if(o.kind!=="text")return{...n,kind:"binary"};if(!o.text)return{...n,kind:"empty"};let l=o.text.split(`
500
500
  `),c=l.at(-1)==="";c&&l.pop();let p=`--- /dev/null
501
501
  +++ b/${e.replace(/[\r\n]/g," ")}
502
502
  @@ -0,0 +1,${l.length} @@
503
503
  ${l.map(d=>`+${d}`).join(`
504
504
  `)}
505
505
  ${c?"":`\
506
- `}`;return Buffer.byteLength(p)>Ld||l.length>Ud?{...n,kind:"too-large"}:{...n,kind:"text",patch:p}}if(s.untracked||(i==="staged"?s.index:s.worktree)===".")return{...n,kind:"empty"};let a=i==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let o=await ee(t,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...i==="staged"?["--cached"]:[],"--",...a],Ld);return o?o.split(`
507
- `).length>Ud?{...n,kind:"too-large"}:/^Binary files /m.test(o)?{...n,kind:"binary"}:{...n,kind:"text",patch:o}:{...n,kind:"empty"}}catch(o){if(o instanceof H&&o.status===413)return{...n,kind:"too-large"};throw o}}var to=new Set,lS="Co-authored-by: pi-webapp <pi-webapp@emath.top>",cS=/^Co-authored-by:\s*[^\n]*<pi-webapp@emath\.top>\s*$/i;async function pS(t,e){let i=await ee(t,["-c","trailer.separators=:","interpret-trailers","--parse","--no-divider"],void 0,{input:e});if(i.split(`
508
- `).some(s=>cS.test(s)))return e;let r=e.includes(`\r
506
+ `}`;return Buffer.byteLength(p)>qd||l.length>jd?{...n,kind:"too-large"}:{...n,kind:"text",patch:p}}if(s.untracked||(i==="staged"?s.index:s.worktree)===".")return{...n,kind:"empty"};let a=i==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let o=await ee(t,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...i==="staged"?["--cached"]:[],"--",...a],qd);return o?o.split(`
507
+ `).length>jd?{...n,kind:"too-large"}:/^Binary files /m.test(o)?{...n,kind:"binary"}:{...n,kind:"text",patch:o}:{...n,kind:"empty"}}catch(o){if(o instanceof H&&o.status===413)return{...n,kind:"too-large"};throw o}}var io=new Set,dS="Co-authored-by: pi-webapp <pi-webapp@emath.top>",uS=/^Co-authored-by:\s*[^\n]*<pi-webapp@emath\.top>\s*$/i;async function mS(t,e){let i=await ee(t,["-c","trailer.separators=:","interpret-trailers","--parse","--no-divider"],void 0,{input:e});if(i.split(`
508
+ `).some(s=>uS.test(s)))return e;let r=e.includes(`\r
509
509
  `)?`\r
510
510
  `:`
511
- `;return`${e.replace(/(?:\r?\n[^\S\r\n]*)+$/,"")}${i?r:r+r}${lS}${r}`}var le=(t,e=409)=>{throw new H("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,t)};async function dS(t){return Bd(Nr(t,(await ee(t,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function ro(t,e,i=!1){let r=null;try{let n=await Ge(t);n.kind==="repository"&&(r=await dS(n.cwd))}catch(n){if(!i)throw n}if(!r)return e();if(to.has(r))return le("busy");to.add(r);try{return await e()}finally{to.delete(r)}}async function $n(t){let e=await Ge(t),i={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return i;let r=await Hi(e.root);if(r.kind!=="repository")return i;let[n,s,a]=await Promise.all([ee(e.cwd,["ls-files","--stage","-z"]),ee(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),ee(e.cwd,["rev-parse","--absolute-git-dir"])]),o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],l=(await Promise.all(o.map(async g=>{try{return await io(Nr(a.replace(/\n$/,""),g)),g}catch(h){if(h.code==="ENOENT")return null;throw h}}))).filter(Boolean),c=await Promise.all(r.entries.map(async g=>{try{let h=await io(Nr(e.root,g.path));return[g.path,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.mode]}catch(h){if(["ENOENT","ENOTDIR"].includes(h.code??""))return[g.path,"missing"];throw h}})),p=s.split(`
512
- `).filter(Boolean).map(g=>{let[h,,f]=g.split("\0");return{name:h,current:h===r.branch,occupied:!!f&&h!==r.branch}}),d=r.truncated||p.length>512?"too_many_changes":l.includes("index.lock")?"index_locked":l.length||r.entries.some(g=>g.conflict)?"operation_in_progress":null,m=sS("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:n,refs:s,entries:r.entries,files:c,present:l})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:m,staged:r.entries.filter(g=>!g.untracked&&g.index!==".").length,dirty:r.entries.length>0,blocked:d,branches:p.slice(0,512)}}async function uS(t,e){ui(e);let i=Fd(Nr(t.cwd,e));for(;;)try{let s=await Bd(i),a=oS(t.cwd,s);if(a===".."||a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||aS(a))return le("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;i=Fd(i)}let r=await Hi(t.cwd),n=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!n||n.submodule||n.conflict)return le("invalid_path",400);try{let s=await io(Nr(t.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return le("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return n}async function Hd(t,e,i){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new H("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return ro(t,async()=>{let n=await Ge(t);if(n.kind!=="repository")return le("invalid_path",404);i(n.root);let s=await $n(n.cwd);if(s.version!==e.expected)return le("state_changed");if(s.blocked)return le(s.blocked);let a,o;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return le("invalid_path",400);let p=await uS(n,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return le("state_changed");let d=[e.path];r==="unstage"&&p.originalPath&&(ui(p.originalPath),d.push(p.originalPath)),a=r==="stage"?["add","--",...d]:s.head?["restore","--staged","--",...d]:["rm","--cached","-f","--ignore-unmatch","--",...d]}else if(r==="commit"){if(n.scope)return le("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return le("invalid_message",400);if(e.coAuthor!==void 0&&typeof e.coAuthor!="boolean")throw new H("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");if(!s.staged)return le("nothing_staged",400);o=e.coAuthor?await pS(n.cwd,e.message):e.message,a=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.head)return le("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return le("invalid_branch",400);try{await ee(n.cwd,["check-ref-format","--branch",e.branch])}catch{return le("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return le("invalid_branch",400);let p=s.branches.find(m=>m.name===e.branch),d=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return le("branch_exists");if(r==="switch-branch"&&(!p||p.current))return le("invalid_branch",400);if(d&&n.scope)return le("root_required",400);if(d&&s.dirty)return le("dirty_worktree");if(p?.occupied)return le("branch_in_use");a=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:d?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let l=await $n(n.cwd);if(l.version!==e.expected||l.blocked)return le(l.blocked??"state_changed");i(n.root),await ee(n.cwd,a,2*1024*1024,{write:!0,input:o});let c=(await ee(n.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:c}})}import{createHash as mS}from"node:crypto";var Pr=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Gd="%H%x00%P%x00%an%x00%aI%x00%s",Wd=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function $d(t){let[e,i,r]=await Promise.all([ee(t,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),ee(t,["rev-parse","--verify","--quiet","HEAD"]).then(o=>o.trim(),()=>null),ee(t,["symbolic-ref","-q","HEAD"]).then(o=>o.trim(),()=>null)]),n=[];for(let o of e.split(`
513
- `).filter(Boolean)){let[l,c,p,d,m]=o.split("\0"),g=c==="commit"?p:d==="commit"?m:void 0;if(!g||!Pr.test(g))continue;let h=l.startsWith("refs/heads/")?"branch":l.startsWith("refs/remotes/")?"remote":"tag";n.push({name:l.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:g,kind:h})}if(n.length>512)throw new H("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...n.map(o=>o.hash),...i&&Pr.test(i)?[i]:[]])].sort(),a=mS("sha256").update(JSON.stringify({refs:n,head:i,symbolic:r})).digest("hex");return{refs:n,tips:s,head:i,snapshot:a}}function Vd(t){let[e,i,r,n,s]=t;if(!e||!Pr.test(e)||!i?.split(" ").filter(Boolean).every(a=>Pr.test(a)))throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:i.split(" ").filter(Boolean),author:r,authoredAt:n,subject:s}}async function zd(t,e={}){let i=e.limit??50;if(!Number.isInteger(i)||i<1||i>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await Ge(t),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await $d(r.cwd),a=0;if(e.cursor!==void 0){let d;try{d=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!d||typeof d.snapshot!="string"||!/^[a-f0-9]{64}$/.test(d.snapshot)||!Number.isInteger(d.offset)||d.offset<1||d.offset>1e4)throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(d.snapshot!==s.snapshot)throw new H("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);a=d.offset}let o={...n,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return o;let c=(await ee(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${Gd}`,`--max-count=${i+1}`,`--skip=${a}`,...s.tips,"--"])).split("\0");if(c.at(-1)===""&&c.pop(),c.length%5)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let d=0;d<c.length;d+=5)p.push(Vd(c.slice(d,d+5)));return o.commits=p.slice(0,i),p.length>i&&a+i<=1e4&&(o.nextCursor=Buffer.from(JSON.stringify({snapshot:s.snapshot,offset:a+i})).toString("base64url")),o}async function Kd(t,e){if(typeof e!="string"||!Pr.test(e))throw new H("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let i=await Ge(t);if(i.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await $d(i.cwd);if(!r.tips.length)throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await ee(i.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await ee(i.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return i}function Yd(t,e,i){if(!Number.isInteger(i)||i<0||i>=Math.max(1,e.length))throw new H("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[i],t]:[t]}async function Qd(t,e,i){let n=(await ee(t.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${Gd}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(n.at(-1)===""&&n.pop(),n.length!==10)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=Vd(n.slice(0,5)),a=Yd(e,s.parents,i),o=["diff-tree","--root","-r","--no-commit-id",...Wd],[l,c]=await Promise.all([ee(t.cwd,[...o,"--name-status","-z",...a,"--","."]),ee(t.cwd,[...o,"--numstat","-z",...a,"--","."])]),p=new Map;for(let g of c.split("\0").filter(Boolean)){let h=g.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);h&&p.set(h[3],[h[1]==="-"?null:Number(h[1]),h[2]==="-"?null:Number(h[2])])}let d=l.split("\0");if(d.at(-1)===""&&d.pop(),d.length%2)throw new H("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let m=[];for(let g=0;g<d.length&&m.length<1e3;g+=2){let h=d[g+1],[f,b]=p.get(h)??[null,null];m.push({path:h,status:d[g],additions:f,deletions:b})}return{...s,email:n[5],committer:n[6],committerEmail:n[7],committedAt:n[8],message:n[9],root:t.root,scope:t.scope,parentIndex:i,files:m,truncated:d.length>2e3}}async function Jd(t,e,i=0){return Qd(await Kd(t,e),e,i)}async function Xd(t,e,i,r=0){ui(i);let n=await Kd(t,e),s=await Qd(n,e,r),a=s.files.find(l=>l.path===i);if(!a)throw new H("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let o={hash:e,path:i,parentIndex:r,parentHash:s.parents[r]??null};if(a.additions===null)return{...o,kind:"binary"};try{let l=await ee(n.cwd,["diff-tree","--root","-r","--no-commit-id",...Wd,"--src-prefix=a/","--dst-prefix=b/","-p",...Yd(e,s.parents,r),"--",i],524288);return l.split(`
514
- `).length>1e4?{...o,kind:"too-large"}:l?{...o,kind:"text",patch:l}:{...o,kind:"empty"}}catch(l){if(l instanceof H&&l.status===413)return{...o,kind:"too-large"};throw l}}var Zd=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function eu(t,e,i){if(t.endsWith("/control"))return $n(e);if(t.endsWith("/status"))return Hi(e);if(t.endsWith("/history")){if(i.limit!==void 0&&typeof i.limit!="number"||i.cursor!==void 0&&typeof i.cursor!="string")throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return zd(e,{limit:i.limit,cursor:i.cursor})}if(t.endsWith("/diff")){if(typeof i.path!="string"||!["staged","unstaged","untracked"].includes(i.area))throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return jd(e,i.path,i.area)}if(typeof i.hash!="string"||i.parentIndex!==void 0&&(!Number.isInteger(i.parentIndex)||i.parentIndex<0))throw new H("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=i.parentIndex;if(t.endsWith("/commit-detail"))return Jd(e,i.hash,r);if(t.endsWith("/commit-diff")&&typeof i.path=="string")return Xd(e,i.hash,i.path,r);throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var zn=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),gS=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),tu={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},fS=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),hS=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function iu(t){return t==="/api/message"||t==="/api/prompt-queue"||t.startsWith("/api/provider/")||t.startsWith("/api/workspace/files/")||t.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(t)}function We(t){return t.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function rt(t){let e={};for(let i of fS){let r=t[i];i==="toolName"?typeof r=="string"&&(zn.has(r)||r==="custom")&&(e[i]=r):i==="failureKind"?gS.has(r)&&(e[i]=r):i==="level"?(r==="warning"||r==="error")&&(e[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[i]=r):i==="route"&&typeof r=="string"?e[i]=hS.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[i]=r.split("/").map(We).join("/"):typeof r=="string"?e[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:We(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[i]=r)}return e}function no(t){let e=t.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function Gi(t,e=0){let i=t instanceof Error?t:new Error(typeof t=="string"?t:"Non-Error rejection"),r=new Error(We(i.message));if(r.name=We(i.name).slice(0,100),i.stack){let n=i.stack.split(`
515
- `).slice(1,31).map(s=>{let a=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${We(s.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:We(s)});r.stack=`${r.name}: ${r.message}
511
+ `;return`${e.replace(/(?:\r?\n[^\S\r\n]*)+$/,"")}${i?r:r+r}${dS}${r}`}var le=(t,e=409)=>{throw new H("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,t)};async function gS(t){return Wd(Nr(t,(await ee(t,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function no(t,e,i=!1){let r=null;try{let n=await We(t);n.kind==="repository"&&(r=await gS(n.cwd))}catch(n){if(!i)throw n}if(!r)return e();if(io.has(r))return le("busy");io.add(r);try{return await e()}finally{io.delete(r)}}async function $n(t){let e=await We(t),i={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return i;let r=await Hi(e.root);if(r.kind!=="repository")return i;let[n,s,a]=await Promise.all([ee(e.cwd,["ls-files","--stage","-z"]),ee(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),ee(e.cwd,["rev-parse","--absolute-git-dir"])]),o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],l=(await Promise.all(o.map(async g=>{try{return await ro(Nr(a.replace(/\n$/,""),g)),g}catch(h){if(h.code==="ENOENT")return null;throw h}}))).filter(Boolean),c=await Promise.all(r.entries.map(async g=>{try{let h=await ro(Nr(e.root,g.path));return[g.path,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.mode]}catch(h){if(["ENOENT","ENOTDIR"].includes(h.code??""))return[g.path,"missing"];throw h}})),p=s.split(`
512
+ `).filter(Boolean).map(g=>{let[h,,f]=g.split("\0");return{name:h,current:h===r.branch,occupied:!!f&&h!==r.branch}}),d=r.truncated||p.length>512?"too_many_changes":l.includes("index.lock")?"index_locked":l.length||r.entries.some(g=>g.conflict)?"operation_in_progress":null,m=lS("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:n,refs:s,entries:r.entries,files:c,present:l})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:m,staged:r.entries.filter(g=>!g.untracked&&g.index!==".").length,dirty:r.entries.length>0,blocked:d,branches:p.slice(0,512)}}async function fS(t,e){ui(e);let i=Hd(Nr(t.cwd,e));for(;;)try{let s=await Wd(i),a=pS(t.cwd,s);if(a===".."||a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||cS(a))return le("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;i=Hd(i)}let r=await Hi(t.cwd),n=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!n||n.submodule||n.conflict)return le("invalid_path",400);try{let s=await ro(Nr(t.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return le("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return n}async function Gd(t,e,i){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new H("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return no(t,async()=>{let n=await We(t);if(n.kind!=="repository")return le("invalid_path",404);i(n.root);let s=await $n(n.cwd);if(s.version!==e.expected)return le("state_changed");if(s.blocked)return le(s.blocked);let a,o;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return le("invalid_path",400);let p=await fS(n,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return le("state_changed");let d=[e.path];r==="unstage"&&p.originalPath&&(ui(p.originalPath),d.push(p.originalPath)),a=r==="stage"?["add","--",...d]:s.head?["restore","--staged","--",...d]:["rm","--cached","-f","--ignore-unmatch","--",...d]}else if(r==="commit"){if(n.scope)return le("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return le("invalid_message",400);if(e.coAuthor!==void 0&&typeof e.coAuthor!="boolean")throw new H("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");if(!s.staged)return le("nothing_staged",400);o=e.coAuthor?await mS(n.cwd,e.message):e.message,a=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.head)return le("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return le("invalid_branch",400);try{await ee(n.cwd,["check-ref-format","--branch",e.branch])}catch{return le("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return le("invalid_branch",400);let p=s.branches.find(m=>m.name===e.branch),d=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return le("branch_exists");if(r==="switch-branch"&&(!p||p.current))return le("invalid_branch",400);if(d&&n.scope)return le("root_required",400);if(d&&s.dirty)return le("dirty_worktree");if(p?.occupied)return le("branch_in_use");a=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:d?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let l=await $n(n.cwd);if(l.version!==e.expected||l.blocked)return le(l.blocked??"state_changed");i(n.root),await ee(n.cwd,a,2*1024*1024,{write:!0,input:o});let c=(await ee(n.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:c}})}import{createHash as hS}from"node:crypto";var Pr=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,$d="%H%x00%P%x00%an%x00%aI%x00%s",Vd=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function zd(t){let[e,i,r]=await Promise.all([ee(t,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),ee(t,["rev-parse","--verify","--quiet","HEAD"]).then(o=>o.trim(),()=>null),ee(t,["symbolic-ref","-q","HEAD"]).then(o=>o.trim(),()=>null)]),n=[];for(let o of e.split(`
513
+ `).filter(Boolean)){let[l,c,p,d,m]=o.split("\0"),g=c==="commit"?p:d==="commit"?m:void 0;if(!g||!Pr.test(g))continue;let h=l.startsWith("refs/heads/")?"branch":l.startsWith("refs/remotes/")?"remote":"tag";n.push({name:l.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:g,kind:h})}if(n.length>512)throw new H("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...n.map(o=>o.hash),...i&&Pr.test(i)?[i]:[]])].sort(),a=hS("sha256").update(JSON.stringify({refs:n,head:i,symbolic:r})).digest("hex");return{refs:n,tips:s,head:i,snapshot:a}}function Kd(t){let[e,i,r,n,s]=t;if(!e||!Pr.test(e)||!i?.split(" ").filter(Boolean).every(a=>Pr.test(a)))throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:i.split(" ").filter(Boolean),author:r,authoredAt:n,subject:s}}async function Yd(t,e={}){let i=e.limit??50;if(!Number.isInteger(i)||i<1||i>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await We(t),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await zd(r.cwd),a=0;if(e.cursor!==void 0){let d;try{d=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!d||typeof d.snapshot!="string"||!/^[a-f0-9]{64}$/.test(d.snapshot)||!Number.isInteger(d.offset)||d.offset<1||d.offset>1e4)throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(d.snapshot!==s.snapshot)throw new H("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);a=d.offset}let o={...n,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return o;let c=(await ee(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${$d}`,`--max-count=${i+1}`,`--skip=${a}`,...s.tips,"--"])).split("\0");if(c.at(-1)===""&&c.pop(),c.length%5)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let d=0;d<c.length;d+=5)p.push(Kd(c.slice(d,d+5)));return o.commits=p.slice(0,i),p.length>i&&a+i<=1e4&&(o.nextCursor=Buffer.from(JSON.stringify({snapshot:s.snapshot,offset:a+i})).toString("base64url")),o}async function Qd(t,e){if(typeof e!="string"||!Pr.test(e))throw new H("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let i=await We(t);if(i.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await zd(i.cwd);if(!r.tips.length)throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await ee(i.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await ee(i.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return i}function Jd(t,e,i){if(!Number.isInteger(i)||i<0||i>=Math.max(1,e.length))throw new H("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[i],t]:[t]}async function Xd(t,e,i){let n=(await ee(t.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${$d}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(n.at(-1)===""&&n.pop(),n.length!==10)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=Kd(n.slice(0,5)),a=Jd(e,s.parents,i),o=["diff-tree","--root","-r","--no-commit-id",...Vd],[l,c]=await Promise.all([ee(t.cwd,[...o,"--name-status","-z",...a,"--","."]),ee(t.cwd,[...o,"--numstat","-z",...a,"--","."])]),p=new Map;for(let g of c.split("\0").filter(Boolean)){let h=g.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);h&&p.set(h[3],[h[1]==="-"?null:Number(h[1]),h[2]==="-"?null:Number(h[2])])}let d=l.split("\0");if(d.at(-1)===""&&d.pop(),d.length%2)throw new H("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let m=[];for(let g=0;g<d.length&&m.length<1e3;g+=2){let h=d[g+1],[f,b]=p.get(h)??[null,null];m.push({path:h,status:d[g],additions:f,deletions:b})}return{...s,email:n[5],committer:n[6],committerEmail:n[7],committedAt:n[8],message:n[9],root:t.root,scope:t.scope,parentIndex:i,files:m,truncated:d.length>2e3}}async function Zd(t,e,i=0){return Xd(await Qd(t,e),e,i)}async function eu(t,e,i,r=0){ui(i);let n=await Qd(t,e),s=await Xd(n,e,r),a=s.files.find(l=>l.path===i);if(!a)throw new H("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let o={hash:e,path:i,parentIndex:r,parentHash:s.parents[r]??null};if(a.additions===null)return{...o,kind:"binary"};try{let l=await ee(n.cwd,["diff-tree","--root","-r","--no-commit-id",...Vd,"--src-prefix=a/","--dst-prefix=b/","-p",...Jd(e,s.parents,r),"--",i],524288);return l.split(`
514
+ `).length>1e4?{...o,kind:"too-large"}:l?{...o,kind:"text",patch:l}:{...o,kind:"empty"}}catch(l){if(l instanceof H&&l.status===413)return{...o,kind:"too-large"};throw l}}var tu=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function iu(t,e,i){if(t.endsWith("/control"))return $n(e);if(t.endsWith("/status"))return Hi(e);if(t.endsWith("/history")){if(i.limit!==void 0&&typeof i.limit!="number"||i.cursor!==void 0&&typeof i.cursor!="string")throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return Yd(e,{limit:i.limit,cursor:i.cursor})}if(t.endsWith("/diff")){if(typeof i.path!="string"||!["staged","unstaged","untracked"].includes(i.area))throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return Bd(e,i.path,i.area)}if(typeof i.hash!="string"||i.parentIndex!==void 0&&(!Number.isInteger(i.parentIndex)||i.parentIndex<0))throw new H("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=i.parentIndex;if(t.endsWith("/commit-detail"))return Zd(e,i.hash,r);if(t.endsWith("/commit-diff")&&typeof i.path=="string")return eu(e,i.hash,i.path,r);throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var zn=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),yS=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ru={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},bS=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),_S=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function nu(t){return t==="/api/message"||t==="/api/prompt-queue"||t.startsWith("/api/provider/")||t.startsWith("/api/workspace/files/")||t.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(t)}function Ge(t){return t.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function rt(t){let e={};for(let i of bS){let r=t[i];i==="toolName"?typeof r=="string"&&(zn.has(r)||r==="custom")&&(e[i]=r):i==="failureKind"?yS.has(r)&&(e[i]=r):i==="level"?(r==="warning"||r==="error")&&(e[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[i]=r):i==="route"&&typeof r=="string"?e[i]=_S.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[i]=r.split("/").map(Ge).join("/"):typeof r=="string"?e[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:Ge(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[i]=r)}return e}function so(t){let e=t.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function Wi(t,e=0){let i=t instanceof Error?t:new Error(typeof t=="string"?t:"Non-Error rejection"),r=new Error(Ge(i.message));if(r.name=Ge(i.name).slice(0,100),i.stack){let n=i.stack.split(`
515
+ `).slice(1,31).map(s=>{let a=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${Ge(s.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:Ge(s)});r.stack=`${r.name}: ${r.message}
516
516
  ${n.join(`
517
- `)}`}else r.stack=void 0;return e<3&&i.cause!==void 0&&(r.cause=Gi(i.cause,e+1)),r}function xt(t,e){let i=new Error(e);return t instanceof Error&&(i.name=t.name,t.stack&&(i.stack=`${i.name}: ${e}
517
+ `)}`}else r.stack=void 0;return e<3&&i.cause!==void 0&&(r.cause=Wi(i.cause,e+1)),r}function xt(t,e){let i=new Error(e);return t instanceof Error&&(i.name=t.name,t.stack&&(i.stack=`${i.name}: ${e}
518
518
  ${t.stack.split(`
519
519
  `).slice(1).join(`
520
- `)}`)),i}function yS(t){return{...t.filename?{filename:no(t.filename)}:{},...t.abs_path?{abs_path:no(t.abs_path)}:{},...t.function?{function:We(t.function)}:{},lineno:t.lineno,colno:t.colno,in_app:t.in_app}}function bS(t){let e=rt(t.contexts?.diagnostic??{}),i=ru(e);return{event_id:t.event_id,timestamp:t.timestamp,platform:t.platform,level:t.level,release:t.release,dist:t.dist,environment:We(t.environment??"production"),...t.message?{message:We(t.message)}:{},exception:t.exception?{values:t.exception.values?.slice(0,4).map(r=>({type:We(r.type??"Error"),value:We(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(yS)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:t.tags?.side,buildId:t.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:e},breadcrumbs:t.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:We(r.category??"app"),data:rt(r.data??{})})),debug_meta:t.debug_meta?{images:t.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:no(r.code_file)}:{}}))}:void 0}}function ru(t){if(!(t.stage!=="tool"||t.originalStackAvailable!==!1||!t.toolName||!t.failureKind))return["pi-webapp-tool-result",String(t.toolName),String(t.toolId??"builtin"),String(t.failureKind),String(t.errorCode??"unknown")]}function nu(t,e){return e.attachments=[],bS(t)}var Cr=class{items=[];bytes=0;encoder=new TextEncoder;add(e,i={}){let r={timestamp:Date.now()/1e3,category:We(e),data:rt(i)},n=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:n}),this.bytes+=n;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},so=class{windowAt=-1;total=0;seen=new Map;take(e,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);let r=this.seen.get(e);if(r&&i-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:i,repeats:0}),{repeats:r?.repeats??0}}},_S=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function mi(t){return t instanceof Error&&(t.name==="AbortError"||_S.has(t.message))}var Vn=class{budget=new so;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,i,r,n,s=new Cr){this.client=e,this.side=i,this.buildId=r,this.scopeClass=n.Scope,this.breadcrumbs=s,e.addIntegration(n.linkedErrorsIntegration({limit:4}))}setState(e){this.state=rt(e)}capture(e,i={},r){try{if(mi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=Gi(e),s=rt({...this.state,...i}),a=ru(s),o=a?JSON.stringify(a):`${n.name}:${n.message}:${n.stack?.split(`
521
- `)[1]??""}:${i.stage??""}`,l=this.budget.take(o);if(!l)return;let c=new this.scopeClass;c.setClient(this.client),c.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&c.setLevel("warning"),a&&c.setFingerprint(a),c.setContext("diagnostic",{...s,repeats:l.repeats});for(let p of this.breadcrumbs.snapshot())c.addBreadcrumb(p,100);return c.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function su(t,e){return t({...e,bufferSize:20},async({body:i})=>{let r=await fetch(e.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var au={metadata:Id,routes:Zd,coordinateStart:(t,e)=>ro(t,e,!0),requestFailure:t=>t instanceof H?{status:t.status,body:{error:t.message,errorCode:"validation_error",reason:t.reason}}:null,async handle({path:t,body:e,snapshot:i,busyWorkspaces:r,json:n}){let s=i();if(e.sessionId!==s.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let a=p=>!i().idle||r().some(d=>{let m=(g,h)=>{let f=wS(g,h);return f!==".."&&!f.startsWith("../")&&!f.startsWith("..\\")&&!vS(f)};return m(p,d)||m(d,p)}),o=p=>{let d=i();if(d.sessionId!==s.sessionId||d.cwd!==s.cwd)throw new H("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(a(p))throw new H("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},l=t.endsWith("/write"),c=l?await Hd(s.cwd,e,o):await eu(t,s.cwd,e);if(!l){let p=i();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(t.endsWith("/control")){let d=c;d.root&&a(d.root)&&(d.blocked??="agent_busy")}}n(200,c)}catch(a){if(a instanceof H||a instanceof X)n(a.status,{error:a.message,errorCode:"validation_error",...a instanceof H?{reason:a.reason}:{}});else throw xt(a,"Git \u64CD\u4F5C\u5931\u8D25")}}};var ou={id:He.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as SS,open as kS,opendir as ES,realpath as TS}from"node:fs/promises";import{join as pu}from"node:path";var IS=5e3,ao=2e4,lu=100,cu=200,AS=5e3,xS=512*1024,OS=4e3,RS=240,NS=new Set([".git","node_modules",".hg",".svn"]);function PS(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}function CS(t,e){return t==="D"||e==="D"?t==="A"?"added":"deleted":t==="A"&&(e==="."||e==="M")?"added":"modified"}async function du(t){let e;try{e=await Ge(t)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let i;try{i=await ee(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},n=i.split("\0");for(let s=0;s<n.length;s++){let a=n[s],o=a[0];if(!["1","2","u","?","!"].includes(o??""))continue;let l=o==="?"||o==="!"?1:o==="1"?8:o==="2"?9:10,c=0;for(let g=0;g<l;g++)c=a.indexOf(" ",c)+1;o==="2"&&s++;let p=PS(e.scope,a.slice(c));if(!p)continue;if(r.entries.length===IS){r.truncated=!0;break}let d=a.slice(2,4),m=o==="?"?"untracked":o==="!"?"ignored":o==="u"?"conflict":CS(d[0],d[1]);r.entries.push({path:p,state:m})}return r}async function DS(t){let e=await TS(t),i;try{i=await Ge(e)}catch{i=void 0}if(i?.kind==="repository")try{let a=(await ee(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:a.slice(0,ao),truncated:a.length>ao}}catch(s){if(!(s instanceof H))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),a;try{a=await ES(pu(e,s))}catch{continue}for await(let o of a){let l=s?`${s}/${o.name}`:o.name;if(o.isDirectory())NS.has(o.name)||n.push(l);else if(o.isFile()){if(r.length===ao)return{root:e,paths:r,truncated:!0};r.push(l)}}}return{root:e,paths:r,truncated:!1}}function MS(t,e){let i=t.toLowerCase(),r=i.slice(i.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(i.includes(e))return 3;let n=0;for(let s of e)if(n=i.indexOf(s,n)+1,!n)return;return 4}async function uu(t,e,i){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new X("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(i!=="name"&&i!=="content")throw new X("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:a}=await DS(t);if(i==="name"){let d=s.flatMap(m=>{let g=MS(m,r);return g===void 0?[]:[{path:m,score:g}]}).sort((m,g)=>m.score-g.score||m.path.length-g.path.length||m.path.localeCompare(g.path));return{kind:"name",results:d.slice(0,lu).map(({path:m})=>({path:m})),truncated:a||d.length>lu}}let o=[],l=Date.now()+OS,c=0,p=a;for(let d of s){if(o.length>=cu||c>=AS||Date.now()>l){p=!0;break}let m=pu(n,d);try{let g=await SS(m);if(!g.isFile()||g.size===0||g.size>xS)continue;c++;let h=await kS(m,"r"),f;try{f=await h.readFile()}finally{await h.close()}if(f.includes(0))continue;let b=f.toString("utf8").split(`
522
- `);for(let S=0;S<b.length;S++){let E=b[S],A=E.toLowerCase().indexOf(r);if(A<0)continue;let C=Math.max(0,A-60);if(o.push({path:d,line:S+1,text:(C?"\u2026":"")+E.slice(C,C+RS).replace(/\r$/u,"")}),o.length>=cu)break}}catch{}}return{kind:"content",results:o,truncated:p}}var Wi="/api/local-file-actions",mu="X-Pi-Local-Files";import{execFile as JS,spawn as XS}from"node:child_process";import{createHash as ZS}from"node:crypto";import{realpath as ek}from"node:fs";import{lstat as tk}from"node:fs/promises";import{posix as xu,win32 as co}from"node:path";import{promisify as Ou}from"node:util";var ik=Ou(ek.native),Ru=Ou(JS),be=()=>({ok:!1,reason:"failed"}),Kn=()=>({ok:!1,reason:"not-found"}),Au=t=>typeof t=="string"&&t.length>0&&t.length<=256,Nu=t=>/[<>:"|?*\x00-\x1f]|[. ]$|\.\{[0-9a-f-]+\}$/i.test(t)||/^(?:CON|PRN|AUX|NUL|COM[0-9¹²³]|LPT[0-9¹²³]) *(?:\.|$)/i.test(t);function rk(t,e){if(!t||typeof t!="object")return;let{sessionId:i,workspaceId:r,path:n,kind:s}=t;if(s!=="file"&&s!=="directory"||typeof n!="string"||n.length>4096||/[\\\0]/.test(n)||/^[a-z]:/i.test(n))return;let a=n===""?[]:n.split("/");if(!a.some(o=>!o||o==="."||o===".."||e==="win32"&&Nu(o))&&!(!a.length&&s!=="directory")){if(Au(i)&&!Object.hasOwn(t,"workspaceId"))return{sessionId:i,segments:a,kind:s};if(Au(r)&&!Object.hasOwn(t,"sessionId")&&!a.length)return{workspaceId:r,segments:a,kind:s}}}function Yn(t,e){return typeof t!="string"||t.includes("\0")?!1:e==="darwin"?xu.isAbsolute(t):/^[a-z]:[\\/]/i.test(t)&&t.slice(3).split(/[\\/]/).filter(Boolean).every(i=>!Nu(i))}async function nk(t){let{stdout:e}=await Ru("/usr/bin/osascript",["-l","JavaScript","-e",'ObjC.import("AppKit"); function run(argv) { return $.NSWorkspace.sharedWorkspace.isFilePackageAtPath(argv[0]) ? "package" : "folder"; }',"--",t],{timeout:3e3});return e.trim()==="folder"}function sk(t,e,i,r){let n=(c,p)=>i("/usr/bin/open",[...c,"--",p],{shell:!1,timeout:3e3});if(t==="darwin")return{showItemInFolder:c=>n(["-R"],c),openPath:async c=>(await n(["-a","Finder"],c),"")};let s=c=>Yn(c,"win32")&&c.length<=4096&&!/[,=%]/.test(c)&&c.slice(3).split(/[\\/]/).every(p=>!/^CON(?:IN|OUT)\$ *(?:\.|$)/i.test(p))&&co.normalize(c)===c,a=typeof e=="string"?e.replaceAll("/","\\"):void 0;a?.length>3&&a.endsWith("\\")&&(a=a.slice(0,-1));let o=s(a)&&co.join(a,"explorer.exe"),l=(c,p)=>{if(!o||!s(c)||c.length>3&&c.endsWith("\\"))return!1;let d=`${p?"/select,":"/e,"}${c.length===3?c:`"${c}"`}`;return new Promise(m=>{let g=r(o,[d],{argv0:`"${o}"`,cwd:a,shell:!1,windowsVerbatimArguments:!0,stdio:"ignore"});g.once("error",()=>m(!1)),g.once("spawn",()=>{g.unref(),m(!0)})})};return{showItemInFolder:c=>l(c,!0),openPath:async c=>await l(c,!1)?"":"failed"}}async function ak(t){if(t==="darwin"){let{listMacApps:r,openMacApp:n}=await Promise.resolve().then(()=>(_u(),bu));return{list:r,open:n}}let{listWindowsApps:e,openWindowsApp:i}=await Promise.resolve().then(()=>(Iu(),Tu));return{list:e,open:i}}var ok=t=>ZS("sha256").update(t).digest("base64url"),lk=/\.(?:app|application|bat|cmd|com|command|cpl|desktop|dll|exe|gadget|hta|inf|ins|isp|jar|jse|lnk|msc|msi|msp|pif|pkg|ps1|reg|scf|scr|shb|sct|url|vb[es]|vxd|webloc|ws[cfh])$/i;function ck(t){let e=new Map;for(let i of t){if(typeof i?.id!="string"||!i.id||i.id.length>4096||typeof i.name!="string")continue;let r=i.name.replace(/[\x00-\x1f\x7f]/g," ").trim().slice(0,120),n=ok(i.id);if(!r||e.has(n))continue;let s=typeof i.icon=="string"&&i.icon.length<=24e3&&/^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(i.icon)?i.icon:void 0;e.set(n,{nativeId:i.id,item:{id:n,name:r,...s&&{icon:s},...i.isDefault===!0&&{isDefault:!0}}})}return[...e.values()].sort((i,r)=>+!!r.item.isDefault-+!!i.item.isDefault||i.item.name.localeCompare(r.item.name)).slice(0,16)}function Pu({platform:t=process.platform,realpath:e=ik,inspect:i=tk,macFolder:r=nk,getApps:n=ak,systemRoot:s=process.env.SystemRoot,runFile:a=Ru,spawnProcess:o=XS,shell:l=sk(t,s,a,o)}={}){let c=t==="win32"?co:xu;return async(p,d,m,{lookupRoot:g,trusted:h})=>{try{if(t!=="darwin"&&t!=="win32"||p!=="show"&&p!=="list"&&p!=="open"||!h())return be();let f=rk(d,t);if(!f||p!=="show"&&!f.sessionId||p==="open"&&(typeof m!="string"||!/^[A-Za-z0-9_-]{43}$/.test(m)))return be();let b=await g(f);if(b===void 0)return Kn();if(!Yn(b,t))return be();let S=await e(b);if(!Yn(S,t)||!(await i(S)).isDirectory())return be();let E=f.segments.length?await e(c.join(S,...f.segments)):S,A=S.endsWith(c.sep)?S:S+c.sep;if(!Yn(E,t)||E!==S&&!E.startsWith(A))return be();let C=await i(E);if(f.kind==="directory"?!C.isDirectory():!C.isFile())return Kn();if(f.kind==="directory"&&t==="darwin"){if(!await r(E)||await e(E)!==E)return be();let N=await i(E);if(!N.isDirectory()||N.dev!==C.dev||N.ino!==C.ino)return be()}if(!h())return be();if(p!=="show"){if(f.kind==="file"&&lk.test(E))return p==="list"?{ok:!0,apps:[]}:be();let N=await n(t),R=ck(await N.list(E,f.kind));if(!h())return be();if(p==="list")return{ok:!0,apps:R.map(({item:x})=>x)};let G=R.find(({item:x})=>x.id===m);if(!G)return be();if(await g(f)!==b||await e(b)!==S||await e(c.join(S,...f.segments))!==E)return Kn();let I=await i(E);return C.dev!==I.dev||C.ino!==I.ino||!h()||await N.open(E,G.nativeId,f.kind)===!1?be():{ok:!0}}if(f.kind==="file"){if(await l.showItemInFolder(E)===!1)return be()}else if(await l.openPath(E)!=="")return be();return{ok:!0}}catch(f){return f?.code==="ENOENT"||f?.code==="ENOTDIR"?Kn():be()}}}var Cu=Pu();async function Du({body:t,localFileRequest:e,snapshot:i,json:r}){if(!e||!Cu){r(403,{ok:!1,reason:"failed"});return}let{operation:n,target:s,appId:a}=t;if(n!=="show"&&n!=="list"&&n!=="open"){r(400,{ok:!1,reason:"failed"});return}let o=i(),l=typeof s=="object"&&s!==null&&Object.hasOwn(s,"workspaceId");if(!l&&t.sessionId!==o.sessionId){r(409,{ok:!1,reason:"not-found"});return}let c=()=>{if(!e.trusted())return!1;if(l)return!0;let d=i();return d.sessionId===o.sessionId&&d.cwd===o.cwd},p=await Cu(n,s,a,{trusted:c,async lookupRoot(d){if(d.sessionId!==void 0)return d.sessionId===o.sessionId&&c()?o.cwd:void 0;let m=(await e.workspaces()).items.find(g=>g.id===d.workspaceId);return m?.available===!1?void 0:m?.path}});r(200,p)}var Mu={metadata:ou,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search",Wi],async handle(t){let{path:e,body:i,snapshot:r,json:n,res:s}=t;if(e===Wi)return Du(t);let a=r();if(i.sessionId!==a.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let o=e.slice(e.lastIndexOf("/")+1);if(!(o==="status"||o==="search")&&(typeof i.path!="string"||i.path.length>4096)){n(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let c=i.path,p=()=>{let d=r();return d.sessionId!==a.sessionId||d.cwd!==a.cwd};try{if(o==="raw"){let m=await Dd(a.cwd,c);if(p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}s.writeHead(200,{"Content-Type":m.mimeType,"Content-Length":m.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),s.end(m.bytes);return}if(o==="write"&&p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let d=o==="list"?await Pd(a.cwd,c):o==="write"?await Md(a.cwd,c,i.text,i.version):o==="status"?await du(a.cwd):o==="search"?await uu(a.cwd,i.query,i.mode):await Rr(a.cwd,c,eo);if(o!=="write"&&p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}n(200,d)}catch(d){if(d instanceof X)n(d.status,{error:d.message,errorCode:"validation_error",...d.reason?{reason:d.reason}:{}});else throw xt(d,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Lu={id:He.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as ju,constants as po,statSync as Fu}from"node:fs";import{createRequire as bk}from"node:module";import{execFile as Bu}from"node:child_process";import{accessSync as pk,chmodSync as dk,constants as uk,statSync as mk}from"node:fs";import{createRequire as gk}from"node:module";import{dirname as fk,join as hk}from"node:path";var Uu=gk(import.meta.url);function yk(t){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let i=hk(t,e,"spawn-helper"),r;try{r=mk(i).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{pk(i,uk.X_OK)}catch{dk(i,r|73)}}}function qu(...t){return yk(fk(Uu.resolve("node-pty/package.json"))),Uu("node-pty").spawn(...t)}var Ot=class extends Error{reason;constructor(e,i,r){super(i,{cause:r}),this.reason=e}},Hu=bk(import.meta.url),uo=class{pid;pty;screen;serializer;followers=new Set;outputListeners=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,i,r,n,s,a,o,l){this.sessionId=e,this.abandoned=o,this.graceMs=l;let{Terminal:c}=Hu("@xterm/headless"),{SerializeAddon:p}=Hu("@xterm/addon-serialize");this.screen=new c({cols:r,rows:n,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let d=Object.fromEntries(Object.entries(process.env).filter(([m,g])=>g!==void 0&&!/^PI_WEBAPP_RESTART_/.test(m)));try{this.pty=qu(s,a,{name:"xterm-256color",cwd:i,cols:r,rows:n,env:{...d,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(m){throw this.screen.dispose(),new Ot("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",m)}this.pid=this.pty.pid,this.screen.onData(m=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(m)}),this.pty.onData(m=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(g=>{if(this.disposed){g();return}this.screen.write(m,()=>{this.broadcast({type:"output",data:m});for(let h of this.outputListeners)h(m);g()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(m=>this.pty.onExit(({exitCode:g,signal:h})=>{this.exit={type:"exit",exitCode:g,signal:h},this.pending.then(()=>{this.broadcast(this.exit);for(let f of this.outputListeners)f("");m()})})),this.scheduleExpiry()}broadcast(e){for(let i of this.followers)i(e)||this.followers.delete(i);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}get exitCode(){return this.exit?.exitCode}get running(){return!this.exit&&!this.disposed}settle(e,i,r,n){return new Promise(s=>{let a,o="",l=!n,c=()=>{clearTimeout(a),clearTimeout(d),this.outputListeners.delete(p),r?.removeEventListener("abort",c),s()},p=m=>{if(!this.running){c();return}!l&&o.length<64*1024&&(o+=m,l=n(o)),clearTimeout(a),l&&(a=setTimeout(c,e))},d=setTimeout(c,i);this.outputListeners.add(p),r?.addEventListener("abort",c,{once:!0}),r?.aborted?c():p("")})}async text(e){if(await this.pending,this.disposed)throw new Error("Terminal closed");let i=this.screen.buffer.active,r=i.length-1;for(;r>=0&&!i.getLine(r)?.translateToString(!0).trim();)r--;let n=[];for(let s=Math.max(0,r-e*4);s<=r;s++){let a=i.getLine(s);if(!a)continue;let o=a.translateToString(!0);a.isWrapped&&n.length?n[n.length-1]+=o:n.push(o)}return n.slice(-e).join(`
523
- `)}resize(e,i){this.exit||this.disposed||(this.pty.resize(e,i),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,i),this.broadcast({type:"resize",cols:e,rows:i}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>Bu("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let i=(await new Promise(n=>Bu("ps",["-axo","pid=,ppid="],(s,a)=>n(s?"":a)))).trim().split(`
524
- `).map(n=>n.trim().split(/\s+/).map(Number)),r=n=>i.filter(([,s])=>s===n).flatMap(([s])=>[...r(s),s]);for(let n of[...r(this.pid),this.pid])try{process.kill(n,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending;for(let e of this.outputListeners)e("");this.followers.clear(),this.screen.dispose()}},Qn=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,i,r,n,s){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,i);if(this.terminals.size>=32||[...this.terminals.values()].filter(c=>c.sessionId===i).length>=8)throw new Ot("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let a=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(ju(a,po.X_OK),!Fu(a).isFile())throw new Error("Not a shell file")}catch(c){throw new Ot("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",c)}try{if(!Fu(r).isDirectory())throw new Error("Not a directory");ju(r,po.R_OK|po.X_OK)}catch(c){throw new Ot("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",c)}let o=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),l=new uo(i,r,n,s,a,o,()=>{this.remove(e,i)},this.options.graceMs??5*6e4);return this.terminals.set(e,l),l}get(e,i){let r=this.terminals.get(e);if(!r||r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}resolve(e,i){if(e!==void 0)return{id:e,terminal:this.get(e,i)};let r=[...this.terminals].filter(([,n])=>n.sessionId===i&&n.running);if(r.length===1)return{id:r[0][0],terminal:r[0][1]};throw new Error(r.length?`This session has ${r.length} open terminals (${r.map(([n])=>n).join(", ")}); pass terminalId.`:"This session has no open terminal. Ask the user to open one in the workspace panel.")}async remove(e,i){let r=this.terminals.get(e);if(r){if(r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var Gu=(t,e)=>Number.isInteger(t)&&Number.isInteger(e)&&Number(t)>=2&&Number(t)<=500&&Number(e)>=1&&Number(e)<=300,Wu="terminal-input";async function $u(t,e,i,r,n,s){let a=(c,p)=>{i.writeHead(c,{"Content-Type":"application/json","Cache-Control":"no-store"}),i.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){a(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let o=t.slice(14),l=r();if(o!=="close"&&e.sessionId!==l.sessionId){a(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((o==="create"||o==="resize")&&!Gu(e.cols,e.rows)){a(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(o==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){a(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(o==="create"){n.create(e.id,e.sessionId,l.cwd,e.cols,e.rows),a(201,{id:e.id});return}if(o==="close"){await n.remove(e.id,e.sessionId),a(200,{closed:!0});return}let c=n.get(e.id,e.sessionId);if(o==="attach"){let p=!1,d;i.once("close",()=>{p=!0,d?.(),s.delete(i)}),d=await c.attach(m=>p?!1:(i.headersSent||i.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),i.writableLength>1024*1024?(i.destroy(),!1):(i.write(`${JSON.stringify(m)}
525
- `),!0))),p?d():s.add(i);return}if(o==="input")c.write(e.data);else if(o==="resize")c.resize(e.cols,e.rows);else{a(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}a(200,{accepted:!0})}catch(c){i.headersSent?i.end():a(400,{error:c instanceof Ot?c.message:o==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:c instanceof Ot?c.reason:o==="create"?"terminal_runtime_unavailable":void 0})}}var _k=/^[a-f0-9-]{36}$/i,Vu=32*1024,vk=300,wk=3e4,Yu=t=>t<32||t>=127&&t<=159,Qu=t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid terminal tool input");return t};function Ju(t){if(t!==void 0){if(typeof t!="string"||!_k.test(t))throw new Error("terminalId must be the terminal tab's contentId");return t}}function mo(t,e,i,r,n){if(t===void 0)return e;if(!Number.isInteger(t)||t<i||t>r)throw new Error(`${n} must be an integer from ${i} to ${r}`);return t}function Xn(t){let e=Qu(t);if(typeof e.text!="string")throw new Error("text must be a string");let i=e.text.replace(/\r\n?/g,`
520
+ `)}`)),i}function vS(t){return{...t.filename?{filename:so(t.filename)}:{},...t.abs_path?{abs_path:so(t.abs_path)}:{},...t.function?{function:Ge(t.function)}:{},lineno:t.lineno,colno:t.colno,in_app:t.in_app}}function wS(t){let e=rt(t.contexts?.diagnostic??{}),i=su(e);return{event_id:t.event_id,timestamp:t.timestamp,platform:t.platform,level:t.level,release:t.release,dist:t.dist,environment:Ge(t.environment??"production"),...t.message?{message:Ge(t.message)}:{},exception:t.exception?{values:t.exception.values?.slice(0,4).map(r=>({type:Ge(r.type??"Error"),value:Ge(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(vS)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:t.tags?.side,buildId:t.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:e},breadcrumbs:t.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:Ge(r.category??"app"),data:rt(r.data??{})})),debug_meta:t.debug_meta?{images:t.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:so(r.code_file)}:{}}))}:void 0}}function su(t){if(!(t.stage!=="tool"||t.originalStackAvailable!==!1||!t.toolName||!t.failureKind))return["pi-webapp-tool-result",String(t.toolName),String(t.toolId??"builtin"),String(t.failureKind),String(t.errorCode??"unknown")]}function au(t,e){return e.attachments=[],wS(t)}var Cr=class{items=[];bytes=0;encoder=new TextEncoder;add(e,i={}){let r={timestamp:Date.now()/1e3,category:Ge(e),data:rt(i)},n=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:n}),this.bytes+=n;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},ao=class{windowAt=-1;total=0;seen=new Map;take(e,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);let r=this.seen.get(e);if(r&&i-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:i,repeats:0}),{repeats:r?.repeats??0}}},SS=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function mi(t){return t instanceof Error&&(t.name==="AbortError"||SS.has(t.message))}var Vn=class{budget=new ao;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,i,r,n,s=new Cr){this.client=e,this.side=i,this.buildId=r,this.scopeClass=n.Scope,this.breadcrumbs=s,e.addIntegration(n.linkedErrorsIntegration({limit:4}))}setState(e){this.state=rt(e)}capture(e,i={},r){try{if(mi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=Wi(e),s=rt({...this.state,...i}),a=su(s),o=a?JSON.stringify(a):`${n.name}:${n.message}:${n.stack?.split(`
521
+ `)[1]??""}:${i.stage??""}`,l=this.budget.take(o);if(!l)return;let c=new this.scopeClass;c.setClient(this.client),c.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&c.setLevel("warning"),a&&c.setFingerprint(a),c.setContext("diagnostic",{...s,repeats:l.repeats});for(let p of this.breadcrumbs.snapshot())c.addBreadcrumb(p,100);return c.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function ou(t,e){return t({...e,bufferSize:20},async({body:i})=>{let r=await fetch(e.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var lu={metadata:xd,routes:tu,coordinateStart:(t,e)=>no(t,e,!0),requestFailure:t=>t instanceof H?{status:t.status,body:{error:t.message,errorCode:"validation_error",reason:t.reason}}:null,async handle({path:t,body:e,snapshot:i,busyWorkspaces:r,json:n}){let s=i();if(e.sessionId!==s.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let a=p=>!i().idle||r().some(d=>{let m=(g,h)=>{let f=ES(g,h);return f!==".."&&!f.startsWith("../")&&!f.startsWith("..\\")&&!kS(f)};return m(p,d)||m(d,p)}),o=p=>{let d=i();if(d.sessionId!==s.sessionId||d.cwd!==s.cwd)throw new H("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(a(p))throw new H("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},l=t.endsWith("/write"),c=l?await Gd(s.cwd,e,o):await iu(t,s.cwd,e);if(!l){let p=i();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(t.endsWith("/control")){let d=c;d.root&&a(d.root)&&(d.blocked??="agent_busy")}}n(200,c)}catch(a){if(a instanceof H||a instanceof X)n(a.status,{error:a.message,errorCode:"validation_error",...a instanceof H?{reason:a.reason}:{}});else throw xt(a,"Git \u64CD\u4F5C\u5931\u8D25")}}};var cu={id:He.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as TS,open as IS,opendir as AS,realpath as xS}from"node:fs/promises";import{join as uu}from"node:path";var OS=5e3,oo=2e4,pu=100,du=200,RS=5e3,NS=512*1024,PS=4e3,CS=240,DS=new Set([".git","node_modules",".hg",".svn"]);function MS(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}function LS(t,e){return t==="D"||e==="D"?t==="A"?"added":"deleted":t==="A"&&(e==="."||e==="M")?"added":"modified"}async function mu(t){let e;try{e=await We(t)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let i;try{i=await ee(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},n=i.split("\0");for(let s=0;s<n.length;s++){let a=n[s],o=a[0];if(!["1","2","u","?","!"].includes(o??""))continue;let l=o==="?"||o==="!"?1:o==="1"?8:o==="2"?9:10,c=0;for(let g=0;g<l;g++)c=a.indexOf(" ",c)+1;o==="2"&&s++;let p=MS(e.scope,a.slice(c));if(!p)continue;if(r.entries.length===OS){r.truncated=!0;break}let d=a.slice(2,4),m=o==="?"?"untracked":o==="!"?"ignored":o==="u"?"conflict":LS(d[0],d[1]);r.entries.push({path:p,state:m})}return r}async function US(t){let e=await xS(t),i;try{i=await We(e)}catch{i=void 0}if(i?.kind==="repository")try{let a=(await ee(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:a.slice(0,oo),truncated:a.length>oo}}catch(s){if(!(s instanceof H))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),a;try{a=await AS(uu(e,s))}catch{continue}for await(let o of a){let l=s?`${s}/${o.name}`:o.name;if(o.isDirectory())DS.has(o.name)||n.push(l);else if(o.isFile()){if(r.length===oo)return{root:e,paths:r,truncated:!0};r.push(l)}}}return{root:e,paths:r,truncated:!1}}function qS(t,e){let i=t.toLowerCase(),r=i.slice(i.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(i.includes(e))return 3;let n=0;for(let s of e)if(n=i.indexOf(s,n)+1,!n)return;return 4}async function gu(t,e,i){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new X("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(i!=="name"&&i!=="content")throw new X("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:a}=await US(t);if(i==="name"){let d=s.flatMap(m=>{let g=qS(m,r);return g===void 0?[]:[{path:m,score:g}]}).sort((m,g)=>m.score-g.score||m.path.length-g.path.length||m.path.localeCompare(g.path));return{kind:"name",results:d.slice(0,pu).map(({path:m})=>({path:m})),truncated:a||d.length>pu}}let o=[],l=Date.now()+PS,c=0,p=a;for(let d of s){if(o.length>=du||c>=RS||Date.now()>l){p=!0;break}let m=uu(n,d);try{let g=await TS(m);if(!g.isFile()||g.size===0||g.size>NS)continue;c++;let h=await IS(m,"r"),f;try{f=await h.readFile()}finally{await h.close()}if(f.includes(0))continue;let b=f.toString("utf8").split(`
522
+ `);for(let S=0;S<b.length;S++){let E=b[S],A=E.toLowerCase().indexOf(r);if(A<0)continue;let C=Math.max(0,A-60);if(o.push({path:d,line:S+1,text:(C?"\u2026":"")+E.slice(C,C+CS).replace(/\r$/u,"")}),o.length>=du)break}}catch{}}return{kind:"content",results:o,truncated:p}}var Gi="/api/local-file-actions",fu="X-Pi-Local-Files";import{execFile as ek,spawn as tk}from"node:child_process";import{createHash as ik}from"node:crypto";import{realpath as rk}from"node:fs";import{lstat as nk}from"node:fs/promises";import{posix as Ru,win32 as po}from"node:path";import{promisify as Nu}from"node:util";var sk=Nu(rk.native),Pu=Nu(ek),be=()=>({ok:!1,reason:"failed"}),Kn=()=>({ok:!1,reason:"not-found"}),Ou=t=>typeof t=="string"&&t.length>0&&t.length<=256,Cu=t=>/[<>:"|?*\x00-\x1f]|[. ]$|\.\{[0-9a-f-]+\}$/i.test(t)||/^(?:CON|PRN|AUX|NUL|COM[0-9¹²³]|LPT[0-9¹²³]) *(?:\.|$)/i.test(t);function ak(t,e){if(!t||typeof t!="object")return;let{sessionId:i,workspaceId:r,path:n,kind:s}=t;if(s!=="file"&&s!=="directory"||typeof n!="string"||n.length>4096||/[\\\0]/.test(n)||/^[a-z]:/i.test(n))return;let a=n===""?[]:n.split("/");if(!a.some(o=>!o||o==="."||o===".."||e==="win32"&&Cu(o))&&!(!a.length&&s!=="directory")){if(Ou(i)&&!Object.hasOwn(t,"workspaceId"))return{sessionId:i,segments:a,kind:s};if(Ou(r)&&!Object.hasOwn(t,"sessionId")&&!a.length)return{workspaceId:r,segments:a,kind:s}}}function Yn(t,e){return typeof t!="string"||t.includes("\0")?!1:e==="darwin"?Ru.isAbsolute(t):/^[a-z]:[\\/]/i.test(t)&&t.slice(3).split(/[\\/]/).filter(Boolean).every(i=>!Cu(i))}async function ok(t){let{stdout:e}=await Pu("/usr/bin/osascript",["-l","JavaScript","-e",'ObjC.import("AppKit"); function run(argv) { return $.NSWorkspace.sharedWorkspace.isFilePackageAtPath(argv[0]) ? "package" : "folder"; }',"--",t],{timeout:3e3});return e.trim()==="folder"}function lk(t,e,i,r){let n=(c,p)=>i("/usr/bin/open",[...c,"--",p],{shell:!1,timeout:3e3});if(t==="darwin")return{showItemInFolder:c=>n(["-R"],c),openPath:async c=>(await n(["-a","Finder"],c),"")};let s=c=>Yn(c,"win32")&&c.length<=4096&&!/[,=%]/.test(c)&&c.slice(3).split(/[\\/]/).every(p=>!/^CON(?:IN|OUT)\$ *(?:\.|$)/i.test(p))&&po.normalize(c)===c,a=typeof e=="string"?e.replaceAll("/","\\"):void 0;a?.length>3&&a.endsWith("\\")&&(a=a.slice(0,-1));let o=s(a)&&po.join(a,"explorer.exe"),l=(c,p)=>{if(!o||!s(c)||c.length>3&&c.endsWith("\\"))return!1;let d=`${p?"/select,":"/e,"}${c.length===3?c:`"${c}"`}`;return new Promise(m=>{let g=r(o,[d],{argv0:`"${o}"`,cwd:a,shell:!1,windowsVerbatimArguments:!0,stdio:"ignore"});g.once("error",()=>m(!1)),g.once("spawn",()=>{g.unref(),m(!0)})})};return{showItemInFolder:c=>l(c,!0),openPath:async c=>await l(c,!1)?"":"failed"}}async function ck(t){if(t==="darwin"){let{listMacApps:r,openMacApp:n}=await Promise.resolve().then(()=>(wu(),vu));return{list:r,open:n}}let{listWindowsApps:e,openWindowsApp:i}=await Promise.resolve().then(()=>(xu(),Au));return{list:e,open:i}}var pk=t=>ik("sha256").update(t).digest("base64url"),dk=/\.(?:app|application|bat|cmd|com|command|cpl|desktop|dll|exe|gadget|hta|inf|ins|isp|jar|jse|lnk|msc|msi|msp|pif|pkg|ps1|reg|scf|scr|shb|sct|url|vb[es]|vxd|webloc|ws[cfh])$/i;function uk(t){let e=new Map;for(let i of t){if(typeof i?.id!="string"||!i.id||i.id.length>4096||typeof i.name!="string")continue;let r=i.name.replace(/[\x00-\x1f\x7f]/g," ").trim().slice(0,120),n=pk(i.id);if(!r||e.has(n))continue;let s=typeof i.icon=="string"&&i.icon.length<=24e3&&/^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(i.icon)?i.icon:void 0;e.set(n,{nativeId:i.id,item:{id:n,name:r,...s&&{icon:s},...i.isDefault===!0&&{isDefault:!0}}})}return[...e.values()].sort((i,r)=>+!!r.item.isDefault-+!!i.item.isDefault||i.item.name.localeCompare(r.item.name)).slice(0,16)}function Du({platform:t=process.platform,realpath:e=sk,inspect:i=nk,macFolder:r=ok,getApps:n=ck,systemRoot:s=process.env.SystemRoot,runFile:a=Pu,spawnProcess:o=tk,shell:l=lk(t,s,a,o)}={}){let c=t==="win32"?po:Ru;return async(p,d,m,{lookupRoot:g,trusted:h})=>{try{if(t!=="darwin"&&t!=="win32"||p!=="show"&&p!=="list"&&p!=="open"||!h())return be();let f=ak(d,t);if(!f||p!=="show"&&!f.sessionId||p==="open"&&(typeof m!="string"||!/^[A-Za-z0-9_-]{43}$/.test(m)))return be();let b=await g(f);if(b===void 0)return Kn();if(!Yn(b,t))return be();let S=await e(b);if(!Yn(S,t)||!(await i(S)).isDirectory())return be();let E=f.segments.length?await e(c.join(S,...f.segments)):S,A=S.endsWith(c.sep)?S:S+c.sep;if(!Yn(E,t)||E!==S&&!E.startsWith(A))return be();let C=await i(E);if(f.kind==="directory"?!C.isDirectory():!C.isFile())return Kn();if(f.kind==="directory"&&t==="darwin"){if(!await r(E)||await e(E)!==E)return be();let N=await i(E);if(!N.isDirectory()||N.dev!==C.dev||N.ino!==C.ino)return be()}if(!h())return be();if(p!=="show"){if(f.kind==="file"&&dk.test(E))return p==="list"?{ok:!0,apps:[]}:be();let N=await n(t),R=uk(await N.list(E,f.kind));if(!h())return be();if(p==="list")return{ok:!0,apps:R.map(({item:x})=>x)};let W=R.find(({item:x})=>x.id===m);if(!W)return be();if(await g(f)!==b||await e(b)!==S||await e(c.join(S,...f.segments))!==E)return Kn();let I=await i(E);return C.dev!==I.dev||C.ino!==I.ino||!h()||await N.open(E,W.nativeId,f.kind)===!1?be():{ok:!0}}if(f.kind==="file"){if(await l.showItemInFolder(E)===!1)return be()}else if(await l.openPath(E)!=="")return be();return{ok:!0}}catch(f){return f?.code==="ENOENT"||f?.code==="ENOTDIR"?Kn():be()}}}var Mu=Du();async function Lu({body:t,localFileRequest:e,snapshot:i,json:r}){if(!e||!Mu){r(403,{ok:!1,reason:"failed"});return}let{operation:n,target:s,appId:a}=t;if(n!=="show"&&n!=="list"&&n!=="open"){r(400,{ok:!1,reason:"failed"});return}let o=i(),l=typeof s=="object"&&s!==null&&Object.hasOwn(s,"workspaceId");if(!l&&t.sessionId!==o.sessionId){r(409,{ok:!1,reason:"not-found"});return}let c=()=>{if(!e.trusted())return!1;if(l)return!0;let d=i();return d.sessionId===o.sessionId&&d.cwd===o.cwd},p=await Mu(n,s,a,{trusted:c,async lookupRoot(d){if(d.sessionId!==void 0)return d.sessionId===o.sessionId&&c()?o.cwd:void 0;let m=(await e.workspaces()).items.find(g=>g.id===d.workspaceId);return m?.available===!1?void 0:m?.path}});r(200,p)}var Uu={metadata:cu,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search",Gi],async handle(t){let{path:e,body:i,snapshot:r,json:n,res:s}=t;if(e===Gi)return Lu(t);let a=r();if(i.sessionId!==a.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let o=e.slice(e.lastIndexOf("/")+1);if(!(o==="status"||o==="search")&&(typeof i.path!="string"||i.path.length>4096)){n(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let c=i.path,p=()=>{let d=r();return d.sessionId!==a.sessionId||d.cwd!==a.cwd};try{if(o==="raw"){let m=await Ld(a.cwd,c);if(p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}s.writeHead(200,{"Content-Type":m.mimeType,"Content-Length":m.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),s.end(m.bytes);return}if(o==="write"&&p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let d=o==="list"?await Dd(a.cwd,c):o==="write"?await Ud(a.cwd,c,i.text,i.version):o==="status"?await mu(a.cwd):o==="search"?await gu(a.cwd,i.query,i.mode):await Rr(a.cwd,c,to);if(o!=="write"&&p()){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}n(200,d)}catch(d){if(d instanceof X)n(d.status,{error:d.message,errorCode:"validation_error",...d.reason?{reason:d.reason}:{}});else throw xt(d,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var qu={id:He.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as Bu,constants as uo,statSync as Hu}from"node:fs";import{createRequire as wk}from"node:module";import{execFile as Wu}from"node:child_process";import{accessSync as mk,chmodSync as gk,constants as fk,statSync as hk}from"node:fs";import{createRequire as yk}from"node:module";import{dirname as bk,join as _k}from"node:path";var ju=yk(import.meta.url);function vk(t){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let i=_k(t,e,"spawn-helper"),r;try{r=hk(i).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{mk(i,fk.X_OK)}catch{gk(i,r|73)}}}function Fu(...t){return vk(bk(ju.resolve("node-pty/package.json"))),ju("node-pty").spawn(...t)}var Ot=class extends Error{reason;constructor(e,i,r){super(i,{cause:r}),this.reason=e}},Gu=wk(import.meta.url),mo=class{pid;pty;screen;serializer;followers=new Set;outputListeners=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,i,r,n,s,a,o,l){this.sessionId=e,this.abandoned=o,this.graceMs=l;let{Terminal:c}=Gu("@xterm/headless"),{SerializeAddon:p}=Gu("@xterm/addon-serialize");this.screen=new c({cols:r,rows:n,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let d=Object.fromEntries(Object.entries(process.env).filter(([m,g])=>g!==void 0&&!/^PI_WEBAPP_RESTART_/.test(m)));try{this.pty=Fu(s,a,{name:"xterm-256color",cwd:i,cols:r,rows:n,env:{...d,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(m){throw this.screen.dispose(),new Ot("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",m)}this.pid=this.pty.pid,this.screen.onData(m=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(m)}),this.pty.onData(m=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(g=>{if(this.disposed){g();return}this.screen.write(m,()=>{this.broadcast({type:"output",data:m});for(let h of this.outputListeners)h(m);g()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(m=>this.pty.onExit(({exitCode:g,signal:h})=>{this.exit={type:"exit",exitCode:g,signal:h},this.pending.then(()=>{this.broadcast(this.exit);for(let f of this.outputListeners)f("");m()})})),this.scheduleExpiry()}broadcast(e){for(let i of this.followers)i(e)||this.followers.delete(i);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}get exitCode(){return this.exit?.exitCode}get running(){return!this.exit&&!this.disposed}settle(e,i,r,n){return new Promise(s=>{let a,o="",l=!n,c=()=>{clearTimeout(a),clearTimeout(d),this.outputListeners.delete(p),r?.removeEventListener("abort",c),s()},p=m=>{if(!this.running){c();return}!l&&o.length<64*1024&&(o+=m,l=n(o)),clearTimeout(a),l&&(a=setTimeout(c,e))},d=setTimeout(c,i);this.outputListeners.add(p),r?.addEventListener("abort",c,{once:!0}),r?.aborted?c():p("")})}async text(e){if(await this.pending,this.disposed)throw new Error("Terminal closed");let i=this.screen.buffer.active,r=i.length-1;for(;r>=0&&!i.getLine(r)?.translateToString(!0).trim();)r--;let n=[];for(let s=Math.max(0,r-e*4);s<=r;s++){let a=i.getLine(s);if(!a)continue;let o=a.translateToString(!0);a.isWrapped&&n.length?n[n.length-1]+=o:n.push(o)}return n.slice(-e).join(`
523
+ `)}resize(e,i){this.exit||this.disposed||(this.pty.resize(e,i),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,i),this.broadcast({type:"resize",cols:e,rows:i}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>Wu("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let i=(await new Promise(n=>Wu("ps",["-axo","pid=,ppid="],(s,a)=>n(s?"":a)))).trim().split(`
524
+ `).map(n=>n.trim().split(/\s+/).map(Number)),r=n=>i.filter(([,s])=>s===n).flatMap(([s])=>[...r(s),s]);for(let n of[...r(this.pid),this.pid])try{process.kill(n,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending;for(let e of this.outputListeners)e("");this.followers.clear(),this.screen.dispose()}},Qn=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,i,r,n,s){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,i);if(this.terminals.size>=32||[...this.terminals.values()].filter(c=>c.sessionId===i).length>=8)throw new Ot("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let a=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(Bu(a,uo.X_OK),!Hu(a).isFile())throw new Error("Not a shell file")}catch(c){throw new Ot("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",c)}try{if(!Hu(r).isDirectory())throw new Error("Not a directory");Bu(r,uo.R_OK|uo.X_OK)}catch(c){throw new Ot("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",c)}let o=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),l=new mo(i,r,n,s,a,o,()=>{this.remove(e,i)},this.options.graceMs??5*6e4);return this.terminals.set(e,l),l}get(e,i){let r=this.terminals.get(e);if(!r||r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}resolve(e,i){if(e!==void 0)return{id:e,terminal:this.get(e,i)};let r=[...this.terminals].filter(([,n])=>n.sessionId===i&&n.running);if(r.length===1)return{id:r[0][0],terminal:r[0][1]};throw new Error(r.length?`This session has ${r.length} open terminals (${r.map(([n])=>n).join(", ")}); pass terminalId.`:"This session has no open terminal. Ask the user to open one in the workspace panel.")}async remove(e,i){let r=this.terminals.get(e);if(r){if(r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var $u=(t,e)=>Number.isInteger(t)&&Number.isInteger(e)&&Number(t)>=2&&Number(t)<=500&&Number(e)>=1&&Number(e)<=300,Vu="terminal-input";async function zu(t,e,i,r,n,s){let a=(c,p)=>{i.writeHead(c,{"Content-Type":"application/json","Cache-Control":"no-store"}),i.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){a(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let o=t.slice(14),l=r();if(o!=="close"&&e.sessionId!==l.sessionId){a(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((o==="create"||o==="resize")&&!$u(e.cols,e.rows)){a(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(o==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){a(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(o==="create"){n.create(e.id,e.sessionId,l.cwd,e.cols,e.rows),a(201,{id:e.id});return}if(o==="close"){await n.remove(e.id,e.sessionId),a(200,{closed:!0});return}let c=n.get(e.id,e.sessionId);if(o==="attach"){let p=!1,d;i.once("close",()=>{p=!0,d?.(),s.delete(i)}),d=await c.attach(m=>p?!1:(i.headersSent||i.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),i.writableLength>1024*1024?(i.destroy(),!1):(i.write(`${JSON.stringify(m)}
525
+ `),!0))),p?d():s.add(i);return}if(o==="input")c.write(e.data);else if(o==="resize")c.resize(e.cols,e.rows);else{a(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}a(200,{accepted:!0})}catch(c){i.headersSent?i.end():a(400,{error:c instanceof Ot?c.message:o==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:c instanceof Ot?c.reason:o==="create"?"terminal_runtime_unavailable":void 0})}}var Sk=/^[a-f0-9-]{36}$/i,Ku=32*1024,kk=300,Ek=3e4,Ju=t=>t<32||t>=127&&t<=159,Xu=t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid terminal tool input");return t};function Zu(t){if(t!==void 0){if(typeof t!="string"||!Sk.test(t))throw new Error("terminalId must be the terminal tab's contentId");return t}}function go(t,e,i,r,n){if(t===void 0)return e;if(!Number.isInteger(t)||t<i||t>r)throw new Error(`${n} must be an integer from ${i} to ${r}`);return t}function Xn(t){let e=Xu(t);if(typeof e.text!="string")throw new Error("text must be a string");let i=e.text.replace(/\r\n?/g,`
526
526
  `);if(Buffer.byteLength(i)>4096)throw new Error(`text is longer than ${4096} bytes`);if([...i].some(n=>n!==" "&&n!==`
527
- `&&Yu(n.charCodeAt(0))))throw new Error("text may not contain control characters other than tab and newline");if(e.enter!==void 0&&typeof e.enter!="boolean")throw new Error("enter must be a boolean");let r=e.enter??!0;if(!i&&!r)throw new Error("Nothing to send");return{terminalId:Ju(e.terminalId),text:i,enter:r,waitMs:mo(e.waitMs,3e3,0,wk,"waitMs"),lines:mo(e.lines,40,1,500,"lines")}}function zu(t){let e="";for(let i=0;i<t.length;i++){let r=t.charCodeAt(i);if(r===27){let n=t[i+1];if(n==="]"){for(i+=2;i<t.length&&t.charCodeAt(i)!==7&&t.charCodeAt(i)!==27;)i++;t.charCodeAt(i)===27&&i++}else if(n==="[")for(i+=2;i<t.length&&(t.charCodeAt(i)<64||t.charCodeAt(i)>126);)i++;else i+=n==="("||n===")"?2:1;continue}r===8?e=e.slice(0,-1):!Yu(r)&&!/\s/u.test(t[i])&&(e+=t[i])}return e}var Sk=t=>{let e=zu(t);return i=>{let r=zu(i);return!!r&&!e.startsWith(r)}};async function Ku(t,e,i){let r=await e.text(i),n=r.length>Vu;return{terminalId:t,output:n?r.slice(-Vu):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function Xu(t,e,i,r,n){if(i==="prepare"){let s=Xn(r),{id:a,terminal:o}=t.resolve(s.terminalId,e);if(!o.running)throw new Error("The terminal's shell has exited. Ask the user to open a new terminal.");return{terminalId:a}}if(i==="send"){let s=Xn(r);if(!s.terminalId)throw new Error("terminalId is required");let{id:a,terminal:o}=t.resolve(s.terminalId,e);return n?.throwIfAborted(),o.write(s.text.replace(/\n/g,"\r")+(s.enter?"\r":"")),s.waitMs&&await o.settle(vk,s.waitMs,n,Sk(s.text)),Ku(a,o,s.lines)}if(i==="read"){let s=Qu(r),{id:a,terminal:o}=t.resolve(Ju(s.terminalId),e);return Ku(a,o,mo(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${i}`)}function Zu(){let t=new Qn,e=new Set,i=async()=>{for(let r of e)r.end();e.clear(),await t.clear()};return{metadata:Lu,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,a,o)=>Xu(t,n,s,a,o),handle:r=>$u(r.path,r.body,r.res,r.snapshot,t,e),restartBlocker:()=>t.size?`\u6709 ${t.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:i,disable:i,async close(){await i(),await t.close()}}}import{randomUUID as kk}from"node:crypto";import{Type as Je}from"@earendil-works/pi-ai";var em=Je.String({pattern:"^[a-fA-F0-9-]{36}$",description:`The terminal tab's contentId, for example from the [pi-web workspace tab in view] line of kind "terminal". Optional when this session has exactly one open terminal.`}),tm=t=>Je.Optional(Je.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${t}).`}));function im(t,e=""){let i=t.exitCode===void 0?"":` The shell has exited with code ${t.exitCode}.`;return{content:[{type:"text",text:`${e}Terminal ${t.terminalId}${t.truncated?" (output truncated to the most recent part)":""}:${i}
528
- ${t.output}`}],details:t}}function rm(t){return[{name:"terminal_send",label:"terminal_send",description:`Type a command into one of the user's open workspace terminal tabs (their live interactive shell) and return the terminal's recent output. Use this when the user asks you to run something in "this"/"the" terminal they are looking at; for your own work use bash instead. The user must approve each call in the Web UI before anything is typed, so send one complete command at a time and do not assume it ran if the call fails. Enter is pressed after the text unless enter is false. Output is read after the terminal is quiet for a moment or waitMs passes; for long-running commands call terminal_read later.`,parameters:Je.Object({terminalId:Je.Optional(em),text:Je.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:Je.Optional(Je.Boolean({description:"Press Enter after the text (default true)."})),waitMs:Je.Optional(Je.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:tm(40)}),async execute(e,i,r,n,s){r?.throwIfAborted();let a=s.sessionManager.getSessionId(),o=Xn(i),{terminalId:l}=await t.run(s.cwd,a,"prepare",i,r),c={terminalId:l,text:o.text,enter:o.enter},p=await t.ask({requestId:kk(),sessionId:a,pluginId:He.terminal,kind:Wu,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return im(await t.run(s.cwd,a,"send",{...o,terminalId:l},r),"Sent after the user approved. ")}},{name:"terminal_read",label:"terminal_read",description:"Read the recent text of one of the user's open workspace terminal tabs (scrollback included, plain text). Use it to see what the user is looking at in a terminal or to check on a command started with terminal_send. Does not type anything.",parameters:Je.Object({terminalId:Je.Optional(em),lines:tm(100)}),async execute(e,i,r,n,s){return r?.throwIfAborted(),im(await t.run(s.cwd,s.sessionManager.getSessionId(),"read",i,r))}}]}function nm(t){let e={run:(...i)=>t.run(He.terminal,...i),ask:t.ask};return rm(e)}function sm(){return[Mu,Zu(),au]}import{createHash as Ek,randomUUID as Tk}from"node:crypto";import{mkdir as Ik,open as Ak,readFile as xk,rename as Ok,rm as am,writeFile as Rk}from"node:fs/promises";import{dirname as Nk}from"node:path";var ve=class extends Error{status;constructor(e,i=409){super(e),this.status=i}},es=class t{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await xk(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(i=>typeof i=="string"&&i.length>0&&i.length<=200))throw new ve("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return Ek("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,i,r,n){if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${Tk()}.tmp`,a=`${this.file}.lock`,o;try{if(r!==this.revision())throw new ve("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");n();let l=new Set(this.disabled);i?l.delete(e):l.add(e),await Ik(Nk(this.file),{recursive:!0});try{o=await Ak(a,"wx",384)}catch(p){throw p.code==="EEXIST"?new ve("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await o.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
529
- `);let c=new t(this.file);if(await c.load(),c.revision()!==r)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await Rk(s,JSON.stringify({version:1,disabled:[...l].sort()},null,2)+`
530
- `,{mode:384}),n(),await Ok(s,this.file),this.disabled=l}finally{this.changing=!1;try{await am(s,{force:!0})}finally{o&&(await o.close(),await am(a,{force:!0}))}}}};var ts=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,i){if(this.plugins=e,this.preferences=i,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,i){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===i&&!r.endsWith("/attach"))}external(e){let i=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!i.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>i.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let i=this.external(e);return{...i,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...i.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(i=>({...i.metadata,enabled:this.preferences.enabled(i.metadata.id),managed:!0})),...this.external(e).plugins.map(i=>({id:i.id,name:i.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,i,r,n){if(!this.plugins.some(s=>s.metadata.id===e))throw new ve("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new ve("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,i,r,n),i||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let i=this.plugins.find(n=>n.routes.includes(e.path));if(!i)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(i.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=i.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await i.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,i,r,n,s,a){let o=this.plugins.find(l=>l.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new ve("\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(i,r,n,s,a)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,i){if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let n=i;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let a=n;n=()=>s.coordinateStart(e,a)}try{return await n()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof ve)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let i of this.plugins){let r=i.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as Pk,opendir as Ck,stat as Dk}from"node:fs/promises";import{homedir as Mk}from"node:os";import{basename as Lk,dirname as om,join as lm,posix as Uk,resolve as cm,win32 as qk}from"node:path";function pm(t){return process.platform==="win32"?qk.isAbsolute(t)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(t):Uk.isAbsolute(t)}function jk(t,e,i){if(t.length===i&&e.name.localeCompare(t[t.length-1].name)>=0)return!0;let r=0,n=t.length;for(;r<n;){let s=r+n>>>1;e.name.localeCompare(t[s].name)<0?n=s:r=s+1}return t.splice(r,0,e),t.length<=i?!1:(t.pop(),!0)}async function dm(t){if(t!==void 0&&!pm(t))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=Mk(),i=cm(t??e),r=[];for(let l=i;;l=om(l)){let c=om(l);if(r.unshift({name:c===l?l:Lk(l),path:l,hidden:!1}),c===l)break}let n=[],s=!1,a=await Ck(i);for await(let l of a)!l.isDirectory()&&!l.isSymbolicLink()||jk(n,{name:l.name,isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()},1001)&&(s=!0);let o=[];for(let l of n){let c=lm(i,l.name);if(!l.isDirectory&&l.isSymbolicLink)try{if(!(await Dk(c)).isDirectory())continue}catch{continue}if(o.length===1e3){s=!0;break}o.push({name:l.name,path:c,hidden:l.name.startsWith(".")})}return{path:i,home:e,crumbs:r,entries:o,truncated:s}}async function um(t,e){if(!pm(t))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let i=lm(cm(t),e);return await Pk(i),i}import{execFile as Fk}from"node:child_process";import{accessSync as Bk,constants as Hk}from"node:fs";import{delimiter as Gk,join as Wk}from"node:path";var $k=(t,e,i)=>new Promise((r,n)=>{Fk(t,[...e],{encoding:"utf8",signal:i,windowsHide:!0},(s,a,o)=>{s?n(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:a,stderr:o})):r({stdout:a,stderr:o})})});function Vk(t){for(let e of(t??"").split(Gk))if(e)for(let i of["zenity","kdialog"])try{return Bk(Wk(e,i),Hk.X_OK),!0}catch{}return!1}function mm(t=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":t==="darwin"||t==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Vk(e.PATH)?"native":"browse"}function is(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}function zk(t){return typeof t=="object"&&t!==null&&"stderr"in t&&typeof t.stderr=="string"?t.stderr:""}function go(t){return t.replace(/[\r\n]+$/,"")||null}async function gm(t,e=process.platform,i=$k){if(e==="darwin")try{let r=await i("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],t);return go(r.stdout)}catch(r){if(!t.aborted&&is(r)===1&&/(?:User canceled|-128)/i.test(zk(r)))return null;throw r}if(e==="linux"){try{return go((await i("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(is(r)===1)return null;if(is(r)!=="ENOENT")throw r}try{return go((await i("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(is(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as Kk,randomUUID as Yk}from"node:crypto";import{mkdir as Qk,readFile as Jk,writeFile as Xk}from"node:fs/promises";import{join as fm}from"node:path";import{getAgentDir as Zk}from"@earendil-works/pi-coding-agent";var rs=20*1024*1024,hm=20,eE=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function tE(t){let e=t.indexOf("."),i=(e<0?t:t.slice(0,e)).replace(/[. ]+$/u,"");return eE.test(i)}function iE(t,e){let i=0,r="";for(let n of Buffer.from(t).toString("utf8")){let s=Buffer.byteLength(n);if(i+s>e)break;r+=n,i+=s}return r}function rE(t){if(t===void 0)return"file";let i=t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return tE(i)&&(i=`_${i}`),i=iE(i,255).replace(/[. ]+$/u,""),i===""||i==="."||i===".."?"file":i}function nE(t){return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":t.length>=3&&t.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":t.length>=6&&["GIF87a","GIF89a"].includes(t.toString("ascii",0,6))?"image/gif":t.length>=12&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function ym(t,e,i,r){if(r.byteLength===0||r.byteLength>rs)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=rE(e),s=Kk("sha256").update(r).digest("hex"),a=fm(Zk(),"pi-web","attachments",s);await Qk(a,{recursive:!0});let o=fm(a,n);try{await Xk(o,r,{flag:"wx",mode:384})}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="EEXIST"))throw l}return{id:Yk(),name:n,bytes:r.byteLength,path:o,mediaType:nE(r)??i.replace(/^image\//,"application/"),sessionId:t}}async function bm(t){return{type:"image",data:(await Jk(t.path)).toString("base64"),mimeType:t.mediaType}}import{randomBytes as sE}from"node:crypto";function _m(t,e,i){return t!=="openai-codex"||e!=="oauth"?i:{...i,prompt:r=>r.type==="select"&&r.options.some(n=>n.id==="browser")&&r.options.some(n=>n.id==="device_code")?Promise.resolve("browser"):i.prompt(r)}}var ns=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,i,r,n,s){let a=this.getActive();if(a){if(a.providerId===e&&a.method===i&&n===void 0)return a;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let o=sE(18).toString("base64url"),l={view:{id:o,providerId:e,method:i,status:"running"},controller:new AbortController};return this.flows.set(o,l),r(e,i,{signal:l.controller.signal,notify:c=>{l.view={...l.view,event:c,...c.type==="auth_url"||c.type==="device_code"?{authorization:c}:{}}},prompt:c=>{if(c.type==="secret"&&n!==void 0){let p=n;return n=void 0,Promise.resolve(p)}return new Promise((p,d)=>{let{signal:m,...g}=c;l.answer=p,l.reject=d,l.view={...l.view,status:"waiting",prompt:g},m?.aborted?d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):m?.addEventListener("abort",()=>d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{l.view.status!=="cancelled"&&(l.view={id:o,providerId:e,method:i,status:"done"})}).catch(c=>{if(l.view.status!=="cancelled"){let p=new Error("Provider login failed");c instanceof Error&&c.stack&&(p.stack=`${p.message}
527
+ `&&Ju(n.charCodeAt(0))))throw new Error("text may not contain control characters other than tab and newline");if(e.enter!==void 0&&typeof e.enter!="boolean")throw new Error("enter must be a boolean");let r=e.enter??!0;if(!i&&!r)throw new Error("Nothing to send");return{terminalId:Zu(e.terminalId),text:i,enter:r,waitMs:go(e.waitMs,3e3,0,Ek,"waitMs"),lines:go(e.lines,40,1,500,"lines")}}function Yu(t){let e="";for(let i=0;i<t.length;i++){let r=t.charCodeAt(i);if(r===27){let n=t[i+1];if(n==="]"){for(i+=2;i<t.length&&t.charCodeAt(i)!==7&&t.charCodeAt(i)!==27;)i++;t.charCodeAt(i)===27&&i++}else if(n==="[")for(i+=2;i<t.length&&(t.charCodeAt(i)<64||t.charCodeAt(i)>126);)i++;else i+=n==="("||n===")"?2:1;continue}r===8?e=e.slice(0,-1):!Ju(r)&&!/\s/u.test(t[i])&&(e+=t[i])}return e}var Tk=t=>{let e=Yu(t);return i=>{let r=Yu(i);return!!r&&!e.startsWith(r)}};async function Qu(t,e,i){let r=await e.text(i),n=r.length>Ku;return{terminalId:t,output:n?r.slice(-Ku):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function em(t,e,i,r,n){if(i==="prepare"){let s=Xn(r),{id:a,terminal:o}=t.resolve(s.terminalId,e);if(!o.running)throw new Error("The terminal's shell has exited. Ask the user to open a new terminal.");return{terminalId:a}}if(i==="send"){let s=Xn(r);if(!s.terminalId)throw new Error("terminalId is required");let{id:a,terminal:o}=t.resolve(s.terminalId,e);return n?.throwIfAborted(),o.write(s.text.replace(/\n/g,"\r")+(s.enter?"\r":"")),s.waitMs&&await o.settle(kk,s.waitMs,n,Tk(s.text)),Qu(a,o,s.lines)}if(i==="read"){let s=Xu(r),{id:a,terminal:o}=t.resolve(Zu(s.terminalId),e);return Qu(a,o,go(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${i}`)}function tm(){let t=new Qn,e=new Set,i=async()=>{for(let r of e)r.end();e.clear(),await t.clear()};return{metadata:qu,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,a,o)=>em(t,n,s,a,o),handle:r=>zu(r.path,r.body,r.res,r.snapshot,t,e),restartBlocker:()=>t.size?`\u6709 ${t.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:i,disable:i,async close(){await i(),await t.close()}}}import{randomUUID as Ik}from"node:crypto";import{Type as Je}from"@earendil-works/pi-ai";var im=Je.String({pattern:"^[a-fA-F0-9-]{36}$",description:`The terminal tab's contentId, for example from the [pi-web workspace tab in view] line of kind "terminal". Optional when this session has exactly one open terminal.`}),rm=t=>Je.Optional(Je.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${t}).`}));function nm(t,e=""){let i=t.exitCode===void 0?"":` The shell has exited with code ${t.exitCode}.`;return{content:[{type:"text",text:`${e}Terminal ${t.terminalId}${t.truncated?" (output truncated to the most recent part)":""}:${i}
528
+ ${t.output}`}],details:t}}function sm(t){return[{name:"terminal_send",label:"terminal_send",description:`Type a command into one of the user's open workspace terminal tabs (their live interactive shell) and return the terminal's recent output. Use this when the user asks you to run something in "this"/"the" terminal they are looking at; for your own work use bash instead. The user must approve each call in the Web UI before anything is typed, so send one complete command at a time and do not assume it ran if the call fails. Enter is pressed after the text unless enter is false. Output is read after the terminal is quiet for a moment or waitMs passes; for long-running commands call terminal_read later.`,parameters:Je.Object({terminalId:Je.Optional(im),text:Je.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:Je.Optional(Je.Boolean({description:"Press Enter after the text (default true)."})),waitMs:Je.Optional(Je.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:rm(40)}),async execute(e,i,r,n,s){r?.throwIfAborted();let a=s.sessionManager.getSessionId(),o=Xn(i),{terminalId:l}=await t.run(s.cwd,a,"prepare",i,r),c={terminalId:l,text:o.text,enter:o.enter},p=await t.ask({requestId:Ik(),sessionId:a,pluginId:He.terminal,kind:Vu,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return nm(await t.run(s.cwd,a,"send",{...o,terminalId:l},r),"Sent after the user approved. ")}},{name:"terminal_read",label:"terminal_read",description:"Read the recent text of one of the user's open workspace terminal tabs (scrollback included, plain text). Use it to see what the user is looking at in a terminal or to check on a command started with terminal_send. Does not type anything.",parameters:Je.Object({terminalId:Je.Optional(im),lines:rm(100)}),async execute(e,i,r,n,s){return r?.throwIfAborted(),nm(await t.run(s.cwd,s.sessionManager.getSessionId(),"read",i,r))}}]}function am(t){let e={run:(...i)=>t.run(He.terminal,...i),ask:t.ask};return sm(e)}function om(){return[Uu,tm(),lu]}import{createHash as Ak,randomUUID as xk}from"node:crypto";import{mkdir as Ok,open as Rk,readFile as Nk,rename as Pk,rm as lm,writeFile as Ck}from"node:fs/promises";import{dirname as Dk}from"node:path";var ve=class extends Error{status;constructor(e,i=409){super(e),this.status=i}},es=class t{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Nk(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(i=>typeof i=="string"&&i.length>0&&i.length<=200))throw new ve("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return Ak("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,i,r,n){if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${xk()}.tmp`,a=`${this.file}.lock`,o;try{if(r!==this.revision())throw new ve("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");n();let l=new Set(this.disabled);i?l.delete(e):l.add(e),await Ok(Dk(this.file),{recursive:!0});try{o=await Rk(a,"wx",384)}catch(p){throw p.code==="EEXIST"?new ve("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await o.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
529
+ `);let c=new t(this.file);if(await c.load(),c.revision()!==r)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await Ck(s,JSON.stringify({version:1,disabled:[...l].sort()},null,2)+`
530
+ `,{mode:384}),n(),await Pk(s,this.file),this.disabled=l}finally{this.changing=!1;try{await lm(s,{force:!0})}finally{o&&(await o.close(),await lm(a,{force:!0}))}}}};var ts=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,i){if(this.plugins=e,this.preferences=i,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,i){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===i&&!r.endsWith("/attach"))}external(e){let i=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!i.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>i.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let i=this.external(e);return{...i,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...i.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(i=>({...i.metadata,enabled:this.preferences.enabled(i.metadata.id),managed:!0})),...this.external(e).plugins.map(i=>({id:i.id,name:i.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,i,r,n){if(!this.plugins.some(s=>s.metadata.id===e))throw new ve("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new ve("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,i,r,n),i||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let i=this.plugins.find(n=>n.routes.includes(e.path));if(!i)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(i.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=i.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await i.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,i,r,n,s,a){let o=this.plugins.find(l=>l.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new ve("\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(i,r,n,s,a)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,i){if(this.changing)throw new ve("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let n=i;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let a=n;n=()=>s.coordinateStart(e,a)}try{return await n()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof ve)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let i of this.plugins){let r=i.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as Mk,opendir as Lk,stat as Uk}from"node:fs/promises";import{homedir as qk}from"node:os";import{basename as jk,dirname as cm,join as pm,posix as Fk,resolve as dm,win32 as Bk}from"node:path";function um(t){return process.platform==="win32"?Bk.isAbsolute(t)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(t):Fk.isAbsolute(t)}function Hk(t,e,i){if(t.length===i&&e.name.localeCompare(t[t.length-1].name)>=0)return!0;let r=0,n=t.length;for(;r<n;){let s=r+n>>>1;e.name.localeCompare(t[s].name)<0?n=s:r=s+1}return t.splice(r,0,e),t.length<=i?!1:(t.pop(),!0)}async function mm(t){if(t!==void 0&&!um(t))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=qk(),i=dm(t??e),r=[];for(let l=i;;l=cm(l)){let c=cm(l);if(r.unshift({name:c===l?l:jk(l),path:l,hidden:!1}),c===l)break}let n=[],s=!1,a=await Lk(i);for await(let l of a)!l.isDirectory()&&!l.isSymbolicLink()||Hk(n,{name:l.name,isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()},1001)&&(s=!0);let o=[];for(let l of n){let c=pm(i,l.name);if(!l.isDirectory&&l.isSymbolicLink)try{if(!(await Uk(c)).isDirectory())continue}catch{continue}if(o.length===1e3){s=!0;break}o.push({name:l.name,path:c,hidden:l.name.startsWith(".")})}return{path:i,home:e,crumbs:r,entries:o,truncated:s}}async function gm(t,e){if(!um(t))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let i=pm(dm(t),e);return await Mk(i),i}import{execFile as Wk}from"node:child_process";import{accessSync as Gk,constants as $k}from"node:fs";import{delimiter as Vk,join as zk}from"node:path";var Kk=(t,e,i)=>new Promise((r,n)=>{Wk(t,[...e],{encoding:"utf8",signal:i,windowsHide:!0},(s,a,o)=>{s?n(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:a,stderr:o})):r({stdout:a,stderr:o})})});function Yk(t){for(let e of(t??"").split(Vk))if(e)for(let i of["zenity","kdialog"])try{return Gk(zk(e,i),$k.X_OK),!0}catch{}return!1}function fm(t=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":t==="darwin"||t==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Yk(e.PATH)?"native":"browse"}function is(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}function Qk(t){return typeof t=="object"&&t!==null&&"stderr"in t&&typeof t.stderr=="string"?t.stderr:""}function fo(t){return t.replace(/[\r\n]+$/,"")||null}async function hm(t,e=process.platform,i=Kk){if(e==="darwin")try{let r=await i("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],t);return fo(r.stdout)}catch(r){if(!t.aborted&&is(r)===1&&/(?:User canceled|-128)/i.test(Qk(r)))return null;throw r}if(e==="linux"){try{return fo((await i("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(is(r)===1)return null;if(is(r)!=="ENOENT")throw r}try{return fo((await i("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(is(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as Jk,randomUUID as Xk}from"node:crypto";import{mkdir as Zk,readFile as eE,writeFile as tE}from"node:fs/promises";import{join as ym}from"node:path";import{getAgentDir as iE}from"@earendil-works/pi-coding-agent";var rs=20*1024*1024,bm=20,rE=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function nE(t){let e=t.indexOf("."),i=(e<0?t:t.slice(0,e)).replace(/[. ]+$/u,"");return rE.test(i)}function sE(t,e){let i=0,r="";for(let n of Buffer.from(t).toString("utf8")){let s=Buffer.byteLength(n);if(i+s>e)break;r+=n,i+=s}return r}function aE(t){if(t===void 0)return"file";let i=t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return nE(i)&&(i=`_${i}`),i=sE(i,255).replace(/[. ]+$/u,""),i===""||i==="."||i===".."?"file":i}function oE(t){return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":t.length>=3&&t.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":t.length>=6&&["GIF87a","GIF89a"].includes(t.toString("ascii",0,6))?"image/gif":t.length>=12&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function _m(t,e,i,r){if(r.byteLength===0||r.byteLength>rs)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=aE(e),s=Jk("sha256").update(r).digest("hex"),a=ym(iE(),"pi-web","attachments",s);await Zk(a,{recursive:!0});let o=ym(a,n);try{await tE(o,r,{flag:"wx",mode:384})}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="EEXIST"))throw l}return{id:Xk(),name:n,bytes:r.byteLength,path:o,mediaType:oE(r)??i.replace(/^image\//,"application/"),sessionId:t}}async function vm(t){return{type:"image",data:(await eE(t.path)).toString("base64"),mimeType:t.mediaType}}import{randomBytes as lE}from"node:crypto";function wm(t,e,i){return t!=="openai-codex"||e!=="oauth"?i:{...i,prompt:r=>r.type==="select"&&r.options.some(n=>n.id==="browser")&&r.options.some(n=>n.id==="device_code")?Promise.resolve("browser"):i.prompt(r)}}var ns=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,i,r,n,s){let a=this.getActive();if(a){if(a.providerId===e&&a.method===i&&n===void 0)return a;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let o=lE(18).toString("base64url"),l={view:{id:o,providerId:e,method:i,status:"running"},controller:new AbortController};return this.flows.set(o,l),r(e,i,{signal:l.controller.signal,notify:c=>{l.view={...l.view,event:c,...c.type==="auth_url"||c.type==="device_code"?{authorization:c}:{}}},prompt:c=>{if(c.type==="secret"&&n!==void 0){let p=n;return n=void 0,Promise.resolve(p)}return new Promise((p,d)=>{let{signal:m,...g}=c;l.answer=p,l.reject=d,l.view={...l.view,status:"waiting",prompt:g},m?.aborted?d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):m?.addEventListener("abort",()=>d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{l.view.status!=="cancelled"&&(l.view={id:o,providerId:e,method:i,status:"done"})}).catch(c=>{if(l.view.status!=="cancelled"){let p=new Error("Provider login failed");c instanceof Error&&c.stack&&(p.stack=`${p.message}
531
531
  ${c.stack.split(`
532
532
  `).slice(1).join(`
533
- `)}`);let d=this.reportError(p,{...s,stage:"provider_login"});l.view={id:o,providerId:e,method:i,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:d}}}),{...l.view}}get(e){let i=this.flows.get(e)?.view;return i?{...i}:void 0}getActive(){let e=[...this.flows.values()].find(({view:i})=>i.status==="running"||i.status==="waiting")?.view;return e?{...e}:void 0}respond(e,i){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===i))return!1;let n=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},n(i),!0}cancel(e){let i=this.flows.get(e);return!i||i.view.status==="done"||i.view.status==="error"?!1:(i.view={...i.view,status:"cancelled",prompt:void 0},i.controller.abort(),i.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),i.answer=void 0,i.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as aE}from"node:crypto";import{readFile as oE,rename as lE,rm as cE,stat as pE,writeFile as dE,mkdir as uE}from"node:fs/promises";import{dirname as mE}from"node:path";var gE=["openai-completions","openai-responses","anthropic-messages"];function fo(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!gE.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let i=new URL(e.baseUrl);return(i.protocol==="https:"||i.protocol==="http:")&&!!i.hostname&&!i.username&&!i.password&&!i.hash}catch{return!1}}async function vm(t,e){if(!fo(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let i;try{i=await oE(t,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}let r;if(i===void 0)r={providers:{}};else{try{r=JSON.parse(i)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let n={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await uE(mE(t),{recursive:!0});let s=i===void 0?384:(await pE(t)).mode&511,a=`${t}.pi-web-${aE(6).toString("hex")}.tmp`;try{await dE(a,`${JSON.stringify(n,null,2)}
534
- `,{mode:s,flag:"wx"}),await lE(a,t)}finally{await cE(a,{force:!0})}}import{randomBytes as fE}from"node:crypto";import{mkdir as hE,readFile as yE,rename as bE,rm as _E,stat as vE,writeFile as wE}from"node:fs/promises";import{dirname as SE}from"node:path";function wm(t){if(!t||t.length>2048)return!1;try{let e=new URL(t);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Sm(t){if(!t||typeof t!="object")return!1;let e=t;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&km(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&wm(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function km(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let i of[e.contextWindow,e.maxTokens])if(i!==void 0&&(!Number.isSafeInteger(i)||i<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(i=>i==="text"||i==="image")&&new Set(e.input).size===e.input.length}async function Em(t){let e;try{e=await yE(t,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let i;try{i=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:i,existing:e}}async function kE(t,e,i){await hE(SE(t),{recursive:!0});let r=i===void 0?384:(await vE(t)).mode&511,n=`${t}.pi-web-${fE(6).toString("hex")}.tmp`;try{await wE(n,`${JSON.stringify(e,null,2)}
535
- `,{mode:r,flag:"wx"}),await bE(n,t)}finally{await _E(n,{force:!0})}}async function Tm(t,e,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Em(t),n=r.providers[e],s=new Set(n?.models?.map(a=>a.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:i.getModels(e).map(a=>({id:a.id,name:a.name,contextWindow:a.contextWindow,maxTokens:a.maxTokens,input:[...a.input],source:s.has(a.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[a.id]}))}}async function Im(t,e,i,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await Em(t),a={...n.providers[e]??{}},o=[...a.models??[]],l={...a.modelOverrides??{}};if(i.action==="base_url"){if(i.baseUrl!==null&&!wm(i.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");i.baseUrl===null?delete a.baseUrl:a.baseUrl=i.baseUrl}else if(i.action==="save"){if(!km(i.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let c={id:i.model.id.trim(),...i.model.name===void 0?{}:{name:i.model.name},...i.model.contextWindow===void 0?{}:{contextWindow:i.model.contextWindow},...i.model.maxTokens===void 0?{}:{maxTokens:i.model.maxTokens},...i.model.input===void 0?{}:{input:i.model.input}},p=i.originalId,d=p===void 0?-1:o.findIndex(m=>m.id===p);if(p===void 0&&(o.some(m=>m.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(d>=0){if(c.id!==p&&(o.some(g=>g.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let m={...o[d],...c};for(let g of["name","contextWindow","maxTokens","input"])c[g]===void 0&&delete m[g];o[d]=m}else if(p!==void 0&&r.getModel(e,p)){if(c.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:m,...g}=c;l[p]={...l[p],...g};for(let h of["name","contextWindow","maxTokens","input"])c[h]===void 0&&delete l[p][h]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");o.push(c)}}else{let c=o.findIndex(p=>p.id===i.id);if(c>=0)o.splice(c,1);else if(Object.hasOwn(l,i.id))delete l[i.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}o.length?a.models=o:delete a.models,Object.keys(l).length?a.modelOverrides=l:delete a.modelOverrides,Object.keys(a).length?n.providers[e]=a:delete n.providers[e],await kE(t,n,s)}function Am(t){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(t.trim())}import{randomBytes as sv,createHash as dx}from"node:crypto";import{fileURLToPath as ux}from"node:url";var Mr="pi-webapp@0.1.58-alpha.5+8865989f300423e6c650",nt="8865989f300423e6c650";var mx="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function aa(t=process.env,e=console.warn){let i=r=>{let n={enabled:!1,environment:t.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Mr,buildId:nt},s=t[`PI_WEB_SENTRY_${r}_DSN`]??t.PI_WEB_SENTRY_DSN??mx;if(t.PI_WEB_SENTRY_ENABLED!=="true"||!s)return n;try{let a=new URL(s);if(a.protocol!=="https:"||!/^[\w-]+$/.test(a.username)||a.password||a.search||a.hash||!/\/(?:[\w-]+\/)*\d+$/.test(a.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:i("BROWSER"),node:i("NODE")}}var kt=class{config;ready;reporter;client;salt=sv(16);breadcrumbs=new Cr;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=aa(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let i=ux(import.meta.url).replace(/\\/g,"/"),r=i.lastIndexOf("/src/"),n=r>=0?i.slice(0,r+5):i.slice(0,i.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(i.endsWith("extension.js")?i:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=Promise.resolve().then(()=>(nv(),rv)).then(i=>{if(!this.closed){this.client=new i.NodeClient({...this.config.node,dist:nt,integrations:[],transport:e.transport??(r=>su(i.createTransport,r)),stackParser:i.defaultStackParser,beforeSend:nu,sendClientReports:!1,dataCollection:{...tu,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Vn(this.client,"node",nt,i,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,i={}){try{if(!this.enabled||mi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,i);if(this.early.length>=20)return;let r=sv(16).toString("hex");return this.early.push({error:Gi(e),context:rt(i),eventId:r}),r}catch{return}}setState(e){this.state=rt({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,i={}){this.enabled&&this.breadcrumbs.add(e,i)}session(e){return dx("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),i;try{await Promise.race([this.ready,new Promise(r=>{i=setTimeout(r,500)})])}finally{clearTimeout(i),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as Hx}from"@earendil-works/pi-coding-agent";function ei(t,e,i){if(i!==void 0&&i!=="steer"&&i!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(t.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!t.idle&&!i)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(i&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as hx}from"node:crypto";var av="[pi-web workspace tab in view] ",ov=' \u2014 The user wrote this while looking at that workspace tab. Read "this", "here" or "current" as its content, and when a tool can act on that content (for example read and patch the open drawing or file), act on it in place instead of creating something new.';function gx(t){return{title:t.title,kind:t.kind,contentId:t.contentId,...t.plugin?{plugin:t.plugin}:{},...t.detail?{detail:t.detail}:{},...t.reference?{reference:t.reference}:{}}}function fx(t){let e=t.endsWith(ov)?t.slice(0,-ov.length):t;try{let i=JSON.parse(e);if(typeof i.title!="string"||typeof i.kind!="string"||typeof i.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(i[r]!==void 0&&typeof i[r]!="string")return null;return gx(i)}catch{return null}}function kn(t){let e=[],i=t;for(;;){let n=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(i);if(!n||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(n[3]))break;let s;try{s=JSON.parse(n[2])}catch{break}e.unshift({name:s,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(s)}),i=i.slice(0,n.index)}let r=i.lastIndexOf(av);if(r!==-1&&(r===0||i.slice(r-2,r)===`
533
+ `)}`);let d=this.reportError(p,{...s,stage:"provider_login"});l.view={id:o,providerId:e,method:i,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:d}}}),{...l.view}}get(e){let i=this.flows.get(e)?.view;return i?{...i}:void 0}getActive(){let e=[...this.flows.values()].find(({view:i})=>i.status==="running"||i.status==="waiting")?.view;return e?{...e}:void 0}respond(e,i){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===i))return!1;let n=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},n(i),!0}cancel(e){let i=this.flows.get(e);return!i||i.view.status==="done"||i.view.status==="error"?!1:(i.view={...i.view,status:"cancelled",prompt:void 0},i.controller.abort(),i.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),i.answer=void 0,i.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as cE}from"node:crypto";import{readFile as pE,rename as dE,rm as uE,stat as mE,writeFile as gE,mkdir as fE}from"node:fs/promises";import{dirname as hE}from"node:path";var yE=["openai-completions","openai-responses","anthropic-messages"];function ho(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!yE.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let i=new URL(e.baseUrl);return(i.protocol==="https:"||i.protocol==="http:")&&!!i.hostname&&!i.username&&!i.password&&!i.hash}catch{return!1}}async function Sm(t,e){if(!ho(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let i;try{i=await pE(t,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}let r;if(i===void 0)r={providers:{}};else{try{r=JSON.parse(i)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let n={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await fE(hE(t),{recursive:!0});let s=i===void 0?384:(await mE(t)).mode&511,a=`${t}.pi-web-${cE(6).toString("hex")}.tmp`;try{await gE(a,`${JSON.stringify(n,null,2)}
534
+ `,{mode:s,flag:"wx"}),await dE(a,t)}finally{await uE(a,{force:!0})}}import{randomBytes as bE}from"node:crypto";import{mkdir as _E,readFile as vE,rename as wE,rm as SE,stat as kE,writeFile as EE}from"node:fs/promises";import{dirname as TE}from"node:path";function km(t){if(!t||t.length>2048)return!1;try{let e=new URL(t);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Em(t){if(!t||typeof t!="object")return!1;let e=t;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Tm(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&km(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Tm(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let i of[e.contextWindow,e.maxTokens])if(i!==void 0&&(!Number.isSafeInteger(i)||i<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(i=>i==="text"||i==="image")&&new Set(e.input).size===e.input.length}async function Im(t){let e;try{e=await vE(t,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let i;try{i=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:i,existing:e}}async function IE(t,e,i){await _E(TE(t),{recursive:!0});let r=i===void 0?384:(await kE(t)).mode&511,n=`${t}.pi-web-${bE(6).toString("hex")}.tmp`;try{await EE(n,`${JSON.stringify(e,null,2)}
535
+ `,{mode:r,flag:"wx"}),await wE(n,t)}finally{await SE(n,{force:!0})}}async function Am(t,e,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Im(t),n=r.providers[e],s=new Set(n?.models?.map(a=>a.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:i.getModels(e).map(a=>({id:a.id,name:a.name,contextWindow:a.contextWindow,maxTokens:a.maxTokens,input:[...a.input],source:s.has(a.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[a.id]}))}}async function xm(t,e,i,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await Im(t),a={...n.providers[e]??{}},o=[...a.models??[]],l={...a.modelOverrides??{}};if(i.action==="base_url"){if(i.baseUrl!==null&&!km(i.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");i.baseUrl===null?delete a.baseUrl:a.baseUrl=i.baseUrl}else if(i.action==="save"){if(!Tm(i.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let c={id:i.model.id.trim(),...i.model.name===void 0?{}:{name:i.model.name},...i.model.contextWindow===void 0?{}:{contextWindow:i.model.contextWindow},...i.model.maxTokens===void 0?{}:{maxTokens:i.model.maxTokens},...i.model.input===void 0?{}:{input:i.model.input}},p=i.originalId,d=p===void 0?-1:o.findIndex(m=>m.id===p);if(p===void 0&&(o.some(m=>m.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(d>=0){if(c.id!==p&&(o.some(g=>g.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let m={...o[d],...c};for(let g of["name","contextWindow","maxTokens","input"])c[g]===void 0&&delete m[g];o[d]=m}else if(p!==void 0&&r.getModel(e,p)){if(c.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:m,...g}=c;l[p]={...l[p],...g};for(let h of["name","contextWindow","maxTokens","input"])c[h]===void 0&&delete l[p][h]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");o.push(c)}}else{let c=o.findIndex(p=>p.id===i.id);if(c>=0)o.splice(c,1);else if(Object.hasOwn(l,i.id))delete l[i.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}o.length?a.models=o:delete a.models,Object.keys(l).length?a.modelOverrides=l:delete a.modelOverrides,Object.keys(a).length?n.providers[e]=a:delete n.providers[e],await IE(t,n,s)}function Om(t){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(t.trim())}import{randomBytes as ov,createHash as gx}from"node:crypto";import{fileURLToPath as fx}from"node:url";var Mr="pi-webapp@0.1.58+1f1b095becc8bbba6b6b",nt="1f1b095becc8bbba6b6b";var hx="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function aa(t=process.env,e=console.warn){let i=r=>{let n={enabled:!1,environment:t.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Mr,buildId:nt},s=t[`PI_WEB_SENTRY_${r}_DSN`]??t.PI_WEB_SENTRY_DSN??hx;if(t.PI_WEB_SENTRY_ENABLED!=="true"||!s)return n;try{let a=new URL(s);if(a.protocol!=="https:"||!/^[\w-]+$/.test(a.username)||a.password||a.search||a.hash||!/\/(?:[\w-]+\/)*\d+$/.test(a.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:i("BROWSER"),node:i("NODE")}}var St=class{config;ready;reporter;client;salt=ov(16);breadcrumbs=new Cr;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=aa(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let i=fx(import.meta.url).replace(/\\/g,"/"),r=i.lastIndexOf("/src/"),n=r>=0?i.slice(0,r+5):i.slice(0,i.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(i.endsWith("extension.js")?i:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=Promise.resolve().then(()=>(av(),sv)).then(i=>{if(!this.closed){this.client=new i.NodeClient({...this.config.node,dist:nt,integrations:[],transport:e.transport??(r=>ou(i.createTransport,r)),stackParser:i.defaultStackParser,beforeSend:au,sendClientReports:!1,dataCollection:{...ru,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Vn(this.client,"node",nt,i,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,i={}){try{if(!this.enabled||mi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,i);if(this.early.length>=20)return;let r=ov(16).toString("hex");return this.early.push({error:Wi(e),context:rt(i),eventId:r}),r}catch{return}}setState(e){this.state=rt({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,i={}){this.enabled&&this.breadcrumbs.add(e,i)}session(e){return gx("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),i;try{await Promise.race([this.ready,new Promise(r=>{i=setTimeout(r,500)})])}finally{clearTimeout(i),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as $x}from"@earendil-works/pi-coding-agent";function ei(t,e,i){if(i!==void 0&&i!=="steer"&&i!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(t.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!t.idle&&!i)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(i&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as _x}from"node:crypto";var lv="[pi-web workspace tab in view] ",cv=' \u2014 The user wrote this while looking at that workspace tab. Read "this", "here" or "current" as its content, and when a tool can act on that content (for example read and patch the open drawing or file), act on it in place instead of creating something new.';function yx(t){return{title:t.title,kind:t.kind,contentId:t.contentId,...t.plugin?{plugin:t.plugin}:{},...t.detail?{detail:t.detail}:{},...t.reference?{reference:t.reference}:{}}}function bx(t){let e=t.endsWith(cv)?t.slice(0,-cv.length):t;try{let i=JSON.parse(e);if(typeof i.title!="string"||typeof i.kind!="string"||typeof i.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(i[r]!==void 0&&typeof i[r]!="string")return null;return yx(i)}catch{return null}}function kn(t){let e=[],i=t;for(;;){let n=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(i);if(!n||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(n[3]))break;let s;try{s=JSON.parse(n[2])}catch{break}e.unshift({name:s,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(s)}),i=i.slice(0,n.index)}let r=i.lastIndexOf(lv);if(r!==-1&&(r===0||i.slice(r-2,r)===`
536
536
 
537
537
  `)&&!i.slice(r).includes(`
538
- `)){let n=fx(i.slice(r+av.length));if(n)return{text:i.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:i,attachments:e}}var En=t=>Buffer.byteLength(t.text)+t.images.reduce((e,i)=>e+i.data.length,0),Le=class extends Error{status=409},ti=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...kn(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,i=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+En(s),En({text:e,images:i}))>64*1024*1024)throw new Le("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:hx(),revision:1,text:e,images:i.map(n=>({...n})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new Le("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,i){let r=this.entries.find(n=>n.id===e);if(!r||r.revision!==i)throw new Le("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new Le("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,i,r,n){let s=this.find(e,i);if(r.kind==="remove"){this.entries=this.entries.filter(a=>a!==s),this.changed();return}if(r.kind==="edit"){let a=kn(s.text),o=s.text.slice(a.text.length).replace(/^\n\n/u,""),l=[r.text.trim(),o].filter(Boolean).join(`
538
+ `)){let n=bx(i.slice(r+lv.length));if(n)return{text:i.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:i,attachments:e}}var En=t=>Buffer.byteLength(t.text)+t.images.reduce((e,i)=>e+i.data.length,0),Le=class extends Error{status=409},ti=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...kn(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,i=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+En(s),En({text:e,images:i}))>64*1024*1024)throw new Le("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:_x(),revision:1,text:e,images:i.map(n=>({...n})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new Le("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,i){let r=this.entries.find(n=>n.id===e);if(!r||r.revision!==i)throw new Le("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new Le("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,i,r,n){let s=this.find(e,i);if(r.kind==="remove"){this.entries=this.entries.filter(a=>a!==s),this.changed();return}if(r.kind==="edit"){let a=kn(s.text),o=s.text.slice(a.text.length).replace(/^\n\n/u,""),l=[r.text.trim(),o].filter(Boolean).join(`
539
539
 
540
- `);if(this.validateText(l),this.entries.reduce((c,p)=>c+En(p),0)-En(s)+En({text:l,images:s.images})>64*1024*1024)throw new Le("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=l,s.revision++,delete s.error,this.changed();return}await this.deliver(s,n)}async deliver(e,i){e.status="sending",e.revision++,delete e.error,this.changed();try{await i(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,i){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,i)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,i)}})()}))}};var y=class extends Error{code;status;reason;constructor(e,i,r={}){super(i),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function fe(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var ii=t=>t.code==="ENOENT";var lv=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function dp(t,e,i,r){if(!t)throw new y("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return t.inventory();if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_input","Expected plugin request object",{status:400});let n=i;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(n.operation)))throw new y("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(n.operation!=="pollMany")return t.views(n);if(!Array.isArray(n.views)||!n.views.length||n.views.length>64||n.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new y("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(n.views.map(async s=>{try{return{reply:await t.views({...s,operation:"poll",immediate:!0})}}catch(a){return{failure:oa(a)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new y("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof n.id!="string"||!/^[a-f0-9-]{36}$/.test(n.id)||n.decision!=="allow"&&n.decision!=="deny")throw new y("invalid_input","Invalid approval decision",{status:400});if(!t.decide)throw new y("hosted_unavailable","Approvals are not available in this runtime",{status:503});return t.decide(n.id,n.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new y("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!t.secretAuth)throw new y("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(n.auth==="start"&&typeof n.pluginId=="string"&&n.pluginId.length<=214&&typeof n.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(n.name))return t.secretAuth({phase:"start",pluginId:n.pluginId,name:n.name});if((n.auth==="poll"||n.auth==="cancel")&&typeof n.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(n.deviceId))return t.secretAuth({phase:n.auth,deviceId:n.deviceId});throw new y("invalid_input","Invalid sign-in request",{status:400})}if(typeof n.pluginId!="string"||n.pluginId.length>214||typeof n.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(n.name)||!(n.value===null||typeof n.value=="string"&&n.value.length>=1&&n.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(n.value)))throw new y("invalid_input","Invalid secret request",{status:400});if(!t.secret)throw new y("hosted_unavailable","Secrets are not available in this runtime",{status:503});return t.secret(n.pluginId,n.name,n.value)}if(typeof n.pluginId!="string"||n.pluginId.length>214)throw new y("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new y("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof n.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(n.operation)||n.version!==void 0&&(typeof n.version!="string"||!/^\d+\.\d+\.\d+$/.test(n.version)))throw new y("invalid_input","Invalid plugin management request",{status:400});if(n.downloadId!==void 0&&(typeof n.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(n.downloadId))||n.operation==="cancel-download"&&!n.downloadId)throw new y("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new y("invalid_input","Invalid editor reopen consent",{status:400});if(n.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(n.updatePolicy)||n.operation==="policy"&&(typeof n.updatePolicy!="string"||n.updatePolicy==="pinned"&&!n.version))throw new y("invalid_input","Invalid update policy or missing exact pin",{status:400});return t.manage({pluginId:n.pluginId,operation:n.operation,...typeof n.downloadId=="string"?{downloadId:n.downloadId}:{},...typeof n.updatePolicy=="string"?{updatePolicy:n.updatePolicy}:{},...typeof n.version=="string"?{version:n.version}:{},...typeof n.reopenEditors=="boolean"?{reopenEditors:n.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof n.sessionId!="string"||!n.sessionId||n.sessionId.length>200||!Number.isSafeInteger(n.generation)||Number(n.generation)<1||typeof n.action!="string"||!/^[\w.-]{1,80}$/.test(n.action))throw new y("invalid_input","Invalid plugin action request",{status:400});if(n.viewToken!==void 0&&(typeof n.viewToken!="string"||n.viewToken.length>200)||n.mountId!==void 0&&(typeof n.mountId!="string"||n.mountId.length>200))throw new y("invalid_input","Invalid view flush capability",{status:400});return t.action({sessionId:n.sessionId,pluginId:n.pluginId,generation:Number(n.generation),action:n.action,input:n.input??{},...typeof n.viewToken=="string"?{viewToken:n.viewToken}:{},...typeof n.mountId=="string"?{mountId:n.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new y("invalid_route","Unknown hosted plugin route",{status:404})}function oa(t){let e=fe(t);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as cv}from"node:fs/promises";import{join as pv}from"node:path";async function dv(t){try{let e=JSON.parse(await cv(pv(t,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let i=new Set,r=await cv(pv(t,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let a of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof a=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(a)&&i.add(a);let n={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...i].map(s=>[`/${s}`,{path:s,type:n[s.split(".").pop()]}]))}catch{return{}}}import{access as bx,readFile as gv,realpath as pa,rename as D6,rm as M6,writeFile as L6}from"node:fs/promises";import{dirname as ca,join as Ft,resolve as _x,sep as mv}from"node:path";import{createRequire as vx}from"node:module";var yx=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function Et(t){let e=typeof t=="string"&&yx.exec(t);if(!e||e[0]!==t)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let i=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!i.every(Number.isSafeInteger)||r.some(n=>/^\d+$/.test(n)&&n.length>1&&n[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:i,prerelease:r}}function Ke(t,e){let i=Et(t),r=Et(e);for(let n=0;n<3;n++)if(i.core[n]!==r.core[n])return i.core[n]>r.core[n]?1:-1;if(!i.prerelease.length||!r.prerelease.length)return+!i.prerelease.length-+!r.prerelease.length;for(let n=0;n<Math.max(i.prerelease.length,r.prerelease.length);n++){let s=i.prerelease[n],a=r.prerelease[n];if(s===void 0||a===void 0)return s===void 0?-1:1;if(s===a)continue;let o=/^\d+$/.test(s),l=/^\d+$/.test(a);return o!==l?o?-1:1:o&&s.length!==a.length?s.length>a.length?1:-1:s>a?1:-1}return 0}function uv(t){try{return Et(t).prerelease.length===0}catch{return!1}}function la(t){try{return Et(t),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(t)}catch{return!1}}var ri=1;async function pr(t,e){let i=vx(Ft(t,"package.json"));for(let r of i.resolve.paths(e)??[]){let n=Ft(r,e);try{if(JSON.parse(await gv(Ft(n,"package.json"),"utf8")).name===e)return await pa(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function up(t,e){if(Ke(e?.version,e?.version),e.desktopProtocolVersion!==ri||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let i=await pa(_x(ca(e.launcher),"..")),r=await pa(Ft(t,"pi-web","releases")),n=ca(ca(i));if(await pa(e.launcher)!==Ft(i,"bin","pi-webapp.mjs")||ca(n)!==r||!n.startsWith(r+mv)||!n.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(n.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await gv(Ft(i,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==ri)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let a=await pr(i,"@earendil-works/pi-coding-agent");if(!a.startsWith(n+mv))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let o=Ft(a,"dist","bundle","cli.js");return await Promise.all([e.launcher,o,Ft(i,"dist","extension.js"),Ft(i,"web","dist","index.html")].map(l=>bx(l))),e.fallbackVersion!==void 0&&Et(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:o,desktopProtocolVersion:ri,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}ma();var ga="default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'",Lx="browser.wasm";function vv(t={}){return t.wasm?ga.replace("script-src 'self'","script-src 'self' 'wasm-unsafe-eval'"):ga}function wv(t){let e=t;return!!e&&e.browser?.wasm===!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(Lx)}var Gx={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function T(t,e,i){typeof i=="object"&&i!==null&&"error"in i&&(i={errorCode:e>=500?"server_error":"validation_error",...i,requestId:t.getHeader("X-Request-ID"),operationId:t.getHeader("X-Operation-ID")}),t.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),t.end(JSON.stringify(i))}function Wx(t,e){let i=t.headers.authorization;if(typeof i!="string"||!i.startsWith("Bearer "))return!1;let r=Buffer.from(i.slice(7),"utf8");return r.length===e.length&&Ux(r,e)}async function kv(t,e=64*1024){let i=0,r=[];for await(let n of t){let s=Buffer.isBuffer(n)?n:Buffer.from(n);if(i+=s.length,i>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function $x(t){let e=0,i=[];for await(let r of t){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=n.length,e>rs)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");i.push(n)}return Buffer.concat(i)}function Vx(t){if(!(!t||!/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i.test(t)))try{return new URL(`http://${t}`).origin}catch{return}}async function zx(t,e,i){await new Promise((n,s)=>{t.once("error",s),t.listen(e,i,()=>{t.off("error",s),n()})});let r=t.address();if(r===null||typeof r=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return r.port}async function Ev(t,e,i=new kt,r={}){i.setState({piVersion:Hx});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:Sv(24).toString("base64url"),a=Buffer.from(s),o=mm(),l=new Set,c=new es(r.pluginSettingsFile??yp(Bx(),"pi-web","plugins.json"));try{await c.load()}catch(k){throw await i.close(),k}let p=new ts(sm(),c),d=async()=>await t.plugins?.()??{plugins:[],errors:[]},m=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!c.enabled(k.metadata.id)).map(k=>k.metadata.id)}),g=()=>{for(let k of l)k.write(`${JSON.stringify(m())}
541
- `)},h=new Map,f=new ns((k,v)=>i.capture(k,v)),b=k=>i.setState({nodeVersion:process.version,platform:process.platform,session:i.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),S=process.env.PI_WEBAPP_LISTEN_HOST==="0.0.0.0"?"0.0.0.0":"127.0.0.1",E=S==="127.0.0.1"?r.localFileGrant:void 0,A="",C=!1,N=!1,R={...Gx,...await dv(e)};for(let k of await jx(yp(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!v)continue;let F={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};R[`/assets/${k}`]={path:`assets/${k}`,type:F[v[1]]}}let G=Fx(async(k,v)=>{let F=Sv(18).toString("base64"),W=ce=>typeof ce=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(ce),K=W(k.headers["x-request-id"])?k.headers["x-request-id"]:hp(),J={requestId:K,operationId:W(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",K),J.operationId&&v.setHeader("X-Operation-ID",J.operationId);let O="/",oe=performance.now(),se=(ce,It,Ar)=>{let _=!mi(ce)&&iu(O)?xt(ce,"Agent or provider operation failed"):ce,z=i.capture(_,{...J,route:O,method:k.method,status:It,stage:"http"});T(v,It,{error:Ar,errorId:z,errorReported:i.enabled,errorCode:mi(ce)?"validation_error":"unexpected_error"})};v.once("finish",()=>{O.startsWith("/api/telemetry/")||i.breadcrumb("request",{...J,route:O,method:k.method,status:v.statusCode,durationMs:Math.round(performance.now()-oe)})});try{let ce=S==="0.0.0.0"?Vx(k.headers.host):A;if(ce===void 0){T(v,403,{error:"\u4E3B\u673A\u5730\u5740\u4E0D\u5339\u914D"});return}let It=k.headers.origin===void 0||k.headers.origin===ce;v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${F}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${i.config.browser.dsn?` ${new URL(i.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{O=new URL(k.url??"/",A).pathname}catch{T(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let Ar=R[O];if(k.method==="GET"&&Ar){try{let _=await qx(yp(e,Ar.path));v.writeHead(200,{"Content-Type":Ar.type,"Cache-Control":"no-store"}),v.end(O==="/"?_.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${F}">`):_)}catch(_){se(_,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O.startsWith("/hosted-plugins/")){try{let _=await t.hosted?.asset(O);if(!_){T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy",_.csp??ga),v.writeHead(200,{"Content-Type":_.mime,"Cache-Control":"private, no-store"}),v.end(_.bytes)}catch{T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(k.method==="GET"&&O.startsWith("/plugins/")){try{let _=await t.pluginAsset?.(k.url??O);if(!_){T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":_.type,"Cache-Control":"no-store"}),v.end(_.bytes)}catch(_){se(_,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!O.startsWith("/api/")){T(v,404,{error:"\u672A\u627E\u5230"});return}if(!Wx(k,a)){T(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}let Ja=()=>!!E&&It&&k.headers.host===new URL(A).host&&k.socket.remoteAddress==="127.0.0.1"&&fp(E.key,s,k.headers[mu.toLowerCase()]);if(k.method==="GET"&&O===Wi){E&&Ja()?T(v,200,{platform:E.platform}):T(v,403,{error:"\u7CFB\u7EDF\u6587\u4EF6\u64CD\u4F5C\u4EC5\u9650\u5DF2\u6388\u6743\u7684\u672C\u673A\u684C\u9762"});return}if(k.method==="GET"&&O==="/api/hosted-plugins"){try{T(v,200,await dp(t.hosted,O,void 0))}catch(_){let z=oa(_);T(v,z.status,z.body)}return}if(k.method==="POST"&&lv.includes(O)){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let _;try{_=await kv(k,2*1024*1024)}catch(z){T(v,z instanceof Error&&z.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{T(v,200,await dp(t.hosted,O,_,{draining:C}))}catch(z){let D=oa(z);T(v,D.status,D.body)}return}if(k.method==="GET"&&O==="/api/telemetry/config"){T(v,200,i.config.browser);return}if(k.method==="GET"&&O==="/api/update/version"){try{T(v,200,{current:await t.selfUpdate?.runningVersion()??null,desktopProtocolVersion:ri,...t.selfUpdate?.launcherIdentity?{launcher:t.selfUpdate.launcherIdentity(),desktopHandoffProtocol:t.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(_){se(_,503,_ instanceof Error?_.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&O==="/api/update"){try{T(v,200,await t.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(_){se(_,503,_ instanceof Error?_.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&O==="/api/image"){let _=new URL(k.url??O,A),z=_.searchParams.get("sessionId")??"",D=_.searchParams.get("messageId")??"",j=Number(_.searchParams.get("index"));if(!z||z!==t.snapshot().sessionId||!D||!Number.isInteger(j)||j<0||j>100){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let Z=t.image?.(z,D,j);if(!Z||!["image/png","image/jpeg","image/webp","image/gif"].includes(Z.mimeType)){T(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":Z.mimeType,"Cache-Control":"private, no-store"}),v.end(Z.data);return}if(k.method==="POST"&&O==="/api/attachment"){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let _=new URL(k.url??O,A),z=_.searchParams.get("sessionId"),D=_.searchParams.get("name");try{if(!z||!D||D.length>1024||z!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>rs){T(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let j=await ym(z,D,k.headers["content-type"]??"application/octet-stream",await $x(k));if(z!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}h.set(j.id,j),T(v,201,{id:j.id,name:j.name,bytes:j.bytes})}catch(j){se(j,400,j instanceof Error?j.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&O==="/api/subagent-history"){let _=new URL(k.url??O,A).searchParams,z=_.get("workspaceId"),D=_.get("id");if(!z||!D||z.length>256||D.length>256){T(v,400,{error:"\u5B50\u4EFB\u52A1\u65E0\u6548"});return}try{let j=await t.subagentHistory?.(z,D);j?T(v,200,j):T(v,404,{error:"\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E0D\u53EF\u7528"})}catch(j){se(j,503,"\u65E0\u6CD5\u8BFB\u53D6\u5B50\u4EFB\u52A1\u8BB0\u5F55")}return}if(k.method==="GET"&&O==="/api/session"){try{let _=t.snapshot();b(_),T(v,200,_)}catch(_){se(_,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/plugin-management"){try{T(v,200,p.inventory(await d()))}catch(_){se(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/plugins"){try{T(v,200,p.catalog(await d()))}catch(_){se(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/providers"){try{T(v,200,await t.providers?.()??[])}catch(_){se(_,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/provider/models"){let _=new URL(k.url??O,A).searchParams.get("providerId")??"";try{if(!_||!t.providerModels){T(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}T(v,200,await t.providerModels(_))}catch(z){se(z,400,z instanceof Error?z.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/provider/login/active"){T(v,200,{active:f.getActive()??null});return}if(k.method==="GET"&&O==="/api/provider/login"){let _=new URL(k.url??O,A).searchParams.get("id")??"",z=f.get(_);T(v,z?200:404,z??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(O==="/api/models"||O==="/api/config"||O==="/api/workspaces"||O==="/api/commands")){try{T(v,200,O==="/api/models"?await t.models():O==="/api/config"?await t.config():O==="/api/commands"?t.commands?.()??[]:await t.workspaces())}catch(_){se(_,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/directory/capability"){T(v,200,{kind:o});return}if(k.method==="GET"&&O==="/api/events"){let _;try{_=t.snapshot(),b(_)}catch(z){se(z,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),l.add(v),v.write(`${JSON.stringify({type:"snapshot",session:_})}
542
- `),v.on("close",()=>l.delete(v));return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(O)){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let _;try{_=await kv(k,O==="/api/plugin-action"?544*1024:64*1024)}catch(D){if(D instanceof Error&&D.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){T(v,413,{error:D.message});return}if(D instanceof SyntaxError||mi(D)){T(v,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw D}if(O==="/api/desktop/handoff"){let D=_;if(!D||typeof D.nonce!="string"||typeof D.requestId!="string"){T(v,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!t.selfUpdate?.requestLauncherHandoff){T(v,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(C||N||f.getActive()){T(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let j=p.restartBlocker()??p.restartConfirmations()[0];if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||j){T(v,409,{error:j??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}C=!0;try{await t.selfUpdate.requestLauncherHandoff(D.nonce,D.requestId)}catch(Z){throw C=!1,Z}T(v,202,{accepted:!0,protocol:1,requestId:D.requestId});return}if(typeof _!="object"||_===null||!("sessionId"in _)||typeof _.sessionId!="string"){T(v,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(C&&O!=="/api/update/cancel"){T(v,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(O==="/api/plugin-management"){let D=_;if(typeof D.id!="string"||D.id.length>200||typeof D.enabled!="boolean"||typeof D.expected!="string"){T(v,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let j=()=>{if(t.snapshot().sessionId!==_.sessionId)throw new ve("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length)throw new ve("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(D.id,D.enabled,D.expected,j),T(v,200,p.inventory(await d()))}catch(Z){if(Z instanceof ve)T(v,Z.status,{error:Z.message});else throw Z}finally{g()}return}if(p.mutating&&O!=="/api/abort"){T(v,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}let z=O===Wi&&k.headers.origin===A&&Ja()?{workspaces:()=>t.workspaces(),trusted:()=>!C&&!v.destroyed}:void 0;if(await p.dispatch({path:O,body:_,res:v,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],localFileRequest:z,json:(D,j)=>T(v,D,j)}))return;if(O==="/api/plugin-interaction"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("requestId"in _)||typeof _.requestId!="string"||_.requestId.length>200||!t.resolvePluginInteraction||!("value"in _)){T(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(t.snapshot().cwd,async()=>t.resolvePluginInteraction(_.sessionId,_.pluginId,_.requestId,_.value)),T(v,200,{accepted:!0});return}if(O==="/api/plugin-action"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("action"in _)||typeof _.action!="string"||_.action.length>100){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(Z=>Z.metadata.id===_.pluginId)){let Z=p.actionRoute(_.pluginId,_.action);if(!Z){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let Te="input"in _?_.input:{};if(!Te||typeof Te!="object"||Array.isArray(Te)){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:Z,body:{...Te,sessionId:_.sessionId},res:v,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],json:(it,di)=>T(v,it,it>=200&&it<300?{value:di}:di)});return}if(!t.invokePluginAction){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let j=await p.coordinateStart(t.snapshot().cwd,async()=>t.invokePluginAction(_.sessionId,_.pluginId,_.action,"input"in _?_.input:void 0));T(v,200,{value:j});return}if(O==="/api/update/channel"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in _)||_.channel!=="stable"&&_.channel!=="alpha"){T(v,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!t.selfUpdate?.setChannel){T(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}T(v,200,await t.selfUpdate.setChannel(_.channel));return}if(O==="/api/update/cancel"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.selfUpdate?.cancel){T(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await t.selfUpdate.cancel(),T(v,200,{cancelled:!0,dataPreserved:!0});return}if(O==="/api/update"){if(N){T(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.snapshot().idle){T(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!t.selfUpdate){T(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let D=p.restartBlocker();if((t.busyGitWorkspaces?.()??[]).length||D){T(v,409,{error:D??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let j=_,Z="channel"in j||"version"in j||"allowDowngrade"in j;if(Z&&(j.channel!=="stable"&&j.channel!=="alpha"||typeof j.version!="string"||j.allowDowngrade!==void 0&&typeof j.allowDowngrade!="boolean")){T(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(j.force!==void 0&&typeof j.force!="boolean"){T(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let Te=j.force===!0,it=pe=>T(v,409,{error:pe.join("\uFF1B"),reason:"update_confirm_required"}),di=p.restartConfirmations();if(di.length&&!Te){it(di);return}N=!0;let xr;try{xr=await t.selfUpdate.prepare(Z?{channel:j.channel,version:j.version,allowDowngrade:j.allowDowngrade}:void 0);let pe=p.restartBlocker();if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||pe)throw new Error(pe??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let kd=p.restartConfirmations();if(kd.length&&!Te){it(kd);return}Te&&await p.releaseForRestart(),C=!0;try{await t.selfUpdate.requestRestart(xr,{force:Te})}catch(Ed){let Td=Ed?.code;if(!Te&&(Td==="view_barrier"||Td==="drain_pending")){C=!1,it(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw Ed}}catch(pe){throw C=!1,pe}finally{N=!1}T(v,202,{accepted:!0,version:xr.version});return}if(O==="/api/provider/custom"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in _)||!fo(_.provider)||!t.addCustomProvider){T(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await t.addCustomProvider(_.sessionId,_.provider),T(v,201,{accepted:!0});return}if(O==="/api/provider/models"||O==="/api/provider/logout"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in _)||typeof _.providerId!="string"){T(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(O==="/api/provider/models"){if(!("change"in _)||!Sm(_.change)||!t.updateProviderModel){T(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await t.updateProviderModel(_.sessionId,_.providerId,_.change)}else{if(!t.logoutProvider){T(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await t.logoutProvider(_.sessionId,_.providerId)}T(v,200,{accepted:!0});return}if(O.startsWith("/api/provider/login")){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(O==="/api/provider/login"){if(!("providerId"in _)||typeof _.providerId!="string"||!("method"in _)||_.method!=="api_key"&&_.method!=="oauth"||!t.loginProvider||!t.providers){T(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await t.providers()).some(Te=>Te.id===_.providerId&&Te.methods.includes(_.method))){T(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let j="initialSecret"in _?_.initialSecret:void 0;if(j!==void 0&&(_.method!=="api_key"||typeof j!="string"||!j.trim()||j.length>16384)){T(v,400,{error:"API Key \u65E0\u6548"});return}let Z=f.start(_.providerId,_.method,t.loginProvider,j,J);T(v,202,{id:Z.id});return}if(!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(O==="/api/provider/login/cancel"){T(v,f.cancel(_.id)?202:404,{accepted:!0});return}if(!("value"in _)||typeof _.value!="string"||_.value.length>16384||!f.respond(_.id,_.value)){T(v,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}T(v,202,{accepted:!0});return}if(O==="/api/attachment/remove"){if(!("id"in _)||typeof _.id!="string"||_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}h.get(_.id)?.sessionId===_.sessionId&&h.delete(_.id),T(v,202,{accepted:!0});return}if(O==="/api/directory/pick"){if(o!=="native"){T(v,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let D=new AbortController;v.once("close",()=>D.abort()),T(v,200,{path:await gm(D.signal)});return}if(O==="/api/directory/list"){if("path"in _&&(typeof _.path!="string"||_.path.length>4096)){T(v,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}T(v,200,await dm("path"in _?_.path:void 0));return}if(O==="/api/directory/create"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("name"in _)||typeof _.name!="string"||_.name.length>255){T(v,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}T(v,200,{path:await um(_.path,_.name)});return}if(O==="/api/workspace/add"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("create"in _)||typeof _.create!="boolean"){T(v,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await t.addWorkspace(_.path,_.create),T(v,202,{accepted:!0});return}if(O==="/api/workspace/select"||O==="/api/workspace/remove"||O==="/api/workspace/new-session"){if(!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}O==="/api/workspace/select"?await t.selectWorkspace(_.id):O==="/api/workspace/new-session"?await t.newSessionInWorkspace(_.id):await t.removeWorkspace(_.id),T(v,202,{accepted:!0});return}if(O==="/api/session/select"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await t.selectSession(_.workspaceId,_.id,_.path),T(v,202,{accepted:!0});return}if(O==="/api/session/rename"||O==="/api/session/delete"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"||_.path.length>4096){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(O==="/api/session/rename"){if(!("name"in _)||typeof _.name!="string"){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!t.renameSession){T(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await t.renameSession(_.workspaceId,_.id,_.path,_.name)}else{if(!t.deleteSession){T(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await t.deleteSession(_.workspaceId,_.id,_.path)}T(v,202,{accepted:!0});return}if(O==="/api/thinking-level"){if(!("level"in _)||typeof _.level!="string"){T(v,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await t.setThinkingLevel(_.sessionId,_.level)}else if(O==="/api/model"){if(!("provider"in _)||typeof _.provider!="string"||!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await t.setModel(_.sessionId,_.provider,_.id)}else if(O==="/api/config"){let D=_;if(!["packages","extensions","skills"].includes(D.kind)||!["global","project"].includes(D.scope)||!["add","remove"].includes(D.action)||typeof D.value!="string"||!D.value.trim()||D.value.length>2048){T(v,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(D.action==="add"&&D.kind!=="packages"&&Am(D.value)){T(v,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}T(v,200,await t.updateConfig(D));return}else if(O==="/api/prompt-queue"){let D=_,j=D.action;if(typeof D.id!="string"||D.id.length>100||!Number.isSafeInteger(D.revision)||D.revision<1||!j||typeof j!="object"||!["edit","remove","steer"].includes(j.kind)||j.kind==="edit"&&(typeof j.text!="string"||j.text.length>32e3)){T(v,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let Z=t.snapshot();if(D.sessionId!==Z.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(j.kind==="steer"&&Z.idle){T(v,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(j.kind==="steer"&&Z.interactions?.length){T(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.updateQueuedPrompt){T(v,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(Z.cwd,async()=>t.updateQueuedPrompt(_.sessionId,D.id,D.revision,j))}else if(O==="/api/message"){let D="delivery"in _?_.delivery:void 0;if(D!==void 0&&D!=="steer"&&D!=="followUp"){T(v,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let j="attachments"in _?_.attachments:[];if(!Array.isArray(j)||j.length>hm||j.some(pe=>typeof pe!="string")||new Set(j).size!==j.length){T(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let Z=j.map(pe=>h.get(pe));if(Z.some(pe=>!pe||pe.sessionId!==_.sessionId)){T(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in _)||typeof _.text!="string"||!_.text.trim()&&j.length===0||_.text.length>32e3){T(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let Te=t.snapshot();if(_.sessionId!==Te.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{ei(Te,_.text,D)}catch(pe){T(v,409,{error:pe.message});return}let it=Z,di=[_.text.trim(),...it.map(pe=>`\u9644\u4EF6 ${JSON.stringify(pe.name)}\uFF1A${pe.path}`)].filter(Boolean).join(`
540
+ `);if(this.validateText(l),this.entries.reduce((c,p)=>c+En(p),0)-En(s)+En({text:l,images:s.images})>64*1024*1024)throw new Le("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=l,s.revision++,delete s.error,this.changed();return}await this.deliver(s,n)}async deliver(e,i){e.status="sending",e.revision++,delete e.error,this.changed();try{await i(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,i){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,i)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,i)}})()}))}};var y=class extends Error{code;status;reason;constructor(e,i,r={}){super(i),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function ce(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var ii=t=>t.code==="ENOENT";var pv=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function up(t,e,i,r){if(!t)throw new y("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return t.inventory();if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_input","Expected plugin request object",{status:400});let n=i;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(n.operation)))throw new y("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(n.operation!=="pollMany")return t.views(n);if(!Array.isArray(n.views)||!n.views.length||n.views.length>64||n.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new y("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(n.views.map(async s=>{try{return{reply:await t.views({...s,operation:"poll",immediate:!0})}}catch(a){return{failure:oa(a)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new y("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof n.id!="string"||!/^[a-f0-9-]{36}$/.test(n.id)||n.decision!=="allow"&&n.decision!=="deny")throw new y("invalid_input","Invalid approval decision",{status:400});if(!t.decide)throw new y("hosted_unavailable","Approvals are not available in this runtime",{status:503});return t.decide(n.id,n.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new y("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!t.secretAuth)throw new y("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(n.auth==="start"&&typeof n.pluginId=="string"&&n.pluginId.length<=214&&typeof n.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(n.name))return t.secretAuth({phase:"start",pluginId:n.pluginId,name:n.name});if((n.auth==="poll"||n.auth==="cancel")&&typeof n.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(n.deviceId))return t.secretAuth({phase:n.auth,deviceId:n.deviceId});throw new y("invalid_input","Invalid sign-in request",{status:400})}if(typeof n.pluginId!="string"||n.pluginId.length>214||typeof n.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(n.name)||!(n.value===null||typeof n.value=="string"&&n.value.length>=1&&n.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(n.value)))throw new y("invalid_input","Invalid secret request",{status:400});if(!t.secret)throw new y("hosted_unavailable","Secrets are not available in this runtime",{status:503});return t.secret(n.pluginId,n.name,n.value)}if(typeof n.pluginId!="string"||n.pluginId.length>214)throw new y("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new y("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof n.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(n.operation)||n.version!==void 0&&(typeof n.version!="string"||!/^\d+\.\d+\.\d+$/.test(n.version)))throw new y("invalid_input","Invalid plugin management request",{status:400});if(n.downloadId!==void 0&&(typeof n.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(n.downloadId))||n.operation==="cancel-download"&&!n.downloadId)throw new y("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new y("invalid_input","Invalid editor reopen consent",{status:400});if(n.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(n.updatePolicy)||n.operation==="policy"&&(typeof n.updatePolicy!="string"||n.updatePolicy==="pinned"&&!n.version))throw new y("invalid_input","Invalid update policy or missing exact pin",{status:400});return t.manage({pluginId:n.pluginId,operation:n.operation,...typeof n.downloadId=="string"?{downloadId:n.downloadId}:{},...typeof n.updatePolicy=="string"?{updatePolicy:n.updatePolicy}:{},...typeof n.version=="string"?{version:n.version}:{},...typeof n.reopenEditors=="boolean"?{reopenEditors:n.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof n.sessionId!="string"||!n.sessionId||n.sessionId.length>200||!Number.isSafeInteger(n.generation)||Number(n.generation)<1||typeof n.action!="string"||!/^[\w.-]{1,80}$/.test(n.action))throw new y("invalid_input","Invalid plugin action request",{status:400});if(n.viewToken!==void 0&&(typeof n.viewToken!="string"||n.viewToken.length>200)||n.mountId!==void 0&&(typeof n.mountId!="string"||n.mountId.length>200))throw new y("invalid_input","Invalid view flush capability",{status:400});return t.action({sessionId:n.sessionId,pluginId:n.pluginId,generation:Number(n.generation),action:n.action,input:n.input??{},...typeof n.viewToken=="string"?{viewToken:n.viewToken}:{},...typeof n.mountId=="string"?{mountId:n.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new y("invalid_route","Unknown hosted plugin route",{status:404})}function oa(t){let e=ce(t);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as dv}from"node:fs/promises";import{join as uv}from"node:path";async function mv(t){try{let e=JSON.parse(await dv(uv(t,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let i=new Set,r=await dv(uv(t,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let a of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof a=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(a)&&i.add(a);let n={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...i].map(s=>[`/${s}`,{path:s,type:n[s.split(".").pop()]}]))}catch{return{}}}var mp=t=>`${JSON.stringify(t)}
541
+ `,la=class{streams=new Set;add(e,i){this.streams.add(e),e.once("close",()=>this.streams.delete(e)),e.write(mp(i))}publish(e){if(!this.streams.size)return;let i=mp(e);for(let r of this.streams)this.canWrite(r)&&r.write(i)}close(e){let i=mp({type:"shutdown",reconnect:e});for(let r of this.streams)this.canWrite(r)&&r.end(i);this.streams.clear()}canWrite(e){return!e.destroyed&&e.writableLength<4194304?!0:(this.streams.delete(e),e.destroyed||e.destroy(),!1)}};import{access as wx,readFile as hv,realpath as da,rename as q6,rm as j6,writeFile as F6}from"node:fs/promises";import{dirname as pa,join as Ft,resolve as Sx,sep as fv}from"node:path";import{createRequire as kx}from"node:module";var vx=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function kt(t){let e=typeof t=="string"&&vx.exec(t);if(!e||e[0]!==t)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let i=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!i.every(Number.isSafeInteger)||r.some(n=>/^\d+$/.test(n)&&n.length>1&&n[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:i,prerelease:r}}function Ke(t,e){let i=kt(t),r=kt(e);for(let n=0;n<3;n++)if(i.core[n]!==r.core[n])return i.core[n]>r.core[n]?1:-1;if(!i.prerelease.length||!r.prerelease.length)return+!i.prerelease.length-+!r.prerelease.length;for(let n=0;n<Math.max(i.prerelease.length,r.prerelease.length);n++){let s=i.prerelease[n],a=r.prerelease[n];if(s===void 0||a===void 0)return s===void 0?-1:1;if(s===a)continue;let o=/^\d+$/.test(s),l=/^\d+$/.test(a);return o!==l?o?-1:1:o&&s.length!==a.length?s.length>a.length?1:-1:s>a?1:-1}return 0}function gv(t){try{return kt(t).prerelease.length===0}catch{return!1}}function ca(t){try{return kt(t),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(t)}catch{return!1}}var ri=1;async function pr(t,e){let i=kx(Ft(t,"package.json"));for(let r of i.resolve.paths(e)??[]){let n=Ft(r,e);try{if(JSON.parse(await hv(Ft(n,"package.json"),"utf8")).name===e)return await da(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function gp(t,e){if(Ke(e?.version,e?.version),e.desktopProtocolVersion!==ri||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let i=await da(Sx(pa(e.launcher),"..")),r=await da(Ft(t,"pi-web","releases")),n=pa(pa(i));if(await da(e.launcher)!==Ft(i,"bin","pi-webapp.mjs")||pa(n)!==r||!n.startsWith(r+fv)||!n.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(n.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await hv(Ft(i,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==ri)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let a=await pr(i,"@earendil-works/pi-coding-agent");if(!a.startsWith(n+fv))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let o=Ft(a,"dist","bundle","cli.js");return await Promise.all([e.launcher,o,Ft(i,"dist","extension.js"),Ft(i,"web","dist","index.html")].map(l=>wx(l))),e.fallbackVersion!==void 0&&kt(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:o,desktopProtocolVersion:ri,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}ga();var fa="default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'",jx="browser.wasm";function Sv(t={}){return t.wasm?fa.replace("script-src 'self'","script-src 'self' 'wasm-unsafe-eval'"):fa}function kv(t){let e=t;return!!e&&e.browser?.wasm===!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(jx)}var Vx={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function T(t,e,i){typeof i=="object"&&i!==null&&"error"in i&&(i={errorCode:e>=500?"server_error":"validation_error",...i,requestId:t.getHeader("X-Request-ID"),operationId:t.getHeader("X-Operation-ID")}),t.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),t.end(JSON.stringify(i))}function zx(t,e){let i=t.headers.authorization;if(typeof i!="string"||!i.startsWith("Bearer "))return!1;let r=Buffer.from(i.slice(7),"utf8");return r.length===e.length&&Fx(r,e)}async function Tv(t,e=64*1024){let i=0,r=[];for await(let n of t){let s=Buffer.isBuffer(n)?n:Buffer.from(n);if(i+=s.length,i>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function Kx(t){let e=0,i=[];for await(let r of t){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=n.length,e>rs)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");i.push(n)}return Buffer.concat(i)}function Yx(t){if(!(!t||!/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i.test(t)))try{return new URL(`http://${t}`).origin}catch{return}}async function Qx(t,e,i){await new Promise((n,s)=>{t.once("error",s),t.listen(e,i,()=>{t.off("error",s),n()})});let r=t.address();if(r===null||typeof r=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return r.port}async function Iv(t,e,i=new St,r={}){i.setState({piVersion:$x});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:Ev(24).toString("base64url"),a=Buffer.from(s),o=fm(),l=new la,c=new es(r.pluginSettingsFile??_p(Gx(),"pi-web","plugins.json"));try{await c.load()}catch(k){throw await i.close(),k}let p=new ts(om(),c),d=async()=>await t.plugins?.()??{plugins:[],errors:[]},m=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!c.enabled(k.metadata.id)).map(k=>k.metadata.id)}),g=()=>l.publish(m()),h=new Map,f=new ns((k,v)=>i.capture(k,v)),b=k=>i.setState({nodeVersion:process.version,platform:process.platform,session:i.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),S=process.env.PI_WEBAPP_LISTEN_HOST==="0.0.0.0"?"0.0.0.0":"127.0.0.1",E=S==="127.0.0.1"?r.localFileGrant:void 0,A="",C=!1,N=!1,R={...Vx,...await mv(e)};for(let k of await Hx(_p(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!v)continue;let F={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};R[`/assets/${k}`]={path:`assets/${k}`,type:F[v[1]]}}let W=Wx(async(k,v)=>{let F=Ev(18).toString("base64"),G=pe=>typeof pe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(pe),K=G(k.headers["x-request-id"])?k.headers["x-request-id"]:bp(),J={requestId:K,operationId:G(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",K),J.operationId&&v.setHeader("X-Operation-ID",J.operationId);let O="/",oe=performance.now(),se=(pe,It,Ar)=>{let _=!mi(pe)&&nu(O)?xt(pe,"Agent or provider operation failed"):pe,z=i.capture(_,{...J,route:O,method:k.method,status:It,stage:"http"});T(v,It,{error:Ar,errorId:z,errorReported:i.enabled,errorCode:mi(pe)?"validation_error":"unexpected_error"})};v.once("finish",()=>{O.startsWith("/api/telemetry/")||i.breadcrumb("request",{...J,route:O,method:k.method,status:v.statusCode,durationMs:Math.round(performance.now()-oe)})});try{let pe=S==="0.0.0.0"?Yx(k.headers.host):A;if(pe===void 0){T(v,403,{error:"\u4E3B\u673A\u5730\u5740\u4E0D\u5339\u914D"});return}let It=k.headers.origin===void 0||k.headers.origin===pe;v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${F}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${i.config.browser.dsn?` ${new URL(i.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{O=new URL(k.url??"/",A).pathname}catch{T(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let Ar=R[O];if(k.method==="GET"&&Ar){try{let _=await Bx(_p(e,Ar.path));v.writeHead(200,{"Content-Type":Ar.type,"Cache-Control":"no-store"}),v.end(O==="/"?_.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${F}">`):_)}catch(_){se(_,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O.startsWith("/hosted-plugins/")){try{let _=await t.hosted?.asset(O);if(!_){T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy",_.csp??fa),v.writeHead(200,{"Content-Type":_.mime,"Cache-Control":"private, no-store"}),v.end(_.bytes)}catch{T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(k.method==="GET"&&O.startsWith("/plugins/")){try{let _=await t.pluginAsset?.(k.url??O);if(!_){T(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":_.type,"Cache-Control":"no-store"}),v.end(_.bytes)}catch(_){se(_,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!O.startsWith("/api/")){T(v,404,{error:"\u672A\u627E\u5230"});return}if(!zx(k,a)){T(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}let Xa=()=>!!E&&It&&k.headers.host===new URL(A).host&&k.socket.remoteAddress==="127.0.0.1"&&yp(E.key,s,k.headers[fu.toLowerCase()]);if(k.method==="GET"&&O===Gi){E&&Xa()?T(v,200,{platform:E.platform}):T(v,403,{error:"\u7CFB\u7EDF\u6587\u4EF6\u64CD\u4F5C\u4EC5\u9650\u5DF2\u6388\u6743\u7684\u672C\u673A\u684C\u9762"});return}if(k.method==="GET"&&O==="/api/hosted-plugins"){try{T(v,200,await up(t.hosted,O,void 0))}catch(_){let z=oa(_);T(v,z.status,z.body)}return}if(k.method==="POST"&&pv.includes(O)){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let _;try{_=await Tv(k,2*1024*1024)}catch(z){T(v,z instanceof Error&&z.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{T(v,200,await up(t.hosted,O,_,{draining:C}))}catch(z){let D=oa(z);T(v,D.status,D.body)}return}if(k.method==="GET"&&O==="/api/telemetry/config"){T(v,200,i.config.browser);return}if(k.method==="GET"&&O==="/api/update/version"){try{T(v,200,{current:await t.selfUpdate?.runningVersion()??null,desktopProtocolVersion:ri,...t.selfUpdate?.launcherIdentity?{launcher:t.selfUpdate.launcherIdentity(),desktopHandoffProtocol:t.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(_){se(_,503,_ instanceof Error?_.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&O==="/api/update"){try{T(v,200,await t.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(_){se(_,503,_ instanceof Error?_.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&O==="/api/image"){let _=new URL(k.url??O,A),z=_.searchParams.get("sessionId")??"",D=_.searchParams.get("messageId")??"",j=Number(_.searchParams.get("index"));if(!z||z!==t.snapshot().sessionId||!D||!Number.isInteger(j)||j<0||j>100){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let Z=t.image?.(z,D,j);if(!Z||!["image/png","image/jpeg","image/webp","image/gif"].includes(Z.mimeType)){T(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":Z.mimeType,"Cache-Control":"private, no-store"}),v.end(Z.data);return}if(k.method==="POST"&&O==="/api/attachment"){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let _=new URL(k.url??O,A),z=_.searchParams.get("sessionId"),D=_.searchParams.get("name");try{if(!z||!D||D.length>1024||z!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>rs){T(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let j=await _m(z,D,k.headers["content-type"]??"application/octet-stream",await Kx(k));if(z!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}h.set(j.id,j),T(v,201,{id:j.id,name:j.name,bytes:j.bytes})}catch(j){se(j,400,j instanceof Error?j.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&O==="/api/subagent-history"){let _=new URL(k.url??O,A).searchParams,z=_.get("workspaceId"),D=_.get("id");if(!z||!D||z.length>256||D.length>256){T(v,400,{error:"\u5B50\u4EFB\u52A1\u65E0\u6548"});return}try{let j=await t.subagentHistory?.(z,D);j?T(v,200,j):T(v,404,{error:"\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E0D\u53EF\u7528"})}catch(j){se(j,503,"\u65E0\u6CD5\u8BFB\u53D6\u5B50\u4EFB\u52A1\u8BB0\u5F55")}return}if(k.method==="GET"&&O==="/api/session"){try{let _=t.snapshot();b(_),T(v,200,_)}catch(_){se(_,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/plugin-management"){try{T(v,200,p.inventory(await d()))}catch(_){se(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/plugins"){try{T(v,200,p.catalog(await d()))}catch(_){se(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/providers"){try{T(v,200,await t.providers?.()??[])}catch(_){se(_,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/provider/models"){let _=new URL(k.url??O,A).searchParams.get("providerId")??"";try{if(!_||!t.providerModels){T(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}T(v,200,await t.providerModels(_))}catch(z){se(z,400,z instanceof Error?z.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/provider/login/active"){T(v,200,{active:f.getActive()??null});return}if(k.method==="GET"&&O==="/api/provider/login"){let _=new URL(k.url??O,A).searchParams.get("id")??"",z=f.get(_);T(v,z?200:404,z??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(O==="/api/models"||O==="/api/config"||O==="/api/workspaces"||O==="/api/commands")){try{T(v,200,O==="/api/models"?await t.models():O==="/api/config"?await t.config():O==="/api/commands"?t.commands?.()??[]:await t.workspaces())}catch(_){se(_,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&O==="/api/directory/capability"){T(v,200,{kind:o});return}if(k.method==="GET"&&O==="/api/events"){let _;try{_=t.snapshot(),b(_)}catch(z){se(z,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),l.add(v,{type:"snapshot",session:_});return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(O)){if(!It){T(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let _;try{_=await Tv(k,O==="/api/plugin-action"?544*1024:64*1024)}catch(D){if(D instanceof Error&&D.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){T(v,413,{error:D.message});return}if(D instanceof SyntaxError||mi(D)){T(v,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw D}if(O==="/api/desktop/handoff"){let D=_;if(!D||typeof D.nonce!="string"||typeof D.requestId!="string"){T(v,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!t.selfUpdate?.requestLauncherHandoff){T(v,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(C||N||f.getActive()){T(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let j=p.restartBlocker()??p.restartConfirmations()[0];if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||j){T(v,409,{error:j??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}C=!0;try{await t.selfUpdate.requestLauncherHandoff(D.nonce,D.requestId)}catch(Z){throw C=!1,Z}T(v,202,{accepted:!0,protocol:1,requestId:D.requestId});return}if(typeof _!="object"||_===null||!("sessionId"in _)||typeof _.sessionId!="string"){T(v,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(C&&O!=="/api/update/cancel"){T(v,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(O==="/api/plugin-management"){let D=_;if(typeof D.id!="string"||D.id.length>200||typeof D.enabled!="boolean"||typeof D.expected!="string"){T(v,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let j=()=>{if(t.snapshot().sessionId!==_.sessionId)throw new ve("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length)throw new ve("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(D.id,D.enabled,D.expected,j),T(v,200,p.inventory(await d()))}catch(Z){if(Z instanceof ve)T(v,Z.status,{error:Z.message});else throw Z}finally{g()}return}if(p.mutating&&O!=="/api/abort"){T(v,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}let z=O===Gi&&k.headers.origin===A&&Xa()?{workspaces:()=>t.workspaces(),trusted:()=>!C&&!v.destroyed}:void 0;if(await p.dispatch({path:O,body:_,res:v,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],localFileRequest:z,json:(D,j)=>T(v,D,j)}))return;if(O==="/api/plugin-interaction"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("requestId"in _)||typeof _.requestId!="string"||_.requestId.length>200||!t.resolvePluginInteraction||!("value"in _)){T(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(t.snapshot().cwd,async()=>t.resolvePluginInteraction(_.sessionId,_.pluginId,_.requestId,_.value)),T(v,200,{accepted:!0});return}if(O==="/api/plugin-action"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("action"in _)||typeof _.action!="string"||_.action.length>100){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(Z=>Z.metadata.id===_.pluginId)){let Z=p.actionRoute(_.pluginId,_.action);if(!Z){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let Te="input"in _?_.input:{};if(!Te||typeof Te!="object"||Array.isArray(Te)){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:Z,body:{...Te,sessionId:_.sessionId},res:v,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],json:(it,di)=>T(v,it,it>=200&&it<300?{value:di}:di)});return}if(!t.invokePluginAction){T(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let j=await p.coordinateStart(t.snapshot().cwd,async()=>t.invokePluginAction(_.sessionId,_.pluginId,_.action,"input"in _?_.input:void 0));T(v,200,{value:j});return}if(O==="/api/update/channel"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in _)||_.channel!=="stable"&&_.channel!=="alpha"){T(v,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!t.selfUpdate?.setChannel){T(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}T(v,200,await t.selfUpdate.setChannel(_.channel));return}if(O==="/api/update/cancel"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.selfUpdate?.cancel){T(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await t.selfUpdate.cancel(),T(v,200,{cancelled:!0,dataPreserved:!0});return}if(O==="/api/update"){if(N){T(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.snapshot().idle){T(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!t.selfUpdate){T(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let D=p.restartBlocker();if((t.busyGitWorkspaces?.()??[]).length||D){T(v,409,{error:D??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let j=_,Z="channel"in j||"version"in j||"allowDowngrade"in j;if(Z&&(j.channel!=="stable"&&j.channel!=="alpha"||typeof j.version!="string"||j.allowDowngrade!==void 0&&typeof j.allowDowngrade!="boolean")){T(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(j.force!==void 0&&typeof j.force!="boolean"){T(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let Te=j.force===!0,it=de=>T(v,409,{error:de.join("\uFF1B"),reason:"update_confirm_required"}),di=p.restartConfirmations();if(di.length&&!Te){it(di);return}N=!0;let xr;try{xr=await t.selfUpdate.prepare(Z?{channel:j.channel,version:j.version,allowDowngrade:j.allowDowngrade}:void 0);let de=p.restartBlocker();if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||de)throw new Error(de??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let Td=p.restartConfirmations();if(Td.length&&!Te){it(Td);return}Te&&await p.releaseForRestart(),C=!0;try{await t.selfUpdate.requestRestart(xr,{force:Te})}catch(Id){let Ad=Id?.code;if(!Te&&(Ad==="view_barrier"||Ad==="drain_pending")){C=!1,it(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw Id}}catch(de){throw C=!1,de}finally{N=!1}T(v,202,{accepted:!0,version:xr.version});return}if(O==="/api/provider/custom"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in _)||!ho(_.provider)||!t.addCustomProvider){T(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await t.addCustomProvider(_.sessionId,_.provider),T(v,201,{accepted:!0});return}if(O==="/api/provider/models"||O==="/api/provider/logout"){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in _)||typeof _.providerId!="string"){T(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(O==="/api/provider/models"){if(!("change"in _)||!Em(_.change)||!t.updateProviderModel){T(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await t.updateProviderModel(_.sessionId,_.providerId,_.change)}else{if(!t.logoutProvider){T(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await t.logoutProvider(_.sessionId,_.providerId)}T(v,200,{accepted:!0});return}if(O.startsWith("/api/provider/login")){if(_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(O==="/api/provider/login"){if(!("providerId"in _)||typeof _.providerId!="string"||!("method"in _)||_.method!=="api_key"&&_.method!=="oauth"||!t.loginProvider||!t.providers){T(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await t.providers()).some(Te=>Te.id===_.providerId&&Te.methods.includes(_.method))){T(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let j="initialSecret"in _?_.initialSecret:void 0;if(j!==void 0&&(_.method!=="api_key"||typeof j!="string"||!j.trim()||j.length>16384)){T(v,400,{error:"API Key \u65E0\u6548"});return}let Z=f.start(_.providerId,_.method,t.loginProvider,j,J);T(v,202,{id:Z.id});return}if(!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(O==="/api/provider/login/cancel"){T(v,f.cancel(_.id)?202:404,{accepted:!0});return}if(!("value"in _)||typeof _.value!="string"||_.value.length>16384||!f.respond(_.id,_.value)){T(v,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}T(v,202,{accepted:!0});return}if(O==="/api/attachment/remove"){if(!("id"in _)||typeof _.id!="string"||_.sessionId!==t.snapshot().sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}h.get(_.id)?.sessionId===_.sessionId&&h.delete(_.id),T(v,202,{accepted:!0});return}if(O==="/api/directory/pick"){if(o!=="native"){T(v,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let D=new AbortController;v.once("close",()=>D.abort()),T(v,200,{path:await hm(D.signal)});return}if(O==="/api/directory/list"){if("path"in _&&(typeof _.path!="string"||_.path.length>4096)){T(v,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}T(v,200,await mm("path"in _?_.path:void 0));return}if(O==="/api/directory/create"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("name"in _)||typeof _.name!="string"||_.name.length>255){T(v,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}T(v,200,{path:await gm(_.path,_.name)});return}if(O==="/api/workspace/add"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("create"in _)||typeof _.create!="boolean"){T(v,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await t.addWorkspace(_.path,_.create),T(v,202,{accepted:!0});return}if(O==="/api/workspace/select"||O==="/api/workspace/remove"||O==="/api/workspace/new-session"){if(!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}O==="/api/workspace/select"?await t.selectWorkspace(_.id):O==="/api/workspace/new-session"?await t.newSessionInWorkspace(_.id):await t.removeWorkspace(_.id),T(v,202,{accepted:!0});return}if(O==="/api/session/select"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await t.selectSession(_.workspaceId,_.id,_.path),T(v,202,{accepted:!0});return}if(O==="/api/session/rename"||O==="/api/session/delete"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"||_.path.length>4096){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(O==="/api/session/rename"){if(!("name"in _)||typeof _.name!="string"){T(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!t.renameSession){T(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await t.renameSession(_.workspaceId,_.id,_.path,_.name)}else{if(!t.deleteSession){T(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await t.deleteSession(_.workspaceId,_.id,_.path)}T(v,202,{accepted:!0});return}if(O==="/api/thinking-level"){if(!("level"in _)||typeof _.level!="string"){T(v,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await t.setThinkingLevel(_.sessionId,_.level)}else if(O==="/api/model"){if(!("provider"in _)||typeof _.provider!="string"||!("id"in _)||typeof _.id!="string"){T(v,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await t.setModel(_.sessionId,_.provider,_.id)}else if(O==="/api/config"){let D=_;if(!["packages","extensions","skills"].includes(D.kind)||!["global","project"].includes(D.scope)||!["add","remove"].includes(D.action)||typeof D.value!="string"||!D.value.trim()||D.value.length>2048){T(v,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(D.action==="add"&&D.kind!=="packages"&&Om(D.value)){T(v,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}T(v,200,await t.updateConfig(D));return}else if(O==="/api/prompt-queue"){let D=_,j=D.action;if(typeof D.id!="string"||D.id.length>100||!Number.isSafeInteger(D.revision)||D.revision<1||!j||typeof j!="object"||!["edit","remove","steer"].includes(j.kind)||j.kind==="edit"&&(typeof j.text!="string"||j.text.length>32e3)){T(v,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let Z=t.snapshot();if(D.sessionId!==Z.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(j.kind==="steer"&&Z.idle){T(v,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(j.kind==="steer"&&Z.interactions?.length){T(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.updateQueuedPrompt){T(v,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(Z.cwd,async()=>t.updateQueuedPrompt(_.sessionId,D.id,D.revision,j))}else if(O==="/api/message"){let D="delivery"in _?_.delivery:void 0;if(D!==void 0&&D!=="steer"&&D!=="followUp"){T(v,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let j="attachments"in _?_.attachments:[];if(!Array.isArray(j)||j.length>bm||j.some(de=>typeof de!="string")||new Set(j).size!==j.length){T(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let Z=j.map(de=>h.get(de));if(Z.some(de=>!de||de.sessionId!==_.sessionId)){T(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in _)||typeof _.text!="string"||!_.text.trim()&&j.length===0||_.text.length>32e3){T(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let Te=t.snapshot();if(_.sessionId!==Te.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{ei(Te,_.text,D)}catch(de){T(v,409,{error:de.message});return}let it=Z,di=[_.text.trim(),...it.map(de=>`\u9644\u4EF6 ${JSON.stringify(de.name)}\uFF1A${de.path}`)].filter(Boolean).join(`
543
542
 
544
- `),xr=await Promise.all(it.filter(pe=>["image/png","image/jpeg","image/webp","image/gif"].includes(pe.mediaType)).map(bm));J.operationId??=hp(),v.setHeader("X-Operation-ID",J.operationId),i.breadcrumb("send",{...J,attachmentCount:it.length}),await p.coordinateStart(Te.cwd,async()=>t.send(_.sessionId,di,xr,J,D));for(let pe of j)h.delete(pe)}else if(O==="/api/compact"){if(!t.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await t.compact(_.sessionId)}else if(O==="/api/resume"){let D=t.snapshot();if(_.sessionId!==D.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!D.idle){T(v,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!D.paused){T(v,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(D.interactions?.length){T(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");J.operationId??=hp(),v.setHeader("X-Operation-ID",J.operationId),i.breadcrumb("resume",{...J}),await p.coordinateStart(D.cwd,async()=>t.resume(_.sessionId,J))}else O==="/api/abort"?await t.abort(_.sessionId):await t.newSession(_.sessionId);T(v,202,{accepted:!0})}catch(_){if(_ instanceof Le){T(v,_.status,{error:_.message});return}let z=p.requestFailure(_);if(z){T(v,z.status,z.body);return}let D=_ instanceof Error?_.message:"\u8BF7\u6C42\u5931\u8D25";se(_,D==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,D)}return}T(v,404,{error:"\u672A\u627E\u5230"})}catch(ce){v.headersSent?(i.capture(ce,{...J,route:O,stage:"http_stream"}),v.end()):se(ce,500,"\u8BF7\u6C42\u5931\u8D25")}}),P=k=>Number.isInteger(k)&&k>=1&&k<=65535,I=Number(process.env.PI_WEBAPP_LISTEN_PORT),x=Number(process.env.PI_WEBAPP_RESTART_PORT),L=P(I)?I:n===s&&P(x)?x:0,U;try{U=await zx(G,L,S)}catch(k){throw i.capture(k,{stage:"listen"}),await i.close(),k?.code==="EADDRINUSE"?new Error(`\u7AEF\u53E3 ${L} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09`,{cause:k}):new Error(`\u65E0\u6CD5\u76D1\u542C ${S}:${L}\uFF1A${k instanceof Error?k.message:String(k)}`,{cause:k})}return A=new URL(`http://127.0.0.1:${U}`).origin,{protocolVersion:7,buildId:nt,runPluginTool:(k,v,F,W,K,J)=>p.runAgentAction(k,v,F,W,K,J),reportError(k,v){return i.capture(k,v)},breadcrumb(k,v){i.breadcrumb(k,v)},url:`${A}/#${s}`,publish(k){if(k.type==="snapshot"&&b(k.session),k.type==="error"&&!k.errorCode&&(k={...k,errorCode:"unexpected_error",errorId:i.capture(new Error("Agent execution failed"),{stage:"agent",requestId:k.requestId,operationId:k.operationId})}),k.type==="error"&&(k={...k,errorReported:k.errorReported??i.enabled}),k.type==="snapshot")for(let[F,W]of h)W.sessionId!==k.session.sessionId&&h.delete(F);let v=`${JSON.stringify(k)}
545
- `;for(let F of l)F.write(v)},async close(k){f.close(),await p.close();for(let F of l)F.end(`${JSON.stringify({type:"shutdown",reconnect:k?.reconnect??C})}
546
- `);l.clear();let v;try{await new Promise((F,W)=>{G.close(K=>K?W(K):F()),v=setTimeout(()=>G.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await i.close()}}}}import{getSupportedThinkingLevels as Kx}from"@earendil-works/pi-ai";var Tn="pi-webapp/paused",bp="pi-webapp/resume";function dr(t){for(let e=t.length-1;e>=0;e--){let i=t[e];if(i.type==="custom_message"&&i.customType===bp)return!1;if(i.type==="custom"&&i.customType===Tn)return!0;if(i.type==="message"){if(i.message.role==="user")return!1;if(i.message.role==="assistant"){if(i.message.stopReason==="aborted")return!0;if(i.message.stopReason==="stop"||i.message.stopReason==="length"||i.message.stopReason==="error")return!1}}}return!1}function _p(t,e){let i=[],r;for(let n of t){if(n.type==="message"&&(r=n.id),n.type!=="custom")continue;let s=e.find(a=>n.customType.startsWith(`${a}/`));if(s){try{if(JSON.stringify(n.data).length>128*1024)continue}catch{continue}i.push({id:n.id,pluginId:s,kind:n.customType,data:n.data,timestamp:n.timestamp,...r?{afterMessageId:r}:{}})}}return i}function Bt(t){return typeof t=="string"?[{kind:"text",text:t}]:t.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Yx(t){let e=t.details&&typeof t.details=="object"?t.details:{},i=typeof e.description=="string"?e.description.replace(/\s+/g," ").trim():"",r=e.status==="completed"?"completed":e.status==="failed"||e.status==="error"?"failed":e.status==="cancelled"||e.status==="aborted"?"cancelled":"unknown",n=typeof e.resultPreview=="string"?e.resultPreview.trim()?Bt(e.resultPreview):[]:Bt(t.content);return{id:t.id,role:"notice",timestamp:t.timestamp,blocks:n,subagentNotice:{status:r,...i?{description:i}:{}}}}function Oi(t){if(t.type==="custom_message")return t.display?t.customType==="subagent-notification"?Yx(t):{id:t.id,role:"notice",timestamp:t.timestamp,blocks:Bt(t.content)}:null;if(t.type!=="message")return null;let{message:e}=t;return e.role==="user"||e.role==="assistant"?{id:t.id,role:e.role,timestamp:t.timestamp,blocks:Bt(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:t.id,role:"tool",timestamp:t.timestamp,blocks:Bt(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function fa(t,e){let i=t?.trim();if(i)return i;let r=e.find(s=>s.role==="user");return kn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function Tv(t,e,i=[]){let r=t.sessionManager.getBranch().flatMap(n=>{let s=Oi(n);return s?[s]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:t.cwd,name:fa(e,r),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel??null,thinkingLevels:t.model?Kx(t.model):["off"],idle:t.isIdle(),paused:dr(t.sessionManager.getBranch()),contextUsage:t.getContextUsage()??null,messages:r,pluginEntries:_p(t.sessionManager.getBranch(),i)}}import{randomUUID as vp}from"node:crypto";import{mkdir as Iv,readFile as Qx,realpath as wp,rename as Jx,rm as Xx,stat as Sp,writeFile as Zx}from"node:fs/promises";import{basename as Av,dirname as eO,isAbsolute as xv,join as tO}from"node:path";var In=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function Ri(t){try{let e=await wp(t);return(await Sp(e)).isDirectory()?e:null}catch(e){let i=e.code;if(i==="ENOENT"||i==="ENOTDIR")return null;throw e}}async function Tt(t){let e=await Ri(t);if(e===null)throw new In;return e}var ha=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Qx(this.file,"utf8")),i,r=[];if(Array.isArray(e)?i=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(i=e.items,r=e.hiddenPaths),!Array.isArray(i)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=i.filter(n=>typeof n=="object"&&n!==null&&typeof n.id=="string"&&typeof n.path=="string"&&typeof n.title=="string"),this.hiddenPaths=r.filter(n=>typeof n=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(i=>i.id===e)}async add(e,i=!1){if(!xv(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");i&&await Iv(e,{recursive:!0});let r=await wp(e);if(!(await Sp(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let n=this.hiddenPaths.filter(l=>l!==r),s=this.items.find(l=>l.path===r);if(s)return n.length!==this.hiddenPaths.length&&(await this.save(this.items,n),this.hiddenPaths=n),s;let a={id:vp(),path:r,title:Av(r)||r},o=[a,...this.items];return await this.save(o,n),this.items=o,this.hiddenPaths=n,a})}async discover(e){let i=(await Promise.all([...new Set(e)].filter(xv).map(async r=>{try{let n=await wp(r);return(await Sp(n)).isDirectory()?n:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(a=>a.path),...this.hiddenPaths]),n=[];for(let a of i)r.has(a)||(r.add(a),n.push({id:vp(),path:a,title:Av(a)||a}));if(n.length===0)return;let s=[...this.items,...n];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let i=this.get(e);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),n=[...new Set([...this.hiddenPaths,i.path])];await this.save(r,n),this.items=r,this.hiddenPaths=n})}mutate(e){let i=this.mutationChain.then(e,e);return this.mutationChain=i.then(()=>{},()=>{}),i}async save(e,i){await Iv(eO(this.file),{recursive:!0});let r=`${this.file}.${vp()}.tmp`;try{await Zx(r,JSON.stringify({version:2,items:e,hiddenPaths:i},null,2),{mode:384}),await Jx(r,this.file)}catch(n){throw await Xx(r,{force:!0}),n}}};function Ov(t){return tO(t,"pi-web","workspaces.json")}import{createAgentSession as iR,createEventBus as rR,DefaultResourceLoader as nR,getAgentDir as lw,SessionManager as hr,VERSION as wa}from"@earendil-works/pi-coding-agent";function An(t,e){return!!t?.has(e)||Object.values(He).includes(e)}var Rv="pi-webapp:interaction-open:v1",Nv="pi-webapp:interaction-accept:v1",kp="pi-webapp:interaction-settle:v1",Pv="pi-webapp:interaction-cancel:v1",Ep=class extends Error{};function ya(t,e,i,r=300){return new Promise((n,s)=>{let a=!1,o,l=(m,g)=>{a||(a=!0,clearTimeout(o),p(),d(),i?.removeEventListener("abort",c),m?s(m):n(g))},c=()=>{t.emit(Pv,e),l(new Error("Interaction cancelled"))},p=t.on(Nv,m=>{m?.requestId===e.requestId&&clearTimeout(o)}),d=t.on(kp,m=>{let g=m;g?.requestId===e.requestId&&l(g.error?new Error(g.error):null,g.value)});o=setTimeout(()=>l(new Ep("No Web interaction host")),r),i?.addEventListener("abort",c,{once:!0}),i?.aborted?c():t.emit(Rv,e)})}var ur=class{bus;accepts;changed;requests=new Map;detach;constructor(e,i,r){this.bus=e,this.accepts=i,this.changed=r,this.detach=[e.on(Rv,n=>{!iO(n)||!i(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(Nv,{requestId:n.requestId}),r())}),e.on(Pv,n=>{let s=n,a=this.requests.get(s?.requestId);a&&a.sessionId===s.sessionId&&a.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(i=>i.sessionId===e)}resolve(e,i,r,n){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==i||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(kp,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let i of this.requests.values())this.bus.emit(kp,{requestId:i.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function iO(t){if(!t||typeof t!="object")return!1;let e=t;for(let i of["requestId","sessionId","pluginId","kind"])if(typeof e[i]!="string"||!e[i]||e[i].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Ni(t){return typeof t=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(t)&&t.length<=512&&!t.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function ni(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&Ni(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Ni(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Ni(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Ni(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(i=>Number.isSafeInteger(i)&&i>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(i=>typeof i=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(i))}var rO=1,nO="pi-webapp:action:v1",sO="pi-webapp:action-response:v1",ba="pi-webapp:plugin-changed:v1";function Cv(t){if(!t||typeof t!="object")return!1;let e=t;return e.apiVersion===rO&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function _a(t,e,i=15e3,r){return new Promise((n,s)=>{let a=!1,o=(d,m)=>{a||(a=!0,clearTimeout(c),l(),r?.removeEventListener("abort",p),d?s(d):n(m))},l=t.on(sO,d=>{let m=d;m?.requestId===e.requestId&&o(m.ok?null:new Error(m.error??"Plugin action failed"),m.value)}),c=setTimeout(()=>o(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),i),p=()=>o(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{t.emit(nO,e)}catch(d){o(d instanceof Error?d:new Error(String(d)))}})}import{realpath as sR}from"node:fs/promises";import{readFile as Tp,realpath as Uv,stat as qv}from"node:fs/promises";import{createHash as aO}from"node:crypto";import{dirname as Dv,isAbsolute as oO,join as Ip,parse as lO,resolve as cO,sep as pO,delimiter as dO}from"node:path";import{DefaultPackageManager as uO,getAgentDir as mO,SettingsManager as gO}from"@earendil-works/pi-coding-agent";async function Mv(t,e){let i=await Tp(t),r=e?await Tp(e):void 0;if(i.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let n=aO("sha256").update(i).update("\0").update(r??"").digest("hex");return{clientBytes:i,styleBytes:r,revision:n}}function fO(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(dO).filter(Boolean).map(t=>cO(t))}async function hO(t){let e=Dv(t);for(;e!==lO(e).root;)try{return await qv(Ip(e,"package.json")),e}catch{e=Dv(e)}return null}async function Lv(t,e){let i=await Uv(Ip(t,e));if(!i.startsWith(t+pO))throw new Error("Asset escapes package root");let r=await qv(i);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return i}var Pi=class t{plugins;errors;extensionRoots;constructor(e,i,r){this.plugins=e,this.errors=i,this.extensionRoots=r}static async discover(e,i,r=fO()){let n=gO.create(e,void 0,{projectTrusted:i}),s=new uO({cwd:e,agentDir:mO(),settingsManager:n}),a=await s.resolve(async()=>"skip"),o=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},l=new Set;for(let g of[...a.extensions,...o.extensions]){if(!g.enabled)continue;let h=await hO(g.path);h&&l.add(h)}for(let g of r)oO(g)&&l.add(g);let c=[],p=[],d=[],m=new Set;for(let g of l)try{let h=await Uv(g),f=JSON.parse(await Tp(Ip(h,"package.json"),"utf8"));if(f.piWebapp===void 0)continue;if(typeof f.name!="string"||!f.name)throw new Error("Missing package name");if(!Cv(f.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(m.has(f.name))throw new Error(`Duplicate plugin id: ${f.name}`);let b=await Lv(h,f.piWebapp.client),S=f.piWebapp.style?await Lv(h,f.piWebapp.style):void 0;m.add(f.name),c.push({id:f.name,root:h,manifest:f.piWebapp,clientPath:b,stylePath:S,...await Mv(b,S)}),d.push(h)}catch(h){p.push(`${g}: ${h instanceof Error?h.message:String(h)}`)}return c.sort((g,h)=>g.id.localeCompare(h.id)),new t(c,p,d)}has(e){return this.plugins.some(i=>i.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await Mv(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let i=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(i.pathname);if(!r)return null;let n;try{n=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(o=>o.id===n);if(!s||i.searchParams.has("v")&&i.searchParams.get("v")!==s.revision)return null;let a=r[2]==="client.js"?s.clientBytes:s.styleBytes;return a?{bytes:a,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as yO}from"node:fs/promises";import{SessionManager as bO}from"@earendil-works/pi-coding-agent";async function Ci(t,e){let i=await Tt(t),r=e??await bO.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await yO(s.cwd).catch(()=>null)===i));return r.filter((s,a)=>n[a])}import{createReadStream as _O}from"node:fs";import{readdir as vO,readFile as wO,stat as SO}from"node:fs/promises";import{basename as kO,join as EO}from"node:path";import{createInterface as TO}from"node:readline";import{parseSessionEntries as Bv}from"@earendil-works/pi-coding-agent";function jv(t){switch(t){case"background":case"running":return"running";case"completed":return"completed";case"error":case"failed":case"launch-error":return"failed";case"stopped":case"aborted":case"cancelled":return"cancelled";default:return"unknown"}}var Fv=t=>typeof t=="string"&&t.replace(/\s+/g," ").trim().slice(0,160)||void 0;async function IO(t){let e=new Map,i=new Map,r=new Map,n=[],s=TO({input:_O(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let a of s){if(!a.includes('"Agent"')&&!a.includes('"steer_subagent"')&&!a.includes('"subagents:record"'))continue;let o=Bv(a)[0];if(!o)continue;if(o.type==="custom"&&o.customType==="subagents:record"){let g=o.data;typeof g?.id=="string"&&r.set(g.id,{status:jv(g.status),description:Fv(g.description)})}if(o.type!=="message")continue;let l=o.message;if(l.role==="assistant")for(let g of l.content)g.type==="toolCall"&&(g.name==="Agent"||g.name==="steer_subagent")&&i.set(g.id,{name:g.name,args:g.arguments});if(l.role!=="toolResult"||l.isError)continue;let c=i.get(l.toolCallId);if(!c||c.name!==l.toolName)continue;if(i.delete(l.toolCallId),c.name==="steer_subagent"){let g=l.content.find(f=>f.type==="text")?.text,h=/^Steering message sent to agent ([\w-]+)\./.exec(g??"")?.[1];h&&typeof c.args.message=="string"&&n.push({agentId:h,text:c.args.message});continue}let p=l.details,d=p?.agentId,m=p?.subagentType??c.args.subagent_type;typeof d!="string"||typeof m!="string"||typeof c.args.prompt!="string"||e.set(d,{agentId:d,agentType:m,dispatchCallId:l.toolCallId,prompt:c.args.prompt,status:jv(p?.status),description:Fv(p?.description??c.args.description),steering:[]})}for(let[a,o]of r){let l=e.get(a);l&&(l.status=o.status,l.description=o.description??l.description)}for(let{agentId:a,text:o}of n)e.get(a)?.steering.push(o);return[...e.values()]}var Di=new Map;async function AO(t){let e=await SO(t).catch(()=>null);if(!e?.isFile())return[];let i=`${e.ino}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`,r=Di.get(t);if(r?.key===i)return r.value;let n=IO(t).catch(()=>(Di.get(t)?.key===i&&Di.delete(t),[]));return Di.set(t,{key:i,value:n}),Di.size>256&&Di.delete(Di.keys().next().value),n}async function mr(t,e,i=new Set){let r=new Map(t.map(c=>[c.path,c])),n=new Map,s=t.filter(c=>c.parentSessionPath&&/#[a-f\d]{8}$/i.test(c.name??"")),a=s.some(c=>!r.has(c.parentSessionPath))?await vO(e,{withFileTypes:!0}).catch(()=>[]):[],o=new Map(a.filter(c=>c.isFile()&&/^\d+_.+\.jsonl$/.test(c.name)).map(({name:c})=>[c.replace(/^\d+_/,""),EO(e,c)])),l=new Map;for(let c of s){let p=c.parentSessionPath,d=r.get(p),m=d?.path??o.get(kO(p));if(!m||m===c.path)continue;let g=l.get(m);g||(g=AO(m),l.set(m,g));let h=(await g).filter(R=>c.name?.endsWith(`#${R.agentId.slice(0,8)}`)&&c.firstMessage===R.prompt);if(h.length!==1)continue;let{agentId:f,agentType:b,dispatchCallId:S,description:E,status:A,prompt:C,steering:N}=h[0];n.set(c.id,{prompt:C,steering:N,view:{parentSessionId:d?.id??null,agentId:f,agentType:b,dispatchCallId:S,description:E,status:A==="running"&&!(d&&i.has(d.id))?"unknown":A}})}return n}async function Hv(t,e,i){let[r,...n]=Bv(await wO(t,"utf8"));if(r?.type!=="session"||r.id!==e)throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E0D\u53EF\u7528");let s=[],a=[...i.steering],o=n.filter(d=>d.type!=="session"),l=new Map(o.map(d=>[d.id,d])),c=[];for(let d=o.at(-1);d&&l.delete(d.id);d=d.parentId?l.get(d.parentId):void 0)c.push(d);let p=!1;for(let d of c.reverse()){let m=Oi(d);if(m){if(m.role==="user"){let g=m.blocks.every(h=>h.kind==="text")?m.blocks.map(h=>h.text).join(" "):void 0;if(!p&&g===i.prompt)m.subagentInput="dispatch";else{let h=g===void 0?-1:a.indexOf(g);h>=0&&(m.subagentInput="steering",a.splice(h,1))}p=!0}s.push(m)}}return s}import{copyFile as xO,mkdir as OO,rename as RO,unlink as NO}from"node:fs/promises";import{basename as PO,join as Gv}from"node:path";var Mi=t=>Gv(t,"pi-web","trash");async function Wv(t,e){let i=Mi(e);await OO(i,{recursive:!0});let r=Gv(i,`${Date.now()}_${PO(t)}`);try{await RO(t,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await xO(t,r),await NO(t)}return r}var Li=class{tail=Promise.resolve();run(e){let i=this.tail.then(e);return this.tail=i.catch(()=>{}),i}wrap(e){return(...i)=>this.run(()=>e(...i))}},$v=new WeakMap;function Vv(t,e,i,r=5e3,n=()=>{}){let s=$v.get(t);if(s)return s;let a=(async()=>{let o;try{await Promise.race([t.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((l,c)=>{o=setTimeout(()=>c(new Error("Plugin shutdown timed out")),r)})])}catch(l){i(l instanceof Error?l.message:String(l))}finally{clearTimeout(o);try{n()}finally{t.dispose()}}})();return $v.set(t,a),a}function va(t){let i=[...t].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
547
- `);return{customType:bp,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(i?`
543
+ `),xr=await Promise.all(it.filter(de=>["image/png","image/jpeg","image/webp","image/gif"].includes(de.mediaType)).map(vm));J.operationId??=bp(),v.setHeader("X-Operation-ID",J.operationId),i.breadcrumb("send",{...J,attachmentCount:it.length}),await p.coordinateStart(Te.cwd,async()=>t.send(_.sessionId,di,xr,J,D));for(let de of j)h.delete(de)}else if(O==="/api/compact"){if(!t.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await t.compact(_.sessionId)}else if(O==="/api/resume"){let D=t.snapshot();if(_.sessionId!==D.sessionId){T(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!D.idle){T(v,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!D.paused){T(v,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(D.interactions?.length){T(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");J.operationId??=bp(),v.setHeader("X-Operation-ID",J.operationId),i.breadcrumb("resume",{...J}),await p.coordinateStart(D.cwd,async()=>t.resume(_.sessionId,J))}else O==="/api/abort"?await t.abort(_.sessionId):await t.newSession(_.sessionId);T(v,202,{accepted:!0})}catch(_){if(_ instanceof Le){T(v,_.status,{error:_.message});return}let z=p.requestFailure(_);if(z){T(v,z.status,z.body);return}let D=_ instanceof Error?_.message:"\u8BF7\u6C42\u5931\u8D25";se(_,D==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,D)}return}T(v,404,{error:"\u672A\u627E\u5230"})}catch(pe){v.headersSent?(i.capture(pe,{...J,route:O,stage:"http_stream"}),v.end()):se(pe,500,"\u8BF7\u6C42\u5931\u8D25")}}),P=k=>Number.isInteger(k)&&k>=1&&k<=65535,I=Number(process.env.PI_WEBAPP_LISTEN_PORT),x=Number(process.env.PI_WEBAPP_RESTART_PORT),L=P(I)?I:n===s&&P(x)?x:0,U;try{U=await Qx(W,L,S)}catch(k){throw i.capture(k,{stage:"listen"}),await i.close(),k?.code==="EADDRINUSE"?new Error(`\u7AEF\u53E3 ${L} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09`,{cause:k}):new Error(`\u65E0\u6CD5\u76D1\u542C ${S}:${L}\uFF1A${k instanceof Error?k.message:String(k)}`,{cause:k})}return A=new URL(`http://127.0.0.1:${U}`).origin,{protocolVersion:7,buildId:nt,runPluginTool:(k,v,F,G,K,J)=>p.runAgentAction(k,v,F,G,K,J),reportError(k,v){return i.capture(k,v)},breadcrumb(k,v){i.breadcrumb(k,v)},url:`${A}/#${s}`,publish(k){if(k.type==="snapshot"&&b(k.session),k.type==="error"&&!k.errorCode&&(k={...k,errorCode:"unexpected_error",errorId:i.capture(new Error("Agent execution failed"),{stage:"agent",requestId:k.requestId,operationId:k.operationId})}),k.type==="error"&&(k={...k,errorReported:k.errorReported??i.enabled}),k.type==="snapshot")for(let[v,F]of h)F.sessionId!==k.session.sessionId&&h.delete(v);l.publish(k)},async close(k){f.close(),await p.close(),l.close(k?.reconnect??C);let v;try{await new Promise((F,G)=>{W.close(K=>K?G(K):F()),v=setTimeout(()=>W.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await i.close()}}}}import{getSupportedThinkingLevels as Jx}from"@earendil-works/pi-ai";var Tn="pi-webapp/paused",vp="pi-webapp/resume";function dr(t){for(let e=t.length-1;e>=0;e--){let i=t[e];if(i.type==="custom_message"&&i.customType===vp)return!1;if(i.type==="custom"&&i.customType===Tn)return!0;if(i.type==="message"){if(i.message.role==="user")return!1;if(i.message.role==="assistant"){if(i.message.stopReason==="aborted")return!0;if(i.message.stopReason==="stop"||i.message.stopReason==="length"||i.message.stopReason==="error")return!1}}}return!1}function wp(t,e){let i=[],r;for(let n of t){if(n.type==="message"&&(r=n.id),n.type!=="custom")continue;let s=e.find(a=>n.customType.startsWith(`${a}/`));if(s){try{if(JSON.stringify(n.data).length>128*1024)continue}catch{continue}i.push({id:n.id,pluginId:s,kind:n.customType,data:n.data,timestamp:n.timestamp,...r?{afterMessageId:r}:{}})}}return i}function Bt(t){return typeof t=="string"?[{kind:"text",text:t}]:t.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Xx(t){let e=t.details&&typeof t.details=="object"?t.details:{},i=typeof e.description=="string"?e.description.replace(/\s+/g," ").trim():"",r=e.status==="completed"?"completed":e.status==="failed"||e.status==="error"?"failed":e.status==="cancelled"||e.status==="aborted"?"cancelled":"unknown",n=typeof e.resultPreview=="string"?e.resultPreview.trim()?Bt(e.resultPreview):[]:Bt(t.content);return{id:t.id,role:"notice",timestamp:t.timestamp,blocks:n,subagentNotice:{status:r,...i?{description:i}:{}}}}function Oi(t){if(t.type==="custom_message")return t.display?t.customType==="subagent-notification"?Xx(t):{id:t.id,role:"notice",timestamp:t.timestamp,blocks:Bt(t.content)}:null;if(t.type!=="message")return null;let{message:e}=t;return e.role==="user"||e.role==="assistant"?{id:t.id,role:e.role,timestamp:t.timestamp,blocks:Bt(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:t.id,role:"tool",timestamp:t.timestamp,blocks:Bt(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function ha(t,e){let i=t?.trim();if(i)return i;let r=e.find(s=>s.role==="user");return kn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function Av(t,e,i=[]){let r=t.sessionManager.getBranch().flatMap(n=>{let s=Oi(n);return s?[s]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:t.cwd,name:ha(e,r),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel??null,thinkingLevels:t.model?Jx(t.model):["off"],idle:t.isIdle(),paused:dr(t.sessionManager.getBranch()),contextUsage:t.getContextUsage()??null,messages:r,pluginEntries:wp(t.sessionManager.getBranch(),i)}}import{randomUUID as Sp}from"node:crypto";import{mkdir as xv,readFile as Zx,realpath as kp,rename as eO,rm as tO,stat as Ep,writeFile as iO}from"node:fs/promises";import{basename as Ov,dirname as rO,isAbsolute as Rv,join as nO}from"node:path";var In=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function Ri(t){try{let e=await kp(t);return(await Ep(e)).isDirectory()?e:null}catch(e){let i=e.code;if(i==="ENOENT"||i==="ENOTDIR")return null;throw e}}async function Et(t){let e=await Ri(t);if(e===null)throw new In;return e}var ya=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Zx(this.file,"utf8")),i,r=[];if(Array.isArray(e)?i=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(i=e.items,r=e.hiddenPaths),!Array.isArray(i)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=i.filter(n=>typeof n=="object"&&n!==null&&typeof n.id=="string"&&typeof n.path=="string"&&typeof n.title=="string"),this.hiddenPaths=r.filter(n=>typeof n=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(i=>i.id===e)}async add(e,i=!1){if(!Rv(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");i&&await xv(e,{recursive:!0});let r=await kp(e);if(!(await Ep(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let n=this.hiddenPaths.filter(l=>l!==r),s=this.items.find(l=>l.path===r);if(s)return n.length!==this.hiddenPaths.length&&(await this.save(this.items,n),this.hiddenPaths=n),s;let a={id:Sp(),path:r,title:Ov(r)||r},o=[a,...this.items];return await this.save(o,n),this.items=o,this.hiddenPaths=n,a})}async discover(e){let i=(await Promise.all([...new Set(e)].filter(Rv).map(async r=>{try{let n=await kp(r);return(await Ep(n)).isDirectory()?n:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(a=>a.path),...this.hiddenPaths]),n=[];for(let a of i)r.has(a)||(r.add(a),n.push({id:Sp(),path:a,title:Ov(a)||a}));if(n.length===0)return;let s=[...this.items,...n];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let i=this.get(e);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),n=[...new Set([...this.hiddenPaths,i.path])];await this.save(r,n),this.items=r,this.hiddenPaths=n})}mutate(e){let i=this.mutationChain.then(e,e);return this.mutationChain=i.then(()=>{},()=>{}),i}async save(e,i){await xv(rO(this.file),{recursive:!0});let r=`${this.file}.${Sp()}.tmp`;try{await iO(r,JSON.stringify({version:2,items:e,hiddenPaths:i},null,2),{mode:384}),await eO(r,this.file)}catch(n){throw await tO(r,{force:!0}),n}}};function Nv(t){return nO(t,"pi-web","workspaces.json")}import{createAgentSession as sR,createEventBus as aR,DefaultResourceLoader as oR,getAgentDir as pw,SessionManager as hr,VERSION as Sa}from"@earendil-works/pi-coding-agent";function An(t,e){return!!t?.has(e)||Object.values(He).includes(e)}var Pv="pi-webapp:interaction-open:v1",Cv="pi-webapp:interaction-accept:v1",Tp="pi-webapp:interaction-settle:v1",Dv="pi-webapp:interaction-cancel:v1",Ip=class extends Error{};function ba(t,e,i,r=300){return new Promise((n,s)=>{let a=!1,o,l=(m,g)=>{a||(a=!0,clearTimeout(o),p(),d(),i?.removeEventListener("abort",c),m?s(m):n(g))},c=()=>{t.emit(Dv,e),l(new Error("Interaction cancelled"))},p=t.on(Cv,m=>{m?.requestId===e.requestId&&clearTimeout(o)}),d=t.on(Tp,m=>{let g=m;g?.requestId===e.requestId&&l(g.error?new Error(g.error):null,g.value)});o=setTimeout(()=>l(new Ip("No Web interaction host")),r),i?.addEventListener("abort",c,{once:!0}),i?.aborted?c():t.emit(Pv,e)})}var ur=class{bus;accepts;changed;requests=new Map;detach;constructor(e,i,r){this.bus=e,this.accepts=i,this.changed=r,this.detach=[e.on(Pv,n=>{!sO(n)||!i(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(Cv,{requestId:n.requestId}),r())}),e.on(Dv,n=>{let s=n,a=this.requests.get(s?.requestId);a&&a.sessionId===s.sessionId&&a.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(i=>i.sessionId===e)}resolve(e,i,r,n){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==i||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(Tp,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let i of this.requests.values())this.bus.emit(Tp,{requestId:i.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function sO(t){if(!t||typeof t!="object")return!1;let e=t;for(let i of["requestId","sessionId","pluginId","kind"])if(typeof e[i]!="string"||!e[i]||e[i].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Ni(t){return typeof t=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(t)&&t.length<=512&&!t.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function ni(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&Ni(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Ni(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Ni(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Ni(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(i=>Number.isSafeInteger(i)&&i>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(i=>typeof i=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(i))}var aO=1,oO="pi-webapp:action:v1",lO="pi-webapp:action-response:v1",_a="pi-webapp:plugin-changed:v1";function Mv(t){if(!t||typeof t!="object")return!1;let e=t;return e.apiVersion===aO&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function va(t,e,i=15e3,r){return new Promise((n,s)=>{let a=!1,o=(d,m)=>{a||(a=!0,clearTimeout(c),l(),r?.removeEventListener("abort",p),d?s(d):n(m))},l=t.on(lO,d=>{let m=d;m?.requestId===e.requestId&&o(m.ok?null:new Error(m.error??"Plugin action failed"),m.value)}),c=setTimeout(()=>o(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),i),p=()=>o(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{t.emit(oO,e)}catch(d){o(d instanceof Error?d:new Error(String(d)))}})}import{realpath as lR}from"node:fs/promises";import{readFile as Ap,realpath as jv,stat as Fv}from"node:fs/promises";import{createHash as cO}from"node:crypto";import{dirname as Lv,isAbsolute as pO,join as xp,parse as dO,resolve as uO,sep as mO,delimiter as gO}from"node:path";import{DefaultPackageManager as fO,getAgentDir as hO,SettingsManager as yO}from"@earendil-works/pi-coding-agent";async function Uv(t,e){let i=await Ap(t),r=e?await Ap(e):void 0;if(i.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let n=cO("sha256").update(i).update("\0").update(r??"").digest("hex");return{clientBytes:i,styleBytes:r,revision:n}}function bO(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(gO).filter(Boolean).map(t=>uO(t))}async function _O(t){let e=Lv(t);for(;e!==dO(e).root;)try{return await Fv(xp(e,"package.json")),e}catch{e=Lv(e)}return null}async function qv(t,e){let i=await jv(xp(t,e));if(!i.startsWith(t+mO))throw new Error("Asset escapes package root");let r=await Fv(i);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return i}var Pi=class t{plugins;errors;extensionRoots;constructor(e,i,r){this.plugins=e,this.errors=i,this.extensionRoots=r}static async discover(e,i,r=bO()){let n=yO.create(e,void 0,{projectTrusted:i}),s=new fO({cwd:e,agentDir:hO(),settingsManager:n}),a=await s.resolve(async()=>"skip"),o=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},l=new Set;for(let g of[...a.extensions,...o.extensions]){if(!g.enabled)continue;let h=await _O(g.path);h&&l.add(h)}for(let g of r)pO(g)&&l.add(g);let c=[],p=[],d=[],m=new Set;for(let g of l)try{let h=await jv(g),f=JSON.parse(await Ap(xp(h,"package.json"),"utf8"));if(f.piWebapp===void 0)continue;if(typeof f.name!="string"||!f.name)throw new Error("Missing package name");if(!Mv(f.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(m.has(f.name))throw new Error(`Duplicate plugin id: ${f.name}`);let b=await qv(h,f.piWebapp.client),S=f.piWebapp.style?await qv(h,f.piWebapp.style):void 0;m.add(f.name),c.push({id:f.name,root:h,manifest:f.piWebapp,clientPath:b,stylePath:S,...await Uv(b,S)}),d.push(h)}catch(h){p.push(`${g}: ${h instanceof Error?h.message:String(h)}`)}return c.sort((g,h)=>g.id.localeCompare(h.id)),new t(c,p,d)}has(e){return this.plugins.some(i=>i.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await Uv(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let i=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(i.pathname);if(!r)return null;let n;try{n=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(o=>o.id===n);if(!s||i.searchParams.has("v")&&i.searchParams.get("v")!==s.revision)return null;let a=r[2]==="client.js"?s.clientBytes:s.styleBytes;return a?{bytes:a,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as vO}from"node:fs/promises";import{SessionManager as wO}from"@earendil-works/pi-coding-agent";async function Ci(t,e){let i=await Et(t),r=e??await wO.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await vO(s.cwd).catch(()=>null)===i));return r.filter((s,a)=>n[a])}import{createReadStream as SO}from"node:fs";import{readdir as kO,readFile as EO,stat as TO}from"node:fs/promises";import{basename as IO,join as AO}from"node:path";import{createInterface as xO}from"node:readline";import{parseSessionEntries as Wv}from"@earendil-works/pi-coding-agent";function Bv(t){switch(t){case"background":case"running":return"running";case"completed":return"completed";case"error":case"failed":case"launch-error":return"failed";case"stopped":case"aborted":case"cancelled":return"cancelled";default:return"unknown"}}var Hv=t=>typeof t=="string"&&t.replace(/\s+/g," ").trim().slice(0,160)||void 0;async function OO(t){let e=new Map,i=new Map,r=new Map,n=[],s=xO({input:SO(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let a of s){if(!a.includes('"Agent"')&&!a.includes('"steer_subagent"')&&!a.includes('"subagents:record"'))continue;let o=Wv(a)[0];if(!o)continue;if(o.type==="custom"&&o.customType==="subagents:record"){let g=o.data;typeof g?.id=="string"&&r.set(g.id,{status:Bv(g.status),description:Hv(g.description)})}if(o.type!=="message")continue;let l=o.message;if(l.role==="assistant")for(let g of l.content)g.type==="toolCall"&&(g.name==="Agent"||g.name==="steer_subagent")&&i.set(g.id,{name:g.name,args:g.arguments});if(l.role!=="toolResult"||l.isError)continue;let c=i.get(l.toolCallId);if(!c||c.name!==l.toolName)continue;if(i.delete(l.toolCallId),c.name==="steer_subagent"){let g=l.content.find(f=>f.type==="text")?.text,h=/^Steering message sent to agent ([\w-]+)\./.exec(g??"")?.[1];h&&typeof c.args.message=="string"&&n.push({agentId:h,text:c.args.message});continue}let p=l.details,d=p?.agentId,m=p?.subagentType??c.args.subagent_type;typeof d!="string"||typeof m!="string"||typeof c.args.prompt!="string"||e.set(d,{agentId:d,agentType:m,dispatchCallId:l.toolCallId,prompt:c.args.prompt,status:Bv(p?.status),description:Hv(p?.description??c.args.description),steering:[]})}for(let[a,o]of r){let l=e.get(a);l&&(l.status=o.status,l.description=o.description??l.description)}for(let{agentId:a,text:o}of n)e.get(a)?.steering.push(o);return[...e.values()]}var Di=new Map;async function RO(t){let e=await TO(t).catch(()=>null);if(!e?.isFile())return[];let i=`${e.ino}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`,r=Di.get(t);if(r?.key===i)return r.value;let n=OO(t).catch(()=>(Di.get(t)?.key===i&&Di.delete(t),[]));return Di.set(t,{key:i,value:n}),Di.size>256&&Di.delete(Di.keys().next().value),n}async function mr(t,e,i=new Set){let r=new Map(t.map(c=>[c.path,c])),n=new Map,s=t.filter(c=>c.parentSessionPath&&/#[a-f\d]{8}$/i.test(c.name??"")),a=s.some(c=>!r.has(c.parentSessionPath))?await kO(e,{withFileTypes:!0}).catch(()=>[]):[],o=new Map(a.filter(c=>c.isFile()&&/^\d+_.+\.jsonl$/.test(c.name)).map(({name:c})=>[c.replace(/^\d+_/,""),AO(e,c)])),l=new Map;for(let c of s){let p=c.parentSessionPath,d=r.get(p),m=d?.path??o.get(IO(p));if(!m||m===c.path)continue;let g=l.get(m);g||(g=RO(m),l.set(m,g));let h=(await g).filter(R=>c.name?.endsWith(`#${R.agentId.slice(0,8)}`)&&c.firstMessage===R.prompt);if(h.length!==1)continue;let{agentId:f,agentType:b,dispatchCallId:S,description:E,status:A,prompt:C,steering:N}=h[0];n.set(c.id,{prompt:C,steering:N,view:{parentSessionId:d?.id??null,agentId:f,agentType:b,dispatchCallId:S,description:E,status:A==="running"&&!(d&&i.has(d.id))?"unknown":A}})}return n}async function Gv(t,e,i){let[r,...n]=Wv(await EO(t,"utf8"));if(r?.type!=="session"||r.id!==e)throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E0D\u53EF\u7528");let s=[],a=[...i.steering],o=n.filter(d=>d.type!=="session"),l=new Map(o.map(d=>[d.id,d])),c=[];for(let d=o.at(-1);d&&l.delete(d.id);d=d.parentId?l.get(d.parentId):void 0)c.push(d);let p=!1;for(let d of c.reverse()){let m=Oi(d);if(m){if(m.role==="user"){let g=m.blocks.every(h=>h.kind==="text")?m.blocks.map(h=>h.text).join(" "):void 0;if(!p&&g===i.prompt)m.subagentInput="dispatch";else{let h=g===void 0?-1:a.indexOf(g);h>=0&&(m.subagentInput="steering",a.splice(h,1))}p=!0}s.push(m)}}return s}import{copyFile as NO,mkdir as PO,rename as CO,unlink as DO}from"node:fs/promises";import{basename as MO,join as $v}from"node:path";var Mi=t=>$v(t,"pi-web","trash");async function Vv(t,e){let i=Mi(e);await PO(i,{recursive:!0});let r=$v(i,`${Date.now()}_${MO(t)}`);try{await CO(t,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await NO(t,r),await DO(t)}return r}var Li=class{tail=Promise.resolve();run(e){let i=this.tail.then(e);return this.tail=i.catch(()=>{}),i}wrap(e){return(...i)=>this.run(()=>e(...i))}},zv=new WeakMap;function Kv(t,e,i,r=5e3,n=()=>{}){let s=zv.get(t);if(s)return s;let a=(async()=>{let o;try{await Promise.race([t.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((l,c)=>{o=setTimeout(()=>c(new Error("Plugin shutdown timed out")),r)})])}catch(l){i(l instanceof Error?l.message:String(l))}finally{clearTimeout(o);try{n()}finally{t.dispose()}}})();return zv.set(t,a),a}function wa(t){let i=[...t].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
544
+ `);return{customType:vp,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(i?`
548
545
  Already displayed assistant text (reference data):
549
- ${JSON.stringify(i)}`:"")}}import{createHash as CO}from"node:crypto";import{readFile as Kv,realpath as zv,writeFile as DO,unlink as MO}from"node:fs/promises";import{basename as LO,dirname as Ap,extname as UO,isAbsolute as qO,join as Yv,parse as jO,relative as FO,sep as BO}from"node:path";import{DefaultPackageManager as Qv,getAgentDir as Jv,SettingsManager as Xv}from"@earendil-works/pi-coding-agent";var xn=new Map;async function HO(t){let e=Ap(t);for(;e!==jO(e).root;){try{let i=JSON.parse(await Kv(Yv(e,"package.json"),"utf8"));if(typeof i.name=="string")return i.name}catch{}e=Ap(e)}return null}function GO(t,e){let i=FO(t,e);return i===""||i!==".."&&!i.startsWith(`..${BO}`)&&!qO(i)}async function Zv(t,e,i){let r=Xv.create(t,void 0,{projectTrusted:i}),s=await new Qv({cwd:t,agentDir:Jv(),settingsManager:r}).resolve(async()=>"skip"),a=await Promise.all(e.map(c=>zv(c))),o=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await zv(c.path);await HO(p)!=="pi-webapp"&&(a.some(d=>GO(d,p))||o.add(p))}let l=await WO(t,a);return{paths:[...l.paths,...o],release:l.release}}async function WO(t,e){let r=await new Qv({cwd:t,agentDir:Jv(),settingsManager:Xv.create(t)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],a=async()=>{for(let l of n.splice(0)){let c=(xn.get(l)??1)-1;c?xn.set(l,c):(xn.delete(l),await MO(l).catch(()=>{}))}},o=new Set;try{for(let l of r.extensions){if(!l.enabled||o.has(l.path))continue;o.add(l.path);let c=UO(l.path);if(![".js",".mjs"].includes(c)){s.push(l.path);continue}let p=await Kv(l.path),d=CO("sha256").update(p).digest("hex"),m=Yv(Ap(l.path),`.pi-web-runtime-${LO(l.path,c)}-${d}${c}`);await DO(m,p,{flag:"wx"}).catch(g=>{if(g.code!=="EEXIST")throw g}),xn.set(m,(xn.get(m)??0)+1),n.push(m),s.push(m)}return{paths:s,release:a}}catch(l){throw await a(),l}}import{createHash as $O}from"node:crypto";var xp={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},si=t=>t!==null&&typeof t=="object"?t:void 0,VO=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function tw(t,e){let i=t instanceof Error?t:si(t)?.error instanceof Error?si(t).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!i?.stack,level:"error"},n=(p,d,m)=>{Object.assign(r,{failureKind:p,errorCode:d,errorSummary:m.slice(0,512),summaryOmitted:!1,level:i?"error":"warning"}),delete r.summaryOmittedReason},s=si(i)?.code;if(typeof s=="string"&&xp[s]){let p=xp[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let a=i?.message??"";if(!i){let p=si(t)?.content;Array.isArray(p)&&(a=p.slice(0,8).flatMap(d=>{let m=si(d);return m?.type==="text"&&typeof m.text=="string"?[m.text.length>16384?`${m.text.slice(0,8192)}
546
+ ${JSON.stringify(i)}`:"")}}import{createHash as LO}from"node:crypto";import{readFile as Qv,realpath as Yv,writeFile as UO,unlink as qO}from"node:fs/promises";import{basename as jO,dirname as Op,extname as FO,isAbsolute as BO,join as Jv,parse as HO,relative as WO,sep as GO}from"node:path";import{DefaultPackageManager as Xv,getAgentDir as Zv,SettingsManager as ew}from"@earendil-works/pi-coding-agent";var xn=new Map;async function $O(t){let e=Op(t);for(;e!==HO(e).root;){try{let i=JSON.parse(await Qv(Jv(e,"package.json"),"utf8"));if(typeof i.name=="string")return i.name}catch{}e=Op(e)}return null}function VO(t,e){let i=WO(t,e);return i===""||i!==".."&&!i.startsWith(`..${GO}`)&&!BO(i)}async function tw(t,e,i){let r=ew.create(t,void 0,{projectTrusted:i}),s=await new Xv({cwd:t,agentDir:Zv(),settingsManager:r}).resolve(async()=>"skip"),a=await Promise.all(e.map(c=>Yv(c))),o=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await Yv(c.path);await $O(p)!=="pi-webapp"&&(a.some(d=>VO(d,p))||o.add(p))}let l=await zO(t,a);return{paths:[...l.paths,...o],release:l.release}}async function zO(t,e){let r=await new Xv({cwd:t,agentDir:Zv(),settingsManager:ew.create(t)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],a=async()=>{for(let l of n.splice(0)){let c=(xn.get(l)??1)-1;c?xn.set(l,c):(xn.delete(l),await qO(l).catch(()=>{}))}},o=new Set;try{for(let l of r.extensions){if(!l.enabled||o.has(l.path))continue;o.add(l.path);let c=FO(l.path);if(![".js",".mjs"].includes(c)){s.push(l.path);continue}let p=await Qv(l.path),d=LO("sha256").update(p).digest("hex"),m=Jv(Op(l.path),`.pi-web-runtime-${jO(l.path,c)}-${d}${c}`);await UO(m,p,{flag:"wx"}).catch(g=>{if(g.code!=="EEXIST")throw g}),xn.set(m,(xn.get(m)??0)+1),n.push(m),s.push(m)}return{paths:s,release:a}}catch(l){throw await a(),l}}import{createHash as KO}from"node:crypto";var Rp={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},si=t=>t!==null&&typeof t=="object"?t:void 0,YO=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function rw(t,e){let i=t instanceof Error?t:si(t)?.error instanceof Error?si(t).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!i?.stack,level:"error"},n=(p,d,m)=>{Object.assign(r,{failureKind:p,errorCode:d,errorSummary:m.slice(0,512),summaryOmitted:!1,level:i?"error":"warning"}),delete r.summaryOmittedReason},s=si(i)?.code;if(typeof s=="string"&&Rp[s]){let p=Rp[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let a=i?.message??"";if(!i){let p=si(t)?.content;Array.isArray(p)&&(a=p.slice(0,8).flatMap(d=>{let m=si(d);return m?.type==="text"&&typeof m.text=="string"?[m.text.length>16384?`${m.text.slice(0,8192)}
550
547
  [truncated]
551
548
  ${m.text.slice(-8192)}`:m.text]:[]}).join(`
552
549
  `))}let o=e==="bash"||e==="powershell",l=a.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(o){let p=l.match(/^Command exited with code (-?\d{1,10})$/),d=l.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return n("process_exit","nonzero_exit",l),r.exitCode=Number(p[1]),r;if(d&&Number.isFinite(Number(d[1]))&&Number(d[1])>0)return n("timeout","timeout",l),r.timeoutMs=Number(d[1])*1e3,r;if(l==="Command aborted")return n("cancelled","cancelled",l),r}let c=a.slice(0,8192).split(/\r?\n/,1)[0]??"";if(a==="Operation aborted"||i?.name==="AbortError")n("cancelled","cancelled","Operation aborted");else if(a==="Tool execution was blocked")n("blocked","blocked",a);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(a))n("not_found","ENOENT","Working directory does not exist");else if(!o||!a.includes(`
553
- `)||/^Validation failed for tool\b/.test(c)){let p=c.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let d=xp[p[1]],m=c.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);n(d.kind,p[1],`${p[1]}: ${d.summary}${m?`; operation=${m[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(a))n("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(c)||c==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(c))n("validation","invalid_arguments",c.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(a))n("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let d=VO.find(m=>m.pattern.test(a));d&&n("validation",d.code,d.summary)}}return r}var zO=256;function ew(t,e,i){t.delete(e),t.set(e,i),t.size>zO&&t.delete(t.keys().next().value)}var gr=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:zn.has(e.toolName)?e.toolName:"custom",...zn.has(e.toolName)?{}:{toolId:$O("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,i){try{this.options.breadcrumb(e,i)}catch{}}start(e,i={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?si(e.args)?.timeout:void 0,n=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...rt(i),...this.identity(e),stage:"tool"};ew(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:n}),this.breadcrumb("tool_start",s)}catch{}}end(e,i={}){this.finish(e,i,"tool_execution_end")}message(e,i={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},i,"message_end")}catch{}}finish(e,i,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let n=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),ew(this.completed,e.toolCallId,!0);let s={...n?.context??{...rt(i),...this.identity(e),stage:"tool"},diagnosticSource:r};if(n&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-n.started)),n.timeoutMs!==void 0&&(s.timeoutMs=n.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let a=e.result instanceof Error?e.result:si(e.result)?.error instanceof Error?si(e.result).error:void 0,o=n?.cancelled&&!a?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:tw(e.result,e.toolName);if(Object.assign(s,o,{code:"tool_failed"}),this.breadcrumb(o.failureKind==="cancelled"?"tool_cancelled":o.failureKind==="blocked"?"tool_blocked":"tool_failed",s),o.failureKind==="cancelled"||o.failureKind==="blocked")return;let l;a?l=iw(a,e.toolName):(l=new Error(`${s.toolName}: ${o.failureKind} (${o.errorCode??"unknown"})`),l.name="ToolResultFailure",l.stack=void 0),this.options.capture(l,s)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function iw(t,e,i=0){let r=tw(t,e),n=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return n.name=t.name,n.stack=t.stack?`${n.name}: ${n.message}
550
+ `)||/^Validation failed for tool\b/.test(c)){let p=c.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let d=Rp[p[1]],m=c.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);n(d.kind,p[1],`${p[1]}: ${d.summary}${m?`; operation=${m[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(a))n("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(c)||c==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(c))n("validation","invalid_arguments",c.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(a))n("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let d=YO.find(m=>m.pattern.test(a));d&&n("validation",d.code,d.summary)}}return r}var QO=256;function iw(t,e,i){t.delete(e),t.set(e,i),t.size>QO&&t.delete(t.keys().next().value)}var gr=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:zn.has(e.toolName)?e.toolName:"custom",...zn.has(e.toolName)?{}:{toolId:KO("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,i){try{this.options.breadcrumb(e,i)}catch{}}start(e,i={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?si(e.args)?.timeout:void 0,n=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...rt(i),...this.identity(e),stage:"tool"};iw(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:n}),this.breadcrumb("tool_start",s)}catch{}}end(e,i={}){this.finish(e,i,"tool_execution_end")}message(e,i={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},i,"message_end")}catch{}}finish(e,i,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let n=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),iw(this.completed,e.toolCallId,!0);let s={...n?.context??{...rt(i),...this.identity(e),stage:"tool"},diagnosticSource:r};if(n&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-n.started)),n.timeoutMs!==void 0&&(s.timeoutMs=n.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let a=e.result instanceof Error?e.result:si(e.result)?.error instanceof Error?si(e.result).error:void 0,o=n?.cancelled&&!a?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:rw(e.result,e.toolName);if(Object.assign(s,o,{code:"tool_failed"}),this.breadcrumb(o.failureKind==="cancelled"?"tool_cancelled":o.failureKind==="blocked"?"tool_blocked":"tool_failed",s),o.failureKind==="cancelled"||o.failureKind==="blocked")return;let l;a?l=nw(a,e.toolName):(l=new Error(`${s.toolName}: ${o.failureKind} (${o.errorCode??"unknown"})`),l.name="ToolResultFailure",l.stack=void 0),this.options.capture(l,s)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function nw(t,e,i=0){let r=rw(t,e),n=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return n.name=t.name,n.stack=t.stack?`${n.name}: ${n.message}
554
551
  ${t.stack.split(`
555
552
  `).slice(1).join(`
556
- `)}`:void 0,i<3&&t.cause instanceof Error&&(n.cause=iw(t.cause,e,i+1)),Gi(n)}import{randomUUID as sw}from"node:crypto";import{randomUUID as KO}from"node:crypto";import{EnvHttpProxyAgent as YO,getGlobalDispatcher as fz,setGlobalDispatcher as hz}from"undici";var rw=t=>({httpProxy:t.http_proxy??t.HTTP_PROXY??t.all_proxy??t.ALL_PROXY??"",httpsProxy:t.https_proxy??t.HTTPS_PROXY??t.all_proxy??t.ALL_PROXY??"",noProxy:t.no_proxy??t.NO_PROXY??""});function QO(t,e){let i=rw(t),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&i.httpsProxy||i.httpProxy))return!1;let n=i.noProxy.toLowerCase();if(n==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),a=r.hostname.toLowerCase();return!n.split(/[,\s]/).filter(Boolean).some(o=>{let l=o.match(/^(.+):(\d+)$/),c=(l?.[1]??o).replace(/^\*?\./,"");return(!l||Number(l[2])===s)&&(a===c||a.endsWith("."+c))})}function JO(t){let e=rw(t);for(let i of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(i).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new YO(e)}function Op({env:t=process.env,onFailure:e=()=>{},fetchRequest:i=globalThis.fetch,autoClose:r=!1}={}){let n,s=new Set,a=i===globalThis.fetch,o=(p,d)=>{try{e(p,d)}catch{}},l=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,d)=>{let m={requestId:KO(),phase:"headers",proxied:a&&QO(t,p)},g=r?void 0:n,h=!1,f=d?.signal??(p instanceof Request?p.signal:void 0),b=()=>S(),S=()=>{f?.removeEventListener("abort",b),!h&&r&&(h=!0,l(g).catch(()=>{}))},E;try{a?(g??=JO(t),s.add(g),r||(n=g),E=await i(p,{...d,dispatcher:g})):E=await i(p,d)}catch(R){throw o(R,m),S(),R}if(E.ok||o(void 0,{...m,status:E.status}),!E.body)return S(),E;let A=E.body.getReader();f?.addEventListener("abort",b,{once:!0}),f?.aborted&&S();let C=new ReadableStream({async pull(R){try{let G=await A.read();G.done?(R.close(),A.releaseLock(),S()):R.enqueue(G.value)}catch(G){o(G,{...m,phase:"body"}),R.error(G),A.releaseLock(),S()}},async cancel(R){try{await A.cancel(R)}finally{A.releaseLock(),S()}}}),N=new Response(C,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(N,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),N},close:async()=>{await Promise.all([...s].map(l))}}}var nw=(t,e)=>Op({autoClose:!0}).fetch(t,e);var XO=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),ZO=t=>typeof t=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(t)?t:void 0;function Rp(t,e={}){let i=[],r=new Set,n=(l,c=0)=>{if(!l||c>4||r.has(l)||i.length>=8)return;r.add(l);let p=ZO(l.code);if(i.push({name:XO.has(l.name)?l.name:"Error",...p?{code:p}:{}}),n(l.cause,c+1),l instanceof AggregateError)for(let d of l.errors.slice(0,4))n(d,c+1)};n(t);let s=i.flatMap(l=>l.code?[l.code]:[]),a=e.stage==="model_admission"||s.some(l=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(l))?"lifecycle":s.some(l=>/CERT|TLS|SSL/.test(l))?"tls":s.some(l=>/^PROXY_/.test(l))||e.proxied&&s.some(l=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(l))?"proxy":s.some(l=>/TIMEOUT|ETIMEDOUT/.test(l))||i.some(l=>/TimeoutError$/.test(l.name))?"timeout":i.some(l=>l.name==="AbortError"||l.code==="ABORT_ERR"||l.code==="UND_ERR_ABORTED")?"cancelled":s.some(l=>/ENOTFOUND|EAI_AGAIN/.test(l))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",o=l=>typeof l=="string"&&/^[\w-]{1,80}$/.test(l)?l:void 0;return{errorId:sw(),requestId:o(e.requestId)??sw(),...o(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:a,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:i}}function aw({env:t=process.env,onDiagnostic:e=()=>{},fetchRequest:i=globalThis.fetch}={}){return Op({env:t,fetchRequest:i,onFailure:(r,n)=>e(Rp(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function eR(t){let e={...process.env,...t};for(let i of["http_proxy","https_proxy","all_proxy","no_proxy"])t&&i.toUpperCase()in t&&!(i in t)&&delete e[i];return e}var tR=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function ow(t,e,i=()=>{}){let r=t.agent.streamFunction;t.agent.streamFunction=async(n,s,a)=>{if(!tR.has(n.api))return r(n,s,a);let o=i(),l=aw({env:eR(a?.env),...a?.fetch?{fetchRequest:a.fetch}:{},onDiagnostic:c=>{let p={...c,...o?{operationId:o}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let c=await r(n,s,{...a,fetch:l.fetch});return c.result().finally(()=>l.close()).catch(()=>{}),c}catch(c){throw await l.close(),c}}}function fr(t,e,i){try{t()}catch(r){let n=Rp(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...n})),i?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:n.errorId,requestId:n.requestId,stage:n.stage,code:"hosted_admission_blocked",networkKind:n.kind,networkStage:n.stage,causeCodes:n.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var aR=["read","grep","find","ls"];var cw=200,Sa=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Li;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,i,r=()=>!1,n=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},a=()=>{},o=[],l){this.hosted=l,this.publish=e,this.fallbackModel=i,this.isProjectTrusted=r,this.reportError=n,this.onSessionsChanged=a,this.customTools=o,this.offHosted=l?.adapter.onThaw(()=>{for(let c of this.runtimes.values())this.scheduleQueued(c)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(c,p)=>{try{s.enabled()&&s.breadcrumb(c,p)}catch{}},anonymize:c=>{try{return s.enabled()?s.anonymize(c):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await Tt(e),n=i==="continue"?this.selectedByWorkspace.get(r):typeof i=="object"&&"sessionId"in i?this.runtimes.get(i.sessionId):void 0;if(n){if(n.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(n);return}if(typeof i=="object"&&"sessionId"in i)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(i==="new")s=hr.create(r);else if(i==="continue"){let o=await hr.listAll(),l=await Ci(r,o),c=l[0]?.parentSessionPath?await mr(o,Mi(lw())):null,p=l.find(d=>!c?.has(d.id));s=p?hr.open(p.path):hr.create(r)}else s="sessionManager"in i?i.sessionManager:hr.open(i.sessionFile);if(await sR(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let a=this.runtimes.get(s.getSessionId());if(a){if(a.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(a);return}await this.replace(r,s,i==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let i=this.selectedByWorkspace.get(await Tt(e));return!i||!this.blank(i)?!1:(this.activate(i),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let i=this.runtimes.get(e);return!this.disposed&&i&&!i.closing?{cwd:i.cwd,sessionId:e}:null}hasSession(e,i){return this.runtimes.get(i)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:i,cwd:r,prompts:n}=e,s=i.sessionManager.getBranch(),a=s.flatMap(o=>{let l=Oi(o);return l?[l]:[]});return{sessionId:i.sessionManager.getSessionId(),cwd:r,path:i.sessionManager.getSessionFile()??null,idle:i.isIdle&&!n.sending,name:fa(i.sessionManager.getSessionName(),a),modified:s.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(i=>Oi(i)?.role==="user")}rename(e,i){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(i),!0}discard(e){return this.queue.run(async()=>{let i=this.runtimes.get(e);if(!i||i.closing)return null;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!i.session.isIdle||i.prompts.sending||i.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===i,n=i.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(i.cwd)===i&&this.selectedByWorkspace.delete(i.cwd),r&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged(),{path:n,cwd:i.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,i){!this.disposed&&this.active===e&&!e.closing&&this.publish(i)}diagnostic(e,i,r,n){let s=`plugin=${i} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${n}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,i,r,n){let s=this.runtimes.get(i.getSessionId()),a=await Pi.discover(e,this.isProjectTrusted(e)),o=rR(),l=await Zv(e,a.extensionRoots,this.isProjectTrusted(e)),c=new nR({cwd:e,agentDir:lw(),noExtensions:!0,additionalExtensionPaths:l.paths,eventBus:o,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,i.getSessionId()))]:[]}),p=null;try{await c.reload();let d=c.getExtensions().errors;if(d.length)throw new Error(d.map(P=>`${P.path}: ${P.error}`).join("; "));let m=i.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:g}=await iR({cwd:e,sessionManager:i,model:m,resourceLoader:c,customTools:this.customTools}),h=new gr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(P,I)=>this.telemetry.breadcrumb(P,I),anonymize:P=>this.telemetry.anonymize(P)}),f={session:g,cwd:e,catalog:a,bus:o,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:l.release,tools:h,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};f.prompts=s?.prompts??new ti(()=>{let P=this.runtimes.get(i.getSessionId())??f;this.publishFor(P,{type:"snapshot",session:this.snapshotOf(P)}),!this.disposed&&!P.closing&&this.onSessionsChanged()}),p=f,ow(g,P=>{f.networkDiagnostic=P},()=>f.operation?.operationId);let b=P=>this.publishFor(f,P),S=f.detached,E=(P,I)=>{S&&(S.events.push({seq:++S.seq,type:P,...I===void 0?{}:{text:I}}),S.events.length>cw&&S.events.splice(0,S.events.length-cw))};f.interactions=new ur(o,P=>!f.closing&&P.sessionId===g.sessionManager.getSessionId()&&An(a,P.pluginId),()=>b({type:"snapshot",session:this.snapshotOf(f)}));let A=0,C=o.on(ba,()=>b({type:"snapshot",session:this.snapshotOf(f)})),N=g.subscribe(P=>{if(S&&!f.closing&&(P.type==="message_end"&&P.message.role==="assistant"&&(P.message.stopReason==="error"?E("error",P.message.errorMessage??"Agent response failed"):S.lastText=P.message.content.flatMap(I=>I.type==="text"?[I.text]:[]).join(`
557
- `)),P.type==="agent_settled"&&E("turn_end",S.lastText)),!this.disposed&&!f.closing){let I={...f.operation,session:this.telemetry.anonymize(g.sessionManager.getSessionId()),piVersion:wa,model:g.model?`${g.model.provider}/${g.model.id}`:null,thinkingLevel:g.thinkingLevel};if(P.type==="agent_start"&&(f.activityId++,this.telemetry.breadcrumb("agent_start",I)),P.type==="tool_execution_start"&&h.start(P,I),P.type==="tool_execution_end"&&h.end(P,I),P.type==="message_end"&&P.message.role==="assistant"&&P.message.stopReason==="error"){f.agentErrorReported=!0;let x=f.networkDiagnostic,L=this.reportError(new Error("Agent response failed"),{...f.operation,stage:"agent",code:"agent_failed",piVersion:wa,...x?{networkKind:x.kind,networkStage:x.stage,causeCodes:x.causes.flatMap(U=>U.code?[U.code]:[]).join(","),requestId:x.requestId}:{}})??x?.errorId;b({type:"error",message:P.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:L,inTranscript:!0,...f.operation})}P.type==="message_end"&&P.message.role==="toolResult"&&h.message(P.message,I),P.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",I),h.clear(),f.operation=void 0)}P.type==="message_update"&&P.message.role==="assistant"&&(f.streaming={id:"stream",role:"assistant",timestamp:new Date(P.message.timestamp).toISOString(),blocks:Bt(P.message.content)},Date.now()-A>=60&&(A=Date.now(),b({type:"stream",message:f.streaming}))),P.type==="agent_settled"&&this.scheduleQueued(f),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(P.type)&&((P.type==="message_end"&&P.message.role==="assistant"||P.type==="agent_settled")&&(f.streaming=null,b({type:"stream",message:null})),b({type:"snapshot",session:this.snapshotOf(f)}),!this.disposed&&!f.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(P.type)&&this.onSessionsChanged())});f.detach=()=>{C(),N()},f.releaseHosted=this.hosted?.adapter.attach(g);let R=[],G=!0;if(await g.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:P=>{G&&R.push(P.error),this.diagnostic(f,a.plugins.find(I=>P.extensionPath.startsWith(I.root+"/"))?.id??P.extensionPath,P.event??"runtime",P.error)}}),G=!1,R.length)throw new Error(R.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");f.detached&&(f.detached.restoreTools=g.getActiveToolNames(),g.setActiveToolsByName(aR)),this.runtimes.set(g.sessionManager.getSessionId(),f),p=null,f.detached?this.onSessionsChanged():this.activate(f)}catch(d){throw this.hosted?.adapter.releasePending(i.getSessionId()),p?await this.close(p,"quit"):(o.clear(),await l.release()),d}}async close(e,i){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await Vv(e.session,i,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:i,cwd:r,catalog:n}=e,s=i.sessionManager.getBranch().flatMap(a=>{let o=Oi(a);return o?[o]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:r,name:fa(i.sessionManager.getSessionName(),s),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel,thinkingLevels:i.getAvailableThinkingLevels(),idle:i.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:dr(i.sessionManager.getBranch()),promptQueue:{steering:[...i.getSteeringMessages()],followUp:[...i.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:i.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(i.sessionManager.getSessionId()),pluginEntries:_p(i.sessionManager.getBranch(),n.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let i=this.active;if(this.disposed||!i||i.closing||e.sessionId!==i.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=i.session.extensionRunner,n=await _a(i.bus,e,15e3,i.waitController.signal);if(this.active!==i||i.closing||r!==i.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),n}requestInteraction(e,i){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):ya(r.bus,e,i)}resolveInteraction(e,i,r,n){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,i,r,n)}async send(e,i=[],r,n){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(ei(this.snapshot(),e,n),n==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,i,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new Le("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,i,r,n)}async prompt(e,i,r,n,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");fr(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),ei({...this.snapshotOf(e),idle:e.session.isIdle},i,s);let a=e.session,o=a.isIdle;o&&(e.operation=n,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...n,piVersion:wa});let l=!1,c,p,d=new Promise((m,g)=>{c=m,p=g});a.prompt(i,{images:r,streamingBehavior:s,preflightResult:m=>{m&&(l=!0,c())}}).then(()=>{l||c()}).catch(m=>{if(!l)p(m);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let g=this.reportError(xt(m,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:wa});this.publishFor(e,{type:"error",message:m instanceof Error?m.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:g,...n})}});try{await d}catch(m){throw o&&(e.operation=void 0),m}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!dr(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(i,r,n)=>this.prompt(e,i,r,n))}async updateQueuedPrompt(e,i,r){let n=this.active;if(this.disposed||!n||n.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&n.session.isIdle)throw new Le("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await n.prompts.update(e,i,r,(s,a,o)=>this.prompt(n,s,a,o,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Tn),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");fr(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=i.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!dr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!dr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=va(this.snapshotOf(i).messages);i.operation=e,i.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(a=>{if(!this.disposed&&!i.closing&&!i.agentErrorReported){let o=this.reportError(xt(a,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(i,{type:"error",message:a instanceof Error?a.message:"\u7EE7\u7EED\u5931\u8D25",errorId:o,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(i=>({provider:i.provider,id:i.id,name:i.name}))}async setModel(e,i){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let n=r.session.modelRuntime.getModel(e,i);if(!n)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(n),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,i,r){return this.queue.run(async()=>{this.ensureAvailable();let n=await Tt(e),s=hr.create(n);return await this.replace(n,s,"new",i),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let i=this.runtimes.get(e);return!this.disposed&&i?.detached&&!i.closing?i:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(i=>i.detached?.owner===e&&!i.closing).length}async sendDetached(e,i,r){let n=this.detachedRuntime(e);if(!n)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&n.detached.restoreTools&&(n.session.setActiveToolsByName(n.detached.restoreTools),n.detached.restoreTools=null),!n.session.isIdle||n.prompts.length>0){n.prompts.enqueue(i,[],void 0),this.scheduleQueued(n);return}await this.prompt(n,i,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let i=this.detachedRuntime(e);i&&(this.runtimes.delete(e),this.active===i&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged())})}detachedEvents(e,i){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(n=>n.seq>i),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(i=>this.close(i,"quit")))})}};import{basename as Np,dirname as oR}from"node:path";function pw(t,e){let i=r=>e[r].map(n=>({name:r==="skills"&&Np(n.path).toLowerCase()==="skill.md"?Np(oR(n.path)):Np(n.path),path:n.path,source:n.metadata.source,scope:n.metadata.scope,enabled:n.enabled}));return{packages:t.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:i("extensions"),skills:i("skills")}}import{execFile as lR}from"node:child_process";var cR=(t,e)=>new Promise((i,r)=>{lR(t,[...e],{windowsHide:!0},n=>{n?r(n):i()})});async function Pp(t,e=process.platform,i=process.env,r=cR){if(i.PI_WEBAPP_AUTO_OPEN==="0"||i.PI_WEBAPP_RUNTIME==="desktop"||i.SSH_CONNECTION||i.SSH_TTY||i.SSH_CLIENT||e==="linux"&&!i.DISPLAY&&!i.WAYLAND_DISPLAY)return!1;let n=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;if(n===null)return!1;let s=e==="darwin"||e==="win32"?await Promise.resolve().then(()=>(ma(),_v)).catch(()=>{}):void 0;return await r(n,[s?await s.localFileLaunchUrl(t,e,i):t]),!0}import{execFile as aN}from"node:child_process";import{randomUUID as Qp}from"node:crypto";import{existsSync as Fw}from"node:fs";import{access as oN,mkdir as Pn,mkdtemp as lN,readFile as oi,realpath as cN,rename as Bw,rm as Hw,writeFile as Gw}from"node:fs/promises";import{join as ue}from"node:path";import{createHash as Mp}from"node:crypto";import{readdir as yR,realpath as hw,rename as bR,stat as _R}from"node:fs/promises";import{join as ai}from"node:path";import{constants as Cp}from"node:fs";import{DatabaseSync as pR}from"node:sqlite";import{lstat as mw,mkdir as dR,open as On,rename as uR,unlink as gw}from"node:fs/promises";import{dirname as mR,join as dw,resolve as gR}from"node:path";import{randomUUID as fR}from"node:crypto";import{setTimeout as hR}from"node:timers/promises";async function Se(t){await dR(t,{recursive:!0,mode:448});let e=await mw(t);if(!e.isDirectory()||e.isSymbolicLink())throw new y("invalid_storage","Plugin storage must be a real directory")}async function ye(t,e){let i;try{i=await On(t,Cp.O_RDONLY|Cp.O_NONBLOCK|(Cp.O_NOFOLLOW??0))}catch(r){if(ii(r))return null;throw r}try{let r=await i.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new y("invalid_storage","Invalid storage record size or type");let n=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<n.length;){let a=await i.read(n,s,n.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==r.size)throw new y("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await i.close()}}async function ke(t,e=2*1024*1024){let i=await ye(t,e);if(!i)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new y("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function Ye(t){let e=await ye(t,2097152);if(e===null)return null;let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new y("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!i||typeof i!="object"||Array.isArray(i))throw new y("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return i}async function te(t,e){let i=`${t}.${fR()}.tmp`,r=await On(i,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await uR(i,t);let n;try{n=await On(mR(t),"r"),await n.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await n?.close()}}finally{await gw(i).catch(()=>{})}}var fw='{"version":2,"mechanism":"sqlite-exclusive"}',uw=t=>t.toString("utf8")===fw,ka=new Set;async function Dp(t,e,i=0){await Se(t);let r=dw(t,`${e}.lock`),n=dw(t,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new y(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),o;try{o=await On(n,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await o?.close()}let l=await mw(n);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new y("invalid_storage","Ownership database must be a small, single-link regular file");let c=new pR(n,{allowExtension:!1}),p=gR(n),d=Date.now()+i,m=!1;try{for(;;){if(!ka.has(p))try{c.exec("BEGIN EXCLUSIVE"),ka.add(p),m=!0;break}catch(f){if(f.errcode!==5)throw f}if(Date.now()>=d)throw new y(s,"Another host owns this plugin storage; wait for it to stop before retrying");await hR(10)}let h=await ye(r,4096);if(h===null){let f;try{f=await On(r,"wx",384),await f.writeFile(fw),await f.sync()}catch(b){if(b.code!=="EEXIST")throw b}finally{await f?.close()}h=await ye(r,4096)}if(h===null||!uw(h))throw a()}catch(h){throw c.close(),m&&ka.delete(p),h}let g=!1;return async()=>{if(g)return;let h=await ye(r,4096);if(h===null||!uw(h))throw new y("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await gw(r),c.close(),ka.delete(p),g=!0}}async function Ee(t,e,i=2e3){let r=await Dp(t,"transaction",i);try{return await e()}finally{await r()}}var Ea=t=>ai(t,"host-pair"),vR=t=>Mp("sha256").update(JSON.stringify(t)).digest("hex"),wR=10*6e4;async function SR(t){let e=Mp("sha256"),i=0,r=0;async function n(s){let a=(await yR(ai(t,s),{withFileTypes:!0})).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0);for(let o of a){if(!s&&o.name==="node_modules")continue;let l=s?`${s}/${o.name}`:o.name;if(o.isSymbolicLink()||!o.isFile()&&!o.isDirectory())throw new y("host_pair_required","Candidate package contains non-regular resources");if(++i>1e4)throw new y("host_pair_required","Candidate package resource budget exceeded");if(o.isDirectory()){await n(l);continue}let c=await ye(ai(t,l),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new y("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([l,Mp("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function Lp(t,e){let i=await hw(e),r=ai(e,"dist","hosted-worker.js");if(await hw(r)!==ai(i,"dist","hosted-worker.js"))throw new y("host_pair_required","Candidate worker must remain inside the staged host");let n=await ye(ai(e,"package.json"),512*1024);if(!n)throw new y("host_pair_required","Candidate package metadata missing");let s=JSON.parse(n.toString("utf8")),a=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==t||a?.protocol!==2||a?.runtimeProtocol!==1||a?.pairJournal!==1||a?.ownershipProtocol!==2||!Array.isArray(a?.capabilities)||!["state","workspace","legacy","panels","messages"].every(l=>a.capabilities.includes(l)))throw new y("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let o=await ye(r,32*1024*1024);if(!o)throw new y("host_pair_required","Candidate worker missing");return vR([n.toString("base64"),o.toString("base64"),await SR(e)])}async function Ta(t){await bR(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var kR=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function Up(t){let e=ai(Ea(t),"intent.json"),i,r=!0;try{i=await Ye(e)}catch{i=null,r=!1}if(!r||i&&!kR(i))return await Ta(e),null;if(i){let{lifecyclePhase:n,...s}=i,a=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await _R(e).then(o=>o.mtime.toISOString(),()=>new Date(0).toISOString());i={...s,updatedAt:a,phase:s.phase==="selected"&&n==="restart-requested"?"restart-requested":s.phase==="reconciled"&&n==="cancelled"?"cancelled":s.phase==="reconciled"&&n==="required-action"?"required-action":s.phase}}return i}async function Ia(t,e){let{lifecyclePhase:i,...r}={...e,selections:[],updatedAt:new Date().toISOString()},n=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await te(ai(Ea(t),"intent.json"),n)}var qp=t=>t&&["selecting","selected","restart-requested"].includes(t.phase),yw=(t,e=Date.now())=>!!t&&!!qp(t)&&e-Date.parse(t.updatedAt??"")<wR;import{promisify as pN}from"node:util";import{realpathSync as vw,statSync as ER}from"node:fs";import{basename as TR,delimiter as IR,dirname as bw,join as jp,resolve as AR}from"node:path";function _w(t){if(!t)return null;try{let e=vw(t);return TR(e)==="npm-cli.js"&&ER(e).isFile()?e:null}catch{return null}}function xR({execPath:t=process.execPath,env:e=process.env}={}){let i=_w(e.npm_execpath);if(i)return i;let r=new Set([bw(t)]);try{r.add(bw(vw(t)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(IR).filter(Boolean))r.add(AR(s));for(let s of r)for(let a of[jp(s,"node_modules","npm","bin","npm-cli.js"),jp(s,"..","lib","node_modules","npm","bin","npm-cli.js"),jp(s,"npm")]){let o=_w(a);if(o)return o}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function ww(t){return{file:process.execPath,args:[xR(),...t]}}import{randomUUID as OR}from"node:crypto";import{mkdir as Ew,readFile as RR,rename as Bp,rm as NR,unlink as b7,writeFile as PR}from"node:fs/promises";import{isAbsolute as Sw,join as Rn}from"node:path";var Hp=1,CR=1440*6e4,Aa=t=>Rn(t,"pi-web","upgrade"),Gp=t=>Rn(Aa(t),"candidate.json"),DR=t=>Rn(Aa(t),"transaction.json"),kw=t=>Rn(Aa(t),"history"),Tw=/^[a-f0-9-]{36}$/i;async function MR(t,e){let i=`${t}.${OR()}.tmp`;try{await PR(i,e,{mode:384}),await Bp(i,t)}finally{await NR(i,{force:!0})}}var LR=(t,e)=>MR(t,JSON.stringify(e));async function Fp(t,e){await Bp(t,`${t}.${e}-${Date.now()}`).catch(i=>{if(i?.code!=="ENOENT")throw i})}async function Iw(t,e,i=()=>!1){let r;try{r=JSON.parse(await RR(t,"utf8"))}catch(n){return n?.code==="ENOENT"||await Fp(t,"invalid"),null}return e(r)?i(r)?(await Fp(t,"expired"),null):r:(await Fp(t,"invalid"),null)}function Aw(t){if(!t||typeof t!="object"||t.schema!==Hp||!Tw.test(t.id??""))return!1;try{Et(t.version)}catch{return!1}return typeof t.launcher=="string"&&Sw(t.launcher)&&typeof t.packageRoot=="string"&&Sw(t.packageRoot)&&["stable","alpha"].includes(t.channel)&&typeof t.downgrade=="boolean"&&!Number.isNaN(Date.parse(t.createdAt??""))}async function xa(t,e=Date.now()){return Iw(Gp(t),Aw,i=>e-Date.parse(i.createdAt)>CR)}async function xw(t,e){let i={schema:Hp,createdAt:new Date().toISOString(),...e};if(!Aw(i))throw new Error("Invalid upgrade candidate");return await Ew(Aa(t),{recursive:!0,mode:448}),await LR(Gp(t),i),i}async function Wp(t,e,i){let r=await xa(t);!r||e&&r.id!==e||(await Ew(kw(t),{recursive:!0,mode:448}),await Bp(Gp(t),Rn(kw(t),`${r.id}-candidate-${i}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var UR=["selected","committed","rolled-back"];function qR(t){return!!t&&typeof t=="object"&&t.schema===Hp&&Tw.test(t.id??"")&&UR.includes(t.phase)&&typeof t.version=="string"&&typeof t.from=="string"&&!Number.isNaN(Date.parse(t.updatedAt??""))}async function Ow(t){return Iw(DR(t),qR)}import{readFile as jR,rename as FR,writeFile as BR,unlink as HR}from"node:fs/promises";import{join as GR}from"node:path";import{randomUUID as WR}from"node:crypto";var $p=1,Rw=t=>GR(t,"pi-web","launcher-handoff.json");function Nw(t){return t?.protocol===$p&&typeof t.nonce=="string"&&t.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(t.requestId)&&Number.isSafeInteger(t.pid)&&t.pid>0&&["requested","draining","stopped","refused","failed"].includes(t.phase)}async function Vp(t){try{let e=JSON.parse(await jR(Rw(t),"utf8"));if(!Nw(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function $R(t,e){let i=`${t}.${WR()}.tmp`;try{await BR(i,JSON.stringify(e),{mode:384}),await FR(i,t)}finally{await HR(i).catch(()=>{})}}async function Pw(t,e){if(!Nw(e))throw new Error("Invalid launcher handoff receipt");await $R(Rw(t),e)}import{execFile as VR}from"node:child_process";import{cp as zR,readFile as zp,realpath as KR,rm as YR}from"node:fs/promises";import{join as yr,sep as QR}from"node:path";import{promisify as JR}from"node:util";var Cw=JR(VR),Kp=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Yp(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=t;return Kp.map(i=>{let r=e[i];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${i}@${r}`})}async function Oa(t){return Promise.all(Kp.map(async e=>{let i=await pr(t,e),r=JSON.parse(await zp(yr(i,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Dw(t,e){let i=JSON.parse(await zp(yr(e,"package.json"),"utf8"));if(i.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=i.peerDependencies===void 0?await Oa(t):Yp(i.peerDependencies);if(JSON.stringify(await Oa(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let n=await pr(t,"node-pty"),s=await pr(e,"node-pty"),a=await KR(yr(e,"../.."));if(n===s||!s.startsWith(a+QR))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let o=async d=>JSON.parse(await zp(yr(d,"package.json"),"utf8")).version;if(await o(n)!==await o(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await YR(s,{recursive:!0,force:!0}),await zR(n,s,{recursive:!0});let l={...process.env};delete l.NODE_OPTIONS,delete l.NODE_PATH,delete l.ELECTRON_RUN_AS_NODE,await Cw(process.execPath,[yr(e,"desktop","check-pty.cjs")],{cwd:e,env:l,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await pr(e,Kp[0]),{stdout:p}=await Cw(process.execPath,[yr(c,"dist","bundle","cli.js"),"--version"],{cwd:e,env:l,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}import{lstat as Lw,readdir as Uw,readFile as XR,realpath as Mw,rm as ZR}from"node:fs/promises";import{join as Nn,relative as eN,sep as qw}from"node:path";var tN=1440*6e4,iN=1024*1024,rN=4,nN=t=>t==="releases"||t==="history"||t.endsWith("-history");async function sN(t,e){let i=new Set,r=[...new Set(e.flatMap(a=>[a+qw,a+"/"]))],n=a=>{if(typeof a=="string")for(let o of r){let l=a.indexOf(o);l>=0&&i.add(a.slice(l+o.length).split(/[\\/]/)[0])}else Array.isArray(a)?a.forEach(n):a&&typeof a=="object"&&Object.values(a).forEach(n)},s=async(a,o)=>{let l=await Uw(a,{withFileTypes:!0}).catch(()=>[]);for(let c of l){let p=Nn(a,c.name);if(c.isDirectory()){o<rN&&!nN(c.name)&&await s(p,o+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await Lw(p)).size>iN)continue;n(JSON.parse(await XR(p,"utf8")))}catch{}}};return await s(t,0),i}async function jw(t){let e=Nn(t.agentDir,"pi-web"),i;try{i=await Mw(Nn(e,"releases"))}catch{return[]}let r=t.now??Date.now(),n=t.graceMs??tN,s=await sN(e,[Nn(e,"releases"),i]);try{let o=eN(i,await Mw(t.packageRoot));o&&!o.startsWith("..")&&s.add(o.split(qw)[0])}catch{}let a=[];for(let o of await Uw(i,{withFileTypes:!0}).catch(()=>[])){if(!o.isDirectory()||s.has(o.name))continue;let l=Nn(i,o.name);try{if(r-(await Lw(l)).mtimeMs<n)continue;await ZR(l,{recursive:!0,force:!0}),a.push(o.name)}catch{}}return a}var dN=pN(aN),br=t=>["committed","cancelled","failed"].includes(t);function Ww(t){let e=t.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function uN(t,e){try{let i=ww(t),{stdout:r}=await dN(i.file,i.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(i){let r=i;throw new Error(r.stderr?.trim()||r.message)}}var Ra=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??uN,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async i=>{let r=(await this.runNpm(["view",`pi-webapp@${i}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return Oa(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Yp(s)},this.verifyPackage=e.verifyPackage??Dw,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?$p:0}}async requestLauncherHandoff(e,i){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(i))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!br(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let n=ue(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await oi(n,"utf8")),a=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!a(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let o=await Vp(this.agentDir);if(o?.nonce===e&&["requested","draining"].includes(o.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let l,c=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(l=await this.beforeRestart(),!a(JSON.parse(await oi(n,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:i,pid:s.pid,phase:"requested"};try{await Pw(this.agentDir,p),c=!0}catch(d){let m=await Vp(this.agentDir).catch(()=>null);if(c=m?.nonce===e&&m?.requestId===i&&["requested","draining","stopped"].includes(m.phase),!c)throw d}this.restartPending=!0}finally{!c&&l&&await l()}}async current(){let e=JSON.parse(await oi(ue(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Et(e.version),e.version}async pruneReleases(){if(this.preparing||this.preparedUpdate||this.restartPending||this.cancellation)return[];let e=await this.transaction();return e&&!br(e.phase)?[]:jw({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),i=await this.transaction();if(!i||br(i.phase)||i.id===this.ownTransaction)return e;if(i.version===e&&["selecting","selected","restart-requested"].includes(i.phase))await this.record({...i,phase:"committed",message:"Selected version is running"});else if(i.phase==="restart-requested"){let r=await Ow(this.agentDir);await this.record({...i,phase:"failed",message:r?.id===i.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Wp(this.agentDir,i.id,"superseded"),await this.record({...i,phase:"failed",message:`Interrupted while ${i.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return ue(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await Ye(this.transactionPath)}catch{return await Ta(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await Ta(this.transactionPath),null):e:null}async record(e){if(await Pn(ue(this.agentDir,"pi-web"),{recursive:!0}),await te(this.transactionPath,e),br(e.phase)){let i=ue(this.agentDir,"pi-web","update-history");await Pn(i,{recursive:!0}),await te(ue(i,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),i=await xa(this.agentDir);i&&(!e||i.id===e.id)&&await Wp(this.agentDir,i.id,"cancelled"),e&&!br(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return ue(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await oi(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let i=`${this.preferencePath}.${Qp()}.tmp`;try{await Pn(ue(this.agentDir,"pi-web"),{recursive:!0}),await Gw(i,JSON.stringify({channel:e}),{mode:384}),await Bw(i,this.preferencePath)}finally{this.savingPreference=!1,await Hw(i,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),i=await this.channel(),r=Fw(ue(this.packageRoot,".git")),n={current:e,channel:i,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(n.launcher=this.launcherIdentity(),n.launcherHandoff={supported:n.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(n.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!br(s.phase)?n.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(n.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...n,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&i==="alpha"&&!this.desktopReleaseChannels)return{...n,canRestart:!1,reason:n.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?n.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":n.canRestart||(n.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&n.canRestart&&(n.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let a=JSON.parse((await this.runNpm(["view","pi-webapp",i==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),o=Array.isArray(a)&&a.length===1?a[0]:a,l=i==="alpha"?o:{latest:o};if(!l||!uv(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let c=l.latest;if(i==="alpha"&&l.alpha!==void 0){if(!la(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");Ke(l.alpha,c)>0&&(c=l.alpha)}if(n.latest=c,n.downgrade=Ke(c,e)<0,n.available=i==="stable"?Ke(c,e)!==0:Ke(c,e)>0,n.available&&this.pluginWarnings){let p=await this.pluginWarnings(c).catch(()=>[]);p.length&&(n.pluginWarnings=p)}this.desktopManaged&&n.downgrade&&!this.desktopReleaseChannels&&Ke(c,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(n.canRestart=!1,n.requiresDesktopUpgrade=!0,n.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(a){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`)}return n}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let i=this.prepareUpdate(e);this.preparation=i;try{return await i}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(Fw(ue(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let i=await this.check();if(e.channel!==i.channel||e.version!==i.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let i=await this.check();if(e&&(e.channel!==i.channel||e.version!==i.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!i.canRestart)throw new Error(i.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!i.available||!i.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(i.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=ue(this.agentDir,"pi-web","releases");await Pn(r,{recursive:!0});let n=await lN(ue(await cN(r),`${i.latest}-`)),s=ue(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),a={schema:1,id:Qp(),phase:"downloading",version:i.latest,channel:i.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=a.id,await this.record(a);try{let o=this.desktopManaged?await this.targetPeerSpecs(i.latest):[];await this.runNpm(["install",`pi-webapp@${i.latest}`,...o,"--prefix",n,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=ue(n,"node_modules","pi-webapp");a={...a,phase:"validating",packageRoot:l},await this.record(a);let c=JSON.parse(await oi(ue(l,"package.json"),"utf8"));if(c.name!=="pi-webapp"||c.version!==i.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await oi(ue(this.packageRoot,"package.json"),"utf8"));if(i.downgrade&&Ww(c)!==Ww(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let d=ue(l,"bin","pi-webapp.mjs");return await Promise.all([d,ue(l,"dist","extension.js"),ue(l,"web","dist","index.html")].map(m=>oN(m))),this.desktopManaged&&(await up(this.agentDir,{version:i.latest,launcher:d,desktopProtocolVersion:ri}),await this.verifyPackage(this.packageRoot,l)),await this.prefetchPlugins?.(i.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await xw(this.agentDir,{id:a.id,version:i.latest,launcher:d,packageRoot:l,channel:i.channel??"stable",downgrade:!!i.downgrade}),a={...a,phase:"prepared"},await this.record(a),this.preparedUpdate={id:a.id,update:{version:i.latest,launcher:d},channel:i.channel??"stable"},{version:i.latest,launcher:d}}catch(o){await Hw(n,{recursive:!0,force:!0});let l=(o instanceof Error?o.message:String(o)).slice(0,500);throw await this.record({...a,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${l}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),o}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:i=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let n,s=!1,a=ue(this.agentDir,"pi-web","launcher.restart");try{if(n=await this.beforeRestart?.(i),(await xa(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let o=await this.transaction();o?.id===r.id&&await this.record({...o,phase:"restart-requested"});try{if(JSON.parse(await oi(a,"utf8"))?.nonce!==this.launcherNonce){let c=ue(this.agentDir,"pi-web","restart-history");await Pn(c,{recursive:!0,mode:448}),await Bw(a,ue(c,`stale-${Qp()}.json`))}}catch{}try{await Gw(a,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(l){try{let c=JSON.parse(await oi(a,"utf8"));s=c.nonce===this.launcherNonce&&c.candidate===r.id}catch{}if(!s)throw l}this.restartPending=!0}catch(o){if(s){this.restartPending=!0;return}let l=await this.transaction();throw l?.id===r.id&&l.phase==="restart-requested"&&await this.record({...l,phase:"prepared"}),n&&await n(),o}}};import{createHash as C0,randomUUID as SP}from"node:crypto";import{randomUUID as J1}from"node:crypto";import{join as hd}from"node:path";import{randomUUID as zw}from"node:crypto";import{randomUUID as mN}from"node:crypto";function $w(t){let i=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(a=>typeof t[a]!="function").map(a=>String(a));if(i.length)return{supported:!1,missing:i};let r=`__pi_web_contract_${mN().replaceAll("-","")}`,n;try{if(n=t.getActiveTools(),!Array.isArray(n))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{t.registerTool(s),t.setActiveTools([...n,r]),(t.getAllTools().find(o=>o.name===r)?.exposure!=="hidden"||t.getActiveTools().includes(r))&&i.push("hidden-tool-exposure");let a={type:"object",properties:{contract:{type:"boolean"}}};t.registerTool({...s,parameters:a}),t.getAllTools().find(o=>o.name===r)?.parameters!==a&&i.push("dynamic-tool-registry")}catch{i.push("tool-registry-contract")}finally{try{t.setActiveTools(n)}catch{i.push("active-tool-registry")}}return{supported:!i.length,missing:i}}var gN;function Vw(){return gN??=fN().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function fN(){let{createAgentSession:t,DefaultResourceLoader:e,SessionManager:i}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:n,rm:s}=await import("node:fs/promises"),{tmpdir:a}=await import("node:os"),{join:o}=await import("node:path"),l=await n(o(a(),"pi-sdk-contract-")),c,p=[],d=0,m=0,g=!1,h=!1;try{let f=(N,R,G)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:R,parameters:{type:"object",properties:{}},execute:G}),b=()=>({content:[],details:void 0}),S=new e({cwd:l,agentDir:l,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[N=>{N.on("tool_call",R=>{if(R.toolName==="__contract_direct"&&(g=!!R.parentToolCallId),R.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let R of["hidden","model-only"])N.registerTool(f(`__contract_${R.replace("-","_")}`,R,async()=>(m++,b())));N.registerTool(f("__contract_protected","direct",async()=>(m++,b()))),N.registerTool(f("__contract_direct","direct",async()=>(d++,b()))),N.registerTool(f("__contract_driver","direct",async(R,G,P,I,x)=>{let L=await x.executeTool("__contract_hidden",{}),U=await x.executeTool("__contract_model_only",{}),k=await x.executeTool("__contract_direct",{}),v=await x.executeTool("__contract_protected",{});return(!L.isError||!U.isError)&&p.push("nested-tool-exposure"),(k.isError||d!==1)&&p.push("nested-tool-execution"),(!v.isError||m!==0)&&p.push("nested-tool-permission-guard"),g||p.push("nested-parent-identity"),h=!0,b()}))}]});await S.reload(),{session:c}=await t({cwd:l,agentDir:l,sessionManager:i.inMemory(l),resourceLoader:S}),await c.bindExtensions({mode:"print"});let E=c.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(E);let A=0;c.agent.streamFunction=async N=>{let R=A++===0,G={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:R?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:R?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},P=r();return P.push({type:"start",partial:G}),P.push({type:"done",reason:R?"toolUse":"stop",message:G}),P.end(G),P};let C;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((N,R)=>{C=setTimeout(()=>R(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(C)}return h||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(l,{recursive:!0,force:!0})}}var Na=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=Vw().then(e=>{this.sdkContract=e;for(let i of this.bindings)if(i.ready&&!i.disposed)try{this.publish(i)}catch{i.compatible=!1,i.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(i=>this.waiters.add(i))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let i;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,n)=>{i=setTimeout(()=>n(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(i)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async i=>{await this.verifyCompatibility(),this.install(i,e)}}mountTui(e,i){let r=this.install(e,i);r.ready=!0;try{this.publish(r)}catch(n){throw this.release(r),n}return()=>this.release(r)}install(e,i){let r={pi:e,scope:{...i},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let n=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{n(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),n(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),n(e.on("tool_call",s=>{let a=r.owned.get(s.toolName);if(!a)return;let o=this.descriptors.get(a)?.find(l=>l.name===s.toolName);if(!o||!this.allowed(r,a,o,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),n(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),n(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let i=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!i)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");i.session=e,i.ready=!0,i.off=e.subscribe(r=>{r.type==="agent_settled"&&(i.busy=!1,this.notify())});try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}releasePending(e){for(let i of this.bindings)!i.session&&!i.ready&&i.scope.sessionId===e&&this.release(i)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let i of e.handlers)i();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,i,r,n=!1){let s=this.service.policy(i,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!n||s.allowNested===!0)}change(e,i){if(!this.frozen||[...this.bindings].some(n=>n.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(i);this.validateChange(e,r),this.descriptors.set(e,r);for(let n of this.bindings)n.ready&&this.publish(n)}validateChange(e,i){for(let n of this.bindings)if(n.compatible!==!1)for(let[s,a]of n.owned)this.assertOwner(n,a,s);let r=new Set;for(let n of i){if(!n.name||!n.action||!n.parameters||n.parameters.type!=="object"||r.has(n.name))throw new Error("Invalid hosted tool descriptor");r.add(n.name);for(let[s,a]of this.descriptors)if(s!==e&&a.some(o=>o.name===n.name))throw new Error(`Hosted tool ownership conflict: ${n.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,n.name)}}assertOwner(e,i,r){let n=e.owned.get(r);if(n&&n!==i)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(a=>a.name===r);if(s&&(!n||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=$w(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,n]of e.owned)this.assertOwner(e,n,r);for(let[r,n]of this.descriptors)for(let s of n)this.assertOwner(e,r,s.name);let i=new Set;for(let[r,n]of this.descriptors)for(let s of n){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;i.add(s.name);let a=this.service.policy(r,e.scope),o=a.exposure??"direct",l=!a.allowNested&&o==="direct"?"model-only":o,c={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:l,execute:async(p,d,m)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:zw(),scope:{...e.scope},kind:"tool",action:s.action,input:d},m)}};e.pi.registerTool(c),e.definitions.set(s.name,c)}for(let r of e.owned.keys())if(!i.has(r)){let n={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:hN};e.pi.registerTool(n),e.definitions.set(r,n)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let n=e.definitions.get(r);return!n||n.exposure==="direct"||n.exposure==="model-only"}))}async invokeAction(e,i,r,n,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(o=>o.scope.sessionId===i.sessionId&&o.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let a=this.service.policy(e,i);if(!a.enabled||a.planMode||a.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:zw(),scope:i,kind:"action",action:r,input:n},s)}};async function hN(){throw new Error("Hosted tool unavailable")}import{randomBytes as T1,randomUUID as I1,timingSafeEqual as A1}from"node:crypto";import{join as tt}from"node:path";var yN=30,Kw=/^[a-z][a-z0-9-]{0,63}$/,bN=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Cn=t=>{throw new y("invalid_package",t)},Jp=(t,e)=>t===void 0?[]:!Array.isArray(t)||t.length>32?Cn(`Invalid ${e} declaration`):t;function _r(t){let e=t&&typeof t=="object"?t:{},i=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(o=>typeof o=="string"):[]),r=i.has("secrets")?Jp(e.secrets,"secrets").map(o=>{let l=o?.name;return typeof l=="string"&&Kw.test(l)?l:Cn("Invalid secret name")}):[],n=e.network,s=i.has("network")?Jp(n?.hosts,"network").map(o=>typeof o=="string"&&bN.test(o)?o:Cn("Network hosts must be exact lowercase DNS names")):[],a=i.has("scheduler")?Jp(e.schedules,"schedules").map(o=>{let l=o;return!l||typeof l.id!="string"||!Kw.test(l.id)||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!Number.isSafeInteger(l.intervalSec)||l.intervalSec<yN||l.intervalSec>86400?Cn("Invalid schedule declaration"):{id:l.id,intervalSec:l.intervalSec,action:l.action}}):[];return new Set(a.map(o=>o.id)).size!==a.length&&Cn("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:a,sessions:i.has("sessions")}}import{lookup as _N}from"node:dns/promises";import{isIP as vN}from"node:net";var wN=new Set(["GET","POST","PATCH","PUT","DELETE"]),SN=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),kN=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Pa=(t,e)=>{throw new y("network_denied",t,{status:403,reason:e})};function EN(t){let e=t.toLowerCase().replace(/^::ffff:/,"");if(vN(e)===4){let[i,r]=e.split(".").map(Number);return i===0||i===10||i===127||i===169&&r===254||i===172&&r>=16&&r<=31||i===192&&r===168||i===100&&r>=64&&r<=127||i>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Yw(t,e,i,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new y("invalid_input","Invalid network request");let a;try{a=new URL(s.url)}catch{throw new y("invalid_input","Invalid URL")}(a.protocol!=="https:"||a.username||a.password||a.port&&a.port!=="443")&&Pa("Only plain https on port 443 is allowed","scheme"),e.includes(a.hostname)||Pa("Host is not declared by the plugin","host");let o=(s.method??"GET").toUpperCase();if(!wN.has(o))throw new y("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new y("invalid_input","Invalid body");let l={};for(let[E,A]of Object.entries(s.headers??{})){if(typeof A!="string"||SN.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new y("invalid_input",`Header not allowed: ${E.slice(0,64)}`);l[E]=A}let c=null;if(s.secret!==void 0){if(i.includes(s.secret)||Pa("Secret is not declared by the plugin","secret"),c=await n.secrets.get(t,s.secret),!c)throw new y("secret_missing","Secret has not been configured",{status:412});l.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async E=>(await _N(E,{all:!0})).map(A=>A.address)))(a.hostname);(!p.length||p.some(EN))&&Pa("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,m=n.maxResponseBytes??2*1024*1024,g=await(n.fetch??fetch)(a,{method:o,headers:l,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),h=[],f=0;if(g.body)for await(let E of g.body){if(f+=E.byteLength,f>m)throw new y("response_too_large","Network response exceeds limit",{status:502});h.push(Buffer.from(E))}let b=Buffer.concat(h).toString("utf8"),S={};return g.headers.forEach((E,A)=>{kN.has(A.toLowerCase())&&(S[A.toLowerCase()]=E)}),c&&(b=b.split(c).join("[redacted]")),{status:g.status,headers:S,body:b}}var Ca=(t,e,i)=>{if(typeof t!="string"||!t||t.length>e)throw new y("invalid_input",`Invalid ${i}`);return t};async function Qw(t,e,i,r,n,s){let a=n&&typeof n=="object"&&!Array.isArray(n)?n:{};if(r==="sessions.create"){if(a.mode!=="plan")throw new y("invalid_input","Plugin sessions must start in plan mode");if(t.activeCount(e)>=s)throw new y("quota_exceeded","Too many active plugin sessions",{status:429});return t.create({pluginId:e,cwd:i,title:Ca(a.title,200,"title"),prompt:Ca(a.prompt,64*1024,"prompt"),mode:"plan"})}let o=Ca(a.sessionId,200,"sessionId");if(t.ownerOf(o)!==e)throw new y("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(a.mode!==void 0&&a.mode!=="execute")throw new y("invalid_input","Invalid mode");return await t.send(o,Ca(a.message,64*1024,"message"),a.mode),{ok:!0};case"sessions.release":return await t.release(o),{ok:!0};case"sessions.abort":return await t.abort(o),{ok:!0};case"sessions.events":return t.events(o,Number.isSafeInteger(a.after)&&a.after>=0?a.after:0);default:throw new y("method_denied","Unknown sessions method")}}var TN=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),Da=class{options;constructor(e){this.options=e}handles(e){return TN.has(e)}async call(e,i,r,n,s){let a=_r(i);if(n==="network.fetch"){if(!a.networkHosts.length)throw new y("capability_denied","Plugin did not declare network access",{status:403});return Yw(e,a.networkHosts,a.secrets,s,this.options)}if(!a.sessions||!this.options.sessions)throw new y("capability_denied","Sessions capability is unavailable",{status:403});return Qw(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var Ma=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,i){this.stop(e);let r=this.deps.setInterval??((n,s)=>{let a=setInterval(n,s);return a.unref(),a});this.timers.set(e,i.map(n=>r(()=>{this.tick(e,n)},n.intervalSec*1e3)))}stop(e){let i=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])i(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,i){let r=`${e}\0${i.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,i),!0}catch(n){return this.deps.onError?.(e,i,n),!1}finally{this.running.delete(r)}}};import{createHash as pd,timingSafeEqual as i1}from"node:crypto";import{lstat as m0,mkdtemp as cd,readdir as r1,readFile as n1,realpath as s1,rename as a1,rm as li,writeFile as o1}from"node:fs/promises";import{tmpdir as l1}from"node:os";import{join as ae}from"node:path";import{gunzipSync as PN}from"node:zlib";import{mkdir as CN,writeFile as DN}from"node:fs/promises";import{dirname as MN,join as LN}from"node:path";import{constants as Xp}from"node:fs";import{lstat as Zw,open as IN,readdir as Jw,realpath as e0}from"node:fs/promises";import{createHash as AN}from"node:crypto";import{join as t0,relative as xN,resolve as ON,sep as RN}from"node:path";var me={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024},NN={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],cjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"],ttf:["font/ttf"],otf:["font/otf"],wasm:["application/wasm"]},ne=t=>AN("sha256").update(t).digest("hex");function re(t){throw new y("invalid_package",t)}async function Ui(t,e,i){let r=e.split("/");(!r.length||r.some(o=>!o||o==="."||o===".."||!/^[\w.-]+$/.test(o)))&&re("Invalid resource path");let n=t;for(let o=0;o<r.length;o++){n=t0(n,r[o]);let l=await Zw(n);(l.isSymbolicLink()||(o<r.length-1?!l.isDirectory():!l.isFile()||l.nlink!==1))&&re("Links and non-regular package files are forbidden")}let s=await e0(n);(s!==ON(t,e)||xN(t,s).startsWith(`..${RN}`))&&re("Resource escapes package root");let a=await IN(n,Xp.O_RDONLY|Xp.O_NONBLOCK|(Xp.O_NOFOLLOW??0));try{let o=await a.stat();(!o.isFile()||o.nlink!==1||o.size>i)&&re("Oversized or non-regular package file");let l=Buffer.alloc(Math.min(o.size+1,i+1)),c=0;for(;c<l.length;){let p=await a.read(l,c,l.length-c,c);if(!p.bytesRead)break;c+=p.bytesRead}return(c>i||c!==o.size)&&re("Package resource changed during read"),l.subarray(0,c)}finally{await a.close()}}function Xw(t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return re("Invalid package JSON")}}async function qi(t,e){let i=await e0(t);(await Zw(t)).isSymbolicLink()&&re("Package root cannot be a symlink");let r=Xw(await Ui(i,"package.json",me.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&re("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&re("Invalid package version"),ni(r.piWebapp)||re("Unsupported hosted manifest"),r.type!=="module"&&re("Hosted package must declare ESM module type");for(let d of await Jw(i,{withFileTypes:!0}))d.name==="dist"&&d.isDirectory()||(!d.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(d.name))&&re("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(d=>/^(?:preinstall|install|postinstall|prepare)$/.test(d))&&re("Hosted packages cannot run install lifecycle scripts");for(let d of["dependencies","optionalDependencies"]){let m=r[d];m&&(typeof m!="object"||Object.keys(m).length>0)&&re("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=Xw(await Ui(i,n.resourcesManifest.slice(2),me.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>me.files)&&re("Invalid resource manifest");let a=new Map,o=0;for(let d of s.files){(!d||typeof d!="object")&&re("Invalid resource entry");let m=d,g={...m,path:typeof m.path=="string"&&m.path.startsWith("./")?m.path.slice(2):m.path};(!Ni(`./${g.path}`)||typeof g.sha256!="string"||!/^[a-f0-9]{64}$/.test(g.sha256)||!Number.isSafeInteger(g.bytes)||g.bytes<0||a.has(g.path))&&re("Invalid or duplicate resource");let h=g.path.split(".").at(-1);NN[h]?.includes(g.mime)||re("Unsupported resource MIME");let f=h==="js"||h==="mjs"||h==="cjs"?me.js:h==="css"?me.css:["woff","woff2","ttf","otf"].includes(h)?me.font:h==="wasm"?me.wasm:me.other;(g.bytes>f||(o+=g.bytes)>me.total)&&re("Resource budget exceeded");let b=await Ui(i,g.path,f);(b.length!==g.bytes||ne(b)!==g.sha256)&&re("Resource integrity mismatch"),a.set(g.path,Object.freeze({...g}))}for(let d of[n.backend.entry,n.frontend.document,n.frontend.controller])a.has(d.slice(2))||re("Entrypoint is absent from resource manifest");let l=0;async function c(d,m=0){m>16&&re("Package directory nesting limit exceeded");for(let g of await Jw(t0(i,d),{withFileTypes:!0})){++l>me.files*2&&re("Too many package entries");let h=`${d}/${g.name}`;(g.isSymbolicLink()||!g.isDirectory()&&!g.isFile())&&re("Invalid archive member"),g.isDirectory()?await c(h,m+1):h!==n.resourcesManifest.slice(2)&&!a.has(h)&&re("Undeclared distribution asset")}}await c("dist");let p=ne(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...a.values()].sort((d,m)=>d.path.localeCompare(m.path))}));return{id:r.name,version:r.version,root:i,manifest:n,resources:a,digest:p}}async function i0(t,e,i){if(i!==t.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Ni(`./${r}`))return null;let n=t.resources.get(r);if(!n||r===t.manifest.backend.entry.slice(2))return null;let s=await Ui(t.root,r,n.bytes);if(s.length!==n.bytes||ne(s)!==n.sha256)throw new y("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var La=64*1024*1024,UN=me.total+me.files*2048,ie=t=>{throw new y("invalid_archive",t)};function vr(t){let e=t.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?t:t.subarray(0,e))}catch{return ie("Archive has invalid UTF-8 paths")}}function r0(t){let e=vr(t).trim();if(!/^[0-7]+$/.test(e))return ie("Unsupported archive number encoding");let i=parseInt(e,8);return Number.isSafeInteger(i)?i:ie("Archive number exceeds limits")}function qN(t){let e=t.endsWith("/")?t.slice(0,-1):t;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return ie("Archive must have one package root");let i=e.slice(8);return i.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?ie("Archive path is not a safe relative package path"):i}function jN(t){let e={},i=0;for(;i<t.length;){let r=t.indexOf(32,i);if(r<0)return ie("Invalid PAX header");let n=t.subarray(i,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return ie("Invalid PAX record length");let s=Number(n),a=i+s;if(a>t.length||a<=r+2||t[a-1]!==10)return ie("Truncated PAX record");let o=vr(t.subarray(r+1,a-1)),l=o.indexOf("=");if(l<1)return ie("Invalid PAX record");let c=o.slice(0,l),p=o.slice(l+1);if(Object.hasOwn(e,c)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(c))return ie("Unsupported PAX feature");e[c]=p,i=a}return e}function FN(t){if(!t.length||t.length>La)return ie("Compressed archive exceeds budget");let e;try{e=PN(t,{maxOutputLength:UN})}catch{return ie("Invalid or oversized gzip archive")}let i=[],r=new Set,n=0,s=0,a=0,o=0,l=null,c=!1;for(;n+512<=e.length;){let d=e.subarray(n,n+512);if(n+=512,d.every(C=>C===0)){if(l||e.subarray(n).some(C=>C!==0))return ie("Unexpected archive data after end marker");c=!0;break}if(++o>me.files*2)return ie("Too many archive headers");let m=0;for(let C=0;C<512;C++)m+=C>=148&&C<156?32:d[C];if(r0(d.subarray(148,156))!==m)return ie("Invalid tar header checksum");let g=vr(d.subarray(257,263));if(g&&g!=="ustar"&&g!=="ustar ")return ie("Unsupported tar format");let h=d[156],f=vr(d.subarray(345,500)),b=(f?f+"/":"")+vr(d.subarray(0,100)),S=r0(d.subarray(124,136));if(l&&(l.path!==void 0&&(b=l.path),l.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(l.size))return ie("Invalid PAX size");S=Number(l.size)}if(!Number.isSafeInteger(S)||S<0||S>me.total||n+S>e.length)return ie("Truncated or oversized tar member");let E=e.subarray(n,n+S);if(n+=Math.ceil(S/512)*512,h===120){if(l||S>8192)return ie("Oversized or chained PAX header");l=jN(E);continue}if(l=null,h!==0&&h!==48&&h!==53)return ie("Links and special archive members are forbidden");let A=h===53;if(A&&S!==0||vr(d.subarray(157,257)))return ie("Invalid archive link or directory");if(b=qN(b),!b&&!A)return ie("Invalid package root member");if(r.has(b))return ie("Duplicate archive member");if(r.add(b),++s>me.files||(a+=S)>me.total)return ie("Unpacked archive exceeds budget");i.push({path:b,data:E,directory:A})}if(!c||!r.has("package.json"))return ie("Archive is incomplete or has no package.json");let p=new Set(i.filter(d=>!d.directory).map(d=>d.path));for(let d of i){let m=d.path.split("/");for(let g=1;g<m.length;g++)if(p.has(m.slice(0,g).join("/")))return ie("Archive file/directory collision")}return i}async function Zp(t,e){let i=FN(t);for(let r of i){if(!r.path)continue;let n=LN(e,r.path);await CN(r.directory?n:MN(n),{recursive:!0,mode:448}),r.directory||await DN(n,r.data,{flag:"wx",mode:384})}}import{lstat as BN,mkdir as HN,readdir as GN,realpath as WN,writeFile as $N}from"node:fs/promises";import{dirname as VN,join as ed}from"node:path";async function n0(t,e){let i=await WN(t),r=await Ui(i,"package.json",me.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("invalid_package","package.json must be an object");let s=[],a=0,o=0;async function l(m,g){if(g>16)throw new y("invalid_package","Package directory nesting limit exceeded");for(let h of await GN(ed(i,m),{withFileTypes:!0})){let f=`${m}/${h.name}`;if(++a>me.files)throw new y("invalid_package","Too many package entries");if(h.isDirectory()){await l(f,g+1);continue}if(!h.isFile())throw new y("invalid_package",`Links and non-regular files are forbidden: ${f}`);let b=await Ui(i,f,me.js);if((o+=b.length)>me.total)throw new y("invalid_package","Resource budget exceeded");let S=ed(e,f);await HN(VN(S),{recursive:!0,mode:448}),await $N(S,b,{flag:"wx",mode:384}),s.push([f,ne(b)])}}let c;try{c=await BN(ed(i,"dist"))}catch(m){throw m.code==="ENOENT"?new y("dist_missing","dist/ does not exist yet; build the plugin first"):m}if(!c.isDirectory())throw new y("invalid_package","dist must be a real directory");await l("dist",0);let{version:p,...d}=n;return s.sort((m,g)=>m[0].localeCompare(g[0])),{contentHash:ne(JSON.stringify({package:d,files:s})),packageJson:n}}function Fe(t){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(t);return!e||e[0]!==t||e.slice(1).some(i=>!Number.isSafeInteger(Number(i)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function yt(t,e){let i=Fe(t),r=Fe(e);if(!i||!r)throw new y("invalid_version","Only exact stable semantic versions are supported");return i.major-r.major||i.minor-r.minor||i.patch-r.patch}function s0(t){let e=Fe(t);if(e)return e;if(!la(t))return null;let[i,r]=t.split("-alpha."),n=Fe(i),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function td(t){return!!s0(t)}function wr(t,e){if(!td(t)||typeof e!="string"||e.length>256)return!1;let i=e.split("||");if(!i.length||i.some(n=>!n.trim()))return!1;let r=[];for(let n of i){let s=n.trim().split(/\s+/),a=!0;for(let o of s){let l=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(o),c=l&&s0(l[2]);if(!l||!c)return!1;let p=l[2],d=Ke(t,p);switch(l[1]??"="){case"=":a&&=d===0;break;case">=":a&&=d>=0;break;case"<=":a&&=d<=0;break;case">":a&&=d>0;break;case"<":a&&=d<0;break;case"~":a&&=d>=0&&Ke(t,`${c.major}.${c.minor+1}.0-0`)<0;break;case"^":{let m=c.major?`${c.major+1}.0.0`:c.minor?`0.${c.minor+1}.0`:`0.0.${c.patch+1}`;a&&=d>=0&&Ke(t,`${m}-0`)<0;break}}}r.push(a)}return r.some(Boolean)}var id=64*1024*1024,rd=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function nd(t,e){let i=t.get(e);if(!i)throw new y("unreviewed_plugin","No trusted tool policy for this package");return i}function a0(t,e){let i=t.get(e)?.workspace?.files??rd;for(let r of i)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>id||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new y("invalid_policy","Invalid workspace file rule");return i}function o0(t,e){let i=t.get(e)?.runtime?.invokeTimeoutMs;return i===void 0?void 0:Math.min(Math.max(i,1e3),18e4)}var l0=["drawing","design"],zN=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,KN=/^[a-z][a-z0-9.-]{0,79}$/,sd=/^[a-z][a-z0-9_]{0,63}$/,ji=/^[a-z][a-z0-9_-]{0,63}$/,YN=/^[a-z][a-z0-9-]{0,63}$/,Dn=class{where;constructor(e){this.where=e}fail(e,i){throw new y("invalid_catalog",`${this.where}: ${e} ${i}`)}object(e,i,r,n=r){(!e||typeof e!="object"||Array.isArray(e))&&this.fail(i,"must be an object");let s=e;for(let a of Object.keys(s))r.includes(a)||this.fail(`${i}.${a}`,"is not a known field");for(let a of n)s[a]===void 0&&this.fail(`${i}.${a}`,"is required");return s}string(e,i,r=200,n){return(typeof e!="string"||!e.trim()||e.length>r)&&this.fail(i,`must be a non-empty string of at most ${r} characters`),n&&!n.test(e)&&this.fail(i,`has an invalid format (${JSON.stringify(e)})`),e}strings(e,i,r,n=64){(!Array.isArray(e)||e.length>n)&&this.fail(i,`must be an array of at most ${n} strings`);let s=e.map((a,o)=>this.string(a,`${i}[${o}]`,80,r));return new Set(s).size!==s.length&&this.fail(i,"contains duplicates"),s}text(e,i,r=500){let n=this.object(e,i,["zh","en"]);return{zh:this.string(n.zh,`${i}.zh`,r),en:this.string(n.en,`${i}.en`,r)}}integer(e,i,r,n){return(!Number.isSafeInteger(e)||e<r||e>n)&&this.fail(i,`must be an integer from ${r} to ${n}`),e}https(e,i,r){let n=this.string(e,i,2048),s;try{s=new URL(n)}catch{this.fail(i,"must be an absolute URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash||r!==void 0&&s.hostname!==r)&&this.fail(i,`must be an https URL${r?` on ${r}`:""} without credentials or fragment`),n}subset(e,i,r,n){for(let s of e)i.includes(s)||this.fail(r,`lists "${s}", which is not one of its ${n}`)}};function QN(t,e,i){let r=t.object(e,i,["entry","panels","artifactTools","toolViews","panelAlias"]),n=t.object(r.entry,`${i}.entry`,["label","description","kind"]),s=t.object(r.panelAlias,`${i}.panelAlias`,["prefix","kind","title"]);return{entry:{label:t.string(n.label,`${i}.entry.label`,64),description:t.text(n.description,`${i}.entry.description`,120),kind:t.string(n.kind,`${i}.entry.kind`,32,ji)},panels:t.strings(r.panels,`${i}.panels`,ji,16),artifactTools:t.strings(r.artifactTools,`${i}.artifactTools`,sd,128),toolViews:t.strings(r.toolViews,`${i}.toolViews`,sd,128),panelAlias:{prefix:t.string(s.prefix,`${i}.panelAlias.prefix`,32,/^[a-z][a-z0-9-]{0,30}:$/),kind:t.string(s.kind,`${i}.panelAlias.kind`,32,ji),title:t.string(s.title,`${i}.panelAlias.title`,64)}}}function JN(t,e,i){return(!Array.isArray(e)||e.length<1||e.length>16)&&t.fail(i,"must be an array of 1 to 16 rules"),e.map((r,n)=>{let s=`${i}[${n}]`,a=t.object(r,s,["extension","binary","maxBytes","createDirectory"],["extension","binary","maxBytes"]);return typeof a.binary!="boolean"&&t.fail(`${s}.binary`,"must be a boolean"),{extension:t.string(a.extension,`${s}.extension`,17,/^\.[a-z0-9]{1,16}$/),binary:a.binary,maxBytes:t.integer(a.maxBytes,`${s}.maxBytes`,1,id),...a.createDirectory!==void 0?{createDirectory:t.string(a.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function XN(t,e,i){let r=t.object(e,i,Object.keys(e&&typeof e=="object"?e:{}),[]);return Object.keys(r).length>16&&t.fail(i,"declares more than 16 secrets"),Object.fromEntries(Object.entries(r).map(([n,s])=>{let a=`${i}.${n}`;t.string(n,`${i} key`,64,YN);let o=t.object(s,a,["provider","scope","createUrl","clientId"],["provider","scope","createUrl"]);return o.provider!=="github"&&t.fail(`${a}.provider`,'must be "github" (the only sign-in the host implements)'),[n,{provider:"github",scope:t.string(o.scope,`${a}.scope`,200,/^[\w:. -]+$/),createUrl:t.https(o.createUrl,`${a}.createUrl`,"github.com"),...o.clientId!==void 0?{clientId:t.string(o.clientId,`${a}.clientId`,64,/^[A-Za-z0-9._-]+$/)}:{}}]}))}function ZN(t,e,i="policy"){let r=new Dn(e),n=r.object(t,i,["tools","readonlyActions","actions","checkpointActions","contribution","browser","workspace","runtime","secrets"],["tools","readonlyActions","actions","checkpointActions","contribution"]),s=r.object(n.tools,`${i}.tools`,Object.keys(n.tools&&typeof n.tools=="object"?n.tools:{}),[]);Object.keys(s).length>128&&r.fail(`${i}.tools`,"declares more than 128 tools");for(let[g,h]of Object.entries(s))r.string(g,`${i}.tools key`,64,sd),r.string(h,`${i}.tools.${g}`,64,ji);let a=Object.keys(s),o=Object.values(s),l=r.strings(n.readonlyActions,`${i}.readonlyActions`,ji),c=r.strings(n.actions,`${i}.actions`,ji),p=r.strings(n.checkpointActions,`${i}.checkpointActions`,ji);r.subset(l,o,`${i}.readonlyActions`,"tool actions"),r.subset(p,c,`${i}.checkpointActions`,"actions");let d=QN(r,n.contribution,`${i}.contribution`);r.subset(d.artifactTools,a,`${i}.contribution.artifactTools`,"tools"),r.subset(d.toolViews,a,`${i}.contribution.toolViews`,"tools");let m={tools:s,readonlyActions:l,actions:c,checkpointActions:p,contribution:d};if(n.browser!==void 0){let g=r.object(n.browser,`${i}.browser`,["wasm"],[]);g.wasm!==void 0&&typeof g.wasm!="boolean"&&r.fail(`${i}.browser.wasm`,"must be a boolean"),m.browser=g.wasm===void 0?{}:{wasm:g.wasm}}if(n.workspace!==void 0&&(m.workspace={files:JN(r,r.object(n.workspace,`${i}.workspace`,["files"]).files,`${i}.workspace.files`)}),n.runtime!==void 0){let g=r.object(n.runtime,`${i}.runtime`,["invokeTimeoutMs"],[]);m.runtime=g.invokeTimeoutMs===void 0?{}:{invokeTimeoutMs:r.integer(g.invokeTimeoutMs,`${i}.runtime.invokeTimeoutMs`,1e3,18e4)}}return n.secrets!==void 0&&(m.secrets=XN(r,n.secrets,`${i}.secrets`)),m}var e1=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function ad(t,e,i="plugin"){let r=new Dn(e),n=r.object(t,i,e1,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${i}.id`,214,zN);n.icon!==void 0&&!l0.includes(n.icon)&&r.fail(`${i}.icon`,`must be one of ${l0.join(", ")}`);let a=r.https(n.registry,`${i}.registry`);new URL(a).origin!==a&&r.fail(`${i}.registry`,"must be a bare origin such as https://registry.npmjs.org");let o=r.string(n.recommendedVersion,`${i}.recommendedVersion`,64);return Fe(o)||r.fail(`${i}.recommendedVersion`,"must be a stable x.y.z version"),n.reviewed!==void 0&&r.string(n.reviewed,`${i}.reviewed`,1e3),{id:s,name:r.string(n.name,`${i}.name`,64),...n.icon!==void 0?{icon:n.icon}:{},description:r.text(n.description,`${i}.description`),registry:a,recommendedVersion:o,requiredCapabilities:r.strings(n.requiredCapabilities,`${i}.requiredCapabilities`,KN),policy:ZN(n.policy,e,`${i}.policy`)}}function c0(t,e){let i=new Dn(e),r=i.object(t,"catalog",["schemaVersion","plugins"]);r.schemaVersion!==1&&i.fail("catalog.schemaVersion","must be 1"),(!Array.isArray(r.plugins)||r.plugins.length>64)&&i.fail("catalog.plugins","must be an array of at most 64 entries");let n=r.plugins.map((a,o)=>ad(a,e,`catalog.plugins[${o}]`)),s=n.map(a=>a.id);for(let[a,o]of s.entries())s.indexOf(o)!==a&&i.fail(`catalog.plugins[${a}].id`,`duplicates ${o}`);return n}function od(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))od(e)}return t}var p0={schemaVersion:1,plugins:[{id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"],reviewed:"Policy reviewed against package 6328c63.",policy:{tools:{excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"},readonlyActions:["read","reference"],actions:["list","new","open","import","get","focus","sync","initialize","accept","reject","save"],checkpointActions:["sync","get","list"],contribution:{entry:{label:"Excalidraw",description:{zh:"\u624B\u7ED8\u56FE\u7A3F",en:"Editable drawings"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}}}},{id:"@chengzhiyi/pi-pencil",name:"OpenPencil",icon:"design",description:{zh:"\u57FA\u4E8E OpenPencil \u7684 UI \u8BBE\u8BA1\uFF1A\u7F16\u8F91\u5DE5\u4F5C\u533A\u91CC\u7684 .fig \u8BBE\u8BA1\u7A3F\uFF0Cagent \u7684\u4FEE\u6539\u76F4\u63A5\u51FA\u73B0\u5728\u753B\u5E03\u4E0A\uFF0C\u53EF\u968F\u65F6\u64A4\u9500\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"UI design on OpenPencil: edit .fig designs in your workspace; the agent's changes appear on the canvas directly and you can undo them. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.0.2",requiredCapabilities:["state","workspace","panels","browser.wasm"],reviewed:"The tool set is deliberately small. Agent changes apply directly as new revisions; undoing one (revert), saving, syncing and locking stay human-only. accept/reject remain for proposals stored by older builds. import turns a file the person picked (.fig/.jam/.pen/.drawio) into a new design; upload carries an action input over the 2 MB request limit in chunks (bounded and owned by the uploading session in the plugin). A checkpoint freeze may flush a person's first edits in an empty workspace, which creates their design.",policy:{tools:{pencil_read_me:"reference",pencil_status:"status",pencil_inspect:"inspect",pencil_render:"render",pencil_apply_changes:"apply"},readonlyActions:["reference","status","inspect","render"],actions:["list","get","accept","reject","revert","save","open","import","upload","create","rename","selection","sync","lock"],checkpointActions:["get","list","sync","create"],contribution:{entry:{label:"OpenPencil",description:{zh:"UI \u8BBE\u8BA1",en:"UI design"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["pencil_apply_changes"],toolViews:[],panelAlias:{prefix:"pencil:",kind:"editor",title:"OpenPencil"}},browser:{wasm:!0},workspace:{files:[{extension:".fig",binary:!0,maxBytes:67108864,createDirectory:"designs"}]},runtime:{invokeTimeoutMs:12e4}}}]};var d0=od(c0(p0,"official-plugins.json")),et=Object.freeze(d0.map(({policy:t,...e})=>Object.freeze(e))),Ua=new Map(d0.map(t=>[t.id,t.policy]));function Qe(t,e=et){let i=e.find(r=>r.id===t);if(!i)throw new y("unknown_plugin","Plugin is not in the trusted official catalog");return i}function ld(t,e,i){let r=t.piWebapp;return t.name===e.id&&!!Fe(t.version)&&!t.deprecated&&ni(r)&&wr(i,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function u0(t,e,i,r,n){if(!t||typeof t!="object"||!("versions"in t)||!t.versions||typeof t.versions!="object"||Array.isArray(t.versions))throw new y("registry_invalid","Invalid registry version catalog");let s=Object.entries(t.versions);if(s.length>1e4)throw new y("registry_invalid","Registry version catalog exceeds budget");let o=s.flatMap(([l,c])=>{if(!c||typeof c!="object")return[];let p=c;return p.version===l&&ld(p,e,i)&&(!n||l===n)&&(!r||yt(l,r)>=0)?[p]:[]}).sort((l,c)=>yt(c.version,l.version))[0];if(!o)throw new y("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!o.dist||typeof o.dist.tarball!="string"||typeof o.dist.integrity!="string")throw new y("registry_invalid","Release is missing its immutable tarball integrity");return o}function c1(t,e){let i=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!i)throw new y("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(i[1],"base64"),n=pd("sha512").update(t).digest();if(r.length!==n.length||!i1(r,n))throw new y("integrity_mismatch","Downloaded package failed integrity verification")}var Sr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!td(e.hostVersion))throw new y("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??et,this.fetcher=e.fetch??nw}async index(){let e=await ke(ae(this.root,"installed.json"));if(!e){if(await ye(ae(this.root,"installed.json"),2*1024*1024))throw new y("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new y("invalid_storage","Invalid plugin installation index");for(let[i,r]of Object.entries(e.versions))if(this.catalog.some(n=>n.id===i)){if(!Array.isArray(r)||r.length>16||new Set(r.map(n=>n.version)).size!==r.length)throw new y("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(i,n)}return e}validateRecord(e,i){if(!i||!Fe(i.version)||!/^[a-f0-9]{64}$/.test(i.digest)||i.directory!==`${ne(e)}/${i.version}-${i.digest}`||typeof i.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(i.integrity)||typeof i.installedAt!="string")throw new y("invalid_storage","Invalid installed plugin record")}path(e){return ae(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),i=await Ye(ae(this.root,"install-journal.json"));if(i){if(i.schema!==1||Object.keys(i).some(s=>!["schema","pluginId","next"].includes(s)))throw new y("invalid_storage","Invalid install journal");Qe(i.pluginId,this.catalog),this.validateRecord(i.pluginId,i.next);let n=e.versions[i.pluginId]?.find(s=>s.version===i.next.version);if(n&&n.digest!==i.next.digest)throw new y("invalid_storage","Conflicting installation journal");await li(ae(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=ae(this.root,"staging");await Se(r);for(let n of await r1(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await m0(ae(r,n))).isSymbolicLink())throw new y("invalid_storage","Invalid abandoned staging directory");await li(ae(r,n),{recursive:!0})}return e}async recoverCollection(e){let i=ae(this.root,"gc-journal.json"),r=await Ye(i);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new y("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");Qe(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let n=r.records.filter(s=>e.versions[r.pluginId]?.some(a=>a.directory===s.directory));if(n.length&&n.length!==r.records.length)throw new y("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!n.length){await Se(ae(this.root,"versions")),await Se(ae(this.root,"versions",ne(r.pluginId)));for(let s of r.records)await li(this.path(s),{recursive:!0,force:!0})}await li(i)}async collect(e,i){return Qe(e,this.catalog),Ee(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]??[],s=new Set(await i()),a=n.at(-1);a&&s.add(a.version);let o=n.filter(l=>!s.has(l.version));return await this.removeLocked(e,r,o),o.map(l=>l.version)})}async removeLocked(e,i,r){r.length&&(await Se(ae(this.root,"versions")),await Se(ae(this.root,"versions",ne(e))),await te(ae(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),i.versions[e]=(i.versions[e]??[]).filter(n=>!r.some(s=>s.directory===n.directory)),i.revision++,await te(ae(this.root,"installed.json"),i),await this.recoverCollection(i))}async inventory(){return Ee(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,i){let r;try{r=new URL(e)}catch{throw new y("registry_denied","Invalid registry URL")}let n=new URL(i.registry);if(r.protocol!=="https:"||r.origin!==n.origin||r.username||r.password||r.hash||r.search)throw new y("registry_denied","Only the official registry origin is permitted");return r}async download(e,i,r,n="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),a;try{a=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(d){throw r?.aborted?r.reason:new y("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!a.ok||!a.body)throw await a.body?.cancel().catch(()=>{}),new y(a.status===404?`${n}_not_found`:"download_failed",`Registry ${n} request failed (${a.status})`);if(a.url&&new URL(a.url).origin!==e.origin)throw new y("registry_denied","Registry redirect is forbidden");let o=a.body.getReader(),l=[],c=0,p=()=>{o.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(a.headers.get("content-length"))>i)throw new y("download_too_large","Registry response exceeds budget");for(;;){let d=await o.read();if(d.done)break;if(c+=d.value.length,c>i)throw new y("download_too_large","Registry response exceeds budget");l.push(Buffer.from(d.value))}return s.throwIfAborted(),Buffer.concat(l)}catch(d){throw r?.aborted?r.reason:d instanceof y?d:new y("registry_unreachable",d instanceof Error?d.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await o.cancel().catch(()=>{}),o.releaseLock()}}async check(e,i,r,n){let s=Qe(e,this.catalog);if(r&&!Fe(r))throw new y("invalid_version","Choose an exact stable version");let a=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),o,l=await this.download(a,8*1024*1024,n,"metadata");try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l))}catch{throw new y("registry_invalid","Invalid registry metadata JSON")}return u0(o,s,this.hostVersion,i,r)}async install(e,i,r){let n=Qe(e,this.catalog);if(!ld(i,n,this.hostVersion))throw new y("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(i.dist.tarball,n),La,r);return this.installArchive(e,s,i.dist.integrity,i.version,r)}async installArchive(e,i,r,n,s){let a=Qe(e,this.catalog);if(!Fe(n))throw new y("invalid_version","Choose an exact stable version");if(i.length>La)throw new y("download_too_large","Package archive exceeds budget");return c1(i,r),Ee(this.root,async()=>{let o=await this.recoverLocked();s?.throwIfAborted();let l=await cd(ae(this.root,"staging","stage-"));try{await Zp(i,l),s?.throwIfAborted();let c=await qi(l,e);if(c.version!==n||!ni(c.manifest)||!wr(this.hostVersion,c.manifest.hostRange)||!a.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new y("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,o,l,c,r,s)}finally{await li(l,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,i,r,n,s,a){let o=i.versions[e]?.find(d=>d.version===n.version);if(o&&o.digest!==n.digest)throw new y("version_replaced","An installed immutable version cannot be replaced with different content");let l={version:n.version,digest:n.digest,integrity:s,directory:`${ne(e)}/${n.version}-${n.digest}`,installedAt:new Date().toISOString()};if(await Se(ae(this.root,"versions",ne(e))),!o&&(i.versions[e]?.length??0)>=16)throw new y("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await te(ae(this.root,"install-journal.json"),{schema:1,pluginId:e,next:l});let c=this.path(l),p=!1;try{await m0(c),p=!0}catch(d){if(!ii(d))throw d}if(p){if((await qi(c,e)).digest!==n.digest)throw new y("resource_changed","Installed package content was modified")}else await a1(r,c);return a?.throwIfAborted(),o||(i.versions[e]=[...i.versions[e]??[],l],i.revision++,await te(ae(this.root,"installed.json"),i)),await li(ae(this.root,"install-journal.json")),{...n,root:await s1(c)}}async installDevArchive(e,i,r){Qe(e,this.catalog);let n=await n1(i),s="sha512-"+pd("sha512").update(n).digest("base64"),a=await cd(ae(l1(),"pi-dev-archive-"));try{await Zp(n,a);let o=(await qi(a,e)).version;return await this.installArchive(e,n,s,o,r)}finally{await li(a,{recursive:!0,force:!0})}}async installDevDirectory(e,i,r){let n=Qe(e,this.catalog);return Ee(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let a=await cd(ae(this.root,"staging","stage-"));try{let{contentHash:o,packageJson:l}=await n0(i,a);r?.throwIfAborted();let c=ae(this.root,"dev-sources.json"),p=await ke(c)??{},d=p[e],m=s.versions[e]??[],g=d?.contentHash===o?m.find(R=>R.version===d.version):void 0;if(g){let R=await qi(this.path(g),e);if(R.digest!==g.digest)throw new y("resource_changed","Installed package integrity changed");return R}let h=typeof l.version=="string"?Fe(l.version):null;if(!h)throw new y("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let f=Math.max(-1,...m.map(R=>Fe(R.version)).filter(R=>R&&R.major===h.major&&R.minor===h.minor).map(R=>R.patch)),b=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),f+1),S=`${h.major}.${h.minor}.${b}`;await o1(ae(a,"package.json"),JSON.stringify({...l,version:S},null,2),{flag:"wx",mode:384});let E=await qi(a,e);if(!wr(this.hostVersion,E.manifest.hostRange))throw new y("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let A=n.requiredCapabilities.filter(R=>!E.manifest.capabilities.includes(R));if(A.length)throw new y("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let C="sha512-"+pd("sha512").update(o).digest("base64"),N=await this.commitStaged(e,s,a,E,C,r);return p[e]={contentHash:o,version:S},await te(c,p),N}finally{await li(a,{recursive:!0,force:!0})}},1e4)}async load(e,i){let r=Qe(e,this.catalog);return Ee(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(o=>o.version===i);if(!s)throw new y("not_installed","Plugin version is not installed");let a=await qi(this.path(s),e);if(a.digest!==s.digest)throw new y("resource_changed","Installed package integrity changed");if(!wr(this.hostVersion,a.manifest.hostRange)||!r.requiredCapabilities.every(o=>a.manifest.capabilities.includes(o)))throw new y("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return a})}async removeVersions(e,i){Qe(e,this.catalog),await Ee(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(a=>i.includes(a.version));await this.removeLocked(e,r,s)})}};import{lstat as qa,mkdir as p1,open as g0,realpath as f0,readdir as dd,link as d1,rename as u1,unlink as Fi,copyFile as m1,rm as g1}from"node:fs/promises";import{dirname as f1,isAbsolute as h0,join as Q,relative as y0,resolve as h1,sep as ud,win32 as y1}from"node:path";import{randomUUID as md}from"node:crypto";var Mn=192*1024*1024,_9=512*1024,_0=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function b1(t){if(!t||typeof t!="object"||Array.isArray(t))throw new y("invalid_input","Expected object input");return t}function b0(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new y("invalid_input","Invalid state key");return t}function Ln(t){if(t&&(!_0(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new y("invalid_storage","Invalid active plugin record");return t}var Bi=class{root;pluginId;legacy;checkpoint;files;constructor(e,i,r,n,s=rd){this.root=Q(e,ne(i)),this.pluginId=i,this.legacy=r,this.checkpoint=n,this.files=s}rule(e){let i=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!i)throw new y("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return i}active(){return ke(Q(this.root,"active.json")).then(Ln)}async recover(){return Ee(this.root,async()=>{let e=await this.active(),i=await Ye(Q(this.root,"transition.json"));if(!i)return{active:e,recovered:"none"};if(!i.next||!Object.hasOwn(i,"before")||Object.keys(i).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(i,"version")&&i.version!==1)throw new y("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ln(i.next),Ln(i.before);let r=e?.operationId===i.next.operationId?"committed":"not_committed";if(!((a,o)=>a===null||o===null?a===o:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===o[l]))(e,r==="committed"?i.next:i.before))throw new y("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=i.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await te(Q(this.root,"previous.json"),s),r==="committed"){let a=await Ye(Q(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(o=>["version","stateRef"].includes(o))&&await Fi(Q(this.root,"fork.json"))}return await Fi(Q(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,i){return Ee(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new y("stale_generation","Plugin activation changed concurrently");let n=await Ye(Q(this.root,"fork.json"));if(n&&(n.version!==1||n.stateRef!==i.stateRef||Object.keys(n).some(a=>!["version","stateRef"].includes(a))))throw new y("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Ln({...i,generation:e+1,operationId:md()});await Se(Q(this.root,"states")),await Se(Q(this.root,"states",s.stateRef)),await te(Q(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await te(Q(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await te(Q(this.root,"previous.json"),r),await Fi(Q(this.root,"transition.json")),await Fi(Q(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return Ee(this.root,async()=>{let i=await this.assertGeneration(e,!1),r=md(),n=Q(this.root,"states",r);if(await Ye(Q(this.root,"fork.json")))throw new y("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await te(Q(this.root,"fork.json"),{version:1,stateRef:r}),await Se(n);let s=Q(this.root,"states",i.stateRef);for(let a of await dd(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new y("invalid_storage","Unexpected state file");if(!await ye(Q(s,a),Mn))throw new y("invalid_storage","Missing state file");await m1(Q(s,a),Q(n,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return Ee(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await ye(Q(this.root,c),2*1024*1024))throw new y("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let i=await this.active(),r=Ln(await Ye(Q(this.root,"previous.json")));if(!i&&await ye(Q(this.root,"active.json"),2*1024*1024))throw new y("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let n=[i,r].filter(c=>!!c),s=Q(this.root,"states");await Se(s);let a=await dd(s),o=new Set(n.map(c=>c.stateRef));for(let c of a){if(!_0(c))throw new y("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=Q(s,c),d=await qa(p);if(!d.isDirectory()||d.isSymbolicLink())throw new y("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await dd(p)){let g=await qa(Q(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new y("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!o.has(c)){let h=await ke(Q(p,m),Mn);if(!h)throw new y("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let f=h;if(Object.keys(f).some(b=>!["requestId","inputHash","nextHash","committed"].includes(b))||f.committed!==!0||!/^[a-f0-9]{64}$/.test(f.inputHash)||!/^[a-f0-9]{64}$/.test(f.nextHash)||typeof f.requestId!="string")throw new y("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(f=>!["revision","schema","value","requestId","inputHash"].includes(f)))throw new y("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let c of o)if(!a.includes(c))throw new y("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(n);for(let c of a)o.has(c)||await g1(Q(s,c),{recursive:!0,force:!0});return l})}async assertGeneration(e,i=!0){let r=await this.active();if(!r||r.generation!==e||i&&!r.enabled)throw new y("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new y("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,i,r,n="session"){if(n!=="session"&&n!=="workspace")throw new y("invalid_input","Invalid state scope");let s=n==="workspace"?(this.scopeKey(i),JSON.stringify([i.scope.workspaceId,i.scope.cwd])):this.scopeKey(i);return Q(this.root,"states",e.stateRef,`${ne(s+":state:"+r)}.json`)}async call(e,i,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new y("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=b1(r);return Ee(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(i){case"state.read":{let a=await ke(this.statePath(s,e,b0(n.key),n.scope),Mn);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,b0(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new y("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new y("invalid_input","State value must be JSON serializable");let o=JSON.stringify(n);if(Buffer.byteLength(o)>Mn)throw new y("state_too_large","Plugin state exceeds limit");let l=await ke(a,Mn);l&&this.validateState(l);let c=ne(o);if(l?.requestId===e.requestId&&l.inputHash===c)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==n.expectedRevision)throw new y("revision_conflict","Plugin state changed concurrently");let p={revision:n.expectedRevision+1,schema:s.schema,value:n.value,requestId:e.requestId,inputHash:c};return await te(a,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let a=this.rule(n.path),{target:o}=await this.fileTarget(e.scope.cwd,n.path),l=n.maxBytes===void 0?a.maxBytes:n.maxBytes;if(!Number.isSafeInteger(l)||l<=0||l>a.maxBytes)throw new y("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(a.binary?"base64":"utf-8"))throw new y("invalid_input","Encoding does not match the reviewed file rule");let c=await ye(o,l);return c?a.binary?{base64:c.toString("base64"),bytes:c.length,hash:ne(c)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:ne(c)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new y("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new y("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,i,r=!1){let n=this.rule(i);if(typeof i!="string"||i.length>4096||i.includes("\\")||i.includes("\0")||h0(i)||y1.isAbsolute(i))throw new y("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await f0(e),a=h1(s,i),o=y0(s,a);if(!o||o===".."||o.startsWith(`..${ud}`)||h0(o))throw new y("invalid_path","Workspace path escapes root");let l=s,c=o.split(ud);for(let d=0;d<c.length;d++){l=Q(l,c[d]);let m;try{m=await qa(l)}catch(g){if(!ii(g))throw g;if(d<c.length-1){if(!r||!n.createDirectory||y0(s,l)!==n.createDirectory)throw new y("invalid_path","Workspace directory does not exist");try{await p1(l,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}m=await qa(l)}}if(m&&(m.isSymbolicLink()||(d<c.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new y("invalid_path","Workspace path contains a link or non-regular file")}let p=await f0(f1(a));if(p!==s&&!p.startsWith(s+ud))throw new y("invalid_path","Workspace directory changed");return{target:a,parent:p}}async commitFile(e,i,r){let n=this.rule(r.path),s=n.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!s||s.length>n.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new y("invalid_input","Invalid file content or expected hash");let{target:a,parent:o}=await this.fileTarget(i.scope.cwd,r.path,!0),l=Q(this.root,"states",e.stateRef,`${ne(this.scopeKey(i)+":file:"+i.requestId+":"+String(r.path))}.json`),c=ne(JSON.stringify(r)),p=ne(s),d=await ke(l);if(d&&(d.requestId!==i.requestId||d.inputHash!==c||d.nextHash!==p))throw new y("duplicate_request","Request ID was reused with different content");let m;try{m=await g0(`${a}.lock`,"wx",384)}catch(h){throw h.code==="EEXIST"?new y("file_busy","Workspace file is locked; original file preserved"):h}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:i.requestId}));let h=await ye(a,n.maxBytes),f=h?ne(h):null;if(d&&f===p)return{hash:p};if(d?.committed||f!==r.expectedHash)throw new y("file_conflict","Workspace file already exists or changed externally");await te(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!1}),g=Q(o,`.plugin-${md()}.tmp`);let b=await g0(g,"wx",384);try{await b.writeFile(s),await b.sync()}finally{await b.close()}if((await this.fileTarget(i.scope.cwd,r.path)).parent!==o)throw new y("file_conflict","Workspace directory changed during save");let E=await ye(a,n.maxBytes);if((E?ne(E):null)!==r.expectedHash)throw new y("file_conflict","Workspace file changed during save");if(await this.assertGeneration(i.generation),r.expectedHash===null){try{await d1(g,a)}catch(A){throw A.code==="EEXIST"?new y("file_conflict","Workspace file was created concurrently"):A}await Fi(g),g=void 0}else await u1(g,a),g=void 0;return await te(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{g&&await Fi(g).catch(()=>{}),await m.close(),await Fi(`${a}.lock`)}}};import{randomUUID as k1}from"node:crypto";import{fork as _1}from"node:child_process";import{randomUUID as v1}from"node:crypto";import{join as w1}from"node:path";import{EventEmitter as S1}from"node:events";var v0=192*1024*1024,Un=class t{child;pending=new Map;events=new S1;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,i,r,n){this.package=e,this.generation=i,this.broker=n;let s={};for(let a of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[a]&&(s[a]=process.env[a]);this.child=_1(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",a=>{this.receive(a)}),this.child.once("error",a=>this.fail(a)),this.child.once("exit",()=>this.fail(new y("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,i,r,n,s=1e4){let a=new t(e,i,r,n);try{await a.request("initialize",{entry:w1(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:i},s);let o=await a.request("describe",void 0,s);if(!o||!Array.isArray(o.tools)||o.tools.length>128)throw new y("invalid_tools","Invalid hosted tool catalog");let l=new Set;for(let c of o.tools){if(!c||typeof c.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(c.name)||l.has(c.name)||typeof c.label!="string"||typeof c.description!="string"||typeof c.action!="string"||!/^[\w.-]{1,80}$/.test(c.action)||!c.parameters||typeof c.parameters!="object"||Array.isArray(c.parameters)||c.parameters.type!=="object")throw new y("invalid_tools","Invalid or duplicate tool descriptor");l.add(c.name)}return a.tools=structuredClone(o.tools),await a.request("health",void 0,s),a}catch(o){throw await a.dispose(),o}}fail(e){this.stopped=!0;for(let i of this.pending.values())clearTimeout(i.timer),i.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let i;try{i=Buffer.byteLength(JSON.stringify(e))}catch{return}if(i>v0){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let n=this.pending.get(r.id);if(!n)return;if(clearTimeout(n.timer),this.pending.delete(r.id),!n.expired){let s=r.error;r.ok===!0?n.resolve(r.value):n.reject(new y(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let n=this.pending.get(r.invocationId);try{if(!n?.invocation||n.expired)throw new y("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(n.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:fe(s)})}}}request(e,i,r=3e4,n){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new y("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new y("worker_busy","Too many plugin requests"));let s=n?.requestId??v1();if(this.pending.has(s))return Promise.reject(new y("duplicate_request","An identical request is still running"));let a={type:"request",id:s,method:e,input:i};return Buffer.byteLength(JSON.stringify(a))>v0?Promise.reject(new y("message_too_large","Plugin request exceeds limit")):new Promise((o,l)=>{let c=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),l(new y("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:o,reject:l,timer:c,invocation:n,expired:!1}),this.child.send(a,p=>{p&&(clearTimeout(c),this.pending.delete(s),l(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,i=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,i,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(i=>{let r=()=>{clearTimeout(n),this.events.off("idle",r),i(!0)},n=setTimeout(()=>{this.events.off("idle",r),i(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new y("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let i=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",i),this.child.kill("SIGTERM")})}}}};var E1={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},ja=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,i,r=E1,n){this.broker=e,this.workerEntry=i,this.hooks=r,this.capabilities=n}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let i=this.operations.then(e,e);return this.operations=i.catch(()=>{}),i}async ownRuntime(){if(this.releaseOwnership)return;let e=await Dp(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,i,r)=>this.capabilities?.handles(i)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,i,r):this.broker.call(e,i,r);invoke(e,i){return this.phaseValue!=="active"||!this.worker?Promise.reject(new y("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},i)}flushAction(e,i){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new y("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},i)}replace(e,i=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new y("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new y("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(c){throw this.worker||await this.releaseOwnership?.(),c}let n=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let a=null,o=!1,l=!1;try{if(a=await Un.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(i))throw new y("drain_pending","Plugin calls are still running; switch deferred without killing them");if(l=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(i))throw new y("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new y("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(a.tools)),this.phaseValue="switching";let c=r?await this.broker.forkState(n):k1(),p=await this.broker.activate(n,{version:e.version,stateRef:c,schema:e.manifest.dataSchemaVersion,enabled:!0});o=!0,this.worker=a,a=null,this.phaseValue="active",this.pendingPackage=null;let d=!1;try{await this.hooks.committed(p)}catch{d=!0}return await s?.dispose(),{pending:!1,active:p,...d?{reconnectRequired:!0}:{}}}catch(c){throw o||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",l&&await this.hooks.resume().catch(()=>{})),c}finally{await a?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,i=!1){return this.serialize(async()=>{let r=this.worker,n=this.phaseValue,s=await this.broker.active(),a=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new y("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Un.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(l){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),l}}};this.phaseValue="draining";try{let l=async c=>{try{await c()}catch(p){if(!i)throw p}};await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Plugin work is still draining; current host retained")}),await l(()=>this.hooks.freeze()),await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(l){try{await a(),this.phaseValue=n,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw l}let o=!1;return()=>this.serialize(async()=>{o||(await a(),this.phaseValue=n,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let i=this.worker,r;try{r=(await this.broker.recover()).active}catch(a){throw i||await this.releaseOwnership?.(),a}if(!r){if(i)throw this.phaseValue="failed",new y("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!i&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let n=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Checkpoint synchronization is still running");let a=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await i?.dispose(),await this.hooks.committed(a)}catch(a){throw this.worker===i&&(this.phaseValue=n,s&&await this.hooks.resume().catch(()=>{})),a}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let i=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Host checkpoint synchronization is still running");await i?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(n){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),n}})}};import{readFile as w0}from"node:fs/promises";var Fa=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new Sr({root:tt(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let i=e.capabilities?new Da(e.capabilities):void 0;this.scheduler=new Ma({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:I1(),scope:s,kind:"action",action:n.action,input:{schedule:n.id}})},onError:(r,n,s)=>e.onScheduleError?.(r,n.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let n=new Bi(tt(e.root,"data"),r.id,e.legacy?.(r.id),void 0,e.workspaceRules?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new ja(n,e.workerEntry,{validateCandidate:a=>s.validateCandidate?.(a),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async a=>{if(a.enabled){let o=await this.installer.load(r.id,a.version);this.packages.set(r.id,o),this.assetTokens.set(r.id,T1(24).toString("base64url"));try{this.scheduler.start(r.id,_r(o.manifest).schedules)}catch(l){this.scheduler.stop(r.id),this.errors.set(r.id,fe(l))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(a)}},i))}}devSource(e){let i=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return!i&&!r?null:async n=>(await this.collectSettled(e).catch(()=>{}),i?this.installer.installDevDirectory(e,i,n):this.installer.installDevArchive(e,r,n))}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){Qe(e,this.installer.catalog);let i=this.supervisors.get(e);if(!i)throw new y("unknown_plugin","Plugin runtime is not registered");return i}serialize(e,i){if(this.supervisor(e),this.closing)return Promise.reject(new y("manager_closed","Plugin manager is shutting down"));let r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,fe(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,i,r=!1){return this.options.lifecycle?this.options.lifecycle(e,i,r):i()}async policies(){let e=await ke(tt(this.options.root,"policies","policies.json"));if(!e){if(await ye(tt(this.options.root,"policies","policies.json"),2*1024*1024))throw new y("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[i,r]of Object.entries(e))if(this.installer.catalog.some(n=>n.id===i)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new y("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(i=>[i,{updatePolicy:"notify"}]))}async diagnostics(){return await ke(tt(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,i){await Ee(tt(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...i,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await te(tt(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,i){return this.recordCheck(e,{status:"up-to-date",version:i,message:"Developer source installed"})}async check(e,i,r,n){try{let s=await this.installer.check(e,i,r,n),a=!i||yt(s.version,i)>0;return a?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:a?"available":"up-to-date",version:s.version,message:a?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:fe(s).code,message:fe(s).message}),s}}async setPolicy(e,i){if(this.supervisor(e),!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion))throw new y("invalid_input","Invalid plugin update policy");await Ee(tt(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await te(tt(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return Ee(Ea(this.options.root),async()=>{let e=await Up(this.options.root);if(!e)return{intent:e,admitted:!1};if(!qp(e))return e.phase==="required-action"&&await Ia(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await Lp(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Lp(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await w0(this.options.workerEntry)).equals(await w0(tt(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){return await Ia(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${fe(i).message}; data retained`}),{intent:e,admitted:!1}}return await Ia(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await Ee(tt(this.options.root,"policies"),async()=>{let i=await this.policies();await te(tt(this.options.root,"policies","policies.json"),i)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let i of this.installer.catalog){let r=this.supervisor(i.id),n=await r.broker.active();if(n?.enabled)try{let s=await this.compatiblePackage(i.id,n.version);await this.lifecycle(i.id,()=>r.replace(s)),this.packages.set(i.id,s),e||await this.collectSettled(i.id)}catch(s){let a=fe(s),o=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(i.id,{...a,message:`Plugin unavailable: startup failed (${a.code}): ${a.message}; data retained. ${o}`})}}}async compatiblePackage(e,i){try{return await this.installer.load(e,i)}catch(r){if(fe(r).code!=="incompatible_plugin")throw r;let n=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==i).sort((s,a)=>yt(a,s));for(let s of n)try{return await this.installer.load(e,s)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),i=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let a=this.supervisor(s.id),o=await a.broker.active(),l=this.packages.get(s.id),c=(e.versions[s.id]??[]).map(p=>p.version).sort((p,d)=>yt(d,p));return{id:s.id,name:s.name,description:s.description,official:s.official!==!1,installed:!!c.length,installedVersions:c,version:c[0]??null,activeVersion:o?.version??null,enabled:o?.enabled??!1,phase:a.phase,generation:a.generation,pendingVersion:a.pendingVersion,updatePolicy:i[s.id]?.updatePolicy??"notify",pinnedVersion:i[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...l&&a.phase==="active"?{digest:l.digest,document:l.manifest.frontend.document.slice(2),controller:l.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${l.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,i])=>i.phase==="active"&&i.generation!==null?[{pluginId:e,generation:i.generation,descriptors:i.tools}]:[])}async manage(e,i,r,n){return this.serialize(e,async()=>{let s=this.supervisor(e),a=(await this.installer.inventory()).versions[e]??[],o=a.map(c=>c.version).sort((c,p)=>yt(p,c))[0],l=await(async()=>{switch(i){case"check":return this.isDevPlugin(e)?{version:o??null,dev:!0}:{version:(await this.check(e,o,void 0,n)).version};case"install":{let c=this.devSource(e);if(c){let m=await c(n);return await this.recordDevSync(e,m.version),{installed:!0,version:m.version}}let p=await this.check(e,o,r,n),d=await this.installer.install(e,p,n);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:d.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:d.version}}case"enable":{let c=r??o;if(!c)throw new y("not_installed","Install the plugin first");let p=await this.installer.load(e,c),d=await this.lifecycle(e,()=>s.replace(p));return d.pending||this.packages.set(e,p),d}case"retry":{let c=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return c&&!p.pending&&this.packages.set(e,await this.installer.load(e,c)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!o)throw new y("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let h=await c(n),f=await s.broker.active();if(await this.recordDevSync(e,h.version),!f?.enabled)return{installed:!0,enabled:!1,version:h.version};if(f.version===h.version&&!s.pendingVersion)return{unchanged:!0,version:h.version};let b=await this.lifecycle(e,()=>s.replace(h));return b.pending||this.packages.set(e,h),b}let p=await this.check(e,o,r,n),d=await s.broker.active();if(p.version===o&&(!d?.enabled||d.version===o)&&!s.pendingVersion)return{unchanged:!0,version:o};let m=p.version===o?await this.installer.load(e,o):await this.installer.install(e,p,n);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:m.version,message:"Selected compatible release installed; activation may wait for editors"}),!d?.enabled)return{installed:!0,enabled:!1,version:m.version};let g=await this.lifecycle(e,()=>s.replace(m));return g.pending||this.packages.set(e,m),g}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,a.map(c=>c.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new y("invalid_operation","Unknown plugin management operation")}})().catch(async c=>{if(["install","update"].includes(i)){this.available.delete(e);let p=fe(c);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw c});return["install","enable","retry","update"].includes(i)&&await this.collectSettled(e),l})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let i=this.supervisor(e);return i.broker.collect(async r=>this.installer.collect(e,async()=>{let n=(await this.policies())[e];return[...r.map(s=>s.version),...i.pendingVersion?[i.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...n?.pinnedVersion?[n.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r,this.options.invokeTimeoutMs?.(e))}flush(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Flush generation changed",{status:409})):n.flushAction(r)}async asset(e,i,r){let n=this.packages.get(e);if(!n)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(n.version,(s.get(n.version)??0)+1);try{return await i0(n,r,i)}finally{let a=s.get(n.version)-1;a?s.set(n.version,a):s.delete(n.version)}}async assetRequest(e){let i=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.assetTokens.get(r),s=Buffer.from(i[2]);if(!n||s.length!==Buffer.byteLength(n)||!A1(s,Buffer.from(n)))return null;let a=await this.asset(r,i[3],i[4]);return a?{...a,pluginId:r}:null}servedManifest(e){return this.packages.get(e)?.manifest??null}async reconcileHostUpgrade(){if(yw(await Up(this.options.root)))return!1;let e=await this.installer.inventory(),i=await this.policies(),r=!0;for(let n of this.installer.catalog){let s=e.versions[n.id];if(s?.length)try{let a=await this.supervisor(n.id).broker.active(),o=a?.enabled?a.version:s.map(c=>c.version).sort((c,p)=>yt(p,c))[0];try{await this.installer.load(n.id,o);continue}catch(c){if(fe(c).code!=="incompatible_plugin")throw c}let l=await this.manage(n.id,"update");l&&typeof l=="object"&&"pending"in l&&l.pending&&(r=!1)}catch(a){r=!1;let o=fe(a);this.errors.set(n.id,o),await this.recordCheck(n.id,{status:"failed",code:o.code,message:o.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,i){let r=new Sr({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),n=await this.installer.inventory();for(let s of this.installer.catalog){let a=(n.versions[s.id]??[]).map(c=>c.version).sort((c,p)=>yt(p,c)),o=await this.supervisor(s.id).broker.active();if(!a.length||this.isDevPlugin(s.id))continue;let l=!1;for(let c of new Set([...o?.enabled?[o.version]:[],...a]))try{await r.load(s.id,c),l=!0;break}catch{}if(!l)try{let c=await r.check(s.id,a[0],void 0,i),p=await r.install(s.id,c,i);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(c){i?.throwIfAborted();let p=fe(c);await this.recordCheck(s.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let i=new Sr({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),n=[];for(let s of this.installer.catalog){let a=r.versions[s.id],o=await this.supervisor(s.id).broker.active();if(!o?.enabled)continue;if(!a?.length){n.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let l=[o.version,...a.map(d=>d.version).sort((d,m)=>yt(m,d))],c=!1,p="";for(let d of new Set(l))try{await i.load(s.id,d),c=!0;break}catch(m){p||=fe(m).message}c||n.push({pluginId:s.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[];try{for(let[i,r]of this.supervisors)e.push(await this.lifecycle(i,()=>r.suspendForRestart(),!0));this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(i){throw await Promise.allSettled(e.reverse().map(r=>r())),this.closing=!1,i}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let i=[],r=async()=>{let n=await Promise.allSettled(i.map(a=>a()));this.closing=!1;let s=n.find(a=>a.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let n of this.supervisors.values())i.push(await n.suspendForRestart(void 0,e));return r}catch(n){throw await r(),n}}};import{randomUUID as x1}from"node:crypto";var V=t=>Object.assign(new Error(t),{status:409,code:"view_barrier"}),qn=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,i,r=2e4,n=15e3,s=12e4){this.pluginId=e,this.generation=i,this.pollMs=r,this.freezeMs=n,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));blockedOnlyByWork=()=>[...this.views.values()].every(e=>e.kind==="controller"||e.frozen||this.immediate||!["editor","workspace"].includes(e.kind));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(i=>i.scope.ownerId===e).map(i=>({...i.identity,viewToken:i.token,kind:i.kind,dirty:i.dirty,busy:i.busy}))}sameScope(e,i,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===i.sessionId&&e.identity.mountId===i.mountId&&e.identity.generation===i.generation}recovery(e,i){return{state:i,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,i){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&i.sessionId===e.sessionId&&r.scope.ownerId===i.ownerId&&r.scope.workspaceId===i.workspaceId)}admitAction(e,i){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||i.ownerId!==r.scope.ownerId||i.workspaceId!==r.scope.workspaceId||i.sessionId!==r.identity.sessionId)throw V("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw V("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,i,r=++this.sequence){return e.commands.push({id:r,type:i,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,i){if(!e||e.pluginId!==this.pluginId||e.sessionId!==i.sessionId||!i.ownerId||!i.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw V("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw V("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw V("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw V("Invalid registration capability");let a=e.viewToken??x1();if(this.cancelledRegistrations.has(a)||this.recoveries.has(a))throw V("View initialization was cancelled; register a new document identity");let o=this.views.get(a);if(o){if(!this.sameScope(o,e,i)||o.kind!==e.kind)throw V("Duplicate view capability");return{viewToken:a,commands:[]}}if([...this.views.values()].some(l=>l.scope.ownerId===i.ownerId&&l.identity.mountId===e.mountId))throw V("Duplicate mount");return this.views.set(a,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...i},token:a,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:a,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw V("Invalid view capability");let r=this.views.get(e.viewToken),n=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,i))throw V("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw V("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let a=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:a}}}if(r&&this.sameScope(r,e,i)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw V("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw V("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&n&&this.sameScope(n,e,i)){if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!n){if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");if(this.switching)throw V("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,i))throw V("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw V("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw V("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw V("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(V("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw V("Invalid acknowledgement");let a=r.commands.find(o=>o.id===e.commandId);if(!a)throw V("Unknown command acknowledgement");r.commands=r.commands.filter(o=>o.id>e.commandId),a.type==="freeze"&&this.barrier?.id===a.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(V(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw V("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw V("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw V("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw V("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw V("Invalid poll cursor");if(r.waiter)throw V("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw V("Invalid poll mode");return!e.immediate&&!r.commands.some(a=>a.id>e.after)&&await new Promise(a=>{let o=setTimeout(l,Math.min(25e3,Math.max(50,this.pollMs)));function l(){clearTimeout(o),r.waiter=void 0,a()}r.waiter=l}),{viewToken:r.token,commands:r.commands.filter(a=>a.id>e.after)}}default:throw V("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw V("A view barrier is already active");if(!this.canSwitch()){let i=[...this.views.values()].filter(n=>n.activeActions||n.kind!=="controller"&&!n.frozen&&(n.busy||!this.immediate&&["editor","workspace"].includes(n.kind))),r=V(`Close editors before updating; old version retained. Pending views: ${i.map(n=>`${n.kind}:${n.identity.mountId}${n.activeActions?` (action in flight x${n.activeActions})`:n.busy?" (busy)":""}`).join(", ")}`);throw this.blockedOnlyByWork()?Object.assign(r,{reason:"view_busy"}):r}this.switching=!0;let e=++this.sequence;try{await new Promise((i,r)=>{let n=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):i())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>n(),reject:s=>n(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(a=>this.barrier?.pending.has(a.token));n(V(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(a=>`${a.kind}:${a.identity.mountId} (session ${a.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||n()})}catch(i){throw await this.resume(),i}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(i=>!i.frozen))throw V("Cannot commit before all views freeze");this.generation=e.generation;for(let i of this.views.values())this.enqueue(i,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(V("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(V("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var S0={"image/png":t=>t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":t=>t[0]===255&&t[1]===216,"image/webp":t=>t.subarray(0,4).toString("latin1")==="RIFF"&&t.subarray(8,12).toString("latin1")==="WEBP"};function k0(t){let e=t;if(!e||typeof e!="object"||e.$hosted!=="tool-result"||!Array.isArray(e.content))return{content:[{type:"text",text:JSON.stringify(t)??"null"}],details:t};let i=[],r=0;for(let n of e.content.slice(0,16)){let s=n;if(s?.type==="text"&&typeof s.text=="string")i.push({type:"text",text:s.text.slice(0,262144)});else if(s?.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&S0[s.mimeType]&&r<4){let a=/^[A-Za-z0-9+/]*={0,2}$/.test(s.data)?Buffer.from(s.data,"base64"):null;a&&a.length<=2097152&&S0[s.mimeType](a)?(i.push({type:"image",data:s.data,mimeType:s.mimeType}),r++):i.push({type:"text",text:"[image omitted by host: invalid or too large]"})}}return i.some(n=>n.type==="text")||i.unshift({type:"text",text:"(no text)"}),{content:i,details:e.details??null}}import{randomUUID as O1}from"node:crypto";var R1="Ov23limJmKiuu8cOP83E";function gd(t,e,i=process.env){let r=t?.secrets&&Object.hasOwn(t.secrets,e)?t.secrets[e]:void 0;if(r?.provider==="github")return{clientId:i.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||r.clientId||R1,scope:r.scope,createUrl:r.createUrl}}var N1="https://github.com/login/device/code",P1="https://github.com/login/oauth/access_token",C1=8,Ba=class{flows=new Map;fetcher;now;constructor(e=(r,n)=>fetch(r,{...n,signal:n.signal??AbortSignal.timeout(15e3)}),i=Date.now){this.fetcher=e,this.now=i}async post(e,i){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(i).toString()})}catch{throw new y("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let n=await r.json().catch(()=>null);if(!n||typeof n!="object"||!r.ok&&!("error"in n))throw new y("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,i,r){if(!r.clientId)throw new y("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[d,m]of this.flows)m.expiresAt<=this.now()&&this.flows.delete(d);if(this.flows.size>=C1)throw new y("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(N1,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:a,verification_uri:o}=n,l=Number(n.expires_in),c=Math.max(Number(n.interval)||5,1);if(typeof s!="string"||typeof a!="string"||typeof o!="string"||!o.startsWith("https://github.com/")||!Number.isFinite(l))throw new y("oauth_failed",typeof n.error_description=="string"?n.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=O1();return this.flows.set(p,{pluginId:e,name:i,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+l*1e3,interval:c,nextPoll:this.now()+c*1e3}),{deviceId:p,userCode:a,verificationUri:o,interval:c,expiresIn:l}}async poll(e){let i=this.flows.get(e);if(!i||i.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<i.nextPoll)return{status:"pending"};i.nextPoll=this.now()+i.interval*1e3;let r=await this.post(P1,{client_id:i.clientId,device_code:i.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:i.pluginId,name:i.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return i.interval+=5,i.nextPoll=this.now()+i.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as fd,readFileSync as E0,readdirSync as D1,statSync as M1}from"node:fs";import{lstat as L1,readdir as U1,writeFile as q1,mkdir as j1,rename as F1}from"node:fs/promises";import{delimiter as B1,dirname as H1,isAbsolute as G1,join as pi,resolve as jn}from"node:path";var Ha=t=>et.some(e=>e.id===t),T0=()=>et.map(t=>t.id).join(", "),ci="piWebappCatalog",W1="https://registry.npmjs.org";function $1(t,e){let i=t[ci];if(i===void 0)throw new y("invalid_catalog",`${e}: ${t.name} is not an official plugin (official: ${T0()}). Describe it in package.json "${ci}" with name, description and policy`);if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_catalog",`${e}: ${ci} must be an object`);if("id"in i||"registry"in i)throw new y("invalid_catalog",`${e}: ${ci} must not set id or registry; the package name is the id`);return{...ad({registry:W1,recommendedVersion:"0.0.0",requiredCapabilities:[...t.piWebapp.capabilities],...i,id:t.name},e,ci),official:!1}}function V1(t=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(t??"").split(/[;\n]/).map(s=>s.trim()).filter(Boolean)){let s=n.lastIndexOf("="),a=n.slice(0,s),o=n.slice(s+1),l=s<1?`entry "${n}" is not <id>=<path.tgz>`:Ha(a)?o.endsWith(".tgz")?fd(jn(o))?null:`archive not found: ${jn(o)}`:`"${o}" is not a .tgz archive`:`"${a}" is not an official plugin (official: ${T0()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(l){i.push({level:"error",source:r,...Ha(a)?{pluginId:a}:{},message:l});continue}e.set(a,jn(o))}return{archives:e,notices:i}}var I0=t=>pi(t,"pi-web","hosted-dev.json"),A0=t=>pi(t,"pi-web","hosted-dev-status.json");function z1(t,e,i=process.cwd()){let r=[],n=[],s=(t.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(B1).map(o=>o.trim()).filter(Boolean);for(let o of s)r.push({path:jn(i,o),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let a=s.length>0;if(e&&fd(e)){a=!0;try{let o=JSON.parse(E0(e,"utf8")),l=o&&typeof o=="object"?o.roots:void 0;if(!Array.isArray(l))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let c of l)typeof c!="string"||!G1(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:jn(c),source:e})}catch(o){n.push({level:"error",source:e,message:`cannot read dev configuration: ${o instanceof Error?o.message:String(o)}`})}}return{specs:r,notices:n,configured:a}}function K1(t){let e=[];try{e=D1(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name!=="node_modules"&&fd(pi(t,i.name,"package.json"))).map(i=>i.name)}catch{}return e.length?`package.json not found; this looks like a parent folder (packages inside: ${e.slice(0,3).join(", ")}). Point at the package directory itself`:"package.json not found; the folder is not a package (is the right branch checked out?)"}function Y1(t){let e=(n,s)=>({notice:{level:"error",source:t.source,...s?{pluginId:s}:{},message:`${t.path}: ${n}`}}),i;try{i=M1(t.path)}catch{return e("directory does not exist")}if(!i.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(E0(pi(t.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?K1(t.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!ni(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Ha(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:$1({name:r.name,piWebapp:r.piWebapp,[ci]:r[ci]},"package.json")}}catch(n){return e(fe(n).message,r.name)}}var Ga=class{catalog=[];policies=new Map;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let i=V1(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.archives=i.archives,this.archiveNotices=i.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let i=z1(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let a of i.specs){let o=Y1(a);if(o.notice){r.push(o.notice);continue}let l=o.pluginId;if(n.has(l)){r.push({level:"error",pluginId:l,source:a.source,message:`${a.path}: plugin ${l} is already provided by ${n.get(l)}`});continue}if(this.archives.has(l)&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${l}; the dev directory wins`}),!Ha(l)&&!this.catalog.some(c=>c.id===l)){if(!e){r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: ${l} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}let{policy:c,...p}=o.entry;this.catalog.push(p),this.policies.set(l,c)}else o.entry&&JSON.stringify(o.entry.policy)!==JSON.stringify(this.policies.get(l))&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: the ${ci} policy changed; restart pi-webapp once (npm run stop && npm run start) to apply it. Code still reloads live.`});n.set(l,a.path),s.set(l,a.source)}for(let a of[...this.roots.keys()])n.has(a)||this.roots.delete(a);for(let[a,o]of n)this.roots.set(a,o);this.rootSource.clear();for(let[a,o]of s)this.rootSource.set(a,o);return this.fileNotices=i.notices,this.rootNotices=r,{configured:i.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Wa=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let i of this.options.sources.notices())this.log(`${i.level}: ${i.message}`);let e=()=>{this.current=this.tick().catch(i=>{this.running&&this.log(`poll failed: ${fe(i).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let i=this.roots.get(e);i&&(i.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,i])=>({pluginId:e,root:i.root,state:i.state,...i.version?{version:i.version}:{},...i.message?{message:i.message}:{}}))}}log(e){(this.options.log??(i=>console.error(`pi-webapp [hosted-dev] ${i}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let i of[...this.roots.keys()])e.has(i)||this.roots.delete(i);for(let[i,r]of e){let n=this.roots.get(i);(!n||n.root!==r)&&(n={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(i,n));let s=await Q1(r);if(s===null){this.set(i,n,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),n.seen=void 0;continue}if(s!==n.seen){n.seen=s;continue}if(!this.stopped){if(s===n.applied){n.retry&&this.options.switcher.retry&&await this.apply(i,n,s,!0);continue}await this.apply(i,n,s)}}await this.publish()}set(e,i,r,n={}){let s=i.state!==r||i.message!==n.message||i.version!==n.version;i.state=r,i.message=n.message,i.code=n.code,i.version=n.version??i.version,s&&(i.at=new Date().toISOString(),this.log(`${e}: ${r}${n.version?` ${n.version}`:""}${n.message?` \u2014 ${n.message}`:""}`))}async apply(e,i,r,n=!1){n||this.set(e,i,"switching");try{let a=(await(n?this.options.switcher.retry(e):this.options.switcher.update(e))).plugins.find(o=>o.pluginId===e);i.applied=r,i.retry=!!a?.installed&&!!a.pendingVersion,a?.installed?a.pendingVersion?this.set(e,i,"pending",{version:a.version,message:`Waiting for editors to close before switching to ${a.pendingVersion}`}):this.set(e,i,"synced",{version:a.version}):this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(s){let a=fe(s),o=a.reason==="view_busy",l=o||["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(a.code);n?(i.applied=r,i.retry=l):l||(i.applied=r);let c=a.code==="not_installed";o?this.set(e,i,"pending",{message:"An open editor is saving; switching once it finishes"}):c?this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,i,"error",{code:a.code,message:`${a.message} (${a.code}). Fix and save again.`})}i.at=new Date().toISOString()}async publish(){let e=this.info(),i=JSON.stringify(e);i!==this.lastNotices&&(this.lastNotices=i,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let n=Object.fromEntries([...this.roots].map(([o,l])=>[o,{root:l.root,state:l.state,version:l.version,message:l.message,code:l.code,at:l.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(o=>o.id),plugins:n,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let a=`${r}.${process.pid}.tmp`;try{await j1(H1(r),{recursive:!0}),await q1(a,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await F1(a,r)}catch{}}};async function Q1(t){let e=[],i=async(r,n)=>{let s=await L1(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await i(pi(t,"package.json"),"package.json");let r=async(n,s,a)=>{if(!(a>16||e.length>8192))for(let o of(await U1(n,{withFileTypes:!0})).sort((l,c)=>l.name.localeCompare(c.name)))o.isDirectory()?await r(pi(n,o.name),`${s}/${o.name}`,a+1):await i(pi(n,o.name),`${s}/${o.name}`)};if(await r(pi(t,"dist"),"dist",0),!e.some(n=>n.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function X1(t){try{return[..._r(t).secrets]}catch{return[]}}var $a=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ba;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Ua,e.dev?.enabled&&(this.devWatcher=new Wa({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async i=>{let r=await this.inventory();return r.plugins.find(n=>n.pluginId===i)?.installed?this.manage({pluginId:i,operation:"update",reopenEditors:!0}):r},retry:i=>this.manage({pluginId:i,operation:"retry",reopenEditors:!0})}})),this.adapter=new Na({policy:(i,r)=>{let n=e.policy?.(i,r);return{...n,enabled:!this.recovery.has(i)&&this.manager.tools.some(s=>s.pluginId===i)&&n?.enabled!==!1}},invoke:async(i,r,n)=>{n?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(o=>o.pluginId===i);if(!s)throw new y("plugin_unavailable","Hosted tool unavailable");let a=await this.manager.invoke(i,s.generation,r);return k0(a)}}),this.manager=new Fa({...e,workspaceRules:i=>a0(this.trusted,i),invokeTimeoutMs:i=>o0(this.trusted,i),lifecycle:(i,r,n)=>this.lifecycle(i,r,n),hooks:i=>({canSwitch:()=>this.coordinator(i).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(nd(this.trusted,i).tools).length)throw new y("unreviewed_tool","Official tool set changed; review required");this.verifyTools(i,r),this.adapter.validateChange(i,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(i).freeze()},committed:async r=>{try{let n=r.enabled?this.manager.tools.find(s=>s.pluginId===i)?.descriptors:[];if(!n)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(i,n),r.enabled){let s=await this.manager.installer.load(i,r.version);this.documents.set(i,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:X1(s.manifest)})}else this.documents.delete(i);this.adapter.change(i,n),await this.coordinator(i).committed(r),e.changed?.(),this.recovery.delete(i)}catch(n){throw this.recovery.set(i,n),await this.coordinator(i).committed(r).catch(()=>{}),n}},resume:()=>this.coordinator(i).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:i=>this.manage(i),secret:async(i,r,n)=>{let s=this.options.capabilities?.secrets,a=this.documents.get(i)?.secrets;if(!s)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(!a?.includes(r))throw new y("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return n===null?await s.delete(i,r):await s.set(i,r,n),this.options.changed?.(),this.inventory()},secretAuth:async i=>{let r=this.options.capabilities?.secrets;if(!r)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(i.phase==="cancel")return this.deviceFlows.cancel(i.deviceId),{status:"cancelled"};if(i.phase==="start"){let s=this.documents.get(i.pluginId)?.secrets.includes(i.name)?gd(this.trusted.get(i.pluginId),i.name):void 0;if(!s)throw new y("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(i.pluginId,i.name,s)}let n=await this.deviceFlows.poll(i.deviceId);return n.status!=="granted"?{status:n.status}:(await r.set(n.pluginId,n.name,n.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(i,r)=>{if(!this.options.approvals)throw new y("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(i,r),this.inventory()},action:(i,r)=>this.action(i,r?.checkpointOnly),views:async i=>{if(i.operation==="list-pending"){if(typeof i.pluginId!="string")throw new y("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(i.pluginId).pendingViews(this.options.ownerId)}}let r=i,n=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(n))},asset:async i=>{let r=await this.manager.assetRequest(i);if(!r)return null;let n=this.trusted.get(r.pluginId)?.browser?.wasm===!0&&wv(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:vv({wasm:n})}}}}verifyTools(e,i){let r=nd(this.trusted,e);for(let n of i)if(!Object.hasOwn(r.tools,n.name)||r.tools[n.name]!==n.action||n.readonly!==r.readonlyActions.includes(n.action))throw new y("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let i=this.views.get(e);if(!i)throw new y("unknown_plugin","Hosted coordinator unavailable");return i}scope(e,i){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||i&&(r.cwd!==i.cwd||r.workspaceId!==i.workspaceId))throw new y("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,i){let r=this.manager.tools.find(n=>n.pluginId===e);if(!r||r.generation!==i)throw new y("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,i=!1){let r=this.queue.then(async()=>{if(this.closing&&!i)throw new y("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,i,r=!1){let n=this.switches.then(async()=>{if(this.closing&&!r)throw new y("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await i();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let a=await new Bi(hd(this.options.root,"data"),e).active();a&&await this.coordinator(e).committed(a).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new y("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=n.catch(()=>{}),n.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let i,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(n=>{i=setTimeout(()=>n(!1),e),i.unref?.()})])}finally{clearTimeout(i)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??et)try{let i=await new Bi(hd(this.options.root,"data"),e.id).active();this.views.set(e.id,new qn(e.id,i?.generation??0))}catch(i){this.recovery.set(e.id,i),this.views.set(e.id,new qn(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=hd(this.options.root,"host-version.json");(await ke(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await Se(this.options.root),await te(e,{version:this.options.hostVersion}))}).catch(e=>{for(let i of this.options.catalog??et)this.recovery.set(i.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),i=this.options.capabilities?.secrets,r=new Map;for(let n of e.plugins){let s=n.enabled?this.documents.get(n.id)?.secrets??[]:[];i&&s.length&&r.set(n.id,await Promise.all(s.map(async a=>{let o=gd(this.trusted.get(n.id),a);return{name:a,configured:await i.has(n.id,a),...o?{signIn:o.clientId?"browser":"token-page",...o.createUrl?{createUrl:o.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(n=>({pluginId:n.id,name:n.name,official:n.official,installed:n.installed,enabled:n.enabled,description:n.description,...r.has(n.id)?{secrets:r.get(n.id)}:{},icon:(this.options.catalog??et).find(s=>s.id===n.id)?.icon,hasRetainedData:n.activeVersion!==null,phase:this.recovery.has(n.id)?"reconnect-required":n.phase,updatePolicy:n.updatePolicy,pinnedVersion:n.pinnedVersion,updateDiagnostic:n.updateDiagnostic,...n.enabled&&n.activeVersion?{version:n.activeVersion}:n.version?{version:n.version}:{},...n.availableVersion?{availableVersion:n.availableVersion}:{},...n.pendingVersion?{pendingVersion:n.pendingVersion}:{},...n.generation!==null?{generation:n.generation}:{},...this.recovery.has(n.id)||n.error?{error:this.recovery.get(n.id)instanceof Error?this.recovery.get(n.id).message:n.error?.message??"Recovery required",errorCode:this.recovery.has(n.id)?"reconnect_required":n.error?.code}:{},...n.enabled&&n.assetBase&&this.documents.has(n.id)&&this.trusted.has(n.id)?{documentUrl:n.assetBase+this.documents.get(n.id).document,controllerUrl:n.assetBase+this.documents.get(n.id).controller,contribution:structuredClone(this.trusted.get(n.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new y("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new y("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let i=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(i){if(this.downloads.has(e.pluginId))throw new y("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,i)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new y("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let n=await this.manager.manage(e.pluginId,e.operation,e.version,i?.abort.signal);if(this.recovery.has(e.pluginId)||n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired)throw new y("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{i&&this.downloads.get(e.pluginId)===i&&this.downloads.delete(e.pluginId)}}async action(e,i=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new y("action_denied","Action is not reviewed by this host",{status:403});let n=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:J1(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||i){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new y("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new y("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{n()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let i=await this.manager.suspendForRestart(e),r=!1,n=async()=>{if(!r)try{await i(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=n,n}catch(i){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),i}finally{for(let i of this.views.values())i.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let i of this.views.values())i.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Z1,readdir as eP,unlink as tP}from"node:fs/promises";import{join as kr}from"node:path";import{randomUUID as iP}from"node:crypto";var yd="hosted-migration.json";function x0(t,e="@chengzhiyi/pi-excalidraw"){return async i=>{let{cwd:r,sessionId:n}=i.scope,s=kr(t,ne(JSON.stringify([r,n])));await Se(t),await Se(s);let a=kr(s,"scope.lock"),o;try{o=await Z1(a,"wx",384)}catch(l){throw l.code==="EEXIST"?new y("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):l}try{await o.writeFile(JSON.stringify({pid:process.pid,operationId:iP()}));let l=await ke(kr(s,yd));if(l&&(l.version!==1||l.pluginId!==e))throw new y("invalid_storage","Legacy scope belongs to another migration");let c=await eP(s),p=[];for(let m of c){if(m==="scope.lock"||m==="focus.json"||m===yd||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(m))continue;if(!/^[\w-]{1,80}\.json$/.test(m))throw new y("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new y("invalid_storage","Too many legacy checkpoints");let g=await ke(kr(s,m),3*512*1024);if(!g||g.version!==1||g.cwd!==r||g.sessionId!==n||!g.draft||m!==`${g.draft.id}.json`)throw new y("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(g.draft)}let d=await ke(kr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(m=>m.id===d)))throw new y("invalid_storage","Invalid legacy focused drawing");return l||await te(kr(s,yd),{version:1,pluginId:e,operationId:i.requestId}),{drafts:p,focused:d}}finally{await o.close(),await tP(a)}}}import{join as dP}from"node:path";import{randomUUID as rP}from"node:crypto";var nP=6e4,Va=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:i,sessionId:r,title:n})=>({id:e,pluginId:i,sessionId:r,title:n}))}async authorize(e,i){let r=this.entries.get(i);if(r&&r.pluginId!==e)throw new y("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new y("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<nP?new y("execute_denied","The user denied execution",{status:403}):(this.entries.set(i,{id:rP(),pluginId:e,sessionId:i,title:this.options.describe?.(i)??i,status:"pending"}),this.options.changed?.(),new y("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,i){let r=[...this.entries.values()].find(n=>n.id===e&&n.status==="pending");if(!r)throw new y("unknown_approval","No such pending approval",{status:404});r.status=i?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as sP,readFile as aP,rename as oP,writeFile as lP}from"node:fs/promises";import{randomUUID as cP,createHash as pP}from"node:crypto";import{join as O0}from"node:path";var za=class{dir;queue=Promise.resolve();constructor(e){this.dir=O0(e,"secrets")}file=e=>O0(this.dir,`${pP("sha256").update(e).digest("hex")}.json`);async read(e){try{let i=JSON.parse(await aP(this.file(e),"utf8"));if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch(i){if(!ii(i))throw new y("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let i=this.queue.then(e,e);return this.queue=i.catch(()=>{}),i}async get(e,i){return(await this.read(e))[i]??null}has(e,i){return this.get(e,i).then(r=>r!==null)}set(e,i,r){return this.mutate(e,n=>{n[i]=r})}delete(e,i){return this.mutate(e,r=>{delete r[i]})}mutate(e,i){return this.serialize(async()=>{let r=await this.read(e);i(r),await sP(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${cP()}.tmp`;await lP(n,JSON.stringify(r),{mode:384}),await oP(n,this.file(e))})}};function R0(t,e){let i=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:n,title:s,prompt:a}){let o=await t.createDetached(n,r,s);try{await t.sendDetached(o,a,!1)}catch(l){throw await t.releaseDetached(o),l}return{sessionId:o}},ownerOf:r=>t.detachedOwner(r),activeCount:r=>t.detachedCount(r),async send(r,n,s){let a=t.detachedOwner(r);if(s==="execute"&&(!a||!await e(a,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await t.sendDetached(r,n,s==="execute")},abort:r=>t.abortDetached(r),release:r=>t.releaseDetached(r),async events(r,n){let s=t.detachedEvents(r,n);return{events:s.events.map(i),next:s.next}}}}var uP="scheduler";function N0(t){let e=new Va({describe:t.sessionTitle,changed:t.changed}),i=()=>{let n=t.sessions();if(!n)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return n},r={createDetached:(...n)=>i().createDetached(...n),detachedOwner:n=>t.sessions()?.detachedOwner(n)??null,detachedCount:n=>t.sessions()?.detachedCount(n)??0,sendDetached:(...n)=>i().sendDetached(...n),abortDetached:n=>i().abortDetached(n),releaseDetached:async n=>{e.forget(n),await i().releaseDetached(n)},detachedEvents:(...n)=>i().detachedEvents(...n)};return{approvals:e,capabilities:{secrets:new za(dP(t.root,"capability-secrets")),sessions:R0(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=t.activeWorkspace();if(!n)return null;try{return t.trustedScope(n,uP)}catch{return null}}}}ma();async function mP(){for(let t of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=aa(t),i=new kt({env:t,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await i.ready,e.node.enabled||e.browser.enabled||i.enabled||i.reporter||i.capture(new Error("Disabled release probe"))||await i.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await i.close()}}return{release:Mr,buildId:nt,browser:aa({}).browser}}async function P0(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let t=new kt({monitor:!1});try{if(await t.ready,!t.enabled)throw new Error("Sentry verification transport is disabled");let e=t.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await t.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Mr,buildId:nt}}finally{await t.close()}}var Fn=Ir(fP(bP(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),kP=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),u=globalThis[kP]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Li,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};u.lifecycle??=new Li;u.tuiGeneration??=0;u.stopChanged??=null;u.tuiWaitController??=new AbortController;u.tuiStreaming??=null;u.tuiPrompts??=new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()});u.tuiPromptSessionId??=null;u.tuiAgentError??=!1;var D0=!1;function EP(t){return D0||(D0=!0,setTimeout(()=>{t.pruneReleases().catch(()=>{})},6e4).unref()),t}function Ka(){return u.selected==="sdk"?u.workspaceSessions?.catalog??null:u.tuiCatalog}var TP=null;function IP(){return TP??=_P.create({refreshOnCreate:!1})}var Ya=new Map;async function Tr(){let t=await IP(),e=u.selected==="tui"?u.current?.modelRegistry:void 0,i=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Ya.keys())i.has(r)||(t.unregisterProvider(r),Ya.delete(r));for(let r of i){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),a=n??s;!a||Ya.get(r)===a||(n?t.registerNativeProvider(n):s&&t.registerProvider(r,s),Ya.set(r,a))}return await t.refresh({allowNetwork:!1}),t}function Oe(){return u.selected==="sdk"?u.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():Ht()}function Ht(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...Tv(u.current,u.current.sessionManager.getSessionName(),u.tuiCatalog?.ids()??[]),idle:u.current.isIdle()&&!u.tuiPrompts.sending,streaming:u.tuiStreaming,queuedPrompts:u.tuiPrompts.view(),hasPendingPrompts:u.current.hasPendingMessages?.()??!1,interactions:u.interactions?.pending(u.current.sessionManager.getSessionId())??[]}}async function Sd(t,e,i,r,n){let s=Be(t);ei({...Ht(),idle:s.isIdle()},e,n);let a=s.isIdle();a&&fr(()=>u.hosted?.adapter.assertAdmission(),r,(o,l)=>u.bridge?.reportError?.(o,l)),a&&(u.operation=r);try{let o=i.length?[{type:"text",text:e},...i]:e;if(u.replacementContext!==null&&u.replacementSessionId===t)await u.replacementContext.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n});else{if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n})}u.current?.sessionManager.getSessionId()===t&&u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Ht()})}catch(o){throw a&&(u.operation=void 0),o}}function vd(){let t=u.current?.sessionManager.getSessionId(),e=u.tuiGeneration,i=()=>{if(!t||!u.current||u.tuiGeneration!==e||u.current.sessionManager.getSessionId()!==t||u.tuiAgentError)return!1;let r=Ht();return!u.hosted?.adapter.isFrozen&&u.current.isIdle()&&!r.paused&&!r.interactions.length};u.tuiPrompts.schedule(i,(r,n,s)=>Sd(t,r,n,s))}function Me(t){if(Oe().sessionId!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function q0(){let t=(u.workspaces?.list()??[]).map(d=>({...d})),e=u.activeWorkspaceId,i=Oe(),n=u.current?Ht():null,s=await Ri(i.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)),a=n?await Ri(n.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)):null,o=await Bn.listAll(),l=u.workspaceSessions?.retainedSessions()??[];n&&a&&l.push({sessionId:n.sessionId,cwd:a,path:null,name:n.name,modified:n.messages.at(-1)?.timestamp??new Date().toISOString(),idle:n.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&n.idle&&u.tuiPrompts.length===0&&!n.messages.some(d=>d.role==="user")});let c=await mr(o,Mi(Ae()),new Set(l.filter(d=>!d.idle).map(d=>d.sessionId))),p=(await Promise.all(t.map(async d=>{let g=(await Ci(d.path,o).catch(h=>(h instanceof In?d.available=!1:u.bridge?.reportError?.(h,{stage:"workspace_sessions"}),[]))).map(h=>({id:h.id,workspaceId:d.id,path:h.path,name:h.name||h.firstMessage?.slice(0,50)||"",modified:h.modified.toISOString(),idle:!0}));for(let h of l.filter(f=>f.cwd===d.path)){if(h.blank&&h.sessionId!==i.sessionId)continue;let f=g.findIndex(S=>S.id===h.sessionId),b={id:h.sessionId,workspaceId:d.id,path:h.path??g[f]?.path??null,name:h.name,modified:h.modified,idle:h.idle};f<0?g.unshift(b):g[f]=b}return d.path===s&&!g.some(h=>h.id===i.sessionId)&&g.unshift({id:i.sessionId,workspaceId:d.id,path:null,name:i.name,modified:new Date().toISOString(),idle:i.idle}),g.map(h=>{let f=c.get(h.id)?.view;return f?{...h,subagent:f}:h})}))).flat();return{items:t,activeId:e,sessions:p}}var M0=0;async function xe(){if(!u.bridge)return;let t=++M0;try{let e=await q0();t===M0&&u.bridge?.publish({type:"workspaces",value:e})}catch(e){u.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function wd(t,e=!1){let i=u.workspaces?.get(t);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Tt(i.path),!e&&u.current&&i.path===await Ri(u.current.cwd)&&!u.workspaceSessions?.hasWorkspace(i.path))u.selected="tui",u.activeWorkspaceId=t,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Oe()});else{if(!u.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await u.workspaceSessions.reuseBlank(i.path))&&await u.workspaceSessions.open(i.path,e?"new":"continue"),u.selected="sdk",u.activeWorkspaceId=t,u.bridge?.publish({type:"snapshot",session:Oe()})}await xe()}async function L0(t,e,i){let r=u.workspaces?.get(t);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await Tt(r.path);if(u.workspaceSessions?.hasSession(n,e)||u.current?.sessionManager.getSessionId()===e&&await Ri(u.current.cwd)===n)return r;if(!(await Ci(n)).some(a=>a.id===e&&a.path===i))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function Be(t){let e=u.current;if(e===null||e.sessionManager.getSessionId()!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function Ue(t){u.current=t,u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Oe()})}function j0(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let t=u.selected==="sdk"?u.workspaceSessions?.path:u.current.cwd;if(!t)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=u.selected==="tui"?u.current.isProjectTrusted():u.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return vP.create(t,void 0,{projectTrusted:e})}async function F0(){let t=j0(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),i=new U0({cwd:Oe().cwd,agentDir:Ae(),settingsManager:t}),r=pw(i.listConfiguredPackages(),await i.resolve(async()=>"skip"));return{projectTrusted:t.isProjectTrusted(),global:e(t.getGlobalSettings()),project:e(t.getProjectSettings()),installed:r}}async function AP(t){Me(t.sessionId);let e=u.selected==="tui"?Be(t.sessionId):null;if(e?!e.isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=j0();if(t.scope==="project"&&!i.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=t.value.trim(),n=t.scope==="project"?i.getProjectSettings():i.getGlobalSettings();if(t.kind==="packages"){let s=new U0({cwd:Oe().cwd,agentDir:Ae(),settingsManager:i});t.action==="add"?await s.installAndPersist(r,{local:t.scope==="project"}):await s.removeAndPersist(r,{local:t.scope==="project"})}else if(t.kind==="extensions"){let s=n.extensions??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectExtensionPaths(a):i.setExtensionPaths(a)}else{let s=n.skills??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectSkillPaths(a):i.setSkillPaths(a)}return await i.flush(),u.selected==="tui"?(u.commandContext&&await u.commandContext.reload(),u.current&&Ue(u.current)):(await u.workspaceSessions?.reload(),u.bridge?.publish({type:"plugins_changed"})),await F0()}function Qa(t,e=Pp){if(u.hostedMode===!1||u.hostedMode===void 0&&u.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");u.hostedMode=!0;let i=(c,p)=>{let d=bd(c);return{cwd:d,sessionId:p,workspaceId:C0("sha256").update(d).digest("hex")}},r=Er(Ae(),"pi-web","hosted"),n=new Ga({configPath:I0(Ae())});u.hosted??=new $a({root:r,...n.enabled?{dev:n,devStatusPath:A0(Ae())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...et,...n.catalog],policies:new Map([...Ua,...n.policies])}:{},...N0({root:r,sessions:()=>u.workspaceSessions,activeWorkspace:()=>u.workspaceSessions?.path??null,trustedScope:i,sessionTitle:c=>u.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(hP(Ir(Fn,"../../package.json"),"utf8")).version,packageRoot:Ir(Fn,"../.."),workerEntry:Ir(Fn,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${C0("sha256").update(Ae()).digest("hex")}`,resolveSession:c=>{let p=u.current;if(p?.sessionManager.getSessionId()===c)return i(p.cwd,c);let d=u.workspaceSessions?.hostedScope(c);return d?i(d.cwd,c):null},legacy:()=>x0(Er(Ae(),"pi-web","diagrams")),changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),u.offHostedThaw?.(),u.offHostedThaw=u.hosted?.adapter.onThaw(vd),u.pi=t;let s=nm({async run(...c){if(!u.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return u.bridge.runPluginTool(...c)},async ask(c,p){if(u.pi&&c.sessionId===u.current?.sessionManager.getSessionId())return ya(u.pi.events,c,p);if(!u.workspaceSessions)throw new Error("The Web workbench is not open");return u.workspaceSessions.requestInteraction(c,p)}});for(let c of s)t.registerTool(c);u.tools?.clear(),u.tools=new gr({enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,capture:(c,p)=>u.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>u.bridge?.breadcrumb?.(c,p),anonymize:c=>u.telemetry?.session(c)??"unavailable"});let a=c=>({...u.operation,session:u.telemetry?.session(c.sessionManager.getSessionId()),piVersion:_d,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});u.interactions?.dispose(),u.interactions=new ur(t.events,c=>!!u.bridge&&c.sessionId===u.current?.sessionManager.getSessionId()&&An(u.tuiCatalog,c.pluginId),()=>{u.current&&u.selected==="tui"&&Ue(u.current)});let o=()=>{u.stopChanged?.(),u.stopChanged=t.events.on(ba,()=>{u.selected==="tui"&&u.current&&Ue(u.current)})};o(),t.on("session_start",async(c,p)=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiWaitController=new AbortController,u.tuiGeneration++,o(),u.current=p,u.releaseHostedTui?.(),u.releaseHostedTui=u.hosted?.adapter.mountTui(t,i(p.cwd,p.sessionManager.getSessionId())),u.hosted&&!await u.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),u.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(u.tuiPrompts=new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()}),u.tuiPromptSessionId=p.sessionManager.getSessionId()),u.tuiAgentError=!1,u.bridge){let d=await Pi.discover(p.cwd,p.isProjectTrusted?.()??!1);if(u.current!==p)return;u.tuiCatalog=d}u.replacementSessionId!==p.sessionManager.getSessionId()&&(u.replacementContext=null,u.replacementSessionId=null),Ue(p),u.bridge&&u.selected==="tui"&&u.bridge.publish({type:"plugins_changed"}),u.selected==="tui"&&u.workspaces&&u.workspaces.add(p.cwd).then(async d=>{u.selected!=="tui"||u.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(u.activeWorkspaceId=d.id,await xe())}).catch(d=>{u.bridge?.publish({type:"error",message:d instanceof Error?d.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:u.bridge.reportError?.(d,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!u.autoOpened&&(u.autoOpened=!0,l(p).catch(d=>{p.ui.notify(d instanceof Error?d.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),t.on("agent_start",(c,p)=>{u.tuiAgentError=!1,u.bridge?.breadcrumb?.("agent_start",a(p)),Ue(p),xe()}),t.on("agent_end",(c,p)=>Ue(p)),t.on("agent_settled",(c,p)=>{u.bridge?.breadcrumb?.("agent_end",a(p)),u.tools?.clear(),u.operation=void 0,u.tuiStreaming=null,vd(),Ue(p),xe()}),t.on("tool_execution_start",(c,p)=>{u.tools?.start(c,a(p))}),t.on("tool_execution_end",(c,p)=>{u.tools?.end(c,a(p))}),t.on("model_select",(c,p)=>Ue(p)),t.on("thinking_level_select",(c,p)=>Ue(p)),t.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){u.tuiAgentError=!0;let d=u.bridge?.reportError?.(new Error("Agent response failed"),{...u.operation,stage:"agent",code:"agent_failed",piVersion:_d});u.selected==="tui"&&u.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:d,inTranscript:!0,...u.operation})}c.message.role==="toolResult"&&u.tools?.message(c.message,a(p)),c.message.role==="assistant"&&(u.tuiStreaming=null),u.selected==="tui"&&c.message.role==="assistant"&&u.bridge?.publish({type:"stream",message:null}),Ue(p),xe()}),t.on("session_info_changed",(c,p)=>Ue(p)),t.on("message_update",(c,p)=>{if(u.current=p,c.message.role!=="assistant"||(u.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:Bt(c.message.content)},u.selected!=="tui"||u.bridge===null))return;let d=Date.now();d-u.lastStreamAt<60||(u.lastStreamAt=d,u.bridge.publish({type:"stream",message:u.tuiStreaming}))}),t.on("session_shutdown",async c=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiGeneration++,u.stopChanged?.(),u.stopChanged=null,u.interactions?.cancelAll(),u.releaseHostedTui?.(),u.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){u.current=null;return}await u.hosted?.shutdown(),u.hosted=void 0,u.offHostedThaw?.(),u.offHostedThaw=void 0,u.current=null;let p=u.bridge,d=u.telemetry;u.bridge=null,u.commandContext=null,u.replacementContext=null,u.replacementSessionId=null,u.pi=null;let m=u.workspaceSessions;u.workspaceSessions=null,await m?.dispose(),u.selected="tui",u.activeWorkspaceId=null,u.autoOpened=!1,u.tuiCatalog=null,u.stopPluginWatch?.(),u.stopPluginWatch=null,u.operation=void 0,u.telemetry=null,p?await p.close():await d?.close()});let l=async c=>{u.telemetry??=new kt;try{u.current=c,u.commandContext="newSession"in c?c:null,u.pi=t,u.tuiCatalog=await Pi.discover(c.cwd,c.isProjectTrusted?.()??!1),u.workspaces===null&&(u.workspaces=new ha(Ov(Ae())),await u.workspaces.load());try{await u.workspaces.discover((await Bn.listAll()).map(m=>m.cwd))}catch(m){c.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${m instanceof Error?m.message:String(m)}`,"warning")}let p=await u.workspaces.add(c.cwd);if(u.selected==="tui"&&(u.activeWorkspaceId=p.id),u.bridge&&(u.bridge.protocolVersion!==7||u.bridge.buildId!==nt||typeof u.bridge.reportError!="function"||typeof u.bridge.runPluginTool!="function")){let m=u.bridge;if(u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)&&u.workspaceSessions.session&&!u.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");u.bridge=null,await m.close(),await u.telemetry.close(),u.telemetry=new kt}if(u.bridge===null){let m=u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)?u.workspaceSessions:null,g=m?.session&&m.path?{path:m.path,sessionManager:m.session.sessionManager}:null;m&&(await m.dispose(),u.workspaceSessions=null),u.workspaceSessions??=new Sa(f=>{u.selected==="sdk"&&u.bridge?.publish(f)},()=>u.current?.model,f=>{try{return!!u.current&&bd(u.current.cwd)===f&&(u.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,b)=>u.bridge?.reportError?.(f,b),{enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,breadcrumb:(f,b)=>u.bridge?.breadcrumb?.(f,b),anonymize:f=>u.telemetry?.session(f)??"unavailable"},()=>{xe()},s,{adapter:u.hosted.adapter,scope:i}),g&&await u.workspaceSessions.open(g.path,{sessionManager:g.sessionManager});let h={hosted:u.hosted?.handlers,selfUpdate:EP(new Ra({agentDir:Ae(),packageRoot:Ir(Fn,"../.."),launcherNonce:process.env.PI_WEBAPP_FOREGROUND==="1"?void 0:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:f=>u.hosted.manager.hostUpdateWarnings(f),prefetchPlugins:(f,b)=>u.hosted.manager.prefetchForHost(f,b),beforeRestart:f=>u.hosted.prepareRestart(f)})),snapshot:Oe,busyGitWorkspaces:()=>{let f=(u.workspaceSessions?.retainedSessions()??[]).filter(b=>!b.idle).map(b=>b.cwd);if(u.current&&(!u.current.isIdle()||u.tuiPrompts.sending))try{f.push(bd(u.current.cwd))}catch{f.push(u.current.cwd)}return f},plugins:async()=>{let f=Ka();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Ka()?.asset(f)??null,async invokePluginAction(f,b,S,E){if(Me(f),!Ka()?.has(b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let A=u.selected,C=u.tuiGeneration,N=u.workspaceSessions?.session,R={requestId:SP(),sessionId:f,pluginId:b,action:S,input:E},G=u.selected==="sdk"?await u.workspaceSessions.invokePluginAction(R):await _a(u.pi.events,R,15e3,u.tuiWaitController.signal);if(Me(f),A!==u.selected||(A==="tui"?C!==u.tuiGeneration:N!==u.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return u.selected==="tui"&&u.current&&Ue(u.current),G},async resolvePluginInteraction(f,b,S,E){if(Me(f),!An(Ka(),b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");u.selected==="sdk"?u.workspaceSessions.resolveInteraction(f,b,S,E):u.interactions.resolve(f,b,S,E)},image(f,b,S){Me(f);let A=(u.selected==="sdk"?u.workspaceSessions?.session?.sessionManager.getBranch():u.current?.sessionManager.getBranch())?.find(N=>N.id===b);if(A?.type!=="message"||A.message.role!=="user"||!Array.isArray(A.message.content))return null;let C=A.message.content[S];return C?.type!=="image"?null:{data:Buffer.from(C.data,"base64"),mimeType:C.mimeType}},async workspaces(){return q0()},async addWorkspace(f,b){let S=await u.workspaces.add(f,b);try{await wd(S.id,!0)}catch(E){throw await xe(),E}},async selectWorkspace(f){await wd(f)},async newSessionInWorkspace(f){await wd(f,!0)},async removeWorkspace(f){if(f===u.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await u.workspaces.remove(f),await xe()},async subagentHistory(f,b){let S=u.workspaces?.get(f);if(!S)return null;let E=await Bn.listAll(),A=(await Ci(S.path,E)).find(N=>N.id===b);if(!A)return null;let C=(await mr(E,Mi(Ae()))).get(b);return C?Hv(A.path,b,C):null},async selectSession(f,b,S){let E=u.workspaces?.get(f);if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Tt(E.path),b===u.current?.sessionManager.getSessionId()&&E.path===await Ri(u.current.cwd))u.selected="tui",u.activeWorkspaceId=f,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Oe()});else{if(u.selected==="sdk"&&u.workspaceSessions?.session?.sessionManager.getSessionId()===b&&u.workspaceSessions.path===E.path)return;if(u.workspaceSessions?.hasSession(E.path,b))await u.workspaceSessions.open(E.path,{sessionId:b});else{let A=await Bn.listAll();if(!(await Ci(E.path,A)).some(R=>R.id===b&&R.path===S))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");if((await mr(A,Mi(Ae()))).has(b))throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E3A\u53EA\u8BFB");await u.workspaceSessions.open(E.path,{sessionFile:S})}u.selected="sdk",u.activeWorkspaceId=f,u.bridge?.publish({type:"snapshot",session:Oe()})}await xe()},async renameSession(f,b,S,E){let A=E.replace(/\s+/g," ").trim();if(A.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await L0(f,b,S),u.current?.sessionManager.getSessionId()===b&&u.pi?u.pi.setSessionName(A):u.workspaceSessions?.rename(b,A)||Bn.open(S).appendSessionInfo(A),u.selected==="tui"&&u.current?.sessionManager.getSessionId()===b&&u.bridge?.publish({type:"snapshot",session:Oe()}),await xe()},async deleteSession(f,b,S){let E=await L0(f,b,S);if(u.current?.sessionManager.getSessionId()===b)throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664");let A=await u.workspaceSessions?.discard(b)??null,C=A?.path??(S||null);C&&await Wv(C,Ae()),A?.wasActive&&u.selected==="sdk"&&(await u.workspaceSessions.open(E.path,"new"),u.selected="sdk",u.activeWorkspaceId=f,u.bridge?.publish({type:"snapshot",session:Oe()})),await xe()},async models(){if(u.selected==="sdk")return u.workspaceSessions?.models()??[];let f=u.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let b=f.scopedModels?.map(S=>`${S.model.provider}/${S.model.id}`)??[];return f.modelRegistry.getAvailable().filter(S=>b.length===0||b.includes(`${S.provider}/${S.id}`)).map(S=>({provider:S.provider,id:S.id,name:S.name}))},async providers(){let f=await Tr(),b=new Set((await f.listCredentials()).map(S=>S.providerId));return f.getProviders().map(S=>({id:S.id,name:S.name,configured:f.getProviderAuthStatus(S.id).configured,storedCredential:b.has(S.id),methods:[S.auth.apiKey?.login?"api_key":null,S.auth.oauth?"oauth":null].filter(E=>E!==null)}))},async providerModels(f){let b=await Tr();return Tm(Er(Ae(),"models.json"),f,b)},async updateProviderModel(f,b,S){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=Oe().model;if(S.action==="remove"&&E===`${b}/${S.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(S.action==="save"&&S.originalId&&S.originalId!==S.model.id&&E===`${b}/${S.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let A=await Tr();await Im(Er(Ae(),"models.json"),b,S,A),await A.refresh({providers:[b],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1});let C=S.action==="save"?S.model.id:S.action==="base_url"&&E?.startsWith(`${b}/`)?E.slice(b.length+1):null;if(C&&E===`${b}/${C}`)if(u.selected==="sdk")try{await u.workspaceSessions.setModel(b,C)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let N=Be(f),R=N.modelRegistry.find(b,C);if(!R||!u.pi||!await u.pi.setModel(R))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");Ue(N)}},async logoutProvider(f,b){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Tr();if(!(await S.listCredentials()).some(E=>E.providerId===b))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await S.logout(b),await u.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1})},async loginProvider(f,b,S){let E=await Tr();await E.login(f,b,_m(f,b,S)),await E.refresh({providers:[f],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,b){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Tr();if(S.getProvider(b.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await vm(Er(Ae(),"models.json"),b),await S.refresh({allowNetwork:!1}),await u.current?.modelRegistry.refresh({allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return u.selected==="tui"?(u.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(Me(f),u.selected==="sdk"){let S=u.workspaceSessions?.session;if(!S||!S.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await S.compact(),u.bridge?.publish({type:"snapshot",session:Oe()});return}let b=Be(f);if(!b.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");b.compact()},async setModel(f,b,S){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.setModel(b,S);return}let E=Be(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let A=E.modelRegistry.find(b,S);if(!A||!E.modelRegistry.getAvailable().some(C=>C.provider===b&&C.id===S))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!u.pi||!await u.pi.setModel(A))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");Ue(E)},async setThinkingLevel(f,b){if(Me(f),!["off","minimal","low","medium","high","xhigh"].includes(b))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(u.selected==="sdk"){let A=u.workspaceSessions?.session;if(!A||!A.isIdle||!A.getAvailableThinkingLevels().includes(b))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");A.setThinkingLevel(b),u.bridge?.publish({type:"snapshot",session:Oe()});return}let E=Be(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!E.model||!wP(E.model).includes(b))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.setThinkingLevel(b),Ue(E)},config:F0,updateConfig:AP,async send(f,b,S=[],E,A){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.send(b,S,E,A);return}let C=Be(f);if(ei(Ht(),b,A),A==="followUp"&&(!C.isIdle()||u.tuiPrompts.length>0)){u.tuiPrompts.enqueue(b,S,E),vd();return}if(C.isIdle()&&u.tuiPrompts.sending)throw new Le("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Sd(f,b,S,E,A)},async updateQueuedPrompt(f,b,S,E){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.updateQueuedPrompt(b,S,E);return}if(E.kind==="steer"&&Be(f).isIdle())throw new Le("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await u.tuiPrompts.update(b,S,E,(A,C,N)=>Sd(f,A,C,N,"steer"))},async abort(f){if(Me(f),u.selected==="sdk")await u.workspaceSessions.stop();else{let b=Be(f);if(b.isIdle()&&!u.tuiPrompts.sending)return;if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.tools?.cancel(),u.bridge?.breadcrumb?.("cancel",{...u.operation}),u.pi.appendEntry(Tn),b.abort()}},async resume(f,b){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.resume(b);return}let S=Be(f);if(fr(()=>u.hosted?.adapter.assertAdmission(),b,(E,A)=>u.bridge?.reportError?.(E,A)),!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!u.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!S.modelRegistry.hasConfiguredAuth(S.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");u.operation=b;try{u.pi.sendMessage(va(Oe().messages),{triggerTurn:!0})}catch(E){throw u.operation=void 0,E}},async newSession(f){if(Me(f),u.selected==="sdk"){let E=u.workspaces?.get(u.activeWorkspaceId??"");if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await u.workspaceSessions.reuseBlank(E.path)||await u.workspaceSessions.open(E.path,"new"),await xe();return}let b=Be(f);if(!b.isIdle()||u.tuiPrompts.length>0||u.commandContext===null){await u.workspaceSessions.open(b.cwd,"new"),u.selected="sdk",u.bridge?.publish({type:"snapshot",session:Oe()}),await xe();return}if((await u.commandContext.newSession({withSession:async E=>{u.commandContext=E,u.replacementContext=E,u.replacementSessionId=E.sessionManager.getSessionId(),u.current=E}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await xe()}};h.addWorkspace=u.lifecycle.wrap(h.addWorkspace),h.selectWorkspace=u.lifecycle.wrap(h.selectWorkspace),h.newSessionInWorkspace=u.lifecycle.wrap(h.newSessionInWorkspace),h.removeWorkspace=u.lifecycle.wrap(h.removeWorkspace),h.selectSession=u.lifecycle.wrap(h.selectSession),h.renameSession=u.lifecycle.wrap(h.renameSession),h.deleteSession=u.lifecycle.wrap(h.deleteSession),h.newSession=u.lifecycle.wrap(h.newSession),h.updateConfig=u.lifecycle.wrap(h.updateConfig);try{let f=da(),b=f&&await ua(Ae(),!0);u.bridge=await Ev(h,Fn,u.telemetry,{localFileGrant:f&&b?{platform:f,key:b}:void 0})}catch(f){throw process.env.PI_WEBAPP_LAUNCHER_NONCE&&c.ui.notify(`pi-webapp-start-error: ${f instanceof Error?f.message:String(f)}`,"error"),f}}if(u.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let m=[],g=null;for(let h of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(gP).filter(Boolean))try{m.push(yP(Er(Ir(h),"dist"),(f,b)=>{let S=String(b??"");["client.js","client.css"].includes(S)&&(g&&clearTimeout(g),g=setTimeout(()=>u.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){u.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${h}: ${String(f)}`})}u.stopPluginWatch=()=>{for(let h of m)h.close();g&&clearTimeout(g)}}let d=await e(u.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${u.bridge.url}`,d?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw u.telemetry?.capture(p,{stage:"open_web",piVersion:_d}),u.bridge||(await u.telemetry?.close(),u.telemetry=null),p}};t.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(c,p)=>l(p)}),t.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(c,p)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(c))throw new Error("Launcher stop receipt ID required");try{await u.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!0})}`,"info")}catch(d){console.error("pi-webapp: plugin shutdown refused the stop request:",d),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!1})}`,"warning")}}}),t.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(c,p)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await p.waitForIdle(),await u.lifecycle.run(async()=>{let d=u.workspaceSessions?.session;d&&(await d.waitForIdle(),await u.workspaceSessions.reload()),await p.reload()}))}})}var LY=Qa;export{LY as default,mP as verifySentryDisabledRelease,P0 as verifySentryNodeRelease};
553
+ `)}`:void 0,i<3&&t.cause instanceof Error&&(n.cause=nw(t.cause,e,i+1)),Wi(n)}import{randomUUID as ow}from"node:crypto";import{randomUUID as JO}from"node:crypto";import{EnvHttpProxyAgent as XO,getGlobalDispatcher as vz,setGlobalDispatcher as wz}from"undici";var sw=t=>({httpProxy:t.http_proxy??t.HTTP_PROXY??t.all_proxy??t.ALL_PROXY??"",httpsProxy:t.https_proxy??t.HTTPS_PROXY??t.all_proxy??t.ALL_PROXY??"",noProxy:t.no_proxy??t.NO_PROXY??""});function ZO(t,e){let i=sw(t),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&i.httpsProxy||i.httpProxy))return!1;let n=i.noProxy.toLowerCase();if(n==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),a=r.hostname.toLowerCase();return!n.split(/[,\s]/).filter(Boolean).some(o=>{let l=o.match(/^(.+):(\d+)$/),c=(l?.[1]??o).replace(/^\*?\./,"");return(!l||Number(l[2])===s)&&(a===c||a.endsWith("."+c))})}function eR(t){let e=sw(t);for(let i of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(i).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new XO(e)}function Np({env:t=process.env,onFailure:e=()=>{},fetchRequest:i=globalThis.fetch,autoClose:r=!1}={}){let n,s=new Set,a=i===globalThis.fetch,o=(p,d)=>{try{e(p,d)}catch{}},l=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,d)=>{let m={requestId:JO(),phase:"headers",proxied:a&&ZO(t,p)},g=r?void 0:n,h=!1,f=d?.signal??(p instanceof Request?p.signal:void 0),b=()=>S(),S=()=>{f?.removeEventListener("abort",b),!h&&r&&(h=!0,l(g).catch(()=>{}))},E;try{a?(g??=eR(t),s.add(g),r||(n=g),E=await i(p,{...d,dispatcher:g})):E=await i(p,d)}catch(R){throw o(R,m),S(),R}if(E.ok||o(void 0,{...m,status:E.status}),!E.body)return S(),E;let A=E.body.getReader();f?.addEventListener("abort",b,{once:!0}),f?.aborted&&S();let C=new ReadableStream({async pull(R){try{let W=await A.read();W.done?(R.close(),A.releaseLock(),S()):R.enqueue(W.value)}catch(W){o(W,{...m,phase:"body"}),R.error(W),A.releaseLock(),S()}},async cancel(R){try{await A.cancel(R)}finally{A.releaseLock(),S()}}}),N=new Response(C,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(N,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),N},close:async()=>{await Promise.all([...s].map(l))}}}var aw=(t,e)=>Np({autoClose:!0}).fetch(t,e);var tR=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),iR=t=>typeof t=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(t)?t:void 0;function Pp(t,e={}){let i=[],r=new Set,n=(l,c=0)=>{if(!l||c>4||r.has(l)||i.length>=8)return;r.add(l);let p=iR(l.code);if(i.push({name:tR.has(l.name)?l.name:"Error",...p?{code:p}:{}}),n(l.cause,c+1),l instanceof AggregateError)for(let d of l.errors.slice(0,4))n(d,c+1)};n(t);let s=i.flatMap(l=>l.code?[l.code]:[]),a=e.stage==="model_admission"||s.some(l=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(l))?"lifecycle":s.some(l=>/CERT|TLS|SSL/.test(l))?"tls":s.some(l=>/^PROXY_/.test(l))||e.proxied&&s.some(l=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(l))?"proxy":s.some(l=>/TIMEOUT|ETIMEDOUT/.test(l))||i.some(l=>/TimeoutError$/.test(l.name))?"timeout":i.some(l=>l.name==="AbortError"||l.code==="ABORT_ERR"||l.code==="UND_ERR_ABORTED")?"cancelled":s.some(l=>/ENOTFOUND|EAI_AGAIN/.test(l))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",o=l=>typeof l=="string"&&/^[\w-]{1,80}$/.test(l)?l:void 0;return{errorId:ow(),requestId:o(e.requestId)??ow(),...o(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:a,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:i}}function lw({env:t=process.env,onDiagnostic:e=()=>{},fetchRequest:i=globalThis.fetch}={}){return Np({env:t,fetchRequest:i,onFailure:(r,n)=>e(Pp(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function rR(t){let e={...process.env,...t};for(let i of["http_proxy","https_proxy","all_proxy","no_proxy"])t&&i.toUpperCase()in t&&!(i in t)&&delete e[i];return e}var nR=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function cw(t,e,i=()=>{}){let r=t.agent.streamFunction;t.agent.streamFunction=async(n,s,a)=>{if(!nR.has(n.api))return r(n,s,a);let o=i(),l=lw({env:rR(a?.env),...a?.fetch?{fetchRequest:a.fetch}:{},onDiagnostic:c=>{let p={...c,...o?{operationId:o}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let c=await r(n,s,{...a,fetch:l.fetch});return c.result().finally(()=>l.close()).catch(()=>{}),c}catch(c){throw await l.close(),c}}}function fr(t,e,i){try{t()}catch(r){let n=Pp(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...n})),i?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:n.errorId,requestId:n.requestId,stage:n.stage,code:"hosted_admission_blocked",networkKind:n.kind,networkStage:n.stage,causeCodes:n.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var cR=["read","grep","find","ls"];var dw=200,ka=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Li;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,i,r=()=>!1,n=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},a=()=>{},o=[],l){this.hosted=l,this.publish=e,this.fallbackModel=i,this.isProjectTrusted=r,this.reportError=n,this.onSessionsChanged=a,this.customTools=o,this.offHosted=l?.adapter.onThaw(()=>{for(let c of this.runtimes.values())this.scheduleQueued(c)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(c,p)=>{try{s.enabled()&&s.breadcrumb(c,p)}catch{}},anonymize:c=>{try{return s.enabled()?s.anonymize(c):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await Et(e),n=i==="continue"?this.selectedByWorkspace.get(r):typeof i=="object"&&"sessionId"in i?this.runtimes.get(i.sessionId):void 0;if(n){if(n.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(n);return}if(typeof i=="object"&&"sessionId"in i)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(i==="new")s=hr.create(r);else if(i==="continue"){let o=await hr.listAll(),l=await Ci(r,o),c=l[0]?.parentSessionPath?await mr(o,Mi(pw())):null,p=l.find(d=>!c?.has(d.id));s=p?hr.open(p.path):hr.create(r)}else s="sessionManager"in i?i.sessionManager:hr.open(i.sessionFile);if(await lR(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let a=this.runtimes.get(s.getSessionId());if(a){if(a.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(a);return}await this.replace(r,s,i==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let i=this.selectedByWorkspace.get(await Et(e));return!i||!this.blank(i)?!1:(this.activate(i),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let i=this.runtimes.get(e);return!this.disposed&&i&&!i.closing?{cwd:i.cwd,sessionId:e}:null}hasSession(e,i){return this.runtimes.get(i)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:i,cwd:r,prompts:n}=e,s=i.sessionManager.getBranch(),a=s.flatMap(o=>{let l=Oi(o);return l?[l]:[]});return{sessionId:i.sessionManager.getSessionId(),cwd:r,path:i.sessionManager.getSessionFile()??null,idle:i.isIdle&&!n.sending,name:ha(i.sessionManager.getSessionName(),a),modified:s.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(i=>Oi(i)?.role==="user")}rename(e,i){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(i),!0}discard(e){return this.queue.run(async()=>{let i=this.runtimes.get(e);if(!i||i.closing)return null;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!i.session.isIdle||i.prompts.sending||i.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===i,n=i.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(i.cwd)===i&&this.selectedByWorkspace.delete(i.cwd),r&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged(),{path:n,cwd:i.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,i){!this.disposed&&this.active===e&&!e.closing&&this.publish(i)}diagnostic(e,i,r,n){let s=`plugin=${i} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${n}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,i,r,n){let s=this.runtimes.get(i.getSessionId()),a=await Pi.discover(e,this.isProjectTrusted(e)),o=aR(),l=await tw(e,a.extensionRoots,this.isProjectTrusted(e)),c=new oR({cwd:e,agentDir:pw(),noExtensions:!0,additionalExtensionPaths:l.paths,eventBus:o,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,i.getSessionId()))]:[]}),p=null;try{await c.reload();let d=c.getExtensions().errors;if(d.length)throw new Error(d.map(P=>`${P.path}: ${P.error}`).join("; "));let m=i.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:g}=await sR({cwd:e,sessionManager:i,model:m,resourceLoader:c,customTools:this.customTools}),h=new gr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(P,I)=>this.telemetry.breadcrumb(P,I),anonymize:P=>this.telemetry.anonymize(P)}),f={session:g,cwd:e,catalog:a,bus:o,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:l.release,tools:h,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};f.prompts=s?.prompts??new ti(()=>{let P=this.runtimes.get(i.getSessionId())??f;this.publishFor(P,{type:"snapshot",session:this.snapshotOf(P)}),!this.disposed&&!P.closing&&this.onSessionsChanged()}),p=f,cw(g,P=>{f.networkDiagnostic=P},()=>f.operation?.operationId);let b=P=>this.publishFor(f,P),S=f.detached,E=(P,I)=>{S&&(S.events.push({seq:++S.seq,type:P,...I===void 0?{}:{text:I}}),S.events.length>dw&&S.events.splice(0,S.events.length-dw))};f.interactions=new ur(o,P=>!f.closing&&P.sessionId===g.sessionManager.getSessionId()&&An(a,P.pluginId),()=>b({type:"snapshot",session:this.snapshotOf(f)}));let A=0,C=o.on(_a,()=>b({type:"snapshot",session:this.snapshotOf(f)})),N=g.subscribe(P=>{if(S&&!f.closing&&(P.type==="message_end"&&P.message.role==="assistant"&&(P.message.stopReason==="error"?E("error",P.message.errorMessage??"Agent response failed"):S.lastText=P.message.content.flatMap(I=>I.type==="text"?[I.text]:[]).join(`
554
+ `)),P.type==="agent_settled"&&E("turn_end",S.lastText)),!this.disposed&&!f.closing){let I={...f.operation,session:this.telemetry.anonymize(g.sessionManager.getSessionId()),piVersion:Sa,model:g.model?`${g.model.provider}/${g.model.id}`:null,thinkingLevel:g.thinkingLevel};if(P.type==="agent_start"&&(f.activityId++,this.telemetry.breadcrumb("agent_start",I)),P.type==="tool_execution_start"&&h.start(P,I),P.type==="tool_execution_end"&&h.end(P,I),P.type==="message_end"&&P.message.role==="assistant"&&P.message.stopReason==="error"){f.agentErrorReported=!0;let x=f.networkDiagnostic,L=this.reportError(new Error("Agent response failed"),{...f.operation,stage:"agent",code:"agent_failed",piVersion:Sa,...x?{networkKind:x.kind,networkStage:x.stage,causeCodes:x.causes.flatMap(U=>U.code?[U.code]:[]).join(","),requestId:x.requestId}:{}})??x?.errorId;b({type:"error",message:P.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:L,inTranscript:!0,...f.operation})}P.type==="message_end"&&P.message.role==="toolResult"&&h.message(P.message,I),P.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",I),h.clear(),f.operation=void 0)}P.type==="message_update"&&P.message.role==="assistant"&&(f.streaming={id:"stream",role:"assistant",timestamp:new Date(P.message.timestamp).toISOString(),blocks:Bt(P.message.content)},Date.now()-A>=60&&(A=Date.now(),b({type:"stream",message:f.streaming}))),P.type==="agent_settled"&&this.scheduleQueued(f),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(P.type)&&((P.type==="message_end"&&P.message.role==="assistant"||P.type==="agent_settled")&&(f.streaming=null,b({type:"stream",message:null})),b({type:"snapshot",session:this.snapshotOf(f)}),!this.disposed&&!f.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(P.type)&&this.onSessionsChanged())});f.detach=()=>{C(),N()},f.releaseHosted=this.hosted?.adapter.attach(g);let R=[],W=!0;if(await g.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:P=>{W&&R.push(P.error),this.diagnostic(f,a.plugins.find(I=>P.extensionPath.startsWith(I.root+"/"))?.id??P.extensionPath,P.event??"runtime",P.error)}}),W=!1,R.length)throw new Error(R.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");f.detached&&(f.detached.restoreTools=g.getActiveToolNames(),g.setActiveToolsByName(cR)),this.runtimes.set(g.sessionManager.getSessionId(),f),p=null,f.detached?this.onSessionsChanged():this.activate(f)}catch(d){throw this.hosted?.adapter.releasePending(i.getSessionId()),p?await this.close(p,"quit"):(o.clear(),await l.release()),d}}async close(e,i){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await Kv(e.session,i,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:i,cwd:r,catalog:n}=e,s=i.sessionManager.getBranch().flatMap(a=>{let o=Oi(a);return o?[o]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:r,name:ha(i.sessionManager.getSessionName(),s),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel,thinkingLevels:i.getAvailableThinkingLevels(),idle:i.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:dr(i.sessionManager.getBranch()),promptQueue:{steering:[...i.getSteeringMessages()],followUp:[...i.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:i.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(i.sessionManager.getSessionId()),pluginEntries:wp(i.sessionManager.getBranch(),n.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let i=this.active;if(this.disposed||!i||i.closing||e.sessionId!==i.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=i.session.extensionRunner,n=await va(i.bus,e,15e3,i.waitController.signal);if(this.active!==i||i.closing||r!==i.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),n}requestInteraction(e,i){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):ba(r.bus,e,i)}resolveInteraction(e,i,r,n){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,i,r,n)}async send(e,i=[],r,n){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(ei(this.snapshot(),e,n),n==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,i,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new Le("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,i,r,n)}async prompt(e,i,r,n,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");fr(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),ei({...this.snapshotOf(e),idle:e.session.isIdle},i,s);let a=e.session,o=a.isIdle;o&&(e.operation=n,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...n,piVersion:Sa});let l=!1,c,p,d=new Promise((m,g)=>{c=m,p=g});a.prompt(i,{images:r,streamingBehavior:s,preflightResult:m=>{m&&(l=!0,c())}}).then(()=>{l||c()}).catch(m=>{if(!l)p(m);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let g=this.reportError(xt(m,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:Sa});this.publishFor(e,{type:"error",message:m instanceof Error?m.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:g,...n})}});try{await d}catch(m){throw o&&(e.operation=void 0),m}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!dr(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(i,r,n)=>this.prompt(e,i,r,n))}async updateQueuedPrompt(e,i,r){let n=this.active;if(this.disposed||!n||n.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&n.session.isIdle)throw new Le("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await n.prompts.update(e,i,r,(s,a,o)=>this.prompt(n,s,a,o,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Tn),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");fr(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=i.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!dr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!dr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=wa(this.snapshotOf(i).messages);i.operation=e,i.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(a=>{if(!this.disposed&&!i.closing&&!i.agentErrorReported){let o=this.reportError(xt(a,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(i,{type:"error",message:a instanceof Error?a.message:"\u7EE7\u7EED\u5931\u8D25",errorId:o,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(i=>({provider:i.provider,id:i.id,name:i.name}))}async setModel(e,i){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let n=r.session.modelRuntime.getModel(e,i);if(!n)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(n),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,i,r){return this.queue.run(async()=>{this.ensureAvailable();let n=await Et(e),s=hr.create(n);return await this.replace(n,s,"new",i),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let i=this.runtimes.get(e);return!this.disposed&&i?.detached&&!i.closing?i:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(i=>i.detached?.owner===e&&!i.closing).length}async sendDetached(e,i,r){let n=this.detachedRuntime(e);if(!n)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&n.detached.restoreTools&&(n.session.setActiveToolsByName(n.detached.restoreTools),n.detached.restoreTools=null),!n.session.isIdle||n.prompts.length>0){n.prompts.enqueue(i,[],void 0),this.scheduleQueued(n);return}await this.prompt(n,i,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let i=this.detachedRuntime(e);i&&(this.runtimes.delete(e),this.active===i&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged())})}detachedEvents(e,i){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(n=>n.seq>i),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(i=>this.close(i,"quit")))})}};import{basename as Cp,dirname as pR}from"node:path";function uw(t,e){let i=r=>e[r].map(n=>({name:r==="skills"&&Cp(n.path).toLowerCase()==="skill.md"?Cp(pR(n.path)):Cp(n.path),path:n.path,source:n.metadata.source,scope:n.metadata.scope,enabled:n.enabled}));return{packages:t.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:i("extensions"),skills:i("skills")}}import{execFile as dR}from"node:child_process";var uR=(t,e)=>new Promise((i,r)=>{dR(t,[...e],{windowsHide:!0},n=>{n?r(n):i()})});async function Dp(t,e=process.platform,i=process.env,r=uR){if(i.PI_WEBAPP_AUTO_OPEN==="0"||i.PI_WEBAPP_RUNTIME==="desktop"||i.SSH_CONNECTION||i.SSH_TTY||i.SSH_CLIENT||e==="linux"&&!i.DISPLAY&&!i.WAYLAND_DISPLAY)return!1;let n=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;if(n===null)return!1;let s=e==="darwin"||e==="win32"?await Promise.resolve().then(()=>(ga(),wv)).catch(()=>{}):void 0;return await r(n,[s?await s.localFileLaunchUrl(t,e,i):t]),!0}import{execFile as cN}from"node:child_process";import{randomUUID as Xp}from"node:crypto";import{existsSync as Hw}from"node:fs";import{access as pN,mkdir as Pn,mkdtemp as dN,readFile as oi,realpath as uN,rename as Ww,rm as Gw,writeFile as $w}from"node:fs/promises";import{join as me}from"node:path";import{createHash as Up}from"node:crypto";import{readdir as vR,realpath as bw,rename as wR,stat as SR}from"node:fs/promises";import{join as ai}from"node:path";import{constants as Mp}from"node:fs";import{DatabaseSync as mR}from"node:sqlite";import{lstat as fw,mkdir as gR,open as On,rename as fR,unlink as hw}from"node:fs/promises";import{dirname as hR,join as mw,resolve as yR}from"node:path";import{randomUUID as bR}from"node:crypto";import{setTimeout as _R}from"node:timers/promises";async function Se(t){await gR(t,{recursive:!0,mode:448});let e=await fw(t);if(!e.isDirectory()||e.isSymbolicLink())throw new y("invalid_storage","Plugin storage must be a real directory")}async function ye(t,e){let i;try{i=await On(t,Mp.O_RDONLY|Mp.O_NONBLOCK|(Mp.O_NOFOLLOW??0))}catch(r){if(ii(r))return null;throw r}try{let r=await i.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new y("invalid_storage","Invalid storage record size or type");let n=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<n.length;){let a=await i.read(n,s,n.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==r.size)throw new y("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await i.close()}}async function ke(t,e=2*1024*1024){let i=await ye(t,e);if(!i)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new y("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function Ye(t){let e=await ye(t,2097152);if(e===null)return null;let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new y("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!i||typeof i!="object"||Array.isArray(i))throw new y("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return i}async function te(t,e){let i=`${t}.${bR()}.tmp`,r=await On(i,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await fR(i,t);let n;try{n=await On(hR(t),"r"),await n.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await n?.close()}}finally{await hw(i).catch(()=>{})}}var yw='{"version":2,"mechanism":"sqlite-exclusive"}',gw=t=>t.toString("utf8")===yw,Ea=new Set;async function Lp(t,e,i=0){await Se(t);let r=mw(t,`${e}.lock`),n=mw(t,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new y(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),o;try{o=await On(n,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await o?.close()}let l=await fw(n);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new y("invalid_storage","Ownership database must be a small, single-link regular file");let c=new mR(n,{allowExtension:!1}),p=yR(n),d=Date.now()+i,m=!1;try{for(;;){if(!Ea.has(p))try{c.exec("BEGIN EXCLUSIVE"),Ea.add(p),m=!0;break}catch(f){if(f.errcode!==5)throw f}if(Date.now()>=d)throw new y(s,"Another host owns this plugin storage; wait for it to stop before retrying");await _R(10)}let h=await ye(r,4096);if(h===null){let f;try{f=await On(r,"wx",384),await f.writeFile(yw),await f.sync()}catch(b){if(b.code!=="EEXIST")throw b}finally{await f?.close()}h=await ye(r,4096)}if(h===null||!gw(h))throw a()}catch(h){throw c.close(),m&&Ea.delete(p),h}let g=!1;return async()=>{if(g)return;let h=await ye(r,4096);if(h===null||!gw(h))throw new y("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await hw(r),c.close(),Ea.delete(p),g=!0}}async function Ee(t,e,i=2e3){let r=await Lp(t,"transaction",i);try{return await e()}finally{await r()}}var Ta=t=>ai(t,"host-pair"),kR=t=>Up("sha256").update(JSON.stringify(t)).digest("hex"),ER=10*6e4;async function TR(t){let e=Up("sha256"),i=0,r=0;async function n(s){let a=(await vR(ai(t,s),{withFileTypes:!0})).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0);for(let o of a){if(!s&&o.name==="node_modules")continue;let l=s?`${s}/${o.name}`:o.name;if(o.isSymbolicLink()||!o.isFile()&&!o.isDirectory())throw new y("host_pair_required","Candidate package contains non-regular resources");if(++i>1e4)throw new y("host_pair_required","Candidate package resource budget exceeded");if(o.isDirectory()){await n(l);continue}let c=await ye(ai(t,l),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new y("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([l,Up("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function qp(t,e){let i=await bw(e),r=ai(e,"dist","hosted-worker.js");if(await bw(r)!==ai(i,"dist","hosted-worker.js"))throw new y("host_pair_required","Candidate worker must remain inside the staged host");let n=await ye(ai(e,"package.json"),512*1024);if(!n)throw new y("host_pair_required","Candidate package metadata missing");let s=JSON.parse(n.toString("utf8")),a=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==t||a?.protocol!==2||a?.runtimeProtocol!==1||a?.pairJournal!==1||a?.ownershipProtocol!==2||!Array.isArray(a?.capabilities)||!["state","workspace","legacy","panels","messages"].every(l=>a.capabilities.includes(l)))throw new y("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let o=await ye(r,32*1024*1024);if(!o)throw new y("host_pair_required","Candidate worker missing");return kR([n.toString("base64"),o.toString("base64"),await TR(e)])}async function Ia(t){await wR(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var IR=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function jp(t){let e=ai(Ta(t),"intent.json"),i,r=!0;try{i=await Ye(e)}catch{i=null,r=!1}if(!r||i&&!IR(i))return await Ia(e),null;if(i){let{lifecyclePhase:n,...s}=i,a=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await SR(e).then(o=>o.mtime.toISOString(),()=>new Date(0).toISOString());i={...s,updatedAt:a,phase:s.phase==="selected"&&n==="restart-requested"?"restart-requested":s.phase==="reconciled"&&n==="cancelled"?"cancelled":s.phase==="reconciled"&&n==="required-action"?"required-action":s.phase}}return i}async function Aa(t,e){let{lifecyclePhase:i,...r}={...e,selections:[],updatedAt:new Date().toISOString()},n=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await te(ai(Ta(t),"intent.json"),n)}var Fp=t=>t&&["selecting","selected","restart-requested"].includes(t.phase),_w=(t,e=Date.now())=>!!t&&!!Fp(t)&&e-Date.parse(t.updatedAt??"")<ER;import{promisify as mN}from"node:util";import{realpathSync as Sw,statSync as AR}from"node:fs";import{basename as xR,delimiter as OR,dirname as vw,join as Bp,resolve as RR}from"node:path";function ww(t){if(!t)return null;try{let e=Sw(t);return xR(e)==="npm-cli.js"&&AR(e).isFile()?e:null}catch{return null}}function NR({execPath:t=process.execPath,env:e=process.env}={}){let i=ww(e.npm_execpath);if(i)return i;let r=new Set([vw(t)]);try{r.add(vw(Sw(t)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(OR).filter(Boolean))r.add(RR(s));for(let s of r)for(let a of[Bp(s,"node_modules","npm","bin","npm-cli.js"),Bp(s,"..","lib","node_modules","npm","bin","npm-cli.js"),Bp(s,"npm")]){let o=ww(a);if(o)return o}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function kw(t){return{file:process.execPath,args:[NR(),...t]}}import{randomUUID as PR}from"node:crypto";import{mkdir as Iw,readFile as CR,rename as Wp,rm as DR,unlink as k7,writeFile as MR}from"node:fs/promises";import{isAbsolute as Ew,join as Rn}from"node:path";var Gp=1,LR=1440*6e4,xa=t=>Rn(t,"pi-web","upgrade"),$p=t=>Rn(xa(t),"candidate.json"),UR=t=>Rn(xa(t),"transaction.json"),Tw=t=>Rn(xa(t),"history"),Aw=/^[a-f0-9-]{36}$/i;async function qR(t,e){let i=`${t}.${PR()}.tmp`;try{await MR(i,e,{mode:384}),await Wp(i,t)}finally{await DR(i,{force:!0})}}var jR=(t,e)=>qR(t,JSON.stringify(e));async function Hp(t,e){await Wp(t,`${t}.${e}-${Date.now()}`).catch(i=>{if(i?.code!=="ENOENT")throw i})}async function xw(t,e,i=()=>!1){let r;try{r=JSON.parse(await CR(t,"utf8"))}catch(n){return n?.code==="ENOENT"||await Hp(t,"invalid"),null}return e(r)?i(r)?(await Hp(t,"expired"),null):r:(await Hp(t,"invalid"),null)}function Ow(t){if(!t||typeof t!="object"||t.schema!==Gp||!Aw.test(t.id??""))return!1;try{kt(t.version)}catch{return!1}return typeof t.launcher=="string"&&Ew(t.launcher)&&typeof t.packageRoot=="string"&&Ew(t.packageRoot)&&["stable","alpha"].includes(t.channel)&&typeof t.downgrade=="boolean"&&!Number.isNaN(Date.parse(t.createdAt??""))}async function Oa(t,e=Date.now()){return xw($p(t),Ow,i=>e-Date.parse(i.createdAt)>LR)}async function Rw(t,e){let i={schema:Gp,createdAt:new Date().toISOString(),...e};if(!Ow(i))throw new Error("Invalid upgrade candidate");return await Iw(xa(t),{recursive:!0,mode:448}),await jR($p(t),i),i}async function Vp(t,e,i){let r=await Oa(t);!r||e&&r.id!==e||(await Iw(Tw(t),{recursive:!0,mode:448}),await Wp($p(t),Rn(Tw(t),`${r.id}-candidate-${i}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var FR=["selected","committed","rolled-back"];function BR(t){return!!t&&typeof t=="object"&&t.schema===Gp&&Aw.test(t.id??"")&&FR.includes(t.phase)&&typeof t.version=="string"&&typeof t.from=="string"&&!Number.isNaN(Date.parse(t.updatedAt??""))}async function Nw(t){return xw(UR(t),BR)}import{readFile as HR,rename as WR,writeFile as GR,unlink as $R}from"node:fs/promises";import{join as VR}from"node:path";import{randomUUID as zR}from"node:crypto";var zp=1,Pw=t=>VR(t,"pi-web","launcher-handoff.json");function Cw(t){return t?.protocol===zp&&typeof t.nonce=="string"&&t.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(t.requestId)&&Number.isSafeInteger(t.pid)&&t.pid>0&&["requested","draining","stopped","refused","failed"].includes(t.phase)}async function Kp(t){try{let e=JSON.parse(await HR(Pw(t),"utf8"));if(!Cw(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function KR(t,e){let i=`${t}.${zR()}.tmp`;try{await GR(i,JSON.stringify(e),{mode:384}),await WR(i,t)}finally{await $R(i).catch(()=>{})}}async function Dw(t,e){if(!Cw(e))throw new Error("Invalid launcher handoff receipt");await KR(Pw(t),e)}import{execFile as YR}from"node:child_process";import{cp as QR,readFile as Yp,realpath as JR,rm as XR}from"node:fs/promises";import{join as yr,sep as ZR}from"node:path";import{promisify as eN}from"node:util";var Mw=eN(YR),Qp=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Jp(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=t;return Qp.map(i=>{let r=e[i];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${i}@${r}`})}async function Ra(t){return Promise.all(Qp.map(async e=>{let i=await pr(t,e),r=JSON.parse(await Yp(yr(i,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Lw(t,e){let i=JSON.parse(await Yp(yr(e,"package.json"),"utf8"));if(i.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=i.peerDependencies===void 0?await Ra(t):Jp(i.peerDependencies);if(JSON.stringify(await Ra(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let n=await pr(t,"node-pty"),s=await pr(e,"node-pty"),a=await JR(yr(e,"../.."));if(n===s||!s.startsWith(a+ZR))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let o=async d=>JSON.parse(await Yp(yr(d,"package.json"),"utf8")).version;if(await o(n)!==await o(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await XR(s,{recursive:!0,force:!0}),await QR(n,s,{recursive:!0});let l={...process.env};delete l.NODE_OPTIONS,delete l.NODE_PATH,delete l.ELECTRON_RUN_AS_NODE,await Mw(process.execPath,[yr(e,"desktop","check-pty.cjs")],{cwd:e,env:l,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await pr(e,Qp[0]),{stdout:p}=await Mw(process.execPath,[yr(c,"dist","bundle","cli.js"),"--version"],{cwd:e,env:l,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}import{lstat as qw,readdir as jw,readFile as tN,realpath as Uw,rm as iN}from"node:fs/promises";import{join as Nn,relative as rN,sep as Fw}from"node:path";var nN=1440*6e4,sN=1024*1024,aN=4,oN=t=>t==="releases"||t==="history"||t.endsWith("-history");async function lN(t,e){let i=new Set,r=[...new Set(e.flatMap(a=>[a+Fw,a+"/"]))],n=a=>{if(typeof a=="string")for(let o of r){let l=a.indexOf(o);l>=0&&i.add(a.slice(l+o.length).split(/[\\/]/)[0])}else Array.isArray(a)?a.forEach(n):a&&typeof a=="object"&&Object.values(a).forEach(n)},s=async(a,o)=>{let l=await jw(a,{withFileTypes:!0}).catch(()=>[]);for(let c of l){let p=Nn(a,c.name);if(c.isDirectory()){o<aN&&!oN(c.name)&&await s(p,o+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await qw(p)).size>sN)continue;n(JSON.parse(await tN(p,"utf8")))}catch{}}};return await s(t,0),i}async function Bw(t){let e=Nn(t.agentDir,"pi-web"),i;try{i=await Uw(Nn(e,"releases"))}catch{return[]}let r=t.now??Date.now(),n=t.graceMs??nN,s=await lN(e,[Nn(e,"releases"),i]);try{let o=rN(i,await Uw(t.packageRoot));o&&!o.startsWith("..")&&s.add(o.split(Fw)[0])}catch{}let a=[];for(let o of await jw(i,{withFileTypes:!0}).catch(()=>[])){if(!o.isDirectory()||s.has(o.name))continue;let l=Nn(i,o.name);try{if(r-(await qw(l)).mtimeMs<n)continue;await iN(l,{recursive:!0,force:!0}),a.push(o.name)}catch{}}return a}var gN=mN(cN),br=t=>["committed","cancelled","failed"].includes(t);function Vw(t){let e=t.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function fN(t,e){try{let i=kw(t),{stdout:r}=await gN(i.file,i.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(i){let r=i;throw new Error(r.stderr?.trim()||r.message)}}var Na=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;async resumeUnacceptedRestart(e,i){if(!(e||!i))try{await i()}catch(r){console.error("pi-webapp: failed to resume after an unaccepted restart:",r)}}constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??fN,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async i=>{let r=(await this.runNpm(["view",`pi-webapp@${i}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return Ra(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Jp(s)},this.verifyPackage=e.verifyPackage??Lw,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?zp:0}}async requestLauncherHandoff(e,i){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(i))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!br(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let n=me(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await oi(n,"utf8")),a=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!a(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let o=await Kp(this.agentDir);if(o?.nonce===e&&["requested","draining"].includes(o.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let l,c=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(l=await this.beforeRestart(),!a(JSON.parse(await oi(n,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:i,pid:s.pid,phase:"requested"};try{await Dw(this.agentDir,p),c=!0}catch(d){let m=await Kp(this.agentDir).catch(()=>null);if(c=m?.nonce===e&&m?.requestId===i&&["requested","draining","stopped"].includes(m.phase),!c)throw d}this.restartPending=!0}finally{await this.resumeUnacceptedRestart(c,l)}}async current(){let e=JSON.parse(await oi(me(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return kt(e.version),e.version}async pruneReleases(){if(this.preparing||this.preparedUpdate||this.restartPending||this.cancellation)return[];let e=await this.transaction();return e&&!br(e.phase)?[]:Bw({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),i=await this.transaction();if(!i||br(i.phase)||i.id===this.ownTransaction)return e;if(i.version===e&&["selecting","selected","restart-requested"].includes(i.phase))await this.record({...i,phase:"committed",message:"Selected version is running"});else if(i.phase==="restart-requested"){let r=await Nw(this.agentDir);await this.record({...i,phase:"failed",message:r?.id===i.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Vp(this.agentDir,i.id,"superseded"),await this.record({...i,phase:"failed",message:`Interrupted while ${i.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return me(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await Ye(this.transactionPath)}catch{return await Ia(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await Ia(this.transactionPath),null):e:null}async record(e){if(await Pn(me(this.agentDir,"pi-web"),{recursive:!0}),await te(this.transactionPath,e),br(e.phase)){let i=me(this.agentDir,"pi-web","update-history");await Pn(i,{recursive:!0}),await te(me(i,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),i=await Oa(this.agentDir);i&&(!e||i.id===e.id)&&await Vp(this.agentDir,i.id,"cancelled"),e&&!br(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return me(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await oi(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let i=`${this.preferencePath}.${Xp()}.tmp`;try{await Pn(me(this.agentDir,"pi-web"),{recursive:!0}),await $w(i,JSON.stringify({channel:e}),{mode:384}),await Ww(i,this.preferencePath)}finally{this.savingPreference=!1,await Gw(i,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),i=await this.channel(),r=Hw(me(this.packageRoot,".git")),n={current:e,channel:i,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(n.launcher=this.launcherIdentity(),n.launcherHandoff={supported:n.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(n.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!br(s.phase)?n.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(n.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...n,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&i==="alpha"&&!this.desktopReleaseChannels)return{...n,canRestart:!1,reason:n.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?n.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":n.canRestart||(n.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&n.canRestart&&(n.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let a=JSON.parse((await this.runNpm(["view","pi-webapp",i==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),o=Array.isArray(a)&&a.length===1?a[0]:a,l=i==="alpha"?o:{latest:o};if(!l||!gv(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let c=l.latest;if(i==="alpha"&&l.alpha!==void 0){if(!ca(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");Ke(l.alpha,c)>0&&(c=l.alpha)}if(n.latest=c,n.downgrade=Ke(c,e)<0,n.available=i==="stable"?Ke(c,e)!==0:Ke(c,e)>0,n.available&&this.pluginWarnings){let p=await this.pluginWarnings(c).catch(()=>[]);p.length&&(n.pluginWarnings=p)}this.desktopManaged&&n.downgrade&&!this.desktopReleaseChannels&&Ke(c,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(n.canRestart=!1,n.requiresDesktopUpgrade=!0,n.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(a){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`)}return n}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let i=this.prepareUpdate(e);this.preparation=i;try{return await i}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(Hw(me(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let i=await this.check();if(e.channel!==i.channel||e.version!==i.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let i=await this.check();if(e&&(e.channel!==i.channel||e.version!==i.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!i.canRestart)throw new Error(i.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!i.available||!i.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(i.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=me(this.agentDir,"pi-web","releases");await Pn(r,{recursive:!0});let n=await dN(me(await uN(r),`${i.latest}-`)),s=me(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),a={schema:1,id:Xp(),phase:"downloading",version:i.latest,channel:i.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=a.id,await this.record(a);try{let o=this.desktopManaged?await this.targetPeerSpecs(i.latest):[];await this.runNpm(["install",`pi-webapp@${i.latest}`,...o,"--prefix",n,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=me(n,"node_modules","pi-webapp");a={...a,phase:"validating",packageRoot:l},await this.record(a);let c=JSON.parse(await oi(me(l,"package.json"),"utf8"));if(c.name!=="pi-webapp"||c.version!==i.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await oi(me(this.packageRoot,"package.json"),"utf8"));if(i.downgrade&&Vw(c)!==Vw(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let d=me(l,"bin","pi-webapp.mjs");return await Promise.all([d,me(l,"dist","extension.js"),me(l,"web","dist","index.html")].map(m=>pN(m))),this.desktopManaged&&(await gp(this.agentDir,{version:i.latest,launcher:d,desktopProtocolVersion:ri}),await this.verifyPackage(this.packageRoot,l)),await this.prefetchPlugins?.(i.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Rw(this.agentDir,{id:a.id,version:i.latest,launcher:d,packageRoot:l,channel:i.channel??"stable",downgrade:!!i.downgrade}),a={...a,phase:"prepared"},await this.record(a),this.preparedUpdate={id:a.id,update:{version:i.latest,launcher:d},channel:i.channel??"stable"},{version:i.latest,launcher:d}}catch(o){await Gw(n,{recursive:!0,force:!0});let l=(o instanceof Error?o.message:String(o)).slice(0,500);throw await this.record({...a,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${l}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),o}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:i=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let n,s=!1,a=me(this.agentDir,"pi-web","launcher.restart");try{if(n=await this.beforeRestart?.(i),(await Oa(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let o=await this.transaction();o?.id===r.id&&await this.record({...o,phase:"restart-requested"});try{if(JSON.parse(await oi(a,"utf8"))?.nonce!==this.launcherNonce){let c=me(this.agentDir,"pi-web","restart-history");await Pn(c,{recursive:!0,mode:448}),await Ww(a,me(c,`stale-${Xp()}.json`))}}catch{}try{await $w(a,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(l){try{let c=JSON.parse(await oi(a,"utf8"));s=c.nonce===this.launcherNonce&&c.candidate===r.id}catch{}if(!s)throw l}this.restartPending=!0}catch(o){if(s){this.restartPending=!0;return}try{let l=await this.transaction();l?.id===r.id&&l.phase==="restart-requested"&&await this.record({...l,phase:"prepared"})}catch(l){console.error("pi-webapp: failed to reset the update journal after an unaccepted restart:",l)}throw o}finally{await this.resumeUnacceptedRestart(s,n)}}};import{createHash as L0,randomUUID as TP}from"node:crypto";import{randomUUID as eP}from"node:crypto";import{join as bd}from"node:path";import{randomUUID as Yw}from"node:crypto";import{randomUUID as hN}from"node:crypto";function zw(t){let i=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(a=>typeof t[a]!="function").map(a=>String(a));if(i.length)return{supported:!1,missing:i};let r=`__pi_web_contract_${hN().replaceAll("-","")}`,n;try{if(n=t.getActiveTools(),!Array.isArray(n))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{t.registerTool(s),t.setActiveTools([...n,r]),(t.getAllTools().find(o=>o.name===r)?.exposure!=="hidden"||t.getActiveTools().includes(r))&&i.push("hidden-tool-exposure");let a={type:"object",properties:{contract:{type:"boolean"}}};t.registerTool({...s,parameters:a}),t.getAllTools().find(o=>o.name===r)?.parameters!==a&&i.push("dynamic-tool-registry")}catch{i.push("tool-registry-contract")}finally{try{t.setActiveTools(n)}catch{i.push("active-tool-registry")}}return{supported:!i.length,missing:i}}var yN;function Kw(){return yN??=bN().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function bN(){let{createAgentSession:t,DefaultResourceLoader:e,SessionManager:i}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:n,rm:s}=await import("node:fs/promises"),{tmpdir:a}=await import("node:os"),{join:o}=await import("node:path"),l=await n(o(a(),"pi-sdk-contract-")),c,p=[],d=0,m=0,g=!1,h=!1;try{let f=(N,R,W)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:R,parameters:{type:"object",properties:{}},execute:W}),b=()=>({content:[],details:void 0}),S=new e({cwd:l,agentDir:l,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[N=>{N.on("tool_call",R=>{if(R.toolName==="__contract_direct"&&(g=!!R.parentToolCallId),R.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let R of["hidden","model-only"])N.registerTool(f(`__contract_${R.replace("-","_")}`,R,async()=>(m++,b())));N.registerTool(f("__contract_protected","direct",async()=>(m++,b()))),N.registerTool(f("__contract_direct","direct",async()=>(d++,b()))),N.registerTool(f("__contract_driver","direct",async(R,W,P,I,x)=>{let L=await x.executeTool("__contract_hidden",{}),U=await x.executeTool("__contract_model_only",{}),k=await x.executeTool("__contract_direct",{}),v=await x.executeTool("__contract_protected",{});return(!L.isError||!U.isError)&&p.push("nested-tool-exposure"),(k.isError||d!==1)&&p.push("nested-tool-execution"),(!v.isError||m!==0)&&p.push("nested-tool-permission-guard"),g||p.push("nested-parent-identity"),h=!0,b()}))}]});await S.reload(),{session:c}=await t({cwd:l,agentDir:l,sessionManager:i.inMemory(l),resourceLoader:S}),await c.bindExtensions({mode:"print"});let E=c.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(E);let A=0;c.agent.streamFunction=async N=>{let R=A++===0,W={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:R?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:R?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},P=r();return P.push({type:"start",partial:W}),P.push({type:"done",reason:R?"toolUse":"stop",message:W}),P.end(W),P};let C;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((N,R)=>{C=setTimeout(()=>R(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(C)}return h||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(l,{recursive:!0,force:!0})}}var Pa=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=Kw().then(e=>{this.sdkContract=e;for(let i of this.bindings)if(i.ready&&!i.disposed)try{this.publish(i)}catch{i.compatible=!1,i.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(i=>this.waiters.add(i))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let i;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,n)=>{i=setTimeout(()=>n(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(i)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async i=>{await this.verifyCompatibility(),this.install(i,e)}}mountTui(e,i){let r=this.install(e,i);r.ready=!0;try{this.publish(r)}catch(n){throw this.release(r),n}return()=>this.release(r)}install(e,i){let r={pi:e,scope:{...i},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let n=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{n(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),n(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),n(e.on("tool_call",s=>{let a=r.owned.get(s.toolName);if(!a)return;let o=this.descriptors.get(a)?.find(l=>l.name===s.toolName);if(!o||!this.allowed(r,a,o,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),n(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),n(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let i=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!i)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");i.session=e,i.ready=!0,i.off=e.subscribe(r=>{r.type==="agent_settled"&&(i.busy=!1,this.notify())});try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}releasePending(e){for(let i of this.bindings)!i.session&&!i.ready&&i.scope.sessionId===e&&this.release(i)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let i of e.handlers)i();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,i,r,n=!1){let s=this.service.policy(i,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!n||s.allowNested===!0)}change(e,i){if(!this.frozen||[...this.bindings].some(n=>n.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(i);this.validateChange(e,r),this.descriptors.set(e,r);for(let n of this.bindings)n.ready&&this.publish(n)}validateChange(e,i){for(let n of this.bindings)if(n.compatible!==!1)for(let[s,a]of n.owned)this.assertOwner(n,a,s);let r=new Set;for(let n of i){if(!n.name||!n.action||!n.parameters||n.parameters.type!=="object"||r.has(n.name))throw new Error("Invalid hosted tool descriptor");r.add(n.name);for(let[s,a]of this.descriptors)if(s!==e&&a.some(o=>o.name===n.name))throw new Error(`Hosted tool ownership conflict: ${n.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,n.name)}}assertOwner(e,i,r){let n=e.owned.get(r);if(n&&n!==i)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(a=>a.name===r);if(s&&(!n||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=zw(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,n]of e.owned)this.assertOwner(e,n,r);for(let[r,n]of this.descriptors)for(let s of n)this.assertOwner(e,r,s.name);let i=new Set;for(let[r,n]of this.descriptors)for(let s of n){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;i.add(s.name);let a=this.service.policy(r,e.scope),o=a.exposure??"direct",l=!a.allowNested&&o==="direct"?"model-only":o,c={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:l,execute:async(p,d,m)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Yw(),scope:{...e.scope},kind:"tool",action:s.action,input:d},m)}};e.pi.registerTool(c),e.definitions.set(s.name,c)}for(let r of e.owned.keys())if(!i.has(r)){let n={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:_N};e.pi.registerTool(n),e.definitions.set(r,n)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let n=e.definitions.get(r);return!n||n.exposure==="direct"||n.exposure==="model-only"}))}async invokeAction(e,i,r,n,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(o=>o.scope.sessionId===i.sessionId&&o.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let a=this.service.policy(e,i);if(!a.enabled||a.planMode||a.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:Yw(),scope:i,kind:"action",action:r,input:n},s)}};async function _N(){throw new Error("Hosted tool unavailable")}import{randomBytes as x1,randomUUID as O1,timingSafeEqual as R1}from"node:crypto";import{join as tt}from"node:path";var vN=30,Qw=/^[a-z][a-z0-9-]{0,63}$/,wN=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Cn=t=>{throw new y("invalid_package",t)},Zp=(t,e)=>t===void 0?[]:!Array.isArray(t)||t.length>32?Cn(`Invalid ${e} declaration`):t;function _r(t){let e=t&&typeof t=="object"?t:{},i=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(o=>typeof o=="string"):[]),r=i.has("secrets")?Zp(e.secrets,"secrets").map(o=>{let l=o?.name;return typeof l=="string"&&Qw.test(l)?l:Cn("Invalid secret name")}):[],n=e.network,s=i.has("network")?Zp(n?.hosts,"network").map(o=>typeof o=="string"&&wN.test(o)?o:Cn("Network hosts must be exact lowercase DNS names")):[],a=i.has("scheduler")?Zp(e.schedules,"schedules").map(o=>{let l=o;return!l||typeof l.id!="string"||!Qw.test(l.id)||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!Number.isSafeInteger(l.intervalSec)||l.intervalSec<vN||l.intervalSec>86400?Cn("Invalid schedule declaration"):{id:l.id,intervalSec:l.intervalSec,action:l.action}}):[];return new Set(a.map(o=>o.id)).size!==a.length&&Cn("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:a,sessions:i.has("sessions")}}import{lookup as SN}from"node:dns/promises";import{isIP as kN}from"node:net";var EN=new Set(["GET","POST","PATCH","PUT","DELETE"]),TN=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),IN=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ca=(t,e)=>{throw new y("network_denied",t,{status:403,reason:e})};function AN(t){let e=t.toLowerCase().replace(/^::ffff:/,"");if(kN(e)===4){let[i,r]=e.split(".").map(Number);return i===0||i===10||i===127||i===169&&r===254||i===172&&r>=16&&r<=31||i===192&&r===168||i===100&&r>=64&&r<=127||i>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Jw(t,e,i,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new y("invalid_input","Invalid network request");let a;try{a=new URL(s.url)}catch{throw new y("invalid_input","Invalid URL")}(a.protocol!=="https:"||a.username||a.password||a.port&&a.port!=="443")&&Ca("Only plain https on port 443 is allowed","scheme"),e.includes(a.hostname)||Ca("Host is not declared by the plugin","host");let o=(s.method??"GET").toUpperCase();if(!EN.has(o))throw new y("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new y("invalid_input","Invalid body");let l={};for(let[E,A]of Object.entries(s.headers??{})){if(typeof A!="string"||TN.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new y("invalid_input",`Header not allowed: ${E.slice(0,64)}`);l[E]=A}let c=null;if(s.secret!==void 0){if(i.includes(s.secret)||Ca("Secret is not declared by the plugin","secret"),c=await n.secrets.get(t,s.secret),!c)throw new y("secret_missing","Secret has not been configured",{status:412});l.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async E=>(await SN(E,{all:!0})).map(A=>A.address)))(a.hostname);(!p.length||p.some(AN))&&Ca("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,m=n.maxResponseBytes??2*1024*1024,g=await(n.fetch??fetch)(a,{method:o,headers:l,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),h=[],f=0;if(g.body)for await(let E of g.body){if(f+=E.byteLength,f>m)throw new y("response_too_large","Network response exceeds limit",{status:502});h.push(Buffer.from(E))}let b=Buffer.concat(h).toString("utf8"),S={};return g.headers.forEach((E,A)=>{IN.has(A.toLowerCase())&&(S[A.toLowerCase()]=E)}),c&&(b=b.split(c).join("[redacted]")),{status:g.status,headers:S,body:b}}var Da=(t,e,i)=>{if(typeof t!="string"||!t||t.length>e)throw new y("invalid_input",`Invalid ${i}`);return t};async function Xw(t,e,i,r,n,s){let a=n&&typeof n=="object"&&!Array.isArray(n)?n:{};if(r==="sessions.create"){if(a.mode!=="plan")throw new y("invalid_input","Plugin sessions must start in plan mode");if(t.activeCount(e)>=s)throw new y("quota_exceeded","Too many active plugin sessions",{status:429});return t.create({pluginId:e,cwd:i,title:Da(a.title,200,"title"),prompt:Da(a.prompt,64*1024,"prompt"),mode:"plan"})}let o=Da(a.sessionId,200,"sessionId");if(t.ownerOf(o)!==e)throw new y("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(a.mode!==void 0&&a.mode!=="execute")throw new y("invalid_input","Invalid mode");return await t.send(o,Da(a.message,64*1024,"message"),a.mode),{ok:!0};case"sessions.release":return await t.release(o),{ok:!0};case"sessions.abort":return await t.abort(o),{ok:!0};case"sessions.events":return t.events(o,Number.isSafeInteger(a.after)&&a.after>=0?a.after:0);default:throw new y("method_denied","Unknown sessions method")}}var xN=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),Ma=class{options;constructor(e){this.options=e}handles(e){return xN.has(e)}async call(e,i,r,n,s){let a=_r(i);if(n==="network.fetch"){if(!a.networkHosts.length)throw new y("capability_denied","Plugin did not declare network access",{status:403});return Jw(e,a.networkHosts,a.secrets,s,this.options)}if(!a.sessions||!this.options.sessions)throw new y("capability_denied","Sessions capability is unavailable",{status:403});return Xw(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var La=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,i){this.stop(e);let r=this.deps.setInterval??((n,s)=>{let a=setInterval(n,s);return a.unref(),a});this.timers.set(e,i.map(n=>r(()=>{this.tick(e,n)},n.intervalSec*1e3)))}stop(e){let i=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])i(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,i){let r=`${e}\0${i.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,i),!0}catch(n){return this.deps.onError?.(e,i,n),!1}finally{this.running.delete(r)}}};import{createHash as ud,timingSafeEqual as s1}from"node:crypto";import{lstat as h0,mkdtemp as dd,readdir as a1,readFile as o1,realpath as l1,rename as c1,rm as li,writeFile as p1}from"node:fs/promises";import{tmpdir as d1}from"node:os";import{join as ae}from"node:path";import{gunzipSync as MN}from"node:zlib";import{mkdir as LN,writeFile as UN}from"node:fs/promises";import{dirname as qN,join as jN}from"node:path";import{constants as ed}from"node:fs";import{lstat as t0,open as ON,readdir as Zw,realpath as i0}from"node:fs/promises";import{createHash as RN}from"node:crypto";import{join as r0,relative as NN,resolve as PN,sep as CN}from"node:path";var ge={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024},DN={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],cjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"],ttf:["font/ttf"],otf:["font/otf"],wasm:["application/wasm"]},ne=t=>RN("sha256").update(t).digest("hex");function re(t){throw new y("invalid_package",t)}async function Ui(t,e,i){let r=e.split("/");(!r.length||r.some(o=>!o||o==="."||o===".."||!/^[\w.-]+$/.test(o)))&&re("Invalid resource path");let n=t;for(let o=0;o<r.length;o++){n=r0(n,r[o]);let l=await t0(n);(l.isSymbolicLink()||(o<r.length-1?!l.isDirectory():!l.isFile()||l.nlink!==1))&&re("Links and non-regular package files are forbidden")}let s=await i0(n);(s!==PN(t,e)||NN(t,s).startsWith(`..${CN}`))&&re("Resource escapes package root");let a=await ON(n,ed.O_RDONLY|ed.O_NONBLOCK|(ed.O_NOFOLLOW??0));try{let o=await a.stat();(!o.isFile()||o.nlink!==1||o.size>i)&&re("Oversized or non-regular package file");let l=Buffer.alloc(Math.min(o.size+1,i+1)),c=0;for(;c<l.length;){let p=await a.read(l,c,l.length-c,c);if(!p.bytesRead)break;c+=p.bytesRead}return(c>i||c!==o.size)&&re("Package resource changed during read"),l.subarray(0,c)}finally{await a.close()}}function e0(t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return re("Invalid package JSON")}}async function qi(t,e){let i=await i0(t);(await t0(t)).isSymbolicLink()&&re("Package root cannot be a symlink");let r=e0(await Ui(i,"package.json",ge.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&re("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&re("Invalid package version"),ni(r.piWebapp)||re("Unsupported hosted manifest"),r.type!=="module"&&re("Hosted package must declare ESM module type");for(let d of await Zw(i,{withFileTypes:!0}))d.name==="dist"&&d.isDirectory()||(!d.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(d.name))&&re("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(d=>/^(?:preinstall|install|postinstall|prepare)$/.test(d))&&re("Hosted packages cannot run install lifecycle scripts");for(let d of["dependencies","optionalDependencies"]){let m=r[d];m&&(typeof m!="object"||Object.keys(m).length>0)&&re("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=e0(await Ui(i,n.resourcesManifest.slice(2),ge.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>ge.files)&&re("Invalid resource manifest");let a=new Map,o=0;for(let d of s.files){(!d||typeof d!="object")&&re("Invalid resource entry");let m=d,g={...m,path:typeof m.path=="string"&&m.path.startsWith("./")?m.path.slice(2):m.path};(!Ni(`./${g.path}`)||typeof g.sha256!="string"||!/^[a-f0-9]{64}$/.test(g.sha256)||!Number.isSafeInteger(g.bytes)||g.bytes<0||a.has(g.path))&&re("Invalid or duplicate resource");let h=g.path.split(".").at(-1);DN[h]?.includes(g.mime)||re("Unsupported resource MIME");let f=h==="js"||h==="mjs"||h==="cjs"?ge.js:h==="css"?ge.css:["woff","woff2","ttf","otf"].includes(h)?ge.font:h==="wasm"?ge.wasm:ge.other;(g.bytes>f||(o+=g.bytes)>ge.total)&&re("Resource budget exceeded");let b=await Ui(i,g.path,f);(b.length!==g.bytes||ne(b)!==g.sha256)&&re("Resource integrity mismatch"),a.set(g.path,Object.freeze({...g}))}for(let d of[n.backend.entry,n.frontend.document,n.frontend.controller])a.has(d.slice(2))||re("Entrypoint is absent from resource manifest");let l=0;async function c(d,m=0){m>16&&re("Package directory nesting limit exceeded");for(let g of await Zw(r0(i,d),{withFileTypes:!0})){++l>ge.files*2&&re("Too many package entries");let h=`${d}/${g.name}`;(g.isSymbolicLink()||!g.isDirectory()&&!g.isFile())&&re("Invalid archive member"),g.isDirectory()?await c(h,m+1):h!==n.resourcesManifest.slice(2)&&!a.has(h)&&re("Undeclared distribution asset")}}await c("dist");let p=ne(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...a.values()].sort((d,m)=>d.path.localeCompare(m.path))}));return{id:r.name,version:r.version,root:i,manifest:n,resources:a,digest:p}}async function n0(t,e,i){if(i!==t.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Ni(`./${r}`))return null;let n=t.resources.get(r);if(!n||r===t.manifest.backend.entry.slice(2))return null;let s=await Ui(t.root,r,n.bytes);if(s.length!==n.bytes||ne(s)!==n.sha256)throw new y("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var Ua=64*1024*1024,FN=ge.total+ge.files*2048,ie=t=>{throw new y("invalid_archive",t)};function vr(t){let e=t.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?t:t.subarray(0,e))}catch{return ie("Archive has invalid UTF-8 paths")}}function s0(t){let e=vr(t).trim();if(!/^[0-7]+$/.test(e))return ie("Unsupported archive number encoding");let i=parseInt(e,8);return Number.isSafeInteger(i)?i:ie("Archive number exceeds limits")}function BN(t){let e=t.endsWith("/")?t.slice(0,-1):t;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return ie("Archive must have one package root");let i=e.slice(8);return i.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?ie("Archive path is not a safe relative package path"):i}function HN(t){let e={},i=0;for(;i<t.length;){let r=t.indexOf(32,i);if(r<0)return ie("Invalid PAX header");let n=t.subarray(i,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return ie("Invalid PAX record length");let s=Number(n),a=i+s;if(a>t.length||a<=r+2||t[a-1]!==10)return ie("Truncated PAX record");let o=vr(t.subarray(r+1,a-1)),l=o.indexOf("=");if(l<1)return ie("Invalid PAX record");let c=o.slice(0,l),p=o.slice(l+1);if(Object.hasOwn(e,c)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(c))return ie("Unsupported PAX feature");e[c]=p,i=a}return e}function WN(t){if(!t.length||t.length>Ua)return ie("Compressed archive exceeds budget");let e;try{e=MN(t,{maxOutputLength:FN})}catch{return ie("Invalid or oversized gzip archive")}let i=[],r=new Set,n=0,s=0,a=0,o=0,l=null,c=!1;for(;n+512<=e.length;){let d=e.subarray(n,n+512);if(n+=512,d.every(C=>C===0)){if(l||e.subarray(n).some(C=>C!==0))return ie("Unexpected archive data after end marker");c=!0;break}if(++o>ge.files*2)return ie("Too many archive headers");let m=0;for(let C=0;C<512;C++)m+=C>=148&&C<156?32:d[C];if(s0(d.subarray(148,156))!==m)return ie("Invalid tar header checksum");let g=vr(d.subarray(257,263));if(g&&g!=="ustar"&&g!=="ustar ")return ie("Unsupported tar format");let h=d[156],f=vr(d.subarray(345,500)),b=(f?f+"/":"")+vr(d.subarray(0,100)),S=s0(d.subarray(124,136));if(l&&(l.path!==void 0&&(b=l.path),l.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(l.size))return ie("Invalid PAX size");S=Number(l.size)}if(!Number.isSafeInteger(S)||S<0||S>ge.total||n+S>e.length)return ie("Truncated or oversized tar member");let E=e.subarray(n,n+S);if(n+=Math.ceil(S/512)*512,h===120){if(l||S>8192)return ie("Oversized or chained PAX header");l=HN(E);continue}if(l=null,h!==0&&h!==48&&h!==53)return ie("Links and special archive members are forbidden");let A=h===53;if(A&&S!==0||vr(d.subarray(157,257)))return ie("Invalid archive link or directory");if(b=BN(b),!b&&!A)return ie("Invalid package root member");if(r.has(b))return ie("Duplicate archive member");if(r.add(b),++s>ge.files||(a+=S)>ge.total)return ie("Unpacked archive exceeds budget");i.push({path:b,data:E,directory:A})}if(!c||!r.has("package.json"))return ie("Archive is incomplete or has no package.json");let p=new Set(i.filter(d=>!d.directory).map(d=>d.path));for(let d of i){let m=d.path.split("/");for(let g=1;g<m.length;g++)if(p.has(m.slice(0,g).join("/")))return ie("Archive file/directory collision")}return i}async function td(t,e){let i=WN(t);for(let r of i){if(!r.path)continue;let n=jN(e,r.path);await LN(r.directory?n:qN(n),{recursive:!0,mode:448}),r.directory||await UN(n,r.data,{flag:"wx",mode:384})}}import{lstat as GN,mkdir as $N,readdir as VN,realpath as zN,writeFile as KN}from"node:fs/promises";import{dirname as YN,join as id}from"node:path";async function a0(t,e){let i=await zN(t),r=await Ui(i,"package.json",ge.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("invalid_package","package.json must be an object");let s=[],a=0,o=0;async function l(m,g){if(g>16)throw new y("invalid_package","Package directory nesting limit exceeded");for(let h of await VN(id(i,m),{withFileTypes:!0})){let f=`${m}/${h.name}`;if(++a>ge.files)throw new y("invalid_package","Too many package entries");if(h.isDirectory()){await l(f,g+1);continue}if(!h.isFile())throw new y("invalid_package",`Links and non-regular files are forbidden: ${f}`);let b=await Ui(i,f,ge.js);if((o+=b.length)>ge.total)throw new y("invalid_package","Resource budget exceeded");let S=id(e,f);await $N(YN(S),{recursive:!0,mode:448}),await KN(S,b,{flag:"wx",mode:384}),s.push([f,ne(b)])}}let c;try{c=await GN(id(i,"dist"))}catch(m){throw m.code==="ENOENT"?new y("dist_missing","dist/ does not exist yet; build the plugin first"):m}if(!c.isDirectory())throw new y("invalid_package","dist must be a real directory");await l("dist",0);let{version:p,...d}=n;return s.sort((m,g)=>m[0].localeCompare(g[0])),{contentHash:ne(JSON.stringify({package:d,files:s})),packageJson:n}}function Fe(t){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(t);return!e||e[0]!==t||e.slice(1).some(i=>!Number.isSafeInteger(Number(i)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Tt(t,e){let i=Fe(t),r=Fe(e);if(!i||!r)throw new y("invalid_version","Only exact stable semantic versions are supported");return i.major-r.major||i.minor-r.minor||i.patch-r.patch}function o0(t){let e=Fe(t);if(e)return e;if(!ca(t))return null;let[i,r]=t.split("-alpha."),n=Fe(i),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function rd(t){return!!o0(t)}function wr(t,e){if(!rd(t)||typeof e!="string"||e.length>256)return!1;let i=e.split("||");if(!i.length||i.some(n=>!n.trim()))return!1;let r=[];for(let n of i){let s=n.trim().split(/\s+/),a=!0;for(let o of s){let l=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(o),c=l&&o0(l[2]);if(!l||!c)return!1;let p=l[2],d=Ke(t,p);switch(l[1]??"="){case"=":a&&=d===0;break;case">=":a&&=d>=0;break;case"<=":a&&=d<=0;break;case">":a&&=d>0;break;case"<":a&&=d<0;break;case"~":a&&=d>=0&&Ke(t,`${c.major}.${c.minor+1}.0-0`)<0;break;case"^":{let m=c.major?`${c.major+1}.0.0`:c.minor?`0.${c.minor+1}.0`:`0.0.${c.patch+1}`;a&&=d>=0&&Ke(t,`${m}-0`)<0;break}}}r.push(a)}return r.some(Boolean)}function l0(t){return t==="workspace"||t==="design"}var nd=64*1024*1024,sd=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function ad(t,e){let i=t.get(e);if(!i)throw new y("unreviewed_plugin","No trusted tool policy for this package");return i}function c0(t,e){let i=t.get(e)?.workspace?.files??sd;for(let r of i)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>nd||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new y("invalid_policy","Invalid workspace file rule");return i}function p0(t,e){let i=t.get(e)?.runtime?.invokeTimeoutMs;return i===void 0?void 0:Math.min(Math.max(i,1e3),18e4)}var d0=["drawing","design"],QN=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,JN=/^[a-z][a-z0-9.-]{0,79}$/,od=/^[a-z][a-z0-9_]{0,63}$/,ji=/^[a-z][a-z0-9_-]{0,63}$/,XN=/^[a-z][a-z0-9-]{0,63}$/,Dn=class{where;constructor(e){this.where=e}fail(e,i){throw new y("invalid_catalog",`${this.where}: ${e} ${i}`)}object(e,i,r,n=r){(!e||typeof e!="object"||Array.isArray(e))&&this.fail(i,"must be an object");let s=e;for(let a of Object.keys(s))r.includes(a)||this.fail(`${i}.${a}`,"is not a known field");for(let a of n)s[a]===void 0&&this.fail(`${i}.${a}`,"is required");return s}string(e,i,r=200,n){return(typeof e!="string"||!e.trim()||e.length>r)&&this.fail(i,`must be a non-empty string of at most ${r} characters`),n&&!n.test(e)&&this.fail(i,`has an invalid format (${JSON.stringify(e)})`),e}strings(e,i,r,n=64){(!Array.isArray(e)||e.length>n)&&this.fail(i,`must be an array of at most ${n} strings`);let s=e.map((a,o)=>this.string(a,`${i}[${o}]`,80,r));return new Set(s).size!==s.length&&this.fail(i,"contains duplicates"),s}text(e,i,r=500){let n=this.object(e,i,["zh","en"]);return{zh:this.string(n.zh,`${i}.zh`,r),en:this.string(n.en,`${i}.en`,r)}}integer(e,i,r,n){return(!Number.isSafeInteger(e)||e<r||e>n)&&this.fail(i,`must be an integer from ${r} to ${n}`),e}https(e,i,r){let n=this.string(e,i,2048),s;try{s=new URL(n)}catch{this.fail(i,"must be an absolute URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash||r!==void 0&&s.hostname!==r)&&this.fail(i,`must be an https URL${r?` on ${r}`:""} without credentials or fragment`),n}subset(e,i,r,n){for(let s of e)i.includes(s)||this.fail(r,`lists "${s}", which is not one of its ${n}`)}};function ZN(t,e,i){let r=t.object(e,i,["entry","panels","artifactTools","toolViews","panelAlias"]),n=t.object(r.entry,`${i}.entry`,["label","description","kind","category"],["label","description","kind"]),s=n.category;s!==void 0&&!l0(s)&&t.fail(`${i}.entry.category`,'must be "workspace" or "design"');let a=t.object(r.panelAlias,`${i}.panelAlias`,["prefix","kind","title"]);return{entry:{label:t.string(n.label,`${i}.entry.label`,64),description:t.text(n.description,`${i}.entry.description`,120),kind:t.string(n.kind,`${i}.entry.kind`,32,ji),...s!==void 0?{category:s}:{}},panels:t.strings(r.panels,`${i}.panels`,ji,16),artifactTools:t.strings(r.artifactTools,`${i}.artifactTools`,od,128),toolViews:t.strings(r.toolViews,`${i}.toolViews`,od,128),panelAlias:{prefix:t.string(a.prefix,`${i}.panelAlias.prefix`,32,/^[a-z][a-z0-9-]{0,30}:$/),kind:t.string(a.kind,`${i}.panelAlias.kind`,32,ji),title:t.string(a.title,`${i}.panelAlias.title`,64)}}}function e1(t,e,i){return(!Array.isArray(e)||e.length<1||e.length>16)&&t.fail(i,"must be an array of 1 to 16 rules"),e.map((r,n)=>{let s=`${i}[${n}]`,a=t.object(r,s,["extension","binary","maxBytes","createDirectory"],["extension","binary","maxBytes"]);return typeof a.binary!="boolean"&&t.fail(`${s}.binary`,"must be a boolean"),{extension:t.string(a.extension,`${s}.extension`,17,/^\.[a-z0-9]{1,16}$/),binary:a.binary,maxBytes:t.integer(a.maxBytes,`${s}.maxBytes`,1,nd),...a.createDirectory!==void 0?{createDirectory:t.string(a.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function t1(t,e,i){let r=t.object(e,i,Object.keys(e&&typeof e=="object"?e:{}),[]);return Object.keys(r).length>16&&t.fail(i,"declares more than 16 secrets"),Object.fromEntries(Object.entries(r).map(([n,s])=>{let a=`${i}.${n}`;t.string(n,`${i} key`,64,XN);let o=t.object(s,a,["provider","scope","createUrl","clientId"],["provider","scope","createUrl"]);return o.provider!=="github"&&t.fail(`${a}.provider`,'must be "github" (the only sign-in the host implements)'),[n,{provider:"github",scope:t.string(o.scope,`${a}.scope`,200,/^[\w:. -]+$/),createUrl:t.https(o.createUrl,`${a}.createUrl`,"github.com"),...o.clientId!==void 0?{clientId:t.string(o.clientId,`${a}.clientId`,64,/^[A-Za-z0-9._-]+$/)}:{}}]}))}function i1(t,e,i="policy"){let r=new Dn(e),n=r.object(t,i,["tools","readonlyActions","actions","checkpointActions","contribution","browser","workspace","runtime","secrets"],["tools","readonlyActions","actions","checkpointActions","contribution"]),s=r.object(n.tools,`${i}.tools`,Object.keys(n.tools&&typeof n.tools=="object"?n.tools:{}),[]);Object.keys(s).length>128&&r.fail(`${i}.tools`,"declares more than 128 tools");for(let[g,h]of Object.entries(s))r.string(g,`${i}.tools key`,64,od),r.string(h,`${i}.tools.${g}`,64,ji);let a=Object.keys(s),o=Object.values(s),l=r.strings(n.readonlyActions,`${i}.readonlyActions`,ji),c=r.strings(n.actions,`${i}.actions`,ji),p=r.strings(n.checkpointActions,`${i}.checkpointActions`,ji);r.subset(l,o,`${i}.readonlyActions`,"tool actions"),r.subset(p,c,`${i}.checkpointActions`,"actions");let d=ZN(r,n.contribution,`${i}.contribution`);r.subset(d.artifactTools,a,`${i}.contribution.artifactTools`,"tools"),r.subset(d.toolViews,a,`${i}.contribution.toolViews`,"tools");let m={tools:s,readonlyActions:l,actions:c,checkpointActions:p,contribution:d};if(n.browser!==void 0){let g=r.object(n.browser,`${i}.browser`,["wasm"],[]);g.wasm!==void 0&&typeof g.wasm!="boolean"&&r.fail(`${i}.browser.wasm`,"must be a boolean"),m.browser=g.wasm===void 0?{}:{wasm:g.wasm}}if(n.workspace!==void 0&&(m.workspace={files:e1(r,r.object(n.workspace,`${i}.workspace`,["files"]).files,`${i}.workspace.files`)}),n.runtime!==void 0){let g=r.object(n.runtime,`${i}.runtime`,["invokeTimeoutMs"],[]);m.runtime=g.invokeTimeoutMs===void 0?{}:{invokeTimeoutMs:r.integer(g.invokeTimeoutMs,`${i}.runtime.invokeTimeoutMs`,1e3,18e4)}}return n.secrets!==void 0&&(m.secrets=t1(r,n.secrets,`${i}.secrets`)),m}var r1=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function ld(t,e,i="plugin"){let r=new Dn(e),n=r.object(t,i,r1,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${i}.id`,214,QN);n.icon!==void 0&&!d0.includes(n.icon)&&r.fail(`${i}.icon`,`must be one of ${d0.join(", ")}`);let a=r.https(n.registry,`${i}.registry`);new URL(a).origin!==a&&r.fail(`${i}.registry`,"must be a bare origin such as https://registry.npmjs.org");let o=r.string(n.recommendedVersion,`${i}.recommendedVersion`,64);return Fe(o)||r.fail(`${i}.recommendedVersion`,"must be a stable x.y.z version"),n.reviewed!==void 0&&r.string(n.reviewed,`${i}.reviewed`,1e3),{id:s,name:r.string(n.name,`${i}.name`,64),...n.icon!==void 0?{icon:n.icon}:{},description:r.text(n.description,`${i}.description`),registry:a,recommendedVersion:o,requiredCapabilities:r.strings(n.requiredCapabilities,`${i}.requiredCapabilities`,JN),policy:i1(n.policy,e,`${i}.policy`)}}function u0(t,e){let i=new Dn(e),r=i.object(t,"catalog",["schemaVersion","plugins"]);r.schemaVersion!==1&&i.fail("catalog.schemaVersion","must be 1"),(!Array.isArray(r.plugins)||r.plugins.length>64)&&i.fail("catalog.plugins","must be an array of at most 64 entries");let n=r.plugins.map((a,o)=>ld(a,e,`catalog.plugins[${o}]`)),s=n.map(a=>a.id);for(let[a,o]of s.entries())s.indexOf(o)!==a&&i.fail(`catalog.plugins[${a}].id`,`duplicates ${o}`);return n}function cd(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))cd(e)}return t}var m0={schemaVersion:1,plugins:[{id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"],reviewed:"Policy reviewed against package 6328c63.",policy:{tools:{excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"},readonlyActions:["read","reference"],actions:["list","new","open","import","get","focus","sync","initialize","accept","reject","save"],checkpointActions:["sync","get","list"],contribution:{entry:{label:"Excalidraw",description:{zh:"\u7ED8\u5236\u6D41\u7A0B\u56FE\u548C\u624B\u7ED8\u8349\u56FE",en:"Draw diagrams and freehand sketches"},kind:"workspace",category:"design"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}}}},{id:"@chengzhiyi/pi-pencil",name:"OpenPencil",icon:"design",description:{zh:"\u57FA\u4E8E OpenPencil \u7684 UI \u8BBE\u8BA1\uFF1A\u7F16\u8F91\u5DE5\u4F5C\u533A\u91CC\u7684 .fig \u8BBE\u8BA1\u7A3F\uFF0Cagent \u7684\u4FEE\u6539\u76F4\u63A5\u51FA\u73B0\u5728\u753B\u5E03\u4E0A\uFF0C\u53EF\u968F\u65F6\u64A4\u9500\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"UI design on OpenPencil: edit .fig designs in your workspace; the agent's changes appear on the canvas directly and you can undo them. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.0.2",requiredCapabilities:["state","workspace","panels","browser.wasm"],reviewed:"The tool set is deliberately small. Agent changes apply directly as new revisions; undoing one (revert), saving, syncing and locking stay human-only. accept/reject remain for proposals stored by older builds. import turns a file the person picked (.fig/.jam/.pen/.drawio) into a new design; upload carries an action input over the 2 MB request limit in chunks (bounded and owned by the uploading session in the plugin). A checkpoint freeze may flush a person's first edits in an empty workspace, which creates their design.",policy:{tools:{pencil_read_me:"reference",pencil_status:"status",pencil_inspect:"inspect",pencil_render:"render",pencil_apply_changes:"apply"},readonlyActions:["reference","status","inspect","render"],actions:["list","get","accept","reject","revert","save","open","import","upload","create","rename","selection","sync","lock"],checkpointActions:["get","list","sync","create"],contribution:{entry:{label:"OpenPencil",description:{zh:"\u8BBE\u8BA1\u754C\u9762\u4E0E\u7EC4\u4EF6",en:"Design interfaces and components"},kind:"workspace",category:"design"},panels:["workspace","editor"],artifactTools:["pencil_apply_changes"],toolViews:[],panelAlias:{prefix:"pencil:",kind:"editor",title:"OpenPencil"}},browser:{wasm:!0},workspace:{files:[{extension:".fig",binary:!0,maxBytes:67108864,createDirectory:"designs"}]},runtime:{invokeTimeoutMs:12e4}}}]};var g0=cd(u0(m0,"official-plugins.json")),et=Object.freeze(g0.map(({policy:t,...e})=>Object.freeze(e))),qa=new Map(g0.map(t=>[t.id,t.policy]));function Qe(t,e=et){let i=e.find(r=>r.id===t);if(!i)throw new y("unknown_plugin","Plugin is not in the trusted official catalog");return i}function pd(t,e,i){let r=t.piWebapp;return t.name===e.id&&!!Fe(t.version)&&!t.deprecated&&ni(r)&&wr(i,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function f0(t,e,i,r,n){if(!t||typeof t!="object"||!("versions"in t)||!t.versions||typeof t.versions!="object"||Array.isArray(t.versions))throw new y("registry_invalid","Invalid registry version catalog");let s=Object.entries(t.versions);if(s.length>1e4)throw new y("registry_invalid","Registry version catalog exceeds budget");let o=s.flatMap(([l,c])=>{if(!c||typeof c!="object")return[];let p=c;return p.version===l&&pd(p,e,i)&&(!n||l===n)&&(!r||Tt(l,r)>=0)?[p]:[]}).sort((l,c)=>Tt(c.version,l.version))[0];if(!o)throw new y("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!o.dist||typeof o.dist.tarball!="string"||typeof o.dist.integrity!="string")throw new y("registry_invalid","Release is missing its immutable tarball integrity");return o}function u1(t,e){let i=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!i)throw new y("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(i[1],"base64"),n=ud("sha512").update(t).digest();if(r.length!==n.length||!s1(r,n))throw new y("integrity_mismatch","Downloaded package failed integrity verification")}var Sr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!rd(e.hostVersion))throw new y("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??et,this.fetcher=e.fetch??aw}async index(){let e=await ke(ae(this.root,"installed.json"));if(!e){if(await ye(ae(this.root,"installed.json"),2*1024*1024))throw new y("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new y("invalid_storage","Invalid plugin installation index");for(let[i,r]of Object.entries(e.versions))if(this.catalog.some(n=>n.id===i)){if(!Array.isArray(r)||r.length>16||new Set(r.map(n=>n.version)).size!==r.length)throw new y("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(i,n)}return e}validateRecord(e,i){if(!i||!Fe(i.version)||!/^[a-f0-9]{64}$/.test(i.digest)||i.directory!==`${ne(e)}/${i.version}-${i.digest}`||typeof i.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(i.integrity)||typeof i.installedAt!="string")throw new y("invalid_storage","Invalid installed plugin record")}path(e){return ae(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),i=await Ye(ae(this.root,"install-journal.json"));if(i){if(i.schema!==1||Object.keys(i).some(s=>!["schema","pluginId","next"].includes(s)))throw new y("invalid_storage","Invalid install journal");Qe(i.pluginId,this.catalog),this.validateRecord(i.pluginId,i.next);let n=e.versions[i.pluginId]?.find(s=>s.version===i.next.version);if(n&&n.digest!==i.next.digest)throw new y("invalid_storage","Conflicting installation journal");await li(ae(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=ae(this.root,"staging");await Se(r);for(let n of await a1(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await h0(ae(r,n))).isSymbolicLink())throw new y("invalid_storage","Invalid abandoned staging directory");await li(ae(r,n),{recursive:!0})}return e}async recoverCollection(e){let i=ae(this.root,"gc-journal.json"),r=await Ye(i);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new y("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");Qe(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let n=r.records.filter(s=>e.versions[r.pluginId]?.some(a=>a.directory===s.directory));if(n.length&&n.length!==r.records.length)throw new y("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!n.length){await Se(ae(this.root,"versions")),await Se(ae(this.root,"versions",ne(r.pluginId)));for(let s of r.records)await li(this.path(s),{recursive:!0,force:!0})}await li(i)}async collect(e,i){return Qe(e,this.catalog),Ee(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]??[],s=new Set(await i()),a=n.at(-1);a&&s.add(a.version);let o=n.filter(l=>!s.has(l.version));return await this.removeLocked(e,r,o),o.map(l=>l.version)})}async removeLocked(e,i,r){r.length&&(await Se(ae(this.root,"versions")),await Se(ae(this.root,"versions",ne(e))),await te(ae(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),i.versions[e]=(i.versions[e]??[]).filter(n=>!r.some(s=>s.directory===n.directory)),i.revision++,await te(ae(this.root,"installed.json"),i),await this.recoverCollection(i))}async inventory(){return Ee(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,i){let r;try{r=new URL(e)}catch{throw new y("registry_denied","Invalid registry URL")}let n=new URL(i.registry);if(r.protocol!=="https:"||r.origin!==n.origin||r.username||r.password||r.hash||r.search)throw new y("registry_denied","Only the official registry origin is permitted");return r}async download(e,i,r,n="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),a;try{a=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(d){throw r?.aborted?r.reason:new y("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!a.ok||!a.body)throw await a.body?.cancel().catch(()=>{}),new y(a.status===404?`${n}_not_found`:"download_failed",`Registry ${n} request failed (${a.status})`);if(a.url&&new URL(a.url).origin!==e.origin)throw new y("registry_denied","Registry redirect is forbidden");let o=a.body.getReader(),l=[],c=0,p=()=>{o.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(a.headers.get("content-length"))>i)throw new y("download_too_large","Registry response exceeds budget");for(;;){let d=await o.read();if(d.done)break;if(c+=d.value.length,c>i)throw new y("download_too_large","Registry response exceeds budget");l.push(Buffer.from(d.value))}return s.throwIfAborted(),Buffer.concat(l)}catch(d){throw r?.aborted?r.reason:d instanceof y?d:new y("registry_unreachable",d instanceof Error?d.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await o.cancel().catch(()=>{}),o.releaseLock()}}async check(e,i,r,n){let s=Qe(e,this.catalog);if(r&&!Fe(r))throw new y("invalid_version","Choose an exact stable version");let a=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),o,l=await this.download(a,8*1024*1024,n,"metadata");try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l))}catch{throw new y("registry_invalid","Invalid registry metadata JSON")}return f0(o,s,this.hostVersion,i,r)}async install(e,i,r){let n=Qe(e,this.catalog);if(!pd(i,n,this.hostVersion))throw new y("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(i.dist.tarball,n),Ua,r);return this.installArchive(e,s,i.dist.integrity,i.version,r)}async installArchive(e,i,r,n,s){let a=Qe(e,this.catalog);if(!Fe(n))throw new y("invalid_version","Choose an exact stable version");if(i.length>Ua)throw new y("download_too_large","Package archive exceeds budget");return u1(i,r),Ee(this.root,async()=>{let o=await this.recoverLocked();s?.throwIfAborted();let l=await dd(ae(this.root,"staging","stage-"));try{await td(i,l),s?.throwIfAborted();let c=await qi(l,e);if(c.version!==n||!ni(c.manifest)||!wr(this.hostVersion,c.manifest.hostRange)||!a.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new y("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,o,l,c,r,s)}finally{await li(l,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,i,r,n,s,a){let o=i.versions[e]?.find(d=>d.version===n.version);if(o&&o.digest!==n.digest)throw new y("version_replaced","An installed immutable version cannot be replaced with different content");let l={version:n.version,digest:n.digest,integrity:s,directory:`${ne(e)}/${n.version}-${n.digest}`,installedAt:new Date().toISOString()};if(await Se(ae(this.root,"versions",ne(e))),!o&&(i.versions[e]?.length??0)>=16)throw new y("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await te(ae(this.root,"install-journal.json"),{schema:1,pluginId:e,next:l});let c=this.path(l),p=!1;try{await h0(c),p=!0}catch(d){if(!ii(d))throw d}if(p){if((await qi(c,e)).digest!==n.digest)throw new y("resource_changed","Installed package content was modified")}else await c1(r,c);return a?.throwIfAborted(),o||(i.versions[e]=[...i.versions[e]??[],l],i.revision++,await te(ae(this.root,"installed.json"),i)),await li(ae(this.root,"install-journal.json")),{...n,root:await l1(c)}}async installDevArchive(e,i,r){Qe(e,this.catalog);let n=await o1(i),s="sha512-"+ud("sha512").update(n).digest("base64"),a=await dd(ae(d1(),"pi-dev-archive-"));try{await td(n,a);let o=(await qi(a,e)).version;return await this.installArchive(e,n,s,o,r)}finally{await li(a,{recursive:!0,force:!0})}}async installDevDirectory(e,i,r){let n=Qe(e,this.catalog);return Ee(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let a=await dd(ae(this.root,"staging","stage-"));try{let{contentHash:o,packageJson:l}=await a0(i,a);r?.throwIfAborted();let c=ae(this.root,"dev-sources.json"),p=await ke(c)??{},d=p[e],m=s.versions[e]??[],g=d?.contentHash===o?m.find(R=>R.version===d.version):void 0;if(g){let R=await qi(this.path(g),e);if(R.digest!==g.digest)throw new y("resource_changed","Installed package integrity changed");return R}let h=typeof l.version=="string"?Fe(l.version):null;if(!h)throw new y("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let f=Math.max(-1,...m.map(R=>Fe(R.version)).filter(R=>R&&R.major===h.major&&R.minor===h.minor).map(R=>R.patch)),b=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),f+1),S=`${h.major}.${h.minor}.${b}`;await p1(ae(a,"package.json"),JSON.stringify({...l,version:S},null,2),{flag:"wx",mode:384});let E=await qi(a,e);if(!wr(this.hostVersion,E.manifest.hostRange))throw new y("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let A=n.requiredCapabilities.filter(R=>!E.manifest.capabilities.includes(R));if(A.length)throw new y("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let C="sha512-"+ud("sha512").update(o).digest("base64"),N=await this.commitStaged(e,s,a,E,C,r);return p[e]={contentHash:o,version:S},await te(c,p),N}finally{await li(a,{recursive:!0,force:!0})}},1e4)}async load(e,i){let r=Qe(e,this.catalog);return Ee(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(o=>o.version===i);if(!s)throw new y("not_installed","Plugin version is not installed");let a=await qi(this.path(s),e);if(a.digest!==s.digest)throw new y("resource_changed","Installed package integrity changed");if(!wr(this.hostVersion,a.manifest.hostRange)||!r.requiredCapabilities.every(o=>a.manifest.capabilities.includes(o)))throw new y("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return a})}async removeVersions(e,i){Qe(e,this.catalog),await Ee(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(a=>i.includes(a.version));await this.removeLocked(e,r,s)})}};import{lstat as ja,mkdir as m1,open as y0,realpath as b0,readdir as md,link as g1,rename as f1,unlink as Fi,copyFile as h1,rm as y1}from"node:fs/promises";import{dirname as b1,isAbsolute as _0,join as Q,relative as v0,resolve as _1,sep as gd,win32 as v1}from"node:path";import{randomUUID as fd}from"node:crypto";var Mn=192*1024*1024,I9=512*1024,S0=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function w1(t){if(!t||typeof t!="object"||Array.isArray(t))throw new y("invalid_input","Expected object input");return t}function w0(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new y("invalid_input","Invalid state key");return t}function Ln(t){if(t&&(!S0(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new y("invalid_storage","Invalid active plugin record");return t}var Bi=class{root;pluginId;legacy;checkpoint;files;constructor(e,i,r,n,s=sd){this.root=Q(e,ne(i)),this.pluginId=i,this.legacy=r,this.checkpoint=n,this.files=s}rule(e){let i=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!i)throw new y("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return i}active(){return ke(Q(this.root,"active.json")).then(Ln)}async recover(){return Ee(this.root,async()=>{let e=await this.active(),i=await Ye(Q(this.root,"transition.json"));if(!i)return{active:e,recovered:"none"};if(!i.next||!Object.hasOwn(i,"before")||Object.keys(i).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(i,"version")&&i.version!==1)throw new y("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ln(i.next),Ln(i.before);let r=e?.operationId===i.next.operationId?"committed":"not_committed";if(!((a,o)=>a===null||o===null?a===o:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===o[l]))(e,r==="committed"?i.next:i.before))throw new y("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=i.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await te(Q(this.root,"previous.json"),s),r==="committed"){let a=await Ye(Q(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(o=>["version","stateRef"].includes(o))&&await Fi(Q(this.root,"fork.json"))}return await Fi(Q(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,i){return Ee(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new y("stale_generation","Plugin activation changed concurrently");let n=await Ye(Q(this.root,"fork.json"));if(n&&(n.version!==1||n.stateRef!==i.stateRef||Object.keys(n).some(a=>!["version","stateRef"].includes(a))))throw new y("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Ln({...i,generation:e+1,operationId:fd()});await Se(Q(this.root,"states")),await Se(Q(this.root,"states",s.stateRef)),await te(Q(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await te(Q(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await te(Q(this.root,"previous.json"),r),await Fi(Q(this.root,"transition.json")),await Fi(Q(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return Ee(this.root,async()=>{let i=await this.assertGeneration(e,!1),r=fd(),n=Q(this.root,"states",r);if(await Ye(Q(this.root,"fork.json")))throw new y("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await te(Q(this.root,"fork.json"),{version:1,stateRef:r}),await Se(n);let s=Q(this.root,"states",i.stateRef);for(let a of await md(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new y("invalid_storage","Unexpected state file");if(!await ye(Q(s,a),Mn))throw new y("invalid_storage","Missing state file");await h1(Q(s,a),Q(n,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return Ee(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await ye(Q(this.root,c),2*1024*1024))throw new y("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let i=await this.active(),r=Ln(await Ye(Q(this.root,"previous.json")));if(!i&&await ye(Q(this.root,"active.json"),2*1024*1024))throw new y("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let n=[i,r].filter(c=>!!c),s=Q(this.root,"states");await Se(s);let a=await md(s),o=new Set(n.map(c=>c.stateRef));for(let c of a){if(!S0(c))throw new y("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=Q(s,c),d=await ja(p);if(!d.isDirectory()||d.isSymbolicLink())throw new y("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await md(p)){let g=await ja(Q(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new y("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!o.has(c)){let h=await ke(Q(p,m),Mn);if(!h)throw new y("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let f=h;if(Object.keys(f).some(b=>!["requestId","inputHash","nextHash","committed"].includes(b))||f.committed!==!0||!/^[a-f0-9]{64}$/.test(f.inputHash)||!/^[a-f0-9]{64}$/.test(f.nextHash)||typeof f.requestId!="string")throw new y("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(f=>!["revision","schema","value","requestId","inputHash"].includes(f)))throw new y("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let c of o)if(!a.includes(c))throw new y("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(n);for(let c of a)o.has(c)||await y1(Q(s,c),{recursive:!0,force:!0});return l})}async assertGeneration(e,i=!0){let r=await this.active();if(!r||r.generation!==e||i&&!r.enabled)throw new y("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new y("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,i,r,n="session"){if(n!=="session"&&n!=="workspace")throw new y("invalid_input","Invalid state scope");let s=n==="workspace"?(this.scopeKey(i),JSON.stringify([i.scope.workspaceId,i.scope.cwd])):this.scopeKey(i);return Q(this.root,"states",e.stateRef,`${ne(s+":state:"+r)}.json`)}async call(e,i,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new y("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=w1(r);return Ee(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(i){case"state.read":{let a=await ke(this.statePath(s,e,w0(n.key),n.scope),Mn);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,w0(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new y("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new y("invalid_input","State value must be JSON serializable");let o=JSON.stringify(n);if(Buffer.byteLength(o)>Mn)throw new y("state_too_large","Plugin state exceeds limit");let l=await ke(a,Mn);l&&this.validateState(l);let c=ne(o);if(l?.requestId===e.requestId&&l.inputHash===c)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==n.expectedRevision)throw new y("revision_conflict","Plugin state changed concurrently");let p={revision:n.expectedRevision+1,schema:s.schema,value:n.value,requestId:e.requestId,inputHash:c};return await te(a,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let a=this.rule(n.path),{target:o}=await this.fileTarget(e.scope.cwd,n.path),l=n.maxBytes===void 0?a.maxBytes:n.maxBytes;if(!Number.isSafeInteger(l)||l<=0||l>a.maxBytes)throw new y("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(a.binary?"base64":"utf-8"))throw new y("invalid_input","Encoding does not match the reviewed file rule");let c=await ye(o,l);return c?a.binary?{base64:c.toString("base64"),bytes:c.length,hash:ne(c)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:ne(c)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new y("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new y("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,i,r=!1){let n=this.rule(i);if(typeof i!="string"||i.length>4096||i.includes("\\")||i.includes("\0")||_0(i)||v1.isAbsolute(i))throw new y("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await b0(e),a=_1(s,i),o=v0(s,a);if(!o||o===".."||o.startsWith(`..${gd}`)||_0(o))throw new y("invalid_path","Workspace path escapes root");let l=s,c=o.split(gd);for(let d=0;d<c.length;d++){l=Q(l,c[d]);let m;try{m=await ja(l)}catch(g){if(!ii(g))throw g;if(d<c.length-1){if(!r||!n.createDirectory||v0(s,l)!==n.createDirectory)throw new y("invalid_path","Workspace directory does not exist");try{await m1(l,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}m=await ja(l)}}if(m&&(m.isSymbolicLink()||(d<c.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new y("invalid_path","Workspace path contains a link or non-regular file")}let p=await b0(b1(a));if(p!==s&&!p.startsWith(s+gd))throw new y("invalid_path","Workspace directory changed");return{target:a,parent:p}}async commitFile(e,i,r){let n=this.rule(r.path),s=n.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!s||s.length>n.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new y("invalid_input","Invalid file content or expected hash");let{target:a,parent:o}=await this.fileTarget(i.scope.cwd,r.path,!0),l=Q(this.root,"states",e.stateRef,`${ne(this.scopeKey(i)+":file:"+i.requestId+":"+String(r.path))}.json`),c=ne(JSON.stringify(r)),p=ne(s),d=await ke(l);if(d&&(d.requestId!==i.requestId||d.inputHash!==c||d.nextHash!==p))throw new y("duplicate_request","Request ID was reused with different content");let m;try{m=await y0(`${a}.lock`,"wx",384)}catch(h){throw h.code==="EEXIST"?new y("file_busy","Workspace file is locked; original file preserved"):h}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:i.requestId}));let h=await ye(a,n.maxBytes),f=h?ne(h):null;if(d&&f===p)return{hash:p};if(d?.committed||f!==r.expectedHash)throw new y("file_conflict","Workspace file already exists or changed externally");await te(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!1}),g=Q(o,`.plugin-${fd()}.tmp`);let b=await y0(g,"wx",384);try{await b.writeFile(s),await b.sync()}finally{await b.close()}if((await this.fileTarget(i.scope.cwd,r.path)).parent!==o)throw new y("file_conflict","Workspace directory changed during save");let E=await ye(a,n.maxBytes);if((E?ne(E):null)!==r.expectedHash)throw new y("file_conflict","Workspace file changed during save");if(await this.assertGeneration(i.generation),r.expectedHash===null){try{await g1(g,a)}catch(A){throw A.code==="EEXIST"?new y("file_conflict","Workspace file was created concurrently"):A}await Fi(g),g=void 0}else await f1(g,a),g=void 0;return await te(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{g&&await Fi(g).catch(()=>{}),await m.close(),await Fi(`${a}.lock`)}}};import{randomUUID as I1}from"node:crypto";import{fork as S1}from"node:child_process";import{randomUUID as k1}from"node:crypto";import{join as E1}from"node:path";import{EventEmitter as T1}from"node:events";var k0=192*1024*1024,Un=class t{child;pending=new Map;events=new T1;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,i,r,n){this.package=e,this.generation=i,this.broker=n;let s={};for(let a of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[a]&&(s[a]=process.env[a]);this.child=S1(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",a=>{this.receive(a)}),this.child.once("error",a=>this.fail(a)),this.child.once("exit",()=>this.fail(new y("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,i,r,n,s=1e4){let a=new t(e,i,r,n);try{await a.request("initialize",{entry:E1(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:i},s);let o=await a.request("describe",void 0,s);if(!o||!Array.isArray(o.tools)||o.tools.length>128)throw new y("invalid_tools","Invalid hosted tool catalog");let l=new Set;for(let c of o.tools){if(!c||typeof c.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(c.name)||l.has(c.name)||typeof c.label!="string"||typeof c.description!="string"||typeof c.action!="string"||!/^[\w.-]{1,80}$/.test(c.action)||!c.parameters||typeof c.parameters!="object"||Array.isArray(c.parameters)||c.parameters.type!=="object")throw new y("invalid_tools","Invalid or duplicate tool descriptor");l.add(c.name)}return a.tools=structuredClone(o.tools),await a.request("health",void 0,s),a}catch(o){throw await a.dispose(),o}}fail(e){this.stopped=!0;for(let i of this.pending.values())clearTimeout(i.timer),i.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let i;try{i=Buffer.byteLength(JSON.stringify(e))}catch{return}if(i>k0){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let n=this.pending.get(r.id);if(!n)return;if(clearTimeout(n.timer),this.pending.delete(r.id),!n.expired){let s=r.error;r.ok===!0?n.resolve(r.value):n.reject(new y(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let n=this.pending.get(r.invocationId);try{if(!n?.invocation||n.expired)throw new y("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(n.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:ce(s)})}}}request(e,i,r=3e4,n){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new y("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new y("worker_busy","Too many plugin requests"));let s=n?.requestId??k1();if(this.pending.has(s))return Promise.reject(new y("duplicate_request","An identical request is still running"));let a={type:"request",id:s,method:e,input:i};return Buffer.byteLength(JSON.stringify(a))>k0?Promise.reject(new y("message_too_large","Plugin request exceeds limit")):new Promise((o,l)=>{let c=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),l(new y("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:o,reject:l,timer:c,invocation:n,expired:!1}),this.child.send(a,p=>{p&&(clearTimeout(c),this.pending.delete(s),l(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,i=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,i,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(i=>{let r=()=>{clearTimeout(n),this.events.off("idle",r),i(!0)},n=setTimeout(()=>{this.events.off("idle",r),i(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new y("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let i=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",i),this.child.kill("SIGTERM")})}}}};var A1={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Fa=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,i,r=A1,n){this.broker=e,this.workerEntry=i,this.hooks=r,this.capabilities=n}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let i=this.operations.then(e,e);return this.operations=i.catch(()=>{}),i}async ownRuntime(){if(this.releaseOwnership)return;let e=await Lp(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,i,r)=>this.capabilities?.handles(i)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,i,r):this.broker.call(e,i,r);invoke(e,i){return this.phaseValue!=="active"||!this.worker?Promise.reject(new y("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},i)}flushAction(e,i){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new y("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},i)}replace(e,i=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new y("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new y("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(c){throw this.worker||await this.releaseOwnership?.(),c}let n=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let a=null,o=!1,l=!1;try{if(a=await Un.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(i))throw new y("drain_pending","Plugin calls are still running; switch deferred without killing them");if(l=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(i))throw new y("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new y("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(a.tools)),this.phaseValue="switching";let c=r?await this.broker.forkState(n):I1(),p=await this.broker.activate(n,{version:e.version,stateRef:c,schema:e.manifest.dataSchemaVersion,enabled:!0});o=!0,this.worker=a,a=null,this.phaseValue="active",this.pendingPackage=null;let d=!1;try{await this.hooks.committed(p)}catch{d=!0}return await s?.dispose(),{pending:!1,active:p,...d?{reconnectRequired:!0}:{}}}catch(c){throw o||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",l&&await this.hooks.resume().catch(()=>{})),c}finally{await a?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,i=!1){return this.serialize(async()=>{let r=this.worker,n=this.phaseValue,s=await this.broker.active(),a=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new y("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Un.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(l){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),l}}};this.phaseValue="draining";try{let l=async c=>{try{await c()}catch(p){if(!i)throw p}};await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Plugin work is still draining; current host retained")}),await l(()=>this.hooks.freeze()),await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(l){try{await a(),this.phaseValue=n,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw l}let o=!1;return()=>this.serialize(async()=>{o||(await a(),this.phaseValue=n,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let i=this.worker,r;try{r=(await this.broker.recover()).active}catch(a){throw i||await this.releaseOwnership?.(),a}if(!r){if(i)throw this.phaseValue="failed",new y("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!i&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let n=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Checkpoint synchronization is still running");let a=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await i?.dispose(),await this.hooks.committed(a)}catch(a){throw this.worker===i&&(this.phaseValue=n,s&&await this.hooks.resume().catch(()=>{})),a}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let i=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Host checkpoint synchronization is still running");await i?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(n){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),n}})}};import{readFile as E0}from"node:fs/promises";var Ba=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new Sr({root:tt(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let i=e.capabilities?new Ma(e.capabilities):void 0;this.scheduler=new La({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:O1(),scope:s,kind:"action",action:n.action,input:{schedule:n.id}})},onError:(r,n,s)=>e.onScheduleError?.(r,n.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let n=new Bi(tt(e.root,"data"),r.id,e.legacy?.(r.id),void 0,e.workspaceRules?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new Fa(n,e.workerEntry,{validateCandidate:a=>s.validateCandidate?.(a),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async a=>{if(a.enabled){let o=await this.installer.load(r.id,a.version);this.packages.set(r.id,o),this.assetTokens.set(r.id,x1(24).toString("base64url"));try{this.scheduler.start(r.id,_r(o.manifest).schedules)}catch(l){this.scheduler.stop(r.id),this.errors.set(r.id,ce(l))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(a)}},i))}}devSource(e){let i=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return!i&&!r?null:async n=>(await this.collectSettled(e).catch(()=>{}),i?this.installer.installDevDirectory(e,i,n):this.installer.installDevArchive(e,r,n))}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){Qe(e,this.installer.catalog);let i=this.supervisors.get(e);if(!i)throw new y("unknown_plugin","Plugin runtime is not registered");return i}serialize(e,i){if(this.supervisor(e),this.closing)return Promise.reject(new y("manager_closed","Plugin manager is shutting down"));let r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,ce(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,i,r=!1){return this.options.lifecycle?this.options.lifecycle(e,i,r):i()}async policies(){let e=await ke(tt(this.options.root,"policies","policies.json"));if(!e){if(await ye(tt(this.options.root,"policies","policies.json"),2*1024*1024))throw new y("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[i,r]of Object.entries(e))if(this.installer.catalog.some(n=>n.id===i)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new y("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(i=>[i,{updatePolicy:"notify"}]))}async diagnostics(){return await ke(tt(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,i){await Ee(tt(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...i,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await te(tt(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,i){return this.recordCheck(e,{status:"up-to-date",version:i,message:"Developer source installed"})}async check(e,i,r,n){try{let s=await this.installer.check(e,i,r,n),a=!i||Tt(s.version,i)>0;return a?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:a?"available":"up-to-date",version:s.version,message:a?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:ce(s).code,message:ce(s).message}),s}}async setPolicy(e,i){if(this.supervisor(e),!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion))throw new y("invalid_input","Invalid plugin update policy");await Ee(tt(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await te(tt(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return Ee(Ta(this.options.root),async()=>{let e=await jp(this.options.root);if(!e)return{intent:e,admitted:!1};if(!Fp(e))return e.phase==="required-action"&&await Aa(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await qp(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await qp(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await E0(this.options.workerEntry)).equals(await E0(tt(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){return await Aa(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${ce(i).message}; data retained`}),{intent:e,admitted:!1}}return await Aa(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await Ee(tt(this.options.root,"policies"),async()=>{let r=await this.policies();await te(tt(this.options.root,"policies","policies.json"),r)});let{admitted:e}=await this.settleHostPair(),{versions:i}=await this.installer.inventory();for(let r of this.installer.catalog){let n=this.supervisor(r.id);try{let s=await n.broker.active();if(!s?.enabled)continue;let a=await this.localCandidate(this.installer,r.id,i[r.id]??[],s.version);await this.lifecycle(r.id,()=>n.replace(a)),this.packages.set(r.id,a),e||await this.collectSettled(r.id)}catch(s){let a=ce(s),o=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(r.id,{...a,message:`Plugin unavailable: startup failed (${a.code}): ${a.message}; data retained. ${o}`})}}}async localCandidate(e,i,r,n){let s;if(n!==void 0)try{return await e.load(i,n)}catch(o){if(ce(o).code!=="incompatible_plugin")throw o;s=o}let a=r.map(o=>o.version).filter(o=>o!==n).sort((o,l)=>Tt(l,o));for(let o of a)try{return await e.load(i,o)}catch{}throw s??new y("incompatible_plugin","No usable installed release for the target host")}async inventory(){let e=await this.installer.inventory(),i=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let a=this.supervisor(s.id),o=await a.broker.active(),l=this.packages.get(s.id),c=(e.versions[s.id]??[]).map(p=>p.version).sort((p,d)=>Tt(d,p));return{id:s.id,name:s.name,description:s.description,official:s.official!==!1,installed:!!c.length,installedVersions:c,version:c[0]??null,activeVersion:o?.version??null,enabled:o?.enabled??!1,phase:a.phase,generation:a.generation,pendingVersion:a.pendingVersion,updatePolicy:i[s.id]?.updatePolicy??"notify",pinnedVersion:i[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...l&&a.phase==="active"?{digest:l.digest,document:l.manifest.frontend.document.slice(2),controller:l.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${l.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,i])=>i.phase==="active"&&i.generation!==null?[{pluginId:e,generation:i.generation,descriptors:i.tools}]:[])}async manage(e,i,r,n){return this.serialize(e,async()=>{let s=this.supervisor(e),a=(await this.installer.inventory()).versions[e]??[],o=a.map(c=>c.version).sort((c,p)=>Tt(p,c))[0],l=await(async()=>{switch(i){case"check":return this.isDevPlugin(e)?{version:o??null,dev:!0}:{version:(await this.check(e,o,void 0,n)).version};case"install":{let c=this.devSource(e);if(c){let m=await c(n);return await this.recordDevSync(e,m.version),{installed:!0,version:m.version}}let p=await this.check(e,o,r,n),d=await this.installer.install(e,p,n);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:d.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:d.version}}case"enable":{let c=r??o;if(!c)throw new y("not_installed","Install the plugin first");let p=await this.installer.load(e,c),d=await this.lifecycle(e,()=>s.replace(p));return d.pending||this.packages.set(e,p),d}case"retry":{let c=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return c&&!p.pending&&this.packages.set(e,await this.installer.load(e,c)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!o)throw new y("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let h=await c(n),f=await s.broker.active();if(await this.recordDevSync(e,h.version),!f?.enabled)return{installed:!0,enabled:!1,version:h.version};if(f.version===h.version&&!s.pendingVersion)return{unchanged:!0,version:h.version};let b=await this.lifecycle(e,()=>s.replace(h));return b.pending||this.packages.set(e,h),b}let p=await this.check(e,o,r,n),d=await s.broker.active();if(p.version===o&&(!d?.enabled||d.version===o)&&!s.pendingVersion)return{unchanged:!0,version:o};let m=p.version===o?await this.installer.load(e,o):await this.installer.install(e,p,n);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:m.version,message:"Selected compatible release installed; activation may wait for editors"}),!d?.enabled)return{installed:!0,enabled:!1,version:m.version};let g=await this.lifecycle(e,()=>s.replace(m));return g.pending||this.packages.set(e,m),g}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,a.map(c=>c.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new y("invalid_operation","Unknown plugin management operation")}})().catch(async c=>{if(["install","update"].includes(i)){this.available.delete(e);let p=ce(c);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw c});return["install","enable","retry","update"].includes(i)&&await this.collectSettled(e),l})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let i=this.supervisor(e);return i.broker.collect(async r=>this.installer.collect(e,async()=>{let n=(await this.policies())[e];return[...r.map(s=>s.version),...i.pendingVersion?[i.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...n?.pinnedVersion?[n.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r,this.options.invokeTimeoutMs?.(e))}flush(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Flush generation changed",{status:409})):n.flushAction(r)}async asset(e,i,r){let n=this.packages.get(e);if(!n)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(n.version,(s.get(n.version)??0)+1);try{return await n0(n,r,i)}finally{let a=s.get(n.version)-1;a?s.set(n.version,a):s.delete(n.version)}}async assetRequest(e){let i=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.assetTokens.get(r),s=Buffer.from(i[2]);if(!n||s.length!==Buffer.byteLength(n)||!R1(s,Buffer.from(n)))return null;let a=await this.asset(r,i[3],i[4]);return a?{...a,pluginId:r}:null}servedManifest(e){return this.packages.get(e)?.manifest??null}async reconcileHostUpgrade(){if(_w(await jp(this.options.root)))return!1;let e=await this.installer.inventory(),i=await this.policies(),r=!0;for(let n of this.installer.catalog){let s=e.versions[n.id];if(s?.length)try{let a=await this.supervisor(n.id).broker.active(),o=a?.enabled?a.version:s.map(c=>c.version).sort((c,p)=>Tt(p,c))[0];try{await this.installer.load(n.id,o);continue}catch(c){if(ce(c).code!=="incompatible_plugin")throw c}let l=await this.manage(n.id,"update");l&&typeof l=="object"&&"pending"in l&&l.pending&&(r=!1)}catch(a){r=!1;let o=ce(a);this.errors.set(n.id,o),await this.recordCheck(n.id,{status:"failed",code:o.code,message:o.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,i){let r=new Sr({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),n=await this.installer.inventory();for(let s of this.installer.catalog){if(i?.throwIfAborted(),this.isDevPlugin(s.id))continue;let a=n.versions[s.id]??[];try{let o=await this.supervisor(s.id).broker.active();if(!o?.enabled&&!a.length)continue;try{await this.localCandidate(r,s.id,a,o?.enabled?o.version:void 0);continue}catch(l){if(ce(l).code!=="incompatible_plugin")throw l}}catch(o){i?.throwIfAborted();let l=ce(o);await this.recordCheck(s.id,{status:"failed",code:l.code,message:`Plugin prefetch skipped: ${l.message}. Downloading another release would not resolve this startup error.`}).catch(()=>{});continue}try{let o=a.map(p=>p.version).sort((p,d)=>Tt(d,p))[0],l=await r.check(s.id,o,void 0,i),c=await r.install(s.id,l,i);await this.recordCheck(s.id,{status:"up-to-date",version:c.version,message:"Release compatible with the next software version downloaded; activation unchanged"})}catch(o){i?.throwIfAborted();let l=ce(o);await this.recordCheck(s.id,{status:"failed",code:l.code,message:`${l.message}; no compatible release was prefetched for the software update`}).catch(()=>{})}}}async hostUpdateWarnings(e){let i=new Sr({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),n=[];for(let s of this.installer.catalog)try{let a=await this.supervisor(s.id).broker.active();if(!a?.enabled)continue;await this.localCandidate(i,s.id,r.versions[s.id]??[],a.version)}catch(a){let o=ce(a),l=o.code==="incompatible_plugin"?"Install a compatible release.":"Resolve the local plugin error before it can start.";n.push({pluginId:s.id,message:`Plugin unavailable after the update to ${e}: ${o.message}. ${l}`})}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[];try{for(let[i,r]of this.supervisors)e.push(await this.lifecycle(i,()=>r.suspendForRestart(),!0));this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(i){throw await Promise.allSettled(e.reverse().map(r=>r())),this.closing=!1,i}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let i=[],r=async()=>{let n=await Promise.allSettled(i.map(a=>a()));this.closing=!1;let s=n.find(a=>a.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let n of this.supervisors.values())i.push(await n.suspendForRestart(void 0,e));return r}catch(n){throw await r(),n}}};import{randomUUID as N1}from"node:crypto";var V=t=>Object.assign(new Error(t),{status:409,code:"view_barrier"}),qn=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,i,r=2e4,n=15e3,s=12e4){this.pluginId=e,this.generation=i,this.pollMs=r,this.freezeMs=n,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));blockedOnlyByWork=()=>[...this.views.values()].every(e=>e.kind==="controller"||e.frozen||this.immediate||!["editor","workspace"].includes(e.kind));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(i=>i.scope.ownerId===e).map(i=>({...i.identity,viewToken:i.token,kind:i.kind,dirty:i.dirty,busy:i.busy}))}sameScope(e,i,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===i.sessionId&&e.identity.mountId===i.mountId&&e.identity.generation===i.generation}recovery(e,i){return{state:i,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,i){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&i.sessionId===e.sessionId&&r.scope.ownerId===i.ownerId&&r.scope.workspaceId===i.workspaceId)}admitAction(e,i){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||i.ownerId!==r.scope.ownerId||i.workspaceId!==r.scope.workspaceId||i.sessionId!==r.identity.sessionId)throw V("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw V("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,i,r=++this.sequence){return e.commands.push({id:r,type:i,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,i){if(!e||e.pluginId!==this.pluginId||e.sessionId!==i.sessionId||!i.ownerId||!i.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw V("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw V("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw V("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw V("Invalid registration capability");let a=e.viewToken??N1();if(this.cancelledRegistrations.has(a)||this.recoveries.has(a))throw V("View initialization was cancelled; register a new document identity");let o=this.views.get(a);if(o){if(!this.sameScope(o,e,i)||o.kind!==e.kind)throw V("Duplicate view capability");return{viewToken:a,commands:[]}}if([...this.views.values()].some(l=>l.scope.ownerId===i.ownerId&&l.identity.mountId===e.mountId))throw V("Duplicate mount");return this.views.set(a,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...i},token:a,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:a,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw V("Invalid view capability");let r=this.views.get(e.viewToken),n=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,i))throw V("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw V("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let a=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:a}}}if(r&&this.sameScope(r,e,i)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw V("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw V("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&n&&this.sameScope(n,e,i)){if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!n){if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");if(this.switching)throw V("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,i))throw V("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw V("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw V("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw V("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(V("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw V("Invalid acknowledgement");let a=r.commands.find(o=>o.id===e.commandId);if(!a)throw V("Unknown command acknowledgement");r.commands=r.commands.filter(o=>o.id>e.commandId),a.type==="freeze"&&this.barrier?.id===a.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(V(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw V("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw V("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw V("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw V("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw V("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw V("Invalid poll cursor");if(r.waiter)throw V("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw V("Invalid poll mode");return!e.immediate&&!r.commands.some(a=>a.id>e.after)&&await new Promise(a=>{let o=setTimeout(l,Math.min(25e3,Math.max(50,this.pollMs)));function l(){clearTimeout(o),r.waiter=void 0,a()}r.waiter=l}),{viewToken:r.token,commands:r.commands.filter(a=>a.id>e.after)}}default:throw V("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw V("A view barrier is already active");if(!this.canSwitch()){let i=[...this.views.values()].filter(n=>n.activeActions||n.kind!=="controller"&&!n.frozen&&(n.busy||!this.immediate&&["editor","workspace"].includes(n.kind))),r=V(`Close editors before updating; old version retained. Pending views: ${i.map(n=>`${n.kind}:${n.identity.mountId}${n.activeActions?` (action in flight x${n.activeActions})`:n.busy?" (busy)":""}`).join(", ")}`);throw this.blockedOnlyByWork()?Object.assign(r,{reason:"view_busy"}):r}this.switching=!0;let e=++this.sequence;try{await new Promise((i,r)=>{let n=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):i())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>n(),reject:s=>n(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(a=>this.barrier?.pending.has(a.token));n(V(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(a=>`${a.kind}:${a.identity.mountId} (session ${a.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||n()})}catch(i){throw await this.resume(),i}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(i=>!i.frozen))throw V("Cannot commit before all views freeze");this.generation=e.generation;for(let i of this.views.values())this.enqueue(i,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(V("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(V("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var T0={"image/png":t=>t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":t=>t[0]===255&&t[1]===216,"image/webp":t=>t.subarray(0,4).toString("latin1")==="RIFF"&&t.subarray(8,12).toString("latin1")==="WEBP"};function I0(t){let e=t;if(!e||typeof e!="object"||e.$hosted!=="tool-result"||!Array.isArray(e.content))return{content:[{type:"text",text:JSON.stringify(t)??"null"}],details:t};let i=[],r=0;for(let n of e.content.slice(0,16)){let s=n;if(s?.type==="text"&&typeof s.text=="string")i.push({type:"text",text:s.text.slice(0,262144)});else if(s?.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&T0[s.mimeType]&&r<4){let a=/^[A-Za-z0-9+/]*={0,2}$/.test(s.data)?Buffer.from(s.data,"base64"):null;a&&a.length<=2097152&&T0[s.mimeType](a)?(i.push({type:"image",data:s.data,mimeType:s.mimeType}),r++):i.push({type:"text",text:"[image omitted by host: invalid or too large]"})}}return i.some(n=>n.type==="text")||i.unshift({type:"text",text:"(no text)"}),{content:i,details:e.details??null}}import{randomUUID as P1}from"node:crypto";var C1="Ov23limJmKiuu8cOP83E";function hd(t,e,i=process.env){let r=t?.secrets&&Object.hasOwn(t.secrets,e)?t.secrets[e]:void 0;if(r?.provider==="github")return{clientId:i.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||r.clientId||C1,scope:r.scope,createUrl:r.createUrl}}var D1="https://github.com/login/device/code",M1="https://github.com/login/oauth/access_token",L1=8,Ha=class{flows=new Map;fetcher;now;constructor(e=(r,n)=>fetch(r,{...n,signal:n.signal??AbortSignal.timeout(15e3)}),i=Date.now){this.fetcher=e,this.now=i}async post(e,i){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(i).toString()})}catch{throw new y("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let n=await r.json().catch(()=>null);if(!n||typeof n!="object"||!r.ok&&!("error"in n))throw new y("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,i,r){if(!r.clientId)throw new y("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[d,m]of this.flows)m.expiresAt<=this.now()&&this.flows.delete(d);if(this.flows.size>=L1)throw new y("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(D1,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:a,verification_uri:o}=n,l=Number(n.expires_in),c=Math.max(Number(n.interval)||5,1);if(typeof s!="string"||typeof a!="string"||typeof o!="string"||!o.startsWith("https://github.com/")||!Number.isFinite(l))throw new y("oauth_failed",typeof n.error_description=="string"?n.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=P1();return this.flows.set(p,{pluginId:e,name:i,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+l*1e3,interval:c,nextPoll:this.now()+c*1e3}),{deviceId:p,userCode:a,verificationUri:o,interval:c,expiresIn:l}}async poll(e){let i=this.flows.get(e);if(!i||i.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<i.nextPoll)return{status:"pending"};i.nextPoll=this.now()+i.interval*1e3;let r=await this.post(M1,{client_id:i.clientId,device_code:i.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:i.pluginId,name:i.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return i.interval+=5,i.nextPoll=this.now()+i.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as yd,readFileSync as A0,readdirSync as U1,statSync as q1}from"node:fs";import{lstat as j1,readdir as F1,writeFile as B1,mkdir as H1,rename as W1}from"node:fs/promises";import{delimiter as G1,dirname as $1,isAbsolute as V1,join as pi,resolve as jn}from"node:path";var Wa=t=>et.some(e=>e.id===t),x0=()=>et.map(t=>t.id).join(", "),ci="piWebappCatalog",z1="https://registry.npmjs.org";function K1(t,e){let i=t[ci];if(i===void 0)throw new y("invalid_catalog",`${e}: ${t.name} is not an official plugin (official: ${x0()}). Describe it in package.json "${ci}" with name, description and policy`);if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_catalog",`${e}: ${ci} must be an object`);if("id"in i||"registry"in i)throw new y("invalid_catalog",`${e}: ${ci} must not set id or registry; the package name is the id`);return{...ld({registry:z1,recommendedVersion:"0.0.0",requiredCapabilities:[...t.piWebapp.capabilities],...i,id:t.name},e,ci),official:!1}}function Y1(t=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(t??"").split(/[;\n]/).map(s=>s.trim()).filter(Boolean)){let s=n.lastIndexOf("="),a=n.slice(0,s),o=n.slice(s+1),l=s<1?`entry "${n}" is not <id>=<path.tgz>`:Wa(a)?o.endsWith(".tgz")?yd(jn(o))?null:`archive not found: ${jn(o)}`:`"${o}" is not a .tgz archive`:`"${a}" is not an official plugin (official: ${x0()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(l){i.push({level:"error",source:r,...Wa(a)?{pluginId:a}:{},message:l});continue}e.set(a,jn(o))}return{archives:e,notices:i}}var O0=t=>pi(t,"pi-web","hosted-dev.json"),R0=t=>pi(t,"pi-web","hosted-dev-status.json");function Q1(t,e,i=process.cwd()){let r=[],n=[],s=(t.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(G1).map(o=>o.trim()).filter(Boolean);for(let o of s)r.push({path:jn(i,o),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let a=s.length>0;if(e&&yd(e)){a=!0;try{let o=JSON.parse(A0(e,"utf8")),l=o&&typeof o=="object"?o.roots:void 0;if(!Array.isArray(l))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let c of l)typeof c!="string"||!V1(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:jn(c),source:e})}catch(o){n.push({level:"error",source:e,message:`cannot read dev configuration: ${o instanceof Error?o.message:String(o)}`})}}return{specs:r,notices:n,configured:a}}function J1(t){let e=[];try{e=U1(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name!=="node_modules"&&yd(pi(t,i.name,"package.json"))).map(i=>i.name)}catch{}return e.length?`package.json not found; this looks like a parent folder (packages inside: ${e.slice(0,3).join(", ")}). Point at the package directory itself`:"package.json not found; the folder is not a package (is the right branch checked out?)"}function X1(t){let e=(n,s)=>({notice:{level:"error",source:t.source,...s?{pluginId:s}:{},message:`${t.path}: ${n}`}}),i;try{i=q1(t.path)}catch{return e("directory does not exist")}if(!i.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(A0(pi(t.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?J1(t.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!ni(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Wa(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:K1({name:r.name,piWebapp:r.piWebapp,[ci]:r[ci]},"package.json")}}catch(n){return e(ce(n).message,r.name)}}var Ga=class{catalog=[];policies=new Map;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let i=Y1(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.archives=i.archives,this.archiveNotices=i.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let i=Q1(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let a of i.specs){let o=X1(a);if(o.notice){r.push(o.notice);continue}let l=o.pluginId;if(n.has(l)){r.push({level:"error",pluginId:l,source:a.source,message:`${a.path}: plugin ${l} is already provided by ${n.get(l)}`});continue}if(this.archives.has(l)&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${l}; the dev directory wins`}),!Wa(l)&&!this.catalog.some(c=>c.id===l)){if(!e){r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: ${l} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}let{policy:c,...p}=o.entry;this.catalog.push(p),this.policies.set(l,c)}else o.entry&&JSON.stringify(o.entry.policy)!==JSON.stringify(this.policies.get(l))&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: the ${ci} policy changed; restart pi-webapp once (npm run stop && npm run start) to apply it. Code still reloads live.`});n.set(l,a.path),s.set(l,a.source)}for(let a of[...this.roots.keys()])n.has(a)||this.roots.delete(a);for(let[a,o]of n)this.roots.set(a,o);this.rootSource.clear();for(let[a,o]of s)this.rootSource.set(a,o);return this.fileNotices=i.notices,this.rootNotices=r,{configured:i.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},$a=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let i of this.options.sources.notices())this.log(`${i.level}: ${i.message}`);let e=()=>{this.current=this.tick().catch(i=>{this.running&&this.log(`poll failed: ${ce(i).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let i=this.roots.get(e);i&&(i.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,i])=>({pluginId:e,root:i.root,state:i.state,...i.version?{version:i.version}:{},...i.message?{message:i.message}:{}}))}}log(e){(this.options.log??(i=>console.error(`pi-webapp [hosted-dev] ${i}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let i of[...this.roots.keys()])e.has(i)||this.roots.delete(i);for(let[i,r]of e){let n=this.roots.get(i);(!n||n.root!==r)&&(n={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(i,n));let s=await Z1(r);if(s===null){this.set(i,n,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),n.seen=void 0;continue}if(s!==n.seen){n.seen=s;continue}if(!this.stopped){if(s===n.applied){n.retry&&this.options.switcher.retry&&await this.apply(i,n,s,!0);continue}await this.apply(i,n,s)}}await this.publish()}set(e,i,r,n={}){let s=i.state!==r||i.message!==n.message||i.version!==n.version;i.state=r,i.message=n.message,i.code=n.code,i.version=n.version??i.version,s&&(i.at=new Date().toISOString(),this.log(`${e}: ${r}${n.version?` ${n.version}`:""}${n.message?` \u2014 ${n.message}`:""}`))}async apply(e,i,r,n=!1){n||this.set(e,i,"switching");try{let a=(await(n?this.options.switcher.retry(e):this.options.switcher.update(e))).plugins.find(o=>o.pluginId===e);i.applied=r,i.retry=!!a?.installed&&!!a.pendingVersion,a?.installed?a.pendingVersion?this.set(e,i,"pending",{version:a.version,message:`Waiting for editors to close before switching to ${a.pendingVersion}`}):this.set(e,i,"synced",{version:a.version}):this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(s){let a=ce(s),o=a.reason==="view_busy",l=o||["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(a.code);n?(i.applied=r,i.retry=l):l||(i.applied=r);let c=a.code==="not_installed";o?this.set(e,i,"pending",{message:"An open editor is saving; switching once it finishes"}):c?this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,i,"error",{code:a.code,message:`${a.message} (${a.code}). Fix and save again.`})}i.at=new Date().toISOString()}async publish(){let e=this.info(),i=JSON.stringify(e);i!==this.lastNotices&&(this.lastNotices=i,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let n=Object.fromEntries([...this.roots].map(([o,l])=>[o,{root:l.root,state:l.state,version:l.version,message:l.message,code:l.code,at:l.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(o=>o.id),plugins:n,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let a=`${r}.${process.pid}.tmp`;try{await H1($1(r),{recursive:!0}),await B1(a,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await W1(a,r)}catch{}}};async function Z1(t){let e=[],i=async(r,n)=>{let s=await j1(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await i(pi(t,"package.json"),"package.json");let r=async(n,s,a)=>{if(!(a>16||e.length>8192))for(let o of(await F1(n,{withFileTypes:!0})).sort((l,c)=>l.name.localeCompare(c.name)))o.isDirectory()?await r(pi(n,o.name),`${s}/${o.name}`,a+1):await i(pi(n,o.name),`${s}/${o.name}`)};if(await r(pi(t,"dist"),"dist",0),!e.some(n=>n.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function tP(t){try{return[..._r(t).secrets]}catch{return[]}}var Va=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ha;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??qa,e.dev?.enabled&&(this.devWatcher=new $a({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async i=>{let r=await this.inventory();return r.plugins.find(n=>n.pluginId===i)?.installed?this.manage({pluginId:i,operation:"update",reopenEditors:!0}):r},retry:i=>this.manage({pluginId:i,operation:"retry",reopenEditors:!0})}})),this.adapter=new Pa({policy:(i,r)=>{let n=e.policy?.(i,r);return{...n,enabled:!this.recovery.has(i)&&this.manager.tools.some(s=>s.pluginId===i)&&n?.enabled!==!1}},invoke:async(i,r,n)=>{n?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(o=>o.pluginId===i);if(!s)throw new y("plugin_unavailable","Hosted tool unavailable");let a=await this.manager.invoke(i,s.generation,r);return I0(a)}}),this.manager=new Ba({...e,workspaceRules:i=>c0(this.trusted,i),invokeTimeoutMs:i=>p0(this.trusted,i),lifecycle:(i,r,n)=>this.lifecycle(i,r,n),hooks:i=>({canSwitch:()=>this.coordinator(i).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(ad(this.trusted,i).tools).length)throw new y("unreviewed_tool","Official tool set changed; review required");this.verifyTools(i,r),this.adapter.validateChange(i,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(i).freeze()},committed:async r=>{try{let n=r.enabled?this.manager.tools.find(s=>s.pluginId===i)?.descriptors:[];if(!n)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(i,n),r.enabled){let s=await this.manager.installer.load(i,r.version);this.documents.set(i,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:tP(s.manifest)})}else this.documents.delete(i);this.adapter.change(i,n),await this.coordinator(i).committed(r),e.changed?.(),this.recovery.delete(i)}catch(n){throw this.recovery.set(i,n),await this.coordinator(i).committed(r).catch(()=>{}),n}},resume:()=>this.coordinator(i).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:i=>this.manage(i),secret:async(i,r,n)=>{let s=this.options.capabilities?.secrets,a=this.documents.get(i)?.secrets;if(!s)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(!a?.includes(r))throw new y("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return n===null?await s.delete(i,r):await s.set(i,r,n),this.options.changed?.(),this.inventory()},secretAuth:async i=>{let r=this.options.capabilities?.secrets;if(!r)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(i.phase==="cancel")return this.deviceFlows.cancel(i.deviceId),{status:"cancelled"};if(i.phase==="start"){let s=this.documents.get(i.pluginId)?.secrets.includes(i.name)?hd(this.trusted.get(i.pluginId),i.name):void 0;if(!s)throw new y("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(i.pluginId,i.name,s)}let n=await this.deviceFlows.poll(i.deviceId);return n.status!=="granted"?{status:n.status}:(await r.set(n.pluginId,n.name,n.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(i,r)=>{if(!this.options.approvals)throw new y("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(i,r),this.inventory()},action:(i,r)=>this.action(i,r?.checkpointOnly),views:async i=>{if(i.operation==="list-pending"){if(typeof i.pluginId!="string")throw new y("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(i.pluginId).pendingViews(this.options.ownerId)}}let r=i,n=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(n))},asset:async i=>{let r=await this.manager.assetRequest(i);if(!r)return null;let n=this.trusted.get(r.pluginId)?.browser?.wasm===!0&&kv(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:Sv({wasm:n})}}}}verifyTools(e,i){let r=ad(this.trusted,e);for(let n of i)if(!Object.hasOwn(r.tools,n.name)||r.tools[n.name]!==n.action||n.readonly!==r.readonlyActions.includes(n.action))throw new y("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let i=this.views.get(e);if(!i)throw new y("unknown_plugin","Hosted coordinator unavailable");return i}scope(e,i){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||i&&(r.cwd!==i.cwd||r.workspaceId!==i.workspaceId))throw new y("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,i){let r=this.manager.tools.find(n=>n.pluginId===e);if(!r||r.generation!==i)throw new y("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,i=!1){let r=this.queue.then(async()=>{if(this.closing&&!i)throw new y("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,i,r=!1){let n=this.switches.then(async()=>{if(this.closing&&!r)throw new y("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await i();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let a=await new Bi(bd(this.options.root,"data"),e).active();a&&await this.coordinator(e).committed(a).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new y("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=n.catch(()=>{}),n.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let i,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(n=>{i=setTimeout(()=>n(!1),e),i.unref?.()})])}finally{clearTimeout(i)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??et)try{let i=await new Bi(bd(this.options.root,"data"),e.id).active();this.views.set(e.id,new qn(e.id,i?.generation??0))}catch(i){this.recovery.set(e.id,i),this.views.set(e.id,new qn(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=bd(this.options.root,"host-version.json");(await ke(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await Se(this.options.root),await te(e,{version:this.options.hostVersion}))}).catch(e=>{for(let i of this.options.catalog??et)this.recovery.set(i.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),i=this.options.capabilities?.secrets,r=new Map;for(let n of e.plugins){let s=n.enabled?this.documents.get(n.id)?.secrets??[]:[];i&&s.length&&r.set(n.id,await Promise.all(s.map(async a=>{let o=hd(this.trusted.get(n.id),a);return{name:a,configured:await i.has(n.id,a),...o?{signIn:o.clientId?"browser":"token-page",...o.createUrl?{createUrl:o.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(n=>({pluginId:n.id,name:n.name,official:n.official,installed:n.installed,enabled:n.enabled,description:n.description,...r.has(n.id)?{secrets:r.get(n.id)}:{},icon:(this.options.catalog??et).find(s=>s.id===n.id)?.icon,hasRetainedData:n.activeVersion!==null,phase:this.recovery.has(n.id)?"reconnect-required":n.phase,updatePolicy:n.updatePolicy,pinnedVersion:n.pinnedVersion,updateDiagnostic:n.updateDiagnostic,...n.enabled&&n.activeVersion?{version:n.activeVersion}:n.version?{version:n.version}:{},...n.availableVersion?{availableVersion:n.availableVersion}:{},...n.pendingVersion?{pendingVersion:n.pendingVersion}:{},...n.generation!==null?{generation:n.generation}:{},...this.recovery.has(n.id)||n.error?{error:this.recovery.get(n.id)instanceof Error?this.recovery.get(n.id).message:n.error?.message??"Recovery required",errorCode:this.recovery.has(n.id)?"reconnect_required":n.error?.code}:{},...n.enabled&&n.assetBase&&this.documents.has(n.id)&&this.trusted.has(n.id)?{documentUrl:n.assetBase+this.documents.get(n.id).document,controllerUrl:n.assetBase+this.documents.get(n.id).controller,contribution:structuredClone(this.trusted.get(n.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new y("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new y("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let i=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(i){if(this.downloads.has(e.pluginId))throw new y("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,i)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new y("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let n=await this.manager.manage(e.pluginId,e.operation,e.version,i?.abort.signal);if(this.recovery.has(e.pluginId)||n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired)throw new y("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{i&&this.downloads.get(e.pluginId)===i&&this.downloads.delete(e.pluginId)}}async action(e,i=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new y("action_denied","Action is not reviewed by this host",{status:403});let n=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:eP(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||i){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new y("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new y("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{n()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let i=await this.manager.suspendForRestart(e),r=!1,n=async()=>{if(!r)try{await i(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=n,n}catch(i){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),i}finally{for(let i of this.views.values())i.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let i of this.views.values())i.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as iP,readdir as rP,unlink as nP}from"node:fs/promises";import{join as kr}from"node:path";import{randomUUID as sP}from"node:crypto";var _d="hosted-migration.json";function N0(t,e="@chengzhiyi/pi-excalidraw"){return async i=>{let{cwd:r,sessionId:n}=i.scope,s=kr(t,ne(JSON.stringify([r,n])));await Se(t),await Se(s);let a=kr(s,"scope.lock"),o;try{o=await iP(a,"wx",384)}catch(l){throw l.code==="EEXIST"?new y("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):l}try{await o.writeFile(JSON.stringify({pid:process.pid,operationId:sP()}));let l=await ke(kr(s,_d));if(l&&(l.version!==1||l.pluginId!==e))throw new y("invalid_storage","Legacy scope belongs to another migration");let c=await rP(s),p=[];for(let m of c){if(m==="scope.lock"||m==="focus.json"||m===_d||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(m))continue;if(!/^[\w-]{1,80}\.json$/.test(m))throw new y("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new y("invalid_storage","Too many legacy checkpoints");let g=await ke(kr(s,m),3*512*1024);if(!g||g.version!==1||g.cwd!==r||g.sessionId!==n||!g.draft||m!==`${g.draft.id}.json`)throw new y("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(g.draft)}let d=await ke(kr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(m=>m.id===d)))throw new y("invalid_storage","Invalid legacy focused drawing");return l||await te(kr(s,_d),{version:1,pluginId:e,operationId:i.requestId}),{drafts:p,focused:d}}finally{await o.close(),await nP(a)}}}import{join as gP}from"node:path";import{randomUUID as aP}from"node:crypto";var oP=6e4,za=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:i,sessionId:r,title:n})=>({id:e,pluginId:i,sessionId:r,title:n}))}async authorize(e,i){let r=this.entries.get(i);if(r&&r.pluginId!==e)throw new y("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new y("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<oP?new y("execute_denied","The user denied execution",{status:403}):(this.entries.set(i,{id:aP(),pluginId:e,sessionId:i,title:this.options.describe?.(i)??i,status:"pending"}),this.options.changed?.(),new y("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,i){let r=[...this.entries.values()].find(n=>n.id===e&&n.status==="pending");if(!r)throw new y("unknown_approval","No such pending approval",{status:404});r.status=i?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as lP,readFile as cP,rename as pP,writeFile as dP}from"node:fs/promises";import{randomUUID as uP,createHash as mP}from"node:crypto";import{join as P0}from"node:path";var Ka=class{dir;queue=Promise.resolve();constructor(e){this.dir=P0(e,"secrets")}file=e=>P0(this.dir,`${mP("sha256").update(e).digest("hex")}.json`);async read(e){try{let i=JSON.parse(await cP(this.file(e),"utf8"));if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch(i){if(!ii(i))throw new y("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let i=this.queue.then(e,e);return this.queue=i.catch(()=>{}),i}async get(e,i){return(await this.read(e))[i]??null}has(e,i){return this.get(e,i).then(r=>r!==null)}set(e,i,r){return this.mutate(e,n=>{n[i]=r})}delete(e,i){return this.mutate(e,r=>{delete r[i]})}mutate(e,i){return this.serialize(async()=>{let r=await this.read(e);i(r),await lP(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${uP()}.tmp`;await dP(n,JSON.stringify(r),{mode:384}),await pP(n,this.file(e))})}};function C0(t,e){let i=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:n,title:s,prompt:a}){let o=await t.createDetached(n,r,s);try{await t.sendDetached(o,a,!1)}catch(l){throw await t.releaseDetached(o),l}return{sessionId:o}},ownerOf:r=>t.detachedOwner(r),activeCount:r=>t.detachedCount(r),async send(r,n,s){let a=t.detachedOwner(r);if(s==="execute"&&(!a||!await e(a,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await t.sendDetached(r,n,s==="execute")},abort:r=>t.abortDetached(r),release:r=>t.releaseDetached(r),async events(r,n){let s=t.detachedEvents(r,n);return{events:s.events.map(i),next:s.next}}}}var fP="scheduler";function D0(t){let e=new za({describe:t.sessionTitle,changed:t.changed}),i=()=>{let n=t.sessions();if(!n)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return n},r={createDetached:(...n)=>i().createDetached(...n),detachedOwner:n=>t.sessions()?.detachedOwner(n)??null,detachedCount:n=>t.sessions()?.detachedCount(n)??0,sendDetached:(...n)=>i().sendDetached(...n),abortDetached:n=>i().abortDetached(n),releaseDetached:async n=>{e.forget(n),await i().releaseDetached(n)},detachedEvents:(...n)=>i().detachedEvents(...n)};return{approvals:e,capabilities:{secrets:new Ka(gP(t.root,"capability-secrets")),sessions:C0(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=t.activeWorkspace();if(!n)return null;try{return t.trustedScope(n,fP)}catch{return null}}}}ga();async function hP(){for(let t of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=aa(t),i=new St({env:t,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await i.ready,e.node.enabled||e.browser.enabled||i.enabled||i.reporter||i.capture(new Error("Disabled release probe"))||await i.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await i.close()}}return{release:Mr,buildId:nt,browser:aa({}).browser}}async function M0(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let t=new St({monitor:!1});try{if(await t.ready,!t.enabled)throw new Error("Sentry verification transport is disabled");let e=t.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await t.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Mr,buildId:nt}}finally{await t.close()}}var Fn=Ir(bP(wP(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),IP=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),u=globalThis[IP]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Li,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};u.lifecycle??=new Li;u.tuiGeneration??=0;u.stopChanged??=null;u.tuiWaitController??=new AbortController;u.tuiStreaming??=null;u.tuiPrompts??=new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()});u.tuiPromptSessionId??=null;u.tuiAgentError??=!1;var U0=!1;function AP(t){return U0||(U0=!0,setTimeout(()=>{t.pruneReleases().catch(()=>{})},6e4).unref()),t}function Ya(){return u.selected==="sdk"?u.workspaceSessions?.catalog??null:u.tuiCatalog}var xP=null;function OP(){return xP??=SP.create({refreshOnCreate:!1})}var Qa=new Map;async function Tr(){let t=await OP(),e=u.selected==="tui"?u.current?.modelRegistry:void 0,i=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Qa.keys())i.has(r)||(t.unregisterProvider(r),Qa.delete(r));for(let r of i){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),a=n??s;!a||Qa.get(r)===a||(n?t.registerNativeProvider(n):s&&t.registerProvider(r,s),Qa.set(r,a))}return await t.refresh({allowNetwork:!1}),t}function Oe(){return u.selected==="sdk"?u.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():Ht()}function Ht(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...Av(u.current,u.current.sessionManager.getSessionName(),u.tuiCatalog?.ids()??[]),idle:u.current.isIdle()&&!u.tuiPrompts.sending,streaming:u.tuiStreaming,queuedPrompts:u.tuiPrompts.view(),hasPendingPrompts:u.current.hasPendingMessages?.()??!1,interactions:u.interactions?.pending(u.current.sessionManager.getSessionId())??[]}}async function Ed(t,e,i,r,n){let s=Be(t);ei({...Ht(),idle:s.isIdle()},e,n);let a=s.isIdle();a&&fr(()=>u.hosted?.adapter.assertAdmission(),r,(o,l)=>u.bridge?.reportError?.(o,l)),a&&(u.operation=r);try{let o=i.length?[{type:"text",text:e},...i]:e;if(u.replacementContext!==null&&u.replacementSessionId===t)await u.replacementContext.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n});else{if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n})}u.current?.sessionManager.getSessionId()===t&&u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Ht()})}catch(o){throw a&&(u.operation=void 0),o}}function Sd(){let t=u.current?.sessionManager.getSessionId(),e=u.tuiGeneration,i=()=>{if(!t||!u.current||u.tuiGeneration!==e||u.current.sessionManager.getSessionId()!==t||u.tuiAgentError)return!1;let r=Ht();return!u.hosted?.adapter.isFrozen&&u.current.isIdle()&&!r.paused&&!r.interactions.length};u.tuiPrompts.schedule(i,(r,n,s)=>Ed(t,r,n,s))}function Me(t){if(Oe().sessionId!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function B0(){let t=(u.workspaces?.list()??[]).map(d=>({...d})),e=u.activeWorkspaceId,i=Oe(),n=u.current?Ht():null,s=await Ri(i.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)),a=n?await Ri(n.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)):null,o=await Bn.listAll(),l=u.workspaceSessions?.retainedSessions()??[];n&&a&&l.push({sessionId:n.sessionId,cwd:a,path:null,name:n.name,modified:n.messages.at(-1)?.timestamp??new Date().toISOString(),idle:n.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&n.idle&&u.tuiPrompts.length===0&&!n.messages.some(d=>d.role==="user")});let c=await mr(o,Mi(Ae()),new Set(l.filter(d=>!d.idle).map(d=>d.sessionId))),p=(await Promise.all(t.map(async d=>{let g=(await Ci(d.path,o).catch(h=>(h instanceof In?d.available=!1:u.bridge?.reportError?.(h,{stage:"workspace_sessions"}),[]))).map(h=>({id:h.id,workspaceId:d.id,path:h.path,name:h.name||h.firstMessage?.slice(0,50)||"",modified:h.modified.toISOString(),idle:!0}));for(let h of l.filter(f=>f.cwd===d.path)){if(h.blank&&h.sessionId!==i.sessionId)continue;let f=g.findIndex(S=>S.id===h.sessionId),b={id:h.sessionId,workspaceId:d.id,path:h.path??g[f]?.path??null,name:h.name,modified:h.modified,idle:h.idle};f<0?g.unshift(b):g[f]=b}return d.path===s&&!g.some(h=>h.id===i.sessionId)&&g.unshift({id:i.sessionId,workspaceId:d.id,path:null,name:i.name,modified:new Date().toISOString(),idle:i.idle}),g.map(h=>{let f=c.get(h.id)?.view;return f?{...h,subagent:f}:h})}))).flat();return{items:t,activeId:e,sessions:p}}var q0=0;async function xe(){if(!u.bridge)return;let t=++q0;try{let e=await B0();t===q0&&u.bridge?.publish({type:"workspaces",value:e})}catch(e){u.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function kd(t,e=!1){let i=u.workspaces?.get(t);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Et(i.path),!e&&u.current&&i.path===await Ri(u.current.cwd)&&!u.workspaceSessions?.hasWorkspace(i.path))u.selected="tui",u.activeWorkspaceId=t,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Oe()});else{if(!u.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await u.workspaceSessions.reuseBlank(i.path))&&await u.workspaceSessions.open(i.path,e?"new":"continue"),u.selected="sdk",u.activeWorkspaceId=t,u.bridge?.publish({type:"snapshot",session:Oe()})}await xe()}async function j0(t,e,i){let r=u.workspaces?.get(t);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await Et(r.path);if(u.workspaceSessions?.hasSession(n,e)||u.current?.sessionManager.getSessionId()===e&&await Ri(u.current.cwd)===n)return r;if(!(await Ci(n)).some(a=>a.id===e&&a.path===i))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function Be(t){let e=u.current;if(e===null||e.sessionManager.getSessionId()!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function Ue(t){u.current=t,u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Oe()})}function H0(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let t=u.selected==="sdk"?u.workspaceSessions?.path:u.current.cwd;if(!t)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=u.selected==="tui"?u.current.isProjectTrusted():u.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return kP.create(t,void 0,{projectTrusted:e})}async function W0(){let t=H0(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),i=new F0({cwd:Oe().cwd,agentDir:Ae(),settingsManager:t}),r=uw(i.listConfiguredPackages(),await i.resolve(async()=>"skip"));return{projectTrusted:t.isProjectTrusted(),global:e(t.getGlobalSettings()),project:e(t.getProjectSettings()),installed:r}}async function RP(t){Me(t.sessionId);let e=u.selected==="tui"?Be(t.sessionId):null;if(e?!e.isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=H0();if(t.scope==="project"&&!i.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=t.value.trim(),n=t.scope==="project"?i.getProjectSettings():i.getGlobalSettings();if(t.kind==="packages"){let s=new F0({cwd:Oe().cwd,agentDir:Ae(),settingsManager:i});t.action==="add"?await s.installAndPersist(r,{local:t.scope==="project"}):await s.removeAndPersist(r,{local:t.scope==="project"})}else if(t.kind==="extensions"){let s=n.extensions??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectExtensionPaths(a):i.setExtensionPaths(a)}else{let s=n.skills??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectSkillPaths(a):i.setSkillPaths(a)}return await i.flush(),u.selected==="tui"?(u.commandContext&&await u.commandContext.reload(),u.current&&Ue(u.current)):(await u.workspaceSessions?.reload(),u.bridge?.publish({type:"plugins_changed"})),await W0()}function Ja(t,e=Dp){if(u.hostedMode===!1||u.hostedMode===void 0&&u.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");u.hostedMode=!0;let i=(c,p)=>{let d=vd(c);return{cwd:d,sessionId:p,workspaceId:L0("sha256").update(d).digest("hex")}},r=Er(Ae(),"pi-web","hosted"),n=new Ga({configPath:O0(Ae())});u.hosted??=new Va({root:r,...n.enabled?{dev:n,devStatusPath:R0(Ae())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...et,...n.catalog],policies:new Map([...qa,...n.policies])}:{},...D0({root:r,sessions:()=>u.workspaceSessions,activeWorkspace:()=>u.workspaceSessions?.path??null,trustedScope:i,sessionTitle:c=>u.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(_P(Ir(Fn,"../../package.json"),"utf8")).version,packageRoot:Ir(Fn,"../.."),workerEntry:Ir(Fn,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${L0("sha256").update(Ae()).digest("hex")}`,resolveSession:c=>{let p=u.current;if(p?.sessionManager.getSessionId()===c)return i(p.cwd,c);let d=u.workspaceSessions?.hostedScope(c);return d?i(d.cwd,c):null},legacy:()=>N0(Er(Ae(),"pi-web","diagrams")),changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),u.offHostedThaw?.(),u.offHostedThaw=u.hosted?.adapter.onThaw(Sd),u.pi=t;let s=am({async run(...c){if(!u.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return u.bridge.runPluginTool(...c)},async ask(c,p){if(u.pi&&c.sessionId===u.current?.sessionManager.getSessionId())return ba(u.pi.events,c,p);if(!u.workspaceSessions)throw new Error("The Web workbench is not open");return u.workspaceSessions.requestInteraction(c,p)}});for(let c of s)t.registerTool(c);u.tools?.clear(),u.tools=new gr({enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,capture:(c,p)=>u.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>u.bridge?.breadcrumb?.(c,p),anonymize:c=>u.telemetry?.session(c)??"unavailable"});let a=c=>({...u.operation,session:u.telemetry?.session(c.sessionManager.getSessionId()),piVersion:wd,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});u.interactions?.dispose(),u.interactions=new ur(t.events,c=>!!u.bridge&&c.sessionId===u.current?.sessionManager.getSessionId()&&An(u.tuiCatalog,c.pluginId),()=>{u.current&&u.selected==="tui"&&Ue(u.current)});let o=()=>{u.stopChanged?.(),u.stopChanged=t.events.on(_a,()=>{u.selected==="tui"&&u.current&&Ue(u.current)})};o(),t.on("session_start",async(c,p)=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiWaitController=new AbortController,u.tuiGeneration++,o(),u.current=p,u.releaseHostedTui?.(),u.releaseHostedTui=u.hosted?.adapter.mountTui(t,i(p.cwd,p.sessionManager.getSessionId())),u.hosted&&!await u.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),u.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(u.tuiPrompts=new ti(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:Ht()}),xe()}),u.tuiPromptSessionId=p.sessionManager.getSessionId()),u.tuiAgentError=!1,u.bridge){let d=await Pi.discover(p.cwd,p.isProjectTrusted?.()??!1);if(u.current!==p)return;u.tuiCatalog=d}u.replacementSessionId!==p.sessionManager.getSessionId()&&(u.replacementContext=null,u.replacementSessionId=null),Ue(p),u.bridge&&u.selected==="tui"&&u.bridge.publish({type:"plugins_changed"}),u.selected==="tui"&&u.workspaces&&u.workspaces.add(p.cwd).then(async d=>{u.selected!=="tui"||u.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(u.activeWorkspaceId=d.id,await xe())}).catch(d=>{u.bridge?.publish({type:"error",message:d instanceof Error?d.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:u.bridge.reportError?.(d,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!u.autoOpened&&(u.autoOpened=!0,l(p).catch(d=>{p.ui.notify(d instanceof Error?d.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),t.on("agent_start",(c,p)=>{u.tuiAgentError=!1,u.bridge?.breadcrumb?.("agent_start",a(p)),Ue(p),xe()}),t.on("agent_end",(c,p)=>Ue(p)),t.on("agent_settled",(c,p)=>{u.bridge?.breadcrumb?.("agent_end",a(p)),u.tools?.clear(),u.operation=void 0,u.tuiStreaming=null,Sd(),Ue(p),xe()}),t.on("tool_execution_start",(c,p)=>{u.tools?.start(c,a(p))}),t.on("tool_execution_end",(c,p)=>{u.tools?.end(c,a(p))}),t.on("model_select",(c,p)=>Ue(p)),t.on("thinking_level_select",(c,p)=>Ue(p)),t.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){u.tuiAgentError=!0;let d=u.bridge?.reportError?.(new Error("Agent response failed"),{...u.operation,stage:"agent",code:"agent_failed",piVersion:wd});u.selected==="tui"&&u.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:d,inTranscript:!0,...u.operation})}c.message.role==="toolResult"&&u.tools?.message(c.message,a(p)),c.message.role==="assistant"&&(u.tuiStreaming=null),u.selected==="tui"&&c.message.role==="assistant"&&u.bridge?.publish({type:"stream",message:null}),Ue(p),xe()}),t.on("session_info_changed",(c,p)=>Ue(p)),t.on("message_update",(c,p)=>{if(u.current=p,c.message.role!=="assistant"||(u.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:Bt(c.message.content)},u.selected!=="tui"||u.bridge===null))return;let d=Date.now();d-u.lastStreamAt<60||(u.lastStreamAt=d,u.bridge.publish({type:"stream",message:u.tuiStreaming}))}),t.on("session_shutdown",async c=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiGeneration++,u.stopChanged?.(),u.stopChanged=null,u.interactions?.cancelAll(),u.releaseHostedTui?.(),u.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){u.current=null;return}await u.hosted?.shutdown(),u.hosted=void 0,u.offHostedThaw?.(),u.offHostedThaw=void 0,u.current=null;let p=u.bridge,d=u.telemetry;u.bridge=null,u.commandContext=null,u.replacementContext=null,u.replacementSessionId=null,u.pi=null;let m=u.workspaceSessions;u.workspaceSessions=null,await m?.dispose(),u.selected="tui",u.activeWorkspaceId=null,u.autoOpened=!1,u.tuiCatalog=null,u.stopPluginWatch?.(),u.stopPluginWatch=null,u.operation=void 0,u.telemetry=null,p?await p.close():await d?.close()});let l=async c=>{u.telemetry??=new St;try{u.current=c,u.commandContext="newSession"in c?c:null,u.pi=t,u.tuiCatalog=await Pi.discover(c.cwd,c.isProjectTrusted?.()??!1),u.workspaces===null&&(u.workspaces=new ya(Nv(Ae())),await u.workspaces.load());try{await u.workspaces.discover((await Bn.listAll()).map(m=>m.cwd))}catch(m){c.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${m instanceof Error?m.message:String(m)}`,"warning")}let p=await u.workspaces.add(c.cwd);if(u.selected==="tui"&&(u.activeWorkspaceId=p.id),u.bridge&&(u.bridge.protocolVersion!==7||u.bridge.buildId!==nt||typeof u.bridge.reportError!="function"||typeof u.bridge.runPluginTool!="function")){let m=u.bridge;if(u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)&&u.workspaceSessions.session&&!u.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");u.bridge=null,await m.close(),await u.telemetry.close(),u.telemetry=new St}if(u.bridge===null){let m=u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)?u.workspaceSessions:null,g=m?.session&&m.path?{path:m.path,sessionManager:m.session.sessionManager}:null;m&&(await m.dispose(),u.workspaceSessions=null),u.workspaceSessions??=new ka(f=>{u.selected==="sdk"&&u.bridge?.publish(f)},()=>u.current?.model,f=>{try{return!!u.current&&vd(u.current.cwd)===f&&(u.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,b)=>u.bridge?.reportError?.(f,b),{enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,breadcrumb:(f,b)=>u.bridge?.breadcrumb?.(f,b),anonymize:f=>u.telemetry?.session(f)??"unavailable"},()=>{xe()},s,{adapter:u.hosted.adapter,scope:i}),g&&await u.workspaceSessions.open(g.path,{sessionManager:g.sessionManager});let h={hosted:u.hosted?.handlers,selfUpdate:AP(new Na({agentDir:Ae(),packageRoot:Ir(Fn,"../.."),launcherNonce:process.env.PI_WEBAPP_FOREGROUND==="1"?void 0:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:f=>u.hosted.manager.hostUpdateWarnings(f),prefetchPlugins:(f,b)=>u.hosted.manager.prefetchForHost(f,b),beforeRestart:f=>u.hosted.prepareRestart(f)})),snapshot:Oe,busyGitWorkspaces:()=>{let f=(u.workspaceSessions?.retainedSessions()??[]).filter(b=>!b.idle).map(b=>b.cwd);if(u.current&&(!u.current.isIdle()||u.tuiPrompts.sending))try{f.push(vd(u.current.cwd))}catch{f.push(u.current.cwd)}return f},plugins:async()=>{let f=Ya();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Ya()?.asset(f)??null,async invokePluginAction(f,b,S,E){if(Me(f),!Ya()?.has(b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let A=u.selected,C=u.tuiGeneration,N=u.workspaceSessions?.session,R={requestId:TP(),sessionId:f,pluginId:b,action:S,input:E},W=u.selected==="sdk"?await u.workspaceSessions.invokePluginAction(R):await va(u.pi.events,R,15e3,u.tuiWaitController.signal);if(Me(f),A!==u.selected||(A==="tui"?C!==u.tuiGeneration:N!==u.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return u.selected==="tui"&&u.current&&Ue(u.current),W},async resolvePluginInteraction(f,b,S,E){if(Me(f),!An(Ya(),b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");u.selected==="sdk"?u.workspaceSessions.resolveInteraction(f,b,S,E):u.interactions.resolve(f,b,S,E)},image(f,b,S){Me(f);let A=(u.selected==="sdk"?u.workspaceSessions?.session?.sessionManager.getBranch():u.current?.sessionManager.getBranch())?.find(N=>N.id===b);if(A?.type!=="message"||A.message.role!=="user"||!Array.isArray(A.message.content))return null;let C=A.message.content[S];return C?.type!=="image"?null:{data:Buffer.from(C.data,"base64"),mimeType:C.mimeType}},async workspaces(){return B0()},async addWorkspace(f,b){let S=await u.workspaces.add(f,b);try{await kd(S.id,!0)}catch(E){throw await xe(),E}},async selectWorkspace(f){await kd(f)},async newSessionInWorkspace(f){await kd(f,!0)},async removeWorkspace(f){if(f===u.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await u.workspaces.remove(f),await xe()},async subagentHistory(f,b){let S=u.workspaces?.get(f);if(!S)return null;let E=await Bn.listAll(),A=(await Ci(S.path,E)).find(N=>N.id===b);if(!A)return null;let C=(await mr(E,Mi(Ae()))).get(b);return C?Gv(A.path,b,C):null},async selectSession(f,b,S){let E=u.workspaces?.get(f);if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Et(E.path),b===u.current?.sessionManager.getSessionId()&&E.path===await Ri(u.current.cwd))u.selected="tui",u.activeWorkspaceId=f,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Oe()});else{if(u.selected==="sdk"&&u.workspaceSessions?.session?.sessionManager.getSessionId()===b&&u.workspaceSessions.path===E.path)return;if(u.workspaceSessions?.hasSession(E.path,b))await u.workspaceSessions.open(E.path,{sessionId:b});else{let A=await Bn.listAll();if(!(await Ci(E.path,A)).some(R=>R.id===b&&R.path===S))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");if((await mr(A,Mi(Ae()))).has(b))throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E3A\u53EA\u8BFB");await u.workspaceSessions.open(E.path,{sessionFile:S})}u.selected="sdk",u.activeWorkspaceId=f,u.bridge?.publish({type:"snapshot",session:Oe()})}await xe()},async renameSession(f,b,S,E){let A=E.replace(/\s+/g," ").trim();if(A.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await j0(f,b,S),u.current?.sessionManager.getSessionId()===b&&u.pi?u.pi.setSessionName(A):u.workspaceSessions?.rename(b,A)||Bn.open(S).appendSessionInfo(A),u.selected==="tui"&&u.current?.sessionManager.getSessionId()===b&&u.bridge?.publish({type:"snapshot",session:Oe()}),await xe()},async deleteSession(f,b,S){let E=await j0(f,b,S);if(u.current?.sessionManager.getSessionId()===b)throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664");let A=await u.workspaceSessions?.discard(b)??null,C=A?.path??(S||null);C&&await Vv(C,Ae()),A?.wasActive&&u.selected==="sdk"&&(await u.workspaceSessions.open(E.path,"new"),u.selected="sdk",u.activeWorkspaceId=f,u.bridge?.publish({type:"snapshot",session:Oe()})),await xe()},async models(){if(u.selected==="sdk")return u.workspaceSessions?.models()??[];let f=u.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let b=f.scopedModels?.map(S=>`${S.model.provider}/${S.model.id}`)??[];return f.modelRegistry.getAvailable().filter(S=>b.length===0||b.includes(`${S.provider}/${S.id}`)).map(S=>({provider:S.provider,id:S.id,name:S.name}))},async providers(){let f=await Tr(),b=new Set((await f.listCredentials()).map(S=>S.providerId));return f.getProviders().map(S=>({id:S.id,name:S.name,configured:f.getProviderAuthStatus(S.id).configured,storedCredential:b.has(S.id),methods:[S.auth.apiKey?.login?"api_key":null,S.auth.oauth?"oauth":null].filter(E=>E!==null)}))},async providerModels(f){let b=await Tr();return Am(Er(Ae(),"models.json"),f,b)},async updateProviderModel(f,b,S){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=Oe().model;if(S.action==="remove"&&E===`${b}/${S.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(S.action==="save"&&S.originalId&&S.originalId!==S.model.id&&E===`${b}/${S.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let A=await Tr();await xm(Er(Ae(),"models.json"),b,S,A),await A.refresh({providers:[b],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1});let C=S.action==="save"?S.model.id:S.action==="base_url"&&E?.startsWith(`${b}/`)?E.slice(b.length+1):null;if(C&&E===`${b}/${C}`)if(u.selected==="sdk")try{await u.workspaceSessions.setModel(b,C)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let N=Be(f),R=N.modelRegistry.find(b,C);if(!R||!u.pi||!await u.pi.setModel(R))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");Ue(N)}},async logoutProvider(f,b){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Tr();if(!(await S.listCredentials()).some(E=>E.providerId===b))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await S.logout(b),await u.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1})},async loginProvider(f,b,S){let E=await Tr();await E.login(f,b,wm(f,b,S)),await E.refresh({providers:[f],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,b){if(Me(f),u.selected==="tui"?!Be(f).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Tr();if(S.getProvider(b.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Sm(Er(Ae(),"models.json"),b),await S.refresh({allowNetwork:!1}),await u.current?.modelRegistry.refresh({allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return u.selected==="tui"?(u.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(Me(f),u.selected==="sdk"){let S=u.workspaceSessions?.session;if(!S||!S.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await S.compact(),u.bridge?.publish({type:"snapshot",session:Oe()});return}let b=Be(f);if(!b.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");b.compact()},async setModel(f,b,S){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.setModel(b,S);return}let E=Be(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let A=E.modelRegistry.find(b,S);if(!A||!E.modelRegistry.getAvailable().some(C=>C.provider===b&&C.id===S))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!u.pi||!await u.pi.setModel(A))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");Ue(E)},async setThinkingLevel(f,b){if(Me(f),!["off","minimal","low","medium","high","xhigh"].includes(b))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(u.selected==="sdk"){let A=u.workspaceSessions?.session;if(!A||!A.isIdle||!A.getAvailableThinkingLevels().includes(b))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");A.setThinkingLevel(b),u.bridge?.publish({type:"snapshot",session:Oe()});return}let E=Be(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!E.model||!EP(E.model).includes(b))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.setThinkingLevel(b),Ue(E)},config:W0,updateConfig:RP,async send(f,b,S=[],E,A){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.send(b,S,E,A);return}let C=Be(f);if(ei(Ht(),b,A),A==="followUp"&&(!C.isIdle()||u.tuiPrompts.length>0)){u.tuiPrompts.enqueue(b,S,E),Sd();return}if(C.isIdle()&&u.tuiPrompts.sending)throw new Le("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Ed(f,b,S,E,A)},async updateQueuedPrompt(f,b,S,E){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.updateQueuedPrompt(b,S,E);return}if(E.kind==="steer"&&Be(f).isIdle())throw new Le("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await u.tuiPrompts.update(b,S,E,(A,C,N)=>Ed(f,A,C,N,"steer"))},async abort(f){if(Me(f),u.selected==="sdk")await u.workspaceSessions.stop();else{let b=Be(f);if(b.isIdle()&&!u.tuiPrompts.sending)return;if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.tools?.cancel(),u.bridge?.breadcrumb?.("cancel",{...u.operation}),u.pi.appendEntry(Tn),b.abort()}},async resume(f,b){if(Me(f),u.selected==="sdk"){await u.workspaceSessions.resume(b);return}let S=Be(f);if(fr(()=>u.hosted?.adapter.assertAdmission(),b,(E,A)=>u.bridge?.reportError?.(E,A)),!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!u.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!S.modelRegistry.hasConfiguredAuth(S.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");u.operation=b;try{u.pi.sendMessage(wa(Oe().messages),{triggerTurn:!0})}catch(E){throw u.operation=void 0,E}},async newSession(f){if(Me(f),u.selected==="sdk"){let E=u.workspaces?.get(u.activeWorkspaceId??"");if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await u.workspaceSessions.reuseBlank(E.path)||await u.workspaceSessions.open(E.path,"new"),await xe();return}let b=Be(f);if(!b.isIdle()||u.tuiPrompts.length>0||u.commandContext===null){await u.workspaceSessions.open(b.cwd,"new"),u.selected="sdk",u.bridge?.publish({type:"snapshot",session:Oe()}),await xe();return}if((await u.commandContext.newSession({withSession:async E=>{u.commandContext=E,u.replacementContext=E,u.replacementSessionId=E.sessionManager.getSessionId(),u.current=E}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await xe()}};h.addWorkspace=u.lifecycle.wrap(h.addWorkspace),h.selectWorkspace=u.lifecycle.wrap(h.selectWorkspace),h.newSessionInWorkspace=u.lifecycle.wrap(h.newSessionInWorkspace),h.removeWorkspace=u.lifecycle.wrap(h.removeWorkspace),h.selectSession=u.lifecycle.wrap(h.selectSession),h.renameSession=u.lifecycle.wrap(h.renameSession),h.deleteSession=u.lifecycle.wrap(h.deleteSession),h.newSession=u.lifecycle.wrap(h.newSession),h.updateConfig=u.lifecycle.wrap(h.updateConfig);try{let f=ua(),b=f&&await ma(Ae(),!0);u.bridge=await Iv(h,Fn,u.telemetry,{localFileGrant:f&&b?{platform:f,key:b}:void 0})}catch(f){throw process.env.PI_WEBAPP_LAUNCHER_NONCE&&c.ui.notify(`pi-webapp-start-error: ${f instanceof Error?f.message:String(f)}`,"error"),f}}if(u.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let m=[],g=null;for(let h of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(yP).filter(Boolean))try{m.push(vP(Er(Ir(h),"dist"),(f,b)=>{let S=String(b??"");["client.js","client.css"].includes(S)&&(g&&clearTimeout(g),g=setTimeout(()=>u.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){u.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${h}: ${String(f)}`})}u.stopPluginWatch=()=>{for(let h of m)h.close();g&&clearTimeout(g)}}let d=await e(u.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${u.bridge.url}`,d?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw u.telemetry?.capture(p,{stage:"open_web",piVersion:wd}),u.bridge||(await u.telemetry?.close(),u.telemetry=null),p}};t.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(c,p)=>l(p)}),t.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(c,p)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(c))throw new Error("Launcher stop receipt ID required");try{await u.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!0})}`,"info")}catch(d){console.error("pi-webapp: plugin shutdown refused the stop request:",d),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!1})}`,"warning")}}}),t.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(c,p)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await p.waitForIdle(),await u.lifecycle.run(async()=>{let d=u.workspaceSessions?.session;d&&(await d.waitForIdle(),await u.workspaceSessions.reload()),await p.reload()}))}})}var WY=Ja;export{WY as default,hP as verifySentryDisabledRelease,M0 as verifySentryNodeRelease};
558
555
 
559
- //# debugId=392fc95c-8b1a-47c8-ae18-972e14ee10b2
556
+ //# debugId=d6f7f3e4-0a03-4e7d-bd6c-922fb146710d