pi-webapp 0.1.38-alpha.2 → 0.1.39-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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]="22c0885d-1b53-4ae4-8036-c222e68dddce",r._sentryDebugIdIdentifier="sentry-dbid-22c0885d-1b53-4ae4-8036-c222e68dddce")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Oe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}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 Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as A,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function S(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await A(r,J.O_RDONLY|J.O_NONBLOCK|(J.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 i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(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 I(r){let e=await g(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 b(r,e){let t=`${r}.${me()}.tmp`,n=await A(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await A(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await S(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await A(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await A(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as x,copyFile as _e,rm as xe}from"node:fs/promises";import{dirname as Se,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var N=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Pe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(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 D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(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");T(t.next),T(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 s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await x(d(this.root,"fork.json"))}return await x(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).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 s=T({...t,generation:e+1,operationId:G()});await S(d(this.root,"states")),await S(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await x(d(this.root,"transition.json")),await x(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(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 b(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),N))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(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=T(await I(d(this.root,"previous.json")));if(!t&&await g(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 i=[t,n].filter(l=>!!l),s=d(this.root,"states");await S(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),N);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.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(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}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(i);for(let l of a)c.has(l)||await xe(d(s,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,`${y(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 i=Pe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key)),N);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key));if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>N)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,N);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);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")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!L(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(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 Z(Se(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(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:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(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 Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await x(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await x(p).catch(()=>{}),await u.close(),await x(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Oe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(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 g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(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 se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"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 oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[P,le,O,j,q,...Ae]=process.argv.slice(2),Ne=le&&!Ae.length&&(P==="inspect"&&!O&&!j&&!q||P==="recover-locks"&&O&&j&&!q||["recover-fork","reconcile-transition"].includes(P??"")&&O&&j&&q);if(!Ne)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]="dae7ac1a-0e54-4b9d-9a3e-4c6a8a6884bd",r._sentryDebugIdIdentifier="sentry-dbid-dae7ac1a-0e54-4b9d-9a3e-4c6a8a6884bd")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Oe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}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 Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as A,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function S(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await A(r,J.O_RDONLY|J.O_NONBLOCK|(J.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 i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(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 I(r){let e=await g(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 b(r,e){let t=`${r}.${me()}.tmp`,n=await A(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await A(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await S(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await A(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await A(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as x,copyFile as _e,rm as xe}from"node:fs/promises";import{dirname as Se,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var N=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Pe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(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 D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(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");T(t.next),T(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 s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await x(d(this.root,"fork.json"))}return await x(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).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 s=T({...t,generation:e+1,operationId:G()});await S(d(this.root,"states")),await S(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await x(d(this.root,"transition.json")),await x(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(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 b(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),N))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(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=T(await I(d(this.root,"previous.json")));if(!t&&await g(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 i=[t,n].filter(l=>!!l),s=d(this.root,"states");await S(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),N);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.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(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}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(i);for(let l of a)c.has(l)||await xe(d(s,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,`${y(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 i=Pe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key)),N);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key));if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>N)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,N);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);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")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!L(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(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 Z(Se(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(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:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(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 Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await x(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await x(p).catch(()=>{}),await u.close(),await x(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Oe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(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 g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(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 se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"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 oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[P,le,O,j,q,...Ae]=process.argv.slice(2),Ne=le&&!Ae.length&&(P==="inspect"&&!O&&!j&&!q||P==="recover-locks"&&O&&j&&!q||["recover-fork","reconcile-transition"].includes(P??"")&&O&&j&&q);if(!Ne)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=je(le),e=P==="inspect"?await $(r):P==="recover-locks"?await ce(r,O,j):P==="recover-fork"?await ae(r,O,j,q):await se(r,O,j,q);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var mt=void 0;export{mt as default};
7
7
 
8
- //# debugId=22c0885d-1b53-4ae4-8036-c222e68dddce
8
+ //# debugId=dae7ac1a-0e54-4b9d-9a3e-4c6a8a6884bd
@@ -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]="c867f2e8-772c-4975-81b8-0085d499d42e",t._sentryDebugIdIdentifier="sentry-dbid-c867f2e8-772c-4975-81b8-0085d499d42e")}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]="e5513558-9b26-4322-a25e-ad8d4bb6874d",t._sentryDebugIdIdentifier="sentry-dbid-e5513558-9b26-4322-a25e-ad8d4bb6874d")}catch{}})();import{AsyncLocalStorage as b}from"node:async_hooks";import{pathToFileURL as y}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 b,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(y(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=c867f2e8-772c-4975-81b8-0085d499d42e
3
+ //# debugId=e5513558-9b26-4322-a25e-ad8d4bb6874d
@@ -1,5 +1,8 @@
1
1
  # Hosted UI / all-window barrier handoff (ORI-26)
2
2
 
3
+ Current host-owned tool chrome, page-level parameter dialogs and the evaluated
4
+ Shadow DOM boundary are described in [hosted tool UI](hosted-tool-ui.md).
5
+
3
6
  Historical frontend milestone; current optional-default ownership and builtin removal
4
7
  are documented in [migration verification](hosted-excalidraw-migration.md). The earlier
5
8
  scope below is preserved as provenance, not the current composition.
@@ -0,0 +1,319 @@
1
+ # Hosted tool UI (2026-10-29)
2
+
3
+ ## Scope and acceptance
4
+
5
+ Fix collapsed drawing cards retaining a 240px iframe, inline parameter details,
6
+ and ambiguous uninstall confirmation. The host owns generic card chrome,
7
+ parameter dialogs and operation confirmations; the independently installed
8
+ plugin owns preview/editor rendering and business state. No host code may inspect
9
+ the plugin DOM. Retain authenticated scoped RPC, CAS persistence, all-view save
10
+ barriers, version checks, archive integrity and the iframe adapter.
11
+
12
+ Acceptance: repeated collapse uses only header height; long parameters use a
13
+ viewport-bounded, themed dialog with focus containment and restoration; uninstall,
14
+ disable and immediate update explain the requested operation. Actual packaged
15
+ plugin tests must exercise preview → editor → edit → save → close/update, failure
16
+ retention, multiple mounts and disposal.
17
+
18
+ ## Ordered implementation
19
+
20
+ 1. Add failing browser regressions and an additive tool UI capability contract.
21
+ 2. Negotiate host tool chrome and content-size reports over the existing private
22
+ MessagePort. Keep collapsed frames mounted and coordinated. Render parameter
23
+ text from host-owned tool inputs/results, never plugin-provided HTML.
24
+ 3. Distinguish management confirmation copy; preserve the operation/save barrier.
25
+ 4. Test Shadow DOM with the pinned real editor, audit global resources/lifecycle,
26
+ and document the smallest safe production boundary. Do not migrate the editor
27
+ merely to remove the iframe.
28
+ 5. Run independent build/package checks, focused browser and lifecycle suites,
29
+ type checks and domain/transport tests; record actual coverage and limitations.
30
+
31
+ The pre-existing untracked `.pi-tasks/` directory is outside this change. No
32
+ publishing, pushing, deployment or release-version change is authorized.
33
+
34
+ ## Decision: host chrome, isolated plugin content
35
+
36
+ Production remains data/RPC + iframe content. The host owns tool chrome,
37
+ parameters, mount-scoped notifications and existing JSON-contributed sidebar/panel
38
+ routes. The plugin owns previews, candidates, native editing and business state.
39
+ Generic host UI imports no Excalidraw code and never reads its DOM or React state.
40
+ The reviewed official catalog in integration.ts remains unchanged; opening
41
+ arbitrary additional hosted packages is outside this change.
42
+
43
+ The card takes ordinary tool call/result data and a child renderer independent of
44
+ transport. A future trusted custom element can use this seam after meeting the
45
+ lifecycle contract, including registration with the existing view coordinator.
46
+ No uncoordinated custom-element loader is introduced in production.
47
+
48
+ ## Additive UI protocol
49
+
50
+ initialize may include `hostUi: { toolCard: true, autoResize: true,
51
+ notifications: true }`. Services are individually optional. Runtime protocol stays
52
+ 1; no new required backend capability or protocol npm release is needed.
53
+
54
+ | Private-port method | Input | Host behavior |
55
+ | --- | --- | --- |
56
+ | toolPresentation | `{title: string}` (nonempty, ≤160 characters) | Tool mounts only; enables native host chrome. Plugin renders only preview after acceptance. |
57
+ | resize | `{height: number}` (finite, 0–4096 CSS pixels) | Tool mounts only; rounds up with a 1px floor. No DOM inspection. |
58
+ | notify | `{message: string, level: "info" \| "error"}` (≤4000 characters) | Dismissible mount-owned status/alert; no HTML. |
59
+
60
+ All messages use the origin/source/mount/generation-bound private MessagePort and
61
+ grant no backend authority. Dead mounts reject late UI requests. Parameters are
62
+ text from the host's current call/result, never plugin-provided HTML. Theme and
63
+ language continue through initialize/update. The body-portaled dialog uses host
64
+ tokens, a bounded scroll area and shared focus containment. Updated contents do
65
+ not recreate the dialog owner.
66
+
67
+ The plugin measures its own auto-height root with ResizeObserver and coalesces
68
+ reports with requestAnimationFrame. Tool roots use auto height, avoiding feedback
69
+ from the iframe viewport that prevents shrinking. Expanded previews keep scroll
70
+ limits. Collapse hides the host body without unmounting its iframe, retaining
71
+ readiness, edits and barrier membership. Expand does not create a new identity.
72
+
73
+ ## Compatibility
74
+
75
+ - New host + new plugin: native card/dialog and automatic preview height.
76
+ - New host + old frame: no opt-in or duplicate header; existing 240px legacy
77
+ rendering stays supported. Old collapse/dialog bugs require a plugin update.
78
+ - Old host + new plugin: legacy chrome plus a real native HTML dialog, necessarily
79
+ bounded by the old iframe viewport. Both updates are needed for the full fix.
80
+
81
+ ## Lifecycle and upgrade
82
+
83
+ 1. Register the authenticated view, connect the immutable document and exact
84
+ identity, negotiate optional UI, and acknowledge actual realm readiness.
85
+ 2. Update call/result, locale, theme and visibility within the same session.
86
+ Folding is presentation only; it neither creates nor closes a view.
87
+ 3. Send/close/disable/uninstall/replacement retain the all-view flush/freeze
88
+ barrier. Failed saves retain views/generation. Ordinary updates wait for
89
+ editors; immediate update warns of clearing native undo/redo history.
90
+ 4. Dispose removes the host overlay/focus listeners. Plugin cleanup disconnects
91
+ the size observer, cancels its queued animation frame, unmounts React, disposes
92
+ models and removes timers/global events/ports. React effects release thumbnail
93
+ blobs, polling, theme observers, beforeunload and Canvas resources. Existing
94
+ pagehide handles realm teardown. Abrupt loss retains unknown-view recovery;
95
+ no clean acknowledgment is invented.
96
+ 5. Committed generations use fresh iframe realms and digest-qualified immutable
97
+ URLs, avoiding old module state. Catalog/status refreshes retain frames/undo.
98
+ Archive retention/garbage collection are unchanged; assets are not prematurely
99
+ deleted. No production custom-element registry/cache is introduced.
100
+
101
+ ## Web Components / Shadow DOM evidence
102
+
103
+ The plugin's test/shadow-dom.browser.mjs imports the actual built Canvas and exact
104
+ bundled React copy, injects the full stylesheet into an open Shadow Root, opens
105
+ native Help, and mounts/disposes two guarded custom elements. It reproduces an
106
+ unstyled body portal: Help's .Modal computes to position static, versus absolute
107
+ in the real iframe editor; the fixture expands to approximately 9,000px height.
108
+ Evidence and screenshot: pi-extensions/artifacts/shadow-dom-probe/.
109
+
110
+ Concrete additional source constraints:
111
+
112
+ - canvas-env.ts writes window.EXCALIDRAW_ASSET_PATH; Canvas/vendor font handling
113
+ uses document.fonts. Vendor code queries document.activeElement and creates
114
+ a body-level .excalidraw-tooltip. Shadow DOM redirects none of these operations.
115
+ - rpc.ts owns a module-level port/pending map; model.ts owns a registry with
116
+ dispose-all; interaction.ts owns one busy flag. Sharing these unchanged in a
117
+ document couples mounts and disposal.
118
+ - Guarding a stable element tag does not upgrade its constructor. Cache-busted
119
+ dynamic import does not unload modules, listeners or FontFaces.
120
+
121
+ Benefits would include natural content sizing, direct DOM focus integration and
122
+ fewer document/React copies for lightweight renderers. The native card/dialog seam
123
+ already obtains the main UX benefit without migrating the editor. Trust does not
124
+ isolate window/document. A safe editor adapter requires instance-owned RPC/model/
125
+ busy/disposal scopes, supported portal and focus roots, scoped styles/font
126
+ ownership and a versioned renderer factory, then the same multi-view/native
127
+ regressions. These are migration gates, not a claim Shadow DOM can never work.
128
+
129
+ React stays pinned/bundled inside the independently built plugin (18.3.1); host
130
+ React is not injected/shared. The probe deliberately uses the exact plugin
131
+ React/ReactDOM pair. A future component adapter must inject CSS per shadow root,
132
+ use immutable module-relative assets, explicitly arrange fonts/portals, and pass
133
+ locale/theme per instance instead of mutating the host body. Injecting all vendor
134
+ CSS into the host to cover escaped portals defeats the intended style boundary.
135
+
136
+
137
+ ## Verification record
138
+
139
+ Executed on macOS with real headless Chromium and isolated temporary workspaces.
140
+ Registry/provider transports in hosted browser fixtures are deterministic local
141
+ fixtures; SDK sessions, workers, package installation, authenticated HTTP, view
142
+ registration, saves and freeze acknowledgments are real. Synthetic upgrade
143
+ versions change only test release metadata, not the frontend payload.
144
+
145
+ | Check | Result |
146
+ | --- | --- |
147
+ | Host npm run check / npm run build | Passed (existing bundle-size/Sentry proxy warnings remain). |
148
+ | Host npm test | 463 Node + 94 desktop tests passed; 5 conditional skips. |
149
+ | Actual 0.1.2 archive install/import/save/drain/restart/disable/uninstall | Separately passed with explicit archive/version; not counted as a skip. |
150
+ | Plugin repository pnpm check / pnpm test | Passed: 40 script, 7 protocol, 19 Excalidraw, 54 plan-mode tests. Used installed Node 22.23.2 for the repository's transform-types test script. |
151
+ | Host browser final UI/management/production/owned-runtime matrix | 11 passed, including desktop/mobile full lifecycle and injected save failure. |
152
+ | Host native parity / native compat / viewport parity | 13 passed, including IME events, drag, shortcuts, native source/SVG/PNG, zoom/pan, streaming and competing windows. |
153
+ | Pre-change plugin package with new host | Production desktop lifecycle passed; legacy rendering remains available. |
154
+ | Exact package verify / independent offline build | Passed; 152 copied dependency versions, no host module resolution, 427 controlled resources. |
155
+ | Plugin iframe browser test | Handshake, native drag, busy/flush/freeze/restore/session fence/dispose passed. |
156
+ | Strict-CSP archive browser | Passed: Chinese SVG font decode, PNG/source export, frame-local legacy dialog; zero CSP violations, external requests or console/page errors. |
157
+ | Shadow DOM probe | Successfully reproduced the body-portal/style incompatibility; two mounts and two disposals, zero external requests/page errors. |
158
+
159
+ New regression coverage: repeated fold/unfold with unchanged iframe identity;
160
+ long parameters at 390px dark/1440px light; Shift-Tab/Tab, Escape, button close,
161
+ programmatic focus escape and restoration; two independent cards/editors; native
162
+ Chinese text and composition events; actual failed checkpoints preventing tab
163
+ close/uninstall/immediate update; retained edits subsequently saved and surviving
164
+ replacement; three disable/enable cycles with an open parameter dialog removed,
165
+ no host focus-listener growth, no residual host portals and no console errors.
166
+
167
+ CSP fixture maintenance fixes a stale hardcoded archive version and implements
168
+ the existing host-owned download relay in the independent test harness. It does
169
+ not relax CSP or change production export code. Host fixtures normalize metadata
170
+ for their local synthetic releases. The native/legacy iframe adapters are retained.
171
+
172
+ Evidence is local and ignored by Git:
173
+
174
+ - Host artifacts/hosted-tool-ui/: host-tests.log, host-build.log, final-browser/,
175
+ failure-retention/, cleanup/, screenshots/, legacy-compat/.
176
+ - Plugin artifacts/shadow-dom-probe/: evidence.json and body-portal.png.
177
+ - Plugin artifacts/chengzhiyi-pi-excalidraw-0.1.2.tgz: independently packed artifact.
178
+
179
+ Not certified: OS-native IME candidate windows, packaged Electron/Windows/Linux
180
+ interaction, Firefox/WebKit, live npm/provider networks, or the 50-generation
181
+ browser stress suite. Full host tests conditionally skip two external-version
182
+ archive gates, hot bootstrap gate and Windows PTY; the exact current archive gate
183
+ was run separately. Native IME coverage here is browser composition/text insertion.
184
+ The full editor is not migrated to Shadow DOM; required instance/portal/font/cache
185
+ work is described above. No package versions, lockfiles, server authorization,
186
+ state schema or broker save/coordination rules changed; no publish/push/deploy.
187
+
188
+ ## Refresh recovery UI follow-up
189
+
190
+ Recovery records previously rendered as unstyled sections before AppFrame. Since
191
+ AppFrame consumes 100% of the viewport, those sections pushed the entire app below
192
+ the fold, producing document scrollbars and incorrect resize geometry. Recovery
193
+ now lives in plugin management, with an explanation and a bounded, themed
194
+ details dialog. Recovery never renders before AppFrame or floats over the
195
+ conversation. Each discard uses a separate confirmation;
196
+ cancel/failure preserves the journal and capability. Dismissing the dialog only
197
+ hides details, not the recovery entry.
198
+
199
+ The optional host view operation `reconcile` returns `recovery: closed` only for
200
+ an authenticated, already retired capability (accepted close or explicit discard).
201
+ A clean/frozen view or a generation change is not a substitute for the actual
202
+ close receipt: its owner may still be active. Subsequent local edits may not have
203
+ reached the host. Unknown tokens/server restart/evicted proof records remain
204
+ unconfirmed. The in-memory retired-proof cache is bounded to 1024; eviction never
205
+ confers permission to discard. Scope checks include user, workspace, session,
206
+ mount, generation and token. Old hosts without this operation retain all records.
207
+
208
+ Browser coverage adds real repeated reloads with checkpoint preservation,
209
+ sidebar dragging, 390/1024/1440 viewport changes, and 20 pending records in 320px
210
+ Chinese dark/1440px English light dialogs. It checks no document overflow or frame
211
+ offset, internal scrolling, cancel focus restoration, failed discard retention,
212
+ and automatic removal of server-confirmed closed records. Unit coverage proves
213
+ clean-looking/dirty/unknown views cannot be silently retired, and even a
214
+ committed old generation needs its actual close receipt before automatic removal.
215
+
216
+ ## Launcher and uninstall follow-up
217
+
218
+ The workspace adapter previously used a font diamond while management used a
219
+ pencil. Hosted cards now carry an optional reviewed `icon` key; the host's shared
220
+ artwork registry supplies both surfaces. The offline catalog provides artwork for
221
+ absent packages and older hosts. This imports no plugin editor or business code.
222
+ The disclosure uses a fixed 24px SVG container instead of baseline-aligned text,
223
+ including on narrow screens.
224
+
225
+ A history renderer's `workbench.entry` is now optional. The drawing history fallback
226
+ keeps explicit historical links and tool output readable, but contributes no
227
+ workspace launcher. After an authoritative catalog reports disabled/uninstalled,
228
+ all owned tabs in retained session docks close. Pending updates, failed catalog
229
+ reads and save-barrier failures do not authorize this cleanup. Frozen realms close
230
+ through the existing capability flow; no host reads plugin DOM or model state.
231
+ Uninstallation displays the authoritative uninstalled state with a Reinstall
232
+ action. Reinstall/enable restores access to existing drawings, without reopening
233
+ old editor tabs implicitly.
234
+
235
+ Refreshing destroys a document before asynchronous frame flush/close can finish.
236
+ A clean-looking status is insufficient to discard possibly newer local edits.
237
+ The recovery list is therefore retained, but only shown inside plugin management,
238
+ with an explanation of its effect on disable/uninstall. A `view_barrier` error now
239
+ explains the pending save confirmation. Confirmed closes are still removed via
240
+ `reconcile`. After a server restart, explicit per-record `discard` may dismiss an
241
+ unknown capability; it acknowledges no save, changes no drawing and cannot retire
242
+ another live capability. The host never auto-discards records, clears another
243
+ tab's storage or weakens the all-view save barrier.
244
+
245
+ Browser regression: real independently installed Excalidraw in English/Chinese,
246
+ 1440px/390px, with an unresolved old editor plus an edited live editor. Failed
247
+ uninstall retains the editor/package; explicit recovery followed by uninstall
248
+ removes the launcher and owned tabs and enables reinstallation. Reinstallation
249
+ preserves scene elements and restores the same workspace/management icon. Existing
250
+ collapse/parameter regressions additionally measure SVG vertical centering.
251
+
252
+
253
+ Verification for this follow-up: 14 browser cases passed (the 12-case UI set,
254
+ plus both corrected production lifecycle cases), 466 Node tests + 94 desktop
255
+ tests passed (5 pre-existing skips), targeted final integration/routes/client
256
+ checks passed, and typecheck/full build passed. Browser evidence lives under
257
+ `artifacts/hosted-tool-ui/uninstall-acceptance`, `uninstall-production`, and
258
+ `uninstall-chain`. The existing live preview receives the compatible frontend
259
+ without force-restarting its old backend or discarding uncertain drafts. New
260
+ server reconciliation/retained-data metadata applies on the next safe restart;
261
+ older-backend artwork/reinstall fallbacks remain supported.
262
+
263
+
264
+ ## Alpha integration
265
+
266
+ The alpha merge keeps its existing structured `HostedViewRecovery` contract.
267
+ The close-proof cache reports `recovery.state = retired`; unknown authoring
268
+ capabilities remain `absent` and need explicit review, not automatic dismissal.
269
+ Controller-only records and provably unstarted registrations use alpha's existing
270
+ safe retirement/cancellation rules. Editable drafts still require a real save
271
+ barrier or an explicit, separately confirmed recovery decision.
272
+
273
+ Recovery reconciliation runs in a host hook even when management is closed, so
274
+ refreshing a controller-only document cannot accumulate lifecycle blockers. Its
275
+ UI appears only in plugin management. The themed page dialog retains alpha's
276
+ per-view backup snapshots/downloads, opening a drawing for comparison, and
277
+ retain-for-recovery action. Retention revokes stale writes without replacing or
278
+ discarding a drawing. Both retention and discard use the host modal/focus system.
279
+ The merge preserves alpha's per-plugin publication isolation and app-owned update
280
+ recovery; it does not replace those changes with older boolean recovery flags.
281
+
282
+
283
+ Alpha merge verification: 513 Node tests and 94 desktop tests passed (5 existing
284
+ skips), 35 recovery/lifecycle focused tests passed, and typecheck/full build
285
+ passed. Twenty browser scenarios were verified, including controller-only reload,
286
+ real dirty-draft backup download and explicit retention, per-view discard failure,
287
+ operation confirmations, independent cards/editors, update, uninstall/reinstall,
288
+ themed narrow dialogs, and keyboard focus. Browser evidence is in
289
+ `artifacts/alpha-merge/browser` and `artifacts/alpha-merge/browser-followup`.
290
+
291
+ ## Complete CI matrix follow-up
292
+
293
+ The dialog focus boundary includes React-owned portal menus. Modal and drawer
294
+ providers supply an owning element ref; MenuSurface registers its portal layer
295
+ before moving focus and unregisters on unmount. Focus outside that scope is still
296
+ contained. Escape belongs to the innermost menu first, and closes the drawer only
297
+ after its menu has closed. The ownership registry contains host UI elements, not
298
+ plugin DOM/state, and creates no global event listeners of its own.
299
+
300
+ CI keeps the immutable public Excalidraw 0.1.0 fixture for legacy compatibility and
301
+ adds a separate `HOSTED_TOOL_UI_TGZ` pinned to public 0.1.3. Both use SHA-512 SRI;
302
+ the newer fixture also verifies release provenance against source commit
303
+ `d419333729106787d069ca9617a7637b66d4280d`. Native chrome tests explicitly select the
304
+ UI-capable fixture; they never silently substitute it for legacy regressions. An
305
+ additional real legacy iframe/editor test proves negotiation fallback still works.
306
+ The public npm install/upgrade gate continues using actual registry transport.
307
+
308
+ Workspace-grid tests now assert the three specific enabled launchers and absence
309
+ of a drawing launcher, rather than counting every BUILTIN_IDS metadata entry.
310
+ Public reinstall tests select Reinstall; competing-window recovery tests open
311
+ management and separately confirm each old capability in the new dialog. Their
312
+ scene/CAS, downloadable backup, losing geometry and clean-shutdown assertions are
313
+ preserved. No retry, timeout, lifecycle gate or test-group exclusion is relaxed.
314
+
315
+ The full matrix also exposed a terminal-test sampling race: a fullscreen mode
316
+ attribute changes before ResizeObserver/HTTP resize reaches the PTY. The test now
317
+ uses a fresh, completed shell measurement for each query, waits for the actual
318
+ fullscreen size change, and requires the original push size to return on exit.
319
+ This strengthens the existing resize assertion without changing terminal behavior.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.38-alpha.2",
3
+ "version": "0.1.39-alpha.1",
4
4
  "type": "module",
5
5
  "piWebappDesktopProtocol": 1,
6
6
  "piWebappDataVersion": 1,
@@ -30,7 +30,7 @@
30
30
  "pi-webapp": "./bin/pi-webapp.mjs"
31
31
  },
32
32
  "pi": {
33
- "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.38-alpha.2/assets/cover-webapp.png",
33
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.39-alpha.1/assets/cover-webapp.png",
34
34
  "extensions": [
35
35
  "./dist/extension.js"
36
36
  ]