pi-webapp 0.1.36-alpha.1 → 0.1.36
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 +25 -25
- package/dist/hosted-recovery.js +3 -3
- package/dist/hosted-worker.js +2 -2
- package/docs/hosted-crash-safe-ownership.md +118 -0
- package/docs/hosted-ori54-uninstall.md +5 -0
- package/docs/hosted-update-recovery.md +8 -1
- package/package.json +3 -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]="5d9aa245-ed90-4d29-85b3-5b927a79bbef",r._sentryDebugIdIdentifier="sentry-dbid-5d9aa245-ed90-4d29-85b3-5b927a79bbef")}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 de,join as fe}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(de(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=fe(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 f,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=f(e,h(t)),this.pluginId=t,this.legacy=n,this.checkpoint=s}active(){return x(f(this.root,"active.json")).then(N)}async recover(){return P(this.root,async()=>{let e=await this.active(),t=await b(f(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(d=>a[d]===c[d]))(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(f(this.root,"previous.json"),i),n==="committed"){let a=await b(f(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await _(f(this.root,"fork.json"))}return await _(f(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(f(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(f(this.root,"states")),await S(f(this.root,"states",i.stateRef)),await m(f(this.root,"transition.json"),{version:1,before:n,next:i}),await this.checkpoint?.("prepared");try{await m(f(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(f(this.root,"previous.json"),n),await _(f(this.root,"transition.json")),await _(f(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=f(this.root,"states",n);if(await b(f(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(f(this.root,"fork.json"),{version:1,stateRef:n}),await S(s);let i=f(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(f(i,a),j))throw new o("invalid_storage","Missing state file");await me(f(i,a),f(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(f(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(f(this.root,"previous.json")));if(!t&&await w(f(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=f(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=f(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(f(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(f(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 d=await e(s);for(let l of a)c.has(l)||await ye(f(i,l),{recursive:!0,force:!0});return d})}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 f(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 d=await x(a,j);d&&this.validateState(d);let l=h(c);if(d?.requestId===e.requestId&&d.inputHash===l)return{revision:d.revision,schema:d.schema,value:d.value};if((d?.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 d=await w(a,c);return d?{text:new TextDecoder("utf-8",{fatal:!0}).decode(d),hash:h(d)}: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,d=a.split(J);for(let u=0;u<d.length;u++){c=f(c,d[u]);let p;try{p=await C(c)}catch(g){if(!L(g))throw g;if(u<d.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<d.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=f(this.root,"states",e.stateRef,`${h(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=h(JSON.stringify(n)),d=h(n.text),l=await x(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==d))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===d)return{hash:d};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:d,committed:!1}),p=f(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:d,committed:!0}),{hash:d}}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),d=s+a,l=await Z(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,d+"/");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:d,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")),d=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))||!d||l&&typeof l.stateRef!="string"||[d?.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]="ccd5233e-3350-4f2c-b4e6-a07c7edae6b7",r._sentryDebugIdIdentifier="sentry-dbid-ccd5233e-3350-4f2c-b4e6-a07c7edae6b7")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Oe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var L=r=>r.code==="ENOENT";var Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as A,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function S(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await A(r,J.O_RDONLY|J.O_NONBLOCK|(J.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 i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(r){let e=await g(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function b(r,e){let t=`${r}.${me()}.tmp`,n=await A(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await A(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await S(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await A(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await A(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as x,copyFile as _e,rm as xe}from"node:fs/promises";import{dirname as Se,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var N=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Pe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(t.next),T(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await x(d(this.root,"fork.json"))}return await x(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=T({...t,generation:e+1,operationId:G()});await S(d(this.root,"states")),await S(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await x(d(this.root,"transition.json")),await x(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await b(d(this.root,"fork.json"),{version:1,stateRef:n}),await S(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),N))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=T(await I(d(this.root,"previous.json")));if(!t&&await g(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,n].filter(l=>!!l),s=d(this.root,"states");await S(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),N);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(i);for(let l of a)c.has(l)||await xe(d(s,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n){return d(this.root,"states",e.stateRef,`${y(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 i=Pe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key)),N);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key));if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>N)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,N);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!L(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await Z(Se(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await x(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await x(p).catch(()=>{}),await u.close(),await x(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Oe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[P,le,O,j,q,...Ae]=process.argv.slice(2),Ne=le&&!Ae.length&&(P==="inspect"&&!O&&!j&&!q||P==="recover-locks"&&O&&j&&!q||["recover-fork","reconcile-transition"].includes(P??"")&&O&&j&&q);if(!Ne)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
|
-
CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=
|
|
6
|
+
CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=je(le),e=P==="inspect"?await $(r):P==="recover-locks"?await ce(r,O,j):P==="recover-fork"?await ae(r,O,j,q):await se(r,O,j,q);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var mt=void 0;export{mt as default};
|
|
7
7
|
|
|
8
|
-
//# debugId=
|
|
8
|
+
//# debugId=ccd5233e-3350-4f2c-b4e6-a07c7edae6b7
|
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]="9ecc9ca4-f436-4320-8b0b-df1efc3dfcd3",t._sentryDebugIdIdentifier="sentry-dbid-9ecc9ca4-f436-4320-8b0b-df1efc3dfcd3")}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};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=9ecc9ca4-f436-4320-8b0b-df1efc3dfcd3
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# ORI-54 follow-up: crash-safe ownership
|
|
2
|
+
|
|
3
|
+
Status: local validation complete; awaiting cross-platform PR checks and release.
|
|
4
|
+
Not yet published or applied to the user's storage.
|
|
5
|
+
|
|
6
|
+
## Why the first fix was insufficient
|
|
7
|
+
|
|
8
|
+
The previous stop receipt protects ordinary launcher shutdown: a rejected editor
|
|
9
|
+
flush must not close RPC input or claim a successful drain. It cannot protect a
|
|
10
|
+
host process killed independently of the launcher, or SIGKILL/power loss.
|
|
11
|
+
|
|
12
|
+
The old runtime and transaction mutexes used `open(path, "wx")` plus a JSON PID
|
|
13
|
+
record. Those files outlive their process. Refusing to steal an uncertain owner's
|
|
14
|
+
lock was correct, but every abnormal exit could permanently block the plugin,
|
|
15
|
+
then block the paired updater and consequently all management operations.
|
|
16
|
+
|
|
17
|
+
Observed local recurrence: the validated host (Pi PID 16260) exited on SIGTERM at
|
|
18
|
+
2026-10-27T23:36:36Z. Its runtime marker survived. Subsequent startup/paired update
|
|
19
|
+
reported `runtime_owned` then `host_pair_required`. The log does not establish who
|
|
20
|
+
sent the signal. This is not evidence of drawing corruption.
|
|
21
|
+
|
|
22
|
+
## Replacement mutex
|
|
23
|
+
|
|
24
|
+
Use Node's built-in `node:sqlite` (`DatabaseSync`, available in the existing Node
|
|
25
|
+
>=22.19 support range) to hold `BEGIN EXCLUSIVE` on a dedicated empty database for
|
|
26
|
+
each runtime/transaction lock. SQLite's OS byte-range locks release when the
|
|
27
|
+
connection or process closes, including SIGKILL. No PID probe, timeout lease,
|
|
28
|
+
heartbeat, pathname stealing, or extra npm/native addon is involved.
|
|
29
|
+
|
|
30
|
+
- `<name>.ownership.sqlite` is a stable inode. Never unlink, rename or replace it.
|
|
31
|
+
It contains no plugin data or application transaction; no plugin snapshot is
|
|
32
|
+
stored in SQLite. Never set journal mode to WAL or reuse these connections for
|
|
33
|
+
other queries.
|
|
34
|
+
- `<name>.lock` contains the exact v2 compatibility marker. Old O_EXCL code cannot
|
|
35
|
+
enter while it exists. New code first acquires kernel custody, then creates the
|
|
36
|
+
marker exclusively, or reuses an existing **exact v2** marker under that custody.
|
|
37
|
+
- Normal release removes only its own marker **before** closing kernel custody,
|
|
38
|
+
after all application work/drain has finished. Thus old hosts can still acquire
|
|
39
|
+
storage after a clean stop. No abandoned pathname is deleted during acquisition.
|
|
40
|
+
- A legacy owner can win initial O_EXCL creation; the new host then refuses and
|
|
41
|
+
releases kernel custody without touching the legacy record. Live v2 contenders
|
|
42
|
+
fail/wait on the kernel lock, including contenders in the same process.
|
|
43
|
+
- Unknown, malformed, empty, legacy live-PID and legacy dead-PID markers all refuse
|
|
44
|
+
online migration. Legacy offline recovery/verified backup remains required.
|
|
45
|
+
- Transactions yield between busy retries; synchronous SQLite waiting must not
|
|
46
|
+
block the owner's JS event loop. A process-local custody set suppresses native
|
|
47
|
+
lock attempts against a known local holder: Windows native lock retries can
|
|
48
|
+
otherwise stall the releasing JS event loop even with SQLite busy timeout zero.
|
|
49
|
+
This set grants no ownership; every acquisition still requires SQLite custody,
|
|
50
|
+
and path aliases/independent processes are checked by SQLite. Local timeouts
|
|
51
|
+
close only the waiting connection, never clear the holder's set entry.
|
|
52
|
+
Contention timeouts never permit takeover.
|
|
53
|
+
- Activation, fork, workspace-file and pairing journals retain their existing
|
|
54
|
+
validation and CAS semantics. Kernel mutex availability is not proof that an
|
|
55
|
+
interrupted application transaction committed or that a journal may be deleted.
|
|
56
|
+
- The legacy offline recovery tool skips v2 markers and never touches SQLite lock
|
|
57
|
+
inodes. A clean release removes v2 markers itself.
|
|
58
|
+
|
|
59
|
+
Use local filesystems only, with one stable storage namespace and working SQLite
|
|
60
|
+
locking. Network/shared filesystems with uncertain locking and external deletion
|
|
61
|
+
of ownership databases are not supported. Same-user malicious filesystem mutation
|
|
62
|
+
is not an isolation boundary. Power-loss durability and every filesystem/platform
|
|
63
|
+
remain separate certification concerns; no broad certification is claimed here.
|
|
64
|
+
|
|
65
|
+
## Compatibility and deployment
|
|
66
|
+
|
|
67
|
+
Host metadata now declares `piWebappHostedRuntime.ownershipProtocol: 2`.
|
|
68
|
+
New paired selection rejects candidate hosts lacking that support before writing
|
|
69
|
+
selection intent, rather than updating back into the known crash-deadlock design.
|
|
70
|
+
The outer hosted protocol remains 2 so existing hosts can stage the new package.
|
|
71
|
+
|
|
72
|
+
An existing legacy marker is **not** made safe by installing this code. Its first
|
|
73
|
+
repair still requires new scoped downtime permission, all owners externally
|
|
74
|
+
stopped, full verified storage/workspace backup, fingerprint-bound legacy lock
|
|
75
|
+
quarantine, and restart with one owner. Preserve pair journals and current state;
|
|
76
|
+
never roll back to an older snapshot to bypass this gate. The previous one-time
|
|
77
|
+
recovery permission is not reused for a second incident.
|
|
78
|
+
|
|
79
|
+
## Verification scope
|
|
80
|
+
|
|
81
|
+
- `test/hosted-ownership.test.ts`: real subprocess SIGTERM/SIGKILL for runtime and
|
|
82
|
+
transaction custody; live independent-process and same-process exclusion;
|
|
83
|
+
unchanged application state/journal bytes; legacy/partial/unknown lock refusal;
|
|
84
|
+
event-loop-safe transaction contention; deterministic partial-marker race;
|
|
85
|
+
symlink/hardlink rejection. `test/hosted-update-recovery.test.ts` verifies legacy
|
|
86
|
+
offline recovery skips v2 fences.
|
|
87
|
+
- `test/hosted-launcher-stop.test.ts`: real Pi RPC, failed-flush stop refusal;
|
|
88
|
+
abnormal Pi exit, cold start, activation of a staged newer package and actual
|
|
89
|
+
uninstall; manually edited persistent drawing value/revision retained. The
|
|
90
|
+
staged archive test does not claim real-registry update coverage.
|
|
91
|
+
- `test/hosted-pair-update.test.ts`: process exit during selection reconciles the
|
|
92
|
+
same validated pair without offline lock deletion; downgrade capability gate.
|
|
93
|
+
- Existing paired HTTP updater, state/generation CAS, refusal and browser suites
|
|
94
|
+
remain necessary. Native Linux/Windows and minimum-Node checks remain release
|
|
95
|
+
gates, not claims inferred from macOS tests.
|
|
96
|
+
|
|
97
|
+
Local results (macOS): `check` and `build` passed. Integrity-pinned published
|
|
98
|
+
fixtures enabled: core Node suite **465 passed, 1 Windows-only skipped**; desktop
|
|
99
|
+
suite **94 passed**. The combined command hit the harness's 240s wall time after
|
|
100
|
+
core completed, so desktop was run separately to completion. Browser production
|
|
101
|
+
archive lifecycle at desktop/mobile sizes plus Chinese/English retained-lock
|
|
102
|
+
regressions: **4 passed**. Pure ownership suite on the actual bundled desktop
|
|
103
|
+
Node 22.23.3: **8 passed**. CI now requires Node 22.19.0 on Linux and includes the
|
|
104
|
+
pure custody tests in both macOS/Windows smoke checks before publishing.
|
|
105
|
+
|
|
106
|
+
Windows CI follow-up: the initial 30-way contention test still timed out after
|
|
107
|
+
its isolated budget was raised to 10s. Do not classify that as merely runner
|
|
108
|
+
slowness. The local retry suppression above removes redundant native attempts;
|
|
109
|
+
the strengthened test again uses the unchanged **2s production budget**, counts
|
|
110
|
+
exactly 30 native acquisitions, checks timed-out local waiters preserve independent
|
|
111
|
+
process exclusion, and settles all callers before cleanup. On macOS the preceding
|
|
112
|
+
implementation fails this new assertion (541 native attempts versus 30), while
|
|
113
|
+
the fix passes all 8 ownership tests and TypeScript checks. Native Windows CI
|
|
114
|
+
must still confirm the fix before release.
|
|
115
|
+
|
|
116
|
+
Old-source control: the real-RPC SIGKILL regression was run against the preceding
|
|
117
|
+
ORI-54 fix (`d21ac8b`) in an isolated source tree. Cold start produced `disabled`
|
|
118
|
+
instead of `active`, reproducing the underlying design failure.
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Runtime ownership, unavailable editor and uninstall (ORI-54)
|
|
2
2
|
|
|
3
|
+
> Follow-up: this first fix covers orderly shutdown, not independent process
|
|
4
|
+
> termination. The recurrence and replacement kernel mutex are documented in
|
|
5
|
+
> [crash-safe ownership](hosted-crash-safe-ownership.md). Do not treat successful
|
|
6
|
+
> normal-stop verification as certification against abnormal host exits.
|
|
7
|
+
|
|
3
8
|
## Cause
|
|
4
9
|
|
|
5
10
|
The reported `runtime_owned` error is not an archive/uninstall error. The
|
|
@@ -36,7 +36,14 @@ distinct. See [ORI-42 evidence and reproduction](hosted-ori42-management.md).
|
|
|
36
36
|
|
|
37
37
|
## Offline operator recovery — no automatic stealing
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
The [ORI-54 crash-safe ownership follow-up](hosted-crash-safe-ownership.md)
|
|
40
|
+
introduces kernel-managed v2 mutexes. Exact v2 markers are reused only under
|
|
41
|
+
SQLite exclusive custody; neither their abandoned pathname nor their stable
|
|
42
|
+
`*.ownership.sqlite` inode is removed by startup or this recovery tool. Normal
|
|
43
|
+
owners remove their own marker on release. The following recovery procedure is
|
|
44
|
+
still required for **legacy or unknown** markers; upgrading never reclaims them.
|
|
45
|
+
|
|
46
|
+
Legacy `runtime.lock` and `transaction.lock` are never removed by startup, PID inference,
|
|
40
47
|
heartbeat timeout, UI or an HTTP endpoint. The utility below is **offline only**.
|
|
41
48
|
Its confirmation is an operator attestation, not an OS-enforced proof of dead
|
|
42
49
|
ownership. Filesystem rename is NOT an online compare-and-swap primitive.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-webapp",
|
|
3
|
-
"version": "0.1.36
|
|
3
|
+
"version": "0.1.36",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"piWebappDesktopProtocol": 1,
|
|
6
6
|
"piWebappDataVersion": 1,
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
"protocol": 2,
|
|
9
9
|
"runtimeProtocol": 1,
|
|
10
10
|
"pairJournal": 1,
|
|
11
|
+
"ownershipProtocol": 2,
|
|
11
12
|
"capabilities": [
|
|
12
13
|
"state",
|
|
13
14
|
"workspace",
|
|
@@ -29,7 +30,7 @@
|
|
|
29
30
|
"pi-webapp": "./bin/pi-webapp.mjs"
|
|
30
31
|
},
|
|
31
32
|
"pi": {
|
|
32
|
-
"image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.36
|
|
33
|
+
"image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.36/assets/cover-webapp.png",
|
|
33
34
|
"extensions": [
|
|
34
35
|
"./dist/extension.js"
|
|
35
36
|
]
|
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-L5x3gcS_.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]="b0842c75-f6a6-480a-960b-6122414d1386",e._sentryDebugIdIdentifier="sentry-dbid-b0842c75-f6a6-480a-960b-6122414d1386")}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 f=document.createElement("link");if(f.rel=l?"stylesheet":B,l||(f.as="script"),f.crossOrigin="",f.href=o,m&&f.setAttribute("nonce",m),document.head.appendChild(f),l)return new Promise((T,N)=>{f.addEventListener("load",T),f.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.36
|
|
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.36+be8a0f322ec18f6f45ab",J="be8a0f322ec18f6f45ab";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 u,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(u)return u.capture(e,t);z&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){u==null||u.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}),u==null||u.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}},[]);u=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";u.setState({...y,browser:n,platform:navigator.platform}),y={...y,browser:n,platform:navigator.platform};for(const a of _)u.capture(a.error,a.context);r.environment==="sentry-verification"&&P&&u.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],z=!1}}G();A(()=>import("./app-L5x3gcS_.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=b0842c75-f6a6-480a-960b-6122414d1386
|