pi-webapp 0.1.31 → 0.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/extension.js +28 -28
- package/dist/hosted-recovery.js +2 -2
- package/dist/hosted-worker.js +2 -2
- package/docs/hosted-host-versions.md +44 -0
- package/package.json +2 -2
- package/web/dist/assets/app.js +3 -3
package/dist/hosted-recovery.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="1cdc12a6-b808-46ff-9738-9ce130403211",r._sentryDebugIdIdentifier="sentry-dbid-1cdc12a6-b808-46ff-9738-9ce130403211")}catch{}})();import{resolve as Se}from"node:path";import{lstat as Z,readdir as _e,rename as ee}from"node:fs/promises";import{join as k}from"node:path";import{createHash as se}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=r=>r.code==="ENOENT";var qe={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var h=r=>se("sha256").update(r).digest("hex");import{constants as M}from"node:fs";import{lstat as ae,mkdir as ce,open as q,rename as le,unlink as z}from"node:fs/promises";import{dirname as fe,join as de}from"node:path";import{randomUUID as ue}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";async function S(r){await ce(r,{recursive:!0,mode:448});let e=await ae(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function w(r,e){let t;try{t=await q(r,M.O_RDONLY|M.O_NONBLOCK|(M.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let s=Buffer.alloc(Math.min(n.size+1,e+1)),i=0;for(;i<s.length;){let a=await t.read(s,i,s.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==n.size)throw new o("invalid_storage","Storage record changed during read");return s.subarray(0,i)}finally{await t.close()}}async function x(r,e=2*1024*1024){let t=await w(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 b(r){let e=await w(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 m(r,e){let t=`${r}.${ue()}.tmp`,n=await q(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await le(t,r);let s;try{s=await q(fe(r),"r"),await s.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await s?.close()}}finally{await z(t).catch(()=>{})}}async function P(r,e,t=2e3){await S(r);let n=de(r,"transaction.lock"),s=Date.now()+t,i;for(;;)try{i=await q(n,"wx",384);break}catch(a){if(a.code!=="EEXIST")throw a;if(Date.now()>=s)throw new o("storage_busy","Plugin storage is locked; stop all writers before recovering an abandoned lock");await pe(10)}try{return await i.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),await e()}finally{await i.close(),await z(n)}}import{lstat as C,mkdir as he,open as B,realpath as K,readdir as F,link as ge,rename as we,unlink as _,copyFile as me,rm as ye}from"node:fs/promises";import{dirname as ve,isAbsolute as V,join as d,relative as X,resolve as be,sep as J,win32 as ke}from"node:path";import{randomUUID as W}from"node:crypto";var j=192*1024*1024,A=512*1024,Q=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Ie(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function Y(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function N(r){if(r&&(!Q(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 H=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,s){this.root=d(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(d(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(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");N(t.next),N(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 i=t.before;if(n==="committed"&&i&&i.stateRef!==e.stateRef&&await m(d(this.root,"previous.json"),i),n==="committed"){let a=await b(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(d(this.root,"fork.json"))}return await _(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return P(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let s=await b(d(this.root,"fork.json"));if(s&&(s.version!==1||s.stateRef!==t.stateRef||Object.keys(s).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 i=N({...t,generation:e+1,operationId:W()});await S(d(this.root,"states")),await S(d(this.root,"states",i.stateRef)),await m(d(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(d(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==i.stateRef&&await m(d(this.root,"previous.json"),n),await _(d(this.root,"transition.json")),await _(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return P(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=W(),s=d(this.root,"states",n);if(await b(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 m(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=d(this.root,"states",t.stateRef);for(let a of await F(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await w(d(i,a),j))throw new o("invalid_storage","Missing state file");await me(d(i,a),d(s,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return P(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(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=N(await b(d(this.root,"previous.json")));if(!t&&await w(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 s=[t,n].filter(l=>!!l),i=d(this.root,"states");await S(i);let a=await F(i),c=new Set(s.map(l=>l.stateRef));for(let l of a){if(!Q(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(i,l),p=await C(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await F(u)){let y=await C(d(u,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!y.isFile()||y.isSymbolicLink()||y.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let v=await x(d(u,g),j);if(!v)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let I=v;if(Object.keys(I).some($=>!["requestId","inputHash","nextHash","committed"].includes($))||I.committed!==!0||!/^[a-f0-9]{64}$/.test(I.inputHash)||!/^[a-f0-9]{64}$/.test(I.nextHash)||typeof I.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(v).some(I=>!["revision","schema","value","requestId","inputHash"].includes(I)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}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(s);for(let l of a)c.has(l)||await ye(d(i,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n){return d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let s=Ie(n);return P(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await x(this.statePath(i,e,Y(s.key)),j);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,Y(s.key));if(!Number.isSafeInteger(s.expectedRevision)||s.expectedRevision<0||s.schema!==i.schema||!Object.hasOwn(s,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(s.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(s);if(Buffer.byteLength(c)>j)throw new o("state_too_large","Plugin state exceeds limit");let f=await x(a,j);f&&this.validateState(f);let l=h(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==s.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:s.expectedRevision+1,schema:i.schema,value:s.value,requestId:e.requestId,inputHash:l};return await m(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,s.path),c=s.maxBytes===void 0?A:s.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>A)throw new o("invalid_input","Invalid workspace read limit");let f=await w(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:h(f)}:null}case"workspace.commit":return this.commitFile(i,e,s);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")||V(t)||ke.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let s=await K(e),i=be(s,t),a=X(s,i);if(!a||a===".."||a.startsWith(`..${J}`)||V(a))throw new o("invalid_path","Workspace path escapes root");let c=s,f=a.split(J);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<f.length-1){if(!n||X(s,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await he(c,{mode:448})}catch(y){if(y.code!=="EEXIST")throw y}p=await C(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 K(ve(i));if(l!==s&&!l.startsWith(s+J))throw new o("invalid_path","Workspace directory changed");return{target:i,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>A||!(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:s,parent:i}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),f=h(n.text),l=await x(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 B(`${s}.lock`,"wx",384)}catch(g){throw g.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):g}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let g=await w(s,A),y=g?h(g):null;if(l&&y===f)return{hash:f};if(l?.committed||y!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(i,`.plugin-${W()}.tmp`);let v=await B(p,"wx",384);try{await v.writeFile(n.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==i)throw new o("file_conflict","Workspace directory changed during save");let $=await w(s,A);if(($?h($):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ge(p,s)}catch(G){throw G.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):G}await _(p),p=void 0}else await we(p,s),p=void 0;return await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await _(p).catch(()=>{}),await u.close(),await _(`${s}.lock`)}}};var U="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function T(r){let e=[];async function t(n,s=""){let i=await Z(n);if(!i.isDirectory()||i.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await _e(n)).sort()){let c=k(n,a),f=s+a,l=await Z(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 w(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:h(u)})}}}return await t(r),{fingerprint:h(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 te(r,e,t,n){let s=new H(r,e),i=await T(s.root);if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return s.recover()}async function ne(r,e,t,n){let s=new H(r,e),i=s.root;if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await T(i);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await w(k(i,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await b(k(i,"fork.json")),f=await s.active(),l=await b(k(i,"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 ee(k(i,"fork.json"),k(i,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function re(r,e,t){if(t!==U||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await T(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let s=n.files.filter(i=>["runtime.lock","transaction.lock"].includes(i.path));for(let i of s){let a=`recovered-${e}-${i.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let i of s)await ee(k(r,i.path),k(r,`recovered-${e}-${i.path}.json`));return await m(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:s,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:s.map(i=>i.path),fingerprint:e}}var[R,ie,E,O,D,...xe]=process.argv.slice(2),Pe=ie&&!xe.length&&(R==="inspect"&&!E&&!O&&!D||R==="recover-locks"&&E&&O&&!D||["recover-fork","reconcile-transition"].includes(R??"")&&E&&O&&D);if(!Pe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
|
|
1
|
+
(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="09680f36-9ad0-4c70-932c-9b22c5b09fdf",r._sentryDebugIdIdentifier="sentry-dbid-09680f36-9ad0-4c70-932c-9b22c5b09fdf")}catch{}})();import{resolve as Se}from"node:path";import{lstat as Z,readdir as _e,rename as ee}from"node:fs/promises";import{join as k}from"node:path";import{createHash as se}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=r=>r.code==="ENOENT";var qe={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var h=r=>se("sha256").update(r).digest("hex");import{constants as M}from"node:fs";import{lstat as ae,mkdir as ce,open as q,rename as le,unlink as z}from"node:fs/promises";import{dirname as fe,join as de}from"node:path";import{randomUUID as ue}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";async function S(r){await ce(r,{recursive:!0,mode:448});let e=await ae(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function w(r,e){let t;try{t=await q(r,M.O_RDONLY|M.O_NONBLOCK|(M.O_NOFOLLOW??0))}catch(n){if(L(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let s=Buffer.alloc(Math.min(n.size+1,e+1)),i=0;for(;i<s.length;){let a=await t.read(s,i,s.length-i,i);if(!a.bytesRead)break;i+=a.bytesRead}if(i>e||i!==n.size)throw new o("invalid_storage","Storage record changed during read");return s.subarray(0,i)}finally{await t.close()}}async function x(r,e=2*1024*1024){let t=await w(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 b(r){let e=await w(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 m(r,e){let t=`${r}.${ue()}.tmp`,n=await q(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await le(t,r);let s;try{s=await q(fe(r),"r"),await s.sync()}catch(i){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(i.code??""))throw i}finally{await s?.close()}}finally{await z(t).catch(()=>{})}}async function P(r,e,t=2e3){await S(r);let n=de(r,"transaction.lock"),s=Date.now()+t,i;for(;;)try{i=await q(n,"wx",384);break}catch(a){if(a.code!=="EEXIST")throw a;if(Date.now()>=s)throw new o("storage_busy","Plugin storage is locked; stop all writers before recovering an abandoned lock");await pe(10)}try{return await i.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),await e()}finally{await i.close(),await z(n)}}import{lstat as C,mkdir as he,open as B,realpath as K,readdir as F,link as ge,rename as we,unlink as _,copyFile as me,rm as ye}from"node:fs/promises";import{dirname as ve,isAbsolute as V,join as d,relative as X,resolve as be,sep as J,win32 as ke}from"node:path";import{randomUUID as W}from"node:crypto";var j=192*1024*1024,A=512*1024,Q=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Ie(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function Y(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function N(r){if(r&&(!Q(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 H=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,s){this.root=d(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(d(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(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");N(t.next),N(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 i=t.before;if(n==="committed"&&i&&i.stateRef!==e.stateRef&&await m(d(this.root,"previous.json"),i),n==="committed"){let a=await b(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(d(this.root,"fork.json"))}return await _(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return P(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let s=await b(d(this.root,"fork.json"));if(s&&(s.version!==1||s.stateRef!==t.stateRef||Object.keys(s).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 i=N({...t,generation:e+1,operationId:W()});await S(d(this.root,"states")),await S(d(this.root,"states",i.stateRef)),await m(d(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(d(this.root,"active.json"),i)}catch(a){if((await this.active())?.operationId!==i.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==i.stateRef&&await m(d(this.root,"previous.json"),n),await _(d(this.root,"transition.json")),await _(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),i})}async forkState(e){return P(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=W(),s=d(this.root,"states",n);if(await b(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 m(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=d(this.root,"states",t.stateRef);for(let a of await F(i)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await w(d(i,a),j))throw new o("invalid_storage","Missing state file");await me(d(i,a),d(s,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return P(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await w(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=N(await b(d(this.root,"previous.json")));if(!t&&await w(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 s=[t,n].filter(l=>!!l),i=d(this.root,"states");await S(i);let a=await F(i),c=new Set(s.map(l=>l.stateRef));for(let l of a){if(!Q(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(i,l),p=await C(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await F(u)){let y=await C(d(u,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!y.isFile()||y.isSymbolicLink()||y.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let v=await x(d(u,g),j);if(!v)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let I=v;if(Object.keys(I).some($=>!["requestId","inputHash","nextHash","committed"].includes($))||I.committed!==!0||!/^[a-f0-9]{64}$/.test(I.inputHash)||!/^[a-f0-9]{64}$/.test(I.nextHash)||typeof I.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(v).some(I=>!["revision","schema","value","requestId","inputHash"].includes(I)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}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(s);for(let l of a)c.has(l)||await ye(d(i,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n){return d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let s=Ie(n);return P(this.root,async()=>{let i=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await x(this.statePath(i,e,Y(s.key)),j);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(i,e,Y(s.key));if(!Number.isSafeInteger(s.expectedRevision)||s.expectedRevision<0||s.schema!==i.schema||!Object.hasOwn(s,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(s.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(s);if(Buffer.byteLength(c)>j)throw new o("state_too_large","Plugin state exceeds limit");let f=await x(a,j);f&&this.validateState(f);let l=h(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==s.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:s.expectedRevision+1,schema:i.schema,value:s.value,requestId:e.requestId,inputHash:l};return await m(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,s.path),c=s.maxBytes===void 0?A:s.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>A)throw new o("invalid_input","Invalid workspace read limit");let f=await w(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:h(f)}:null}case"workspace.commit":return this.commitFile(i,e,s);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")||V(t)||ke.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let s=await K(e),i=be(s,t),a=X(s,i);if(!a||a===".."||a.startsWith(`..${J}`)||V(a))throw new o("invalid_path","Workspace path escapes root");let c=s,f=a.split(J);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<f.length-1){if(!n||X(s,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await he(c,{mode:448})}catch(y){if(y.code!=="EEXIST")throw y}p=await C(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 K(ve(i));if(l!==s&&!l.startsWith(s+J))throw new o("invalid_path","Workspace directory changed");return{target:i,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>A||!(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:s,parent:i}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),f=h(n.text),l=await x(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 B(`${s}.lock`,"wx",384)}catch(g){throw g.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):g}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let g=await w(s,A),y=g?h(g):null;if(l&&y===f)return{hash:f};if(l?.committed||y!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(i,`.plugin-${W()}.tmp`);let v=await B(p,"wx",384);try{await v.writeFile(n.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==i)throw new o("file_conflict","Workspace directory changed during save");let $=await w(s,A);if(($?h($):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ge(p,s)}catch(G){throw G.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):G}await _(p),p=void 0}else await we(p,s),p=void 0;return await m(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await _(p).catch(()=>{}),await u.close(),await _(`${s}.lock`)}}};var U="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function T(r){let e=[];async function t(n,s=""){let i=await Z(n);if(!i.isDirectory()||i.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await _e(n)).sort()){let c=k(n,a),f=s+a,l=await Z(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 w(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:h(u)})}}}return await t(r),{fingerprint:h(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 te(r,e,t,n){let s=new H(r,e),i=await T(s.root);if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(i.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return s.recover()}async function ne(r,e,t,n){let s=new H(r,e),i=s.root;if(n!==U)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await T(i);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await w(k(i,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await b(k(i,"fork.json")),f=await s.active(),l=await b(k(i,"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 ee(k(i,"fork.json"),k(i,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function re(r,e,t){if(t!==U||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await T(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let s=n.files.filter(i=>["runtime.lock","transaction.lock"].includes(i.path));for(let i of s){let a=`recovered-${e}-${i.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let i of s)await ee(k(r,i.path),k(r,`recovered-${e}-${i.path}.json`));return await m(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:s,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:s.map(i=>i.path),fingerprint:e}}var[R,ie,E,O,D,...xe]=process.argv.slice(2),Pe=ie&&!xe.length&&(R==="inspect"&&!E&&!O&&!D||R==="recover-locks"&&E&&O&&!D||["recover-fork","reconcile-transition"].includes(R??"")&&E&&O&&D);if(!Pe)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
|
|
2
2
|
inspect BROKER_ROOT
|
|
3
3
|
recover-locks BROKER_ROOT FINGERPRINT CONFIRMATION
|
|
4
4
|
reconcile-transition DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
|
|
5
5
|
recover-fork DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
|
|
6
6
|
CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=Se(ie),e=R==="inspect"?await T(r):R==="recover-locks"?await re(r,E,O):R==="recover-fork"?await ne(r,E,O,D):await te(r,E,O,D);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var ft=void 0;export{ft as default};
|
|
7
7
|
|
|
8
|
-
//# debugId=
|
|
8
|
+
//# debugId=09680f36-9ad0-4c70-932c-9b22c5b09fdf
|
package/dist/hosted-worker.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="
|
|
1
|
+
(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="50a09ade-ddba-4562-834f-f6d1da310ec8",t._sentryDebugIdIdentifier="sentry-dbid-50a09ade-ddba-4562-834f-f6d1da310ec8")}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 d=l.getStore();if(!d)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 u=`b${++v}`;return new Promise((m,w)=>{s.set(u,{resolve:m,reject:w}),a({type:"broker-request",id:u,invocationId:d.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=50a09ade-ddba-4562-834f-f6d1da310ec8
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Hosted plugin host versions
|
|
2
|
+
|
|
3
|
+
The host supports exact stable `x.y.z` and `x.y.z-alpha.N` identities. Core
|
|
4
|
+
components and the alpha sequence must be non-negative safe integers without
|
|
5
|
+
leading zeroes. Other channels, build metadata, prefixes and malformed versions
|
|
6
|
+
fail closed. Plugin package versions remain stable-only.
|
|
7
|
+
|
|
8
|
+
Never strip the alpha suffix: startup markers, diagnostics and paired updates
|
|
9
|
+
must preserve the exact package version.
|
|
10
|
+
|
|
11
|
+
## Consolidated compatibility policy
|
|
12
|
+
|
|
13
|
+
The former prerelease-host branch and the main implementation differed on whether
|
|
14
|
+
an alpha host must require a same-core alpha comparator in every matching range.
|
|
15
|
+
The consolidated implementation keeps main's existing behavior, so already
|
|
16
|
+
published official plugins remain usable on compatible alpha hosts. It also
|
|
17
|
+
retains the alternate branch's explicit alpha comparator support and rejects
|
|
18
|
+
unsafe numeric alpha identities.
|
|
19
|
+
|
|
20
|
+
- Bounded comparator, `^`, `~` and `||` ranges accept stable or exact alpha targets.
|
|
21
|
+
- Unknown syntax and wildcards fail the entire range, including another OR branch.
|
|
22
|
+
- Full prerelease precedence applies: `0.1.31-alpha.5 < 0.1.31`.
|
|
23
|
+
- `0.1.31-alpha.5` matches `>=0.1.0 <1.0.0` and
|
|
24
|
+
`>=0.1.31-alpha.0 <0.1.31`, but not `>=0.1.31` or
|
|
25
|
+
`>=0.1.31-alpha.6`.
|
|
26
|
+
- Caret/tilde upper bounds exclude the next boundary's prereleases.
|
|
27
|
+
- No additional same-core prerelease opt-in restriction is imposed. This is the
|
|
28
|
+
host's bounded compatibility policy, not npm's complete range grammar.
|
|
29
|
+
- SHA-512 archive validation, immutable code, resource checks, busy/unknown
|
|
30
|
+
lifecycle fencing and exact paired-update identities remain unchanged.
|
|
31
|
+
|
|
32
|
+
## Release regression
|
|
33
|
+
|
|
34
|
+
`node scripts/test-release-host.mjs` copies the source into a disposable directory,
|
|
35
|
+
shares installed dependencies, rewrites the copy's version to `0.1.31-alpha.5`,
|
|
36
|
+
builds, then runs launcher/session/bootstrap and installation compatibility tests.
|
|
37
|
+
It neither publishes nor mutates the original checkout. CI also retains its real
|
|
38
|
+
alpha-identity bootstrap preflight; release artifacts are built/tested after
|
|
39
|
+
version selection.
|
|
40
|
+
|
|
41
|
+
The original failure happened before hosted startup: the installer rejected the
|
|
42
|
+
alpha package version synchronously during extension factory initialization.
|
|
43
|
+
Missing `host-version.json` was a secondary symptom. Regression tests check actual
|
|
44
|
+
package identity, not a hard-coded source version.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-webapp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.32",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"piWebappDesktopProtocol": 1,
|
|
6
6
|
"piWebappDataVersion": 1,
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"pi-webapp": "./bin/pi-webapp.mjs"
|
|
30
30
|
},
|
|
31
31
|
"pi": {
|
|
32
|
-
"image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.
|
|
32
|
+
"image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.32/assets/cover-webapp.png",
|
|
33
33
|
"extensions": [
|
|
34
34
|
"./dist/extension.js"
|
|
35
35
|
]
|
package/web/dist/assets/app.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/app-CkT84si6.js","assets/app.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="
|
|
2
|
+
var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8fe625d0-c681-4b97-aed0-5f6f55e208ff",e._sentryDebugIdIdentifier="sentry-dbid-8fe625d0-c681-4b97-aed0-5f6f55e208ff")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();const B="modulepreload",D=function(e){return"/"+e},I={},A=function(t,i,r){let s=Promise.resolve();if(i&&i.length>0){let a=function(o){return Promise.all(o.map(l=>Promise.resolve(l).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),m=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));s=a(i.map(o=>{if(o=D(o),o in I)return;I[o]=!0;const l=o.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${g}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":B,l||(u.as="script"),u.crossOrigin="",u.href=o,m&&u.setAttribute("nonce",m),document.head.appendChild(u),l)return new Promise((T,N)=>{u.addEventListener("load",T),u.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})},j=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),q=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ee={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},R=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level"]),U=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function te(e){return e==="/api/message"||e==="/api/prompt-queue"||e.startsWith("/api/provider/")||e.startsWith("/api/workspace/files/")||e.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(e)}function p(e){return e.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function h(e){const t={};for(const i of R){const r=e[i];i==="toolName"?typeof r=="string"&&(j.has(r)||r==="custom")&&(t[i]=r):i==="failureKind"?q.has(r)&&(t[i]=r):i==="level"?(r==="warning"||r==="error")&&(t[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(t[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(t[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(t[i]=r):i==="route"&&typeof r=="string"?t[i]=U.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?t[i]=r.split("/").map(p).join("/"):typeof r=="string"?t[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:p(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(t[i]=r)}return t}function v(e){var r;const t=e.replace(/\\/g,"/").split(/[?#]/)[0];return t.startsWith("node:")?t.slice(0,150):`app:///${(((r=t.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/))==null?void 0:r[1])??t.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function S(e,t=0){const i=e instanceof Error?e:new Error(typeof e=="string"?e:"Non-Error rejection"),r=new Error(p(i.message));if(r.name=p(i.name).slice(0,100),i.stack){const s=i.stack.split(`
|
|
3
3
|
`).slice(1,31).map(n=>{const a=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${p(n.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:p(n)});r.stack=`${r.name}: ${r.message}
|
|
4
4
|
${s.join(`
|
|
5
5
|
`)}`}else r.stack=void 0;return t<3&&i.cause!==void 0&&(r.cause=S(i.cause,t+1)),r}function re(e,t){const i=new Error(t);return e instanceof Error&&(i.name=e.name,e.stack&&(i.stack=`${i.name}: ${t}
|
|
6
6
|
${e.stack.split(`
|
|
7
7
|
`).slice(1).join(`
|
|
8
8
|
`)}`)),i}function F(e){return{...e.filename?{filename:v(e.filename)}:{},...e.abs_path?{abs_path:v(e.abs_path)}:{},...e.function?{function:p(e.function)}:{},lineno:e.lineno,colno:e.colno,in_app:e.in_app}}function K(e){var r,s,n,a,c,m;const t=h(((r=e.contexts)==null?void 0:r.diagnostic)??{}),i=C(t);return{event_id:e.event_id,timestamp:e.timestamp,platform:e.platform,level:e.level,release:e.release,dist:e.dist,environment:p(e.environment??"production"),...e.message?{message:p(e.message)}:{},exception:e.exception?{values:(s=e.exception.values)==null?void 0:s.slice(0,4).map(o=>{var l;return{type:p(o.type??"Error"),value:p(o.value??""),...o.stacktrace?{stacktrace:{frames:(l=o.stacktrace.frames)==null?void 0:l.slice(-30).map(F)}}:{},...o.mechanism?{mechanism:{type:o.mechanism.type,handled:o.mechanism.handled}}:{}}})}:void 0,tags:{side:(n=e.tags)==null?void 0:n.side,buildId:(a=e.tags)==null?void 0:a.buildId,...t.toolName?{toolName:t.toolName}:{},...t.failureKind?{failureKind:t.failureKind}:{},...t.errorCode?{errorCode:t.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:t},breadcrumbs:(c=e.breadcrumbs)==null?void 0:c.slice(-100).map(o=>({timestamp:o.timestamp,category:p(o.category??"app"),data:h(o.data??{})})),debug_meta:e.debug_meta?{images:(m=e.debug_meta.images)==null?void 0:m.slice(0,10).map(o=>({type:o.type,debug_id:o.debug_id,...o.code_file?{code_file:v(o.code_file)}:{}}))}:void 0}}function C(e){if(!(e.stage!=="tool"||e.originalStackAvailable!==!1||!e.toolName||!e.failureKind))return["pi-webapp-tool-result",String(e.toolName),String(e.toolId??"builtin"),String(e.failureKind),String(e.errorCode??"unknown")]}function ie(e,t){return t.attachments=[],K(e)}class Z{constructor(){d(this,"items",[]);d(this,"bytes",0);d(this,"encoder",new TextEncoder)}add(t,i={}){const r={timestamp:Date.now()/1e3,category:p(t),data:h(i)},s=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:s}),this.bytes+=s;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:t})=>t)}}class V{constructor(){d(this,"windowAt",-1);d(this,"total",0);d(this,"seen",new Map)}take(t,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);const r=this.seen.get(t);if(r&&i-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(t,{at:i,repeats:0}),{repeats:(r==null?void 0:r.repeats)??0}}}const W=new Set(["目录路径必须是绝对路径","父目录路径必须是绝对路径","文件夹名称无效","工作区目录不可用,请恢复目录或从列表移除后重新添加","会话已切换","Pi 正在运行,请等待当前回复结束","请等待当前回复结束","请等待当前回复结束再切换工作区","请等待当前回复结束再切换会话","请先切换到其他工作区","新会话已取消","已有登录正在进行","模型不可用","模型提供方未配置认证","当前模型不支持此推理强度","其他提供方的登录正在进行,请先完成或取消当前登录","当前会话没有暂停的任务","请先完成当前交互或审批","请先选择模型","请先连接当前模型","插件未启用","会话运行实例已切换","提供方已存在","文件超过 20 MB","请求内容过大","会话不属于该工作区","推理强度无效"]);function L(e){return e instanceof Error&&(e.name==="AbortError"||W.has(e.message))}class se{constructor(t,i,r,s,n=new Z){d(this,"budget",new V);d(this,"breadcrumbs");d(this,"scopeClass");d(this,"seen",new WeakSet);d(this,"state",{});d(this,"client");d(this,"side");d(this,"buildId");this.client=t,this.side=i,this.buildId=r,this.scopeClass=s.Scope,this.breadcrumbs=n,t.addIntegration(s.linkedErrorsIntegration({limit:4}))}setState(t){this.state=h(t)}capture(t,i={},r){var s;try{if(L(t))return;if(typeof t=="object"&&t!==null){if(this.seen.has(t))return;this.seen.add(t)}const n=S(t),a=h({...this.state,...i}),c=C(a),m=c?JSON.stringify(c):`${n.name}:${n.message}:${((s=n.stack)==null?void 0:s.split(`
|
|
9
|
-
`)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.
|
|
9
|
+
`)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.32+9db7470eeebb3b3dbb6a",J="9db7470eeebb3b3dbb6a";function Q(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}let f,z=!0,$=!1,P=!1,_=[];const E=new WeakSet,b=new Map;let y={};function k(e,t={}){try{if(L(e))return;if(typeof e=="object"&&e!==null){if(E.has(e))return;E.add(e)}if(f)return f.capture(e,t);z&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){f==null||f.breadcrumbs.add(e,t)}function ce(e){e.sessionId&&(b.has(e.sessionId)||(b.size>=32&&b.delete(b.keys().next().value),b.set(e.sessionId,Q())),e={...e,session:b.get(e.sessionId)}),y=h({...y,...e}),f==null||f.setState(y)}function G(){$||($=!0,P=new URL(location.href).searchParams.get("sentry_release_probe")==="1",window.addEventListener("error",e=>{e instanceof ErrorEvent?k(e.error??new Error(e.message),{stage:"global"}):(e.target instanceof HTMLScriptElement||e.target instanceof HTMLLinkElement)&&k(new Error("Application resource failed to load"),{stage:"resource"})},!0),window.addEventListener("unhandledrejection",e=>k(e.reason,{stage:"unhandled_rejection"})),X())}async function X(){var e;try{const t=M();if(!t)return;const i=await fetch("/api/telemetry/config",{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e3)});if(!i.ok)return;const r=await i.json();if(!r.enabled||!r.dsn)return;const{createBrowserReporter:s}=await A(async()=>{const{createBrowserReporter:a}=await import("./telemetry-client-CBQBug9X.js");return{createBrowserReporter:a}},[]);f=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";f.setState({...y,browser:n,platform:navigator.platform}),y={...y,browser:n,platform:navigator.platform};for(const a of _)f.capture(a.error,a.context);r.environment==="sentry-verification"&&P&&f.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],z=!1}}G();A(()=>import("./app-CkT84si6.js").then(e=>e.p),__vite__mapDeps([0,1])).catch(e=>k(e,{stage:"startup"}));export{se as E,A as _,Q as a,te as b,ae as c,M as d,ie as e,ne as f,oe as i,re as o,ee as p,k as r,ce as s};
|
|
10
10
|
|
|
11
|
-
//# debugId=
|
|
11
|
+
//# debugId=8fe625d0-c681-4b97-aed0-5f6f55e208ff
|