pi-webapp 0.1.31-alpha.5 → 0.1.31

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.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/bin/package-pi-cli.d.mts +1 -0
  4. package/bin/package-pi-cli.mjs +26 -0
  5. package/bin/pi-webapp.mjs +4 -2
  6. package/dist/extension.js +27 -25
  7. package/dist/hosted-recovery.js +3 -1
  8. package/dist/hosted-worker.js +3 -1
  9. package/docs/sentry.md +15 -11
  10. package/package.json +4 -4
  11. package/web/dist/assets/app-CkT84si6.js +2 -0
  12. package/web/dist/assets/app.js +4 -2
  13. package/web/dist/assets/asciidoc-fDuF7HNn.js +2 -0
  14. package/web/dist/assets/bat-CIKKTCO7.js +2 -0
  15. package/web/dist/assets/bibtex-D13O2Wvh.js +2 -0
  16. package/web/dist/assets/c-BxgHfdNM.js +2 -0
  17. package/web/dist/assets/clojure-CiHGeAtp.js +2 -0
  18. package/web/dist/assets/cmake-DmzJtVCe.js +2 -0
  19. package/web/dist/assets/cpp-WTsyTmWk.js +2 -0
  20. package/web/dist/assets/csharp-BusYHIEz.js +2 -0
  21. package/web/dist/assets/css-D-q0lhfR.js +2 -0
  22. package/web/dist/assets/csv-DFLln536.js +2 -0
  23. package/web/dist/assets/dart-CafiI-9_.js +2 -0
  24. package/web/dist/assets/diff-Br1ISN9_.js +2 -0
  25. package/web/dist/assets/dotenv-CIz2XDph.js +2 -0
  26. package/web/dist/assets/elixir-R3IvWmT5.js +2 -0
  27. package/web/dist/assets/erlang-NGps-vi9.js +2 -0
  28. package/web/dist/assets/fish-ByHW6pZw.js +2 -0
  29. package/web/dist/assets/fsharp-BOBx9XdV.js +2 -0
  30. package/web/dist/assets/go-BeHf35-M.js +2 -0
  31. package/web/dist/assets/graphql-Bu7dAtew.js +2 -0
  32. package/web/dist/assets/groovy-zjY2ZfG0.js +2 -0
  33. package/web/dist/assets/haskell-CMvfT32Y.js +2 -0
  34. package/web/dist/assets/hcl-RKiXyu-a.js +2 -0
  35. package/web/dist/assets/html-COcRjUs1.js +2 -0
  36. package/web/dist/assets/html-derivative-C2Epw9Yg.js +2 -0
  37. package/web/dist/assets/http-BtEaP0_p.js +2 -0
  38. package/web/dist/assets/ini-DuzuNcum.js +2 -0
  39. package/web/dist/assets/java-K8yEFi64.js +2 -0
  40. package/web/dist/assets/javascript-D_ijBMSX.js +2 -0
  41. package/web/dist/assets/julia-yApUWuwQ.js +2 -0
  42. package/web/dist/assets/kotlin-BSbocnsc.js +2 -0
  43. package/web/dist/assets/latex-B2rh6wcV.js +2 -0
  44. package/web/dist/assets/less-DrDudO82.js +2 -0
  45. package/web/dist/assets/log-ljR8DmTe.js +2 -0
  46. package/web/dist/assets/lua-DyIUvKwX.js +2 -0
  47. package/web/dist/assets/make-D75dUjYA.js +2 -0
  48. package/web/dist/assets/markdown-CW047eNb.js +2 -0
  49. package/web/dist/assets/mdx-XsqTTZB4.js +2 -0
  50. package/web/dist/assets/nix-CipIrdNI.js +2 -0
  51. package/web/dist/assets/perl-CpGQZpC_.js +2 -0
  52. package/web/dist/assets/php-mDUeg8is.js +2 -0
  53. package/web/dist/assets/plugin-BNln-AV2.js +2 -0
  54. package/web/dist/assets/plugin-BR-ExlfJ.js +2 -0
  55. package/web/dist/assets/plugin-DO3fYZIM.js +2 -0
  56. package/web/dist/assets/powershell-jgDnaG9I.js +2 -0
  57. package/web/dist/assets/proto-BIjSd36w.js +2 -0
  58. package/web/dist/assets/python-D7_Ztkaq.js +2 -0
  59. package/web/dist/assets/r-CJzV5ecV.js +2 -0
  60. package/web/dist/assets/rst-D36AriVO.js +2 -0
  61. package/web/dist/assets/ruby-DfvZI7yF.js +2 -0
  62. package/web/dist/assets/rust-DSBpfBj6.js +2 -0
  63. package/web/dist/assets/scala-C5J7wQ_u.js +2 -0
  64. package/web/dist/assets/scss-Ce0Xtdy1.js +2 -0
  65. package/web/dist/assets/sql-B8q9hRYB.js +2 -0
  66. package/web/dist/assets/svelte-Bbeskamu.js +2 -0
  67. package/web/dist/assets/swift-BYyWkiAC.js +2 -0
  68. package/web/dist/assets/system-verilog-DeQRavVp.js +2 -0
  69. package/web/dist/assets/telemetry-client-CBQBug9X.js +2 -0
  70. package/web/dist/assets/toml-D4Tpftfr.js +2 -0
  71. package/web/dist/assets/vb-CT8kYl35.js +2 -0
  72. package/web/dist/assets/verilog-CRrcH6Pt.js +2 -0
  73. package/web/dist/assets/vue-_U3Asls5.js +2 -0
  74. package/web/dist/assets/xml-DCBoxqhY.js +2 -0
  75. package/web/dist/assets/yaml-jmrW97Mk.js +2 -0
