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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/extension.js +48 -48
  2. package/dist/hosted-recovery.js +3 -3
  3. package/dist/hosted-worker.js +2 -2
  4. package/docs/hosted-plugin-capabilities-rfc.md +3 -2
  5. package/docs/hosted-plugin-installation.md +13 -1
  6. package/package.json +2 -2
  7. package/web/dist/.vite/manifest.json +33 -33
  8. package/web/dist/assets/{MarkdownText-DF8BJV5i.js → MarkdownText-5A28xefP.js} +4 -4
  9. package/web/dist/assets/{app-DwYC983k.js → app-DPpdQGWp.js} +9 -9
  10. package/web/dist/assets/app.js +4 -4
  11. package/web/dist/assets/{code-editor-Njczr4Aq.js → code-editor-3HWVxL8r.js} +4 -4
  12. package/web/dist/assets/{dist-DEGJW0Al.js → dist-2vnWdv_G.js} +2 -2
  13. package/web/dist/assets/{dist-l9rzcKKN.js → dist-BeuVYjPU.js} +2 -2
  14. package/web/dist/assets/{dist-BpfysUin.js → dist-C3o_MAP2.js} +2 -2
  15. package/web/dist/assets/{dist-CLXF6v7a.js → dist-C4Lo5j0a.js} +2 -2
  16. package/web/dist/assets/{dist-xLBkmO57.js → dist-CSu9t8Od.js} +2 -2
  17. package/web/dist/assets/{dist-D2xI7N8L.js → dist-CTA0zpmX.js} +2 -2
  18. package/web/dist/assets/{dist-B88A-0-q.js → dist-CUO62CW5.js} +2 -2
  19. package/web/dist/assets/{dist-CjWP7qLx.js → dist-CdLT51Xs.js} +2 -2
  20. package/web/dist/assets/{dist-BSEV8UWP.js → dist-Cf6teL6k.js} +2 -2
  21. package/web/dist/assets/{dist-BFaxoH5a.js → dist-D2PpQCGI.js} +2 -2
  22. package/web/dist/assets/{dist-B-bd7VCM.js → dist-DjovY3po.js} +2 -2
  23. package/web/dist/assets/{graphql-a_9GNzod.js → graphql-B8opAFBz.js} +2 -2
  24. package/web/dist/assets/{http-DokH81pJ.js → http-TSVA7THf.js} +2 -2
  25. package/web/dist/assets/{php-BYAot5gz.js → php-DsbOr8xg.js} +2 -2
  26. package/web/dist/assets/{plugin-AWio_je_.js → plugin-C3GBA35u.js} +2 -2
  27. package/web/dist/assets/{plugin-BZPaYR4m.js → plugin-Cmwhxdvh.js} +2 -2
  28. package/web/dist/assets/{plugin-BGIBdp5R.js → plugin-cl5toiff.js} +3 -3
  29. package/web/dist/assets/{rst-CUsouaiW.js → rst-DjHKhQNY.js} +2 -2
  30. package/web/dist/assets/{ruby-eGmSFUio.js → ruby-Csf2IhZx.js} +2 -2
  31. package/web/dist/assets/{svelte-CEoWEKJ2.js → svelte-CsknkYPO.js} +2 -2
  32. package/web/dist/assets/{vue-SlhNqE3a.js → vue-laIDtfXB.js} +2 -2
