@popmelt.com/core 0.38.1 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +4 -3
  2. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  3. package/codex-plugin/.codex-plugin/plugin.json +1 -1
  4. package/dist/{ExploreAttachment-IIEORQP3.mjs → ExploreAttachment-OA2PUTNR.mjs} +1 -1
  5. package/dist/PagePreviewLayer-HKADULHD.mjs +1 -0
  6. package/dist/ParticipantRuntime-IU2STHIT.mjs +1 -0
  7. package/dist/PhoneHostGate-CS3KFCP5.mjs +1 -0
  8. package/dist/PopmeltTasteConnectedPane-TRQCY5SM.mjs +1 -0
  9. package/dist/{SamplePlacementOverlay-EOJW6XGE.mjs → SamplePlacementOverlay-SNA4WB6Z.mjs} +1 -1
  10. package/dist/ShareProjectPane-QLHMNZNU.mjs +1 -0
  11. package/dist/SuppliedContext-SFOM3R3K.mjs +1 -0
  12. package/dist/{ThreadErrorCard-CTMVMETS.mjs → ThreadErrorCard-NJUVLWMU.mjs} +1 -1
  13. package/dist/ThreadPanel-RVCNMX7B.mjs +1 -0
  14. package/dist/adapter-react-three-fiber.mjs +1 -1
  15. package/dist/adapter-three.d.mts +9 -8
  16. package/dist/adapter-three.mjs +3 -3
  17. package/dist/bridge-entry.mjs +1 -1
  18. package/dist/{bridgeSSEStream-HUFNXYPG.mjs → bridgeSSEStream-2KKFO64A.mjs} +1 -1
  19. package/dist/{bridgeWebSocketStream-AS22Y2FP.mjs → bridgeWebSocketStream-XTHQPBPI.mjs} +1 -1
  20. package/dist/browser-runtime-BUC4RUD7.mjs +1 -0
  21. package/dist/browser.mjs +1 -1
  22. package/dist/canvas-chat-note-XMVKWL2J.mjs +1 -0
  23. package/dist/{checkFixture-UNTXJKRN.mjs → checkFixture-I2ALOQTM.mjs} +1 -1
  24. package/dist/chunk-4B6HUJCH.mjs +1 -0
  25. package/dist/{chunk-BJUSVIDN.mjs → chunk-4LN72RDZ.mjs} +1 -1
  26. package/dist/{chunk-3VOEPWRL.mjs → chunk-5TCWBNV4.mjs} +1 -1
  27. package/dist/chunk-742KV4YS.mjs +1 -0
  28. package/dist/{chunk-WJVRGXOS.mjs → chunk-7D4BUDKG.mjs} +1 -1
  29. package/dist/chunk-ADOCYY5I.mjs +1 -0
  30. package/dist/chunk-B4RLDY5H.mjs +1 -0
  31. package/dist/chunk-B4ZKGIGU.mjs +1 -0
  32. package/dist/{chunk-ZHXTB5IN.mjs → chunk-BDUWFDBP.mjs} +1 -1
  33. package/dist/chunk-CHK24QU5.mjs +1 -0
  34. package/dist/{chunk-TCGXG7UA.mjs → chunk-CPFVBR6Q.mjs} +1 -1
  35. package/dist/{chunk-GTVTUWGH.mjs → chunk-D3BHAI37.mjs} +1 -1
  36. package/dist/chunk-DKBVNKIG.mjs +24 -0
  37. package/dist/chunk-EOAWCUFT.mjs +1 -0
  38. package/dist/{chunk-QXFBFKN6.mjs → chunk-EWTZVC7E.mjs} +1 -1
  39. package/dist/{chunk-2WQXHUEQ.mjs → chunk-FD6IIFJC.mjs} +1 -1
  40. package/dist/{chunk-TEXVTTWA.mjs → chunk-FPSR4NAR.mjs} +1 -1
  41. package/dist/{chunk-KHDXOXYF.mjs → chunk-G6ITTTFD.mjs} +1 -1
  42. package/dist/chunk-H4GG2RS4.mjs +1 -0
  43. package/dist/chunk-HM6EBJVO.mjs +1 -0
  44. package/dist/chunk-HOWDQUPT.mjs +1 -0
  45. package/dist/{chunk-XJJDBMZI.mjs → chunk-HQVWOBYH.mjs} +1 -1
  46. package/dist/chunk-IWF42SDV.mjs +1 -0
  47. package/dist/{chunk-GLF7Z5IR.mjs → chunk-K22VZV3V.mjs} +1 -1
  48. package/dist/chunk-K2OUXYDM.mjs +1 -0
  49. package/dist/chunk-KOHR4LAQ.mjs +1 -0
  50. package/dist/chunk-KY4YVZ3O.mjs +1 -0
  51. package/dist/chunk-LLVF422C.mjs +1 -0
  52. package/dist/chunk-LSKP5UC6.mjs +1 -0
  53. package/dist/{chunk-F3VZQGPM.mjs → chunk-LUTP7QBD.mjs} +1 -1
  54. package/dist/chunk-ML7YV4RV.mjs +1 -0
  55. package/dist/{chunk-TXL2CR66.mjs → chunk-MLNC5TMP.mjs} +1 -1
  56. package/dist/chunk-MSWRCFPJ.mjs +1 -0
  57. package/dist/chunk-NC7YXD7Q.mjs +1 -0
  58. package/dist/{chunk-BEGAJYOY.mjs → chunk-OEJXPUAR.mjs} +1 -1
  59. package/dist/{chunk-43BZCDGL.mjs → chunk-OL7RDZ2R.mjs} +1 -1
  60. package/dist/{chunk-N3MHDOMU.mjs → chunk-P3IOAIYB.mjs} +1 -1
  61. package/dist/chunk-PQKSXNIZ.mjs +1 -0
  62. package/dist/{chunk-AEC67LMY.mjs → chunk-QDFQPABM.mjs} +1 -1
  63. package/dist/chunk-RALP6ENI.mjs +30 -0
  64. package/dist/chunk-RRB5IHBT.mjs +1 -0
  65. package/dist/{chunk-UOK5LOPJ.mjs → chunk-UFUH63SR.mjs} +1 -1
  66. package/dist/chunk-UIADZXVT.mjs +1 -0
  67. package/dist/{chunk-JAMYVQFC.mjs → chunk-V56MNQLF.mjs} +1 -1
  68. package/dist/{chunk-5F34UIKL.mjs → chunk-VWFST2IX.mjs} +1 -1
  69. package/dist/{chunk-FQLIJAUB.mjs → chunk-W5JUAOLA.mjs} +1 -1
  70. package/dist/cli.mjs +1 -1
  71. package/dist/codex-note-context-4ORRY4CH.mjs +1 -0
  72. package/dist/codex-project-LMAR3FMS.mjs +1 -0
  73. package/dist/{codex-store-mount-WJAATWHT.mjs → codex-store-mount-MNIL3VK6.mjs} +1 -1
  74. package/dist/dev-server-ZLT7TAUF.mjs +1 -0
  75. package/dist/guest-admission.mjs +1 -1
  76. package/dist/guest-live-canvas.mjs +1 -1
  77. package/dist/{index-CHp2bgs1.d.mts → index-D6bSXWNT.d.mts} +1 -1
  78. package/dist/index.mjs +1 -1
  79. package/dist/memory-legacy.d.mts +1 -1
  80. package/dist/memory-legacy.mjs +1 -1
  81. package/dist/memory-store.d.mts +84 -84
  82. package/dist/memory-store.mjs +1 -1
  83. package/dist/{page-interaction-TV3P6B3X.mjs → page-interaction-GC2UN47Y.mjs} +1 -1
  84. package/dist/{page-planes-2ZepTpen.d.mts → page-planes-9GVbnVZa.d.mts} +240 -1
  85. package/dist/peer-client-XNTMFSOV.mjs +1 -0
  86. package/dist/plugin-astro.d.mts +1 -1
  87. package/dist/plugin-astro.mjs +1 -1
  88. package/dist/plugin-nuxt.mjs +1 -1
  89. package/dist/plugin-vite.d.mts +1 -1
  90. package/dist/plugin-vite.mjs +1 -1
  91. package/dist/server.d.mts +4 -2
  92. package/dist/server.mjs +1 -1
  93. package/dist/shared-page-JN7T4DDQ.mjs +1 -0
  94. package/infra/phone-pairing/README.md +25 -0
  95. package/infra/phone-pairing/binding.mjs +105 -0
  96. package/infra/phone-pairing/machine-config.mjs +134 -0
  97. package/infra/phone-pairing/machine-service.mjs +159 -0
  98. package/infra/phone-pairing/machine.mjs +98 -0
  99. package/infra/phone-pairing/managed-install.mjs +179 -0
  100. package/package.json +42 -25
  101. package/dist/PagePreviewLayer-AFSRCBAX.mjs +0 -1
  102. package/dist/ParticipantRuntime-ZNEFG34O.mjs +0 -1
  103. package/dist/PhoneHostGate-OCIMKPLM.mjs +0 -1
  104. package/dist/PopmeltTasteConnectedPane-N2A5XPRO.mjs +0 -1
  105. package/dist/ShareProjectPane-VYWTF3FW.mjs +0 -1
  106. package/dist/SuppliedContext-3S4HT6U6.mjs +0 -1
  107. package/dist/ThreadPanel-G7OKSWD4.mjs +0 -1
  108. package/dist/browser-runtime-Q26JF5EA.mjs +0 -1
  109. package/dist/canvas-chat-note-OLVVP55Y.mjs +0 -1
  110. package/dist/chunk-2IWVTTYX.mjs +0 -1
  111. package/dist/chunk-3OGSLX4V.mjs +0 -1
  112. package/dist/chunk-A4GARXVQ.mjs +0 -1
  113. package/dist/chunk-AGCS65LT.mjs +0 -1
  114. package/dist/chunk-AYZUOBFI.mjs +0 -1
  115. package/dist/chunk-BOZVNUHJ.mjs +0 -1
  116. package/dist/chunk-DBCBG5J6.mjs +0 -1
  117. package/dist/chunk-EFWBHWHP.mjs +0 -1
  118. package/dist/chunk-FYURSPM3.mjs +0 -1
  119. package/dist/chunk-G6BN5TAZ.mjs +0 -1
  120. package/dist/chunk-IW7V7WNL.mjs +0 -1
  121. package/dist/chunk-JJK4LAN6.mjs +0 -1
  122. package/dist/chunk-JJRKR4X3.mjs +0 -1
  123. package/dist/chunk-KF73S7MG.mjs +0 -1
  124. package/dist/chunk-KL5ODVJA.mjs +0 -1
  125. package/dist/chunk-L356S4EY.mjs +0 -1
  126. package/dist/chunk-OZBMHEOD.mjs +0 -1
  127. package/dist/chunk-P2WAXWAZ.mjs +0 -1
  128. package/dist/chunk-PRPXMDZ7.mjs +0 -1
  129. package/dist/chunk-QQPUMPKU.mjs +0 -1
  130. package/dist/chunk-TSQEBZYO.mjs +0 -1
  131. package/dist/chunk-UTP56NCY.mjs +0 -1
  132. package/dist/chunk-VG4ZV2OT.mjs +0 -30
  133. package/dist/chunk-WC7B5NU3.mjs +0 -24
  134. package/dist/chunk-X6I6KQDG.mjs +0 -1
  135. package/dist/codex-note-context-4X7I5AIJ.mjs +0 -1
  136. package/dist/codex-project-Q6YT5P37.mjs +0 -1
  137. package/dist/dev-server-NROXLQKM.mjs +0 -1
  138. package/dist/peer-client-DWC5F6JN.mjs +0 -1
  139. package/dist/shared-page-GO76UP7I.mjs +0 -1
  140. /package/dist/{chunk-L45FX4SU.mjs → chunk-CZJILD7T.mjs} +0 -0
