pi-webapp 0.1.51 → 0.1.52-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +12 -8
  2. package/README.zh-CN.md +12 -8
  3. package/bin/pi-webapp.mjs +47 -2
  4. package/bin/upgrade-transaction.d.mts +17 -0
  5. package/bin/upgrade-transaction.mjs +122 -0
  6. package/dist/extension.js +31 -31
  7. package/dist/hosted-recovery.js +5 -4
  8. package/dist/hosted-worker.js +2 -2
  9. package/docs/desktop-testing.md +1 -1
  10. package/docs/desktop.md +8 -3
  11. package/docs/hosted-paired-updater.md +7 -0
  12. package/docs/hosted-update-recovery.md +42 -12
  13. package/package.json +4 -4
  14. package/web/dist/.vite/manifest.json +264 -241
  15. package/web/dist/assets/CodeBlock-BdAsIj3e.js +159 -0
  16. package/web/dist/assets/CodeBlock.css +1 -0
  17. package/web/dist/assets/MarkdownText-NoTY0xls.js +280 -0
  18. package/web/dist/assets/MarkdownText.css +1 -0
  19. package/web/dist/assets/app-DDY_2HbQ.js +38 -0
  20. package/web/dist/assets/app.css +1 -1
  21. package/web/dist/assets/app.js +4 -4
  22. package/web/dist/assets/c-vzw8O3dF.js +2 -0
  23. package/web/dist/assets/clsx-h-WltqkG.js +2 -0
  24. package/web/dist/assets/{cpp-M92QQ27h.js → cpp-DKT7ktbv.js} +2 -2
  25. package/web/dist/assets/css-TMM_5IvK.js +2 -0
  26. package/web/dist/assets/{elixir-DIe8-kxb.js → elixir-BUI7oAoL.js} +2 -2
  27. package/web/dist/assets/graphql-DIl_ZhLK.js +2 -0
  28. package/web/dist/assets/html-CFUZAbjn.js +2 -0
  29. package/web/dist/assets/{html-derivative-B-zMOKjI.js → html-derivative-Di3X0LuZ.js} +2 -2
  30. package/web/dist/assets/http-BwEAzFe-.js +2 -0
  31. package/web/dist/assets/icons-C-HoxwKl.js +7 -0
  32. package/web/dist/assets/java-BLj8-EuU.js +2 -0
  33. package/web/dist/assets/{julia-CTkez5_b.js → julia-DR93JiX6.js} +2 -2
  34. package/web/dist/assets/{latex--YAwAQ5f.js → latex-D2AiaQEH.js} +2 -2
  35. package/web/dist/assets/lua-DVAEEjUj.js +2 -0
  36. package/web/dist/assets/{perl-C6cfY4X6.js → perl-B8jsoAXk.js} +2 -2
  37. package/web/dist/assets/php-BGmvzxwe.js +2 -0
  38. package/web/dist/assets/plugin-B2Gl-6V6.js +2 -0
  39. package/web/dist/assets/{plugin-Cw0h9Dlw.js → plugin-C9-V_VLi.js} +4 -4
  40. package/web/dist/assets/plugin-e6UWq_j6.js +4 -0
  41. package/web/dist/assets/r-BpV6ph8o.js +2 -0
  42. package/web/dist/assets/rolldown-runtime-CgmABjMJ.js +1 -0
  43. package/web/dist/assets/rst-C4gxDDt3.js +2 -0
  44. package/web/dist/assets/ruby-BzF-keyw.js +2 -0
  45. package/web/dist/assets/{scss-DOxJ7xu_.js → scss-D6FyrCGQ.js} +2 -2
  46. package/web/dist/assets/sql-r_e_QA5-.js +2 -0
  47. package/web/dist/assets/svelte-CBtRvh2E.js +2 -0
  48. package/web/dist/assets/vue-CJULmGDv.js +2 -0
  49. package/web/dist/assets/xml-BOIvddFt.js +2 -0
  50. package/web/src/ui/shared/LICENSE.txt +21 -0
  51. package/web/dist/assets/WorkspacePanel.css +0 -1
  52. package/web/dist/assets/WorkspacePanel.module-7fbly3iv.js +0 -7
  53. package/web/dist/assets/app-rE2dO2Sf.js +0 -503
  54. package/web/dist/assets/c-D2xwndn2.js +0 -2
  55. package/web/dist/assets/css-COynAVCS.js +0 -2
  56. package/web/dist/assets/dist-DvRDAAjZ.js +0 -2
  57. package/web/dist/assets/graphql-BUOosdAq.js +0 -2
  58. package/web/dist/assets/html-Dkdzkf5m.js +0 -2
  59. package/web/dist/assets/http-iVoGgZyc.js +0 -2
  60. package/web/dist/assets/java-C0tX6Zjj.js +0 -2
  61. package/web/dist/assets/json-Hfsf52vC.js +0 -2
  62. package/web/dist/assets/lua-2gStHmQ-.js +0 -2
  63. package/web/dist/assets/php-B4BGKN5F.js +0 -2
  64. package/web/dist/assets/plugin-D3ueGV13.js +0 -2
  65. package/web/dist/assets/plugin-Daa3_Q-m.js +0 -4
  66. package/web/dist/assets/r-vFiqf_wZ.js +0 -2
  67. package/web/dist/assets/rst-DEFIrwXa.js +0 -2
  68. package/web/dist/assets/ruby-CGfRnGY4.js +0 -2
  69. package/web/dist/assets/shellscript-DugvE863.js +0 -2
  70. package/web/dist/assets/sql-BJwLzEN3.js +0 -2
  71. package/web/dist/assets/svelte-Cnhqc3fy.js +0 -2
  72. package/web/dist/assets/typescript-dAcDzF3q.js +0 -2
  73. package/web/dist/assets/vue-b-L2NQfY.js +0 -2
  74. package/web/dist/assets/xml-Dg-qt816.js +0 -2