@@ -1,9 +1,9 @@
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]="cffbbe68-7431-4977-a879-5cc153a0ca45",t._sentryDebugIdIdentifier="sentry-dbid-cffbbe68-7431-4977-a879-5cc153a0ca45")}catch{}})();import{resolve as Fe}from"node:path";import{lstat as le,mkdir as Ce,readdir as Me,rename as de}from"node:fs/promises";import{join as k}from"node:path";import{createHash as me}from"node:crypto";var s=class extends Error{code;status;reason;constructor(e,n,r={}){super(n),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};var $=t=>t.code==="ENOENT";var rt={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024};var v=t=>me("sha256").update(t).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ye}from"node:sqlite";import{lstat as Y,mkdir as ve,open as N,rename as be,unlink as Z}from"node:fs/promises";import{dirname as ke,join as X,resolve as Ie}from"node:path";import{randomUUID as _e}from"node:crypto";import{setTimeout as xe}from"node:timers/promises";async function O(t){await ve(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 w(t,e){let n;try{n=await N(t,J.O_RDONLY|J.O_NONBLOCK|(J.O_NOFOLLOW??0))}catch(r){if($(r))return null;throw r}try{let r=await n.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new s("invalid_storage","Invalid storage record size or type");let o=Buffer.alloc(Math.min(r.size+1,e+1)),i=0;for(;i<o.length;){let a=await n.read(o,i,o.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==r.size)throw new s("invalid_storage","Storage record changed during read");return o.subarray(0,i)}finally{await n.close()}}async function A(t,e=2*1024*1024){let n=await w(t,e);if(!n)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new s("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(t){let e=await w(t,2097152);if(e===null)return null;let n;try{n=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(!n||typeof n!="object"||Array.isArray(n))throw new s("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return n}async function b(t,e){let n=`${t}.${_e()}.tmp`,r=await N(n,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await be(n,t);let o;try{o=await N(ke(t),"r"),await o.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await o?.close()}}finally{await Z(n).catch(()=>{})}}var Q='{"version":2,"mechanism":"sqlite-exclusive"}',C=t=>t.toString("utf8")===Q,L=new Set;async function Pe(t,e,n=0){await O(t);let r=X(t,`${e}.lock`),o=X(t,`${e}.ownership.sqlite`),i=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new s(i,"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(o,"wx",384)}catch(u){if(u.code!=="EEXIST")throw u}finally{await c?.close()}let d=await Y(o);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.size>1024*1024)throw new s("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ye(o,{allowExtension:!1}),p=Ie(o),h=Date.now()+n,m=!1;try{for(;;){if(!L.has(p))try{l.exec("BEGIN EXCLUSIVE"),L.add(p),m=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=h)throw new s(i,"Another host owns this plugin storage; wait for it to stop before retrying");await xe(10)}let u=await w(r,4096);if(u===null){let y;try{y=await N(r,"wx",384),await y.writeFile(Q),await y.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await y?.close()}u=await w(r,4096)}if(u===null||!C(u))throw a()}catch(u){throw l.close(),m&&L.delete(p),u}let g=!1;return async()=>{if(g)return;let u=await w(r,4096);if(u===null||!C(u))throw new s("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Z(r),l.close(),L.delete(p),g=!0}}async function x(t,e,n=2e3){let r=await Pe(t,"transaction",n);try{return await e()}finally{await r()}}import{readdir as ut,realpath as ht,rename as Se,stat as Ee}from"node:fs/promises";import{join as U}from"node:path";var M=t=>U(t,"host-pair");var yt=10*6e4;async function Re(t){await Se(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Oe=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=U(M(t),"intent.json"),n,r=!0;try{n=await I(e)}catch{n=null,r=!1}if(!r||n&&!Oe(n))return await Re(e),null;if(n){let{lifecyclePhase:o,...i}=n,a=typeof i.updatedAt=="string"&&!Number.isNaN(Date.parse(i.updatedAt))?i.updatedAt:await Ee(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());n={...i,updatedAt:a,phase:i.phase==="selected"&&o==="restart-requested"?"restart-requested":i.phase==="reconciled"&&o==="cancelled"?"cancelled":i.phase==="reconciled"&&o==="required-action"?"required-action":i.phase}}return n}async function te(t,e){let{lifecyclePhase:n,...r}={...e,selections:[],updatedAt:new Date().toISOString()},o=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await b(U(M(t),"intent.json"),o)}import{lstat as F,mkdir as Ae,open as ne,realpath as ie,readdir as z,link as je,rename as Ne,unlink as P,copyFile as He,rm as Te}from"node:fs/promises";import{dirname as De,isAbsolute as oe,join as f,relative as se,resolve as qe,sep as B,win32 as $e}from"node:path";import{randomUUID as G}from"node:crypto";var kt=64*1024*1024,re=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);var H=192*1024*1024,At=512*1024,ce=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function Le(t){if(!t||typeof t!="object"||Array.isArray(t))throw new s("invalid_input","Expected object input");return t}function ae(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new s("invalid_input","Invalid state key");return t}function T(t){if(t&&(!ce(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 D=class{root;pluginId;legacy;checkpoint;files;constructor(e,n,r,o,i=re){this.root=f(e,v(n)),this.pluginId=n,this.legacy=r,this.checkpoint=o,this.files=i}rule(e){let n=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!n)throw new s("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return n}active(){return A(f(this.root,"active.json")).then(T)}async recover(){return x(this.root,async()=>{let e=await this.active(),n=await I(f(this.root,"transition.json"));if(!n)return{active:e,recovered:"none"};if(!n.next||!Object.hasOwn(n,"before")||Object.keys(n).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(n,"version")&&n.version!==1)throw new s("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(n.next),T(n.before);let r=e?.operationId===n.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(d=>a[d]===c[d]))(e,r==="committed"?n.next:n.before))throw new s("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let i=n.before;if(r==="committed"&&i&&i.stateRef!==e.stateRef&&await b(f(this.root,"previous.json"),i),r==="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:r}})}async activate(e,n){return x(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new s("stale_generation","Plugin activation changed concurrently");let o=await I(f(this.root,"fork.json"));if(o&&(o.version!==1||o.stateRef!==n.stateRef||Object.keys(o).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 i=T({...n,generation:e+1,operationId:G()});await O(f(this.root,"states")),await O(f(this.root,"states",i.stateRef)),await b(f(this.root,"transition.json"),{version:1,before:r,next:i}),await this.checkpoint?.("prepared");try{await b(f(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==i.stateRef&&await b(f(this.root,"previous.json"),r),await P(f(this.root,"transition.json")),await P(f(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return x(this.root,async()=>{let n=await this.assertGeneration(e,!1),r=G(),o=f(this.root,"states",r);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 b(f(this.root,"fork.json"),{version:1,stateRef:r}),await O(o);let i=f(this.root,"states",n.stateRef);for(let a of await z(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new s("invalid_storage","Unexpected state file");if(!await w(f(i,a),H))throw new s("invalid_storage","Missing state file");await He(f(i,a),f(o,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return x(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(f(this.root,l),2*1024*1024))throw new s("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let n=await this.active(),r=T(await I(f(this.root,"previous.json")));if(!n&&await w(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 o=[n,r].filter(l=>!!l),i=f(this.root,"states");await O(i);let a=await z(i),c=new Set(o.map(l=>l.stateRef));for(let l of a){if(!ce(l))throw new s("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=f(i,l),h=await F(p);if(!h.isDirectory()||h.isSymbolicLink())throw new s("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await z(p)){let g=await F(f(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new s("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let u=await A(f(p,m),H);if(!u)throw new s("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(u,"committed")){let y=u;if(Object.keys(y).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||y.committed!==!0||!/^[a-f0-9]{64}$/.test(y.inputHash)||!/^[a-f0-9]{64}$/.test(y.nextHash)||typeof y.requestId!="string")throw new s("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(u).some(y=>!["revision","schema","value","requestId","inputHash"].includes(y)))throw new s("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(u)}}}}for(let l of c)if(!a.includes(l))throw new s("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let d=await e(o);for(let l of a)c.has(l)||await Te(f(i,l),{recursive:!0,force:!0});return d})}async assertGeneration(e,n=!0){let r=await this.active();if(!r||r.generation!==e||n&&!r.enabled)throw new s("stale_generation","Plugin generation is no longer active");return r}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,n,r,o="session"){if(o!=="session"&&o!=="workspace")throw new s("invalid_input","Invalid state scope");let i=o==="workspace"?(this.scopeKey(n),JSON.stringify([n.scope.workspaceId,n.scope.cwd])):this.scopeKey(n);return f(this.root,"states",e.stateRef,`${v(i+":state:"+r)}.json`)}async call(e,n,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new s("invalid_lease","Invalid invocation lease");this.scopeKey(e);let o=Le(r);return x(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(n){case"state.read":{let a=await A(this.statePath(i,e,ae(o.key),o.scope),H);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,ae(o.key),o.scope);if(!Number.isSafeInteger(o.expectedRevision)||o.expectedRevision<0||o.schema!==i.schema||!Object.hasOwn(o,"value"))throw new s("invalid_input","Invalid state revision or schema");if(JSON.stringify(o.value)===void 0)throw new s("invalid_input","State value must be JSON serializable");let c=JSON.stringify(o);if(Buffer.byteLength(c)>H)throw new s("state_too_large","Plugin state exceeds limit");let d=await A(a,H);d&&this.validateState(d);let l=v(c);if(d?.requestId===e.requestId&&d.inputHash===l)return{revision:d.revision,schema:d.schema,value:d.value};if((d?.revision??0)!==o.expectedRevision)throw new s("revision_conflict","Plugin state changed concurrently");let p={revision:o.expectedRevision+1,schema:i.schema,value:o.value,requestId:e.requestId,inputHash:l};return await b(a,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let a=this.rule(o.path),{target:c}=await this.fileTarget(e.scope.cwd,o.path),d=o.maxBytes===void 0?a.maxBytes:o.maxBytes;if(!Number.isSafeInteger(d)||d<=0||d>a.maxBytes)throw new s("invalid_input","Invalid workspace read limit");if(o.encoding!==void 0&&o.encoding!==(a.binary?"base64":"utf-8"))throw new s("invalid_input","Encoding does not match the reviewed file rule");let l=await w(c,d);return l?a.binary?{base64:l.toString("base64"),bytes:l.length,hash:v(l)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(l),hash:v(l)}:null}case"workspace.commit":return this.commitFile(i,e,o);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,n,r=!1){let o=this.rule(n);if(typeof n!="string"||n.length>4096||n.includes("\\")||n.includes("\0")||oe(n)||$e.isAbsolute(n))throw new s("invalid_path",`Use a workspace-relative ${o.extension} path`);let i=await ie(e),a=qe(i,n),c=se(i,a);if(!c||c===".."||c.startsWith(`..${B}`)||oe(c))throw new s("invalid_path","Workspace path escapes root");let d=i,l=c.split(B);for(let h=0;h<l.length;h++){d=f(d,l[h]);let m;try{m=await F(d)}catch(g){if(!$(g))throw g;if(h<l.length-1){if(!r||!o.createDirectory||se(i,d)!==o.createDirectory)throw new s("invalid_path","Workspace directory does not exist");try{await Ae(d,{mode:448})}catch(u){if(u.code!=="EEXIST")throw u}m=await F(d)}}if(m&&(m.isSymbolicLink()||(h<l.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new s("invalid_path","Workspace path contains a link or non-regular file")}let p=await ie(De(a));if(p!==i&&!p.startsWith(i+B))throw new s("invalid_path","Workspace directory changed");return{target:a,parent:p}}async commitFile(e,n,r){let o=this.rule(r.path),i=o.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!i||i.length>o.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new s("invalid_input","Invalid file content or expected hash");let{target:a,parent:c}=await this.fileTarget(n.scope.cwd,r.path,!0),d=f(this.root,"states",e.stateRef,`${v(this.scopeKey(n)+":file:"+n.requestId+":"+String(r.path))}.json`),l=v(JSON.stringify(r)),p=v(i),h=await A(d);if(h&&(h.requestId!==n.requestId||h.inputHash!==l||h.nextHash!==p))throw new s("duplicate_request","Request ID was reused with different content");let m;try{m=await ne(`${a}.lock`,"wx",384)}catch(u){throw u.code==="EEXIST"?new s("file_busy","Workspace file is locked; original file preserved"):u}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:n.requestId}));let u=await w(a,o.maxBytes),y=u?v(u):null;if(h&&y===p)return{hash:p};if(h?.committed||y!==r.expectedHash)throw new s("file_conflict","Workspace file already exists or changed externally");await b(d,{requestId:n.requestId,inputHash:l,nextHash:p,committed:!1}),g=f(c,`.plugin-${G()}.tmp`);let _=await ne(g,"wx",384);try{await _.writeFile(i),await _.sync()}finally{await _.close()}if((await this.fileTarget(n.scope.cwd,r.path)).parent!==c)throw new s("file_conflict","Workspace directory changed during save");let K=await w(a,o.maxBytes);if((K?v(K):null)!==r.expectedHash)throw new s("file_conflict","Workspace file changed during save");if(await this.assertGeneration(n.generation),r.expectedHash===null){try{await je(g,a)}catch(V){throw V.code==="EEXIST"?new s("file_conflict","Workspace file was created concurrently"):V}await P(g),g=void 0}else await Ne(g,a),g=void 0;return await b(d,{requestId:n.requestId,inputHash:l,nextHash:p,committed:!0}),{hash:p}}finally{g&&await P(g).catch(()=>{}),await m.close(),await P(`${a}.lock`)}}};var W="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function j(t){let e=[];async function n(r,o=""){let i=await le(r);if(!i.isDirectory()||i.isSymbolicLink())throw new s("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Me(r)).sort()){let c=k(r,a),d=o+a,l=await le(c);if(l.isSymbolicLink())throw new s("invalid_storage","Recovery refuses links");if(l.isDirectory())await n(c,d+"/");else{if(e.length>=1e4)throw new s("invalid_storage","Recovery inspection budget exceeded");let p=await w(c,192*1024*1024);if(!p)throw new s("invalid_storage","Recovery input disappeared");e.push({path:d,bytes:p.length,sha256:v(p)})}}}return await n(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 fe(t,e,n,r){let o=new D(t,e),i=await j(o.root);if(r!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==n)throw new s("recovery_changed","Storage changed since inspection");return o.recover()}async function pe(t,e,n,r){let o=new D(t,e),i=o.root;if(r!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await j(i);if(a.fingerprint!==n)throw new s("recovery_changed","Storage changed since inspection");if(await w(k(i,"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(k(i,"fork.json")),d=await o.active(),l=await I(k(i,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(h=>!["version","stateRef"].includes(h))||!d||l&&typeof l.stateRef!="string"||[d?.stateRef,l?.stateRef].includes(c.stateRef))throw new s("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let p=`recovered-${n}-fork.json`;if(a.files.some(h=>h.path===p))throw new s("recovery_changed","Recovery evidence already exists");return await de(k(i,"fork.json"),k(i,p)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:n}}async function ue(t,e,n){if(n!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let r=await j(t);if(r.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let o=[];for(let i of r.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await w(k(t,i.path),2097152);a&&!C(a)&&o.push(i)}for(let i of o){let a=`recovered-${e}-${i.path}.json`;if(r.files.some(c=>c.path===a))throw new s("recovery_changed","Recovery evidence already exists")}for(let i of o)await de(k(t,i.path),k(t,`recovered-${e}-${i.path}.json`));return await b(k(t,`recovery-${e}.json`),{version:1,fingerprint:e,locks:o,confirmation:n,recoveredAt:new Date().toISOString()}),{recovered:o.map(i=>i.path),fingerprint:e}}async function he(t,e,n){if(n!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let r=M(t),o=await j(r);if(o.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing settled, inspect again");let i=o.files.find(a=>a.path==="intent.json");if(!i)throw new s("invalid_input","No host pair journal to settle");return x(r,async()=>{let a=await w(k(r,"intent.json"),2097152);if(!a||v(a)!==i.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 d=k(r,"history",`${c.id}-settled-${e}.json`);if(await w(d,2*1024*1024))throw new s("recovery_changed","Recovery evidence already exists");return await Ce(k(r,"history"),{recursive:!0,mode:448}),await b(d,c),await te(t,{...c,phase:"reconciled",message:`Settled offline by operator; current host and plugin data retained. Was: ${c.message??"no message"}`}),await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,settled:c.id,confirmation:n,recoveredAt:new Date().toISOString()}),{settled:c.id,version:c.version,fingerprint:e}})}var[S,ge,E,R,q,...We]=process.argv.slice(2),Je=ge&&!We.length&&(S==="inspect"&&!E&&!R&&!q||["recover-locks","settle-pair"].includes(S??"")&&E&&R&&!q||["recover-fork","reconcile-transition"].includes(S??"")&&E&&R&&q);if(!Je)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]="cc90b020-2bc0-4818-89ed-06824c863d1c",t._sentryDebugIdIdentifier="sentry-dbid-cc90b020-2bc0-4818-89ed-06824c863d1c")}catch{}})();import{resolve as Me}from"node:path";import{lstat as le,mkdir as Ce,readdir as Fe,rename as de}from"node:fs/promises";import{join as k}from"node:path";import{createHash as me}from"node:crypto";var s=class extends Error{code;status;reason;constructor(e,n,r={}){super(n),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};var $=t=>t.code==="ENOENT";var rt={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024};var v=t=>me("sha256").update(t).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ye}from"node:sqlite";import{lstat as Y,mkdir as ve,open as N,rename as be,unlink as Z}from"node:fs/promises";import{dirname as ke,join as X,resolve as Ie}from"node:path";import{randomUUID as _e}from"node:crypto";import{setTimeout as xe}from"node:timers/promises";async function O(t){await ve(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 w(t,e){let n;try{n=await N(t,J.O_RDONLY|J.O_NONBLOCK|(J.O_NOFOLLOW??0))}catch(r){if($(r))return null;throw r}try{let r=await n.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new s("invalid_storage","Invalid storage record size or type");let o=Buffer.alloc(Math.min(r.size+1,e+1)),i=0;for(;i<o.length;){let a=await n.read(o,i,o.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==r.size)throw new s("invalid_storage","Storage record changed during read");return o.subarray(0,i)}finally{await n.close()}}async function A(t,e=2*1024*1024){let n=await w(t,e);if(!n)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new s("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(t){let e=await w(t,2097152);if(e===null)return null;let n;try{n=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(!n||typeof n!="object"||Array.isArray(n))throw new s("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return n}async function b(t,e){let n=`${t}.${_e()}.tmp`,r=await N(n,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await be(n,t);let o;try{o=await N(ke(t),"r"),await o.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await o?.close()}}finally{await Z(n).catch(()=>{})}}var Q='{"version":2,"mechanism":"sqlite-exclusive"}',C=t=>t.toString("utf8")===Q,L=new Set;async function Se(t,e,n=0){await O(t);let r=X(t,`${e}.lock`),o=X(t,`${e}.ownership.sqlite`),i=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new s(i,"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(o,"wx",384)}catch(p){if(p.code!=="EEXIST")throw p}finally{await c?.close()}let d=await Y(o);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.size>1024*1024)throw new s("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ye(o,{allowExtension:!1}),u=Ie(o),h=Date.now()+n,m=!1;try{for(;;){if(!L.has(u))try{l.exec("BEGIN EXCLUSIVE"),L.add(u),m=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=h)throw new s(i,"Another host owns this plugin storage; wait for it to stop before retrying");await xe(10)}let p=await w(r,4096);if(p===null){let y;try{y=await N(r,"wx",384),await y.writeFile(Q),await y.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await y?.close()}p=await w(r,4096)}if(p===null||!C(p))throw a()}catch(p){throw l.close(),m&&L.delete(u),p}let g=!1;return async()=>{if(g)return;let p=await w(r,4096);if(p===null||!C(p))throw new s("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Z(r),l.close(),L.delete(u),g=!0}}async function x(t,e,n=2e3){let r=await Se(t,"transaction",n);try{return await e()}finally{await r()}}import{readdir as pt,realpath as ht,rename as Pe,stat as Re}from"node:fs/promises";import{join as U}from"node:path";var F=t=>U(t,"host-pair");var yt=10*6e4;async function Ee(t){await Pe(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Oe=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=U(F(t),"intent.json"),n,r=!0;try{n=await I(e)}catch{n=null,r=!1}if(!r||n&&!Oe(n))return await Ee(e),null;if(n){let{lifecyclePhase:o,...i}=n,a=typeof i.updatedAt=="string"&&!Number.isNaN(Date.parse(i.updatedAt))?i.updatedAt:await Re(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());n={...i,updatedAt:a,phase:i.phase==="selected"&&o==="restart-requested"?"restart-requested":i.phase==="reconciled"&&o==="cancelled"?"cancelled":i.phase==="reconciled"&&o==="required-action"?"required-action":i.phase}}return n}async function te(t,e){let{lifecyclePhase:n,...r}={...e,selections:[],updatedAt:new Date().toISOString()},o=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await b(U(F(t),"intent.json"),o)}import{lstat as M,mkdir as Ae,open as ne,realpath as ie,readdir as B,link as je,rename as Ne,unlink as S,copyFile as He,rm as Te}from"node:fs/promises";import{dirname as De,isAbsolute as oe,join as f,relative as se,resolve as qe,sep as z,win32 as $e}from"node:path";import{randomUUID as G}from"node:crypto";var kt=64*1024*1024,re=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);var H=192*1024*1024,At=512*1024,ce=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function Le(t){if(!t||typeof t!="object"||Array.isArray(t))throw new s("invalid_input","Expected object input");return t}function ae(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new s("invalid_input","Invalid state key");return t}function T(t){if(t&&(!ce(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 D=class{root;pluginId;legacy;checkpoint;files;constructor(e,n,r,o,i=re){this.root=f(e,v(n)),this.pluginId=n,this.legacy=r,this.checkpoint=o,this.files=i}rule(e){let n=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!n)throw new s("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return n}active(){return A(f(this.root,"active.json")).then(T)}async recover(){return x(this.root,async()=>{let e=await this.active(),n=await I(f(this.root,"transition.json"));if(!n)return{active:e,recovered:"none"};if(!n.next||!Object.hasOwn(n,"before")||Object.keys(n).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(n,"version")&&n.version!==1)throw new s("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(n.next),T(n.before);let r=e?.operationId===n.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(d=>a[d]===c[d]))(e,r==="committed"?n.next:n.before))throw new s("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let i=n.before;if(r==="committed"&&i&&i.stateRef!==e.stateRef&&await b(f(this.root,"previous.json"),i),r==="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 S(f(this.root,"fork.json"))}return await S(f(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,n){return x(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new s("stale_generation","Plugin activation changed concurrently");let o=await I(f(this.root,"fork.json"));if(o&&(o.version!==1||o.stateRef!==n.stateRef||Object.keys(o).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 i=T({...n,generation:e+1,operationId:G()});await O(f(this.root,"states")),await O(f(this.root,"states",i.stateRef)),await b(f(this.root,"transition.json"),{version:1,before:r,next:i}),await this.checkpoint?.("prepared");try{await b(f(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==i.stateRef&&await b(f(this.root,"previous.json"),r),await S(f(this.root,"transition.json")),await S(f(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return x(this.root,async()=>{let n=await this.assertGeneration(e,!1),r=G(),o=f(this.root,"states",r);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 b(f(this.root,"fork.json"),{version:1,stateRef:r}),await O(o);let i=f(this.root,"states",n.stateRef);for(let a of await B(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new s("invalid_storage","Unexpected state file");if(!await w(f(i,a),H))throw new s("invalid_storage","Missing state file");await He(f(i,a),f(o,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return x(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(f(this.root,l),2*1024*1024))throw new s("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let n=await this.active(),r=T(await I(f(this.root,"previous.json")));if(!n&&await w(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 o=[n,r].filter(l=>!!l),i=f(this.root,"states");await O(i);let a=await B(i),c=new Set(o.map(l=>l.stateRef));for(let l of a){if(!ce(l))throw new s("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=f(i,l),h=await M(u);if(!h.isDirectory()||h.isSymbolicLink())throw new s("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await B(u)){let g=await M(f(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new s("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let p=await A(f(u,m),H);if(!p)throw new s("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(p,"committed")){let y=p;if(Object.keys(y).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||y.committed!==!0||!/^[a-f0-9]{64}$/.test(y.inputHash)||!/^[a-f0-9]{64}$/.test(y.nextHash)||typeof y.requestId!="string")throw new s("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(p).some(y=>!["revision","schema","value","requestId","inputHash"].includes(y)))throw new s("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(p)}}}}for(let l of c)if(!a.includes(l))throw new s("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let d=await e(o);for(let l of a)c.has(l)||await Te(f(i,l),{recursive:!0,force:!0});return d})}async assertGeneration(e,n=!0){let r=await this.active();if(!r||r.generation!==e||n&&!r.enabled)throw new s("stale_generation","Plugin generation is no longer active");return r}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,n,r,o="session"){if(o!=="session"&&o!=="workspace")throw new s("invalid_input","Invalid state scope");let i=o==="workspace"?(this.scopeKey(n),JSON.stringify([n.scope.workspaceId,n.scope.cwd])):this.scopeKey(n);return f(this.root,"states",e.stateRef,`${v(i+":state:"+r)}.json`)}async call(e,n,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new s("invalid_lease","Invalid invocation lease");this.scopeKey(e);let o=Le(r);return x(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(n){case"state.read":{let a=await A(this.statePath(i,e,ae(o.key),o.scope),H);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,ae(o.key),o.scope);if(!Number.isSafeInteger(o.expectedRevision)||o.expectedRevision<0||o.schema!==i.schema||!Object.hasOwn(o,"value"))throw new s("invalid_input","Invalid state revision or schema");if(JSON.stringify(o.value)===void 0)throw new s("invalid_input","State value must be JSON serializable");let c=JSON.stringify(o);if(Buffer.byteLength(c)>H)throw new s("state_too_large","Plugin state exceeds limit");let d=await A(a,H);d&&this.validateState(d);let l=v(c);if(d?.requestId===e.requestId&&d.inputHash===l)return{revision:d.revision,schema:d.schema,value:d.value};if((d?.revision??0)!==o.expectedRevision)throw new s("revision_conflict","Plugin state changed concurrently");let u={revision:o.expectedRevision+1,schema:i.schema,value:o.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let a=this.rule(o.path),{target:c}=await this.fileTarget(e.scope.cwd,o.path),d=o.maxBytes===void 0?a.maxBytes:o.maxBytes;if(!Number.isSafeInteger(d)||d<=0||d>a.maxBytes)throw new s("invalid_input","Invalid workspace read limit");if(o.encoding!==void 0&&o.encoding!==(a.binary?"base64":"utf-8"))throw new s("invalid_input","Encoding does not match the reviewed file rule");let l=await w(c,d);return l?a.binary?{base64:l.toString("base64"),bytes:l.length,hash:v(l)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(l),hash:v(l)}:null}case"workspace.commit":return this.commitFile(i,e,o);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,n,r=!1){let o=this.rule(n);if(typeof n!="string"||n.length>4096||n.includes("\\")||n.includes("\0")||oe(n)||$e.isAbsolute(n))throw new s("invalid_path",`Use a workspace-relative ${o.extension} path`);let i=await ie(e),a=qe(i,n),c=se(i,a);if(!c||c===".."||c.startsWith(`..${z}`)||oe(c))throw new s("invalid_path","Workspace path escapes root");let d=i,l=c.split(z);for(let h=0;h<l.length;h++){d=f(d,l[h]);let m;try{m=await M(d)}catch(g){if(!$(g))throw g;if(h<l.length-1){if(!r||!o.createDirectory||se(i,d)!==o.createDirectory)throw new s("invalid_path","Workspace directory does not exist");try{await Ae(d,{mode:448})}catch(p){if(p.code!=="EEXIST")throw p}m=await M(d)}}if(m&&(m.isSymbolicLink()||(h<l.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new s("invalid_path","Workspace path contains a link or non-regular file")}let u=await ie(De(a));if(u!==i&&!u.startsWith(i+z))throw new s("invalid_path","Workspace directory changed");return{target:a,parent:u}}async commitFile(e,n,r){let o=this.rule(r.path),i=o.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!i||i.length>o.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new s("invalid_input","Invalid file content or expected hash");let{target:a,parent:c}=await this.fileTarget(n.scope.cwd,r.path,!0),d=f(this.root,"states",e.stateRef,`${v(this.scopeKey(n)+":file:"+n.requestId+":"+String(r.path))}.json`),l=v(JSON.stringify(r)),u=v(i),h=await A(d);if(h&&(h.requestId!==n.requestId||h.inputHash!==l||h.nextHash!==u))throw new s("duplicate_request","Request ID was reused with different content");let m;try{m=await ne(`${a}.lock`,"wx",384)}catch(p){throw p.code==="EEXIST"?new s("file_busy","Workspace file is locked; original file preserved"):p}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:n.requestId}));let p=await w(a,o.maxBytes),y=p?v(p):null;if(h&&y===u)return{hash:u};if(h?.committed||y!==r.expectedHash)throw new s("file_conflict","Workspace file already exists or changed externally");await b(d,{requestId:n.requestId,inputHash:l,nextHash:u,committed:!1}),g=f(c,`.plugin-${G()}.tmp`);let _=await ne(g,"wx",384);try{await _.writeFile(i),await _.sync()}finally{await _.close()}if((await this.fileTarget(n.scope.cwd,r.path)).parent!==c)throw new s("file_conflict","Workspace directory changed during save");let K=await w(a,o.maxBytes);if((K?v(K):null)!==r.expectedHash)throw new s("file_conflict","Workspace file changed during save");if(await this.assertGeneration(n.generation),r.expectedHash===null){try{await je(g,a)}catch(V){throw V.code==="EEXIST"?new s("file_conflict","Workspace file was created concurrently"):V}await S(g),g=void 0}else await Ne(g,a),g=void 0;return await b(d,{requestId:n.requestId,inputHash:l,nextHash:u,committed:!0}),{hash:u}}finally{g&&await S(g).catch(()=>{}),await m.close(),await S(`${a}.lock`)}}};var W="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function j(t){let e=[];async function n(r,o=""){let i=await le(r);if(!i.isDirectory()||i.isSymbolicLink())throw new s("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Fe(r)).sort()){let c=k(r,a),d=o+a,l=await le(c);if(l.isSymbolicLink())throw new s("invalid_storage","Recovery refuses links");if(l.isDirectory())await n(c,d+"/");else{if(e.length>=1e4)throw new s("invalid_storage","Recovery inspection budget exceeded");let u=await w(c,192*1024*1024);if(!u)throw new s("invalid_storage","Recovery input disappeared");e.push({path:d,bytes:u.length,sha256:v(u)})}}}return await n(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 fe(t,e,n,r){let o=new D(t,e),i=await j(o.root);if(r!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==n)throw new s("recovery_changed","Storage changed since inspection");return o.recover()}async function ue(t,e,n,r){let o=new D(t,e),i=o.root;if(r!==W)throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await j(i);if(a.fingerprint!==n)throw new s("recovery_changed","Storage changed since inspection");if(await w(k(i,"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(k(i,"fork.json")),d=await o.active(),l=await I(k(i,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(h=>!["version","stateRef"].includes(h))||!d||l&&typeof l.stateRef!="string"||[d?.stateRef,l?.stateRef].includes(c.stateRef))throw new s("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${n}-fork.json`;if(a.files.some(h=>h.path===u))throw new s("recovery_changed","Recovery evidence already exists");return await de(k(i,"fork.json"),k(i,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:n}}async function pe(t,e,n){if(n!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let r=await j(t);if(r.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let o=[];for(let i of r.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await w(k(t,i.path),2097152);a&&!C(a)&&o.push(i)}for(let i of o){let a=`recovered-${e}-${i.path}.json`;if(r.files.some(c=>c.path===a))throw new s("recovery_changed","Recovery evidence already exists")}for(let i of o)await de(k(t,i.path),k(t,`recovered-${e}-${i.path}.json`));return await b(k(t,`recovery-${e}.json`),{version:1,fingerprint:e,locks:o,confirmation:n,recoveredAt:new Date().toISOString()}),{recovered:o.map(i=>i.path),fingerprint:e}}async function he(t,e,n){if(n!==W||!/^[a-f0-9]{64}$/.test(e))throw new s("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let r=F(t),o=await j(r);if(o.fingerprint!==e)throw new s("recovery_changed","Storage changed since inspection; nothing settled, inspect again");let i=o.files.find(a=>a.path==="intent.json");if(!i)throw new s("invalid_input","No host pair journal to settle");return x(r,async()=>{let a=await w(k(r,"intent.json"),2097152);if(!a||v(a)!==i.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 d=k(r,"history",`${c.id}-settled-${e}.json`);if(await w(d,2*1024*1024))throw new s("recovery_changed","Recovery evidence already exists");return await Ce(k(r,"history"),{recursive:!0,mode:448}),await b(d,c),await te(t,{...c,phase:"reconciled",message:`Settled offline by operator; current host and plugin data retained. Was: ${c.message??"no message"}`}),await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,settled:c.id,confirmation:n,recoveredAt:new Date().toISOString()}),{settled:c.id,version:c.version,fingerprint:e}})}var[P,ge,R,E,q,...We]=process.argv.slice(2),Je=ge&&!We.length&&(P==="inspect"&&!R&&!E&&!q||["recover-locks","settle-pair"].includes(P??"")&&R&&E&&!q||["recover-fork","reconcile-transition"].includes(P??"")&&R&&E&&q);if(!Je)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
5
5
  recover-fork DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
6
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=Fe(ge),e=S==="inspect"?await j(t):S==="recover-locks"?await ue(t,E,R):S==="settle-pair"?await he(t,E,R):S==="recover-fork"?await pe(t,E,R,q):await fe(t,E,R,q);console.log(JSON.stringify(e,null,2))}catch(t){console.error(t instanceof Error?t.message:"Recovery failed"),process.exitCode=1}var Jt=void 0;export{Jt as default};
7
+ CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let t=Me(ge),e=P==="inspect"?await j(t):P==="recover-locks"?await pe(t,R,E):P==="settle-pair"?await he(t,R,E):P==="recover-fork"?await ue(t,R,E,q):await fe(t,R,E,q);console.log(JSON.stringify(e,null,2))}catch(t){console.error(t instanceof Error?t.message:"Recovery failed"),process.exitCode=1}var Jt=void 0;export{Jt as default};
8
8
 
9
- //# debugId=cffbbe68-7431-4977-a879-5cc153a0ca45
9
+ //# debugId=cc90b020-2bc0-4818-89ed-06824c863d1c
@@ -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]="8643b57a-f3a1-4a66-8fc8-c13470feede5",t._sentryDebugIdIdentifier="sentry-dbid-8643b57a-f3a1-4a66-8fc8-c13470feede5")}catch{}})();import{AsyncLocalStorage as y}from"node:async_hooks";import{pathToFileURL as b}from"node:url";function c(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var f=new y,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(b(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(p,g){let u=f.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,w)=>{s.set(d,{resolve:m,reject:w}),a({type:"broker-request",id:d,invocationId:u.requestId,method:p,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return f.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
1
+ (function(){try{var t=typeof 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]="cb67587f-8541-4199-bb12-d5ed736c1afd",t._sentryDebugIdIdentifier="sentry-dbid-cb67587f-8541-4199-bb12-d5ed736c1afd")}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=8643b57a-f3a1-4a66-8fc8-c13470feede5
3
+ //# debugId=cb67587f-8541-4199-bb12-d5ed736c1afd
@@ -1,6 +1,6 @@
1
1
  # RFC: hosted plugin capabilities (secrets, network, scheduler, sessions)
2
2
 
3
- Status: host core, `HostedPluginManager` wiring, session adapter, production bootstrap, secrets UI, policies, dev-archive install and the first consumer (`@chengzhiyi/pi-github`) implemented and covered by tests (`test/hosted-github-e2e.test.ts`) plus a live smoke run. Pending: execute-approval UI, secrets UI/keychain, generic (non-excalidraw) plugin catalog/integration, workspace-level plugin state. Motivated by `@chengzhiyi/pi-github` (issue -> agent loop), but nothing here is GitHub-specific.
3
+ Status: host core, `HostedPluginManager` wiring, session adapter, production bootstrap, secrets UI, policies, dev-archive install and the first consumer (`@chengzhiyi/pi-github`) implemented and covered by tests plus a live smoke run. The GitHub package has since been withdrawn; the host no longer names it, and its end-to-end test was removed with it. The capabilities themselves stay, inert until a plugin declares them. Pending: execute-approval UI, secrets UI/keychain, generic (non-excalidraw) plugin catalog/integration, workspace-level plugin state. Motivated by `@chengzhiyi/pi-github` (issue -> agent loop), but nothing here is GitHub-specific.
4
4
 
5
5
  ## Principles
6
6
  - Plugin code stays in a child process with an allowlisted environment. It never receives secrets and never opens sockets itself.
@@ -31,7 +31,7 @@ Hosts are exact lowercase DNS names (no wildcards, no IPs). Schedule interval is
31
31
 
32
32
  ## Not done
33
33
  1. **Execute approval (done)**: `sessions.send {mode:"execute"}` calls `ExecuteApprovals.authorize`, which queues a request and fails with `approval_required` (409); the plugin retries on later ticks. The host UI (`ExecuteApprovalPrompt`, fed by `approvals` in the hosted catalog and refreshed by `hosted_plugins_changed`) shows Allow/Deny; `POST /api/hosted-plugins/approvals {id, decision}` (bearer + same-origin + JSON like other hosted routes, fenced while restarting) is the only way to grant. A grant lasts for that session only and is dropped on `sessions.release`; a denial blocks re-asking for 60 s. A request cannot be answered by another plugin. In-memory only: a host restart clears pending/granted state, which re-asks (fail-closed).
34
- 2. **Plugin installability (host side done)**: reviewed per-plugin trust data now lives in `plugin-policies.ts` (`HostedPluginPolicy`: tools, readonly actions, UI actions, checkpoint actions, contribution), passed to `HostedPluginIntegration` via `policies` next to the catalog. Excalidraw's policy is the built-in default. Still needed for GitHub: a catalog entry + policy (deliberately not registered until the package is publishable, so no dead card appears), a frontend entry in the package, and client-side generality (icon mapping in `PluginIcon.tsx`, excalidraw-only `view-journal.ts`; `state-broker` still restricts `workspace.commit` to `.excalidraw` paths, which is a safe default for plugins that write no files).
34
+ 2. **Plugin installability (host side done)**: reviewed per-plugin trust data now lives in `official-plugins.json` (types in `plugin-policies.ts`, validation in `catalog-schema.ts`; `HostedPluginPolicy`: tools, readonly actions, UI actions, checkpoint actions, contribution), passed to `HostedPluginIntegration` via `policies` next to the catalog. Excalidraw's policy is the built-in default. Still needed for GitHub: a catalog entry + policy (deliberately not registered until the package is publishable, so no dead card appears), a frontend entry in the package, and client-side generality (icon mapping in `PluginIcon.tsx`, excalidraw-only `view-journal.ts`; `state-broker` still restricts `workspace.commit` to `.excalidraw` paths, which is a safe default for plugins that write no files).
35
35
  3. **State scope (done)**: `state.read`/`state.compareAndSwap` accept `scope: "workspace"` (default `"session"`). Workspace state is keyed by the authenticated `[workspaceId, cwd]`, so every chat session and scheduled tick of one workspace shares it (CAS on revision still arbitrates); session state is unchanged and isolated. Covered by `test/hosted-workspace-state.test.ts`.
36
36
  4. Secrets entry UI (route + settings), OS-keychain `SecretStore`, daily budget, ownership persistence across restarts.
37
37
  5. DNS pinning for `network.fetch`; refresh the vendored protocol tgz.
@@ -40,4 +40,5 @@ Hosts are exact lowercase DNS names (no wildcards, no IPs). Schedule interval is
40
40
  - **Secrets UI/route**: `POST /api/hosted-plugins/secrets {pluginId,name,value|null}` (declared names of an *enabled* plugin only; value never returned); catalog cards expose `secrets: [{name, configured}]`; `management.tsx` renders a write-only token field.
41
41
  - **Dev archives**: `PI_WEBAPP_HOSTED_DEV_ARCHIVES="<id>=<path.tgz>;..."` adds a catalog entry (ids known to `dev-plugins.ts` only) and installs/updates from the local archive through the normal extraction/identity/resource validation (`installDevArchive`); no registry, no publisher SRI.
42
42
  - **Dev roots (hot reload)**: `PI_WEBAPP_HOSTED_DEV_ROOTS=<package dir>[:<dir>…]` and/or `<agentDir>/pi-web/hosted-dev.json` (`{"roots":[abs paths]}`, re-read on every poll) opt a plugin package *directory* in. `installDevDirectory` snapshots only `package.json` + `dist/` (no links, bounded) into staging and runs the same `validateHostedPackage` + host-range + capability checks as an archive; it assigns a strictly increasing patch version per distinct content hash (`dev-sources.json`), reusing the version for unchanged content. `HostedDevWatcher` (host side, polled signature that must be stable across two polls) then runs the normal serialized `update` with `reopenEditors`, so freeze/switch/reopen is the existing path; a failed build leaves the running plugin untouched, and uninstalled plugins are never "updated". Diagnostics for bad paths/ids/manifests are logged (`[hosted-dev]`), shown on the Plugins page (`catalog.dev`) and written to `pi-web/hosted-dev-status.json`, which `pnpm dev` in the plugin workspace reads. The plugin catalog is fixed at host start, so a plugin registered afterwards is reported as "restart once". Production (official catalog, SRI, immutable versions) is unchanged and dev mode is inert without the explicit opt-in.
43
+ - **Self-described dev packages**: an official plugin in a dev root always runs under its reviewed `official-plugins.json` policy. Any other package must describe itself in `package.json` `piWebappCatalog` (`name`, `description`, `policy`, optional `icon`/`recommendedVersion`/`requiredCapabilities`, which default to the manifest's capabilities); it is validated by the same `parseCatalogEntry` as official data, joins the catalog at startup only, and is never labelled Official. A later edit to its policy is reported as needing a restart, while code keeps reloading live. `PI_WEBAPP_HOSTED_DEV_ARCHIVES` accepts official ids only.
43
44
  - **Shutdown bug found by the smoke run**: `integration.lifecycle` cleared the "immediate reopen" consent for *all* plugins after the first plugin finished, so with two catalog plugins a later plugin's open workspace view blocked `stop` ("Close editors before updating"). Fixed (consent cleared only after the whole shutdown); regression `test/hosted-multi-plugin-shutdown.test.ts`. The stop failure reason is now logged to `launcher.log`, and the refusal message names busy/in-flight views.
@@ -12,7 +12,19 @@ builtin drawings remain registered until parity and migration are verified.
12
12
 
13
13
  ## Modules
14
14
 
15
- - `official-catalog.ts`: offline metadata only, trusted exact package identity,
15
+ - `official-plugins.json`: the reviewed official plugins, one entry per plugin —
16
+ the catalog card (`id`, `name`, `icon`, `description`, `registry`,
17
+ `recommendedVersion`, `requiredCapabilities`) and its trust `policy` (tools,
18
+ readonly/UI/checkpoint actions, contribution, and optional browser, workspace,
19
+ runtime and secret sign-in rules). It is the only place the host names a plugin
20
+ (Excalidraw's legacy-drawing migration excepted); adding or changing one is a
21
+ data edit plus a host release. `catalog-schema.ts` validates it strictly at
22
+ startup (unknown keys, bounds, subset rules) and deep-freezes the result. The
23
+ same entry shape is what a dev package declares in `package.json`
24
+ `piWebappCatalog` (minus `id`/`registry`) and what a signed remote catalog will
25
+ carry later.
26
+ - `official-catalog.ts`: loads that file into `OFFICIAL_PLUGINS` and
27
+ `DEFAULT_POLICIES`; offline metadata only, trusted exact package identity,
16
28
  compatible stable-version selection, explicit independent/host-update policy.
17
29
  Never follows `latest`, installs absent plugins during host updates, enables
18
30
  disabled plugins, or silently downgrades a newer compatible version.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.55-alpha.1",
3
+ "version": "0.1.55-alpha.3",
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.55-alpha.1/assets/cover-webapp.png",
33
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.55-alpha.3/assets/cover-webapp.png",
34
34
  "extensions": [
35
35
  "./dist/extension.js"
36
36
  ]
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "../../node_modules/@codemirror/lang-angular/dist/index.js": {
3
- "file": "assets/dist-CLXF6v7a.js",
3
+ "file": "assets/dist-C4Lo5j0a.js",
4
4
  "name": "dist",
5
5
  "src": "../../node_modules/@codemirror/lang-angular/dist/index.js",
6
6
  "isDynamicEntry": true,
7
7
  "imports": [
8
8
  "_dist-IkQ96Etc.js",
9
9
  "../../node_modules/@codemirror/lang-html/dist/index.js",
10
- "_dist-D2xI7N8L.js",
10
+ "_dist-CTA0zpmX.js",
11
11
  "_dist-DTWmF6Zy.js"
12
12
  ]
13
13
  },
@@ -22,7 +22,7 @@
22
22
  ]
23
23
  },
24
24
  "../../node_modules/@codemirror/lang-go/dist/index.js": {
25
- "file": "assets/dist-BpfysUin.js",
25
+ "file": "assets/dist-C3o_MAP2.js",
26
26
  "name": "dist",
27
27
  "src": "../../node_modules/@codemirror/lang-go/dist/index.js",
28
28
  "isDynamicEntry": true,
@@ -33,7 +33,7 @@
33
33
  ]
34
34
  },
35
35
  "../../node_modules/@codemirror/lang-html/dist/index.js": {
36
- "file": "assets/dist-xLBkmO57.js",
36
+ "file": "assets/dist-CSu9t8Od.js",
37
37
  "name": "dist",
38
38
  "src": "../../node_modules/@codemirror/lang-html/dist/index.js",
39
39
  "isDynamicEntry": true,
@@ -41,7 +41,7 @@
41
41
  "_dist-DTWmF6Zy.js",
42
42
  "_dist-IkQ96Etc.js",
43
43
  "_dist-RJnNnBqa.js",
44
- "_dist-D2xI7N8L.js"
44
+ "_dist-CTA0zpmX.js"
45
45
  ]
46
46
  },
47
47
  "../../node_modules/@codemirror/lang-java/dist/index.js": {
@@ -55,7 +55,7 @@
55
55
  ]
56
56
  },
57
57
  "../../node_modules/@codemirror/lang-jinja/dist/index.js": {
58
- "file": "assets/dist-B88A-0-q.js",
58
+ "file": "assets/dist-CUO62CW5.js",
59
59
  "name": "dist",
60
60
  "src": "../../node_modules/@codemirror/lang-jinja/dist/index.js",
61
61
  "isDynamicEntry": true,
@@ -87,7 +87,7 @@
87
87
  ]
88
88
  },
89
89
  "../../node_modules/@codemirror/lang-liquid/dist/index.js": {
90
- "file": "assets/dist-BSEV8UWP.js",
90
+ "file": "assets/dist-Cf6teL6k.js",
91
91
  "name": "dist",
92
92
  "src": "../../node_modules/@codemirror/lang-liquid/dist/index.js",
93
93
  "isDynamicEntry": true,
@@ -98,7 +98,7 @@
98
98
  ]
99
99
  },
100
100
  "../../node_modules/@codemirror/lang-markdown/dist/index.js": {
101
- "file": "assets/dist-l9rzcKKN.js",
101
+ "file": "assets/dist-BeuVYjPU.js",
102
102
  "name": "dist",
103
103
  "src": "../../node_modules/@codemirror/lang-markdown/dist/index.js",
104
104
  "isDynamicEntry": true,
@@ -109,7 +109,7 @@
109
109
  ]
110
110
  },
111
111
  "../../node_modules/@codemirror/lang-php/dist/index.js": {
112
- "file": "assets/dist-DEGJW0Al.js",
112
+ "file": "assets/dist-2vnWdv_G.js",
113
113
  "name": "dist",
114
114
  "src": "../../node_modules/@codemirror/lang-php/dist/index.js",
115
115
  "isDynamicEntry": true,
@@ -120,7 +120,7 @@
120
120
  ]
121
121
  },
122
122
  "../../node_modules/@codemirror/lang-python/dist/index.js": {
123
- "file": "assets/dist-CjWP7qLx.js",
123
+ "file": "assets/dist-CdLT51Xs.js",
124
124
  "name": "dist",
125
125
  "src": "../../node_modules/@codemirror/lang-python/dist/index.js",
126
126
  "isDynamicEntry": true,
@@ -152,7 +152,7 @@
152
152
  ]
153
153
  },
154
154
  "../../node_modules/@codemirror/lang-sql/dist/index.js": {
155
- "file": "assets/dist-BFaxoH5a.js",
155
+ "file": "assets/dist-D2PpQCGI.js",
156
156
  "name": "dist",
157
157
  "src": "../../node_modules/@codemirror/lang-sql/dist/index.js",
158
158
  "isDynamicEntry": true,
@@ -163,14 +163,14 @@
163
163
  ]
164
164
  },
165
165
  "../../node_modules/@codemirror/lang-vue/dist/index.js": {
166
- "file": "assets/dist-B-bd7VCM.js",
166
+ "file": "assets/dist-DjovY3po.js",
167
167
  "name": "dist",
168
168
  "src": "../../node_modules/@codemirror/lang-vue/dist/index.js",
169
169
  "isDynamicEntry": true,
170
170
  "imports": [
171
171
  "_dist-IkQ96Etc.js",
172
172
  "../../node_modules/@codemirror/lang-html/dist/index.js",
173
- "_dist-D2xI7N8L.js",
173
+ "_dist-CTA0zpmX.js",
174
174
  "_dist-DTWmF6Zy.js"
175
175
  ]
176
176
  },
@@ -907,14 +907,14 @@
907
907
  "isDynamicEntry": true
908
908
  },
909
909
  "../../node_modules/@shikijs/langs/dist/http.mjs": {
910
- "file": "assets/http-DokH81pJ.js",
910
+ "file": "assets/http-TSVA7THf.js",
911
911
  "name": "http",
912
912
  "src": "../../node_modules/@shikijs/langs/dist/http.mjs",
913
913
  "isDynamicEntry": true,
914
914
  "imports": [
915
915
  "ui/shared/primitives/markdown/MarkdownText.tsx",
916
916
  "_xml-BOIvddFt.js",
917
- "_graphql-a_9GNzod.js"
917
+ "_graphql-B8opAFBz.js"
918
918
  ]
919
919
  },
920
920
  "../../node_modules/@shikijs/langs/dist/ini.mjs": {
@@ -1001,7 +1001,7 @@
1001
1001
  ]
1002
1002
  },
1003
1003
  "../../node_modules/@shikijs/langs/dist/php.mjs": {
1004
- "file": "assets/php-BYAot5gz.js",
1004
+ "file": "assets/php-DsbOr8xg.js",
1005
1005
  "name": "php",
1006
1006
  "src": "../../node_modules/@shikijs/langs/dist/php.mjs",
1007
1007
  "isDynamicEntry": true,
@@ -1033,7 +1033,7 @@
1033
1033
  "isDynamicEntry": true
1034
1034
  },
1035
1035
  "../../node_modules/@shikijs/langs/dist/rst.mjs": {
1036
- "file": "assets/rst-CUsouaiW.js",
1036
+ "file": "assets/rst-DjHKhQNY.js",
1037
1037
  "name": "rst",
1038
1038
  "src": "../../node_modules/@shikijs/langs/dist/rst.mjs",
1039
1039
  "isDynamicEntry": true,
@@ -1049,7 +1049,7 @@
1049
1049
  ]
1050
1050
  },
1051
1051
  "../../node_modules/@shikijs/langs/dist/ruby.mjs": {
1052
- "file": "assets/ruby-eGmSFUio.js",
1052
+ "file": "assets/ruby-Csf2IhZx.js",
1053
1053
  "name": "ruby",
1054
1054
  "src": "../../node_modules/@shikijs/langs/dist/ruby.mjs",
1055
1055
  "isDynamicEntry": true,
@@ -1059,7 +1059,7 @@
1059
1059
  "_css-TMM_5IvK.js",
1060
1060
  "_xml-BOIvddFt.js",
1061
1061
  "_sql-r_e_QA5-.js",
1062
- "_graphql-a_9GNzod.js",
1062
+ "_graphql-B8opAFBz.js",
1063
1063
  "../../node_modules/@shikijs/langs/dist/cpp.mjs",
1064
1064
  "_c-vzw8O3dF.js",
1065
1065
  "ui/shared/primitives/markdown/MarkdownText.tsx",
@@ -1089,7 +1089,7 @@
1089
1089
  ]
1090
1090
  },
1091
1091
  "../../node_modules/@shikijs/langs/dist/svelte.mjs": {
1092
- "file": "assets/svelte-CEoWEKJ2.js",
1092
+ "file": "assets/svelte-CsknkYPO.js",
1093
1093
  "name": "svelte",
1094
1094
  "src": "../../node_modules/@shikijs/langs/dist/svelte.mjs",
1095
1095
  "isDynamicEntry": true,
@@ -1130,7 +1130,7 @@
1130
1130
  "isDynamicEntry": true
1131
1131
  },
1132
1132
  "../../node_modules/@shikijs/langs/dist/vue.mjs": {
1133
- "file": "assets/vue-SlhNqE3a.js",
1133
+ "file": "assets/vue-laIDtfXB.js",
1134
1134
  "name": "vue",
1135
1135
  "src": "../../node_modules/@shikijs/langs/dist/vue.mjs",
1136
1136
  "isDynamicEntry": true,
@@ -1385,7 +1385,7 @@
1385
1385
  "src": "../../node_modules/katex/dist/fonts/KaTeX_Typewriter-Regular.woff2"
1386
1386
  },
1387
1387
  "../../src/host/client/app.tsx": {
1388
- "file": "assets/app-DwYC983k.js",
1388
+ "file": "assets/app-DPpdQGWp.js",
1389
1389
  "name": "app",
1390
1390
  "src": "../../src/host/client/app.tsx",
1391
1391
  "isDynamicEntry": true,
@@ -1417,7 +1417,7 @@
1417
1417
  ]
1418
1418
  },
1419
1419
  "../../src/plugins/builtin/files/client/code-editor.ts": {
1420
- "file": "assets/code-editor-Njczr4Aq.js",
1420
+ "file": "assets/code-editor-3HWVxL8r.js",
1421
1421
  "name": "code-editor",
1422
1422
  "src": "../../src/plugins/builtin/files/client/code-editor.ts",
1423
1423
  "isDynamicEntry": true,
@@ -1434,7 +1434,7 @@
1434
1434
  "../../node_modules/@codemirror/lang-go/dist/index.js",
1435
1435
  "../../node_modules/@codemirror/lang-html/dist/index.js",
1436
1436
  "../../node_modules/@codemirror/lang-java/dist/index.js",
1437
- "_dist-D2xI7N8L.js",
1437
+ "_dist-CTA0zpmX.js",
1438
1438
  "../../node_modules/@codemirror/lang-jinja/dist/index.js",
1439
1439
  "../../node_modules/@codemirror/lang-json/dist/index.js",
1440
1440
  "../../node_modules/@codemirror/lang-less/dist/index.js",
@@ -1546,7 +1546,7 @@
1546
1546
  ]
1547
1547
  },
1548
1548
  "../../src/plugins/builtin/files/client/plugin.tsx": {
1549
- "file": "assets/plugin-BGIBdp5R.js",
1549
+ "file": "assets/plugin-cl5toiff.js",
1550
1550
  "name": "plugin",
1551
1551
  "src": "../../src/plugins/builtin/files/client/plugin.tsx",
1552
1552
  "isDynamicEntry": true,
@@ -1564,7 +1564,7 @@
1564
1564
  ]
1565
1565
  },
1566
1566
  "../../src/plugins/builtin/git/client/plugin.tsx": {
1567
- "file": "assets/plugin-BZPaYR4m.js",
1567
+ "file": "assets/plugin-Cmwhxdvh.js",
1568
1568
  "name": "plugin",
1569
1569
  "src": "../../src/plugins/builtin/git/client/plugin.tsx",
1570
1570
  "isDynamicEntry": true,
@@ -1582,7 +1582,7 @@
1582
1582
  ]
1583
1583
  },
1584
1584
  "../../src/plugins/builtin/terminal/client/plugin.tsx": {
1585
- "file": "assets/plugin-AWio_je_.js",
1585
+ "file": "assets/plugin-C3GBA35u.js",
1586
1586
  "name": "plugin",
1587
1587
  "src": "../../src/plugins/builtin/terminal/client/plugin.tsx",
1588
1588
  "isDynamicEntry": true,
@@ -1635,8 +1635,8 @@
1635
1635
  "_rolldown-runtime-CgmABjMJ.js"
1636
1636
  ]
1637
1637
  },
1638
- "_dist-D2xI7N8L.js": {
1639
- "file": "assets/dist-D2xI7N8L.js",
1638
+ "_dist-CTA0zpmX.js": {
1639
+ "file": "assets/dist-CTA0zpmX.js",
1640
1640
  "name": "dist",
1641
1641
  "imports": [
1642
1642
  "_rolldown-runtime-CgmABjMJ.js",
@@ -1665,8 +1665,8 @@
1665
1665
  "_dist-IkQ96Etc.js"
1666
1666
  ]
1667
1667
  },
1668
- "_graphql-a_9GNzod.js": {
1669
- "file": "assets/graphql-a_9GNzod.js",
1668
+ "_graphql-B8opAFBz.js": {
1669
+ "file": "assets/graphql-B8opAFBz.js",
1670
1670
  "name": "graphql",
1671
1671
  "imports": [
1672
1672
  "_rolldown-runtime-CgmABjMJ.js",
@@ -1766,7 +1766,7 @@
1766
1766
  ]
1767
1767
  },
1768
1768
  "ui/shared/primitives/markdown/MarkdownText.tsx": {
1769
- "file": "assets/MarkdownText-DF8BJV5i.js",
1769
+ "file": "assets/MarkdownText-5A28xefP.js",
1770
1770
  "name": "MarkdownText",
1771
1771
  "src": "ui/shared/primitives/markdown/MarkdownText.tsx",
1772
1772
  "isDynamicEntry": true,
@@ -1827,7 +1827,7 @@
1827
1827
  "../../node_modules/@shikijs/langs/dist/perl.mjs",
1828
1828
  "../../node_modules/@shikijs/langs/dist/verilog.mjs",
1829
1829
  "../../node_modules/@shikijs/langs/dist/system-verilog.mjs",
1830
- "_graphql-a_9GNzod.js",
1830
+ "_graphql-B8opAFBz.js",
1831
1831
  "../../node_modules/@shikijs/langs/dist/proto.mjs",
1832
1832
  "../../node_modules/@shikijs/langs/dist/hcl.mjs",
1833
1833
  "../../node_modules/@shikijs/langs/dist/nix.mjs",