@@ -1 +1 @@
1
- import{a as e}from"./chunk-JJK4LAN6.mjs";import{a as t}from"./chunk-CIKFUS7J.mjs";import{existsSync as r}from"fs";import{realpath as o}from"fs/promises";import{join as a}from"path";import{createRequire as i}from"module";import{pathToFileURL as n}from"url";async function s(e){return await(import(n(i(a(e,"package.json")).resolve("vite")).href))}function m(i,n){if(!r(a(i,"index.html"))||"custom"===n?.config.appType)return;let m,p=!1,c=()=>{m=void 0};return n?.watcher?.on("all",c),n?.httpServer?.once("close",()=>{n?.watcher?.off("all",c)}),async({url:r,document:a,projectId:l})=>{if(!n&&a&&!p&&c(),!m){p=!0;let t=(async()=>{let t=await s(i);return e(t.build,await o(i),"/")})();m=t,t.then(()=>{p=!1},()=>{p=!1,m===t&&c()})}let u;try{u=decodeURIComponent(r.pathname.slice(1))}catch{return}if(/[\\%]/.test(u)||u.split("/").some(e=>e.startsWith(".")||"node_modules"===e))return;let f=await(await m)(u,a,{version:1,projectId:l,url:r.origin+t,revision:"unversioned"});return f?new Response(Buffer.from(f.body),{headers:{"Content-Type":f.type}}):void 0}}export{s as a,m as b};
1
+ import{a as e}from"./chunk-LLVF422C.mjs";import{a as t}from"./chunk-CIKFUS7J.mjs";import{existsSync as r}from"fs";import{realpath as o}from"fs/promises";import{join as a}from"path";import{createRequire as i}from"module";import{pathToFileURL as n}from"url";async function s(e){return await(import(n(i(a(e,"package.json")).resolve("vite")).href))}function m(i,n){if(!r(a(i,"index.html"))||"custom"===n?.config.appType)return;let m,p=!1,c=()=>{m=void 0};return n?.watcher?.on("all",c),n?.httpServer?.once("close",()=>{n?.watcher?.off("all",c)}),async({url:r,document:a,projectId:l})=>{if(!n&&a&&!p&&c(),!m){p=!0;let t=(async()=>{let t=await s(i);return e(t.build,await o(i),"/")})();m=t,t.then(()=>{p=!1},()=>{p=!1,m===t&&c()})}let u;try{u=decodeURIComponent(r.pathname.slice(1))}catch{return}if(/[\\%]/.test(u)||u.split("/").some(e=>e.startsWith(".")||"node_modules"===e))return;let f=await(await m)(u,a,{version:1,projectId:l,url:r.origin+t,revision:"unversioned"});return f?new Response(Buffer.from(f.body),{headers:{"Content-Type":f.type}}):void 0}}export{s as a,m as b};
@@ -0,0 +1 @@
1
+ "use client";import{b as e}from"./chunk-LSKP5UC6.mjs";import{b as t,f as r,g as n,j as i,h as o,l as a,c as l,a as s,d as c,q as p}from"./chunk-AWWUJO3N.mjs";import{c as d,b as u}from"./chunk-Q6N77LIS.mjs";import{o as h,m,a as f}from"./chunk-AOTDTBQO.mjs";import{v as g,m as y}from"./chunk-LH7HKUCK.mjs";import{c as b}from"./chunk-ZVDKW7TO.mjs";import{a as v}from"./chunk-7D4BUDKG.mjs";import{b as w}from"./chunk-OEJXPUAR.mjs";import{createContext as x,useState as k,useRef as S,useLayoutEffect as C,useContext as O,useMemo as E}from"react";import{createPortal as W}from"react-dom";import{jsx as P,Fragment as T,jsxs as M}from"react/jsx-runtime";var j=x({visible:!0,toggle:()=>{}});function A(e,t,r){let n=e.closest(".sp-card");if(!n)return;let i=e.closest(".sp-steer-frame")??e,o=Array.from(n.querySelectorAll(".sp-zoom-actions, .sp-actions, .tag-option, .pager")),a=()=>{let r=e.getBoundingClientRect();if(!r.width||!r.height)return;let a=e.clientWidth/r.width,l=e.clientHeight/r.height;t({compact:!n.closest(".sp-workspace"),viewport:{width:i.clientWidth,height:i.clientHeight},bounds:o.map(e=>{let t=e.getBoundingClientRect();return{left:(t.left-r.left)*a,right:(t.right-r.left)*a,top:(t.top-r.top)*l,bottom:(t.bottom-r.top)*l}})})},l=new ResizeObserver(a);l.observe(i),l.observe(n);for(let e of o)l.observe(e),e.addEventListener("pointermove",r,{passive:!0});return a(),()=>{l.disconnect();for(let e of o)e.removeEventListener("pointermove",r)}}function R(e,t){return e.computedStyleMap?.().get(t)?.toString()??("max-width"===t?getComputedStyle(e).maxWidth:f(e,t))}function I(e){let t=getComputedStyle(e).display,r=R(e,"width");return"inline"===t||t.startsWith("inline-")&&(!r||"auto"===r)||/^(fit-content|max-content|min-content)/.test(r??"")}function F(e,t){let r=h(e)??e,n=I(r);if(!n){let e=r instanceof HTMLElement?r.offsetWidth:r.getBoundingClientRect().width;if(e>0)return{width:e,intrinsic:n}}for(let e=y(r);e;e=y(e)){if(!e.clientWidth||I(e))continue;let r=getComputedStyle(e),n=e.clientWidth-(parseFloat(r.paddingLeft)||0)-(parseFloat(r.paddingRight)||0);n>0&&(t=Math.min(t,n));break}return{width:t,intrinsic:n}}function z(e,t){if(e){if(/^[\d.]+px$/.test(e))return parseFloat(e);if(/^[\d.]+%$/.test(e))return t*parseFloat(e)/100}}function N(e){let t=[];for(let r=e;r;r=y(r))t.unshift(r);return{boxes:t,measure:function(r=!1){let n=e.ownerDocument.documentElement.clientWidth;for(let i of t){let t=getComputedStyle(i);if("inline"===t.display||"contents"===t.display)continue;let o=(parseFloat(t.paddingLeft)||0)+(parseFloat(t.paddingRight)||0)+(parseFloat(t.borderLeftWidth)||0)+(parseFloat(t.borderRightWidth)||0),a="border-box"===t.boxSizing,l=z(R(i,"width"),n),s=z(R(i,"max-width"),n),c=void 0===l?n-o:l-(a?o:0);n=Math.max(0,Math.min(c,void 0===s?1/0:s-(a?o:0))),r&&i===e&&(n+=o)}return n}}}function L(e,t,r){let n={},i=e&&getComputedStyle(e);if(i)for(let e of c)n[e]=i.getPropertyValue(e);let o=d(),a=e=>{let{raisedSurface:t,primary:r}=v[e];return i&&o&&u(o(i.color,t),o(t,t))>=4.5?i.color:r};return{style:n,width:t,fonts:r,lightInk:a("light"),darkInk:a("dark")}}function D(e,t){let r=t.flatMap(e=>"fixture"in e?[e.fixture.bundle]:[]).join(","),[n,i]=k({}),o=S(new Map);return C(()=>{let e=o.current;return i({}),()=>{for(let t of e.values())t.abort();e.clear()}},[e]),C(()=>{let t=o.current;for(let n of r.split(",")){if(!/^[a-f0-9]{64}$/.test(n)||t.has(n))continue;let r=new AbortController;t.set(n,r),w(e+"/files/explore-"+n+".json",{signal:r.signal}).then(async e=>{if(409===e.status)return"The saved recipe could not reproduce the original preview with this checkout.";if(!e.ok)throw Error("This fixture bundle could not be loaded.");let t=await e.json();if("string"!=typeof t.script||"string"!=typeof t.css)throw Error("Invalid fixture bundle.");return t}).catch(()=>"This fixture bundle could not be loaded.").then(e=>{r.signal.aborted||i(t=>({...t,[n]:e}))})}},[e,r]),n}function B({frameKey:e,bundle:t,...r}){let[n,i]=k(null);if("string"==typeof t)return P("div",{className:"sp-steer-frame",role:"alert",children:t});let o=n&&n.key!==e?n:null,a=[];return o&&a.push(P(K,{...o.props,captureRef:void 0,presentation:"retiring"},o.key)),t&&a.push(P(K,{...r,bundle:t,presentation:n?.key===e?"current":"pending",onReady:()=>i({key:e,props:{...r,bundle:t}})},e)),a.length?P(T,{children:a}):P("div",{className:"sp-steer-frame",role:"status",children:"Loading preview…"})}function K(l){let s=b(),c=S(null),p=S(null),d=S(null),u=S(null),h=S(null),m=S({...l,feedbackOnly:s});m.current={...l,feedbackOnly:s};let{toggle:f}=O(j),y=S(f);y.current=f;let[v,w]=k(0),[x,W]=k(""),R=E(()=>{if(l.readOnly&&!l.frozenParent||location.pathname!==l.target.pathname)return null;if("component"===l.previewScope){let{component:e,element:r}=t(l.target);return e??r}return g(l.target.selector,l.target.element)},[l.target,l.previewScope,l.readOnly,l.frozenParent]),{mirror:I,fillScene:z,framing:D,capture:B,readOnly:K}=l,H=E(()=>({script:l.bundle.script,css:l.bundle.css}),[l.bundle.script,l.bundle.css]);C(()=>{c.current&&(c.current.inert="retiring"===l.presentation||"pending"===l.presentation)},[l.presentation]),C(()=>{let e=c.current;if(!v||!e?.contentWindow)return;let{port1:t,port2:l}=new MessageChannel;u.current=t;let s,f=m.current.initial,g=R&&N(R),b="",w=()=>{let e=L(R,g?.measure()??document.documentElement.clientWidth,b);if(B&&(e.width=B.width,e.style=B.style,e.lightInk=e.darkInk=B.style.color||"currentColor"),m.current.pageInk&&(e.lightInk=e.darkInk=m.current.pageInk),p.current){let t=s??{width:p.current.clientWidth,height:p.current.clientHeight};if(I){let r=R&&!z?F(R,g?.measure(!0)??e.width):null;e.slot=r?{width:r.width,height:t.height}:t,r&&(e.intrinsic=r.intrinsic)}else e.surface=B?{width:Math.min(B.viewport.width,t.width),height:Math.min(B.viewport.height,t.height)}:t,R&&Object.assign(e,F(R,e.width))}return e},x=!1,k=e=>{(x||!I)&&t.postMessage(e)},S=()=>k({type:"reference",reference:w(),theme:m.current.theme});h.current=S;let C=new ResizeObserver(e=>{let t=e.find(e=>e.target===p.current)?.contentRect;t&&(s={width:t.width,height:t.height}),S()});for(let e of g?.boxes??[])C.observe(e);p.current&&C.observe(p.current),C.observe(e.ownerDocument.documentElement);let O=!1,E=new AbortController,P=R?r(R,E.signal).then(e=>{!O&&e&&(b=e,S())}).catch(()=>{}):Promise.resolve(),T=I?void 0:A(e,e=>k({type:"controls",bounds:e}),()=>k({type:"controlEnter"})),M=e.closest(".sp-workspace"),j=["wheel","gesturestart","gesturechange","gestureend"],X=t=>{if(!D||"retiring"===m.current.presentation)return;let r=t;if("wheel"===r.type&&!r.ctrlKey&&1===D.getScale())return;t.preventDefault(),t.stopPropagation();let n=e.getBoundingClientRect();k({type:"framingGesture",event:r.type,clientX:r.clientX-n.left,clientY:r.clientY-n.top,deltaX:r.deltaX,deltaY:r.deltaY,deltaMode:r.deltaMode,ctrlKey:r.ctrlKey,scale:r.scale??1})};for(let e of j)M?.addEventListener(e,X,{capture:!0,passive:!1});let U=JSON.stringify(f),Y=!1,V=D?.subscribe(()=>{Y||k({type:"framing",view:D.snapshot()})}),$=0,J=!1,q=new Map,G=()=>new Promise((e,t)=>{if(!J||O)return void t(Error("The option is still loading. Try again in a moment."));let r=++$,n=setTimeout(()=>{q.delete(r),t(Error("The preview capture timed out. Please try again."))},8e3);q.set(r,{resolve:e,reject:t,timer:n}),k({type:"capture",id:r,background:m.current.captureBackground??"transparent"})}),Q=m.current.captureRef;Q&&(Q.current=G),t.onmessage=({data:e})=>{if(!O&&"retiring"!==m.current.presentation&&e&&"object"==typeof e)switch(e.type){case"capture":{let t=q.get(e.id);if(!t)break;q.delete(e.id),clearTimeout(t.timer),e.image instanceof Blob&&"image/png"===e.image.type&&e.image.size>0&&e.image.size<=8388608?t.resolve(e.image):t.reject(Error("Could not capture the reviewed option. Please try again."));break}case"edits":if(I||!Array.isArray(e.edits)||e.edits.length>512)return;try{let t=i(f,e.edits.map(e=>{if(!o(e.part,e.property))throw Error();return a({...e,batchId:"",option:0}),e})),r=JSON.stringify(t);U!==r&&(U=r,m.current.onChange?.(t))}catch{}break;case"framing":{let{view:t,fit:r}=e;if(!D||!Number.isFinite(r)||r<=0||r>1||!t||!(null===t.pageScale||Number.isFinite(t.pageScale)&&t.pageScale>0&&t.pageScale<=4)||!Number.isFinite(t.focusX)||!Number.isFinite(t.focusY))return;Y=!0,D.setFitScale(r),D.restore(t),Y=!1;break}case"tag":!I&&"string"==typeof e.part&&n.test(e.part)&&m.current.onTag?.(e.part,"string"==typeof e.label?e.label.slice(0,80):void 0);break;case"preview":m.current.onPreview?.(e.parts);break;case"escape":m.current.onEscape?.();break;case"toggle":I||y.current();break;case"canvas":"boolean"==typeof e.present&&m.current.onCanvas?.(e.present);break;case"ready":J=!0,m.current.onReady?.(),k({type:"interaction",selected:m.current.selected,feedbackOnly:m.current.feedbackOnly}),I&&k({type:"styles",parts:m.current.parts??{}});break;case"size":d.current&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&(d.current.style.height=Math.min(16384,Math.max(1,e.height))+"px",d.current.style.width=Math.min(16384,Math.max(1,e.width))+"px");break;case"error":m.current.onError?.(),I||m.current.onReady?.(),W(String(e.message).slice(0,300))}};let Z=()=>{O||!e.contentWindow||(x=!0,e.contentWindow.postMessage({bundle:H,initial:f,parts:I?m.current.parts:void 0,reference:w(),theme:m.current.theme,accent:m.current.accent,framing:D?.snapshot()??{pageScale:null,focusX:0,focusY:0},feedbackOnly:m.current.feedbackOnly,readOnly:K,mirror:!!I,fillScene:z},"*",[l]))};return I?P.then(Z):Z(),()=>{for(let e of j)M?.removeEventListener(e,X,!0);O=!0,T?.(),C.disconnect(),E.abort(),V?.(),u.current=null,h.current=null,t.close(),Q?.current===G&&(Q.current=null);for(let e of q.values())clearTimeout(e.timer),e.reject(Error("The preview changed before it could be captured. Try again."));q.clear(),m.current.onPreview?.(null)}},[v,H,R,I,z,D,B,K]),C(()=>{u.current?.postMessage({type:"interaction",selected:l.selected,feedbackOnly:s})},[l.selected,s]),C(()=>{u.current?.postMessage({type:"styles",parts:l.parts??{}})},[l.parts]),C(()=>{h.current?.()},[l.theme,l.pageInk]);let X=P("iframe",{ref:c,title:l.frozenParent?"Edited parent at iteration time":K?"Original at exploration time":I?"Explore page preview":"Edit or interact with this option",sandbox:"allow-scripts","aria-hidden":"retiring"===l.presentation||void 0,referrerPolicy:"no-referrer",srcDoc:e,style:{border:0,colorScheme:I?void 0:l.theme,display:"block",position:"absolute",top:B?"max(0px, calc(50% - "+B.viewport.height/2+"px))":0,left:B?"max(0px, calc(50% - "+B.viewport.width/2+"px))":0,width:B?.viewport.width??"100vw",height:B?.viewport.height??"100vh",maxWidth:"none",maxHeight:"none",opacity:"pending"===l.presentation?0:1},onLoad:()=>w(e=>e+1)});return M(T,{children:[M("span",{ref:p,className:I?void 0:"sp-steer-frame",style:{display:"block",overflow:"clip",...I?{position:"relative",minWidth:0,height:z?"100%":void 0}:{gridArea:"1 / 1"}},children:[I&&!z&&P("span",{ref:d,"aria-hidden":"true",style:{display:"block",maxWidth:"100%"}}),X]}),x&&P("span",{role:"alert",children:x})]})}function H(e){return Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),t]))}function X({node:e,picker:t,path:r=[],live:n}){let i="row"===e.kind||"column"===e.kind,o=r.join("."),a={display:"inline-flex",flexDirection:"column"===e.kind?"column":"row",alignItems:i&&"column"===e.kind?"flex-start":"center",gap:e.space??0,flexWrap:i&&"row"===e.kind?"inherit":void 0,maxWidth:"100%",boxSizing:"border-box",color:e.ink,background:e.fill,border:e.stroke?"1px solid "+e.stroke:void 0,borderRadius:e.radius,padding:e.px||e.py?String(e.py??0)+"px "+String(e.px??0)+"px":void 0,fontSize:e.size?e.size+"px":void 0,fontWeight:e.weight,...H(e.style),...H(n?.[o])},l=o+"/label",s=!i&&"text"!==e.kind;return M("span",{style:a,className:[t&&"sp-piece"].filter(Boolean).join(" ")||void 0,"data-sp-fill":t&&(e.fill||a.backgroundColor)?"":void 0,"data-sp-ink":t&&a.color?"":void 0,"data-scratch-text":"text"===e.kind||void 0,"data-popmelt-label":p(e),"data-scratch-part":o,tabIndex:t?-1:void 0,"data-badge-hover":t?.hovered===o||void 0,"data-tagged":t?.selected===o||void 0,children:[t&&P("button",{type:"button",className:"sp-piece-hit",onClick:()=>t.tag(o),"aria-label":`Tag ${e.kind}${e.label?": "+e.label:""}`,"aria-pressed":t.selected===o}),i?e.children?.map((e,i)=>P(X,{live:n,node:e,path:[...r,i],picker:t},i)):t&&s?P("button",{type:"button",className:"sp-label-hit","data-popmelt-label":p(e,"label"),"data-sp-fill":e.labelStyle?.["background-color"]?"":void 0,"data-sp-ink":e.labelStyle?.color?"":void 0,"data-scratch-text":"",style:H(e.labelStyle),"data-scratch-part":l,"data-badge-hover":t.hovered===l||void 0,"data-tagged":t.selected===l||void 0,onClick:()=>t.tag(l),"aria-label":"Tag text: "+e.label,"aria-pressed":t.selected===l,children:n?.[l]?.text??e.label}):s?P("span",{"data-popmelt-label":p(e,"label"),"data-scratch-part":l,style:{display:"inline-block",...H(e.labelStyle),...H(n?.[l])},children:n?.[l]?.text??e.label}):n?.[o]?.text??e.label]})}function U({element:e,scene:t,active:r,revealOnPage:n,children:i}){let[o,a]=k(null);return C(()=>{let r=e.ownerDocument,n=r.createElement("span");n.dataset.popmeltExploreCache="",n.setAttribute("inert","");let i=!t&&(e.hasAttribute("data-popmelt-explore-original")?h(e)??e:e),o=getComputedStyle(i||e);if(t)n.style.cssText="position:absolute;inset:0;display:block;overflow:hidden";else{if(n.style.display=o.display.startsWith("inline")?"inline-flex":"block","absolute"===o.position||"fixed"===o.position)for(let e of["position","top","right","bottom","left","z-index","transform","transform-origin"])n.style.setProperty(e,o.getPropertyValue(e));if("inline"!==o.display)for(let t of["width","max-width"]){let r=R(i||e,t);r&&n.style.setProperty(t,r)}for(let e of[...c,"align-self","grid-area","margin"])n.style.setProperty(e,o.getPropertyValue(e))}let l=n.style.cssText;n.style.visibility="hidden",t||(n.style.position="fixed",n.style.left="0",n.style.top="0",n.style.width=N(e).measure()+"px",n.style.height="0",n.style.overflow="clip");let s=r.createElement("style");return s.textContent="[data-popmelt-explore-original] { display: none !important; } [data-popmelt-explore-scene] > :not([data-popmelt-explore-preview]) { opacity: 0 !important; pointer-events: none !important; } [data-popmelt-explore-scene-position] { position: relative !important; }",t?(n.append(s),e.append(n)):e.before(s,n),a({host:n,style:l,position:"static"===o.position||e.hasAttribute("data-popmelt-explore-scene-position")}),()=>{n.remove(),s.remove()}},[e,t]),C(()=>{if(!o||!r)return;let{host:n,style:i,position:a}=o,l=n.style.cssText;n.style.cssText=i,n.dataset.popmeltExplorePreview="";let s=t?"data-popmelt-explore-scene":"data-popmelt-explore-original";t&&a&&e.setAttribute("data-popmelt-explore-scene-position",""),e.setAttribute(s,"");let c=m(e,n);return()=>{e.removeAttribute(s),t&&a&&e.removeAttribute("data-popmelt-explore-scene-position"),n.removeAttribute("data-popmelt-explore-preview"),n.style.cssText=l,c()}},[o,e,t,r]),C(()=>{if(!o||!r||!n)return;let e=requestAnimationFrame(()=>o.host.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"}));return()=>cancelAnimationFrame(e)},[o,r,n]),o&&W(i,o.host)}function Y({preview:e,active:r,onReady:n}){let{option:i,target:o,bundle:a,parts:c,theme:p,accentColor:d,hasCanvas:u,revealOnPage:h}=e,[m,f]=k(e.targets),[g,y]=k(null);C(()=>f(e.targets),[e.targets]);let b="fixture"in i?l(m,i.previewScope,u):m.element;if(C(()=>{let e=()=>{if(b?.isConnected)return;let e=t(o);(e.element!==m.element||e.component!==m.component||e.legacyScene!==m.legacyScene)&&f(e)},r=new MutationObserver(e);return r.observe(document,{subtree:!0,childList:!0}),e(),()=>r.disconnect()},[b,o,m]),C(()=>{!("fixture"in i)&&b?.isConnected&&n()},[i,b,n]),!b?.isConnected)return null;let v="fixture"in i&&(s(b)===b||(b===m.component||b===m.legacyScene)&&!!b.querySelector("canvas"));return P(U,{element:b,scene:v,active:r&&(!("fixture"in i)||g?.element===b&&g.scene===v),revealOnPage:h,children:"fixture"in i?a&&P(K,{mirror:!0,fillScene:v,bundle:a,target:o,previewScope:i.previewScope,theme:p,accent:d,initial:[],parts:c,onReady:()=>{y({element:b,scene:v}),n()}}):P(X,{node:i.root,live:c})})}function V({preview:e}){let t=e.index>=0?(e=>e.threadId+":"+e.batchId+":"+e.index+("fixture"in e.option?":"+e.option.fixture.bundle:""))(e):null,[r,n]=k([]),[i,o]=k(null),a=r.find(e=>e.key===t),l=e.enabled&&!e.suspended&&null!==t?a?.ready?t:i:null;return C(()=>{l!==i&&o(l)},[l,i]),C(()=>{!t||"fixture"in e.option&&!e.bundle||n(r=>{let n=r.find(e=>e.key===t),o=r.filter(e=>e.key!==t);for(;o.length>2;){let e=o.findIndex(e=>e.key!==i);o.splice(e,1)}return[...o,{key:t,preview:e,ready:n?.ready??!1}]})},[t,e,i]),P(T,{children:r.map(r=>P(Y,{preview:r.key===t?e:r.preview,active:e.enabled&&!e.suspended&&null!==t&&r.key===l,onReady:()=>n(e=>e.some(e=>e.key===r.key&&!e.ready)?e.map(e=>e.key===r.key?{...e,ready:!0}:e):e)},r.key))})}export{j as a,A as b,D as c,B as d,K as e,V as f};
@@ -1 +1 @@
1
- "use client";import{e}from"./chunk-RJWFSAKE.mjs";import{w as t}from"./chunk-P2WAXWAZ.mjs";import{a as n}from"./chunk-2F2BVGFH.mjs";import{d as r}from"./chunk-RWZ7SVMO.mjs";import{l as o}from"./chunk-5IZHN3A7.mjs";import{h as i}from"./chunk-VXRRHXUP.mjs";import{b as l}from"./chunk-6RMM7JB6.mjs";import{useState as a,useEffect as d,useRef as s,useLayoutEffect as c}from"react";import{jsxs as p,jsx as m,Fragment as u}from"react/jsx-runtime";function v({tree:e,x:t,y:n}){let o=s(null);return c(()=>{let t=o.current,n=t.shadowRoot??t.attachShadow({mode:"open"}),i=r(e,t.ownerDocument,"preview");if(i)return i.style.margin="0",n.replaceChildren(i),()=>n.replaceChildren()},[e]),m("div",{ref:o,"data-devtools":"placement-card-ghost",inert:!0,"aria-hidden":"true",style:{position:"fixed",left:t,top:n,display:"grid",width:"max-content",transform:"translate(-50%, -50%)",pointerEvents:"none",opacity:.48,zIndex:2}})}function f({sample:r,initialPoint:f,getSubjects:h,onPlace:y,onCancel:w,color:x}){let[g,k]=a(null),[E,P]=a("");d(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopImmediatePropagation(),w())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[w]);let j=s(f),R=s(null),I=(t,n)=>e(r,i(t,n),{x:t,y:n},h());c(()=>{let t=()=>{let t=j.current,n=R.current;if(!n||!t)return k(null);let o=n.getRootNode();if(!n.contains(o.elementFromPoint(t.x,t.y)))return k(null);try{k(e(r,i(t.x,t.y),t,h()))}catch{k(null)}};return t(),window.addEventListener("scroll",t,!0),window.addEventListener("resize",t),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t)}},[r,h]);let L=g?.objectPlacement,b=g?.payload.canvases?.[0]?.value;c(()=>{if(L?.preview&&void 0!==b)try{L.preview(b)}catch{}},[L,b]),c(()=>()=>{try{L?.preview?.(null)}catch{}},[L]);return p("div",{ref:R,"data-devtools":"sample-placement",style:{position:"fixed",inset:0,zIndex:10003,pointerEvents:"auto",cursor:o(x)},onPointerMove:e=>((e,t)=>{j.current={x:e,y:t};try{k(I(e,t))}catch{k(null)}})(e.clientX,e.clientY),onPointerLeave:()=>{j.current=null,k(null)},onPointerDown:e=>e.stopPropagation(),onPointerUp:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),e.stopPropagation(),((e,t)=>{try{let r=I(e,t);if(!r)return;let o=r.payload.placedElement;o&&(o.sourceSlot=n(o,r.target)),y(r.payload)}catch(e){P(e instanceof Error?e.message:"Could not place this sample.")}})(e.clientX,e.clientY)},children:[E&&m("div",{role:"alert",style:{position:"fixed",zIndex:4,left:"50%",top:12,transform:"translateX(-50%)",background:"#111",color:"white",padding:"5px 9px",borderRadius:8,font:`12px/16px ${l}`,pointerEvents:"none"},children:E}),g&&p(u,{children:[m(t,{element:g.target,color:x,spotlight:!0,hideTooltip:!0,hideFill:!0,outlineZIndex:1}),"element"===r.kind&&m(v,{tree:r.tree,x:g.pointer.x,y:g.pointer.y}),g.marker&&m("div",{"data-devtools":"placement-insertion-line",style:{position:"fixed",...g.marker,pointerEvents:"none",zIndex:2,borderRadius:4,backgroundColor:x}})]})]})}export{f as a};
1
+ "use client";import{e}from"./chunk-RJWFSAKE.mjs";import{x as t}from"./chunk-EOAWCUFT.mjs";import{a as n}from"./chunk-2F2BVGFH.mjs";import{d as r}from"./chunk-RWZ7SVMO.mjs";import{l as o}from"./chunk-5IZHN3A7.mjs";import{h as i}from"./chunk-VXRRHXUP.mjs";import{b as l}from"./chunk-6RMM7JB6.mjs";import{useState as a,useEffect as d,useRef as s,useLayoutEffect as c}from"react";import{jsxs as p,jsx as m,Fragment as u}from"react/jsx-runtime";function v({tree:e,x:t,y:n}){let o=s(null);return c(()=>{let t=o.current,n=t.shadowRoot??t.attachShadow({mode:"open"}),i=r(e,t.ownerDocument,"preview");if(i)return i.style.margin="0",n.replaceChildren(i),()=>n.replaceChildren()},[e]),m("div",{ref:o,"data-devtools":"placement-card-ghost",inert:!0,"aria-hidden":"true",style:{position:"fixed",left:t,top:n,display:"grid",width:"max-content",transform:"translate(-50%, -50%)",pointerEvents:"none",opacity:.48,zIndex:2}})}function f({sample:r,initialPoint:f,getSubjects:h,onPlace:y,onCancel:w,color:x}){let[g,k]=a(null),[E,P]=a("");d(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopImmediatePropagation(),w())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[w]);let j=s(f),R=s(null),C=(t,n)=>e(r,i(t,n),{x:t,y:n},h());c(()=>{let t=()=>{let t=j.current,n=R.current;if(!n||!t)return k(null);let o=n.getRootNode();if(!n.contains(o.elementFromPoint(t.x,t.y)))return k(null);try{k(e(r,i(t.x,t.y),t,h()))}catch{k(null)}};return t(),window.addEventListener("scroll",t,!0),window.addEventListener("resize",t),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t)}},[r,h]);let I=g?.objectPlacement,L=g?.payload.canvases?.[0]?.value;c(()=>{if(I?.preview&&void 0!==L)try{I.preview(L)}catch{}},[I,L]),c(()=>()=>{try{I?.preview?.(null)}catch{}},[I]);return p("div",{ref:R,"data-devtools":"sample-placement",style:{position:"fixed",inset:0,zIndex:10003,pointerEvents:"auto",cursor:o(x)},onPointerMove:e=>((e,t)=>{j.current={x:e,y:t};try{k(C(e,t))}catch{k(null)}})(e.clientX,e.clientY),onPointerLeave:()=>{j.current=null,k(null)},onPointerDown:e=>e.stopPropagation(),onPointerUp:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),e.stopPropagation(),((e,t)=>{try{let r=C(e,t);if(!r)return;let o=r.payload.placedElement;o&&(o.sourceSlot=n(o,r.target)),y(r.payload)}catch(e){P(e instanceof Error?e.message:"Could not place this sample.")}})(e.clientX,e.clientY)},children:[E&&m("div",{role:"alert",style:{position:"fixed",zIndex:4,left:"50%",top:12,transform:"translateX(-50%)",background:"#111",color:"white",padding:"5px 9px",borderRadius:8,font:`12px/16px ${l}`,pointerEvents:"none"},children:E}),g&&p(u,{children:[m(t,{element:g.target,color:x,spotlight:!0,hideTooltip:!0,hideFill:!0,outlineZIndex:1}),"element"===r.kind&&m(v,{tree:r.tree,x:g.pointer.x,y:g.pointer.y}),g.marker&&m("div",{"data-devtools":"placement-insertion-line",style:{position:"fixed",...g.marker,pointerEvents:"none",zIndex:2,borderRadius:4,backgroundColor:x}})]})]})}export{f as a};
@@ -0,0 +1 @@
1
+ "use client";import{a as l}from"./chunk-OL7RDZ2R.mjs";import{b as t}from"./chunk-OEJXPUAR.mjs";import{v as e}from"./chunk-OA63PYHZ.mjs";import{useState as n,useRef as r,useCallback as o,useEffect as a}from"react";import{jsxs as i,jsx as s}from"react/jsx-runtime";function c(l,e,i=0,s){let[c,u]=n(null),[d,p]=n(!1),g=r(null),b=r(!1),h=o(()=>{if(!e)return;if(g.current)return void(b.current=!0);let n=new AbortController;g.current=n,p(!0);let r=setTimeout(()=>n.abort(),8e3);t(`${e}/provider-setup/${l}`,{cache:"no-store",signal:n.signal}).then(async t=>{if(!t.ok){if("cloudflared"===l&&(400===t.status||404===t.status)){let l=404===t.status||"Unsupported provider operation"===(await t.json().catch(()=>null))?.error;if(l)return void(g.current===n&&u({bridgeUrl:e,status:null,unsupported:l}))}throw new Error("Provider status unavailable")}let r=await t.json();if("boolean"!=typeof r?.installed)throw new Error("Invalid provider status");g.current===n&&(u({bridgeUrl:e,status:r}),"cloudflared"!==l&&r.installed&&"signed_in"===r.auth&&s?.())}).catch(()=>{g.current===n&&u(t=>"cloudflared"!==l&&t?.bridgeUrl===e?t:{bridgeUrl:e,status:null})}).finally(()=>{clearTimeout(r),g.current===n&&(g.current=null,b.current?(b.current=!1,h()):p(!1))})},[e,l,s]);return a(()=>()=>{let l=g.current;g.current=null,b.current=!1,l?.abort()},[h]),a(()=>{e?h():u(null)},[h,i,e]),{current:c?.bridgeUrl===e?c:null,checking:d,refresh:h}}var u={codex:{label:"Codex",installUrl:"https://github.com/openai/codex#installing-and-running-codex-cli",installTool:"npm",installPackage:"@openai/codex",loginArgs:["login"]},claude:{label:"Claude Code",installUrl:"https://code.claude.com/docs/en/setup#install-claude-code",installTool:"npm",installPackage:"@anthropic-ai/claude-code",loginArgs:["auth","login"]},cursor:{label:"Grok Code (Cursor)",installUrl:"https://cursor.com/docs/cli/installation",installTool:"brew",installPackage:"cursor-cli",loginArgs:["login"]},opencode:{label:"OpenCode",installUrl:"https://opencode.ai/docs/",installTool:"npm",installPackage:"@opencode/cli",loginArgs:["auth","login"]},copilot:{label:"GitHub Copilot",installUrl:"https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli",installTool:"npm",installPackage:"@github/copilot",loginArgs:["login"]},omp:{label:"Oh My Pi",installUrl:"https://github.com/can1357/oh-my-pi#install",installTool:"bun",installPackage:"@oh-my-pi/pi-coding-agent",loginArgs:["setup"]}},d={...u,cloudflared:{label:"cloudflared",installUrl:"https://developers.cloudflare.com/tunnel/downloads/",installTool:"brew",installPackage:"cloudflared",loginArgs:[]}};function p({provider:t,bridgeUrl:n,canLaunch:r,style:o,onComplete:c,label:u,icon:p}){let g=d[t],{state:b,start:h}=l(t,n,"install"),m="opening"===b||"pending"===b;return a(()=>{"complete"===b&&c()},[b,c]),r&&"manual"!==b&&"failed"!==b&&"complete"!==b?i("button",{type:"button",style:o,"data-provider-action":"",disabled:m,"aria-label":u?void 0:`Install CLI ${g.label}`,onClick:()=>{h()},children:[p,m?"Installing…":u??"Install CLI"]}):i("a",{href:g.installUrl,target:"_blank",rel:"noreferrer",style:o,"data-provider-action":"","aria-label":u??`Install ${g.label} CLI`,children:[p,u??("idle"!==b?"Install help":"cloudflared"===t?"Install instructions":"Install CLI"),!p&&s(e,{size:14,"aria-hidden":"true"})]})}export{u as a,d as b,c,p as d};
@@ -0,0 +1 @@
1
+ import{a as e,b as t}from"./chunk-KOHR4LAQ.mjs";function i(e,t){return{storeId:e,explanationId:t}}function r(e,t){let{fromId:r,toId:a,toStoreId:n,...o}=t;return{...o,from:i(e,r),to:i(n??e,a)}}var a={project:0,route:1,component:2,selector:2,file:3},n={intention:0,principle:1,pattern:2};function o(e,t){let i=a[e.scope.kind]-a[t.scope.kind];return 0!==i?i:n[e.kind]-n[t.kind]}function s(e){return"expresses"===e||"excepts"===e}function d(e){let t=structuredClone(e),i=new Set;return t.relations=e.relations.flatMap(t=>{let r=function(e,t){if("expresses"===t.type||"excepts"===t.type)return structuredClone(t);if("operationalizes"===t.type)return{...structuredClone(t),type:"expresses"};if("instantiates"===t.type)return{...structuredClone(t),type:"expresses",fromId:t.toId,toId:t.fromId};if("refines"===t.type){let i=e.explanations.find(e=>e.id===t.fromId),r=e.explanations.find(e=>e.id===t.toId);if(!i||!r)return;let a=o(i,r);return 0===a?void 0:a>0?{...structuredClone(t),type:"expresses"}:{...structuredClone(t),type:"expresses",fromId:t.toId,toId:t.fromId}}}(e,t);if(!r)return[];let a=`${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`;return i.has(a)?[]:(i.add(a),[r])}),t}import{createHash as c}from"crypto";import{mkdir as l,open as p,readFile as u,readdir as h,rename as m,unlink as f}from"fs/promises";import{join as y}from"path";import{isUuidV7 as I,validateProjectMemoryBundle as w}from"./memory.mjs";var v={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function g(e){return c("sha256").update(JSON.stringify(e)).digest("hex")}function j(e){return g(e)}function b(e,t,i){[...t.records,...t.recordReplacements??[]].some(e=>"advisory_explanation"===e.recordType)&&!e.manifest.features.includes("advisory_explanations")&&e.manifest.features.push("advisory_explanations");for(let i of t.recordReplacements??[]){if("advisory_explanation"!==i.recordType)throw new Error(`Record replacement is not supported for ${i.recordType}.`);let t=e.records.findIndex(e=>e.recordType===i.recordType&&e.id===i.id);if(t<0)throw new Error(`Record replacement target not found: ${i.recordType} ${i.id}`);let r=e.records[t];if(r.projectId!==i.projectId||r.createdAt!==i.createdAt||r.participantId!==i.participantId)throw new Error(`Record replacement changed immutable identity for ${i.id}.`);e.records[t]=structuredClone(i)}for(let i of t.projectionUpdates){let t=e.records.find(e=>e.recordType===i.entityType&&e.id===i.entityId);if(!t||"proposal"!==t.recordType&&"decision"!==t.recordType)throw new Error(`Projection target not found: ${i.entityType} ${i.entityId}`);if(t.state!==i.fromState)throw new Error(`Projection state conflict for ${i.entityType} ${i.entityId}: expected ${i.fromState}, found ${t.state}`);t.state=i.state}return e.records.push(...t.records),e.events.push(...t.events),e.relationships.push(...t.relationships),e.artifacts.push(...t.artifacts),e.tombstones.push(...t.tombstones),e.manifest.updatedAt=i,e}async function x(e,t){let i=`${e}.${process.pid}.${Date.now()}.tmp`,r=await p(i,"w");try{await r.writeFile(`${JSON.stringify(t,null,2)}\n`,"utf8"),await r.sync()}finally{await r.close()}try{await m(i,e)}catch(e){throw await f(i).catch(()=>{}),e}}async function T(e){return JSON.parse(await u(e,"utf8"))}var k=class{constructor(e){this.writeChain=Promise.resolve(),this.memoryDir=y(e,".popmelt","memory"),this.journalDir=y(this.memoryDir,"journal"),this.manifestPath=y(this.memoryDir,"manifest.json"),this.checkpointPath=y(this.memoryDir,"checkpoint.json"),this.lockPath=y(this.memoryDir,"writer.lock")}async readHead(){let e=await T(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=w(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await l(this.journalDir,{recursive:!0});try{throw await u(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(e){if(e instanceof Error&&"Memory journal is already initialized."===e.message||"ENOENT"!==e.code)throw e}await this.withWriterLock(async()=>{try{throw await u(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(e){if(e instanceof Error&&"Memory journal is already initialized."===e.message||"ENOENT"!==e.code)throw e}let t=g(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await x(this.checkpointPath,i),await x(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await x(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=g(e.bundle),i=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await x(y(this.memoryDir,i),r),e.manifest.checkpoint={file:i,sequence:r.sequence,hash:t},await x(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!I(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let i=await this.loadInternal();if(i.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let r=i.report.headSequence+1,a={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:i.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:i.report.headHash,mutation:e},n={...a,hash:j(a)},o=function(e,t,i){return b(structuredClone(e),t,i)}(i.bundle,e,t.committedAt),s=w(o);if(!s.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(s.issues)}`);let d=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await x(y(this.journalDir,d),n),i.manifest.head={sequence:r,hash:n.hash},i.manifest.updatedAt=t.committedAt,await x(this.manifestPath,i.manifest),{bundle:o,report:{checkpointSequence:i.report.checkpointSequence,appliedTransactions:i.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:i.report.ignoredTemporaryFiles,headSequence:r,headHash:n.hash}}}))}async commitReviewPlan(e,t){return this.commit({...v,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await T(this.manifestPath),t=await T(y(this.memoryDir,e.checkpoint.file));if(1!==e.storageVersion||1!==t.storageVersion)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==g(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let i=await h(this.journalDir),r=i.filter(e=>e.endsWith(".tmp")),a=i.filter(e=>/^\d{12}-[0-9a-f-]+\.json$/i.test(e)).sort().filter(e=>Number(e.slice(0,12))>t.sequence),n=structuredClone(t.bundle),o=t.sequence,s=t.journalHash??null,d=new Set;for(let t of a){let i=await T(y(this.journalDir,t)),{hash:r,...a}=i;if(r!==j(a))throw new Error(`Journal hash mismatch: ${t}`);if(i.sequence!==o+1)throw new Error(`Journal sequence gap at ${t}`);if(i.previousHash!==s)throw new Error(`Journal chain mismatch at ${t}`);if(i.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${t}`);if(d.has(i.transactionId))throw new Error(`Duplicate transaction ID: ${i.transactionId}`);b(n,i.mutation,i.committedAt),o=i.sequence,s=i.hash,d.add(i.transactionId)}if(e.head.sequence>o)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===o&&e.head.hash!==s)throw new Error("Journal manifest head hash mismatch.");let c=w(n);if(!c.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(c.issues)}`);return{bundle:n,manifest:e,transactionIds:d,report:{checkpointSequence:t.sequence,appliedTransactions:a.length,recoveredTransactions:Math.max(0,o-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:o,headHash:s}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){let t;await l(this.memoryDir,{recursive:!0});try{t=await p(this.lockPath,"wx")}catch(e){if("EEXIST"!==e.code)throw e;let i=await T(this.lockPath).catch(()=>({})),r=!0;if("number"==typeof i.pid)try{process.kill(i.pid,0)}catch(e){r="ESRCH"!==e.code}if(r)throw new Error("Memory journal is locked by another writer.");await f(this.lockPath),t=await p(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:(new Date).toISOString()})),await e()}finally{await t.close(),await f(this.lockPath).catch(()=>{})}}};import{mkdir as S,readFile as A,writeFile as _}from"fs/promises";import{join as E}from"path";import{planOwnerReviewAction as $,retrieveActionPacket as q,selectContextualReviewPackets as M}from"./memory.mjs";import{createHash as R}from"crypto";import{mkdir as P,open as z,readFile as C,rename as D,unlink as B}from"fs/promises";import{join as N}from"path";function O(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function V(e){return R("sha256").update(JSON.stringify(e)).digest("hex")}var J=class{constructor(e){this.indexDir=N(e,".popmelt","memory","indexes"),this.indexPath=N(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let i=JSON.parse(await C(this.indexPath,"utf8")),{checksum:r,...a}=i;if(1===i.version&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===t.sequence&&i.journalHead.hash===t.hash&&r===V(a))return i}catch(e){if("ENOENT"!==e.code&&!(e instanceof SyntaxError))throw e}let i=function(e,t,i=(new Date).toISOString()){let r={},a={},n={},o=(e,t,i)=>{let r=e[t]??=[];r.includes(i)||r.push(i)};for(let t of e.records)if("subject"===t.recordType){let e=t;for(let t of[e.label,...e.aliases,...e.locators.filter(e=>"current"===e.status).map(e=>e.value)]){let i=O(t);i&&o(r,i,e.id)}}else if("decision"===t.recordType&&"active"===t.state)for(let e of t.subjects)o(a,e.subjectId,t.id);else if("proposal"===t.recordType&&["pending","deferred"].includes(t.state))for(let e of t.subjects)o(n,e.subjectId,t.id);let s={version:1,projectId:e.manifest.projectId,journalHead:t,generatedAt:i,subjectIdsByValue:r,decisionIdsBySubject:a,proposalIdsBySubject:n};return{...s,checksum:V(s)}}(e,t);return await P(this.indexDir,{recursive:!0}),await async function(e,t){let i=`${e}.${process.pid}.${Date.now()}.tmp`,r=await z(i,"w");try{await r.writeFile(`${JSON.stringify(t,null,2)}\n`,"utf8"),await r.sync()}finally{await r.close()}try{await D(i,e)}catch(e){throw await B(i).catch(()=>{}),e}}(this.indexPath,i),i}};import{randomBytes as H}from"crypto";function W(e=Date.now()){let t=Math.max(0,Math.min(Math.floor(e),0xffffffffffff)).toString(16).padStart(12,"0"),i=H(10).toString("hex"),r=(3&Number.parseInt(i[3],16)|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${i.slice(0,3)}-${r}${i.slice(4,7)}-${i.slice(7,19)}`}var F="popmelt:imprint",L="popmelt:imprint-evidence",U="popmelt:imprint-relation";function K(e){return e.sourceRefs.find(e=>"external"===e.kind&&e.uri===F)?.id}function G(e){let t=new Set;return e.filter(e=>{let i=`${e.kind}:${e.id}:${e.uri??""}`;return!t.has(i)&&(t.add(i),!0)})}function Q(e,t){if(!e)return[];let i=new Set(e.relations.flatMap(e=>"expresses"!==e.type||e.toStoreId||e.toId!==t?[]:[e.fromId]));return e.concrete.filter(e=>i.has(e.id)).map(e=>({id:e.id,modelPath:e.modelPath,value:structuredClone(e.value),createdAt:e.createdAt,updatedAt:e.updatedAt}))}function X(e){return"expresses"===e?"expresses":"excepts"===e?"excepts":void 0}var Y=class{constructor(e){this.projectRoot=e,this.store=new k(e),this.indexStore=new J(e),this.manifestPath=E(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await A(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if("ENOENT"===e.code)return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise||(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let e=await this.store.load();return e.report.recoveredTransactions>0&&(e=await this.store.recover()),await this.refreshIndex(e),await this.status()}let i=await t({...e,projectRoot:this.projectRoot});if(i.report.schemaIssues.some(e=>"error"===e.severity))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(i.bundle)}catch(e){if(!(e instanceof Error&&e.message.includes("already initialized")))throw e}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(e){return this.runtimeState={state:"degraded",error:e instanceof Error?e.message:String(e)},await this.status()}})()),this.initializationPromise}async analyzeLegacy(e={}){return(await t({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let t,i=E(this.projectRoot,".popmelt","memory","migrations"),r=E(i,"imprint-advisories-v2.json");try{let e=JSON.parse(await A(r,"utf8"));return{migrated:!1,explanations:e.explanations??0,evidence:e.evidence??0}}catch{}try{t=d(JSON.parse(await A(E(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!t?.explanations)return await S(i,{recursive:!0}),await _(r,JSON.stringify({version:2,migratedAt:(new Date).toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let a=await this.store.load(),n=a.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status),o=a.bundle.records.find(e=>"participant"===e.recordType&&"ai"===e.kind&&"active"===e.status)??n,s=a.bundle.records.find(e=>"subject"===e.recordType&&"project"===e.subjectType);if(!o||!s)return{migrated:!1,explanations:0,evidence:0};let c=a.bundle.manifest.projectId,l=new Set(a.bundle.records.map(e=>e.id)),p=new Set(a.bundle.relationships.flatMap(e=>e.sourceRefs.flatMap(e=>"external"===e.kind&&e.uri===U?[e.id]:[]))),u=new Map,h=a.bundle.records.filter(e=>"advisory_explanation"===e.recordType);for(let i of t.explanations){let t=h.find(e=>K(e)===i.id);u.set(i.id,t?.id??e(c,"imprint-explanation",i.id,Date.parse(i.createdAt)))}let m=[],f=[],y=[],I=0;for(let i of t.explanations){let r=u.get(i.id),a=h.find(e=>e.id===r),n=[],d=i.evidence.length?i.evidence:[{id:`fallback:${i.id}`,kind:"observation",stance:"supports",summary:i.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:i.createdAt}];for(let t of d){let a=e(c,"imprint-evidence-record",t.id,Date.parse(t.createdAt));n.push(a),!l.has(a)&&(m.push({id:a,schemaVersion:1,projectId:c,createdAt:t.createdAt,participantId:o.id,sourceRefs:G([{kind:"external",id:t.id,uri:L},{kind:"external",id:i.id,uri:F},{kind:"thread",id:t.threadId},{kind:"message",id:t.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(t.kind)?"user_feedback":"judgment",summary:t.summary,availability:"available",artifactIds:[]}),y.push({id:e(c,"imprint-evidence-link",`${i.id}:${t.id}`,Date.parse(t.createdAt)),schemaVersion:1,projectId:c,createdAt:t.createdAt,participantId:o.id,sourceRefs:[{kind:"external",id:t.id,uri:L}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:r},to:{entityType:"evidence",entityId:a},reason:"This advisory explanation was derived from collaboration evidence."}),I+=1)}let p={id:r,schemaVersion:1,projectId:c,createdAt:a?.createdAt??i.createdAt,participantId:a?.participantId??o.id,sourceRefs:G([...a?.sourceRefs??[],{kind:"external",id:i.id,uri:F}]),recordType:"advisory_explanation",kind:i.kind,state:i.state,statement:i.statement,rationale:i.rationale,scope:structuredClone(i.scope),subjectIds:[s.id],evidenceIds:[...new Set([...a?.evidenceIds??[],...n])],concreteBindings:Q(t,i.id),supersededById:i.supersededBy?u.get(i.supersededBy):void 0,updatedAt:i.updatedAt};a?f.push(p):m.push(p)}for(let i of t.relations){let t=X(i.type);if(!t||i.toStoreId)continue;let r=u.get(i.fromId),a=u.get(i.toId);!r||!a||p.has(i.id)||y.push({id:e(c,"imprint-relation",i.id,Date.parse(i.createdAt)),schemaVersion:1,projectId:c,createdAt:i.createdAt,participantId:o.id,sourceRefs:[{kind:"external",id:i.id,uri:U}],recordType:"relationship",relationshipType:t,from:{entityType:"advisory_explanation",entityId:r},to:{entityType:"advisory_explanation",entityId:a},reason:i.rationale||"The Imprint graph connected these explanations."})}let w=(new Date).toISOString();if(m.length||f.length||y.length)try{let i=await this.store.commit({records:m,recordReplacements:f,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:e(c,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:w});await this.refreshIndex(i)}catch(e){if(!(e instanceof Error&&e.message.includes("Transaction already exists")))throw e}return await S(i,{recursive:!0}),await _(r,JSON.stringify({version:2,migratedAt:w,explanations:t.explanations.length,evidence:I,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:I}}async review(e,t={}){let i=await this.loadSource(t),r=await this.withIndexedCandidates(i,e);return{source:i.source,selection:M(i.bundle,r)}}async contextualize(e,t={}){let i=await this.loadSource(t),r=await this.withIndexedCandidates(i,e);return{source:i.source,actionPacket:q(i.bundle,r),reviewSelection:M(i.bundle,r)}}async imprintTopology(){let e;try{e=await this.loadJournalSource()}catch(e){if("ENOENT"===e.code)return{explanations:[],relations:[]};throw e}return{explanations:e.bundle.records.flatMap(e=>"advisory_explanation"===e.recordType?[{memoryId:e.id,explanationId:K(e)??e.id}]:[]),relations:e.bundle.relationships.flatMap(e=>"expresses"!==e.relationshipType&&"excepts"!==e.relationshipType||"advisory_explanation"!==e.from.entityType||"advisory_explanation"!==e.to.entityType?[]:[{id:e.id,type:e.relationshipType,from:{memoryId:e.from.entityId,...e.from.storeId?{storeId:e.from.storeId}:{}},to:{memoryId:e.to.entityId,...e.to.storeId?{storeId:e.to.storeId}:{}},rationale:e.reason}])}}async planReview(e,t={}){let i=await this.loadSource(t);return{source:i.source,result:$(i.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let i=await t({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(i.report.schemaIssues.some(e=>"error"===e.severity))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(i.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:i.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let i=await this.store.load(),r=$(i.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let a=await this.store.commitReviewPlan(r.plan,t);return await this.refreshIndex(a),a}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),i=t.bundle.records.find(t=>"proposal"===t.recordType&&t.id===e.proposalId),r=t.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status);if(!i||"pending"!==i.state||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:i?"pending"!==i.state?`The proposal is already ${i.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let a=Date.now(),n=new Date(a).toISOString(),o={proposalId:i.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:n},s="accept"===e.action?{...o,action:"accept",eventId:W(a),decisionId:W(a),kind:e.kind,reason:e.reason}:"edit_and_accept"===e.action?{...o,action:"edit_and_accept",withdrawalEventId:W(a),replacementProposalId:W(a),acceptanceEventId:W(a),decisionId:W(a),relationshipId:W(a),claim:e.claim,kind:e.kind,subjects:i.subjects,subjectSemantics:i.subjectSemantics,reason:e.reason}:"reject"===e.action?{...o,action:"reject",eventId:W(a),reason:e.reason}:{...o,action:"defer",eventId:W(a),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:i.subjects.map(e=>e.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},d=$(t.bundle,s);if(!d.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:d.errors.map(e=>e.message).join(" ")};let c=await this.store.commitReviewPlan(d.plan,{transactionId:W(a),committedAt:n});await this.refreshIndex(c);let l=d.plan.resultRefs.find(e=>"decision"===e.entityType)?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:l,message:"accept"===e.action||"edit_and_accept"===e.action?"Accepted product memory was committed.":"reject"===e.action?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:c.report.headSequence}}async captureCompletedJob(t){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let i=await this.store.load(),r=function(t,i){let r=t.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status),a=t.records.find(e=>"participant"===e.recordType&&"ai"===e.kind&&"active"===e.status);if(!r||!a)throw new Error("Canonical memory requires active human and AI participants before job capture.");let n=t.manifest.projectId,o=`${i.threadId}:${i.jobId}`,s=new Date(i.createdAt).toISOString(),d=new Date(i.completedAt).toISOString(),c={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},l=c.records,p=t.records.find(e=>"thread"===e.recordType&&e.sourceRefs.some(e=>"thread"===e.kind&&e.id===i.threadId));p||(p={id:e(n,"live-thread",i.threadId,i.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"thread",id:i.threadId}],recordType:"thread",state:"question_asked"===i.outcome?"open":"resolved",messageArtifactIds:[],outcome:"question_asked"===i.outcome?"question_unresolved":i.resolutions.some(e=>"resolved"===e.status)?"implementation_only":"no_outcome",resultRefs:[]},l.push(p));let u=[];for(let a of[...new Set(i.subjectHints.filter(Boolean))]){let o=t.records.find(e=>"subject"===e.recordType&&e.locators.some(e=>e.value===a&&"current"===e.status));o||(o={id:e(n,"live-subject",a,i.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"external",id:a}],recordType:"subject",subjectType:"element",label:a,aliases:[],locators:[{id:e(n,"live-locator",a,i.createdAt),kind:"dom_selector",value:a,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:a}]}]},l.push(o)),u.push(o)}for(let a of[...new Set((i.filePaths??[]).filter(Boolean))]){let o=t.records.find(e=>"subject"===e.recordType&&e.locators.some(e=>"source_file"===e.kind&&e.value===a&&"current"===e.status));o||(o={id:e(n,"live-file-subject",a,i.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"external",id:a}],recordType:"subject",subjectType:"file",label:a,aliases:[],locators:[{id:e(n,"live-file-locator",a,i.createdAt),kind:"source_file",value:a,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:a}]}]},l.push(o)),u.push(o)}let h,m=(i.semanticCandidates??[]).filter(e=>e.claim.trim());if(m.length>0){h=e(n,"live-observation",o,i.createdAt);let a={id:h,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"thread",id:i.threadId}],recordType:"observation",state:"open",statement:m.map(e=>e.claim.trim()).join(" "),captureContext:{subjectIds:u.map(e=>e.id),artifactIds:[]},resolvedByIds:[]};l.push(a)}let f=e(n,"live-iteration",o,i.completedAt),y={id:f,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:a.id,sourceRefs:[{kind:"thread",id:i.threadId},{kind:"external",id:i.jobId,uri:"popmelt:job"},...(i.submissionIds??[]).map(e=>({kind:"external",id:e,uri:"popmelt:submission"})),...i.outcomeId?[{kind:"external",id:i.outcomeId,uri:"popmelt:outcome"}]:[],...(i.imprintEvidenceIds??[]).map(e=>({kind:"external",id:e,uri:"popmelt:imprint-evidence"})),...h?[{kind:"record",id:h}]:[]],recordType:"iteration",threadIds:[p.id],startedAt:s,completedAt:d,requestSummary:i.requestSummary||"[request unavailable]",responseSummary:i.responseSummary?.slice(0,2e3),outcome:i.outcome,execution:i.execution,artifactIds:[],...i.imprintAssessment?{imprintAssessment:i.imprintAssessment}:{}};l.push(y);let I=[],w=i.resolutions.filter(e=>"resolved"===e.status&&e.summary.trim()),v=u.length>0?u:t.records.filter(e=>"subject"===e.recordType&&"project"===e.subjectType).slice(0,1);if(m.length>0&&0===v.length)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[r,s]of m.entries()){let c=e(n,"live-proposal",`${o}:${r}`,i.completedAt),p=v.map(e=>({subjectId:e.id,role:"governed"})),u={id:c,schemaVersion:1,projectId:t.manifest.projectId,createdAt:d,participantId:a.id,sourceRefs:[{kind:"iteration",id:f},{kind:"thread",id:i.threadId}],recordType:"proposal",state:"pending",claim:s.claim.trim(),rationale:s.rationale?.trim()||void 0,proposedKind:s.proposedKind,subjects:p,subjectSemantics:p.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:s.sourceText?.trim()||i.requestSummary,iterationId:f,inferredById:a.id}};l.push(u),I.push(c)}if(w.length>0){let r=new Set(i.governingDecisionIds??[]),s=t.records.filter(e=>"decision"===e.recordType&&"active"===e.state&&r.has(e.id)),c={id:e(n,"live-implementation",o,i.completedAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:d,participantId:a.id,sourceRefs:[{kind:"iteration",id:f}],recordType:"implementation_attempt",state:"completed",iterationIds:[f],coverageClaims:s.map(e=>({decisionId:e.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${w.map(e=>e.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:f}]})),summary:w.map(e=>e.summary).join(" "),artifactIds:[]};l.push(c)}return{mutation:c,iterationId:f,proposalIds:I,observationId:h}}(i.bundle,t),a=e(i.bundle.manifest.projectId,"live-capture-transaction",`${t.threadId}:${t.jobId}`,t.completedAt);try{let e=await this.store.commit(r.mutation,{transactionId:a,committedAt:new Date(t.completedAt).toISOString()});return await this.refreshIndex(e),{status:"captured",iterationId:r.iterationId,proposalIds:r.proposalIds,headSequence:e.report.headSequence}}catch(e){if(e instanceof Error&&e.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:r.iterationId,proposalIds:r.proposalIds};throw e}}async recordImprintEvidence(t){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||0===t.summary.changes.length)return;let i;try{i=d(JSON.parse(await A(E(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let r=await this.store.load(),a=r.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status),n=r.bundle.records.find(e=>"participant"===e.recordType&&"ai"===e.kind&&"active"===e.status),o=t.action?a:n??a,s=r.bundle.records.find(e=>"subject"===e.recordType&&"project"===e.subjectType);if(!o||!s)return;let c=t.occurredAt??(new Date).toISOString(),l=Date.parse(c),p=r.bundle.manifest.projectId,u=[],h=[],m=[],f=r.bundle.records.filter(e=>"advisory_explanation"===e.recordType),y=new Map(f.flatMap(e=>{let t=K(e);return t?[[t,e.id]]:[]}));for(let r of t.summary.changes)if(!y.has(r.explanationId)){let t=i?.explanations.find(e=>e.id===r.explanationId);y.set(r.explanationId,e(p,"imprint-explanation",r.explanationId,Date.parse(t?.createdAt??c)))}for(let r of t.summary.changes){let a={kind:"external",id:r.explanationId,uri:F},n=y.get(r.explanationId),d=f.find(e=>e.id===n),I=i?.explanations.find(e=>e.id===r.explanationId),w={id:e(p,"imprint-live-evidence",`${t.summary.transactionId}:${r.explanationId}:${t.action??"automatic"}`,l),schemaVersion:1,projectId:p,createdAt:c,participantId:o.id,sourceRefs:[a,{kind:"thread",id:t.threadId},{kind:"message",id:t.jobId}],recordType:"evidence",kind:t.action?"user_feedback":"judgment",summary:t.action?`${t.action}: ${t.summary.detail}`:`${t.summary.kind}: ${t.summary.detail}`,availability:"available",artifactIds:[]};u.push(w);let v={id:n,schemaVersion:1,projectId:p,createdAt:d?.createdAt??I?.createdAt??c,participantId:d?.participantId??o.id,sourceRefs:G([...d?.sourceRefs??[],a,{kind:"thread",id:t.threadId},{kind:"message",id:t.jobId}]),recordType:"advisory_explanation",kind:I?.kind??d?.kind??"pattern",state:I?.state??r.state,statement:I?.statement??r.statement,rationale:I?.rationale??d?.rationale??t.summary.detail,scope:structuredClone(I?.scope??d?.scope??{kind:"project",values:[]}),subjectIds:d?.subjectIds??[s.id],evidenceIds:[...new Set([...d?.evidenceIds??[],w.id])],concreteBindings:I?Q(i,r.explanationId):d?.concreteBindings??[],supersededById:I?.supersededBy?y.get(I.supersededBy):d?.supersededById,updatedAt:I?.updatedAt??c};d?h.push(v):u.push(v),m.push({id:e(p,"imprint-live-evidence-link",`${t.summary.transactionId}:${r.explanationId}:${t.action??"automatic"}`,l),schemaVersion:1,projectId:p,createdAt:c,participantId:o.id,sourceRefs:[a],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:v.id},to:{entityType:"evidence",entityId:w.id},reason:t.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let I=new Set(r.bundle.relationships.flatMap(e=>e.sourceRefs.flatMap(e=>"external"===e.kind&&e.uri===U?[e.id]:[])));for(let r of i?.relations??[]){let i=X(r.type);if(!i)continue;let a=y.get(r.fromId),n=r.toStoreId?t.qualifiedExplanationMemoryIds?.[`${r.toStoreId}:${r.toId}`]:y.get(r.toId);!a||!n||I.has(r.id)||m.push({id:e(p,"imprint-relation",r.id,Date.parse(r.createdAt)),schemaVersion:1,projectId:p,createdAt:r.createdAt,participantId:o.id,sourceRefs:[{kind:"external",id:r.id,uri:U}],recordType:"relationship",relationshipType:i,from:{entityType:"advisory_explanation",entityId:a},to:{entityType:"advisory_explanation",entityId:n,...r.toStoreId?{storeId:r.toStoreId}:{}},reason:r.rationale||"The Imprint graph connected these explanations."})}let w=e(r.bundle.manifest.projectId,"imprint-evidence",`${t.summary.transactionId}:${t.action??"automatic"}`,l);try{let e=await this.store.commit({records:u,recordReplacements:h,events:[],relationships:m,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:w,committedAt:c});await this.refreshIndex(e)}catch(e){if(!(e instanceof Error&&e.message.includes("Transaction already exists")))throw e}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let t;try{t=d(JSON.parse(await A(E(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let i=await this.store.load(),r=i.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status),a=i.bundle.records.find(e=>"participant"===e.recordType&&"ai"===e.kind&&"active"===e.status)??r;if(!a)return{status:"not_ready",relationships:0,explanations:0};let n=i.bundle.records.find(e=>"subject"===e.recordType&&"project"===e.subjectType);if(!n)return{status:"not_ready",relationships:0,explanations:0};let o=i.bundle.manifest.projectId,s=i.bundle.records.filter(e=>"advisory_explanation"===e.recordType),c=new Map(s.flatMap(e=>{let t=K(e);return t?[[t,e]]:[]})),l=new Map([...[...c].map(([e,t])=>[e,t.id]),...t.explanations.filter(e=>!c.has(e.id)).map(t=>[t.id,e(o,"imprint-explanation",t.id,Date.parse(t.createdAt))])]),p=[],u=[],h=new Set(t.explanations.map(e=>e.id));for(let e of t.explanations){let i=c.get(e.id);if(!i){p.push({id:l.get(e.id),schemaVersion:1,projectId:o,createdAt:e.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:e.id,uri:F}],recordType:"advisory_explanation",kind:e.kind,state:e.state,statement:e.statement,rationale:e.rationale,scope:structuredClone(e.scope),subjectIds:[n.id],evidenceIds:[],concreteBindings:Q(t,e.id),supersededById:e.supersededBy?l.get(e.supersededBy):void 0,updatedAt:e.updatedAt});continue}let r={...structuredClone(i),kind:e.kind,state:e.state,statement:e.statement,rationale:e.rationale,scope:structuredClone(e.scope),concreteBindings:Q(t,e.id),supersededById:e.supersededBy?l.get(e.supersededBy):void 0,updatedAt:e.updatedAt},s=e=>JSON.stringify({kind:e.kind,state:e.state,statement:e.statement,rationale:e.rationale,scope:e.scope,concreteBindings:e.concreteBindings,supersededById:e.supersededById,updatedAt:e.updatedAt});s(i)!==s(r)&&u.push(r)}for(let[e,i]of c)h.has(e)||"retired"===i.state||u.push({...structuredClone(i),state:"retired",supersededById:void 0,updatedAt:t.updatedAt});let m=new Set(i.bundle.tombstones.flatMap(e=>"relationship"===e.objectType?[e.objectId]:[])),f=new Map(i.bundle.relationships.flatMap(e=>{if(m.has(e.id))return[];let t=e.sourceRefs.find(e=>"external"===e.kind&&e.uri===U)?.id;return t?[[t,e]]:[]})),y=[],I=new Set;for(let i of t.relations){let t=X(i.type);if(!t||i.toStoreId)continue;let r=l.get(i.fromId),n=l.get(i.toId);if(!r||!n)continue;let s=f.get(i.id);s&&s.relationshipType===t&&"advisory_explanation"===s.from.entityType&&s.from.entityId===r&&"advisory_explanation"===s.to.entityType&&s.to.entityId===n||(s&&I.add(i.id),y.push({id:e(o,"imprint-relation",`${i.id}:${t}:${r}:${n}`,Date.parse(i.createdAt)),schemaVersion:1,projectId:o,createdAt:i.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:i.id,uri:U}],recordType:"relationship",relationshipType:t,from:{entityType:"advisory_explanation",entityId:r},to:{entityType:"advisory_explanation",entityId:n},reason:i.rationale||"The Imprint graph connected these explanations."}))}let w=new Set(t.relations.map(e=>e.id)),v=r?[...f].filter(([e])=>!w.has(e)||I.has(e)).map(([,i])=>({id:e(o,"imprint-relationship-tombstone",i.id,Date.parse(t.updatedAt)),schemaVersion:1,projectId:o,objectId:i.id,objectType:"relationship",deletedAt:t.updatedAt,deletedById:r.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!(p.length||u.length||y.length||v.length))return{status:"no_change",relationships:0,explanations:0,headSequence:i.report.headSequence};let g=t.updatedAt,j=e(o,"imprint-graph-sync",t.head.hash??String(t.head.sequence),Date.parse(g));try{let e=await this.store.commit({records:p,recordReplacements:u,events:[],relationships:y,artifacts:[],tombstones:v,projectionUpdates:[]},{transactionId:j,committedAt:g});return await this.refreshIndex(e),{status:"synced",relationships:y.length+v.length,explanations:p.length+u.length,headSequence:e.report.headSequence}}catch(e){if(!(e instanceof Error&&e.message.includes("Transaction already exists")))throw e;return{status:"no_change",relationships:0,explanations:0,headSequence:i.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let i={};for(let e of t.bundle.records)i[e.recordType]=(i[e.recordType]??0)+1;return{status:e,journal:t.report,records:i,openFreshnessSignals:t.bundle.records.filter(e=>"freshness_signal"===e.recordType&&"open"===e.state).length,unavailableEvidence:t.bundle.records.filter(e=>"evidence"===e.recordType&&"available"!==e.availability).length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),i=new Set(t.records.flatMap(e=>"model_projection"===e.recordType&&"applied"===e.state?e.coverage.filter(e=>"projected"===e.status).map(e=>e.decisionId):[])),r=new Set(t.relationships.flatMap(e=>"contradicts"===e.relationshipType&&"decision"===e.from.entityType&&"decision"===e.to.entityType?[e.from.entityId,e.to.entityId]:[])),a=new Set(t.records.flatMap(e=>"freshness_signal"===e.recordType&&"open"===e.state&&"decision"===e.target.entityType?[e.target.entityId]:[]));return t.records.filter(e=>"decision"===e.recordType&&"active"===e.state&&!i.has(e.id)&&!r.has(e.id)&&!a.has(e.id)).sort((e,t)=>t.createdAt.localeCompare(e.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(e=>"decision"===e.recordType&&"active"===e.state?[e.id]:[])),i=new Map;for(let r of e.records.filter(e=>"model_entry"===e.recordType).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)))r.decisionIds.some(e=>t.has(e))&&i.set(r.key,r);return[...i.values()]}async getImprintView(e=[],t){if(!(await this.status()).initialized)return{head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]};let i=await this.store.load(),r=i.bundle.records.filter(e=>"advisory_explanation"===e.recordType),a=new Map(r.map(e=>[e.id,e])),n=new Map(r.flatMap(e=>{let t=K(e);return t?[[t,e.id]]:[]})),o=new Set(e.map(e=>n.get(e)??e)),s=new Map(i.bundle.records.flatMap(e=>"participant"===e.recordType?[[e.id,e.kind]]:[])),d=new Map(i.bundle.records.flatMap(e=>"evidence"===e.recordType?[[e.id,e]]:[])),c=new Set(i.bundle.tombstones.flatMap(e=>"relationship"===e.objectType?[e.objectId]:[])),l=new Set(["expresses","operationalizes","excepts"]),p={testing:0,emerging:1,grounded:2,challenged:3,retired:4},u=r.map(e=>{let n=e.evidenceIds.flatMap(e=>{let t=d.get(e);if(!t)return[];let i=t.sourceRefs.find(e=>"thread"===e.kind)?.id,r=t.sourceRefs.find(e=>"message"===e.kind)?.id,a="judgment"===t.kind||"user_feedback"===t.kind||"project_state"===t.kind?t.kind:"other",n=s.get(t.participantId)??"unknown";return[{id:t.id,kind:a,summary:t.summary,createdAt:t.createdAt,participantKind:n,threadId:i,jobId:r}]}).sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),p=i.bundle.relationships.flatMap(t=>{if(c.has(t.id))return[];if(!l.has(t.relationshipType))return[];let i="advisory_explanation"===t.from.entityType&&t.from.entityId===e.id&&"advisory_explanation"===t.to.entityType,r="advisory_explanation"===t.to.entityType&&t.to.entityId===e.id&&"advisory_explanation"===t.from.entityType;if(!i&&!r)return[];let n=i?t.to.entityId:t.from.entityId,o=a.get(n);return o?[{id:t.id,type:"excepts"===t.relationshipType?"excepts":"expresses",direction:i?"outgoing":"incoming",explanationId:o.id,statement:o.statement,rationale:t.reason}]:[]}),u=[...(e.supersededById?[e.supersededById]:[]).flatMap(t=>{let i=a.get(t);return i?[{id:`supersedes:${e.id}:${i.id}`,type:"supersedes",direction:"incoming",explanationId:i.id,statement:i.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(t=>t.supersededById===e.id?[{id:`supersedes:${t.id}:${e.id}`,type:"supersedes",direction:"outgoing",explanationId:t.id,statement:t.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],h=[...new Set([...e.sourceRefs.flatMap(e=>"thread"===e.kind?[e.id]:[]),...n.flatMap(e=>e.threadId?[e.threadId]:[])])].filter(e=>!t||t.has(e));return{id:e.id,kind:e.kind,state:e.state,statement:e.statement,rationale:e.rationale,scope:structuredClone(e.scope),createdAt:e.createdAt,updatedAt:e.updatedAt,evidenceCount:n.length,recentEvidence:n.slice(0,4),concrete:e.concreteBindings.map(e=>({...structuredClone(e)})),relations:[...p,...u],sourceThreadIds:h,needsGrounding:"testing"===e.state&&o.has(e.id)}}).sort((e,t)=>Number(t.needsGrounding)-Number(e.needsGrounding)||p[e.state]-p[t.state]||t.updatedAt.localeCompare(e.updatedAt)),h={total:u.filter(e=>"retired"!==e.state).length,emerging:u.filter(e=>"emerging"===e.state).length,testing:u.filter(e=>"testing"===e.state).length,grounded:u.filter(e=>"grounded"===e.state).length,challenged:u.filter(e=>"challenged"===e.state).length,retired:u.filter(e=>"retired"===e.state).length,needsGrounding:u.filter(e=>e.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:h,explanations:u}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(e=>"decision"===e.recordType&&"active"===e.state?[e.id]:[])),i=new Map;for(let r of e.records.filter(e=>"model_entry"===e.recordType).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)))r.decisionIds.some(e=>t.has(e))&&i.set(r.key,r);let r=[...i.values()],a=e.records.filter(e=>"verification_attempt"===e.recordType);return{decisions:e.records.filter(e=>"decision"===e.recordType&&"active"===e.state).map(e=>{let t=a.filter(t=>t.targets.some(t=>"decision"===t.entityType&&t.entityId===e.id)).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0];return{id:e.id,kind:e.kind,claim:e.claim,projected:r.some(t=>t.decisionIds.includes(e.id)),verification:t?t.state:"unverified"}}),entries:r.map(e=>({id:e.id,key:e.key,value:e.value,decisionIds:e.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),i=t.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status),r=t.bundle.records.find(e=>"subject"===e.recordType&&"project"===e.subjectType);if(!i||!r)throw new Error("Canonical owner or project subject is unavailable.");let a=Date.now(),n=new Date(a).toISOString(),o=W(a),s=W(a),d=W(a),c=W(a),l=W(a),p=new Set(t.bundle.records.flatMap(t=>"model_entry"===t.recordType&&t.key===e.key?t.decisionIds:[])),u=t.bundle.records.filter(e=>"decision"===e.recordType&&"active"===e.state&&p.has(e.id)),h={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:n,participantId:i.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},m=[{subjectId:r.id,role:"governed"}],f={...h,id:o,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:m,origin:{mode:"declared",sourceText:e.claim,reviewedById:i.id}},y={...h,id:s,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:o},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},I={...h,id:d,recordType:"decision",proposalId:o,acceptanceEventId:s,acceptedById:i.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:m,noChange:!1,effectiveAt:n},w={...h,id:c,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[d],value:e.value},v={...h,id:l,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${a}`,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:n,decisionIds:[d],entryIds:[c],coverage:[{decisionId:d,status:"projected"}]},g={...h,id:W(a),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:c},to:{entityType:"decision",entityId:d},reason:"The model change is projected from the owner-confirmed decision."},j=u.map(t=>({...h,id:W(a),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:t.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),b=u.map(t=>({...h,id:W(a),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:I.id},to:{entityType:"decision",entityId:t.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),x=await this.store.commit({records:[f,I,w,v],events:[y,...j],relationships:[g,...b],artifacts:[],tombstones:[],projectionUpdates:u.map(e=>({entityType:"decision",entityId:e.id,fromState:"active",state:"superseded"}))},{transactionId:W(a),committedAt:n});return await this.refreshIndex(x),{decisionId:d,entryId:c}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),i=t.records.find(t=>"proposal"===t.recordType&&"pending"===t.state&&t.sourceRefs.some(t=>t.id===e));return i?{proposalId:i.id,claim:i.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),i=new Map(t.records.flatMap(e=>"subject"===e.recordType?[[e.id,e.label]]:[]));return t.records.filter(t=>"proposal"===t.recordType&&"pending"===t.state&&t.sourceRefs.some(t=>"thread"===t.kind&&t.id===e)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt)).map(e=>({proposalId:e.id,claim:e.claim,rationale:e.rationale,proposedKind:e.proposedKind,subjectLabels:e.subjects.flatMap(e=>{let t=i.get(e.subjectId);return t?[t]:[]})}))}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(0===e.changes.length)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),i=t.bundle.records.find(t=>"model_projection"===t.recordType&&"applied"===t.state&&t.runId===e.runId);if(i)return{projectionId:i.id,entryIds:i.entryIds,headSequence:t.report.headSequence};let r=t.bundle.records.filter(t=>"decision"===t.recordType&&e.decisionIds.includes(t.id)&&"active"===t.state);if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let a=t.bundle.records.find(e=>"participant"===e.recordType&&"human"===e.kind&&"active"===e.status);if(!a)throw new Error("No active local owner participant is available.");let n=Date.now(),o=new Date(n).toISOString(),s=W(n),d=e.changes.map(i=>{let s=i.decisionIds?.filter(t=>e.decisionIds.includes(t)),d=s?.length?s:e.decisionIds,c=[...new Set(r.filter(e=>d.includes(e.id)).flatMap(e=>e.subjects.map(e=>e.subjectId)))];return{id:W(n),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:o,participantId:a.id,sourceRefs:d.map(e=>({kind:"record",id:e})),recordType:"model_entry",key:i.path.map(String).join("."),subjectIds:c,decisionIds:d,value:i.value}}),c=new Set(d.flatMap(e=>e.decisionIds)),l={id:s,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:o,participantId:a.id,sourceRefs:e.decisionIds.map(e=>({kind:"record",id:e})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:a.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:o,decisionIds:e.decisionIds,entryIds:d.map(e=>e.id),coverage:e.decisionIds.map(t=>e.coverage?.find(e=>e.decisionId===t)??{decisionId:t,status:c.has(t)?"projected":"unprojected"})},p=d.flatMap(e=>e.decisionIds.map(i=>({id:W(n),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:o,participantId:a.id,sourceRefs:[{kind:"record",id:l.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:e.id},to:{entityType:"decision",entityId:i},reason:"The owner applied this model entry as a projection of accepted product truth."}))),u=await this.store.commit({records:[...d,l],events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:W(n),committedAt:o});return await this.refreshIndex(u),{projectionId:s,entryIds:d.map(e=>e.id),headSequence:u.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await t({...e,projectRoot:this.projectRoot})).bundle}}async loadJournalSource(){let e=await this.store.readHead(),t=`${e.checkpointSequence}:${e.checkpointHash}:${e.sequence}:${e.hash??""}`;if(this.contextualSourceCache?.headKey===t)return this.contextualSourceCache.value;let i=await this.store.load(),r={source:"journal",bundle:i.bundle,journal:i.report};return this.contextualSourceCache={headKey:t,value:r},r}async withIndexedCandidates(e,t){if("journal"!==e.source||!e.journal)return t;let i=function(e,t){let i=[...new Set(t.flatMap(t=>e.subjectIdsByValue[O(t)]??[]))];if(i.length)return{subjectIds:i,decisionIds:[...new Set(i.flatMap(t=>e.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(i.flatMap(t=>e.proposalIdsBySubject[t]??[]))]}}(await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),t.subjectHints??[]);return i?{...t,subjectIds:[...new Set([...t.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Z(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function ee(e,t){if("string"!=typeof e||!e.trim())throw new Error(`${t} must be a non-empty string.`);return e}function te(e,t,i){let r=ee(e,t);if(!i.includes(r))throw new Error(`${t} is invalid.`);return r}function ie(e){let t=Z(e),i=Z(t.authority),r=i.level,a=i.mode,n=te(r,"authority.level",["owner","delegate","contributor"]),o=te(a,"authority.mode",["local_trusted","hosted"]),s={proposalId:ee(t.proposalId,"proposalId"),participantId:ee(t.participantId,"participantId"),occurredAt:ee(t.occurredAt,"occurredAt"),authority:{level:n,mode:o,grantId:"string"==typeof i.grantId?i.grantId:void 0}};switch(t.action){case"accept":return{...s,action:"accept",eventId:ee(t.eventId,"eventId"),decisionId:ee(t.decisionId,"decisionId"),kind:te(t.kind,"kind",["principle","preference","rule","constraint"]),reason:ee(t.reason,"reason"),rationale:"string"==typeof t.rationale?t.rationale:void 0};case"reject":return{...s,action:"reject",eventId:ee(t.eventId,"eventId"),reason:ee(t.reason,"reason")};case"defer":{let e=Z(t.context);if(!Array.isArray(e.subjectIds)||!Array.isArray(e.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...s,action:"defer",eventId:ee(t.eventId,"eventId"),reason:"string"==typeof t.reason?t.reason:void 0,context:{taskContext:"string"==typeof e.taskContext?e.taskContext:void 0,subjectIds:e.subjectIds.map(e=>ee(e,"subjectId")),resurfaceWhen:e.resurfaceWhen.map(e=>te(e,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:"string"==typeof e.revisitAfter?e.revisitAfter:void 0}}}case"edit_and_accept":if(!Array.isArray(t.subjects))throw new Error("subjects must be an array.");return{...s,action:"edit_and_accept",withdrawalEventId:ee(t.withdrawalEventId,"withdrawalEventId"),replacementProposalId:ee(t.replacementProposalId,"replacementProposalId"),acceptanceEventId:ee(t.acceptanceEventId,"acceptanceEventId"),decisionId:ee(t.decisionId,"decisionId"),relationshipId:ee(t.relationshipId,"relationshipId"),claim:ee(t.claim,"claim"),kind:te(t.kind,"kind",["principle","preference","rule","constraint"]),subjects:t.subjects.map(e=>{let t=Z(e);return{subjectId:ee(t.subjectId,"subjectId"),role:te(t.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:"string"==typeof t.subjectSemantics?t.subjectSemantics:void 0,rationale:"string"==typeof t.rationale?t.rationale:void 0,reason:ee(t.reason,"reason")};default:throw new Error("Unsupported owner review action.")}}function re(e){let t=Z(e),i=(e,t)=>{if(void 0!==e){if(!Array.isArray(e))throw new Error(`${t} must be an array.`);return e.map(e=>ee(e,t))}},r=(e,t)=>{if(void 0!==e){if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error(`${t} must be a positive number.`);return e}},a=void 0===t.resurface?void 0:Z(t.resurface);if(void 0!==t.generatedAt&&("string"!=typeof t.generatedAt||Number.isNaN(Date.parse(t.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:"string"==typeof t.action?t.action:void 0,text:"string"==typeof t.text?t.text:void 0,subjectIds:i(t.subjectIds,"subjectIds"),subjectHints:i(t.subjectHints,"subjectHints"),maxPackets:r(t.maxPackets,"maxPackets"),maxEstimatedTokens:r(t.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:"string"==typeof t.generatedAt?t.generatedAt:void 0,resurface:a?{differentAction:!0===a.differentAction,newEvidence:!0===a.newEvidence,newConflict:!0===a.newConflict,ownerRequested:!0===a.ownerRequested}:void 0}}export{i as a,r as b,o as c,s as d,d as e,j as f,k as g,Y as h,ie as i,re as j};
@@ -1 +1 @@
1
- "use client";import{i as e,g as t,a as r}from"./chunk-AGCS65LT.mjs";import{b as n}from"./chunk-SUAHDXJZ.mjs";var a=new Set;function o(e,t){let n=new URL(e).origin;"websocket"===t&&new URL(e).pathname!==r?a.add(n):a.delete(n)}function i(t){return a.has(new URL(t).origin)?new s(t,!0):e(t)?new s(t):new EventSource(t)}var s=class{constructor(e,t=!1){this.readyState=0,this.onerror=null,this.controller=new AbortController,this.listeners=new Map,this.fail=()=>{this.controller.signal.aborted||(this.readyState=2,this.controller.abort(),this.emit("error",""),this.onerror?.call(this,new Event("error")))},typeof document<"u"&&document.addEventListener("resume",this.fail,{signal:this.controller.signal}),this.read(e,t)}addEventListener(e,t){let r=this.listeners.get(e)??new Set;r.add(t),this.listeners.set(e,r)}close(){this.readyState=2,this.controller.abort(),this.listeners.clear()}emit(e,t){let r=new MessageEvent(e,{data:t});for(let t of this.listeners.get(e)??[])t(r)}async read(e,t){try{if(t){let{readBridgeWebSocket:t}=await(import("./bridgeWebSocketStream-AS22Y2FP.mjs"));return void await t(e,this.controller.signal,(e,t)=>{"connected"===e&&(this.readyState=1),this.emit(e,t)})}let{readBridgeSSE:r}=await(import("./bridgeSSEStream-HUFNXYPG.mjs"));await r(e,this.controller.signal,()=>{this.readyState=1},(e,t)=>this.emit(e,t))}catch{this.fail()}}},l="http://localhost:1111",c=new Map;function d(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function u(e,r={}){return t(e,function(e={}){let t=d();if(!t)return e;let r=new Headers(e.headers);return r.set("X-Popmelt-Project-Id",t),{...e,headers:r}}(r))}async function p(e,t,r){let n=new URLSearchParams({annotationId:t,kind:r.kind,name:r.name}),a=await g(`${e}/draft-attachments?${n}`,{method:"POST",headers:{"Content-Type":r.blob.type},body:r.blob},15e3);if(!a.ok)throw new Error((await a.json().catch(()=>null))?.error||`Bridge returned ${a.status}`);return(await a.json()).attachment}async function h(e,t){0!==t.length&&await g(`${e}/draft-attachments/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:t})},5e3)}async function f(e,t){await g(`${e}/draft-attachments/${encodeURIComponent(t)}`,{method:"DELETE"},5e3)}async function w(e,t){if((c.get(e)??0)>Date.now())return null;try{let r=await g(`${e}/capture/native`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageUrl:t.url,clip:t.clip,scale:t.scale})},2500);if(!r.ok)return c.set(e,Date.now()+(404===r.status||501===r.status?6e4:1e4)),null;let n=await r.blob();return n.size>0?n:null}catch{return c.set(e,Date.now()+1e4),null}}function g(e,t={},r=15e3){let n=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r);return u(e,{...t,signal:n.signal}).finally(()=>clearTimeout(a))}async function m(e=l){try{let t=await g(`${e}/ui-preferences`,{},5e3);return t.ok?await t.json():null}catch{return null}}async function y(e,t){try{let r=await g(`${e}/ui-preferences`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:t})},5e3);return r.ok?await r.json():null}catch{return null}}async function $(e=l,t){try{let r=t?`?refresh=${encodeURIComponent(t)}`:"",n=await g(`${e}/capabilities${r}`,{},t?35e3:5e3);return n.ok?await n.json():null}catch{return null}}async function b(e,t,r="/status"){let n=new AbortController,a=setTimeout(()=>n.abort(),t);try{let t=await u(`${e}${r}`,{signal:n.signal});if(!t.ok)return null;let a=await t.json();return o(e,a.eventTransport),a}catch{return null}finally{n.abort(),clearTimeout(a)}}async function I(e=l){return b(e,2e3)}async function j(e){return b(`http://localhost:${e}`,500,"/status?discovery=1")}async function S(e){return I(e)}async function k(e,t){if(typeof location<"u"&&e&&(e===location.origin+r||n(e??""))){let r=await S(e);return t&&r?.projectId===t?{url:e,port:Number(location.port)||443,projectId:t}:null}if(e&&e!==l)try{let r=new URL(e),n=await S(e);if(!n&&!t)return null;if((n||!t)&&(!n||!t||n.projectId===t)){if(n?.projectId&&!t)return null;if(n)return{url:e,port:parseInt(r.port,10)||1111,projectId:n.projectId}}}catch{if(!t)return null}let a=typeof window<"u"?window.location.origin:null,o=await j(1111);if(o){if(t&&o.projectId===t)return{url:"http://localhost:1111",port:1111,projectId:o.projectId};if(o.devOrigin&&a&&o.devOrigin===a&&!t&&!o.projectId)return{url:"http://localhost:1111",port:1111,projectId:o.projectId}}let i=function(e=1111){return Array.from({length:Math.min(32,65536-e)},(t,r)=>e+r)}().slice(1).map(e=>j(e).then(t=>t?{status:t,port:e}:null)),s=(await Promise.all(i)).filter(e=>null!==e),c=[];o&&c.push({port:1111,devOrigin:o.devOrigin,projectId:o.projectId});for(let e of s)c.push({port:e.port,devOrigin:e.status.devOrigin,projectId:e.status.projectId});if(t){let e=c.find(e=>e.projectId===t);if(e)return{url:`http://localhost:${e.port}`,port:e.port,projectId:e.projectId}}if(a){let e=c.find(e=>e.devOrigin===a&&!e.projectId);if(e)return{url:`http://localhost:${e.port}`,port:e.port,projectId:e.projectId}}return 1!==c.length||c[0].projectId?null:{url:`http://localhost:${c[0].port}`,port:c[0].port,projectId:c[0].projectId}}async function v(e=l,t,r=-1,n={}){try{let a=await g(`${e}/jobs/${t}/events?afterSeq=${r}`,{},5e3);if(404===a.status||410===a.status)return null;if(!a.ok){if(n.retryUnavailable&&(429===a.status||a.status>=500))throw new Error("Bridge history is temporarily unavailable");return null}return await a.json()}catch(e){if(n.retryUnavailable)throw e;return null}}async function T(e,t,r=l,n,a,o,i,s,c,d,u,p,h){let f=O({screenshots:e,feedbackJson:t,color:n,provider:a,model:o,pastedImages:i,sourceId:s,agentSettings:c,continuationThreadId:d,continuationSelectorAliases:u,continuationTargetBindingId:p}),w=await g(`${r}/send`,{method:"POST",body:f,...h?{headers:{"X-Popmelt-Peer-Grant":h}}:{}},3e4);if(!w.ok){let e=await w.text();throw new Error(`Bridge returned ${w.status}: ${e}`)}return w.json()}function O({screenshots:e,feedbackJson:t,color:r,provider:n,model:a,pastedImages:o,sourceId:i,agentSettings:s,continuationThreadId:l,continuationSelectorAliases:c,continuationTargetBindingId:d}){let u=new FormData;if(e instanceof Map){let t=!0;for(let[r,n]of e){let e=encodeURIComponent(r);u.append(`screenshot-${e}`,n,`screenshot-${e}.webp`),t&&(u.append("screenshot",n,"screenshot.webp"),t=!1)}t&&u.append("screenshot",new Blob([],{type:"image/webp"}),"screenshot.webp")}else u.append("screenshot",e,"screenshot.webp");if(u.append("feedback",t),r&&u.append("color",r),n&&u.append("provider",n),a&&u.append("model",a),function(e,t){t?.reasoningEffort&&e.append("reasoningEffort",t.reasoningEffort),t?.serviceTier&&e.append("serviceTier",t.serviceTier)}(u,s),i&&u.append("sourceId",i),l&&u.append("continuationThreadId",l),d&&u.append("continuationTargetBindingId",d),c?.length&&u.append("continuationSelectorAliases",JSON.stringify(c)),o)for(let[e,t]of o)for(let r=0;r<t.length;r++)u.append(`image-${e}-${r}`,t[r],`image-${e}-${r}.webp`);return u}async function E(e=l){let t=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});try{let r=await g(`${e}/memory/imprint-view`,{},5e3);return r.ok?r.json():t()}catch{return t()}}function P(e){return new Promise(t=>setTimeout(t,e))}async function B(e=l,t,r=15e3){let n=Date.now();try{let t=await g(`${e}/restart`,{method:"POST"},5e3);if(!t.ok){let e=await t.text().catch(()=>"");return{ok:!1,error:e?`Bridge restart returned ${t.status}: ${e}`:`Bridge restart returned ${t.status}`,elapsedMs:Date.now()-n}}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"Bridge restart request failed",elapsedMs:Date.now()-n}}let a=null,o=e,i=d();for(;Date.now()-n<r;){if(await P(350),a=await I(o),!a?.ok&&i){let t=await k(e,i);t?.url&&(o=t.url,a=await I(o))}if(a?.ok&&(!i||a.projectId===i)&&(!t||a.version===t))return{ok:!0,status:a,elapsedMs:Date.now()-n,bridgeUrl:o}}let s=t?` with version ${t}`:"";return a?.ok&&t&&a.version!==t?{ok:!1,error:`Bridge is running version ${a.version??"unknown"}, but this page expects ${t}. Refresh the page to load the current package. If the mismatch remains, rebuild or update the package used by the bridge, then restart it.`,status:a,elapsedMs:Date.now()-n}:{ok:!1,error:`Bridge did not come back${s} within ${Math.round(r/1e3)}s`,status:a,elapsedMs:Date.now()-n}}async function U(e=l){return(await B(e)).ok}async function C(e,t,r=l,n,a,o,i,s,c,d){let u,p=`${r}/reply`;if(i&&i.length>0){let r=new FormData,l=new Blob([new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,10,73,68,65,84,120,156,98,0,0,0,2,0,1,229,39,222,252,0,0,0,0,73,69,78,68,174,66,96,130])],{type:"image/png"});r.append("screenshot",l,"screenshot.png"),r.append("feedback",JSON.stringify({threadId:e,reply:t,color:n,provider:a,model:o,sourceId:s,...c,...d}));for(let e=0;e<i.length;e++)r.append(`image-reply-${e}`,i[e],`reply-image-${e}.webp`);u={method:"POST",body:r}}else u={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:e,reply:t,color:n,provider:a,model:o,sourceId:s,...c,...d})};let h=await g(p,u,3e4);if(!h.ok){let e=await h.text();throw new Error(`Bridge returned ${h.status}: ${e}`)}return h.json()}async function D(e,t=l,r=!1){let n=await g(`${t}/thread/${encodeURIComponent(e)}/archive${r?"?cancelQueued=true":""}`,{method:"POST"},15e3);if(!n.ok&&404!==n.status){let e=await n.text();throw new Error(`Bridge returned ${n.status}: ${e}`)}return n.json()}async function A(e,t=l){let r=await g(`${t}/thread/${encodeURIComponent(e)}/restore`,{method:"POST"},15e3);if(!r.ok)throw new Error(`Thread restore failed: ${r.status}`)}async function M(e=l){let t=await g(`${e}/workspace/clear`,{method:"POST"},5e3);if(!t.ok){let e=await t.text();throw new Error(`Bridge returned ${t.status}: ${e}`)}return t.json()}export{i as a,u as b,p as c,h as d,f as e,w as f,m as g,y as h,$ as i,I as j,k,v as l,T as m,O as n,E as o,B as p,U as q,C as r,D as s,A as t,M as u};
1
+ "use client";import{i as e,g as t,a as r}from"./chunk-HM6EBJVO.mjs";import{b as n}from"./chunk-SUAHDXJZ.mjs";var a=new Set;function o(e,t){let n=new URL(e).origin;"websocket"===t&&new URL(e).pathname!==r?a.add(n):a.delete(n)}function i(t){return a.has(new URL(t).origin)?new s(t,!0):e(t)?new s(t):new EventSource(t)}var s=class{constructor(e,t=!1){this.readyState=0,this.onerror=null,this.controller=new AbortController,this.listeners=new Map,this.fail=()=>{this.controller.signal.aborted||(this.readyState=2,this.controller.abort(),this.emit("error",""),this.onerror?.call(this,new Event("error")))},typeof document<"u"&&document.addEventListener("resume",this.fail,{signal:this.controller.signal}),this.read(e,t)}addEventListener(e,t){let r=this.listeners.get(e)??new Set;r.add(t),this.listeners.set(e,r)}close(){this.readyState=2,this.controller.abort(),this.listeners.clear()}emit(e,t){let r=new MessageEvent(e,{data:t});for(let t of this.listeners.get(e)??[])t(r)}async read(e,t){try{if(t){let{readBridgeWebSocket:t}=await(import("./bridgeWebSocketStream-XTHQPBPI.mjs"));return void await t(e,this.controller.signal,(e,t)=>{"connected"===e&&(this.readyState=1),this.emit(e,t)})}let{readBridgeSSE:r}=await(import("./bridgeSSEStream-2KKFO64A.mjs"));await r(e,this.controller.signal,()=>{this.readyState=1},(e,t)=>this.emit(e,t))}catch{this.fail()}}},l="http://localhost:1111",c=new Map;function d(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function u(e,r={}){return t(e,function(e={}){let t=d();if(!t)return e;let r=new Headers(e.headers);return r.set("X-Popmelt-Project-Id",t),{...e,headers:r}}(r))}async function p(e,t,r){let n=new URLSearchParams({annotationId:t,kind:r.kind,name:r.name}),a=await g(`${e}/draft-attachments?${n}`,{method:"POST",headers:{"Content-Type":r.blob.type},body:r.blob},15e3);if(!a.ok)throw new Error((await a.json().catch(()=>null))?.error||`Bridge returned ${a.status}`);return(await a.json()).attachment}async function h(e,t){0!==t.length&&await g(`${e}/draft-attachments/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:t})},5e3)}async function f(e,t){await g(`${e}/draft-attachments/${encodeURIComponent(t)}`,{method:"DELETE"},5e3)}async function w(e,t){if((c.get(e)??0)>Date.now())return null;try{let r=await g(`${e}/capture/native`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageUrl:t.url,clip:t.clip,scale:t.scale})},2500);if(!r.ok)return c.set(e,Date.now()+(404===r.status||501===r.status?6e4:1e4)),null;let n=await r.blob();return n.size>0?n:null}catch{return c.set(e,Date.now()+1e4),null}}function g(e,t={},r=15e3){let n=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r);return u(e,{...t,signal:n.signal}).finally(()=>clearTimeout(a))}async function m(e=l){try{let t=await g(`${e}/ui-preferences`,{},5e3);return t.ok?await t.json():null}catch{return null}}async function y(e,t){try{let r=await g(`${e}/ui-preferences`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:t})},5e3);return r.ok?await r.json():null}catch{return null}}async function $(e=l,t){try{let r=t?`?refresh=${encodeURIComponent(t)}`:"",n=await g(`${e}/capabilities${r}`,{},t?35e3:5e3);return n.ok?await n.json():null}catch{return null}}async function b(e,t,r="/status"){let n=new AbortController,a=setTimeout(()=>n.abort(),t);try{let t=await u(`${e}${r}`,{signal:n.signal});if(!t.ok)return null;let a=await t.json();return o(e,a.eventTransport),a}catch{return null}finally{n.abort(),clearTimeout(a)}}async function I(e=l){return b(e,2e3)}async function j(e){return b(`http://localhost:${e}`,500,"/status?discovery=1")}async function S(e){return I(e)}async function k(e,t){if(typeof location<"u"&&e&&(e===location.origin+r||n(e??""))){let r=await S(e);return t&&r?.projectId===t?{url:e,port:Number(location.port)||443,projectId:t}:null}if(e&&e!==l)try{let r=new URL(e),n=await S(e);if(!n&&!t)return null;if((n||!t)&&(!n||!t||n.projectId===t)){if(n?.projectId&&!t)return null;if(n)return{url:e,port:parseInt(r.port,10)||1111,projectId:n.projectId}}}catch{if(!t)return null}let a=typeof window<"u"?window.location.origin:null,o=await j(1111);if(o){if(t&&o.projectId===t)return{url:"http://localhost:1111",port:1111,projectId:o.projectId};if(o.devOrigin&&a&&o.devOrigin===a&&!t&&!o.projectId)return{url:"http://localhost:1111",port:1111,projectId:o.projectId}}let i=function(e=1111){return Array.from({length:Math.min(32,65536-e)},(t,r)=>e+r)}().slice(1).map(e=>j(e).then(t=>t?{status:t,port:e}:null)),s=(await Promise.all(i)).filter(e=>null!==e),c=[];o&&c.push({port:1111,devOrigin:o.devOrigin,projectId:o.projectId});for(let e of s)c.push({port:e.port,devOrigin:e.status.devOrigin,projectId:e.status.projectId});if(t){let e=c.find(e=>e.projectId===t);if(e)return{url:`http://localhost:${e.port}`,port:e.port,projectId:e.projectId}}if(a){let e=c.find(e=>e.devOrigin===a&&!e.projectId);if(e)return{url:`http://localhost:${e.port}`,port:e.port,projectId:e.projectId}}return 1!==c.length||c[0].projectId?null:{url:`http://localhost:${c[0].port}`,port:c[0].port,projectId:c[0].projectId}}async function v(e=l,t,r=-1,n={}){try{let a=await g(`${e}/jobs/${t}/events?afterSeq=${r}`,{},5e3);if(404===a.status||410===a.status)return null;if(!a.ok){if(n.retryUnavailable&&(429===a.status||a.status>=500))throw new Error("Bridge history is temporarily unavailable");return null}return await a.json()}catch(e){if(n.retryUnavailable)throw e;return null}}async function T(e,t,r=l,n,a,o,i,s,c,d,u,p,h){let f=O({screenshots:e,feedbackJson:t,color:n,provider:a,model:o,pastedImages:i,sourceId:s,agentSettings:c,continuationThreadId:d,continuationSelectorAliases:u,continuationTargetBindingId:p}),w=await g(`${r}/send`,{method:"POST",body:f,...h?{headers:{"X-Popmelt-Peer-Grant":h}}:{}},3e4);if(!w.ok){let e=await w.text();throw new Error(`Bridge returned ${w.status}: ${e}`)}return w.json()}function O({screenshots:e,feedbackJson:t,color:r,provider:n,model:a,pastedImages:o,sourceId:i,agentSettings:s,continuationThreadId:l,continuationSelectorAliases:c,continuationTargetBindingId:d}){let u=new FormData;if(e instanceof Map){let t=!0;for(let[r,n]of e){let e=encodeURIComponent(r);u.append(`screenshot-${e}`,n,`screenshot-${e}.webp`),t&&(u.append("screenshot",n,"screenshot.webp"),t=!1)}t&&u.append("screenshot",new Blob([],{type:"image/webp"}),"screenshot.webp")}else u.append("screenshot",e,"screenshot.webp");if(u.append("feedback",t),r&&u.append("color",r),n&&u.append("provider",n),a&&u.append("model",a),function(e,t){t?.reasoningEffort&&e.append("reasoningEffort",t.reasoningEffort),t?.serviceTier&&e.append("serviceTier",t.serviceTier)}(u,s),i&&u.append("sourceId",i),l&&u.append("continuationThreadId",l),d&&u.append("continuationTargetBindingId",d),c?.length&&u.append("continuationSelectorAliases",JSON.stringify(c)),o)for(let[e,t]of o)for(let r=0;r<t.length;r++)u.append(`image-${e}-${r}`,t[r],`image-${e}-${r}.webp`);return u}async function E(e=l){let t=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});try{let r=await g(`${e}/memory/imprint-view`,{},5e3);return r.ok?r.json():t()}catch{return t()}}function P(e){return new Promise(t=>setTimeout(t,e))}async function B(e=l,t,r=15e3){let n=Date.now();try{let t=await g(`${e}/restart`,{method:"POST"},5e3);if(!t.ok){let e=await t.text().catch(()=>"");return{ok:!1,error:e?`Bridge restart returned ${t.status}: ${e}`:`Bridge restart returned ${t.status}`,elapsedMs:Date.now()-n}}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"Bridge restart request failed",elapsedMs:Date.now()-n}}let a=null,o=e,i=d();for(;Date.now()-n<r;){if(await P(350),a=await I(o),!a?.ok&&i){let t=await k(e,i);t?.url&&(o=t.url,a=await I(o))}if(a?.ok&&(!i||a.projectId===i)&&(!t||a.version===t))return{ok:!0,status:a,elapsedMs:Date.now()-n,bridgeUrl:o}}let s=t?` with version ${t}`:"";return a?.ok&&t&&a.version!==t?{ok:!1,error:`Bridge is running version ${a.version??"unknown"}, but this page expects ${t}. Refresh the page to load the current package. If the mismatch remains, rebuild or update the package used by the bridge, then restart it.`,status:a,elapsedMs:Date.now()-n}:{ok:!1,error:`Bridge did not come back${s} within ${Math.round(r/1e3)}s`,status:a,elapsedMs:Date.now()-n}}async function D(e=l){return(await B(e)).ok}async function U(e,t,r=l,n,a,o,i,s,c,d){let u,p=`${r}/reply`;if(i&&i.length>0){let r=new FormData,l=new Blob([new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,10,73,68,65,84,120,156,98,0,0,0,2,0,1,229,39,222,252,0,0,0,0,73,69,78,68,174,66,96,130])],{type:"image/png"});r.append("screenshot",l,"screenshot.png"),r.append("feedback",JSON.stringify({threadId:e,reply:t,color:n,provider:a,model:o,sourceId:s,...c,...d}));for(let e=0;e<i.length;e++)r.append(`image-reply-${e}`,i[e],`reply-image-${e}.webp`);u={method:"POST",body:r}}else u={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:e,reply:t,color:n,provider:a,model:o,sourceId:s,...c,...d})};let h=await g(p,u,3e4);if(!h.ok){let e=await h.text();throw new Error(`Bridge returned ${h.status}: ${e}`)}return h.json()}async function C(e,t=l,r=!1){let n=await g(`${t}/thread/${encodeURIComponent(e)}/archive${r?"?cancelQueued=true":""}`,{method:"POST"},15e3);if(!n.ok&&404!==n.status){let e=await n.text();throw new Error(`Bridge returned ${n.status}: ${e}`)}return n.json()}async function M(e,t=l){let r=await g(`${t}/thread/${encodeURIComponent(e)}/restore`,{method:"POST"},15e3);if(!r.ok)throw new Error(`Thread restore failed: ${r.status}`)}async function A(e=l){let t=await g(`${e}/workspace/clear`,{method:"POST"},5e3);if(!t.ok){let e=await t.text();throw new Error(`Bridge returned ${t.status}: ${e}`)}return t.json()}export{i as a,u as b,p as c,h as d,f as e,w as f,m as g,y as h,$ as i,I as j,k,v as l,T as m,O as n,E as o,B as p,D as q,U as r,C as s,M as t,A as u};
@@ -1 +1 @@
1
- "use client";import{j as e}from"./chunk-TEXVTTWA.mjs";import{b as n}from"./chunk-BEGAJYOY.mjs";import{v as t,L as i}from"./chunk-OA63PYHZ.mjs";import{useState as r,useRef as a,useEffect as o,useCallback as l}from"react";import{jsx as d,jsxs as c,Fragment as u}from"react/jsx-runtime";function p(e,t,i){let[d,c]=r("idle"),u=a(!0),p=a(!1),s=`${t}/provider-${i}/${e}`;o(()=>(u.current=!0,()=>{u.current=!1}),[]);let m=l(async e=>{let t=await n(s,{method:e,cache:"no-store",signal:AbortSignal.timeout(1e4),..."POST"===e?{headers:{"Content-Type":"application/json"},body:"{}"}:{}});if(!t.ok)throw new Error("Provider action unavailable");let i=await t.json();return["pending","complete","failed","manual"].includes(i.state)?i.state:"failed"},[s]);return o(()=>{if("pending"!==d)return;let e,n=!1,t=Date.now()+6e5;async function i(){try{let r=await m("GET");if(n)return;"pending"!==r||Date.now()>=t?c("pending"===r?"failed":r):e=setTimeout(()=>{i()},1500)}catch{n||c("failed")}}return e=setTimeout(()=>{i()},1500),()=>{n=!0,clearTimeout(e)}},[d,m]),{state:d,start:async function(){if(!p.current){p.current=!0,c("opening");try{let e=await m("POST");u.current&&c(e)}catch{u.current&&c("failed")}finally{p.current=!1}}}}}function s({provider:n,bridgeUrl:a}){let{state:o,start:l}=p(n,a,"login"),[s,m]=r(!1),g="codex"===n?"Codex":"Claude",h="codex"===n?"codex login":"claude auth login",f={...e("dark"),display:"inline-flex",alignItems:"center",gap:8,font:"inherit",fontWeight:400,color:"var(--popmelt-thread-primary)",background:"var(--popmelt-thread-control)",cursor:"pointer"};return d("span",{"data-provider-sign-in":n,children:"complete"===o?c("span",{role:"status",children:["Signed in to ",g,". Send your reply to continue."]}):c(u,{children:[c("button",{type:"button",style:f,disabled:"opening"===o||"pending"===o,onClick:()=>{l()},children:["opening"===o?"Opening…":"pending"===o?`Signing in to ${g}…`:`Sign in to ${g}`,d(t,{size:14,"aria-hidden":"true"})]}),d("span",{role:"status",children:"pending"===o?" Complete sign-in in the terminal window, then return here.":"manual"===o?" Open your terminal and paste the login command.":"failed"===o?" Sign-in did not finish. Try again, or use your terminal.":" to continue."}),("manual"===o||"failed"===o)&&c("button",{type:"button",style:{...f,marginLeft:6},onClick:()=>{navigator.clipboard.writeText(h).then(()=>m(!0)).catch(()=>m(!1))},"aria-label":`Copy ${g} login command`,children:[s?"Copied":h,d(i,{size:14,"aria-hidden":"true"})]})]})})}export{p as a,s as b};
1
+ "use client";import{j as e}from"./chunk-FPSR4NAR.mjs";import{b as n}from"./chunk-OEJXPUAR.mjs";import{v as t,L as i}from"./chunk-OA63PYHZ.mjs";import{useState as r,useRef as a,useEffect as o,useCallback as l}from"react";import{jsx as d,jsxs as c,Fragment as u}from"react/jsx-runtime";function p(e,t,i){let[d,c]=r("idle"),u=a(!0),p=a(!1),s=`${t}/provider-${i}/${e}`;o(()=>(u.current=!0,()=>{u.current=!1}),[]);let m=l(async e=>{let t=await n(s,{method:e,cache:"no-store",signal:AbortSignal.timeout(1e4),..."POST"===e?{headers:{"Content-Type":"application/json"},body:"{}"}:{}});if(!t.ok)throw new Error("Provider action unavailable");let i=await t.json();return["pending","complete","failed","manual"].includes(i.state)?i.state:"failed"},[s]);return o(()=>{if("pending"!==d)return;let e,n=!1,t=Date.now()+6e5;async function i(){try{let r=await m("GET");if(n)return;"pending"!==r||Date.now()>=t?c("pending"===r?"failed":r):e=setTimeout(()=>{i()},1500)}catch{n||c("failed")}}return e=setTimeout(()=>{i()},1500),()=>{n=!0,clearTimeout(e)}},[d,m]),{state:d,start:async function(){if(!p.current){p.current=!0,c("opening");try{let e=await m("POST");u.current&&c(e)}catch{u.current&&c("failed")}finally{p.current=!1}}}}}function s({provider:n,bridgeUrl:a}){let{state:o,start:l}=p(n,a,"login"),[s,m]=r(!1),g="codex"===n?"Codex":"Claude",h="codex"===n?"codex login":"claude auth login",f={...e("dark"),display:"inline-flex",alignItems:"center",gap:8,font:"inherit",fontWeight:400,color:"var(--popmelt-thread-primary)",background:"var(--popmelt-thread-control)",cursor:"pointer"};return d("span",{"data-provider-sign-in":n,children:"complete"===o?c("span",{role:"status",children:["Signed in to ",g,". Send your reply to continue."]}):c(u,{children:[c("button",{type:"button",style:f,disabled:"opening"===o||"pending"===o,onClick:()=>{l()},children:["opening"===o?"Opening…":"pending"===o?`Signing in to ${g}…`:`Sign in to ${g}`,d(t,{size:14,"aria-hidden":"true"})]}),d("span",{role:"status",children:"pending"===o?" Complete sign-in in the terminal window, then return here.":"manual"===o?" Open your terminal and paste the login command.":"failed"===o?" Sign-in did not finish. Try again, or use your terminal.":" to continue."}),("manual"===o||"failed"===o)&&c("button",{type:"button",style:{...f,marginLeft:6},onClick:()=>{navigator.clipboard.writeText(h).then(()=>m(!0)).catch(()=>m(!1))},"aria-label":`Copy ${g} login command`,children:[s?"Copied":h,d(i,{size:14,"aria-hidden":"true"})]})]})})}export{p as a,s as b};
@@ -1 +1 @@
1
- import{c as t}from"./chunk-2WQXHUEQ.mjs";import{f as r}from"./chunk-UOK5LOPJ.mjs";import{r as e}from"./chunk-VG4ZV2OT.mjs";import{f as a}from"./chunk-6EO73WJN.mjs";async function o(o,s){let i=await a(o);if(!i||!s)return[];let n=await e(o,s);return n.length?(await Promise.all([i,...i.mountedStores].map(async e=>{try{let a=await t(e,o);if(!a)return[];let{endpoint:s,request:i}=a,m=[];for(let t of n){let a=await r(s,"/participants/read-canvas-receipt",{...i,method:"POST",body:JSON.stringify({receiptId:t})});a.response.ok&&m.push({storeId:e.storeId,receipt:a.body})}return m}catch{return[]}}))).flat():[]}export{o as a};
1
+ import{c as t}from"./chunk-FD6IIFJC.mjs";import{f as r}from"./chunk-UFUH63SR.mjs";import{r as e}from"./chunk-RALP6ENI.mjs";import{f as a}from"./chunk-6EO73WJN.mjs";async function o(o,s){let i=await a(o);if(!i||!s)return[];let n=await e(o,s);return n.length?(await Promise.all([i,...i.mountedStores].map(async e=>{try{let a=await t(e,o);if(!a)return[];let{endpoint:s,request:i}=a,m=[];for(let t of n){let a=await r(s,"/participants/read-canvas-receipt",{...i,method:"POST",body:JSON.stringify({receiptId:t})});a.response.ok&&m.push({storeId:e.storeId,receipt:a.body})}return m}catch{return[]}}))).flat():[]}export{o as a};
@@ -0,0 +1 @@
1
+ import{a as e}from"./chunk-K22VZV3V.mjs";import{d as t}from"./chunk-UIADZXVT.mjs";var i={codex:{label:"Codex",installUrl:"https://github.com/openai/codex#installing-and-running-codex-cli",installTool:"npm",installPackage:"@openai/codex",loginArgs:["login"]},claude:{label:"Claude Code",installUrl:"https://code.claude.com/docs/en/setup#install-claude-code",installTool:"npm",installPackage:"@anthropic-ai/claude-code",loginArgs:["auth","login"]},cursor:{label:"Grok Code (Cursor)",installUrl:"https://cursor.com/docs/cli/installation",installTool:"brew",installPackage:"cursor-cli",loginArgs:["login"]},opencode:{label:"OpenCode",installUrl:"https://opencode.ai/docs/",installTool:"npm",installPackage:"@opencode/cli",loginArgs:["auth","login"]},copilot:{label:"GitHub Copilot",installUrl:"https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli",installTool:"npm",installPackage:"@github/copilot",loginArgs:["login"]},omp:{label:"Oh My Pi",installUrl:"https://github.com/can1357/oh-my-pi#install",installTool:"bun",installPackage:"@oh-my-pi/pi-coding-agent",loginArgs:["setup"]}},n={...i,cloudflared:{label:"cloudflared",installUrl:"https://developers.cloudflare.com/tunnel/downloads/",installTool:"brew",installPackage:"cloudflared",loginArgs:[]}},r=e=>"cloudflared"===e?["install","cloudflared"]:"cursor"===e?["install","--cask","cursor-cli"]:["install","-g",i[e].installPackage];import{execFile as o}from"child_process";import{readFile as s}from"fs/promises";import{homedir as a}from"os";import{join as l}from"path";import{stripVTControlCharacters as d}from"util";var c={id:"",label:"Codex default",source:"cli",isDefault:!0};function h(e){return/^claude-(?:ai|code)(?:$|[-.])/i.test(e)}var p=[{id:"",label:"Claude default",source:"static"},{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:w()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:w()}],u=[c],m={id:"",label:"Default",source:"cli"},f={id:"",label:"OMP default",source:"cli"},g=/^\s*-\s+"([^"]+)"/;function y(e){let t=e.release_date??e.releaseDate,i=e.tier_rank??e.tierRank;return{..."string"==typeof t&&Number.isFinite(Date.parse(t))?{releaseDate:t}:{},..."number"==typeof i&&Number.isFinite(i)?{tierRank:i}:{},..."number"==typeof e.priority&&Number.isFinite(e.priority)?{catalogPriority:e.priority}:{}}}function v(e,t){let i=new Map(t.map(e=>[e.id,e])),n=new Map(t.map(e=>[E(e.label),e]));return e.map(e=>{if("openai-codex"!==e.upstreamProvider||(e.speedTiers?.length??0)>0)return e;let t=e.id.includes("/")?e.id.slice(e.id.indexOf("/")+1):e.id,r=((t?i.get(t):void 0)??n.get(E(e.label)))?.speedTiers?.filter(e=>["default","flex","priority"].includes(e.id));return r?.length?{...e,speedTiers:r}:e})}function w(){return["low","medium","high","xhigh","max"].map(e=>({effort:e}))}function b(e){let t=[],i=e=>{if("string"!=typeof e)return;let i=e.trim();i&&i.length<=256&&!/\s/.test(i)&&!h(i)&&t.push(i)};try{(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e;i(t.model),t.modelUsage&&"object"==typeof t.modelUsage&&!Array.isArray(t.modelUsage)&&Object.keys(t.modelUsage).forEach(i)})(JSON.parse(e))}catch{let t=!1;for(let n of e.split("\n"))if(/^\s+--model\s/.test(n)?t=!0:/^\s+-\S/.test(n)&&(t=!1),t)for(let e of n.matchAll(/['"]([^'"]+)['"]/g))/^(?:(?:opus|sonnet|haiku|fable|best|opusplan)(?:\[1m\])?|claude-[a-z0-9]+(?:[-.][a-z0-9]+)*(?:\[1m\])?)$/.test(e[1])&&i(e[1])}return N(t.map(e=>({id:e,label:k(e),source:"cli"})))}function k(e){if(!e)return"Default";let t={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},i=e.replace(/-\d{8,}$/,"");if(t[e])return t[e];if(t[i])return t[i];let n=i.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let e="sonnet"===n[1]?"Sonn":function(e){return e.charAt(0).toUpperCase()+e.slice(1)}(n[1]);return`${e}${n[2]&&n[3]?` ${n[2]}.${n[3]}`:""}${n[4]?" Fast":""}`}let r=i.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark|luna|sol|terra))?$/);if(r){let e=r[2]?`${r[1]}.${r[2]}`:r[1];return"mini"===r[3]?`Mini ${e}`:"codex"===r[3]?`Codex ${e}`:"spark"===r[3]?`Spark ${e}`:"luna"===r[3]?`GPT ${e} Luna`:"sol"===r[3]?`GPT ${e} Sol`:"terra"===r[3]?`GPT ${e} Terra`:`GPT ${e}`}return i}async function x(e="copilot"){let t=function(e){let t=[],i=!1;for(let n of e.split("\n")){if(/^\s*`model`:/.test(n)){i=!0;continue}if(i&&/^\s*`[^`]+`:/.test(n))break;if(!i)continue;let e=n.match(g);if(!e?.[1])continue;let r=e[1];t.push({id:r,label:k(r),source:"cli"})}return N([m,...t])}(await C(e,["help","config"]));return t.length>1?t:[m]}async function S(e,t){let i=d(await C(e,["models"],1e4,t)),n=[{id:"",label:"Cursor default",source:"static",isDefault:!0}];if(/^No models available for this account\./im.test(i))return n;let r=/^Available models[ \t]*\r?\n([\s\S]*)/im.exec(i)?.[1];if(void 0===r)throw new Error("Unrecognized Cursor model catalog");for(let e of r.split(/\r?\n/)){if(/^Tip:/i.test(e.trim()))break;let t=e.trim().replace(/ \((?:current|default)(?:, (?:current|default))*\)$/,""),i=/^(\S+)(?:\s+-\s+(.+))?$/.exec(t);i&&n.push({id:i[1],label:i[2]||i[1],source:"cli"})}return N(n)}async function I(e,t){let i=await C(e,["models","--standalone"],5e3,t),n=new Set(i.split(/\r?\n/).map(e=>e.trim()).filter(e=>/^[^\s/]+\/[^\s]+$/.test(e)));if(!n.size&&i.trim())throw new Error("Unrecognized OpenCode model catalog");return[{id:"",label:"OpenCode default",source:"static",isDefault:!0},...Array.from(n,e=>({id:e,label:e,source:"cli"}))]}async function A(e="omp"){let[t,i,n]=await Promise.all([C(e,["config","get","modelRoles","--json"],1e4),C(e,["config","get","defaultThinkingLevel","--json"],1e4),C(e,["models","--json"],3e4)]);return function(e,t,i){let[n]=function(e,t){let i=JSON.parse(e),n="modelRoles"===i.key&&i.value&&"object"==typeof i.value&&"default"in i.value?i.value.default:i.modelRoles?.value?.default;if("string"!=typeof n||!n.trim())return[f];let r,o=n.trim(),s=o.split("/").pop()||o;if(t){let e=JSON.parse(t);"defaultThinkingLevel"===e.key&&"string"==typeof e.value&&e.value.trim()&&(r=e.value.trim())}return[{id:"",label:k(s),source:"cli",...r?{defaultReasoningLevel:r}:{}}]}(e,t),r=function(e){let t=JSON.parse(e),i="modelRoles"===t.key&&t.value&&"object"==typeof t.value&&"default"in t.value?t.value.default:t.modelRoles?.value?.default;return"string"==typeof i&&i.trim()?i.trim():void 0}(e),o=JSON.parse(i),s=Array.isArray(o.models)?o.models:[],a=s.flatMap(e=>{let t="string"==typeof e.provider?e.provider.trim():"",i="string"==typeof e.id?e.id.trim():"",o="string"==typeof e.selector&&e.selector.trim()?e.selector.trim():t&&i?`${t}/${i}`:"";if(!t||!i||!o)return[];let s=Array.isArray(e.thinking)?e.thinking.flatMap(e=>"string"==typeof e&&e.trim()?[{effort:e.trim()}]:[]):[];return o===r?[{...n??f,...y(e),isDefault:!0,upstreamProvider:t,...s.length>0?{supportedReasoningLevels:s}:{}}]:[{id:o,...y(e),label:k(i),source:"cli",upstreamProvider:t,...s.length>0?{supportedReasoningLevels:s}:{}}]}),l=s.find(e=>("string"==typeof e.selector?e.selector.trim():"string"==typeof e.provider&&"string"==typeof e.id?`${e.provider.trim()}/${e.id.trim()}`:"")===r),d=Array.isArray(l?.thinking)?l.thinking.flatMap(e=>"string"==typeof e&&e.trim()?[{effort:e.trim()}]:[]):[],c={...n??f,isDefault:!0,...r?.includes("/")?{upstreamProvider:r.split("/")[0]}:{},...d.length>0?{supportedReasoningLevels:d}:{}};return a.some(e=>e.isDefault)?N(a):N([c,...a])}(t,i,n)}async function M(e="codex"){let t=await C(e,["debug","models"]).catch(async()=>{let e=process.env.CODEX_HOME||l(a(),".codex");return O(l(e,"models_cache.json"))});try{return N(function(e){return[c,...e.filter(e=>""!==e.id)]}(function(e){let t=JSON.parse(e);return(Array.isArray(t.models)?t.models:[]).filter(e=>void 0===e.visibility||"list"===e.visibility).sort((e,t)=>("number"==typeof e.priority?e.priority:Number.MAX_SAFE_INTEGER)-("number"==typeof t.priority?t.priority:Number.MAX_SAFE_INTEGER)).flatMap(e=>{let t="string"==typeof e.slug?e.slug:"string"==typeof e.id?e.id:"";if(!t)return[];let i="string"==typeof e.display_name&&e.display_name.trim()?e.display_name.trim():k(t),n=Array.isArray(e.supported_reasoning_levels)?e.supported_reasoning_levels.flatMap(e=>{if(!e||"object"!=typeof e)return[];let t=e;return"string"!=typeof t.effort?[]:[{effort:t.effort,..."string"==typeof t.description?{description:t.description}:{}}]}):void 0,r=Array.isArray(e.service_tiers)?e.service_tiers.flatMap(e=>{if(!e||"object"!=typeof e)return[];let t=e;return"string"!=typeof t.id?[]:[{id:t.id,label:"string"==typeof t.name?t.name:t.id,..."string"==typeof t.description?{description:t.description}:{}}]}):void 0;return[{id:t,label:i,source:"cli",...y(e),..."string"==typeof e.default_reasoning_level?{defaultReasoningLevel:e.default_reasoning_level}:{},...n&&n.length>0?{supportedReasoningLevels:n}:{},...r&&r.length>0?{speedTiers:r}:{}}]})}(t)))}catch{return u}}async function P(e="claude",t){let i=process.env.CLAUDE_CONFIG_DIR||l(a(),".claude"),n=[l(i,"stats-cache.json"),l(i,"settings.json"),...t?[l(t,".claude","settings.json"),l(t,".claude","settings.local.json")]:[]],[r,...o]=await Promise.all([C(e,["--help"]).catch(()=>""),...n.map(e=>O(e).catch(()=>""))]),s=[r,...o].flatMap(b);for(let e of["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL"])s.push(...b(JSON.stringify({model:process.env[e]})));return N([...p,...s])}function C(e,t,i=5e3,n){return new Promise((r,s)=>{o(e,t,{cwd:n,encoding:"utf-8",timeout:i},(e,t)=>{e?s(e):r(t)})})}async function O(e){return s(e,"utf-8")}function N(e){let t=new Set,i=[];for(let n of e)t.has(n.id)||(t.add(n.id),i.push(n));return i}function E(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}import{execFile as j,spawn as T}from"child_process";import{constants as _}from"fs";import{access as R,stat as L}from"fs/promises";import{join as H,resolve as D}from"path";import{homedir as $}from"os";import{stripVTControlCharacters as q}from"util";var F=32768;function J(e,t,i,n=F){return new Promise(r=>{j(e,t,{cwd:i,timeout:5e3,maxBuffer:n},(e,t,i)=>r({code:e?"number"==typeof e.code?e.code:null:0,stdout:t,stderr:i}))})}async function U(e,t){try{let i=/[/\\]/.test(e)?D(t,e):(await J("win32"===process.platform?"where.exe":"which",[e],t)).stdout.trim().split(/\r?\n/)[0];return i&&(await L(i)).isFile()?(await R(i,_.X_OK),i):null}catch{return null}}async function V(e,t){if(t)return U(t,e);let i="win32"===process.platform?"cursor-agent.exe":"cursor-agent",n=await U(i,e)??await U(H($(),".local","bin",i),e);if(n)return n;let r=await U("agent",e);if(!r)return null;let o=await J(r,["--help"],e);return 0===o.code&&/\bCursor Agent\b/i.test(o.stdout)?r:null}function z(e){return!0===e?"signed_in":!1===e?"signed_out":"unknown"}async function W(e,t,i){if("cursor"===e){let e=await J(t,["status","--format","json"],i);try{let t=z(JSON.parse(e.stdout).isAuthenticated);return"signed_in"===t&&0!==e.code?"unknown":t}catch{if(!/unknown option.*--format/i.test(e.stderr))return"unknown";let n=await J(t,["status"],i),r=q(n.stdout+"\n"+n.stderr);return/\bnot (?:logged in|authenticated)\b/i.test(r)?"signed_out":0===n.code&&/\b(?:logged in|authenticated)\b/i.test(r)?"signed_in":"unknown"}}if("opencode"===e)try{return(await I(t,i)).some(e=>e.id)?"signed_in":"signed_out"}catch{return"unknown"}if("omp"===e)return async function(e,t){let{code:i,stdout:n}=await J(e,["models","--json"],t,4194304);if(0!==i)return"unknown";try{let e=JSON.parse(n)?.models;return Array.isArray(e)?e.length?e.some(e=>"string"==typeof e?.provider&&e.provider.trim()&&"string"==typeof e.id&&e.id.trim())?"signed_in":"unknown":"signed_out":"unknown"}catch{return"unknown"}}(t,i);if("copilot"===e)return function(e,t){return new Promise(i=>{let n=T(e,["--headless","--stdio","--no-auto-update"],{cwd:t,stdio:["pipe","pipe","ignore"]}),r=Buffer.alloc(0),o=!1,s=e=>{o||(o=!0,clearTimeout(a),n.kill("SIGKILL"),i(e))},a=setTimeout(()=>s("unknown"),5e3);n.on("error",()=>s("unknown")),n.on("close",()=>s("unknown")),n.stdin.on("error",()=>s("unknown")),n.stdout.on("data",e=>{if(r=Buffer.concat([r,e]),r.length>F)return s("unknown");for(;r.length>0;){let e=r.indexOf("\r\n\r\n");if(e<0)return;let t=Number(/Content-Length:\s*(\d+)/i.exec(r.subarray(0,e).toString())?.[1]);if(!Number.isSafeInteger(t)||t<=0||t>F)return s("unknown");let i=e+4+t;if(r.length<i)return;try{let t=JSON.parse(r.subarray(e+4,i).toString());if(1===t?.id)return s(z(t.result?.isAuthenticated))}catch{return s("unknown")}r=r.subarray(i)}});let l=JSON.stringify({jsonrpc:"2.0",id:1,method:"auth.getStatus",params:{}});n.stdin.write(`Content-Length: ${Buffer.byteLength(l)}\r\n\r\n${l}`)})}(t,i);let{code:n,stdout:r,stderr:o}=await J(t,"codex"===e?["login","status"]:["auth","status","--json"],i);return null===n?"unknown":"codex"===e?0===n&&/^logged in\b/im.test(r+"\n"+o)?"signed_in":1===n&&/^not logged in\b/im.test(r+"\n"+o)?"signed_out":"unknown":G(0===n,r)}function G(e,t){try{let i=z(JSON.parse(t)?.loggedIn);return"signed_in"!==i||e?i:"unknown"}catch{return"unknown"}}function B(e,t){let{label:n,installUrl:r,loginArgs:o}=i[e];return"missing"===t?{status:"missing",nextStep:`Install the ${n} CLI using ${r} in the environment that runs the dev server, then rerun doctor.`}:"signed_out"===t?{status:"not_authenticated",nextStep:`Run ${[e,...o].join(" ")} and ask the user to complete sign-in. Then rerun doctor.`}:"signed_in"===t?{status:"authenticated",nextStep:null}:{status:"unverified",nextStep:`Run ${"codex"===e?"codex login status":"claude auth status"} in the environment that runs the dev server, resolve any CLI errors, then rerun doctor.`}}var Y="style-src 'unsafe-inline'; font-src https://popmelt.com/fonts/chillax/Chillax-Variable.woff2";function X(e,i,n=""){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="light dark"><meta name="referrer" content="no-referrer"><title>${e} · Popmelt</title><style>@font-face {\n font-family: Chillax;\n src: url('https://popmelt.com/fonts/chillax/Chillax-Variable.woff2')\n format('woff2');\n font-style: normal;\n font-weight: 200 700;\n font-display: swap;\n}\n\n:root {\n color-scheme: light dark;\n --page-background: light-dark(#eaeaea, #111);\n --page-text: light-dark(#333, #ddd);\n --secondary-text: light-dark(#626262, #a3a3a3);\n --primary-background: light-dark(#000, #fff);\n --primary-text: light-dark(#eaeaea, #000);\n --focus-ring: light-dark(#525252, #eee);\n --pill-radius: 999px;\n}\n\nbody {\n margin: 0;\n background: var(--page-background);\n color: var(--page-text);\n font:\n 16px -apple-system,\n BlinkMacSystemFont,\n system-ui,\n sans-serif;\n}\n\n[hidden] {\n display: none !important;\n}\n.pairing-screen {\n position: relative;\n box-sizing: border-box;\n display: grid;\n place-items: center;\n min-height: 100svh;\n padding-block: calc(env(safe-area-inset-top) + 7rem)\n calc(env(safe-area-inset-bottom) + min(7rem, 25svh));\n padding-inline: max(\n 1.5rem,\n env(safe-area-inset-left),\n env(safe-area-inset-right)\n );\n}\n\n.passkey-symbol {\n position: absolute;\n inset-block-start: calc(env(safe-area-inset-top) + 1.5rem);\n justify-self: center;\n width: 32px;\n height: 32px;\n color: light-dark(#000, #ddd);\n}\n\n.passkey-symbol svg {\n display: block;\n width: 100%;\n height: 100%;\n}\n\n.view-stage {\n display: grid;\n width: 100%;\n place-items: center;\n}\n\n.view-content {\n display: grid;\n justify-items: center;\n gap: 0.75rem;\n width: min(100%, 32rem);\n text-align: center;\n}\n\n.view-title {\n margin: 0;\n font:\n 500 clamp(2rem, 1.375rem + 1.7vw, 3rem) / 1.15 Chillax,\n system-ui,\n sans-serif;\n letter-spacing: -0.025em;\n}\n\n.view-note {\n margin: 0;\n color: var(--secondary-text);\n font-size: clamp(1rem, 0.9375rem + 0.25vw, 1.25rem);\n line-height: 1.5;\n}\n\n.bookmark-control {\n text-wrap: balance;\n}\n.bookmark-project {\n display: inline-block;\n max-width: 100%;\n}\n\n.bookmark-action {\n position: relative;\n inset-block-start: -2px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 4px;\n min-height: 34px;\n margin-inline-end: 4px;\n padding: 3px 10px 3px 6.5px;\n border: 0;\n border-radius: 12px;\n background: light-dark(#ddd, #242424);\n color: var(--page-text);\n font: inherit;\n font-weight: 500;\n vertical-align: middle;\n cursor: pointer;\n}\n\n.bookmark-action svg {\n flex: none;\n}\n@media (any-pointer: coarse) {\n .bookmark-action::after {\n content: '';\n position: absolute;\n inset: -5px 0;\n }\n}\n@media (hover: hover) {\n .bookmark-action:hover {\n background: light-dark(#d4d4d4, #303030);\n }\n}\n.bookmark-action:active,\n.bookmark-action[aria-expanded='true'] {\n background: light-dark(#ccc, #383838);\n}\n\n#bookmark-help {\n position: fixed;\n box-sizing: border-box;\n width: min(22rem, calc(100vw - 24px));\n max-height: calc(100dvh - 24px);\n overflow: auto;\n margin: auto;\n padding: 16px;\n border: 1px solid light-dark(#d3d3d3, #373737);\n border-radius: 20px;\n background: light-dark(#fafafa, #1c1c1c);\n color: var(--page-text);\n box-shadow: 0 12px 44px #0003;\n font:\n 1rem/1.45 -apple-system,\n BlinkMacSystemFont,\n system-ui,\n sans-serif;\n text-align: start;\n}\n#bookmark-help::backdrop {\n background: rgb(0 0 0 / 40%);\n}\n#bookmark-help header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n}\n#bookmark-help h2 {\n margin: 0;\n font:\n 500 1.375rem/1.2 Chillax,\n system-ui,\n sans-serif;\n letter-spacing: -0.02em;\n}\n.bookmark-close {\n position: relative;\n display: grid;\n place-items: center;\n flex: none;\n width: 32px;\n height: 32px;\n border: 0;\n border-radius: 50%;\n padding: 0;\n color: var(--page-text);\n background: light-dark(#e8e8e8, #303030);\n cursor: pointer;\n}\n.bookmark-close::after {\n content: '';\n position: absolute;\n inset: -6px;\n}\n.bookmark-close:focus-visible {\n outline: 2px solid var(--focus-ring);\n outline-offset: 3px;\n}\n.bookmark-steps {\n display: grid;\n gap: 14px;\n margin: 18px 0 2px;\n padding: 0;\n list-style: none;\n}\n.bookmark-steps li {\n display: flex;\n align-items: center;\n gap: 12px;\n}\n.bookmark-steps li > span {\n display: grid;\n flex: none;\n place-items: center;\n width: 32px;\n height: 32px;\n background: light-dark(#ebebeb, #2b2b2b);\n border-radius: 9px;\n}\n.bookmark-steps p,\n.bookmark-shortcut {\n margin: 0;\n color: var(--secondary-text);\n}\n.bookmark-steps strong {\n color: var(--page-text);\n font-weight: 550;\n}\n.bookmark-shortcut {\n display: none;\n}\n.bookmark-shortcut kbd {\n padding: 2px 5px;\n border: 1px solid light-dark(#ccc, #555);\n border-radius: 5px;\n font: inherit;\n color: var(--page-text);\n}\n@media (hover: hover) and (pointer: fine) {\n .bookmark-shortcut:not([hidden]) {\n display: block;\n margin: 18px 0 2px;\n }\n}\n@media (max-width: 34rem) {\n #bookmark-help {\n margin-block-end: max(12px, env(safe-area-inset-bottom));\n }\n}\n\n.primary-action {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 0.5rem;\n box-sizing: border-box;\n border-radius: var(--pill-radius);\n font: inherit;\n font-weight: 500;\n cursor: pointer;\n min-height: 3.375rem;\n padding: 0.625rem 1.5rem;\n border: 0;\n color: var(--primary-text);\n background: var(--primary-background);\n text-decoration: none;\n}\n\n.view-content .primary-action,\n.view-progress {\n margin-block-start: 0.75rem;\n}\n.primary-action svg {\n flex: none;\n}\n.primary-action:is(:disabled, [aria-disabled='true']) {\n cursor: progress;\n}\n.view-progress {\n display: grid;\n place-items: center;\n min-height: 3.375rem;\n}\n.progress-dots {\n display: inline-grid;\n grid-template-columns: 1fr 1fr 1fr;\n}\n.progress-dots > span {\n overflow: hidden;\n}\n\n@media (max-width: 34rem) {\n .view-content .primary-action {\n justify-self: stretch;\n }\n}\n\n.visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .primary-action {\n transition: scale 120ms ease-out;\n }\n .progress-spinner {\n animation: progress-spin 800ms linear infinite;\n }\n .progress-dots {\n animation: progress-dots 1800ms step-end infinite;\n }\n\n @media (hover: hover) {\n .primary-action:not(:disabled, [aria-disabled='true']):hover {\n scale: 1.02;\n }\n }\n\n .primary-action:not(:disabled, [aria-disabled='true']):active {\n scale: 0.99;\n }\n}\n\n@keyframes progress-spin {\n to {\n transform: rotate(1turn);\n }\n}\n\n@keyframes progress-dots {\n from {\n grid-template-columns: 0fr 0fr 0fr;\n }\n 25% {\n grid-template-columns: 1fr 0fr 0fr;\n }\n 50% {\n grid-template-columns: 1fr 1fr 0fr;\n }\n 75%,\n to {\n grid-template-columns: 1fr 1fr 1fr;\n }\n}\n\n.primary-action:focus-visible,\n.bookmark-action:focus-visible {\n outline: 2px solid var(--focus-ring);\n outline-offset: 4px;\n}\n\n.passkey-symbol {\n cursor: grab;\n touch-action: pan-y;\n user-select: none;\n}\n</style></head>\n<body><main class="pairing-screen"><svg class="passkey-symbol" viewBox="7 7 26 26" role="img" aria-label="Popmelt logo. Drag left or right to spin."><path fill="currentColor" d="${t}"/></svg>\n<section class="view-content" aria-live="polite"><h1 class="view-title">${e}</h1>${i}</section></main>\n${n?"<script>"+n+"<\/script>":""}<script>// The device page owns one symbol for its entire lifetime.\n(() => {\n // Flatten curves to subpixel accuracy, rather than spending 24 vertices on\n // even microscopic curves. At the logo's native size one unit is one pixel.\n function flattenCubic(a, b, c, d) {\n const points = [];\n const middle = (p, q) => ({\n x: (p.x + q.x) / 2,\n y: (p.y + q.y) / 2,\n });\n const visit = (a, b, c, d, depth) => {\n const dx = d.x - a.x;\n const dy = d.y - a.y;\n const lengthSquared = dx * dx + dy * dy;\n const distance = (p) => {\n const t =\n lengthSquared === 0\n ? 0\n : Math.max(\n 0,\n Math.min(\n 1,\n ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared,\n ),\n );\n return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);\n };\n if (depth === 16 || Math.max(distance(b), distance(c)) <= 0.01) {\n points.push(d);\n return;\n }\n const ab = middle(a, b),\n bc = middle(b, c),\n cd = middle(c, d);\n const abc = middle(ab, bc),\n bcd = middle(bc, cd);\n const center = middle(abc, bcd);\n visit(a, ab, abc, center, depth + 1);\n visit(center, bcd, cd, d, depth + 1);\n };\n visit(a, b, c, d, 0);\n return points;\n }\n const pointPath = ({ x, y }) =>\n \`L\${Math.round(x * 1000) / 1000} \${Math.round(y * 1000) / 1000}\`;\n function createSurfaceProjector(surface, centerX, radius, rimY) {\n const tau = Math.PI * 2;\n const wrap = (angle) => ((angle % tau) + tau) % tau;\n // Circular order never changes. Sort and calculate each point's trig once.\n const points = surface\n .map((p) => ({\n ...p,\n angle: wrap(p.longitude),\n sin: Math.sin(p.longitude),\n cos: Math.cos(p.longitude),\n }))\n .sort((a, b) => a.angle - b.angle);\n return function projectSurface(rotation) {\n const phase = rotation % tau;\n const sin = Math.sin(phase),\n cos = Math.cos(phase);\n const edge = wrap(Math.PI / 2 - phase);\n let low = 0,\n high = points.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (points[middle].angle < edge) low = middle + 1;\n else high = middle;\n }\n let path = '';\n for (let offset = 1; offset <= points.length; offset++) {\n const p = points[(low - offset + points.length) % points.length];\n if (wrap(edge - p.angle) >= Math.PI) break;\n path += pointPath({\n x: centerX + radius * (p.sin * cos + p.cos * sin),\n y: rimY + p.height * (p.cos * cos - p.sin * sin),\n });\n }\n return path;\n };\n }\n const svg = document.querySelector('.passkey-symbol');\n const mark = svg.querySelector('path');\n const LOGO_MARK_PATH = mark.getAttribute('d');\n // Unwrap the original lower contour onto a spherical longitude profile. Every\n // point keeps its surface height as it turns, so the original silhouette comes\n // back through projection alone, with no seam-specific morph or easing.\n function createSurfaceRotation() {\n const outline = [];\n let x = 0;\n let y = 0;\n for (const [, command, values] of LOGO_MARK_PATH.matchAll(\n /([A-Z])([^A-Z]*)/g,\n )) {\n const n = (values.match(/-?\\d*\\.?\\d+/g) ?? []).map(Number);\n const startX = x;\n const startY = y;\n if (command === 'Z') continue;\n if (command === 'H') x = n[0];\n else if (command === 'V') y = n[0];\n else {\n x = n[n.length - 2];\n y = n[n.length - 1];\n }\n if (command === 'C') {\n outline.push(\n ...flattenCubic(\n { x: startX, y: startY },\n { x: n[0], y: n[1] },\n { x: n[2], y: n[3] },\n { x, y },\n ),\n );\n } else outline.push({ x, y });\n }\n // Keep the upper dome intact and unwrap only the material below its rim.\n // Including the dome's side edges would turn them into broad extra drips.\n const rimY = 24;\n const first = outline.findIndex((point) => point.y >= rimY);\n let last = first;\n while (last + 1 < outline.length && outline[last + 1].y >= rimY) last++;\n const intersect = (from, to) => ({\n x: from.x + ((to.x - from.x) * (rimY - from.y)) / (to.y - from.y),\n y: rimY,\n });\n const right = intersect(outline[first - 1], outline[first]);\n const left = intersect(outline[last], outline[last + 1]);\n const centerX = (right.x + left.x) / 2;\n const radius = (right.x - left.x) / 2;\n const lower = [right, ...outline.slice(first, last + 1), left];\n const front = lower.map((point) => {\n const longitude = Math.asin(\n Math.max(-1, Math.min(1, (point.x - centerX) / radius)),\n );\n const depth = Math.cos(longitude);\n return {\n longitude,\n height: depth > 0.00001 ? (point.y - rimY) / depth : 0,\n };\n });\n // Complete the unseen half with rounded alternating drips. Its endpoints\n // meet the original rim; these details rotate into view as real surface\n // geometry, rather than changing any front-facing silhouette over time.\n const rear = [];\n const rearHeights = [8, 6.2, 8.6, 6.5, 8];\n const insetHeights = [0, 1.4, 0.8, 1.8, 1.1, 0];\n const addCurve = (a, b, c, d) => {\n const point = (p) => ({ x: p[0] * radius, y: p[1] });\n rear.push({ longitude: a[0], height: a[1] });\n rear.push(\n ...flattenCubic(point(a), point(b), point(c), point(d)).map((p) => ({\n longitude: p.x / radius,\n height: p.y,\n })),\n );\n };\n for (const [index, height] of rearHeights.entries()) {\n const start = Math.PI / 2 + (index / rearHeights.length) * Math.PI;\n const end = start + Math.PI / rearHeights.length;\n const center = (start + end) / 2;\n const width = 0.145;\n const leftHeight = insetHeights[index];\n const rightHeight = insetHeights[index + 1];\n addCurve(\n [start, leftHeight],\n [center - width, leftHeight],\n [center - width, leftHeight + 0.7],\n [center - width, height - 1.4],\n );\n for (let step = 0; step <= 32; step++) {\n const angle = Math.PI * (1 - step / 32);\n rear.push({\n longitude: center + width * Math.cos(angle),\n height: height - 1.4 + 1.4 * Math.sin(angle),\n });\n }\n addCurve(\n [center + width, height - 1.4],\n [center + width, rightHeight + 0.7],\n [center + width, rightHeight],\n [end, rightHeight],\n );\n }\n const project = createSurfaceProjector(\n [...front, ...rear],\n centerX,\n radius,\n rimY,\n );\n const upperRight =\n \`M\${outline[0].x} \${outline[0].y}\` +\n outline.slice(1, first).map(pointPath).join('') +\n pointPath(right);\n const upperLeft =\n pointPath(left) +\n outline\n .slice(last + 1)\n .map(pointPath)\n .join('') +\n 'Z';\n return (rotation) => {\n const phase = Math.atan2(Math.sin(rotation), Math.cos(rotation));\n if (Math.abs(phase) < 1e-9) return LOGO_MARK_PATH;\n return upperRight + project(phase) + upperLeft;\n };\n }\n const NORMAL_VELOCITY = (-Math.PI * 2) / 15;\n // Client navigation replaces the header, but retains this shared motion. The\n // regular and floating headers also use one clock so neither doubles the speed.\n const motion = {\n rotation: 0,\n velocity: NORMAL_VELOCITY,\n previousTime: null,\n dragging: false,\n };\n const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');\n let frame = 0;\n const dragSensitivity = (Math.PI * 2) / 160;\n const friction = 1.8;\n let drag = null;\n let visible = false;\n const surfaceRotation = createSurfaceRotation();\n const draw = (path) => {\n mark.setAttribute('d', path);\n };\n // Restore the angle before paint, including when sign-in changes the logo's\n // surrounding button. Rendering itself stays deterministic for hydration.\n draw(surfaceRotation(motion.rotation));\n const tick = (time) => {\n const dt =\n motion.previousTime === null\n ? 0\n : Math.min((time - motion.previousTime) / 1000, 0.05);\n motion.previousTime = time;\n if (!motion.dragging) {\n // Integrate the decaying flick exactly so different refresh rates feel alike.\n const decay = Math.exp(-friction * dt);\n motion.rotation +=\n NORMAL_VELOCITY * dt +\n ((motion.velocity - NORMAL_VELOCITY) * (1 - decay)) / friction;\n motion.velocity =\n NORMAL_VELOCITY + (motion.velocity - NORMAL_VELOCITY) * decay;\n }\n motion.rotation %= Math.PI * 2;\n draw(surfaceRotation(motion.rotation));\n frame = requestAnimationFrame(tick);\n };\n const sync = () => {\n cancelAnimationFrame(frame);\n const shown = visible && !document.hidden;\n if (reducedMotion.matches) {\n motion.velocity = 0;\n if (shown) draw(surfaceRotation(motion.rotation));\n } else if (shown) {\n frame = requestAnimationFrame(tick);\n }\n if (!shown || reducedMotion.matches) motion.previousTime = null;\n };\n const onPointerDown = (event) => {\n if (motion.dragging || !event.isPrimary || event.button !== 0) return;\n svg.setPointerCapture(event.pointerId);\n drag = {\n pointerId: event.pointerId,\n x: event.clientX,\n time: event.timeStamp,\n };\n motion.dragging = true;\n motion.velocity = 0;\n svg.style.cursor = 'grabbing';\n };\n const onPointerMove = (event) => {\n if (!drag || drag.pointerId !== event.pointerId) return;\n const delta = (event.clientX - drag.x) * dragSensitivity;\n const dt = Math.max((event.timeStamp - drag.time) / 1000, 0.001);\n const blend = 1 - Math.exp(-dt / 0.035);\n motion.velocity +=\n (Math.max(-24, Math.min(24, delta / dt)) - motion.velocity) * blend;\n motion.rotation += delta;\n drag.x = event.clientX;\n drag.time = event.timeStamp;\n draw(surfaceRotation(motion.rotation));\n };\n const onPointerEnd = (event) => {\n if (!drag || drag.pointerId !== event.pointerId) return;\n // Holding still before release should stop a flick, not replay an old one.\n motion.velocity *= Math.exp(\n -Math.max(0, event.timeStamp - drag.time - 40) / 60,\n );\n if (event.type !== 'pointerup' || reducedMotion.matches)\n motion.velocity = 0;\n drag = null;\n motion.dragging = false;\n svg.style.cursor = 'grab';\n if (svg.hasPointerCapture(event.pointerId))\n svg.releasePointerCapture(event.pointerId);\n };\n svg.addEventListener('pointerdown', onPointerDown);\n svg.addEventListener('pointermove', onPointerMove);\n svg.addEventListener('pointerup', onPointerEnd);\n svg.addEventListener('pointercancel', onPointerEnd);\n svg.addEventListener('lostpointercapture', onPointerEnd);\n const observer = new IntersectionObserver(([entry]) => {\n visible = entry?.isIntersecting ?? false;\n sync();\n });\n observer.observe(svg);\n reducedMotion.addEventListener('change', sync);\n document.addEventListener('visibilitychange', sync);\n})();\n<\/script></body></html>`}function K(e,t,i,n){return X(e,'<p class="view-note" hidden></p><div class="view-progress"><svg class="progress-spinner" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" aria-hidden="true"><path d="M12 3a9 9 0 1 1-9 9"/></svg></div>',`\nconst ticket = location.hash.slice(1);\nhistory.replaceState(null,'',location.pathname);\n${n}.then(async response => {\n if (!response.ok) throw Error();\n location.replace((await response.json()).path);\n}).catch(() => {\n document.querySelector('h1').textContent = ${JSON.stringify(t)};\n const note = document.querySelector('.view-note');\n note.textContent = ${JSON.stringify(i)};\n note.hidden = false;\n document.querySelector('.view-progress').hidden = true;\n});`)}function Z(e,t){try{let i=new URL(e),n=new URL(t),r=["localhost","127.0.0.1","[::1]"];return i.origin===e&&n.origin===t&&e!==t&&["http:","https:"].includes(i.protocol)&&i.protocol===n.protocol&&i.port===n.port&&r.includes(i.hostname)&&r.includes(n.hostname)}catch{return!1}}import{randomBytes as Q,X509Certificate as ee}from"crypto";import{execFile as te}from"child_process";import{mkdtemp as ie,readFile as ne,rm as re,writeFile as oe}from"fs/promises";import*as se from"http";import*as ae from"https";import{networkInterfaces as le,tmpdir as de}from"os";import{join as ce}from"path";import{promisify as he}from"util";import pe from"./qr-encoder.mjs";var ue="/__popmelt_pair",me=6048e5,fe=()=>Q(32).toString("base64url"),ge="__Host-popmelt-wifi",ye=["accept","accept-language","accept-encoding","content-type","content-length","range","if-none-match","if-modified-since","user-agent"],ve=["origin","x-popmelt-project-id","x-popmelt-phone-proof","x-popmelt-phone-route","x-popmelt-phone-token","x-popmelt-phone-origin","x-popmelt-draft-revision","x-popmelt-source-revision"];function we(){let t=Object.entries(le()).sort(([e],[t])=>Number(/^(en0|wl|wi-fi)/i.test(t))-Number(/^(en0|wl|wi-fi)/i.test(e)));for(let[e,i]of t){if(/^(utun|tun|tap|docker|bridge|veth|vmnet|tailscale|wsl)/i.test(e))continue;let t=i?.find(e=>!e.internal&&"IPv4"===e.family&&/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e.address));if(t)return t.address}throw new e(503,"Connect this computer to Wi-Fi and try again.")}function be(e,t){if(!/^\/(?!\/)/.test(e)||/[\\#]/.test(e)||Array.from(e).some(e=>e.charCodeAt(0)<32))return null;try{let i=new URL(e,t),n=decodeURIComponent(i.pathname);return i.origin!==t||n.includes("\\")||n.includes("//")||/(?:^|\/)\./.test(n)||/%[0-9a-f]{2}/i.test(n)||/^\/(?:__|@fs(?:\/|$)|popmelt(?:\/|$))/.test(n)?null:i.pathname+i.search}catch{return null}}async function ke(t){let i=await ie(ce(de(),"popmelt-wifi-tls-"));try{let e=ce(i,"tls.cnf");return await oe(e,"[req]\nprompt=no\ndistinguished_name=name\nx509_extensions=tls\n[name]\nCN=Popmelt Wi-Fi\n[tls]\nbasicConstraints=critical,CA:FALSE\nextendedKeyUsage=serverAuth\nsubjectAltName=IP:"+t+"\n"),await he(te)("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-days","7","-config",e,"-keyout",ce(i,"key"),"-out",ce(i,"cert")],{timeout:15e3,windowsHide:!0}),{key:await ne(ce(i,"key")),cert:await ne(ce(i,"cert"))}}catch{throw new e(503,"Could not create a Wi-Fi certificate. Check that OpenSSL is installed and try again.")}finally{await re(i,{recursive:!0,force:!0})}}var xe=K("Pairing over Wi-Fi","Wi-Fi code expired","This pairing code expired or was used. Open Pairing on your computer for a new code.","fetch(location.pathname,{method:'POST',headers:{'X-Popmelt-Wifi-Ticket':ticket},cache:'no-store'})");function Se(e,t,i,n,r,o=!1){let s=e=>{t.writeHead(e,{"Cache-Control":"no-store"}),t.end()},a=e.url??"/";if(o&&(e.headers["service-worker"]||"serviceworker"===e.headers["sec-fetch-dest"]))return s(403);let l="/popmelt/phone"===a,d={};if(l){if(e.headers.origin&&e.headers.origin!==r||("POST"!==e.method||e.headers.origin!==r||!e.headers["x-popmelt-phone-proof"])&&(e.headers["x-popmelt-phone-origin"]!==r||!e.headers["x-popmelt-phone-token"]))return s(403);for(let t of ve)void 0!==e.headers[t]&&(d[t]=e.headers[t])}else{if("GET"!==e.method&&"HEAD"!==e.method)return s(405);if(be(a,r)!==a)return s(404)}for(let t of ye)void 0!==e.headers[t]&&(d[t]=e.headers[t]);let c=l?new URL("http://127.0.0.1:"+n):i,h=("https:"===c.protocol?ae:se).request({hostname:"[::1]"===c.hostname?"::1":c.hostname,port:c.port||void 0,path:l?"/phone-host":a,method:e.method,headers:d},e=>{let i={...e.headers,"referrer-policy":"no-referrer"};delete i["set-cookie"],o&&(i["cache-control"]="private, no-store",delete i["cdn-cache-control"],delete i["cloudflare-cdn-cache-control"],delete i["clear-site-data"]),t.writeHead(e.statusCode??502,i),e.on("error",()=>t.destroy()),e.pipe(t)});t.on("close",()=>h.destroy()),h.on("error",()=>t.headersSent?t.destroy():s(502)),e.pipe(h)}function Ie(t,i=we){let n,r="";function o(){let e=n;n=void 0,e?.then(e=>e.close(),()=>{})}return{close:o,async code(s,a,l){let d=new URL(s);if(!["http:","https:"].includes(d.protocol)||!["localhost","127.0.0.1","[::1]"].includes(d.hostname)||d.origin!==s||Number(d.port)===a||be(l,d.origin)!==l||l.length>2048)throw new e(400,"Open Pairing on the local development page.");let c=i(),h=c+" "+d.origin;if(n&&r!==h&&o(),!n){r=h;let e=async function(e,t,i,n){let r,o=await ke(i),s=new ee(o.cert).fingerprint256,a=new Map,l=new Map,d="";function c(){let e=Date.now();for(let[t,i]of a)i.expiresAt<=e&&a.delete(t);for(let[t,i]of l)i<=e&&l.delete(t)}function h(e){clearTimeout(r),r=setTimeout(()=>{c(),a.size||l.size?h(Math.max(...[...a.values()].map(e=>e.expiresAt),...l.values())-Date.now()):u()},e),r.unref()}let p=ae.createServer({...o,minVersion:"TLSv1.2"},async(i,r)=>{let o=e=>{r.writeHead(e,{"Cache-Control":"no-store"}),r.end()};if(i.headers.host!==d.slice(8))return o(403);let s=i.url??"/";if(!s.startsWith("/")||s.startsWith("//")||/[\\#\r\n]/.test(s))return o(400);if(r.setHeader("Referrer-Policy","no-referrer"),c(),s===ue){if(r.setHeader("Cache-Control","no-store"),"GET"===i.method)return r.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":"default-src 'none'; script-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; "+Y}),void r.end(xe);if("POST"!==i.method||i.headers.origin!==d)return o(403);let e=String(i.headers["x-popmelt-wifi-ticket"]),t=a.get(e);if(!t||!a.delete(e))return o(403);if(l.size>=32)return o(429);try{let e=await n(d);if(!p.listening)return o(503);if(l.size>=32)return o(429);let i=fe();l.set(i,Date.now()+me),h(me),r.writeHead(200,{"Content-Type":"application/json","Set-Cookie":ge+"="+i+"; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=604800"}),r.end(JSON.stringify({path:t.path+"#popmelt-phone="+e}))}catch{o(503)}return}if("/popmelt/phone"!==s){let e=i.headers.cookie?.split(";").map(e=>e.trim()).find(e=>e.startsWith(ge+"="))?.slice(20);if(!e||!l.has(e))return o(403)}Se(i,r,e,t,d)});function u(){clearTimeout(r),a.clear(),l.clear(),p.close(),p.closeAllConnections()}await new Promise((e,t)=>{p.once("error",t),p.listen(0,i,()=>{p.removeListener("error",t),e()})});let m=p.address();if(!m||"string"==typeof m)throw u(),Error("Wi-Fi listener unavailable");return d="https://"+i+":"+m.port,{server:p,close:u,code(e){c(),a.size>=32&&a.delete(a.keys().next().value);let t=fe(),i=Date.now()+6e4;a.set(t,{path:e,expiresAt:i}),l.size||h(3e5);let n=pe(0,"M");return n.addData(d+ue+"#"+t),n.make(),{image:n.createDataURL(6,24),origin:d,fingerprint:s,expiresAt:i}}}}(d,a,c,t);n=e,e.then(t=>t.server.once("close",()=>{n===e&&(n=void 0)}),()=>{n===e&&(n=void 0)})}let p=n,u=await p;if(n!==p)throw new e(409,"Wi-Fi pairing was closed. Try again.");return u.code(l)}}}import{createHash as Ae,createHmac as Me,randomBytes as Pe,randomUUID as Ce}from"crypto";import{mkdir as Oe,readFile as Ne,rename as Ee,unlink as je,writeFile as Te}from"fs/promises";import{join as _e}from"path";import{constants as Re}from"fs";import{open as Le,realpath as He}from"fs/promises";import{basename as De,join as $e,resolve as qe,sep as Fe}from"path";import{parse as Je}from"parse5";function Ue(e){if("string"!=typeof e)return;let t=e.replace(/\s+/g," ").trim();return t&&t.length<=160?t:void 0}async function Ve(e){let t=De(qe(e)),i=await He(e).catch(()=>{});if(!i)return t;async function n(e){let t=await He(e).catch(()=>{});if(!t||!t.startsWith(i+Fe))return;let n=await Le(t,Re.O_RDONLY|Re.O_NONBLOCK).catch(()=>{});if(n)try{let e=await n.stat();if(e.isFile()&&e.size<=262144){let t=Buffer.alloc(e.size),{bytesRead:i}=await n.read(t,0,t.length,0);return t.toString("utf8",0,i)}}catch{}finally{await n.close()}}async function r(e){let t=await n(e);try{return t&&JSON.parse(t)}catch{return}}let o,s,a,l=await n($e(i,"index.html"))??await n($e(i,"public/index.html")),d=l&&Je(l).childNodes.find(e=>"html"===e.nodeName),c=d&&"childNodes"in d&&d.childNodes.find(e=>"head"===e.nodeName);if(c&&"childNodes"in c)for(let e of c.childNodes){if(!("tagName"in e))continue;let t=t=>e.attrs.find(e=>e.name===t)?.value;if("meta"===e.tagName&&"application-name"===t("name")?.toLowerCase()&&(s??=Ue(t("content"))),"title"===e.tagName&&(a??=Ue(e.childNodes.map(e=>"value"in e?e.value:"").join(""))),!o&&"link"===e.tagName&&t("rel")?.toLowerCase().split(/\s+/).includes("manifest"))try{let e=new URL(t("href")??"","https://project.invalid/"),i=decodeURIComponent(e.pathname).slice(1);"https://project.invalid"===e.origin&&/\.(?:json|webmanifest)$/i.test(i)&&!i.includes("\\")&&i.split("/").every(e=>e&&!e.startsWith(".")&&"node_modules"!==e)&&(o=i)}catch{}}for(let e of new Set([o,"manifest.webmanifest","site.webmanifest","manifest.json"]))if(e)for(let t of["public","","static","app","src/app"]){let n=await r($e(i,t,e)),o=Ue(n?.name)??Ue(n?.short_name);if(o)return o}let h=await r($e(i,"package.json"));return s??Ue(h?.productName)??Ue(h?.displayName)??a??Ue(h?.name)??t}function ze(e,t,i){if(e.id!==t)throw new Error("A peer names itself");let n=i.trim();if(!n||n.length>48||[...n].some(e=>{let t=e.codePointAt(0);return t<32||127===t}))throw new Error("Peer names must be 1–48 printable characters");return{...e,name:n}}function We(e){let{selector:t,durableSelector:i,pathname:n,annotationNumber:r,changes:o}=e;return{selector:t,durableSelector:i,pathname:n,annotationNumber:r,changes:o.map(({property:e,original:t,modified:i,token:n})=>({property:e,original:t,modified:i,token:n}))}}function Ge(e,t){if((e.pathname??"")!==(t.pathname??"")||e.selector!==t.selector&&(!e.durableSelector||e.durableSelector!==t.durableSelector))return!1;let i=e=>JSON.stringify(e.map(({property:e,original:t,modified:i,token:n})=>[e,t,i,n??null]).sort((e,t)=>String(e[0]).localeCompare(String(t[0]))));return i(e.changes)===i(t.changes)}var Be={isAnnotating:!1,activeTool:"inspector",activeColor:"oklch(0.628 0.258 29)",strokeWidth:3,annotations:[],undoStack:[],redoStack:[],selectedAnnotationIds:[],lastSelectedId:null,styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]};function Ye(e){if(!e||"object"!=typeof e)return!1;let t=e;return(void 0===t.subject||null!==t.subject&&(void 0===t.subject.inserted||!0===t.subject.inserted)&&(void 0===t.subject.label||"string"==typeof t.subject.label&&t.subject.label.length<=256)&&[t.subject.adapter,t.subject.key,t.subject.canvasSelector].every(e=>"string"==typeof e&&e.length>0&&e.length<=2048))&&"string"==typeof t.pathname&&t.pathname.startsWith("/")&&t.pathname.length<=2048&&"string"==typeof t.selector&&t.selector.length>0&&t.selector.length<=2048&&"string"==typeof t.format&&t.format.length>0&&t.format.length<=128&&"string"==typeof t.value&&t.value.length<=65536}var Xe=["circle","square","diamond","hexagon"],Ke=e=>e.map((t,i)=>{let n=e=>{let i=Math.hypot(e[0]-t[0],e[1]-t[1]),n=Math.min(3,i/2)/i;return[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n].join(" ")};return`${i?"L":"M"}${n(e[(i+e.length-1)%e.length])} Q${t.join(" ")} ${n(e[(i+1)%e.length])}`}).join(" ")+" Z",Ze=(Ke([[12,1],[23,12],[12,23],[1,12]]),Ke([[12,2],[21,7],[21,17],[12,22],[3,17],[3,7]]),[210,150,270,90,330,30].map(e=>function(e){return(e%360+360)%360}(29+e))),Qe=(e,t)=>Math.min(Math.abs(e-t),360-Math.abs(e-t)),et=[.68,.5,.82,.59,.75,.43],tt=[0,5,1,2,3,4];function it(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Invalid peer color slot");let t=e%Ze.length,i=1+e-t+tt.indexOf(t);return Xe[i%Xe.length]}function nt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Invalid peer color slot");let t=Math.floor(e/Ze.length),i=et;return`oklch(${i[t%i.length]} ${.14/(1+.25*Math.floor(t/i.length))} ${Ze[e%Ze.length]})`}function rt(e){let t=new Set(e),i={circle:1,square:0,diamond:0,hexagon:0};for(let e of t)i[it(e)]++;let n=Math.min(...Object.values(i));for(let e=0;;e++){let r=Ze.filter((i,n)=>t.has(e*Ze.length+n)),o=-1,s=-1;for(let a=0;a<Ze.length;a++){let l=e*Ze.length+a;if(t.has(l)||i[it(l)]!==n)continue;let d=r.length?Math.min(...r.map(e=>Qe(Ze[a],e))):180;d>s&&(o=l,s=d)}if(-1!==o)return o}}var ot=8388608,st=100,at=(...e)=>JSON.stringify(e),lt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),dt=e=>structuredClone(e),ct=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},ht=(e,t)=>ut(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function pt(e,t){let i=new Map([...e.checkpoint?.receipts??[],...e.events].map(e=>[e.id,e])),n=[],r=[];for(let o of t){let t=i.get(o.id);if(t){if(!lt(t,o))throw new Error("Plane event identity was reused")}else e.checkpoint&&ht(o,e.checkpoint.through)<=0?r.push(o):n.push(o)}return{pending:n,superseded:r}}function ut(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function mt(e,t,i,n){let r=i.reduce((e,t)=>!e||ut(t.stamp,e)>0?t.stamp:e,t),o=Math.max(Math.floor(n),r?.time??0);return{actor:e,time:o,counter:o===r?.time?r.counter+1:0}}function ft(e){let t=new Map;for(let i of e.canvasSamples??[])t.set(at("canvas",at(i.pathname,i.selector)),i);for(let i of e.annotations){t.set(at("annotation",i.id),!0);for(let[e,n]of Object.entries(i))"id"!==e&&void 0!==n&&t.set(at("annotation",i.id,e),n)}for(let i of e.styleModifications){let e=at(i.pathname??"/",i.selector),{changes:n,...r}=i;t.set(at("styleMeta",e),r);for(let i of n)t.set(at("style",e,i.property),i)}for(let i of e.textModifications)t.set(at("text",at(i.pathname??"/",i.selector,JSON.stringify(i.textNodePath))),i);for(let i of e.domModifications)t.set(at("dom",i.id),i);for(let i of e.spacingTokenChanges)t.set(at("spacing",i.tokenPath),i);for(let i of e.spacingTokenMods)t.set(at("spacingMod",i.tokenPath),i);return t}function gt(e,t){let i=ft(e),n=ft(t);return[...new Set([...i.keys(),...n.keys()])].filter(e=>!("styleMeta"===JSON.parse(e)[0]&&!n.has(e))).filter(e=>!lt(i.get(e),n.get(e))).map(e=>({key:e,...n.has(e)?{value:dt(n.get(e))}:{}}))}function yt(e,t){let i={...t,canvasSamples:void 0,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},n=new Map;for(let[t,i]of e){let[e,r,o]=JSON.parse(t);"annotation"===e&&!o&&!0===i&&n.set(r,{id:r})}let r=new Map;for(let[t,o]of e){let[s,a,l]=JSON.parse(t);if("canvas"===s&&Ye(o)&&(i.canvasSamples??=[]).push(o),"annotation"===s&&l&&n.has(a)&&Object.defineProperty(n.get(a),l,{value:o,enumerable:!0,configurable:!0,writable:!0}),"style"===s){let t=r.get(a),i=e.get(at("styleMeta",a));if(!i)continue;t||(t={...i,changes:[]},r.set(a,t)),t.changes.push(o)}"text"===s&&i.textModifications.push(o),"dom"===s&&i.domModifications.push(o),"spacing"===s&&i.spacingTokenChanges.push(o),"spacingMod"===s&&i.spacingTokenMods.push(o)}return i.annotations=[...n.values()],i.styleModifications=[...r.values()],i.selectedAnnotationIds=t.selectedAnnotationIds.filter(e=>n.has(e)),i.lastSelectedId=i.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,i}var vt=e=>({canvasSamples:e.canvasSamples,annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function wt(e=Be){let t=[...e.undoStack.slice(-st),vt(e)],i={...dt(e),...dt(t[0]),undoStack:[],redoStack:[]},n=[];for(let e=1;e<t.length;e++){let r=`migration:${e}`;n.push({id:r,stamp:{time:0,counter:e,actor:"migration"},kind:"edit",group:r,changes:gt({...i,...t[e-1]},{...i,...t[e]})})}let r=e,o=[];for(let t of[...e.redoStack].reverse().slice(0,st)){let e=`migration:${n.length+1}`,s={...i,...t};n.push({id:e,stamp:{time:0,counter:n.length+1,actor:"migration"},kind:"edit",group:e,changes:gt(r,s)}),o.push(e),r=s}for(let e of o.reverse()){let t=`migration:${n.length+1}`;n.push({id:t,stamp:{time:0,counter:n.length+1,actor:"migration"},kind:"undo",target:e})}return{version:1,base:i,events:n}}function bt(e,t){let i=new Map(e.events.map(e=>[e.id,e]));for(let n of function(e,t){let i=pt(e,t);if(i.superseded.length)throw new ct;return i.pending}(e,t)){let e=i.get(n.id);if(e&&!lt(e,n))throw new Error("Plane event identity was reused");i.set(n.id,n)}if(i.size>8192)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...i.values()].sort(ht)}}function kt(e){if(1!==e.version&&2!==e.version)throw new Error("Unsupported plane history version");if(2===e.version&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,i=t?new Map(dt(t.cells)):ft(e.base),n=new Map(t?.writers??[]),r=dt(t?.undo??[]),o=dt(t?.redo??[]),s=(e,t)=>{let r=[],o=[...e].sort((e,t)=>JSON.parse(e.key).length-JSON.parse(t.key).length);for(let e of o){let[o,s,a]=JSON.parse(e.key);if("styleMeta"===o&&void 0===e.value)continue;let l=n.get(e.key)??"base";if(void 0!==e.guard&&l!==e.guard||"annotation"===o&&a&&!i.has(at(o,s)))continue;let d=i.get(e.key);void 0===e.value?i.delete(e.key):i.set(e.key,e.value);let c=e.restoreWriter??t;if(n.set(e.key,c),r.push({key:e.key,before:d,after:e.value,beforeWriter:l,afterWriter:c}),"annotation"===o&&!a&&void 0===e.value)for(let e of[...i.keys()]){let[t,a]=JSON.parse(e);t===o&&a===s&&(r.push({key:e,before:i.get(e),after:void 0,beforeWriter:n.get(e)??"base",afterWriter:c}),i.delete(e),n.set(e,c))}}return r};for(let t of e.events)if("edit"===t.kind){let e=s(t.changes,t.group??t.id);if(t.reset&&(r.length=0,o.length=0),!t.group||!e.length)continue;let i=r.find(e=>e.id===t.group);if(i)for(let t of e){let e=i.changes.find(e=>e.key===t.key);e?(e.after=t.after,e.afterWriter=t.afterWriter):i.changes.push(t)}else r.push({id:t.group,writer:t.group,changes:e,...t.pulledFrom&&{pulledFrom:t.pulledFrom}});o.length=0,r.length>st&&r.shift()}else{let e="undo"===t.kind?r:o,i="undo"===t.kind?o:r,n=e.findIndex(e=>e.id===t.target);if(n<0)continue;let a=e.splice(n,1)[0],l=s(a.changes.map(e=>({key:e.key,value:e.before,guard:e.afterWriter,restoreWriter:e.beforeWriter})),t.id);l.length&&i.push({id:t.id,writer:t.id,changes:l,...a.pulledFrom&&{pulledFrom:a.pulledFrom}}),i.length>st&&i.shift()}return{cells:i,writers:n,undo:r,redo:o}}function xt(e){if(e.events.length<1024)return e;let t=e.events.slice(0,-512),{cells:i,writers:n,undo:r,redo:o}=kt({...e,events:t}),s=new Set([...i.keys(),...[...r,...o].flatMap(e=>e.changes.map(e=>e.key))]),a=t.at(-1);return{version:2,...e.hostStyleDeletions?{hostStyleDeletions:dt(e.hostStyleDeletions)}:{},...e.hostDeletions?{hostDeletions:dt(e.hostDeletions)}:{},base:{...yt(new Map,e.base),undoStack:[],redoStack:[]},checkpoint:{through:{id:a.id,stamp:dt(a.stamp)},cells:dt([...i]),writers:[...n].filter(([e])=>s.has(e)),undo:r,redo:o,receipts:dt(t.slice(-512))},events:e.events.slice(-512)}}function St(e,t=e.base,i=!0){let{cells:n,writers:r,undo:o,redo:s}=kt(e),a=yt(n,t);a.styleModifications=a.styleModifications.filter(t=>!e.hostStyleDeletions?.some(e=>Ge(t,e)));let l=new Set(Object.keys(e.hostDeletions??{}));a.annotations=a.annotations.filter(e=>!l.has(e.id)),a.selectedAnnotationIds=a.selectedAnnotationIds.filter(e=>!l.has(e));let d=e=>{let i=new Map(n);for(let t of e.changes)(r.get(t.key)??"base")===t.afterWriter&&(void 0===t.before?i.delete(t.key):i.set(t.key,t.before));return vt(yt(i,t))},c=e=>e.filter(e=>e.changes.some(e=>"styleMeta"!==JSON.parse(e.key)[0]&&(r.get(e.key)??"base")===e.afterWriter&&!lt(e.before,n.get(e.key)))),h=c(o),p=c(s);return a.undoStack=i?h.map(d):[],a.redoStack=i?p.map(d):[],{state:dt(a),undo:h.map(e=>e.id),undoPullSource:h.at(-1)?.pulledFrom,redo:p.map(e=>e.id)}}var It=class extends Error{constructor(e,t){super(t),this.code=e}},At=class extends e{constructor(){super(410,"Invitation unavailable")}},Mt=2097152,Pt=15e3,Ct=2592e6,Ot=e=>Et(`popmelt-admission:${e}`),Nt=()=>Pe(32).toString("base64url"),Et=e=>Ae("sha256").update(e).digest("hex");function jt(e){let t=function(e){let t=0,i=e=>{void 0!==e&&Number.isFinite(e)&&e>t&&(t=e)};i(e?.checkpoint?.through.stamp.time);for(let t of e?.events??[])i(t.stamp.time);return t||void 0}(e.draft.history);return structuredClone({identity:e.identity,shape:"host"===e.identity.relationship?"circle":it(e.colorSlot),color:"host"===e.identity.relationship?Be.activeColor:nt(e.colorSlot),planeId:e.planeId,permission:e.permission,permissionEpoch:e.permissionEpoch,...void 0!==e.revokedAt?{revokedAt:e.revokedAt}:{},draftRevision:e.draft.revision,...void 0!==t?{lastActivityAt:t}:{}})}function Tt(e){return ze({id:"name",name:"",kind:"human",relationship:"guest"},"name",e).name}function _t(t){let i=JSON.stringify(t);if(!i||Buffer.byteLength(i)>Mt)throw new e(413,"Draft exceeds the local session limit");let n=JSON.parse(i);if(!n||void 0!==n.canvasSamples&&(!Array.isArray(n.canvasSamples)||!n.canvasSamples.every(Ye))||["annotations","styleModifications","textModifications","domModifications","spacingTokenChanges","spacingTokenMods","undoStack","redoStack","selectedAnnotationIds"].some(e=>!Array.isArray(n[e])))throw new e(400,"Expected a complete annotation state");return n}var Rt=class{constructor(e,t,i=Date.now,n=!1,r){if(this.sourceId=t,this.now=i,this.pinDraftSource=n,this.hostBasis=r,this.invites=new Map,this.runtimes=new Map,this.hostColors=new Map,this.tail=Promise.resolve(),this.closed=!1,this.projectName="",!t.trim())throw new Error("Source identity is required");this.saved={version:1,sourceId:t,members:[],projectVisibility:"private"},this.directory=_e(e,".popmelt"),this.file=_e(this.directory,"participant-sessions.json"),this.ready=Promise.all([this.load(),Ve(e).then(e=>{this.projectName=e})]).then(()=>{}),this.ready.catch(()=>{})}async load(){try{let e=JSON.parse(await Ne(this.file,"utf8"));if(1!==e.version||void 0!==e.projectVisibility&&"private"!==e.projectVisibility&&"public"!==e.projectVisibility||e.sourceId!==this.sourceId||!Array.isArray(e.members)||e.members.length>32||1!==e.members.filter(e=>"host"===e.identity.relationship).length||new Set(e.members.map(e=>e.identity.id)).size!==e.members.length||e.members.some(e=>!e.identity.id||!/^[a-f0-9]{64}$/.test(e.tokenHash)||!["human","assistant"].includes(e.identity.kind)||!["host","guest"].includes(e.identity.relationship)||!["direct","approval-required","blocked"].includes(e.permission)||!Number.isSafeInteger(e.permissionEpoch)||e.permissionEpoch<0||!Number.isSafeInteger(e.draft.revision)||e.draft.revision<0))throw new Error("Invalid saved participant sessions");if(void 0!==e.admissions&&(!Array.isArray(e.admissions)||e.admissions.length>128||new Set(e.admissions.map(e=>e.id)).size!==e.admissions.length||e.admissions.some(t=>!t||"string"!=typeof t.id||"string"!=typeof t.name||!t.name.trim()||t.name.length>48||!/^[a-f0-9]{64}$/.test(t.tokenHash)||!/^[a-f0-9]{64}$/.test(t.memberTokenHash)||!Number.isFinite(t.createdAt)||!Number.isFinite(t.expiresAt)||t.expiresAt<=t.createdAt||!["pending","granted","declined","cancelled"].includes(t.status)||"granted"===t.status&&!e.members.some(e=>e.identity.id===t.participantId))))throw new Error("Invalid saved admission requests");let t=!1,i=[];if(void 0!==e.colorIdentities&&(!Array.isArray(e.colorIdentities)||e.colorIdentities.length>512||new Set(e.colorIdentities.map(e=>e.id)).size!==e.colorIdentities.length||new Set(e.colorIdentities.map(e=>e.colorSlot)).size!==e.colorIdentities.length||e.colorIdentities.some(e=>!e||"string"!=typeof e.id||!/^[a-f0-9]{64}$/.test(e.tokenHash)||!Number.isSafeInteger(e.colorSlot)||e.colorSlot<0||e.colorSlot>=672)))throw new Error("Invalid saved peer color identities");let n=[],r=[...e.members.filter(e=>"guest"===e.identity.relationship&&void 0===e.revokedAt),...(e.admissions??[]).filter(e=>"pending"===e.status&&e.expiresAt>this.now())];for(let e of r){let t=e.colorSlot;void 0!==t&&Number.isSafeInteger(t)&&t>=0&&t<672&&!i.includes(t)?i.push(t):n.push(e)}i.push(...(e.colorIdentities??[]).map(e=>e.colorSlot));for(let e of n)e.colorSlot=rt(i),i.push(e.colorSlot),t=!0;for(let i of e.admissions??[]){if("granted"!==i.status)continue;let n=e.members.find(e=>e.identity.id===i.participantId);void 0!==n.revokedAt&&(i.status="cancelled",t=!0),i.colorSlot!==n.colorSlot&&(i.colorSlot=n.colorSlot,t=!0)}for(let i of e.members){if(!i.draft.history)continue;let e=xt(i.draft.history);e!==i.draft.history&&(i.draft={...i.draft,revision:i.draft.revision+1,history:e,state:_t(St(e,void 0,!1).state)},i.draftRevision=i.draft.revision,t=!0)}t?await this.commit(e):this.saved=e}catch(e){if("ENOENT"!==e.code)throw e}}serial(e){let t=this.tail.then(async()=>{if(await this.ready,this.closed)throw new Error("Participant sessions are closed");return e()});return this.tail=t.catch(()=>{}),t}async commit(e){await Oe(this.directory,{recursive:!0});let t=`${this.file}.${Ce()}.tmp`;try{await Te(t,JSON.stringify(e),{mode:384,flag:"wx"}),await Ee(t,this.file),this.saved=e}finally{await je(t).catch(e=>{if("ENOENT"!==e.code)throw e})}}requirePublic(){if("private"===this.saved.projectVisibility)throw new e(403,"This project is private")}member(e,t=!1){if(!e||"string"!=typeof e.token)throw new Error("Participant capability required");let i=this.saved.members.find(t=>t.identity.id===e.participantId);if(!i||i.tokenHash!==Et(e.token))throw new Error("Participant capability required");if("host"!==i.identity.relationship&&"private"===this.saved.projectVisibility){if(t)return{...i,permission:"blocked"};this.requirePublic()}return i}host(e){let t=this.member(e);if("host"!==t.identity.relationship)throw new Error("Host capability required");return t}writableRuntime(e,t=!1){let i=this.runtimes.get(JSON.stringify([e.participantId,e.runtimeId]));if(!i||i.runtimeId!==e.runtimeId||i.token!==e.token||i.expiresAt<=this.now())throw new It("runtime_expired","Runtime lease expired or replaced");let n=this.saved.members.find(t=>t.identity.id===e.participantId);if("host"!==n.identity.relationship&&this.requirePublic(),!t&&"blocked"===n.permission)throw new Error("Participant access is blocked");return n}occupiedColorSlots(){return[...Array.from(this.invites.values()).filter(e=>e.expiresAt>this.now()),...this.saved.colorIdentities??[],...this.saved.members.filter(e=>"guest"===e.identity.relationship),...(this.saved.admissions??[]).filter(e=>"pending"===e.status&&e.expiresAt>this.now())].flatMap(e=>void 0===e.colorSlot?[]:[e.colorSlot])}newMember(e,t,i=!1,n){let r={participantId:Ce(),token:Nt()};return{credential:r,member:{...i?{}:{colorSlot:n??rt(this.occupiedColorSlots())},identity:{id:r.participantId,name:Tt(e),kind:t,relationship:i?"host":"guest"},tokenHash:Et(r.token),planeId:Ce(),permission:i?"direct":"approval-required",permissionEpoch:0,draftRevision:0,draft:{revision:0,source:null,state:null}}}}createHost(e){return this.serial(async()=>{if(this.saved.members.length)throw new Error("The room already has a host");let{credential:t,member:i}=this.newMember(e,"human",!0);return await this.commit({...this.saved,members:[i]}),{credential:t,participant:jt(i)}})}recoverHost(){return this.serial(async()=>{let e=structuredClone(this.saved),t=e.members.find(e=>"host"===e.identity.relationship);if(!t)throw new Error("The room has no host");let i={participantId:t.identity.id,token:Nt()};t.tokenHash=Et(i.token),await this.commit(e);for(let[e,i]of this.runtimes)i.participantId===t.identity.id&&this.runtimes.delete(e);return i})}authenticate(e,t=!1){return this.serial(()=>jt(this.member(e,t)))}canReadNow(e){try{return"blocked"!==this.member(e).permission}catch{return!1}}checkExecution(e,t,i,n){return this.serial(()=>{let r=this.saved.members.find(t=>t.identity.id===e),o=i&&this.saved.members.some(e=>!(e.identity.id!==i||"host"!==e.identity.relationship&&"private"===this.saved.projectVisibility||"direct"!==e.permission||void 0!==e.revokedAt||void 0!==n&&e.permissionEpoch!==n));if(!r||void 0!==r.revokedAt||"host"!==r.identity.relationship&&"private"===this.saved.projectVisibility||r.permissionEpoch!==t||"blocked"===r.permission||(i?!o:"direct"!==r.permission))throw new Error("Implementation authority changed; request fresh approval");return jt(r)})}invite(e,t){return this.serial(()=>{let i=this.host(e);this.requirePublic();for(let[e,t]of this.invites)t.expiresAt<=this.now()&&this.invites.delete(e);if(this.invites.size>=32)throw new Error("Too many outstanding invitations");let n=Nt(),r=this.now()+3e5;return this.invites.set(Et(n),{expiresAt:r,issuerId:i.identity.id,sharedPath:t}),{token:n,expiresAt:r}})}availableInvite(e){this.requirePublic();let t=this.invites.get(Et(e));if(!t||t.expiresAt<=this.now())throw new At;return t}inviteAppearance(e){return e.colorSlot??=rt(this.occupiedColorSlots()),{projectName:this.projectName,color:nt(e.colorSlot),shape:it(e.colorSlot)}}visitGuestInvite(t,i,n){return this.serial(async()=>{this.requirePublic();let r=Et(i),o=Et(t),s=this.now(),a=this.saved.members.find(e=>void 0===e.revokedAt&&e.browser?.keyHash===r);if("blocked"===a?.permission)throw new e(403,"Guest access is unavailable.");let l=a?.browser?.invitations.find(e=>e.hash===o&&e.expires>s),d=(e,t)=>({participantId:e,token:Me("sha256",t).update(i).digest("base64url")});if(a?.browser&&l)return{credential:d(a.identity.id,a.browser.salt),sharedPath:l.sharedPath};let c=this.availableInvite(t);if(void 0===n)return{appearance:this.inviteAppearance(c)};if(!a&&this.saved.members.length>=32)throw new e(409,"Participant limit reached");let h=a?structuredClone(a):this.newMember(n,"human",!1,c.colorSlot).member,p=h.browser??={keyHash:r,salt:Nt(),invitations:[]},u=d(h.identity.id,p.salt);h.tokenHash=Et(u.token);let m=c.sharedPath??"/";p.invitations=p.invitations.filter(e=>e.expires>s).slice(-31),p.invitations.push({hash:o,sharedPath:m,expires:s+Ct});let f=a?this.saved.members.map(e=>e===a?h:e):[...this.saved.members,h];return await this.commit({...this.saved,members:f}),this.invites.delete(o),{credential:u,sharedPath:m}})}guestInviteAppearance(e){return this.serial(()=>this.inviteAppearance(this.availableInvite(e)))}revokeInvite(e,t){return this.serial(async()=>{this.host(e);let i=Et(t),n=this.saved.members.find(e=>e.browser?.invitations.some(e=>e.hash===i));if(n?.browser){let e={...n.browser,invitations:n.browser.invitations.filter(e=>e.hash!==i)};await this.commit({...this.saved,members:this.saved.members.map(t=>t===n?{...t,browser:e}:t)})}this.invites.delete(i)})}join(t,i,n,r,o="approval-required"){return this.serial(async()=>{let s=this.availableInvite(t);if("human"!==n&&"assistant"!==n)throw new Error("Unknown participant kind");if(this.saved.members.length>=32)throw new Error("Participant limit reached");let a=r&&this.saved.colorIdentities?.find(e=>e.id===r.id);if(r&&(!a||"string"!=typeof r.token||a.tokenHash!==Et(r.token)))throw new e(401,"Color identity capability required");if(a&&this.saved.members.some(e=>e.colorIdentityId===a.id&&void 0===e.revokedAt))throw new e(409,"This peer identity is already connected");let{credential:l,member:d}=this.newMember(i,n,!1,a?.colorSlot??s.colorSlot);return"assistant"===n&&(d.permission=o),a&&(d.colorIdentityId=a.id),await this.commit({...this.saved,members:[...this.saved.members,d],...a?{admissions:this.saved.admissions?.map(e=>e.colorIdentityId===a.id&&"pending"===e.status?{...e,status:"cancelled"}:e)}:{}}),this.invites.delete(Et(t)),{credential:l,participant:jt(d),...s.sharedPath&&{sharedPath:s.sharedPath}}})}async joinOrRequestAdmission(e,t,i){try{return{joined:await this.join(e,t,"human",i)}}catch(e){if(!(e instanceof At))throw e;return{admission:await this.requestAdmission(i,t,i)}}}snapshot(e,t){return this.serial(()=>{let i=this.member(e,!0);return"blocked"===i.permission?[jt(i)]:this.saved.members.filter(e=>void 0===e.revokedAt&&("private"!==this.saved.projectVisibility||"host"===e.identity.relationship)).map(e=>{let n=jt(e);if(t&&e.identity.id!==i.identity.id&&"blocked"!==e.permission){let i=[...new Set(e.draft.state?.annotations.flatMap(e=>e.threadId?[e.threadId]:[]))].filter(e=>!t(e));i.length&&(n.hiddenAnnotationThreadIds=i)}if("host"===e.identity.relationship){if("host"===i.identity.relationship){let e=this.now(),t=new Set([...this.runtimes.values()].filter(t=>t.expiresAt>e).map(e=>e.participantId));n.connectedGuestCount=this.saved.members.filter(e=>"guest"===e.identity.relationship&&"human"===e.identity.kind&&void 0===e.revokedAt&&"blocked"!==e.permission&&t.has(e.identity.id)).length}n.projectName=this.projectName,n.modelSelection=this.saved.modelSelection,n.projectVisibility=this.saved.projectVisibility??"public"}let r=this.hostColors.get(e.identity.id);return r?{...n,color:r}:n})})}isHost(e){return this.serial(()=>this.saved.members.some(t=>t.identity.id===e&&"host"===t.identity.relationship))}setProjectVisibility(t,i){return this.serial(async()=>{if("host"!==this.member(t).identity.relationship)throw new e(403,"Only the host can change project visibility");if("public"!==i&&"private"!==i)throw new e(400,"Invalid project visibility");if(i===(this.saved.projectVisibility??"public"))return[];let n=structuredClone(this.saved);n.projectVisibility=i;let r=n.members.filter(e=>"guest"===e.identity.relationship&&void 0===e.revokedAt);for(let e of r)e.permissionEpoch++,"private"===i&&e.browser&&(e.browser.invitations=[]);if("private"===i)for(let e of n.admissions??[])"pending"===e.status&&(e.status="cancelled");if(await this.commit(n),"private"===i){this.invites.clear();let e=new Set(r.map(e=>e.identity.id));for(let[t,i]of this.runtimes)e.has(i.participantId)&&this.runtimes.delete(t)}return r.map(jt)})}setHostModelSelection(t,i){return this.serial(async()=>{if("host"!==this.member(t).identity.relationship)throw new e(403,"Only the host can choose the model");let n=i;if(!n||!["codex","claude","copilot","omp","opencode","cursor"].includes(n.provider)||"string"!=typeof n.model||n.model.length>256||"string"!=typeof n.label||!n.label.trim()||n.label.length>256)throw new e(400,"Invalid host model selection");let r={provider:n.provider,model:n.model,label:n.label};return JSON.stringify(r)!==JSON.stringify(this.saved.modelSelection)&&await this.commit({...this.saved,modelSelection:r}),structuredClone(r)})}inheritedModelSelection(t){return this.serial(()=>{let i=this.saved.members.find(e=>e.identity.id===t);if(!i||void 0!==i.revokedAt||"host"!==i.identity.relationship&&"private"===this.saved.projectVisibility||"blocked"===i.permission)throw new e(403,"Participant access is unavailable");if("host"===i.identity.relationship)return null;if(!this.saved.modelSelection)throw new e(409,"The host must select a model before guests can run requests");return structuredClone(this.saved.modelSelection)})}admission(t){if(this.requirePublic(),!t||"string"!=typeof t.id||"string"!=typeof t.token||!/^[a-f0-9]{64}$/.test(t.token))throw new e(401,"Admission request capability required");let i=this.saved.admissions?.find(e=>e.id===t.id);if(!i||i.tokenHash!==Et(t.token))throw new e(401,"Admission request capability required");return i}admissionView(e){return{id:e.id,name:e.name,...void 0!==e.colorSlot?{color:nt(e.colorSlot),shape:it(e.colorSlot)}:{},createdAt:e.createdAt,expiresAt:e.expiresAt,status:e.expiresAt<=this.now()?"expired":e.status}}reserveAdmissionColor(t){return this.serial(async()=>{this.requirePublic(),this.validateAdmissionReceipt(t);let i=this.saved.colorIdentities?.find(e=>e.id===t.id);if(i){if(i.tokenHash!==Et(t.token))throw new e(401,"Color identity capability required");return{color:nt(i.colorSlot),shape:it(i.colorSlot)}}let n=this.saved.colorIdentities??[];if(n.length>=512){let e=new Set([...this.saved.members.flatMap(e=>void 0===e.revokedAt&&e.colorIdentityId?[e.colorIdentityId]:[]),...(this.saved.admissions??[]).flatMap(e=>e.expiresAt>this.now()&&e.colorIdentityId?[e.colorIdentityId]:[])]);n=n.filter(t=>e.has(t.id))}if(n.length>=512)throw new e(429,"Peer color identity limit reached");let r=this.saved.admissions?.find(e=>e.id===t.id);if(r&&r.tokenHash!==Et(t.token))throw new e(401,"Admission request capability required");let o=structuredClone(this.saved),s=void 0!==r?.colorSlot&&("granted"===r.status||"pending"===r.status&&r.expiresAt>this.now())?r.colorSlot:rt(this.occupiedColorSlots());return o.colorIdentities=[...n,{id:t.id,tokenHash:Et(t.token),colorSlot:s}],r&&(o.admissions.find(e=>e.id===r.id).colorIdentityId=t.id),"granted"===r?.status&&(o.members.find(e=>e.identity.id===r.participantId).colorIdentityId=t.id),await this.commit(o),{color:nt(s),shape:it(s)}})}validateAdmissionReceipt(t){if(!t||"string"!=typeof t.id||!/^[\w-]{16,64}$/.test(t.id)||"string"!=typeof t.token||!/^[a-f0-9]{64}$/.test(t.token))throw new e(400,"Invalid admission request")}requestAdmission(t,i,n){return this.serial(async()=>{if(this.requirePublic(),this.validateAdmissionReceipt(t),this.saved.admissions?.find(e=>e.id===t.id))return this.admissionView(this.admission(t));let r=n&&this.saved.colorIdentities?.find(e=>e.id===n.id);if(n&&(!r||"string"!=typeof n.token||r.tokenHash!==Et(n.token)))throw new e(401,"Color identity capability required");if(r&&(this.saved.members.some(e=>e.colorIdentityId===r.id&&void 0===e.revokedAt)||this.saved.admissions?.some(e=>e.colorIdentityId===r.id&&("granted"===e.status||"pending"===e.status&&e.expiresAt>this.now()))))throw new e(409,"This peer identity already has an active request");if(!this.saved.members.length)throw new e(409,"The host has not started this session yet");let o=(this.saved.admissions??[]).filter(e=>e.expiresAt>this.now());if(o.length>=128||o.filter(e=>"pending"===e.status).length>=32)throw new e(429,"Too many access requests. Please try again later.");let s={id:t.id,colorSlot:r?.colorSlot??rt(this.occupiedColorSlots()),...r?{colorIdentityId:r.id}:{},name:Tt(i),createdAt:this.now(),expiresAt:this.now()+864e5,status:"pending",tokenHash:Et(t.token),memberTokenHash:Et(Ot(t.token))};return await this.commit({...this.saved,admissions:[...o,s]}),this.admissionView(s)})}admissionStatus(e){return this.serial(()=>{let t=this.admission(e),i=this.admissionView(t);if("granted"===i.status){let n={participantId:t.participantId,token:Ot(e.token)},r=this.member(n);if("blocked"===r.permission)return{...i,status:"declined"};i.credential=n,i.participant=jt(r)}return i})}cancelAdmission(e){return this.serial(async()=>{let t=this.admission(e);if("pending"===t.status&&t.expiresAt>this.now()){let e=structuredClone(this.saved);return e.admissions.find(e=>e.id===t.id).status="cancelled",await this.commit(e),{...this.admissionView(t),status:"cancelled"}}return this.admissionView(t)})}listAdmissions(e){return this.serial(()=>(this.host(e),(this.saved.admissions??[]).map(e=>this.admissionView(e)).filter(e=>"pending"===e.status)))}decideAdmission(t,i,n){return this.serial(async()=>{if(this.host(t),this.requirePublic(),"grant"!==n&&"decline"!==n)throw new e(400,"Invalid admission decision");let r=structuredClone(this.saved),o=r.admissions?.find(e=>e.id===i);if(!o)throw new e(404,"Access request not found");if("pending"!==o.status||o.expiresAt<=this.now())return this.admissionView(o);if("grant"===n){if(o.colorIdentityId&&(r.members=r.members.filter(e=>!(void 0!==e.revokedAt&&e.colorIdentityId===o.colorIdentityId))),r.members.length>=32)throw new e(409,"Participant limit reached");let{member:t}=this.newMember(o.name,"human",!1,o.colorSlot);t.tokenHash=o.memberTokenHash,t.colorIdentityId=o.colorIdentityId,r.members.push(t),o.participantId=t.identity.id,o.status="granted"}else o.status="declined";return await this.commit(r),this.admissionView(o)})}planeAppBasis(t,i){return this.serial(()=>{let n;try{n=this.member(t)}catch{throw new e(403,"Plane access denied")}let r=this.saved.members.find(e=>e.identity.id===i);if("blocked"===n.permission||void 0!==n.revokedAt)throw new e(403,"Plane access denied");if(!r||"blocked"===r.permission||void 0!==r.revokedAt||"private"===this.saved.projectVisibility&&"host"!==r.identity.relationship)throw new e(404,"Plane unavailable");return{id:i,revision:r.draft.source?.revision}})}hasSharedAnnotation(e,t,i,n){return this.serial(()=>{let r=this.member(e),o=this.saved.members.find(e=>t?e.identity.id===t:"host"===e.identity.relationship);return"blocked"!==r.permission&&void 0===r.revokedAt&&void 0===o?.revokedAt&&"blocked"!==o?.permission&&!!o?.draft.state?.annotations.some(e=>"dismissed"!==e.status&&e.threadId===i&&n.has(e.id))})}readPlane(t,i,n=2){return this.serial(()=>{if("blocked"===this.member(t).permission)throw new Error("Participant access is blocked");let r=this.saved.members.find(e=>e.identity.id===i);if(!r)throw new Error("Unknown participant");if(t.participantId===i&&2===r.draft.history?.version&&2!==n)throw new e(409,"Update Popmelt to read compacted history");return structuredClone({version:1,author:r.identity,planeId:r.planeId,draft:t.participantId===i?{...r.draft,history:r.draft.history??wt(r.draft.state??Be)}:{...r.draft,history:void 0}})})}rename(e,t){return this.serial(async()=>{let i=this.member(e),n=structuredClone(this.saved),r=n.members.find(e=>e.identity.id===i.identity.id);return r.identity.name=Tt(t),await this.commit(n),jt(r)})}setPermission(e,t,i){return this.serial(async()=>{this.host(e);let n=structuredClone(this.saved),r=n.members.find(e=>e.identity.id===t);if(!r||"host"===r.identity.relationship)throw new Error("Choose a guest participant");if(void 0!==r.revokedAt)throw new Error("Participant access was removed");if(!["direct","approval-required","blocked"].includes(i))throw new Error("Unknown permission");return r.permission!==i&&(r.permission=i,r.permissionEpoch++,"blocked"===i&&r.browser&&(r.browser.invitations=[]),await this.commit(n)),jt(r)})}isRevokedNow(e){return this.saved.members.some(t=>t.identity.id===e&&void 0!==t.revokedAt)}revokeAccess(e,t){return this.serial(async()=>{this.host(e);let i=structuredClone(this.saved),n=i.members.find(e=>e.identity.id===t);if(!n||"host"===n.identity.relationship)throw new Error("Choose a guest participant");if(void 0===n.revokedAt){n.revokedAt=this.now(),n.permission="blocked",n.permissionEpoch++,n.draft={revision:n.draft.revision+1,source:null,state:null},n.draftRevision=n.draft.revision,delete n.recovery;for(let e of i.admissions??[])e.participantId===t&&"granted"===e.status&&(e.status="cancelled");await this.commit(i)}for(let[e,i]of this.runtimes)i.participantId===t&&this.runtimes.delete(e);return jt(n)})}connect(e,t,i){return this.serial(()=>{let n=this.member(e);if(!t||t.length>128)throw new Error("Runtime identity required");for(let[e,t]of this.runtimes)t.expiresAt<=this.now()&&this.runtimes.delete(e);let r=JSON.stringify([n.identity.id,t]),o=this.runtimes.get(r);if(o&&o.expiresAt>this.now()){if(o.runtimeId!==t||o.token!==i)throw new It("runtime_busy","This runtime identity is already connected");return o.expiresAt=this.now()+Pt,structuredClone(o)}if([...this.runtimes.values()].filter(e=>e.participantId===n.identity.id).length>=8)throw new It("runtime_busy","Too many active views of this plane");let s={participantId:n.identity.id,runtimeId:t,token:Nt(),expiresAt:this.now()+Pt};return this.runtimes.set(r,s),structuredClone(s)})}renew(e,t){return this.serial(()=>{let i=this.writableRuntime(e,!0);if("host"===i.identity.relationship&&void 0!==t){if("string"!=typeof t||!t.trim()||t.length>128)throw new Error("Invalid host annotation color");this.hostColors.set(i.identity.id,t)}let n=this.runtimes.get(JSON.stringify([e.participantId,e.runtimeId]));return n.expiresAt=this.now()+Pt,structuredClone(n)})}checkRuntime(e){return this.serial(()=>{this.writableRuntime(e)})}moderateAnnotations(t,i,n,r=!1){return this.serial(async()=>{let o=this.member(t),s="host"===o.identity.relationship;if(void 0!==o.revokedAt||"blocked"===o.permission||!s&&o.identity.id!==i)throw new e(403,"Only the author or host can remove peer annotations");if(!Array.isArray(n)||!n.length||n.length>256||n.some(e=>"string"!=typeof e||!e||e.length>256))throw new e(400,"Invalid annotation identities");let a=structuredClone(this.saved),l=a.members.find(e=>e.identity.id===i&&void 0===e.revokedAt);if(!l||"guest"!==l.identity.relationship)throw new e(404,"Peer plane unavailable");let d=l.draft.history??wt(l.draft.state??Be),c={...d.hostDeletions},h={...l.annotationDeletionAuthors};if(!s&&n.some(e=>Object.hasOwn(c,e)&&h[e]!==o.identity.id))throw new e(403,"Only the host can restore a host deletion");let p=St(d,void 0,!1).state,u=new Set(n),m=r?Object.values(c).filter(e=>u.has(e.id)):p.annotations.filter(e=>u.has(e.id)),f=new Set(m.flatMap(e=>e.groupId?[e.groupId]:[])),g=new Set(m.flatMap(e=>e.threadId?[e.threadId]:[])),y=r?m:p.annotations.filter(e=>u.has(e.id)||e.groupId&&f.has(e.groupId)||e.threadId&&g.has(e.threadId));if(!y.length){let t=(r?p.annotations:Object.values(c)).filter(e=>u.has(e.id));if(!t.length)throw new e(409,"Annotation changed or is no longer available");return{annotationIds:t.map(e=>e.id),threadIds:[...new Set(t.flatMap(e=>e.threadId?[e.threadId]:[]))]}}if(r){let e=St({...d,hostDeletions:{}},void 0,!1).state,t=new Map(y.map(e=>[e.id,e])),i={...e,annotations:[...e.annotations.map(e=>t.get(e.id)??e),...y.filter(t=>!e.annotations.some(e=>e.id===t.id))]};d=bt(d,[{id:Ce(),kind:"edit",stamp:mt("host-moderation",d.checkpoint?.through.stamp,d.events,this.now()),changes:gt(e,i)}]);for(let e of y)delete c[e.id],delete h[e.id]}else for(let e of y)Object.defineProperty(c,e.id,{value:structuredClone(e),enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(h,e.id,{value:o.identity.id,enumerable:!0,configurable:!0,writable:!0});if(l.annotationDeletionAuthors=h,d=xt({...d,hostDeletions:c}),JSON.stringify(d).length>ot)throw new e(413,"Plane history exceeds the local session limit");return l.draft={...l.draft,revision:l.draft.revision+1,history:d,state:_t(St(d,void 0,!1).state)},l.draftRevision=l.draft.revision,await this.commit(a),{annotationIds:y.map(e=>e.id),threadIds:[...g]}})}moderateStyles(t,i,n,r=!1){return this.serial(async()=>{let o=this.member(t);if("host"!==o.identity.relationship||void 0!==o.revokedAt||"blocked"===o.permission)throw new e(403,"Only the host can moderate peer styles");if(!Array.isArray(n)||!n.length||n.length>256||n.some(e=>!e||"string"!=typeof e.selector||!e.selector||void 0!==e.pathname&&"string"!=typeof e.pathname||void 0!==e.durableSelector&&"string"!=typeof e.durableSelector||!Array.isArray(e.changes)||!e.changes.length||e.changes.some(e=>!e||"string"!=typeof e.property||"string"!=typeof e.original||"string"!=typeof e.modified||void 0!==e.token&&"string"!=typeof e.token)))throw new e(400,"Invalid style identities");let s=structuredClone(this.saved),a=s.members.find(e=>e.identity.id===i&&void 0===e.revokedAt);if(!a||"guest"!==a.identity.relationship)throw new e(404,"Peer plane unavailable");let l=a.draft.history??wt(a.draft.state??Be),d=l.hostStyleDeletions??[],c=St({...l,hostStyleDeletions:[]},void 0,!1).state,h=r?d:[...c.styleModifications,...d],p=n.map(e=>h.find(t=>Ge(t,e)));if(p.some(e=>!e))throw new e(409,"Style edit changed or is no longer available");let u=p.map(e=>We(e));if(l=xt({...l,hostStyleDeletions:r?d.filter(e=>!u.some(t=>Ge(e,t))):[...d,...u.filter(e=>!d.some(t=>Ge(e,t)))]}),JSON.stringify(l).length>ot)throw new e(413,"Plane history exceeds the local session limit");return a.draft={...a.draft,revision:a.draft.revision+1,history:l,state:_t(St(l,void 0,!1).state)},a.draftRevision=a.draft.revision,await this.commit(s),{styleModifications:u}})}annotationsDeleted(e,t,i=[]){return this.serial(()=>{let n=this.saved.members.find(t=>t.identity.id===e);return i.some(e=>n?.draft.history?.hostStyleDeletions?.some(t=>Ge(e,t)))||t.some(e=>Object.hasOwn(n?.draft.history?.hostDeletions??{},e))})}disconnect(e){return this.serial(()=>{this.writableRuntime(e,!0),this.runtimes.delete(JSON.stringify([e.participantId,e.runtimeId]))})}async checkDraftBasis(e,t){if(this.pinDraftSource&&e.draft.source&&"unversioned"!==e.draft.source.revision&&e.draft.source.revision!==t.revision&&("host"!==e.identity.relationship||!this.hostBasis||await this.hostBasis(e.identity.id)!==t.revision))throw new It("draft_conflict","This plane already has a draft on another source revision. Reopen the plane to restore its source.")}publish(e,t,i,n){let r=_t(n),o=structuredClone(i),s=structuredClone(e);return this.serial(async()=>{let e=this.writableRuntime(s);if(await this.checkDraftBasis(e,o),e.draft.history||[...this.runtimes.values()].filter(t=>t.participantId===e.identity.id&&t.expiresAt>this.now()).length>1)throw new It("draft_conflict","Use shared plane events instead of replacing a snapshot");if(e.draft.revision!==t)throw new It("draft_conflict","Draft revision changed; reconcile before writing");if(o.sourceId!==this.sourceId||!o.revision||o.revision.length>256)throw new Error("Draft source does not match this room");let i=structuredClone(this.saved),n=i.members.find(t=>t.identity.id===e.identity.id);return n.draft={revision:t+1,source:o,state:r},n.draftRevision=n.draft.revision,await this.commit(i),structuredClone(n.draft)})}merge(t,i,n,r,o=2){let s;try{if(s=function(e){if(!Array.isArray(e)||e.length>8192||JSON.stringify(e).length>ot)throw new Error("Plane history exceeds the local session limit");for(let t of e){let e=e=>"string"==typeof e&&e.length>0&&e.length<=256;if(!t||!e(t.id)||!t.stamp||!e(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if("edit"!==t.kind){if(!e(t.target))throw new Error("Invalid history target");continue}if(void 0!==t.group&&!e(t.group)||void 0!==t.pulledFrom&&(!e(t.pulledFrom?.participantId)||!e(t.pulledFrom?.planeId)||!Number.isSafeInteger(t.pulledFrom?.revision)||t.pulledFrom.revision<0)||void 0!==t.reset&&"boolean"!=typeof t.reset||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let e of t.changes){if(!e||"string"!=typeof e.key||e.key.length>8192)throw new Error("Invalid property key");let t=JSON.parse(e.key);if(!Array.isArray(t)||t.length<2||t.length>3||t.some(e=>"string"!=typeof e||!e.length)||!["annotation","canvas","style","styleMeta","text","dom","spacing","spacingMod"].includes(t[0])||"canvas"===t[0]&&void 0!==e.value&&(!Ye(e.value)||t[1]!==at(e.value.pathname,e.value.selector))||"style"===t[0]&&3!==t.length||!["style","annotation"].includes(t[0])&&2!==t.length||"annotation"===t[0]&&2===t.length&&void 0!==e.value&&!0!==e.value||i.has(e.key))throw new Error("Invalid property key");i.add(e.key)}}return dt(e)}(r),s.length>256)throw new Error("Plane synchronization batch is too large")}catch(t){throw new e(400,t instanceof Error?t.message:"Invalid plane events")}let a=structuredClone(t),l=structuredClone(n);return this.serial(async()=>{let t=this.writableRuntime(a);if(await this.checkDraftBasis(t,l),2!==o)throw new e(409,"Update Popmelt to synchronize compacted history");if(!Number.isSafeInteger(i)||i<0||i>t.draft.revision)throw new It("draft_conflict","Invalid draft revision");if(l.sourceId!==this.sourceId||!l.revision||l.revision.length>256)throw new e(400,"Draft source does not match this room");if(s.some(e=>e.stamp.time>this.now()+3e5))throw new e(400,"Plane event clock is invalid");let n,r=t.draft.history??wt(t.draft.state??Be),d=0;try{let e=pt(r,s);d=e.pending.length,n=xt(bt(r,e.pending))}catch(t){throw new e(400,t instanceof Error?t.message:"Invalid plane merge")}if(JSON.stringify(n).length>ot)throw new e(413,"Plane history exceeds the local session limit");if(t.draft.history&&!d&&n.checkpoint?.through.id===r.checkpoint?.through.id&&l.revision===t.draft.source?.revision)return structuredClone(t.draft);let c=_t(St(n,void 0,!1).state),h=structuredClone(this.saved),p=h.members.find(e=>e.identity.id===t.identity.id);if(i!==t.draft.revision&&d>0)for(p.recovery=[...p.recovery??[],{at:this.now(),before:t.draft.state,after:c}].slice(-5);JSON.stringify(p.recovery).length>Mt&&p.recovery.length>1;)p.recovery.shift();return p.draft={revision:t.draft.revision+1,source:s.length&&!d?t.draft.source:l,state:c,history:n},p.draftRevision=p.draft.revision,await this.commit(h),structuredClone(p.draft)})}checkPermission(e,t){return this.serial(()=>{let i=this.member(e);if(i.permissionEpoch!==t||"direct"!==i.permission)throw new Error("Current host approval is required for implementation");return jt(i)})}async close(){await this.tail,this.closed=!0,this.invites.clear(),this.runtimes.clear()}};export{h as a,n as b,r as c,p as d,u as e,m as f,f as g,v as h,x as i,S as j,I as k,A as l,M as m,P as n,U as o,V as p,W as q,G as r,B as s,Y as t,X as u,K as v,Ve as w,Z as x,we as y,be as z,ke as A,Se as B,Ie as C,ze as D,We as E,Ge as F,It as G,Ct as H,Rt as I};