@@ -1,8 +1,9 @@
1
- (function(){try{var r=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="dc077186-12e5-40ab-a64a-bbcbb6011afc",r._sentryDebugIdIdentifier="sentry-dbid-dc077186-12e5-40ab-a64a-bbcbb6011afc")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Pe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var q=r=>r.code==="ENOENT";var Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as N,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function x(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await N(r,J.O_RDONLY|J.O_NONBLOCK|(J.O_NOFOLLOW??0))}catch(n){if(q(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(r){let e=await g(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function b(r,e){let t=`${r}.${me()}.tmp`,n=await N(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await N(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await x(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await N(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await N(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as S,copyFile as _e,rm as Se}from"node:fs/promises";import{dirname as xe,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var A=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Oe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(t.next),T(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await S(d(this.root,"fork.json"))}return await S(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=T({...t,generation:e+1,operationId:G()});await x(d(this.root,"states")),await x(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await S(d(this.root,"transition.json")),await S(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await b(d(this.root,"fork.json"),{version:1,stateRef:n}),await x(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),A))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=T(await I(d(this.root,"previous.json")));if(!t&&await g(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,n].filter(l=>!!l),s=d(this.root,"states");await x(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),A);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(i);for(let l of a)c.has(l)||await Se(d(s,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n,i="session"){if(i!=="session"&&i!=="workspace")throw new o("invalid_input","Invalid state scope");let s=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return d(this.root,"states",e.stateRef,`${y(s+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Oe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key),i.scope),A);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>A)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,A);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!q(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await Z(xe(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await S(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await S(p).catch(()=>{}),await u.close(),await S(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Pe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[O,le,P,j,L,...Ne]=process.argv.slice(2),Ae=le&&!Ne.length&&(O==="inspect"&&!P&&!j&&!L||O==="recover-locks"&&P&&j&&!L||["recover-fork","reconcile-transition"].includes(O??"")&&P&&j&&L);if(!Ae)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
2
- inspect BROKER_ROOT
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]="a1fc7407-9c41-4fbb-b884-17275dea4d46",t._sentryDebugIdIdentifier="sentry-dbid-a1fc7407-9c41-4fbb-b884-17275dea4d46")}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
+ 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
5
5
  recover-fork DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
6
- CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=je(le),e=O==="inspect"?await $(r):O==="recover-locks"?await ce(r,P,j):O==="recover-fork"?await ae(r,P,j,L):await se(r,P,j,L);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var mt=void 0;export{mt as default};
6
+ settle-pair HOSTED_ROOT FINGERPRINT CONFIRMATION
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};
7
8
 
8
- //# debugId=dc077186-12e5-40ab-a64a-bbcbb6011afc
9
+ //# debugId=a1fc7407-9c41-4fbb-b884-17275dea4d46
@@ -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]="b5ff461a-cd8b-497c-b07c-c717e77196af",t._sentryDebugIdIdentifier="sentry-dbid-b5ff461a-cd8b-497c-b07c-c717e77196af")}catch{}})();import{AsyncLocalStorage as b}from"node:async_hooks";import{pathToFileURL as y}from"node:url";function d(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 c=`b${++v}`;return new Promise((m,w)=>{s.set(c,{resolve:m,reject:w}),a({type:"broker-request",id:c,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:d(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]="daeb4e47-323e-4bf7-a735-3c6471935fc6",t._sentryDebugIdIdentifier="sentry-dbid-daeb4e47-323e-4bf7-a735-3c6471935fc6")}catch{}})();import{AsyncLocalStorage as y}from"node:async_hooks";import{pathToFileURL as b}from"node:url";function c(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var l=new y,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(b(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(f,g){let u=l.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,w)=>{s.set(d,{resolve:m,reject:w}),a({type:"broker-request",id:d,invocationId:u.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
2
2
 
3
- //# debugId=b5ff461a-cd8b-497c-b07c-c717e77196af
3
+ //# debugId=daeb4e47-323e-4bf7-a735-3c6471935fc6
@@ -67,7 +67,7 @@ Web 版,或从可信源码构建运行,不必购买开发者会员。
67
67
  四平台发布清单可包含 macOS arm64 的可选更新 ZIP;没有发布者身份时仍只走 DMG 手动安装。
68
68
  执行 packaged smoke(含 PTY/浏览器共享后台)。
69
69
  这些检查不能替代“浏览器下载 → Finder 安装 → 用户明确同意”的隔离场景人工验收。
70
- - 每次交付递增 `desktop/release.json` 的构建号、重新生成校验和。
70
+ - 每次交付先运行 `npm run desktop:prepare-build`:递增 `desktop/release.json` 的构建号,并把 `package.json` 版本设为 npm 下一个未发布版本;再重新生成校验和。
71
71
  不覆盖已有公开 Release,不以移除隔离或本机可启动宣称通过 Gatekeeper。
72
72
 
73
73
  English summary: These are complete **ad-hoc signed**, **unnotarized** opt-in test builds,
package/docs/desktop.md CHANGED
@@ -215,7 +215,7 @@ keeps its existing name; this rename is for the native desktop application.
215
215
 
216
216
  Download builds from **[GitHub Releases](https://github.com/chengzhiyi/pi-webapp/releases)**,
217
217
  not the npm package, source ZIP or an expired Actions artifact. The current
218
- [build 14 release](https://github.com/chengzhiyi/pi-webapp/releases/tag/desktop-v0.1.39-b14) offers macOS arm64/Intel, Windows x64, and Linux x64 test installers. Build 12 fixes quit responsiveness, loading-window shutdown alerts and backend-stop recovery. It also supports persistent stable/preview business-package updates from Settings; older build 10 shells need this one-time installer upgrade.
218
+ [build 17 release](https://github.com/chengzhiyi/pi-webapp/releases/tag/desktop-v0.1.52-b17) offers macOS arm64/Intel, Windows x64, and Linux x64 test installers. Build 12 fixes quit responsiveness, loading-window shutdown alerts and backend-stop recovery. It also supports persistent stable/preview business-package updates from Settings; older build 10 shells need this one-time installer upgrade.
219
219
  Use each release's actual asset list and acceptance notes, not matrix configuration
220
220
  alone, to determine support.
221
221
 
@@ -232,8 +232,13 @@ alone, to determine support.
232
232
 
233
233
  For repeatable publication, commit the intended version/build and push a tag
234
234
  pointing to that verified source SHA; do not silently follow a moving main while
235
- its independent npm pipeline may write another version. Increment the desktop
236
- build number for each delivered rebuild. Tag creation/release is an intentional
235
+ its independent npm pipeline may write another version. Prepare each delivered
236
+ rebuild with `npm run desktop:prepare-build`: it increments the desktop build
237
+ number and sets package.json to the next unreleased npm base (for example
238
+ 0.1.52 while npm latest is 0.1.51). npm publishes never write their version
239
+ back, and the shell treats package.json as its bundled backend version. A stale
240
+ value lets an older npm package selected in Settings outrank the newer bundled
241
+ code. `--check-source` fails when package.json is older than npm latest. Tag creation/release is an intentional
237
242
  publication action, not part of an ordinary main commit.
238
243
 
239
244
  The release pipeline uses four **native** targets:
@@ -1,5 +1,12 @@
1
1
  # ORI-38 — controlled host / official-plugin paired updater
2
2
 
3
+ > **Superseded in 0.1.51.** The host + plugin pair transaction described here is
4
+ > retired: plugins no longer take part in host updates, and the launcher owns
5
+ > selection, health admission and rollback. See the upgrade contract in
6
+ > [plugin lifecycle and host update recovery](plugin-update-recovery.md). This page
7
+ > is kept as the record of the earlier design; `host-pair/intent.json` is now only
8
+ > read and settled for compatibility with hosts up to 0.1.50.
9
+
3
10
  ## Delivery boundary
4
11
 
5
12
  Base: `4c0ebbd`, dedicated branch `feat/ori38-paired-update`, worktree `../pi-webapp-ori38`.
@@ -19,21 +19,22 @@ Protocol, resource integrity, permission and data-schema checks remain required.
19
19
  Open editing realms must acknowledge a real checkpoint before activation; a
20
20
  refresh or a newer drawing is never treated as proof that unsaved edits survived.
21
21
 
22
- Host package preparation downloads and validates code without selecting it.
23
- `update-transaction.json` records downloading, validating, prepared, selecting,
24
- selected, restart-requested, and committed phases. Selection follows a reversible
25
- view/worker suspend. Before handoff, failure restores only the pointer bytes owned
26
- by this transaction under the update mutex and resumes the exact old generation.
27
- Cancelled/failed/committed records remain in `update-history`; host-pair records
22
+ Host package preparation downloads and validates code and writes a candidate; it
23
+ never selects it. The launcher owns selection, health admission and rollback (see
24
+ the upgrade contract in [plugin lifecycle and host update recovery](plugin-update-recovery.md)).
25
+ `update-transaction.json` records downloading, validating, prepared,
26
+ restart-requested, committed and failed phases with the real failure cause;
27
+ `selecting`/`selected` appear only in records written by releases before 0.1.51.
28
+ Cancelled/failed/committed records remain in `update-history`. The launcher keeps
29
+ its own outcomes in `upgrade/history`. Host-pair records written by older hosts
28
30
  remain on disk with a terminal cancelled/reconciled phase, never erased.
29
31
 
30
32
  Settings exposes **Cancel unfinished update** through an authenticated same-session
31
- endpoint. It can recover a legacy selected transaction only when the selected
32
- pointer digest still matches its receipt and the current launcher is verified.
33
- A competing pointer is never overwritten. Plugin active state, drawings, backups,
34
- ownership databases and lock markers are not changed by cancellation. Once the
35
- launcher accepts restart, cancellation is refused until health admission or a
36
- verified fallback invocation establishes which host owns recovery.
33
+ endpoint. It aborts a running download or retires a prepared candidate (moved to
34
+ `upgrade/history`). Plugin active state, drawings, backups, ownership databases and
35
+ lock markers are not changed by cancellation. Once the launcher holds the restart
36
+ request, cancellation is refused: the launcher admits the new version or rolls back
37
+ by itself.
37
38
 
38
39
  See [architecture and verification](plugin-update-recovery.md) for the new contract.
39
40
  The ORI-42 reports below are historical evidence, not the current update policy.
@@ -130,6 +131,35 @@ Restart one owner only after recovery. Confirm inventory, enabled intent, active
130
131
  version/generation and latest drawing revisions; compare workspace hashes to the
131
132
  verified backup. The UI explains the offline recovery path for lock errors.
132
133
 
134
+ ### Stale required-action pair journal (hosts up to 0.1.50)
135
+
136
+ Hosts up to 0.1.50 rewrite `host-pair/intent.json` as `required-action` on every
137
+ startup in which an enabled plugin fails to load (for example a developer source
138
+ missing from `installed.json`). Those hosts then refuse every update with
139
+ `Host pair selection pending (<version>, required-action)`, including updates that
140
+ contain the fix, and plugin management is refused too. Newer hosts store a settled
141
+ record as `reconciled` with `lifecyclePhase: "required-action"`, which no host fences.
142
+
143
+ With a desktop shell that has it, prefer the menu item *Reset Update State and Use
144
+ Bundled Version…*: it stops the backend, moves this journal (and every other upgrade
145
+ record) aside and starts the bundled version, no command line needed.
146
+
147
+ Otherwise, quit Pi completely, including its background launcher (`pi-webapp stop`,
148
+ or `pi-webapp stop --force` when a plugin view never confirms its save), back up the
149
+ hosted root (`~/.pi/agent/pi-web/hosted`), then run the recovery CLI from a newer
150
+ package or a source checkout:
151
+
152
+ ```sh
153
+ node dist/hosted-recovery.js inspect "$HOSTED_ROOT/host-pair"
154
+ node dist/hosted-recovery.js settle-pair "$HOSTED_ROOT" "$FINGERPRINT" "$CONFIRMATION"
155
+ ```
156
+
157
+ Only a `required-action` journal is settled; an in-flight `selecting`/`selected`/
158
+ `restart-requested` record is refused (use **Cancel unfinished update**). The original
159
+ record is kept as `history/<id>-settled-<fingerprint>.json`. No pointer, plugin code
160
+ or plugin data changes. The broken plugin stays unavailable on its card until it is
161
+ reinstalled or disabled, but it no longer blocks the update.
162
+
133
163
  ## Fault matrix and reproducible evidence
134
164
 
135
165
  New `test/hosted-update-recovery.test.ts` runs 14 cases. SIGKILL cases use real
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.51",
3
+ "version": "0.1.52-alpha.10",
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.51/assets/cover-webapp.png",
33
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.52-alpha.10/assets/cover-webapp.png",
34
34
  "extensions": [
35
35
  "./dist/extension.js"
36
36
  ]
@@ -68,6 +68,7 @@
68
68
  "lint:fix": "biome lint --write",
69
69
  "test": "node --import ./test/setup-env.mjs --experimental-strip-types --test --test-concurrency=4 test/*.test.ts && npm run test:desktop",
70
70
  "test:desktop": "node --test desktop/test/*.test.mjs",
71
+ "test:quick": "node --import ./test/setup-env.mjs --import ./test/setup-quick.mjs --experimental-strip-types --test --test-concurrency=4 test/*.test.ts",
71
72
  "desktop:icons": "node scripts/generate-desktop-icons.mjs",
72
73
  "desktop:sync-runtime": "node scripts/sync-desktop-runtime.mjs",
73
74
  "desktop:prepare": "npm run build && node scripts/prepare-desktop.mjs",
@@ -76,6 +77,7 @@
76
77
  "desktop:smoke:handoff": "node scripts/smoke-desktop-handoff.mjs",
77
78
  "desktop:smoke:legacy": "node scripts/smoke-desktop-legacy.mjs",
78
79
  "desktop:package": "node scripts/package-desktop.mjs",
80
+ "desktop:prepare-build": "node scripts/prepare-desktop-build.mjs",
79
81
  "build": "node scripts/build.mjs",
80
82
  "build:web": "node scripts/build.mjs browser",
81
83
  "build:extension": "node scripts/build.mjs node",
@@ -152,8 +154,6 @@
152
154
  "node-pty": "1.1.0",
153
155
  "react": "^19.3.1",
154
156
  "react-dom": "^19.3.1",
155
- "react-markdown": "^10.1.0",
156
- "remark-gfm": "^4.0.1",
157
157
  "shiki": "^4.3.1",
158
158
  "simple-icons": "^16.31.0",
159
159
  "undici": "7.30.1"