ryugi-artifacts 1.108.6 → 1.108.7

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 (115) hide show
  1. package/dist/cli.cjs +8 -8
  2. package/dist/document-engine.cjs +1 -1
  3. package/dist/runtime/Figtree-OFL.txt +93 -0
  4. package/dist/runtime/ryugi-mockup.js +270 -2
  5. package/dist/runtime/ryugi-preview-bridge.js +2 -2
  6. package/dist/runtime/ryugi-ui.js +1 -1
  7. package/dist/server.cjs +93 -93
  8. package/dist/viewer/{AgentDock-BMyCZfOA.js → AgentDock-fdzdI0YU.js} +1 -1
  9. package/dist/viewer/{ArtboardLayout-Ca63S-ht.js → ArtboardLayout-CyP7z5iV.js} +1 -1
  10. package/dist/viewer/{ArtifactList-CyHqaLMU.js → ArtifactList-D1Cv2wcz.js} +1 -1
  11. package/dist/viewer/{ArtifactModal-CNcJ9SwG.js → ArtifactModal-BRPuHjh3.js} +1 -1
  12. package/dist/viewer/{BottomSheet-CPpAPNxv.js → BottomSheet-DksTxPPS.js} +1 -1
  13. package/dist/viewer/{Canvas-CZAIguUl.js → Canvas-DA9wKktu.js} +1 -1
  14. package/dist/viewer/{CommentPopover-SiWZ0XbH.js → CommentPopover-Bz3qXsBS.js} +1 -1
  15. package/dist/viewer/{DocumentExportMenu-D3KMkrvj.js → DocumentExportMenu-Cb03PJdE.js} +1 -1
  16. package/dist/viewer/DocumentLayout-16zcY3cg.js +2 -0
  17. package/dist/viewer/DocumentPage-B__O7sY3.js +3 -0
  18. package/dist/viewer/{DraggablePanel-GsMby8P2.js → DraggablePanel-BlNQ_JOj.js} +1 -1
  19. package/dist/viewer/{DropdownMenu-BXvqn_bX.js → DropdownMenu-DhVZ3e22.js} +1 -1
  20. package/dist/viewer/Figtree-OFL.txt +93 -0
  21. package/dist/viewer/{GroupVerdict-DWVpUZS_.js → GroupVerdict-DkOR7Neo.js} +1 -1
  22. package/dist/viewer/{HtmlLayout-DlU3MyPC.js → HtmlLayout-BQS68lEe.js} +1 -1
  23. package/dist/viewer/{Input-vV0jo5B6.js → Input-YumXWTse.js} +1 -1
  24. package/dist/viewer/{MenuSubmenuTrigger-BaYw4HuY.js → MenuSubmenuTrigger-DZ2Nb6Hm.js} +1 -1
  25. package/dist/viewer/{PhoneArtboardBar-DWHrTBZF.js → PhoneArtboardBar-CZKL18gK.js} +1 -1
  26. package/dist/viewer/{Popover-BRvZS1gZ.js → Popover-i0m3nwq7.js} +1 -1
  27. package/dist/viewer/{PreviewArtifactLayout-neL_d_3n.js → PreviewArtifactLayout-B4SZfLvw.js} +1 -1
  28. package/dist/viewer/PreviewLayout-DiIQthoy.js +2 -0
  29. package/dist/viewer/{ReportLayout-BLVLfLGU.js → ReportLayout-DPnqWYPZ.js} +1 -1
  30. package/dist/viewer/{RyugiMark-d0ZfdfP2.js → RyugiMark-Ch2tF00h.js} +1 -1
  31. package/dist/viewer/{Segmented-BIBgIkNi.js → Segmented-BV_iofkK.js} +1 -1
  32. package/dist/viewer/{SelectScrollUpArrow-DNQWHWMc.js → SelectScrollUpArrow-BNSyHMPX.js} +1 -1
  33. package/dist/viewer/{SlidesLayout-MGWpipwc.js → SlidesLayout-CSeSindR.js} +3 -3
  34. package/dist/viewer/{SnapshotDocument-DX9wLXWv.js → SnapshotDocument-TIzAsI0l.js} +1 -1
  35. package/dist/viewer/{SplitFrame-CiqjUPs6.js → SplitFrame-C3Mr0Ehv.js} +1 -1
  36. package/dist/viewer/{StoryboardLayout-BkntJIHV.js → StoryboardLayout-DZVJbnzc.js} +1 -1
  37. package/dist/viewer/{StoryboardRender-BniWnBGv.js → StoryboardRender-DORxY44d.js} +1 -1
  38. package/dist/viewer/{ThreadView-WZruOpTE.js → ThreadView-CbKzFwUf.js} +1 -1
  39. package/dist/viewer/{Tooltip-DKnMl1yQ.js → Tooltip-81DgA1Zr.js} +1 -1
  40. package/dist/viewer/{VerifyLayout-Bjh7Ddzn.js → VerifyLayout--deiRi4o.js} +1 -1
  41. package/dist/viewer/{VirtualizedEditor-uWe43zaI-DIyWJhFX.js → VirtualizedEditor-uWe43zaI-1EQ0fdB8.js} +1 -1
  42. package/dist/viewer/{VirtualizedRenderer-C_d95FXi-BkojOMeR.js → VirtualizedRenderer-C_d95FXi-CixG8E4F.js} +1 -1
  43. package/dist/viewer/{WarningsBadge-B0H-6XNv.js → WarningsBadge-fEXkyk3t.js} +1 -1
  44. package/dist/viewer/{WhiteboardEditor-cZ32fLqJ-DfASNG0e.js → WhiteboardEditor-cZ32fLqJ-BRt-wSEn.js} +2 -2
  45. package/dist/viewer/WhiteboardLayout-qGm-CExy.js +4 -0
  46. package/dist/viewer/{WritingCursor-B1KstzsM.js → WritingCursor-OdCSWg_M.js} +1 -1
  47. package/dist/viewer/{agentLook-DAbDap_r.js → agentLook-EhrjbD1n.js} +1 -1
  48. package/dist/viewer/{artifact-list-Dk7B04aS.js → artifact-list-D22lTyyh.js} +1 -1
  49. package/dist/viewer/{auto-publish-D0gnAgNH.js → auto-publish-BXmqx8BX.js} +1 -1
  50. package/dist/viewer/{channel-W8z1JRUp.js → channel-CaUFZV2H.js} +3 -3
  51. package/dist/viewer/{crop-encode-jcaJuFwz.js → crop-encode-Udgh8S7r.js} +1 -1
  52. package/dist/viewer/{dist-8GuhHKSd.js → dist-0JlH-iFk.js} +1 -1
  53. package/dist/viewer/{dist-DKWGY7vW.js → dist-B-RrlmaY.js} +1 -1
  54. package/dist/viewer/{dist-e32bsEFO.js → dist-BMJWStKC.js} +1 -1
  55. package/dist/viewer/{dist-hskNTNrk.js → dist-BNiHzkc8.js} +1 -1
  56. package/dist/viewer/{dist-D5w5f0nx.js → dist-C0Fbwkds.js} +1 -1
  57. package/dist/viewer/{dist-DdWP5O5Z.js → dist-C4fPBi1f.js} +1 -1
  58. package/dist/viewer/{dist-BLDdWa7l.js → dist-C81vCo2L.js} +1 -1
  59. package/dist/viewer/dist-CY11yEtD.js +1 -0
  60. package/dist/viewer/{dist-DzgE9d65.js → dist-CjVeWopx.js} +1 -1
  61. package/dist/viewer/{dist-BKKpgaMc.js → dist-CuWYFfBf.js} +1 -1
  62. package/dist/viewer/{dist-CilrySXL.js → dist-DBnvEq5g.js} +1 -1
  63. package/dist/viewer/{dist-IX2iT14j.js → dist-DD00JDtU.js} +1 -1
  64. package/dist/viewer/{dist-B6IVYls_.js → dist-DKWARfq1.js} +1 -1
  65. package/dist/viewer/{dist-BTzyPMeC.js → dist-DRUJxMS6.js} +1 -1
  66. package/dist/viewer/{dist-C6DCB_Rj.js → dist-DRmbQ1f0.js} +1 -1
  67. package/dist/viewer/{dist-EFdcYRKe.js → dist-DurHsNXj.js} +1 -1
  68. package/dist/viewer/{dist-DE-DH2i7.js → dist-DzmIJXNR.js} +1 -1
  69. package/dist/viewer/{dist-CqeeTfim.js → dist-G4Vj4mFX.js} +1 -1
  70. package/dist/viewer/{dist-DNO7AZoy.js → dist-R6N8uqUg.js} +1 -1
  71. package/dist/viewer/{dist-BC8nvFq2.js → dist-i-_vhfnL.js} +1 -1
  72. package/dist/viewer/{dist-Bpgppm6o.js → dist-kzNj8Wks.js} +1 -1
  73. package/dist/viewer/{dist-B2aqeAk-.js → dist-o-mpdm3Q.js} +1 -1
  74. package/dist/viewer/{dist-w08ese3i.js → dist-rs8SY6NP.js} +1 -1
  75. package/dist/viewer/{dist-BhE_JiAo.js → dist-vjczWTJX.js} +1 -1
  76. package/dist/viewer/{editor-IGV7cqIf.js → editor-BabkJ7hH.js} +6 -6
  77. package/dist/viewer/figtree-latin-ext-wght-normal-DCwSJGxG.woff2 +0 -0
  78. package/dist/viewer/figtree-latin-wght-normal-D_ZTVpCC.woff2 +0 -0
  79. package/dist/viewer/{fit-CwTJJcvD.js → fit-BJ0VxRML.js} +1 -1
  80. package/dist/viewer/{icons-Dwk8RW6i.js → icons-8mizjIXE.js} +1 -1
  81. package/dist/viewer/{imperative-9zI7cd1I.js → imperative-iclc26pT.js} +1 -1
  82. package/dist/viewer/index.css +1 -1
  83. package/dist/viewer/index.html +12 -12
  84. package/dist/viewer/index.js +2 -2
  85. package/dist/viewer/index2.css +1 -1
  86. package/dist/viewer/{local-BIV9Bn_B.js → local-DzHVL3fo.js} +1 -1
  87. package/dist/viewer/{local-split-host-DJJKo1Vj.js → local-split-host-DaeACaX5.js} +1 -1
  88. package/dist/viewer/plugin-_bGVeqI0-BkU-g6bb.js +2 -0
  89. package/dist/viewer/preview.html +3 -3
  90. package/dist/viewer/preview.js +1 -1
  91. package/dist/viewer/{printDocument-BbvYpCaV.js → printDocument-Bh1qUAf9.js} +1 -1
  92. package/dist/viewer/{ref-DcFpXWwa.js → ref-JbqCEGXp.js} +1 -1
  93. package/dist/viewer/{route-CAQRGuux.js → route-DdpUUY_w.js} +5 -5
  94. package/dist/viewer/{route-messages-AShIvXR0.js → route-messages-BMv2jmvl.js} +1 -1
  95. package/dist/viewer/{settings-CxJUVRn8.js → settings-wKTRexHi.js} +1 -1
  96. package/dist/viewer/{snap-Bp7A7-zR.js → snap-1DJNMR4r.js} +1 -1
  97. package/dist/viewer/{split-CeIplvJa.js → split-BJA_5Rtf.js} +2 -2
  98. package/dist/viewer/{stable-DVc3NRmV.js → stable-CZy_447C.js} +1 -1
  99. package/dist/viewer/{styles-BBTLo6nS.js → styles-BHI9FTnz.js} +1 -1
  100. package/dist/viewer/{transport-CazJfalj.js → transport-Djlo7-HU.js} +1 -1
  101. package/dist/viewer/{url-BS6kqcve.js → url-B_fuREEU.js} +1 -1
  102. package/dist/viewer/{useArtifactFeed-CymUjnz1.js → useArtifactFeed-B9RfhN8_.js} +1 -1
  103. package/dist/viewer/{useArtifactSocket-BOU81P_2.js → useArtifactSocket-ns9zjgVa.js} +1 -1
  104. package/dist/viewer/{useLayerZIndex-D5QVXpVc.js → useLayerZIndex-VAxAVO-V.js} +1 -1
  105. package/dist/viewer/{useStoryboardData-BbPOAS-Z.js → useStoryboardData-DCPDhUMO.js} +1 -1
  106. package/dist/viewer/{view-BatCe1Ci.js → view-DLrABahQ.js} +1 -1
  107. package/dist/viewer/{viewport-CFJHn_Y6-DuJwG-4n.js → viewport-CFJHn_Y6-B0Ka3uWP.js} +1 -1
  108. package/package.json +1 -1
  109. package/dist/viewer/DocumentLayout-Vo9s9zeJ.js +0 -2
  110. package/dist/viewer/DocumentPage-CIvaYNgp.js +0 -3
  111. package/dist/viewer/Goeist-DFcbbrZE.woff2 +0 -0
  112. package/dist/viewer/PreviewLayout-BuviWNGi.js +0 -2
  113. package/dist/viewer/WhiteboardLayout-CwmEBIBu.js +0 -4
  114. package/dist/viewer/dist-Cg7E0M7K.js +0 -1
  115. package/dist/viewer/plugin-_bGVeqI0-_v5JtKHd.js +0 -2
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r=Object.setPrototypeOf({},null);for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n&1||t(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("node:fs");u=l(u,1);let d=require("node:path");d=l(d,1);let f=require("node:child_process"),p=require("node:crypto");p=l(p,1);let m=require("node:readline");m=l(m,1);let h=require("node:util"),g=require("node:os");g=l(g,1);let _=require("node:net");_=l(_,1);let v=require("node:url"),y=require("node:process");y=l(y,1);let b=require("node:tty");var x=`1.108.6`;const S=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Ryugi ${e} (${x}${t?` · ${t}`:``})`},C=process.platform!==`win32`;function w(e,...t){C&&(process.title=[S(e),...t].join(` `))}const T=[`desktop`,`laptop`,`tablet`,`mobile`],E=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),D=4096;function ee(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>256)return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!==`http:`||n.username||n.password||n.search||n.hash||n.pathname!==`/`&&n.pathname!==``)return null;let r=n.hostname.toLowerCase();if(!E.has(r))return null;let i=n.port?Number(n.port):80;return!Number.isInteger(i)||i<1||i>65535?null:{origin:n.origin,host:n.host,hostname:r===`[::1]`?`::1`:r,port:i}}function O(e){let t=e.trim();if(!t||t.length>1024)return null;let n=/^https?:\/\//i.test(t)?t:`http://${t}`,r;try{r=new URL(n)}catch{return null}let i=ee(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function k(e){if(typeof e==`string`)return T.includes(e)?e:null;if(typeof e==`object`&&e&&!Array.isArray(e)){let{w:t,h:n}=e;if(typeof t==`number`&&typeof n==`number`&&Number.isInteger(t)&&Number.isInteger(n)&&t>=240&&t<=D&&n>=240&&n<=D)return{w:t,h:n}}return null}function A(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function te(e){let t;try{t=JSON.parse(e)}catch(e){return{config:null,issues:[`preview.json is not valid JSON: ${e.message}`]}}if(typeof t!=`object`||!t||Array.isArray(t))return{config:null,issues:[`preview.json must be a JSON object`]};let n=t,r=[];n.version!==1&&r.push(`preview.json requires version: 1`);let i=ee(n.url);i||r.push(`preview.json url must be a local loopback http origin (e.g. http://localhost:5173 or http://127.0.0.1:3000)`);let a;n.title!==void 0&&(typeof n.title!=`string`||!n.title.trim()||n.title.length>200?r.push(`preview.json title must be a non-empty string (<= 200 chars)`):a=n.title.trim());let o;if(n.path!==void 0){let e=A(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=k(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${T.join(`, `)} or { w, h } (240..${D})`)}return r.length>0||!i?{config:null,issues:r}:{config:{version:1,url:i.origin,...a?{title:a}:{},...o?{path:o}:{},...s?{viewport:s}:{}},issues:[]}}const ne={claude:`Claude Code`,"claude-code":`Claude Code`,cowork:`Claude Cowork`,codex:`Codex`,cursor:`Cursor`,"cursor-cli":`Cursor`,gemini:`Gemini CLI`,"gemini-cli":`Gemini CLI`,grok:`Grok`,"grok-cli":`Grok`,"github-copilot":`GitHub Copilot`,"github-copilot-cli":`GitHub Copilot`,kilo:`Kilo Code`,omp:`OMP`,"oh-my-pi":`OMP`,opencode:`OpenCode`,"qwen-code":`Qwen Code`,antigravity:`Antigravity`,augment:`Augment`,"augment-cli":`Augment`,goose:`Goose`,amp:`Amp`,cline:`Cline`,roo:`Roo Code`,devin:`Devin`,replit:`Replit`,v0:`v0`};[...new Set(Object.values(ne))];const j=[[`omp`,e=>!!e.OMPCODE],[`grok`,e=>!!(e.GROK_AGENT||e.GROK_SESSION_ID)],[`cowork`,e=>!!e.CLAUDE_CODE_IS_COWORK],[`kilo`,e=>!!e.KILO],[`codex`,e=>!!(e.CODEX_THREAD_ID||e.CODEX_SANDBOX||e.CODEX_CI)],[`cursor`,e=>!!(e.CURSOR_AGENT||e.CURSOR_TRACE_ID)],[`gemini`,e=>!!e.GEMINI_CLI],[`github-copilot`,e=>!!e.COPILOT_CLI],[`opencode`,e=>e.OPENCODE===`1`||!!e.OPENCODE_CLIENT],[`qwen-code`,e=>!!e.QWEN_CODE],[`antigravity`,e=>!!e.ANTIGRAVITY_AGENT],[`augment`,e=>!!e.AUGMENT_AGENT],[`cline`,e=>!!e.CLINE_ACTIVE],[`roo`,e=>!!e.ROO_ACTIVE],[`claude`,e=>!!(e.CLAUDECODE||e.CLAUDE_CODE)]],re=[`AI_AGENT`,`AGENT`,`OMPCODE`,`GROK_AGENT`,`GROK_SESSION_ID`,`CLAUDE_CODE_IS_COWORK`,`KILO`,`CODEX_THREAD_ID`,`CODEX_SANDBOX`,`CODEX_CI`,`CURSOR_AGENT`,`CURSOR_TRACE_ID`,`GEMINI_CLI`,`COPILOT_CLI`,`OPENCODE`,`OPENCODE_CLIENT`,`QWEN_CODE`,`ANTIGRAVITY_AGENT`,`AUGMENT_AGENT`,`CLINE_ACTIVE`,`ROO_ACTIVE`,`CLAUDECODE`,`CLAUDE_CODE`],M=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0,ie=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(e){let t=ae(e),n=t===ne.claude?`claude`:t===ne.codex?`codex`:t===ne.antigravity?`antigravity`:null;if(!n)return null;let r=n===`claude`?e.CLAUDE_CODE_SESSION_ID:n===`codex`?e.CODEX_THREAD_ID||e.CODEX_SESSION_ID:e.ANTIGRAVITY_CONVERSATION_ID;return!r||!ie.test(r)?null:{host:n,id:r}}function ae(e){if(e.CLAUDE_CODE_IS_COWORK)return ne.cowork;let t=M(e.AI_AGENT);if(t)return ne[t]??t;let n=j.find(([,t])=>t(e))?.[0];if(n)return ne[n];let r=M(e.AGENT);if(r&&!/^(?:1|true|yes)$/.test(r))return ne[r]??r}const oe=[`artboard`,`document`,`html`,`whiteboard`,`verify`,`slides`,`report`,`storyboard`],se={artboard:`canvas.json`,document:`doc.xml`,html:`index.html`,whiteboard:`scene.excalidraw`,verify:`verify.xml`,slides:`index.html`,report:`report.tsx`,storyboard:`storyboard.xml`};({...se});const ce=[`html`,`image`,`video`],le=e=>e.type===`image`||e.type===`video`,ue=/* @__PURE__ */ RegExp(`^[a-z0-9][a-z0-9-]*$`),de=/* @__PURE__ */ RegExp(`^(?:[\\w-]{21}|[a-f0-9]{32})$`);function fe(e){let t=``,n=new Uint8Array(e*2);for(;t.length<e;){crypto.getRandomValues(n);for(let r of n)if(!(r>=248)&&(t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[r%62],t.length===e))break}return t}const pe=()=>fe(21),me=e=>ue.test(e),he=e=>de.test(e),ge=e=>oe.includes(e);function P(e,t,n){if(!ge(t)||!me(n))return null;let r=d.default.join(e,t,n);try{return u.default.statSync(r).isDirectory()?r:null}catch{return null}}function _e(e){let t=d.default.join(e,`.artifact-id`),n;try{n=u.default.readFileSync(t,`utf8`).trim()}catch(r){if(r.code!==`ENOENT`)throw r;n=pe();try{u.default.writeFileSync(t,`${n}\n`,{flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;return _e(e)}}if(!he(n))throw Error(`Invalid artifact ID in ${t}`);return n}function ve(e){try{return u.default.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function ye(e){let t=[],n=[];for(let r of ve(e))if(!r.startsWith(`.`)){if(!ge(r))n.push(`unknown artifact type directory: ${r}/ (known: ${oe.join(`, `)})`);else for(let i of ve(d.default.join(e,r)))me(i)?t.push({type:r,id:i,dir:d.default.join(e,r,i)}):n.push(`invalid artifact id: ${r}/${i} (use lowercase letters, digits and hyphens)`)}return{artifacts:t,warnings:n}}function be(e,t=me){let[n,r]=e.split(`/`);return!n||!r||!ge(n)||!t(r)?null:{type:n,id:r}}function xe(e,t){let n=0,r;try{r=u.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.name===t)continue;let r=d.default.join(e,i.name);try{n=Math.max(n,i.isDirectory()?xe(r):u.default.statSync(r).mtimeMs)}catch{continue}}return n}function Se(e,t,n){if(!ge(t)||!me(n))throw Error(`Invalid artifact locator`);let r=d.default.join(e,t,n);return u.default.mkdirSync(r,{recursive:!0}),`/${t}/${_e(r)}`}({html:`text/html; charset=utf-8`,js:`text/javascript; charset=utf-8`,mjs:`text/javascript; charset=utf-8`,css:`text/css; charset=utf-8`,json:`application/json; charset=utf-8`,xml:`application/xml; charset=utf-8`,txt:`text/plain; charset=utf-8`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`}).json;const Ce=()=>p.default.randomBytes(24).toString(`base64url`);function we(e){try{return u.default.readFileSync(e,`utf8`).trim()}catch{return``}}function Te(e,t){return e===`darwin`?{bin:`open`,args:[t]}:e===`win32`?{bin:`cmd`,args:[`/c`,`start`,`""`,t]}:e===`linux`||e===`freebsd`||e===`openbsd`?{bin:`xdg-open`,args:[t]}:null}const Ee=(0,h.promisify)(f.execFile),De=String.raw`
2
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r=Object.setPrototypeOf({},null);for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n&1||t(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("node:fs");u=l(u,1);let d=require("node:path");d=l(d,1);let f=require("node:child_process"),p=require("node:crypto");p=l(p,1);let m=require("node:readline");m=l(m,1);let h=require("node:util"),g=require("node:os");g=l(g,1);let _=require("node:net");_=l(_,1);let v=require("node:url"),y=require("node:process");y=l(y,1);let b=require("node:tty");var x=`1.108.7`;const S=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Ryugi ${e} (${x}${t?` · ${t}`:``})`},C=process.platform!==`win32`;function w(e,...t){C&&(process.title=[S(e),...t].join(` `))}const T=[`desktop`,`laptop`,`tablet`,`mobile`],E=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),D=4096;function ee(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>256)return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!==`http:`||n.username||n.password||n.search||n.hash||n.pathname!==`/`&&n.pathname!==``)return null;let r=n.hostname.toLowerCase();if(!E.has(r))return null;let i=n.port?Number(n.port):80;return!Number.isInteger(i)||i<1||i>65535?null:{origin:n.origin,host:n.host,hostname:r===`[::1]`?`::1`:r,port:i}}function O(e){let t=e.trim();if(!t||t.length>1024)return null;let n=/^https?:\/\//i.test(t)?t:`http://${t}`,r;try{r=new URL(n)}catch{return null}let i=ee(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function k(e){if(typeof e==`string`)return T.includes(e)?e:null;if(typeof e==`object`&&e&&!Array.isArray(e)){let{w:t,h:n}=e;if(typeof t==`number`&&typeof n==`number`&&Number.isInteger(t)&&Number.isInteger(n)&&t>=240&&t<=D&&n>=240&&n<=D)return{w:t,h:n}}return null}function A(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function te(e){let t;try{t=JSON.parse(e)}catch(e){return{config:null,issues:[`preview.json is not valid JSON: ${e.message}`]}}if(typeof t!=`object`||!t||Array.isArray(t))return{config:null,issues:[`preview.json must be a JSON object`]};let n=t,r=[];n.version!==1&&r.push(`preview.json requires version: 1`);let i=ee(n.url);i||r.push(`preview.json url must be a local loopback http origin (e.g. http://localhost:5173 or http://127.0.0.1:3000)`);let a;n.title!==void 0&&(typeof n.title!=`string`||!n.title.trim()||n.title.length>200?r.push(`preview.json title must be a non-empty string (<= 200 chars)`):a=n.title.trim());let o;if(n.path!==void 0){let e=A(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=k(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${T.join(`, `)} or { w, h } (240..${D})`)}return r.length>0||!i?{config:null,issues:r}:{config:{version:1,url:i.origin,...a?{title:a}:{},...o?{path:o}:{},...s?{viewport:s}:{}},issues:[]}}const ne={claude:`Claude Code`,"claude-code":`Claude Code`,cowork:`Claude Cowork`,codex:`Codex`,cursor:`Cursor`,"cursor-cli":`Cursor`,gemini:`Gemini CLI`,"gemini-cli":`Gemini CLI`,grok:`Grok`,"grok-cli":`Grok`,"github-copilot":`GitHub Copilot`,"github-copilot-cli":`GitHub Copilot`,kilo:`Kilo Code`,omp:`OMP`,"oh-my-pi":`OMP`,opencode:`OpenCode`,"qwen-code":`Qwen Code`,antigravity:`Antigravity`,augment:`Augment`,"augment-cli":`Augment`,goose:`Goose`,amp:`Amp`,cline:`Cline`,roo:`Roo Code`,devin:`Devin`,replit:`Replit`,v0:`v0`};[...new Set(Object.values(ne))];const j=[[`omp`,e=>!!e.OMPCODE],[`grok`,e=>!!(e.GROK_AGENT||e.GROK_SESSION_ID)],[`cowork`,e=>!!e.CLAUDE_CODE_IS_COWORK],[`kilo`,e=>!!e.KILO],[`codex`,e=>!!(e.CODEX_THREAD_ID||e.CODEX_SANDBOX||e.CODEX_CI)],[`cursor`,e=>!!(e.CURSOR_AGENT||e.CURSOR_TRACE_ID)],[`gemini`,e=>!!e.GEMINI_CLI],[`github-copilot`,e=>!!e.COPILOT_CLI],[`opencode`,e=>e.OPENCODE===`1`||!!e.OPENCODE_CLIENT],[`qwen-code`,e=>!!e.QWEN_CODE],[`antigravity`,e=>!!e.ANTIGRAVITY_AGENT],[`augment`,e=>!!e.AUGMENT_AGENT],[`cline`,e=>!!e.CLINE_ACTIVE],[`roo`,e=>!!e.ROO_ACTIVE],[`claude`,e=>!!(e.CLAUDECODE||e.CLAUDE_CODE)]],re=[`AI_AGENT`,`AGENT`,`OMPCODE`,`GROK_AGENT`,`GROK_SESSION_ID`,`CLAUDE_CODE_IS_COWORK`,`KILO`,`CODEX_THREAD_ID`,`CODEX_SANDBOX`,`CODEX_CI`,`CURSOR_AGENT`,`CURSOR_TRACE_ID`,`GEMINI_CLI`,`COPILOT_CLI`,`OPENCODE`,`OPENCODE_CLIENT`,`QWEN_CODE`,`ANTIGRAVITY_AGENT`,`AUGMENT_AGENT`,`CLINE_ACTIVE`,`ROO_ACTIVE`,`CLAUDECODE`,`CLAUDE_CODE`],M=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0,ie=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(e){let t=ae(e),n=t===ne.claude?`claude`:t===ne.codex?`codex`:t===ne.antigravity?`antigravity`:null;if(!n)return null;let r=n===`claude`?e.CLAUDE_CODE_SESSION_ID:n===`codex`?e.CODEX_THREAD_ID||e.CODEX_SESSION_ID:e.ANTIGRAVITY_CONVERSATION_ID;return!r||!ie.test(r)?null:{host:n,id:r}}function ae(e){if(e.CLAUDE_CODE_IS_COWORK)return ne.cowork;let t=M(e.AI_AGENT);if(t)return ne[t]??t;let n=j.find(([,t])=>t(e))?.[0];if(n)return ne[n];let r=M(e.AGENT);if(r&&!/^(?:1|true|yes)$/.test(r))return ne[r]??r}const oe=[`artboard`,`document`,`html`,`whiteboard`,`verify`,`slides`,`report`,`storyboard`],se={artboard:`canvas.json`,document:`doc.xml`,html:`index.html`,whiteboard:`scene.excalidraw`,verify:`verify.xml`,slides:`index.html`,report:`report.tsx`,storyboard:`storyboard.xml`};({...se});const ce=[`html`,`image`,`video`],le=e=>e.type===`image`||e.type===`video`,ue=/* @__PURE__ */ RegExp(`^[a-z0-9][a-z0-9-]*$`),de=/* @__PURE__ */ RegExp(`^(?:[\\w-]{21}|[a-f0-9]{32})$`);function fe(e){let t=``,n=new Uint8Array(e*2);for(;t.length<e;){crypto.getRandomValues(n);for(let r of n)if(!(r>=248)&&(t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[r%62],t.length===e))break}return t}const pe=()=>fe(21),me=e=>ue.test(e),he=e=>de.test(e),ge=e=>oe.includes(e);function P(e,t,n){if(!ge(t)||!me(n))return null;let r=d.default.join(e,t,n);try{return u.default.statSync(r).isDirectory()?r:null}catch{return null}}function _e(e){let t=d.default.join(e,`.artifact-id`),n;try{n=u.default.readFileSync(t,`utf8`).trim()}catch(r){if(r.code!==`ENOENT`)throw r;n=pe();try{u.default.writeFileSync(t,`${n}\n`,{flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;return _e(e)}}if(!he(n))throw Error(`Invalid artifact ID in ${t}`);return n}function ve(e){try{return u.default.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function ye(e){let t=[],n=[];for(let r of ve(e))if(!r.startsWith(`.`)){if(!ge(r))n.push(`unknown artifact type directory: ${r}/ (known: ${oe.join(`, `)})`);else for(let i of ve(d.default.join(e,r)))me(i)?t.push({type:r,id:i,dir:d.default.join(e,r,i)}):n.push(`invalid artifact id: ${r}/${i} (use lowercase letters, digits and hyphens)`)}return{artifacts:t,warnings:n}}function be(e,t=me){let[n,r]=e.split(`/`);return!n||!r||!ge(n)||!t(r)?null:{type:n,id:r}}function xe(e,t){let n=0,r;try{r=u.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.name===t)continue;let r=d.default.join(e,i.name);try{n=Math.max(n,i.isDirectory()?xe(r):u.default.statSync(r).mtimeMs)}catch{continue}}return n}function Se(e,t,n){if(!ge(t)||!me(n))throw Error(`Invalid artifact locator`);let r=d.default.join(e,t,n);return u.default.mkdirSync(r,{recursive:!0}),`/${t}/${_e(r)}`}({html:`text/html; charset=utf-8`,js:`text/javascript; charset=utf-8`,mjs:`text/javascript; charset=utf-8`,css:`text/css; charset=utf-8`,json:`application/json; charset=utf-8`,xml:`application/xml; charset=utf-8`,txt:`text/plain; charset=utf-8`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`}).json;const Ce=()=>p.default.randomBytes(24).toString(`base64url`);function we(e){try{return u.default.readFileSync(e,`utf8`).trim()}catch{return``}}function Te(e,t){return e===`darwin`?{bin:`open`,args:[t]}:e===`win32`?{bin:`cmd`,args:[`/c`,`start`,`""`,t]}:e===`linux`||e===`freebsd`||e===`openbsd`?{bin:`xdg-open`,args:[t]}:null}const Ee=(0,h.promisify)(f.execFile),De=String.raw`
3
3
  function run(urls) {
4
4
  function key(url) {
5
5
  return String(url).split(/[?#]/)[0].replace(/^(https?:\/\/)127\.0\.0\.1:/, '$1localhost:').replace(/\/$/, '');
@@ -317,7 +317,7 @@ getElementsByTagNameNS(e,t){return this.getElementsByTagName(t)}createAttributeN
317
317
  `),Zh=(e,t)=>e.split(`
318
318
  `).map(e=>e&&`${t}${e}`).join(`
319
319
  `);function Qh(e){let t;try{t=JSON.parse(e)}catch{return`[chart]`}let n=t.x??``,r=t.series??[],i=e=>`| ${e.map(e=>String(e??``)).join(` | `)} |`,a=[i([n,...r.map(e=>e.label??e.key)]),i(Array.from({length:r.length+1},()=>`---`)),...(t.data??[]).map(e=>i([e[n],...r.map(t=>e[t.key])]))].join(`
320
- `);return t.title?`**${t.title}**\n\n${a}`:a}const $h=e=>e.root;function eg(e,t){return new Jh(new Map(t.map(e=>[e.id,e]))).document($h(e).children)}const tg=e=>[...e.replaceAll(/\s/g,``)].length;function ng(e,t=[]){let n=new Jh(new Map(t.map(e=>[e.id,e]))),r=[];for(let t of $h(e).children??[])t.type===`heading`?r.push({id:Uh(t.$?.blockId),level:Number(Uh(t.tag).slice(1))||1,title:n.inline(t.children),chars:0}):r.length&&(r.at(-1).chars+=tg(n.block(t)));return r}function rg(e){try{return _n(hn(u.default.readFileSync(d.default.join(e,`comments.json`),`utf8`))).threads}catch{return[]}}function ig(e){let t=zh(u.default.readFileSync(d.default.join(e,`doc.xml`),`utf8`)),n=cn(en(t),rg(e)),r=bn(e);return{markdown:(r?`${Bh}\n\n${r.markdown}\n\n---\n\n`:``)+eg(t,n),outline:ng(t,n)}}function ag(e,t,n,r){if(e===`submit`)return{op:`submit`,submit:!t.withdraw};if(!t.ask)throw new F(`comment ${e} needs --ask <questionId>`);if(e===`note`)return{op:`note`,ask:t.ask,text:n()};let i=r?.trim();if(!t.clear&&!t.choice&&!i)throw new F(`comment answer needs --choice <value>, --text <answer>, or --clear`);return{op:`answer`,ask:t.ask,choice:t.clear?null:t.choice??null,answer:t.clear?null:i??null}}var og='# Document writing\n\nWrite `doc.xml` under the returned artifact directory; put assets in `assets/`. Re-read immediately before each edit: the human and server edit this file too. Patch intended blocks, preserve existing IDs and human text; new blocks omit IDs and receive them from the server. Never edit `comments.json` or `.state/`. The server normalizes aliases and indentation after saving. Finish with `check`; pending merging or browser work means check again, not success.\n\nUse a closed `<doc>`. Choose blocks for the reader: diagrams show relationships, charts compare numbers, tables map exact attributes, prose explains reasons. A first draft can contain `<pending intent="What remains to investigate"/>`; fill every pending before claiming completion. Diagrams use native mermaid, or a whiteboard of this project embedded with a reference (below); never pictures of text or box drawing in code blocks.\n\nComplete block and inline vocabulary:\n\n- `h1`–`h6`, `p`, `blockquote`, `ul`/`ol` with `li`, `table`/`tr`/`th`/`td`, `hr`.\n- Inline `b i u s code sub sup mark a br`; aliases `strong em del strike`. Links use `href`. Ordered lists accept `start`; checklists use `<ul type="check"><li checked="true">Done</li></ul>`.\n- `codeblock lang="ts"`: code; use CDATA for literal XML/angle brackets. `mermaid`: native flowcharts/sequences/states. `math`: inline LaTeX, `display="block"` for a block.\n- `img src="assets/image.png" alt="…" caption="…" width="640"`: real images.\n- `alert type="note|tip|important|warning|caution"`: block children. `details summary="…" open="true"`: collapsed depth; omit open for collapsed. `steps` contains `step title="…"` with block children; titles omit numbering.\n- `footnote ref="1"` inline; `footnote-section` contains `def ref="1"` definitions.\n- `chart`: CDATA ChartSpec JSON. Required `version:1`, `type:bar|line|area|pie`, `x` category field, `series:[{key,label?}]`, `data` rows containing x and every series key. Values numbers/null, pie nonnegative. At most 6 series and 6 pie rows. Optional title/subtitle/note/source/xLabel/stacked/donut/highlight, format `{unit,compact,decimals,signed}`, y `{min,max}`, refs `[{y,label}]`. `highlight` is a `series.key` and highlights that entire series; omit it when unnecessary. With `series:[{key:"failures"}]` and rows `[{phase:"Before",failures:12},{phase:"After",failures:4}]`, `highlight:"failures"` is valid; `highlight:"After"` is invalid because it is a row/category value.\n- `dynamic url="assets/demo.html" initial-height="240"`: CDATA JSON becomes `window.ryugiProps`. Self-contained sandboxed HTML, inline scripts/styles, size by content, transparent body. Browser controls persist on HTML rewrite; changing props resets them. Runtime is incomplete until the block has run. Native HTML/CSS/JS and `ryugi-icon` work; storage/cookies do not.\n- `pending intent="…"`, inline `ask`/`option` and `ref` (below; a whiteboard `ref` can also embed as a block). Other tags are rejected.\n\n```xml\n<doc>\n <h1>Retry policy</h1>\n <p>Retry failed delivery at most <b>3</b> times.</p>\n <mermaid><![CDATA[flowchart LR\n ingress --> queue --> worker]]></mermaid>\n <p>Choose a strategy: <ask id="retry-strategy" recommend="exponential"><option value="fixed">Fixed delay</option><option value="exponential">Exponential backoff</option></ask></p>\n <details summary="Evidence"><codeblock lang="text"><![CDATA[attempts: 3]]></codeblock></details>\n</doc>\n```\n\nQuestions: `ask` is inline in p/li/table-cell paragraphs, never directly under doc. Its unique stable id is lowercase letters/digits/hyphens; never reuse an old question ID. Options contain plain text and distinct `value`s; `recommend` must name an option. No options makes an open question: `<ask id="other" placeholder="Describe it"/>`. Human picks are drafts until submitted. Read `comment list --sections threads,asks --detail`. Apply submitted answers, then `comment note --ask <id> --text <what changed>`. Every submitted question needs a note, even unanswered ones (state what was left or assumed). Record terminal answers only when actually supplied via `comment answer --ask <id> --choice <value>` or `--text`, then `comment submit`. Never invent an answer; wait after withdrawal. Changed settled answers require a human instruction and a fresh note.\n\nReferences: inline `<ref document="slug"/>`, `<ref document="slug" block="block-id"/>` (one top-level block of a document: the `id` of its `h2`, `p`, list…; name this document\'s own slug to jump within it), `<ref html="slug">label</ref>`, `<ref artboard="slug" group="q1"/>` (or board), `<ref whiteboard="slug" frame="f1"/>` (or page), `<ref slides="slug" slide="slide-id"/>` (a deck, or one slide of it). Exactly one kind, at most one allowed subtarget, lowercase slug. Optional plain text label; server adds `to` when resolved, preserve it. Missing targets, including a block the document no longer has, are warnings; clear before handoff. Keep referenced IDs stable; when changing a target, update the reference too. A reference under its section heading connects that section to its companion canvas. Live choices/verdicts belong in refs, not duplicated prose.\n\nEmbedded whiteboards: `<ref whiteboard="slug" frame="f1" embed="true"/>` draws the whiteboard in the document instead of a chip. Write it as a paragraph of its own directly under `<doc>`, e.g. `<p><ref whiteboard="sync-flow" frame="f-steps" embed="true"/></p>`; never beside text, in a list, table or quote. `frame` shows that frame cut to its box, `page` one page, neither the main page. Only whiteboard references embed. The drawing follows the whiteboard live: draw and change it on the whiteboard, not in the document; a reader clicks it to open the whole whiteboard. A missing whiteboard or frame is the same check warning as any reference.\n\nAfter editing, run the returned Check command. It names invalid blocks, chart/math/diagram errors, unresolved refs and pending dynamic work. Read complete feedback before acting; reply/resolve and acknowledge only the receipt for evidence actually used.\n';const sg=/^(.+?)->(.+?)(?:#([1-9]\d*))?$/;function cg(e){if(e.node&&e.edge)throw new F(`comment add takes --node or --edge, not both`);if(e.node)return{kind:`node`,id:e.node};if(!e.edge)return;let t=sg.exec(e.edge);if(!t)throw new F(`comment add --edge needs "<from>-><to>", with #n for the nth edge between them`);return{kind:`edge`,from:t[1],to:t[2],index:t[3]?Number(t[3])-1:0}}const lg=e=>t=>ag(e,t,()=>Kt(t),t.text);function ug(e,t,n){try{let e=ig(d.default.dirname(n));return{markdown:e.markdown,rows:e.outline}}catch(e){return{warnings:[{code:`W_DOCUMENT_MARKDOWN`,message:`could not read the document as markdown, so it is shown as LiteXML: ${e.message}`}]}}}const dg={authoring:og,localGet:{key:`outline`,read:ug,columns:[{key:`id`,required:!0,positional:!0},{key:`level`,positional:!0},{key:`title`,positional:!0},{key:`chars`}]},changes:!0,review:{sections:[`asks`]},commentActions:{submit:lg(`submit`),answer:lg(`answer`),note:lg(`note`),add:e=>{if(!e.block)throw new F(`comment add needs --block <blockId>`);let t=cg(e);return{op:`add`,blockId:e.block,...t?{diagram:t}:{},...e.quote?{quote:e.quote}:{},text:Kt(e)}}}},fg={authoring:'# HTML writing\n\nWrite one complete `index.html` with a descriptive `<title>`, inline or relative styles/scripts/images. The page reloads on edits. Native HTML/CSS/JavaScript works; use labelled controls and visible results. Assets stay inside this artifact directory; CDN fonts/scripts work, absolute local paths do not. The iframe is sandboxed: localStorage/sessionStorage/cookies throw; keep state in DOM/variables. Popups, forms, downloads and clipboard work.\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Retry explorer</title>\n </head>\n <body>\n <label>Attempts <input id="attempts" type="range" min="1" max="5" value="3" /></label>\n <output id="result"></output>\n <script>\n const input = document.getElementById(\'attempts\');\n const render = () =>\n (document.getElementById(\'result\').textContent = input.value + \' attempts\');\n input.addEventListener(\'input\', render);\n render();\n <\/script>\n </body>\n</html>\n```\n\nStable control IDs preserve human input, checks, details and scroll across rewrites. Restoration fires input/change: render from those events. Script-only state resets. Use one surface for one investigation; comparison across independent screens belongs on an artboard. Re-read files before editing; never edit comments or `.state/`.\n\nBundled UI elements require no imports. Use native HTML/CSS for layout. `ryugi-icon name="message-square" size="18"` provides Lucide kebab-case icons (stroke-width defaults 2, color currentColor); label the button, icons are decorative. Unknown names become runtime warnings. For JS-only icons add `<meta name="ryugi-icons" content="1">` and await customElements.whenDefined(\'ryugi-icon\'). Preview glyphs map to the app\'s existing business icons when implementing the design.\n\nRun Check after edits. It distinguishes current static evidence from browser runtime. A closed/unloaded tab means runtime pending; open the returned URL and check again. Uncaught exceptions, rejected promises and missing relative assets are warnings; no browser run is not proof that a page works.\n\n# UI components\n\nHTML artifacts can use a small set of Lobe UI components through Web\nComponents. The artifacts server loads the runtime automatically when the page\ncontains a `<ryugi-…>` element:\n\n```html\n<ryugi-button variant="primary">Save</ryugi-button>\n```\n\nNo script tag is needed. If you create components dynamically, add\n`<meta name="ryugi-ui" content="1">` to the page so the runtime is loaded.\n\nThe runtime loads with `defer`. A page script that needs the components should\nwait for the document event:\n\n```js\ndocument.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n // custom elements are defined\n },\n { once: true },\n);\n```\n\nUse these for controls and basic display. Use plain HTML and CSS for layout;\nthere is no layout wrapper to learn.\n\n## Rules\n\n- Give every interactive control a stable `id`. The viewer restores custom\n controls across rewrites by `id`, the same way it restores native inputs.\n- Listen for `ryugi-change` on controls:\n\n ```js\n document.addEventListener(\'ryugi-change\', (event) => {\n const { value, checked } = event.detail;\n console.log(event.target.id, value, checked);\n });\n ```\n\n It bubbles. `value` is a string, number, boolean, or `null`; `checked` is\n present for checkboxes and switches.\n\n- `value` / `checked` attributes set the initial state. Read the current state\n from the element\'s `value` / `checked` property after `ryugi-ui:ready`, and\n listen for `ryugi-change` for later updates.\n- `class` styles the host; `style` is forwarded to the component as well, so\n `style="width:100%"` works. Style the host, not the component\'s internal\n classes.\n- Keep children simple. For `ryugi-button`, `ryugi-card`, `ryugi-text`,\n `ryugi-tag`, `ryugi-checkbox`, and `ryugi-badge`, the original children are\n moved into the component. `ryugi-select`, `ryugi-segmented`, and\n `ryugi-radio-group` use option children instead.\n- Do not invent a `ryugi-` tag. If a component is not listed here, use HTML.\n- `ryugi-card` already paints a surface. Do not put a background, border and\n padding on both the host and the card: pick one. For a floating panel,\n either position the host and let the card paint its own surface, or make the\n host the surface and use `variant="borderless"` without `glass`/`shadow`.\n- Components follow `prefers-color-scheme`. Set `<html data-theme="light">`\n or `data-theme="dark"` before the runtime loads to pin the whole page.\n Without an explicit theme, the runtime follows OS theme changes.\n Lobe tokens such as `--lobe-color-primary` can be overridden on the host or\n page.\n\n## Controls\n\n### Button\n\n```html\n<ryugi-button variant="primary" size="middle" icon="plus">Add</ryugi-button>\n<ryugi-button variant="outlined" loading>Working…</ryugi-button>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `size`\n(`small`, `middle`, `large`), `block`, `loading`, `disabled`, `shape`, `type`,\n`icon` (any Lucide kebab-case name; `refresh` and `trash` remain aliases).\nRun `node app/ryugi.cjs guide icons` for standalone icons and mapping the preview\'s\nactions to business icons when implementing the app.\n\nUses the native `click` event.\n\n### Action icon\n\n```html\n<ryugi-action-icon icon="settings" title="Settings" aria-label="Settings"></ryugi-action-icon>\n```\n\nAttributes: `icon` (same set as Button), `size`, `disabled`, `title`,\n`aria-label`. Uses the native `click` event.\n\n### Tooltip and popover\n\n```html\n<ryugi-tooltip content="Copy a private link" placement="top">\n <ryugi-icon name="copy" size="14"></ryugi-icon> Copy\n</ryugi-tooltip>\n<ryugi-popover id="sharing" content="Only people you invite can open this link.">\n Sharing details\n</ryugi-popover>\n```\n\nBoth provide a native button trigger; children are its label and decorative\nicons, not nested buttons or controls. `content` is plain text, `placement`\nsets the floating position. Tooltip opens on hover/focus; Popover opens on\nclick (`trigger="hover"` opts into hover). Tooltip also accepts `open` for\na controlled preview. Native trigger clicks still reach your handlers.\n\n### Action menu\n\n```html\n<ryugi-menu id="actions" label="More" icon="ellipsis">\n <ryugi-menu-item value="copy" icon="copy">Copy link</ryugi-menu-item>\n <ryugi-menu-item value="delete" icon="trash-2" disabled>Delete</ryugi-menu-item>\n</ryugi-menu>\n```\n\nAttributes: `label`, `icon`, `placement`, `disabled`. Items accept `value`,\n`icon`, `disabled`; their text is the label. Selecting an enabled item emits\n`ryugi-change` with its action in `event.detail.value`. Actions are not\nrestored as control values on reload.\n\n### Input\n\n```html\n<ryugi-input id="title" placeholder="Title" value="Ryugi" style="width:100%"></ryugi-input>\n```\n\nAttributes: `type`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`, `borderless`), `allowClear`, `placeholder`, `value`,\n`disabled`, `name`, `aria-label`.\n\n### Textarea\n\n```html\n<ryugi-textarea id="notes" rows="4" placeholder="Notes" style="width:100%"></ryugi-textarea>\n```\n\nAttributes: `rows`, `size`, `variant`, `placeholder`, `value`, `disabled`,\n`name`.\n\n### Number\n\n```html\n<ryugi-input-number id="count" value="12" min="0" max="100" step="1"></ryugi-input-number>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `precision`, `controls`, `size`,\n`variant`, `placeholder`, `disabled`.\n\n### Slider\n\n```html\n<ryugi-slider id="size" value="32" min="0" max="100" step="1"></ryugi-slider>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `disabled`.\n\n### Slider with number input\n\nThe most useful control for tuning an exact value.\n\n```html\n<ryugi-slider-input id="radius" value="8" min="0" max="32" step="1"></ryugi-slider-input>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `controls`, `size`, `variant`,\n`disabled`.\n\n### Switch\n\n```html\n<ryugi-switch id="dark" checked></ryugi-switch>\n```\n\nAttributes: `checked`, `loading`, `size`, `disabled`, `name`.\n\n### Checkbox\n\n```html\n<ryugi-checkbox id="compact">Compact</ryugi-checkbox>\n```\n\nAttributes: `checked`, `shape`, `size`, `disabled`, `name`. Children are the\nlabel.\n\n### Segmented\n\n```html\n<ryugi-segmented id="mode" value="grid">\n <ryugi-segment value="list">List</ryugi-segment>\n <ryugi-segment value="grid">Grid</ryugi-segment>\n <ryugi-segment value="masonry">Masonry</ryugi-segment>\n</ryugi-segmented>\n```\n\nAttributes: `value`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`), `block`, `glass`, `shadow`, `vertical`, `disabled`.\n\n### Select\n\n```html\n<ryugi-select id="layout" value="a" placeholder="Choose layout">\n <ryugi-option value="a">Sidebar</ryugi-option>\n <ryugi-option value="b">Top tabs</ryugi-option>\n <ryugi-option value="c">Bottom rail</ryugi-option>\n</ryugi-select>\n```\n\nAttributes: `value`, `placeholder`, `size`, `variant`, `allowClear`,\n`showSearch`, `loading`, `mode` (`multiple`, `tags`), `disabled`.\n\n### Radio group\n\n```html\n<ryugi-radio-group id="density" value="comfortable">\n <ryugi-radio value="compact">Compact</ryugi-radio>\n <ryugi-radio value="comfortable">Comfortable</ryugi-radio>\n <ryugi-radio value="spacious">Spacious</ryugi-radio>\n</ryugi-radio-group>\n```\n\nAttributes: `value`, `horizontal`, `gap`, `size`, `disabled`.\n\n### Colour picker\n\n```html\n<ryugi-color-picker id="accent" value="#c56473" trigger="field"></ryugi-color-picker>\n```\n\nAttributes: `value`, `alpha`, `defaultFormat` (`hex`, `rgb`, `hsl`),\n`trigger` (`swatch`, `field`, `chip`), `size`, `disabled`.\n\n## Display\n\n### Toast\n\nHTML artifacts can call the bundled Lobe UI toast API as `window.ryugiToast`.\nIf the page has no `ryugi-` UI controls, opt in with the meta tag. Wait for\n`ryugi-ui:ready` before calling it:\n\n```html\n<meta name="ryugi-ui" content="1" />\n<button id="save" type="button">Save</button>\n<script>\n document.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n document.getElementById(\'save\').addEventListener(\'click\', async () => {\n try {\n await saveDraft(); // the page\'s own operation\n window.ryugiToast.success({ id: \'save-result\', title: \'Saved\' });\n } catch {\n window.ryugiToast.error({\n id: \'save-result\',\n title: \'Save failed\',\n description: \'Try again.\',\n });\n }\n });\n },\n { once: true },\n );\n<\/script>\n```\n\nMethods: `success`, `error`, `info`, `warning`, `loading`. Each takes a string\nmessage or `{ title, description, id, duration }`. Text is rendered as text,\nnot HTML. A stable `id` refreshes the same notification instead of stacking\ncopies. The default duration is 5000ms; `duration: 0` stays until closed.\n`loading` stays until closed by default.\n\nCalls return a handle with `id` and `close()`. Use\n`window.ryugiToast.dismiss(id)` to close one, or `dismiss()` to close all.\nToasts appear at the bottom right and follow the page\'s theme. They are\ntransient: rewriting the page does not restore them. No `ryugi-toast` tag is\nneeded. Artboard pages do not load this UI runtime.\n\n### Tag\n\n```html\n<ryugi-tag variant="outlined">New</ryugi-tag>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`, `solid`), `size`,\n`shape` (`normal`, `round`), `color`, `closable`.\n\n### Alert\n\n```html\n<ryugi-alert\n type="info"\n title="Streaming"\n description="Pending boards draw as skeletons."\n></ryugi-alert>\n```\n\nAttributes: `type` (`success`, `info`, `warning`, `error`, `secondary`),\n`variant` (`soft`, `outlined`, `plain`), `title`, `description`, `showIcon`,\n`closable`. Text children are used as the title when `title` is absent.\n\n### Progress\n\n```html\n<ryugi-progress percent="64" size="small"></ryugi-progress>\n```\n\nAttributes: `percent`, `size`, `status`.\n\n### Badge\n\n```html\n<ryugi-badge count="3" status="processing"></ryugi-badge>\n<ryugi-badge count="3">\n <ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n</ryugi-badge>\n```\n\nAttributes: `count`, `dot`, `status`, `text`, `showZero`, `size`, `color`.\n\n### Avatar\n\n```html\n<ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n```\n\nAttributes: `src`, `alt`, `size`, `shape`.\n\n### Divider\n\n```html\n<ryugi-divider dashed></ryugi-divider>\n```\n\nAttributes: `orientation`, `dashed`.\n\n### Card\n\n```html\n<ryugi-card variant="outlined" shadow>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Supporting copy.</ryugi-text>\n</ryugi-card>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `shadow`,\n`glass`, `clickable`. Children are preserved, including nested components.\n`glass`, `shadow` and `variant` paint the inner Block surface, not the host.\nIf the host supplies the panel background and padding, omit `glass`/`shadow`\nand use `variant="borderless"` so there is only one visible container.\n\n### Text\n\n```html\n<ryugi-text type="secondary">Secondary body text</ryugi-text>\n<ryugi-text strong>Strong label</ryugi-text>\n<ryugi-text code>const x = 1</ryugi-text>\n```\n\nAttributes: `type` (`secondary`, `success`, `warning`, `danger`, `info`),\n`strong`, `code`, `italic`, `underline`, `delete`, `mark`, `align`, `weight`.\n\n## Complete tuning panel\n\n```html\n<ryugi-card>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Tune the reading column.</ryugi-text>\n\n <ryugi-slider-input id="measure" value="64" min="40" max="90" step="1"></ryugi-slider-input>\n\n <ryugi-segmented id="density" value="comfortable">\n <ryugi-segment value="compact">Compact</ryugi-segment>\n <ryugi-segment value="comfortable">Comfortable</ryugi-segment>\n <ryugi-segment value="spacious">Spacious</ryugi-segment>\n </ryugi-segmented>\n\n <ryugi-switch id="dark"></ryugi-switch>\n <ryugi-tag>Live preview</ryugi-tag>\n</ryugi-card>\n\n<script>\n document.addEventListener(\'ryugi-change\', (event) => {\n document.body.dataset[event.target.id] = event.detail.value;\n });\n<\/script>\n```\n\n## Not included in the first version\n\nTabs, Modal, Drawer, Table, DatePicker, and layout\ncomponents. Use plain HTML/CSS or a later component if one is added.\n',phoneScreens:!0};var pg='## Mockup components\n\n`<ryugi-ios-shell>` draws the device and nothing else: the screen (402×874, iPhone 17), status bar, Dynamic Island, home indicator and, with `bezel`, the frame (442×914). Size phone boards to match. Never hand-draw those parts. Everything on the screen (navigation bar, glass buttons, tab bar, cards, lists, inputs, sheets, a floating composer) is the product\'s own design system: write it by hand in HTML/CSS from the variables of `tokens.css`, in the product\'s own style, including its own Liquid Glass where the product uses it. Do not imitate iOS Settings rows unless the product\'s own screens look like that. The shell renders in light DOM, so selection, comments and the Inspector reach every part. The server loads it when the page contains the tag; for a shell created by script add `<meta name="ryugi-mockup" content="1">` and wait for `ryugi-mockup:ready` on `document`.\n\n```html\n<!doctype html>\n<html lang="zh">\n <head>\n <meta charset="utf-8" />\n <link rel="stylesheet" href="../tokens.css" />\n <style>\n html,\n body {\n margin: 0;\n }\n .nav {\n display: flex;\n align-items: center;\n justify-content: space-between;\n height: 44px;\n padding: 0 16px;\n }\n .mark {\n font: 700 26px/32px var(--font-display);\n color: var(--color-text);\n }\n .glass {\n display: flex;\n border-radius: 22px;\n background: var(--color-glass);\n backdrop-filter: blur(16px) saturate(1.8);\n color: var(--color-text);\n }\n .glass > * {\n display: grid;\n place-items: center;\n width: 44px;\n height: 44px;\n }\n .card {\n margin: 8px 16px;\n padding: 16px;\n border-radius: var(--radius-card);\n background: var(--color-surface);\n }\n </style>\n </head>\n <body>\n <ryugi-ios-shell>\n <div class="nav">\n <span class="mark">喵旅</span>\n <span class="glass">\n <span\n ><ryugi-icon symbol="person.crop.circle" name="circle-user" size="22"></ryugi-icon\n ></span>\n <span><ryugi-icon symbol="plus" name="plus" size="22"></ryugi-icon></span>\n </span>\n </div>\n <section class="card">…</section>\n </ryugi-ios-shell>\n </body>\n</html>\n```\n\nThe variable names in the example (`--font-display`, `--radius-card`, `--color-glass`) stand for roles; use the names the product\'s own `tokens.css` defines.\n\n| Element | Attributes | Children |\n| ------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `ryugi-ios-shell` | `bezel`, `time` (9:41), `hide="status island home all"` (any of them) | the screen content: it flows from below the status bar (`--safe-top`, 62px); absolutely positioned content measures from the screen\'s top edge. `--safe-bottom` is 34px. Both stay when parts are hidden |\n| `ryugi-token-sheet` | `appearance` to show one set only | one `<script type="application/json">` |\n\nBoth take `appearance="light|dark"`, otherwise follow the nearest `[data-appearance]`, then the system. Unknown attribute values raise a runtime warning.\n\nIcons: `<ryugi-icon name>` is a Lucide icon. Add `symbol`, an SF Symbol name (`wallet.bifold.fill`): when the local server runs on macOS it draws the symbol through the system and shows it at the symbol\'s own proportions, tinted with `currentColor`; anywhere else (other systems, Ryugi Cloud, published links) the Lucide icon shows. Write both. Use `symbol` only in mockups of apps for Apple platforms; that is the condition of Apple\'s license. Symbol images are never part of `pages/` and are never published.\n\nProduct tokens live in one stylesheet (on an artboard `pages/tokens.css`), light on `:root`, dark on `[data-appearance="dark"]`. The shell\'s root carries `data-appearance`, so light and dark phones sit side by side and your content under `[data-appearance="dark"]` flips with them. The shell reads `--color-bg` (screen), `--color-text` (status bar, home indicator) and `--font-body`, falling back to iOS system values; the token sheet also reads `--color-text-secondary`, `--color-separator`, `--color-surface`, `--color-fill` and `--color-accent`. Your content reads the same variables plus the product\'s own (radius, spacing, type, glass).\n\n`ryugi-token-sheet` draws the token table from JSON that names tokens, never values; values come from the stylesheet in both appearances:\n\n```json\n{\n "groups": [\n {\n "name": "Text",\n "kind": "color",\n "tokens": [\n {\n "name": "--color-text-secondary",\n "use": "行右侧的值",\n "on": "--color-surface",\n "board": "t-color-a"\n }\n ]\n },\n {\n "name": "Type",\n "kind": "type",\n "tokens": [{ "name": "--type-body", "use": "正文", "sample": "招商银行储蓄卡" }]\n }\n ]\n}\n```\n\nKinds: `color` (swatches; with `on`, WCAG contrast per appearance flagged under 4.5:1, or 3:1 with `"large": true`), `type` (a `font` shorthand), `space`, `radius`, `size`, `shadow`, `motion` (`<duration> <easing>`, click to play). Token and group names are English; `use` and `sample` follow the product\'s language. Missing variables and broken JSON show inline errors.\n',mg="## Phone mockups\n\nEvery phone screen is a `<ryugi-ios-shell>`: it draws the 402×874 screen, status bar, Dynamic Island and home indicator, and `bezel` adds the 442×914 frame. Never hand-draw those parts; everything on the screen is the product's own design from its `tokens.css`. Before the first phone screen or `<ryugi-token-sheet>`, read the mockup guide: `start --artifact <artifact> --help --mockup`.\n",hg='# Report writing\n\nA report is data and presentation kept apart. Each data source is a Node script that prints JSON; the report is `report.tsx`, one default-exported component built only from `@ryugi/report` that imports the data it draws.\n\n```\nreport/<id>/\n report.tsx\n sources/<source-id>/source.json\n sources/<source-id>/<script>.mjs\n data/<source-id>.json written by the hub when a source runs; never write it by hand\n assets/<file>.png images the report shows (png, jpg, gif, webp, avif, svg)\n```\n\n## Data sources\n\n`sources/<source-id>/source.json`: `{ "title": "Commits per day", "description": "main branch, last 30 days", "input": "git history of the repo", "script": "collect.mjs", "args": ["--days", "30"] }`. `title` and `script` are required; the script is a `.mjs`, `.js` or `.cjs` file in the same folder. Source ids are kebab-case.\n\nThe script runs with the project root as cwd and Node from the hub, so it can use the project\'s `node_modules`. Its env is the hub\'s env with the project\'s `.env` and `.env.local` laid over it; read secrets and machine paths from env or `args`, never write them into the script. It must print one JSON value on stdout (at most 2 MB; the whole report\'s data at most 10 MB) and exit 0 within 60 s. Do the aggregation in the script: the report only draws. A stderr line `ryugi:input <text>` replaces the input shown in the panel for that run, such as the commit the data was read at; other stderr is shown when the run fails.\n\nRun sources with `ryugi report refresh --artifact report/<id>` (all) or with `--only <source-id>` (one). The hub runs them, one run per source at a time, and writes `data/<source-id>.json`. Refresh after adding or changing a source, and before `check`. Reports fetched from someone else\'s Cloud link are read-only: never run their scripts.\n\n## report.tsx\n\n```tsx\nimport {\n BarChart,\n Grid,\n Report,\n Section,\n Stat,\n Table,\n useMemo,\n useState,\n Param,\n} from \'@ryugi/report\';\nimport days from \'./data/commits-per-day.json\';\n\nexport default function Commits() {\n const [span, setSpan] = useState(14);\n const shown = useMemo(() => days.slice(-span), [span]);\n return (\n <Report title="Ryugi commits" caption="main branch">\n <Param label="Window" min={7} max={30} unit="days" value={span} onChange={setSpan} />\n <Grid columns={3}>\n <Stat\n id="total"\n source="commits-per-day"\n title="Commits"\n value={shown.reduce((sum, day) => sum + day.commits, 0)}\n />\n </Grid>\n <Section id="daily" title="Per day">\n <BarChart\n id="per-day"\n source="commits-per-day"\n title="Commits per day"\n data={shown}\n x="date"\n series={[{ key: \'commits\', label: \'Commits\' }]}\n />\n <Table\n id="days"\n source="commits-per-day"\n title="Days"\n rows={shown}\n rowKey="date"\n columns={[{ key: \'date\' }, { key: \'commits\', align: \'right\' }]}\n />\n </Section>\n </Report>\n );\n}\n```\n\nImports come only from `@ryugi/report` and `./data/<source-id>.json` (default import; the source must exist). JSX uses SDK components only: no `div`, `img`, `a` or other native elements, no network calls, `document` / `window` / `location` / `navigator` / storage access, `globalThis`, `eval`, `Function`, `.constructor`, `import()` / `require()` or timers. Words in text and strings are fine; the check reads code. The page cannot reach the network either way. `report.tsx` stays under 64 KB; put data in a source. Derive with `useMemo` and plain expressions; keep state in `useState`.\n\nEvery Stat, chart, Table, Callout, Image and Section needs an `id`: kebab-case, unique in the report, and stable across edits, since comments and references hold on to it. Stat, charts and Table also need `source`: the source id, or a list of them, that the block\'s numbers come from; the hover chip and the sources panel read it. Write `id`, `source` and `title` as string literals.\n\nComponents:\n\n- `Report` `{ title, caption? }`: the root; `title` is the artifact\'s title.\n- `Section` `{ id?, title? }`, `Grid` `{ columns?: 1 | 2 | 3 | 4 }`, `Card`, `Stack` `{ gap? }`, `Divider`.\n- `H2`, `H3`, `Text` `{ tone?: \'muted\' }`, `List` `{ items }`, `Callout` `{ id, title?, tone?: \'info\' | \'success\' | \'warning\' | \'error\' }`.\n- `Stat` `{ id, source, title, value, unit?, delta?, format?, note? }`; `delta` is signed and shown up or down.\n- `Table` `{ id, source, title?, rows, rowKey, columns: { key, label?, align?, format? }[] }`; every row prints; a click on a row starts a comment on it.\n- `LineChart`, `BarChart`, `AreaChart`, `PieChart`, `ScatterChart` `{ id, source, title, data, x, series: { key, label?, color? }[], subtitle?, stacked?, donut?, highlight?, refs?: { label, y }[], format?, note? }`: the same chart renderer as a document\'s chart block. A `ScatterChart` needs a numeric `x` in every row. A reader clicks a point to pin it and comments on that point.\n- `Param` `{ label, value, onChange, min?, max?, step?, unit? }` (a slider with a number field when min and max are set), `Select` `{ label?, value, options, onChange }`, `Toggle` `{ label, checked, onChange }`. Printed, they show the value the reader set; a comment on a point or row records them too.\n- `Image` `{ id, src, alt, caption?, width? }`: an image file from the report folder, `src` written as a string such as `"assets/sources-panel.png"`; `alt` describes it. Copy screenshots and figures into `assets/` first; remote URLs are not allowed. Comments anchor to the image as a block.\n- `useState`, `useMemo` from `@ryugi/report`.\n\n`format` is `{ unit?, decimals?, compact?, signed? }`.\n\n## Check, comments, references\n\n`ryugi check --artifact report/<id>` reports static issues (imports, native elements, missing or repeated ids, unknown sources, missing data files) and, once a browser has opened the report, render errors.\n\nComments anchor to a block, a table row or a chart point: `ryugi comment add --artifact report/<id> --block <block-id> [--point <series>:<x> | --row <rowKey>]`. A comment keeps the value it was made on and which data it saw; after a refresh changes that data it is marked data changed and stays where it was.\n\nReference a report from a document with `<ref report="<id>"/>`, or one block with `<ref report="<id>" block="<block-id>"/>`. A deck names it inline with the same `<ref>`, and shows one block on a slide with `<embed report="<id>" block="<block-id>"/>`; give the blocks a deck shows a stable `id`.\n\nPublishing includes `report.tsx`, `sources/**`, `data/**` and the images under `assets/` with the report\'s visibility. Publishing is refused while a script, `report.tsx` or the data holds an absolute machine path (`/Users/…`, `/home/…`, `C:\\\\…`, not checked in data) or something that looks like a secret (`sk-…`, `ghp_…`, `AKIA…`, a private key, a value from `.env`); the refusal names the file and line.\n';function gg(e){if(!e.block)throw new F(`comment add on a report needs --block <blockId>`);if(e.point!==void 0&&e.row!==void 0)throw new F(`comment add takes --point or --row, not both`);let t;if(e.point!==void 0){let n=e.point.indexOf(`:`);if(n<=0||n===e.point.length-1)throw new F(`--point needs <series>:<x>, such as commits:Nov 2`);t={series:e.point.slice(0,n),x:e.point.slice(n+1)}}return{op:`add`,block:e.block,...t?{point:t}:{},...e.row===void 0?{}:{row:e.row},text:Kt(e)}}const _g={authoring:hg,review:{sections:[]},commentActions:{add:gg}};var vg='# Slides writing\n\nWrite one complete `deck.xml` under the returned artifact directory; put images in `assets/` and reference them with relative paths. The deck is for an audience: your human partner presents it. Re-read before each edit; never edit `comments.json` or `.state/`. Finish with `check`.\n\nThe file holds what the slides say. The server compiles it into the page and adds the presentation engine, theme, code highlighting, diagrams and formulas. Only the tags and attributes below exist: there is no `class` and no `style`, and `check` reports anything else by slide and tag.\n\n```xml\n<deck title="Retry policy" lang="en">\n <slide id="cover" layout="cover">\n <kicker>Delivery · Q3</kicker>\n <h1>Retry policy</h1>\n <subtitle>Why failed deliveries now retry three times</subtitle>\n <notes>Open with last month\'s incident.</notes>\n </slide>\n\n <slide id="what-changes">\n <h2>What changes</h2>\n <ol steps="true">\n <li>At most three attempts</li>\n <li>Exponential backoff</li>\n </ol>\n </slide>\n\n <slide id="backoff" layout="code">\n <h2>Backoff</h2>\n <codeblock lang="ts" lines="1|2-3"><![CDATA[\n const delay = (attempt: number) =>\n Math.min(30_000,\n 500 * 2 ** attempt);\n ]]></codeblock>\n </slide>\n</deck>\n```\n\n## Slides\n\n- One slide is one `<slide>` directly inside `<deck>`. The deck\'s `title` is required; `lang` is optional.\n- Every slide needs a unique, stable `id` of lowercase letters, digits and hyphens. Comments and document references find a slide by its id: keep the id when you rewrite a slide, and only change it when the slide becomes a different slide. Deleting a slide orphans its comments.\n- The canvas is fixed at 1280×720. Content that leaves that box is reported by `check` as overflow, naming the slide. Fix it by cutting or splitting the slide; `zoom="0.8"` on the slide (0.3 to 1) is for the one dense slide that must stay whole.\n- While the deck is open in the viewer, `check` also names contact sheet images (`Sheet:`) that show every slide at its last step, twelve to an image, with overflowing and hidden slides marked. After editing, run `check`, open those images, and look for slides that are too full or that all look like the same template. `sheet_not_drawn` under `Pending` means the open viewer has not drawn this version yet. `Sheet: unavailable (…)` means it cannot be drawn, as for a deck holding a video or an iframe: go on without it.\n- `hidden="true"` keeps a slide in the file and out of the talk: it shows, marked, only while the deck is worked on; presenting, the audience window, the PDF and a published link never get it, and it takes no page number.\n- `<group id="evidence" title="What the data says">` inside `<deck>` gathers the slides of one part of the talk. It holds only `<slide>` and `<include>`, never another group; its `id` follows the slide id rules and is unique among slides and groups, and `title` is required. The grid view shows each group as a titled row; the audience sees nothing of it. Slides outside any group are fine, before, between or after groups.\n- `cover="<slide id>"` on `<deck>` names the slide that stands for the deck in lists and links. `check` warns when it names a slide that is missing or hidden.\n- Write XML: close every tag, quote every attribute, write `&lt;` and `&amp;` in text; common names such as `&nbsp;`, `&mdash;` and `&rarr;` work, any other is an error, so write the character itself. Code, diagrams and formulas go in `<![CDATA[ … ]]>` so nothing in them needs escaping. CDATA ends at the first `]]>`: code that contains `]]>` comes from a file with `src`. End the file with `</deck>`.\n\n## Layouts\n\nPick the layout that fits what the slide says, and vary them: a deck of identical title-and-bullets slides reads as a template. Each layout adds a few places of its own; a place used in another layout is reported. The theme adds the page number itself.\n\n| `layout` | Use it for | Inside the slide |\n| ----------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------- |\n| `default` | A title with text, a list, a table or code | Optional `<label>`, an `<h2>`, then blocks. Omitting `layout` gives this one |\n| `cover` | The first slide | `<kicker>`, `<h1>`, `<subtitle>` |\n| `section` | The start of a new part | Optional `<label>`, then an `<h1>` or `<h2>` |\n| `statement` | One sentence the audience should remember | Optional `<label>`, an `<h2>` with the key words in `<mark>`, optional `<subtitle>` |\n| `two-cols` | Two things side by side | An `<h2>`, then exactly two `<col>`, each holding blocks |\n| `image` | Text beside a picture | One `<col>` holding the text and one `<img>`; whichever comes first is on the left |\n| `quote` | A quotation | `<quote>` and `<cite>` |\n| `fact` | One number that matters | `<big value="10–12" unit="working days"/>`, then up to three `<fact value="5 days" label="API"/>` |\n| `code` | Code as the subject of the slide | Optional `<label>`, an `<h2>` and one `<codeblock>` or one `<magic>` |\n| `end` | The last slide | An `<h1>` |\n| `none` | A slide you lay out yourself | `src` naming an HTML file; see Free HTML. No padding and no page number |\n\n```xml\n<slide id="numbers" layout="fact">\n <big value="13" unit="harnesses supported"/>\n <fact value="5" label="artifact types"/>\n <fact value="0" label="subscriptions"/>\n</slide>\n<slide id="before-after" layout="two-cols">\n <h2>Before and after</h2>\n <col>\n <h3>Before</h3>\n <p>One attempt, then a page.</p>\n </col>\n <col>\n <h3>After</h3>\n <p>Three attempts, then a page.</p>\n </col>\n</slide>\n<slide id="dashboard" layout="image">\n <col>\n <label>Result</label>\n <h2>Failures fell by half</h2>\n </col>\n <img src="assets/dashboard.png" alt="Failure rate before and after the change" frame="true"/>\n</slide>\n```\n\n## Blocks and text\n\nBlocks sit in a slide or a `<col>`: `<h1>`, `<h2>`, `<h3>`, `<p>`, `<ul>` and `<ol>` of `<li>` (a list may nest in an item), `<table>` of `<tr>` holding `<th>` or `<td>`, `<blockquote>`, `<hr/>`, `<alert type="note|tip|important|warning|caution">` holding blocks, `<img>`, `<icon>`, `<codeblock>`, `<magic>`, `<mermaid>`, `<math>`, `<html>`, `<embed>` and `<notes>`.\n\nBlocks and inline tags a document also has carry the same names here. Inside text: `<b>`/`<strong>`, `<i>`/`<em>`, `<u>`, `<s>`/`<del>`, `<sub>`, `<sup>`, `<code>`, `<mark>`, `<a href="…">`, `<br/>`, `<math>`, `<icon>` and `<ref>`.\n\n- `<img src="assets/chart.png" alt="…"/>` shows a file of the artifact directory. `frame="true"` gives a screenshot rounded corners and a shadow.\n- `<icon name="check" size="32"/>` draws an icon; `size` is in pixels.\n- `<mermaid>` holds a Mermaid diagram and `<math>` a LaTeX formula, both in CDATA. `<math>` inside text is an inline formula.\n- `<notes>` holds speaker notes, shown only to the presenter. One per slide, plain text with `<br/>` between lines.\n\n```xml\n<h2>How a delivery flows</h2>\n<mermaid><![CDATA[\n flowchart LR\n A["ingress<br/>edge"] --> B[queue] --> C[worker]\n]]></mermaid>\n<table>\n <tr><th>Attempt</th><th>Delay</th></tr>\n <tr><td>1</td><td><math>500 \\cdot 2^1</math> ms</td></tr>\n</table>\n<p><icon name="check" size="24"/> Shipped behind a flag, see <a href="https://example.com/rfc">the RFC</a>.</p>\n```\n\n## Code\n\n`<codeblock lang="ts">` is a code block, named as in a document; `<code>` is inline code inside text. Write the code in CDATA; the indentation it shares with the XML is taken off.\n\n- `lines`: stepped line highlight. Parts are separated by `|`, each one step, lines count from 1: `1`, `2-3`, `2-3,5`; `all` lights every line and `hide` hides the block for that step.\n- `src="src/retry.ts#L10-24"`: take the code from a file of the project instead of writing it, optionally only those lines. The path is relative to the project root; files outside the project, dot-files such as `.env`, and files over 512 KB are refused, and so are files named like secrets (`secrets.*`, `credentials.*`, `*.pem`, `*.key`, `*.tfstate`, `*.tfvars`, SSH keys) and files git ignores. Never show a file that holds a secret under another name. What a deck shows is published with it.\n- `numbers="true"`: line numbers. `title="src/retry.ts"`: a title above the block. `max-height="320"`: a height in pixels past which the block scrolls, following the highlighted lines. `diff="true"`: lines starting with `+` or `-` are drawn as added or removed.\n- `<magic lang="ts">` holds two or more `<step>`, each the whole code at one step, in CDATA; what stays moves into place, and each step after the first is a step of the slide.\n\n```xml\n<codeblock lang="ts" src="src/retry.ts#L10-24" numbers="true" title="src/retry.ts" lines="all|3-5"/>\n<codeblock lang="ts" diff="true"><![CDATA[\n const attempts =\n - 1;\n + 3;\n]]></codeblock>\n<magic lang="ts">\n <step><![CDATA[const delay = 500;]]></step>\n <step><![CDATA[const delay = (attempt: number) => 500 * 2 ** attempt;]]></step>\n</magic>\n```\n\n## Steps and marks\n\n- `step="true"` on a block or a list item: it appears on the next step. `steps="true"` on a `<ul>`, `<ol>`, `<table>` or `<col>` makes each item, row or block a step.\n- `step="2"` places a step by number, and `step="with"` makes it appear together with the step before it.\n- `<mark>` highlights words. `type="highlight"`, `underline`, `circle` or `strike` draws that mark; with `step` the words are there from the start and the mark is drawn on its step.\n- `morph="title"` on a block in two consecutive slides moves it from one to the other; a name is used once per slide and the pair should hold the same text.\n\n```xml\n<h2 morph="title">The <mark type="underline" step="true">retry budget</mark> is per delivery</h2>\n<p step="true">Three attempts in total.</p>\n<p step="with">The first one counts.</p>\n<ul steps="true">\n <li>500 ms</li>\n <li>1 s</li>\n</ul>\n```\n\n## Several files and free HTML\n\n- `<include src="parts/appendix.xml"/>` inside `<deck>` puts the slides of another file of the artifact directory there. That file starts with `<slides>`, holds only `<slide>`, and cannot include further files. Ids stay unique across all files.\n- `<html src="parts/demo.html"/>` is a block of HTML you write yourself, in a file of the artifact directory.\n- `<slide id="demo" layout="none" src="parts/demo.html"/>` is a whole slide of your own HTML: you own every pixel of 1280×720. It may hold `<notes>` and nothing else.\n- A free HTML file is a fragment: no page wrapper, every `<div>` closed. `data-step` on an element inside it makes that element a step. It runs in the deck\'s sandbox: no localStorage, sessionStorage or cookies.\n\n```xml\n<deck title="Retry policy">\n <slide id="live-demo" layout="none" src="parts/demo.html">\n <notes>Click through the three states.</notes>\n </slide>\n <slide id="curve">\n <h2>The backoff curve</h2>\n <html src="parts/curve.html"/>\n </slide>\n <include src="parts/appendix.xml"/>\n</deck>\n```\n\n## Other artifacts\n\n`<embed>` puts another artifact of this project on the slide. Name the target by its slug, as a document\'s `<ref>` does:\n\n- `<embed artboard="settings-page" board="q1-b"/>` shows one board of an artboard, in a box of the board\'s shape.\n- `<embed whiteboard="sync-flow" frame="f1"/>` shows one frame of a whiteboard; `page="<page id>"` instead of `frame` shows a whole page. The box takes the shape of the frame or of what is drawn on the page.\n- `<embed report="q3-revenue" block="by-month"/>` shows one block of a report at the slide\'s width and at the block\'s own height, in the deck\'s light or dark.\n- `<embed slides="launch" slide="pricing"/>` shows one slide of another deck at 1280×720, at its last step, in that deck\'s own theme. Embeds on that slide hold their place under their names: decks nest one level.\n- `<embed html="spring-curve"/>` shows an html page, at 1280×720.\n\nAn embed is live: it shows the target as it is now, changes when the target does, and can be scrolled and clicked during the talk. Its corner button opens the target nearly full screen at the embedded part, and Esc closes it. In thumbnails, PNG and PDF export and the contact sheet every embed is a picture of the target.\n\n`<ref>` names another artifact inside text, as a chip: `<ref document="retry-policy">the design</ref>`, `<ref report="q3-revenue" block="by-month"/>`, `<ref whiteboard="sync-flow" frame="f1"/>`. Every kind a document can reference can be named, with the same attributes; with no text of its own the chip shows the target\'s title. Clicking it opens the target nearly full screen; nothing opens while the slide is edited or the pen or laser is on.\n\nPublished, a deck shows the published versions of what it embeds and names. A target that is private, unpublished or gone shows to visitors as its chip text or as an unpublished artifact, never its title or a picture of it; its owner sees it. Publishing the deck offers what it embeds and names to publish with it.\n\nAn embed takes `step` and `morph` like any block. `check` warns, naming the slide, when the artifact or the part it names (board, frame, page, block, slide) is not there, and the slide shows the target\'s name in its place. A `<ref>` to a missing target is warned about the same way.\n\n```xml\n<slide id="settings" layout="two-cols">\n <h2>The settings page</h2>\n <col>\n <p>Option B keeps billing on the first screen.</p>\n </col>\n <col>\n <embed artboard="settings-page" board="q1-b"/>\n </col>\n</slide>\n```\n\n## Theme, motion and glow\n\nChange the look for the whole deck with one `<theme>` before the first slide. `name` picks the theme: `paper` (the default: warm paper, one seal-coloured accent, glow) or `mono` (black on white, monospace labels, emphasis by weight, no glow). `appearance` is `light`, `dark` or `auto`; `auto`, the default, follows the system of whoever opens the deck and prints light, so write `light` or `dark` when the room decides. Every other attribute overrides one variable of the theme, in both appearances. A deck that sets its own `paper`, `surface` or `ink` is `light` unless it names an appearance: those colours suit one appearance only. Do not restyle slide by slide.\n\n```xml\n<deck title="Retry policy">\n <theme name="paper" appearance="dark" accent="#0a7cff" transition="slide-left" fragment="rise" glow-opacity="0.6"/>\n <slide id="cover" layout="cover" transition="fade" glow="top-right" glow-seed="launch">\n <h1>Retry policy</h1>\n </slide>\n</deck>\n```\n\n| `<theme>` attribute | Values | Paper |\n| ----------------------------- | ------------------------------------------------------------ | ------------------------------- |\n| `paper`, `surface` | the slide\'s background, and that of code and cards | |\n| `ink`, `ink-2`, `ink-3` | text, secondary text, labels | |\n| `accent`, `on-accent`, `info` | the accent colour, text on it, and the second accent | |\n| `rule`, `rule-strong` | hairlines | |\n| `font`, `font-mono` | font families | |\n| `transition` | `view`, `fade-out`, `fade`, `slide-left`, `slide-up`, `none` | `view` |\n| `transition-duration` | a time | `500ms` |\n| `transition-blur` | a length | `5px` |\n| `fragment` | `blur`, `fade`, `rise` | `blur` |\n| `fragment-duration` | a time | `500ms` |\n| `fragment-blur` | a length | `3px` |\n| `glow` | `on`, `off` | `on` |\n| `glow-1`, `glow-2`, `glow-3` | colours of the three shapes | `#9440e3`, `#41d1ff`, `#dce354` |\n| `glow-fade` | the colour each shape fades to | `rgb(255 255 255 / 0.1)` |\n| `glow-opacity` | 0 to 1 | `1` |\n| `glow-blur` | a length | `70px` |\n| `glow-drift` | how long the glow takes to move to the next slide\'s place | `2500ms` |\n| `glow-hue` | an angle | `0deg` |\n| `glow-at` | a glow place | `full` |\n\nTransitions:\n\n- `view`: the slide fades out, then the next fades in, both blurred; blocks with the same `morph` on both slides move and resize between them.\n- `fade-out`: the same fade out then in, without moving blocks.\n- `fade`: both slides cross-fade.\n- `slide-left`, `slide-up`: the next slide pushes in from the right or from below; going back reverses it.\n- `none`: the slide changes at once.\n\nSteps: `blur` fades a step in from a blur, `rise` also lifts it 12px, `fade` only fades it.\n\nOn a `<slide>`:\n\n- `transition`: the transition into this slide, one of the values above.\n- `glow`: where this slide\'s glow sits: `full`, `top`, `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`, or `none` for no glow. Left out, the place follows the layout and changes from slide to slide.\n- `glow-seed`: any text; the same seed on the same page number always gives the same shapes.\n- `glow-opacity`: 0 to 1, this slide only.\n- `glow-hue`: degrees, this slide only.\n\n`check` reports an unknown transition or glow place and a `morph` name used twice in one slide. With reduced motion, turns are instant and the glow does not move.\n\n## Placing blocks freely\n\nA layout arranges a slide for you. When a slide must sit exactly as drawn, put `free="true"` on it: every block it holds, inside a `<col>` too, then takes `x`, `y` and `w` in slide pixels of the 1280×720 canvas, and `h` when its height matters (pictures, embeds, diagrams). The layout stays named, so its type sizes still apply, and removing `free` with the coordinates brings the layout back. A block on a free slide without `x`, `y` and `w` is reported, and so are coordinates on a slide that is not free. Later blocks sit on top of earlier ones.\n\n```xml\n<slide id="library" layout="two-cols" free="true">\n <h2 id="b4k2qz" x="96" y="80" w="520">The library</h2>\n <col>\n <p x="96" y="180" w="420" align="center" color="muted">Every artifact, one server.</p>\n </col>\n <col>\n <img x="640" y="120" w="560" h="380" src="assets/library.png" alt="The library page" frame="true"/>\n </col>\n</slide>\n```\n\n- `align="left|center|right|justify"` and `color` work on text blocks on any slide. `color` takes a theme colour, `ink|muted|faint|accent|info`, which follows the theme and its light and dark appearances, or a fixed `#RRGGBB` / `#RRGGBBAA`, which does not. Prefer the theme colours.\n- On a free slide, `w="fill"` stretches a block from its `x` to the right safe margin, and a text block may take `h`: what does not fit is clipped, unless the block also has `fit="shrink"`, which shrinks its text until it fits.\n\n### Look attributes\n\nYour human partner tunes blocks in the viewer\'s tweak panel. Each setting is one attribute on the block, on any slide; `check` reports a value outside its range and an attribute on a block that does not take it.\n\n| Attribute | Blocks | Value |\n| --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- |\n| `size="32"` | text | font size, 8–400 px |\n| `weight="600"` | text | 100–900 in steps of 100 |\n| `font="Avenir Next"` | text | `mono` or a font name; a font missing on another machine falls back to the theme font |\n| `leading="1.4"` | text | line height, 0.8–3 |\n| `tracking="-0.5"` | text | letter spacing, -20–100 px |\n| `pad="16"` | text, table, codeblock, code, alert, big, fact | padding, 0–200 px |\n| `fill="surface"` | all but hr, icon and html | a theme colour (`surface`, `paper`, `ink`, `muted`, `faint`, `accent`, `info`) or hex |\n| `opacity="80"` | all but html | 0–100 |\n| `radius="12"` | all but hr, icon and html | 0–360 px |\n| `border="solid"` | all but hr, icon and html | `solid`, `dashed` or `dotted`, 1 px in the theme\'s rule colour |\n| `shadow="0 8 24 #00000040"` | all but hr, icon and html | x, y, blur in px and a colour |\n\n```xml\n<slide id="promise" free="true">\n <p x="96" y="180" w="fill" h="120" fit="shrink" size="32" weight="600" fill="surface" radius="12" pad="16">Every artifact, one server.</p>\n</slide>\n```\n\nThese are deliberate choices: keep these attributes when you rewrite a block, unless changing them is the point.\n\n- An `id` on a block (letters, digits, `_` and `-`, at most 32) is how the viewer and comments know that block again. Your human partner\'s edits give blocks ids: keep every block id when you rewrite a slide, as you keep slide ids.\n\n## Rules\n\n- A talk is given offline: keep fonts, scripts and images inside the artifact directory and avoid CDNs.\n- Notes are not secret: they are hidden from viewers in the interface but remain in the page source.\n- Your human partner can edit notes in the viewer. Saving writes that slide\'s `<notes>` back as plain text lines joined by `<br/>`, replacing any markup inside it, in the file the slide is written in.\n- Keep the whole artifact under 20 MB.\n- Your human partner can edit slides in the viewer: select blocks, drag and resize them (which makes a slide `free="true"`), type into them, change their tag, alignment, colour and every look attribute, restack blocks, change a slide\'s layout, add text boxes, copy, paste and delete. Each edit rewrites the slide in `deck.xml` or its include file in place and is listed by `changes`. Re-read the file before every edit. When you write over one of their edits before you have read it, `check` warns with `W_HUMAN_EDIT_OVERWRITTEN`, naming the slide, the block and what they had set: put their edit back unless you meant to change it.\n- Your human partner can restructure the deck in the viewer\'s grid: reorder and duplicate slides, skip them, add placeholder slides, delete them, and create, rename or move groups. Each change rewrites `deck.xml` (and an include file, for a slide written there) in place, keeping the rest of the text as it was. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact slides/<id>` and read them before editing the deck, so you build on their order instead of writing it back.\n\n## Feedback\n\nComments are anchored to a slide, usually to a point on it. `comment list --sections threads --detail` shows the slide id, its title, the text under the pin and the message. A comment made on selected blocks lists them as `nodes`, each with its block (`#id`, or its position on the slide) and its text: change those blocks. Edit that slide, keep its id, run `check`, then reply with what changed. A comment whose slide was deleted is listed as an orphan.\n\nRun the returned Check command after every edit. Without a browser it reports XML that does not parse, tags, attributes and values the deck cannot take, files it cannot read, missing or duplicate ids, unknown layouts, missing assets and embeds whose target is not there, each naming its slide. Slides that overflow and code, diagram or formula errors come from the browser: with no browser open the result is pending, not clean.\n';const yg=[`default`,`cover`,`section`,`statement`,`two-cols`,`image`,`quote`,`fact`,`code`,`end`,`none`],bg=/^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/,xg=e=>{let t=e.trim();return t===`all`||t===`hide`?t:null};function Sg(e){let t=[];for(let n of e.split(`|`)){let e=xg(n);if(e){t.push(e);continue}let r=/* @__PURE__ */ new Set;for(let e of n.split(`,`)){let t=bg.exec(e);if(!t)continue;let n=Number(t[1]),i=t[2]===void 0?n:Number(t[2]),a=Math.max(n,i);for(let e=Math.max(1,Math.min(n,i));e<=a&&!(r.size>=2e3);e++)r.add(e)}r.size&&t.push([...r].sort((e,t)=>e-t))}return t}const Cg=e=>e.split(`|`).every(e=>xg(e)!==null||e.split(`,`).every(e=>{let t=bg.exec(e);return t!==null&&Number(t[1])>=1&&Number(t[2]??1)>=1})),wg=[`view`,`fade-out`,`fade`,`slide-left`,`slide-up`,`none`],Tg=[`full`,`top`,`bottom`,`left`,`right`,`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`,`none`],Eg=e=>wg.includes(e),Dg=e=>Tg.includes(e),Og=/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i;function kg(e){let t=e?.trim();return!t||Og.test(t)?null:t.split(/[?#]/)[0]||null}const Ag=/^[a-z0-9][a-z0-9-]*$/,jg=`((?:"[^"]*"|'[^']*'|[^'">])*)`,Mg=RegExp(`<!--[\\s\\S]*?(?:-->|$)|<(script|style|textarea|template|title)\\b${jg}>([\\s\\S]*?)(?:<\\/\\1\\s*>|$)|<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)${jg}>`,`gi`),Ng=/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,Pg=/reveal(?:\.min)?(?:\.esm)?\.m?js(?:[?#]|$)/i,Fg={lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,amp:`&`};function Ig(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(Ng)){let e=n[1].toLowerCase();t.has(e)||t.set(e,n[2]??n[3]??n[4]??``)}return t}function Lg(e){return e.replaceAll(/<[^>]*>/g,``).replaceAll(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi,(e,t,n,r)=>t?String.fromCodePoint(Number(t)):n?String.fromCodePoint(Number.parseInt(n,16)):Fg[String(r).toLowerCase()]??e).replaceAll(/\s+/g,` `).trim().slice(0,200)}function Rg(e){let t=e.toLowerCase(),n=[],r=[],i=null,a=null,o=!1,s=!1,c=0,l=/* @__PURE__ */ new Set,u=e=>{let t=kg(e);t&&l.add(t)},d=e=>{for(let t=n.length-1;t>=0;t--)if(n[t].tag===e){for(let e of n.splice(t))e.kind===`slide`&&(i=null),e.kind===`notes`&&--c;return}};Mg.lastIndex=0;for(let l=Mg.exec(e);l;l=Mg.exec(e)){let[,f,p=``,m=``,h,g,_=``]=l;if(f){let e=f.toLowerCase();e===`title`&&!i&&a===null&&(a=Lg(m)||null);let t=e===`script`?Ig(p).get(`src`):void 0;u(t),e===`script`&&(Pg.test(t??``)||m.includes(`Reveal.initialize`))&&(s=!0);let r=n.at(-1);e===`template`&&i&&!c&&r?.kind===`magic`&&(r.templates=(r.templates??0)+1,r.templates>1&&(i.steps+=1));continue}if(!g)continue;let v=g.toLowerCase();if(h){(v===`div`||v===`section`||v===`aside`)&&d(v);continue}let y=Ig(_);u(y.get(`src`)),v===`link`&&u(y.get(`href`));let b=(y.get(`class`)??``).split(/\s+/).filter(Boolean),x=n.at(-1)?.kind;if(i&&!c){let n=y.get(`data-morph`)?.trim();if(n&&(i.morphs.has(n)&&!i.morphRepeats.includes(n)&&i.morphRepeats.push(n),i.morphs.add(n)),b.includes(`fragment`)){let e=y.get(`data-fragment-index`);e!==void 0&&i.positions.has(e)||(i.steps+=1),e!==void 0&&i.positions.add(e)}if(v===`code`&&(i.steps+=Math.max(0,Sg(y.get(`data-lines`)??``).length-1)),!i.titled&&/^h[1-3]$/.test(v)){let n=t.indexOf(`</${v}`,Mg.lastIndex);i.title=Lg(e.slice(Mg.lastIndex,n===-1?void 0:n)),i.titled=!0}}if(v===`div`){let e=`other`;!o&&x===`reveal`&&b.includes(`slides`)?(e=`slides`,o=!0):!o&&b.includes(`reveal`)?e=`reveal`:i&&b.includes(`magic-move`)&&(e=`magic`),n.push({tag:v,kind:e})}else if(v===`section`){if(x===`slides`){let e=b.find(e=>e.startsWith(`l-`)),t=e?e.slice(2):`default`;i={id:y.get(`id`)||null,layout:t,title:``,steps:0,notes:!1,nested:!1,titled:!1,unknownLayout:yg.includes(t)?null:t,transition:y.get(`data-transition`)?.trim()??null,glow:y.get(`data-glow`)?.trim()??null,morphs:/* @__PURE__ */ new Set,morphRepeats:[],positions:/* @__PURE__ */ new Set,...y.has(`data-deck-hidden`)?{hidden:!0}:{},...y.get(`data-deck-group`)?{group:y.get(`data-deck-group`)}:{}},r.push(i),n.push({tag:v,kind:`slide`})}else i&&(i.nested=!0),n.push({tag:v,kind:`other`})}else if(v===`aside`){let e=i!==null&&b.includes(`notes`);e&&(i.notes=!0,c+=1),n.push({tag:v,kind:e?`notes`:`other`})}}let f=[],p=/* @__PURE__ */ new Set,m=r.map(({nested:e,titled:t,unknownLayout:n,transition:r,glow:i,morphs:a,morphRepeats:o,positions:s,...c},l)=>{let u=c.id??void 0;c.id?Ag.test(c.id)?p.has(c.id)&&f.push({code:`duplicate_id`,slide:l,id:u}):f.push({code:`invalid_id`,slide:l,id:u}):f.push({code:`missing_id`,slide:l}),c.id&&p.add(c.id),e&&f.push({code:`nested_slide`,slide:l,...u?{id:u}:{}}),n&&f.push({code:`unknown_layout`,slide:l,...u?{id:u}:{},detail:n});let d={slide:l,...u?{id:u}:{}};r!==null&&!Eg(r)&&f.push({code:`unknown_transition`,...d,detail:r}),i!==null&&!Dg(i)&&f.push({code:`unknown_glow`,...d,detail:i});for(let e of o)f.push({code:`duplicate_morph`,...d,detail:e});return c});return s&&f.push({code:`own_reveal`,slide:-1}),{complete:/<\/html\s*>\s*$/i.test(e),hasDeck:o,title:a,slides:m,issues:f,assets:[...l]}}const zg=new Map(Object.entries({lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`,nbsp:`\xA0`,mdash:`—`,ndash:`–`,hellip:`…`,rarr:`→`,larr:`←`,uarr:`↑`,darr:`↓`,harr:`↔`,copy:`©`,reg:`®`,trade:`™`,times:`×`,divide:`÷`,middot:`·`,bull:`•`,laquo:`«`,raquo:`»`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`,deg:`°`,plusmn:`±`,le:`≤`,ge:`≥`,ne:`≠`,euro:`€`,pound:`£`,yen:`¥`})),Bg=/[A-Za-z_][\w.-]*/y,Vg=/\s*/y,Hg=e=>`name`in e;function Ug(e,t){return e.replaceAll(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]*));/g,(e,n,r,i,a)=>{let o=n?Number(n):r?Number.parseInt(r,16):null;if(o!==null)return o>0&&o<=1114111?String.fromCodePoint(o):e;let s=zg.get(i);return s===void 0&&t?.(i,a),s??e})}function Wg(e){return Hg(e)?e.children.map(Wg).join(``):e.text}function Gg(e){let t=[],n=null,r=t=>{if(!n){n=[];for(let t=e.indexOf(`
320
+ `);return t.title?`**${t.title}**\n\n${a}`:a}const $h=e=>e.root;function eg(e,t){return new Jh(new Map(t.map(e=>[e.id,e]))).document($h(e).children)}const tg=e=>[...e.replaceAll(/\s/g,``)].length;function ng(e,t=[]){let n=new Jh(new Map(t.map(e=>[e.id,e]))),r=[];for(let t of $h(e).children??[])t.type===`heading`?r.push({id:Uh(t.$?.blockId),level:Number(Uh(t.tag).slice(1))||1,title:n.inline(t.children),chars:0}):r.length&&(r.at(-1).chars+=tg(n.block(t)));return r}function rg(e){try{return _n(hn(u.default.readFileSync(d.default.join(e,`comments.json`),`utf8`))).threads}catch{return[]}}function ig(e){let t=zh(u.default.readFileSync(d.default.join(e,`doc.xml`),`utf8`)),n=cn(en(t),rg(e)),r=bn(e);return{markdown:(r?`${Bh}\n\n${r.markdown}\n\n---\n\n`:``)+eg(t,n),outline:ng(t,n)}}function ag(e,t,n,r){if(e===`submit`)return{op:`submit`,submit:!t.withdraw};if(!t.ask)throw new F(`comment ${e} needs --ask <questionId>`);if(e===`note`)return{op:`note`,ask:t.ask,text:n()};let i=r?.trim();if(!t.clear&&!t.choice&&!i)throw new F(`comment answer needs --choice <value>, --text <answer>, or --clear`);return{op:`answer`,ask:t.ask,choice:t.clear?null:t.choice??null,answer:t.clear?null:i??null}}var og='# Document writing\n\nWrite `doc.xml` under the returned artifact directory; put assets in `assets/`. Re-read immediately before each edit: the human and server edit this file too. Patch intended blocks, preserve existing IDs and human text; new blocks omit IDs and receive them from the server. Never edit `comments.json` or `.state/`. The server normalizes aliases and indentation after saving. Finish with `check`; pending merging or browser work means check again, not success.\n\nUse a closed `<doc>`. Choose blocks for the reader: diagrams show relationships, charts compare numbers, tables map exact attributes, prose explains reasons. A first draft can contain `<pending intent="What remains to investigate"/>`; fill every pending before claiming completion. Diagrams use native mermaid, or a whiteboard of this project embedded with a reference (below); never pictures of text or box drawing in code blocks.\n\nComplete block and inline vocabulary:\n\n- `h1`–`h6`, `p`, `blockquote`, `ul`/`ol` with `li`, `table`/`tr`/`th`/`td`, `hr`.\n- Inline `b i u s code sub sup mark a br`; aliases `strong em del strike`. Links use `href`. Ordered lists accept `start`; checklists use `<ul type="check"><li checked="true">Done</li></ul>`.\n- `codeblock lang="ts"`: code; use CDATA for literal XML/angle brackets. `mermaid`: native flowcharts/sequences/states. `math`: inline LaTeX, `display="block"` for a block.\n- `img src="assets/image.png" alt="…" caption="…" width="640"`: real images.\n- `alert type="note|tip|important|warning|caution"`: block children. `details summary="…" open="true"`: collapsed depth; omit open for collapsed. `steps` contains `step title="…"` with block children; titles omit numbering.\n- `footnote ref="1"` inline; `footnote-section` contains `def ref="1"` definitions.\n- `chart`: CDATA ChartSpec JSON. Required `version:1`, `type:bar|line|area|pie`, `x` category field, `series:[{key,label?}]`, `data` rows containing x and every series key. Values numbers/null, pie nonnegative. At most 6 series and 6 pie rows. Optional title/subtitle/note/source/xLabel/stacked/donut/highlight, format `{unit,compact,decimals,signed}`, y `{min,max}`, refs `[{y,label}]`. `highlight` is a `series.key` and highlights that entire series; omit it when unnecessary. With `series:[{key:"failures"}]` and rows `[{phase:"Before",failures:12},{phase:"After",failures:4}]`, `highlight:"failures"` is valid; `highlight:"After"` is invalid because it is a row/category value.\n- `dynamic url="assets/demo.html" initial-height="240"`: CDATA JSON becomes `window.ryugiProps`. Self-contained sandboxed HTML, inline scripts/styles, size by content, transparent body. Browser controls persist on HTML rewrite; changing props resets them. Runtime is incomplete until the block has run. Native HTML/CSS/JS and `ryugi-icon` work; storage/cookies do not.\n- `pending intent="…"`, inline `ask`/`option` and `ref` (below; a whiteboard `ref` can also embed as a block). Other tags are rejected.\n\n```xml\n<doc>\n <h1>Retry policy</h1>\n <p>Retry failed delivery at most <b>3</b> times.</p>\n <mermaid><![CDATA[flowchart LR\n ingress --> queue --> worker]]></mermaid>\n <p>Choose a strategy: <ask id="retry-strategy" recommend="exponential"><option value="fixed">Fixed delay</option><option value="exponential">Exponential backoff</option></ask></p>\n <details summary="Evidence"><codeblock lang="text"><![CDATA[attempts: 3]]></codeblock></details>\n</doc>\n```\n\nQuestions: `ask` is inline in p/li/table-cell paragraphs, never directly under doc. Its unique stable id is lowercase letters/digits/hyphens; never reuse an old question ID. Options contain plain text and distinct `value`s; `recommend` must name an option. No options makes an open question: `<ask id="other" placeholder="Describe it"/>`. Human picks are drafts until submitted. Read `comment list --sections threads,asks --detail`. Apply submitted answers, then `comment note --ask <id> --text <what changed>`. Every submitted question needs a note, even unanswered ones (state what was left or assumed). Record terminal answers only when actually supplied via `comment answer --ask <id> --choice <value>` or `--text`, then `comment submit`. Never invent an answer; wait after withdrawal. Changed settled answers require a human instruction and a fresh note.\n\nReferences: inline `<ref document="slug"/>`, `<ref document="slug" block="block-id"/>` (one top-level block of a document: the `id` of its `h2`, `p`, list…; name this document\'s own slug to jump within it), `<ref html="slug">label</ref>`, `<ref artboard="slug" group="q1"/>` (or board), `<ref whiteboard="slug" frame="f1"/>` (or page), `<ref slides="slug" slide="slide-id"/>` (a deck, or one slide of it). Exactly one kind, at most one allowed subtarget, lowercase slug. Optional plain text label; server adds `to` when resolved, preserve it. Missing targets, including a block the document no longer has, are warnings; clear before handoff. Keep referenced IDs stable; when changing a target, update the reference too. A reference under its section heading connects that section to its companion canvas. Live choices/verdicts belong in refs, not duplicated prose.\n\nEmbedded whiteboards: `<ref whiteboard="slug" frame="f1" embed="true"/>` draws the whiteboard in the document instead of a chip. Write it as a paragraph of its own directly under `<doc>`, e.g. `<p><ref whiteboard="sync-flow" frame="f-steps" embed="true"/></p>`; never beside text, in a list, table or quote. `frame` shows that frame cut to its box, `page` one page, neither the main page. Only whiteboard references embed. The drawing follows the whiteboard live: draw and change it on the whiteboard, not in the document; a reader clicks it to open the whole whiteboard. A missing whiteboard or frame is the same check warning as any reference.\n\nAfter editing, run the returned Check command. It names invalid blocks, chart/math/diagram errors, unresolved refs and pending dynamic work. Read complete feedback before acting; reply/resolve and acknowledge only the receipt for evidence actually used.\n';const sg=/^(.+?)->(.+?)(?:#([1-9]\d*))?$/;function cg(e){if(e.node&&e.edge)throw new F(`comment add takes --node or --edge, not both`);if(e.node)return{kind:`node`,id:e.node};if(!e.edge)return;let t=sg.exec(e.edge);if(!t)throw new F(`comment add --edge needs "<from>-><to>", with #n for the nth edge between them`);return{kind:`edge`,from:t[1],to:t[2],index:t[3]?Number(t[3])-1:0}}const lg=e=>t=>ag(e,t,()=>Kt(t),t.text);function ug(e,t,n){try{let e=ig(d.default.dirname(n));return{markdown:e.markdown,rows:e.outline}}catch(e){return{warnings:[{code:`W_DOCUMENT_MARKDOWN`,message:`could not read the document as markdown, so it is shown as LiteXML: ${e.message}`}]}}}const dg={authoring:og,localGet:{key:`outline`,read:ug,columns:[{key:`id`,required:!0,positional:!0},{key:`level`,positional:!0},{key:`title`,positional:!0},{key:`chars`}]},changes:!0,review:{sections:[`asks`]},commentActions:{submit:lg(`submit`),answer:lg(`answer`),note:lg(`note`),add:e=>{if(!e.block)throw new F(`comment add needs --block <blockId>`);let t=cg(e);return{op:`add`,blockId:e.block,...t?{diagram:t}:{},...e.quote?{quote:e.quote}:{},text:Kt(e)}}}},fg={authoring:'# HTML writing\n\nWrite one complete `index.html` with a descriptive `<title>`, inline or relative styles/scripts/images. The page reloads on edits. Native HTML/CSS/JavaScript works; use labelled controls and visible results. Assets stay inside this artifact directory; CDN fonts/scripts work, absolute local paths do not. The iframe is sandboxed: localStorage/sessionStorage/cookies throw; keep state in DOM/variables. Popups, forms, downloads and clipboard work.\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Retry explorer</title>\n </head>\n <body>\n <label>Attempts <input id="attempts" type="range" min="1" max="5" value="3" /></label>\n <output id="result"></output>\n <script>\n const input = document.getElementById(\'attempts\');\n const render = () =>\n (document.getElementById(\'result\').textContent = input.value + \' attempts\');\n input.addEventListener(\'input\', render);\n render();\n <\/script>\n </body>\n</html>\n```\n\nStable control IDs preserve human input, checks, details and scroll across rewrites. Restoration fires input/change: render from those events. Script-only state resets. Use one surface for one investigation; comparison across independent screens belongs on an artboard. Re-read files before editing; never edit comments or `.state/`.\n\nBundled UI elements require no imports. Use native HTML/CSS for layout. `ryugi-icon name="message-square" size="18"` provides Lucide kebab-case icons (stroke-width defaults 2, color currentColor); label the button, icons are decorative. Unknown names become runtime warnings. For JS-only icons add `<meta name="ryugi-icons" content="1">` and await customElements.whenDefined(\'ryugi-icon\'). Preview glyphs map to the app\'s existing business icons when implementing the design.\n\nRun Check after edits. It distinguishes current static evidence from browser runtime. A closed/unloaded tab means runtime pending; open the returned URL and check again. Uncaught exceptions, rejected promises and missing relative assets are warnings; no browser run is not proof that a page works.\n\n# UI components\n\nHTML artifacts can use a small set of Lobe UI components through Web\nComponents. The artifacts server loads the runtime automatically when the page\ncontains a `<ryugi-…>` element:\n\n```html\n<ryugi-button variant="primary">Save</ryugi-button>\n```\n\nNo script tag is needed. If you create components dynamically, add\n`<meta name="ryugi-ui" content="1">` to the page so the runtime is loaded.\n\nThe runtime loads with `defer`. A page script that needs the components should\nwait for the document event:\n\n```js\ndocument.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n // custom elements are defined\n },\n { once: true },\n);\n```\n\nUse these for controls and basic display. Use plain HTML and CSS for layout;\nthere is no layout wrapper to learn.\n\n## Rules\n\n- Give every interactive control a stable `id`. The viewer restores custom\n controls across rewrites by `id`, the same way it restores native inputs.\n- Listen for `ryugi-change` on controls:\n\n ```js\n document.addEventListener(\'ryugi-change\', (event) => {\n const { value, checked } = event.detail;\n console.log(event.target.id, value, checked);\n });\n ```\n\n It bubbles. `value` is a string, number, boolean, or `null`; `checked` is\n present for checkboxes and switches.\n\n- `value` / `checked` attributes set the initial state. Read the current state\n from the element\'s `value` / `checked` property after `ryugi-ui:ready`, and\n listen for `ryugi-change` for later updates.\n- `class` styles the host; `style` is forwarded to the component as well, so\n `style="width:100%"` works. Style the host, not the component\'s internal\n classes.\n- Keep children simple. For `ryugi-button`, `ryugi-card`, `ryugi-text`,\n `ryugi-tag`, `ryugi-checkbox`, and `ryugi-badge`, the original children are\n moved into the component. `ryugi-select`, `ryugi-segmented`, and\n `ryugi-radio-group` use option children instead.\n- Do not invent a `ryugi-` tag. If a component is not listed here, use HTML.\n- `ryugi-card` already paints a surface. Do not put a background, border and\n padding on both the host and the card: pick one. For a floating panel,\n either position the host and let the card paint its own surface, or make the\n host the surface and use `variant="borderless"` without `glass`/`shadow`.\n- Components follow `prefers-color-scheme`. Set `<html data-theme="light">`\n or `data-theme="dark"` before the runtime loads to pin the whole page.\n Without an explicit theme, the runtime follows OS theme changes.\n Lobe tokens such as `--lobe-color-primary` can be overridden on the host or\n page.\n\n## Controls\n\n### Button\n\n```html\n<ryugi-button variant="primary" size="middle" icon="plus">Add</ryugi-button>\n<ryugi-button variant="outlined" loading>Working…</ryugi-button>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `size`\n(`small`, `middle`, `large`), `block`, `loading`, `disabled`, `shape`, `type`,\n`icon` (any Lucide kebab-case name; `refresh` and `trash` remain aliases).\nRun `node app/ryugi.cjs guide icons` for standalone icons and mapping the preview\'s\nactions to business icons when implementing the app.\n\nUses the native `click` event.\n\n### Action icon\n\n```html\n<ryugi-action-icon icon="settings" title="Settings" aria-label="Settings"></ryugi-action-icon>\n```\n\nAttributes: `icon` (same set as Button), `size`, `disabled`, `title`,\n`aria-label`. Uses the native `click` event.\n\n### Tooltip and popover\n\n```html\n<ryugi-tooltip content="Copy a private link" placement="top">\n <ryugi-icon name="copy" size="14"></ryugi-icon> Copy\n</ryugi-tooltip>\n<ryugi-popover id="sharing" content="Only people you invite can open this link.">\n Sharing details\n</ryugi-popover>\n```\n\nBoth provide a native button trigger; children are its label and decorative\nicons, not nested buttons or controls. `content` is plain text, `placement`\nsets the floating position. Tooltip opens on hover/focus; Popover opens on\nclick (`trigger="hover"` opts into hover). Tooltip also accepts `open` for\na controlled preview. Native trigger clicks still reach your handlers.\n\n### Action menu\n\n```html\n<ryugi-menu id="actions" label="More" icon="ellipsis">\n <ryugi-menu-item value="copy" icon="copy">Copy link</ryugi-menu-item>\n <ryugi-menu-item value="delete" icon="trash-2" disabled>Delete</ryugi-menu-item>\n</ryugi-menu>\n```\n\nAttributes: `label`, `icon`, `placement`, `disabled`. Items accept `value`,\n`icon`, `disabled`; their text is the label. Selecting an enabled item emits\n`ryugi-change` with its action in `event.detail.value`. Actions are not\nrestored as control values on reload.\n\n### Input\n\n```html\n<ryugi-input id="title" placeholder="Title" value="Ryugi" style="width:100%"></ryugi-input>\n```\n\nAttributes: `type`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`, `borderless`), `allowClear`, `placeholder`, `value`,\n`disabled`, `name`, `aria-label`.\n\n### Textarea\n\n```html\n<ryugi-textarea id="notes" rows="4" placeholder="Notes" style="width:100%"></ryugi-textarea>\n```\n\nAttributes: `rows`, `size`, `variant`, `placeholder`, `value`, `disabled`,\n`name`.\n\n### Number\n\n```html\n<ryugi-input-number id="count" value="12" min="0" max="100" step="1"></ryugi-input-number>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `precision`, `controls`, `size`,\n`variant`, `placeholder`, `disabled`.\n\n### Slider\n\n```html\n<ryugi-slider id="size" value="32" min="0" max="100" step="1"></ryugi-slider>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `disabled`.\n\n### Slider with number input\n\nThe most useful control for tuning an exact value.\n\n```html\n<ryugi-slider-input id="radius" value="8" min="0" max="32" step="1"></ryugi-slider-input>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `controls`, `size`, `variant`,\n`disabled`.\n\n### Switch\n\n```html\n<ryugi-switch id="dark" checked></ryugi-switch>\n```\n\nAttributes: `checked`, `loading`, `size`, `disabled`, `name`.\n\n### Checkbox\n\n```html\n<ryugi-checkbox id="compact">Compact</ryugi-checkbox>\n```\n\nAttributes: `checked`, `shape`, `size`, `disabled`, `name`. Children are the\nlabel.\n\n### Segmented\n\n```html\n<ryugi-segmented id="mode" value="grid">\n <ryugi-segment value="list">List</ryugi-segment>\n <ryugi-segment value="grid">Grid</ryugi-segment>\n <ryugi-segment value="masonry">Masonry</ryugi-segment>\n</ryugi-segmented>\n```\n\nAttributes: `value`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`), `block`, `glass`, `shadow`, `vertical`, `disabled`.\n\n### Select\n\n```html\n<ryugi-select id="layout" value="a" placeholder="Choose layout">\n <ryugi-option value="a">Sidebar</ryugi-option>\n <ryugi-option value="b">Top tabs</ryugi-option>\n <ryugi-option value="c">Bottom rail</ryugi-option>\n</ryugi-select>\n```\n\nAttributes: `value`, `placeholder`, `size`, `variant`, `allowClear`,\n`showSearch`, `loading`, `mode` (`multiple`, `tags`), `disabled`.\n\n### Radio group\n\n```html\n<ryugi-radio-group id="density" value="comfortable">\n <ryugi-radio value="compact">Compact</ryugi-radio>\n <ryugi-radio value="comfortable">Comfortable</ryugi-radio>\n <ryugi-radio value="spacious">Spacious</ryugi-radio>\n</ryugi-radio-group>\n```\n\nAttributes: `value`, `horizontal`, `gap`, `size`, `disabled`.\n\n### Colour picker\n\n```html\n<ryugi-color-picker id="accent" value="#c56473" trigger="field"></ryugi-color-picker>\n```\n\nAttributes: `value`, `alpha`, `defaultFormat` (`hex`, `rgb`, `hsl`),\n`trigger` (`swatch`, `field`, `chip`), `size`, `disabled`.\n\n## Display\n\n### Toast\n\nHTML artifacts can call the bundled Lobe UI toast API as `window.ryugiToast`.\nIf the page has no `ryugi-` UI controls, opt in with the meta tag. Wait for\n`ryugi-ui:ready` before calling it:\n\n```html\n<meta name="ryugi-ui" content="1" />\n<button id="save" type="button">Save</button>\n<script>\n document.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n document.getElementById(\'save\').addEventListener(\'click\', async () => {\n try {\n await saveDraft(); // the page\'s own operation\n window.ryugiToast.success({ id: \'save-result\', title: \'Saved\' });\n } catch {\n window.ryugiToast.error({\n id: \'save-result\',\n title: \'Save failed\',\n description: \'Try again.\',\n });\n }\n });\n },\n { once: true },\n );\n<\/script>\n```\n\nMethods: `success`, `error`, `info`, `warning`, `loading`. Each takes a string\nmessage or `{ title, description, id, duration }`. Text is rendered as text,\nnot HTML. A stable `id` refreshes the same notification instead of stacking\ncopies. The default duration is 5000ms; `duration: 0` stays until closed.\n`loading` stays until closed by default.\n\nCalls return a handle with `id` and `close()`. Use\n`window.ryugiToast.dismiss(id)` to close one, or `dismiss()` to close all.\nToasts appear at the bottom right and follow the page\'s theme. They are\ntransient: rewriting the page does not restore them. No `ryugi-toast` tag is\nneeded. Artboard pages do not load this UI runtime.\n\n### Tag\n\n```html\n<ryugi-tag variant="outlined">New</ryugi-tag>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`, `solid`), `size`,\n`shape` (`normal`, `round`), `color`, `closable`.\n\n### Alert\n\n```html\n<ryugi-alert\n type="info"\n title="Streaming"\n description="Pending boards draw as skeletons."\n></ryugi-alert>\n```\n\nAttributes: `type` (`success`, `info`, `warning`, `error`, `secondary`),\n`variant` (`soft`, `outlined`, `plain`), `title`, `description`, `showIcon`,\n`closable`. Text children are used as the title when `title` is absent.\n\n### Progress\n\n```html\n<ryugi-progress percent="64" size="small"></ryugi-progress>\n```\n\nAttributes: `percent`, `size`, `status`.\n\n### Badge\n\n```html\n<ryugi-badge count="3" status="processing"></ryugi-badge>\n<ryugi-badge count="3">\n <ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n</ryugi-badge>\n```\n\nAttributes: `count`, `dot`, `status`, `text`, `showZero`, `size`, `color`.\n\n### Avatar\n\n```html\n<ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n```\n\nAttributes: `src`, `alt`, `size`, `shape`.\n\n### Divider\n\n```html\n<ryugi-divider dashed></ryugi-divider>\n```\n\nAttributes: `orientation`, `dashed`.\n\n### Card\n\n```html\n<ryugi-card variant="outlined" shadow>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Supporting copy.</ryugi-text>\n</ryugi-card>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `shadow`,\n`glass`, `clickable`. Children are preserved, including nested components.\n`glass`, `shadow` and `variant` paint the inner Block surface, not the host.\nIf the host supplies the panel background and padding, omit `glass`/`shadow`\nand use `variant="borderless"` so there is only one visible container.\n\n### Text\n\n```html\n<ryugi-text type="secondary">Secondary body text</ryugi-text>\n<ryugi-text strong>Strong label</ryugi-text>\n<ryugi-text code>const x = 1</ryugi-text>\n```\n\nAttributes: `type` (`secondary`, `success`, `warning`, `danger`, `info`),\n`strong`, `code`, `italic`, `underline`, `delete`, `mark`, `align`, `weight`.\n\n## Complete tuning panel\n\n```html\n<ryugi-card>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Tune the reading column.</ryugi-text>\n\n <ryugi-slider-input id="measure" value="64" min="40" max="90" step="1"></ryugi-slider-input>\n\n <ryugi-segmented id="density" value="comfortable">\n <ryugi-segment value="compact">Compact</ryugi-segment>\n <ryugi-segment value="comfortable">Comfortable</ryugi-segment>\n <ryugi-segment value="spacious">Spacious</ryugi-segment>\n </ryugi-segmented>\n\n <ryugi-switch id="dark"></ryugi-switch>\n <ryugi-tag>Live preview</ryugi-tag>\n</ryugi-card>\n\n<script>\n document.addEventListener(\'ryugi-change\', (event) => {\n document.body.dataset[event.target.id] = event.detail.value;\n });\n<\/script>\n```\n\n## Not included in the first version\n\nTabs, Modal, Drawer, Table, DatePicker, and layout\ncomponents. Use plain HTML/CSS or a later component if one is added.\n',phoneScreens:!0};var pg='## Mockup components\n\n`<ryugi-ios-shell>` draws the device and nothing else: the screen (402×874, iPhone 17), status bar, Dynamic Island, home indicator and, with `bezel`, the frame (442×914). Size phone boards to match. Never hand-draw those parts. Three system controls are built in as well: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` draw the iOS switch, segmented control and slider, with the frosted knob that opens into clear glass while it is pressed, dragged or travelling; use them wherever the product shows one of these controls instead of drawing your own. Everything else on the screen (navigation bar, glass buttons, tab bar, cards, lists, inputs, sheets, a floating composer) is the product\'s own design system: write it by hand in HTML/CSS from the variables of `tokens.css`, in the product\'s own style, including its own Liquid Glass where the product uses it. Do not imitate iOS Settings rows unless the product\'s own screens look like that. The shell renders in light DOM, so selection, comments and the Inspector reach every part. The server loads it when the page contains the tag; for a shell created by script add `<meta name="ryugi-mockup" content="1">` and wait for `ryugi-mockup:ready` on `document`.\n\n```html\n<!doctype html>\n<html lang="zh">\n <head>\n <meta charset="utf-8" />\n <link rel="stylesheet" href="../tokens.css" />\n <style>\n html,\n body {\n margin: 0;\n }\n .nav {\n display: flex;\n align-items: center;\n justify-content: space-between;\n height: 44px;\n padding: 0 16px;\n }\n .mark {\n font: 700 26px/32px var(--font-display);\n color: var(--color-text);\n }\n .glass {\n display: flex;\n border-radius: 22px;\n background: var(--color-glass);\n backdrop-filter: blur(16px) saturate(1.8);\n color: var(--color-text);\n }\n .glass > * {\n display: grid;\n place-items: center;\n width: 44px;\n height: 44px;\n }\n .card {\n margin: 8px 16px;\n padding: 16px;\n border-radius: var(--radius-card);\n background: var(--color-surface);\n }\n </style>\n </head>\n <body>\n <ryugi-ios-shell>\n <div class="nav">\n <span class="mark">喵旅</span>\n <span class="glass">\n <span\n ><ryugi-icon symbol="person.crop.circle" name="circle-user" size="22"></ryugi-icon\n ></span>\n <span><ryugi-icon symbol="plus" name="plus" size="22"></ryugi-icon></span>\n </span>\n </div>\n <section class="card">…</section>\n </ryugi-ios-shell>\n </body>\n</html>\n```\n\nThe variable names in the example (`--font-display`, `--radius-card`, `--color-glass`) stand for roles; use the names the product\'s own `tokens.css` defines.\n\n| Element | Attributes | Children |\n| ------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `ryugi-ios-shell` | `bezel`, `time` (9:41), `hide="status island home all"` (any of them) | the screen content: it flows from below the status bar (`--safe-top`, 62px); absolutely positioned content measures from the screen\'s top edge. `--safe-bottom` is 34px. Both stay when parts are hidden |\n| `ryugi-token-sheet` | `appearance` to show one set only | one `<script type="application/json">` |\n\nAll of them take `appearance="light|dark"`, otherwise follow the nearest `[data-appearance]`, then the system. Unknown attribute values raise a runtime warning.\n\n### iOS controls\n\n```html\n<div class="row">\n <span>自动暂停</span>\n <ryugi-ios-switch id="auto-pause" checked></ryugi-ios-switch>\n</div>\n<ryugi-ios-segmented id="range" value="week" block>\n <ryugi-ios-segment value="day">日</ryugi-ios-segment>\n <ryugi-ios-segment value="week">周</ryugi-ios-segment>\n <ryugi-ios-segment value="month">月</ryugi-ios-segment>\n</ryugi-ios-segmented>\n<ryugi-ios-slider\n id="volume"\n label="播报音量"\n value="65"\n start-icon="volume-1"\n end-icon="volume-2"\n></ryugi-ios-slider>\n```\n\n| Element | Attributes | Events |\n| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |\n| `ryugi-ios-switch` | `checked`, `disabled`, `size="sm md lg"` (track 22, 28, 36px; md), `color`, `label` and `description` beside it, `label-side="left"` | `change`, `detail.checked` |\n| `ryugi-ios-segmented` | `value`, `size="sm md lg"` (28, 32, 40px; md), `block` to fill the width; children are `<ryugi-ios-segment value>`, whose content (text, a `ryugi-icon`) is the label | `change`, `detail.value` |\n| `ryugi-ios-slider` | `value`, `min`, `max`, `step` (0, 100, 1), `size="sm md lg xl"` (track 8, 12, 18, 26px; md), `color`, `label` above with the value unless `hide-value`, `start-icon` and `end-icon` (Lucide names) | `input` while dragging, `change` when it lands, `detail.value` |\n\nThey are interactive: a tap flips the switch, the knob drags, the segmented lens can be held and dragged to another option, the slider follows the pointer, and the keyboard works. Their state is reflected in the `checked` and `value` attributes, and setting those from a script moves the control. The on colour of the switch and the filled part of the slider read `--color-accent` unless `color` names one (`#34c759`). The track, the segmented background and the selected pill follow the appearance; labels read `--color-text` and `--color-text-secondary`.\n\nIcons: `<ryugi-icon name>` is a Lucide icon. Add `symbol`, an SF Symbol name (`wallet.bifold.fill`): when the local server runs on macOS it draws the symbol through the system and shows it at the symbol\'s own proportions, tinted with `currentColor`; anywhere else (other systems, Ryugi Cloud, published links) the Lucide icon shows. Write both. Use `symbol` only in mockups of apps for Apple platforms; that is the condition of Apple\'s license. Symbol images are never part of `pages/` and are never published.\n\nProduct tokens live in one stylesheet (on an artboard `pages/tokens.css`), light on `:root`, dark on `[data-appearance="dark"]`. The shell\'s root carries `data-appearance`, so light and dark phones sit side by side and your content under `[data-appearance="dark"]` flips with them. The shell reads `--color-bg` (screen), `--color-text` (status bar, home indicator) and `--font-body`, falling back to iOS system values; the token sheet also reads `--color-text-secondary`, `--color-separator`, `--color-surface`, `--color-fill` and `--color-accent`. Your content reads the same variables plus the product\'s own (radius, spacing, type, glass).\n\n`ryugi-token-sheet` draws the token table from JSON that names tokens, never values; values come from the stylesheet in both appearances:\n\n```json\n{\n "groups": [\n {\n "name": "Text",\n "kind": "color",\n "tokens": [\n {\n "name": "--color-text-secondary",\n "use": "行右侧的值",\n "on": "--color-surface",\n "board": "t-color-a"\n }\n ]\n },\n {\n "name": "Type",\n "kind": "type",\n "tokens": [{ "name": "--type-body", "use": "正文", "sample": "招商银行储蓄卡" }]\n }\n ]\n}\n```\n\nKinds: `color` (swatches; with `on`, WCAG contrast per appearance flagged under 4.5:1, or 3:1 with `"large": true`), `type` (a `font` shorthand), `space`, `radius`, `size`, `shadow`, `motion` (`<duration> <easing>`, click to play). Token and group names are English; `use` and `sample` follow the product\'s language. Missing variables and broken JSON show inline errors.\n',mg="## Phone mockups\n\nEvery phone screen is a `<ryugi-ios-shell>`: it draws the 402×874 screen, status bar, Dynamic Island and home indicator, and `bezel` adds the 442×914 frame. Never hand-draw those parts, nor a switch, segmented control or slider: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` are built in. Everything else on the screen is the product's own design from its `tokens.css`. Before the first phone screen or `<ryugi-token-sheet>`, read the mockup guide: `start --artifact <artifact> --help --mockup`.\n",hg='# Report writing\n\nA report is data and presentation kept apart. Each data source is a Node script that prints JSON; the report is `report.tsx`, one default-exported component built only from `@ryugi/report` that imports the data it draws.\n\n```\nreport/<id>/\n report.tsx\n sources/<source-id>/source.json\n sources/<source-id>/<script>.mjs\n data/<source-id>.json written by the hub when a source runs; never write it by hand\n assets/<file>.png images the report shows (png, jpg, gif, webp, avif, svg)\n```\n\n## Data sources\n\n`sources/<source-id>/source.json`: `{ "title": "Commits per day", "description": "main branch, last 30 days", "input": "git history of the repo", "script": "collect.mjs", "args": ["--days", "30"] }`. `title` and `script` are required; the script is a `.mjs`, `.js` or `.cjs` file in the same folder. Source ids are kebab-case.\n\nThe script runs with the project root as cwd and Node from the hub, so it can use the project\'s `node_modules`. Its env is the hub\'s env with the project\'s `.env` and `.env.local` laid over it; read secrets and machine paths from env or `args`, never write them into the script. It must print one JSON value on stdout (at most 2 MB; the whole report\'s data at most 10 MB) and exit 0 within 60 s. Do the aggregation in the script: the report only draws. A stderr line `ryugi:input <text>` replaces the input shown in the panel for that run, such as the commit the data was read at; other stderr is shown when the run fails.\n\nRun sources with `ryugi report refresh --artifact report/<id>` (all) or with `--only <source-id>` (one). The hub runs them, one run per source at a time, and writes `data/<source-id>.json`. Refresh after adding or changing a source, and before `check`. Reports fetched from someone else\'s Cloud link are read-only: never run their scripts.\n\n## report.tsx\n\n```tsx\nimport {\n BarChart,\n Grid,\n Report,\n Section,\n Stat,\n Table,\n useMemo,\n useState,\n Param,\n} from \'@ryugi/report\';\nimport days from \'./data/commits-per-day.json\';\n\nexport default function Commits() {\n const [span, setSpan] = useState(14);\n const shown = useMemo(() => days.slice(-span), [span]);\n return (\n <Report title="Ryugi commits" caption="main branch">\n <Param label="Window" min={7} max={30} unit="days" value={span} onChange={setSpan} />\n <Grid columns={3}>\n <Stat\n id="total"\n source="commits-per-day"\n title="Commits"\n value={shown.reduce((sum, day) => sum + day.commits, 0)}\n />\n </Grid>\n <Section id="daily" title="Per day">\n <BarChart\n id="per-day"\n source="commits-per-day"\n title="Commits per day"\n data={shown}\n x="date"\n series={[{ key: \'commits\', label: \'Commits\' }]}\n />\n <Table\n id="days"\n source="commits-per-day"\n title="Days"\n rows={shown}\n rowKey="date"\n columns={[{ key: \'date\' }, { key: \'commits\', align: \'right\' }]}\n />\n </Section>\n </Report>\n );\n}\n```\n\nImports come only from `@ryugi/report` and `./data/<source-id>.json` (default import; the source must exist). JSX uses SDK components only: no `div`, `img`, `a` or other native elements, no network calls, `document` / `window` / `location` / `navigator` / storage access, `globalThis`, `eval`, `Function`, `.constructor`, `import()` / `require()` or timers. Words in text and strings are fine; the check reads code. The page cannot reach the network either way. `report.tsx` stays under 64 KB; put data in a source. Derive with `useMemo` and plain expressions; keep state in `useState`.\n\nEvery Stat, chart, Table, Callout, Image and Section needs an `id`: kebab-case, unique in the report, and stable across edits, since comments and references hold on to it. Stat, charts and Table also need `source`: the source id, or a list of them, that the block\'s numbers come from; the hover chip and the sources panel read it. Write `id`, `source` and `title` as string literals.\n\nComponents:\n\n- `Report` `{ title, caption? }`: the root; `title` is the artifact\'s title.\n- `Section` `{ id?, title? }`, `Grid` `{ columns?: 1 | 2 | 3 | 4 }`, `Card`, `Stack` `{ gap? }`, `Divider`.\n- `H2`, `H3`, `Text` `{ tone?: \'muted\' }`, `List` `{ items }`, `Callout` `{ id, title?, tone?: \'info\' | \'success\' | \'warning\' | \'error\' }`.\n- `Stat` `{ id, source, title, value, unit?, delta?, format?, note? }`; `delta` is signed and shown up or down.\n- `Table` `{ id, source, title?, rows, rowKey, columns: { key, label?, align?, format? }[] }`; every row prints; a click on a row starts a comment on it.\n- `LineChart`, `BarChart`, `AreaChart`, `PieChart`, `ScatterChart` `{ id, source, title, data, x, series: { key, label?, color? }[], subtitle?, stacked?, donut?, highlight?, refs?: { label, y }[], format?, note? }`: the same chart renderer as a document\'s chart block. A `ScatterChart` needs a numeric `x` in every row. A reader clicks a point to pin it and comments on that point.\n- `Param` `{ label, value, onChange, min?, max?, step?, unit? }` (a slider with a number field when min and max are set), `Select` `{ label?, value, options, onChange }`, `Toggle` `{ label, checked, onChange }`. Printed, they show the value the reader set; a comment on a point or row records them too.\n- `Image` `{ id, src, alt, caption?, width? }`: an image file from the report folder, `src` written as a string such as `"assets/sources-panel.png"`; `alt` describes it. Copy screenshots and figures into `assets/` first; remote URLs are not allowed. Comments anchor to the image as a block.\n- `useState`, `useMemo` from `@ryugi/report`.\n\n`format` is `{ unit?, decimals?, compact?, signed? }`.\n\n## Check, comments, references\n\n`ryugi check --artifact report/<id>` reports static issues (imports, native elements, missing or repeated ids, unknown sources, missing data files) and, once a browser has opened the report, render errors.\n\nComments anchor to a block, a table row or a chart point: `ryugi comment add --artifact report/<id> --block <block-id> [--point <series>:<x> | --row <rowKey>]`. A comment keeps the value it was made on and which data it saw; after a refresh changes that data it is marked data changed and stays where it was.\n\nReference a report from a document with `<ref report="<id>"/>`, or one block with `<ref report="<id>" block="<block-id>"/>`. A deck names it inline with the same `<ref>`, and shows one block on a slide with `<embed report="<id>" block="<block-id>"/>`; give the blocks a deck shows a stable `id`.\n\nPublishing includes `report.tsx`, `sources/**`, `data/**` and the images under `assets/` with the report\'s visibility. Publishing is refused while a script, `report.tsx` or the data holds an absolute machine path (`/Users/…`, `/home/…`, `C:\\\\…`, not checked in data) or something that looks like a secret (`sk-…`, `ghp_…`, `AKIA…`, a private key, a value from `.env`); the refusal names the file and line.\n';function gg(e){if(!e.block)throw new F(`comment add on a report needs --block <blockId>`);if(e.point!==void 0&&e.row!==void 0)throw new F(`comment add takes --point or --row, not both`);let t;if(e.point!==void 0){let n=e.point.indexOf(`:`);if(n<=0||n===e.point.length-1)throw new F(`--point needs <series>:<x>, such as commits:Nov 2`);t={series:e.point.slice(0,n),x:e.point.slice(n+1)}}return{op:`add`,block:e.block,...t?{point:t}:{},...e.row===void 0?{}:{row:e.row},text:Kt(e)}}const _g={authoring:hg,review:{sections:[]},commentActions:{add:gg}};var vg='# Slides writing\n\nWrite one complete `deck.xml` under the returned artifact directory; put images in `assets/` and reference them with relative paths. The deck is for an audience: your human partner presents it. Re-read before each edit; never edit `comments.json` or `.state/`. Finish with `check`.\n\nThe file holds what the slides say. The server compiles it into the page and adds the presentation engine, theme, code highlighting, diagrams and formulas. Only the tags and attributes below exist: there is no `class` and no `style`, and `check` reports anything else by slide and tag.\n\n```xml\n<deck title="Retry policy" lang="en">\n <slide id="cover" layout="cover">\n <kicker>Delivery · Q3</kicker>\n <h1>Retry policy</h1>\n <subtitle>Why failed deliveries now retry three times</subtitle>\n <notes>Open with last month\'s incident.</notes>\n </slide>\n\n <slide id="what-changes">\n <h2>What changes</h2>\n <ol steps="true">\n <li>At most three attempts</li>\n <li>Exponential backoff</li>\n </ol>\n </slide>\n\n <slide id="backoff" layout="code">\n <h2>Backoff</h2>\n <codeblock lang="ts" lines="1|2-3"><![CDATA[\n const delay = (attempt: number) =>\n Math.min(30_000,\n 500 * 2 ** attempt);\n ]]></codeblock>\n </slide>\n</deck>\n```\n\n## Slides\n\n- One slide is one `<slide>` directly inside `<deck>`. The deck\'s `title` is required; `lang` is optional.\n- Every slide needs a unique, stable `id` of lowercase letters, digits and hyphens. Comments and document references find a slide by its id: keep the id when you rewrite a slide, and only change it when the slide becomes a different slide. Deleting a slide orphans its comments.\n- The canvas is fixed at 1280×720. Content that leaves that box is reported by `check` as overflow, naming the slide. Fix it by cutting or splitting the slide; `zoom="0.8"` on the slide (0.3 to 1) is for the one dense slide that must stay whole.\n- While the deck is open in the viewer, `check` also names contact sheet images (`Sheet:`) that show every slide at its last step, twelve to an image, with overflowing and hidden slides marked. After editing, run `check`, open those images, and look for slides that are too full or that all look like the same template. `sheet_not_drawn` under `Pending` means the open viewer has not drawn this version yet. `Sheet: unavailable (…)` means it cannot be drawn, as for a deck holding a video or an iframe: go on without it.\n- `hidden="true"` keeps a slide in the file and out of the talk: it shows, marked, only while the deck is worked on; presenting, the audience window, the PDF and a published link never get it, and it takes no page number.\n- `<group id="evidence" title="What the data says">` inside `<deck>` gathers the slides of one part of the talk. It holds only `<slide>` and `<include>`, never another group; its `id` follows the slide id rules and is unique among slides and groups, and `title` is required. The grid view shows each group as a titled row; the audience sees nothing of it. Slides outside any group are fine, before, between or after groups.\n- `cover="<slide id>"` on `<deck>` names the slide that stands for the deck in lists and links. `check` warns when it names a slide that is missing or hidden.\n- Write XML: close every tag, quote every attribute, write `&lt;` and `&amp;` in text; common names such as `&nbsp;`, `&mdash;` and `&rarr;` work, any other is an error, so write the character itself. Code, diagrams and formulas go in `<![CDATA[ … ]]>` so nothing in them needs escaping. CDATA ends at the first `]]>`: code that contains `]]>` comes from a file with `src`. End the file with `</deck>`.\n\n## Layouts\n\nPick the layout that fits what the slide says, and vary them: a deck of identical title-and-bullets slides reads as a template. Each layout adds a few places of its own; a place used in another layout is reported. The theme adds the page number itself.\n\n| `layout` | Use it for | Inside the slide |\n| ----------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------- |\n| `default` | A title with text, a list, a table or code | Optional `<label>`, an `<h2>`, then blocks. Omitting `layout` gives this one |\n| `cover` | The first slide | `<kicker>`, `<h1>`, `<subtitle>` |\n| `section` | The start of a new part | Optional `<label>`, then an `<h1>` or `<h2>` |\n| `statement` | One sentence the audience should remember | Optional `<label>`, an `<h2>` with the key words in `<mark>`, optional `<subtitle>` |\n| `two-cols` | Two things side by side | An `<h2>`, then exactly two `<col>`, each holding blocks |\n| `image` | Text beside a picture | One `<col>` holding the text and one `<img>`; whichever comes first is on the left |\n| `quote` | A quotation | `<quote>` and `<cite>` |\n| `fact` | One number that matters | `<big value="10–12" unit="working days"/>`, then up to three `<fact value="5 days" label="API"/>` |\n| `code` | Code as the subject of the slide | Optional `<label>`, an `<h2>` and one `<codeblock>` or one `<magic>` |\n| `end` | The last slide | An `<h1>` |\n| `none` | A slide you lay out yourself | `src` naming an HTML file; see Free HTML. No padding and no page number |\n\n```xml\n<slide id="numbers" layout="fact">\n <big value="13" unit="harnesses supported"/>\n <fact value="5" label="artifact types"/>\n <fact value="0" label="subscriptions"/>\n</slide>\n<slide id="before-after" layout="two-cols">\n <h2>Before and after</h2>\n <col>\n <h3>Before</h3>\n <p>One attempt, then a page.</p>\n </col>\n <col>\n <h3>After</h3>\n <p>Three attempts, then a page.</p>\n </col>\n</slide>\n<slide id="dashboard" layout="image">\n <col>\n <label>Result</label>\n <h2>Failures fell by half</h2>\n </col>\n <img src="assets/dashboard.png" alt="Failure rate before and after the change" frame="true"/>\n</slide>\n```\n\n## Blocks and text\n\nBlocks sit in a slide or a `<col>`: `<h1>`, `<h2>`, `<h3>`, `<p>`, `<ul>` and `<ol>` of `<li>` (a list may nest in an item), `<table>` of `<tr>` holding `<th>` or `<td>`, `<blockquote>`, `<hr/>`, `<alert type="note|tip|important|warning|caution">` holding blocks, `<img>`, `<icon>`, `<codeblock>`, `<magic>`, `<mermaid>`, `<math>`, `<html>`, `<embed>` and `<notes>`.\n\nBlocks and inline tags a document also has carry the same names here. Inside text: `<b>`/`<strong>`, `<i>`/`<em>`, `<u>`, `<s>`/`<del>`, `<sub>`, `<sup>`, `<code>`, `<mark>`, `<a href="…">`, `<br/>`, `<math>`, `<icon>` and `<ref>`.\n\n- `<img src="assets/chart.png" alt="…"/>` shows a file of the artifact directory. `frame="true"` gives a screenshot rounded corners and a shadow.\n- `<icon name="check" size="32"/>` draws an icon; `size` is in pixels.\n- `<mermaid>` holds a Mermaid diagram and `<math>` a LaTeX formula, both in CDATA. `<math>` inside text is an inline formula.\n- `<notes>` holds speaker notes, shown only to the presenter. One per slide, plain text with `<br/>` between lines.\n\n```xml\n<h2>How a delivery flows</h2>\n<mermaid><![CDATA[\n flowchart LR\n A["ingress<br/>edge"] --> B[queue] --> C[worker]\n]]></mermaid>\n<table>\n <tr><th>Attempt</th><th>Delay</th></tr>\n <tr><td>1</td><td><math>500 \\cdot 2^1</math> ms</td></tr>\n</table>\n<p><icon name="check" size="24"/> Shipped behind a flag, see <a href="https://example.com/rfc">the RFC</a>.</p>\n```\n\n## Code\n\n`<codeblock lang="ts">` is a code block, named as in a document; `<code>` is inline code inside text. Write the code in CDATA; the indentation it shares with the XML is taken off.\n\n- `lines`: stepped line highlight. Parts are separated by `|`, each one step, lines count from 1: `1`, `2-3`, `2-3,5`; `all` lights every line and `hide` hides the block for that step.\n- `src="src/retry.ts#L10-24"`: take the code from a file of the project instead of writing it, optionally only those lines. The path is relative to the project root; files outside the project, dot-files such as `.env`, and files over 512 KB are refused, and so are files named like secrets (`secrets.*`, `credentials.*`, `*.pem`, `*.key`, `*.tfstate`, `*.tfvars`, SSH keys) and files git ignores. Never show a file that holds a secret under another name. What a deck shows is published with it.\n- `numbers="true"`: line numbers. `title="src/retry.ts"`: a title above the block. `max-height="320"`: a height in pixels past which the block scrolls, following the highlighted lines. `diff="true"`: lines starting with `+` or `-` are drawn as added or removed.\n- `<magic lang="ts">` holds two or more `<step>`, each the whole code at one step, in CDATA; what stays moves into place, and each step after the first is a step of the slide.\n\n```xml\n<codeblock lang="ts" src="src/retry.ts#L10-24" numbers="true" title="src/retry.ts" lines="all|3-5"/>\n<codeblock lang="ts" diff="true"><![CDATA[\n const attempts =\n - 1;\n + 3;\n]]></codeblock>\n<magic lang="ts">\n <step><![CDATA[const delay = 500;]]></step>\n <step><![CDATA[const delay = (attempt: number) => 500 * 2 ** attempt;]]></step>\n</magic>\n```\n\n## Steps and marks\n\n- `step="true"` on a block or a list item: it appears on the next step. `steps="true"` on a `<ul>`, `<ol>`, `<table>` or `<col>` makes each item, row or block a step.\n- `step="2"` places a step by number, and `step="with"` makes it appear together with the step before it.\n- `<mark>` highlights words. `type="highlight"`, `underline`, `circle` or `strike` draws that mark; with `step` the words are there from the start and the mark is drawn on its step.\n- `morph="title"` on a block in two consecutive slides moves it from one to the other; a name is used once per slide and the pair should hold the same text.\n\n```xml\n<h2 morph="title">The <mark type="underline" step="true">retry budget</mark> is per delivery</h2>\n<p step="true">Three attempts in total.</p>\n<p step="with">The first one counts.</p>\n<ul steps="true">\n <li>500 ms</li>\n <li>1 s</li>\n</ul>\n```\n\n## Several files and free HTML\n\n- `<include src="parts/appendix.xml"/>` inside `<deck>` puts the slides of another file of the artifact directory there. That file starts with `<slides>`, holds only `<slide>`, and cannot include further files. Ids stay unique across all files.\n- `<html src="parts/demo.html"/>` is a block of HTML you write yourself, in a file of the artifact directory.\n- `<slide id="demo" layout="none" src="parts/demo.html"/>` is a whole slide of your own HTML: you own every pixel of 1280×720. It may hold `<notes>` and nothing else.\n- A free HTML file is a fragment: no page wrapper, every `<div>` closed. `data-step` on an element inside it makes that element a step. It runs in the deck\'s sandbox: no localStorage, sessionStorage or cookies.\n\n```xml\n<deck title="Retry policy">\n <slide id="live-demo" layout="none" src="parts/demo.html">\n <notes>Click through the three states.</notes>\n </slide>\n <slide id="curve">\n <h2>The backoff curve</h2>\n <html src="parts/curve.html"/>\n </slide>\n <include src="parts/appendix.xml"/>\n</deck>\n```\n\n## Other artifacts\n\n`<embed>` puts another artifact of this project on the slide. Name the target by its slug, as a document\'s `<ref>` does:\n\n- `<embed artboard="settings-page" board="q1-b"/>` shows one board of an artboard, in a box of the board\'s shape.\n- `<embed whiteboard="sync-flow" frame="f1"/>` shows one frame of a whiteboard; `page="<page id>"` instead of `frame` shows a whole page. The box takes the shape of the frame or of what is drawn on the page.\n- `<embed report="q3-revenue" block="by-month"/>` shows one block of a report at the slide\'s width and at the block\'s own height, in the deck\'s light or dark.\n- `<embed slides="launch" slide="pricing"/>` shows one slide of another deck at 1280×720, at its last step, in that deck\'s own theme. Embeds on that slide hold their place under their names: decks nest one level.\n- `<embed html="spring-curve"/>` shows an html page, at 1280×720.\n\nAn embed is live: it shows the target as it is now, changes when the target does, and can be scrolled and clicked during the talk. Its corner button opens the target nearly full screen at the embedded part, and Esc closes it. In thumbnails, PNG and PDF export and the contact sheet every embed is a picture of the target.\n\n`<ref>` names another artifact inside text, as a chip: `<ref document="retry-policy">the design</ref>`, `<ref report="q3-revenue" block="by-month"/>`, `<ref whiteboard="sync-flow" frame="f1"/>`. Every kind a document can reference can be named, with the same attributes; with no text of its own the chip shows the target\'s title. Clicking it opens the target nearly full screen; nothing opens while the slide is edited or the pen or laser is on.\n\nPublished, a deck shows the published versions of what it embeds and names. A target that is private, unpublished or gone shows to visitors as its chip text or as an unpublished artifact, never its title or a picture of it; its owner sees it. Publishing the deck offers what it embeds and names to publish with it.\n\nAn embed takes `step` and `morph` like any block. `check` warns, naming the slide, when the artifact or the part it names (board, frame, page, block, slide) is not there, and the slide shows the target\'s name in its place. A `<ref>` to a missing target is warned about the same way.\n\n```xml\n<slide id="settings" layout="two-cols">\n <h2>The settings page</h2>\n <col>\n <p>Option B keeps billing on the first screen.</p>\n </col>\n <col>\n <embed artboard="settings-page" board="q1-b"/>\n </col>\n</slide>\n```\n\n## Theme, motion and glow\n\nChange the look for the whole deck with one `<theme>` before the first slide. `name` picks the theme: `paper` (the default: warm paper, one seal-coloured accent, glow) or `mono` (black on white, monospace labels, emphasis by weight, no glow). `appearance` is `light`, `dark` or `auto`; `auto`, the default, follows the system of whoever opens the deck and prints light, so write `light` or `dark` when the room decides. Every other attribute overrides one variable of the theme, in both appearances. A deck that sets its own `paper`, `surface` or `ink` is `light` unless it names an appearance: those colours suit one appearance only. Do not restyle slide by slide.\n\n```xml\n<deck title="Retry policy">\n <theme name="paper" appearance="dark" accent="#0a7cff" transition="slide-left" fragment="rise" glow-opacity="0.6"/>\n <slide id="cover" layout="cover" transition="fade" glow="top-right" glow-seed="launch">\n <h1>Retry policy</h1>\n </slide>\n</deck>\n```\n\n| `<theme>` attribute | Values | Paper |\n| ----------------------------- | ------------------------------------------------------------ | ------------------------------- |\n| `paper`, `surface` | the slide\'s background, and that of code and cards | |\n| `ink`, `ink-2`, `ink-3` | text, secondary text, labels | |\n| `accent`, `on-accent`, `info` | the accent colour, text on it, and the second accent | |\n| `rule`, `rule-strong` | hairlines | |\n| `font`, `font-mono` | font families | |\n| `transition` | `view`, `fade-out`, `fade`, `slide-left`, `slide-up`, `none` | `view` |\n| `transition-duration` | a time | `500ms` |\n| `transition-blur` | a length | `5px` |\n| `fragment` | `blur`, `fade`, `rise` | `blur` |\n| `fragment-duration` | a time | `500ms` |\n| `fragment-blur` | a length | `3px` |\n| `glow` | `on`, `off` | `on` |\n| `glow-1`, `glow-2`, `glow-3` | colours of the three shapes | `#9440e3`, `#41d1ff`, `#dce354` |\n| `glow-fade` | the colour each shape fades to | `rgb(255 255 255 / 0.1)` |\n| `glow-opacity` | 0 to 1 | `1` |\n| `glow-blur` | a length | `70px` |\n| `glow-drift` | how long the glow takes to move to the next slide\'s place | `2500ms` |\n| `glow-hue` | an angle | `0deg` |\n| `glow-at` | a glow place | `full` |\n\nTransitions:\n\n- `view`: the slide fades out, then the next fades in, both blurred; blocks with the same `morph` on both slides move and resize between them.\n- `fade-out`: the same fade out then in, without moving blocks.\n- `fade`: both slides cross-fade.\n- `slide-left`, `slide-up`: the next slide pushes in from the right or from below; going back reverses it.\n- `none`: the slide changes at once.\n\nSteps: `blur` fades a step in from a blur, `rise` also lifts it 12px, `fade` only fades it.\n\nOn a `<slide>`:\n\n- `transition`: the transition into this slide, one of the values above.\n- `glow`: where this slide\'s glow sits: `full`, `top`, `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`, or `none` for no glow. Left out, the place follows the layout and changes from slide to slide.\n- `glow-seed`: any text; the same seed on the same page number always gives the same shapes.\n- `glow-opacity`: 0 to 1, this slide only.\n- `glow-hue`: degrees, this slide only.\n\n`check` reports an unknown transition or glow place and a `morph` name used twice in one slide. With reduced motion, turns are instant and the glow does not move.\n\n## Placing blocks freely\n\nA layout arranges a slide for you. When a slide must sit exactly as drawn, put `free="true"` on it: every block it holds, inside a `<col>` too, then takes `x`, `y` and `w` in slide pixels of the 1280×720 canvas, and `h` when its height matters (pictures, embeds, diagrams). The layout stays named, so its type sizes still apply, and removing `free` with the coordinates brings the layout back. A block on a free slide without `x`, `y` and `w` is reported, and so are coordinates on a slide that is not free. Later blocks sit on top of earlier ones.\n\n```xml\n<slide id="library" layout="two-cols" free="true">\n <h2 id="b4k2qz" x="96" y="80" w="520">The library</h2>\n <col>\n <p x="96" y="180" w="420" align="center" color="muted">Every artifact, one server.</p>\n </col>\n <col>\n <img x="640" y="120" w="560" h="380" src="assets/library.png" alt="The library page" frame="true"/>\n </col>\n</slide>\n```\n\n- `align="left|center|right|justify"` and `color` work on text blocks on any slide. `color` takes a theme colour, `ink|muted|faint|accent|info`, which follows the theme and its light and dark appearances, or a fixed `#RRGGBB` / `#RRGGBBAA`, which does not. Prefer the theme colours.\n- On a free slide, `w="fill"` stretches a block from its `x` to the right safe margin, and a text block may take `h`: what does not fit is clipped, unless the block also has `fit="shrink"`, which shrinks its text until it fits.\n\n### Look attributes\n\nYour human partner tunes blocks in the viewer\'s tweak panel. Each setting is one attribute on the block, on any slide; `check` reports a value outside its range and an attribute on a block that does not take it.\n\n| Attribute | Blocks | Value |\n| --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- |\n| `size="32"` | text | font size, 8–400 px |\n| `weight="600"` | text | 100–900 in steps of 100 |\n| `font="Avenir Next"` | text | `mono` or a font name; a font missing on another machine falls back to the theme font |\n| `leading="1.4"` | text | line height, 0.8–3 |\n| `tracking="-0.5"` | text | letter spacing, -20–100 px |\n| `pad="16"` | text, table, codeblock, code, alert, big, fact | padding, 0–200 px |\n| `fill="surface"` | all but hr, icon and html | a theme colour (`surface`, `paper`, `ink`, `muted`, `faint`, `accent`, `info`) or hex |\n| `opacity="80"` | all but html | 0–100 |\n| `radius="12"` | all but hr, icon and html | 0–360 px |\n| `border="solid"` | all but hr, icon and html | `solid`, `dashed` or `dotted`, 1 px in the theme\'s rule colour |\n| `shadow="0 8 24 #00000040"` | all but hr, icon and html | x, y, blur in px and a colour |\n\n```xml\n<slide id="promise" free="true">\n <p x="96" y="180" w="fill" h="120" fit="shrink" size="32" weight="600" fill="surface" radius="12" pad="16">Every artifact, one server.</p>\n</slide>\n```\n\nThese are deliberate choices: keep these attributes when you rewrite a block, unless changing them is the point.\n\n- An `id` on a block (letters, digits, `_` and `-`, at most 32) is how the viewer and comments know that block again. Your human partner\'s edits give blocks ids: keep every block id when you rewrite a slide, as you keep slide ids.\n\n## Rules\n\n- A talk is given offline: keep fonts, scripts and images inside the artifact directory and avoid CDNs.\n- Notes are not secret: they are hidden from viewers in the interface but remain in the page source.\n- Your human partner can edit notes in the viewer. Saving writes that slide\'s `<notes>` back as plain text lines joined by `<br/>`, replacing any markup inside it, in the file the slide is written in.\n- Keep the whole artifact under 20 MB.\n- Your human partner can edit slides in the viewer: select blocks, drag and resize them (which makes a slide `free="true"`), type into them, change their tag, alignment, colour and every look attribute, restack blocks, change a slide\'s layout, add text boxes, copy, paste and delete. Each edit rewrites the slide in `deck.xml` or its include file in place and is listed by `changes`. Re-read the file before every edit. When you write over one of their edits before you have read it, `check` warns with `W_HUMAN_EDIT_OVERWRITTEN`, naming the slide, the block and what they had set: put their edit back unless you meant to change it.\n- Your human partner can restructure the deck in the viewer\'s grid: reorder and duplicate slides, skip them, add placeholder slides, delete them, and create, rename or move groups. Each change rewrites `deck.xml` (and an include file, for a slide written there) in place, keeping the rest of the text as it was. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact slides/<id>` and read them before editing the deck, so you build on their order instead of writing it back.\n\n## Feedback\n\nComments are anchored to a slide, usually to a point on it. `comment list --sections threads --detail` shows the slide id, its title, the text under the pin and the message. A comment made on selected blocks lists them as `nodes`, each with its block (`#id`, or its position on the slide) and its text: change those blocks. Edit that slide, keep its id, run `check`, then reply with what changed. A comment whose slide was deleted is listed as an orphan.\n\nRun the returned Check command after every edit. Without a browser it reports XML that does not parse, tags, attributes and values the deck cannot take, files it cannot read, missing or duplicate ids, unknown layouts, missing assets and embeds whose target is not there, each naming its slide. Slides that overflow and code, diagram or formula errors come from the browser: with no browser open the result is pending, not clean.\n';const yg=[`default`,`cover`,`section`,`statement`,`two-cols`,`image`,`quote`,`fact`,`code`,`end`,`none`],bg=/^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/,xg=e=>{let t=e.trim();return t===`all`||t===`hide`?t:null};function Sg(e){let t=[];for(let n of e.split(`|`)){let e=xg(n);if(e){t.push(e);continue}let r=/* @__PURE__ */ new Set;for(let e of n.split(`,`)){let t=bg.exec(e);if(!t)continue;let n=Number(t[1]),i=t[2]===void 0?n:Number(t[2]),a=Math.max(n,i);for(let e=Math.max(1,Math.min(n,i));e<=a&&!(r.size>=2e3);e++)r.add(e)}r.size&&t.push([...r].sort((e,t)=>e-t))}return t}const Cg=e=>e.split(`|`).every(e=>xg(e)!==null||e.split(`,`).every(e=>{let t=bg.exec(e);return t!==null&&Number(t[1])>=1&&Number(t[2]??1)>=1})),wg=[`view`,`fade-out`,`fade`,`slide-left`,`slide-up`,`none`],Tg=[`full`,`top`,`bottom`,`left`,`right`,`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`,`none`],Eg=e=>wg.includes(e),Dg=e=>Tg.includes(e),Og=/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i;function kg(e){let t=e?.trim();return!t||Og.test(t)?null:t.split(/[?#]/)[0]||null}const Ag=/^[a-z0-9][a-z0-9-]*$/,jg=`((?:"[^"]*"|'[^']*'|[^'">])*)`,Mg=RegExp(`<!--[\\s\\S]*?(?:-->|$)|<(script|style|textarea|template|title)\\b${jg}>([\\s\\S]*?)(?:<\\/\\1\\s*>|$)|<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)${jg}>`,`gi`),Ng=/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,Pg=/reveal(?:\.min)?(?:\.esm)?\.m?js(?:[?#]|$)/i,Fg={lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,amp:`&`};function Ig(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(Ng)){let e=n[1].toLowerCase();t.has(e)||t.set(e,n[2]??n[3]??n[4]??``)}return t}function Lg(e){return e.replaceAll(/<[^>]*>/g,``).replaceAll(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi,(e,t,n,r)=>t?String.fromCodePoint(Number(t)):n?String.fromCodePoint(Number.parseInt(n,16)):Fg[String(r).toLowerCase()]??e).replaceAll(/\s+/g,` `).trim().slice(0,200)}function Rg(e){let t=e.toLowerCase(),n=[],r=[],i=null,a=null,o=!1,s=!1,c=0,l=/* @__PURE__ */ new Set,u=e=>{let t=kg(e);t&&l.add(t)},d=e=>{for(let t=n.length-1;t>=0;t--)if(n[t].tag===e){for(let e of n.splice(t))e.kind===`slide`&&(i=null),e.kind===`notes`&&--c;return}};Mg.lastIndex=0;for(let l=Mg.exec(e);l;l=Mg.exec(e)){let[,f,p=``,m=``,h,g,_=``]=l;if(f){let e=f.toLowerCase();e===`title`&&!i&&a===null&&(a=Lg(m)||null);let t=e===`script`?Ig(p).get(`src`):void 0;u(t),e===`script`&&(Pg.test(t??``)||m.includes(`Reveal.initialize`))&&(s=!0);let r=n.at(-1);e===`template`&&i&&!c&&r?.kind===`magic`&&(r.templates=(r.templates??0)+1,r.templates>1&&(i.steps+=1));continue}if(!g)continue;let v=g.toLowerCase();if(h){(v===`div`||v===`section`||v===`aside`)&&d(v);continue}let y=Ig(_);u(y.get(`src`)),v===`link`&&u(y.get(`href`));let b=(y.get(`class`)??``).split(/\s+/).filter(Boolean),x=n.at(-1)?.kind;if(i&&!c){let n=y.get(`data-morph`)?.trim();if(n&&(i.morphs.has(n)&&!i.morphRepeats.includes(n)&&i.morphRepeats.push(n),i.morphs.add(n)),b.includes(`fragment`)){let e=y.get(`data-fragment-index`);e!==void 0&&i.positions.has(e)||(i.steps+=1),e!==void 0&&i.positions.add(e)}if(v===`code`&&(i.steps+=Math.max(0,Sg(y.get(`data-lines`)??``).length-1)),!i.titled&&/^h[1-3]$/.test(v)){let n=t.indexOf(`</${v}`,Mg.lastIndex);i.title=Lg(e.slice(Mg.lastIndex,n===-1?void 0:n)),i.titled=!0}}if(v===`div`){let e=`other`;!o&&x===`reveal`&&b.includes(`slides`)?(e=`slides`,o=!0):!o&&b.includes(`reveal`)?e=`reveal`:i&&b.includes(`magic-move`)&&(e=`magic`),n.push({tag:v,kind:e})}else if(v===`section`){if(x===`slides`){let e=b.find(e=>e.startsWith(`l-`)),t=e?e.slice(2):`default`;i={id:y.get(`id`)||null,layout:t,title:``,steps:0,notes:!1,nested:!1,titled:!1,unknownLayout:yg.includes(t)?null:t,transition:y.get(`data-transition`)?.trim()??null,glow:y.get(`data-glow`)?.trim()??null,morphs:/* @__PURE__ */ new Set,morphRepeats:[],positions:/* @__PURE__ */ new Set,...y.has(`data-deck-hidden`)?{hidden:!0}:{},...y.get(`data-deck-group`)?{group:y.get(`data-deck-group`)}:{}},r.push(i),n.push({tag:v,kind:`slide`})}else i&&(i.nested=!0),n.push({tag:v,kind:`other`})}else if(v===`aside`){let e=i!==null&&b.includes(`notes`);e&&(i.notes=!0,c+=1),n.push({tag:v,kind:e?`notes`:`other`})}}let f=[],p=/* @__PURE__ */ new Set,m=r.map(({nested:e,titled:t,unknownLayout:n,transition:r,glow:i,morphs:a,morphRepeats:o,positions:s,...c},l)=>{let u=c.id??void 0;c.id?Ag.test(c.id)?p.has(c.id)&&f.push({code:`duplicate_id`,slide:l,id:u}):f.push({code:`invalid_id`,slide:l,id:u}):f.push({code:`missing_id`,slide:l}),c.id&&p.add(c.id),e&&f.push({code:`nested_slide`,slide:l,...u?{id:u}:{}}),n&&f.push({code:`unknown_layout`,slide:l,...u?{id:u}:{},detail:n});let d={slide:l,...u?{id:u}:{}};r!==null&&!Eg(r)&&f.push({code:`unknown_transition`,...d,detail:r}),i!==null&&!Dg(i)&&f.push({code:`unknown_glow`,...d,detail:i});for(let e of o)f.push({code:`duplicate_morph`,...d,detail:e});return c});return s&&f.push({code:`own_reveal`,slide:-1}),{complete:/<\/html\s*>\s*$/i.test(e),hasDeck:o,title:a,slides:m,issues:f,assets:[...l]}}const zg=new Map(Object.entries({lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`,nbsp:`\xA0`,mdash:`—`,ndash:`–`,hellip:`…`,rarr:`→`,larr:`←`,uarr:`↑`,darr:`↓`,harr:`↔`,copy:`©`,reg:`®`,trade:`™`,times:`×`,divide:`÷`,middot:`·`,bull:`•`,laquo:`«`,raquo:`»`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`,deg:`°`,plusmn:`±`,le:`≤`,ge:`≥`,ne:`≠`,euro:`€`,pound:`£`,yen:`¥`})),Bg=/[A-Za-z_][\w.-]*/y,Vg=/\s*/y,Hg=e=>`name`in e;function Ug(e,t){return e.replaceAll(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]*));/g,(e,n,r,i,a)=>{let o=n?Number(n):r?Number.parseInt(r,16):null;if(o!==null)return o>0&&o<=1114111?String.fromCodePoint(o):e;let s=zg.get(i);return s===void 0&&t?.(i,a),s??e})}function Wg(e){return Hg(e)?e.children.map(Wg).join(``):e.text}function Gg(e){let t=[],n=null,r=t=>{if(!n){n=[];for(let t=e.indexOf(`
321
321
  `);t!==-1;t=e.indexOf(`
322
322
  `,t+1))n.push(t)}let r=0,i=n.length;for(;r<i;){let e=r+i>>1;n[e]<t?r=e+1:i=e}return r+1},i=(e,n)=>t.push({line:r(e),message:n}),a=[],o=[],s=()=>o.at(-1)?.children??a,c=/* @__PURE__ */ new Set,l=e=>(t,n)=>{c.has(t)||(c.add(t),i(e+n,`&${t}; is not an entity a deck knows: write the character itself, or &amp; for a plain &`))},u=(t,n,r)=>{if(n<=t)return;let a=e.slice(t,n),o=r?-1:a.indexOf(`]]>`);o!==-1&&i(t+o,`a ]]> outside CDATA: the section before it ended early. Split it as ]]]]><![CDATA[> or take the code from a file`),s().push({start:t,end:n,cdata:r,text:r?a:Ug(a,l(t))})},d=0;for(;d<e.length;){let n=e.indexOf(`<`,d);if(n===-1){u(d,e.length,!1);break}if(u(d,n,!1),e.startsWith(`<!--`,n)){let t=e.indexOf(`-->`,n+4);if(t===-1){i(n,`a comment is never closed with -->`);break}d=t+3;continue}if(e.startsWith(`<![CDATA[`,n)){let t=e.indexOf(`]]>`,n+9);if(t===-1){i(n,`a CDATA section is never closed with ]]>`);break}u(n+9,t,!0),d=t+3;continue}if(e.startsWith(`<?`,n)||e.startsWith(`<!`,n)){let t=e.indexOf(`>`,n);d=t===-1?e.length:t+1;continue}if(e[n+1]===`/`){Bg.lastIndex=n+2;let t=Bg.exec(e)?.[0],r=e.indexOf(`>`,n);if(!t||r===-1){i(n,`a closing tag is not finished`);break}d=r+1;let a=o.length-1;for(;a>=0&&o[a].name!==t;)--a;if(a===-1&&o.length===0){i(n,`</${t}> closes nothing that is open`);continue}a!==o.length-1&&i(n,`</${t}> closes <${o.at(-1).name}>, which is still open`);for(let e of o.splice(a===-1?o.length-1:a))e.innerEnd=n,e.end=d;continue}Bg.lastIndex=n+1;let a=Bg.exec(e)?.[0];if(!a){i(n,`a "<" that starts no tag: write &lt; or use CDATA`),d=n+1;continue}let c=/* @__PURE__ */ new Map,f=n+1+a.length,p=!1,m=!1;for(;f<e.length;){if(Vg.lastIndex=f,f+=Vg.exec(e)[0].length,e[f]===`>`){f+=1,m=!0;break}if(e.startsWith(`/>`,f)){f+=2,p=!0,m=!0;break}Bg.lastIndex=f;let t=Bg.exec(e)?.[0],n=t?e[f+t.length+1]:void 0;if(!t||e[f+t.length]!==`=`||n!==`"`&&n!==`'`){i(f,`<${a}> has an attribute that is not name="value"`);break}let r=f+t.length+2,o=e.indexOf(n,r);if(o===-1){i(f,`<${a}> has an attribute value that is never closed`);break}c.has(t)||c.set(t,Ug(e.slice(r,o),l(r))),f=o+1}if(!m){let r=e.indexOf(`>`,f);if((t.length===0||r===-1)&&i(n,`<${a}> is not finished`),r===-1)break;f=r+1}let h={name:a,attrs:c,children:[],start:n,end:f,innerStart:f,innerEnd:f,line:r(n),selfClosing:p};if(s().push(h),d=f,!p){if(o.length>=100){i(n,`elements are nested more than 100 deep`);break}o.push(h)}}let f=t.length>0&&d<e.length;for(let t of o)f||i(t.start,`<${t.name}> is never closed`),t.innerEnd=e.length,t.end=e.length;let p=a.filter(Hg),m=a.find(e=>!Hg(e)&&e.text.trim()!==``);return p.length>1?i(p[1].start,`only one root element is allowed`):m&&i(m.start,`text outside the root element`),{root:p[0]??null,errors:t}}const Kg=/* @__PURE__ */ `h1.h2.h3.p.blockquote.ul.ol.table.img.icon.alert.hr.codeblock.code.magic.mermaid.math.chart.embed.html.kicker.subtitle.label.quote.cite.big.fact`.split(`.`),qg=[`h1`,`h2`,`h3`,`p`,`blockquote`,`ul`,`ol`,`kicker`,`subtitle`,`label`,`quote`,`cite`],Jg=[`ink`,`muted`,`faint`,`accent`,`info`],Yg=[`left`,`center`,`right`],Xg=[`x`,`y`,`w`,`h`],Zg=/^[A-Za-z0-9_-]{1,32}$/,Qg=e=>Kg.includes(e);function $g(e){let t=/* @__PURE__ */ new Map;return e.children.filter(Hg).forEach((e,n)=>{e.name===`col`?e.children.filter(Hg).forEach((e,r)=>{Qg(e.name)&&t.set(e,`${n}.${r}`)}):Qg(e.name)&&t.set(e,String(n))}),t}const e_=Jg,t_=[`surface`,`paper`,`ink`,`muted`,`faint`,`accent`,`info`],n_=[`solid`,`dashed`,`dotted`],r_=[...Yg,`justify`],i_={ink:`ink`,muted:`ink-2`,faint:`ink-3`,accent:`accent`,info:`info`,surface:`surface`,paper:`paper`},a_=e=>`var(--deck-${i_[e]??e})`,o_=[`img`,`embed`,`chart`,`mermaid`,`math`,`magic`],s_=[`table`,`codeblock`,`code`,`alert`,`big`,`fact`],c_=[`hr`,`icon`],l_=[`fill`,`opacity`,`radius`,`border`,`shadow`],u_=[`font`,`weight`,`size`,`leading`,`tracking`,`fit`];function d_(e){return qg.includes(e)?[`pad`,...u_,`align`,`color`,...l_]:o_.includes(e)?[...l_]:s_.includes(e)?[`pad`,...l_]:c_.includes(e)?[`opacity`]:[]}const f_=/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i,p_=/^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,63}$/u,m_=(e,t,n)=>/^-?\d+$/.test(e)&&Number(e)>=t&&Number(e)<=n,h_=(e,t,n,r)=>RegExp(`^-?\\d+(?:\\.\\d{1,${r}})?$`).test(e)&&Number(e)>=t&&Number(e)<=n,g_=(e,t)=>t.includes(e)||f_.test(e);function __(e){let t=e.split(` `);if(t.length!==4)return null;let[n,r,i,a]=t;return m_(n,-200,200)&&m_(r,-200,200)&&m_(i,0,200)&&g_(a,t_)?[n,r,i,a]:null}const v_={pad:[e=>m_(e,0,200),`must be whole pixels from 0 to 200`],font:[e=>e===`mono`||p_.test(e),`must be mono or a font name: letters, digits, spaces, - _ . (at most 64)`],weight:[e=>m_(e,100,900)&&Number(e)%100==0,`must be 100, 200 … 900`],size:[e=>m_(e,8,400),`must be whole pixels from 8 to 400`],leading:[e=>h_(e,.8,3,2),`must be 0.8 to 3, at most two decimals`],tracking:[e=>h_(e,-20,100,1),`must be -20 to 100 pixels, at most one decimal`],fit:[e=>e===`shrink`,`must be shrink`],fill:[e=>g_(e,t_),`must be #RRGGBB, #RRGGBBAA or ${t_.join(`, `)}`],opacity:[e=>m_(e,0,100),`must be 0 to 100`],radius:[e=>m_(e,0,360),`must be whole pixels from 0 to 360`],border:[e=>n_.includes(e),`must be ${n_.join(`, `)}`],shadow:[e=>__(e)!==null,`must be "x y blur colour": x and y -200 to 200, blur 0 to 200`],align:[e=>r_.includes(e),`must be ${r_.join(`, `)}`],color:[e=>g_(e,e_),`must be #RRGGBB, #RRGGBBAA or a theme colour: ${e_.join(`, `)}`]};function y_(e,t,n){let r=Object.hasOwn(v_,t)?v_[t]:void 0;return r?d_(e).includes(t)?r[0](n)?null:`${t}="${n}" ${r[1]}`:`<${e}> takes no ${t}`:`${t} is not a look attribute`}const b_=e=>f_.test(e)?e:a_(e);function x_(e,t){switch(e){case`pad`:return[[`padding`,`${t}px`]];case`font`:return[[`font-family`,t===`mono`?`var(--deck-font-mono)`:`"${t}", var(--deck-font)`]];case`weight`:return[[`font-weight`,t]];case`size`:return[[`font-size`,`${t}px`]];case`leading`:return[[`line-height`,t]];case`tracking`:return[[`letter-spacing`,`${t}px`]];case`fill`:return[[`background-color`,b_(t)]];case`opacity`:return[[`opacity`,String(Number(t)/100)]];case`radius`:return[[`border-radius`,`${t}px`]];case`border`:return[[`border`,`1px ${t} var(--deck-rule-strong)`]];case`shadow`:{let e=__(t);if(!e)return[];let[n,r,i,a]=e;return[[`box-shadow`,`${n}px ${r}px ${i}px ${b_(a)}`]]}case`color`:return[[`color`,b_(t)]];case`align`:return[[`text-align`,t]];default:return[]}}const S_={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},C_=/^[1-9]\d?$/,w_=(e,t)=>e.name===`col`||(e.name===`ul`||e.name===`ol`)&&t.name===`li`||e.name===`table`&&t.name===`tr`&&t.children.some(e=>Hg(e)&&e.name===`td`);function T_(e){return e.name===`codeblock`?Math.max(0,Sg(e.attrs.get(`lines`)??``).length-1):e.name===`magic`?Math.max(0,e.children.filter(e=>Hg(e)&&e.name===`step`).length-1):0}function E_(e){let t=/* @__PURE__ */ new Set,n=e=>{let r=e.attrs.get(`step`)??``;C_.test(r)&&t.add(Number(r)-1);for(let t of e.children)Hg(t)&&n(t)};return n(e),t}function D_(e,t){let n={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},r=E_(e),i=0,a=null,o=()=>{for(;r.has(i);)i+=1;return i+=1,i-1},s=(e,r)=>{if(e.name===`notes`)return;let c=e.attrs.get(`step`)??(r?`true`:`false`),l=null;c===`true`?l=o():c===`with`?(n.explicit=!0,a===null?t.bad(e,`step`,`has no step before it to appear with`):l=a):C_.test(c)?(n.explicit=!0,l=Number(c)-1):c!==`false`&&t.bad(e,`step`,`must be true, with, or a step number from 1`),l!==null&&(n.index.set(e,l),a=l);let u=T_(e);if(u>0){n.from.set(e,o());for(let e=1;e<u;e+=1)o();a=i-1}if(e.name===`codeblock`||e.name===`magic`)return;let d=e.attrs.get(`steps`);d!==void 0&&d!==`true`&&d!==`false`&&t.bad(e,`steps`,`must be true or false`);for(let t of e.children)Hg(t)&&s(t,d===`true`&&w_(e,t))};for(let t of e.children)Hg(t)&&s(t,!1);return n}const O_=/^[a-z0-9-]{1,16}$/,k_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,A_={readFile:(e,t)=>({error:`${t} cannot be read here`})},j_=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`);function M_(e){let t=e.filter(([e,t])=>e===`style`&&t!==!0);if(t.length<2)return e;let n=t.map(([,e])=>e).join(`;`),r=e.findIndex(([e])=>e===`style`);return e.flatMap((e,t)=>e[0]===`style`?t===r?[[`style`,n]]:[]:[e])}function N_(e,{classes:t,attrs:n},r){return`<${[e,...r===void 0?[]:[`id="${j_(r)}"`],...t.length?[`class="${t.join(` `)}"`]:[],...M_(n).map(([e,t])=>t===!0?e:`${e}="${j_(t)}"`)].join(` `)}>`}const P_=/^[a-z0-9][a-z0-9-]*$/;var F_=class{env;audience;sources;deps=[];embeds=[];issues=[];refs=[];warnings=[];id;free=!1;placed=/* @__PURE__ */ new Map;blockIds=/* @__PURE__ */ new Set;slide=-1;steps=S_;constructor(e,t=!1,n=!1){this.env=e,this.audience=t,this.sources=n}issue(e,t,n){return{code:e,slide:this.slide,...this.id?{id:this.id}:{},...n?{tag:n}:{},detail:t}}report(e,t,n){this.issues.push(this.issue(e,t,n))}warn(e,t,n){this.warnings.push(this.issue(e,t,n))}read(e,t,n){let r=this.env.readFile(e,t);if(typeof r!=`string`)return this.report(`file`,r.error,n.name),null;let i=`${e}:${t}`;return this.deps.includes(i)||this.deps.push(i),r}bad(e,t,n){this.report(`bad_value`,`${t}="${e.attrs.get(t)??``}" ${n}`,e.name)}flag(e,t){let n=e.attrs.get(t);return n===void 0||n===`false`?!1:n===`true`||(this.bad(e,t,`must be true or false`),!1)}decor(e,t=[]){let n=this.attrs(e,[...t,`morph`,`step`,...this.blockAttrs(e)]),r=this.plain(e),i=this.steps.index.get(e);i!==void 0&&(r.classes.push(`fragment`),this.steps.explicit&&r.attrs.push([`data-fragment-index`,String(i)]));let a=e.attrs.get(`step`);this.sources&&a!==void 0&&O_.test(a)&&r.attrs.push([`data-deck-step`,a]);let o=n.get(`morph`);return o!==void 0&&(P_.test(o)?r.attrs.push([`data-morph`,o]):this.bad(e,`morph`,`must be lowercase letters, digits and hyphens`)),r}blockAttrs(e){return this.placed.has(e)?[`id`,...Xg,...d_(e.name)]:[]}plain(e){let t={classes:[],attrs:[]},n=this.placed.get(e);if(n===void 0)return t;this.id&&this.sources&&t.attrs.push([`data-deck-src`,`${this.id}:${n}`],[`data-deck-tag`,e.name]);let r=e.attrs.get(`id`);r!==void 0&&(Zg.test(r)?this.blockIds.has(r)?this.report(`bad_value`,`id="${r}" is used by another block on this slide`,e.name):(this.blockIds.add(r),this.sources&&t.attrs.push([`data-deck-id`,r])):this.bad(e,`id`,`must be letters, digits, _ and -, at most 32`));let i=this.place(e,t),a={},o=t.attrs.some(([e])=>e===`data-deck-placed`);for(let t of[`w`,`h`]){let n=e.attrs.get(t);o&&n!==void 0&&(t===`h`||n===`fill`)&&(a[t]=n)}o&&a.h!==void 0&&qg.includes(e.name)&&i.push(`overflow:hidden`);for(let n of d_(e.name)){let r=e.attrs.get(n);if(r===void 0)continue;let o=y_(e.name,n,r);o?this.report(`bad_value`,o,e.name):n===`fit`&&!e.attrs.has(`h`)?this.report(`bad_value`,`fit="shrink" needs h on a free="true" slide`,e.name):(a[n]=r,n===`align`?t.attrs.push([`data-align`,r]):n===`color`&&Jg.includes(r)?t.attrs.push([`data-color`,r]):n===`fit`?t.attrs.push([`data-deck-fit`,r]):i.push(...x_(n,r).map(([e,t])=>`${e}:${t}`)))}return i.length&&t.attrs.push([`style`,i.join(`;`)]),this.sources&&Object.keys(a).length&&t.attrs.push([`data-deck-look`,JSON.stringify(a)]),t}place(e,t){let n=Xg.filter(t=>e.attrs.has(t));if(!this.free)return n.length&&this.report(`bad_value`,`${n.join(`, `)} only work on a slide with free="true"`,e.name),[];if(![`x`,`y`,`w`].every(t=>e.attrs.has(t)))return this.report(`misplaced`,`<${e.name}> on a free="true" slide needs x, y and w`,e.name),[];let r={},i=!0;for(let t of n){let n=e.attrs.get(t);if(t===`w`&&n===`fill`)continue;let a=Number(n),o=t===`w`||t===`h`;!/^-?\d+$/.test(n)||Math.abs(a)>4e3||o&&a<=0?(this.bad(e,t,o?`must be a whole number of pixels above 0`:`must be a whole number of pixels`),i=!1):r[t]=a}if(!i)return[];let a=r.w??Math.max(1,1184-r.x),o=[`left:${r.x}px`,`top:${r.y}px`,`width:${a}px`];return r.h!==void 0&&o.push(`height:${r.h}px`),t.attrs.push([`data-deck-placed`,!0]),o}attrs(e,t){for(let n of e.attrs.keys())t.includes(n)||this.report(`unknown_attr`,n,e.name);return e.attrs}};const I_=/^([^#]+?)(?:#L(\d+)(?:-(\d+))?)?$/,L_=/<\/?(?:section|html|body|head)\b|<!doctype/i,R_=/<(\/?)div\b/gi;function z_(e,t){let n=e.attrs.get(`src`).trim(),r=I_.exec(n);if(!r)return t.bad(e,`src`,`must be a path, optionally followed by #L10 or #L10-24`),null;let[,i,a,o]=r,s=t.read(`project`,i,e);if(s===null)return null;let c=s.replaceAll(`\r
323
323
  `,`
@@ -938,10 +938,10 @@ Run Check after edits; skeleton_not_completed/browser_not_run needs the board op
938
938
  `).map(e=>` ${e.replaceAll(/\p{Cc}/gu,e=>e===` `?e:``)}`))}t.groups.length||e||t.page||s.push(`No messages.`),h(t.page)}else if(t.kind===`diagnostics`){let e=n.detail?t.items.length:t.preview??3;for(let n of t.items.slice(0,e))s.push(` ${n.location?`${lC(n.location)} `:``}${lC(n.code)}: ${u(n.message,`data.${t.key}`)}`);e<t.items.length&&c.push({path:`data.${t.key}`,reason:`preview`,count:t.items.length-e})}else m(e&&`${e}:`,t.summary),s.push(...t.text.trimEnd().split(`
939
939
  `).map(e=>` ${e.replaceAll(/\p{Cc}/gu,e=>e===` `||e===`
940
940
  `?e:``)}`))}t.page&&h(t.page),(a||(t.effects??[]).some(e=>e.state!==`confirmed`))&&s.push(...bC(t.effects??[]));for(let e of t.warnings??[])s.push(`Warning: ${lC(e.message)}`);let _=e.actions??t.next??[],v=[..._,...g.filter(e=>!_.some(t=>yC(t)===yC(e)))],y=/* @__PURE__ */ new Set,b=v.find(e=>e.label===`Details`);for(let e of c){if(e.count===void 0)continue;let t=`${e.count} more ${xC(e.path)}`;b&&!y.has(b)?(y.add(b),s.push(`${t} · Details: ${yC(b)}`)):s.push(t)}for(let e of v)y.has(e)||s.push(`${lC(e.label??`Next`)}: ${e.reason?`${lC(e.reason)} · `:``}${yC(e)}`);return`${s.join(`
941
- `)}\n`}function CC(e,t,n=1){return SC({heading:gC(e.command),status:``,facts:[],sections:[]},e,{...t,fields:void 0},void 0,[],n)}function Z(e,t){return{run:(n,r,i,a)=>wC(e,t,n,r,i,a)}}async function wC(e,t,n,r,i,a){let o=0,s=Promise.resolve(),c,l=!1,u=[],d=new AbortController,f=()=>d.abort(i?.reason);i?.addEventListener(`abort`,f,{once:!0}),i?.aborted&&f();let p={signal:d.signal,effects:new rC,payloads:{},progress(e){l||h(n.format===`jsonl`?`stdout`:`stderr`,n.format===`jsonl`?m(`progress`,e):`${e.phase}${e.current===void 0?``:` ${e.current}${e.total===void 0?``:`/${e.total}`}`}\n`)},diagnostic(e){h(`stderr`,`${e.trimEnd()}\n`)}};function m(e,t){return`${JSON.stringify({schema:`ryugi.cli/v1`,...t,seq:o++,kind:e})}\n`}function h(e,t){s=s.then(()=>r.write(e,t)).catch(e=>{c=e,d.abort(e)})}async function g(){if(await s,c)throw c}let _=8388608;async function v(e,t){if((typeof t==`string`?new TextEncoder().encode(t).byteLength:t.byteLength)>_)throw new K({code:`E_RESULT_TOO_LARGE`,message:`Result exceeds 8 MiB; read one object or save it to a file.`});await g(),await r.write(e,t)}async function y(t,r=`result`){let i={...t,effects:t.effects.length?t.effects:p.effects.snapshot()};i.effects.some(e=>e.state===`unknown`)&&(i.actions=[...i.actions,...a?.(e.id,void 0,i.effects)??[]]),u=i.effects;let o=PS(e.id,i,n,e.output);if(n.format===`json`)await v(`stdout`,`${JSON.stringify(o)}\n`);else if(n.format===`jsonl`){let t=o,n=e.output.collection;if(n&&r===`result`){let e=o.data,r=e[n];if(Array.isArray(r)){for(let e of r)await v(`stdout`,m(`item`,{collection:n,data:e}));let i={...e};delete i[n],t={...o,data:i}}}await v(`stdout`,m(r,t))}else if(n.format===`raw`||n.format===`source`){let e=p.payloads[n.format];if(e===void 0)throw new K({code:`E_PAYLOAD_UNAVAILABLE`,message:`No ${n.format} payload was returned.`});await v(`stdout`,e)}else if(n.format===`quiet`){if(!e.output.scalar)throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`This command has no scalar output.`});await v(`stdout`,`${e.output.scalar(i.data)}\n`)}else await v(i.completion.kind===`failed`?`stderr`:`stdout`,SC(e.present(i),o,n,e.output.collection,e.output.requiredFields,MS(i.completion).code));return MS(i.completion).code}try{if(!e.output.formats.includes(n.format)||e.mode===`live`&&[`json`,`quiet`,`raw`,`source`,`table`].includes(n.format))throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`${n.format} is not supported for ${e.id}. Supported: ${e.output.formats.join(`, `)}`});if(n.detail&&!e.output.detail)throw new K({code:`E_OPTION_UNSUPPORTED`,message:`--detail is not supported for this operation.`});let r=n.fields?.find(t=>!e.output.fields?.includes(t));if(r)throw new K({code:`E_FIELD_UNKNOWN`,message:`Unknown output field: ${r}`});if(n.format===`jsonl`&&await v(`stdout`,m(`meta`,{command:e.id})),e.mode===`finite`){let n=await e.run(t,p);return l=!0,await y(n)}let i=!1,a;for await(let n of e.run(t,p)){if(a||n.kind===`ready`&&i)throw new K({code:`E_LIFECYCLE_INVALID`,message:`Invalid command lifecycle.`});if(n.kind===`ready`){i=!0;try{await y(n.result,`ready`)}catch(e){throw d.abort(e),e}}else a=n.result,l=!0}if(!a)throw new K({code:`E_LIFECYCLE_INCOMPLETE`,message:`Command ended without a terminal result.`});return await y(a)}catch(t){if(l=!0,t instanceof K&&t.raw!==void 0&&(p.payloads.raw=t.raw),t?.code===`EPIPE`)return 141;let i=d.signal.aborted&&(d.signal.reason===`SIGINT`||d.signal.reason===`SIGTERM`)?d.signal.reason:void 0,o=i?{code:`E_INTERRUPTED`,message:`Command interrupted by ${i}.`,details:{signal:i}}:jS(t),s=t instanceof K?t.kind===`action_required`:t?.code===2,c=p.effects.snapshot(),f=J(null,i?{kind:`interrupted`,signal:i}:s?{kind:`action_required`,reason:o.message}:{kind:`failed`,error:o},{effects:c.length?c:u,actions:[...a?.(e.id,o,c.length?c:u)??[],...t?.actions??[]]}),h={...PS(e.id,f,{...n,fields:void 0},{}),error:o};try{await g(),n.format===`json`||n.format===`jsonl`?await r.write(`stdout`,n.format===`json`?`${JSON.stringify(h)}\n`:m(`result`,h)):n.format===`raw`&&p.payloads.raw!==void 0&&o.code!==`E_RESULT_TOO_LARGE`&&Buffer.byteLength(p.payloads.raw)<=_?await r.write(`stdout`,p.payloads.raw):await r.write(`stderr`,CC(h,n,MS(f.completion).code)),n.verbose&&t instanceof Error&&t.stack&&await r.write(`stderr`,`${t.stack}\n`)}catch(e){if(e?.code===`EPIPE`)return 141}return MS(f.completion).code}finally{i?.removeEventListener(`abort`,f)}}function TC(e){let t=e.values;if(t.foreground&&t.background)throw new K({code:`E_OPTION_CONFLICT`,message:`Choose --foreground or --background.`});if(t.open&&t[`no-open`])throw new K({code:`E_OPTION_CONFLICT`,message:`Choose --open or --no-open.`});return{projectDir:e.projectDir,artifact:t.artifact,background:!!t.background,foreground:!!t.foreground,host:t.host??`127.0.0.1`,urlHost:t[`url-host`],port:t.port,open:t[`no-open`]?!1:t.open?!0:process.env.ARTIFACTS_OPEN!==`0`,openExisting:!!t.open,mockup:!!t.mockup}}function EC(e,t){let n=t?d.default.dirname(d.default.dirname(t.root)):e.projectDir,r=e.artifact?lS(n,e.artifact):void 0;return{cliVersion:`1.108.6`,serverVersion:et(ke().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:sS(e.artifact,{mockup:e.mockup})}:{},reused:!!t?.reused,...t?{url:t.cloudLink??t.link??t.url,localUrl:t.link??t.url}:{},...e.artifact?{artifact:e.artifact}:{},cloud:t?.cloudLink?`live_link_reserved`:`local_only`}}function DC({data:e}){return{heading:`Server`,status:e.status,subject:e.reused?`reused`:void 0,facts:[X(`Scope`,Y(e,`scope`)),X(`CLI version`,Y(e,`cliVersion`)),X(`Server version`,Y(e,`serverVersion`)),X(`Project`,Y(e,`project`),!0),...e.artifact?[X(`Artifact`,Y(e,`artifact`),!0)]:[],...e.write?[X(`Write`,Y(e,`write`),!0),X(`Content`,Y(e,`content`),!0)]:[],...e.url?[X(`Open`,Y(e,`url`),!0)]:[],...e.localUrl&&e.localUrl!==e.url?[X(`Local`,Y(e,`localUrl`),!0)]:[],X(`Cloud`,Y(e,`cloud`))],sections:e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[]}}function OC(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&ge(n)?Qx[n].onStart:void 0;r&&r(d.default.join(d.default.dirname(d.default.dirname(t.root)),`.ryugi`,`artifacts`,e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[];return e.artifact&&i.push(q([`check`,`--project-dir`,d.default.dirname(d.default.dirname(t.root)),`--artifact`,e.artifact],`Check`)),t.loginHint&&i.push(q([`publish`,`--login`,`--from`,`hint`,`--project-dir`,e.projectDir],`Sign in`)),J(EC(e,t),void 0,{actions:i,warnings:[...t.loginHint?[{code:`W_LOGIN_OPTIONAL`,message:t.loginHint.message}]:[],...t.cloudLimit?[{code:`W_CLOUD_LIMIT`,message:String(t.cloudLimit.message??`Cloud link unavailable; local server is ready.`)}]:[]]})}async function*kC(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=tw(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:OC(e,n)})},failure(e){s=String(e.error??`Server failed`)},log:e=>t.diagnostic(e)}).then(n=>{if(t.signal.aborted){let n=t.signal.reason===`SIGINT`?`SIGINT`:`SIGTERM`;l({kind:`result`,result:J({...EC(e,o),status:`stopped`},{kind:`interrupted`,signal:n},{effects:t.effects.snapshot()})})}else if(n!==0||s)throw new K({code:`E_SERVER_FAILED`,message:s??`Server exited with ${n}.`});else l({kind:`result`,result:J({...EC(e,o),status:o?.reused?`running`:`stopped`},void 0,{effects:t.effects.snapshot()})})}).catch(e=>{a=e}).finally(()=>{i=!0,r?.()});try{for(;!i||n.length;)n.length?yield n.shift():await new Promise(e=>{r=e});if(a)throw a}finally{await u}}function AC(e,t=`start`){let n=TC(e);return n.library=t===`browse`,n.foreground?Z({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>kC(n,t),present:DC},e):Z({id:t,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.url},async run(e,t){let r,i,a=t.effects.begin(`start`,n.projectDir);if(await tw(n,{signal:t.signal,ready(e){r=e,t.effects.confirm(a,{reused:!!e.reused})},failure(e){i=String(e.error??`Server failed`)},log:e=>t.diagnostic(e)})!==0||!r)throw new K({code:`E_SERVER_FAILED`,message:i??`Server did not become ready.`});return OC(n,r)},present:DC},e)}const jC=e=>e.startsWith(`local-`);function MC(e,t){return e&&t&&e===t?`keep`:jC(e)&&t&&!jC(t)?`protected`:`replace`}const NC=`https://ryugi.innei.dev`,PC=1e4,FC=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},IC=FC(`RYUGI_START_SETTLE_MS`,6e3),LC=FC(`RYUGI_STOP_GRACE_MS`,7e3),RC=FC(`RYUGI_START_ALIVE_MS`,1e3),zC=e=>(e.RYUGI_CLOUD_ORIGIN||NC).replace(/\/+$/,``),BC=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},VC=(e,t)=>{let n=BC(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function HC(e,t,n){let r={type:`server-started`,url:e.url,port:e.port,root:t.root};if(n){let i=new URL(e.url),a=be(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${Se(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function UC(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(VC(t,`/api/cloud/reserve/${r}`),{method:`POST`,headers:{"X-Ryugi-Project":encodeURIComponent(n.project)},signal:AbortSignal.timeout(5e3)})).json();return typeof i==`string`?{...e,cloudLink:i}:typeof a?.upgradeUrl==`string`?{...e,cloudLimit:{message:a.message,upgradeUrl:a.upgradeUrl}}:e}catch{return e}}async function WC(e){for(let t=0;t<150;t++){try{return u.default.mkdirSync(e),!0}catch{}try{if(Date.now()-u.default.statSync(e).mtimeMs>6e4){u.default.rmdirSync(e);continue}}catch{}await qe(100)}return!1}function GC(e){let t=Number(et(e.pid)),n=et(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:Qe(t,n)?t:null}function KC(e){try{let t=JSON.parse(et(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function qC(e){try{return(await fetch(VC(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function JC(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await $e(e,LC)){try{process.kill(e,`SIGKILL`)}catch{}if(!await $e(e,2e3))throw new F(`The ${t} (pid ${e}) did not stop; stop it with \`${We()} stop\` and retry`)}}async function YC(){let e=Pe();for(let t of Re(e)){if(Qe(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await $e(t.pid,5e3)}try{ze(e,t)}catch{}}}function XC(e,t){if(!t)return;let n=Object.fromEntries(re.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]));if(!Object.keys(n).length)return;let r=d.default.join(e.state,t);u.default.mkdirSync(r,{recursive:!0}),u.default.writeFileSync(d.default.join(r,`agent`),`${JSON.stringify(n)}\n`)}function ZC(e){let t={...process.env,ARTIFACTS_HOST:e.host,ARTIFACTS_URL_HOST:e.urlHost};process.env.RYUGI_ARTIFACTS_COMMAND&&(t.RYUGI_ARTIFACTS_LAUNCHER=process.env.RYUGI_ARTIFACTS_COMMAND);for(let e of[`RYUGI_ARTIFACTS_OWNER`,`RYUGI_ARTIFACTS_VERSION`,`RYUGI_ARTIFACTS_COMMAND`,`ARTIFACTS_OPEN_CMD`,`ARTIFACTS_ROOT`])delete t[e];return t}const QC=e=>e.split(`
941
+ `)}\n`}function CC(e,t,n=1){return SC({heading:gC(e.command),status:``,facts:[],sections:[]},e,{...t,fields:void 0},void 0,[],n)}function Z(e,t){return{run:(n,r,i,a)=>wC(e,t,n,r,i,a)}}async function wC(e,t,n,r,i,a){let o=0,s=Promise.resolve(),c,l=!1,u=[],d=new AbortController,f=()=>d.abort(i?.reason);i?.addEventListener(`abort`,f,{once:!0}),i?.aborted&&f();let p={signal:d.signal,effects:new rC,payloads:{},progress(e){l||h(n.format===`jsonl`?`stdout`:`stderr`,n.format===`jsonl`?m(`progress`,e):`${e.phase}${e.current===void 0?``:` ${e.current}${e.total===void 0?``:`/${e.total}`}`}\n`)},diagnostic(e){h(`stderr`,`${e.trimEnd()}\n`)}};function m(e,t){return`${JSON.stringify({schema:`ryugi.cli/v1`,...t,seq:o++,kind:e})}\n`}function h(e,t){s=s.then(()=>r.write(e,t)).catch(e=>{c=e,d.abort(e)})}async function g(){if(await s,c)throw c}let _=8388608;async function v(e,t){if((typeof t==`string`?new TextEncoder().encode(t).byteLength:t.byteLength)>_)throw new K({code:`E_RESULT_TOO_LARGE`,message:`Result exceeds 8 MiB; read one object or save it to a file.`});await g(),await r.write(e,t)}async function y(t,r=`result`){let i={...t,effects:t.effects.length?t.effects:p.effects.snapshot()};i.effects.some(e=>e.state===`unknown`)&&(i.actions=[...i.actions,...a?.(e.id,void 0,i.effects)??[]]),u=i.effects;let o=PS(e.id,i,n,e.output);if(n.format===`json`)await v(`stdout`,`${JSON.stringify(o)}\n`);else if(n.format===`jsonl`){let t=o,n=e.output.collection;if(n&&r===`result`){let e=o.data,r=e[n];if(Array.isArray(r)){for(let e of r)await v(`stdout`,m(`item`,{collection:n,data:e}));let i={...e};delete i[n],t={...o,data:i}}}await v(`stdout`,m(r,t))}else if(n.format===`raw`||n.format===`source`){let e=p.payloads[n.format];if(e===void 0)throw new K({code:`E_PAYLOAD_UNAVAILABLE`,message:`No ${n.format} payload was returned.`});await v(`stdout`,e)}else if(n.format===`quiet`){if(!e.output.scalar)throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`This command has no scalar output.`});await v(`stdout`,`${e.output.scalar(i.data)}\n`)}else await v(i.completion.kind===`failed`?`stderr`:`stdout`,SC(e.present(i),o,n,e.output.collection,e.output.requiredFields,MS(i.completion).code));return MS(i.completion).code}try{if(!e.output.formats.includes(n.format)||e.mode===`live`&&[`json`,`quiet`,`raw`,`source`,`table`].includes(n.format))throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`${n.format} is not supported for ${e.id}. Supported: ${e.output.formats.join(`, `)}`});if(n.detail&&!e.output.detail)throw new K({code:`E_OPTION_UNSUPPORTED`,message:`--detail is not supported for this operation.`});let r=n.fields?.find(t=>!e.output.fields?.includes(t));if(r)throw new K({code:`E_FIELD_UNKNOWN`,message:`Unknown output field: ${r}`});if(n.format===`jsonl`&&await v(`stdout`,m(`meta`,{command:e.id})),e.mode===`finite`){let n=await e.run(t,p);return l=!0,await y(n)}let i=!1,a;for await(let n of e.run(t,p)){if(a||n.kind===`ready`&&i)throw new K({code:`E_LIFECYCLE_INVALID`,message:`Invalid command lifecycle.`});if(n.kind===`ready`){i=!0;try{await y(n.result,`ready`)}catch(e){throw d.abort(e),e}}else a=n.result,l=!0}if(!a)throw new K({code:`E_LIFECYCLE_INCOMPLETE`,message:`Command ended without a terminal result.`});return await y(a)}catch(t){if(l=!0,t instanceof K&&t.raw!==void 0&&(p.payloads.raw=t.raw),t?.code===`EPIPE`)return 141;let i=d.signal.aborted&&(d.signal.reason===`SIGINT`||d.signal.reason===`SIGTERM`)?d.signal.reason:void 0,o=i?{code:`E_INTERRUPTED`,message:`Command interrupted by ${i}.`,details:{signal:i}}:jS(t),s=t instanceof K?t.kind===`action_required`:t?.code===2,c=p.effects.snapshot(),f=J(null,i?{kind:`interrupted`,signal:i}:s?{kind:`action_required`,reason:o.message}:{kind:`failed`,error:o},{effects:c.length?c:u,actions:[...a?.(e.id,o,c.length?c:u)??[],...t?.actions??[]]}),h={...PS(e.id,f,{...n,fields:void 0},{}),error:o};try{await g(),n.format===`json`||n.format===`jsonl`?await r.write(`stdout`,n.format===`json`?`${JSON.stringify(h)}\n`:m(`result`,h)):n.format===`raw`&&p.payloads.raw!==void 0&&o.code!==`E_RESULT_TOO_LARGE`&&Buffer.byteLength(p.payloads.raw)<=_?await r.write(`stdout`,p.payloads.raw):await r.write(`stderr`,CC(h,n,MS(f.completion).code)),n.verbose&&t instanceof Error&&t.stack&&await r.write(`stderr`,`${t.stack}\n`)}catch(e){if(e?.code===`EPIPE`)return 141}return MS(f.completion).code}finally{i?.removeEventListener(`abort`,f)}}function TC(e){let t=e.values;if(t.foreground&&t.background)throw new K({code:`E_OPTION_CONFLICT`,message:`Choose --foreground or --background.`});if(t.open&&t[`no-open`])throw new K({code:`E_OPTION_CONFLICT`,message:`Choose --open or --no-open.`});return{projectDir:e.projectDir,artifact:t.artifact,background:!!t.background,foreground:!!t.foreground,host:t.host??`127.0.0.1`,urlHost:t[`url-host`],port:t.port,open:t[`no-open`]?!1:t.open?!0:process.env.ARTIFACTS_OPEN!==`0`,openExisting:!!t.open,mockup:!!t.mockup}}function EC(e,t){let n=t?d.default.dirname(d.default.dirname(t.root)):e.projectDir,r=e.artifact?lS(n,e.artifact):void 0;return{cliVersion:`1.108.7`,serverVersion:et(ke().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:sS(e.artifact,{mockup:e.mockup})}:{},reused:!!t?.reused,...t?{url:t.cloudLink??t.link??t.url,localUrl:t.link??t.url}:{},...e.artifact?{artifact:e.artifact}:{},cloud:t?.cloudLink?`live_link_reserved`:`local_only`}}function DC({data:e}){return{heading:`Server`,status:e.status,subject:e.reused?`reused`:void 0,facts:[X(`Scope`,Y(e,`scope`)),X(`CLI version`,Y(e,`cliVersion`)),X(`Server version`,Y(e,`serverVersion`)),X(`Project`,Y(e,`project`),!0),...e.artifact?[X(`Artifact`,Y(e,`artifact`),!0)]:[],...e.write?[X(`Write`,Y(e,`write`),!0),X(`Content`,Y(e,`content`),!0)]:[],...e.url?[X(`Open`,Y(e,`url`),!0)]:[],...e.localUrl&&e.localUrl!==e.url?[X(`Local`,Y(e,`localUrl`),!0)]:[],X(`Cloud`,Y(e,`cloud`))],sections:e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[]}}function OC(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&ge(n)?Qx[n].onStart:void 0;r&&r(d.default.join(d.default.dirname(d.default.dirname(t.root)),`.ryugi`,`artifacts`,e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[];return e.artifact&&i.push(q([`check`,`--project-dir`,d.default.dirname(d.default.dirname(t.root)),`--artifact`,e.artifact],`Check`)),t.loginHint&&i.push(q([`publish`,`--login`,`--from`,`hint`,`--project-dir`,e.projectDir],`Sign in`)),J(EC(e,t),void 0,{actions:i,warnings:[...t.loginHint?[{code:`W_LOGIN_OPTIONAL`,message:t.loginHint.message}]:[],...t.cloudLimit?[{code:`W_CLOUD_LIMIT`,message:String(t.cloudLimit.message??`Cloud link unavailable; local server is ready.`)}]:[]]})}async function*kC(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=tw(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:OC(e,n)})},failure(e){s=String(e.error??`Server failed`)},log:e=>t.diagnostic(e)}).then(n=>{if(t.signal.aborted){let n=t.signal.reason===`SIGINT`?`SIGINT`:`SIGTERM`;l({kind:`result`,result:J({...EC(e,o),status:`stopped`},{kind:`interrupted`,signal:n},{effects:t.effects.snapshot()})})}else if(n!==0||s)throw new K({code:`E_SERVER_FAILED`,message:s??`Server exited with ${n}.`});else l({kind:`result`,result:J({...EC(e,o),status:o?.reused?`running`:`stopped`},void 0,{effects:t.effects.snapshot()})})}).catch(e=>{a=e}).finally(()=>{i=!0,r?.()});try{for(;!i||n.length;)n.length?yield n.shift():await new Promise(e=>{r=e});if(a)throw a}finally{await u}}function AC(e,t=`start`){let n=TC(e);return n.library=t===`browse`,n.foreground?Z({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>kC(n,t),present:DC},e):Z({id:t,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.url},async run(e,t){let r,i,a=t.effects.begin(`start`,n.projectDir);if(await tw(n,{signal:t.signal,ready(e){r=e,t.effects.confirm(a,{reused:!!e.reused})},failure(e){i=String(e.error??`Server failed`)},log:e=>t.diagnostic(e)})!==0||!r)throw new K({code:`E_SERVER_FAILED`,message:i??`Server did not become ready.`});return OC(n,r)},present:DC},e)}const jC=e=>e.startsWith(`local-`);function MC(e,t){return e&&t&&e===t?`keep`:jC(e)&&t&&!jC(t)?`protected`:`replace`}const NC=`https://ryugi.innei.dev`,PC=1e4,FC=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},IC=FC(`RYUGI_START_SETTLE_MS`,6e3),LC=FC(`RYUGI_STOP_GRACE_MS`,7e3),RC=FC(`RYUGI_START_ALIVE_MS`,1e3),zC=e=>(e.RYUGI_CLOUD_ORIGIN||NC).replace(/\/+$/,``),BC=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},VC=(e,t)=>{let n=BC(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function HC(e,t,n){let r={type:`server-started`,url:e.url,port:e.port,root:t.root};if(n){let i=new URL(e.url),a=be(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${Se(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function UC(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(VC(t,`/api/cloud/reserve/${r}`),{method:`POST`,headers:{"X-Ryugi-Project":encodeURIComponent(n.project)},signal:AbortSignal.timeout(5e3)})).json();return typeof i==`string`?{...e,cloudLink:i}:typeof a?.upgradeUrl==`string`?{...e,cloudLimit:{message:a.message,upgradeUrl:a.upgradeUrl}}:e}catch{return e}}async function WC(e){for(let t=0;t<150;t++){try{return u.default.mkdirSync(e),!0}catch{}try{if(Date.now()-u.default.statSync(e).mtimeMs>6e4){u.default.rmdirSync(e);continue}}catch{}await qe(100)}return!1}function GC(e){let t=Number(et(e.pid)),n=et(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:Qe(t,n)?t:null}function KC(e){try{let t=JSON.parse(et(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function qC(e){try{return(await fetch(VC(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function JC(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await $e(e,LC)){try{process.kill(e,`SIGKILL`)}catch{}if(!await $e(e,2e3))throw new F(`The ${t} (pid ${e}) did not stop; stop it with \`${We()} stop\` and retry`)}}async function YC(){let e=Pe();for(let t of Re(e)){if(Qe(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await $e(t.pid,5e3)}try{ze(e,t)}catch{}}}function XC(e,t){if(!t)return;let n=Object.fromEntries(re.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]));if(!Object.keys(n).length)return;let r=d.default.join(e.state,t);u.default.mkdirSync(r,{recursive:!0}),u.default.writeFileSync(d.default.join(r,`agent`),`${JSON.stringify(n)}\n`)}function ZC(e){let t={...process.env,ARTIFACTS_HOST:e.host,ARTIFACTS_URL_HOST:e.urlHost};process.env.RYUGI_ARTIFACTS_COMMAND&&(t.RYUGI_ARTIFACTS_LAUNCHER=process.env.RYUGI_ARTIFACTS_COMMAND);for(let e of[`RYUGI_ARTIFACTS_OWNER`,`RYUGI_ARTIFACTS_VERSION`,`RYUGI_ARTIFACTS_COMMAND`,`ARTIFACTS_OPEN_CMD`,`ARTIFACTS_ROOT`])delete t[e];return t}const QC=e=>e.split(`
942
942
  `).find(e=>e.includes(`"server-started"`)),$C=e=>e.split(`
943
943
  `).find(e=>e.includes(`"server-error"`));async function ew(e,t,n){let r=await fetch(VC(e,`/api/hub/projects`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({dir:t.project,...n?{open:n}:{},...n&&process.env.ARTIFACTS_OPEN_CMD?{openCmd:process.env.ARTIFACTS_OPEN_CMD}:{}}),signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new F(`The artifacts server refused this project: ${await r.text()}`)}async function tw(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!Ge.test(e.artifact))throw new F(Ke);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new F(`--port must be a port number`);e.urlHost||=e.host===`127.0.0.1`||e.host===`localhost`?`localhost`:e.host,process.umask(63);let n=Ue(e.projectDir),r=ke();Ae(r.home),u.default.mkdirSync(n.state,{recursive:!0}),u.default.existsSync(d.default.join(n.state,`.gitignore`))||u.default.writeFileSync(d.default.join(n.state,`.gitignore`),`*
944
- `);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.108.6`,a=Me(r.projects).some(e=>e.dir===n.project),o=async(r,i)=>{XC(n,e.artifact);let o=e.open&&!e.library&&(!i||!a);await ew(r,n,o?e.artifact??!0:void 0);let s=HC(r,n,e.artifact);i&&(s.reused=!0);let c=await UC(s,r,n,e.artifact),l=Ut(n.project);if(t.signal?.throwIfAborted(),e.library&&e.open&&(process.env.ARTIFACTS_OPEN_CMD?await new Promise(e=>(0,f.execFile)(process.env.ARTIFACTS_OPEN_CMD,[r.url],()=>e())):await Oe(r.url,[r.url]).catch(e=>t.log(e.message,`stderr`))),await t.ready(l?{...c,loginHint:l}:c),i&&a&&process.platform===`darwin`&&e.open&&e.openExisting&&e.artifact&&!process.env.ARTIFACTS_OPEN_CMD){let e=c.link;await Oe(typeof c.cloudLink==`string`?c.cloudLink:e,[e]).catch(e=>t.log(e.message,`stderr`))}};if(!await WC(r.lock))throw new F(`Another start is still starting the artifacts server; retry in a moment`);let s=!0,c=()=>{if(s){s=!1;try{u.default.rmdirSync(r.lock)}catch{}}};try{t.signal?.throwIfAborted();let a=GC(r),s=KC(r);if(a&&!s){for(let e=0;e<IC&&Je(a)&&!s;e+=100)await qe(100),s=KC(r);!s&&Je(a)&&(Ve(r,{action:`replaced`,pid:a,running:et(r.version)??``,cli:i,reasons:[`no-info`]}),await JC(a,`stopping artifacts server`))}if(a&&s){let t=et(r.version)??``,n=MC(t,i),l=[...n===`keep`?[]:[`version`],...(s.host??`127.0.0.1`)===e.host?[]:[`host`],...(s.urlHost??`localhost`)===e.urlHost?[]:[`urlHost`],...(s.cloudOrigin??NC)===zC(process.env)?[]:[`cloudOrigin`],...e.port!==void 0&&String(s.port)!==e.port?[`port`]:[]],u={pid:a,running:t,cli:i},d=n===`protected`||l.length===0;if(d&&await qC(s))return l.length&&Ve(r,{...u,action:`kept`,reasons:l}),c(),await o(s,!0),0;Ve(r,{...u,action:`replaced`,reasons:d?[...l,`unanswered`]:l}),await JC(a,`running artifacts server`)}await YC(),u.default.rmSync(r.info,{force:!0});let l=p.default.randomBytes(24).toString(`hex`);u.default.writeFileSync(r.serverId,`${l}\n`),u.default.writeFileSync(r.version,`${i}\n`);let h=[d.default.join(__dirname,`server.cjs`),`--artifacts-server-id=${l}`,...e.port?[`--port=${e.port}`]:[]],g=ZC(e);if(e.foreground){let e=(0,f.spawn)(process.execPath,h,{env:g,stdio:[`ignore`,`pipe`,`pipe`]});u.default.writeFileSync(r.pid,`${e.pid}\n`);let n=()=>{e.kill(`SIGTERM`)};if(t.signal)t.signal.addEventListener(`abort`,n,{once:!0});else for(let e of[`SIGINT`,`SIGTERM`])process.on(e,n);m.default.createInterface({input:e.stderr}).on(`line`,e=>t.log(e,`stderr`));let i=new Promise(t=>e.on(`close`,e=>t(e??1))),a=!1,s;m.default.createInterface({input:e.stdout}).on(`line`,e=>{let r;try{r=JSON.parse(e)}catch{t.log(e,`stdout`);return}r.type!==`server-started`||a?t.event?t.event(r):r.type===`server-error`||r.type===`error`?t.failure(r):t.log(JSON.stringify(r),`stderr`):(a=!0,c(),s=o(r,!1),s.catch(()=>n()))});try{let e=await i;return await s,e}finally{if(t.signal)t.signal.removeEventListener(`abort`,n);else for(let e of[`SIGINT`,`SIGTERM`])process.removeListener(e,n)}}try{u.default.renameSync(r.log,`${r.log}.1`)}catch{}let _=u.default.openSync(r.log,`w`),v=(0,f.spawn)(process.execPath,h,{env:g,detached:!0,windowsHide:!0,stdio:[`ignore`,_,_]});u.default.closeSync(_),v.unref(),u.default.writeFileSync(r.pid,`${v.pid}\n`);for(let i=0;i<PC;i+=100){let i=et(r.log)??``,a=QC(i);if(a){for(let t=0;t<RC;t+=100){if(!Je(v.pid))throw new F(`Server started but was killed. Retry in a persistent terminal with: ${We()} start --project-dir ${n.project}${e.artifact?` --artifact ${e.artifact}`:``} --host ${e.host} --url-host ${e.urlHost} --foreground`);await qe(100)}return c(),await o(JSON.parse(a),!1),0}let s=$C(i);if(s)return t.failure(JSON.parse(s)),1;await qe(100)}throw new F(`Server failed to start within ${PC/1e3} seconds`)}finally{c()}}const nw={semantic:AC,name:`start`,summary:`Start this machine's artifacts server if needed and register the project with it`,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Also print a link that opens this artifact`},host:{type:`string`,value:`<host>`,help:`Interface to listen on (default: 127.0.0.1)`},"url-host":{type:`string`,value:`<host>`,help:`Host in printed URLs (default: localhost for a loopback --host)`},port:{type:`string`,value:`<n>`,help:`Port to listen on (default: the first free of 27319-27321)`},open:{type:`boolean`,help:`Open or focus the artifact, including when reusing a server`},"no-open":{type:`boolean`,help:`Do not open a browser`},foreground:{type:`boolean`,help:`Run the server in this process until Ctrl+C`},background:{type:`boolean`,help:`Run until ready and detach (the default; incompatible with --foreground)`},mockup:{type:`boolean`,help:`Include the phone mockup guide in the writing description; with --help, print only the guide`}}},rw=e=>`No artifacts server is running for this project. Start it with \`${We()} start --project-dir ${e}\`, then run this again.`,iw=e=>{try{let{url:t}=JSON.parse(et(e)??``);return typeof t==`string`?t:null}catch{return null}};function aw(e,t){let n=ke(),r=iw(n.info);return r?Me(n.projects).some(t=>t.dir===e)?r:null:iw(t)}function ow(e){let t=Ue(e),n=aw(t.project,t.info);if(!n)throw new K({code:`E_SERVER_NOT_RUNNING`,message:rw(t.project)});let r=new URL(n),i=r.searchParams.get(`key`)??``;return r.hostname===`localhost`&&(r.hostname=`127.0.0.1`),{project:t.project,async call(e,n,a,o){let s;try{let c=new URL(`${r.origin}${n}`);c.searchParams.set(`key`,i);let l=zt(process.env);s=await fetch(c,{method:e,signal:o,headers:{"X-Ryugi-Client":`cli`,"X-Ryugi-Project":encodeURIComponent(t.project),...l?{"x-ryugi-cloud-token":l}:{},...a?{"Content-Type":`application/json`}:{}},body:a?JSON.stringify(a):void 0})}catch{throw new K({code:`E_SERVER_UNREACHABLE`,message:rw(t.project)})}let c=new Uint8Array(await s.arrayBuffer()),l;try{l=JSON.parse(new TextDecoder().decode(c))}catch{}if(!l||typeof l!=`object`||Array.isArray(l))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid JSON response; the operation result is unknown.`,httpStatus:s.status},`failed`,c);return{status:s.status,json:l,raw:c}}}}async function sw(){let e=ke(),t=iw(e.info),n={scope:`machine`,version:et(e.version)};if(!t)return{...n,status:`not_running`};try{let e=new URL(`/api/status`,t);e.search=new URL(t).search;let r=await fetch(e,{signal:AbortSignal.timeout(1e3)}),i=await r.json();return{...n,status:r.ok&&typeof i.pid==`number`?`running`:`unreachable`,pid:typeof i.pid==`number`?i.pid:void 0}}catch{return{...n,status:`unreachable`}}}const cw=`preview.json`,lw=/^[a-z0-9][a-z0-9-]{0,63}$/;function uw(e){return d.default.join(d.default.dirname(e),`preview`)}function dw(e,t){return lw.test(t)?d.default.join(uw(e),t):null}function fw(e){let t=uw(e),n;try{n=u.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!lw.test(e))continue;let n=d.default.join(t,e);u.default.existsSync(d.default.join(n,`preview.json`))&&r.push({id:e,payload:pw(n,e)})}return r}function pw(e,t,n){let r=d.default.join(e,cw),i,a=1;try{let e=u.default.statSync(r);a=Math.trunc(e.mtimeMs)||1,i=u.default.readFileSync(r,`utf8`)}catch{return{title:t,version:a,config:null,issues:[`preview.json is missing`],warnings:[`preview.json is missing`],proxyUrl:n??null}}let{config:o,issues:s}=te(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function mw(e,t){u.default.mkdirSync(e,{recursive:!0}),Rt(d.default.join(e,cw),t)}function hw(e,t,n){return new Promise(r=>{let i=_.default.connect({host:e,port:t}),a=!1,o=e=>{a||(a=!0,i.destroy(),r(e))};i.setTimeout(n,()=>o(!1)),i.once(`connect`,()=>o(!0)),i.once(`error`,()=>o(!1))})}async function gw(e,t=800){let n=ee(e);if(!n)return!1;if(n.hostname!==`localhost`)return hw(n.hostname,n.port,t);let r=await Promise.all([hw(`127.0.0.1`,n.port,t),hw(`::1`,n.port,t)]);return r[0]||r[1]}function _w(e){let t=typeof e==`string`&&e.trim()?e.trim():`dev`;if(!lw.test(t))throw new F(`Preview --id must use lowercase letters, digits, and hyphens.`);return t}function vw(e){let t=e.anchor??{},n=typeof t.route==`string`?t.route:`/`,r=t.kind===`box`?`box`:`element`,i=t.pageRect??t.rect,a=t.source,o=a?.file?`${a.file}${a.line?`:${a.line}`:``}`:a?.component?`<${a.component}>`:``,s=r===`box`&&i?`box (${i.x},${i.y} ${i.w}x${i.h})`:[typeof t.selector==`string`?t.selector:``,typeof t.text==`string`?`"${t.text.slice(0,48)}"`:``].filter(Boolean).join(` `),c=t.viewport,l=typeof t.cropPath==`string`?t.cropPath:``,u=[[`${String(e.id??``)} [${String(e.status??`open`)}]`,n,s,o,c?`${c.w}x${c.h}`:``,l?`crop ${l}`:``].filter(Boolean).join(` · `)],d=Array.isArray(e.messages)?e.messages:[];for(let e of d){if(e.deleted)continue;let t=e.author===`agent`?String(e.name||`agent`):`human`;u.push(` ${String(e.id??``)} ${t}: ${String(e.text??``)}`)}return Array.isArray(t.errors)&&t.errors.length>0&&u.push(` errors: ${t.errors.join(` | `)}`),u}function yw({data:e}){return{heading:`Preview ${e.action}`,status:e.action===`open`?`ready`:`ok`,subject:e.id?`preview/${e.id}`:void 0,facts:[...e.url?[X(`Target`,{key:`url`,value:e.url})]:[],...e.upstreamAlive===void 0?[]:[X(`Upstream`,{key:`upstreamAlive`,value:e.upstreamAlive?`online`:`offline`})],...e.open?[X(`Open`,{key:`open`,value:e.open},!0)]:[],...e.receipt?[X(`Receipt`,{key:`receipt`,value:e.receipt})]:[]],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
944
+ `);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.108.7`,a=Me(r.projects).some(e=>e.dir===n.project),o=async(r,i)=>{XC(n,e.artifact);let o=e.open&&!e.library&&(!i||!a);await ew(r,n,o?e.artifact??!0:void 0);let s=HC(r,n,e.artifact);i&&(s.reused=!0);let c=await UC(s,r,n,e.artifact),l=Ut(n.project);if(t.signal?.throwIfAborted(),e.library&&e.open&&(process.env.ARTIFACTS_OPEN_CMD?await new Promise(e=>(0,f.execFile)(process.env.ARTIFACTS_OPEN_CMD,[r.url],()=>e())):await Oe(r.url,[r.url]).catch(e=>t.log(e.message,`stderr`))),await t.ready(l?{...c,loginHint:l}:c),i&&a&&process.platform===`darwin`&&e.open&&e.openExisting&&e.artifact&&!process.env.ARTIFACTS_OPEN_CMD){let e=c.link;await Oe(typeof c.cloudLink==`string`?c.cloudLink:e,[e]).catch(e=>t.log(e.message,`stderr`))}};if(!await WC(r.lock))throw new F(`Another start is still starting the artifacts server; retry in a moment`);let s=!0,c=()=>{if(s){s=!1;try{u.default.rmdirSync(r.lock)}catch{}}};try{t.signal?.throwIfAborted();let a=GC(r),s=KC(r);if(a&&!s){for(let e=0;e<IC&&Je(a)&&!s;e+=100)await qe(100),s=KC(r);!s&&Je(a)&&(Ve(r,{action:`replaced`,pid:a,running:et(r.version)??``,cli:i,reasons:[`no-info`]}),await JC(a,`stopping artifacts server`))}if(a&&s){let t=et(r.version)??``,n=MC(t,i),l=[...n===`keep`?[]:[`version`],...(s.host??`127.0.0.1`)===e.host?[]:[`host`],...(s.urlHost??`localhost`)===e.urlHost?[]:[`urlHost`],...(s.cloudOrigin??NC)===zC(process.env)?[]:[`cloudOrigin`],...e.port!==void 0&&String(s.port)!==e.port?[`port`]:[]],u={pid:a,running:t,cli:i},d=n===`protected`||l.length===0;if(d&&await qC(s))return l.length&&Ve(r,{...u,action:`kept`,reasons:l}),c(),await o(s,!0),0;Ve(r,{...u,action:`replaced`,reasons:d?[...l,`unanswered`]:l}),await JC(a,`running artifacts server`)}await YC(),u.default.rmSync(r.info,{force:!0});let l=p.default.randomBytes(24).toString(`hex`);u.default.writeFileSync(r.serverId,`${l}\n`),u.default.writeFileSync(r.version,`${i}\n`);let h=[d.default.join(__dirname,`server.cjs`),`--artifacts-server-id=${l}`,...e.port?[`--port=${e.port}`]:[]],g=ZC(e);if(e.foreground){let e=(0,f.spawn)(process.execPath,h,{env:g,stdio:[`ignore`,`pipe`,`pipe`]});u.default.writeFileSync(r.pid,`${e.pid}\n`);let n=()=>{e.kill(`SIGTERM`)};if(t.signal)t.signal.addEventListener(`abort`,n,{once:!0});else for(let e of[`SIGINT`,`SIGTERM`])process.on(e,n);m.default.createInterface({input:e.stderr}).on(`line`,e=>t.log(e,`stderr`));let i=new Promise(t=>e.on(`close`,e=>t(e??1))),a=!1,s;m.default.createInterface({input:e.stdout}).on(`line`,e=>{let r;try{r=JSON.parse(e)}catch{t.log(e,`stdout`);return}r.type!==`server-started`||a?t.event?t.event(r):r.type===`server-error`||r.type===`error`?t.failure(r):t.log(JSON.stringify(r),`stderr`):(a=!0,c(),s=o(r,!1),s.catch(()=>n()))});try{let e=await i;return await s,e}finally{if(t.signal)t.signal.removeEventListener(`abort`,n);else for(let e of[`SIGINT`,`SIGTERM`])process.removeListener(e,n)}}try{u.default.renameSync(r.log,`${r.log}.1`)}catch{}let _=u.default.openSync(r.log,`w`),v=(0,f.spawn)(process.execPath,h,{env:g,detached:!0,windowsHide:!0,stdio:[`ignore`,_,_]});u.default.closeSync(_),v.unref(),u.default.writeFileSync(r.pid,`${v.pid}\n`);for(let i=0;i<PC;i+=100){let i=et(r.log)??``,a=QC(i);if(a){for(let t=0;t<RC;t+=100){if(!Je(v.pid))throw new F(`Server started but was killed. Retry in a persistent terminal with: ${We()} start --project-dir ${n.project}${e.artifact?` --artifact ${e.artifact}`:``} --host ${e.host} --url-host ${e.urlHost} --foreground`);await qe(100)}return c(),await o(JSON.parse(a),!1),0}let s=$C(i);if(s)return t.failure(JSON.parse(s)),1;await qe(100)}throw new F(`Server failed to start within ${PC/1e3} seconds`)}finally{c()}}const nw={semantic:AC,name:`start`,summary:`Start this machine's artifacts server if needed and register the project with it`,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Also print a link that opens this artifact`},host:{type:`string`,value:`<host>`,help:`Interface to listen on (default: 127.0.0.1)`},"url-host":{type:`string`,value:`<host>`,help:`Host in printed URLs (default: localhost for a loopback --host)`},port:{type:`string`,value:`<n>`,help:`Port to listen on (default: the first free of 27319-27321)`},open:{type:`boolean`,help:`Open or focus the artifact, including when reusing a server`},"no-open":{type:`boolean`,help:`Do not open a browser`},foreground:{type:`boolean`,help:`Run the server in this process until Ctrl+C`},background:{type:`boolean`,help:`Run until ready and detach (the default; incompatible with --foreground)`},mockup:{type:`boolean`,help:`Include the phone mockup guide in the writing description; with --help, print only the guide`}}},rw=e=>`No artifacts server is running for this project. Start it with \`${We()} start --project-dir ${e}\`, then run this again.`,iw=e=>{try{let{url:t}=JSON.parse(et(e)??``);return typeof t==`string`?t:null}catch{return null}};function aw(e,t){let n=ke(),r=iw(n.info);return r?Me(n.projects).some(t=>t.dir===e)?r:null:iw(t)}function ow(e){let t=Ue(e),n=aw(t.project,t.info);if(!n)throw new K({code:`E_SERVER_NOT_RUNNING`,message:rw(t.project)});let r=new URL(n),i=r.searchParams.get(`key`)??``;return r.hostname===`localhost`&&(r.hostname=`127.0.0.1`),{project:t.project,async call(e,n,a,o){let s;try{let c=new URL(`${r.origin}${n}`);c.searchParams.set(`key`,i);let l=zt(process.env);s=await fetch(c,{method:e,signal:o,headers:{"X-Ryugi-Client":`cli`,"X-Ryugi-Project":encodeURIComponent(t.project),...l?{"x-ryugi-cloud-token":l}:{},...a?{"Content-Type":`application/json`}:{}},body:a?JSON.stringify(a):void 0})}catch{throw new K({code:`E_SERVER_UNREACHABLE`,message:rw(t.project)})}let c=new Uint8Array(await s.arrayBuffer()),l;try{l=JSON.parse(new TextDecoder().decode(c))}catch{}if(!l||typeof l!=`object`||Array.isArray(l))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid JSON response; the operation result is unknown.`,httpStatus:s.status},`failed`,c);return{status:s.status,json:l,raw:c}}}}async function sw(){let e=ke(),t=iw(e.info),n={scope:`machine`,version:et(e.version)};if(!t)return{...n,status:`not_running`};try{let e=new URL(`/api/status`,t);e.search=new URL(t).search;let r=await fetch(e,{signal:AbortSignal.timeout(1e3)}),i=await r.json();return{...n,status:r.ok&&typeof i.pid==`number`?`running`:`unreachable`,pid:typeof i.pid==`number`?i.pid:void 0}}catch{return{...n,status:`unreachable`}}}const cw=`preview.json`,lw=/^[a-z0-9][a-z0-9-]{0,63}$/;function uw(e){return d.default.join(d.default.dirname(e),`preview`)}function dw(e,t){return lw.test(t)?d.default.join(uw(e),t):null}function fw(e){let t=uw(e),n;try{n=u.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!lw.test(e))continue;let n=d.default.join(t,e);u.default.existsSync(d.default.join(n,`preview.json`))&&r.push({id:e,payload:pw(n,e)})}return r}function pw(e,t,n){let r=d.default.join(e,cw),i,a=1;try{let e=u.default.statSync(r);a=Math.trunc(e.mtimeMs)||1,i=u.default.readFileSync(r,`utf8`)}catch{return{title:t,version:a,config:null,issues:[`preview.json is missing`],warnings:[`preview.json is missing`],proxyUrl:n??null}}let{config:o,issues:s}=te(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function mw(e,t){u.default.mkdirSync(e,{recursive:!0}),Rt(d.default.join(e,cw),t)}function hw(e,t,n){return new Promise(r=>{let i=_.default.connect({host:e,port:t}),a=!1,o=e=>{a||(a=!0,i.destroy(),r(e))};i.setTimeout(n,()=>o(!1)),i.once(`connect`,()=>o(!0)),i.once(`error`,()=>o(!1))})}async function gw(e,t=800){let n=ee(e);if(!n)return!1;if(n.hostname!==`localhost`)return hw(n.hostname,n.port,t);let r=await Promise.all([hw(`127.0.0.1`,n.port,t),hw(`::1`,n.port,t)]);return r[0]||r[1]}function _w(e){let t=typeof e==`string`&&e.trim()?e.trim():`dev`;if(!lw.test(t))throw new F(`Preview --id must use lowercase letters, digits, and hyphens.`);return t}function vw(e){let t=e.anchor??{},n=typeof t.route==`string`?t.route:`/`,r=t.kind===`box`?`box`:`element`,i=t.pageRect??t.rect,a=t.source,o=a?.file?`${a.file}${a.line?`:${a.line}`:``}`:a?.component?`<${a.component}>`:``,s=r===`box`&&i?`box (${i.x},${i.y} ${i.w}x${i.h})`:[typeof t.selector==`string`?t.selector:``,typeof t.text==`string`?`"${t.text.slice(0,48)}"`:``].filter(Boolean).join(` `),c=t.viewport,l=typeof t.cropPath==`string`?t.cropPath:``,u=[[`${String(e.id??``)} [${String(e.status??`open`)}]`,n,s,o,c?`${c.w}x${c.h}`:``,l?`crop ${l}`:``].filter(Boolean).join(` · `)],d=Array.isArray(e.messages)?e.messages:[];for(let e of d){if(e.deleted)continue;let t=e.author===`agent`?String(e.name||`agent`):`human`;u.push(` ${String(e.id??``)} ${t}: ${String(e.text??``)}`)}return Array.isArray(t.errors)&&t.errors.length>0&&u.push(` errors: ${t.errors.join(` | `)}`),u}function yw({data:e}){return{heading:`Preview ${e.action}`,status:e.action===`open`?`ready`:`ok`,subject:e.id?`preview/${e.id}`:void 0,facts:[...e.url?[X(`Target`,{key:`url`,value:e.url})]:[],...e.upstreamAlive===void 0?[]:[X(`Upstream`,{key:`upstreamAlive`,value:e.upstreamAlive?`online`:`offline`})],...e.open?[X(`Open`,{key:`open`,value:e.open},!0)]:[],...e.receipt?[X(`Receipt`,{key:`receipt`,value:e.receipt})]:[]],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
945
945
  `)}]:[]}}const bw={name:`preview`,summary:`Manage local dev server previews (open, list, comments, reply, resolve, ack)`,usage:[`open --url <http://localhost:port> [--id dev]`,`list`,`comments [--id dev] [--all] [--agent <name>]`,`reply --thread <id> --text <message> [--id dev] [--agent <name>]`,`resolve --thread <id> [--id dev] [--agent <name>]`,`ack --receipt <id> [--id dev] [--agent <name>]`],positionals:1,options:{id:{type:`string`,value:`<id>`,help:`Preview id (default: dev)`},url:{type:`string`,value:`<http://localhost:port>`,help:`Local loopback dev server URL`},all:{type:`boolean`,help:`Include all threads, not just unread ones`},thread:{type:`string`,value:`<id>`,help:`Comment thread ID for reply/resolve`},text:{type:`string`,value:`<message>`,help:`Reply message text`},receipt:{type:`string`,value:`<id>`,help:`Review receipt ID to acknowledge`},agent:{type:`string`,value:`<name>`,help:`Agent name for comments/replies`}},semantic:e=>Z({id:`preview`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.open??e.lines[0]??`ok`},async run(t,n){let r=e.positionals[0]||`list`,i=Ue(e.projectDir);if(r===`list`){let e=fw(i.root);return J({action:`list`,lines:e.length?e.map(({id:e,payload:t})=>`${e} · ${t.config?.url??`(invalid)`}${t.config?.path??`/`}`):[`No local previews configured yet.`]})}if(r===`open`){let t=_w(e.values.id),r=e.values.url;if(!r)throw new F(`Pass --url http://localhost:<port>`);let a=O(r);if(!a)throw new F(`--url must be a local loopback http URL (e.g. http://localhost:5182)`);let o=dw(i.root,t),s=null;try{s=te(u.default.readFileSync(d.default.join(o,`preview.json`),`utf8`)).config}catch{}mw(o,{version:1,url:a.url,...s?.title?{title:s.title}:{},...a.path&&a.path!==`/`?{path:a.path}:s?.path?{path:s.path}:{},...s?.viewport?{viewport:s.viewport}:{}});let c=``;if(await tw({projectDir:e.projectDir,background:!1,foreground:!1,host:`127.0.0.1`,open:!1},{signal:n.signal,ready(e){c=e.url},failure(e){throw new F(String(e.error??`Failed to start Hub`))},log(e){n.diagnostic(e)}})!==0||!c)throw new F(`Hub did not start.`);let l=`${new URL(c).origin}/preview/${encodeURIComponent(t)}?project=${encodeURIComponent(i.project)}`,f=await gw(a.url);return J({action:`open`,id:t,url:a.url,upstreamAlive:f,open:l,lines:f?[]:[`Upstream ${a.url} is not listening yet; start your dev server and reload.`]})}let a=_w(e.values.id),o=ow(e.projectDir),s=e.values.agent||`Agent`;if(r===`comments`){let t=await o.call(`POST`,`/api/agent/v1/preview/${encodeURIComponent(a)}/review`,{op:`list`,section:`threads`,detail:!0,all:!!e.values.all,agent:s},n.signal);if(t.status<200||t.status>=300)throw new F(t.json?.error||`HTTP ${t.status}`);let r=Array.isArray(t.json?.items)?t.json.items:[];return J({action:`comments`,id:a,lines:r.length?r.flatMap(vw):[`No unread preview comments.`],receipt:typeof t.json?.receipt==`string`?t.json.receipt:void 0})}if(r===`reply`||r===`resolve`){let t=e.values.thread;if(!t)throw new F(`Pass --thread <id> for preview ${r}`);let i=e.values.text;if(r===`reply`&&!i?.trim())throw new F(`Pass --text <message> for preview reply`);let c=await o.call(`POST`,`/api/agent/preview/${encodeURIComponent(a)}/comments`,r===`reply`?{op:`reply`,threadId:t,text:i,agent:s}:{op:`resolve`,threadId:t,agent:s},n.signal);if(c.status<200||c.status>=300)throw new F(c.json?.error||`HTTP ${c.status}`);return J({action:r,id:a,lines:[r===`reply`?`Replied to preview/${a} thread ${t}`:`Resolved preview/${a} thread ${t}`]})}if(r===`ack`){let t=e.values.receipt;if(!t)throw new F(`Pass --receipt <id> for preview ack`);let r=await o.call(`POST`,`/api/agent/v1/preview/${encodeURIComponent(a)}/review`,{op:`ack`,receipt:t,agent:s},n.signal);if(r.status<200||r.status>=300)throw new F(r.json?.error||`HTTP ${r.status}`);return J({action:`ack`,id:a,receipt:t,lines:[`Acknowledged receipt ${t}`]})}throw new F(`Unknown preview action "${r}". Use open, list, comments, reply, resolve, or ack.`)},present:yw},e)},xw=/^report\/[a-z0-9][a-z0-9-]*$/,Sw=e=>typeof e==`object`&&!!e&&Array.isArray(e.sources),Cw=({sources:e})=>e.map(e=>e.ok?`${e.id}: ok in ${(e.durationMs/1e3).toFixed(1)} s${e.shape?` · ${e.shape}`:``}`:`${e.id}: failed · ${e.error??`unknown error`}`),ww={name:`report`,summary:`Run the data sources of a report on this machine (needs a running server)`,usage:[`refresh --artifact report/<id> [--only <source-id>]`],details:`refresh runs each data source script under sources/<id>/ and writes its JSON to data/<id>.json; a failed run keeps the last good data. Prints one line per source with the shape of its data.`,positionals:1,options:{artifact:{type:`string`,value:`report/<id>`,help:`The report`},only:{type:`string`,value:`<source-id>`,help:`Run only this data source`}},semantic:e=>Z({id:`report`,mode:`finite`,output:{detail:!1,formats:[`brief`,`json`,`jsonl`,`raw`],fields:[`artifact`,`sources`,`issues`,`lines`],scalar:e=>e.sources.every(e=>e.ok)?`ok`:`failed`},async run(t,n){if(e.positionals[0]!==`refresh`)throw new F(`usage: ryugi report refresh --artifact report/<id>`);let r=e.values.artifact;if(!r||!xw.test(r))throw new F(`--artifact must be report/<id>`);let i=e.values.only,a=await ow(e.projectDir).call(`POST`,`/api/${r}/refresh`,i?{source:i}:{},n.signal);if(n.payloads.raw=a.raw,a.status<200||a.status>=300)throw new F(a.json?.error||`HTTP ${a.status}`);if(!Sw(a.json))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid refresh report.`});let o={...a.json,artifact:r,lines:Cw(a.json)},s=o.sources.filter(e=>!e.ok);return J(o,s.length?s.length===o.sources.length?{kind:`failed`,error:{code:`E_REPORT_SOURCE_FAILED`,message:Cw({sources:s}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:Tw},e)};function Tw({data:e}){return{heading:`Refresh`,status:e.sources.every(e=>e.ok)?``:`failed`,subject:e.artifact??``,facts:[X(`Sources`,{key:`sources`,value:String(e.sources.length)})],sections:[{kind:`content`,key:`lines`,text:(e.lines??Cw(e)).join(`
946
946
  `)},...e.issues?.length?[{kind:`content`,key:`issues`,text:e.issues.join(`
947
947
  `)}]:[]]}}const Ew=/^storyboard\/[a-z0-9][a-z0-9-]*$/,Dw=e=>typeof e==`object`&&!!e&&Array.isArray(e.lines),Ow=e=>typeof e==`object`&&!!e&&typeof e.n==`number`&&Array.isArray(e.shots),kw=({lines:e})=>e.map(e=>e.ok?`${e.id}: ${Math.round((e.duration??0)*100)/100}s${e.cached?` (unchanged)`:``}`:`${e.id}: failed · ${e.error??`unknown error`}`),Aw=e=>{let t=Math.round(e);return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},jw=e=>[`cut ${e.n}: ${e.file} · ${e.shots.length} shot${e.shots.length===1?``:`s`}, ${Aw(e.shots.at(-1)?.end??0)} · timing from the ${e.mapped===`map`?`map`:`storyboard's durations`}`],Mw=(e,t)=>d.default.resolve(e,t),Nw=e=>e.state===`done`?[`cut ${e.n}: cuts/${e.n}.mp4`]:e.state===`running`?[`cut ${e.n}: ${Math.round(e.progress*100)}% · ${e.stage}`]:[`cut ${e.n} ${e.state}${e.error?`: ${e.error}`:``}`];function Pw(e,t,n){let r=d.default.join(e,`.ryugi`,`artifacts`,...t.split(`/`));if(!u.default.existsSync(r))throw new F(`${t} not found in ${e}`);return Ux(r,n)?[`wrote ${Hx}`]:[`${Hx} is already there; pass --force to replace it with the latest template`]}const Fw=e=>typeof e==`object`&&!!e&&typeof e.state==`string`,Iw=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(r),n()})});function Lw(e,t){if(t!==void 0)try{return JSON.parse(u.default.readFileSync(Mw(e,t),`utf8`))}catch(e){throw new F(`--map ${t} is not readable JSON: ${e.message}`)}}const Rw={name:`storyboard`,summary:`Voice the lines of a storyboard, export or register a cut, or refresh its render script, on this machine`,usage:[`voice --artifact storyboard/<id> [--line <line-id>] [--force]`,`cut --artifact storyboard/<id> --file <1080p.mp4> [--map <map.json>] [--master <4k.mp4>]`,`export --artifact storyboard/<id> [--wait]`,`template --artifact storyboard/<id> [--force]`],details:`voice runs voice/voice.mjs for every line whose words, voice or lexicon changed and prints each line's length, so shot durations can be fitted to the voice; a failed line keeps the audio it had. cut copies the 1080p H.264 file in as the next version under cuts/, with each shot's range from --map ({"shots":[{"id","start","end"}]}) or from the storyboard's durations; --master records where the full-size master lives without copying it. export asks the server to run render/render.mjs on the current timeline and registers what it writes as the next cut; --wait prints its progress until it ends. template copies the latest render script to render/render.mjs; --force replaces one that is already there.`,positionals:1,options:{artifact:{type:`string`,value:`storyboard/<id>`,help:`The storyboard`},line:{type:`string`,value:`<line-id>`,help:`voice: voice only this line`},force:{type:`boolean`,help:`voice: voice again even when the words did not change; template: replace render/render.mjs`},wait:{type:`boolean`,help:`export: wait for the export to end, printing its progress`},file:{type:`string`,value:`<1080p.mp4>`,help:`cut: the finished video to register`},map:{type:`string`,value:`<map.json>`,help:`cut: each shot's start and end in the video`},master:{type:`string`,value:`<4k.mp4>`,help:`cut: where the full-size master is kept`}},semantic:e=>Z({id:`storyboard`,mode:`finite`,output:{detail:!1,formats:[`brief`,`json`,`jsonl`,`raw`],fields:[`artifact`,`action`,`lines`,`cut`,`export`,`error`,`summary`],scalar:e=>e.error||e.lines.some(e=>!e.ok)?`failed`:`ok`},async run(t,n){let r=e.positionals[0];if(r!==`voice`&&r!==`cut`&&r!==`export`&&r!==`template`)throw new F(`usage: ryugi storyboard voice|cut|export|template --artifact storyboard/<id>`);let i=e.values.artifact;if(!i||!Ew.test(i))throw new F(`--artifact must be storyboard/<id>`);if(r===`template`)return J({action:r,artifact:i,lines:[],summary:Pw(e.projectDir,i,!!e.values.force)},{kind:`succeeded`});let a=ow(e.projectDir);if(r===`export`){let t=await a.call(`POST`,`/api/${i}/export`,{},n.signal);if(n.payloads.raw=t.raw,t.status<200||t.status>=300||!Fw(t.json))throw new F(t.json?.error||`HTTP ${t.status}`);let o=t.json,s=[];for(;e.values.wait&&o.state===`running`&&!n.signal?.aborted;){let e=Nw(o)[0];s.at(-1)!==e&&s.push(e),await Iw(1e3,n.signal);let t=await a.call(`GET`,`/api/${i}/export`,void 0,n.signal);Fw(t.json)&&(o=t.json)}return J({action:r,artifact:i,export:o,lines:[],summary:[...s,...Nw(o)],...o.error?{error:o.error}:{}},o.state===`failed`||o.state===`cancelled`?{kind:`failed`,error:{code:`E_STORYBOARD_EXPORT`,message:o.error??o.state}}:{kind:`succeeded`})}if(r===`cut`){let t=e.values.file;if(!t)throw new F(`storyboard cut needs --file <1080p.mp4>`);let o=Lw(e.projectDir,e.values.map),s=e.values.master,c=await a.call(`POST`,`/api/${i}/cut`,{file:Mw(e.projectDir,t),...o===void 0?{}:{map:o},...s?{master:Mw(e.projectDir,s)}:{}},n.signal);if(n.payloads.raw=c.raw,c.status<200||c.status>=300)throw new F(c.json?.error||`HTTP ${c.status}`);if(!Ow(c.json))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid cut.`});let l=c.json;return J({action:r,artifact:i,cut:l,lines:[],summary:jw(l)},{kind:`succeeded`})}let o=e.values.line,s=await a.call(`POST`,`/api/${i}/voice`,{...o?{line:o}:{},force:!!e.values.force},n.signal);if(n.payloads.raw=s.raw,!Dw(s.json))throw s.status<200||s.status>=300?new F(s.json?.error||`HTTP ${s.status}`):new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid voice report.`});let c={action:r,artifact:i,lines:s.json.lines,...s.json.error?{error:s.json.error}:{},summary:kw(s.json)};if(c.error)return J(c,{kind:`failed`,error:{code:`E_STORYBOARD_VOICE`,message:c.error}});let l=c.lines.filter(e=>!e.ok);return J(c,l.length?l.length===c.lines.length?{kind:`failed`,error:{code:`E_STORYBOARD_VOICE`,message:kw({lines:l}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:zw},e)};function zw({data:e}){let t=e.action===`cut`;return{heading:{cut:`Cut`,export:`Export`,template:`Template`,voice:`Voice`}[e.action],status:e.error||e.lines.some(e=>!e.ok)?`failed`:``,subject:e.artifact??``,facts:t?[X(`Version`,{key:`cut`,value:String(e.cut?.n??``)})]:e.action===`export`?[X(`Version`,{key:`export`,value:String(e.export?.n??``)})]:e.action===`voice`?[X(`Lines`,{key:`lines`,value:String(e.lines.length)})]:[],sections:[...e.error?[{kind:`content`,key:`error`,text:e.error}]:[],{kind:`content`,key:`summary`,text:(e.summary??[]).join(`
@@ -994,7 +994,7 @@ StandardError=append:${t}
994
994
  WantedBy=default.target
995
995
  `}const jE=(e,t)=>{if(e.status!==0)throw Error(`${t} failed: ${e.stderr.trim()}`)};function ME(e){let t=`gui/${e.uid}/${wE}`,n=d.default.join(e.home,`Library`,`LaunchAgents`,`${wE}.plist`);return{file:n,kind:`agent`,check:()=>null,render:OE,load:()=>{e.run(`launchctl`,[`bootout`,t]),jE(e.run(`launchctl`,[`bootstrap`,`gui/${e.uid}`,n]),`launchctl bootstrap`)},migrate:()=>{let e=u.default.readFileSync(n,`utf8`);return e.includes(EE)?(u.default.writeFileSync(n,e.replace(EE,`<key>ProcessType</key>
996
996
  <string>Standard</string>`)),!0):!1},unload:()=>{e.run(`launchctl`,[`bootout`,t])},removed:()=>{},restart:()=>jE(e.run(`launchctl`,[`kickstart`,`-k`,t]),`launchctl kickstart`),linger:()=>void 0}}function NE(e){let t=(...t)=>e.run(`systemctl`,[`--user`,...t]),n,r=()=>n??=t(`show-environment`),i=()=>{let t=r();return t.status===0?/^XDG_CONFIG_HOME=(.+)$/m.exec(t.stdout??``)?.[1]??d.default.join(e.home,`.config`):e.configHome??d.default.join(e.home,`.config`)};return{get file(){return d.default.join(i(),`systemd`,`user`,TE)},kind:`service`,check:()=>{let e=r();return e.status===0?null:`systemd user services are not available here (systemctl --user: ${e.stderr.trim()||`failed`}); ryugi daemon needs systemd on Linux`},render:AE,load:()=>{jE(t(`daemon-reload`),`systemctl --user daemon-reload`),jE(t(`enable`,TE),`systemctl --user enable ${TE}`),jE(t(`restart`,TE),`systemctl --user restart ${TE}`)},migrate:()=>!1,unload:()=>{t(`disable`,`--now`,TE)},removed:()=>{t(`daemon-reload`)},restart:()=>jE(t(`restart`,TE),`systemctl --user restart ${TE}`),linger:()=>{let t=e.run(`loginctl`,[`enable-linger`]);return t.status===0?{enabled:!0}:{enabled:!1,error:t.stderr.trim()||`exit ${t.status}`}}}}function PE(e){return e.platform===`darwin`?ME(e):e.platform===`linux`?NE(e):null}const FE={darwin:[`arm64`],linux:[`x64`,`arm64`]},IE=e=>({binary:d.default.join(e,`.ryugi`,`bin`,`ryugi-daemon`),log:d.default.join(e,`.ryugi`,`daemon`,`daemon.log`)});function LE(e){return hE(`ryugi-daemon-${e.platform}-${e.arch}`,e.version,process.env.RYUGI_DAEMON_RELEASE_BASE||`https://github.com/Innei/ryugi/releases/download`,e.fetch)}async function RE(e,t,n){if(d.default.resolve(e.serverHome)!==d.default.join(e.home,`.ryugi`,`server`))return{status:`other-hub`};let r=IE(e.home),i=PE(e);if(!i||!u.default.existsSync(i.file)||!u.default.existsSync(r.binary))return{status:`not-installed`};let a=await t.call(`status`,{}).catch(()=>null);if(!a?.version)return{status:`not-running`};if(e.daemonSource?a.source===e.daemonSource:a.version===e.version)return{status:`current`};let o=await LE(e);return n?.(),gE(r.binary,o),i.migrate()?i.load():i.restart(),{status:`updated`,from:a.version,to:e.version}}const zE=(e,t)=>e.enabled?`linger on: the daemon keeps running after you log out`:`linger off (${e.error}): the daemon stops when you log out; to keep it running, an admin can run: sudo loginctl enable-linger ${t}`;async function BE(e,t){let n=PE(e);if(!n)throw new F(`ryugi daemon runs on macOS (Apple silicon) and Linux (x64, arm64) with systemd`);if(!t.binary&&!FE[e.platform]?.includes(e.arch))throw new F(e.platform===`darwin`?`ryugi-daemon ships for Apple silicon Macs only`:`ryugi-daemon ships for Linux x64 and arm64 only`);let r=n.check();if(r)throw new F(r);let i=IE(e.home),a=t.binary?u.default.readFileSync(t.binary):await LE(e).catch(e=>{throw new F(e.message)});gE(i.binary,a),u.default.mkdirSync(d.default.dirname(i.log),{recursive:!0,mode:448}),u.default.mkdirSync(d.default.dirname(n.file),{recursive:!0}),u.default.writeFileSync(n.file,n.render({binary:i.binary,hubStart:e.hubStart,path:e.path,log:i.log}));try{n.load()}catch(e){throw new F(e.message)}let o=n.linger();return{binary:i.binary,kind:n.kind,service:n.file,...o?{linger:o}:{}}}function VE(e){let t=PE(e);if(!t)throw new F(`ryugi daemon runs on macOS (Apple silicon) and Linux (x64, arm64) with systemd`);let n=IE(e.home),r=t.file;return t.unload(),u.default.rmSync(r,{force:!0}),u.default.rmSync(n.binary,{force:!0}),t.removed(),{binary:n.binary,service:r}}async function HE(e){let{cloud:t}=e;try{await e.daemon.call(`status`,{})}catch{throw new F(`the daemon is not running; start it with: ryugi daemon install`)}let n=await e.fetch(`${t.origin}/api/devices/confirm`,{method:`POST`,headers:{Authorization:`Bearer ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({code:e.code.trim().toUpperCase(),hostId:t.hostId,...e.label?{label:e.label}:{}})}),r=await n.json().catch(()=>null);if(!n.ok||!r?.deviceId)throw new F(r?.error?.message??`Cloud refused the code: HTTP ${n.status}`);let i=r.label??``;return await e.daemon.call(`trust.add`,{deviceId:r.deviceId,label:i}),{deviceId:r.deviceId,label:i}}function UE(e,t,n){let r=t.filter(e=>e.state===`running`&&e.attach),i=n?r.find(e=>e.taskId===n||e.artifact===n):r.length===1?r[0]:void 0;if(!i)throw r.length===0?new F(`no daemon session is running`):n?new F(`no running daemon session ${n}`):new F(`several daemon sessions are running; name one:\n${r.map(e=>` ${e.taskId} ${e.artifact}`).join(`
997
- `)}`);return[IE(e).binary,`attach`,i.attach]}const WE=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],GE=()=>(process.env.RYUGI_CLOUD_ORIGIN||`https://ryugi.innei.dev`).replace(/\/+$/,``);function KE(){return{arch:process.arch,fetch,home:g.default.homedir(),hubStart:[process.execPath,u.default.realpathSync(process.argv[1])],configHome:process.env.XDG_CONFIG_HOME||void 0,run:(e,t)=>{let n=(0,f.spawnSync)(e,t,{encoding:`utf8`});return{status:n.status,stderr:n.stderr||(n.error?.message??``),stdout:n.stdout??``}},path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,uid:process.getuid?.()??0,version:process.env.RYUGI_ARTIFACTS_VERSION||`1.108.6`}}function qE(){let e=Vt(process.env,process.platform,g.default.homedir()),t=GE(),n=Bt(e,t);if(!n)throw new F(`sign in to Ryugi Cloud (${t}) on this computer first`);return{origin:t,token:n.token,hostId:dE(e)}}const JE=()=>uE(lE());async function YE(e){try{return await e()}catch(e){let t=e.code;throw t===`ENOENT`||t===`ECONNREFUSED`?new F(`the daemon is not running; install it with: ryugi daemon install`):new F(e.message)}}async function XE(){return(await YE(()=>JE().call(`sessions.local`,{}))).sessions}async function ZE(e){let[t,n,r]=e.positionals;if(!t||!WE.includes(t))throw new F(`usage: ryugi daemon ${WE.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await BE(KE(),{binary:e.values.binary});return i(`installed`,[`binary ${t.binary}`,`${t.kind.padEnd(8)}${t.service}`,...t.linger?[zE(t.linger,g.default.userInfo().username)]:[]])}case`uninstall`:{let e=VE(KE());return i(`removed`,[`removed ${e.binary}`,`removed ${e.service}`])}case`status`:{let e=await YE(()=>JE().call(`status`,{}));return i(`running`,[`version ${e.version}`,`remote ${e.remote?`on`:`off`}`,`sessions ${e.sessions} running, ${e.queued} queued`])}case`trust`:{if(!n)throw new F(`usage: ryugi daemon trust <code>`);let t=await HE({code:n,cloud:qE(),daemon:JE(),fetch,label:e.values.label});return i(`trusted`,[`${t.deviceId} ${t.label}`])}case`devices`:{if(n===`revoke`){if(!r)throw new F(`usage: ryugi daemon devices revoke <device-id>`);let e=qE(),t=await fetch(`${e.origin}/api/devices/${encodeURIComponent(r)}`,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok&&t.status!==404)throw new F(`Cloud refused the revoke: HTTP ${t.status}`);return await YE(()=>JE().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await YE(()=>JE().call(`trust.list`,{}));return i(`listed`,e.devices.length?e.devices.map(e=>`${e.id} ${e.label}`):[`no trusted devices; pair one from Ryugi Cloud on the phone`])}case`remote`:if(n!==`on`&&n!==`off`)throw new F(`usage: ryugi daemon remote on|off`);return await YE(()=>JE().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await XE();return i(`listed`,e.length?e.map(e=>`${e.taskId} ${e.state.padEnd(7)} ${e.harness.padEnd(6)} ${e.artifact} ${e.projectDir}`):[`no daemon sessions`])}default:{let[e,...t]=UE(g.default.homedir(),await XE(),n);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
997
+ `)}`);return[IE(e).binary,`attach`,i.attach]}const WE=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],GE=()=>(process.env.RYUGI_CLOUD_ORIGIN||`https://ryugi.innei.dev`).replace(/\/+$/,``);function KE(){return{arch:process.arch,fetch,home:g.default.homedir(),hubStart:[process.execPath,u.default.realpathSync(process.argv[1])],configHome:process.env.XDG_CONFIG_HOME||void 0,run:(e,t)=>{let n=(0,f.spawnSync)(e,t,{encoding:`utf8`});return{status:n.status,stderr:n.stderr||(n.error?.message??``),stdout:n.stdout??``}},path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,uid:process.getuid?.()??0,version:process.env.RYUGI_ARTIFACTS_VERSION||`1.108.7`}}function qE(){let e=Vt(process.env,process.platform,g.default.homedir()),t=GE(),n=Bt(e,t);if(!n)throw new F(`sign in to Ryugi Cloud (${t}) on this computer first`);return{origin:t,token:n.token,hostId:dE(e)}}const JE=()=>uE(lE());async function YE(e){try{return await e()}catch(e){let t=e.code;throw t===`ENOENT`||t===`ECONNREFUSED`?new F(`the daemon is not running; install it with: ryugi daemon install`):new F(e.message)}}async function XE(){return(await YE(()=>JE().call(`sessions.local`,{}))).sessions}async function ZE(e){let[t,n,r]=e.positionals;if(!t||!WE.includes(t))throw new F(`usage: ryugi daemon ${WE.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await BE(KE(),{binary:e.values.binary});return i(`installed`,[`binary ${t.binary}`,`${t.kind.padEnd(8)}${t.service}`,...t.linger?[zE(t.linger,g.default.userInfo().username)]:[]])}case`uninstall`:{let e=VE(KE());return i(`removed`,[`removed ${e.binary}`,`removed ${e.service}`])}case`status`:{let e=await YE(()=>JE().call(`status`,{}));return i(`running`,[`version ${e.version}`,`remote ${e.remote?`on`:`off`}`,`sessions ${e.sessions} running, ${e.queued} queued`])}case`trust`:{if(!n)throw new F(`usage: ryugi daemon trust <code>`);let t=await HE({code:n,cloud:qE(),daemon:JE(),fetch,label:e.values.label});return i(`trusted`,[`${t.deviceId} ${t.label}`])}case`devices`:{if(n===`revoke`){if(!r)throw new F(`usage: ryugi daemon devices revoke <device-id>`);let e=qE(),t=await fetch(`${e.origin}/api/devices/${encodeURIComponent(r)}`,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok&&t.status!==404)throw new F(`Cloud refused the revoke: HTTP ${t.status}`);return await YE(()=>JE().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await YE(()=>JE().call(`trust.list`,{}));return i(`listed`,e.devices.length?e.devices.map(e=>`${e.id} ${e.label}`):[`no trusted devices; pair one from Ryugi Cloud on the phone`])}case`remote`:if(n!==`on`&&n!==`off`)throw new F(`usage: ryugi daemon remote on|off`);return await YE(()=>JE().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await XE();return i(`listed`,e.length?e.map(e=>`${e.taskId} ${e.state.padEnd(7)} ${e.harness.padEnd(6)} ${e.artifact} ${e.projectDir}`):[`no daemon sessions`])}default:{let[e,...t]=UE(g.default.homedir(),await XE(),n);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
998
998
  `),i((0,f.spawnSync)(e,t,{stdio:`inherit`}).status===0?`detached`:`failed`,[])}}}function QE({data:e}){return{heading:`Daemon`,status:e.status,summary:``,facts:[],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
999
999
  `)}]:[]}}const $E={name:`daemon`,summary:`Install and run the daemon that starts agent sessions from your phone`,usage:[`install [--binary <path>]`,`uninstall`,`status`,`trust <code> [--label <name>]`,`devices [revoke <device-id>]`,`remote on|off`,`sessions`,`attach [<task-id>|<type>/<id>]`],details:`install downloads ryugi-daemon for this version, checks its sha256 and runs it as a launchd agent on macOS or a systemd user service on Linux, turning on linger there so it keeps running after you log out (--binary installs a local build instead). trust confirms the code shown on the phone with Ryugi Cloud and adds the device to the daemon. remote off makes the daemon refuse new tasks, resumes and screens. attach opens a daemon session in this terminal.`,positionals:3,options:{binary:{type:`string`,value:`<path>`,help:`Install this ryugi-daemon build instead of downloading one`},label:{type:`string`,value:`<name>`,help:`Name for the trusted device`}},semantic:e=>Z({id:`daemon`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},async run(){let t=await ZE(e);return J(t,t.status===`failed`?{kind:`failed`,error:{code:`E_DAEMON`,message:`daemon ${t.action} failed`}}:{kind:`succeeded`})},present:QE},e)},eD=e=>{let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(e)),t};function tD(e){let t=(0,p.createHash)(`sha256`).update(`codex-plugin-bundle-v1`),n=[e];for(;n.length;){let r=n.pop(),i=d.default.relative(e,r),a=i?d.default.basename(i):``;if(a&&(a===`__pycache__`||a===`.venv`||a.endsWith(`.pyc`)||a.endsWith(`.egg-info`)))continue;let o=Buffer.from(i);t.update(eD(o.length)).update(o);let s=u.default.lstatSync(r);if(s.isDirectory()){t.update(`directory`);let e=u.default.readdirSync(r).sort((e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t)));for(let t=e.length-1;t>=0;t--)n.push(d.default.join(r,e[t]))}else if(s.isFile())t.update(`file`).update(eD(s.size)).update(u.default.readFileSync(r));else throw Error(`Unsupported Codex plugin entry: ${r}`)}return`sha256:${t.digest(`hex`)}`}const nD=e=>e.replaceAll(/(?<=[a-z\d])([A-Z])/g,`_$1`).toLowerCase();function rD(e,t){let n=JSON.parse(u.default.readFileSync(d.default.join(e,`.codex-plugin/plugin.json`),`utf8`));if(typeof n.hooks!=`string`)return[];let r=d.default.posix.normalize(n.hooks.replaceAll(`\\`,`/`)),i=JSON.parse(u.default.readFileSync(d.default.join(e,r),`utf8`)).hooks??{},a=[];for(let[e,n]of Object.entries(i))n.forEach((n,i)=>(n.hooks??[]).forEach((n,o)=>a.push(`${t}:${r}:${nD(e)}:${i}:${o}`)));return a}function iD(e){let t=/* @__PURE__ */ new Map,n;for(let r of e.split(/\r?\n/)){let e=r.match(/^\s*\[\s*hooks\.state\."((?:[^"\\]|\\.)*)"\s*\]\s*$/);if(e){n={},t.set(JSON.parse(`"${e[1]}"`),n);continue}if(/^\s*\[/.test(r)){n=void 0;continue}let i=r.match(/^\s*([\w-]+)\s*=\s*(.+?)\s*$/);n&&i&&(n[i[1]]=i[2].replace(/^"(.*)"$/,`$1`))}return t}function aD(e,t,n,r=g.default.homedir()){let i=rD(e,t),a=d.default.join(n.CODEX_HOME||d.default.join(r,`.codex`),`config.toml`),o=iD(u.default.existsSync(a)?u.default.readFileSync(a,`utf8`):``),s=tD(e),c=i.filter(e=>{let t=o.get(e);return t?.trusted_content_hash!==s||t.enabled===`false`});return{declared:i.length,blocked:c.length}}function oD(e,t){try{return u.default.realpathSync(e)===u.default.realpathSync(t)}catch{return d.default.resolve(e)===d.default.resolve(t)}}function sD(e,t){let n=JSON.parse(t(`claude`,[`plugin`,`list`,`--json`]));if(!Array.isArray(n))throw Error(`Claude returned an unknown plugin list`);let r=n.find(t=>t.id===e&&t.scope===`user`);return!r||typeof r.installPath!=`string`?null:{path:r.installPath,source:typeof r.readFromFolder==`string`?r.readFromFolder:r.installPath,version:String(r.version||`unknown`)}}function cD(e,t){let n=sD(e,t);if(!n)throw Error(`Native Claude plugin not found: ${e}`);return n}function lD(e,t){if(!e.nativeSource||!e.registration)return`foreign`;let n=sD(e.registration,t);if(!n)return`missing`;if(oD(n.source,e.nativeSource))return`owned`;let[r,i]=e.registration.split(`@`),a=d.default.dirname(n.path);return n.source===n.path&&d.default.basename(a)===r&&d.default.basename(d.default.dirname(a))===i&&oD(a,d.default.dirname(e.nativeSource))?`owned`:`foreign`}function uD(e,t){let n=e.path;if(e.harness===`claude-code`){let n=lD(e,t);if(n===`missing`)throw Error(`Native Claude plugin not found: ${e.registration}`);return n===`owned`}if(e.harness===`codex`){let e=JSON.parse(t(`codex`,[`plugin`,`list`,`--json`]));return Array.isArray(e.installed)&&e.installed.some(e=>e.pluginId===`ryugi@ryugi-managed`&&typeof e.source?.path==`string`&&oD(e.source.path,n))}if(e.harness===`pi`)return t(`pi`,[`list`]).split(/\r?\n/).some(e=>d.default.isAbsolute(e.trim())&&oD(e.trim(),n));if(e.harness===`gemini`){let e=JSON.parse(t(`gemini`,[`extensions`,`list`,`--output-format`,`json`]));return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.installMetadata?.type===`link`&&typeof e.installMetadata.source==`string`&&oD(e.installMetadata.source,n)&&typeof e.path==`string`&&oD(e.path,n))}if(e.harness===`copilot`){let e=JSON.parse(t(`copilot`,[`plugin`,`list`,`--json`]));return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.marketplace===`ryugi-managed`&&typeof e.installedFrom==`string`&&oD(e.installedFrom,d.default.dirname(n)))}if(e.harness===`agy`){let e=JSON.parse(t(`agy`,[`plugin`,`list`,`--json`])),r=JSON.parse(u.default.readFileSync(d.default.join(n,`.antigravity-plugin/plugin.json`),`utf8`)).version;return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.enabled!==!1&&e.version===r)}return!0}function dD(e,t,n){let r=JSON.parse(n(e,[`plugin`,`marketplace`,`list`,`--json`])),i=e===`codex`?r.marketplaces:r;if(!Array.isArray(i))throw Error(`${e} returned an unknown marketplace list`);return i.some(n=>n.name===`ryugi-managed`&&(e===`codex`?typeof n.root==`string`&&oD(n.root,t):typeof n.source==`string`&&oD(n.source.replace(/^Local:\s*/i,``),t)))}function fD(e,t){let n=JSON.parse(t(e,[`plugin`,`marketplace`,`list`,`--json`])),r=e===`codex`?n.marketplaces:n;if(!Array.isArray(r))throw Error(`${e} returned an unknown marketplace list`);return r.some(e=>e.name===`ryugi-managed`)}function pD(e){let t=(0,p.createHash)(`sha256`);function n(r){for(let i of u.default.readdirSync(r).sort()){let a=d.default.join(r,i),o=u.default.lstatSync(a);if(o.isSymbolicLink())throw Error(`Plugin contains an unexpected symlink: ${a}`);t.update(d.default.relative(e,a)),t.update(o.isDirectory()?`\0dir\0`:`\0file\0`),o.isDirectory()?n(a):t.update(u.default.readFileSync(a))}}return n(e),t.digest(`hex`)}function mD(e,t,n){if(u.default.existsSync(t))throw Error(`Candidate already exists: ${t}`);u.default.mkdirSync(t,{recursive:!0});try{for(let n of[`skills`,`hooks`,`lib`,`assets`,`index.js`,`package.json`,`LICENSE`,`GEMINI.md`,`gemini-extension.json`,`.pi`,`.opencode`,`.antigravity-plugin`,`.claude-plugin`,`.codex-plugin`,`.cursor-plugin`]){let r=d.default.join(e,n);u.default.existsSync(r)&&u.default.cpSync(r,d.default.join(t,n),{recursive:!0,filter(t){let n=d.default.relative(e,t).replaceAll(`\\`,`/`);if(/^skills\/artifacts\/app\/(cli\.cjs|server\.cjs|viewer|runtime)(\/|$)/.test(n))return!1;if(u.default.lstatSync(t).isSymbolicLink())throw Error(`Plugin source symlink is not supported: ${t}`);return!0}})}for(let e of[`artifacts`,`interface-craft`,...n===`full`?[`using-ryugi`]:[]])if(!u.default.existsSync(d.default.join(t,`skills`,e,`SKILL.md`)))throw Error(`Incomplete Ryugi plugin: missing ${e}`);if(n===`artifacts`){for(let e of u.default.readdirSync(d.default.join(t,`skills`)))[`artifacts`,`interface-craft`].includes(e)||u.default.rmSync(d.default.join(t,`skills`,e),{recursive:!0,force:!0});u.default.writeFileSync(d.default.join(t,`GEMINI.md`),`# Ryugi Artifacts
1000
1000
  Use the artifacts and interface-craft skills when requested.
@@ -1091,7 +1091,7 @@ Full workflow: Artifacts plus brainstorming, specs, TDD, debugging, git
1091
1091
  worktrees and verification skills. Injects the Ryugi workflow into every
1092
1092
  new session. Rerun install to switch.`,`Content`,{output:n});let t=await hk({output:n,message:`What would you like to install?`,initialValue:e,options:[{value:`artifacts`,label:`Artifacts`,hint:`visual pages only; sessions unchanged`},{value:`full`,label:`Full workflow`,hint:`Artifacts + workflow skills; changes every session`}]});return xO(t)?null:t},async targets(t){let r=_D.filter(t=>!e.detected.includes(t.id));if(r.length&&uk(r.map(e=>`${e.label}: ${e.command} not found`).join(`
1093
1093
  `),`Unavailable`,{output:n}),!e.detected.length)return[];let i=await ak({output:n,message:`Install into which harnesses? (empty = CLI only)`,required:!1,initialValues:t,options:_D.filter(t=>e.detected.includes(t.id)).map(t=>({value:t.id,label:t.label,hint:`${e.previous[t.id]?.mode||`new`} · ${t.comments}`}))});return xO(i)?null:i},async review(t){uk([`CLI: ${t.root}`,`Command: ${t.binDir}`,`Content: ${t.mode}`,...t.targets.map(n=>`${n}: ${e.previous[n]?.mode||`new`} → ${t.mode}; ${_D.find(e=>e.id===n).comments}`),...t.targets.length?[`Start a new harness session after installation.`]:[`CLI only; no harness plugins.`]].join(`
1094
- `),`Installation plan`,{output:n});let r=await hk({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return xO(r)?`cancel`:r}},t);return r||ok(`Cancelled. No installation changes made.`,{output:n}),r}function yk(){return fk({output:process.stderr,onCancel:()=>{}})}function bk(e){for(let t of[`package.json`,`.codex-plugin/plugin.json`])try{let n=JSON.parse(u.default.readFileSync(d.default.join(e,t),`utf8`)),r=String(n.version??``).replace(/-(?:full|artifacts)\.[\da-f]+$/,``);if(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(r))return r}catch{}return null}function xk(e){let t=/* @__PURE__ */ new Map;return(n,r)=>{let i=JSON.stringify([n,r]);return t.has(i)||t.set(i,e(n,r)),t.get(i)}}function Sk(e,t){let n=xk(t),r=[],i;try{i=Object.values(BD(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&lD(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&cD(e.registration,n).path:e.path;if(!t)continue;let i=d.default.join(t,`skills/artifacts/app/hook-bin.sh`);if(!u.default.existsSync(i))continue;let a=bk(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!u.default.readFileSync(i,`utf8`).includes(`.ryugi/hook`)})}catch{a=!1}return{plugins:r,complete:a}}function Ck(e,t){return Sk(e,t.run).plugins}function wk(e,t,n){let r=Sk(e,t);return ED(n,r),r}function Tk(e){let t=[],n=[];if(e.status!==`done`)return{warnings:t,actions:n};for(let r of e.failed)t.push({code:`W_HOOK_BINARY`,severity:`warning`,message:`ryugi-hook ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`ryugi`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function Ek(e,t){let n=/* @__PURE__ */ new Map,r=t?1:25,i=null;return{report(a,o,s){let c=s?` ${Math.floor(Math.floor(o/s*100)/r)*r}%`:t?` ${(o/1048576).toFixed(1)} MB`:``;if(n.get(a)===c)return;n.set(a,c);let l=`Downloading ryugi-hook ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=yk()).start(l)},finish(){i?.stop(`Downloaded ryugi-hook ${[...n.keys()].join(`, `)}`)}}}async function Dk(e,t,n){let r=Ek(t,n);try{return await Ok({...e,progress:r.report})}finally{r.finish()}}function Ok(e){return kk(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function kk(e){let t=g.default.homedir(),n=ke().home;if(d.default.resolve(n)!==d.default.join(t,`.ryugi`,`server`))return{status:`other-hub`};let r=wk(e.root??jD(),e.run??vD,t);return AD({arch:process.arch,cleanup:e.cleanup,env:process.env,fetch,home:t,installed:r,platform:process.platform,progress:e.progress,retry:!0,serverHome:n,version:`1.108.6`})}const Ak=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(d.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;function jk(e,t={}){let n=[],r=new LD(e).current();if(r){let i=new LD(e,t.binDir||d.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=RD(i.binDir,t.env||process.env);n.push({component:`PATH`,status:a?`attention`:`ok`,message:a||`${i.binDir} is on PATH`});for(let e of[`dist/cli.cjs`,`dist/server.cjs`,`dist/document-engine.cjs`,`dist/viewer/index.html`,`dist/runtime/ryugi-ui.js`])n.push({component:`CLI ${e}`,status:u.default.existsSync(d.default.join(r.packageRoot,e))?`ok`:`attention`,message:d.default.join(r.packageRoot,e)})}else n.push({component:`CLI runtime`,status:`attention`,message:`No self-managed runtime; retain the current package-manager or development CLI.`});for(let r of Object.values(BD(e).harnesses))try{if(r.harness===`claude-code`){let e=d.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||d.default.join(t.home||g.default.homedir(),`.claude`),`settings.json`);if(!JSON.parse(u.default.readFileSync(e,`utf8`)).enabledPlugins?.[r.registration])throw Error(`Recorded Claude plugin is not enabled at user scope`);if(!uD(r,t.run||vD))throw Error(`Native Claude source no longer matches the record`)}else if(SD(r,xD(r.harness,{root:e,home:t.home})),!uD(r,t.run||vD))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=aD(r.path,r.registration||`ryugi@ryugi-managed`,t.env||process.env,t.home);n.push(e.blocked?{component:r.harness,status:`attention`,message:`${i}; ${e.blocked} of ${e.declared} Codex hooks are not approved for this version, so comments will not arrive. Open Codex Settings → Hooks, choose Ryugi, press Trust all, then start a new chat.`}:{component:r.harness,status:`ok`,message:`${i}; hooks trusted; new session required`});continue}n.push({component:r.harness,status:`ok`,message:`${i}; restart/new session required; delivery unverified`})}catch(e){n.push({component:r.harness,status:`attention`,message:e.message})}let i=t.home||g.default.homedir(),a=yE(process.platform,process.arch);for(let r of Ck(e,{run:t.run||vD})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.ryugi/hook; run ryugi update to refresh it`});continue}if(!a)continue;let t=d.default.join(vE(i,r.version),`ryugi-hook`);n.push(u.default.existsSync(t)?{component:e,status:`ok`,message:t}:{component:e,status:`attention`,message:`no ryugi-hook ${r.version}, so this plugin's hooks skip; run ryugi hook install ${r.version}`})}return n}function Mk(e,t={}){let n=BD(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||vD;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(![`ryugi@ryugi-dev`,`ryugi-artifacts@ryugi-dev`].includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=lD(o,i);if(e===`foreign`)throw Error(`Native Claude source changed; preserving it`);e===`owned`&&i(`claude`,[`plugin`,`uninstall`,o.registration,`--scope`,`user`])}else{if(SD(o,xD(a,{root:e,home:t.home})),!uD(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,`ryugi@ryugi-managed`]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,`ryugi@ryugi-managed`]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,`ryugi`]),a===`opencode`){let e=t.env||process.env,n=d.default.join(e.XDG_CONFIG_HOME||d.default.join(t.home||g.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!u.default.existsSync(n)||u.default.readFileSync(n,`utf8`)!==Ak(o.path))throw Error(`Plugin entry was changed; preserving ${n}`);u.default.unlinkSync(n)}u.default.rmSync(o.path,{recursive:!0})}delete n.harnesses[a],VD(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new LD(e).current();if(n){let i=new LD(e,t.binDir||d.default.dirname(n.bin));i.ownsBin()?(u.default.unlinkSync(i.bin),r.removed.push(`CLI command`)):r.failures.push({component:`CLI command`,message:`Command changed; preserving ${i.bin}`})}}return r}const Nk={name:`doctor`,summary:`Check installed CLI ownership, plugin files and native registrations`,options:{"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`}},semantic:e=>Z({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(){let t=jk(d.default.resolve(e.values[`install-dir`]||jD()));return J({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})},present:({data:e})=>({heading:`Doctor`,status:e.checks.some(e=>e.status===`attention`)?`attention`:`ok`,facts:[],sections:[{kind:`records`,key:`checks`,rows:e.checks.map(e=>({...e})),columns:[{key:`component`,required:!0},{key:`status`,required:!0},{key:`message`,required:!0}]}]})},e)},Pk={"X-Ryugi-Version":x},Fk=/<head(\s[^>]*)?>/i,Ik=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,Lk=/^<script>([\s\S]*?)<\/script>/,Rk=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function zk(e){let t=Fk.exec(e);return t?t.index+t[0].length:Ik.exec(e)?.[0].length??0}function Bk(e){let t=zk(e),n=e.slice(t);n.startsWith(`<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>`)&&(n=n.slice(153));let r=Lk.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(Rk,``)}function Vk(e,t=4){let n=0,r;try{r=u.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.isSymbolicLink())continue;let r=d.default.join(e,i.name);i.isDirectory()?t>0&&(n=Math.max(n,Vk(r,t-1))):i.isFile()&&(n=Math.max(n,u.default.statSync(r).mtimeMs))}return n}const Hk=e=>{let t=Vk(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function Uk(e){let t=/* @__PURE__ */ new Set([...Object.keys(GS),`artifact`,`source`]),n=Object.keys(e.values).find(e=>!t.has(e));if(n)throw new K({code:`E_ARGUMENT_INVALID`,message:`--${n} applies to Cloud reads only. Local reads accept --artifact, --detail or --source.`});let r=e.values.artifact;r&&lS(e.projectDir,r);let i=!!e.values.source||e.values.format===`source`;if(i&&!r)throw new K({code:`E_ARGUMENT_INVALID`,message:`Local --source requires --artifact <type>/<id>.`});let{project:a,root:o}=Ue(e.projectDir);return Z({id:`get`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`,...r?[`source`]:[]],detail:!0},async run(t,n){let s=r?{artifacts:[{type:r.split(`/`)[0],id:r.split(`/`)[1],dir:``}],warnings:[]}:ye(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=lS(a,r);if(i.content===`existing`){let e=u.default.realpathSync(i.write);if(!e.startsWith(`${o}${d.default.sep}`))throw new K({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source escapes its project: ${i.write}`});let t=u.default.statSync(e);if(!t.isFile())throw new K({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source is not a regular file: ${i.write}`});return{artifact:r,...i,bytes:t.size,modifiedAt:t.mtime.toISOString(),...n?Hk(n):{}}}return{artifact:r,...i,...n?Hk(n):{}}});c.sort((e,t)=>(t.updatedAt??``).localeCompare(e.updatedAt??``));let l,f;if(r&&(i||e.values.detail)){if(c[0]?.content!==`existing`)throw new K({code:`E_ARTIFACT_NOT_FOUND`,message:`Content not written yet: ${c[0]?.write}`});let e=u.default.readFileSync(c[0].write);l=e.toString(`utf8`),f=p.default.createHash(`sha256`).update(e).digest(`hex`),n.payloads.source=l}let[m,h]=r?.split(`/`)??[],g=s.warnings.map(e=>({code:`W_ARTIFACT_DISCOVERY`,message:e})),_=m&&ge(m)&&h&&c[0]?.content===`existing`?Qx[m].localGet:void 0,v=_?.read(o,h,c[0].write);g.push(...v?.warnings??[]);let y=l!==void 0&&!i?v?.markdown:void 0,b=y??l;return J({origin:`local`,project:a,complete:!0,...r?{}:{server:await sw()},items:c,..._&&v?.rows?{[_.key]:v.rows}:{},...b===void 0?{}:{content:b,contentFormat:y===void 0?void 0:`markdown`,sha256:f}},void 0,{warnings:g,actions:r?[q([`check`,`--project-dir`,a,`--artifact`,r],`Check`)]:[],coverage:r&&l===void 0?{omitted:[{path:`data.content`,reason:`summary`}]}:{}})},present({data:e}){return{heading:`Local artifacts`,status:`complete`,subject:e.project,facts:e.server?[{label:`Server`,binding:{key:`server`,value:`${e.server.status}${e.server.version?` · ${e.server.version}`:``}`}}]:[],sections:[{kind:`records`,key:`items`,rows:e.items,columns:[{key:`artifact`,required:!0,positional:!0},{key:`content`,positional:!0},{key:`updatedAt`,label:`Updated`,positional:!0},{key:`write`,label:`Edit`,required:!0},{key:`bytes`}]},...oe.flatMap(t=>{let n=Qx[t].localGet,r=n&&e[n.key];return n&&Array.isArray(r)?[{kind:`records`,key:n.key,rows:r,columns:n.columns}]:[]}),...e.content===void 0?[]:[{kind:`content`,key:`content`,text:e.content,title:e.contentFormat===`markdown`?`Markdown`:`Complete source`}]]}}},e)}function Wk({data:e}){let t=ge(e.type)?Qx[e.type].outlineView:void 0;return{heading:`Cloud artifact`,status:e.status===`downloaded`||e.status===`partial`?e.status:``,subject:e.id,summary:[e.type,`v${e.version}`,e.visibility].join(` · `),facts:[X(`Title`,Y(e,`title`)),...e.saved?[X(`Saved`,Y(e,`saved`),!0),X(`Bytes`,Y(e,`bytes`))]:[],...e.dir?[X(`Downloaded`,Y(e,`dir`),!0)]:e.files?[X(`Files available`,{key:`files`,value:e.files.join(`, `)})]:[]],sections:[...e.outline?[{kind:`records`,key:`outline`,...t?{rows:t.rows(e.outline),columns:t.columns}:{rows:e.outline,columns:[{key:`id`,positional:!0,required:!0},{key:`type`,positional:!0},{key:`preview`,positional:!0}]}}]:[],...e.prompt===void 0?[]:[{kind:`content`,key:`prompt`,title:Bh.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...gT(e.comments.threads,`comments`),title:`Published snapshot comments`}]:[]]}}const Gk=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,Kk=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!d.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function qk(e,t,n){if(!e.contentBase||!Array.isArray(e.files))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return a complete download manifest.`});if(e.files.some(e=>!Kk(e)))throw new K({code:`E_FILE_PATH_UNSAFE`,message:`The manifest contains an unsafe file path.`});if(u.default.existsSync(t))throw new K({code:`E_FILE_EXISTS`,message:`Download directory already exists: ${t}`});u.default.mkdirSync(d.default.dirname(t),{recursive:!0}),u.default.mkdirSync(t,{mode:448});for(let r of e.files){let i=d.default.join(t,...r.split(`/`)),a=n.effects.begin(`download`,i);try{let t=await fetch(`${e.contentBase}${r.split(`/`).map(encodeURIComponent).join(`/`)}`,{headers:Pk,signal:n.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);u.default.mkdirSync(d.default.dirname(i),{recursive:!0});let o=Buffer.from(await t.arrayBuffer()),s=Yw(i,r.endsWith(`.html`)?Bk(o.toString(`utf8`)):o);n.effects.confirm(a,{bytes:s.bytes})}catch(e){throw n.effects.set(a,`failed`,{message:e.message}),new K({code:`E_DOWNLOAD_FAILED`,message:`Could not download ${r}: ${e.message}`})}}}function Jk(e){let t=e.positionals[0];if(!t)return Uk(e);if(e.values.artifact)throw new K({code:`E_OPTION_CONFLICT`,message:`Choose a local --artifact or a Cloud link/id, not both.`});let{origin:n,id:r,grant:i}=Qk(t,(process.env.RYUGI_CLOUD_ORIGIN||`https://ryugi.innei.dev`).replace(/\/+$/,``)),a=Gk(e,`save`);if(a!==void 0&&!a.trim())throw new K({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});let o=!!e.values.source||e.values.format===`source`||a!==void 0,s=Gk(e,`block`),c=Gk(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||Gk(e,`fields`)||Gk(e,`cursor`)||Gk(e,`limit`)))throw new K({code:`E_OPTION_CONFLICT`,message:`Source must be a complete document; use --snapshot to pin its version.`});if(s&&(l||u||Gk(e,`cursor`)))throw new K({code:`E_OPTION_CONFLICT`,message:`--block reads one complete block and cannot combine with detail, cursor or download.`});let f=Gk(e,`limit`);if(f&&(!/^\d+$/.test(f)||+f<1||+f>100))throw new K({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});let p=new URLSearchParams({semantic:`1`});for(let t of[`snapshot`,`cursor`,`fields`,`limit`,`section`,`page`]){let n=Gk(e,t);n&&p.set(t,n)}return u&&p.set(`detail`,`1`),s&&p.set(`block`,s),l&&p.set(`download`,`1`),(e.values[`no-comments`]||o)&&p.set(`no-comments`,`1`),Z({id:`get`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`source`,`quiet`],requiredFields:[`id`,`type`,`visibility`,`version`,`status`,...l?[`dir`]:[],...a?[`saved`,`bytes`]:[]],fields:[`id`,`type`,`title`,`visibility`,`version`,`updatedAt`,`outline`,`files`,`content`,`comments`,`saved`,`bytes`],scalar:e=>e.saved??e.id},async run(f,m){let h=Bt(Vt(process.env,process.platform,g.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:h?{...Pk,Authorization:`Bearer ${h.token}`}:Pk,signal:m.signal}),v=await _.text();m.payloads.raw=v;let y;try{y=JSON.parse(v)}catch{throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`})}if(!_.ok)throw new K({code:_.status===404?`E_NOT_FOUND`:`E_CLOUD_FAILED`,httpStatus:_.status,message:y.error||`HTTP ${_.status}`});if(y.schema!==`ryugi.cloud-read/v1`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`});let b;if(o){if(y.type!==`document`||typeof y.content!=`string`)throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`Source is available for documents only.`});m.payloads.source=y.content,a&&(b=Yw(a,y.content,m.effects),m.payloads.source=``,(e.values.source||e.values.format===`source`)&&m.diagnostic(`Saved ${b.file} (${b.bytes} bytes)`))}let{schema:x,page:S,contentBase:C,...w}=y,T={...w,...b?{saved:b.file,bytes:b.bytes}:{},status:l?`downloaded`:u||s?`read`:`available`};if(b&&delete T.content,l){T.dir=d.default.resolve(c??d.default.join(process.env.XDG_CACHE_HOME||d.default.join(g.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await qk(y,T.dir,m)}catch(e){if(!m.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=m.effects.snapshot(),J(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=m.effects.snapshot()}let E=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),D=[`get`,...E,`--snapshot`,y.snapshot],ee=[`get`,...E,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return J(T,void 0,{coverage:{page:S,...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[q([...D,`--detail`,`--`,t],`Details`)]:[],...!s&&!o&&!l&&y.page?.nextCursor?[q(ee,`More`)]:[]]})},present:Wk},e)}const Yk=/^[\w-]{1,64}$/,Xk=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,Zk=`Expected a Ryugi Cloud link (https://<host>/a/<id>) or an artifact id.`;function Qk(e,t){if(Yk.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new F(Zk)}let r=Xk.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new F(Zk);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:n.origin,id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const $k={name:`get`,summary:`Discover local artifacts, read native source, or read a published Cloud link/id`,usage:[`[--artifact <type>/<id> [--detail|--source]]`,`<link-or-id> [--out <dir>] [--no-comments] [options]`],details:`Without a link, lists local artifacts without a server or sign-in. --artifact selects local content; --detail or --source reads its complete native file, except that a document shows its heading outline and --detail reads it as markdown (--source keeps LiteXML). Cloud reads show a published outline/manifest; use --detail, --source or --download for more. Local reads never consume feedback.`,semantic:Jk,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Read this local artifact; omit to discover local artifacts`},section:{type:`string`,value:`<outline|files>`,help:`Choose the independently paginated collection`},source:{type:`boolean`,help:`Print complete native source locally, or complete LiteXML from Cloud`},download:{type:`boolean`,help:`Download the complete published manifest`},save:{type:`string`,value:`<file>`,help:`Save complete Cloud document source to a new file; supports structured output`},block:{type:`string`,value:`<id>`,help:`Read one published document block`},page:{type:`string`,value:`<pageId>`,help:`Read one page of a published whiteboard`},snapshot:{type:`string`,value:`<token>`,help:`Pin a published version`},cursor:{type:`string`,value:`<token>`,help:`Continue a manifest or outline page`},limit:{type:`string`,value:`<1-100>`,help:`Maximum outline or manifest rows`},out:{type:`string`,value:`<dir>`,help:`Download files here instead of ~/.cache/ryugi/get/<id>/`},"no-comments":{type:`boolean`,help:`Leave a document's comments out`}},positionals:1};function eA({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[X(`Version`,Y(e,`version`))],sections:[]}}const tA={name:`hook`,summary:`Download the ryugi-hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads ryugi-hook for this platform from the plugin release of <version>, checks its sha256 and keeps it in ~/.ryugi/hook/<version>. The plugin launcher runs it with --background when a hook finds no binary; that waits out the retry delay after a failed download, which a person running it skips.`,positionals:2,options:{background:{type:`boolean`,help:`Wait out the retry delay after a failed download`}},semantic:e=>Z({id:`hook`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},async run(){let[t,n]=e.positionals;if(t!==`install`)throw new F(`Usage: ryugi hook install <version>`);if(!n||!mE(n))throw new F(`hook install needs a release version, not ${n??`nothing`}`);let r=await CE({arch:process.arch,fetch,home:g.default.homedir(),platform:process.platform,retry:!e.values.background,version:n}),i=r.status===`present`||r.status===`installed`,a={action:t,version:n,status:r.status};return r.error&&(a.error=r.error),J(a,i?{kind:`succeeded`}:{kind:`failed`,error:{code:`E_HOOK_INSTALL`,message:r.error??`ryugi-hook ${n} is not available here (${r.status})`}})},present:eA},e)},nA=`Innei/ryugi`,rA={artifacts:`ryugi-artifacts@ryugi-dev`,full:`ryugi@ryugi-dev`};function iA(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function aA(e){let{command:t,args:n,shell:r}=iA(e);return(0,f.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function oA(e){let t=aA(e);if(t.error||t.status!==0)throw Error(`claude ${e.join(` `)} failed: ${(t.stderr||t.stdout||t.error?.message||``).trim()}`);return t.stdout}function sA(){let e=aA([`--version`]);return!e.error&&e.status===0}function cA(e){if(!u.default.existsSync(e))return{};let t=JSON.parse(u.default.readFileSync(e,`utf8`)).enabledPlugins;return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function lA(){let e=JSON.parse(oA([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===`ryugi-dev`)}function uA(e){let t=JSON.parse(oA([`plugin`,`list`,`--json`]));if(!Array.isArray(t))throw Error(`claude plugin list returned no list`);return t.some(t=>t?.id===e&&t?.scope===`user`)}const dA=e=>e===`artifacts`||e===`full`;async function fA(e,t,n){let r=e=>J({mode:null,harness:`claude-code`,installed:null,disabled:[]},{kind:`validation_failed`},{warnings:[{code:`W_INSTALL_MODE`,message:e,severity:`error`}]});if(e!==void 0&&!dA(e))return r(`--mode takes artifacts or full`);if(!sA())return J({mode:dA(e)?e:null,harness:`none`,installed:null,disabled:[]},{kind:`succeeded`},{warnings:[{code:`W_NO_CLAUDE_CODE`,message:`Claude Code was not found; artifacts only is Claude Code only. Install the full plugin by hand on other harnesses.`,severity:`warning`}],actions:[{kind:`url`,label:`Install guide`,url:`https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||d.default.join(g.default.homedir(),`.claude`),a=cA(d.default.join(i,`settings.json`));if(!dA(e))return r(`--mode artifacts|full is required`);let o=e,s=rA[o],c=rA[o===`artifacts`?`full`:`artifacts`],l=(e,t,r)=>{let i=n?.begin(e,t);oA(r),i!==void 0&&n.confirm(i)};lA()||l(`install.marketplace`,nA,[`plugin`,`marketplace`,`add`,nA,`--scope`,`user`]),l(`install.refresh`,`ryugi-dev`,[`plugin`,`marketplace`,`update`,`ryugi-dev`]),uA(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];a[c]===!0&&(l(`install.disable`,c,[`plugin`,`disable`,c,`--scope`,`user`]),u.push(c));let f=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]])cA(d.default.join(t,`.claude`,n))[c]===!0&&(f.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${c} is still enabled at ${e} scope; enable only one Ryugi entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,c,`--scope`,e],label:`Disable at ${e} scope`}));return J({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:f,actions:p})}const pA=`ryugi-artifacts`,mA=[`npm`,`pnpm`,`yarn`,`bun`],hA=[[`npx`,[`/_npx/`]],[`pnpm dlx`,[`/pnpm/dlx/`,`/.pnpm-store/dlx/`]],[`bunx`,[`/bunx-`,`/.bun/install/cache/`]]],gA=[[`pnpm`,[`/pnpm/global/`]],[`yarn`,[`/yarn/global/`]],[`bun`,[`/.bun/install/global/`]],[`npm`,[`/lib/node_modules/${pA}/`,`/npm/node_modules/${pA}/`]]];function _A(e,t){if(t.RYUGI_MANAGED_RUNTIME===`1`&&t.RYUGI_INSTALL_ROOT){let n=d.default.relative(d.default.join(t.RYUGI_INSTALL_ROOT,`versions`),e);if(n&&!n.startsWith(`..`)&&!d.default.isAbsolute(n))return{kind:`managed`}}if(t.RYUGI_ARTIFACTS_COMMAND)return{kind:`launcher`};let n=e;try{n=u.default.realpathSync(e)}catch{}let r=n.replaceAll(`\\`,`/`).toLowerCase(),i=e=>e.some(e=>r.includes(e));for(let[e,t]of hA)if(i(t))return{kind:`transient`,runner:e};for(let[e,t]of gA)if(i(t))return{kind:`global`,pm:e};return r.includes(`/node_modules/`)?{kind:`unknown`}:{kind:`local`}}async function vA(e,t,n=!1,r=!1){let i={bin:null,mode:null,owner:null,targets:[]},a=e=>J(i,{kind:`validation_failed`},{warnings:[{code:`E_INSTALL_PLAN`,message:e,severity:`error`}]}),o=d.default.resolve(e.values[`install-dir`]||jD()),s=new LD(o).current(),c=d.default.resolve(e.values[`bin-dir`]||(s?d.default.dirname(s.bin):MD())),l=BD(o);if(e.values.mode!==void 0&&![`artifacts`,`full`].includes(String(e.values.mode)))return a(`--mode takes artifacts or full`);let f=(e.values.harness===`none`?[]:yD()).filter(e=>e.detected).map(e=>e.id),m={...l.harnesses},h=d.default.join(process.env.CLAUDE_CONFIG_DIR||d.default.join(g.default.homedir(),`.claude`),`settings.json`);if(!m[`claude-code`]&&f.includes(`claude-code`)&&u.default.existsSync(h)){let e=JSON.parse(u.default.readFileSync(h,`utf8`)).enabledPlugins||{},t=e[`ryugi@ryugi-dev`]===!0?`full`:e[`ryugi-artifacts@ryugi-dev`]===!0?`artifacts`:null;t&&(m[`claude-code`]={harness:`claude-code`,mode:t,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:f,previous:m,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=gk({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await vk(_,t)}else v=gk({mode:e.values.mode,harness:e.values.harness},_)}catch(e){return a(e.message)}if(!v)return J(i,{kind:`interrupted`,signal:`SIGINT`});i.mode=v.mode;let y=[],b=[],x=n?yk():null,S,C=!1,w=e=>{x?x.start(e):t.progress({phase:e})};try{if(!e.values[`no-cli`]){t.signal.throwIfAborted();let e=_A(__filename,process.env);if(e.kind===`global`||e.kind===`unknown`){if(e.kind===`unknown`)return a(`Cannot identify CLI ownership; use --no-cli to install plugins while retaining this CLI.`);i.owner=e.pm,i.bin=process.argv[1]||__filename}else{w(`Installing persistent CLI`);let e=new LD(o,c);e.preflight();let n=t.effects.begin(`install.runtime`,o),r=e.install(d.default.resolve(__dirname,`..`));t.effects.confirm(n,r),i.bin=r.bin,i.owner=`ryugi`,x?.stop(`Persistent CLI installed`);let a=RD(c);a&&y.push({code:`W_PATH`,severity:`warning`,message:a})}}for(let n of v.targets){if(await new Promise(e=>setImmediate(e)),t.signal.aborted){i.targets.push({harness:n,mode:v.mode,status:`not_attempted`});continue}w(`Installing ${v.mode} into ${n}`);let r=t.effects.begin(`install.harness`,n);try{if(n===`claude-code`){let r=l.harnesses[n];if(r&&lD(r,vD)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await fA(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=cD(a.data.installed,vD);l.harnesses[n]={harness:n,mode:v.mode,version:o.version,path:o.path,nativeSource:o.source,digest:``,registration:a.data.installed},y.push(...a.warnings),b.push(...a.actions),i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:a.data.installed,disabled:a.data.disabled})}else{S||(S=e.values[`plugin-source`],S||(S=hD(o),C=!0));let r=d.default.join(o,`candidates`,(0,p.randomUUID)());try{let e=mD(S,r,v.mode);l.harnesses[n]=CD(n,e,{root:o,previous:l.harnesses[n],effects:t.effects})}finally{u.default.rmSync(r,{recursive:!0,force:!0})}i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:l.harnesses[n].path})}VD(o,l),t.effects.confirm(r),x?.stop(`${n} installed; start a new session`),y.push({code:`W_NEW_SESSION`,severity:`warning`,message:`${n}: start a new session. ${_D.find(e=>e.id===n).comments}. Comment delivery has not been verified by this installer.`})}catch(e){i.targets.push({harness:n,mode:v.mode,status:`failed`,error:e.message}),x?.stop(`${n} failed`)}}}finally{x?.stop(),C&&S&&u.default.rmSync(S,{recursive:!0,force:!0})}r||(l.selection={mode:v.mode,targets:v.targets});let T=t.effects.begin(`install.selection`,o);VD(o,l),t.effects.confirm(T);let E=Tk(await Dk({cleanup:!1,root:o},t,n));y.push(...E.warnings);let D=i.targets.filter(e=>e.status===`failed`),ee=D.length?[{kind:`command`,argv:[`ryugi`,`install`,`--mode`,v.mode,`--harness`,D.map(e=>e.harness).join(`,`),`--install-dir`,o,...e.values[`no-cli`]?[`--no-cli`]:[],...e.values[`bin-dir`]?[`--bin-dir`,c]:[],...e.values[`plugin-source`]?[`--plugin-source`,String(e.values[`plugin-source`])]:[]],label:`Retry failed targets`}]:[];return ee.push(...b,...E.actions),t.signal.aborted?J(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:ee}):J(i,D.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:D.map(e=>`${e.harness}: ${e.error}`).join(`
1094
+ `),`Installation plan`,{output:n});let r=await hk({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return xO(r)?`cancel`:r}},t);return r||ok(`Cancelled. No installation changes made.`,{output:n}),r}function yk(){return fk({output:process.stderr,onCancel:()=>{}})}function bk(e){for(let t of[`package.json`,`.codex-plugin/plugin.json`])try{let n=JSON.parse(u.default.readFileSync(d.default.join(e,t),`utf8`)),r=String(n.version??``).replace(/-(?:full|artifacts)\.[\da-f]+$/,``);if(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(r))return r}catch{}return null}function xk(e){let t=/* @__PURE__ */ new Map;return(n,r)=>{let i=JSON.stringify([n,r]);return t.has(i)||t.set(i,e(n,r)),t.get(i)}}function Sk(e,t){let n=xk(t),r=[],i;try{i=Object.values(BD(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&lD(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&cD(e.registration,n).path:e.path;if(!t)continue;let i=d.default.join(t,`skills/artifacts/app/hook-bin.sh`);if(!u.default.existsSync(i))continue;let a=bk(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!u.default.readFileSync(i,`utf8`).includes(`.ryugi/hook`)})}catch{a=!1}return{plugins:r,complete:a}}function Ck(e,t){return Sk(e,t.run).plugins}function wk(e,t,n){let r=Sk(e,t);return ED(n,r),r}function Tk(e){let t=[],n=[];if(e.status!==`done`)return{warnings:t,actions:n};for(let r of e.failed)t.push({code:`W_HOOK_BINARY`,severity:`warning`,message:`ryugi-hook ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`ryugi`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function Ek(e,t){let n=/* @__PURE__ */ new Map,r=t?1:25,i=null;return{report(a,o,s){let c=s?` ${Math.floor(Math.floor(o/s*100)/r)*r}%`:t?` ${(o/1048576).toFixed(1)} MB`:``;if(n.get(a)===c)return;n.set(a,c);let l=`Downloading ryugi-hook ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=yk()).start(l)},finish(){i?.stop(`Downloaded ryugi-hook ${[...n.keys()].join(`, `)}`)}}}async function Dk(e,t,n){let r=Ek(t,n);try{return await Ok({...e,progress:r.report})}finally{r.finish()}}function Ok(e){return kk(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function kk(e){let t=g.default.homedir(),n=ke().home;if(d.default.resolve(n)!==d.default.join(t,`.ryugi`,`server`))return{status:`other-hub`};let r=wk(e.root??jD(),e.run??vD,t);return AD({arch:process.arch,cleanup:e.cleanup,env:process.env,fetch,home:t,installed:r,platform:process.platform,progress:e.progress,retry:!0,serverHome:n,version:`1.108.7`})}const Ak=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(d.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;function jk(e,t={}){let n=[],r=new LD(e).current();if(r){let i=new LD(e,t.binDir||d.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=RD(i.binDir,t.env||process.env);n.push({component:`PATH`,status:a?`attention`:`ok`,message:a||`${i.binDir} is on PATH`});for(let e of[`dist/cli.cjs`,`dist/server.cjs`,`dist/document-engine.cjs`,`dist/viewer/index.html`,`dist/runtime/ryugi-ui.js`])n.push({component:`CLI ${e}`,status:u.default.existsSync(d.default.join(r.packageRoot,e))?`ok`:`attention`,message:d.default.join(r.packageRoot,e)})}else n.push({component:`CLI runtime`,status:`attention`,message:`No self-managed runtime; retain the current package-manager or development CLI.`});for(let r of Object.values(BD(e).harnesses))try{if(r.harness===`claude-code`){let e=d.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||d.default.join(t.home||g.default.homedir(),`.claude`),`settings.json`);if(!JSON.parse(u.default.readFileSync(e,`utf8`)).enabledPlugins?.[r.registration])throw Error(`Recorded Claude plugin is not enabled at user scope`);if(!uD(r,t.run||vD))throw Error(`Native Claude source no longer matches the record`)}else if(SD(r,xD(r.harness,{root:e,home:t.home})),!uD(r,t.run||vD))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=aD(r.path,r.registration||`ryugi@ryugi-managed`,t.env||process.env,t.home);n.push(e.blocked?{component:r.harness,status:`attention`,message:`${i}; ${e.blocked} of ${e.declared} Codex hooks are not approved for this version, so comments will not arrive. Open Codex Settings → Hooks, choose Ryugi, press Trust all, then start a new chat.`}:{component:r.harness,status:`ok`,message:`${i}; hooks trusted; new session required`});continue}n.push({component:r.harness,status:`ok`,message:`${i}; restart/new session required; delivery unverified`})}catch(e){n.push({component:r.harness,status:`attention`,message:e.message})}let i=t.home||g.default.homedir(),a=yE(process.platform,process.arch);for(let r of Ck(e,{run:t.run||vD})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.ryugi/hook; run ryugi update to refresh it`});continue}if(!a)continue;let t=d.default.join(vE(i,r.version),`ryugi-hook`);n.push(u.default.existsSync(t)?{component:e,status:`ok`,message:t}:{component:e,status:`attention`,message:`no ryugi-hook ${r.version}, so this plugin's hooks skip; run ryugi hook install ${r.version}`})}return n}function Mk(e,t={}){let n=BD(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||vD;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(![`ryugi@ryugi-dev`,`ryugi-artifacts@ryugi-dev`].includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=lD(o,i);if(e===`foreign`)throw Error(`Native Claude source changed; preserving it`);e===`owned`&&i(`claude`,[`plugin`,`uninstall`,o.registration,`--scope`,`user`])}else{if(SD(o,xD(a,{root:e,home:t.home})),!uD(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,`ryugi@ryugi-managed`]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,`ryugi@ryugi-managed`]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,`ryugi`]),a===`opencode`){let e=t.env||process.env,n=d.default.join(e.XDG_CONFIG_HOME||d.default.join(t.home||g.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!u.default.existsSync(n)||u.default.readFileSync(n,`utf8`)!==Ak(o.path))throw Error(`Plugin entry was changed; preserving ${n}`);u.default.unlinkSync(n)}u.default.rmSync(o.path,{recursive:!0})}delete n.harnesses[a],VD(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new LD(e).current();if(n){let i=new LD(e,t.binDir||d.default.dirname(n.bin));i.ownsBin()?(u.default.unlinkSync(i.bin),r.removed.push(`CLI command`)):r.failures.push({component:`CLI command`,message:`Command changed; preserving ${i.bin}`})}}return r}const Nk={name:`doctor`,summary:`Check installed CLI ownership, plugin files and native registrations`,options:{"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`}},semantic:e=>Z({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(){let t=jk(d.default.resolve(e.values[`install-dir`]||jD()));return J({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})},present:({data:e})=>({heading:`Doctor`,status:e.checks.some(e=>e.status===`attention`)?`attention`:`ok`,facts:[],sections:[{kind:`records`,key:`checks`,rows:e.checks.map(e=>({...e})),columns:[{key:`component`,required:!0},{key:`status`,required:!0},{key:`message`,required:!0}]}]})},e)},Pk={"X-Ryugi-Version":x},Fk=/<head(\s[^>]*)?>/i,Ik=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,Lk=/^<script>([\s\S]*?)<\/script>/,Rk=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function zk(e){let t=Fk.exec(e);return t?t.index+t[0].length:Ik.exec(e)?.[0].length??0}function Bk(e){let t=zk(e),n=e.slice(t);n.startsWith(`<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>`)&&(n=n.slice(153));let r=Lk.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(Rk,``)}function Vk(e,t=4){let n=0,r;try{r=u.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.isSymbolicLink())continue;let r=d.default.join(e,i.name);i.isDirectory()?t>0&&(n=Math.max(n,Vk(r,t-1))):i.isFile()&&(n=Math.max(n,u.default.statSync(r).mtimeMs))}return n}const Hk=e=>{let t=Vk(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function Uk(e){let t=/* @__PURE__ */ new Set([...Object.keys(GS),`artifact`,`source`]),n=Object.keys(e.values).find(e=>!t.has(e));if(n)throw new K({code:`E_ARGUMENT_INVALID`,message:`--${n} applies to Cloud reads only. Local reads accept --artifact, --detail or --source.`});let r=e.values.artifact;r&&lS(e.projectDir,r);let i=!!e.values.source||e.values.format===`source`;if(i&&!r)throw new K({code:`E_ARGUMENT_INVALID`,message:`Local --source requires --artifact <type>/<id>.`});let{project:a,root:o}=Ue(e.projectDir);return Z({id:`get`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`,...r?[`source`]:[]],detail:!0},async run(t,n){let s=r?{artifacts:[{type:r.split(`/`)[0],id:r.split(`/`)[1],dir:``}],warnings:[]}:ye(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=lS(a,r);if(i.content===`existing`){let e=u.default.realpathSync(i.write);if(!e.startsWith(`${o}${d.default.sep}`))throw new K({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source escapes its project: ${i.write}`});let t=u.default.statSync(e);if(!t.isFile())throw new K({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source is not a regular file: ${i.write}`});return{artifact:r,...i,bytes:t.size,modifiedAt:t.mtime.toISOString(),...n?Hk(n):{}}}return{artifact:r,...i,...n?Hk(n):{}}});c.sort((e,t)=>(t.updatedAt??``).localeCompare(e.updatedAt??``));let l,f;if(r&&(i||e.values.detail)){if(c[0]?.content!==`existing`)throw new K({code:`E_ARTIFACT_NOT_FOUND`,message:`Content not written yet: ${c[0]?.write}`});let e=u.default.readFileSync(c[0].write);l=e.toString(`utf8`),f=p.default.createHash(`sha256`).update(e).digest(`hex`),n.payloads.source=l}let[m,h]=r?.split(`/`)??[],g=s.warnings.map(e=>({code:`W_ARTIFACT_DISCOVERY`,message:e})),_=m&&ge(m)&&h&&c[0]?.content===`existing`?Qx[m].localGet:void 0,v=_?.read(o,h,c[0].write);g.push(...v?.warnings??[]);let y=l!==void 0&&!i?v?.markdown:void 0,b=y??l;return J({origin:`local`,project:a,complete:!0,...r?{}:{server:await sw()},items:c,..._&&v?.rows?{[_.key]:v.rows}:{},...b===void 0?{}:{content:b,contentFormat:y===void 0?void 0:`markdown`,sha256:f}},void 0,{warnings:g,actions:r?[q([`check`,`--project-dir`,a,`--artifact`,r],`Check`)]:[],coverage:r&&l===void 0?{omitted:[{path:`data.content`,reason:`summary`}]}:{}})},present({data:e}){return{heading:`Local artifacts`,status:`complete`,subject:e.project,facts:e.server?[{label:`Server`,binding:{key:`server`,value:`${e.server.status}${e.server.version?` · ${e.server.version}`:``}`}}]:[],sections:[{kind:`records`,key:`items`,rows:e.items,columns:[{key:`artifact`,required:!0,positional:!0},{key:`content`,positional:!0},{key:`updatedAt`,label:`Updated`,positional:!0},{key:`write`,label:`Edit`,required:!0},{key:`bytes`}]},...oe.flatMap(t=>{let n=Qx[t].localGet,r=n&&e[n.key];return n&&Array.isArray(r)?[{kind:`records`,key:n.key,rows:r,columns:n.columns}]:[]}),...e.content===void 0?[]:[{kind:`content`,key:`content`,text:e.content,title:e.contentFormat===`markdown`?`Markdown`:`Complete source`}]]}}},e)}function Wk({data:e}){let t=ge(e.type)?Qx[e.type].outlineView:void 0;return{heading:`Cloud artifact`,status:e.status===`downloaded`||e.status===`partial`?e.status:``,subject:e.id,summary:[e.type,`v${e.version}`,e.visibility].join(` · `),facts:[X(`Title`,Y(e,`title`)),...e.saved?[X(`Saved`,Y(e,`saved`),!0),X(`Bytes`,Y(e,`bytes`))]:[],...e.dir?[X(`Downloaded`,Y(e,`dir`),!0)]:e.files?[X(`Files available`,{key:`files`,value:e.files.join(`, `)})]:[]],sections:[...e.outline?[{kind:`records`,key:`outline`,...t?{rows:t.rows(e.outline),columns:t.columns}:{rows:e.outline,columns:[{key:`id`,positional:!0,required:!0},{key:`type`,positional:!0},{key:`preview`,positional:!0}]}}]:[],...e.prompt===void 0?[]:[{kind:`content`,key:`prompt`,title:Bh.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...gT(e.comments.threads,`comments`),title:`Published snapshot comments`}]:[]]}}const Gk=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,Kk=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!d.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function qk(e,t,n){if(!e.contentBase||!Array.isArray(e.files))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return a complete download manifest.`});if(e.files.some(e=>!Kk(e)))throw new K({code:`E_FILE_PATH_UNSAFE`,message:`The manifest contains an unsafe file path.`});if(u.default.existsSync(t))throw new K({code:`E_FILE_EXISTS`,message:`Download directory already exists: ${t}`});u.default.mkdirSync(d.default.dirname(t),{recursive:!0}),u.default.mkdirSync(t,{mode:448});for(let r of e.files){let i=d.default.join(t,...r.split(`/`)),a=n.effects.begin(`download`,i);try{let t=await fetch(`${e.contentBase}${r.split(`/`).map(encodeURIComponent).join(`/`)}`,{headers:Pk,signal:n.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);u.default.mkdirSync(d.default.dirname(i),{recursive:!0});let o=Buffer.from(await t.arrayBuffer()),s=Yw(i,r.endsWith(`.html`)?Bk(o.toString(`utf8`)):o);n.effects.confirm(a,{bytes:s.bytes})}catch(e){throw n.effects.set(a,`failed`,{message:e.message}),new K({code:`E_DOWNLOAD_FAILED`,message:`Could not download ${r}: ${e.message}`})}}}function Jk(e){let t=e.positionals[0];if(!t)return Uk(e);if(e.values.artifact)throw new K({code:`E_OPTION_CONFLICT`,message:`Choose a local --artifact or a Cloud link/id, not both.`});let{origin:n,id:r,grant:i}=Qk(t,(process.env.RYUGI_CLOUD_ORIGIN||`https://ryugi.innei.dev`).replace(/\/+$/,``)),a=Gk(e,`save`);if(a!==void 0&&!a.trim())throw new K({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});let o=!!e.values.source||e.values.format===`source`||a!==void 0,s=Gk(e,`block`),c=Gk(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||Gk(e,`fields`)||Gk(e,`cursor`)||Gk(e,`limit`)))throw new K({code:`E_OPTION_CONFLICT`,message:`Source must be a complete document; use --snapshot to pin its version.`});if(s&&(l||u||Gk(e,`cursor`)))throw new K({code:`E_OPTION_CONFLICT`,message:`--block reads one complete block and cannot combine with detail, cursor or download.`});let f=Gk(e,`limit`);if(f&&(!/^\d+$/.test(f)||+f<1||+f>100))throw new K({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});let p=new URLSearchParams({semantic:`1`});for(let t of[`snapshot`,`cursor`,`fields`,`limit`,`section`,`page`]){let n=Gk(e,t);n&&p.set(t,n)}return u&&p.set(`detail`,`1`),s&&p.set(`block`,s),l&&p.set(`download`,`1`),(e.values[`no-comments`]||o)&&p.set(`no-comments`,`1`),Z({id:`get`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`source`,`quiet`],requiredFields:[`id`,`type`,`visibility`,`version`,`status`,...l?[`dir`]:[],...a?[`saved`,`bytes`]:[]],fields:[`id`,`type`,`title`,`visibility`,`version`,`updatedAt`,`outline`,`files`,`content`,`comments`,`saved`,`bytes`],scalar:e=>e.saved??e.id},async run(f,m){let h=Bt(Vt(process.env,process.platform,g.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:h?{...Pk,Authorization:`Bearer ${h.token}`}:Pk,signal:m.signal}),v=await _.text();m.payloads.raw=v;let y;try{y=JSON.parse(v)}catch{throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`})}if(!_.ok)throw new K({code:_.status===404?`E_NOT_FOUND`:`E_CLOUD_FAILED`,httpStatus:_.status,message:y.error||`HTTP ${_.status}`});if(y.schema!==`ryugi.cloud-read/v1`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`});let b;if(o){if(y.type!==`document`||typeof y.content!=`string`)throw new K({code:`E_FORMAT_UNSUPPORTED`,message:`Source is available for documents only.`});m.payloads.source=y.content,a&&(b=Yw(a,y.content,m.effects),m.payloads.source=``,(e.values.source||e.values.format===`source`)&&m.diagnostic(`Saved ${b.file} (${b.bytes} bytes)`))}let{schema:x,page:S,contentBase:C,...w}=y,T={...w,...b?{saved:b.file,bytes:b.bytes}:{},status:l?`downloaded`:u||s?`read`:`available`};if(b&&delete T.content,l){T.dir=d.default.resolve(c??d.default.join(process.env.XDG_CACHE_HOME||d.default.join(g.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await qk(y,T.dir,m)}catch(e){if(!m.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=m.effects.snapshot(),J(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=m.effects.snapshot()}let E=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),D=[`get`,...E,`--snapshot`,y.snapshot],ee=[`get`,...E,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return J(T,void 0,{coverage:{page:S,...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[q([...D,`--detail`,`--`,t],`Details`)]:[],...!s&&!o&&!l&&y.page?.nextCursor?[q(ee,`More`)]:[]]})},present:Wk},e)}const Yk=/^[\w-]{1,64}$/,Xk=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,Zk=`Expected a Ryugi Cloud link (https://<host>/a/<id>) or an artifact id.`;function Qk(e,t){if(Yk.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new F(Zk)}let r=Xk.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new F(Zk);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:n.origin,id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const $k={name:`get`,summary:`Discover local artifacts, read native source, or read a published Cloud link/id`,usage:[`[--artifact <type>/<id> [--detail|--source]]`,`<link-or-id> [--out <dir>] [--no-comments] [options]`],details:`Without a link, lists local artifacts without a server or sign-in. --artifact selects local content; --detail or --source reads its complete native file, except that a document shows its heading outline and --detail reads it as markdown (--source keeps LiteXML). Cloud reads show a published outline/manifest; use --detail, --source or --download for more. Local reads never consume feedback.`,semantic:Jk,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Read this local artifact; omit to discover local artifacts`},section:{type:`string`,value:`<outline|files>`,help:`Choose the independently paginated collection`},source:{type:`boolean`,help:`Print complete native source locally, or complete LiteXML from Cloud`},download:{type:`boolean`,help:`Download the complete published manifest`},save:{type:`string`,value:`<file>`,help:`Save complete Cloud document source to a new file; supports structured output`},block:{type:`string`,value:`<id>`,help:`Read one published document block`},page:{type:`string`,value:`<pageId>`,help:`Read one page of a published whiteboard`},snapshot:{type:`string`,value:`<token>`,help:`Pin a published version`},cursor:{type:`string`,value:`<token>`,help:`Continue a manifest or outline page`},limit:{type:`string`,value:`<1-100>`,help:`Maximum outline or manifest rows`},out:{type:`string`,value:`<dir>`,help:`Download files here instead of ~/.cache/ryugi/get/<id>/`},"no-comments":{type:`boolean`,help:`Leave a document's comments out`}},positionals:1};function eA({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[X(`Version`,Y(e,`version`))],sections:[]}}const tA={name:`hook`,summary:`Download the ryugi-hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads ryugi-hook for this platform from the plugin release of <version>, checks its sha256 and keeps it in ~/.ryugi/hook/<version>. The plugin launcher runs it with --background when a hook finds no binary; that waits out the retry delay after a failed download, which a person running it skips.`,positionals:2,options:{background:{type:`boolean`,help:`Wait out the retry delay after a failed download`}},semantic:e=>Z({id:`hook`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},async run(){let[t,n]=e.positionals;if(t!==`install`)throw new F(`Usage: ryugi hook install <version>`);if(!n||!mE(n))throw new F(`hook install needs a release version, not ${n??`nothing`}`);let r=await CE({arch:process.arch,fetch,home:g.default.homedir(),platform:process.platform,retry:!e.values.background,version:n}),i=r.status===`present`||r.status===`installed`,a={action:t,version:n,status:r.status};return r.error&&(a.error=r.error),J(a,i?{kind:`succeeded`}:{kind:`failed`,error:{code:`E_HOOK_INSTALL`,message:r.error??`ryugi-hook ${n} is not available here (${r.status})`}})},present:eA},e)},nA=`Innei/ryugi`,rA={artifacts:`ryugi-artifacts@ryugi-dev`,full:`ryugi@ryugi-dev`};function iA(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function aA(e){let{command:t,args:n,shell:r}=iA(e);return(0,f.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function oA(e){let t=aA(e);if(t.error||t.status!==0)throw Error(`claude ${e.join(` `)} failed: ${(t.stderr||t.stdout||t.error?.message||``).trim()}`);return t.stdout}function sA(){let e=aA([`--version`]);return!e.error&&e.status===0}function cA(e){if(!u.default.existsSync(e))return{};let t=JSON.parse(u.default.readFileSync(e,`utf8`)).enabledPlugins;return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function lA(){let e=JSON.parse(oA([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===`ryugi-dev`)}function uA(e){let t=JSON.parse(oA([`plugin`,`list`,`--json`]));if(!Array.isArray(t))throw Error(`claude plugin list returned no list`);return t.some(t=>t?.id===e&&t?.scope===`user`)}const dA=e=>e===`artifacts`||e===`full`;async function fA(e,t,n){let r=e=>J({mode:null,harness:`claude-code`,installed:null,disabled:[]},{kind:`validation_failed`},{warnings:[{code:`W_INSTALL_MODE`,message:e,severity:`error`}]});if(e!==void 0&&!dA(e))return r(`--mode takes artifacts or full`);if(!sA())return J({mode:dA(e)?e:null,harness:`none`,installed:null,disabled:[]},{kind:`succeeded`},{warnings:[{code:`W_NO_CLAUDE_CODE`,message:`Claude Code was not found; artifacts only is Claude Code only. Install the full plugin by hand on other harnesses.`,severity:`warning`}],actions:[{kind:`url`,label:`Install guide`,url:`https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||d.default.join(g.default.homedir(),`.claude`),a=cA(d.default.join(i,`settings.json`));if(!dA(e))return r(`--mode artifacts|full is required`);let o=e,s=rA[o],c=rA[o===`artifacts`?`full`:`artifacts`],l=(e,t,r)=>{let i=n?.begin(e,t);oA(r),i!==void 0&&n.confirm(i)};lA()||l(`install.marketplace`,nA,[`plugin`,`marketplace`,`add`,nA,`--scope`,`user`]),l(`install.refresh`,`ryugi-dev`,[`plugin`,`marketplace`,`update`,`ryugi-dev`]),uA(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];a[c]===!0&&(l(`install.disable`,c,[`plugin`,`disable`,c,`--scope`,`user`]),u.push(c));let f=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]])cA(d.default.join(t,`.claude`,n))[c]===!0&&(f.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${c} is still enabled at ${e} scope; enable only one Ryugi entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,c,`--scope`,e],label:`Disable at ${e} scope`}));return J({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:f,actions:p})}const pA=`ryugi-artifacts`,mA=[`npm`,`pnpm`,`yarn`,`bun`],hA=[[`npx`,[`/_npx/`]],[`pnpm dlx`,[`/pnpm/dlx/`,`/.pnpm-store/dlx/`]],[`bunx`,[`/bunx-`,`/.bun/install/cache/`]]],gA=[[`pnpm`,[`/pnpm/global/`]],[`yarn`,[`/yarn/global/`]],[`bun`,[`/.bun/install/global/`]],[`npm`,[`/lib/node_modules/${pA}/`,`/npm/node_modules/${pA}/`]]];function _A(e,t){if(t.RYUGI_MANAGED_RUNTIME===`1`&&t.RYUGI_INSTALL_ROOT){let n=d.default.relative(d.default.join(t.RYUGI_INSTALL_ROOT,`versions`),e);if(n&&!n.startsWith(`..`)&&!d.default.isAbsolute(n))return{kind:`managed`}}if(t.RYUGI_ARTIFACTS_COMMAND)return{kind:`launcher`};let n=e;try{n=u.default.realpathSync(e)}catch{}let r=n.replaceAll(`\\`,`/`).toLowerCase(),i=e=>e.some(e=>r.includes(e));for(let[e,t]of hA)if(i(t))return{kind:`transient`,runner:e};for(let[e,t]of gA)if(i(t))return{kind:`global`,pm:e};return r.includes(`/node_modules/`)?{kind:`unknown`}:{kind:`local`}}async function vA(e,t,n=!1,r=!1){let i={bin:null,mode:null,owner:null,targets:[]},a=e=>J(i,{kind:`validation_failed`},{warnings:[{code:`E_INSTALL_PLAN`,message:e,severity:`error`}]}),o=d.default.resolve(e.values[`install-dir`]||jD()),s=new LD(o).current(),c=d.default.resolve(e.values[`bin-dir`]||(s?d.default.dirname(s.bin):MD())),l=BD(o);if(e.values.mode!==void 0&&![`artifacts`,`full`].includes(String(e.values.mode)))return a(`--mode takes artifacts or full`);let f=(e.values.harness===`none`?[]:yD()).filter(e=>e.detected).map(e=>e.id),m={...l.harnesses},h=d.default.join(process.env.CLAUDE_CONFIG_DIR||d.default.join(g.default.homedir(),`.claude`),`settings.json`);if(!m[`claude-code`]&&f.includes(`claude-code`)&&u.default.existsSync(h)){let e=JSON.parse(u.default.readFileSync(h,`utf8`)).enabledPlugins||{},t=e[`ryugi@ryugi-dev`]===!0?`full`:e[`ryugi-artifacts@ryugi-dev`]===!0?`artifacts`:null;t&&(m[`claude-code`]={harness:`claude-code`,mode:t,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:f,previous:m,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=gk({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await vk(_,t)}else v=gk({mode:e.values.mode,harness:e.values.harness},_)}catch(e){return a(e.message)}if(!v)return J(i,{kind:`interrupted`,signal:`SIGINT`});i.mode=v.mode;let y=[],b=[],x=n?yk():null,S,C=!1,w=e=>{x?x.start(e):t.progress({phase:e})};try{if(!e.values[`no-cli`]){t.signal.throwIfAborted();let e=_A(__filename,process.env);if(e.kind===`global`||e.kind===`unknown`){if(e.kind===`unknown`)return a(`Cannot identify CLI ownership; use --no-cli to install plugins while retaining this CLI.`);i.owner=e.pm,i.bin=process.argv[1]||__filename}else{w(`Installing persistent CLI`);let e=new LD(o,c);e.preflight();let n=t.effects.begin(`install.runtime`,o),r=e.install(d.default.resolve(__dirname,`..`));t.effects.confirm(n,r),i.bin=r.bin,i.owner=`ryugi`,x?.stop(`Persistent CLI installed`);let a=RD(c);a&&y.push({code:`W_PATH`,severity:`warning`,message:a})}}for(let n of v.targets){if(await new Promise(e=>setImmediate(e)),t.signal.aborted){i.targets.push({harness:n,mode:v.mode,status:`not_attempted`});continue}w(`Installing ${v.mode} into ${n}`);let r=t.effects.begin(`install.harness`,n);try{if(n===`claude-code`){let r=l.harnesses[n];if(r&&lD(r,vD)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await fA(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=cD(a.data.installed,vD);l.harnesses[n]={harness:n,mode:v.mode,version:o.version,path:o.path,nativeSource:o.source,digest:``,registration:a.data.installed},y.push(...a.warnings),b.push(...a.actions),i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:a.data.installed,disabled:a.data.disabled})}else{S||(S=e.values[`plugin-source`],S||(S=hD(o),C=!0));let r=d.default.join(o,`candidates`,(0,p.randomUUID)());try{let e=mD(S,r,v.mode);l.harnesses[n]=CD(n,e,{root:o,previous:l.harnesses[n],effects:t.effects})}finally{u.default.rmSync(r,{recursive:!0,force:!0})}i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:l.harnesses[n].path})}VD(o,l),t.effects.confirm(r),x?.stop(`${n} installed; start a new session`),y.push({code:`W_NEW_SESSION`,severity:`warning`,message:`${n}: start a new session. ${_D.find(e=>e.id===n).comments}. Comment delivery has not been verified by this installer.`})}catch(e){i.targets.push({harness:n,mode:v.mode,status:`failed`,error:e.message}),x?.stop(`${n} failed`)}}}finally{x?.stop(),C&&S&&u.default.rmSync(S,{recursive:!0,force:!0})}r||(l.selection={mode:v.mode,targets:v.targets});let T=t.effects.begin(`install.selection`,o);VD(o,l),t.effects.confirm(T);let E=Tk(await Dk({cleanup:!1,root:o},t,n));y.push(...E.warnings);let D=i.targets.filter(e=>e.status===`failed`),ee=D.length?[{kind:`command`,argv:[`ryugi`,`install`,`--mode`,v.mode,`--harness`,D.map(e=>e.harness).join(`,`),`--install-dir`,o,...e.values[`no-cli`]?[`--no-cli`]:[],...e.values[`bin-dir`]?[`--bin-dir`,c]:[],...e.values[`plugin-source`]?[`--plugin-source`,String(e.values[`plugin-source`])]:[]],label:`Retry failed targets`}]:[];return ee.push(...b,...E.actions),t.signal.aborted?J(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:ee}):J(i,D.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:D.map(e=>`${e.harness}: ${e.error}`).join(`
1095
1095
  `)}}:{kind:`succeeded`},{warnings:y,actions:ee})}function yA({data:e}){return{heading:`Install`,status:e.targets.some(e=>e.status===`failed`)?`partial`:`installed`,summary:e.mode||``,facts:[X(`Command`,Y(e,`bin`)),X(`Owner`,Y(e,`owner`))],sections:[{kind:`records`,key:`targets`,title:`Harnesses`,rows:e.targets.map(e=>({...e})),columns:[{key:`harness`,required:!0},{key:`status`,required:!0},{key:`installed`},{key:`error`}]}]}}const bA={name:`install`,summary:`Install persistent CLI and Artifacts or full Ryugi into selected harnesses`,usage:[`[--mode artifacts|full] [--harness <targets|none>] [options]`],details:`Interactive terminal wizard; automation requires explicit mode and targets (or reuses recorded selections). --harness none installs only the CLI.`,options:{mode:{type:`string`,value:`artifacts|full`,help:`Content mode`},harness:{type:`string`,value:`<targets|none>`,help:`Comma-separated claude-code,codex,cursor,gemini,opencode,pi,copilot,agy; none for CLI only`},yes:{type:`boolean`,help:`Apply an explicit or recorded plan without terminal confirmation`},"no-cli":{type:`boolean`,help:`Keep the current CLI; install only harness plugins`},"install-dir":{type:`string`,value:`<path>`,help:`Managed runtime and installation state directory`},"bin-dir":{type:`string`,value:`<path>`,help:`Command directory (default ~/.local/bin)`},"plugin-source":{type:`string`,value:`<path>`,help:`Use an existing Ryugi plugin checkout (offline or development)`}},semantic(e){return{run(t,n,r,i){return Z({id:`install`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.bin},run:(n,r)=>vA(e,r,t.format===`brief`&&!!process.stdin.isTTY&&!!process.stderr.isTTY&&!process.env.CI),present:yA},e).run(t,n,r,i)}}}},xA=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function SA(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{let t=new URL(e);return t.protocol===`file:`?null:t.pathname}catch{return null}return xA.exec(e)?.[1]??null}function CA(e){let t=SA(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function wA(e){try{return CA((0,f.execFileSync)(`git`,[`-C`,e,`remote`,`get-url`,`origin`],{encoding:`utf8`,timeout:2e3,stdio:[`ignore`,`pipe`,`ignore`],env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}))??d.default.basename(e)}catch{return d.default.basename(e)}}var TA=`# Module vocabulary
1096
1096
 
1097
1097
  Edit \`<project>/.ryugi/modules.json\`. A module is a lasting business area, such as billing or sharing, not a file, flag, task or ticket. Read the file immediately before edits and preserve unrelated modules and stable IDs.
@@ -1131,5 +1131,5 @@ Results:
1131
1131
  name_clash the directory holds something else; nothing written. Pull it under another name with --as
1132
1132
  failed a download or write failed; the local copy is as it was
1133
1133
 
1134
- Local comments.json, marks/ and dotfiles are kept. A document gets the published comments only when it has no comments.json.`,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Pull only the Cloud copy this local artifact is bound to`},project:{type:`string`,value:`<owner/repo>`,help:`Pull another project’s artifacts; they keep publishing under it`},as:{type:`string`,value:`<id>`,help:`With one target: the local id to pull it under`},"dry-run":{type:`boolean`,help:`Report what each artifact would do; write nothing`},force:{type:`boolean`,help:`Take the Cloud version over local edits (conflict) or an unbound directory`}}};function Yj(e){for(let t of Me(e))u.default.rmSync(d.default.join(Ne(t.dir),`.state`,`server-info`),{force:!0})}function Xj({data:e}){return{heading:`Server`,status:e.status,summary:e.status===e.reason?``:e.reason.replaceAll(`_`,` `),facts:[X(`Scope`,Y(e,`scope`)),X(`Artifacts`,Y(e,`artifacts`))],sections:[]}}async function Zj(){let e=ke(),t=t=>{u.default.rmSync(e.info,{force:!0}),Yj(e.projects),u.default.mkdirSync(e.home,{recursive:!0,mode:448}),u.default.writeFileSync(e.stopped,`${JSON.stringify({reason:t,timestamp:Math.floor(Date.now()/1e3)})}\n`)};if(et(e.pid)===null)return{status:`not_running`};let n=Number(et(e.pid)),r=et(e.serverId)??``;if(!Number.isInteger(n)||n<=0||!/^[\w-]{32,64}$/.test(r)||!Qe(n,r))return u.default.rmSync(e.pid,{force:!0}),u.default.rmSync(e.serverId,{force:!0}),t(`stale_pid`),{status:`stale_pid`};t(`stop`),Ve(e,{action:`stopped`,pid:n,running:et(e.version)??``,cli:process.env.RYUGI_ARTIFACTS_VERSION||`1.108.6`});try{process.kill(n,`SIGTERM`)}catch{}if(!await $e(n,7e3)){try{process.kill(n,`SIGKILL`)}catch{}await $e(n,1e3)}if(Je(n))return u.default.rmSync(e.stopped,{force:!0}),{status:`failed`,error:`process still running`};for(let t of[e.pid,e.serverId])u.default.rmSync(t,{force:!0});return t(`stop`),{status:`stopped`}}const Qj={name:`stop`,summary:`Stop this machine's artifacts server; the artifacts are kept`,usage:[`[options]`],options:{},semantic:e=>Z({id:`stop`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.status},async run(e,t){let n=t.effects.begin(`stop`,`machine`),r=await Zj();return r.status!==`failed`&&t.effects.set(n,r.status===`not_running`?`none`:`confirmed`),J({status:r.status===`stopped`?`stopped`:r.status===`failed`?`failed`:`unchanged`,reason:r.status,scope:`machine`,artifacts:`kept`},r.status===`failed`?{kind:`failed`,error:{code:`E_SERVER_STOP_FAILED`,message:r.error}}:{kind:`succeeded`})},present:Xj},e)};function $j({data:e}){return{heading:`Uninstall`,status:e.failures.length?`partial`:`removed`,facts:[X(`Removed`,{key:`removed`,value:e.removed.join(`, `)}),X(`Preserved`,{key:`preserved`,value:e.preserved.join(` `)})],sections:[{kind:`records`,key:`failures`,rows:e.failures,columns:[{key:`component`,required:!0},{key:`message`,required:!0}]}]}}const eM={name:`uninstall`,summary:`Remove recorded integrations and owned command; keep artifacts and data`,options:{"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`},harness:{type:`string`,value:`<targets>`,help:`Only remove these comma-separated harnesses; keep CLI`}},semantic:e=>Z({id:`uninstall`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(t,n){let r=typeof e.values.harness==`string`?e.values.harness.split(`,`).map(zD):void 0;if(r?.some(e=>!_D.some(t=>t.id===e)))return J({removed:[],preserved:[],failures:[]},{kind:`validation_failed`},{warnings:[{code:`E_HARNESS`,severity:`error`,message:`Unknown harness selection`}]});let i=d.default.resolve(e.values[`install-dir`]||jD()),a=n.effects.begin(`uninstall`,i),o=Mk(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),J(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:$j},e)};function tM(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++)if(n[e]!==r[e])return n[e]>r[e];return!1}const nM=e=>d.default.join(e.XDG_CACHE_HOME||d.default.join(g.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function rM(e,t,n){try{u.default.mkdirSync(d.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}`;u.default.writeFileSync(r,JSON.stringify({version:t,checkedAt:n})),u.default.renameSync(r,e)}catch{}}const iM=`ryugi-artifacts`;function aM(e,t){let n=`${iM}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,n]:e===`yarn`?[`global`,`add`,n]:[`add`,`-g`,n]}}const oM=({cmd:e,args:t})=>[e,...t].join(` `);async function sM(e){let t=e.endsWith(`/`)?e:`${e}/`;try{let e=await fetch(new URL(`${iM}/latest`,t),{signal:AbortSignal.timeout(1e4)}),{version:n}=await e.json();if(e.ok&&typeof n==`string`&&/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(n))return n;throw Error(`registry returned ${e.status}`)}catch(e){throw new F(`Could not get the latest ${iM} version from ${t}: ${e.message}`)}}function cM(e,t){return e.kind===`transient`?`You ran ${iM} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${iM}@latest\` to get ${t}.`:e.kind===`local`?"This is a local build from a Ryugi checkout. Update it with `git pull`, then `pnpm build` in artifacts/.":e.kind===`launcher`?`Release cache refreshed to ${t}. Run the returned start command through the launcher to install it and replace the running server.`:null}var lM=class extends F{};async function uM(e,t){if(!FE[process.platform]?.includes(process.arch))return;let n=KE(),r,i=await RE({...n,version:e,serverHome:ke().home},uE(lE()),()=>{r=t.effects.begin(`update.daemon`,IE(n.home).binary)}).catch(e=>({status:`failed`,error:e.message}));if(i.status!==`not-installed`&&i.status!==`other-hub`)return i.status===`updated`&&r!==void 0&&t.effects.confirm(r,{from:i.from,to:i.to}),i}async function dM(e,t={}){if(e.pm!==void 0&&!mA.includes(e.pm))throw new F(`--pm must be one of ${mA.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:_A(e.file,e.env),r=await sM(e.registry);t.beforeCache?.(),rM(nM(e.env),r,Date.now()),t.cacheRefreshed?.();let i={type:`update-check`,current:e.current,latest:r,install:n.kind};if(!tM(r,e.current))return{...i,upToDate:!0,command:null};if(n.kind===`unknown`){let t=mA.map(e=>` ${oM(aM(e,r))}`).join(`
1135
- `);throw new lM(`Could not tell how ${iM} was installed (${e.file}). Install ${r} with one of:\n${t}\nor run \`${iM} update --pm <${mA.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...i,upToDate:!1,command:`ryugi update`};let n=jD(e.env),a=new LD(n).current();if(!a)throw new F(`Managed runtime state is missing; run ryugi doctor.`);let o=new LD(n,d.default.dirname(a.bin)),s=d.default.join(n,`downloads`,`runtime-${(0,p.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(r):(u.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${iM}@${r}`),vD(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${iM}@${r}`]),n=d.default.join(s,`node_modules`,iM)),o.install(n),{type:`updated`,from:e.current,to:r,pm:`ryugi`,command:`ryugi update`}}finally{u.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...i,upToDate:!1,command:null,message:cM(n,r)};let a=aM(n.pm,r);if(e.check)return{...i,upToDate:!1,command:oM(a)};let o=process.platform===`win32`;t.beforeInstall?.();let s=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],c=o?(0,f.spawnSync)(oM(a),{stdio:[...s],env:e.env,shell:!0}):(0,f.spawnSync)(a.cmd,a.args,{stdio:[...s],env:e.env});if(c.stdout?.length&&t.log?.(c.stdout.toString()),c.stderr?.length&&t.log?.(c.stderr.toString()),c.error)throw new F(`Could not run ${oM(a)}: ${c.error.message}`);if(c.status!==0)throw new F(`${oM(a)} exited with ${c.status??c.signal}`);return{type:`updated`,from:e.current,to:r,pm:n.pm,command:oM(a)}}const fM={name:`update`,summary:`Update the CLI through its original owner, then refresh recorded harness integrations and the daemon`,options:{check:{type:`boolean`,help:`Compare CLI versions only; do not install`},"cli-only":{type:`boolean`,help:`Update CLI without refreshing harness plugins`},"plugins-only":{type:`boolean`,help:`Refresh recorded plugins without updating CLI or daemon`},"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`},"plugin-source":{type:`string`,value:`<path>`,help:`Plugin checkout for offline/development refresh`},pm:{type:`string`,value:`<npm|pnpm|yarn|bun>`,help:`Use this package manager instead of detecting it`}},semantic:e=>Z({id:`update`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`current`,`latest`,`install`,`status`,`installed`,`message`,`command`,`plugins`,`daemon`]},async run(t,n){if(e.values[`cli-only`]&&e.values[`plugins-only`])throw new F(`Choose --cli-only or --plugins-only`);let r,i,a;try{a=e.values[`plugins-only`]?{type:`update-check`,current:`1.108.6`,latest:`1.108.6`,install:_A(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await dM({current:`1.108.6`,file:__filename,env:process.env,registry:process.env.npm_config_registry||`https://registry.npmjs.org/`,check:!!e.values.check,pm:e.values.pm},{beforeCache(){i=n.effects.begin(`release-cache`,nM(process.env))},cacheRefreshed(){i!==void 0&&n.effects.confirm(i)},beforeInstall(){r=n.effects.begin(`install`,iM)},log:n.diagnostic})}catch(e){throw e instanceof lM?new K({code:`E_INSTALL_UNKNOWN`,message:e.message},`action_required`):e}a.type===`updated`&&r!==void 0&&n.effects.confirm(r,{from:a.from,to:a.to});let o=a.type===`updated`?{current:a.to,latest:a.to,install:a.pm===`ryugi`?`managed`:`global`,status:`updated`,installed:!0,command:a.command}:{current:a.current,latest:a.latest,install:a.install,status:a.upToDate?`up_to_date`:`available`,installed:!1,command:a.command,...a.message?{message:a.message}:{}},s=d.default.resolve(e.values[`install-dir`]||jD());if(!e.values.check&&!e.values[`cli-only`]){o.plugins=[];for(let t of Object.values(BD(s).harnesses)){let r=await vA({projectDir:e.projectDir,positionals:[],values:{mode:t.mode,harness:t.harness,"no-cli":!0,"install-dir":s,"plugin-source":e.values[`plugin-source`]}},n,!1,!0),i=r.data.targets.find(e=>e.harness===t.harness);o.plugins.push({harness:t.harness,mode:t.mode,status:i?.status||`failed`,error:i?.error||(r.completion.kind===`succeeded`?void 0:r.warnings.map(e=>e.message).join(`; `))})}}if(!e.values.check&&!e.values[`plugins-only`]&&o.status!==`available`){let e=await uM(o.current,n);e&&(o.daemon=e)}let c=e.values.check?{warnings:[],actions:[]}:Tk(await Dk({cleanup:!0,root:s},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return J(o,o.plugins?.some(e=>e.status!==`installed`)||o.daemon?.status===`failed`?{kind:`partial`}:void 0,{effects:n.effects.snapshot(),warnings:c.warnings,actions:[...o.install===`launcher`&&o.status===`available`?[q([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...c.actions]})},present:pM},e)};function pM({data:e}){return{heading:`Update`,status:e.status,facts:[X(`Current`,Y(e,`current`),!0),X(`Latest`,Y(e,`latest`)),X(`Install`,Y(e,`install`)),...e.message?[X(`Advice`,Y(e,`message`))]:[],...e.daemon?[X(`Daemon`,{key:`daemon`,value:e.daemon.status===`updated`?`updated ${e.daemon.from} → ${e.daemon.to}`:e.daemon.status===`failed`?`failed: ${e.daemon.error}`:e.daemon.status===`not-running`?`not running; start it to update it`:`current`})]:[]],sections:e.plugins?.length?[{kind:`records`,key:`plugins`,title:`Harnesses`,rows:e.plugins.map(e=>({...e})),columns:[{key:`harness`,required:!0},{key:`mode`,required:!0},{key:`status`,required:!0},{key:`error`}]}]:[]}}const mM=[nw,Qj,VT,Uj,Jj,ww,Rw,bw,YA,iE,IT,Hw,$k,sE,fM,bA,Nk,$E,tA,eM];function hM(e){return(t,n,r)=>{let i=[`--project-dir`,e.projectDir],a=typeof e.values.artifact==`string`?e.values.artifact:void 0,o=[...i,...a?[`--artifact`,a]:[]];if(r.some(e=>e.state===`unknown`)){let e;if(t.startsWith(`comment`)&&a)e=[`comment`,`list`,...o,...a.startsWith(`verify/`)?[]:[`--sections`,`all`,...t.endsWith(`.ack`)?[]:[`--all`],`--detail`]];else if(t.startsWith(`changes`))e=[`changes`,...o,`--detail`];else if(t.startsWith(`publish`))e=[`publish`,`--list`,...i,...a&&r.some(e=>[`share-key`,`revoke-key`].includes(e.operation)&&e.state===`unknown`)?[`--artifact`,a]:[]];else if(t===`config`)e=[`config`,...i];else if(t.startsWith(`modules`))e=[`modules`,...o];else if(t===`update`)e=[`--version`];else if(t===`install`)return[{kind:`command`,argv:[`claude`,`plugin`,`list`,`--json`],label:`Verify state`,reason:`Inspect installed plugins before any retry; an operation may already have completed.`}];else e=[`get`,...i];return[{...q(e,`Verify state`),reason:`Inspect current state before any retry; an operation may already have completed.`}]}return n?.code===`E_SERVER_NOT_RUNNING`||n?.code===`E_SERVER_UNREACHABLE`?[q([`start`,`--background`,`--no-open`,...o],`Start server`)]:n?.code===`E_ARGUMENT_INVALID`||n?.code===`E_OPTION_CONFLICT`?[q([t.split(`.`)[0],...e.positionals[0]&&t.startsWith(`comment`)?[e.positionals[0]]:[],`--help`],`Help`)]:n?cC(n):[]}}async function gM(e,t,n,r){return wC({id:e,mode:`finite`,output:{formats:[n.format]},run(){throw t},present(){return{heading:`Error`,status:`failed`,facts:[],sections:[]}}},void 0,{...n,fields:void 0,detail:!1},r)}function _M(e,t){return{id:e,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`text`,`version`,`capabilities`,`commands`]},run(){return J(t)},present({data:e}){return e.version?{heading:`ryugi ${e.version}`,status:``,facts:[],sections:[]}:{heading:`Help`,status:``,facts:[],sections:[{kind:`content`,key:`text`,text:e.text}]}}}}async function vM(e,t,n,r,i,a,o){let[s,...c]=e,l=t.find(e=>e.name===s),d;try{if(l?.positionals&&l.usage?.some(e=>/^[a-z]+\s/.test(e))&&(d=qS(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return qS(c,{},0),await Z(_M(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&JS(c)){l||qS(c,{},0);let e=l?QS(l,d):$S(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=qS(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=cS():typeof t.values.artifact==`string`&&(e+=`\n\n${sS(t.values.artifact)}`)}return await Z(_M(`help`,{text:e,commands:t.map(({name:e,summary:t})=>({name:e,summary:t}))}),void 0).run(i,a)}if(!l&&(!s||s.startsWith(`-`)||(()=>{try{return u.default.statSync(s).isDirectory()}catch{return!1}})())){let t=qS(e,n,1);if(t.positionals.length&&t.values[`project-dir`])throw new K({code:`E_ARGUMENT_INVALID`,message:`Specify one project directory.`});return t.projectDir=t.values[`project-dir`]??t.positionals[0]??t.projectDir,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await AC(t,`browse`).run(i,a,o)}if(!l)throw new K({code:s?.includes(`/`)?`E_PROJECT_NOT_FOUND`:`E_UNKNOWN_COMMAND`,message:s?`Unknown command: ${s}`:`Use start --foreground to browse with semantic output.`});let f;try{f=qS(c,ZS(l,d),l.positionals)}catch(e){throw new K({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=Ue(f.projectDir).project,await l.semantic(f).run(i,a,o,hM(f))}catch(e){let t=e instanceof F?new K({code:`E_ARGUMENT_INVALID`,message:e.message}):e;return t instanceof Error&&Object.assign(t,{actions:[q([...l?[l.name,...d&&l.usage?.some(e=>e.startsWith(`${d} `))?[d]:[]]:[],`--help`],`Help`)]}),gM(l?.name??s??`browse`,t,i,a)}}function yM(e=process.stdout,t=process.stderr){let n=/* @__PURE__ */ new WeakMap;for(let r of[e,t])r.on(`error`,e=>n.set(r,e));return{write(r,i){let a=r===`stdout`?e:t,o=n.get(a);return o?Promise.reject(o):new Promise((e,t)=>a.write(i,n=>n?t(n):e()))}}}function bM(e){process.exitCode=e}const xM={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function SM(e){w(`cli`);let t=Object.assign({},GS,...mM.map(e=>e.options)),n=yM(),r;try{r=LS(e,t,US(e,t))}catch(r){return gM(e[0]??`browse`,r,LS(e,t).options,n)}if(r.error)return gM(e[0]??`browse`,r.error,r.options,n);let i=new AbortController,a=()=>i.abort(`SIGINT`),o=()=>i.abort(`SIGTERM`);process.on(`SIGINT`,a),process.on(`SIGTERM`,o);try{return await vM(e,mM,xM,`1.108.6`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}SM(process.argv.slice(2)).then(bM,e=>gM(process.argv[2]??`browse`,e,{format:`brief`},yM()).then(bM));
1134
+ Local comments.json, marks/ and dotfiles are kept. A document gets the published comments only when it has no comments.json.`,options:{artifact:{type:`string`,value:`<type>/<id>`,help:`Pull only the Cloud copy this local artifact is bound to`},project:{type:`string`,value:`<owner/repo>`,help:`Pull another project’s artifacts; they keep publishing under it`},as:{type:`string`,value:`<id>`,help:`With one target: the local id to pull it under`},"dry-run":{type:`boolean`,help:`Report what each artifact would do; write nothing`},force:{type:`boolean`,help:`Take the Cloud version over local edits (conflict) or an unbound directory`}}};function Yj(e){for(let t of Me(e))u.default.rmSync(d.default.join(Ne(t.dir),`.state`,`server-info`),{force:!0})}function Xj({data:e}){return{heading:`Server`,status:e.status,summary:e.status===e.reason?``:e.reason.replaceAll(`_`,` `),facts:[X(`Scope`,Y(e,`scope`)),X(`Artifacts`,Y(e,`artifacts`))],sections:[]}}async function Zj(){let e=ke(),t=t=>{u.default.rmSync(e.info,{force:!0}),Yj(e.projects),u.default.mkdirSync(e.home,{recursive:!0,mode:448}),u.default.writeFileSync(e.stopped,`${JSON.stringify({reason:t,timestamp:Math.floor(Date.now()/1e3)})}\n`)};if(et(e.pid)===null)return{status:`not_running`};let n=Number(et(e.pid)),r=et(e.serverId)??``;if(!Number.isInteger(n)||n<=0||!/^[\w-]{32,64}$/.test(r)||!Qe(n,r))return u.default.rmSync(e.pid,{force:!0}),u.default.rmSync(e.serverId,{force:!0}),t(`stale_pid`),{status:`stale_pid`};t(`stop`),Ve(e,{action:`stopped`,pid:n,running:et(e.version)??``,cli:process.env.RYUGI_ARTIFACTS_VERSION||`1.108.7`});try{process.kill(n,`SIGTERM`)}catch{}if(!await $e(n,7e3)){try{process.kill(n,`SIGKILL`)}catch{}await $e(n,1e3)}if(Je(n))return u.default.rmSync(e.stopped,{force:!0}),{status:`failed`,error:`process still running`};for(let t of[e.pid,e.serverId])u.default.rmSync(t,{force:!0});return t(`stop`),{status:`stopped`}}const Qj={name:`stop`,summary:`Stop this machine's artifacts server; the artifacts are kept`,usage:[`[options]`],options:{},semantic:e=>Z({id:`stop`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.status},async run(e,t){let n=t.effects.begin(`stop`,`machine`),r=await Zj();return r.status!==`failed`&&t.effects.set(n,r.status===`not_running`?`none`:`confirmed`),J({status:r.status===`stopped`?`stopped`:r.status===`failed`?`failed`:`unchanged`,reason:r.status,scope:`machine`,artifacts:`kept`},r.status===`failed`?{kind:`failed`,error:{code:`E_SERVER_STOP_FAILED`,message:r.error}}:{kind:`succeeded`})},present:Xj},e)};function $j({data:e}){return{heading:`Uninstall`,status:e.failures.length?`partial`:`removed`,facts:[X(`Removed`,{key:`removed`,value:e.removed.join(`, `)}),X(`Preserved`,{key:`preserved`,value:e.preserved.join(` `)})],sections:[{kind:`records`,key:`failures`,rows:e.failures,columns:[{key:`component`,required:!0},{key:`message`,required:!0}]}]}}const eM={name:`uninstall`,summary:`Remove recorded integrations and owned command; keep artifacts and data`,options:{"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`},harness:{type:`string`,value:`<targets>`,help:`Only remove these comma-separated harnesses; keep CLI`}},semantic:e=>Z({id:`uninstall`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(t,n){let r=typeof e.values.harness==`string`?e.values.harness.split(`,`).map(zD):void 0;if(r?.some(e=>!_D.some(t=>t.id===e)))return J({removed:[],preserved:[],failures:[]},{kind:`validation_failed`},{warnings:[{code:`E_HARNESS`,severity:`error`,message:`Unknown harness selection`}]});let i=d.default.resolve(e.values[`install-dir`]||jD()),a=n.effects.begin(`uninstall`,i),o=Mk(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),J(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:$j},e)};function tM(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++)if(n[e]!==r[e])return n[e]>r[e];return!1}const nM=e=>d.default.join(e.XDG_CACHE_HOME||d.default.join(g.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function rM(e,t,n){try{u.default.mkdirSync(d.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}`;u.default.writeFileSync(r,JSON.stringify({version:t,checkedAt:n})),u.default.renameSync(r,e)}catch{}}const iM=`ryugi-artifacts`;function aM(e,t){let n=`${iM}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,n]:e===`yarn`?[`global`,`add`,n]:[`add`,`-g`,n]}}const oM=({cmd:e,args:t})=>[e,...t].join(` `);async function sM(e){let t=e.endsWith(`/`)?e:`${e}/`;try{let e=await fetch(new URL(`${iM}/latest`,t),{signal:AbortSignal.timeout(1e4)}),{version:n}=await e.json();if(e.ok&&typeof n==`string`&&/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(n))return n;throw Error(`registry returned ${e.status}`)}catch(e){throw new F(`Could not get the latest ${iM} version from ${t}: ${e.message}`)}}function cM(e,t){return e.kind===`transient`?`You ran ${iM} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${iM}@latest\` to get ${t}.`:e.kind===`local`?"This is a local build from a Ryugi checkout. Update it with `git pull`, then `pnpm build` in artifacts/.":e.kind===`launcher`?`Release cache refreshed to ${t}. Run the returned start command through the launcher to install it and replace the running server.`:null}var lM=class extends F{};async function uM(e,t){if(!FE[process.platform]?.includes(process.arch))return;let n=KE(),r,i=await RE({...n,version:e,serverHome:ke().home},uE(lE()),()=>{r=t.effects.begin(`update.daemon`,IE(n.home).binary)}).catch(e=>({status:`failed`,error:e.message}));if(i.status!==`not-installed`&&i.status!==`other-hub`)return i.status===`updated`&&r!==void 0&&t.effects.confirm(r,{from:i.from,to:i.to}),i}async function dM(e,t={}){if(e.pm!==void 0&&!mA.includes(e.pm))throw new F(`--pm must be one of ${mA.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:_A(e.file,e.env),r=await sM(e.registry);t.beforeCache?.(),rM(nM(e.env),r,Date.now()),t.cacheRefreshed?.();let i={type:`update-check`,current:e.current,latest:r,install:n.kind};if(!tM(r,e.current))return{...i,upToDate:!0,command:null};if(n.kind===`unknown`){let t=mA.map(e=>` ${oM(aM(e,r))}`).join(`
1135
+ `);throw new lM(`Could not tell how ${iM} was installed (${e.file}). Install ${r} with one of:\n${t}\nor run \`${iM} update --pm <${mA.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...i,upToDate:!1,command:`ryugi update`};let n=jD(e.env),a=new LD(n).current();if(!a)throw new F(`Managed runtime state is missing; run ryugi doctor.`);let o=new LD(n,d.default.dirname(a.bin)),s=d.default.join(n,`downloads`,`runtime-${(0,p.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(r):(u.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${iM}@${r}`),vD(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${iM}@${r}`]),n=d.default.join(s,`node_modules`,iM)),o.install(n),{type:`updated`,from:e.current,to:r,pm:`ryugi`,command:`ryugi update`}}finally{u.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...i,upToDate:!1,command:null,message:cM(n,r)};let a=aM(n.pm,r);if(e.check)return{...i,upToDate:!1,command:oM(a)};let o=process.platform===`win32`;t.beforeInstall?.();let s=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],c=o?(0,f.spawnSync)(oM(a),{stdio:[...s],env:e.env,shell:!0}):(0,f.spawnSync)(a.cmd,a.args,{stdio:[...s],env:e.env});if(c.stdout?.length&&t.log?.(c.stdout.toString()),c.stderr?.length&&t.log?.(c.stderr.toString()),c.error)throw new F(`Could not run ${oM(a)}: ${c.error.message}`);if(c.status!==0)throw new F(`${oM(a)} exited with ${c.status??c.signal}`);return{type:`updated`,from:e.current,to:r,pm:n.pm,command:oM(a)}}const fM={name:`update`,summary:`Update the CLI through its original owner, then refresh recorded harness integrations and the daemon`,options:{check:{type:`boolean`,help:`Compare CLI versions only; do not install`},"cli-only":{type:`boolean`,help:`Update CLI without refreshing harness plugins`},"plugins-only":{type:`boolean`,help:`Refresh recorded plugins without updating CLI or daemon`},"install-dir":{type:`string`,value:`<path>`,help:`Managed installation directory`},"plugin-source":{type:`string`,value:`<path>`,help:`Plugin checkout for offline/development refresh`},pm:{type:`string`,value:`<npm|pnpm|yarn|bun>`,help:`Use this package manager instead of detecting it`}},semantic:e=>Z({id:`update`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`current`,`latest`,`install`,`status`,`installed`,`message`,`command`,`plugins`,`daemon`]},async run(t,n){if(e.values[`cli-only`]&&e.values[`plugins-only`])throw new F(`Choose --cli-only or --plugins-only`);let r,i,a;try{a=e.values[`plugins-only`]?{type:`update-check`,current:`1.108.7`,latest:`1.108.7`,install:_A(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await dM({current:`1.108.7`,file:__filename,env:process.env,registry:process.env.npm_config_registry||`https://registry.npmjs.org/`,check:!!e.values.check,pm:e.values.pm},{beforeCache(){i=n.effects.begin(`release-cache`,nM(process.env))},cacheRefreshed(){i!==void 0&&n.effects.confirm(i)},beforeInstall(){r=n.effects.begin(`install`,iM)},log:n.diagnostic})}catch(e){throw e instanceof lM?new K({code:`E_INSTALL_UNKNOWN`,message:e.message},`action_required`):e}a.type===`updated`&&r!==void 0&&n.effects.confirm(r,{from:a.from,to:a.to});let o=a.type===`updated`?{current:a.to,latest:a.to,install:a.pm===`ryugi`?`managed`:`global`,status:`updated`,installed:!0,command:a.command}:{current:a.current,latest:a.latest,install:a.install,status:a.upToDate?`up_to_date`:`available`,installed:!1,command:a.command,...a.message?{message:a.message}:{}},s=d.default.resolve(e.values[`install-dir`]||jD());if(!e.values.check&&!e.values[`cli-only`]){o.plugins=[];for(let t of Object.values(BD(s).harnesses)){let r=await vA({projectDir:e.projectDir,positionals:[],values:{mode:t.mode,harness:t.harness,"no-cli":!0,"install-dir":s,"plugin-source":e.values[`plugin-source`]}},n,!1,!0),i=r.data.targets.find(e=>e.harness===t.harness);o.plugins.push({harness:t.harness,mode:t.mode,status:i?.status||`failed`,error:i?.error||(r.completion.kind===`succeeded`?void 0:r.warnings.map(e=>e.message).join(`; `))})}}if(!e.values.check&&!e.values[`plugins-only`]&&o.status!==`available`){let e=await uM(o.current,n);e&&(o.daemon=e)}let c=e.values.check?{warnings:[],actions:[]}:Tk(await Dk({cleanup:!0,root:s},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return J(o,o.plugins?.some(e=>e.status!==`installed`)||o.daemon?.status===`failed`?{kind:`partial`}:void 0,{effects:n.effects.snapshot(),warnings:c.warnings,actions:[...o.install===`launcher`&&o.status===`available`?[q([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...c.actions]})},present:pM},e)};function pM({data:e}){return{heading:`Update`,status:e.status,facts:[X(`Current`,Y(e,`current`),!0),X(`Latest`,Y(e,`latest`)),X(`Install`,Y(e,`install`)),...e.message?[X(`Advice`,Y(e,`message`))]:[],...e.daemon?[X(`Daemon`,{key:`daemon`,value:e.daemon.status===`updated`?`updated ${e.daemon.from} → ${e.daemon.to}`:e.daemon.status===`failed`?`failed: ${e.daemon.error}`:e.daemon.status===`not-running`?`not running; start it to update it`:`current`})]:[]],sections:e.plugins?.length?[{kind:`records`,key:`plugins`,title:`Harnesses`,rows:e.plugins.map(e=>({...e})),columns:[{key:`harness`,required:!0},{key:`mode`,required:!0},{key:`status`,required:!0},{key:`error`}]}]:[]}}const mM=[nw,Qj,VT,Uj,Jj,ww,Rw,bw,YA,iE,IT,Hw,$k,sE,fM,bA,Nk,$E,tA,eM];function hM(e){return(t,n,r)=>{let i=[`--project-dir`,e.projectDir],a=typeof e.values.artifact==`string`?e.values.artifact:void 0,o=[...i,...a?[`--artifact`,a]:[]];if(r.some(e=>e.state===`unknown`)){let e;if(t.startsWith(`comment`)&&a)e=[`comment`,`list`,...o,...a.startsWith(`verify/`)?[]:[`--sections`,`all`,...t.endsWith(`.ack`)?[]:[`--all`],`--detail`]];else if(t.startsWith(`changes`))e=[`changes`,...o,`--detail`];else if(t.startsWith(`publish`))e=[`publish`,`--list`,...i,...a&&r.some(e=>[`share-key`,`revoke-key`].includes(e.operation)&&e.state===`unknown`)?[`--artifact`,a]:[]];else if(t===`config`)e=[`config`,...i];else if(t.startsWith(`modules`))e=[`modules`,...o];else if(t===`update`)e=[`--version`];else if(t===`install`)return[{kind:`command`,argv:[`claude`,`plugin`,`list`,`--json`],label:`Verify state`,reason:`Inspect installed plugins before any retry; an operation may already have completed.`}];else e=[`get`,...i];return[{...q(e,`Verify state`),reason:`Inspect current state before any retry; an operation may already have completed.`}]}return n?.code===`E_SERVER_NOT_RUNNING`||n?.code===`E_SERVER_UNREACHABLE`?[q([`start`,`--background`,`--no-open`,...o],`Start server`)]:n?.code===`E_ARGUMENT_INVALID`||n?.code===`E_OPTION_CONFLICT`?[q([t.split(`.`)[0],...e.positionals[0]&&t.startsWith(`comment`)?[e.positionals[0]]:[],`--help`],`Help`)]:n?cC(n):[]}}async function gM(e,t,n,r){return wC({id:e,mode:`finite`,output:{formats:[n.format]},run(){throw t},present(){return{heading:`Error`,status:`failed`,facts:[],sections:[]}}},void 0,{...n,fields:void 0,detail:!1},r)}function _M(e,t){return{id:e,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`text`,`version`,`capabilities`,`commands`]},run(){return J(t)},present({data:e}){return e.version?{heading:`ryugi ${e.version}`,status:``,facts:[],sections:[]}:{heading:`Help`,status:``,facts:[],sections:[{kind:`content`,key:`text`,text:e.text}]}}}}async function vM(e,t,n,r,i,a,o){let[s,...c]=e,l=t.find(e=>e.name===s),d;try{if(l?.positionals&&l.usage?.some(e=>/^[a-z]+\s/.test(e))&&(d=qS(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return qS(c,{},0),await Z(_M(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&JS(c)){l||qS(c,{},0);let e=l?QS(l,d):$S(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=qS(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=cS():typeof t.values.artifact==`string`&&(e+=`\n\n${sS(t.values.artifact)}`)}return await Z(_M(`help`,{text:e,commands:t.map(({name:e,summary:t})=>({name:e,summary:t}))}),void 0).run(i,a)}if(!l&&(!s||s.startsWith(`-`)||(()=>{try{return u.default.statSync(s).isDirectory()}catch{return!1}})())){let t=qS(e,n,1);if(t.positionals.length&&t.values[`project-dir`])throw new K({code:`E_ARGUMENT_INVALID`,message:`Specify one project directory.`});return t.projectDir=t.values[`project-dir`]??t.positionals[0]??t.projectDir,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await AC(t,`browse`).run(i,a,o)}if(!l)throw new K({code:s?.includes(`/`)?`E_PROJECT_NOT_FOUND`:`E_UNKNOWN_COMMAND`,message:s?`Unknown command: ${s}`:`Use start --foreground to browse with semantic output.`});let f;try{f=qS(c,ZS(l,d),l.positionals)}catch(e){throw new K({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=Ue(f.projectDir).project,await l.semantic(f).run(i,a,o,hM(f))}catch(e){let t=e instanceof F?new K({code:`E_ARGUMENT_INVALID`,message:e.message}):e;return t instanceof Error&&Object.assign(t,{actions:[q([...l?[l.name,...d&&l.usage?.some(e=>e.startsWith(`${d} `))?[d]:[]]:[],`--help`],`Help`)]}),gM(l?.name??s??`browse`,t,i,a)}}function yM(e=process.stdout,t=process.stderr){let n=/* @__PURE__ */ new WeakMap;for(let r of[e,t])r.on(`error`,e=>n.set(r,e));return{write(r,i){let a=r===`stdout`?e:t,o=n.get(a);return o?Promise.reject(o):new Promise((e,t)=>a.write(i,n=>n?t(n):e()))}}}function bM(e){process.exitCode=e}const xM={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function SM(e){w(`cli`);let t=Object.assign({},GS,...mM.map(e=>e.options)),n=yM(),r;try{r=LS(e,t,US(e,t))}catch(r){return gM(e[0]??`browse`,r,LS(e,t).options,n)}if(r.error)return gM(e[0]??`browse`,r.error,r.options,n);let i=new AbortController,a=()=>i.abort(`SIGINT`),o=()=>i.abort(`SIGTERM`);process.on(`SIGINT`,a),process.on(`SIGTERM`,o);try{return await vM(e,mM,xM,`1.108.7`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}SM(process.argv.slice(2)).then(bM,e=>gM(process.argv[2]??`browse`,e,{format:`brief`},yM()).then(bM));