@@ -1,6 +1,8 @@
1
- (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="cd1cd18e-68f9-4639-9f8f-84fe59d27231",r._sentryDebugIdIdentifier="sentry-dbid-cd1cd18e-68f9-4639-9f8f-84fe59d27231")}catch{}})();import{resolve as Se}from"node:path";import{lstat as Z,readdir as _e,rename as ee}from"node:fs/promises";import{join as k}from"node:path";import{createHash as se}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=r=>r.code==="ENOENT";var qe={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var h=r=>se("sha256").update(r).digest("hex");import{constants as M}from"node:fs";import{lstat as ae,mkdir as ce,open as q,rename as le,unlink as z}from"node:fs/promises";import{dirname as fe,join as de}from"node:path";import{randomUUID as ue}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";async function S(r){await ce(r,{recursive:!0,mode:448});let e=await ae(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function w(r,e){let t;try{t=await q(r,M.O_RDONLY|M.O_NONBLOCK|(M.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let s=Buffer.alloc(Math.min(n.size+1,e+1)),i=0;for(;i<s.length;){let a=await t.read(s,i,s.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==n.size)throw new o("invalid_storage","Storage record changed during read");return s.subarray(0,i)}finally{await t.close()}}async function x(r,e=2*1024*1024){let t=await w(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function b(r){let e=await w(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function m(r,e){let t=`${r}.${ue()}.tmp`,n=await q(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await le(t,r);let s;try{s=await q(fe(r),"r"),await s.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await s?.close()}}finally{await z(t).catch(()=>{})}}async function P(r,e,t=2e3){await S(r);let n=de(r,"transaction.lock"),s=Date.now()+t,i;for(;;)try{i=await q(n,"wx",384);break}catch(a){if(a.code!=="EEXIST")throw a;if(Date.now()>=s)throw new o("storage_busy","Plugin storage is locked; stop all writers before recovering an abandoned lock");await pe(10)}try{return await i.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),await e()}finally{await i.close(),await z(n)}}import{lstat as C,mkdir as he,open as B,realpath as K,readdir as F,link as ge,rename as we,unlink as _,copyFile as me,rm as ye}from"node:fs/promises";import{dirname as ve,isAbsolute as V,join as d,relative as X,resolve as be,sep as J,win32 as ke}from"node:path";import{randomUUID as W}from"node:crypto";var j=192*1024*1024,A=512*1024,Q=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Ie(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function Y(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function N(r){if(r&&(!Q(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var H=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,s){this.root=d(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(d(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");N(t.next),N(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let i=t.before;if(n==="committed"&&i&&i.stateRef!==e.stateRef&&await m(d(this.root,"previous.json"),i),n==="committed"){let a=await b(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(d(this.root,"fork.json"))}return await _(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return P(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let s=await b(d(this.root,"fork.json"));if(s&&(s.version!==1||s.stateRef!==t.stateRef||Object.keys(s).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let i=N({...t,generation:e+1,operationId:W()});await S(d(this.root,"states")),await S(d(this.root,"states",i.stateRef)),await m(d(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(d(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==i.stateRef&&await m(d(this.root,"previous.json"),n),await _(d(this.root,"transition.json")),await _(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return P(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=W(),s=d(this.root,"states",n);if(await b(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await m(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=d(this.root,"states",t.stateRef);for(let a of await F(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await w(d(i,a),j))throw new o("invalid_storage","Missing state file");await me(d(i,a),d(s,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return P(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=N(await b(d(this.root,"previous.json")));if(!t&&await w(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let s=[t,n].filter(l=>!!l),i=d(this.root,"states");await S(i);let a=await F(i),c=new Set(s.map(l=>l.stateRef));for(let l of a){if(!Q(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(i,l),p=await C(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await F(u)){let y=await C(d(u,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!y.isFile()||y.isSymbolicLink()||y.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let v=await x(d(u,g),j);if(!v)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let I=v;if(Object.keys(I).some($=>!["requestId","inputHash","nextHash","committed"].includes($))||I.committed!==!0||!/^[a-f0-9]{64}$/.test(I.inputHash)||!/^[a-f0-9]{64}$/.test(I.nextHash)||typeof I.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(v).some(I=>!["revision","schema","value","requestId","inputHash"].includes(I)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(s);for(let l of a)c.has(l)||await ye(d(i,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}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 o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n){return d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let s=Ie(n);return P(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await x(this.statePath(i,e,Y(s.key)),j);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,Y(s.key));if(!Number.isSafeInteger(s.expectedRevision)||s.expectedRevision<0||s.schema!==i.schema||!Object.hasOwn(s,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(s.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(s);if(Buffer.byteLength(c)>j)throw new o("state_too_large","Plugin state exceeds limit");let f=await x(a,j);f&&this.validateState(f);let l=h(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==s.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:s.expectedRevision+1,schema:i.schema,value:s.value,requestId:e.requestId,inputHash:l};return await m(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,s.path),c=s.maxBytes===void 0?A:s.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>A)throw new o("invalid_input","Invalid workspace read limit");let f=await w(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:h(f)}:null}case"workspace.commit":return this.commitFile(i,e,s);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("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 o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||V(t)||ke.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let s=await K(e),i=be(s,t),a=X(s,i);if(!a||a===".."||a.startsWith(`..${J}`)||V(a))throw new o("invalid_path","Workspace path escapes root");let c=s,f=a.split(J);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<f.length-1){if(!n||X(s,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await he(c,{mode:448})}catch(y){if(y.code!=="EEXIST")throw y}p=await C(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await K(ve(i));if(l!==s&&!l.startsWith(s+J))throw new o("invalid_path","Workspace directory changed");return{target:i,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>A||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:s,parent:i}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),f=h(n.text),l=await x(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await B(`${s}.lock`,"wx",384)}catch(g){throw g.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):g}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let g=await w(s,A),y=g?h(g):null;if(l&&y===f)return{hash:f};if(l?.committed||y!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(i,`.plugin-${W()}.tmp`);let v=await B(p,"wx",384);try{await v.writeFile(n.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==i)throw new o("file_conflict","Workspace directory changed during save");let $=await w(s,A);if(($?h($):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ge(p,s)}catch(G){throw G.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):G}await _(p),p=void 0}else await we(p,s),p=void 0;return await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await _(p).catch(()=>{}),await u.close(),await _(`${s}.lock`)}}};var U="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function T(r){let e=[];async function t(n,s=""){let i=await Z(n);if(!i.isDirectory()||i.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await _e(n)).sort()){let c=k(n,a),f=s+a,l=await Z(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await w(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:h(u)})}}}return await t(r),{fingerprint:h(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function te(r,e,t,n){let s=new H(r,e),i=await T(s.root);if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return s.recover()}async function ne(r,e,t,n){let s=new H(r,e),i=s.root;if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await T(i);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await w(k(i,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await b(k(i,"fork.json")),f=await s.active(),l=await b(k(i,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await ee(k(i,"fork.json"),k(i,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function re(r,e,t){if(t!==U||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await T(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let s=n.files.filter(i=>["runtime.lock","transaction.lock"].includes(i.path));for(let i of s){let a=`recovered-${e}-${i.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let i of s)await ee(k(r,i.path),k(r,`recovered-${e}-${i.path}.json`));return await m(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:s,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:s.map(i=>i.path),fingerprint:e}}var[R,ie,E,O,D,...xe]=process.argv.slice(2),Pe=ie&&!xe.length&&(R==="inspect"&&!E&&!O&&!D||R==="recover-locks"&&E&&O&&!D||["recover-fork","reconcile-transition"].includes(R??"")&&E&&O&&D);if(!Pe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
1
+ (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="1cdc12a6-b808-46ff-9738-9ce130403211",r._sentryDebugIdIdentifier="sentry-dbid-1cdc12a6-b808-46ff-9738-9ce130403211")}catch{}})();import{resolve as Se}from"node:path";import{lstat as Z,readdir as _e,rename as ee}from"node:fs/promises";import{join as k}from"node:path";import{createHash as se}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=r=>r.code==="ENOENT";var qe={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var h=r=>se("sha256").update(r).digest("hex");import{constants as M}from"node:fs";import{lstat as ae,mkdir as ce,open as q,rename as le,unlink as z}from"node:fs/promises";import{dirname as fe,join as de}from"node:path";import{randomUUID as ue}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";async function S(r){await ce(r,{recursive:!0,mode:448});let e=await ae(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function w(r,e){let t;try{t=await q(r,M.O_RDONLY|M.O_NONBLOCK|(M.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let s=Buffer.alloc(Math.min(n.size+1,e+1)),i=0;for(;i<s.length;){let a=await t.read(s,i,s.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==n.size)throw new o("invalid_storage","Storage record changed during read");return s.subarray(0,i)}finally{await t.close()}}async function x(r,e=2*1024*1024){let t=await w(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function b(r){let e=await w(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function m(r,e){let t=`${r}.${ue()}.tmp`,n=await q(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await le(t,r);let s;try{s=await q(fe(r),"r"),await s.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await s?.close()}}finally{await z(t).catch(()=>{})}}async function P(r,e,t=2e3){await S(r);let n=de(r,"transaction.lock"),s=Date.now()+t,i;for(;;)try{i=await q(n,"wx",384);break}catch(a){if(a.code!=="EEXIST")throw a;if(Date.now()>=s)throw new o("storage_busy","Plugin storage is locked; stop all writers before recovering an abandoned lock");await pe(10)}try{return await i.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),await e()}finally{await i.close(),await z(n)}}import{lstat as C,mkdir as he,open as B,realpath as K,readdir as F,link as ge,rename as we,unlink as _,copyFile as me,rm as ye}from"node:fs/promises";import{dirname as ve,isAbsolute as V,join as d,relative as X,resolve as be,sep as J,win32 as ke}from"node:path";import{randomUUID as W}from"node:crypto";var j=192*1024*1024,A=512*1024,Q=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Ie(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function Y(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function N(r){if(r&&(!Q(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var H=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,s){this.root=d(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(d(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");N(t.next),N(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let i=t.before;if(n==="committed"&&i&&i.stateRef!==e.stateRef&&await m(d(this.root,"previous.json"),i),n==="committed"){let a=await b(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(d(this.root,"fork.json"))}return await _(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return P(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let s=await b(d(this.root,"fork.json"));if(s&&(s.version!==1||s.stateRef!==t.stateRef||Object.keys(s).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let i=N({...t,generation:e+1,operationId:W()});await S(d(this.root,"states")),await S(d(this.root,"states",i.stateRef)),await m(d(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(d(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==i.stateRef&&await m(d(this.root,"previous.json"),n),await _(d(this.root,"transition.json")),await _(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return P(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=W(),s=d(this.root,"states",n);if(await b(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await m(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=d(this.root,"states",t.stateRef);for(let a of await F(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await w(d(i,a),j))throw new o("invalid_storage","Missing state file");await me(d(i,a),d(s,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return P(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=N(await b(d(this.root,"previous.json")));if(!t&&await w(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let s=[t,n].filter(l=>!!l),i=d(this.root,"states");await S(i);let a=await F(i),c=new Set(s.map(l=>l.stateRef));for(let l of a){if(!Q(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(i,l),p=await C(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await F(u)){let y=await C(d(u,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!y.isFile()||y.isSymbolicLink()||y.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let v=await x(d(u,g),j);if(!v)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let I=v;if(Object.keys(I).some($=>!["requestId","inputHash","nextHash","committed"].includes($))||I.committed!==!0||!/^[a-f0-9]{64}$/.test(I.inputHash)||!/^[a-f0-9]{64}$/.test(I.nextHash)||typeof I.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(v).some(I=>!["revision","schema","value","requestId","inputHash"].includes(I)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(s);for(let l of a)c.has(l)||await ye(d(i,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}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 o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n){return d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let s=Ie(n);return P(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await x(this.statePath(i,e,Y(s.key)),j);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,Y(s.key));if(!Number.isSafeInteger(s.expectedRevision)||s.expectedRevision<0||s.schema!==i.schema||!Object.hasOwn(s,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(s.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(s);if(Buffer.byteLength(c)>j)throw new o("state_too_large","Plugin state exceeds limit");let f=await x(a,j);f&&this.validateState(f);let l=h(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==s.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:s.expectedRevision+1,schema:i.schema,value:s.value,requestId:e.requestId,inputHash:l};return await m(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,s.path),c=s.maxBytes===void 0?A:s.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>A)throw new o("invalid_input","Invalid workspace read limit");let f=await w(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:h(f)}:null}case"workspace.commit":return this.commitFile(i,e,s);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("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 o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||V(t)||ke.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let s=await K(e),i=be(s,t),a=X(s,i);if(!a||a===".."||a.startsWith(`..${J}`)||V(a))throw new o("invalid_path","Workspace path escapes root");let c=s,f=a.split(J);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<f.length-1){if(!n||X(s,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await he(c,{mode:448})}catch(y){if(y.code!=="EEXIST")throw y}p=await C(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await K(ve(i));if(l!==s&&!l.startsWith(s+J))throw new o("invalid_path","Workspace directory changed");return{target:i,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>A||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:s,parent:i}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),f=h(n.text),l=await x(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await B(`${s}.lock`,"wx",384)}catch(g){throw g.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):g}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let g=await w(s,A),y=g?h(g):null;if(l&&y===f)return{hash:f};if(l?.committed||y!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(i,`.plugin-${W()}.tmp`);let v=await B(p,"wx",384);try{await v.writeFile(n.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==i)throw new o("file_conflict","Workspace directory changed during save");let $=await w(s,A);if(($?h($):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ge(p,s)}catch(G){throw G.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):G}await _(p),p=void 0}else await we(p,s),p=void 0;return await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await _(p).catch(()=>{}),await u.close(),await _(`${s}.lock`)}}};var U="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function T(r){let e=[];async function t(n,s=""){let i=await Z(n);if(!i.isDirectory()||i.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await _e(n)).sort()){let c=k(n,a),f=s+a,l=await Z(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await w(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:h(u)})}}}return await t(r),{fingerprint:h(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function te(r,e,t,n){let s=new H(r,e),i=await T(s.root);if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return s.recover()}async function ne(r,e,t,n){let s=new H(r,e),i=s.root;if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await T(i);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await w(k(i,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await b(k(i,"fork.json")),f=await s.active(),l=await b(k(i,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await ee(k(i,"fork.json"),k(i,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function re(r,e,t){if(t!==U||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await T(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let s=n.files.filter(i=>["runtime.lock","transaction.lock"].includes(i.path));for(let i of s){let a=`recovered-${e}-${i.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let i of s)await ee(k(r,i.path),k(r,`recovered-${e}-${i.path}.json`));return await m(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:s,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:s.map(i=>i.path),fingerprint:e}}var[R,ie,E,O,D,...xe]=process.argv.slice(2),Pe=ie&&!xe.length&&(R==="inspect"&&!E&&!O&&!D||R==="recover-locks"&&E&&O&&!D||["recover-fork","reconcile-transition"].includes(R??"")&&E&&O&&D);if(!Pe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
2
2
  inspect BROKER_ROOT
3
3
  recover-locks BROKER_ROOT FINGERPRINT CONFIRMATION
4
4
  reconcile-transition DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
5
5
  recover-fork DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
6
6
  CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=Se(ie),e=R==="inspect"?await T(r):R==="recover-locks"?await re(r,E,O):R==="recover-fork"?await ne(r,E,O,D):await te(r,E,O,D);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var ft=void 0;export{ft as default};
7
+
8
+ //# debugId=1cdc12a6-b808-46ff-9738-9ce130403211
@@ -1 +1,3 @@
1
- (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="2094b07f-ec9c-426e-b651-e96a924176e7",t._sentryDebugIdIdentifier="sentry-dbid-2094b07f-ec9c-426e-b651-e96a924176e7")}catch{}})();import{AsyncLocalStorage as y}from"node:async_hooks";import{pathToFileURL as b}from"node:url";function c(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 l=new y,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(b(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(f,g){let u=l.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,w)=>{s.set(d,{resolve:m,reject:w}),a({type:"broker-request",id:d,invocationId:u.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
1
+ (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="15cc4280-e2ee-45ad-aded-b138e3e4c78a",t._sentryDebugIdIdentifier="sentry-dbid-15cc4280-e2ee-45ad-aded-b138e3e4c78a")}catch{}})();import{AsyncLocalStorage as y}from"node:async_hooks";import{pathToFileURL as b}from"node:url";function c(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 l=new y,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(b(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(f,g){let u=l.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,w)=>{s.set(d,{resolve:m,reject:w}),a({type:"broker-request",id:d,invocationId:u.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
2
+
3
+ //# debugId=15cc4280-e2ee-45ad-aded-b138e3e4c78a
package/docs/sentry.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # Sentry error collection
2
2
 
3
- Browser and extension error reporting are enabled by default with this built-in public DSN:
3
+ **Browser and extension error reporting are disabled by default.** No reporting SDK is loaded and no Sentry events are sent unless `PI_WEB_SENTRY_ENABLED=true` is explicitly set. A DSN alone does not enable reporting, including an inherited DSN override. Opting in uses this built-in public DSN unless overridden:
4
4
 
5
5
  ```text
6
6
  https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800
7
7
  ```
8
8
 
9
- Start Pi and run `/web`; no environment configuration is needed. To override the default destination, set `PI_WEB_SENTRY_DSN` in the **Pi process environment**. Pi does not automatically read `.env`; `.env.example` is a configuration reference.
9
+ Normal startup needs no telemetry configuration. To intentionally opt in, set `PI_WEB_SENTRY_ENABLED=true` in the **Pi process environment** and optionally override `PI_WEB_SENTRY_DSN`. Pi does not automatically read `.env`; `.env.example` is a configuration reference. Previously configured `PI_WEB_SENTRY_ENABLED=true` remains an explicit opt-in; remove it or set it to `false` to stop reporting.
10
10
 
11
11
  ```sh
12
- PI_WEB_SENTRY_DSN='https://PUBLIC_KEY@o123.ingest.sentry.io/123' pi
12
+ PI_WEB_SENTRY_ENABLED=true PI_WEB_SENTRY_DSN='https://PUBLIC_KEY@o123.ingest.sentry.io/123' pi
13
13
  ```
14
14
 
15
15
  Replace the example with your project's public DSN. `PI_WEB_SENTRY_BROWSER_DSN` and `PI_WEB_SENTRY_NODE_DSN` override the common destination; an explicitly empty override disables that side. An explicitly empty common DSN disables both sides unless a per-side DSN overrides it. Use `PI_WEB_SENTRY_ENABLED=false` to disable both regardless of DSN overrides; disabled SDKs are not loaded and no events are sent. `PI_WEB_SENTRY_ENVIRONMENT` defaults to `production`. Restart Pi after changing runtime configuration. The host's `SENTRY_DSN` is deliberately ignored.
16
16
 
17
- ## What is collected
17
+ ## What is collected when explicitly enabled
18
18
 
19
19
  - Browser errors, unhandled rejections, React render failures, HTTP/response parsing failures, invalid NDJSON/protocol events and unexpected connection failures.
20
20
  - Extension request/workspace/configuration failures, asynchronous Agent and tool failures, and provider-login failures. Fatal exceptions attributable to this extension are best effort; process exit can prevent delivery.
@@ -69,7 +69,9 @@ Request failures and asynchronous error events include additive `errorId`, `requ
69
69
 
70
70
  `npm run build` produces matching browser/extension release IDs and debug IDs. It archives bundles/maps in `.sentry-artifacts/<buildId>/` and removes `.map` files from `web/dist` and `dist`. Archive directories are git-ignored and excluded from the npm package. These private files contain application source; store them as access-controlled CI artifacts. Ordinary local builds do not upload or contact Sentry.
71
71
 
72
- For an upload-required release build, provide these **CI-only** variables:
72
+ The current publishing workflow uses an offline, disabled-by-default release mode. It retains TypeScript/tests, private local maps, exact package comparison, release-channel/SHA checks and hash-bound verification receipts. It verifies the packaged Node default is disabled and serves the packaged browser to confirm no reporting SDK or external requests, including after synthetic errors. No Sentry upload, event ingestion or Sentry credentials are required, and no event IDs are fabricated. This does **not** claim live source-map symbolication has been verified for the release. User opt-in reporting is best effort; restoring upload/live verification requires a deliberate workflow change.
73
+
74
+ For an **optional** upload-required build, provide these **CI-only** variables:
73
75
 
74
76
  ```sh
75
77
  export SENTRY_AUTH_TOKEN='YOUR_CI_TOKEN'
@@ -78,11 +80,11 @@ export SENTRY_PROJECT='YOUR_PROJECT'
78
80
  npm run build:sentry
79
81
  ```
80
82
 
81
- Use `SENTRY_BROWSER_PROJECT` / `SENTRY_NODE_PROJECT` for separate projects. The upload-required command fails on missing credentials or upload failure, and still removes maps from public output. Do not publish after a failed command. Auth tokens are never part of runtime configuration. The ordinary npm `prepack` rebuilds locally without uploading; use `npm pack --ignore-scripts` or `npm publish --ignore-scripts` only after checks and a successful `build:sentry` to package the exact uploaded artifacts.
83
+ Use `SENTRY_BROWSER_PROJECT` / `SENTRY_NODE_PROJECT` for separate projects. The upload-required command fails on missing credentials or upload failure, and still removes maps from public output. Do not publish after a failed command. Auth tokens are never part of runtime configuration. The ordinary npm `prepack` rebuilds locally without uploading; use `npm pack --ignore-scripts` or `npm publish --ignore-scripts` only after checks and the appropriate local/offline or upload/live verification to package the exact checked artifacts.
82
84
 
83
- ### Required Actions configuration
85
+ ### Optional live-verification configuration
84
86
 
85
- The publishing workflow now fails closed until both credentials exist:
87
+ The current disabled release does not use these credentials. The optional `build:sentry` / `verify:sentry` path fails closed until both credentials exist:
86
88
 
87
89
  - Repository secret `SENTRY_AUTH_TOKEN`: source-map upload and release permissions.
88
90
  - Repository secret `SENTRY_VERIFY_AUTH_TOKEN`: event/project read permission (`project:read` or equivalent).
@@ -99,8 +101,10 @@ After the uploaded build, run:
99
101
  mkdir -p .ci/release
100
102
  npm pack --ignore-scripts --json --pack-destination .ci/release > .ci/release/pack.json
101
103
  npm run verify:package -- --pack-manifest .ci/release/pack.json
102
- # Requires SENTRY_VERIFY_AUTH_TOKEN, SENTRY_ORG and the destination project(s).
103
- npm run verify:sentry -- --pack-manifest .ci/release/pack.json
104
+ # Current release: no Sentry network/credentials; verify disabled Node/browser defaults.
105
+ node scripts/verify-sentry-release.mjs --telemetry-disabled --pack-manifest .ci/release/pack.json
106
+ # Optional live mode instead: requires uploaded artifacts and Sentry credentials.
107
+ # npm run verify:sentry -- --pack-manifest .ci/release/pack.json
104
108
  node scripts/publish-verified-release.mjs
105
109
  ```
106
110
 
@@ -108,7 +112,7 @@ node scripts/publish-verified-release.mjs
108
112
 
109
113
  `verify:sentry` first checks credentials and the package, then invokes the packaged Node verification entry and serves the packaged browser assets on loopback with synthetic configuration. It sends only synthetic events to the configured Sentry DSNs with `environment=sentry-verification`; normal imports and normal browser environments do not run these probes. The Node entry requires `PI_WEB_SENTRY_VERIFY_RELEASE=true` and the verification environment; the browser requires a verification-configured server and the explicit `sentry_release_probe=1` URL flag. The CLI sets up these guards itself.
110
114
 
111
- The verifier waits at most 120 seconds for the real events, checks release/build/side/Debug IDs, and requires original application frames to resolve to TypeScript. The synthetic exception must resolve to the exact source file and line recorded in the archived map. Browser maps give application sources stable `app:///src/` and `app:///web/src/` paths before upload. Unmapped external SDK dependencies do not invalidate resolved application frames. A successful run writes `.ci/release/verified.json` with event IDs and the tarball SHA-256. The publisher verifies that receipt and hash before publishing that tarball with lifecycle scripts disabled. Missing credentials, failed uploads, mismatched package assets, unmapped application frames, missing receipts, or changed tarballs block publication. Version synchronization to main occurs only after these checks succeed.
115
+ The verifier waits at most 120 seconds for the real events, checks release/build/side/Debug IDs, and requires original application frames to resolve to TypeScript. The synthetic exception must resolve to the exact source file and line recorded in the archived map. Browser maps give application sources stable `app:///src/` and `app:///web/src/` paths before upload. Unmapped external SDK dependencies do not invalidate resolved application frames. A successful run writes `.ci/release/verified.json` with event IDs and the tarball SHA-256. The publisher verifies the receipt's explicit mode and tarball hash before publishing with lifecycle scripts disabled. Live mode requires real-format Node/browser event IDs; disabled mode requires successful Node/browser disabled checks and forbids event IDs. Missing receipts, unknown modes, failed checks or changed tarballs block publication. Missing credentials, failed uploads and unmapped frames additionally block the optional live path. Release versions are chosen for the artifact only; there is no version-only main commit.
112
116
 
113
117
  For mapping failures, use Sentry's event source-map debugger or its `source-map-debug` API, and inspect matching Debug IDs for application bundles. Old tool-result events without original stacks remain limited even after source maps are uploaded.
114
118
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.31-alpha.5",
3
+ "version": "0.1.31",
4
4
  "type": "module",
5
5
  "piWebappDesktopProtocol": 1,
6
6
  "piWebappDataVersion": 1,
@@ -29,7 +29,7 @@
29
29
  "pi-webapp": "./bin/pi-webapp.mjs"
30
30
  },
31
31
  "pi": {
32
- "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.31-alpha.5/assets/cover-webapp.png",
32
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.31/assets/cover-webapp.png",
33
33
  "extensions": [
34
34
  "./dist/extension.js"
35
35
  ]
@@ -85,8 +85,8 @@
85
85
  "access": "public"
86
86
  },
87
87
  "peerDependencies": {
88
- "@earendil-works/pi-ai": "*",
89
- "@earendil-works/pi-coding-agent": "*"
88
+ "@earendil-works/pi-ai": "1.3.0",
89
+ "@earendil-works/pi-coding-agent": "1.3.0"
90
90
  },
91
91
  "devDependencies": {
92
92
  "@chengzhiyi/pi-web-protocol": "0.1.1",
@@ -540,3 +540,5 @@ XID_Start XIDS`.split(/\s/).map(t=>[Sp(t),t])),joe=new Map([["s",Zn(383)],[Zn(38
540
540
  `),c.push(h);const d=iT(a);return d!==null&&c.push(`
541
541
  `,d),this.lastText=e,this.lastRendered=c,this.lastRendered}}const Mce=T.memo(function({text:e,streaming:n=!1,labels:r,fileMentions:i,pathImages:s,variant:o="body"}){const a=T.useRef(null),c=T.useRef(r),d=T.useMemo(()=>n?((a.current===null||c.current!==r)&&(a.current=new jce(r),c.current=r),a.current.render(e)):(a.current=null,Ice(e,r,i,s)),[e,n,r,i,s]);return f.jsx("div",{className:_t(qr.markdown,o==="compact"&&qr.compact),"data-markdown-variant":o==="compact"?o:void 0,children:d})});function Og(t,e){throw new Error(`${e}: unhandled ${JSON.stringify(t)}`)}function Hl(t,e){const n=t.nodes[e];if(n===void 0)throw new Error(`layout: unknown node ${e}`);return n}function Kt(t,e){const n=Hl(t,e);if(n.kind!=="pane")throw new Error(`layout: ${e} is not a pane`);return n}function Fg(t,e){const n=Hl(t,e);if(n.kind!=="split")throw new Error(`layout: ${e} is not a split`);return n}function hu(t,e){const n=t.tabs[e];if(n===void 0)throw new Error(`layout: unknown tab ${e}`);return n}function _1(t){if(t.host!=="float"||t.rect===void 0)throw new Error(`layout: ${t.id} is not floating`);return t.rect}function Bg(t,e){const n=t.floats.indexOf(e);if(n<0)throw new Error(`layout: floating pane ${e} is not in the z order`);return n}function Ace(t){const e=t.tabs[0];if(e===void 0||t.tabs.length!==1)throw new Error(`layout: ${t.id} does not hold exactly one tab`);return e}function Hg(t,e){for(const n of Object.values(t.nodes))if(n.kind==="split"&&n.children.includes(e))return n}function ms(t,e){for(const n of Object.values(t.nodes))if(n.kind==="pane"&&n.tabs.includes(e))return n;throw new Error(`layout: tab ${e} has no pane`)}function Tp(t){const e=[],n=r=>{const i=Hl(t,r);if(i.kind==="pane"){e.push(i.id);return}for(const s of i.children)n(s)};return n(t.rootId),e}function sT(t){const e=t.reduce((n,r)=>n+r,0);if(!(e>0))throw new Error("layout: sizes must sum above zero");return Math.abs(e-1)<1e-12?[...t]:t.map(n=>n/e)}function t1(t){return Object.entries(t)}function Lce(t){return Object.keys(t)}function Pn(t,e){const n={};for(const[r,i]of t1(t.nodes))r in e||(n[r]=i);for(const[r,i]of t1(e))i!==null&&(n[r]=i);return{...t,nodes:n}}function El(t,e){const n={};for(const[r,i]of t1(t.tabs))r in e||(n[r]=i);for(const[r,i]of t1(e))i!==null&&(n[r]=i);return{...t,tabs:n}}function La(t,e,n){const r=Math.max(0,Math.min(e,t.length));return[...t.slice(0,r),n,...t.slice(r)]}function Rs(t,e){return[...t.slice(0,e),...t.slice(e+1)]}function qg(t,e){const n=Rs(t,e);if(n.length!==0)return n[Math.max(0,e-1)]}function ql(t,e,n){return{...t,tabs:e,activeTabId:n}}function Wg(t,e,n){const r=Hg(t,e);if(r===void 0){if(t.rootId!==e)throw new Error(`layout: ${e} is neither rooted nor parented`);return{...t,rootId:n}}const i=r.children.map(s=>s===e?n:s);return Pn(t,{[r.id]:{...r,children:i}})}function oT(t,e){let n=Hl(t,t.rootId);for(;n.kind==="split";){const r=e(n);if(r===void 0)throw new Error(`layout: split ${n.id} has no children`);n=Hl(t,r)}return n.id}function aT(t){return oT(t,e=>e.children[0])}function Pce(t){return oT(t,e=>e.axis==="row"?e.children.at(-1):e.children[0])}function Ci(t,e){const n={};for(const r of e)n[r]=Kt(t,r).activeTabId;return{type:"restoreFocus",activePaneId:t.activePaneId,floats:t.floats,paneActiveTabs:n}}function Vg(t,e){return[...t.filter(n=>n!==e),e]}function Ih(t,e){return t.activePaneId!==e?t:{...t,activePaneId:aT(t)}}function zce(t){return{kind:"pane",id:t,host:"dock",tabs:[],activeTabId:void 0,rect:void 0}}function Lf(t,e){if(t.nodes[e]!==void 0)throw new Error(`layout: node ${e} already exists`)}function Ug(t,e){if(t.tabs[e]!==void 0)throw new Error(`layout: tab ${e} already exists`)}function Rce(t,e){if(Kt(t,e.paneId).host!=="dock")throw new Error("layout: split requires a docked pane");Lf(t,e.newPaneId);const r=zce(e.newPaneId),i=Hg(t,e.paneId);if(i!==void 0&&i.axis===e.axis){const a=i.children.indexOf(e.paneId),c=e.direction==="after"?a+1:a,d=La(i.children,c,e.newPaneId),h=i.sizes.flatMap((p,g)=>g===a?[p/2,p/2]:[p]);return{state:Pn(t,{[e.newPaneId]:r,[i.id]:{...i,children:d,sizes:h}}),inverse:[{type:"merge",paneId:e.newPaneId},{type:"resize",splitId:i.id,sizes:i.sizes}]}}Lf(t,e.newSplitId);const s=Wg(t,e.paneId,e.newSplitId),o=e.direction==="after"?[e.paneId,e.newPaneId]:[e.newPaneId,e.paneId];return{state:Pn(s,{[e.newPaneId]:r,[e.newSplitId]:{kind:"split",id:e.newSplitId,axis:e.axis,children:o,sizes:[.5,.5]}}),inverse:[{type:"merge",paneId:e.newPaneId}]}}function Dce(t,e){const n=Kt(t,e.paneId);if(n.tabs.length>0)throw new Error("layout: merge requires an empty pane");const r=Ci(t,[]);if(n.host==="float"){const c=Bg(t,e.paneId),d=Pn({...t,floats:Rs(t.floats,c)},{[e.paneId]:null});return{state:Ih(d,e.paneId),inverse:[{type:"insertPane",pane:n,tabs:[],attach:{mode:"float",index:c}},r]}}const i=Hg(t,e.paneId);if(i===void 0)throw new Error("layout: the docked root pane cannot be merged");const s=i.children.indexOf(e.paneId);if(i.children.length>2){const c=Rs(i.children,s),d=sT(Rs(i.sizes,s)),h=Pn(t,{[e.paneId]:null,[i.id]:{...i,children:c,sizes:d}});return{state:Ih(h,e.paneId),inverse:[{type:"insertPane",pane:n,tabs:[],attach:{mode:"child",parentId:i.id,index:s,sizes:i.sizes}},r]}}const o=i.children[1-s];if(o===void 0)throw new Error("layout: merge found a split without a sibling");const a=Pn(Wg(t,i.id,o),{[e.paneId]:null,[i.id]:null});return{state:Ih(a,e.paneId),inverse:[{type:"insertPane",pane:n,tabs:[],attach:{mode:"wrap",targetId:o,split:i}},r]}}function Oce(t,e){const n=Kt(t,e.paneId);if(n.host!=="dock")throw new Error("layout: openTab requires a docked pane");Ug(t,e.tab.id);const r=Ci(t,[n.id]);return{state:{...Pn(El(t,{[e.tab.id]:e.tab}),{[n.id]:ql(n,La(n.tabs,e.index,e.tab.id),e.tab.id)}),activePaneId:n.id},inverse:[{type:"closeTab",tabId:e.tab.id},r]}}function Fce(t,e){const n=Kt(t,e.paneId);if(n.host!=="dock")throw new Error("layout: insertTab requires a docked pane");Ug(t,e.tab.id);const r=Ci(t,[n.id]),i=La(n.tabs,e.index,e.tab.id);return{state:Pn(El(t,{[e.tab.id]:e.tab}),{[n.id]:ql(n,i,n.activeTabId??e.tab.id)}),inverse:[{type:"closeTab",tabId:e.tab.id},r]}}function Bce(t,e){const n=hu(t,e.tabId),r=ms(t,e.tabId),i=r.tabs.indexOf(e.tabId),s=Ci(t,[r.id]);if(r.host==="float"){const a=Bg(t,r.id),c=El(Pn({...t,floats:Rs(t.floats,a)},{[r.id]:null}),{[e.tabId]:null});return{state:Ih(c,r.id),inverse:[{type:"insertPane",pane:r,tabs:[n],attach:{mode:"float",index:a}},s]}}const o=r.activeTabId===e.tabId?qg(r.tabs,i):r.activeTabId;return{state:El(Pn(t,{[r.id]:ql(r,Rs(r.tabs,i),o)}),{[e.tabId]:null}),inverse:[{type:"insertTab",paneId:r.id,tab:n,index:i},s]}}function Hce(t,e){if(Lf(t,e.pane.id),e.pane.tabs.length!==e.tabs.length)throw new Error("layout: insertPane tab records do not match the pane");if(e.pane.host==="dock"&&e.tabs.length>0)throw new Error("layout: insertPane returns a docked pane empty");const n={};for(const o of e.tabs)Ug(t,o.id),n[o.id]=o;const r=e.tabs[0],i=r===void 0?[{type:"merge",paneId:e.pane.id}]:[{type:"closeTab",tabId:r.id},Ci(t,[])],s=e.attach;switch(s.mode){case"child":{const o=Fg(t,s.parentId),a=La(o.children,s.index,e.pane.id);if(s.sizes.length!==a.length)throw new Error("layout: insertPane sizes do not match the split");return i.push({type:"resize",splitId:o.id,sizes:o.sizes}),{state:Pn(El(t,n),{[e.pane.id]:e.pane,[o.id]:{...o,children:a,sizes:s.sizes}}),inverse:i}}case"wrap":{if(!s.split.children.includes(e.pane.id))throw new Error("layout: insertPane wrap split does not list the pane");const o=Wg(t,s.targetId,s.split.id);return{state:Pn(El(o,n),{[e.pane.id]:e.pane,[s.split.id]:s.split}),inverse:i}}case"float":{if(e.pane.host!=="float")throw new Error("layout: float attachment requires a floating pane");const o=La(t.floats,s.index,e.pane.id);return{state:Pn(El({...t,floats:o},n),{[e.pane.id]:e.pane}),inverse:i}}default:return Og(s,"layout: insertPane attachment")}}function qce(t,e){const n=ms(t,e.tabId);if(n.host!=="dock")throw new Error("layout: moveTab source must be docked; use unfloat");const r=Kt(t,e.toPaneId);if(r.host!=="dock")throw new Error("layout: moveTab target must be docked");if(r.id===n.id)throw new Error("layout: moveTab across one pane; use reorderTab");const i=n.tabs.indexOf(e.tabId),s=Ci(t,[n.id,r.id]),o=n.activeTabId===e.tabId?qg(n.tabs,i):n.activeTabId;return{state:{...Pn(t,{[n.id]:ql(n,Rs(n.tabs,i),o),[r.id]:ql(r,La(r.tabs,e.index,e.tabId),e.tabId)}),activePaneId:r.id},inverse:[{type:"moveTab",tabId:e.tabId,toPaneId:n.id,index:i},s]}}function Wce(t,e){const n=ms(t,e.tabId),r=n.tabs.indexOf(e.tabId),i=La(Rs(n.tabs,r),e.index,e.tabId);return{state:Pn(t,{[n.id]:{...n,tabs:i}}),inverse:[{type:"reorderTab",tabId:e.tabId,index:r}]}}function Vce(t,e){const n=ms(t,e.tabId),r=Ci(t,[n.id]),i=Pn(t,{[n.id]:{...n,activeTabId:e.tabId}}),s=n.host==="float"?Vg(i.floats,n.id):i.floats;return{state:{...i,activePaneId:n.id,floats:s},inverse:[r]}}function Uce(t,e){const n=Kt(t,e.paneId),r=Ci(t,[]),i=n.host==="float"?Vg(t.floats,n.id):t.floats;return{state:{...t,activePaneId:n.id,floats:i},inverse:[r]}}function Gce(t,e){const n=Fg(t,e.splitId);if(e.sizes.length!==n.children.length)throw new Error("layout: resize sizes do not match the split");if(e.sizes.some(r=>!(r>0)))throw new Error("layout: resize sizes must all be above zero");return{state:Pn(t,{[n.id]:{...n,sizes:sT(e.sizes)}}),inverse:[{type:"resize",splitId:n.id,sizes:n.sizes}]}}function Kce(t,e){hu(t,e.tabId);const n=ms(t,e.tabId);if(n.host!=="dock")throw new Error("layout: float requires a docked tab");Lf(t,e.newPaneId);const r=n.tabs.indexOf(e.tabId),i=Ci(t,[n.id]),s=n.activeTabId===e.tabId?qg(n.tabs,r):n.activeTabId,o=Pn(t,{[n.id]:ql(n,Rs(n.tabs,r),s),[e.newPaneId]:{kind:"pane",id:e.newPaneId,host:"float",tabs:[e.tabId],activeTabId:e.tabId,rect:e.rect}});return{state:{...o,floats:[...o.floats,e.newPaneId],activePaneId:e.newPaneId},inverse:[{type:"unfloat",paneId:e.newPaneId,toPaneId:n.id,index:r},i]}}function Zce(t,e){const n=Kt(t,e.paneId),r=_1(n),i=Ace(n),s=Kt(t,e.toPaneId);if(s.host!=="dock")throw new Error("layout: unfloat target must be docked");const o=Ci(t,[s.id]);return{state:{...Pn({...t,floats:Rs(t.floats,Bg(t,e.paneId))},{[e.paneId]:null,[s.id]:ql(s,La(s.tabs,e.index,i),i)}),activePaneId:s.id},inverse:[{type:"float",tabId:i,newPaneId:e.paneId,rect:r},o]}}function lT(t,e,n){const r=Pn(t,{[e.id]:{...e,rect:n}});return{...r,activePaneId:e.id,floats:Vg(r.floats,e.id)}}function Xce(t,e){const n=Kt(t,e.paneId),r=_1(n);return{state:lT(t,n,{...r,x:e.x,y:e.y}),inverse:[{type:"moveFloat",paneId:e.paneId,x:r.x,y:r.y},Ci(t,[])]}}function Yce(t,e){const n=Kt(t,e.paneId),r=_1(n);if(!(e.rect.width>0)||!(e.rect.height>0))throw new Error("layout: float size must be above zero");return{state:lT(t,n,e.rect),inverse:[{type:"resizeFloat",paneId:e.paneId,rect:r},Ci(t,[])]}}function Qce(t,e){const n=Ci(t,Lce(e.paneActiveTabs));for(const i of e.floats)if(Kt(t,i).host!=="float")throw new Error(`layout: restoreFocus lists docked pane ${i} as floating`);let r=t;for(const[i,s]of t1(e.paneActiveTabs)){const o=Kt(r,i);r=Pn(r,{[i]:{...o,activeTabId:s}})}return Kt(r,e.activePaneId),{state:{...r,activePaneId:e.activePaneId,floats:e.floats},inverse:[n]}}function w1(t,e){switch(e.type){case"split":return Rce(t,e);case"merge":return Dce(t,e);case"openTab":return Oce(t,e);case"insertTab":return Fce(t,e);case"closeTab":return Bce(t,e);case"insertPane":return Hce(t,e);case"moveTab":return qce(t,e);case"reorderTab":return Wce(t,e);case"focusTab":return Vce(t,e);case"focusPane":return Uce(t,e);case"resize":return Gce(t,e);case"float":return Kce(t,e);case"unfloat":return Zce(t,e);case"moveFloat":return Xce(t,e);case"resizeFloat":return Yce(t,e);case"setExpanded":return{state:{...t,expanded:e.expanded},inverse:[{type:"setExpanded",expanded:t.expanded}]};case"setMode":return{state:{...t,mode:e.mode},inverse:[{type:"setMode",mode:t.mode}]};case"restoreFocus":return Qce(t,e);default:return Og(e,"layout: operation")}}function Jce(t,e){return e.reduce((n,r)=>w1(n,r).state,t)}const eue={entries:[],cursor:0},tue=new Set(["focusTab","focusPane","restoreFocus"]);function nue(t){return tue.has(t.type)}function Pf(t,e){const n=t.entries[e];return n!==void 0&&n.ops.every(nue)}function cT(t){return t.cursor>0}function uT(t){return t.cursor<t.entries.length}function rue(t){return t.entries.flatMap(e=>e.ops)}function iue(t,e,n){if(n.length===0)return{history:t,state:e};let r=e;const i=[];for(const o of n){const a=w1(r,o);r=a.state,i.unshift(...a.inverse)}return{history:{entries:[...t.cursor===t.entries.length?t.entries:t.entries.slice(0,t.cursor),{ops:n,inverse:i}],cursor:t.cursor+1},state:r}}function sue(t,e){if(!cT(t))return;let n=1;if(Pf(t,t.cursor-1))for(;Pf(t,t.cursor-1-n);)n+=1;let r=e;for(const i of t.entries.slice(t.cursor-n,t.cursor).reverse())for(const s of i.inverse)r=w1(r,s).state;return{history:{entries:t.entries,cursor:t.cursor-n},state:r}}function oue(t,e){if(!uT(t))return;let n=1;if(Pf(t,t.cursor))for(;Pf(t,t.cursor+n);)n+=1;let r=e;for(const i of t.entries.slice(t.cursor,t.cursor+n))for(const s of i.ops)r=w1(r,s).state;return{history:{entries:t.entries,cursor:t.cursor+n},state:r}}class aue{constructor(e){q(this,"current");q(this,"recorded",eue);this.current=e}get state(){return this.current}get history(){return this.recorded}get ops(){return rue(this.recorded)}get cursor(){return this.recorded.cursor}get canUndo(){return cT(this.recorded)}get canRedo(){return uT(this.recorded)}dispatch(e){return this.dispatchAll([e])}dispatchAll(e){const n=iue(this.recorded,this.current,e);return this.recorded=n.history,this.current=n.state,this.current}undo(){const e=sue(this.recorded,this.current);return e===void 0?!1:(this.recorded=e.history,this.current=e.state,!0)}redo(){const e=oue(this.recorded,this.current);return e===void 0?!1:(this.recorded=e.history,this.current=e.state,!0)}}const lue=4,dT=.12,O5={width:380,height:300},cue={width:220,height:140},hT=.25;function uue(t){return Tp(t).length}function Gg(t){return uue(t)<lue}function due(t,e,n=hT){let r="left",i=t;return 1-t<i&&(r="right",i=1-t),e<i&&(r="top",i=e),1-e<i&&(r="bottom",i=1-e),i<n?r:"center"}function hue(t){switch(t){case"center":return;case"left":return{axis:"row",direction:"before"};case"right":return{axis:"row",direction:"after"};case"top":return{axis:"column",direction:"before"};case"bottom":return{axis:"column",direction:"after"};default:return Og(t,"layout: dock zone")}}function fT(t,e=dT){if(t.length===0)return[];const n=Math.min(e,1/t.length),r=t.map(a=>a>0?a:0),i=r.reduce((a,c)=>a+c,0);let s=i>0?r.map(a=>a/i):r.map(()=>1/t.length);const o=new Set;for(;;){const a=s.flatMap((h,p)=>!o.has(p)&&h<n?[p]:[]);if(a.length===0)return s;for(const h of a)o.add(h);const c=1-o.size*n,d=s.reduce((h,p,g)=>o.has(g)?h:h+p,0);s=s.map((h,p)=>o.has(p)?n:h/d*c)}}function F5(t,e,n){return e>=t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height}function fue(t,e,n,r=hT){return!(t.width>0)||!(t.height>0)?"center":due((e-t.x)/t.width,(n-t.y)/t.height,r)}function pue(t,e){let n=0;for(const r of t){if(e<r.x+r.width/2)break;n+=1}return n}const tu={divider:0,chip:100,body:48};function mue(t,e=tu){const{pane:n,strip:r}=t;if(!(n.width>0)||!(n.height>0)||!(r.width>0))return{row:!0,column:!0};const i=Math.max(0,n.width-r.width),s=Math.max(0,r.width-t.chipsWidth-t.fillWidth-(t.splitControlWidth??0)),o=(n.width-e.divider)/2-i,a=(n.height-e.divider)/2-i;return{row:o>=s+e.chip,column:a>=r.height+e.body}}const x_=4;function gue(t,e,n,r){return Math.abs(n-t)>=x_||Math.abs(r-e)>=x_}function yue(t,e,n){const r=t[e],i=t[e+1];if(r===void 0||i===void 0)return[...t];const s=[...t];return s[e]=r+n,s[e+1]=i-n,s}function vue(t,e,n){return{...t,x:t.x+e,y:t.y+n}}function bue(t,e,n,r){return{...t,width:Math.max(r.width,t.width+e),height:Math.max(r.height,t.height+n)}}function xue(t,e,n){return{x:Math.max(0,t-__.x),y:Math.max(0,e-__.y),...n}}const __={x:60,y:14},_ue=24,w_={x:160,y:120},Hi=[];function wue(t,e,n,r){for(const i of Kt(t,e).tabs){const s=t.tabs[i];if((s==null?void 0:s.contentId)===n&&(r===void 0||s.kind===r))return i}}function kue(t,e,n){for(const r of[...Tp(t),...t.floats]){const i=wue(t,r,e,n);if(i!==void 0)return i}}function fu(t){const e=Kt(t,t.activePaneId);return e.host==="dock"?e.id:aT(t)}function B5(t,e,n,r){return t.host==="float"?{type:"unfloat",paneId:t.id,toPaneId:n,index:r}:{type:"moveTab",tabId:e,toPaneId:n,index:r}}function Cue(t,e){return t.expanded===e?Hi:[{type:"setExpanded",expanded:e}]}function Sue(t,e){return t.mode===e?Hi:[{type:"setMode",mode:e}]}function Eue(t,e,n,r){if(!Gg(t))return Hi;const i=n??fu(t);if(Kt(t,i).host!=="dock")return Hi;const s=e("pane"),o=[{type:"split",paneId:i,axis:"row",direction:"after",newPaneId:s,newSplitId:e("split")}],a=r==null?void 0:r(e("tab"));return a!==void 0&&o.push({type:"openTab",paneId:s,tab:a,index:0}),o}function $ue(t,e,n,r){if(r===void 0)return Hi;const i=Kt(t,n);return i.host!=="dock"?Hi:[{type:"openTab",paneId:n,tab:r(e("tab")),index:i.tabs.length}]}function Tue(t,e,n){const r=n.revealIfOpened===!1?void 0:kue(t,n.contentId,n.kind);if(r!==void 0)return{ops:[{type:"focusTab",tabId:r}],tabId:r};const i=n.paneId??fu(t),s={id:e("tab"),kind:n.kind,contentId:n.contentId,title:n.title};return{ops:[{type:"openTab",paneId:i,tab:s,index:n.index??Kt(t,i).tabs.length}],tabId:s.id}}function Nue(t,e,n){const r=hu(t,n),i=ms(t,n),s=i.host==="dock"?i.id:fu(t),o=i.host==="dock"?i.tabs.indexOf(n)+1:Kt(t,s).tabs.length,a={...r,id:e("tab")};return{ops:[{type:"openTab",paneId:s,tab:a,index:o}],tabId:a.id}}function Iue(t,e,n,r){const i=ms(t,e);if(Kt(t,n).host!=="dock")return Hi;if(i.id===n){const s=i.tabs.indexOf(e),o=r>s?r-1:r;return o===s?Hi:[{type:"reorderTab",tabId:e,index:o}]}return[B5(i,e,n,r)]}function jue(t,e,n,r,i,s){const o=ms(t,n),a=Kt(t,r);if(a.host!=="dock")return Hi;const c=hue(i);if(c===void 0)return o.id===r?Hi:[B5(o,n,r,a.tabs.length)];if(o.id===r&&o.tabs.length===1&&s===void 0||!Gg(t))return Hi;const h=e("pane"),p=[{type:"split",paneId:r,axis:c.axis,direction:c.direction,newPaneId:h,newSplitId:e("split")}];return p.push(B5(o,n,h,0)),p}function Mue(t,e,n,r){const i=t.floats.length*_ue,s=e("float");return{ops:[{type:"float",tabId:n,newPaneId:s,rect:r??{x:w_.x+i,y:w_.y+i,width:O5.width,height:O5.height}}],paneId:s}}function Aue(t,e,n){const r=n??fu(t);return[{type:"unfloat",paneId:e,toPaneId:r,index:Kt(t,r).tabs.length}]}function Lue(t,e,n){return[{type:"resize",splitId:t,sizes:fT(e,n)}]}function Pue(t,e,n){const r=[];let i=t;for(;;){const o=Tp(i).find(c=>c!==i.rootId&&Kt(i,c).tabs.length===0);if(o===void 0)break;const a={type:"merge",paneId:o};r.push(a),i=w1(i,a).state}const s=Hl(i,i.rootId);return s.kind==="pane"&&s.tabs.length===0&&n!==void 0&&r.push({type:"openTab",paneId:s.id,tab:n(e("tab")),index:0}),r}function zue(t=0){let e=t;return{next:(r=>(e+=1,`${r}${e}`))}}function Rue(t,e,n="push"){const r=t.next("pane"),i=e==null?void 0:e(t.next("tab"));return{nodes:{[r]:{kind:"pane",id:r,host:"dock",tabs:i===void 0?[]:[i.id],activeTabId:i==null?void 0:i.id,rect:void 0}},tabs:i===void 0?{}:{[i.id]:i},rootId:r,floats:[],activePaneId:r,expanded:!1,mode:n}}class Due{constructor(e={}){q(this,"minter");q(this,"sequencer");q(this,"listeners",new Set);q(this,"makePaneTab");q(this,"snapshot");q(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}));q(this,"getSnapshot",()=>this.snapshot);this.minter=zue(),this.makePaneTab=e.makePaneTab,this.sequencer=new aue(Rue(this.minter,e.makeInitialTab,e.mode)),this.snapshot=this.buildSnapshot()}get ops(){return this.sequencer.ops}buildSnapshot(){const e=this.sequencer.state;return{state:e,canUndo:this.sequencer.canUndo,canRedo:this.sequencer.canRedo,canSplit:Gg(e),opCount:this.sequencer.ops.length,cursor:this.sequencer.cursor}}commit(){this.snapshot=this.buildSnapshot();for(const e of[...this.listeners])e()}get state(){return this.sequencer.state}get mint(){return this.minter.next}run(e,n=!1){if(e.length===0)return!1;if(n){const r=Jce(this.state,e);e=[...e,...Pue(r,this.mint,r.floats.length>0?this.makePaneTab:void 0)]}return this.sequencer.dispatchAll(e),this.commit(),!0}setExpanded(e){this.run(Cue(this.state,e))}toggleExpanded(){this.setExpanded(!this.state.expanded)}setMode(e){this.run(Sue(this.state,e))}splitPane(e){return this.run(Eue(this.state,this.mint,e,this.makePaneTab))}addTab(e){return this.run($ue(this.state,this.mint,e,this.makePaneTab))}openContent(e){const n=Tue(this.state,this.mint,e);return this.run(n.ops),n.tabId}duplicateTab(e){const n=Nue(this.state,this.mint,e);return this.run(n.ops),n.tabId}closeTab(e){this.run([{type:"closeTab",tabId:e}],!0)}focusTab(e){this.run([{type:"focusTab",tabId:e}])}focusPane(e){this.run([{type:"focusPane",paneId:e}])}reorderTab(e,n){this.run([{type:"reorderTab",tabId:e,index:n}])}placeTab(e,n,r){return this.run(Iue(this.state,e,n,r),!0)}dropTab(e,n,r){return this.run(jue(this.state,this.mint,e,n,r),!0)}floatTab(e,n){const r=Mue(this.state,this.mint,e,n);return this.run(r.ops,!0),r.paneId}unfloatPane(e,n){this.run(Aue(this.state,e,n))}moveFloat(e,n,r){this.run([{type:"moveFloat",paneId:e,x:n,y:r}])}resizeFloat(e,n){this.run([{type:"resizeFloat",paneId:e,rect:n}])}resizeSplit(e,n){this.run(Lue(e,n))}undo(){return this.sequencer.undo()?(this.commit(),!0):!1}redo(){return this.sequencer.redo()?(this.commit(),!0):!1}activeDockPaneId(){return fu(this.state)}}const Oue={x:0,y:0,width:0,height:0},Fue={row:!0,column:!0};function dh(t){return t===null?Oue:t.getBoundingClientRect()}function Lc(t){const e=Number.parseFloat(t);return Number.isFinite(e)?e:0}function pT(t){const e=[];for(const n of t.querySelectorAll("[data-dockkit-pane]")){const r=n.dataset.dockkitPane;r!==void 0&&e.push([r,n])}return e}function Bue(t){const e=t.querySelector("[data-dockkit-tab]");if(e===null)return tu.chip;const n=getComputedStyle(e),r=Lc(n.minWidth);return r<=0?tu.chip:n.boxSizing==="border-box"?r:r+Lc(n.paddingLeft)+Lc(n.paddingRight)+Lc(n.borderLeftWidth)+Lc(n.borderRightWidth)}function Hue(t){const e=t.querySelector("[data-dockkit-divider]");if(e===null)return tu.divider;const{width:n,height:r}=e.getBoundingClientRect(),i=Math.min(n,r);return i>0?i:tu.divider}function que(t){const e=t.querySelector("[data-dockkit-split-button]");if(e===null)return 0;const n=e.getBoundingClientRect().width;if(!(n>0))return 0;const r=t.querySelector("[data-dockkit-strip]");return n+(r===null?0:Lc(getComputedStyle(r).columnGap))}function Wue(t,e=!1){const n={divider:Hue(t),chip:Bue(t),body:tu.body},r=new Map;for(const[i,s]of pT(t))r.set(i,mue({pane:dh(s),strip:dh(s.querySelector("[data-dockkit-strip]")),chipsWidth:dh(s.querySelector("[data-dockkit-strip-tabs]")).width,fillWidth:dh(s.querySelector("[data-dockkit-strip-fill]")).width,splitControlWidth:e?que(s):0},n));return r}function H5(t,e){return t.get(e)??Fue}function Vue(t,e){if(t.size!==e.size)return!1;for(const[n,r]of t){const i=e.get(n);if(i===void 0||i.row!==r.row||i.column!==r.column)return!1}return!0}function Uue(t,e){typeof t.setPointerCapture=="function"&&t.setPointerCapture(e)}function Gue(t,e,n){Uue(t,e);const r=new AbortController,{signal:i}=r;t.dataset.dockkitPointer=String(e),i.addEventListener("abort",()=>{t.dataset.dockkitPointer===String(e)&&delete t.dataset.dockkitPointer},{once:!0});const s=o=>o.pointerId===e;return window.addEventListener("pointermove",o=>{s(o)&&n.move(o)},{signal:i}),window.addEventListener("pointerup",o=>{s(o)&&(r.abort(),n.up(o))},{signal:i}),window.addEventListener("pointercancel",o=>{s(o)&&(r.abort(),n.cancel())},{signal:i}),()=>{r.abort()}}function mT(t){const e=T.useRef(void 0);return T.useEffect(()=>()=>{var n;(n=e.current)==null||n.stop()},[]),(n,r,i)=>{var a;(a=e.current)==null||a.end();const s=()=>{e.current=void 0,t()},o=Gue(n,r,{move:i.move,up:c=>{s(),i.up(c)},cancel:s});e.current={stop:o,end:()=>{o(),s()}}}}const U3=new WeakMap,Kue=new Set(["Tab","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]);function q5(t,e){var i;(i=U3.get(t))==null||i();const n=()=>{t.removeAttribute("data-dsh-automatic-focus"),t.removeEventListener("blur",n),t.removeEventListener("keydown",r,!0),U3.delete(t)},r=s=>{!s.isComposing&&!s.ctrlKey&&!s.altKey&&!s.metaKey&&Kue.has(s.key)&&n()};U3.set(t,n),t.setAttribute("data-dsh-automatic-focus",""),t.addEventListener("blur",n),t.addEventListener("keydown",r,!0),t.focus(e),t.matches(":focus")||n()}function gT(t){var a;let e=!1,n=!1;const r=()=>{e=!0},i=()=>{e=!1,n=!0},s=()=>{n=!1},o=()=>{e=!1,n=!1};return t.addEventListener("compositionstart",r,!0),t.addEventListener("compositionend",i,!0),t.addEventListener("keyup",s,!0),(a=t.defaultView)==null||a.addEventListener("blur",o),{guards:c=>{const d=e||n||c.isComposing||c.keyCode===229;return n=!1,d},dispose:()=>{var c;t.removeEventListener("compositionstart",r,!0),t.removeEventListener("compositionend",i,!0),t.removeEventListener("keyup",s,!0),(c=t.defaultView)==null||c.removeEventListener("blur",o)}}}const Zue='[role="dialog"][aria-modal="true"], [role="menu"]',G3=new WeakMap,k_='button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], [tabindex="0"]';function $de(t,e,n){const r=T.useRef(n);r.current=n,T.useLayoutEffect(()=>{const i=t.current;if(!e||i===null)return;const s=i.ownerDocument,o=gT(s),a=s.activeElement,c=G3.get(s)??[];G3.set(s,c);const d={element:i,close:()=>{r.current()}};c.push(d);const h=i.querySelector("[data-modal-autofocus]")??i.querySelector(k_)??i;i.contains(s.activeElement)||q5(h);const p=g=>{var S;const y=o.guards(g);if(c.at(-1)!==d||g.defaultPrevented||y||g.ctrlKey||g.altKey||g.metaKey||(g.key==="Escape"&&!g.shiftKey&&(g.preventDefault(),g.repeat||r.current()),g.key!=="Tab")||(S=s.activeElement)!=null&&S.closest('[role="menu"]'))return;const b=[...i.querySelectorAll(k_)].filter($=>!$.closest("[inert], [hidden]")),x=b[0]??i,_=b.at(-1)??i,k=g.shiftKey?s.activeElement===x:s.activeElement===_;(s.activeElement===i||!i.contains(s.activeElement)||k)&&(g.preventDefault(),(g.shiftKey?_:x).focus())};return s.addEventListener("keydown",p),()=>{var y;o.dispose();const g=c.at(-1)===d;if(c.splice(c.indexOf(d),1),s.removeEventListener("keydown",p),c.length===0&&G3.delete(s),g){const b=a instanceof HTMLElement&&a.isConnected?a:(y=c.at(-1))==null?void 0:y.element;b!==void 0&&q5(b)}}},[t,e])}const Xue="_divider_1s7ij_39",Yue="_surface_1s7ij_125",Que="_tabLayout_1s7ij_134",Jue="_tabCell_1s7ij_142",e0e="_emptyTabHost_1s7ij_143",t0e="_floatingCell_1s7ij_156",n0e="_tabHost_1s7ij_162",r0e="_float_1s7ij_156",i0e="_tabHostHeader_1s7ij_177",s0e="_tabHostBody_1s7ij_181",o0e="_tabLayoutDivider_1s7ij_186",a0e="_pane_1s7ij_209",l0e="_tabStrip_1s7ij_237",c0e="_stripTabs_1s7ij_257",u0e="_stripFill_1s7ij_288",d0e="_stripChrome_1s7ij_296",h0e="_paneBody_1s7ij_318",f0e="_slot_1s7ij_327",p0e="_tabActive_1s7ij_346",m0e="_slotCaret_1s7ij_346",g0e="_tab_1s7ij_134",y0e="_tabTitle_1s7ij_389",v0e="_floatTitle_1s7ij_409",b0e="_tabClose_1s7ij_417",x0e="_addTab_1s7ij_449",_0e="_tabQuiet_1s7ij_488",w0e="_tabDragging_1s7ij_505",k0e="_iconButton_1s7ij_511",C0e="_menu_1s7ij_547",S0e="_menuItem_1s7ij_561",E0e="_empty_1s7ij_143",$0e="_dockScrim_1s7ij_599",T0e="_dockHint_1s7ij_601",N0e="_dockHintCard_1s7ij_606",I0e="_dockHintLabel_1s7ij_694",j0e="_floatHeader_1s7ij_765",M0e="_dockGlyph_1s7ij_782",A0e="_floatBody_1s7ij_787",L0e="_floatResize_1s7ij_797",ut={divider:Xue,surface:Yue,tabLayout:Que,tabCell:Jue,emptyTabHost:e0e,floatingCell:t0e,tabHost:n0e,float:r0e,tabHostHeader:i0e,tabHostBody:s0e,tabLayoutDivider:o0e,pane:a0e,tabStrip:l0e,stripTabs:c0e,stripFill:u0e,stripChrome:d0e,paneBody:h0e,slot:f0e,tabActive:p0e,slotCaret:m0e,tab:g0e,tabTitle:y0e,floatTitle:v0e,tabClose:b0e,addTab:x0e,tabQuiet:_0e,tabDragging:w0e,iconButton:k0e,menu:C0e,menuItem:S0e,empty:E0e,dockScrim:$0e,dockHint:T0e,dockHintCard:N0e,dockHintLabel:I0e,floatHeader:j0e,dockGlyph:M0e,floatBody:A0e,floatResize:L0e},K3=4;function P0e(t,e){const n=t.getBoundingClientRect(),r=e.offsetWidth,i=n.left+r+K3>window.innerWidth?Math.max(K3,n.right-r):n.left;return{top:n.bottom+K3,left:i}}function z0e({labels:t,anchor:e,onClose:n,onDismiss:r,extras:i}){const s=T.useRef(null),[o,a]=T.useState(void 0),c=n!==void 0||T.Children.toArray(i).some(d=>d!=="");return T.useLayoutEffect(()=>{s.current!==null&&a(P0e(e,s.current))},[e,c]),T.useEffect(()=>{const d=s.current;if(d===null)return;const h=d.ownerDocument,p=gT(h),g=b=>{if(p.guards(b)||b.defaultPrevented||b.key!=="Escape"||b.ctrlKey||b.altKey||b.metaKey||b.shiftKey||[...h.querySelectorAll(Zue)].at(-1)!==d||(b.preventDefault(),b.repeat))return;const _=d.contains(h.activeElement);r(),_&&q5(e)};h.addEventListener("keydown",g,!0);const y=b=>{b.target instanceof Node&&d.contains(b.target)||r()};return window.addEventListener("pointerdown",y,!0),()=>{p.dispose(),h.removeEventListener("keydown",g,!0),window.removeEventListener("pointerdown",y,!0)}},[e,r,c]),c?gs.createPortal(f.jsxs(Vf,{className:ut.menu,ref:s,role:"menu","data-dockkit-tab-menu":!0,style:o??{visibility:"hidden",top:0,left:0},onPointerDown:d=>{d.stopPropagation()},onClick:d=>{d.stopPropagation()},children:[n!==void 0&&f.jsx("button",{type:"button",role:"menuitem",className:ut.menuItem,"data-dockkit-menu-close":!0,onClick:n,children:t.closeTab}),i]}),document.body):null}function C_(t){t.scrollWidth>t.clientWidth+1?t.dataset.dockkitTabClipped="":delete t.dataset.dockkitTabClipped}function yT({children:t}){const e=T.useRef(null);return T.useLayoutEffect(()=>{e.current!==null&&C_(e.current)}),T.useLayoutEffect(()=>{const n=e.current;if(n===null||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{C_(n)});return r.observe(n),()=>{r.disconnect()}},[]),f.jsx("span",{ref:e,className:ut.tabTitle,"data-dockkit-tab-title":!0,children:t})}const R0e="M9.67272 0.522841C10.8339 0.522841 11.76 0.522714 12.4963 0.602493C13.2453 0.683657 13.8789 0.854248 14.4264 1.25197C14.7504 1.48739 15.0355 1.77247 15.2709 2.0965C15.6686 2.64394 15.8392 3.27758 15.9204 4.02655C16.0002 4.7629 16 5.68895 16 6.85014V9.14986C16 10.3111 16.0002 11.2371 15.9204 11.9735C15.8392 12.7224 15.6686 13.3561 15.2709 13.9035C15.0355 14.2275 14.7504 14.5126 14.4264 14.748C13.8789 15.1458 13.2453 15.3163 12.4963 15.3975C11.76 15.4773 10.8339 15.4772 9.67272 15.4772H6.3273C5.16611 15.4772 4.24006 15.4773 3.50371 15.3975C2.75474 15.3163 2.1211 15.1458 1.57366 14.748C1.24963 14.5126 0.964549 14.2275 0.729131 13.9035C0.331407 13.3561 0.160817 12.7224 0.0796529 11.9735C-0.000126137 11.2371 1.25338e-09 10.3111 1.25338e-09 9.14986V6.85014C1.25329e-09 5.68895 -0.000126137 4.7629 0.0796529 4.02655C0.160817 3.27758 0.331407 2.64394 0.729131 2.0965C0.964549 1.77247 1.24963 1.48739 1.57366 1.25197C2.1211 0.854248 2.75474 0.683657 3.50371 0.602493C4.24006 0.522714 5.16611 0.522841 6.3273 0.522841H9.67272ZM4.1828 14.0873L5.54303 14.1118C5.78636 14.1128 6.04709 14.1169 6.3273 14.1169H9.67272C10.8639 14.1169 11.7032 14.1164 12.3493 14.0465C12.9824 13.9779 13.3497 13.8494 13.6268 13.6482C13.8354 13.4966 14.0195 13.3125 14.1711 13.1039C14.3723 12.8268 14.5007 12.4595 14.5693 11.8264C14.6393 11.1803 14.6398 10.341 14.6398 9.14986V6.85014C14.6398 5.65896 14.6393 4.81967 14.5693 4.1736C14.5007 3.54048 14.3723 3.17318 14.1711 2.89609C14.0195 2.68747 13.8354 2.50337 13.6268 2.35179C13.3497 2.1506 12.9824 2.02212 12.3493 1.95353C11.7032 1.88358 10.8639 1.88307 9.67272 1.88307H6.3273C6.04709 1.88307 5.78636 1.8862 5.54303 1.88715L4.1828 1.91166C3.99125 1.9216 3.8148 1.93577 3.65076 1.95353C3.01764 2.02212 2.65034 2.1506 2.37325 2.35179C2.16463 2.50337 1.98052 2.68747 1.82895 2.89609C1.62776 3.17318 1.49928 3.54048 1.43069 4.1736C1.36074 4.81967 1.36023 5.65896 1.36023 6.85014V9.14986C1.36023 10.341 1.36074 11.1803 1.43069 11.8264C1.49928 12.4595 1.62776 12.8268 1.82895 13.1039C1.98052 13.3125 2.16463 13.4966 2.37325 13.6482C2.65034 13.8494 3.01764 13.9779 3.65076 14.0465C3.81478 14.0642 3.99127 14.0774 4.1828 14.0873Z";function D0e(){return f.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[f.jsx("path",{d:"M13.5 1.5H2.5C1.94772 1.5 1.5 1.94772 1.5 2.5V13.5C1.5 14.0523 1.94772 14.5 2.5 14.5H13.5C14.0523 14.5 14.5 14.0523 14.5 13.5V2.5C14.5 1.94772 14.0523 1.5 13.5 1.5Z",stroke:"currentColor"}),f.jsx("path",{d:"M8 1.5V14.5",stroke:"currentColor"})]})}const O0e={center:"M4.56 3.48H11.44A1.6 1.6 0 0 1 13.04 5.08V10.92A1.6 1.6 0 0 1 11.44 12.52H4.56A1.6 1.6 0 0 1 2.96 10.92V5.08A1.6 1.6 0 0 1 4.56 3.48Z",left:"M4 0.523H8V15.477H4A4 4 0 0 1 0 11.477V4.523A4 4 0 0 1 4 0.523Z",right:"M8 0.523H12A4 4 0 0 1 16 4.523V11.477A4 4 0 0 1 12 15.477H8Z",top:"M0 8V4.523A4 4 0 0 1 4 0.523H12A4 4 0 0 1 16 4.523V8Z",bottom:"M0 8H16V11.477A4 4 0 0 1 12 15.477H4A4 4 0 0 1 0 11.477Z"};function F0e({zone:t}){return f.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[f.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:R0e,fill:"currentColor"}),f.jsx("path",{d:O0e[t],fill:"currentColor"})]})}function Z3({zone:t,active:e,labels:n}){return f.jsx("div",{className:ut.dockHint,"data-dockkit-dock-zone":t,"data-dockkit-drop-active":e||void 0,children:f.jsxs("div",{className:ut.dockHintCard,children:[f.jsx(F0e,{zone:t}),f.jsx("span",{className:ut.dockHintLabel,children:n.dropZone[t]})]})})}function B0e(t,e,n){const r=e.length,i=e.indexOf(n);switch(t){case"ArrowLeft":return e[(i-1+r)%r];case"ArrowRight":return e[(i+1)%r];case"Home":return e[0];case"End":return e.at(-1);default:return}}function H0e(t){return t==="Enter"||t===" "}function q0e(t){const e=t.scrollLeft>1,n=t.scrollLeft+t.clientWidth<t.scrollWidth-1;if(e&&n)return"start end";if(e)return"start";if(n)return"end"}function W0e(t,e){T.useLayoutEffect(()=>{const n=t.current;if(n===null)return;const r=()=>{const s=q0e(n);s===void 0?delete n.dataset.dockkitStripScroll:n.dataset.dockkitStripScroll=s};r(),n.addEventListener("scroll",r,{passive:!0});const i=typeof ResizeObserver>"u"?void 0:new ResizeObserver(r);return i==null||i.observe(n),()=>{n.removeEventListener("scroll",r),i==null||i.disconnect()}},[t,e])}function V0e(t,e,n,r){T.useLayoutEffect(()=>{const i=t.current,s=r===void 0?void 0:e.get(r);if(i===null||s===void 0)return;const o=i.getBoundingClientRect(),a=s.getBoundingClientRect();a.left<o.left?i.scrollLeft+=a.left-o.left-S_:a.right>o.right&&(i.scrollLeft+=a.right-o.right+S_)},[t,e,n,r])}const S_=24;function E_(t,e){switch(e){case"budget":return t.splitPaneDisabled;case"width":return t.splitPaneNarrow}}function vT({state:t,pane:e,callbacks:n}){const[r,i]=T.useState(void 0),[s]=T.useState(()=>new Map),o=T.useRef(null);W0e(o,e.tabs),V0e(o,s,e.tabs,e.activeTabId);const a=n.splitBlock(e.id),c=n.dropTarget,d=c!==void 0&&c.kind==="strip"&&c.paneId===e.id?c.index:void 0,h=g=>{t.activePaneId===e.id&&e.activeTabId===g||n.onFocusTab(g)},p=g=>{const y=s.get(g);y!==void 0&&y.focus()};return f.jsxs("div",{className:ut.tabStrip,role:"tablist","data-dockkit-strip":e.id,"data-window-drag":t.floats.length===0?!0:void 0,children:[f.jsxs("div",{ref:o,className:ut.stripTabs,role:"presentation","data-dockkit-strip-tabs":e.id,children:[e.tabs.map((g,y)=>{var S,$;const b=hu(t,g),x=g===e.activeTabId,_=n.canCloseTab(g),k=!_&&e.tabs.length===1;return f.jsxs(T.Fragment,{children:[(y>0||d===y)&&f.jsx("div",{className:_t(ut.slot,d===y&&ut.slotCaret),"data-dockkit-caret":d===y?y:void 0}),f.jsxs("div",{role:"tab","aria-selected":x,tabIndex:x?0:-1,className:_t(ut.tab,x&&ut.tabActive,k&&ut.tabQuiet,n.draggingTabId===g&&ut.tabDragging),"data-dockkit-tab":g,"data-dockkit-tab-quiet":k||void 0,ref:A=>{A===null?s.delete(g):s.set(g,A)},onPointerDown:A=>{A.button!==2&&n.onTabPressed(g,A)},onClick:A=>{A.stopPropagation(),h(g)},onKeyDown:A=>{if(A.target!==A.currentTarget||A.altKey||A.ctrlKey||A.metaKey||A.shiftKey||A.nativeEvent.isComposing)return;const z=B0e(A.key,e.tabs,g);if(z!==void 0){A.preventDefault(),p(z);return}H0e(A.key)&&(A.preventDefault(),h(g))},onContextMenu:A=>{A.preventDefault();const z=A.currentTarget;i(j=>(j==null?void 0:j.tabId)===g?void 0:{tabId:g,anchor:z})},children:[f.jsx(yT,{children:((S=n.renderTabTitle)==null?void 0:S.call(n,b))??b.title}),_&&f.jsx(yi,{disabled:r!==void 0,label:n.labels.closeTab,shortcutKeys:n.labels.closeTabKeys,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:ut.tabClose,"aria-label":n.labels.closeTab,"aria-keyshortcuts":n.labels.closeTabShortcut,"data-dockkit-tab-close":g,onPointerDown:A=>{A.stopPropagation()},onClick:A=>{A.stopPropagation(),n.onCloseTab(g)},children:f.jsx(AK,{size:14})})}),(r==null?void 0:r.tabId)===g&&f.jsx(z0e,{labels:n.labels,anchor:r.anchor,onClose:_?()=>{i(void 0),n.onCloseTab(g)}:void 0,onDismiss:()=>{i(void 0)},extras:($=n.renderTabMenuItems)==null?void 0:$.call(n,b,()=>{i(void 0)})})]})]},g)}),d===e.tabs.length&&f.jsx("div",{className:_t(ut.slot,ut.slotCaret),"data-dockkit-caret":d})]}),n.canAddTab(e.id)&&f.jsx(yi,{label:n.labels.addTab,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:ut.addTab,"aria-label":n.labels.addTab,"data-dockkit-add-tab":e.id,onClick:g=>{g.stopPropagation(),n.onAddTab(e.id)},children:f.jsx(kK,{size:14})})}),f.jsx("div",{className:ut.stripFill,"data-dockkit-strip-fill":!0}),!(n.hideSplitWhenBlocked&&a!==void 0)&&f.jsx(yi,{label:a===void 0?n.labels.splitPane:E_(n.labels,a),shortcutKeys:n.labels.splitPaneKeys,side:"bottom",delayMs:500,children:f.jsx("span",{tabIndex:a===void 0?void 0:0,"aria-label":a===void 0?void 0:E_(n.labels,a),children:f.jsx("button",{type:"button",className:ut.iconButton,"aria-label":n.labels.splitPane,"aria-keyshortcuts":n.labels.splitPaneShortcut,disabled:a!==void 0,"data-dockkit-split-button":e.id,"data-dockkit-split-blocked":a,onClick:g=>{g.stopPropagation(),n.onSplitPane(e.id)},children:f.jsx(D0e,{})})})}),e.id===n.chromePaneId&&n.chrome!==void 0&&f.jsx("div",{className:ut.stripChrome,"data-dockkit-strip-chrome":!0,onClick:g=>{g.stopPropagation()},children:n.chrome})]})}function bT({pane:t,callbacks:e}){const n=e.dropTarget,r=(n==null?void 0:n.kind)==="zone"&&n.paneId===t.id?n.zone:void 0;return r===void 0?null:f.jsxs(f.Fragment,{children:[f.jsx("div",{className:ut.dockScrim,"data-dockkit-dock-scrim":!0}),e.horizontalDrops&&r!=="center"?f.jsxs(f.Fragment,{children:[f.jsx(Z3,{zone:"left",active:r==="left",labels:e.labels}),f.jsx(Z3,{zone:"right",active:r==="right",labels:e.labels})]}):f.jsx(Z3,{zone:r,active:!0,labels:e.labels})]})}function U0e({state:t,pane:e,callbacks:n}){const r=e.activeTabId===void 0?void 0:hu(t,e.activeTabId);return f.jsxs("section",{className:ut.pane,"data-dockkit-pane":e.id,tabIndex:-1,"data-dockkit-pane-active":t.activePaneId===e.id||void 0,onClick:()=>{t.activePaneId!==e.id&&n.onFocusPane(e.id)},children:[f.jsx(vT,{state:t,pane:e,callbacks:n}),f.jsxs("div",{className:ut.paneBody,children:[r===void 0?f.jsx("p",{className:ut.empty,children:n.labels.emptyPane}):n.renderTab(r),f.jsx(bT,{pane:e,callbacks:n})]})]})}function $_(t,e,n){const r=e-t.originX,i=n-t.originY;return t.mode==="move"?vue(t.rect,r,i):bue(t.rect,r,i,cue)}function G0e(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function K0e(t,e){return t.activePaneId===e&&t.floats.at(-1)===e}function Z0e(t,e){const[n,r]=T.useState(void 0),i=mT(()=>{r(void 0)}),s=a=>{K0e(t,a)||e.focusPane(a)};return{preview:n,raise:s,drag:(a,c,d)=>{d.stopPropagation();const h={mode:a,originX:d.clientX,originY:d.clientY,rect:_1(Kt(t,c))};i(d.currentTarget,d.pointerId,{move:p=>{r({paneId:c,rect:$_(h,p.clientX,p.clientY)})},up:p=>{const g=$_(h,p.clientX,p.clientY);G0e(g,h.rect)?s(c):a==="move"?e.moveFloat(c,g.x,g.y):e.resizeFloat(c,g)}})}}}function X0e({paneId:t,tab:e,labels:n,intents:r,renderTabTitle:i,canCloseTab:s,drag:o}){return f.jsxs("header",{className:_t(ut.tabStrip,ut.floatHeader),"data-dockkit-float-grip":t,onPointerDown:a=>{o("move",t,a)},children:[f.jsx("div",{className:_t(ut.tab,ut.floatTitle),"data-dockkit-float-title":!0,children:f.jsx(yT,{children:(i==null?void 0:i(e))??e.title})}),f.jsx("div",{className:ut.stripFill}),f.jsx(yi,{label:n.dockFloat,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:ut.iconButton,"aria-label":n.dockFloat,"data-dockkit-float-dock":t,onPointerDown:a=>{a.stopPropagation()},onClick:()=>{r.unfloatPane(t)},children:f.jsx(ag,{className:ut.dockGlyph})})}),((s==null?void 0:s(e.id))??!0)&&f.jsx(yi,{label:n.closeTab,shortcutKeys:n.closeTabKeys,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:ut.iconButton,"aria-label":n.closeTab,"data-dockkit-float-close":t,onPointerDown:a=>{a.stopPropagation()},onClick:()=>{r.closeTab(e.id)},children:f.jsx(lg,{})})})]})}function Y0e({state:t,callbacks:e,intents:n,tab:r,pane:i,column:s,floats:o,focusRequest:a,keepMounted:c,active:d=!0}){var z;const h=i.host==="float",p=h||i.activeTabId===r.id,g=d&&p&&(h||t.expanded),y=(c==null?void 0:c(r))??!1,[b,x]=T.useState(g);g&&!b&&x(!0);const _=T.useRef(null),k=T.useRef(null);T.useLayoutEffect(()=>{const j=_.current;j.inert=!g;const L=document.activeElement;!g&&L instanceof HTMLElement&&j.contains(L)&&L.blur();const R=a.current;if(!g||(R==null?void 0:R.tabId)!==r.id||(a.current=void 0,L!==null&&L!==document.body&&L!==document.documentElement&&L!==R.origin))return;const M=j.querySelector("[data-dockkit-strip]"),N=[...(M==null?void 0:M.querySelectorAll("[data-dockkit-tab]"))??[]].find(P=>P.dataset.dockkitTab===r.id);N==null||N.focus({preventScroll:!0})},[g,r.id,a]),T.useEffect(()=>{const j=k.current,L=()=>{g&&(h?o.raise(i.id):t.activePaneId!==i.id&&e.onFocusPane(i.id))};return j.addEventListener("focus",L,!0),()=>{j.removeEventListener("focus",L,!0)}},[g,h,o,i.id,t.activePaneId,e]);const S=h&&((z=o.preview)==null?void 0:z.paneId)===i.id?o.preview.rect:void 0,$=h?S??_1(i):void 0,A=S===void 0?t.floats.indexOf(i.id)+1:t.floats.length+1;return f.jsx("div",{className:_t(ut.tabCell,h&&ut.floatingCell),hidden:!p,"data-dockkit-host":h?"float":"dock","data-dockkit-column":h?void 0:s,style:{gridColumn:h?1:s*2+1,gridRow:1,order:h?A:0},children:f.jsxs("section",{ref:_,tabIndex:-1,className:_t(ut.tabHost,h?ut.float:ut.pane),"aria-hidden":!g||void 0,"data-dockkit-content":r.id,"data-dockkit-pane":!h&&p?i.id:void 0,"data-dockkit-pane-active":!h&&t.activePaneId===i.id||void 0,"data-dockkit-float":h?i.id:void 0,"data-dockkit-float-active":h&&t.activePaneId===i.id||void 0,"data-dockkit-column":h?void 0:s,style:$===void 0?void 0:{left:$.x,top:$.y,width:$.width,height:$.height},onPointerDown:()=>{h&&o.raise(i.id)},onClick:()=>{!h&&t.activePaneId!==i.id&&e.onFocusPane(i.id)},children:[f.jsx("div",{className:ut.tabHostHeader,children:p&&(h?f.jsx(X0e,{paneId:i.id,tab:r,labels:e.labels,intents:n,renderTabTitle:e.renderTabTitle,canCloseTab:e.canCloseTab,drag:o.drag}):f.jsx(vT,{state:t,pane:i,callbacks:e}))}),f.jsxs("div",{ref:k,className:_t(ut.tabHostBody,h?ut.floatBody:ut.paneBody),children:[b&&(y||d&&p)?e.renderTab(r):null,!h&&f.jsx(bT,{pane:i,callbacks:e})]}),h&&f.jsx("div",{className:ut.floatResize,"data-dockkit-float-resize":i.id,onPointerDown:j=>{o.drag("resize",i.id,j)}})]})})}function Q0e(t){const{state:e,callbacks:n,preview:r}=t,i=T.useRef(),s={...n,onFocusTab:p=>{i.current=ms(e,p).activeTabId===p?void 0:{tabId:p,origin:document.activeElement},n.onFocusTab(p)}},o=Hl(e,e.rootId);if(o.kind==="split"&&(o.axis!=="row"||o.children.length!==2))throw new Error("DockLayout requires one pane or two horizontally split panes");const a=o.kind==="pane"?[o]:o.children.map(p=>Kt(e,p)),c=o.kind==="split"?(r==null?void 0:r.splitId)===o.id?r.sizes:o.sizes:[1],d=Z0e(e,t.intents),h=c.map(p=>`minmax(0, ${p}fr)`).join(" 0px ");return f.jsxs("div",{className:ut.tabLayout,"data-dockkit-split":o.kind==="split"?o.id:void 0,style:{gridTemplateColumns:h},children:[Object.values(e.tabs).sort((p,g)=>p.id.localeCompare(g.id)).map(p=>{const g=ms(e,p.id);return f.jsx(Y0e,{...t,callbacks:s,tab:p,pane:g,column:a.findIndex(y=>y.id===g.id),floats:d,focusRequest:i},p.id)}),a.filter(p=>p.tabs.length===0).map(p=>f.jsx("div",{className:ut.emptyTabHost,"data-dockkit-empty":!0,style:{gridColumn:a.indexOf(p)*2+1,gridRow:1},children:f.jsx(U0e,{state:e,pane:p,callbacks:n})},p.id)),o.kind==="split"&&f.jsx("div",{className:_t(ut.divider,ut.tabLayoutDivider),"data-dockkit-divider":`${o.id}:0`,style:{gridColumn:2,gridRow:1},onPointerDown:p=>{n.onDividerPressed(o.id,0,p)}})]})}const hh={draggingTabId:void 0,dropTarget:void 0,sizes:void 0},J0e=new Map,T_=()=>!0;function N_(t,e,n,r,i,s){for(const[o,a]of pT(t)){const c=a.getBoundingClientRect();if(!F5(c,e,n))continue;const d=a.querySelector("[data-dockkit-strip]");if(d!==null&&F5(d.getBoundingClientRect(),e,n)){const p=[...d.querySelectorAll("[data-dockkit-tab]")];return{kind:"strip",paneId:o,index:pue(p.map(g=>g.getBoundingClientRect()),e)}}const h=s==="horizontal"?r&&H5(i,o).row?e<c.x+c.width/2?"left":"right":"center":fue(c,e,n);if(h!=="center"){const p=H5(i,o),g=h==="left"||h==="right"?p.row:p.column;if(!r||!g)return}return{kind:"zone",paneId:o,zone:h}}}function I_(t,e,n,r){const i=(t.axis==="row"?e:n)-t.origin,s=t.extent>0?i/t.extent:0;return fT(yue(t.sizes,t.index,s),r)}const e1e=1e-9;function t1e(t,e){return t.length===e.length&&t.every((n,r)=>{const i=e[r];return i!==void 0&&Math.abs(n-i)<e1e})}function n1e({state:t,canSplit:e,canAddTab:n,canCloseTab:r,intents:i,labels:s,renderTab:o,renderTabTitle:a,renderTabMenuItems:c,chrome:d,onRoom:h,draw:p,dropZones:g="edges",minPaneFraction:y=dT,hideSplitWhenBlocked:b=!1}){const x=T.useRef(null),[_,k]=T.useState(hh),[S,$]=T.useState(J0e),A=mT(()=>{k(hh)}),z=T.useCallback(M=>{const N=x.current;N!==null&&M(N)},[]),j=T.useCallback(()=>{z(M=>{const N=Wue(M,b);$(P=>Vue(P,N)?P:N)})},[z,b]);T.useLayoutEffect(()=>{j()}),T.useEffect(()=>{h==null||h(S)},[S,h]),T.useEffect(()=>{const M=x.current;if(M===null||typeof ResizeObserver>"u")return;const N=new ResizeObserver(()=>{j()});return N.observe(M),()=>{N.disconnect()}},[j]);const L=M=>e?H5(S,M).row?void 0:"width":"budget",R={onFocusTab:i.focusTab.bind(i),onFocusPane:i.focusPane.bind(i),onSplitPane:i.splitPane.bind(i),onAddTab:i.addTab.bind(i),onCloseTab:i.closeTab.bind(i),onTabPressed:(M,N)=>{z(P=>{const G=N.clientX,ee=N.clientY;let K=!1;A(N.currentTarget,N.pointerId,{move:V=>{if(!K){if(!gue(G,ee,V.clientX,V.clientY))return;K=!0}k({...hh,draggingTabId:M,dropTarget:N_(P,V.clientX,V.clientY,e,S,g)})},up:V=>{if(!K)return;const B=N_(P,V.clientX,V.clientY,e,S,g);if(B===void 0){if(F5(P.getBoundingClientRect(),V.clientX,V.clientY))return;i.floatTab(M,xue(V.clientX,V.clientY,O5));return}B.kind==="strip"?i.placeTab(M,B.paneId,B.index):i.dropTab(M,B.paneId,B.zone)}})})},onDividerPressed:(M,N,P)=>{const G=P.currentTarget.parentElement;if(G===null)return;const ee=Fg(t,M),K=G.getBoundingClientRect(),V={index:N,axis:ee.axis,origin:ee.axis==="row"?P.clientX:P.clientY,extent:ee.axis==="row"?K.width:K.height,sizes:ee.sizes};A(P.currentTarget,P.pointerId,{move:B=>{k({...hh,sizes:{splitId:M,sizes:I_(V,B.clientX,B.clientY,y)}})},up:B=>{const Y=I_(V,B.clientX,B.clientY,y);t1e(Y,V.sizes)||i.resizeSplit(M,Y)}})},splitBlock:L,hideSplitWhenBlocked:b,canAddTab:n??T_,canCloseTab:r??T_,dropTarget:_.dropTarget,horizontalDrops:g==="horizontal",draggingTabId:_.draggingTabId,labels:s,renderTab:o,renderTabTitle:a,renderTabMenuItems:c,chromePaneId:Pce(t),chrome:d};return f.jsx("div",{className:ut.surface,ref:x,"data-dockkit-surface":!0,"data-dockkit-drop-zones":g,children:p(R,_.sizes)})}function r1e(t){return f.jsx(n1e,{...t,draw:(e,n)=>f.jsx(Q0e,{...t,callbacks:e,preview:n})})}const i1e="_panel_nj5n1_32",s1e="_iconButton_nj5n1_121",o1e="_collapseGlyph_nj5n1_147",a1e="_panelBody_nj5n1_151",N0={panel:i1e,iconButton:s1e,collapseGlyph:o1e,panelBody:a1e};function l1e(){return f.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:f.jsx("path",{d:"M2.33203 10.4054V13.1681C2.33229 13.444 2.55605 13.6681 2.83203 13.6681H5.49512V14.6681H2.83203C2.00376 14.6681 1.33229 13.9963 1.33203 13.1681V10.4054H2.33203ZM14.6689 13.1681C14.6687 13.996 13.9968 14.6676 13.1689 14.6681H10.4951V13.6681H13.1689C13.4445 13.6676 13.6687 13.4437 13.6689 13.1681V10.4054H14.6689V13.1681ZM13.1689 1.33118C13.9969 1.33163 14.6688 2.00315 14.6689 2.83118V5.4054H13.6689V2.83118C13.6688 2.55544 13.4446 2.33162 13.1689 2.33118H10.4951V1.33118H13.1689ZM5.49512 2.33118H2.83203C2.55598 2.33118 2.33218 2.55516 2.33203 2.83118V5.4054H1.33203V2.83118C1.33218 2.00288 2.00369 1.33118 2.83203 1.33118H5.49512V2.33118Z",fill:"currentColor"})})}function c1e(){return f.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[f.jsx("path",{d:"M9 2.5V6C9 6.26522 9.10536 6.51957 9.29289 6.70711C9.48043 6.89464 9.73478 7 10 7H13.5",stroke:"currentColor"}),f.jsx("path",{d:"M7 13.5V10C7 9.73478 6.89464 9.48043 6.70711 9.29289C6.51957 9.10536 6.26522 9 6 9H2.5",stroke:"currentColor"})]})}function u1e({sessionId:t,fullscreen:e,focus:n=!1,actions:r,t:i,shortcuts:s,toggleFullscreen:o}){const a=e?"push":"fullscreen",c=i(n?"chrome.exitFocus":e?"chrome.exitFullscreen":"chrome.toFullscreen"),d=s.find(p=>p.id==="pane.fullscreen.toggle"),h=s.find(p=>p.id==="sidebar.right.toggle");return f.jsxs(f.Fragment,{children:[f.jsx(yi,{label:c,shortcutKeys:d==null?void 0:d.keys,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:N0.iconButton,"aria-label":c,"aria-keyshortcuts":d==null?void 0:d.aria,"data-sidebar-right-mode":a,onClick:o,children:e?f.jsx(c1e,{}):f.jsx(l1e,{})})}),f.jsx(yi,{label:i("chrome.collapse"),shortcutKeys:h==null?void 0:h.keys,side:"bottom",delayMs:500,children:f.jsx("button",{type:"button",className:N0.iconButton,"aria-label":i("chrome.collapseAria"),"aria-keyshortcuts":h==null?void 0:h.aria,"data-sidebar-right-toggle":!0,onClick:()=>{r.toggleExpanded(t)},children:f.jsx(ag,{className:N0.collapseGlyph})})})]})}function d1e(t,e,n){return{emptyPane:t("dock.emptyPane"),splitPane:t("dock.splitPane"),splitPaneShortcut:e==null?void 0:e.aria,splitPaneKeys:e==null?void 0:e.keys,splitPaneDisabled:t("dock.splitPaneDisabled"),splitPaneNarrow:t("dock.splitPaneNarrow"),closeTab:t("dock.closeTab"),closeTabShortcut:n==null?void 0:n.aria,closeTabKeys:n==null?void 0:n.keys,addTab:t("dock.addTab"),dockFloat:t("dock.dockFloat"),closeFloat:t("dock.closeFloat"),dropZone:{center:t("dock.drop.center"),left:t("dock.drop.left"),right:t("dock.drop.right"),top:t("dock.drop.top"),bottom:t("dock.drop.bottom")}}}const xT={"command.close":"关闭当前页面/窗口","command.refresh":"刷新当前页面","command.noRefresh":"当前页面不支持刷新","command.toggle":"展开/收起右侧栏","command.fullscreen":"面板全屏/退出全屏","command.noSession":"请先选择会话","command.noFocus":"请先聚焦右侧面板","command.stale":"页面已切换,请重新聚焦","command.collapsed":"请先展开右侧栏","command.float":"浮动面板不支持此操作","command.empty":"请先打开页面","command.budget":"已达两格上限","command.width":"栏宽不足,拖宽侧边栏后再分栏","chrome.expand":"打开侧边栏","chrome.expandAria":"打开右侧边栏","chrome.collapse":"收起侧边栏","chrome.collapseAria":"收起右侧边栏","chrome.toFullscreen":"全屏","chrome.exitFullscreen":"退出全屏","chrome.exitFocus":"退出专注模式","dock.emptyPane":"空面板","dock.splitPane":"分栏","dock.splitPaneDisabled":"已达两格上限","dock.splitPaneNarrow":"栏宽不足,拖宽侧边栏后再分栏","dock.closeTab":"关闭","dock.addTab":"新标签页","dock.dockFloat":"收回到侧边栏","dock.closeFloat":"关闭","dock.drop.center":"移到这里","dock.drop.left":"左分栏","dock.drop.right":"右分栏","dock.drop.top":"上分栏","dock.drop.bottom":"下分栏","tab.guide.title":"开始","tab.unavailable":"这类内容还没有可用的查看方式。"},_T={"command.close":"Close current page or window","command.refresh":"Refresh current page","command.noRefresh":"This page cannot be refreshed","command.toggle":"Toggle right sidebar","command.fullscreen":"Toggle panel fullscreen","command.noSession":"Select a session first","command.noFocus":"Focus a right sidebar pane first","command.stale":"The page changed; focus it again","command.collapsed":"Expand the right sidebar first","command.float":"This action is unavailable in a floating panel","command.empty":"Open a page first","command.budget":"Two panes is the limit","command.width":"Not enough width to split, widen the sidebar","chrome.expand":"Open sidebar","chrome.expandAria":"Open right sidebar","chrome.collapse":"Collapse sidebar","chrome.collapseAria":"Collapse right sidebar","chrome.toFullscreen":"Fullscreen","chrome.exitFullscreen":"Exit fullscreen","chrome.exitFocus":"Exit focus mode","dock.emptyPane":"Empty pane","dock.splitPane":"Split","dock.splitPaneDisabled":"Two panes is the limit","dock.splitPaneNarrow":"Not enough width to split, widen the sidebar","dock.closeTab":"Close","dock.addTab":"New tab","dock.dockFloat":"Send back to the sidebar","dock.closeFloat":"Close","dock.drop.center":"Move here","dock.drop.left":"Add left split","dock.drop.right":"Add right split","dock.drop.top":"Add top split","dock.drop.bottom":"Add bottom split","tab.guide.title":"Start","tab.unavailable":"Nothing here can view this kind of content yet."},h1e="_button_1rv3m_2",f1e="_md_1rv3m_23",p1e="_sm_1rv3m_28",m1e="_primary_1rv3m_36",g1e="_ghost_1rv3m_45",y1e="_outline_1rv3m_54",v1e="_toolbar_1rv3m_63",b1e="_icon_1rv3m_71",fh={button:h1e,md:f1e,sm:p1e,primary:m1e,ghost:g1e,outline:y1e,toolbar:v1e,icon:b1e},x1e=T.forwardRef(function({variant:e="ghost",size:n="md",icon:r,className:i,children:s,...o},a){return f.jsxs("button",{ref:a,type:"button",className:_t(fh.button,fh[e],fh[n],i),...o,children:[r!=null&&f.jsx("span",{className:fh.icon,children:r}),s]})}),_1e="_button_11lrx_2",w1e="_icon_11lrx_15",j_={button:_1e,icon:w1e};function bl(t){if(typeof t=="string")return t.length>0;if(!t||typeof t!="object")return!1;const e=t;return typeof e.zh=="string"&&e.zh.length>0&&typeof e.en=="string"&&e.en.length>0}function k1e(t){if(!t||typeof t!="object")return!1;const e=t;if(typeof e.id!="string"||!e.id||typeof e.title!="string"||!e.title||typeof e.action!="string"||!e.action||e.description!==void 0&&typeof e.description!="string"||e.args!==void 0&&(!Array.isArray(e.args)||e.args.some(n=>typeof n!="string")))return!1;if(e.presentation!==void 0){const n=e.presentation;if(!n||!bl(n.label)||n.description!==void 0&&!bl(n.description)||n.icon!==void 0&&typeof n.icon!="function"||n.section!==void 0&&!["add","commands"].includes(n.section))return!1}if(e.input!==void 0){const n=e.input;if(!n||!bl(n.hint)||n.attachments!==void 0&&typeof n.attachments!="boolean"||n.token!==void 0&&(!bl(n.token)||(typeof n.token=="string"?[n.token]:[n.token.zh,n.token.en]).some(i=>/[\s/]/.test(i))))return!1}return!0}function Tde(t){return t}function C1e(t,e){var s;if(!t||typeof t!="object")throw new Error("Module must default export a plugin definition");const n=t;if(n.id!==e||n.apiVersion!==1)throw new Error("Plugin id or apiVersion does not match the catalog");if(typeof n.activate!="function")throw new Error("Plugin must declare synchronous activate(context)");for(const o of["slots","commands","menuItems","interactions","artifactTools"])if(n[o]!==void 0&&!Array.isArray(n[o]))throw new Error(`${o} must be an array`);const r=new Set;for(const o of n.slots??[]){if(!o||!["composer.controls","turn.tail","rightbar.panel","rightbar.title"].includes(o.slot)||typeof o.id!="string"||typeof o.component!="function"||r.has(o.id))throw new Error("Invalid or duplicate slot");r.add(o.id)}for(const o of[...n.commands??[],...n.menuItems??[]]){if(!o||typeof o.id!="string"||typeof o.action!="string"||r.has(o.id))throw new Error("Invalid or duplicate command/menu contribution");r.add(o.id)}if((n.commands??[]).some(o=>!k1e(o)))throw new Error("Invalid command");const i=new Set;for(const o of n.interactions??[]){if(!o||typeof o.kind!="string"||!o.kind||i.has(o.kind)||typeof o.component!="function")throw new Error("Invalid or duplicate interaction");i.add(o.kind)}if(n.composerPlaceholder!==void 0&&typeof n.composerPlaceholder!="function")throw new Error("Invalid composer placeholder");if(n.composerAction!==void 0&&typeof n.composerAction!="function")throw new Error("Invalid composer action");if((s=n.artifactTools)!=null&&s.some(o=>typeof o!="string"))throw new Error("Invalid artifact tools");if(n.workbench){const{entry:o,panels:a,toolViews:c,beforeSend:d}=n.workbench;if(d!==void 0&&typeof d!="function")throw new Error("Invalid workbench pre-send hook");if(c!==void 0&&(!Array.isArray(c)||c.some(h=>!h||!Array.isArray(h.tools)||!h.tools.length||h.tools.some(p=>typeof p!="string"||!p)||typeof h.component!="function")))throw new Error("Invalid workbench tool view");if(n.workbench.resolvePanel!==void 0&&typeof n.workbench.resolvePanel!="function")throw new Error("Invalid workbench artifact resolver");if(n.workbench.apiVersion!==1||!o||typeof o.kind!="string"||!o.kind||!bl(o.label)||!bl(o.description)||o.panelTitle!==void 0&&!bl(o.panelTitle)||typeof o.icon!="function"||!Array.isArray(a)||!a.some(h=>h.kind===o.kind)||a.some(h=>typeof h.kind!="string"||typeof h.component!="function")||new Set(a.map(h=>h.kind)).size!==a.length)throw new Error("Invalid workbench contribution")}return n}function X3(t,e,n){return new Promise((r,i)=>{let s;const o=()=>a(new Error("Plugin load aborted")),a=(c,d)=>{clearTimeout(s),e.removeEventListener("abort",o),c?i(c):r(d)};e.addEventListener("abort",o,{once:!0}),n!==void 0&&(s=setTimeout(()=>a(new Error("Plugin load timed out")),n)),t.then(c=>a(null,c),c=>a(c)),e.aborted&&o()})}class S1e{constructor(e){q(this,"controller",new AbortController);q(this,"cleanups",[]);q(this,"disposed",!1);q(this,"report");this.report=e}context(e){return{sessionId:e,signal:this.controller.signal,onDispose:n=>{if(typeof n!="function")throw new Error("onDispose expects a cleanup function");this.disposed?this.clean(n):this.cleanups.push(n)}}}clean(e){try{e()}catch(n){this.report(n)}}dispose(){if(!this.disposed){this.disposed=!0,this.controller.abort();for(const e of this.cleanups.splice(0).reverse())this.clean(e)}}}const Y3=(t,e=null)=>({sessionId:e,generation:t,plugins:[],errors:[],ready:!1});class E1e{constructor(e){q(this,"environment");q(this,"run",null);q(this,"snapshot",Y3(0));q(this,"generation",0);q(this,"listeners",new Set);q(this,"getSnapshot",()=>this.snapshot);q(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}));this.environment=e}update(e){this.snapshot=e;for(const n of this.listeners)n()}error(e,n,r,i){const s=`plugin=${n} session=${e.sessionId} generation=${e.generation} stage=${r}: ${i instanceof Error?i.message:String(i)}`;(this.environment.report??console.error)(s),this.run===e&&this.update({...this.snapshot,errors:[...this.snapshot.errors,s]})}async start(e,n){var i;this.dispose();const r={sessionId:e,generation:++this.generation,controller:new AbortController,scopes:[]};this.run=r,this.update(Y3(r.generation,e));try{const s=await X3(Promise.resolve().then(n),r.controller.signal);if(this.run!==r)return;for(const o of s.errors)this.error(r,"catalog","discover",o);for(const o of s.plugins){if(this.run!==r)break;const a=new S1e(h=>this.error(r,o.id,"dispose",h));r.scopes.push(a);const c=a.context(e);let d="load";try{const h=await X3(this.environment.loadModule(o.client),r.controller.signal,this.environment.loadTimeoutMs??1e4);if(this.run!==r)break;d="validate";const p=C1e(h==null?void 0:h.default,o.id);if(o.style&&(d="style",await X3(this.environment.loadStyle(o.style,c.signal).then(b=>{c.onDispose(b)}),r.controller.signal,this.environment.loadTimeoutMs??1e4)),this.run!==r)break;d="activate";const g=new Set(this.snapshot.plugins.flatMap(b=>{var x;return((x=b.definition.workbench)==null?void 0:x.panels.map(_=>_.kind))??[]}));if((i=p.workbench)!=null&&i.panels.some(b=>g.has(b.kind)))throw new Error("Workbench panel kind already registered");const y=p.activate(c);if(y!==void 0)throw Promise.resolve(y).catch(b=>this.error(r,o.id,"activate",b)),new Error("activate must be synchronous and return void");if(this.run!==r){a.dispose();break}this.update({...this.snapshot,plugins:[...this.snapshot.plugins,{id:o.id,definition:p,instanceId:`${r.generation}/${o.id}`}]})}catch(h){this.run===r&&this.error(r,o.id,d,h),a.dispose()}}}catch(s){this.run===r&&this.error(r,"catalog","discover",s)}this.run===r&&this.update({...this.snapshot,ready:!0})}dispose(){const e=this.run;if(e){this.run=null,e.controller.abort();for(const n of e.scopes.reverse())n.dispose();this.update(Y3(this.generation))}}}const $1e={"builtin:@pi-webapp/files":()=>Je(()=>import("./plugin-BNln-AV2.js"),__vite__mapDeps([30,8])),"builtin:@pi-webapp/terminal":()=>Je(()=>import("./plugin-DO3fYZIM.js"),__vite__mapDeps([31,8,32])),"builtin:@pi-webapp/git":()=>Je(()=>import("./plugin-BR-ExlfJ.js"),__vite__mapDeps([33,8,34]))};function T1e(t){const e=$1e[t];if(!e)throw new Error("Unknown builtin plugin module");return e()}function N1e(t,e){return new Promise((n,r)=>{const i=document.createElement("link");i.rel="stylesheet",i.href=t;const s=()=>{e.removeEventListener("abort",o),i.onload=i.onerror=null,i.remove()},o=()=>{s(),r(new Error("Plugin stylesheet aborted"))};e.addEventListener("abort",o,{once:!0}),i.onload=()=>{e.removeEventListener("abort",o),i.onload=i.onerror=null,n(s)},i.onerror=()=>{s(),r(new Error("Plugin stylesheet failed to load"))},e.aborted?o():document.head.append(i)})}function I1e(t,e,n,r=0){const[i]=T.useState(()=>new E1e({loadModule:c=>c.startsWith("builtin:")?T1e(c):import(c),loadStyle:N1e})),s=T.useSyncExternalStore(i.subscribe,i.getSnapshot),o=T.useRef(new Map);s.sessionId&&s.ready&&o.current.set(s.sessionId,s.plugins.filter(c=>c.definition.workbench)),T.useEffect(()=>{if(!(!t||!e))return globalThis.__PI_WEBAPP_REACT__=NI,i.start(e,n),()=>i.dispose()},[i,t,e,r]);const a=t&&s.sessionId===e;return{plugins:a?s.plugins:!t&&e?o.current.get(e)??[]:[],errors:a?s.errors:[]}}class Np extends T.Component{constructor(){super(...arguments);q(this,"state",{failed:!1})}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){console.error(`pi-webapp plugin ${this.props.id}:`,n)}render(){return this.state.failed?null:this.props.children}}function Kg(t,e){return{...t,invokeAction:(n,r)=>t.invokePluginAction(e,n,r),resolveInteraction:n=>!t.interaction||t.interaction.pluginId!==e?Promise.reject(new Error("No pending interaction")):t.resolvePluginInteraction(e,t.interaction.requestId,n)}}function j1e({plugins:t,props:e}){var s,o,a,c;const n=(o=(s=e.session)==null?void 0:s.interactions)==null?void 0:o.find(d=>t.some(h=>{var p;return h.id===d.pluginId&&((p=h.definition.interactions)==null?void 0:p.some(g=>g.kind===d.kind))})),r=t.find(d=>d.id===(n==null?void 0:n.pluginId)),i=(c=(a=r==null?void 0:r.definition.interactions)==null?void 0:a.find(d=>d.kind===(n==null?void 0:n.kind)))==null?void 0:c.component;return!n||!r||!i?null:f.jsx(Np,{id:r.id,children:f.jsx(i,{...Kg({...e,interaction:n},r.id)})},`${r.instanceId??r.id}/${n.requestId}`)}function M1e({plugins:t,props:e,call:n,result:r,running:i}){const s=t.flatMap(a=>{var c;return(((c=a.definition.workbench)==null?void 0:c.toolViews)??[]).map(d=>({plugin:a,view:d}))}).find(({view:a})=>a.tools.includes(n.toolName??""));if(!s)return null;const o=s.view.component;return f.jsx(Np,{id:s.plugin.id,children:f.jsx(o,{...Kg(e,s.plugin.id),call:n,result:r,running:i})})}function W5({plugins:t,slot:e,props:n}){const r=t.flatMap(i=>(i.definition.slots??[]).filter(s=>s.slot===e).map(s=>({plugin:i,item:s})));return r.sort((i,s)=>(i.item.order??0)-(s.item.order??0)||i.plugin.id.localeCompare(s.plugin.id)||i.item.id.localeCompare(s.item.id)),f.jsx(f.Fragment,{children:r.map(({plugin:i,item:s})=>{const o=s.component;return f.jsx(Np,{id:i.id,children:f.jsx(o,{...Kg(n,i.id)})},`${i.instanceId??i.id}/${s.id}`)})})}const A1e="_body_1ki04_1",L1e="_toolbar_1ki04_3",P1e="_path_1ki04_4",z1e="_readonly_1ki04_5",R1e="_iconButton_1ki04_6",D1e="_textButton_1ki04_8",O1e="_guideEntry_1ki04_10",F1e="_imageButton_1ki04_10",B1e="_scroll_1ki04_11",H1e="_tree_1ki04_12",q1e="_level_1ki04_12",W1e="_row_1ki04_14",V1e="_chevron_1ki04_19",U1e="_name_1ki04_20",G1e="_state_1ki04_21",K1e="_preview_1ki04_22",Z1e="_markdown_1ki04_23",X1e="_code_1ki04_24",Y1e="_image_1ki04_10",Q1e="_guide_1ki04_10",J1e="_guideGrid_1ki04_30",ede="_guideIcon_1ki04_34",tde="_guideCopy_1ki04_36",nde="_guideLabel_1ki04_37",rde="_guideDescription_1ki04_38",ide="_title_1ki04_40",lo={body:A1e,toolbar:L1e,path:P1e,readonly:z1e,iconButton:R1e,textButton:D1e,guideEntry:O1e,imageButton:F1e,scroll:B1e,tree:H1e,level:q1e,row:W1e,chevron:V1e,name:U1e,state:G1e,preview:K1e,markdown:Z1e,code:X1e,image:Y1e,guide:Q1e,guideGrid:J1e,guideIcon:ede,guideCopy:tde,guideLabel:nde,guideDescription:rde,title:ide};function sde(t,e=[]){const n=T.useRef(new Map),r=T.useMemo(()=>{const y=t??"";let b=n.current.get(y);if(!b){const x=k=>({id:k,kind:"guide",contentId:"guide",title:"开始"});b={controller:new Due({makeInitialTab:x,makePaneTab:x}),resources:new Map,owners:new Map};const _=b;_.controller.subscribe(()=>{var S;const k=_.controller.getSnapshot().state.tabs;for(const[$,A]of _.resources)k[$]||((S=A.dispose)==null||S.call(A),_.resources.delete($));for(const $ of _.owners.keys())k[$]||_.owners.delete($)}),n.current.set(y,b)}return b},[t]),{controller:i,resources:s,owners:o}=r;T.useEffect(()=>{var y;for(const[b,x]of n.current)for(const _ of x.resources.values())(y=_.activate)==null||y.call(_,b===t)},[t]),T.useEffect(()=>{for(const y of n.current.values())for(const[b,x]of[...y.owners])e.includes(x)&&y.controller.closeTab(b)},[e]),T.useEffect(()=>()=>{var y;for(const b of n.current.values())for(const x of b.resources.values())(y=x.dispose)==null||y.call(x)},[]);const a=T.useSyncExternalStore(i.subscribe,i.getSnapshot),c=Kt(a.state,a.state.activePaneId).activeTabId,d=c?hu(a.state,c):void 0,h=(d==null?void 0:d.kind)==="plugin"?d.contentId:null,p=()=>{Object.keys(i.getSnapshot().state.tabs).length||i.openContent({kind:"guide",contentId:"guide",title:"开始"}),i.setExpanded(!0)},g=T.useCallback((y,b,x,_,k)=>{var R;const S=i.getSnapshot().state,$=_&&Kt(S,_).host==="dock"?_:fu(S),A=Kt(S,$),z=A.activeTabId&&((R=S.tabs[A.activeTabId])==null?void 0:R.kind)==="guide"?A.activeTabId:void 0,j=A.tabs.find(M=>{var N,P;return((N=S.tabs[M])==null?void 0:N.kind)===y&&((P=S.tabs[M])==null?void 0:P.contentId)===b}),L=j??i.openContent({kind:y,contentId:b,title:x,paneId:$,revealIfOpened:y!=="files"});return k&&o.set(L,k),j&&i.focusTab(j),z&&i.closeTab(z),i.setExpanded(!0),requestAnimationFrame(()=>{var M;return(M=document.querySelector(`[data-dockkit-content="${L}"]`))==null?void 0:M.focus()}),L},[i,o]);return{controller:i,snapshot:a,panelId:h,resources:s,owners:o,expand:p,openContent:g,shown:a.state.expanded&&Object.keys(a.state.tabs).length>0}}function ode({panel:t,width:e,narrow:n,focus:r,onExitFocus:i,plugins:s,props:o,cwd:a}){var L,R,M;const{controller:c,snapshot:d,openContent:h}=t,{state:p}=d,[g,y]=T.useState(""),b=T.useRef(!1),x=T.useMemo(()=>new Proxy(c,{get(N,P){if(P==="closeTab")return ee=>{var V;if(b.current)return;b.current=!0;const K=((V=o.session)==null?void 0:V.sessionId)??"";Nl.flush(K).then(async()=>{const B=document.querySelector(`[data-dockkit-content="${CSS.escape(ee)}"]`);B&&await Nl.retireWithin(K,B),y(""),N.closeTab(ee)}).catch(B=>y(B instanceof Error?B.message:String(B))).finally(()=>{b.current=!1})};const G=Reflect.get(N,P,N);return typeof G=="function"?G.bind(N):G}}),[c,(L=o.session)==null?void 0:L.sessionId]),_=n||p.mode==="fullscreen",k=o.locale==="zh"?xT:_T,S=N=>k[N]??N,$=N=>typeof N=="string"?N:N[o.locale],A=s.flatMap(N=>{var P;return(((P=N.definition.workbench)==null?void 0:P.panels)??[]).map(G=>({plugin:N,contribution:G}))}),z=()=>{i(),c.setExpanded(!1),requestAnimationFrame(()=>{var N;return(N=document.querySelector("[data-sidebar-right-expand]"))==null?void 0:N.focus()})},j=n?"100vw":e;return f.jsx("div",{className:N0.panel,style:{width:j,"--dsh-sidebar-width":typeof j=="number"?`${j}px`:j},"data-sidebar-right-session":(R=o.session)==null?void 0:R.sessionId,"data-sidebar-right-panel":_?"fullscreen":r?"focus":"push","data-sidebar-right-open":t.shown||void 0,"aria-hidden":!t.shown||void 0,children:f.jsxs("div",{className:N0.panelBody,children:[g&&f.jsx("p",{role:"alert",children:g}),f.jsx(r1e,{state:p,canSplit:d.canSplit&&Tp(p).length<2,dropZones:"horizontal",minPaneFraction:.2,intents:x,labels:d1e(S),active:!0,keepMounted:()=>!0,renderTab:N=>{const P=ms(p,N.id).id,G=p.expanded&&Kt(p,P).activeTabId===N.id;if(N.kind==="guide")return f.jsx("div",{className:lo.guide,children:f.jsxs("div",{className:lo.guideGrid,role:"group","aria-label":O("工作区工具","Workspace tools"),children:[s.map(K=>{var Y;const V=(Y=K.definition.workbench)==null?void 0:Y.entry;if(!V)return null;const B=V.icon;return f.jsxs("button",{type:"button",className:lo.guideEntry,disabled:!o.session||!a,"aria-label":$(V.label),onClick:()=>h(V.kind,V.multiple?Uc():"workspace",$(V.panelTitle??V.label),P,K.id),children:[f.jsx("span",{className:lo.guideIcon,"aria-hidden":"true",children:f.jsx(B,{size:24})}),f.jsxs("span",{className:lo.guideCopy,children:[f.jsx("span",{className:lo.guideLabel,children:$(V.label)}),f.jsx("span",{className:lo.guideDescription,children:$(V.description)})]})]},K.id)}),!s.some(K=>K.definition.workbench)&&f.jsx("p",{className:lo.state,children:O("没有已启用的工作区插件,可在设置中启用。","No workspace plugins enabled. Enable one in Settings.")})]})});const ee=A.find(K=>K.contribution.kind===N.kind);if(ee&&o.session){const{plugin:K,contribution:V}=ee;t.owners.set(N.id,K.id);const B=V.component,Y=(Z,ie,H)=>{let X=t.resources.get(N.id);if(!X){const ne=Z();X={value:ne,dispose:()=>ie==null?void 0:ie(ne),activate:U=>H==null?void 0:H(ne,U)},t.resources.set(N.id,X)}return X.value};return f.jsx(Np,{id:K.id,children:f.jsx(B,{sendMessage:o.sendMessage,session:o.session,locale:o.locale,visible:G,contentId:N.contentId,title:N.title,renderMarkdown:o.renderMarkdown,resource:Y,open:(Z,ie,H)=>h(Z,ie,H,P,K.id)})})}return f.jsx(W5,{plugins:s,slot:"rightbar.panel",props:{...o,panelId:N.contentId}})},renderTabTitle:N=>{var G,ee;if(N.kind==="guide")return S("tab.guide.title");const P=A.find(K=>K.contribution.kind===N.kind);return P?f.jsx("span",{className:lo.title,children:((ee=(G=P.contribution).title)==null?void 0:ee.call(G,N.contentId,N.title))??N.title}):f.jsx(W5,{plugins:s,slot:"rightbar.title",props:{...o,panelId:N.contentId}})},chrome:f.jsx(u1e,{sessionId:((M=o.session)==null?void 0:M.sessionId)??"",fullscreen:_||r,focus:r,shortcuts:[],t:S,actions:{toggleExpanded:z},toggleFullscreen:()=>r?i():n?z():c.setMode(_?"push":"fullscreen")})})]})})}function ade({panel:t,locale:e}){if(t.shown)return null;const n=e==="zh"?xT:_T;return f.jsx(yi,{label:n["chrome.expand"],side:"bottom",delayMs:500,children:f.jsx(x1e,{size:"sm",className:j_.button,"aria-label":n["chrome.expandAria"],"data-sidebar-right-expand":!0,onClick:t.expand,children:f.jsx(ag,{className:j_.icon})})})}function lde(t,e){const n=t.filter(r=>r.enabled&&r.generation!==void 0&&r.contribution&&r.documentUrl&&r.controllerUrl).map(r=>{const i=e.find(s=>s.pluginId===r.pluginId);return i&&i.generation===r.generation&&i.name===r.name&&i.documentUrl===r.documentUrl&&i.controllerUrl===r.controllerUrl&&JSON.stringify(i.contribution)===JSON.stringify(r.contribution)?i:r});return n.length===e.length&&n.every((r,i)=>r===e[i])?e:n}const wT="pi:hosted:unconfirmed-views:v1";function cde(){if(typeof sessionStorage>"u")return[];const t=sessionStorage.getItem(wT);if(!t)return[];const e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Invalid hosted view recovery journal; keep this tab for recovery");return e}const kT=cde();let zf=[...kT];function CT(){typeof sessionStorage<"u"&&sessionStorage.setItem(wT,JSON.stringify(zf))}function ude(t,e,n){zf.push({...t,viewToken:e,kind:n.kind,contentId:n.contentId}),CT()}function ST(t){zf=zf.filter(e=>e.viewToken!==t),CT()}function dde({sessionId:t}){const[e,n]=T.useState(kT),[r,i]=T.useState(""),[s,o]=T.useState(!1);return f.jsxs(f.Fragment,{children:[e.filter(a=>a.sessionId===t).map(a=>f.jsxs("section",{role:"alert","data-unconfirmed-view":a.mountId,children:[f.jsxs("p",{children:["Unconfirmed previous-document ",a.kind," view: ",a.contentId??a.mountId," (generation ",a.generation,"). Its latest edits have NOT been acknowledged. A restored or newer drawing does not prove this view is safe."]}),f.jsx("p",{children:"Check that this view is no longer open in another tab. Use the plugin's Download draft / local backup recovery first. If the latest draft cannot be recovered, discarding may permanently lose edits. Restore is a separate, explicit action and may replace the winning drawing."}),f.jsx("button",{disabled:s,onClick:()=>{window.confirm(`Discard ALL unconfirmed edits for ${a.kind} view ${a.mountId}? This does not save or restore them. Download any recoverable draft first.`)&&(o(!0),i(""),cs.view({...a,operation:"discard",confirmation:"discard-unconfirmed-edits"}).then(()=>{ST(a.viewToken),n(c=>c.filter(d=>d.viewToken!==a.viewToken))}).catch(c=>i(String(c))).finally(()=>o(!1)))},children:"Discard unconfirmed edits for this view"})]},a.viewToken)),r&&f.jsx("p",{role:"alert",children:r})]})}class hde{constructor(e=250,n=async r=>{const i=new AbortController,s=setTimeout(()=>i.abort(),5e3);try{return await h0("/views",{operation:"pollMany",views:r},i.signal)}finally{clearTimeout(s)}}){q(this,"entries",new Set);q(this,"timer");q(this,"running",!1);q(this,"interval");q(this,"request");this.interval=e,this.request=n}add(e){return this.entries.add(e),this.schedule(0),()=>{this.entries.delete(e),!this.entries.size&&this.timer&&(clearTimeout(this.timer),this.timer=void 0)}}schedule(e){this.running||this.timer||!this.entries.size||(this.timer=setTimeout(()=>{this.timer=void 0,this.tick()},e))}async tick(){this.running=!0;const e=[...this.entries];try{for(let n=0;n<e.length;n+=64){const r=e.slice(n,n+64).filter(s=>this.entries.has(s));if(!r.length)continue;const{replies:i}=await this.request(r.map(s=>s.input()));if(!Array.isArray(i)||i.length!==r.length)throw new Error("Invalid aggregate view reply");await Promise.all(r.map(async(s,o)=>{if(this.entries.has(s))try{const a=i[o];if(a.failure)throw Object.assign(new Error(a.failure.body.error),{status:a.failure.status});if(!a.reply||a.reply.viewToken!==s.input().viewToken)throw new Error("Mismatched view reply");await s.accept(a.reply)}catch(a){this.entries.delete(s),s.fail(a)}}))}}catch(n){for(const r of e)this.entries.delete(r)&&r.fail(n)}finally{this.running=!1,this.schedule(this.interval)}}}const fde=new hde;class pde{constructor(e,n,r,i,s,o=fde){q(this,"token","");q(this,"stopped",!1);q(this,"closed",!1);q(this,"closing");q(this,"abort",new AbortController);q(this,"unlisten");q(this,"after",0);q(this,"snapshot");q(this,"frozen",!1);q(this,"frameStarted",!1);q(this,"identity");q(this,"adapter");q(this,"mount");q(this,"reconnect");q(this,"failed");q(this,"poller");this.poller=o,this.identity=e,this.adapter=n,this.mount=r,this.reconnect=i,this.failed=s}get capability(){return{viewToken:this.token,mountId:this.identity.mountId}}connecting(){this.frameStarted=!0}async flushed(){await this.changed({dirty:!1,busy:!1})}async start(){this.token=(await cs.view({...this.identity,operation:"register",kind:this.mount.kind})).viewToken,ude(this.identity,this.token,this.mount)}listen(){this.stopped||this.unlisten||(this.unlisten=this.poller.add({input:()=>({...this.identity,viewToken:this.token,operation:"poll",after:this.after}),accept:e=>this.receive(e),fail:e=>{this.stopped||this.failed(e)}}))}retry(){var e;if(this.stopped)throw new Error("Closed view cannot reconnect");(e=this.unlisten)==null||e.call(this),this.unlisten=void 0,this.listen()}request(e){return cs.view({...this.identity,viewToken:this.token,...e},this.abort.signal)}async changed(e){const n=e;if(typeof(n==null?void 0:n.dirty)!="boolean"||typeof n.busy!="boolean")throw new Error("Invalid frame status");await this.request({operation:"change",dirty:n.dirty,busy:n.busy})}async receive(e){for(const n of e.commands){if(this.stopped)return;let r;try{if(n.type==="freeze"&&!this.frozen&&(this.snapshot=await this.adapter.call("freeze"),this.frozen=!0),n.type==="resume"&&this.frozen&&(await this.adapter.call("restore",this.snapshot),this.frozen=!1),n.type==="committed"){await this.request({operation:"ack",commandId:n.id,ok:!0}),await this.close(),this.reconnect();return}}catch(i){r=i}await this.request({operation:"ack",commandId:n.id,ok:!r,...r?{error:r instanceof Error?r.message:String(r)}:{}}),this.after=n.id,r&&this.failed(r)}}close(){var e;return this.closed?Promise.resolve():this.closing?this.closing:(this.stopped=!0,(e=this.unlisten)==null||e.call(this),this.abort.abort(),this.closing=(async()=>{this.token&&(this.frozen||(this.frameStarted&&await this.adapter.call("freeze"),await cs.view({...this.identity,viewToken:this.token,operation:"change",dirty:!1,busy:!1})),await cs.view({...this.identity,viewToken:this.token,operation:"close"}),this.closed=!0,ST(this.token))})().catch(n=>{throw this.closing=void 0,n}),this.closing)}}function mde(t){var i;const e=t;if(!e||!(e.blob instanceof Blob)||!e.blob.size||e.blob.size>16*1024*1024||typeof e.name!="string"||e.name.length>200||/[/\\\x00-\x1f\x7f]/.test(e.name))throw new Error("Invalid drawing download");const n=(i=e.name.split(".").pop())==null?void 0:i.toLowerCase(),r={png:"image/png",svg:"image/svg+xml",excalidraw:"application/json",json:"application/json"}[n??""];if(!r||e.blob.type!==r)throw new Error("Unsupported drawing download");return{blob:e.blob,name:e.name}}function gde(t){const{blob:e,name:n}=mde(t),r=URL.createObjectURL(e),i=document.createElement("a");i.href=r,i.download=n,i.hidden=!0,document.body.append(i);try{i.click()}finally{i.remove(),setTimeout(()=>URL.revokeObjectURL(r),3e4)}}function V5({card:t,mount:e,update:n,open:r,sendMessage:i,reconnect:s,abort:o}){const a=T.useRef(null),c=T.useRef(null),d=T.useRef(null),h=T.useRef(Promise.resolve()),p=T.useRef({open:r,sendMessage:i,reconnect:s,abort:o});p.current={open:r,sendMessage:i,reconnect:s,abort:o};const[g,y]=T.useState(""),[b,x]=T.useState(Vc);return T.useEffect(()=>{const _=new MutationObserver(()=>x(Vc()));return _.observe(document.body,{attributes:!0,attributeFilter:["data-ds-dark-theme"]}),()=>_.disconnect()},[]),T.useEffect(()=>{var L;if(!a.current||t.generation===void 0)return;const _={pluginId:t.pluginId,generation:t.generation,sessionId:e.sessionId,mountId:crypto.randomUUID()};let k=!0;const S=R=>{k&&y(R instanceof Error?R.message:String(R))};let $;const A=new TB(a.current,_,async(R,M)=>{var P;const N=M;if(R==="action"){if(typeof(N==null?void 0:N.action)!="string")throw new Error("Invalid action");return cs.action({sessionId:_.sessionId,pluginId:_.pluginId,generation:_.generation,...$.capability,action:N.action,input:N.input})}if(R==="downloadDrawing"&&["editor","workspace"].includes(e.kind))return gde(M),null;if(R==="changed")return $.changed(M);if(R==="abort"&&p.current.abort)return await p.current.abort(),null;if(R==="openPanel"){if(typeof(N==null?void 0:N.kind)!="string"||!((P=t.contribution)!=null&&P.panels.includes(N.kind))||typeof N.contentId!="string")throw new Error("Undeclared panel");return p.current.open(N.kind,N.contentId,typeof N.title=="string"?N.title:t.name),null}if(R==="sendMessage"&&typeof(N==null?void 0:N.text)=="string")return await p.current.sendMessage(N.text),null;throw new Error(`Unsupported frame host method: ${R}`)});$=new pde(_,A,e,()=>p.current.reconnect(),S),c.current=A,d.current=$;const z=(async()=>{if(await $.start(),!k)throw new Error("Frame mount cancelled");$.connecting(),await A.connect(e.kind==="controller"?t.controllerUrl:t.documentUrl,{...e,theme:Vc()}),$.listen()})();h.current=z;const j=Nl.add({identity:_,ready:z,adapter:A,afterFlush:()=>$.flushed(),toolCallId:(L=n==null?void 0:n.call)==null?void 0:L.toolCallId,retire:()=>$.close()});return z.catch(S),()=>{k=!1,j(),c.current=null,d.current=null,z.catch(()=>{}).then(()=>$.close()).catch(R=>console.error("Hosted view cleanup did not acknowledge edits",R)).finally(()=>A.dispose())}},[t.pluginId,t.generation,t.documentUrl,t.controllerUrl,e.sessionId,e.kind,e.contentId]),T.useEffect(()=>{h.current.then(()=>{var _;return(_=c.current)==null?void 0:_.call("update",{...e,...n??{},theme:b})}).catch(_=>y(String(_)))},[n,e.locale,b,e.visible,e.title]),f.jsxs("div",{"data-hosted-plugin":t.pluginId,style:{height:e.kind==="controller"?"auto":e.kind==="tool"?240:"100%",minHeight:0},children:[g&&f.jsxs("p",{role:"alert",children:[g," ",f.jsx("button",{type:"button",onClick:()=>{var _;try{(_=d.current)==null||_.retry(),y("")}catch(k){y(String(k))}},children:"Retry view connection"})]}),f.jsx("iframe",{hidden:e.kind==="controller",ref:a,title:`${t.name} ${e.kind}`,style:{width:"100%",height:"100%",border:0}})]})}const Vc=()=>document.body.hasAttribute("data-ds-dark-theme")?"dark":"light";function yde(t,e,n){const r=t.contribution,i=s=>`hosted:${t.pluginId}:${s}`;return{id:t.pluginId,instanceId:`${t.pluginId}/${t.generation}`,definition:{id:t.pluginId,apiVersion:1,activate(){},artifactTools:r.artifactTools,workbench:{apiVersion:1,entry:{...r.entry,kind:i(r.entry.kind),icon:()=>f.jsx("span",{"aria-hidden":"true",children:"◇"})},panels:r.panels.map(s=>({kind:i(s),component:o=>f.jsx(V5,{card:t,reconnect:e,abort:()=>{var a,c;return((c=(a=n.current).abort)==null?void 0:c.call(a))??Promise.reject(new Error("Abort unavailable"))},mount:{kind:s===r.entry.kind?"workspace":"editor",sessionId:o.session.sessionId,contentId:o.contentId,title:o.title,visible:o.visible,locale:o.locale,theme:Vc()},open:(a,c,d)=>o.open(i(a),c,d),sendMessage:o.sendMessage})})),toolViews:r.toolViews.length?[{tools:r.toolViews,component:s=>s.session?f.jsx(V5,{card:t,reconnect:e,abort:()=>{var o,a;return((a=(o=n.current).abort)==null?void 0:a.call(o))??Promise.reject(new Error("Abort unavailable"))},mount:{kind:"tool",sessionId:s.session.sessionId,locale:s.locale,theme:Vc()},update:{call:s.call,result:s.result,running:s.running},open:(o,a)=>s.openPanel(`${r.panelAlias.prefix}${a}`),sendMessage:s.sendMessage},Nl.incarnation(s.session.sessionId,s.call.toolCallId)):null}]:[],resolvePanel:s=>s.startsWith(r.panelAlias.prefix)?{kind:i(r.panelAlias.kind),contentId:s.slice(r.panelAlias.prefix.length),title:r.panelAlias.title}:null}}}}function vde(t,e,n,r,i){const[s,o]=T.useState([]),[a,c]=T.useState(0),[d,h]=T.useState(""),p=T.useMemo(()=>()=>c(x=>x+1),[]);T.useEffect(()=>{if(!t||!e){o([]);return}let x=!0;const _=new AbortController;return window.addEventListener("pi:hosted-catalog-changed",p),cs.catalog(_.signal).then(k=>{x&&(o(S=>lde(k.plugins,S)),h(""))}).catch(k=>{x&&k.status!==404&&h(String(k))}),()=>{x=!1,_.abort(),window.removeEventListener("pi:hosted-catalog-changed",p)}},[t,e,n,a]);const g=T.useRef(new WeakMap),y=T.useMemo(()=>s.map(x=>{let _=g.current.get(x);return _||(_=yde(x,p,r),g.current.set(x,_)),_}),[s,p,r]),b=t&&e?s.map(x=>f.jsx(V5,{card:x,reconnect:p,abort:()=>{var _,k;return((k=(_=r.current).abort)==null?void 0:k.call(_))??Promise.reject(new Error("Abort unavailable"))},mount:{kind:"controller",sessionId:e,locale:i,theme:Vc()},open:(_,k)=>{var S,$;return($=(S=r.current).openPanel)==null?void 0:$.call(S,`${x.contribution.panelAlias.prefix}${k}`)},sendMessage:async _=>{if(!r.current.sendMessage)throw new Error("Composer unavailable");await r.current.sendMessage(_)}},`${e}/${x.pluginId}/${x.generation}`)):null;return{plugins:t?y:[],controllers:f.jsxs(f.Fragment,{children:[f.jsx(dde,{sessionId:e}),b]}),error:d}}const U5="@chengzhiyi/pi-excalidraw",M_=["excalidraw_create_view","diagram_create","diagram_patch"];function bde(t){const e=({locale:n})=>f.jsxs("section",{role:"status",style:{padding:16},children:[f.jsx("h3",{children:"Excalidraw"}),f.jsx("p",{children:n==="zh"?"请安装或启用官方 Excalidraw 插件以恢复旧图稿。未从历史工具参数重建图稿;原检查点、工作区文件和浏览器备份均保留。":"Install or enable the official Excalidraw plugin to recover this drawing. Historical tool arguments are not the latest scene. Checkpoints, workspace files and browser backups are preserved."}),f.jsx("button",{onClick:t,children:n==="zh"?"打开插件管理":"Open plugin management"})]});return{id:U5,instanceId:"drawing-recovery",definition:{id:U5,apiVersion:1,activate(){},artifactTools:M_,workbench:{apiVersion:1,entry:{label:"Excalidraw",description:{zh:"安装或启用官方绘图插件",en:"Install or enable the official drawing plugin"},kind:"drawing-recovery",icon:ug},panels:[{kind:"drawing-recovery",component:e}],toolViews:[{tools:M_,component:e}],resolvePanel:n=>/^diagram:[\w-]{1,80}$/.test(n)?{kind:"drawing-recovery",contentId:n.slice(8),title:"Excalidraw"}:null}}}}function xde(){var Pe,$e,ze,We,ye,it,vt,Ct;const t=xi(),e={"session.new.label":O("新会话","New session"),"session.new":O("新会话","New session"),"toggle.open":O("展开侧栏","Expand sidebar"),"toggle.collapse":O("收起侧栏","Collapse sidebar"),"sidebar.label":O("对话管理","Conversation navigation"),"sidebar.close":O("关闭侧栏","Close sidebar"),"panels.label":O("面板","Panels"),"rightbar.drag.focus":O("继续拖动以专注工作区","Keep dragging to focus workspace"),"rightbar.drag.collapse":O("继续拖动以收起工作区面板","Keep dragging to collapse workspace panel"),"brand.localBuild":"pi-webapp"},n=tee(),r=T.useRef((Pe=n.session)==null?void 0:Pe.sessionId);r.current=($e=n.session)==null?void 0:$e.sessionId;const[i,s]=T.useState("");T.useEffect(()=>s(""),[(ze=n.session)==null?void 0:ze.sessionId]);const{plugins:o,errors:a}=I1e(n.connection==="connected",(We=n.session)==null?void 0:We.sessionId,n.plugins,n.pluginGeneration),c=T.useRef({}),d=vde(n.connection==="connected",(ye=n.session)==null?void 0:ye.sessionId,n.pluginGeneration,c,t),[h,p]=T.useState(!1),[g,y]=T.useState(!1),b=T.useMemo(()=>bde(()=>y(!0)),[]),x=[...o,...d.plugins.filter(pe=>!o.some(Re=>{var et;return Re.id===pe.id||((et=Re.definition.artifactTools)==null?void 0:et.some(qe=>{var Ye;return(Ye=pe.definition.artifactTools)==null?void 0:Ye.includes(qe)}))}))],_=x.some(pe=>pe.id===U5)?x:[...x,b],k=sde((it=n.session)==null?void 0:it.sessionId,n.disabledPlugins),S=k.panelId,$=n.connection==="connected"&&n.session!==null&&n.modelsStatus==="ready"&&n.models.length===0;T.useEffect(()=>{$&&p(!0)},[$]);const A=T.useCallback(()=>{p(!1),requestAnimationFrame(()=>{var pe;return(pe=document.querySelector('[aria-haspopup="dialog"].pi-settings-sidebar'))==null?void 0:pe.focus()})},[]),[z,j]=T.useState(()=>({sidebar:280,viewportWidth:window.innerWidth,narrowExpanded:!1,rightbar:null,rightbarShown:!1,rightbarTrack:!1,rightbarFullscreen:!1,rightbarFocus:!1,rightbarInstant:!1})),L=T.useRef(280),R=T.useRef(!1),[M,N]=T.useState(!1),P=T.useCallback(()=>j(pe=>({...pe,narrowExpanded:!1})),[]),G=async pe=>{var Re;if(!R.current){R.current=!0,N(!0);try{(Re=n.session)!=null&&Re.sessionId&&await Nl.flush(n.session.sessionId),await pe(),y(!1),P()}catch(et){throw s(et instanceof Error?et.message:String(et)),et}finally{R.current=!1,N(!1)}}},ee=T.useMemo(()=>({closeSidebar:P,setViewportWidth(pe){j(Re=>Re.viewportWidth===pe?Re:{...Re,viewportWidth:pe,narrowExpanded:Re.viewportWidth<1024!=pe<1024?!1:Re.narrowExpanded})},setSidebar(pe){L.current=Math.min(420,Math.max(264,Math.round(pe))),j(Re=>({...Re,sidebar:L.current}))},setRightbar(pe){j(Re=>({...Re,rightbar:J3(pe,ya,Re.viewportWidth*Z5)}))},focusRightbar(){j(pe=>({...pe,rightbarFocus:!0}))},collapseRightbar(){j(pe=>({...pe,rightbarFocus:!1})),k.controller.setExpanded(!1)}}),[P,k.controller]),K=pe=>{const Re=_.flatMap(et=>{var Ye,tt;const qe=(tt=(Ye=et.definition.workbench)==null?void 0:Ye.resolvePanel)==null?void 0:tt.call(Ye,pe);return qe?[{...qe,pluginId:et.id}]:[]})[0];Re?k.openContent(Re.kind,Re.contentId,Re.title,void 0,Re.pluginId):k.controller.openContent({kind:"plugin",contentId:pe,title:O("预览","Preview")}),k.controller.setExpanded(!0),j(et=>({...et,narrowExpanded:!1}))},V=()=>k.controller.setExpanded(!1),B=T.useCallback(pe=>{if(!n.session||n.disabledPlugins.includes(ua.files))return;const Re=oM(n.session.cwd,pe);k.openContent("file-preview",Re,Re.split("/").at(-1),void 0,ua.files),j(et=>({...et,narrowExpanded:!1}))},[(vt=n.session)==null?void 0:vt.cwd,n.disabledPlugins,k.openContent]);T.useEffect(()=>{const pe=z.viewportWidth<767||k.snapshot.state.mode==="fullscreen";j(Re=>({...Re,rightbarShown:k.shown&&!g,rightbarTrack:k.shown&&!g,rightbarFullscreen:pe,rightbarFocus:Re.rightbarFocus&&k.shown&&!g&&!pe}))},[k.shown,k.snapshot.state.mode,z.viewportWidth,g]),T.useEffect(()=>{j(pe=>pe.rightbarFocus?{...pe,rightbarFocus:!1}:pe)},[(Ct=n.session)==null?void 0:Ct.sessionId]);const Y=T.useCallback(pe=>f.jsx(Mce,{text:pe,labels:{code:{copyLabel:O("复制","Copy"),copiedLabel:O("已复制","Copied"),toolbarLabels:{codeLabel:O("代码块","Code block"),wrapLabel:O("自动换行","Wrap"),unwrapLabel:O("取消换行","Unwrap")}},footnotes:O("脚注","Footnotes")}}),[t]),Z=async(...pe)=>{var et,qe,Ye;const Re=(et=n.session)==null?void 0:et.sessionId;s("");try{if(Re){await Nl.flush(Re);for(const tt of _)await((Ye=(qe=tt.definition.workbench)==null?void 0:qe.beforeSend)==null?void 0:Ye.call(qe,Re))}if(Re!==r.current)throw new Error(O("会话已切换,请在原会话重试","Session changed. Retry in the original conversation."))}catch(tt){throw s(tt instanceof Error?tt.message:String(tt)),tt}return n.send(...pe)},ie={session:n.session,locale:t,openPanel:K,closePanel:V,panelId:S,invokePluginAction:n.invokePluginAction,resolvePluginInteraction:n.resolvePluginInteraction,sendMessage:pe=>Z(pe,[]),renderMarkdown:Y};c.current={openPanel:K,sendMessage:ie.sendMessage,abort:n.stop};const H=(pe,Re)=>f.jsx(W5,{plugins:_,slot:pe,props:{...ie,turn:Re}}),X=()=>j(pe=>pe.viewportWidth<1024?{...pe,narrowExpanded:!pe.narrowExpanded}:{...pe,sidebar:pe.sidebar===0?L.current:0}),ne=pe=>pe({layoutInfo:z}),U=pe=>pe({activePanelId:g?"plugins":null}),me=pe=>pe([{id:"plugins",label:O("插件","Plugins")}]),be=(pe,Re,et)=>pe==="sidebar.brand.mark"?f.jsx(jh,{size:24}):pe==="sidebar.brand.name"?f.jsx("span",{children:"pi-webapp"}):pe==="sidebar.footer.action"?f.jsx(XJ,{wide:Re.wide,getUpdate:n.getUpdate,getRunningVersion:n.getRunningVersion,setUpdateChannel:n.setUpdateChannel,update:n.update}):pe==="sidebar.panellist"?f.jsx(JK,{size:Re.size}):pe==="sidebar.settings"?f.jsx("div",{className:`pi-settings-trigger-row ${Re.wide?"":"pi-settings-trigger-rail"}`,children:f.jsxs("button",{className:"pi-settings-sidebar","data-wide":Re.wide,type:"button","aria-label":O("Pi 设置","Pi Settings"),"aria-haspopup":"dialog","aria-expanded":h,onClick:()=>p(!0),children:[Re.wide?f.jsx(V_,{size:16}):f.jsx(fj,{size:18}),Re.wide&&f.jsx("span",{children:O("Pi 设置","Pi Settings")})]})}):pe==="sidebar.workspaces"?f.jsx(pQ,{wide:Re.wide,expandSidebar:Re.expandSidebar,session:n.session,workspaces:n.workspaces,navigationBusy:M,connected:n.connection==="connected"&&n.session!==null,onAdd:(qe,Ye)=>G(()=>n.addWorkspace(qe,Ye)),directoryPickerKind:n.directoryPickerKind,pickDirectory:n.pickDirectory,listDirectory:n.listDirectory,createDirectory:n.createDirectory,onRemove:qe=>G(()=>n.removeWorkspace(qe)),onSelectSession:(qe,Ye,tt)=>G(()=>n.selectSession(qe,Ye,tt)),onNewSession:qe=>G(()=>n.newSessionInWorkspace(qe))}):(et==null?void 0:et.fallback)??null,ve=(pe,Re)=>{var et,qe,Ye,tt;return pe==="sidebar"?f.jsx(sM,{collapsed:Re.collapsed,width:Re.width,startSession:()=>{G(n.newSession).catch(()=>{})},sessionBusy:M||n.connection!=="connected"||n.session===null,toggleSidebar:X,selectPanel:()=>{y(!0),P()},usePanels:me,usePanelInfo:U,t:ce=>e[ce]??ce,renderSlot:be}):pe==="main"?f.jsxs(f.Fragment,{children:[f.jsx("div",{hidden:g,style:{height:"100%"},children:f.jsx(IO,{openFile:B,children:f.jsx(dX,{rightbarControl:f.jsx(ade,{panel:k,locale:t}),session:n.session,streaming:n.streaming,connection:n.connection,error:i||n.error,onSend:Z,onUpdateQueuedPrompt:n.updateQueuedPrompt,onLoadImage:n.loadMessageImage,onUpload:n.upload,onDiscardAttachment:n.discardAttachment,onStop:n.stop,onResume:n.resume,onCompact:n.compact,onNewSession:()=>G(n.newSession),commands:n.commands,models:n.models,modelsStatus:n.modelsStatus,onConfigureModels:()=>p(!0),onSetModel:n.setModel,onSetThinkingLevel:n.setThinkingLevel,composerInteraction:(qe=(et=n.session)==null?void 0:et.interactions)!=null&&qe.some(ce=>_.some(Ke=>{var xt;return Ke.id===ce.pluginId&&((xt=Ke.definition.interactions)==null?void 0:xt.some(en=>en.kind===ce.kind))}))?f.jsx(j1e,{plugins:_,props:ie}):void 0,renderToolView:(ce,Ke,xt)=>f.jsx(M1e,{plugins:_,props:ie,call:ce,result:Ke,running:xt}),renderPluginSlot:H,plugins:_,onPluginAction:n.invokePluginAction})})}),g&&f.jsx(qJ,{getPluginManagement:n.getPluginManagement,togglePlugin:n.togglePlugin,generation:n.pluginGeneration})]}):pe==="rightbar"&&Object.keys(k.snapshot.state.tabs).length>0?f.jsx("div",{hidden:g,style:{height:"100%"},children:f.jsx(ode,{panel:k,cwd:(Ye=n.session)==null?void 0:Ye.cwd,width:Re.width,narrow:z.viewportWidth<767,focus:z.rightbarFocus,onExitFocus:()=>j(ce=>({...ce,rightbarFocus:!1})),plugins:_,props:ie},(tt=n.session)==null?void 0:tt.sessionId)}):null};return f.jsxs(f.Fragment,{children:[d.controllers,d.error&&f.jsx("p",{role:"alert",children:d.error}),f.jsx(oj,{useStore:ne,usePanelInfo:U,actions:ee,renderSlot:ve,t:pe=>e[pe]??pe}),a.length>0&&f.jsxs("div",{className:"pi-plugin-errors",role:"status",title:a.join(`
542
542
  `),children:[O("插件加载失败","Plugin load failed"),": ",a.length]}),h&&f.jsx(uJ,{onBack:A,setupMode:$,getConfig:n.getConfig,updateConfig:n.updateConfig,getUpdate:n.getUpdate,getRunningVersion:n.getRunningVersion,setUpdateChannel:n.setUpdateChannel,update:n.update,getProviders:n.getProviders,getProviderModels:n.getProviderModels,updateProviderModel:n.updateProviderModel,logoutProvider:n.logoutProvider,addCustomProvider:n.addCustomProvider,startProviderLogin:n.startProviderLogin,getProviderLogin:n.getProviderLogin,getActiveProviderLogin:n.getActiveProviderLogin,respondProviderLogin:n.respondProviderLogin,cancelProviderLogin:n.cancelProviderLogin,refreshModels:n.refreshModels})]})}vQ();DI();const ET=document.getElementById("root");if(!ET)throw new Error("Missing #root");zI.createRoot(ET).render(f.jsx(FI,{children:f.jsx(xde,{})}));const Nde=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ua as B,Yae as C,Uf as F,DS as H,Sde as I,Vf as M,ml as a,zc as b,hk as c,Tde as d,x1e as e,lo as f,IK as g,TK as h,$de as i,f as j,EK as k,O as l,kK as m,gae as n,gT as o,Nde as p,T as r,pae as s,hae as t,xi as u};
543
+
544
+ //# debugId=cd1b9111-b0a3-4930-92c8-7b8af2b65fb9
@@ -1,9 +1,11 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/app-CkT84si6.js","assets/app.css"])))=>i.map(i=>d[i]);
2
- var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb996b76-e418-4b9b-860e-421fb711a574",e._sentryDebugIdIdentifier="sentry-dbid-eb996b76-e418-4b9b-860e-421fb711a574")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();const B="modulepreload",D=function(e){return"/"+e},I={},A=function(t,i,r){let s=Promise.resolve();if(i&&i.length>0){let a=function(o){return Promise.all(o.map(l=>Promise.resolve(l).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),m=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));s=a(i.map(o=>{if(o=D(o),o in I)return;I[o]=!0;const l=o.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${g}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":B,l||(f.as="script"),f.crossOrigin="",f.href=o,m&&f.setAttribute("nonce",m),document.head.appendChild(f),l)return new Promise((T,N)=>{f.addEventListener("load",T),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})},j=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),q=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ee={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},R=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"]),U=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/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 te(e){return e==="/api/message"||e==="/api/prompt-queue"||e.startsWith("/api/provider/")||e.startsWith("/api/workspace/files/")||e.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(e)}function p(e){return e.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 h(e){const t={};for(const i of R){const r=e[i];i==="toolName"?typeof r=="string"&&(j.has(r)||r==="custom")&&(t[i]=r):i==="failureKind"?q.has(r)&&(t[i]=r):i==="level"?(r==="warning"||r==="error")&&(t[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(t[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)&&(t[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(t[i]=r):i==="route"&&typeof r=="string"?t[i]=U.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?t[i]=r.split("/").map(p).join("/"):typeof r=="string"?t[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:p(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(t[i]=r)}return t}function v(e){var r;const t=e.replace(/\\/g,"/").split(/[?#]/)[0];return t.startsWith("node:")?t.slice(0,150):`app:///${(((r=t.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/))==null?void 0:r[1])??t.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function S(e,t=0){const i=e instanceof Error?e:new Error(typeof e=="string"?e:"Non-Error rejection"),r=new Error(p(i.message));if(r.name=p(i.name).slice(0,100),i.stack){const s=i.stack.split(`
2
+ var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c106f5ef-6da5-41c2-9f53-ef83c3b25ea7",e._sentryDebugIdIdentifier="sentry-dbid-c106f5ef-6da5-41c2-9f53-ef83c3b25ea7")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();const B="modulepreload",D=function(e){return"/"+e},I={},A=function(t,i,r){let s=Promise.resolve();if(i&&i.length>0){let a=function(o){return Promise.all(o.map(l=>Promise.resolve(l).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),m=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));s=a(i.map(o=>{if(o=D(o),o in I)return;I[o]=!0;const l=o.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${g}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":B,l||(u.as="script"),u.crossOrigin="",u.href=o,m&&u.setAttribute("nonce",m),document.head.appendChild(u),l)return new Promise((T,N)=>{u.addEventListener("load",T),u.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})},j=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),q=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ee={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},R=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"]),U=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/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 te(e){return e==="/api/message"||e==="/api/prompt-queue"||e.startsWith("/api/provider/")||e.startsWith("/api/workspace/files/")||e.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(e)}function p(e){return e.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 h(e){const t={};for(const i of R){const r=e[i];i==="toolName"?typeof r=="string"&&(j.has(r)||r==="custom")&&(t[i]=r):i==="failureKind"?q.has(r)&&(t[i]=r):i==="level"?(r==="warning"||r==="error")&&(t[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(t[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)&&(t[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(t[i]=r):i==="route"&&typeof r=="string"?t[i]=U.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?t[i]=r.split("/").map(p).join("/"):typeof r=="string"?t[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:p(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(t[i]=r)}return t}function v(e){var r;const t=e.replace(/\\/g,"/").split(/[?#]/)[0];return t.startsWith("node:")?t.slice(0,150):`app:///${(((r=t.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/))==null?void 0:r[1])??t.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function S(e,t=0){const i=e instanceof Error?e:new Error(typeof e=="string"?e:"Non-Error rejection"),r=new Error(p(i.message));if(r.name=p(i.name).slice(0,100),i.stack){const s=i.stack.split(`
3
3
  `).slice(1,31).map(n=>{const a=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${p(n.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:p(n)});r.stack=`${r.name}: ${r.message}
4
4
  ${s.join(`
5
5
  `)}`}else r.stack=void 0;return t<3&&i.cause!==void 0&&(r.cause=S(i.cause,t+1)),r}function re(e,t){const i=new Error(t);return e instanceof Error&&(i.name=e.name,e.stack&&(i.stack=`${i.name}: ${t}
6
6
  ${e.stack.split(`
7
7
  `).slice(1).join(`
8
8
  `)}`)),i}function F(e){return{...e.filename?{filename:v(e.filename)}:{},...e.abs_path?{abs_path:v(e.abs_path)}:{},...e.function?{function:p(e.function)}:{},lineno:e.lineno,colno:e.colno,in_app:e.in_app}}function K(e){var r,s,n,a,c,m;const t=h(((r=e.contexts)==null?void 0:r.diagnostic)??{}),i=C(t);return{event_id:e.event_id,timestamp:e.timestamp,platform:e.platform,level:e.level,release:e.release,dist:e.dist,environment:p(e.environment??"production"),...e.message?{message:p(e.message)}:{},exception:e.exception?{values:(s=e.exception.values)==null?void 0:s.slice(0,4).map(o=>{var l;return{type:p(o.type??"Error"),value:p(o.value??""),...o.stacktrace?{stacktrace:{frames:(l=o.stacktrace.frames)==null?void 0:l.slice(-30).map(F)}}:{},...o.mechanism?{mechanism:{type:o.mechanism.type,handled:o.mechanism.handled}}:{}}})}:void 0,tags:{side:(n=e.tags)==null?void 0:n.side,buildId:(a=e.tags)==null?void 0:a.buildId,...t.toolName?{toolName:t.toolName}:{},...t.failureKind?{failureKind:t.failureKind}:{},...t.errorCode?{errorCode:t.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:t},breadcrumbs:(c=e.breadcrumbs)==null?void 0:c.slice(-100).map(o=>({timestamp:o.timestamp,category:p(o.category??"app"),data:h(o.data??{})})),debug_meta:e.debug_meta?{images:(m=e.debug_meta.images)==null?void 0:m.slice(0,10).map(o=>({type:o.type,debug_id:o.debug_id,...o.code_file?{code_file:v(o.code_file)}:{}}))}:void 0}}function C(e){if(!(e.stage!=="tool"||e.originalStackAvailable!==!1||!e.toolName||!e.failureKind))return["pi-webapp-tool-result",String(e.toolName),String(e.toolId??"builtin"),String(e.failureKind),String(e.errorCode??"unknown")]}function ie(e,t){return t.attachments=[],K(e)}class Z{constructor(){d(this,"items",[]);d(this,"bytes",0);d(this,"encoder",new TextEncoder)}add(t,i={}){const r={timestamp:Date.now()/1e3,category:p(t),data:h(i)},s=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:s}),this.bytes+=s;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:t})=>t)}}class V{constructor(){d(this,"windowAt",-1);d(this,"total",0);d(this,"seen",new Map)}take(t,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);const r=this.seen.get(t);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(t,{at:i,repeats:0}),{repeats:(r==null?void 0:r.repeats)??0}}}const W=new Set(["目录路径必须是绝对路径","父目录路径必须是绝对路径","文件夹名称无效","工作区目录不可用,请恢复目录或从列表移除后重新添加","会话已切换","Pi 正在运行,请等待当前回复结束","请等待当前回复结束","请等待当前回复结束再切换工作区","请等待当前回复结束再切换会话","请先切换到其他工作区","新会话已取消","已有登录正在进行","模型不可用","模型提供方未配置认证","当前模型不支持此推理强度","其他提供方的登录正在进行,请先完成或取消当前登录","当前会话没有暂停的任务","请先完成当前交互或审批","请先选择模型","请先连接当前模型","插件未启用","会话运行实例已切换","提供方已存在","文件超过 20 MB","请求内容过大","会话不属于该工作区","推理强度无效"]);function L(e){return e instanceof Error&&(e.name==="AbortError"||W.has(e.message))}class se{constructor(t,i,r,s,n=new Z){d(this,"budget",new V);d(this,"breadcrumbs");d(this,"scopeClass");d(this,"seen",new WeakSet);d(this,"state",{});d(this,"client");d(this,"side");d(this,"buildId");this.client=t,this.side=i,this.buildId=r,this.scopeClass=s.Scope,this.breadcrumbs=n,t.addIntegration(s.linkedErrorsIntegration({limit:4}))}setState(t){this.state=h(t)}capture(t,i={},r){var s;try{if(L(t))return;if(typeof t=="object"&&t!==null){if(this.seen.has(t))return;this.seen.add(t)}const n=S(t),a=h({...this.state,...i}),c=C(a),m=c?JSON.stringify(c):`${n.name}:${n.message}:${((s=n.stack)==null?void 0:s.split(`
9
- `)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.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")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.31-alpha.5+0619b36bc9d18102ac62",J="0619b36bc9d18102ac62";function Q(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}let u,z=!0,$=!1,P=!1,_=[];const E=new WeakSet,b=new Map;let y={};function k(e,t={}){try{if(L(e))return;if(typeof e=="object"&&e!==null){if(E.has(e))return;E.add(e)}if(u)return u.capture(e,t);z&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){u==null||u.breadcrumbs.add(e,t)}function ce(e){e.sessionId&&(b.has(e.sessionId)||(b.size>=32&&b.delete(b.keys().next().value),b.set(e.sessionId,Q())),e={...e,session:b.get(e.sessionId)}),y=h({...y,...e}),u==null||u.setState(y)}function G(){$||($=!0,P=new URL(location.href).searchParams.get("sentry_release_probe")==="1",window.addEventListener("error",e=>{e instanceof ErrorEvent?k(e.error??new Error(e.message),{stage:"global"}):(e.target instanceof HTMLScriptElement||e.target instanceof HTMLLinkElement)&&k(new Error("Application resource failed to load"),{stage:"resource"})},!0),window.addEventListener("unhandledrejection",e=>k(e.reason,{stage:"unhandled_rejection"})),X())}async function X(){var e;try{const t=M();if(!t)return;const i=await fetch("/api/telemetry/config",{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e3)});if(!i.ok)return;const r=await i.json();if(!r.enabled||!r.dsn)return;const{createBrowserReporter:s}=await A(async()=>{const{createBrowserReporter:a}=await import("./telemetry-client-CBQBug9X.js");return{createBrowserReporter:a}},[]);u=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";u.setState({...y,browser:n,platform:navigator.platform}),y={...y,browser:n,platform:navigator.platform};for(const a of _)u.capture(a.error,a.context);r.environment==="sentry-verification"&&P&&u.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],z=!1}}G();A(()=>import("./app-CkT84si6.js").then(e=>e.p),__vite__mapDeps([0,1])).catch(e=>k(e,{stage:"startup"}));export{se as E,A as _,Q as a,te as b,ae as c,M as d,ie as e,ne as f,oe as i,re as o,ee as p,k as r,ce as s};
9
+ `)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.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")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.31+1b52d187e9527c28544f",J="1b52d187e9527c28544f";function Q(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}let f,z=!0,$=!1,P=!1,_=[];const E=new WeakSet,y=new Map;let b={};function k(e,t={}){try{if(L(e))return;if(typeof e=="object"&&e!==null){if(E.has(e))return;E.add(e)}if(f)return f.capture(e,t);z&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){f==null||f.breadcrumbs.add(e,t)}function ce(e){e.sessionId&&(y.has(e.sessionId)||(y.size>=32&&y.delete(y.keys().next().value),y.set(e.sessionId,Q())),e={...e,session:y.get(e.sessionId)}),b=h({...b,...e}),f==null||f.setState(b)}function G(){$||($=!0,P=new URL(location.href).searchParams.get("sentry_release_probe")==="1",window.addEventListener("error",e=>{e instanceof ErrorEvent?k(e.error??new Error(e.message),{stage:"global"}):(e.target instanceof HTMLScriptElement||e.target instanceof HTMLLinkElement)&&k(new Error("Application resource failed to load"),{stage:"resource"})},!0),window.addEventListener("unhandledrejection",e=>k(e.reason,{stage:"unhandled_rejection"})),X())}async function X(){var e;try{const t=M();if(!t)return;const i=await fetch("/api/telemetry/config",{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e3)});if(!i.ok)return;const r=await i.json();if(!r.enabled||!r.dsn)return;const{createBrowserReporter:s}=await A(async()=>{const{createBrowserReporter:a}=await import("./telemetry-client-CBQBug9X.js");return{createBrowserReporter:a}},[]);f=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";f.setState({...b,browser:n,platform:navigator.platform}),b={...b,browser:n,platform:navigator.platform};for(const a of _)f.capture(a.error,a.context);r.environment==="sentry-verification"&&P&&f.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],z=!1}}G();A(()=>import("./app-CkT84si6.js").then(e=>e.p),__vite__mapDeps([0,1])).catch(e=>k(e,{stage:"startup"}));export{se as E,A as _,Q as a,te as b,ae as c,M as d,ie as e,ne as f,oe as i,re as o,ee as p,k as r,ce as s};
10
+
11
+ //# debugId=c106f5ef-6da5-41c2-9f53-ef83c3b25ea7