pi-webapp 0.1.52-alpha.7 → 0.1.52-alpha.8

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,4 +1,4 @@
1
- (function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="e325e116-1dbd-4c8a-a503-c738d4f775e9",t._sentryDebugIdIdentifier="sentry-dbid-e325e116-1dbd-4c8a-a503-c738d4f775e9")}catch{}})();import{resolve as Je}from"node:path";import{lstat as ce,mkdir as Le,readdir as Ce,rename as le}from"node:fs/promises";import{join as b}from"node:path";import{createHash as we}from"node:crypto";var s=class extends Error{code;status;reason;constructor(e,r,n={}){super(r),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=t=>t.code==="ENOENT";var et={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var v=t=>we("sha256").update(t).digest("hex");import{constants as U}from"node:fs";import{DatabaseSync as me}from"node:sqlite";import{lstat as Y,mkdir as ye,open as N,rename as ve,unlink as Q}from"node:fs/promises";import{dirname as be,join as X,resolve as ke}from"node:path";import{randomUUID as Ie}from"node:crypto";import{setTimeout as _e}from"node:timers/promises";async function R(t){await ye(t,{recursive:!0,mode:448});let e=await Y(t);if(!e.isDirectory()||e.isSymbolicLink())throw new s("invalid_storage","Plugin storage must be a real directory")}async function g(t,e){let r;try{r=await N(t,U.O_RDONLY|U.O_NONBLOCK|(U.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await r.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new s("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(n.size+1,e+1)),o=0;for(;o<i.length;){let a=await r.read(i,o,i.length-o,o);if(!a.bytesRead)break;o+=a.bytesRead}if(o>e||o!==n.size)throw new s("invalid_storage","Storage record changed during read");return i.subarray(0,o)}finally{await r.close()}}async function j(t,e=2*1024*1024){let r=await g(t,e);if(!r)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new s("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(t){let e=await g(t,2097152);if(e===null)return null;let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new s("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!r||typeof r!="object"||Array.isArray(r))throw new s("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return r}async function y(t,e){let r=`${t}.${Ie()}.tmp`,n=await N(r,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await ve(r,t);let i;try{i=await N(be(t),"r"),await i.sync()}catch(o){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(o.code??""))throw o}finally{await i?.close()}}finally{await Q(r).catch(()=>{})}}var Z='{"version":2,"mechanism":"sqlite-exclusive"}',J=t=>t.toString("utf8")===Z,C=new Set;async function Se(t,e,r=0){await R(t);let n=X(t,`${e}.lock`),i=X(t,`${e}.ownership.sqlite`),o=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new s(o,"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 N(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let l=await Y(i);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new s("invalid_storage","Ownership database must be a small, single-link regular file");let d=new me(i,{allowExtension:!1}),p=ke(i),u=Date.now()+r,m=!1;try{for(;;){if(!C.has(p))try{d.exec("BEGIN EXCLUSIVE"),C.add(p),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=u)throw new s(o,"Another host owns this plugin storage; wait for it to stop before retrying");await _e(10)}let h=await g(n,4096);if(h===null){let w;try{w=await N(n,"wx",384),await w.writeFile(Z),await w.sync()}catch(S){if(S.code!=="EEXIST")throw S}finally{await w?.close()}h=await g(n,4096)}if(h===null||!J(h))throw a()}catch(h){throw d.close(),m&&C.delete(p),h}let k=!1;return async()=>{if(k)return;let h=await g(n,4096);if(h===null||!J(h))throw new s("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Q(n),d.close(),C.delete(p),k=!0}}async function _(t,e,r=2e3){let n=await Se(t,"transaction",r);try{return await e()}finally{await n()}}import{readdir as ft,realpath as pt,rename as Pe,stat as xe}from"node:fs/promises";import{join as G}from"node:path";var M=t=>G(t,"host-pair");var wt=10*6e4;async function Oe(t){await Pe(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Ee=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function ee(t){let e=G(M(t),"intent.json"),r,n=!0;try{r=await I(e)}catch{r=null,n=!1}if(!n||r&&!Ee(r))return await Oe(e),null;if(r){let{lifecyclePhase:i,...o}=r,a=typeof o.updatedAt=="string"&&!Number.isNaN(Date.parse(o.updatedAt))?o.updatedAt:await xe(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());r={...o,updatedAt:a,phase:o.phase==="selected"&&i==="restart-requested"?"restart-requested":o.phase==="reconciled"&&i==="cancelled"?"cancelled":o.phase==="reconciled"&&i==="required-action"?"required-action":o.phase}}return r}async function te(t,e){let{lifecyclePhase:r,...n}={...e,selections:[],updatedAt:new Date().toISOString()},i=n.phase==="cancelled"?{...n,phase:"reconciled",lifecyclePhase:"cancelled"}:n.phase==="required-action"?{...n,phase:"reconciled",lifecyclePhase:"required-action"}:n.phase==="restart-requested"?{...n,phase:"selected",lifecyclePhase:"restart-requested"}:n;await y(G(M(t),"intent.json"),i)}import{lstat as F,mkdir as Re,open as re,realpath as ne,readdir as z,link as je,rename as Ae,unlink as P,copyFile as Ne,rm as Te}from"node:fs/promises";import{dirname as He,isAbsolute as ie,join as f,relative as oe,resolve as qe,sep as B,win32 as $e}from"node:path";import{randomUUID as K}from"node:crypto";var T=192*1024*1024,H=512*1024,ae=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function De(t){if(!t||typeof t!="object"||Array.isArray(t))throw new s("invalid_input","Expected object input");return t}function se(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new s("invalid_input","Invalid state key");return t}function q(t){if(t&&(!ae(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new s("invalid_storage","Invalid active plugin record");return t}var $=class{root;pluginId;legacy;checkpoint;constructor(e,r,n,i){this.root=f(e,v(r)),this.pluginId=r,this.legacy=n,this.checkpoint=i}active(){return j(f(this.root,"active.json")).then(q)}async recover(){return _(this.root,async()=>{let e=await this.active(),r=await I(f(this.root,"transition.json"));if(!r)return{active:e,recovered:"none"};if(!r.next||!Object.hasOwn(r,"before")||Object.keys(r).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(r,"version")&&r.version!==1)throw new s("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");q(r.next),q(r.before);let n=e?.operationId===r.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===c[l]))(e,n==="committed"?r.next:r.before))throw new s("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let o=r.before;if(n==="committed"&&o&&o.stateRef!==e.stateRef&&await y(f(this.root,"previous.json"),o),n==="committed"){let a=await I(f(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await P(f(this.root,"fork.json"))}return await P(f(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,r){return _(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new s("stale_generation","Plugin activation changed concurrently");let i=await I(f(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==r.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new s("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let o=q({...r,generation:e+1,operationId:K()});await R(f(this.root,"states")),await R(f(this.root,"states",o.stateRef)),await y(f(this.root,"transition.json"),{version:1,before:n,next:o}),await this.checkpoint?.("prepared");try{await y(f(this.root,"active.json"),o)}catch(a){if((await this.active())?.operationId!==o.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==o.stateRef&&await y(f(this.root,"previous.json"),n),await P(f(this.root,"transition.json")),await P(f(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),o})}async forkState(e){return _(this.root,async()=>{let r=await this.assertGeneration(e,!1),n=K(),i=f(this.root,"states",n);if(await I(f(this.root,"fork.json")))throw new s("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await y(f(this.root,"fork.json"),{version:1,stateRef:n}),await R(i);let o=f(this.root,"states",r.stateRef);for(let a of await z(o)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new s("invalid_storage","Unexpected state file");if(!await g(f(o,a),T))throw new s("invalid_storage","Missing state file");await Ne(f(o,a),f(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return _(this.root,async()=>{for(let d of["transition.json","fork.json"])if(await g(f(this.root,d),2*1024*1024))throw new s("gc_recovery_required",`GC refused: unresolved ${d}; stop all owners and inspect recovery references`);let r=await this.active(),n=q(await I(f(this.root,"previous.json")));if(!r&&await g(f(this.root,"active.json"),2*1024*1024))throw new s("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[r,n].filter(d=>!!d),o=f(this.root,"states");await R(o);let a=await z(o),c=new Set(i.map(d=>d.stateRef));for(let d of a){if(!ae(d))throw new s("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=f(o,d),u=await F(p);if(!u.isDirectory()||u.isSymbolicLink())throw new s("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await z(p)){let k=await F(f(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!k.isFile()||k.isSymbolicLink()||k.nlink!==1)throw new s("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(d)){let h=await j(f(p,m),T);if(!h)throw new s("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(S=>!["requestId","inputHash","nextHash","committed"].includes(S))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new s("gc_recovery_required",`GC refused: unresolved file intent in states/${d}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new s("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let d of c)if(!a.includes(d))throw new s("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(i);for(let d of a)c.has(d)||await Te(f(o,d),{recursive:!0,force:!0});return l})}async assertGeneration(e,r=!0){let n=await this.active();if(!n||n.generation!==e||r&&!n.enabled)throw new s("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 s("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,r,n,i="session"){if(i!=="session"&&i!=="workspace")throw new s("invalid_input","Invalid state scope");let o=i==="workspace"?(this.scopeKey(r),JSON.stringify([r.scope.workspaceId,r.scope.cwd])):this.scopeKey(r);return f(this.root,"states",e.stateRef,`${v(o+":state:"+n)}.json`)}async call(e,r,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new s("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=De(n);return _(this.root,async()=>{let o=await this.assertGeneration(e.generation);switch(r){case"state.read":{let a=await j(this.statePath(o,e,se(i.key),i.scope),T);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(o,e,se(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==o.schema||!Object.hasOwn(i,"value"))throw new s("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new s("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>T)throw new s("state_too_large","Plugin state exceeds limit");let l=await j(a,T);l&&this.validateState(l);let d=v(c);if(l?.requestId===e.requestId&&l.inputHash===d)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==i.expectedRevision)throw new s("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:o.schema,value:i.value,requestId:e.requestId,inputHash:d};return await y(a,p),{revision:p.revision,schema:p.schema,value:p.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 s("invalid_input","Invalid workspace read limit");let l=await g(a,c);return l?{text:new TextDecoder("utf-8",{fatal:!0}).decode(l),hash:v(l)}:null}case"workspace.commit":return this.commitFile(o,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new s("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 s("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,r,n=!1){if(typeof r!="string"||r.length>4096||!r.endsWith(".excalidraw")||r.includes("\\")||r.includes("\0")||ie(r)||$e.isAbsolute(r))throw new s("invalid_path","Use a workspace-relative .excalidraw path");let i=await ne(e),o=qe(i,r),a=oe(i,o);if(!a||a===".."||a.startsWith(`..${B}`)||ie(a))throw new s("invalid_path","Workspace path escapes root");let c=i,l=a.split(B);for(let p=0;p<l.length;p++){c=f(c,l[p]);let u;try{u=await F(c)}catch(m){if(!L(m))throw m;if(p<l.length-1){if(!n||oe(i,c)!=="diagrams")throw new s("invalid_path","Workspace directory does not exist");try{await Re(c,{mode:448})}catch(k){if(k.code!=="EEXIST")throw k}u=await F(c)}}if(u&&(u.isSymbolicLink()||(p<l.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new s("invalid_path","Workspace path contains a link or non-regular file")}let d=await ne(He(o));if(d!==i&&!d.startsWith(i+B))throw new s("invalid_path","Workspace directory changed");return{target:o,parent:d}}async commitFile(e,r,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 s("invalid_input","Invalid file content or expected hash");let{target:i,parent:o}=await this.fileTarget(r.scope.cwd,n.path,!0),a=f(this.root,"states",e.stateRef,`${v(this.scopeKey(r)+":file:"+r.requestId+":"+String(n.path))}.json`),c=v(JSON.stringify(n)),l=v(n.text),d=await j(a);if(d&&(d.requestId!==r.requestId||d.inputHash!==c||d.nextHash!==l))throw new s("duplicate_request","Request ID was reused with different content");let p;try{p=await re(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new s("file_busy","Workspace file is locked; original file preserved"):m}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:r.requestId}));let m=await g(i,H),k=m?v(m):null;if(d&&k===l)return{hash:l};if(d?.committed||k!==n.expectedHash)throw new s("file_conflict","Workspace file already exists or changed externally");await y(a,{requestId:r.requestId,inputHash:c,nextHash:l,committed:!1}),u=f(o,`.plugin-${K()}.tmp`);let h=await re(u,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(r.scope.cwd,n.path)).parent!==o)throw new s("file_conflict","Workspace directory changed during save");let S=await g(i,H);if((S?v(S):null)!==n.expectedHash)throw new s("file_conflict","Workspace file changed during save");if(await this.assertGeneration(r.generation),n.expectedHash===null){try{await je(u,i)}catch(V){throw V.code==="EEXIST"?new s("file_conflict","Workspace file was created concurrently"):V}await P(u),u=void 0}else await Ae(u,i),u=void 0;return await y(a,{requestId:r.requestId,inputHash:c,nextHash:l,committed:!0}),{hash:l}}finally{u&&await P(u).catch(()=>{}),await p.close(),await P(`${i}.lock`)}}};var W="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function A(t){let e=[];async function r(n,i=""){let o=await ce(n);if(!o.isDirectory()||o.isSymbolicLink())throw new s("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Ce(n)).sort()){let c=b(n,a),l=i+a,d=await ce(c);if(d.isSymbolicLink())throw new s("invalid_storage","Recovery refuses links");if(d.isDirectory())await r(c,l+"/");else{if(e.length>=1e4)throw new s("invalid_storage","Recovery inspection budget exceeded");let p=await g(c,192*1024*1024);if(!p)throw new s("invalid_storage","Recovery input disappeared");e.push({path:l,bytes:p.length,sha256:v(p)})}}}return await r(t),{fingerprint:v(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 de(t,e,r,n){let i=new $(t,e),o=await A(i.root);if(n!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(o.fingerprint!==r)throw new s("recovery_changed","Storage changed since inspection");return i.recover()}async function fe(t,e,r,n){let i=new $(t,e),o=i.root;if(n!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await A(o);if(a.fingerprint!==r)throw new s("recovery_changed","Storage changed since inspection");if(await g(b(o,"transition.json"),2*1024*1024))throw new s("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(b(o,"fork.json")),l=await i.active(),d=await I(b(o,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(u=>!["version","stateRef"].includes(u))||!l||d&&typeof d.stateRef!="string"||[l?.stateRef,d?.stateRef].includes(c.stateRef))throw new s("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let p=`recovered-${r}-fork.json`;if(a.files.some(u=>u.path===p))throw new s("recovery_changed","Recovery evidence already exists");return await le(b(o,"fork.json"),b(o,p)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:r}}async function pe(t,e,r){if(r!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await A(t);if(n.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let o of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(b(t,o.path),2097152);a&&!J(a)&&i.push(o)}for(let o of i){let a=`recovered-${e}-${o.path}.json`;if(n.files.some(c=>c.path===a))throw new s("recovery_changed","Recovery evidence already exists")}for(let o of i)await le(b(t,o.path),b(t,`recovered-${e}-${o.path}.json`));return await y(b(t,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:r,recoveredAt:new Date().toISOString()}),{recovered:i.map(o=>o.path),fingerprint:e}}async function ue(t,e,r){if(r!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=M(t),i=await A(n);if(i.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing settled, inspect again");let o=i.files.find(a=>a.path==="intent.json");if(!o)throw new s("invalid_input","No host pair journal to settle");return _(n,async()=>{let a=await g(b(n,"intent.json"),2097152);if(!a||v(a)!==o.sha256)throw new s("recovery_changed","Host pair journal changed since inspection; nothing settled, inspect again");let c=await ee(t);if(c?.phase!=="required-action")throw new s("invalid_input",`Only a required-action journal can be settled offline (found ${c?.phase??"unreadable journal, now quarantined"})`);let l=b(n,"history",`${c.id}-settled-${e}.json`);if(await g(l,2*1024*1024))throw new s("recovery_changed","Recovery evidence already exists");return await Le(b(n,"history"),{recursive:!0,mode:448}),await y(l,c),await te(t,{...c,phase:"reconciled",message:`Settled offline by operator; current host and plugin data retained. Was: ${c.message??"no message"}`}),await y(b(n,`recovery-${e}.json`),{version:1,fingerprint:e,settled:c.id,confirmation:r,recoveredAt:new Date().toISOString()}),{settled:c.id,version:c.version,fingerprint:e}})}var[x,he,O,E,D,...Me]=process.argv.slice(2),Fe=he&&!Me.length&&(x==="inspect"&&!O&&!E&&!D||["recover-locks","settle-pair"].includes(x??"")&&O&&E&&!D||["recover-fork","reconcile-transition"].includes(x??"")&&O&&E&&D);if(!Fe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
1
+ (function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="24cea7a2-7c69-4066-a62d-9bb52dc4ae29",t._sentryDebugIdIdentifier="sentry-dbid-24cea7a2-7c69-4066-a62d-9bb52dc4ae29")}catch{}})();import{resolve as Je}from"node:path";import{lstat as ce,mkdir as Le,readdir as Ce,rename as le}from"node:fs/promises";import{join as b}from"node:path";import{createHash as we}from"node:crypto";var s=class extends Error{code;status;reason;constructor(e,r,n={}){super(r),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=t=>t.code==="ENOENT";var et={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var v=t=>we("sha256").update(t).digest("hex");import{constants as U}from"node:fs";import{DatabaseSync as me}from"node:sqlite";import{lstat as Y,mkdir as ye,open as N,rename as ve,unlink as Q}from"node:fs/promises";import{dirname as be,join as X,resolve as ke}from"node:path";import{randomUUID as Ie}from"node:crypto";import{setTimeout as _e}from"node:timers/promises";async function R(t){await ye(t,{recursive:!0,mode:448});let e=await Y(t);if(!e.isDirectory()||e.isSymbolicLink())throw new s("invalid_storage","Plugin storage must be a real directory")}async function g(t,e){let r;try{r=await N(t,U.O_RDONLY|U.O_NONBLOCK|(U.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await r.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new s("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(n.size+1,e+1)),o=0;for(;o<i.length;){let a=await r.read(i,o,i.length-o,o);if(!a.bytesRead)break;o+=a.bytesRead}if(o>e||o!==n.size)throw new s("invalid_storage","Storage record changed during read");return i.subarray(0,o)}finally{await r.close()}}async function j(t,e=2*1024*1024){let r=await g(t,e);if(!r)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new s("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(t){let e=await g(t,2097152);if(e===null)return null;let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new s("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!r||typeof r!="object"||Array.isArray(r))throw new s("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return r}async function y(t,e){let r=`${t}.${Ie()}.tmp`,n=await N(r,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await ve(r,t);let i;try{i=await N(be(t),"r"),await i.sync()}catch(o){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(o.code??""))throw o}finally{await i?.close()}}finally{await Q(r).catch(()=>{})}}var Z='{"version":2,"mechanism":"sqlite-exclusive"}',J=t=>t.toString("utf8")===Z,C=new Set;async function Se(t,e,r=0){await R(t);let n=X(t,`${e}.lock`),i=X(t,`${e}.ownership.sqlite`),o=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new s(o,"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 N(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let l=await Y(i);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new s("invalid_storage","Ownership database must be a small, single-link regular file");let d=new me(i,{allowExtension:!1}),p=ke(i),u=Date.now()+r,m=!1;try{for(;;){if(!C.has(p))try{d.exec("BEGIN EXCLUSIVE"),C.add(p),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=u)throw new s(o,"Another host owns this plugin storage; wait for it to stop before retrying");await _e(10)}let h=await g(n,4096);if(h===null){let w;try{w=await N(n,"wx",384),await w.writeFile(Z),await w.sync()}catch(S){if(S.code!=="EEXIST")throw S}finally{await w?.close()}h=await g(n,4096)}if(h===null||!J(h))throw a()}catch(h){throw d.close(),m&&C.delete(p),h}let k=!1;return async()=>{if(k)return;let h=await g(n,4096);if(h===null||!J(h))throw new s("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Q(n),d.close(),C.delete(p),k=!0}}async function _(t,e,r=2e3){let n=await Se(t,"transaction",r);try{return await e()}finally{await n()}}import{readdir as ft,realpath as pt,rename as Pe,stat as xe}from"node:fs/promises";import{join as G}from"node:path";var M=t=>G(t,"host-pair");var wt=10*6e4;async function Oe(t){await Pe(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Ee=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function ee(t){let e=G(M(t),"intent.json"),r,n=!0;try{r=await I(e)}catch{r=null,n=!1}if(!n||r&&!Ee(r))return await Oe(e),null;if(r){let{lifecyclePhase:i,...o}=r,a=typeof o.updatedAt=="string"&&!Number.isNaN(Date.parse(o.updatedAt))?o.updatedAt:await xe(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());r={...o,updatedAt:a,phase:o.phase==="selected"&&i==="restart-requested"?"restart-requested":o.phase==="reconciled"&&i==="cancelled"?"cancelled":o.phase==="reconciled"&&i==="required-action"?"required-action":o.phase}}return r}async function te(t,e){let{lifecyclePhase:r,...n}={...e,selections:[],updatedAt:new Date().toISOString()},i=n.phase==="cancelled"?{...n,phase:"reconciled",lifecyclePhase:"cancelled"}:n.phase==="required-action"?{...n,phase:"reconciled",lifecyclePhase:"required-action"}:n.phase==="restart-requested"?{...n,phase:"selected",lifecyclePhase:"restart-requested"}:n;await y(G(M(t),"intent.json"),i)}import{lstat as F,mkdir as Re,open as re,realpath as ne,readdir as z,link as je,rename as Ae,unlink as P,copyFile as Ne,rm as Te}from"node:fs/promises";import{dirname as He,isAbsolute as ie,join as f,relative as oe,resolve as qe,sep as B,win32 as $e}from"node:path";import{randomUUID as K}from"node:crypto";var T=192*1024*1024,H=512*1024,ae=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function De(t){if(!t||typeof t!="object"||Array.isArray(t))throw new s("invalid_input","Expected object input");return t}function se(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new s("invalid_input","Invalid state key");return t}function q(t){if(t&&(!ae(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new s("invalid_storage","Invalid active plugin record");return t}var $=class{root;pluginId;legacy;checkpoint;constructor(e,r,n,i){this.root=f(e,v(r)),this.pluginId=r,this.legacy=n,this.checkpoint=i}active(){return j(f(this.root,"active.json")).then(q)}async recover(){return _(this.root,async()=>{let e=await this.active(),r=await I(f(this.root,"transition.json"));if(!r)return{active:e,recovered:"none"};if(!r.next||!Object.hasOwn(r,"before")||Object.keys(r).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(r,"version")&&r.version!==1)throw new s("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");q(r.next),q(r.before);let n=e?.operationId===r.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===c[l]))(e,n==="committed"?r.next:r.before))throw new s("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let o=r.before;if(n==="committed"&&o&&o.stateRef!==e.stateRef&&await y(f(this.root,"previous.json"),o),n==="committed"){let a=await I(f(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await P(f(this.root,"fork.json"))}return await P(f(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,r){return _(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new s("stale_generation","Plugin activation changed concurrently");let i=await I(f(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==r.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new s("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let o=q({...r,generation:e+1,operationId:K()});await R(f(this.root,"states")),await R(f(this.root,"states",o.stateRef)),await y(f(this.root,"transition.json"),{version:1,before:n,next:o}),await this.checkpoint?.("prepared");try{await y(f(this.root,"active.json"),o)}catch(a){if((await this.active())?.operationId!==o.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==o.stateRef&&await y(f(this.root,"previous.json"),n),await P(f(this.root,"transition.json")),await P(f(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),o})}async forkState(e){return _(this.root,async()=>{let r=await this.assertGeneration(e,!1),n=K(),i=f(this.root,"states",n);if(await I(f(this.root,"fork.json")))throw new s("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await y(f(this.root,"fork.json"),{version:1,stateRef:n}),await R(i);let o=f(this.root,"states",r.stateRef);for(let a of await z(o)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new s("invalid_storage","Unexpected state file");if(!await g(f(o,a),T))throw new s("invalid_storage","Missing state file");await Ne(f(o,a),f(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return _(this.root,async()=>{for(let d of["transition.json","fork.json"])if(await g(f(this.root,d),2*1024*1024))throw new s("gc_recovery_required",`GC refused: unresolved ${d}; stop all owners and inspect recovery references`);let r=await this.active(),n=q(await I(f(this.root,"previous.json")));if(!r&&await g(f(this.root,"active.json"),2*1024*1024))throw new s("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[r,n].filter(d=>!!d),o=f(this.root,"states");await R(o);let a=await z(o),c=new Set(i.map(d=>d.stateRef));for(let d of a){if(!ae(d))throw new s("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=f(o,d),u=await F(p);if(!u.isDirectory()||u.isSymbolicLink())throw new s("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await z(p)){let k=await F(f(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!k.isFile()||k.isSymbolicLink()||k.nlink!==1)throw new s("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(d)){let h=await j(f(p,m),T);if(!h)throw new s("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(S=>!["requestId","inputHash","nextHash","committed"].includes(S))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new s("gc_recovery_required",`GC refused: unresolved file intent in states/${d}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new s("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let d of c)if(!a.includes(d))throw new s("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(i);for(let d of a)c.has(d)||await Te(f(o,d),{recursive:!0,force:!0});return l})}async assertGeneration(e,r=!0){let n=await this.active();if(!n||n.generation!==e||r&&!n.enabled)throw new s("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 s("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,r,n,i="session"){if(i!=="session"&&i!=="workspace")throw new s("invalid_input","Invalid state scope");let o=i==="workspace"?(this.scopeKey(r),JSON.stringify([r.scope.workspaceId,r.scope.cwd])):this.scopeKey(r);return f(this.root,"states",e.stateRef,`${v(o+":state:"+n)}.json`)}async call(e,r,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new s("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=De(n);return _(this.root,async()=>{let o=await this.assertGeneration(e.generation);switch(r){case"state.read":{let a=await j(this.statePath(o,e,se(i.key),i.scope),T);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(o,e,se(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==o.schema||!Object.hasOwn(i,"value"))throw new s("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new s("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>T)throw new s("state_too_large","Plugin state exceeds limit");let l=await j(a,T);l&&this.validateState(l);let d=v(c);if(l?.requestId===e.requestId&&l.inputHash===d)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==i.expectedRevision)throw new s("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:o.schema,value:i.value,requestId:e.requestId,inputHash:d};return await y(a,p),{revision:p.revision,schema:p.schema,value:p.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 s("invalid_input","Invalid workspace read limit");let l=await g(a,c);return l?{text:new TextDecoder("utf-8",{fatal:!0}).decode(l),hash:v(l)}:null}case"workspace.commit":return this.commitFile(o,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new s("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 s("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,r,n=!1){if(typeof r!="string"||r.length>4096||!r.endsWith(".excalidraw")||r.includes("\\")||r.includes("\0")||ie(r)||$e.isAbsolute(r))throw new s("invalid_path","Use a workspace-relative .excalidraw path");let i=await ne(e),o=qe(i,r),a=oe(i,o);if(!a||a===".."||a.startsWith(`..${B}`)||ie(a))throw new s("invalid_path","Workspace path escapes root");let c=i,l=a.split(B);for(let p=0;p<l.length;p++){c=f(c,l[p]);let u;try{u=await F(c)}catch(m){if(!L(m))throw m;if(p<l.length-1){if(!n||oe(i,c)!=="diagrams")throw new s("invalid_path","Workspace directory does not exist");try{await Re(c,{mode:448})}catch(k){if(k.code!=="EEXIST")throw k}u=await F(c)}}if(u&&(u.isSymbolicLink()||(p<l.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new s("invalid_path","Workspace path contains a link or non-regular file")}let d=await ne(He(o));if(d!==i&&!d.startsWith(i+B))throw new s("invalid_path","Workspace directory changed");return{target:o,parent:d}}async commitFile(e,r,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 s("invalid_input","Invalid file content or expected hash");let{target:i,parent:o}=await this.fileTarget(r.scope.cwd,n.path,!0),a=f(this.root,"states",e.stateRef,`${v(this.scopeKey(r)+":file:"+r.requestId+":"+String(n.path))}.json`),c=v(JSON.stringify(n)),l=v(n.text),d=await j(a);if(d&&(d.requestId!==r.requestId||d.inputHash!==c||d.nextHash!==l))throw new s("duplicate_request","Request ID was reused with different content");let p;try{p=await re(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new s("file_busy","Workspace file is locked; original file preserved"):m}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:r.requestId}));let m=await g(i,H),k=m?v(m):null;if(d&&k===l)return{hash:l};if(d?.committed||k!==n.expectedHash)throw new s("file_conflict","Workspace file already exists or changed externally");await y(a,{requestId:r.requestId,inputHash:c,nextHash:l,committed:!1}),u=f(o,`.plugin-${K()}.tmp`);let h=await re(u,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(r.scope.cwd,n.path)).parent!==o)throw new s("file_conflict","Workspace directory changed during save");let S=await g(i,H);if((S?v(S):null)!==n.expectedHash)throw new s("file_conflict","Workspace file changed during save");if(await this.assertGeneration(r.generation),n.expectedHash===null){try{await je(u,i)}catch(V){throw V.code==="EEXIST"?new s("file_conflict","Workspace file was created concurrently"):V}await P(u),u=void 0}else await Ae(u,i),u=void 0;return await y(a,{requestId:r.requestId,inputHash:c,nextHash:l,committed:!0}),{hash:l}}finally{u&&await P(u).catch(()=>{}),await p.close(),await P(`${i}.lock`)}}};var W="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function A(t){let e=[];async function r(n,i=""){let o=await ce(n);if(!o.isDirectory()||o.isSymbolicLink())throw new s("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Ce(n)).sort()){let c=b(n,a),l=i+a,d=await ce(c);if(d.isSymbolicLink())throw new s("invalid_storage","Recovery refuses links");if(d.isDirectory())await r(c,l+"/");else{if(e.length>=1e4)throw new s("invalid_storage","Recovery inspection budget exceeded");let p=await g(c,192*1024*1024);if(!p)throw new s("invalid_storage","Recovery input disappeared");e.push({path:l,bytes:p.length,sha256:v(p)})}}}return await r(t),{fingerprint:v(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 de(t,e,r,n){let i=new $(t,e),o=await A(i.root);if(n!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(o.fingerprint!==r)throw new s("recovery_changed","Storage changed since inspection");return i.recover()}async function fe(t,e,r,n){let i=new $(t,e),o=i.root;if(n!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await A(o);if(a.fingerprint!==r)throw new s("recovery_changed","Storage changed since inspection");if(await g(b(o,"transition.json"),2*1024*1024))throw new s("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(b(o,"fork.json")),l=await i.active(),d=await I(b(o,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(u=>!["version","stateRef"].includes(u))||!l||d&&typeof d.stateRef!="string"||[l?.stateRef,d?.stateRef].includes(c.stateRef))throw new s("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let p=`recovered-${r}-fork.json`;if(a.files.some(u=>u.path===p))throw new s("recovery_changed","Recovery evidence already exists");return await le(b(o,"fork.json"),b(o,p)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:r}}async function pe(t,e,r){if(r!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await A(t);if(n.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let o of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(b(t,o.path),2097152);a&&!J(a)&&i.push(o)}for(let o of i){let a=`recovered-${e}-${o.path}.json`;if(n.files.some(c=>c.path===a))throw new s("recovery_changed","Recovery evidence already exists")}for(let o of i)await le(b(t,o.path),b(t,`recovered-${e}-${o.path}.json`));return await y(b(t,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:r,recoveredAt:new Date().toISOString()}),{recovered:i.map(o=>o.path),fingerprint:e}}async function ue(t,e,r){if(r!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=M(t),i=await A(n);if(i.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing settled, inspect again");let o=i.files.find(a=>a.path==="intent.json");if(!o)throw new s("invalid_input","No host pair journal to settle");return _(n,async()=>{let a=await g(b(n,"intent.json"),2097152);if(!a||v(a)!==o.sha256)throw new s("recovery_changed","Host pair journal changed since inspection; nothing settled, inspect again");let c=await ee(t);if(c?.phase!=="required-action")throw new s("invalid_input",`Only a required-action journal can be settled offline (found ${c?.phase??"unreadable journal, now quarantined"})`);let l=b(n,"history",`${c.id}-settled-${e}.json`);if(await g(l,2*1024*1024))throw new s("recovery_changed","Recovery evidence already exists");return await Le(b(n,"history"),{recursive:!0,mode:448}),await y(l,c),await te(t,{...c,phase:"reconciled",message:`Settled offline by operator; current host and plugin data retained. Was: ${c.message??"no message"}`}),await y(b(n,`recovery-${e}.json`),{version:1,fingerprint:e,settled:c.id,confirmation:r,recoveredAt:new Date().toISOString()}),{settled:c.id,version:c.version,fingerprint:e}})}var[x,he,O,E,D,...Me]=process.argv.slice(2),Fe=he&&!Me.length&&(x==="inspect"&&!O&&!E&&!D||["recover-locks","settle-pair"].includes(x??"")&&O&&E&&!D||["recover-fork","reconcile-transition"].includes(x??"")&&O&&E&&D);if(!Fe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
2
2
  inspect BROKER_ROOT | HOSTED_ROOT/host-pair
3
3
  recover-locks BROKER_ROOT FINGERPRINT CONFIRMATION
4
4
  reconcile-transition DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
@@ -6,4 +6,4 @@
6
6
  settle-pair HOSTED_ROOT FINGERPRINT CONFIRMATION
7
7
  CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let t=Je(he),e=x==="inspect"?await A(t):x==="recover-locks"?await pe(t,O,E):x==="settle-pair"?await ue(t,O,E):x==="recover-fork"?await fe(t,O,E,D):await de(t,O,E,D);console.log(JSON.stringify(e,null,2))}catch(t){console.error(t instanceof Error?t.message:"Recovery failed"),process.exitCode=1}var $t=void 0;export{$t as default};
8
8
 
9
- //# debugId=e325e116-1dbd-4c8a-a503-c738d4f775e9
9
+ //# debugId=24cea7a2-7c69-4066-a62d-9bb52dc4ae29
@@ -1,3 +1,3 @@
1
- (function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="ef0f23da-1510-4c5c-b2f9-fa4ab57422be",t._sentryDebugIdIdentifier="sentry-dbid-ef0f23da-1510-4c5c-b2f9-fa4ab57422be")}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 f=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(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 globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="b4b95148-5b55-4a6c-a891-30eacc8d5ffe",t._sentryDebugIdIdentifier="sentry-dbid-b4b95148-5b55-4a6c-a891-30eacc8d5ffe")}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=ef0f23da-1510-4c5c-b2f9-fa4ab57422be
3
+ //# debugId=b4b95148-5b55-4a6c-a891-30eacc8d5ffe
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.52-alpha.7",
3
+ "version": "0.1.52-alpha.8",
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.52-alpha.7/assets/cover-webapp.png",
33
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.52-alpha.8/assets/cover-webapp.png",
34
34
  "extensions": [
35
35
  "./dist/extension.js"
36
36
  ]
@@ -126,14 +126,14 @@
126
126
  "isDynamicEntry": true
127
127
  },
128
128
  "../../node_modules/@shikijs/langs/dist/http.mjs": {
129
- "file": "assets/http-DCjgep7B.js",
129
+ "file": "assets/http-Be4OwNYs.js",
130
130
  "name": "http",
131
131
  "src": "../../node_modules/@shikijs/langs/dist/http.mjs",
132
132
  "isDynamicEntry": true,
133
133
  "imports": [
134
- "_CodeBlock-Big96vAT.js",
134
+ "_CodeBlock-CXsuy2XV.js",
135
135
  "_xml-2mvSwqHa.js",
136
- "_graphql-BRCT2swE.js"
136
+ "_graphql-tDnlMSR1.js"
137
137
  ]
138
138
  },
139
139
  "../../node_modules/@shikijs/langs/dist/ini.mjs": {
@@ -220,7 +220,7 @@
220
220
  ]
221
221
  },
222
222
  "../../node_modules/@shikijs/langs/dist/php.mjs": {
223
- "file": "assets/php-C3SzQpXm.js",
223
+ "file": "assets/php-CA2iikjU.js",
224
224
  "name": "php",
225
225
  "src": "../../node_modules/@shikijs/langs/dist/php.mjs",
226
226
  "isDynamicEntry": true,
@@ -229,7 +229,7 @@
229
229
  "_xml-2mvSwqHa.js",
230
230
  "_sql-C8MpZCQu.js",
231
231
  "_javascript-qRALF4mN.js",
232
- "_CodeBlock-Big96vAT.js",
232
+ "_CodeBlock-CXsuy2XV.js",
233
233
  "_css-DE55rRSl.js"
234
234
  ]
235
235
  },
@@ -252,7 +252,7 @@
252
252
  "isDynamicEntry": true
253
253
  },
254
254
  "../../node_modules/@shikijs/langs/dist/rst.mjs": {
255
- "file": "assets/rst-BbwpYVH_.js",
255
+ "file": "assets/rst-B20YvTve.js",
256
256
  "name": "rst",
257
257
  "src": "../../node_modules/@shikijs/langs/dist/rst.mjs",
258
258
  "isDynamicEntry": true,
@@ -261,14 +261,14 @@
261
261
  "../../node_modules/@shikijs/langs/dist/cpp.mjs",
262
262
  "../../node_modules/@shikijs/langs/dist/python.mjs",
263
263
  "_javascript-qRALF4mN.js",
264
- "_CodeBlock-Big96vAT.js",
264
+ "_CodeBlock-CXsuy2XV.js",
265
265
  "../../node_modules/@shikijs/langs/dist/yaml.mjs",
266
266
  "../../node_modules/@shikijs/langs/dist/cmake.mjs",
267
267
  "../../node_modules/@shikijs/langs/dist/ruby.mjs"
268
268
  ]
269
269
  },
270
270
  "../../node_modules/@shikijs/langs/dist/ruby.mjs": {
271
- "file": "assets/ruby-BZIYqgYr.js",
271
+ "file": "assets/ruby-DbEq7LIO.js",
272
272
  "name": "ruby",
273
273
  "src": "../../node_modules/@shikijs/langs/dist/ruby.mjs",
274
274
  "isDynamicEntry": true,
@@ -278,10 +278,10 @@
278
278
  "_css-DE55rRSl.js",
279
279
  "_xml-2mvSwqHa.js",
280
280
  "_sql-C8MpZCQu.js",
281
- "_graphql-BRCT2swE.js",
281
+ "_graphql-tDnlMSR1.js",
282
282
  "../../node_modules/@shikijs/langs/dist/cpp.mjs",
283
283
  "_c-pX-F3haE.js",
284
- "_CodeBlock-Big96vAT.js",
284
+ "_CodeBlock-CXsuy2XV.js",
285
285
  "_lua-N7XV0gng.js",
286
286
  "../../node_modules/@shikijs/langs/dist/yaml.mjs"
287
287
  ]
@@ -308,13 +308,13 @@
308
308
  ]
309
309
  },
310
310
  "../../node_modules/@shikijs/langs/dist/svelte.mjs": {
311
- "file": "assets/svelte-D1CPZuRP.js",
311
+ "file": "assets/svelte-x85eNM8m.js",
312
312
  "name": "svelte",
313
313
  "src": "../../node_modules/@shikijs/langs/dist/svelte.mjs",
314
314
  "isDynamicEntry": true,
315
315
  "imports": [
316
316
  "_javascript-qRALF4mN.js",
317
- "_CodeBlock-Big96vAT.js",
317
+ "_CodeBlock-CXsuy2XV.js",
318
318
  "_css-DE55rRSl.js"
319
319
  ]
320
320
  },
@@ -349,14 +349,14 @@
349
349
  "isDynamicEntry": true
350
350
  },
351
351
  "../../node_modules/@shikijs/langs/dist/vue.mjs": {
352
- "file": "assets/vue-CuxBCPT8.js",
352
+ "file": "assets/vue-Dc671ndk.js",
353
353
  "name": "vue",
354
354
  "src": "../../node_modules/@shikijs/langs/dist/vue.mjs",
355
355
  "isDynamicEntry": true,
356
356
  "imports": [
357
357
  "_css-DE55rRSl.js",
358
358
  "_javascript-qRALF4mN.js",
359
- "_CodeBlock-Big96vAT.js",
359
+ "_CodeBlock-CXsuy2XV.js",
360
360
  "_html-m0MkqRef.js",
361
361
  "_html-derivative-CoNVXKEU.js"
362
362
  ]
@@ -604,13 +604,13 @@
604
604
  "src": "../../node_modules/katex/dist/fonts/KaTeX_Typewriter-Regular.woff2"
605
605
  },
606
606
  "../../src/host/client/app.tsx": {
607
- "file": "assets/app-CTqNMp4O.js",
607
+ "file": "assets/app-C4pNkIrP.js",
608
608
  "name": "app",
609
609
  "src": "../../src/host/client/app.tsx",
610
610
  "isDynamicEntry": true,
611
611
  "imports": [
612
612
  "_clsx-BPDVUjuT.js",
613
- "_icons-B0J_G2pG.js",
613
+ "_icons-DHz2LrCt.js",
614
614
  "index.html"
615
615
  ],
616
616
  "dynamicImports": [
@@ -633,26 +633,26 @@
633
633
  ]
634
634
  },
635
635
  "../../src/plugins/builtin/files/client/plugin.tsx": {
636
- "file": "assets/plugin-DmbOPkvA.js",
636
+ "file": "assets/plugin-lYuuIZFY.js",
637
637
  "name": "plugin",
638
638
  "src": "../../src/plugins/builtin/files/client/plugin.tsx",
639
639
  "isDynamicEntry": true,
640
640
  "imports": [
641
641
  "../../src/host/client/app.tsx",
642
642
  "_clsx-BPDVUjuT.js",
643
- "_icons-B0J_G2pG.js",
643
+ "_icons-DHz2LrCt.js",
644
644
  "index.html",
645
- "_CodeBlock-Big96vAT.js"
645
+ "_CodeBlock-CXsuy2XV.js"
646
646
  ]
647
647
  },
648
648
  "../../src/plugins/builtin/git/client/plugin.tsx": {
649
- "file": "assets/plugin-CiDdlDH_.js",
649
+ "file": "assets/plugin-CkkMaDQr.js",
650
650
  "name": "plugin",
651
651
  "src": "../../src/plugins/builtin/git/client/plugin.tsx",
652
652
  "isDynamicEntry": true,
653
653
  "imports": [
654
654
  "../../src/host/client/app.tsx",
655
- "_icons-B0J_G2pG.js",
655
+ "_icons-DHz2LrCt.js",
656
656
  "_clsx-BPDVUjuT.js",
657
657
  "index.html"
658
658
  ],
@@ -661,7 +661,7 @@
661
661
  ]
662
662
  },
663
663
  "../../src/plugins/builtin/terminal/client/plugin.tsx": {
664
- "file": "assets/plugin-CromzBW2.js",
664
+ "file": "assets/plugin-myms8XIq.js",
665
665
  "name": "plugin",
666
666
  "src": "../../src/plugins/builtin/terminal/client/plugin.tsx",
667
667
  "isDynamicEntry": true,
@@ -674,13 +674,13 @@
674
674
  "assets/plugin2.css"
675
675
  ]
676
676
  },
677
- "_CodeBlock-Big96vAT.js": {
678
- "file": "assets/CodeBlock-Big96vAT.js",
677
+ "_CodeBlock-CXsuy2XV.js": {
678
+ "file": "assets/CodeBlock-CXsuy2XV.js",
679
679
  "name": "CodeBlock",
680
680
  "imports": [
681
681
  "_clsx-BPDVUjuT.js",
682
682
  "../../src/host/client/app.tsx",
683
- "_icons-B0J_G2pG.js",
683
+ "_icons-DHz2LrCt.js",
684
684
  "index.html"
685
685
  ],
686
686
  "dynamicImports": [
@@ -732,7 +732,7 @@
732
732
  "../../node_modules/@shikijs/langs/dist/perl.mjs",
733
733
  "../../node_modules/@shikijs/langs/dist/verilog.mjs",
734
734
  "../../node_modules/@shikijs/langs/dist/system-verilog.mjs",
735
- "_graphql-BRCT2swE.js",
735
+ "_graphql-tDnlMSR1.js",
736
736
  "../../node_modules/@shikijs/langs/dist/proto.mjs",
737
737
  "../../node_modules/@shikijs/langs/dist/hcl.mjs",
738
738
  "../../node_modules/@shikijs/langs/dist/nix.mjs",
@@ -768,13 +768,13 @@
768
768
  "_clsx-BPDVUjuT.js"
769
769
  ]
770
770
  },
771
- "_graphql-BRCT2swE.js": {
772
- "file": "assets/graphql-BRCT2swE.js",
771
+ "_graphql-tDnlMSR1.js": {
772
+ "file": "assets/graphql-tDnlMSR1.js",
773
773
  "name": "graphql",
774
774
  "imports": [
775
775
  "_clsx-BPDVUjuT.js",
776
776
  "_javascript-qRALF4mN.js",
777
- "_CodeBlock-Big96vAT.js"
777
+ "_CodeBlock-CXsuy2XV.js"
778
778
  ]
779
779
  },
780
780
  "_html-derivative-CoNVXKEU.js": {
@@ -793,8 +793,8 @@
793
793
  "_css-DE55rRSl.js"
794
794
  ]
795
795
  },
796
- "_icons-B0J_G2pG.js": {
797
- "file": "assets/icons-B0J_G2pG.js",
796
+ "_icons-DHz2LrCt.js": {
797
+ "file": "assets/icons-DHz2LrCt.js",
798
798
  "name": "icons",
799
799
  "imports": [
800
800
  "_clsx-BPDVUjuT.js"
@@ -852,15 +852,15 @@
852
852
  ]
853
853
  },
854
854
  "ui/shared/primitives/markdown/MarkdownText.tsx": {
855
- "file": "assets/MarkdownText-CfChLqEY.js",
855
+ "file": "assets/MarkdownText-CZK1S3d4.js",
856
856
  "name": "MarkdownText",
857
857
  "src": "ui/shared/primitives/markdown/MarkdownText.tsx",
858
858
  "isDynamicEntry": true,
859
859
  "imports": [
860
860
  "_clsx-BPDVUjuT.js",
861
+ "_icons-DHz2LrCt.js",
861
862
  "../../src/host/client/app.tsx",
862
- "_CodeBlock-Big96vAT.js",
863
- "_icons-B0J_G2pG.js"
863
+ "_CodeBlock-CXsuy2XV.js"
864
864
  ],
865
865
  "css": [
866
866
  "assets/MarkdownText.css"