pi-webapp 0.1.34-alpha.1 → 0.1.34-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +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]="f1c0e2bd-3adb-47fa-a32b-20af8e71ad62",r._sentryDebugIdIdentifier="sentry-dbid-f1c0e2bd-3adb-47fa-a32b-20af8e71ad62")}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 de,join as fe}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(de(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=fe(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 f,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=f(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(f(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(f(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(d=>a[d]===c[d]))(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(f(this.root,"previous.json"),i),n==="committed"){let a=await b(f(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(f(this.root,"fork.json"))}return await _(f(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(f(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(f(this.root,"states")),await S(f(this.root,"states",i.stateRef)),await m(f(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(f(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(f(this.root,"previous.json"),n),await _(f(this.root,"transition.json")),await _(f(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=f(this.root,"states",n);if(await b(f(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(f(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=f(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(f(i,a),j))throw new o("invalid_storage","Missing state file");await me(f(i,a),f(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(f(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(f(this.root,"previous.json")));if(!t&&await w(f(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=f(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=f(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(f(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(f(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 d=await e(s);for(let l of a)c.has(l)||await ye(f(i,l),{recursive:!0,force:!0});return d})}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 f(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 d=await x(a,j);d&&this.validateState(d);let l=h(c);if(d?.requestId===e.requestId&&d.inputHash===l)return{revision:d.revision,schema:d.schema,value:d.value};if((d?.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 d=await w(a,c);return d?{text:new TextDecoder("utf-8",{fatal:!0}).decode(d),hash:h(d)}: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,d=a.split(J);for(let u=0;u<d.length;u++){c=f(c,d[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<d.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<d.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=f(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),d=h(n.text),l=await x(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==d))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===d)return{hash:d};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:d,committed:!1}),p=f(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:d,committed:!0}),{hash:d}}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),d=s+a,l=await Z(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,d+"/");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:d,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")),d=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))||!d||l&&typeof l.stateRef!="string"||[d?.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]="39116fca-54fa-445f-99b7-a69ae7126a27",r._sentryDebugIdIdentifier="sentry-dbid-39116fca-54fa-445f-99b7-a69ae7126a27")}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
- 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 dt=void 0;export{dt as default};
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
7
 
8
- //# debugId=f1c0e2bd-3adb-47fa-a32b-20af8e71ad62
8
+ //# debugId=39116fca-54fa-445f-99b7-a69ae7126a27
@@ -1,3 +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]="f6412e77-b38d-4579-a9ff-7491f15d8846",t._sentryDebugIdIdentifier="sentry-dbid-f6412e77-b38d-4579-a9ff-7491f15d8846")}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 f=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(p,g){let u=f.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:p,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 f.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]="c925315f-d8aa-4bc2-bc18-a16378642822",t._sentryDebugIdIdentifier="sentry-dbid-c925315f-d8aa-4bc2-bc18-a16378642822")}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
2
 
3
- //# debugId=f6412e77-b38d-4579-a9ff-7491f15d8846
3
+ //# debugId=c925315f-d8aa-4bc2-bc18-a16378642822
@@ -0,0 +1,80 @@
1
+ # ORI-53 — drain hosted plugins before a managed update restart
2
+
3
+ ## Failure chain
4
+
5
+ The update route previously set `restarting` before staging and rejected **all**
6
+ hosted POSTs. Later, launcher EOF initiated `session_shutdown`, which requires
7
+ registered views to poll, checkpoint and acknowledge a freeze. The updater's
8
+ HTTP fence prevented those requests. The view barrier permits 15 seconds, but
9
+ the launcher forces termination after 5 seconds. A killed host can leave
10
+ `runtime.lock`; the selected host then refuses plugin ownership and leaves the
11
+ pair journal in `required-action`, blocking the next update.
12
+
13
+ Startup reconciliation also attempted a second management update while that
14
+ pair was pending, replacing the original ownership error with the generic
15
+ `Host pair selection pending` diagnostic.
16
+
17
+ ## Corrected ordering
18
+
19
+ 1. The update route fences ordinary mutations and stages/selects the host/plugin
20
+ pair using the existing integrity, snapshot and pointer checks.
21
+ 2. Before requesting launcher EOF, `SelfUpdater.beforeRestart` calls the
22
+ production hosted integration's shutdown **while authenticated HTTP and
23
+ retained session scopes remain alive**.
24
+ 3. During the fence, existing view capabilities may poll (including pollMany),
25
+ report status, acknowledge and close. New mounts, discard and plugin management
26
+ remain blocked. Actions receive a server-only `checkpointOnly` flag: only the
27
+ already-reviewed checkpoint actions for the exact authenticated active freeze
28
+ capability may execute. JSON cannot override this flag. Bearer, origin,
29
+ workspace/session, generation and mount/token checks remain in place.
30
+ 4. Agent settlement and view flush complete before workers exit and ownership is
31
+ released. A failed flush writes **no restart marker**, returns an HTTP error
32
+ instead of an early 202, restores admission and permits retrying the exact
33
+ retained selection without downloading/selecting a second pair. Changing the
34
+ requested target during that retry is refused.
35
+ 5. After draining, the pair coordinator revalidates host/plugin bytes, active
36
+ state/policy fingerprints and the host selection pointer, then writes the
37
+ restart marker. Only then does the update route return 202. The subsequent
38
+ `session_shutdown` reuses the completed shutdown promise rather than starting
39
+ another view freeze. Shutdown does not disable persisted plugin intent or
40
+ roll back active state.
41
+
42
+ Existing view CHANGE requests are validated against the coordinator's committed
43
+ identity, not the supervisor's transient `active` phase: status notifications
44
+ must remain possible during draining, while old-generation status after commit
45
+ must still fail.
46
+
47
+ ## Diagnostics and existing abandoned locks
48
+
49
+ Startup preserves the actual error code (for example `runtime_owned`) and adds
50
+ its detail to the pending pair journal. Host-linked reconciliation skips a
51
+ pending pair instead of overwriting its startup diagnostic. Subsequent update
52
+ errors include the pending version, phase and recorded cause.
53
+
54
+ This is **not automatic stale-lock reclamation**. A missing PID alone is not
55
+ proof that all owners are stopped. Existing abandoned locks still require the
56
+ stopped-owner, verified-backup, exact-fingerprint recovery procedure in
57
+ [hosted-update-recovery.md](hosted-update-recovery.md). Do not delete the pair
58
+ journal, restore its `before` pointer, or bypass an integrity failure. This code
59
+ change does not mutate an already-running installed release or repair its disk
60
+ state in place.
61
+
62
+ ## Verification
63
+
64
+ - `npm run check`: passed.
65
+ - `npm run build`: passed; inherited chunk-size and Sentry default-export warnings.
66
+ - `npm test`: Node **453 total, 448 passed, 5 skipped, 0 failed**; desktop
67
+ **94 passed, 0 failed**. Optional external-archive/bootstrap and native-platform
68
+ tests keep their existing environment/platform gates.
69
+ - New `test/hosted-restart.test.ts` exercises the real HTTP bridge, updater,
70
+ pair coordinator, hosted manager and child worker with synthetic host packages
71
+ (no npm download or synthetic launcher execution): successful restart ordering,
72
+ negative flush and exact-selection retry, status transport during draining,
73
+ mutation fencing, bearer/origin/forged-scope/capability rejection, ownership
74
+ release, unchanged enabled/generation/stateRef at shutdown, idempotent shutdown,
75
+ next-host reconciliation and preservation of an injected abandoned lock/error.
76
+ - Existing npm/desktop pair, SDK batch, view transport, supervisor ownership,
77
+ launcher, update-safety and recovery suites passed in the full run.
78
+
79
+ No package publication, remote push, live-service restart, online 0.1.33 upgrade,
80
+ or existing user-data/lock recovery is included in this change.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.34-alpha.1",
3
+ "version": "0.1.34-alpha.3",
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.34-alpha.1/assets/cover-webapp.png",
32
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.34-alpha.3/assets/cover-webapp.png",
33
33
  "extensions": [
34
34
  "./dist/extension.js"
35
35
  ]
@@ -1,11 +1,11 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/app-BasYjacK.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]="df3262db-13d1-41ad-bd44-ff239826dd96",e._sentryDebugIdIdentifier="sentry-dbid-df3262db-13d1-41ad-bd44-ff239826dd96")}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]="95e13711-f543-472c-9dd1-214d74cf2319",e._sentryDebugIdIdentifier="sentry-dbid-95e13711-f543-472c-9dd1-214d74cf2319")}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.34-alpha.1+29cca9da0a471e60e7d0",J="29cca9da0a471e60e7d0";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,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(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&&(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}),u==null||u.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}},[]);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({...b,browser:n,platform:navigator.platform}),b={...b,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-BasYjacK.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 b;function M(){if(b!==void 0)return b;const e=location.hash.slice(1);try{b=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{b=e||null}return e&&history.replaceState(null,"",location.pathname),b}const H="pi-webapp@0.1.34-alpha.3+3950596c0a14f9eeff6f",J="3950596c0a14f9eeff6f";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 w={};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)}),w=h({...w,...e}),f==null||f.setState(w)}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({...w,browser:n,platform:navigator.platform}),w={...w,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-BasYjacK.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
10
 
11
- //# debugId=df3262db-13d1-41ad-bd44-ff239826dd96
11
+ //# debugId=95e13711-f543-472c-9dd1-214d74cf2319