pi-webapp 0.1.52-alpha.4 → 0.1.52-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/extension.js +3 -3
- package/dist/hosted-recovery.js +2 -2
- package/dist/hosted-worker.js +2 -2
- package/package.json +2 -2
- package/web/dist/.vite/manifest.json +250 -241
- package/web/dist/assets/CodeBlock-Big96vAT.js +159 -0
- package/web/dist/assets/CodeBlock.css +1 -0
- package/web/dist/assets/MarkdownText-CfChLqEY.js +283 -0
- package/web/dist/assets/MarkdownText.css +1 -0
- package/web/dist/assets/app-CTqNMp4O.js +71 -0
- package/web/dist/assets/app.css +1 -1
- package/web/dist/assets/app.js +4 -4
- package/web/dist/assets/{c-D2xwndn2.js → c-pX-F3haE.js} +2 -2
- package/web/dist/assets/clsx-BPDVUjuT.js +2 -0
- package/web/dist/assets/{cpp-M92QQ27h.js → cpp-BDBvFPIA.js} +2 -2
- package/web/dist/assets/{css-COynAVCS.js → css-DE55rRSl.js} +2 -2
- package/web/dist/assets/{elixir-DIe8-kxb.js → elixir-DY7ZvJxK.js} +2 -2
- package/web/dist/assets/graphql-BRCT2swE.js +2 -0
- package/web/dist/assets/{html-derivative-B-zMOKjI.js → html-derivative-CoNVXKEU.js} +2 -2
- package/web/dist/assets/{html-Dkdzkf5m.js → html-m0MkqRef.js} +2 -2
- package/web/dist/assets/http-DCjgep7B.js +2 -0
- package/web/dist/assets/icons-B0J_G2pG.js +2 -0
- package/web/dist/assets/{java-C0tX6Zjj.js → java-CjwcakDc.js} +2 -2
- package/web/dist/assets/{julia-CTkez5_b.js → julia-CqJ_c0Kg.js} +2 -2
- package/web/dist/assets/{latex--YAwAQ5f.js → latex-tn5aU7p-.js} +2 -2
- package/web/dist/assets/{lua-2gStHmQ-.js → lua-N7XV0gng.js} +2 -2
- package/web/dist/assets/{perl-C6cfY4X6.js → perl-BwP6Tii3.js} +2 -2
- package/web/dist/assets/php-C3SzQpXm.js +2 -0
- package/web/dist/assets/plugin-CiDdlDH_.js +4 -0
- package/web/dist/assets/{plugin-Ck_3M7GH.js → plugin-CromzBW2.js} +4 -4
- package/web/dist/assets/plugin-DmbOPkvA.js +2 -0
- package/web/dist/assets/{r-vFiqf_wZ.js → r-DbfM3jHq.js} +2 -2
- package/web/dist/assets/rst-BbwpYVH_.js +2 -0
- package/web/dist/assets/ruby-BZIYqgYr.js +2 -0
- package/web/dist/assets/{scss-DOxJ7xu_.js → scss-eG7pX568.js} +2 -2
- package/web/dist/assets/{sql-BJwLzEN3.js → sql-C8MpZCQu.js} +2 -2
- package/web/dist/assets/svelte-D1CPZuRP.js +2 -0
- package/web/dist/assets/vue-CuxBCPT8.js +2 -0
- package/web/dist/assets/{xml-Dg-qt816.js → xml-2mvSwqHa.js} +2 -2
- package/web/dist/assets/WorkspacePanel.css +0 -1
- package/web/dist/assets/WorkspacePanel.module-7fbly3iv.js +0 -7
- package/web/dist/assets/app-BRLRVji5.js +0 -503
- package/web/dist/assets/dist-DvRDAAjZ.js +0 -2
- package/web/dist/assets/graphql-BUOosdAq.js +0 -2
- package/web/dist/assets/http-iVoGgZyc.js +0 -2
- package/web/dist/assets/json-Hfsf52vC.js +0 -2
- package/web/dist/assets/php-B4BGKN5F.js +0 -2
- package/web/dist/assets/plugin-CiZqbXIv.js +0 -2
- package/web/dist/assets/plugin-CpMftYuc.js +0 -4
- package/web/dist/assets/rst-DEFIrwXa.js +0 -2
- package/web/dist/assets/ruby-CGfRnGY4.js +0 -2
- package/web/dist/assets/shellscript-DugvE863.js +0 -2
- package/web/dist/assets/svelte-Cnhqc3fy.js +0 -2
- package/web/dist/assets/typescript-dAcDzF3q.js +0 -2
- package/web/dist/assets/vue-b-L2NQfY.js +0 -2
package/dist/hosted-recovery.js
CHANGED
|
@@ -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]="277a4793-bddf-4229-8380-6a58d5899cc3",t._sentryDebugIdIdentifier="sentry-dbid-277a4793-bddf-4229-8380-6a58d5899cc3")}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]="031301fc-e8ce-48dd-acb8-3d8d42a27bb8",t._sentryDebugIdIdentifier="sentry-dbid-031301fc-e8ce-48dd-acb8-3d8d42a27bb8")}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=
|
|
9
|
+
//# debugId=031301fc-e8ce-48dd-acb8-3d8d42a27bb8
|
package/dist/hosted-worker.js
CHANGED
|
@@ -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]="
|
|
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]="05fb7aa0-87b1-42ad-bedb-68f632448837",t._sentryDebugIdIdentifier="sentry-dbid-05fb7aa0-87b1-42ad-bedb-68f632448837")}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=
|
|
3
|
+
//# debugId=05fb7aa0-87b1-42ad-bedb-68f632448837
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-webapp",
|
|
3
|
-
"version": "0.1.52-alpha.
|
|
3
|
+
"version": "0.1.52-alpha.6",
|
|
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.
|
|
33
|
+
"image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.52-alpha.6/assets/cover-webapp.png",
|
|
34
34
|
"extensions": [
|
|
35
35
|
"./dist/extension.js"
|
|
36
36
|
]
|