ryugi-artifacts 1.119.0 → 1.120.1

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 (105) hide show
  1. package/dist/cli.cjs +10 -10
  2. package/dist/document-engine.cjs +2 -2
  3. package/dist/viewer/{AgentDock-D6nl1_G2.js → AgentDock-DIfCUHgZ.js} +1 -1
  4. package/dist/viewer/{ArtboardLayout-B5oKvRae.js → ArtboardLayout-BNViVZgT.js} +4 -4
  5. package/dist/viewer/{ArtifactList-k30Phg7k.js → ArtifactList-3kGz4_Vv.js} +1 -1
  6. package/dist/viewer/{ArtifactModal-CA_k50VC.js → ArtifactModal-Fp67aW8M.js} +1 -1
  7. package/dist/viewer/{BottomSheet-DX7R2n3H.js → BottomSheet-SYC_8Y6k.js} +1 -1
  8. package/dist/viewer/{BrandingMark-B-_Y3wRr.js → BrandingMark-D8kdL9jc.js} +1 -1
  9. package/dist/viewer/{Canvas-CWmVvXd3.js → Canvas-CMN5apcj.js} +1 -1
  10. package/dist/viewer/{CommentPopover-DyhEriqf.js → CommentPopover-CxFndD1f.js} +1 -1
  11. package/dist/viewer/{DocumentExportMenu-COJCZErz.js → DocumentExportMenu-DyhweUFo.js} +1 -1
  12. package/dist/viewer/DocumentLayout-B16AJ4m1.js +2 -0
  13. package/dist/viewer/{DocumentPage-DUezrISY.js → DocumentPage-dMWzmQVw.js} +1 -1
  14. package/dist/viewer/{DraggablePanel-DI2kyNyd.js → DraggablePanel-h7D7Tgnv.js} +1 -1
  15. package/dist/viewer/{DropdownMenu-D6GzThfD.js → DropdownMenu-Dza6-jeN.js} +1 -1
  16. package/dist/viewer/{GroupVerdict-CVdqcvje.js → GroupVerdict-CSoZ7xIi.js} +1 -1
  17. package/dist/viewer/{HtmlLayout-CwdW-lsP.js → HtmlLayout-DursBclJ.js} +1 -1
  18. package/dist/viewer/{Input-FwY9_7g1.js → Input-CkHOfbQE.js} +1 -1
  19. package/dist/viewer/{MenuSubmenuTrigger-CHgeZC3r.js → MenuSubmenuTrigger-CLeiXsan.js} +1 -1
  20. package/dist/viewer/{PhoneArtboardBar-CfnPlzHS.js → PhoneArtboardBar-DOanenAY.js} +1 -1
  21. package/dist/viewer/{Popover-CMWsvaLm.js → Popover-HS6yjzxl.js} +1 -1
  22. package/dist/viewer/{PreviewArtifactLayout-CVaeJt2W.js → PreviewArtifactLayout-NXoiF_BV.js} +1 -1
  23. package/dist/viewer/{PreviewLayout-CyCnO5LD.js → PreviewLayout-BnV4cPB4.js} +2 -2
  24. package/dist/viewer/{ReportLayout-CKse-CI_.js → ReportLayout-w7Tkbjp6.js} +2 -2
  25. package/dist/viewer/{Segmented-BgsODKpL.js → Segmented-D5ApsVJJ.js} +1 -1
  26. package/dist/viewer/{SelectScrollUpArrow-DJ6VG4QD.js → SelectScrollUpArrow-BFRXZrFq.js} +1 -1
  27. package/dist/viewer/{SlidesLayout-CZQ6stQu.js → SlidesLayout-B1mwiNJH.js} +3 -3
  28. package/dist/viewer/{SnapshotDocument-DXe2umS0.js → SnapshotDocument-B9mIj1Hu.js} +1 -1
  29. package/dist/viewer/{SplitFrame-CddECLIm.js → SplitFrame-zVgYFiT_.js} +1 -1
  30. package/dist/viewer/{StoryboardLayout-4Z5izlHu.js → StoryboardLayout-CWuqD7XK.js} +1 -1
  31. package/dist/viewer/{StoryboardRender-WmKx4kWP.js → StoryboardRender-CjFlWvlf.js} +1 -1
  32. package/dist/viewer/{ThreadView-Bv82-G9b.js → ThreadView-DTGR5uqU.js} +1 -1
  33. package/dist/viewer/{Tooltip-ScA024qG.js → Tooltip-Bi4V2FVJ.js} +1 -1
  34. package/dist/viewer/VerifyLayout-8IJyCQab.js +1 -0
  35. package/dist/viewer/{VirtualizedEditor-uWe43zaI-GPE6Ynul.js → VirtualizedEditor-uWe43zaI-St9YpcWe.js} +1 -1
  36. package/dist/viewer/{VirtualizedRenderer-C_d95FXi-DZquW4i2.js → VirtualizedRenderer-C_d95FXi-AQRKmbO2.js} +1 -1
  37. package/dist/viewer/{WarningsBadge-BFzrxU9P.js → WarningsBadge-CyQbVl6h.js} +1 -1
  38. package/dist/viewer/{WhiteboardEditor-DrHOvXez-FD7nzwh5.js → WhiteboardEditor-DrHOvXez-Bd1MyHmC.js} +1 -1
  39. package/dist/viewer/{WhiteboardLayout-JLyg3g-N.js → WhiteboardLayout-D-gmpAvD.js} +1 -1
  40. package/dist/viewer/{WritingCursor-4938YQmb.js → WritingCursor-CLEFH9bN.js} +1 -1
  41. package/dist/viewer/{agentLook-Ch5QYwXQ.js → agentLook-BPPrbQJ3.js} +1 -1
  42. package/dist/viewer/{artifact-list-CSrSAVmf.js → artifact-list-CuXyveqX.js} +1 -1
  43. package/dist/viewer/{auto-publish-Bd8rGjsh.js → auto-publish-DK402eHG.js} +1 -1
  44. package/dist/viewer/{channel-BkZwhSnE.js → channel-Cuvtl_mH.js} +3 -3
  45. package/dist/viewer/{crop-encode-D1qNKsnB.js → crop-encode-7FeBhORX.js} +1 -1
  46. package/dist/viewer/{dist-CKKVvehj.js → dist-48uAq37R.js} +1 -1
  47. package/dist/viewer/{dist-CfbInnxL.js → dist-7mb2bGpU.js} +1 -1
  48. package/dist/viewer/{dist-7pu_W7cw.js → dist-B7uQYv5D.js} +1 -1
  49. package/dist/viewer/{dist-BwOo7fBX.js → dist-BQ-mw7EX.js} +1 -1
  50. package/dist/viewer/{dist-B39Hdt9T.js → dist-BZtYe42f.js} +1 -1
  51. package/dist/viewer/{dist-CJXrx6tO.js → dist-Bk5XPCBt.js} +1 -1
  52. package/dist/viewer/{dist-F5-tYqrv.js → dist-BlsFMD-D.js} +1 -1
  53. package/dist/viewer/{dist-BsMp5KOc.js → dist-C1y9SfQg.js} +1 -1
  54. package/dist/viewer/{dist-CccyHBd4.js → dist-CIFQVgHq.js} +1 -1
  55. package/dist/viewer/{dist-Bg4gTX6Y.js → dist-CPlSf_-n.js} +1 -1
  56. package/dist/viewer/{dist-DsG5kUfc.js → dist-CVLSwR1I.js} +1 -1
  57. package/dist/viewer/{dist-Cy4bvdV4.js → dist-CdLcI1iK.js} +1 -1
  58. package/dist/viewer/{dist-DlQxF5aM.js → dist-D239Hbe5.js} +1 -1
  59. package/dist/viewer/{dist-BINCOObW.js → dist-D3jbkNxp.js} +1 -1
  60. package/dist/viewer/dist-D9hP37Je.js +1 -0
  61. package/dist/viewer/{dist-76fd_plo.js → dist-Dps6vTN-.js} +1 -1
  62. package/dist/viewer/{dist-CsJHw2zG.js → dist-IPNQW5G8.js} +1 -1
  63. package/dist/viewer/{dist-rV2TK6uV.js → dist-J2ZdVVPe.js} +1 -1
  64. package/dist/viewer/{dist-BdfLoyoB.js → dist-ZG8pOFA0.js} +1 -1
  65. package/dist/viewer/{dist-BZOBp3up.js → dist-ZiVOhU9h.js} +1 -1
  66. package/dist/viewer/{dist-PRSLBq1s.js → dist-h__DIjgw.js} +1 -1
  67. package/dist/viewer/{dist-BI9i_lD6.js → dist-heibZsuo.js} +1 -1
  68. package/dist/viewer/{dist-CVRzFs0w.js → dist-lr1VXsEc.js} +1 -1
  69. package/dist/viewer/{dist-CCXlNul9.js → dist-uxyq6tMx.js} +1 -1
  70. package/dist/viewer/{dist-DbVcT1Lu.js → dist-yH5e-0q1.js} +1 -1
  71. package/dist/viewer/{editor-B_68ApKO.js → editor-B9cVjpUI.js} +4 -4
  72. package/dist/viewer/{fit-CwI-iAmO.js → fit-BQe9RV4E.js} +1 -1
  73. package/dist/viewer/{icons-CFEm7hsF.js → icons-CCSPm9SD.js} +1 -1
  74. package/dist/viewer/{imperative-JYnJqj8g.js → imperative-BeC0q_ho.js} +1 -1
  75. package/dist/viewer/index.html +12 -12
  76. package/dist/viewer/index.js +2 -2
  77. package/dist/viewer/index5.css +8 -0
  78. package/dist/viewer/{local-CLKFRRhM.js → local-DjzZ1b9A.js} +1 -1
  79. package/dist/viewer/{local-split-host-CaCpz4m4.js → local-split-host-CeKHc_JX.js} +1 -1
  80. package/dist/viewer/{plugin-_bGVeqI0-4PiOH3Ay.js → plugin-_bGVeqI0--OtMqC7P.js} +2 -2
  81. package/dist/viewer/preview.html +3 -3
  82. package/dist/viewer/preview.js +1 -1
  83. package/dist/viewer/{printDocument-MSfisZgr.js → printDocument-DDB2RpO4.js} +1 -1
  84. package/dist/viewer/{ref-UktF8HDb.js → ref-DjRYiP25.js} +1 -1
  85. package/dist/viewer/{ref-problem-CYl63GMx.js → ref-problem-DkSEcIQm.js} +1 -1
  86. package/dist/viewer/{route-CkzLq5OJ.js → route-BEA0O_Ry.js} +2 -2
  87. package/dist/viewer/{route-messages-DKF6qVON.js → route-messages-o8lg2hOP.js} +1 -1
  88. package/dist/viewer/{settings-7ADt-Tzk.js → settings-BQ3tJuXQ.js} +1 -1
  89. package/dist/viewer/{snap-vj8xjSPP.js → snap-Dh3ZoMla.js} +1 -1
  90. package/dist/viewer/{split-B4_ujJmR.js → split-BZPaH4G4.js} +2 -2
  91. package/dist/viewer/{stable-B9hejXSo.js → stable-DP74aChD.js} +1 -1
  92. package/dist/viewer/{styles-DacPVGT9.js → styles-BtwjIslZ.js} +1 -1
  93. package/dist/viewer/{transport-B-pm0pyk.js → transport-7BF3TWU4.js} +1 -1
  94. package/dist/viewer/{url-Bm8kHXk0.js → url-BaZreTXB.js} +1 -1
  95. package/dist/viewer/{useArtifactFeed-Dx-cjgIy.js → useArtifactFeed-CYcXA6yE.js} +1 -1
  96. package/dist/viewer/{useArtifactSocket-CENr6ga2.js → useArtifactSocket-CZwBSmOD.js} +1 -1
  97. package/dist/viewer/{useLayerZIndex-LP5l6OXo.js → useLayerZIndex-C1JpT09z.js} +1 -1
  98. package/dist/viewer/{useRefBoard-CdKCpZnq.js → useRefBoard-Cj5dzC4F.js} +1 -1
  99. package/dist/viewer/{useStoryboardData-DDYv9NXb.js → useStoryboardData-CbleqK_E.js} +1 -1
  100. package/dist/viewer/{view-BQQpNj-2.js → view-Bw41z8XN.js} +1 -1
  101. package/dist/viewer/{viewport-CFJHn_Y6-17XQvsoP.js → viewport-CFJHn_Y6-DVNTdoOX.js} +1 -1
  102. package/package.json +2 -2
  103. package/dist/viewer/DocumentLayout-D9Ou6HAC.js +0 -2
  104. package/dist/viewer/VerifyLayout-A6dmzUhm.js +0 -1
  105. package/dist/viewer/dist-BxUOsr4j.js +0 -1
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"),d=require("node:path"),f=require("node:crypto"),p=require("node:child_process"),m=require("node:os"),h=require("node:util"),g=require("node:readline"),_=require("node:net"),v=require("node:url"),y=require("node:timers/promises"),b=require("node:process"),x=require("node:tty"),S=require("node:worker_threads");u=l(u,1),d=l(d,1),f=l(f,1),m=l(m,1),g=l(g,1),_=l(_,1),b=l(b,1);var C=`1.119.0`,w=`11cd36d53eef`;const T=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Artideck ${e} (${C}${t?` · ${t}`:``})`},ee=process.platform!==`win32`;function te(e,...t){ee&&(process.title=[T(e),...t].join(` `))}const ne=/^[a-z][a-z0-9-]{0,63}$/;function E(){let e=process.env.RYUGI_PACKAGE;if(e)return ne.test(e)?e:void 0;if(typeof __dirname==`string`)try{let{name:e}=JSON.parse(u.default.readFileSync(d.default.join(__dirname,`..`,`package.json`),`utf8`));return typeof e==`string`&&ne.test(e)?e:void 0}catch{return}}const re=E(),D={"X-Ryugi-Version":C,...re?{"X-Ryugi-Package":re}:{}};function ie(e){e&&(D[`X-Ryugi-Plugins`]=e)}const ae=`properties.json`,oe=e=>!!e&&typeof e==`object`&&!Array.isArray(e),se=e=>oe(e)&&Object.entries(e).every(([e,t])=>/^\d+$/.test(e)&&Number.isSafeInteger(t)&&t>=0),O=e=>oe(e)&&typeof e.name==`string`&&!!e.name.trim()&&e.name.length<=100&&(e.model===void 0||typeof e.model==`string`&&!!e.model&&e.model.length<=200),ce=()=>({version:1,lineage:null,baseline:null,batches:[]});function le(e){let t=JSON.parse(e);if(!oe(t)||t.version!==1||!(t.lineage===null||typeof t.lineage==`string`&&t.lineage&&t.lineage.length<=512)||!(t.baseline===null||se(t.baseline))||t.createdBy!==void 0&&!O(t.createdBy)||!Array.isArray(t.batches)||t.lineage===null!=(t.baseline===null))throw Error(`Invalid document properties`);let n=t.baseline??{};for(let e of t.batches){if(!oe(e)||!se(e.through)||!O(e.by)||Object.entries(n).some(([t,n])=>e.through[t]===void 0||e.through[t]<n))throw Error(`Invalid document attribution batch`);n=e.through}if(t.lineage===null&&t.batches.length)throw Error(`Uninitialized document has attribution batches`);return t}function ue(e){try{return le(u.default.readFileSync(d.default.join(e,ae),`utf8`))}catch(e){if(e.code===`ENOENT`)return;throw e}}function de(e){if(!u.default.existsSync(d.default.join(e,`doc.xml`))){u.default.mkdirSync(e,{recursive:!0});try{u.default.writeFileSync(d.default.join(e,ae),JSON.stringify(ce(),null,2)+`
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"),d=require("node:path"),f=require("node:crypto"),p=require("node:child_process"),m=require("node:os"),h=require("node:util"),g=require("node:readline"),_=require("node:net"),v=require("node:url"),y=require("node:timers/promises"),b=require("node:process"),x=require("node:tty"),S=require("node:worker_threads");u=l(u,1),d=l(d,1),f=l(f,1),m=l(m,1),g=l(g,1),_=l(_,1),b=l(b,1);var C=`1.120.1`,w=`bd2e90fbaca5`;const T=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Artideck ${e} (${C}${t?` · ${t}`:``})`},ee=process.platform!==`win32`;function te(e,...t){ee&&(process.title=[T(e),...t].join(` `))}const ne=/^[a-z][a-z0-9-]{0,63}$/;function E(){let e=process.env.RYUGI_PACKAGE;if(e)return ne.test(e)?e:void 0;if(typeof __dirname==`string`)try{let{name:e}=JSON.parse(u.default.readFileSync(d.default.join(__dirname,`..`,`package.json`),`utf8`));return typeof e==`string`&&ne.test(e)?e:void 0}catch{return}}const re=E(),D={"X-Ryugi-Version":C,...re?{"X-Ryugi-Package":re}:{}};function ie(e){e&&(D[`X-Ryugi-Plugins`]=e)}const ae=`properties.json`,oe=e=>!!e&&typeof e==`object`&&!Array.isArray(e),se=e=>oe(e)&&Object.entries(e).every(([e,t])=>/^\d+$/.test(e)&&Number.isSafeInteger(t)&&t>=0),O=e=>oe(e)&&typeof e.name==`string`&&!!e.name.trim()&&e.name.length<=100&&(e.model===void 0||typeof e.model==`string`&&!!e.model&&e.model.length<=200),ce=()=>({version:1,lineage:null,baseline:null,batches:[]});function le(e){let t=JSON.parse(e);if(!oe(t)||t.version!==1||!(t.lineage===null||typeof t.lineage==`string`&&t.lineage&&t.lineage.length<=512)||!(t.baseline===null||se(t.baseline))||t.createdBy!==void 0&&!O(t.createdBy)||!Array.isArray(t.batches)||t.lineage===null!=(t.baseline===null))throw Error(`Invalid document properties`);let n=t.baseline??{};for(let e of t.batches){if(!oe(e)||!se(e.through)||!O(e.by)||Object.entries(n).some(([t,n])=>e.through[t]===void 0||e.through[t]<n))throw Error(`Invalid document attribution batch`);n=e.through}if(t.lineage===null&&t.batches.length)throw Error(`Uninitialized document has attribution batches`);return t}function ue(e){try{return le(u.default.readFileSync(d.default.join(e,ae),`utf8`))}catch(e){if(e.code===`ENOENT`)return;throw e}}function de(e){if(!u.default.existsSync(d.default.join(e,`doc.xml`))){u.default.mkdirSync(e,{recursive:!0});try{u.default.writeFileSync(d.default.join(e,ae),JSON.stringify(ce(),null,2)+`
3
3
  `,{flag:`wx`,mode:384})}catch(e){if(e.code!==`EEXIST`)throw e}}}const fe=[`artboard`,`document`,`html`,`whiteboard`,`verify`,`slides`,`report`,`storyboard`],k={artboard:`canvas.json`,document:`doc.xml`,html:`index.html`,whiteboard:`scene.excalidraw`,verify:`verify.xml`,slides:`index.html`,report:`report.tsx`,storyboard:`storyboard.xml`};({...k});const pe=[`html`,`image`,`video`],me=e=>e.type===`image`||e.type===`video`,he=`.artideck`,ge=`.ryugi`,_e=e=>d.default.join(e,he),ve=e=>d.default.join(_e(e),`artifacts`),ye=e=>d.default.join(e,ge),be=e=>{try{return u.default.statSync(e).isDirectory()}catch{return!1}},xe=e=>{try{return u.default.lstatSync(e),!0}catch{return!1}},Se=e=>{try{return u.default.realpathSync(e)}catch{return d.default.resolve(e)}},Ce=e=>!be(_e(e))&&be(ye(e))?ye(e):_e(e),we=e=>Ce(e);function Te(e,t,n){let r;try{r=u.default.readFileSync(e,`utf8`)}catch{return}let i=r.split(t+d.default.sep).join(n+d.default.sep);i!==r&&u.default.writeFileSync(e,i)}async function Ee(e){if(e.env.RYUGI_SERVER_HOME)return{conflicts:[],status:`skipped`};let t=ye(e.home);if(!be(t))return{conflicts:[],status:`none`};let n=_e(e.home);try{await e.stopLegacyHub(d.default.join(t,`server`));let r=null;if(!xe(n))try{u.default.renameSync(t,n),r={conflicts:[],status:`moved`}}catch(e){if(!xe(n))throw e}if(!r){let e=A(t,n);r={conflicts:e.conflicts,status:`merged`,...e.errors.length?{error:e.errors.join(`; `)}:{}}}for(let e of[`dev.json`,d.default.join(`server`,`launch.json`)])Te(d.default.join(n,e),t,n);return r}catch(e){return{conflicts:[],error:e.message,status:`failed`}}}const De=e=>d.default.join(Ce(e),`artifacts`),Oe=e=>be(d.default.join(_e(e),`artifacts`))||be(d.default.join(ye(e),`artifacts`));function ke(e,t){try{let[n,r]=[u.default.lstatSync(e),u.default.lstatSync(t)];return n.isFile()&&r.isFile()&&n.size===r.size&&u.default.readFileSync(e).equals(u.default.readFileSync(t))}catch{return!1}}function A(e,t,n=``,r={conflicts:[],errors:[]}){let i;try{i=u.default.readdirSync(e)}catch(e){return e.code===`ENOENT`||(r.conflicts.push(n),r.errors.push(`${n}: ${e.message}`)),r}for(let a of i){let i=d.default.join(e,a),o=d.default.join(t,a),s=d.default.join(n,a);try{xe(o)?be(i)&&be(o)?A(i,o,s,r):ke(i,o)?u.default.rmSync(i):r.conflicts.push(s):u.default.renameSync(i,o)}catch(e){r.conflicts.push(s),r.errors.push(`${s}: ${e.message}`)}}try{u.default.readdirSync(e).length===0&&u.default.rmdirSync(e)}catch{}return r}function Ae(e){try{return(0,p.execFileSync)(`git`,[`-C`,e,`ls-files`,`-z`,`--`,ge],{stdio:[`ignore`,`pipe`,`ignore`]}).length>0}catch{return!1}}function je(e){let t;try{t=u.default.readFileSync(e,`utf8`)}catch{return!1}let n=t.split(`
4
4
  `),r=[],i=!1;for(let[e,t]of n.entries()){if(r.push(t),t.trimStart().startsWith(`#`)||!t.includes(`.ryugi`))continue;let a=t.split(ge).join(he);n.includes(a)||n[e+1]===a||(r.push(a),i=!0)}return i&&u.default.writeFileSync(e,r.join(`
5
5
  `)),i}function Me(e){let t=[];for(let n=e;;n=d.default.dirname(n)){t.push(d.default.join(n,`.gitignore`));let r=d.default.join(n,`.git`);if(xe(r))return be(r)&&t.push(d.default.join(r,`info`,`exclude`)),t;if(d.default.dirname(n)===n)return[d.default.join(e,`.gitignore`)]}}function Ne(e){return Me(e).map(e=>je(e)).some(Boolean)}function Pe(e,t={}){let n={status:`none`,conflicts:[],tracked:!1,gitignore:!1};if(t.home&&Se(e)===Se(t.home))return{...n,status:`skipped`};let r=ye(e);if(!be(r))return n;let i=_e(e);if(n.tracked=Ae(e),!xe(i))try{u.default.renameSync(r,i),n.status=`moved`}catch(e){if(!xe(i))return{...n,status:`failed`,error:e.message}}if(n.status===`none`){let e=A(r,i);n.conflicts=e.conflicts,n.status=`merged`,e.errors.length&&(n.error=e.errors.join(`; `))}return n.gitignore=Ne(e),n}const Fe=e=>new Promise(t=>setTimeout(t,e));function Ie(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Le(e){try{return u.default.readFileSync(`/proc/${e}/cmdline`,`utf8`).split(`\0`)}catch{}let t=(0,p.spawnSync)(`ps`,[`-ww`,`-p`,String(e),`-o`,`command=`],{encoding:`utf8`});if(t.status===0&&t.stdout.trim())return t.stdout.trim().split(/\s+/);let n=(0,p.spawnSync)(`ps`,[`-f`,`-p`,String(e)],{encoding:`utf8`});if(n.status!==0)return null;let r=n.stdout.split(`
@@ -1065,7 +1065,7 @@ if (ffmpeg.status !== 0) {
1065
1065
  process.exit(1);
1066
1066
  }
1067
1067
  console.log(JSON.stringify({ duration: pcm.length / 2 / RATE }));
1068
- `];function jE(e){let t=d.default.join(e,`voice/voice.mjs`);return u.default.existsSync(t)?(AE.includes(u.default.readFileSync(t,`utf8`))&&u.default.writeFileSync(t,kE),!1):(u.default.mkdirSync(d.default.dirname(t),{recursive:!0}),u.default.writeFileSync(t,kE,{flag:`wx`}),!0)}var ME='# Storyboard writing\n\nA storyboard plans a product demo video and plays it back before anything is recorded: shots in order, each with a duration, what happens on screen, and voiceover lines that are synthesized and spoken with captions. Write `storyboard.xml` under the returned artifact directory first, with no shot pictures at all: every shot without `src` plays as a title card, so your human partner can hear the pacing within minutes. Add moving pictures, recorded takes, music and sound effects afterwards. On this machine the hub opens a storyboard in an editor: a monitor, a bin and a multitrack timeline (captions, overlay, picture, voice, music, effects) where your human partner trims, splits, reorders, adds transitions, speed, keys and sounds, and exports the next cut.\n\nThe page opens on a board before the editor: one column per shot, and in each column one frame per voice line, drawn at the middle of the line and kept clear of transitions; a shot without lines gets one frame. Reviewers read the story there and comment on single frames. When the picture changes a lot inside one shot, give that moment its own line so it gets its own frame.\n\nYour human partner edits the timeline and the server writes those edits into `storyboard.xml`; moving an overlay rewrites the times of `sb-cursor`, `sb-type` or `sb-clip` in the shot page. Nothing checks for these changes before you write. Patch only the shots and lines you mean to change and keep every id. Never edit `comments.json`, `audio/`, `cuts/` or `.state/`. Finish with `check`; lines still being voiced are pending, not done.\n\n```xml\n<storyboard title="Shared albums" aspect="16:9" lang="en" voice="Kore" target="10-15">\n <lexicon>\n <say word="Ryugi" as="Lyu-ghee" hint="lyu as in the Chinese name Liu, never an English r; hard g"/>\n </lexicon>\n <music id="bed" src="sound/bed.mp3" at="0" gain="-18" duck="-10" fade-in="1" fade-out="2"/>\n <shot id="hook" title="A wall of text" dur="4">\n <action>The terminal fills with a 300-line plan</action>\n <action>Cut away before anyone could read it</action>\n <line id="hook-1" at="0.4">Your agent wrote 300 lines. Now read them.</line>\n </shot>\n <shot id="sketch" title="Sketch it together" dur="8" src="shots/sketch.html" transition="dissolve" transition-dur="0.4">\n <action>You draw a box; the agent completes the flow</action>\n <key prop="scale" at="2" value="1"/>\n <key prop="scale" at="5" value="1.18" ease="in-out"/>\n <sfx id="click" src="sound/click.wav" at="2.6" gain="-6"/>\n <line id="sketch-1" caption="Sketch it together.">Sketch the structure together, right in the page.</line>\n </shot>\n</storyboard>\n```\n\n## Elements\n\n- `<storyboard>`: `title`; `aspect` is `16:9` (default), `9:16` or `1:1`; `lang`; `voice` is the voice name passed to the voice script; `target` is the intended length as a range of seconds (`"65-80"`), and a total outside it is a warning.\n- `<lexicon>` with `<say word="…" as="…" hint="…"/>`: pronunciations. Before synthesis every whole-word `word` is replaced by `as`; captions keep the original words. A respelling alone is often read wrong, so a line holding the word also tells the speech model that `as` is how `word` is said, followed by `hint` (optional: how it sounds, in plain words). Give every made-up or borrowed name a `hint`.\n- `<shot>`: `id`, `title`, `dur` (seconds, required, one decimal is fine). Optional `src` (a shot page under `shots/`), `take` (a recorded clip under `takes/`) and `take-in` (the second of the take to start from). A shot starts where the shots before it end; never write start times.\n- `<action>`: one thing that happens on screen, one sentence each. Title cards and the script column show them.\n- `<line>`: one voiceover line. `at` is seconds from the shot\'s start; without it the line follows the previous line by 0.3s (the first line starts 0.3s in). `caption` replaces the words shown on screen; without it the caption is the line itself. `gain` is its volume in dB (default 0).\n\nShot and line ids are lowercase letters, digits and hyphens, unique across the whole file; comments are anchored to them.\n\n## Tracks\n\nShots are the spine: everything below is optional, and a storyboard without it is a picture, voice and caption timeline. Times on a shot are seconds from its start on the timeline; music uses whole-video seconds.\n\n- On `<shot>`: `speed` (0.25 to 4, default 1) runs the page clock and the take faster or slower while `dur` stays its length on the timeline; voice, keys and effects are not sped up. `src-in` is the second of the shot page to start from. `transition` is `cut` (default), `dissolve` or `black`, centred on the seam before this shot and `transition-dur` seconds long (default 0.4, at most half the shorter shot); it never changes the total length. `gain` in dB plays a take\'s own sound, which is otherwise muted.\n- `<key prop="…" at="…" value="…" ease="…"/>` inside a shot animates the picture layer: `x` and `y` in design pixels, `scale` as a factor, `opacity` 0 to 1, and `gain` in dB for a take\'s sound. `ease` is `linear` (default), `in`, `out` or `in-out`, easing into that key. One key holds its value for the whole shot; captions do not move.\n- `<sfx id src at gain fade-in fade-out/>` inside a shot plays a sound effect `at` seconds into the shot.\n- `<music id src at from to gain duck fade-in fade-out>` at the top level plays a file from `at` seconds into the video, starting `from` seconds into the file and ending at `to` (default: the end of the video). `duck` lowers it by that many dB while a voice line plays (down in 0.2s, back in 0.4s). Gain `<key prop="gain">` elements inside it change its volume over time, in seconds from `at`.\n- On `<storyboard>`: `mute="music sfx"` silences any of `voice`, `music` and `sfx`, and `captions="off"` hides captions; both carry into the export.\n\nSound files live in `sound/` (mp3, wav, m4a or ogg). Put them there yourself, or your human partner drops them into the editor. `check` reports a track that names a file that is not there.\n\n## Voice\n\nEvery line is synthesized on its own by `voice/voice.mjs` in the artifact directory, which `start` copies from a template the first time and keeps up to date while it is unedited (OpenRouter text-to-speech; it reads `OPENROUTER_API_KEY` from the project\'s `.env` and needs ffmpeg). It reads `{text, voice, lang, out, direction?}` on stdin; `direction` carries the lexicon\'s pronunciations for that line. The hub runs it a second after `storyboard.xml` changes, only for lines whose words, voice or lexicon changed. Run `adeck storyboard voice --artifact storyboard/<id>` to synthesize and print each line\'s length, then fit shot durations to the voice: `check` reports a voiced line that runs past its shot or overlaps the line before it. `--line <id>` voices one line; `--force` re-voices everything after you change the script.\n\n## Shot pages\n\nA shot page is plain HTML with CSS animations, drawn the way the product looks, laid out at 1920×1080 (1080×1920 for `aspect="9:16"`, 1080×1080 for `1:1`) and scaled to fit the player. Time 0 is the shot\'s start; the viewer pauses every animation and seeks it, so scrubbing and frame-by-frame capture show exactly the same frame. Animate only with CSS animations or the Web Animations API, never with `setTimeout`, `setInterval` or `requestAnimationFrame`, and give every animation a finite iteration count. Three elements cover what CSS cannot seek:\n\n- `<sb-clip src="../takes/raw.mp4" from="3.2" to="11.2" at="0.5">` plays part of a recorded video, muted, starting `at` seconds into the shot.\n- `<sb-cursor path="420,300@0 610,340@1.2 click@1.3 700,420@2.4">` moves a pointer through `x,y@seconds` points and ripples on each `click@seconds`.\n- `<sb-type at="2.3" cps="28">text</sb-type>` types its text from `at`, `cps` characters a second.\n\n`sb-cursor` covers the page, so its points are page pixels. Pages cannot reach the network; keep images under `assets/` and refer to them relatively. `check` warns about timers and endless animations, and counts a shot as not yet run until the viewer has shown it.\n\nThe page `…/storyboard/<id>/render` draws only the picture and captions, with transitions, speed and keys, exactly as the editor\'s monitor does (`?captions=0` drops captions, `?from=&to=` draws only that stretch). Its `window.ryugiStoryboard.seek(t)` resolves once that frame is painted, `duration` is the length in seconds, `audio()` lists every voiced line\'s file URL and start, and `mix()` lists every sound with its file, start, end, gain, fades, keys and duck, so any capture tool can step frame by frame and mix the sound in.\n\n## Takes, export and the cut\n\nPut recorded clips in `takes/` and name them with `take` on their shot; the shot then plays the clip under the voiceover, muted unless the shot has a `gain`, and its shot page and overlays are not drawn (put a clip in the page with `sb-clip` to draw over it).\n\nExport renders the timeline into the next cut on this machine. `start` copies an export script to `render/render.mjs` the first time; it drives Chrome over the DevTools protocol and ffmpeg, with no packages to install, renders each shot from the render page frame by frame, reuses shots that did not change, mixes voice, music and effects and writes 1080p H.264. The hub hands it the timeline as JSON on stdin and registers what it writes as the next cut, with a hash of every shot so the editor marks the shots that changed. Run `adeck storyboard export --artifact storyboard/<id> [--wait]` to export from the command line; lines not yet voiced are voiced first. `adeck storyboard template --artifact storyboard/<id> --force` replaces `render/render.mjs` with the latest template; without `--force` a script you changed is kept. A project can replace the script with its own kit that reads the same JSON.\n\nWhen a finished video comes from somewhere else, register it with `adeck storyboard cut --artifact storyboard/<id> --file <1080p.mp4> [--map <map.json>] [--master <4k.mp4>]`. Without `--map` each shot\'s range comes from the storyboard\'s current durations; pass a map (`{"shots":[{"id":"hook","start":0,"end":4.2}]}`) when the cut\'s timing differs. Encode the cut as H.264 1080p at about 1.5 Mbps so it fits the Cloud allowance.\n\n## Comments and references\n\nRead feedback with `comment list`. Comments are anchored to a shot, a line, a moment of a shot (`--at <seconds>`) or a moment of a cut (`--cut <n> --at <seconds>`), which maps to its shot; `comment list` names each thread\'s shot, moment or line, and for an area marked on a recorded take or the cut, the path of its crop. A thread whose shot was deleted stays, marked `shot deleted`. Your human partner can reorder, trim, split and join shots, rewrite titles, actions and voice lines, add, duplicate or delete shots, and set transitions, speed, keys, sounds and mutes in the editor; each edit rewrites only its part of `storyboard.xml`. A split gives the second half the id `<id>-b` and leaves its comments on the first half. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact storyboard/<id>` and read them before editing the file, so you build on their version instead of writing it back. A document or deck links a shot with `<ref storyboard="<id>" shot="<shot-id>"/>`.\n';function NE(e){if(!e.shot&&!e.cut)throw new j(`comment add on a storyboard needs --shot <shotId>, or --cut <n> --at <seconds>`);if(e.line&&e.at!==void 0)throw new j(`comment add takes --line or --at, not both`);let t=it(e.at,`--at`);if(t!==void 0&&t<0)throw new j(`--at must be seconds from 0`);let n;if(e.cut!==void 0){if(n=Number(e.cut),!Number.isInteger(n)||n<1)throw new j(`--cut must be a cut number from 1`);if(t===void 0)throw new j(`a comment on a cut needs --at <seconds>`);if(e.line)throw new j(`comment add takes --line or --cut, not both`)}return{op:`add`,...e.shot?{shot:e.shot}:{},...e.line?{line:e.line}:{},...n===void 0?{}:{cut:n},...t===void 0?{}:{at:t},text:rt(e)}}const PE={authoring:ME,changes:!0,review:{sections:[]},commentActions:{add:NE},onStart:e=>{jE(e),OE(e)}};var FE='# Verify report writing\n\nWrite `verify.xml` and captured files in `evidence/`. Reports cover command output, counts, API behavior, deploy evidence and evals. Claims judged by looking at a screen go in artboard verify groups; reference those groups from the report. Never invent captured output or human verdicts. Report prose uses the human\'s language; IDs/commands/raw logs retain their form.\n\n```xml\n<verify title="Delivery survives reconnect">\n <p>Verified against local build.</p>\n <claim id="delivery" judge="agent" from="local build @ COMMIT" capturedAt="2026-11-13T10:00:00Z">\n <title>Three attempts preserve the delivery</title>\n <result><code>3</code> attempts, <code>1</code> delivery kept</result>\n <table>\n <tr><th>Measured</th><th>Got</th><th>Expected</th></tr>\n <tr><td>Attempts</td><td><code>3</code></td><td>3</td></tr>\n <tr><td>Deliveries kept</td><td><code>1</code></td><td>1</td></tr>\n </table>\n <output src="evidence/delivery.txt"/>\n </claim>\n <gap id="production"><title>Production run</title><why>No production credentials</why><needs>A test key</needs></gap>\n</verify>\n```\n\nRequired report title; optional one introductory p first; only claim/gap/ref after it, no top-level headings. A top-level ref is `<ref artboard="slug" group="v2"/>` or `<ref verify="slug"/>`; any other kind there counts toward nothing and Check notes it. The page reads as one column: a status line, then what waits on the human (gaps, rejected and pending claims), then the agent\'s checks one line each, grouped by environment. Claim needs unique stable id, judge, title and evidence. `from` identifies actual environment/build; capturedAt is the real ISO capture time, not a future/example timestamp. Update both with replaced evidence. Capture command output directly to evidence/*.txt and never edit it. `output src="evidence/…"` keeps it one click away; no HTML output files. Over 200,000 characters is explicitly truncated.\n\nEvery agent claim has one `<result>`: inline, one line, what it proved (`<result><code>897 passed (897)</code></result>`); it is the claim\'s whole line on the page, and Check notes an agent claim without one. Its `code` values follow the copied-value rule below. Claims from the same environment and build use the identical `from` string: the page groups checks by exact `from` and writes it once per group. Above the output, write the result for the person reading: nobody should have to read a log to see what it proved. A claim may hold p, ul/ol, table (tr/th/td), steps (`step title="…"` with block children), codeblock, img, alert, details and inline marks. A table or steps directly inside the claim folds its raw output behind one line. Inside a table or steps, inline `code` means "copied from this claim\'s output": write the value exactly as the output prints it, with no rounding and no unit change. Check and the page name any such value the output does not contain, and that claim then waits on the human. Expected values, ordinals and your own wording stay outside `code`; commands go in a codeblock.\n\njudge="agent" means a command decided the stated predicate, ran in the claimed environment, passed and has raw output plus from. Missing evidence/from needs human judgment. A failed check is a fix or gap, never a passed agent claim. judge="human" requires an ask explaining what would make the judgment wrong; use for unresolved nonscreen tradeoffs, not to re-ask approved decisions. A human claim holding a long table (rulings, decisions) marks each row `<tr cost="change|small|none">`: change (wrong means behavior must change), small (a small cost), none (no effect). Only change rows show; small and none fold behind a count. Check notes a human-claim table over 12 rows without cost. A rejected agent claim remains human-owned until the human passes it, even after new evidence.\n\nGap needs id/title/why/needs (one specific unblock); why and needs may hold inline marks and refs.\n\nReferences: inside a claim\'s p, li or td, the intro and a gap\'s why or needs, write the same inline `<ref>` a document does (`<ref document="spec" block="retry"/>`, `<ref whiteboard="flow" frame="f1"/>`, `<ref verify="login"/>`…) to link the discussion or artifact a claim rests on; it opens beside the report and counts toward nothing. Never inside <result>, and never standing alone in a claim. Missing targets are Check warnings. `<ref verify="slug"/>` at the top level makes another report a part of this one: it counts as one item that passes when that report is done, waits while it waits, and is rejected while it has a rejection; the status line gives each one a sentence with a link. Split a large piece of work into reports this way; reports that wait on each other in a loop are a Check warning. `<ref artboard="slug" group="v2"/>` counts a screen claim toward done; the page sums the groups per artboard in one status-line sentence with a link, not as rows, so the verdict is given on the artboard. Read via comment list; record pass/reject/waive only if requested by the human, reply on rejection threads and replace evidence after a repair. Stable IDs preserve verdicts/comments. Never edit comments.json or `.state/`. Run `check --artifact verify/<id>` before sharing.\n';function IE(e,t){if(t===`pass`||t===`reject`){let n=t===`pass`&&!!e.all;if(!n&&!e.claim)throw new j(t===`pass`?`comment pass on a report needs --claim <claimId>, or --all`:`comment reject on a report needs --claim <claimId>`);let r=t===`reject`?rt(e):e.text?.trim();return{op:`verdict`,verdict:t,...n?{all:!0}:{claim:e.claim},...r?{text:r}:{}}}if(t===`waive`){if(!e.gap)throw new j(`comment waive needs --gap <gapId>`);return{op:`waive`,gap:e.gap}}if(t===`reply`){if(!e.thread)throw new j(`comment reply needs --thread <threadId>`);return{op:`reply`,threadId:e.thread,text:rt(e)}}throw new j(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}const LE={artboard:st,document:ab,html:ob,whiteboard:{authoring:`# Whiteboard writing
1068
+ `];function jE(e){let t=d.default.join(e,`voice/voice.mjs`);return u.default.existsSync(t)?(AE.includes(u.default.readFileSync(t,`utf8`))&&u.default.writeFileSync(t,kE),!1):(u.default.mkdirSync(d.default.dirname(t),{recursive:!0}),u.default.writeFileSync(t,kE,{flag:`wx`}),!0)}var ME='# Storyboard writing\n\nA storyboard plans a product demo video and plays it back before anything is recorded: shots in order, each with a duration, what happens on screen, and voiceover lines that are synthesized and spoken with captions. Write `storyboard.xml` under the returned artifact directory first, with no shot pictures at all: every shot without `src` plays as a title card, so your human partner can hear the pacing within minutes. Add moving pictures, recorded takes, music and sound effects afterwards. On this machine the hub opens a storyboard in an editor: a monitor, a bin and a multitrack timeline (captions, overlay, picture, voice, music, effects) where your human partner trims, splits, reorders, adds transitions, speed, keys and sounds, and exports the next cut.\n\nThe page opens on a board before the editor: one column per shot, and in each column one frame per voice line, drawn at the middle of the line and kept clear of transitions; a shot without lines gets one frame. Reviewers read the story there and comment on single frames. When the picture changes a lot inside one shot, give that moment its own line so it gets its own frame.\n\nYour human partner edits the timeline and the server writes those edits into `storyboard.xml`; moving an overlay rewrites the times of `sb-cursor`, `sb-type` or `sb-clip` in the shot page. Nothing checks for these changes before you write. Patch only the shots and lines you mean to change and keep every id. Never edit `comments.json`, `audio/`, `cuts/` or `.state/`. Finish with `check`; lines still being voiced are pending, not done.\n\n```xml\n<storyboard title="Shared albums" aspect="16:9" lang="en" voice="Kore" target="10-15">\n <lexicon>\n <say word="Ryugi" as="Lyu-ghee" hint="lyu as in the Chinese name Liu, never an English r; hard g"/>\n </lexicon>\n <music id="bed" src="sound/bed.mp3" at="0" gain="-18" duck="-10" fade-in="1" fade-out="2"/>\n <shot id="hook" title="A wall of text" dur="4">\n <action>The terminal fills with a 300-line plan</action>\n <action>Cut away before anyone could read it</action>\n <line id="hook-1" at="0.4">Your agent wrote 300 lines. Now read them.</line>\n </shot>\n <shot id="sketch" title="Sketch it together" dur="8" src="shots/sketch.html" transition="dissolve" transition-dur="0.4">\n <action>You draw a box; the agent completes the flow</action>\n <key prop="scale" at="2" value="1"/>\n <key prop="scale" at="5" value="1.18" ease="in-out"/>\n <sfx id="click" src="sound/click.wav" at="2.6" gain="-6"/>\n <line id="sketch-1" caption="Sketch it together.">Sketch the structure together, right in the page.</line>\n </shot>\n</storyboard>\n```\n\n## Elements\n\n- `<storyboard>`: `title`; `aspect` is `16:9` (default), `9:16` or `1:1`; `lang`; `voice` is the voice name passed to the voice script; `target` is the intended length as a range of seconds (`"65-80"`), and a total outside it is a warning.\n- `<lexicon>` with `<say word="…" as="…" hint="…"/>`: pronunciations. Before synthesis every whole-word `word` is replaced by `as`; captions keep the original words. A respelling alone is often read wrong, so a line holding the word also tells the speech model that `as` is how `word` is said, followed by `hint` (optional: how it sounds, in plain words). Give every made-up or borrowed name a `hint`.\n- `<shot>`: `id`, `title`, `dur` (seconds, required, one decimal is fine). Optional `src` (a shot page under `shots/`), `take` (a recorded clip under `takes/`) and `take-in` (the second of the take to start from). A shot starts where the shots before it end; never write start times.\n- `<action>`: one thing that happens on screen, one sentence each. Title cards and the script column show them.\n- `<line>`: one voiceover line. `at` is seconds from the shot\'s start; without it the line follows the previous line by 0.3s (the first line starts 0.3s in). `caption` replaces the words shown on screen; without it the caption is the line itself. `gain` is its volume in dB (default 0).\n\nShot and line ids are lowercase letters, digits and hyphens, unique across the whole file; comments are anchored to them.\n\n## Tracks\n\nShots are the spine: everything below is optional, and a storyboard without it is a picture, voice and caption timeline. Times on a shot are seconds from its start on the timeline; music uses whole-video seconds.\n\n- On `<shot>`: `speed` (0.25 to 4, default 1) runs the page clock and the take faster or slower while `dur` stays its length on the timeline; voice, keys and effects are not sped up. `src-in` is the second of the shot page to start from. `transition` is `cut` (default), `dissolve` or `black`, centred on the seam before this shot and `transition-dur` seconds long (default 0.4, at most half the shorter shot); it never changes the total length. `gain` in dB plays a take\'s own sound, which is otherwise muted.\n- `<key prop="…" at="…" value="…" ease="…"/>` inside a shot animates the picture layer: `x` and `y` in design pixels, `scale` as a factor, `opacity` 0 to 1, and `gain` in dB for a take\'s sound. `ease` is `linear` (default), `in`, `out` or `in-out`, easing into that key. One key holds its value for the whole shot; captions do not move.\n- `<sfx id src at gain fade-in fade-out/>` inside a shot plays a sound effect `at` seconds into the shot.\n- `<music id src at from to gain duck fade-in fade-out>` at the top level plays a file from `at` seconds into the video, starting `from` seconds into the file and ending at `to` (default: the end of the video). `duck` lowers it by that many dB while a voice line plays (down in 0.2s, back in 0.4s). Gain `<key prop="gain">` elements inside it change its volume over time, in seconds from `at`.\n- On `<storyboard>`: `mute="music sfx"` silences any of `voice`, `music` and `sfx`, and `captions="off"` hides captions; both carry into the export.\n\nSound files live in `sound/` (mp3, wav, m4a or ogg). Put them there yourself, or your human partner drops them into the editor. `check` reports a track that names a file that is not there.\n\n## Voice\n\nEvery line is synthesized on its own by `voice/voice.mjs` in the artifact directory, which `start` copies from a template the first time and keeps up to date while it is unedited (OpenRouter text-to-speech; it reads `OPENROUTER_API_KEY` from the project\'s `.env` and needs ffmpeg). It reads `{text, voice, lang, out, direction?}` on stdin; `direction` carries the lexicon\'s pronunciations for that line. The hub runs it a second after `storyboard.xml` changes, only for lines whose words, voice or lexicon changed. Run `adeck storyboard voice --artifact storyboard/<id>` to synthesize and print each line\'s length, then fit shot durations to the voice: `check` reports a voiced line that runs past its shot or overlaps the line before it. `--line <id>` voices one line; `--force` re-voices everything after you change the script.\n\n## Shot pages\n\nA shot page is plain HTML with CSS animations, drawn the way the product looks, laid out at 1920×1080 (1080×1920 for `aspect="9:16"`, 1080×1080 for `1:1`) and scaled to fit the player. Time 0 is the shot\'s start; the viewer pauses every animation and seeks it, so scrubbing and frame-by-frame capture show exactly the same frame. Animate only with CSS animations or the Web Animations API, never with `setTimeout`, `setInterval` or `requestAnimationFrame`, and give every animation a finite iteration count. Three elements cover what CSS cannot seek:\n\n- `<sb-clip src="../takes/raw.mp4" from="3.2" to="11.2" at="0.5">` plays part of a recorded video, muted, starting `at` seconds into the shot.\n- `<sb-cursor path="420,300@0 610,340@1.2 click@1.3 700,420@2.4">` moves a pointer through `x,y@seconds` points and ripples on each `click@seconds`.\n- `<sb-type at="2.3" cps="28">text</sb-type>` types its text from `at`, `cps` characters a second.\n\n`sb-cursor` covers the page, so its points are page pixels. Pages cannot reach the network; keep images under `assets/` and refer to them relatively. `check` warns about timers and endless animations, and counts a shot as not yet run until the viewer has shown it.\n\nThe page `…/storyboard/<id>/render` draws only the picture and captions, with transitions, speed and keys, exactly as the editor\'s monitor does (`?captions=0` drops captions, `?from=&to=` draws only that stretch). Its `window.ryugiStoryboard.seek(t)` resolves once that frame is painted, `duration` is the length in seconds, `audio()` lists every voiced line\'s file URL and start, and `mix()` lists every sound with its file, start, end, gain, fades, keys and duck, so any capture tool can step frame by frame and mix the sound in.\n\n## Takes, export and the cut\n\nPut recorded clips in `takes/` and name them with `take` on their shot; the shot then plays the clip under the voiceover, muted unless the shot has a `gain`, and its shot page and overlays are not drawn (put a clip in the page with `sb-clip` to draw over it).\n\nExport renders the timeline into the next cut on this machine. `start` copies an export script to `render/render.mjs` the first time; it drives Chrome over the DevTools protocol and ffmpeg, with no packages to install, renders each shot from the render page frame by frame, reuses shots that did not change, mixes voice, music and effects and writes 1080p H.264. The hub hands it the timeline as JSON on stdin and registers what it writes as the next cut, with a hash of every shot so the editor marks the shots that changed. Run `adeck storyboard export --artifact storyboard/<id> [--wait]` to export from the command line; lines not yet voiced are voiced first. `adeck storyboard template --artifact storyboard/<id> --force` replaces `render/render.mjs` with the latest template; without `--force` a script you changed is kept. A project can replace the script with its own kit that reads the same JSON.\n\nWhen a finished video comes from somewhere else, register it with `adeck storyboard cut --artifact storyboard/<id> --file <1080p.mp4> [--map <map.json>] [--master <4k.mp4>]`. Without `--map` each shot\'s range comes from the storyboard\'s current durations; pass a map (`{"shots":[{"id":"hook","start":0,"end":4.2}]}`) when the cut\'s timing differs. Encode the cut as H.264 1080p at about 1.5 Mbps so it fits the Cloud allowance.\n\n## Comments and references\n\nRead feedback with `comment list`. Comments are anchored to a shot, a line, a moment of a shot (`--at <seconds>`) or a moment of a cut (`--cut <n> --at <seconds>`), which maps to its shot; `comment list` names each thread\'s shot, moment or line, and for an area marked on a recorded take or the cut, the path of its crop. A thread whose shot was deleted stays, marked `shot deleted`. Your human partner can reorder, trim, split and join shots, rewrite titles, actions and voice lines, add, duplicate or delete shots, and set transitions, speed, keys, sounds and mutes in the editor; each edit rewrites only its part of `storyboard.xml`. A split gives the second half the id `<id>-b` and leaves its comments on the first half. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact storyboard/<id>` and read them before editing the file, so you build on their version instead of writing it back. A document or deck links a shot with `<ref storyboard="<id>" shot="<shot-id>"/>`.\n';function NE(e){if(!e.shot&&!e.cut)throw new j(`comment add on a storyboard needs --shot <shotId>, or --cut <n> --at <seconds>`);if(e.line&&e.at!==void 0)throw new j(`comment add takes --line or --at, not both`);let t=it(e.at,`--at`);if(t!==void 0&&t<0)throw new j(`--at must be seconds from 0`);let n;if(e.cut!==void 0){if(n=Number(e.cut),!Number.isInteger(n)||n<1)throw new j(`--cut must be a cut number from 1`);if(t===void 0)throw new j(`a comment on a cut needs --at <seconds>`);if(e.line)throw new j(`comment add takes --line or --cut, not both`)}return{op:`add`,...e.shot?{shot:e.shot}:{},...e.line?{line:e.line}:{},...n===void 0?{}:{cut:n},...t===void 0?{}:{at:t},text:rt(e)}}const PE={authoring:ME,changes:!0,review:{sections:[]},commentActions:{add:NE},onStart:e=>{jE(e),OE(e)}};var FE='# Verify report writing\n\nWrite `verify.xml` and captured files in `evidence/`. Reports cover command output, counts, API behavior, deploy evidence and evals. Claims judged by looking at a screen go in artboard verify groups; reference those groups from the report. Never invent captured output or human verdicts. Report prose uses the human\'s language; IDs/commands/raw logs retain their form.\n\n```xml\n<verify title="Delivery survives reconnect">\n <p>Verified against local build.</p>\n <claim id="delivery" judge="agent" from="local build @ COMMIT" capturedAt="2026-11-13T10:00:00Z">\n <title>Three attempts preserve the delivery</title>\n <result><code>3</code> attempts, <code>1</code> delivery kept</result>\n <table>\n <tr><th>Measured</th><th>Got</th><th>Expected</th></tr>\n <tr><td>Attempts</td><td><code>3</code></td><td>3</td></tr>\n <tr><td>Deliveries kept</td><td><code>1</code></td><td>1</td></tr>\n </table>\n <output src="evidence/delivery.txt"/>\n </claim>\n <gap id="production"><title>Production run</title><why>No production credentials</why><needs>A test key</needs></gap>\n</verify>\n```\n\nRequired report title; optional one introductory p first; only claim/gap/ref after it, no top-level headings. A top-level ref is `<ref artboard="slug" group="v2"/>` or `<ref verify="slug"/>`; any other kind there counts toward nothing and Check notes it. The page reads as one column: a status line, then what waits on the human (gaps, rejected and pending claims), then the agent\'s checks one line each, grouped by environment. Claim needs unique stable id, judge, title and evidence. `from` identifies actual environment/build; capturedAt is the real ISO capture time, not a future/example timestamp. Update both with replaced evidence. Capture command output directly to evidence/*.txt and never edit it. `output src="evidence/…"` keeps it one click away; no HTML output files. Over 200,000 characters is explicitly truncated.\n\nEvery agent claim has one `<result>`: inline, one line, what it proved (`<result><code>897 passed (897)</code></result>`); it is the claim\'s whole line on the page, and Check notes an agent claim without one. Its `code` values follow the copied-value rule below. Claims from the same environment and build use the identical `from` string: the page groups checks by exact `from` and writes it once per group. Above the output, write the result for the person reading: nobody should have to read a log to see what it proved. A claim may hold p, ul/ol, table (tr/th/td), steps (`step title="…"` with block children), codeblock, img, alert, details and inline marks. A table or steps directly inside the claim folds its raw output behind one line. Inside a table or steps, inline `code` means "copied from this claim\'s output": write the value exactly as the output prints it, with no rounding and no unit change. Check and the page name any such value the output does not contain, and that claim then waits on the human. Expected values, ordinals and your own wording stay outside `code`; commands go in a codeblock.\n\njudge="agent" means a command decided the stated predicate, ran in the claimed environment, passed and has raw output plus from. Missing evidence/from needs human judgment. A failed check is a fix or gap, never a passed agent claim. judge="human" requires an ask explaining what would make the judgment wrong; use for unresolved nonscreen tradeoffs, not to re-ask approved decisions. A human claim holding a long table (rulings, decisions) marks each row `<tr cost="change|small|none">`: change (wrong means behavior must change), small (a small cost), none (no effect). Only change rows show; small and none fold behind a count. Check notes a human-claim table over 12 rows without cost. A rejected agent claim remains human-owned until the human passes it, even after new evidence.\n\nGap needs id/title/why/needs (one specific unblock); why and needs may hold inline marks and refs.\n\nReferences: inside a claim\'s p, li or td, the intro and a gap\'s why or needs, write the same inline `<ref>` a document does (`<ref document="spec" block="retry"/>`, `<ref whiteboard="flow" frame="f1"/>`, `<ref verify="login"/>`…) to link the discussion or artifact a claim rests on; it opens beside the report and counts toward nothing. Never inside <result>, and never standing alone in a claim. Missing targets are Check warnings. `<ref verify="slug"/>` at the top level makes another report a part of this one: it counts as one item that passes when that report is done, waits while it waits, and is rejected while it has a rejection; the status line gives each one a sentence with a link. Split a large piece of work into reports this way; reports that wait on each other in a loop are a Check warning. `<ref artboard="slug" group="v2"/>` counts a screen claim toward done; the page sums the groups per artboard in one status-line sentence with a link, not as rows, so the verdict is given on the artboard. Read via comment list; record pass/reject/waive only if requested by the human, reply on rejection threads and replace evidence after a repair. Stable IDs preserve verdicts/comments. Never edit comments.json or `.state/`. Run `check --artifact verify/<id>` before sharing.\n';function IE(e,t){if(t===`pass`||t===`reject`){let n=t===`pass`&&!!e.all;if(!n&&!e.claim)throw new j(t===`pass`?`comment pass on a report needs --claim <claimId>, or --all`:`comment reject on a report needs --claim <claimId>`);let r=t===`reject`?rt(e):e.text?.trim();return{op:`verdict`,verdict:t,...n?{all:!0}:{claim:e.claim},...r?{text:r}:{}}}if(t===`waive`){if(!e.gap)throw new j(`comment waive needs --gap <gapId>`);let t=e.text?.trim();return{op:`waive`,gap:e.gap,...t?{text:t}:{}}}if(t===`reply`){if(!e.thread)throw new j(`comment reply needs --thread <threadId>`);return{op:`reply`,threadId:e.thread,text:rt(e)}}throw new j(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}const LE={artboard:st,document:ab,html:ob,whiteboard:{authoring:`# Whiteboard writing
1069
1069
 
1070
1070
  Write \`scene.excalidraw\` (main page); optional \`pages.json\` and \`pages/<id>.excalidraw\`. The browser and agent collaborate live. Preserve IDs and all customData (\`ryugiAuthor\`, \`ryugiRev\`, \`ryugiLastBy\`). Never manufacture revision fields or force over a conflict; the server merges by \`ryugiRev\` and keeps the human version of a conflicting element. Missing elements are not deletion; retain the element and set \`isDeleted:true\`. Bound labels are separate text elements: edit text and originalText.
1071
1071
 
@@ -1230,15 +1230,15 @@ StandardError=append:${t}
1230
1230
  WantedBy=default.target
1231
1231
  `}const sk=(e,t)=>{if(e.status!==0)throw Error(`${t} failed: ${e.stderr.trim()}`)},ck=e=>{try{return u.default.readFileSync(e,`utf8`)}catch{return null}},lk=e=>{let t=ck(e);return t!==null&&!t.includes(nk)},uk=(e,t)=>{u.default.mkdirSync(d.default.dirname(e),{recursive:!0}),u.default.writeFileSync(e,t)};function dk(e){let t=`gui/${e.uid}/${ek}`,n=d.default.join(e.home,`Library`,`LaunchAgents`,`${ek}.plist`),r=d.default.join(e.serverHome,`${ek}.plist`),i=e=>e?n:r;return{file:i,kind:`agent`,check:()=>null,disable:()=>{},legacy:()=>lk(n),render:ik,write:e=>(uk(i(e.autostart),ik(e)),u.default.rmSync(i(!e.autostart),{force:!0}),i(e.autostart)),load:n=>{e.run(`launchctl`,[`bootout`,t]),sk(e.run(`launchctl`,[`bootstrap`,`gui/${e.uid}`,i(n)]),`launchctl bootstrap`)},unload:()=>{e.run(`launchctl`,[`bootout`,t])},linger:()=>void 0}}function fk(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`)},a=()=>d.default.join(i(),`systemd`,`user`,tk);return{file:a,kind:`service`,check:()=>{let e=r();return e.status===0?null:`systemd user services are not available here (systemctl --user: ${e.stderr.trim()||`failed`})`},disable:()=>{t(`disable`,tk)},legacy:()=>lk(a()),render:ok,write:e=>(uk(a(),ok(e)),a()),load:e=>{sk(t(`daemon-reload`),`systemctl --user daemon-reload`),e?sk(t(`enable`,tk),`systemctl --user enable ${tk}`):t(`disable`,tk),sk(t(`restart`,tk),`systemctl --user restart ${tk}`)},unload:()=>{t(`stop`,tk)},linger:()=>{let t=e.run(`loginctl`,[`enable-linger`]);return t.status===0?{enabled:!0}:{enabled:!1,error:t.stderr.trim()||`exit ${t.status}`}}}}function pk(e){return e.platform===`darwin`?dk(e):e.platform===`linux`?fk(e):null}const mk={darwin:[`arm64`],linux:[`x64`,`arm64`]};function hk(e=process.env,t=process.platform,n=process.getuid?.()??-1,r=m.default.tmpdir()){return e.RYUGI_RUNTIME_DIR?d.default.join(e.RYUGI_RUNTIME_DIR,`servers`):t===`win32`?d.default.join(r,`ryugi`,`servers`):`/tmp/ryugi-${n}/servers`}const gk=(e,t)=>d.default.join(e,`${f.default.createHash(`sha256`).update(t).digest(`hex`).slice(0,16)}.json`);function _k(e){if(process.platform!==`win32`)for(let t of[d.default.dirname(e),e]){let e=u.default.lstatSync(t);if(!e.isDirectory()||e.uid!==process.getuid()||e.mode&18)throw Error(`Unsafe registry directory: ${t}`)}}function vk(e){try{let t=JSON.parse(u.default.readFileSync(e,`utf8`));return typeof t.project!=`string`||typeof t.root!=`string`||typeof t.serverId!=`string`||!Number.isInteger(t.pid)||!Number.isFinite(t.startedAt)||![`.artideck`,`.ryugi`].some(e=>t.root===d.default.join(t.project,e,`artifacts`))?null:t}catch{return null}}function yk(e){let t;try{_k(e),t=u.default.readdirSync(e)}catch{return[]}return t.filter(e=>e.endsWith(`.json`)).flatMap(t=>vk(d.default.join(e,t))??[])}function bk(e,t){let n=gk(e,t.project);vk(n)?.serverId===t.serverId&&u.default.rmSync(n,{force:!0})}const xk=/* @__PURE__ */ new Set([`darwin-arm64`,`linux-x64`,`linux-arm64`]),Sk=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,Ck=e=>Sk.test(e);async function wk(e,t,n,r,i,a){let o=`${n.replace(/\/+$/,``)}/v${t}/${e}`,s=await r(o,{signal:i});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`could not download ${e} ${t}: HTTP ${s.status}`),{status:s.status});let c=Number(s.headers.get(`content-length`))||void 0;a?.(0,c);let l=[],u=0,d=s.body?.getReader();for(let e=await d?.read();e&&!e.done;e=await d?.read())l.push(Buffer.from(e.value)),u+=e.value.length,a?.(u,c);let p=Buffer.concat(l),m=await r(`${o}.sha256`,{signal:i});if(!m.ok)throw Object.assign(/* @__PURE__ */ Error(`could not download the sha256 for ${e}: HTTP ${m.status}`),{status:m.status});if((await m.text()).trim().split(/\s+/)[0]?.toLowerCase()!==f.default.createHash(`sha256`).update(p).digest(`hex`))throw Error(`${e} failed its sha256 check; nothing was installed`);return p}function Tk(e,t){u.default.mkdirSync(d.default.dirname(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;u.default.writeFileSync(n,t,{mode:493}),u.default.chmodSync(n,493),u.default.renameSync(n,e)}const Ek=e=>d.default.join(we(e),`hook`),Dk=(e,t)=>d.default.join(Ek(e),t),Ok=[1,116,0];function kk(e){let t=e.split(/[-+]/)[0].split(`.`).map(Number),n=Ok.findIndex((e,n)=>t[n]!==e);return n!==-1&&t[n]>Ok[n]?`adeck-hook`:`ryugi-hook`}const Ak=(e,t,n)=>xk.has(`${e}-${t}`)?`${kk(n)}-${e}-${t}`:null;function jk(e){try{return u.default.statSync(e).isFile()&&!!(u.default.statSync(e).mode&73)}catch{return!1}}function Mk(e,t){try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));return t-n.at<(n.status===404?5:60)*6e4}catch{return!1}}function Nk(e,t){try{return u.default.writeFileSync(e,String(process.pid),{flag:`wx`}),!0}catch{}try{return t-u.default.statSync(e).mtimeMs<3e5?!1:(u.default.rmSync(e,{force:!0}),u.default.writeFileSync(e,String(process.pid),{flag:`wx`}),!0)}catch{return!1}}async function Pk(e){let t=Ak(e.platform,e.arch,e.version);if(!t||!Ck(e.version))return{status:`skipped`};let n=e.now??Date.now(),r=Dk(e.home,e.version),i=d.default.join(r,kk(e.version));if(jk(i))return{status:`present`};u.default.mkdirSync(r,{recursive:!0,mode:448});let a=d.default.join(r,`.failed`);if(!e.retry&&Mk(a,n))return{status:`skipped`,error:`the last download failed; it is retried later`};let o=d.default.join(r,`.lock`);if(!Nk(o,n))return{status:`skipped`,error:`another download is in progress`};let s=AbortSignal.timeout(e.timeoutMs??6e4);try{let n=process.env.RYUGI_HOOK_RELEASE_BASE||`https://github.com/Innei/ryugi/releases/download`;return Tk(i,await wk(t,e.version,n,e.fetch,s,e.onProgress)),u.default.rmSync(a,{force:!0}),{status:`installed`}}catch(t){let r=t.status??null;return u.default.writeFileSync(a,JSON.stringify({at:n,status:r})),{status:`failed`,error:s.aborted?`the download of ${kk(e.version)} ${e.version} timed out`:t.message}}finally{u.default.rmSync(o,{force:!0})}}const Fk=(e,t)=>d.default.resolve(e)===d.default.join(we(t),`server`),Ik=e=>e===`win32`?`adeck-daemon.exe`:`adeck-daemon`,Lk=(e,t)=>`adeck-daemon-${e}-${t}${e===`win32`?`.exe`:``}`,Rk=e=>d.default.join(d.default.dirname(e),d.default.basename(e).replace(/^adeck-daemon/,`ryugi-daemon`));function zk(e,t){Tk(e,t),u.default.rmSync(Rk(e),{force:!0})}function Bk(e){return Fk(e.serverHome,e.home)?d.default.join(we(e.home),`bin`,Ik(e.platform)):d.default.join(e.serverHome,`bin`,Ik(e.platform))}function Vk(e){let t=(0,p.spawnSync)(e,[`--version`],{encoding:`utf8`,timeout:5e3}),n=/^(?:adeck|ryugi)-daemon (\S+)(?: \(src ([^)]+)\))?/.exec(t.stdout??``);return t.status!==0||!n?null:{version:n[1],...n[2]?{source:n[2]}:{}}}const Hk=(e,t)=>!!e&&(t.daemonSource?e.source===t.daemonSource:e.version===t.version);async function Uk(e){let t=e.timeoutMs??18e4,n=AbortSignal.timeout(t);try{return await wk(Lk(e.platform,e.arch),e.version,e.env.RYUGI_DAEMON_RELEASE_BASE||`https://github.com/Innei/ryugi/releases/download`,e.fetch,n)}catch(e){throw n.aborted?Error(`the download timed out after ${t/1e3} s`,{cause:e}):e}}var Wk=class extends Error{};async function Gk(e,t){let n=e.env.RYUGI_DAEMON_BIN;if(n){if(!u.default.existsSync(n))throw new Wk(`RYUGI_DAEMON_BIN names ${n}, which does not exist`);return n}let r=Bk(e);if(!Ck(e.version)){let t=[d.default.join(e.cliDir,Ik(e.platform)),r].find(e=>u.default.existsSync(e));if(t)return t;throw new Wk(`This adeck is a local build (${e.version||`no version`}), so there is no adeck-daemon release to download for it. Build one with \`cargo build --manifest-path daemon/Cargo.toml\` and set RYUGI_DAEMON_BIN to it.`)}return u.default.existsSync(r)&&Hk(Vk(r),e)||(t?.(),zk(r,await Uk(e).catch(t=>{throw new Wk(`Could not download adeck-daemon ${e.version} for ${e.platform}-${e.arch}: ${t.message}. The hub runs from that binary and there is no other way to start it; check the network, or set RYUGI_DAEMON_BIN to a adeck-daemon build.`)}))),r}const Kk=e=>d.default.join(e,`settings.json`);function qk(e){try{let t=JSON.parse(u.default.readFileSync(Kk(e),`utf8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}const Jk=e=>qk(e).sessionControl===!0;function Yk(e,t){u.default.mkdirSync(e,{recursive:!0,mode:448}),IC(Kk(e),{...qk(e),sessionControl:t})}const Xk=/^(RYUGI_|ARTIFACTS_|XDG_|LC_)|^(HOME|USER|LOGNAME|SHELL|LANG|TMPDIR|PATH|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|SSL_CERT_DIR)$|_proxy$|_PROXY$/,Zk=e=>d.default.join(e.home,`launch.json`),Qk=(e,t)=>[`hub`,`--artifacts-server-id=${e}`,...t?[`--port=${t}`]:[]];function $k(e,t){let n={...process.env,ARTIFACTS_HOST:e,ARTIFACTS_URL_HOST:t,RYUGI_NODE:process.execPath,RYUGI_DOCUMENT_ENGINE:d.default.join(__dirname,`document-engine.cjs`),RYUGI_VIEWER_DIR:d.default.join(__dirname,`viewer`),RYUGI_RUNTIME_ASSETS_DIR:d.default.join(__dirname,`runtime`),...re?{RYUGI_PACKAGE:re}:{}};process.env.RYUGI_ARTIFACTS_COMMAND&&(n.RYUGI_ARTIFACTS_LAUNCHER=process.env.RYUGI_ARTIFACTS_COMMAND);for(let e of[`RYUGI_WRITER_HOST`,`RYUGI_WRITER_AGENT`,`RYUGI_ARTIFACTS_OWNER`,`RYUGI_ARTIFACTS_VERSION`,`RYUGI_ARTIFACTS_COMMAND`,`ARTIFACTS_OPEN_CMD`,`ARTIFACTS_ROOT`])delete n[e];return n}function eA(e,t){let n=Object.fromEntries(Object.entries(t.env).filter(e=>Xk.test(e[0])&&e[1]!==void 0)),r=Zk(e),i=`${r}.${process.pid}.tmp`;u.default.writeFileSync(i,`${JSON.stringify({args:t.args,env:n},null,2)}\n`,{mode:384}),u.default.renameSync(i,r),u.default.rmSync(d.default.join(e.home,`hub-start-failures`),{force:!0})}function tA(e){try{let t=JSON.parse(u.default.readFileSync(Zk(e),`utf8`));return Array.isArray(t.args)&&t.env&&typeof t.env==`object`?{args:t.args,env:t.env}:null}catch{return null}}const nA=[`RYUGI_NODE`,`RYUGI_DOCUMENT_ENGINE`,`RYUGI_VIEWER_DIR`,`RYUGI_RUNTIME_ASSETS_DIR`];function rA(e,t){let n=tA(e);return!n||nA.some(e=>n.env[e]!==t[e])}function iA(e,t){let n=e.args.filter(e=>!e.startsWith(`--artifacts-server-id=`));return{...e,args:[n[0]??`hub`,`--artifacts-server-id=${t}`,...n.slice(1)]}}const aA=(e,t)=>{let n=(0,p.spawnSync)(e,t,{encoding:`utf8`});return{status:n.status,stderr:n.stderr||(n.error?.message??``),stdout:n.stdout??``}},oA=(e,t=aA)=>({configHome:process.env.XDG_CONFIG_HOME||void 0,home:m.default.homedir(),platform:process.platform,run:t,serverHome:e.home,uid:process.getuid?.()??0});function sA(e){if(!Fk(e.home,m.default.homedir()))return null;let t=pk(oA(e));return t&&!t.check()?t:null}const cA=e=>{let t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0};async function lA(e,t){try{return await Gk({arch:process.arch,cliDir:__dirname,daemonSource:w||void 0,env:process.env,fetch,home:m.default.homedir(),platform:process.platform,serverHome:e.home,timeoutMs:cA(process.env.RYUGI_DAEMON_DOWNLOAD_TIMEOUT_MS),version:t})}catch(e){throw e instanceof Wk?new j(e.message):e}}function uA(e,t){let n=sA(e);if(!n)return!1;let r=n.legacy();r&&Yk(e.home,!0);let i=r||Jk(e.home);try{return n.write({autostart:i,binary:t,launch:Zk(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`}),n.load(i),!0}catch{return!1}}const dA=1e4,fA=((e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t})(`RYUGI_START_ALIVE_MS`,1e3),pA=(e,t)=>e.split(`
1232
1232
  `).find(e=>e.includes(`"${t}"`));async function mA(e,t,n,r){eA(e,n);try{u.default.renameSync(e.log,`${e.log}.1`)}catch{}let i;if(!uA(e,t)){let r=u.default.openSync(e.log,`w`),a=(0,p.spawn)(t,n.args,{env:n.env,detached:!0,windowsHide:!0,stdio:[`ignore`,r,r]});u.default.closeSync(r),a.unref(),i=a.pid,u.default.writeFileSync(e.pid,`${a.pid}\n`)}for(let t=0;t<dA;t+=100){let t=He(e.log)??``,n=pA(t,`server-started`);if(n){let t=JSON.parse(n),a=i??t.pid;a&&u.default.writeFileSync(e.pid,`${a}\n`);for(let e=0;e<fA;e+=100){if(a&&!Ie(a))throw new j(`Server started but was killed. Retry in a persistent terminal with: ${r}`);await Fe(100)}return{info:t}}let a=pA(t,`server-error`);if(a)return{failed:JSON.parse(a)};let o=pA(t,`server-standing-down`);if(o){let e=JSON.parse(o);return{failed:{type:`server-error`,error:`Another hub (pid ${e.pid}, port ${e.port}) already serves this machine; stop it and retry`}}}await Fe(100)}throw new j(`Server failed to start within ${dA/1e3} seconds`)}function hA(e){let t=eD(process.env,process.platform,m.default.homedir());if($E(t,ZE(process.env)))return;let n=d.default.join(d.default.dirname(t),`login-hint-shown`);try{u.default.mkdirSync(d.default.dirname(n),{recursive:!0,mode:448}),u.default.writeFileSync(n,`1
1233
- `,{flag:`wx`,mode:384})}catch(e){if(e.code===`EEXIST`)return}return{message:`Recommended: sign in to Artideck Cloud to share artifacts and review them from other devices. Sign-in is optional; local work can continue.`,command:`${process.env.RYUGI_ARTIFACTS_COMMAND||`npx artideck`} publish --login --from hint`,projectDir:e,agentInstruction:`Briefly pass this recommendation to your human partner and offer to run command in projectDir. It prints a code and an address; they confirm the code on any device signed in to Artideck Cloud, such as their phone. Continue the current task without waiting for sign-in.`}}function gA(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 _A(e,t){let n=t?d.default.dirname(d.default.dirname(t.root)):e.projectDir,r=e.artifact?JE(n,e.artifact):void 0;return{cliVersion:`1.119.0`,serverVersion:He(XD().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:KE(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 vA({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(e.artifact?.startsWith(`document/`)?`Source`:`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 yA(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&Jv(n)?LE[n].onStart:void 0;r&&r(d.default.join(ve(d.default.dirname(d.default.dirname(t.root))),e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[],a=_A(e,t);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(a,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*bA(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=GA(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:yA(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({..._A(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({..._A(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 xA(e,t=`start`){let n=gA(e);return n.library=t===`browse`,n.foreground?Z({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>bA(n,t),present:vA},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 GA(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 yA(n,r)},present:vA},e)}const SA=e=>e.startsWith(`local-`),CA=e=>/^\d+\.\d+\.\d+$/.test(e)?e.split(`.`).map(Number):null;function wA(e,t){let n=CA(e),r=CA(t);if(!n||!r)return!1;for(let e=0;e<3;e++)if(n[e]!==r[e])return n[e]<r[e];return!1}function TA(e,t){return e&&t&&e===t?`keep`:SA(e)&&t&&!SA(t)||wA(t,e)?`protected`:`replace`}const EA=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},DA=EA(`RYUGI_START_SETTLE_MS`,6e3),OA=EA(`RYUGI_STOP_GRACE_MS`,7e3),kA=e=>ZE(e),AA=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},jA=(e,t)=>{let n=AA(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function MA(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=Lb(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${LT(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function NA(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(jA(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 PA(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 Fe(100)}return!1}function FA(e){let t=Number(He(e.pid)),n=He(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:Be(t,n)?t:null}function IA(e){try{let t=JSON.parse(He(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function LA(e){try{return(await fetch(jA(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function RA(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await Ve(e,OA)){try{process.kill(e,`SIGKILL`)}catch{}if(!await Ve(e,2e3))throw new j(`The ${t} (pid ${e}) did not stop; stop it with \`${Qe()} stop\` and retry`)}}async function zA(){let e=hk();for(let t of yk(e)){if(Be(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await Ve(t.pid,5e3)}try{bk(e,t)}catch{}}}function BA(e,t){if(!t||t.startsWith(`document/`))return;let n=Object.fromEntries(OO.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`)}async function VA(e,t,n){let r=await fetch(jA(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 j(`The artifacts server refused this project: ${await r.text()}`)}async function HA(e,t){let n=XD({RYUGI_SERVER_HOME:e}),r=pk(t??oA(n)),i=[!0,!1].find(t=>{try{return u.default.readFileSync(r.file(t),`utf8`).includes(e)}catch{return!1}});r&&i!==void 0&&r.unload();let a=FA(n);return a&&await RA(a,`artifacts server`),i}async function UA(e,{env:t=process.env,home:n=m.default.homedir(),host:r}={}){let i=!1,a=await Ee({env:t,home:n,stopLegacyHub:async e=>{i=await HA(e,r??oA(XD({RYUGI_SERVER_HOME:e})))!==void 0}});return(a.status===`moved`||a.status===`merged`)&&e(a.conflicts.length?`Moved ~/.ryugi to ~/.artideck; ${a.conflicts.length} file(s) exist in both and stay in ~/.ryugi.`:`Moved ~/.ryugi to ~/.artideck.`),a.status===`failed`&&e(`Could not move ~/.ryugi to ~/.artideck: ${a.error}`),{...a,serviceStopped:i}}async function WA(){let e=XD();return uA(e,await lA(e,process.env.RYUGI_ARTIFACTS_VERSION||`1.119.0`))}async function GA(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!$e.test(e.artifact))throw new j(et);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new j(`--port must be a port number`);e.urlHost||=e.host===`127.0.0.1`||e.host===`localhost`?`localhost`:e.host,process.umask(63),await UA(e=>t.log(e,`stderr`));let n=Ze(e.projectDir),r=XD();ZD(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`),`*
1234
- `);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.119.0`,a=$D(r.projects).some(e=>e.dir===n.project),o=async(r,i)=>{BA(n,e.artifact);let o=e.open&&!e.library&&(!i||!a);await VA(r,n,o?e.artifact??!0:void 0);let s=MA(r,n,e.artifact);i&&(s.reused=!0);let c=await NA(s,r,n,e.artifact),l=hA(n.project);if(t.signal?.throwIfAborted(),e.library&&e.open&&(process.env.ARTIFACTS_OPEN_CMD?await new Promise(e=>(0,p.execFile)(process.env.ARTIFACTS_OPEN_CMD,[r.url],()=>e())):await $O(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 $O(typeof c.cloudLink==`string`?c.cloudLink:e,[e]).catch(e=>t.log(e.message,`stderr`))}};if(!await PA(r.lock))throw new j(`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=FA(r),s=IA(r),l=null;if(a&&!s){for(let e=0;e<DA&&Ie(a)&&!s;e+=100)await Fe(100),s=IA(r);!s&&Ie(a)&&(l={label:`stopping artifacts server`,pid:a,reasons:[`no-info`],running:He(r.version)??``})}if(a&&s){let t=He(r.version)??``,n=TA(t,i),u=[...n===`keep`?[]:[`version`],...(s.host??`127.0.0.1`)===e.host?[]:[`host`],...(s.urlHost??`localhost`)===e.urlHost?[]:[`urlHost`],...(s.cloudOrigin??`https://artideck.dev`)===kA(process.env)?[]:[`cloudOrigin`],...e.port!==void 0&&String(s.port)!==e.port?[`port`]:[],...rA(r,$k(e.host,e.urlHost))?[`launch`]:[]],d={pid:a,running:t,cli:i},f=n===`protected`||u.length===0;if(f&&await LA(s))return u.length&&YO(r,{...d,action:`kept`,reasons:u}),c(),await o(s,!0),0;l={label:`running artifacts server`,pid:a,reasons:f?[...u,`unanswered`]:u,running:t}}let d=await lA(r,i);l&&(YO(r,{action:`replaced`,cli:i,pid:l.pid,reasons:l.reasons,running:l.running}),await RA(l.pid,l.label)),await zA(),u.default.rmSync(r.info,{force:!0});let m=f.default.randomBytes(24).toString(`hex`);u.default.writeFileSync(r.serverId,`${m}\n`),u.default.writeFileSync(r.version,`${i}\n`);let h={args:Qk(m,e.port),env:$k(e.host,e.urlHost)};if(e.foreground){eA(r,h);let e=(0,p.spawn)(d,h.args,{env:h.env,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);g.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;g.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)}}let _=await mA(r,d,h,`${Qe()} start --project-dir ${n.project}${e.artifact?` --artifact ${e.artifact}`:``} --host ${e.host} --url-host ${e.urlHost} --foreground`);return`failed`in _?(t.failure(_.failed),1):(c(),await o(_.info,!1),0)}finally{c()}}const KA={semantic:xA,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`}}};async function qA(e,t,n,r,i){u.default.mkdirSync(d.default.dirname(e),{recursive:!0});let a=d.default.join(d.default.dirname(e),`.`+d.default.basename(e)),o=a+`.`+(0,f.randomUUID)()+`.tmp`,s=a+`.write-lock`;if(!await PA(s))throw new j(`Another document save is in progress. Retry after it finishes.`);try{let r=null;try{r=u.default.readFileSync(e,`utf8`)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.trimEnd()!==t?.trimEnd())throw new j(`Document changed since the base; nothing was saved.`);if(n===r)return;r===null&&de(d.default.dirname(e));let i=r?.match(/^\s*<doc (ryugi-attribution="[A-Za-z0-9_-]+")(?=[\s>])/),a=n.replace(/^(\s*<doc) ryugi-attribution="[A-Za-z0-9_-]+"(?=[\s>])/,`$1`);u.default.writeFileSync(o,i?a.replace(/^(\s*<doc)/,`$1 ${i[1]}`):a,{mode:r===null?384:u.default.statSync(e).mode&511}),u.default.renameSync(o,e)}finally{u.default.rmSync(o,{force:!0}),u.default.rmdirSync(s)}}const JA={hidden:!0,name:`write-document`,summary:`Save a document revision with the calling agent’s attribution`,usage:[`--artifact document/<id> --input <edited.xml> [--base <original.xml>]`],options:{artifact:{type:`string`,help:`Document to create or edit`},base:{type:`string`,help:`Unedited copy from before the edit (omit for creation)`},input:{type:`string`,help:`Edited copy of the LiteXML file`}},semantic:e=>Z({id:`write-document`,mode:`finite`,output:{formats:[`brief`,`json`],fields:[`artifact`,`author`]},run:async()=>{let{artifact:t,base:n,input:r}=e.values;if(typeof t!=`string`||!t.startsWith(`document/`)||!$e.test(t)||typeof r!=`string`)throw new j(`Supply --artifact document/<id> and --input <file>.`);let i=NO(process.env);if(!i)throw new j(`No agent identity in the writing process environment.`);await qA(d.default.join(Je(e.projectDir).root,t,`doc.xml`),typeof n==`string`?u.default.readFileSync(n,`utf8`):null,u.default.readFileSync(r,`utf8`),i,BO(i,process.env));let a;try{a=(await WO({artifact:t,projectDir:e.projectDir})).json.attribution}catch(e){a={status:`unavailable`,message:e.message}}return J({artifact:t,author:i},void 0,{warnings:a?.status===`unavailable`?[{code:`W_ATTRIBUTION`,message:a.message??`Attribution was not recorded`}]:[]})},present:({data:e})=>({heading:`Document`,status:`SAVED`,subject:e.artifact,summary:e.author,facts:[],sections:[]})},e)},YA=[`desktop`,`laptop`,`tablet`,`mobile`],XA=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),ZA=4096;function QA(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(!XA.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 $A(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=QA(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function ej(e){if(typeof e==`string`)return YA.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<=ZA&&n>=240&&n<=ZA)return{w:t,h:n}}return null}function tj(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function nj(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=QA(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=tj(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=ej(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${YA.join(`, `)} or { w, h } (240..${ZA})`)}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 rj=`preview.json`,ij=/^[a-z0-9][a-z0-9-]{0,63}$/;function aj(e){return d.default.join(d.default.dirname(e),`preview`)}function oj(e,t){return ij.test(t)?d.default.join(aj(e),t):null}function sj(e){let t=aj(e),n;try{n=u.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!ij.test(e))continue;let n=d.default.join(t,e);u.default.existsSync(d.default.join(n,rj))&&r.push({id:e,payload:cj(n,e)})}return r}function cj(e,t,n){let r=d.default.join(e,rj),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}=nj(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function lj(e,t){u.default.mkdirSync(e,{recursive:!0}),IC(d.default.join(e,rj),t)}function uj(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 dj(e,t=800){let n=QA(e);if(!n)return!1;if(n.hostname!==`localhost`)return uj(n.hostname,n.port,t);let r=await Promise.all([uj(`127.0.0.1`,n.port,t),uj(`::1`,n.port,t)]);return r[0]||r[1]}function fj(e){let t=typeof e==`string`&&e.trim()?e.trim():`dev`;if(!ij.test(t))throw new j(`Preview --id must use lowercase letters, digits, and hyphens.`);return t}function pj(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 mj({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(`
1233
+ `,{flag:`wx`,mode:384})}catch(e){if(e.code===`EEXIST`)return}return{message:`Recommended: sign in to Artideck Cloud to share artifacts and review them from other devices. Sign-in is optional; local work can continue.`,command:`${process.env.RYUGI_ARTIFACTS_COMMAND||`npx artideck`} publish --login --from hint`,projectDir:e,agentInstruction:`Briefly pass this recommendation to your human partner and offer to run command in projectDir. It prints a code and an address; they confirm the code on any device signed in to Artideck Cloud, such as their phone. Continue the current task without waiting for sign-in.`}}function gA(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 _A(e,t){let n=t?d.default.dirname(d.default.dirname(t.root)):e.projectDir,r=e.artifact?JE(n,e.artifact):void 0;return{cliVersion:`1.120.1`,serverVersion:He(XD().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:KE(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 vA({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(e.artifact?.startsWith(`document/`)?`Source`:`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 yA(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&Jv(n)?LE[n].onStart:void 0;r&&r(d.default.join(ve(d.default.dirname(d.default.dirname(t.root))),e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[],a=_A(e,t);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(a,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*bA(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=GA(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:yA(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({..._A(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({..._A(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 xA(e,t=`start`){let n=gA(e);return n.library=t===`browse`,n.foreground?Z({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>bA(n,t),present:vA},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 GA(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 yA(n,r)},present:vA},e)}const SA=e=>e.startsWith(`local-`),CA=e=>/^\d+\.\d+\.\d+$/.test(e)?e.split(`.`).map(Number):null;function wA(e,t){let n=CA(e),r=CA(t);if(!n||!r)return!1;for(let e=0;e<3;e++)if(n[e]!==r[e])return n[e]<r[e];return!1}function TA(e,t){return e&&t&&e===t?`keep`:SA(e)&&t&&!SA(t)||wA(t,e)?`protected`:`replace`}const EA=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},DA=EA(`RYUGI_START_SETTLE_MS`,6e3),OA=EA(`RYUGI_STOP_GRACE_MS`,7e3),kA=e=>ZE(e),AA=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},jA=(e,t)=>{let n=AA(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function MA(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=Lb(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${LT(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function NA(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(jA(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 PA(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 Fe(100)}return!1}function FA(e){let t=Number(He(e.pid)),n=He(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:Be(t,n)?t:null}function IA(e){try{let t=JSON.parse(He(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function LA(e){try{return(await fetch(jA(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function RA(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await Ve(e,OA)){try{process.kill(e,`SIGKILL`)}catch{}if(!await Ve(e,2e3))throw new j(`The ${t} (pid ${e}) did not stop; stop it with \`${Qe()} stop\` and retry`)}}async function zA(){let e=hk();for(let t of yk(e)){if(Be(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await Ve(t.pid,5e3)}try{bk(e,t)}catch{}}}function BA(e,t){if(!t||t.startsWith(`document/`))return;let n=Object.fromEntries(OO.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`)}async function VA(e,t,n){let r=await fetch(jA(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 j(`The artifacts server refused this project: ${await r.text()}`)}async function HA(e,t){let n=XD({RYUGI_SERVER_HOME:e}),r=pk(t??oA(n)),i=[!0,!1].find(t=>{try{return u.default.readFileSync(r.file(t),`utf8`).includes(e)}catch{return!1}});r&&i!==void 0&&r.unload();let a=FA(n);return a&&await RA(a,`artifacts server`),i}async function UA(e,{env:t=process.env,home:n=m.default.homedir(),host:r}={}){let i=!1,a=await Ee({env:t,home:n,stopLegacyHub:async e=>{i=await HA(e,r??oA(XD({RYUGI_SERVER_HOME:e})))!==void 0}});return(a.status===`moved`||a.status===`merged`)&&e(a.conflicts.length?`Moved ~/.ryugi to ~/.artideck; ${a.conflicts.length} file(s) exist in both and stay in ~/.ryugi.`:`Moved ~/.ryugi to ~/.artideck.`),a.status===`failed`&&e(`Could not move ~/.ryugi to ~/.artideck: ${a.error}`),{...a,serviceStopped:i}}async function WA(){let e=XD();return uA(e,await lA(e,process.env.RYUGI_ARTIFACTS_VERSION||`1.120.1`))}async function GA(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!$e.test(e.artifact))throw new j(et);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new j(`--port must be a port number`);e.urlHost||=e.host===`127.0.0.1`||e.host===`localhost`?`localhost`:e.host,process.umask(63),await UA(e=>t.log(e,`stderr`));let n=Ze(e.projectDir),r=XD();ZD(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`),`*
1234
+ `);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.120.1`,a=$D(r.projects).some(e=>e.dir===n.project),o=async(r,i)=>{BA(n,e.artifact);let o=e.open&&!e.library&&(!i||!a);await VA(r,n,o?e.artifact??!0:void 0);let s=MA(r,n,e.artifact);i&&(s.reused=!0);let c=await NA(s,r,n,e.artifact),l=hA(n.project);if(t.signal?.throwIfAborted(),e.library&&e.open&&(process.env.ARTIFACTS_OPEN_CMD?await new Promise(e=>(0,p.execFile)(process.env.ARTIFACTS_OPEN_CMD,[r.url],()=>e())):await $O(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 $O(typeof c.cloudLink==`string`?c.cloudLink:e,[e]).catch(e=>t.log(e.message,`stderr`))}};if(!await PA(r.lock))throw new j(`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=FA(r),s=IA(r),l=null;if(a&&!s){for(let e=0;e<DA&&Ie(a)&&!s;e+=100)await Fe(100),s=IA(r);!s&&Ie(a)&&(l={label:`stopping artifacts server`,pid:a,reasons:[`no-info`],running:He(r.version)??``})}if(a&&s){let t=He(r.version)??``,n=TA(t,i),u=[...n===`keep`?[]:[`version`],...(s.host??`127.0.0.1`)===e.host?[]:[`host`],...(s.urlHost??`localhost`)===e.urlHost?[]:[`urlHost`],...(s.cloudOrigin??`https://artideck.dev`)===kA(process.env)?[]:[`cloudOrigin`],...e.port!==void 0&&String(s.port)!==e.port?[`port`]:[],...rA(r,$k(e.host,e.urlHost))?[`launch`]:[]],d={pid:a,running:t,cli:i},f=n===`protected`||u.length===0;if(f&&await LA(s))return u.length&&YO(r,{...d,action:`kept`,reasons:u}),c(),await o(s,!0),0;l={label:`running artifacts server`,pid:a,reasons:f?[...u,`unanswered`]:u,running:t}}let d=await lA(r,i);l&&(YO(r,{action:`replaced`,cli:i,pid:l.pid,reasons:l.reasons,running:l.running}),await RA(l.pid,l.label)),await zA(),u.default.rmSync(r.info,{force:!0});let m=f.default.randomBytes(24).toString(`hex`);u.default.writeFileSync(r.serverId,`${m}\n`),u.default.writeFileSync(r.version,`${i}\n`);let h={args:Qk(m,e.port),env:$k(e.host,e.urlHost)};if(e.foreground){eA(r,h);let e=(0,p.spawn)(d,h.args,{env:h.env,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);g.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;g.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)}}let _=await mA(r,d,h,`${Qe()} start --project-dir ${n.project}${e.artifact?` --artifact ${e.artifact}`:``} --host ${e.host} --url-host ${e.urlHost} --foreground`);return`failed`in _?(t.failure(_.failed),1):(c(),await o(_.info,!1),0)}finally{c()}}const KA={semantic:xA,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`}}};async function qA(e,t,n,r,i){u.default.mkdirSync(d.default.dirname(e),{recursive:!0});let a=d.default.join(d.default.dirname(e),`.`+d.default.basename(e)),o=a+`.`+(0,f.randomUUID)()+`.tmp`,s=a+`.write-lock`;if(!await PA(s))throw new j(`Another document save is in progress. Retry after it finishes.`);try{let r=null;try{r=u.default.readFileSync(e,`utf8`)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.trimEnd()!==t?.trimEnd())throw new j(`Document changed since the base; nothing was saved.`);if(n===r)return;r===null&&de(d.default.dirname(e));let i=r?.match(/^\s*<doc (ryugi-attribution="[A-Za-z0-9_-]+")(?=[\s>])/),a=n.replace(/^(\s*<doc) ryugi-attribution="[A-Za-z0-9_-]+"(?=[\s>])/,`$1`);u.default.writeFileSync(o,i?a.replace(/^(\s*<doc)/,`$1 ${i[1]}`):a,{mode:r===null?384:u.default.statSync(e).mode&511}),u.default.renameSync(o,e)}finally{u.default.rmSync(o,{force:!0}),u.default.rmdirSync(s)}}const JA={hidden:!0,name:`write-document`,summary:`Save a document revision with the calling agent’s attribution`,usage:[`--artifact document/<id> --input <edited.xml> [--base <original.xml>]`],options:{artifact:{type:`string`,help:`Document to create or edit`},base:{type:`string`,help:`Unedited copy from before the edit (omit for creation)`},input:{type:`string`,help:`Edited copy of the LiteXML file`}},semantic:e=>Z({id:`write-document`,mode:`finite`,output:{formats:[`brief`,`json`],fields:[`artifact`,`author`]},run:async()=>{let{artifact:t,base:n,input:r}=e.values;if(typeof t!=`string`||!t.startsWith(`document/`)||!$e.test(t)||typeof r!=`string`)throw new j(`Supply --artifact document/<id> and --input <file>.`);let i=NO(process.env);if(!i)throw new j(`No agent identity in the writing process environment.`);await qA(d.default.join(Je(e.projectDir).root,t,`doc.xml`),typeof n==`string`?u.default.readFileSync(n,`utf8`):null,u.default.readFileSync(r,`utf8`),i,BO(i,process.env));let a;try{a=(await WO({artifact:t,projectDir:e.projectDir})).json.attribution}catch(e){a={status:`unavailable`,message:e.message}}return J({artifact:t,author:i},void 0,{warnings:a?.status===`unavailable`?[{code:`W_ATTRIBUTION`,message:a.message??`Attribution was not recorded`}]:[]})},present:({data:e})=>({heading:`Document`,status:`SAVED`,subject:e.artifact,summary:e.author,facts:[],sections:[]})},e)},YA=[`desktop`,`laptop`,`tablet`,`mobile`],XA=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),ZA=4096;function QA(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(!XA.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 $A(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=QA(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function ej(e){if(typeof e==`string`)return YA.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<=ZA&&n>=240&&n<=ZA)return{w:t,h:n}}return null}function tj(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function nj(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=QA(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=tj(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=ej(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${YA.join(`, `)} or { w, h } (240..${ZA})`)}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 rj=`preview.json`,ij=/^[a-z0-9][a-z0-9-]{0,63}$/;function aj(e){return d.default.join(d.default.dirname(e),`preview`)}function oj(e,t){return ij.test(t)?d.default.join(aj(e),t):null}function sj(e){let t=aj(e),n;try{n=u.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!ij.test(e))continue;let n=d.default.join(t,e);u.default.existsSync(d.default.join(n,rj))&&r.push({id:e,payload:cj(n,e)})}return r}function cj(e,t,n){let r=d.default.join(e,rj),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}=nj(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function lj(e,t){u.default.mkdirSync(e,{recursive:!0}),IC(d.default.join(e,rj),t)}function uj(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 dj(e,t=800){let n=QA(e);if(!n)return!1;if(n.hostname!==`localhost`)return uj(n.hostname,n.port,t);let r=await Promise.all([uj(`127.0.0.1`,n.port,t),uj(`::1`,n.port,t)]);return r[0]||r[1]}function fj(e){let t=typeof e==`string`&&e.trim()?e.trim():`dev`;if(!ij.test(t))throw new j(`Preview --id must use lowercase letters, digits, and hyphens.`);return t}function pj(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 mj({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(`
1235
1235
  `)}]:[]}}const hj={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=Je(e.projectDir);if(r===`list`){let e=sj(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=fj(e.values.id),r=e.values.url;if(!r)throw new j(`Pass --url http://localhost:<port>`);let a=$A(r);if(!a)throw new j(`--url must be a local loopback http URL (e.g. http://localhost:5182)`);let o=oj(i.root,t),s=null;try{s=nj(u.default.readFileSync(d.default.join(o,`preview.json`),`utf8`)).config}catch{}lj(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 GA({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 j(String(e.error??`Failed to start Hub`))},log(e){n.diagnostic(e)}})!==0||!c)throw new j(`Hub did not start.`);let l=`${new URL(c).origin}/preview/${encodeURIComponent(t)}?project=${encodeURIComponent(i.project)}`,f=await dj(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=fj(e.values.id),o=rO(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 j(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(pj):[`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 j(`Pass --thread <id> for preview ${r}`);let i=e.values.text;if(r===`reply`&&!i?.trim())throw new j(`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 j(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 j(`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 j(r.json?.error||`HTTP ${r.status}`);return J({action:`ack`,id:a,receipt:t,lines:[`Acknowledged receipt ${t}`]})}throw new j(`Unknown preview action "${r}". Use open, list, comments, reply, resolve, or ack.`)},present:mj},e)},gj=/^report\/[a-z0-9][a-z0-9-]*$/,_j=e=>typeof e==`object`&&!!e&&Array.isArray(e.sources),vj=({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`}`),yj={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 j(`usage: ryugi report refresh --artifact report/<id>`);let r=e.values.artifact;if(!r||!gj.test(r))throw new j(`--artifact must be report/<id>`);let i=e.values.only,a=await rO(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 j(a.json?.error||`HTTP ${a.status}`);if(!_j(a.json))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid refresh report.`});let o={...a.json,artifact:r,lines:vj(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:vj({sources:s}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:bj},e)};function bj({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??vj(e)).join(`
1236
1236
  `)},...e.issues?.length?[{kind:`content`,key:`issues`,text:e.issues.join(`
1237
1237
  `)}]:[]]}}const xj=/^storyboard\/[a-z0-9][a-z0-9-]*$/,Sj=e=>typeof e==`object`&&!!e&&Array.isArray(e.lines),Cj=e=>typeof e==`object`&&!!e&&typeof e.n==`number`&&Array.isArray(e.shots),wj=({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`}`),Tj=e=>{let t=Math.round(e);return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},Ej=e=>[`cut ${e.n}: ${e.file} · ${e.shots.length} shot${e.shots.length===1?``:`s`}, ${Tj(e.shots.at(-1)?.end??0)} · timing from the ${e.mapped===`map`?`map`:`storyboard's durations`}`],Dj=(e,t)=>d.default.resolve(e,t),Oj=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 kj(e,t,n){let r=d.default.join(ve(e),...t.split(`/`));if(!u.default.existsSync(r))throw new j(`${t} not found in ${e}`);return OE(r,n)?[`wrote ${DE}`]:[`${DE} is already there; pass --force to replace it with the latest template`]}const Aj=e=>typeof e==`object`&&!!e&&typeof e.state==`string`,jj=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(r),n()})});function Mj(e,t){if(t!==void 0)try{return JSON.parse(u.default.readFileSync(Dj(e,t),`utf8`))}catch(e){throw new j(`--map ${t} is not readable JSON: ${e.message}`)}}const Nj={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 j(`usage: ryugi storyboard voice|cut|export|template --artifact storyboard/<id>`);let i=e.values.artifact;if(!i||!xj.test(i))throw new j(`--artifact must be storyboard/<id>`);if(r===`template`)return J({action:r,artifact:i,lines:[],summary:kj(e.projectDir,i,!!e.values.force)},{kind:`succeeded`});let a=rO(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||!Aj(t.json))throw new j(t.json?.error||`HTTP ${t.status}`);let o=t.json,s=[];for(;e.values.wait&&o.state===`running`&&!n.signal?.aborted;){let e=Oj(o)[0];s.at(-1)!==e&&s.push(e),await jj(1e3,n.signal);let t=await a.call(`GET`,`/api/${i}/export`,void 0,n.signal);Aj(t.json)&&(o=t.json)}return J({action:r,artifact:i,export:o,lines:[],summary:[...s,...Oj(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 j(`storyboard cut needs --file <1080p.mp4>`);let o=Mj(e.projectDir,e.values.map),s=e.values.master,c=await a.call(`POST`,`/api/${i}/cut`,{file:Dj(e.projectDir,t),...o===void 0?{}:{map:o},...s?{master:Dj(e.projectDir,s)}:{}},n.signal);if(n.payloads.raw=c.raw,c.status<200||c.status>=300)throw new j(c.json?.error||`HTTP ${c.status}`);if(!Cj(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:Ej(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,!Sj(s.json))throw s.status<200||s.status>=300?new j(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:wj(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:wj({lines:l}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:Pj},e)};function Pj({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(`
1238
1238
  `)}]}}const Fj=/^whiteboard\/[a-z0-9][a-z0-9-]*$/,Ij=e=>{let t=e;return typeof e==`object`&&!!e&&typeof t.artifact==`string`&&typeof t.sceneVersion==`number`&&Array.isArray(t.lines)&&[`none`,`current`,`stale`].includes(t.render)},Lj={name:`scene`,summary:`Read a whiteboard: its render and a structure summary (needs a running server)`,usage:[`--artifact whiteboard/<id> [--page <pageId>] [--frame <frameId>]`],details:`Prints the scene version, where the latest browser render is and whether it shows the current scene, then one line per frame, element and arrow, with who drew each. On a whiteboard with several pages it lists the pages; --page or --frame reads one.`,options:{artifact:{type:`string`,value:`whiteboard/<id>`,help:`The whiteboard`},page:{type:`string`,value:`<pageId>`,help:`Read this page of a whiteboard with several pages`},frame:{type:`string`,value:`<frameId>`,help:`Only this frame and the arrows touching it, on whichever page holds it`}},semantic:e=>Z({id:`scene`,mode:`finite`,output:{detail:!1,formats:[`brief`,`json`,`jsonl`,`raw`],fields:[`artifact`,`page`,`pages`,`sceneVersion`,`render`,`renderPath`,`lines`,`conflicts`],scalar:e=>e.render},async run(t,n){let r=e.values.artifact;if(!r||!Fj.test(r))throw new j(`--artifact must be whiteboard/<id>`);let i=e.values.frame,a=e.values.page,o=await rO(e.projectDir).call(`POST`,`/api/agent/${r}/scene`,{...i?{frame:i}:{},...a?{page:a}:{}},n.signal);if(n.payloads.raw=o.raw,o.status<200||o.status>=300)throw new j(o.json?.error||`HTTP ${o.status}`);if(!Ij(o.json))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid scene report.`});let s=o.json;return J(s,{kind:`succeeded`},{actions:(s.pages??[]).map(t=>q([`scene`,`--artifact`,r,`--page`,t.id,`--project-dir`,e.projectDir],`Read ${t.id}`))})},present:Rj},e)};function Rj({data:e}){return{heading:`Scene`,status:e.problem?`invalid`:``,subject:e.artifact,facts:[...e.page?[X(`Page`,Y(e,`page`))]:[],X(`Version`,Y(e,`sceneVersion`)),X(`Render`,Y(e,`render`)),...e.renderPath?[X(`Image`,Y(e,`renderPath`))]:[],...e.problem?[X(`Problem`,Y(e,`problem`))]:[],X(`Conflicts`,{key:`conflicts`,value:e.conflicts.join(`, `)})],sections:[{kind:`content`,key:`lines`,text:e.lines.join(`
1239
- `)}]}}const zj={threads:[`id`,`status`,`waitingOn`,`anchor`,`stale`,`changes`,`messages`,`preview`,`messageCount`,`omittedMessages`],asks:[`id`,`state`,`choice`,`text`,`byRecommendation`,`staleChoice`,`note`],groups:[`id`,`kind`,`verdict`,`choice`,`by`,`byRecommendation`,`round`,`threads`,`evidenceUpdated`,`rejectThreads`,`title`,`from`,`capturedAt`],rounds:[`id`,`state`,`title`,`groups`,`submitted`]},Bj={threads:[`id`,`status`,`waitingOn`],asks:[`id`,`state`],groups:[`id`,`kind`,`verdict`,`choice`],rounds:[`id`,`state`]},Vj=e=>e.startsWith(`document/`)?[`threads`,`asks`]:[`threads`,`groups`,`rounds`];function Hj(e,t){return e.section?`Choose section or sections, not both.`:!e.sections.length||new Set(e.sections).size!==e.sections.length||e.sections.some(e=>!Vj(t).includes(e))?`Choose distinct review sections supported by this artifact.`:e.fields||e.cursor||e.snapshot||e.thread||e.filters&&Object.values(e.filters).some(e=>e!==void 0)?`Fields, filters, thread, cursor and snapshot require a single --section. Follow each collection continuation separately.`:null}function Uj(e){let{section:t,filters:n}=e;if(!t&&(e.detail||e.cursor||e.fields||n&&Object.values(n).some(Boolean)))return`Choose a section before requesting detail, fields, filters or a cursor.`;if(t&&!(t in zj))return`Unknown review section.`;if(n&&Object.keys(n).some(e=>![`status`,`waitingOn`,`kind`,`choiceState`].includes(e)))return`Unknown review filter.`;if(n?.waitingOn&&(t!==`threads`||![`agent`,`human`,`any`].includes(n.waitingOn)))return`waitingOn applies to threads and must be agent, human or any.`;let r=t===`threads`?[`open`,`resolved`]:t===`asks`?[`draft`,`submitted`,`settled`,`orphan`]:t===`groups`?[`pending`,`pass`,`reject`]:[`open`,`submitted`,`closed`];return n?.status&&!r.includes(n.status)?`Invalid status for this section.`:n?.kind&&(t!==`groups`||![`choose`,`verify`].includes(n.kind))?`kind applies to groups.`:t===`groups`&&n?.status&&n.kind!==`verify`?`Verify status requires kind=verify.`:n?.choiceState&&(t!==`groups`||n.kind!==`choose`||![`chosen`,`empty`].includes(n.choiceState))?`choiceState requires a choice group.`:t&&e.fields?.some(e=>!zj[t].includes(e))?`Unknown field for this section.`:null}function Wj(e,t,n){let r=d.default.resolve(e),i=n?.begin(`save`,r),a;try{a=u.default.openSync(r,`wx`,384)}catch(e){throw i!==void 0&&n.set(i,`failed`),new K({code:e.code===`EEXIST`?`E_FILE_EXISTS`:`E_FILE_WRITE_FAILED`,message:`Could not create ${r}: ${e.message}`})}try{u.default.writeFileSync(a,t)}catch(e){throw u.default.closeSync(a),u.default.unlinkSync(r),i!==void 0&&n.set(i,`failed`),new K({code:`E_FILE_WRITE_FAILED`,message:`Could not save ${r}: ${e.message}`})}return u.default.closeSync(a),i!==void 0&&n.confirm(i,{bytes:typeof t==`string`?Buffer.byteLength(t):t.byteLength}),{file:r,bytes:typeof t==`string`?Buffer.byteLength(t):t.byteLength}}function Gj(e,t,n,r,i){let a=[`--artifact`,t,`--project-dir`,e.projectDir];if(n.evidence===`preview`&&n.items.length&&n.snapshot){let t=i.findIndex(e=>e.label===`Read`),o=[`status`,`waiting-on`,`kind`,`choice-state`].flatMap(t=>typeof e.values[t]==`string`?[`--${t}`,String(e.values[t])]:[]),s={...q([`comment`,`list`,...a,`--section`,`threads`,`--detail`,`--snapshot`,n.snapshot,`--limit`,String(r?.returned??n.items.length),...typeof e.values.cursor==`string`?[`--cursor`,e.values.cursor]:[],...o,...e.values.all?[`--all`]:[]],`Read`),reason:`Read the complete captured page before acting. Previews mark nothing read.`};t<0?i.push(s):i.splice(t,1,s)}let o=i.findIndex(e=>e.label===`Acknowledge`);o>=0&&i.splice(o,1)}const Q=e=>typeof e==`string`?e:``,Kj=e=>e.replaceAll(/\s*\n\s*/g,` / `).trim(),qj=(e,t)=>`${e} ${t}${e===1?``:`s`}`,Jj=e=>e[0].toUpperCase()+e.slice(1),Yj=(e,t=[])=>Object.entries(e??{}).filter(([e,n])=>e!==`waitingOnAgent`&&!t.includes(e)&&typeof n==`number`&&n>0).map(([e,t])=>`${t} ${e}`).join(`, `),Xj=e=>e?` (${e})`:``,Zj={asks:{word:`to apply`,none:`nothing to apply`,listed:[`submitted`]},groups:{word:`to act on`,none:`nothing to act on`,listed:[]},rounds:{word:`open or submitted`,none:`nothing open`,listed:[`open`,`submitted`]}};function Qj(e,t,n,r=!1){let i=n?.total??t.items.length,a=t.summary;if(r){let e=`${i} matched`;return{head:e,full:`${e}${Xj(Yj(a))}`,count:i}}if(e===`threads`){let e=Number(a?.waitingOnAgent??0),t=i?`${i} unread${e?`, ${e} waiting on you`:``}`:`nothing unread`,n=Number(a?.resolved??0);return{head:t,full:`${t}${n?` (${n} resolved)`:``}`,count:i}}let o=Zj[e],s=i?`${i} ${o.word}`:o.none,c=e===`groups`?Object.entries(a??{}).reduce((e,[t,n])=>t===`waitingOnAgent`||typeof n!=`number`?e:e+n,0)-i:0,l=e===`groups`?c>0?qj(c,`other`):``:Yj(a,o.listed);return{head:s,full:`${s}${Xj(l)}`,count:i}}function $j(e){if(!e||typeof e!=`object`)return``;let t=e;if(t.kind===`node`)return` node ${Q(t.id)}`;if(t.kind!==`edge`)return``;let n=typeof t.index==`number`&&t.index>0?` #${t.index+1}`:``;return` edge ${Q(t.from)} → ${Q(t.to)}${n}`}function eM(e){let t=e.snapshot&&typeof e.snapshot==`object`?e.snapshot:{},n=Q(t.tag),r=Q(t.title),i=e.point&&typeof e.point==`object`?e.point:null,a=t.value===void 0?``:` = ${Kj(JSON.stringify(t.value))}`,o=i?` · point ${Q(i.series)} @ ${String(i.x)}${a}`:typeof e.row==`string`?` · row ${e.row}${typeof t.value==`object`?``:a}`:``;return`${n?`${n} `:``}${String(e.block)}${r?` "${Kj(r)}"`:``}${o}${e.dataChanged?` · data changed`:``}`}const tM=e=>{let t=Math.round(e*10),n=Math.floor(t/10);return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}.${t%10}`};function nM(e){let t=Q(e.title);return`${e.deleted?`shot ${String(e.shot)} (shot deleted)`:`shot ${typeof e.number==`number`?`${e.number} `:``}${String(e.shot)}${t?` "${Kj(t)}"`:``}`}${typeof e.t==`number`?` · ${typeof e.cut==`number`?`cut ${e.cut} `:``}at ${tM(e.t)}`:``}${typeof e.line==`string`?` · line ${e.line}${Q(e.lineText)?` "${Kj(Q(e.lineText))}"`:``}`:``}${e.mark?` · marked`:``}${Q(e.cropPath)?` · crop ${Q(e.cropPath)}`:``}`}function rM(e){if(!e||typeof e!=`object`)return``;let t=e;if(typeof t.blockId==`string`){let e=Array.isArray(t.blockIds)&&t.blockIds.length>1?t.blockIds:[t.blockId];return`${e.length>1?`blocks`:`block`} ${e.join(`, `)}${$j(t.diagram)}${Q(t.quote)?` "${Kj(Q(t.quote))}"`:``}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(`, `)}`;if(typeof t.block==`string`)return eM(t);if(typeof t.shot==`string`)return nM(t);if(typeof t.slide==`string`){let e=Q(t.title),n=Q(t.text),r=Array.isArray(t.nodes)?t.nodes:[],i=r.length?` · ${r.length} node${r.length===1?``:`s`}: ${r.map(e=>`${Q(e.tag)} ${Q(e.block)} "${Kj(Q(e.text))}"`).join(`, `)}`:``;return`slide ${t.slide}${e?` "${Kj(e)}"`:``}${i||(n?` · on "${Kj(n)}"`:``)}`}let n=Q(t.page);if(typeof t.board==`string`)return`${n?`page ${n} `:``}board ${t.board}`;let r=typeof t.x==`number`&&typeof t.y==`number`?` ${Math.round(t.x)},${Math.round(t.y)}`:``;return`page ${n||`main`}${r}`}const iM={key:`id`,positional:!0,required:!0},aM={key:`line`,positional:!0,required:!0},oM={key:`tail`,positional:!0,required:!0},sM=e=>e.choice?` → ${e.choice}${e.byRecommendation?` (recommended)`:``}`:``;function cM(e,t){return e===`asks`?{columns:[iM,aM,{key:`note`,label:`note`},{key:`staleChoice`,label:`stale choice`}],rows:t.map(e=>({...e,line:`${Q(e.state)}${e.choice?sM(e):Q(e.text)?` · "${Kj(Q(e.text))}"`:`choice`in e||`text`in e?` · no answer`:``}`,note:Q(e.note)&&`"${Kj(Q(e.note))}"`}))}:e===`threads`?{columns:[iM,{key:`status`,positional:!0,required:!0},{key:`waiting`,positional:!0},{key:`where`,positional:!0},{key:`marked`,label:`marked`},{key:`stale`,label:`stale`},{key:`orphan`,label:`orphan`},{key:`messageCount`,positional:!0},{key:`preview`,positional:!0}],rows:t.map(e=>({...lM(e),messageCount:typeof e.messageCount==`number`&&e.messageCount?qj(e.messageCount,`message`):``,preview:Q(e.preview)&&`"${Kj(Q(e.preview))}"`}))}:e===`groups`?{columns:[iM,{key:`kind`,positional:!0,required:!0},aM,{key:`origin`,positional:!0},{key:`evidenceUpdated`,label:`evidence updated`},{key:`rejects`,positional:!0},{key:`threadCount`,positional:!0},oM],rows:t.map(e=>({...e,line:e.kind===`verify`?Q(e.verdict):`${e.round?`round ${e.round}`:``}${e.choice?sM(e):` · no pick`}`.replace(/^ · /,``),origin:typeof e.from==`string`&&e.from?`from ${e.from}`:``,rejects:typeof e.rejectThreads==`number`&&e.rejectThreads?qj(e.rejectThreads,`reject thread`):``,threadCount:typeof e.threads==`number`&&e.threads?qj(e.threads,`thread`):``,tail:Q(e.title)}))}:{columns:[iM,{key:`state`,positional:!0,required:!0},{key:`groupList`,positional:!0},oM],rows:t.map(e=>({...e,groupList:Array.isArray(e.groups)&&e.groups.length?`groups ${e.groups.join(`, `)}`:``,tail:Q(e.title)}))}}function lM(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:``,where:rM(e.anchor&&typeof e.anchor==`object`&&typeof e.page==`string`?{page:e.page,...e.anchor}:e.anchor),marked:Array.isArray(e.marked)?e.marked.map(Q).filter(Boolean).join(`; `):``,reject:e.anchor?.verdict===`reject`,stale:e.stale===!0,orphan:e.orphan===!0}}const uM=e=>e.status===`open`?[`reply --thread ${String(e.id)} --text <message>`,...e.reject?[]:[`resolve --thread ${String(e.id)}`]].join(`, `):``,dM=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function fM(e,t=`items`,n=!0){return{kind:`messages`,key:t,groups:e.map(e=>{let t=lM(e);return{facts:[dM(`id`,t.id),dM(`status`,t.status),dM(`waiting`,t.waiting),dM(`where`,t.where),{label:`marked`,binding:{key:`marked`,value:t.marked}},{label:`reject`,binding:{key:`reject`,value:t.reject}},{label:`stale`,binding:{key:`stale`,value:t.stale}},{label:`orphan`,binding:{key:`orphan`,value:t.orphan}},dM(`spentBy`,n?uM(t):``)],messages:(Array.isArray(e.messages)?e.messages:[]).map(e=>({facts:[dM(`message`,[e.id,`${Q(e.name)||Q(e.author)}${e.author===`agent`?` (agent)`:``}`,Q(e.at)&&lO(Q(e.at)),e.deleted?`(deleted)`:``,Q(e.editedAt)&&`edited ${lO(Q(e.editedAt))}`].filter(Boolean).join(` `))],text:typeof e.text==`string`?e.text:``}))}})}}function pM(e,t,n,r,i){let a=Qj(e,t,n,i),o={key:r?e:`items`,title:Jj(e),summary:a.full};return e===`threads`&&t.evidence===`complete`?{...fM(t.items),...o,...r?{page:n}:{}}:{kind:`records`,...cM(e,t.items),...o,...r?{page:n}:{}}}const mM=[`threads`,`asks`,`groups`,`rounds`];function hM(e,t){let n=e.summary??{},r=e=>t.find(t=>t.label===Jj(e)),i=mM.filter(e=>r(e));return{heading:`Comment list`,status:``,subject:e.artifact,facts:[],sections:i.map(e=>{let t=n[e],r=e===`threads`?Qj(`threads`,{items:[],summary:{waitingOnAgent:n.waitingOnAgent}},{total:Number(t??0)}).head:Yj(t)||`none`;return{kind:`records`,key:e,title:Jj(e),summary:r,columns:[],rows:[]}}),actions:t.filter(e=>!i.some(t=>Jj(t)===e.label))}}function gM({data:e,actions:t,coverage:n},r=`Comment list`,i=!1){if(e.section===`summary`)return hM(e,t);let a=n.page;return{heading:r,status:``,subject:e.artifact,summary:Qj(e.section,e,a,i).head,facts:[...e.evidence===`preview`&&e.snapshot&&e.items.length?[X(`Snapshot`,Y(e,`snapshot`))]:[],...e.delivery?[X(`Delivery`,Y(e,`delivery`))]:[],...e.receipt&&!e.delivery?[X(`Receipt`,Y(e,`receipt`))]:[]],sections:[pM(e.section,e,a,!1,i)]}}function _M({data:e},t=!1){let n=Object.entries(e.sections),r=n.map(([e,n])=>Qj(e,n,n.page,t)).filter(e=>e.count>0).map(e=>e.head);return{heading:`Comment list`,status:``,subject:e.artifact,summary:r.join(` · `)||`nothing new`,facts:[],sections:n.map(([e,n])=>pM(e,n,n.page,!0,t))}}const $=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,vM=[`brief`,`table`,`json`,`jsonl`,`raw`];function yM(e,t=!1){let n=$(e,`artifact`),r=t?VE:BE;if(!n||!UE(r).test(n))throw new K({code:`E_ARGUMENT_INVALID`,message:`--artifact must be ${WE(r)}.`});return n}function bM(e){let t=$(e,`limit`);if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new K({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});return{...t===void 0?{}:{limit:Number(t)},...$(e,`cursor`)?{cursor:$(e,`cursor`)}:{},...$(e,`snapshot`)?{snapshot:$(e,`snapshot`)}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...e.values.hold?{hold:!0}:{},...$(e,`fields`)?{fields:$(e,`fields`).split(`,`).map(e=>e.trim())}:{}}}function xM(e,t){let n=jO(t);return{...e,agent:NO(t)??`Agent`,...n?{session:n}:{}}}async function SM(e,t,n,r,i){let a=await rO(e.projectDir).call(`POST`,`/api/agent/v1/${n}/${r}`,xM(i,process.env),t.signal);if(t.payloads.raw=a.raw,a.json.schema!==`ryugi.review/v1`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported review response.`});if(a.status<200||a.status>=300)throw new K({code:typeof a.json.code==`string`?a.json.code:`E_REVIEW_FAILED`,message:a.json.error||`HTTP ${a.status}`,httpStatus:a.status});return a.json}const CM=/* @__PURE__ */ new Set([`artboard`,`document`,`preview`,`report`,`slides`,`storyboard`,`whiteboard`]);async function wM(e,t,n,r,i){if(!CM.has(t.split(`/`)[0]??``))return null;let a=await rO(e).call(`POST`,`/api/agent/v1/${t}/review`,xM({op:`consume`,thread:n,resolve:r},process.env),i);if(a.json.code===`E_UNDELIVERED`||a.json.code===`E_REJECT_OPEN`)throw new K({code:a.json.code,message:String(a.json.error),httpStatus:a.status});return a.status<200||a.status>=300?{failed:String(a.json.error||`HTTP ${a.status}`)}:typeof a.json.unread==`number`?{consumed:Number(a.json.consumed),unread:a.json.unread}:null}function TM(e,t){return[`--artifact`,t,`--project-dir`,e.projectDir]}function EM(e,t,n){let r=/* @__PURE__ */ new Set([...Object.keys(LD),`artifact`,`receipt`]),i=Object.keys(e.values).find(e=>!r.has(e));if(i)throw new K({code:`E_ARGUMENT_INVALID`,message:`--${i} is not supported for ack.`});let a=$(e,`receipt`);if(!a)throw new K({code:`E_ARGUMENT_INVALID`,message:`ack requires --receipt.`});return Z({id:n===`review`?`comment.ack`:`changes.ack`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){rO(e.projectDir);let o=i.effects.begin(n===`review`?`comment.ack`:`changes.ack`,a),s=await SM(e,i,t,n,{op:`ack`,receipt:a});if(![`acknowledged`,`unchanged`].includes(s.status))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported acknowledgement result; inspect unread state before retrying.`});return i.effects.set(o,s.status===`unchanged`?`none`:`confirmed`,{artifact:t}),J({artifact:t,receipt:a,status:s.status})},present:kM(n===`review`?`comment`:`changes`)},e)}function DM(e,t){let n=$(e,`receipt`);if(!n)throw new K({code:`E_ARGUMENT_INVALID`,message:`deliver requires --receipt.`});return Z({id:`comment.deliver`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){rO(e.projectDir);let a=i.effects.begin(`comment.deliver`,n);if((await SM(e,i,t,`review`,{op:`deliver`,receipt:n})).status!==`delivered`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported delivery result.`});return i.effects.confirm(a,{artifact:t}),J({artifact:t,receipt:n,status:`delivered`})},present:kM(`comment`)},e)}function OM(e,t,n){if(n!==`list`)throw new K({code:`E_ARGUMENT_INVALID`,message:`--sections applies to comment list.`});let r=bM(e),i=$(e,`sections`)?.trim(),a=i===`all`?Vj(t):(i??``).split(`,`).map(e=>e.trim()),o=Object.fromEntries([`status`,`waiting-on`,`kind`,`choice-state`].map(t=>[t,$(e,t)])),s=Hj({...r,sections:a,section:$(e,`section`),thread:$(e,`thread`),filters:o},t);if(s)throw new K({code:`E_ARGUMENT_INVALID`,message:s});return Z({id:`comment.list`,mode:`finite`,output:{formats:vM,detail:!0},async run(n,i){let o=await SM(e,i,t,`review`,{op:`list`,sections:a,...r});for(let e of a){let t=o.sections?.[e];if(!t||!Array.isArray(t.items)||typeof t.snapshot!=`string`||!t.page||typeof t.page.scope!=`string`||typeof t.page.hasMore!=`boolean`||!Number.isInteger(t.page.returned)||!(t.page.total===null||Number.isInteger(t.page.total)))throw new K({code:`E_SERVER_UPGRADE_REQUIRED`,message:`The server does not provide combined review pages. Run start --background for this project to rebuild/restart it.`});if(t.page.returned!==t.items.length||t.page.returned<0||t.page.total!==null&&t.page.total<t.page.returned||t.page.snapshot!==t.snapshot||t.page.nextCursor!==null&&typeof t.page.nextCursor!=`string`||t.page.hasMore!==(typeof t.page.nextCursor==`string`&&t.page.nextCursor.length>0))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned inconsistent combined review coverage.`})}return jM(e,t,a,o,r)},present:e=>_M(e,r.all)},e)}const kM=e=>({data:t})=>({heading:e===`comment`?`Comment ack`:`Changes ack`,status:t.status,subject:t.artifact,facts:[],sections:[]});function AM({data:e}){let t=e.blocks.length;return{heading:`Changes`,status:e.saved?`saved`:``,subject:e.artifact,summary:e.empty?`no human edits`:e.diff===void 0?`${t} block${t===1?``:`s`} changed`:`complete diff`,facts:e.saved?[X(`File`,Y(e,`saved`),!0)]:[...e.receipt?[X(`Receipt`,{key:`receipt`,value:`${e.receipt} · changes ack --receipt ${e.receipt}`})]:[],...e.diff===void 0&&!e.empty&&e.snapshot?[X(`Snapshot`,Y(e,`snapshot`))]:[]],sections:e.empty||e.saved?[]:e.diff===void 0?[{kind:`records`,key:`blocks`,rows:e.blocks.map(e=>({id:e.id,size:[e.additions&&`+${e.additions}`,e.deletions&&`-${e.deletions}`].filter(Boolean).join(` `),preview:e.preview&&`"${e.preview.replaceAll(/\s*\n\s*/g,` / `)}"`})),columns:[{key:`id`,positional:!0,required:!0},{key:`size`,positional:!0},{key:`preview`,positional:!0}]}]:[{kind:`diff`,key:`diff`,text:e.diff}]}}function jM(e,t,n,r,i){let a={},o=[],s=[];for(let c of n){let n=r.sections[c],l=MM(e,t,c,n,i),{artifact:u,section:d,...f}=l.data;a[c]={...f,page:n.page},o.push(...l.actions.map(e=>e.label===`More`?{...e,label:`More (${c})`}:e)),f.evidence===`preview`&&c===`threads`&&s.push({path:`data.sections.threads.items.messages`,reason:`summary`})}return J({artifact:t,sections:a},void 0,{actions:o,coverage:{omitted:s}})}function MM(e,t,n,r,i,a){let o=r.page,s={artifact:t,section:n??`summary`,items:r.items??[],evidence:i.fields?`projected`:n&&n!==`threads`?`state`:i.detail||a?`complete`:`preview`,...r.snapshot?{snapshot:r.snapshot}:{},...r.receipt?{receipt:r.receipt}:{},...r.receipt&&e.values.hold?{delivery:r.receipt}:{},...r.summary?{summary:r.summary}:{}},c=[],l=TM(e,t);if(r.receipt&&c.push(q([`comment`,`ack`,...l,`--receipt`,r.receipt],`Acknowledge`)),o?.nextCursor&&c.push(q([`comment`,`list`,...l,`--section`,n,...i.detail?[`--detail`]:[],...Object.entries({status:$(e,`status`),"waiting-on":$(e,`waiting-on`),kind:$(e,`kind`),"choice-state":$(e,`choice-state`),fields:$(e,`fields`),limit:$(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),...i.all?[`--all`]:[],`--cursor`,o.nextCursor],`More`)),n)n===`threads`&&s.evidence===`preview`&&s.items[0]&&c.push(q([`comment`,`read`,...l,`--thread`,String(s.items[0].id),`--snapshot`,r.snapshot,`--detail`],`Read`));else{c.push(q([`comment`,`list`,...l,`--sections`,`all`,`--detail`,...i.all?[`--all`]:[],...$(e,`limit`)?[`--limit`,$(e,`limit`)]:[]],`Review all`));let n=[`threads`,...LE[t.split(`/`)[0]].review?.sections??[]];c.unshift(...n.map(e=>q([`comment`,`list`,...l,`--section`,e,...e===`asks`?[`--detail`]:[]],e[0].toUpperCase()+e.slice(1))))}if(n===`asks`)for(let e of s.items.filter(e=>e.state===`submitted`))c.push({...q([`comment`,`note`,...l,`--ask`,String(e.id),`--text`,`<what changed>`],`Settle (${e.id})`),reason:`Apply this submitted human answer, then replace the note argument with what changed. Never invent an answer.`});return n===`threads`&&Gj(e,t,s,o,c),J(s,void 0,{actions:c,coverage:{...o?{page:o}:{},...s.evidence===`preview`&&n===`threads`?{omitted:[{path:`data.items.messages`,reason:`summary`}]}:{}}})}function NM(e){let t=yM(e),n=e.positionals[0];if(n===`ack`)return EM(e,t,`review`);if(n===`deliver`)return DM(e,t);if(e.values.sections!==void 0)return OM(e,t,n);if(n!==`list`&&n!==`read`)throw new K({code:`E_ARGUMENT_INVALID`,message:`Expected list, read or ack.`});let r=bM(e),i=n===`read`?`threads`:$(e,`section`),a=$(e,`thread`);if(n===`read`&&!a)throw new K({code:`E_ARGUMENT_INVALID`,message:`read requires --thread.`});if(i&&![`threads`,`asks`,`groups`,`rounds`].includes(i))throw new K({code:`E_ARGUMENT_INVALID`,message:`Unknown review section.`});if(!i&&(r.detail||r.cursor||r.fields||[`status`,`waiting-on`,`kind`,`choice-state`].some(t=>e.values[t])))throw new K({code:`E_ARGUMENT_INVALID`,message:`Select --section before detail, fields, cursor or filters.`});let o=Object.fromEntries([[`status`,$(e,`status`)],[`waitingOn`,$(e,`waiting-on`)],[`kind`,$(e,`kind`)],[`choiceState`,$(e,`choice-state`)]].filter(([,e])=>e!==void 0)),s=Uj({...r,section:i,filters:o});if(s)throw new K({code:`E_ARGUMENT_INVALID`,message:s});return Z({id:`comment.${n}`,mode:`finite`,output:{detail:!0,formats:vM,collection:`items`,requiredFields:i?Bj[i]:[],fields:i?[...zj[i]]:[]},async run(s,c){let l=await SM(e,c,t,`review`,{op:n,...r,...i?{section:i}:{},...a?{thread:a,detail:!0}:{},...Object.keys(o).length?{filters:o}:{}});return MM(e,t,i,l,r,a)},present:t=>gM(t,n===`read`?`Comment read`:`Comment list`,r.all||!!$(e,`status`)&&(i!==`asks`||$(e,`status`)!==`submitted`)||!!$(e,`choice-state`))},e)}function PM(e){let t=yM(e,!0),n=e.positionals[0];if(n===`ack`)return EM(e,t,`changes`);if(n)throw new K({code:`E_ARGUMENT_INVALID`,message:`Expected changes or changes ack.`});let r=bM(e),i=$(e,`save`);if(i!==void 0&&!i.trim())throw new K({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});if(r.detail&&(r.fields||r.cursor||r.limit!==void 0))throw new K({code:`E_OPTION_CONFLICT`,message:`A complete diff cannot use --limit, --cursor or --fields.`});return Z({id:`changes`,mode:`finite`,output:{detail:!0,formats:i?[`brief`,`json`,`jsonl`]:vM,fields:[`artifact`,`snapshot`,`blocks`,`diff`,`empty`]},async run(n,a){let{page:o,schema:s,...c}=await SM(e,a,t,`changes`,{op:`read`,...r}),l=c;if(i&&l.empty!==!0&&typeof l.diff!=`string`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return complete diff evidence; no export was written.`});if(i){let e=Wj(i,l.diff??``,a.effects);l.saved=e.file,l.bytes=e.bytes,delete l.diff}let u=TM(e,t),d=l.receipt?[q([`changes`,`ack`,...u,`--receipt`,l.receipt],`Acknowledge`)]:l.empty?[]:[q([`changes`,...u,`--snapshot`,l.snapshot,...r.all?[`--all`]:[],`--detail`],`Read`)];return o?.nextCursor&&d.push(q([`changes`,...u,...r.all?[`--all`]:[],...Object.entries({fields:$(e,`fields`),limit:$(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),`--cursor`,o.nextCursor],`More`)),J(l,void 0,{actions:d,coverage:{...o?{page:o}:{},...!r.detail&&!l.empty?{omitted:[{path:`data.diff`,reason:`summary`}]}:{}}})},present:AM},e)}const FM={semantic:PM,positionals:1,name:`changes`,summary:`Show what your human partner changed in a document or a deck (needs a running server)`,usage:[`--artifact document/<id>|slides/<id> [--all] [--detail | --save <file>]`,`ack --artifact document/<id>|slides/<id> --receipt <receipt>`],details:`Previews unread document edits without marking them read. Use --detail for complete evidence, then changes ack --receipt after using it.`,options:{limit:{type:`string`,value:`<n>`,help:`Summary records per page (1–100, default 10)`},cursor:{type:`string`,value:`<cursor>`,help:`Continue a change summary snapshot`},snapshot:{type:`string`,value:`<snapshot>`,help:`Read a captured change snapshot`},receipt:{type:`string`,value:`<receipt>`,help:`ack: acknowledge the complete captured diff`},save:{type:`string`,value:`<file>`,help:`Save the complete diff without overwriting an existing file`},artifact:{type:`string`,value:`document/<id>|slides/<id>`,help:`The document or deck`},all:{type:`boolean`,help:`Show historical changes without a receipt`}}},IM={reject:0,pending:1,pass:2,checked:3},LM={reject:`rejected`,pending:`pending`,pass:`passed`,checked:`checked by agent`},RM=(e,t)=>e?`${e} ${t}`:``,zM=e=>e.filter(Boolean).join(` · `),BM=(e,t=!1)=>({key:e,positional:!0,required:t});function VM({data:e}){let{tally:t}=e,n=t=>e.claims.filter(e=>e.state===t).length,r=e.threads.filter(e=>e.status===`open`),i=zM([RM(t.needYou,`on your human partner`),RM(t.notVerified,`not verified`),RM(t.orphaned,`open reject on a claim that is gone`)]);return{heading:`Comment list`,status:``,subject:e.artifact,summary:t.done?`done`:t.rejected?`${t.rejected} to act on`:`nothing to act on`,facts:i?[X(`Waiting`,{key:`waiting`,value:i})]:[],sections:[{kind:`records`,key:`claims`,title:`Claims`,summary:zM([RM(n(`reject`),`rejected`),RM(n(`pending`),`pending`),RM(n(`pass`),`passed`),RM(n(`checked`),`checked by agent`)]),columns:[BM(`id`,!0),BM(`line`,!0),BM(`rejects`),{key:`evidenceUpdated`,label:`evidence updated`},BM(`origin`),BM(`tail`)],rows:[...e.claims].sort((e,t)=>IM[e.state]-IM[t.state]).map(e=>({...e,line:LM[e.state],rejects:e.state===`reject`&&e.rejectThreads?`${e.rejectThreads} reject thread${e.rejectThreads===1?``:`s`}`:``,evidenceUpdated:e.evidenceUpdated||void 0,origin:e.from?`from ${e.from}`:``,tail:e.title}))},...e.rows.length?[{kind:`records`,key:`rows`,title:`Artboard rows`,summary:String(e.rows.length),columns:[BM(`id`,!0),BM(`state`,!0)],rows:e.rows.map(e=>({...e,id:`${e.artboard}/${e.group}`}))}]:[],...e.reports?.length?[{kind:`records`,key:`reports`,title:`Child reports`,summary:String(e.reports.length),columns:[BM(`id`,!0),BM(`state`,!0),BM(`tail`)],rows:e.reports.map(e=>({id:`verify/${e.verify}`,state:e.state===`reject`?`rejected (${e.rejected})`:e.state===`pending`?`pending (${e.needYou})`:e.state===`pass`?`passed`:`not found`,tail:e.title}))}]:[],...e.gaps.length?[{kind:`records`,key:`gaps`,title:`Not verified`,summary:zM([RM(e.gaps.filter(e=>!e.waived).length,`open`),RM(e.gaps.filter(e=>e.waived).length,`waived`)]),columns:[BM(`id`,!0),BM(`line`,!0),BM(`tail`)],rows:e.gaps.map(e=>({...e,line:e.waived?`waived`:`not verified`,tail:e.title}))}]:[],...e.threads.length?[{kind:`messages`,key:`threads`,title:`Threads`,summary:zM([RM(r.length,`open`),RM(e.threads.length-r.length,`resolved`)]),groups:e.threads.map(e=>({facts:[{...X(`Thread`,{key:`id`,value:e.id},!0),positional:!0},X(`On`,{key:`anchor`,value:e.anchor.claim?`claim ${e.anchor.claim}`:`gap ${e.anchor.gap}`},!0),X(`Verdict`,{key:`verdict`,value:e.anchor.verdict??(e.anchor.waive?`waived`:``)}),X(`Status`,{key:`status`,value:e.status},!0),...e.stale?[X(`Stale`,{key:`stale`,value:!0})]:[]],messages:e.messages.map(e=>({facts:[{...X(`Author`,{key:`author`,value:e.author},!0),positional:!0},X(`At`,{key:`at`,value:e.at})],text:e.text}))}))}]:[]]}}function HM(e){let t=e.values.artifact,n=JE(e.projectDir,t);return Z({id:`comment.list`,mode:`finite`,output:{detail:!0,formats:[`brief`,`json`,`jsonl`],fields:[`id`,`state`,`title`,`from`],scalar:e=>e.tally.done?`done`:`open`},async run(r,i){let a=NO(process.env),o=await rO(e.projectDir).call(`POST`,`/api/agent/${t}/comments`,{op:`list`,...a?{agent:a}:{}},i.signal);if(o.status<200||o.status>=300)throw new K({code:o.status===404?`E_ARTIFACT_NOT_FOUND`:`E_COMMENT_FAILED`,message:o.json?.error||`HTTP ${o.status}`,httpStatus:o.status});let s=o.json,c=[`--artifact`,t,`--project-dir`,e.projectDir],l=s.threads.filter(e=>e.status===`open`);return J({...s,artifact:t,projectDir:e.projectDir},void 0,{actions:l.length?[{...q([`check`,...c],`Check`),reason:`After repairing the rejected claim and updating ${n.write} with real evidence. Preserve existing IDs and human edits; a human pass closes the rejection.`},...l.map(e=>({...q([`comment`,`reply`,...c,`--thread`,e.id,`--text`,`<what changed and the replacement evidence>`],`Reply (${e.id})`),reason:`Reply after the repair; leave rejected claims open for the human verdict.`}))]:[]})},present:VM},e)}function UM({data:e}){let t=e.threadId?`thread ${e.threadId}`:e.ask?`ask ${e.ask}`:e.group?`group ${e.group}${e.board?` → ${e.board}`:``}`:e.round?`round ${e.round}`:``;return{heading:`Comment ${e.operation}`,status:e.status,subject:e.artifact,summary:`${t}${e.operation===`answer`&&e.choice?` → ${e.choice}`:``}`,facts:[...e.messageId?[X(`Message`,Y(e,`messageId`))]:[],...e.unread?[X(`Unread`,Y(e,`unread`))]:[],...e.consumeFailed?[X(`Consume failed`,Y(e,`consumeFailed`))]:[],...e.groups?.length?[X(`Groups`,{key:`groups`,value:e.groups.join(`, `)})]:[]],sections:[]}}function WM(e){let t={action:e.positionals[0],artifact:e.values.artifact,projectDir:e.projectDir};for(let n of[`ask`,`at`,`block`,`board`,`choice`,`claim`,`cut`,`edge`,`element`,`gap`,`group`,`line`,`node`,`page`,`quote`,`round`,`shot`,`slide`,`text`,`thread`,`x`,`y`])t[n]=e.values[n];for(let n of[`all`,`clear`,`withdraw`])t[n]=!!e.values[n];return t}function GM(e){let t=WM(e),n=t.action;if(t.artifact?.startsWith(`verify/`)&&[`list`,`read`,`ack`,`deliver`].includes(n??``)){if(n!==`list`)throw new K({code:`E_OPTION_UNSUPPORTED`,message:`A verify report has no thread receipts: comment list shows every thread.`});return HM(e)}if([`list`,`read`,`ack`,`deliver`].includes(n??``))return NM(e);if([`section`,`sections`,`limit`,`cursor`,`snapshot`,`receipt`,`status`,`waiting-on`,`kind`,`choice-state`,`hold`].some(t=>e.values[t]!==void 0))throw new K({code:`E_OPTION_UNSUPPORTED`,message:`Review query options apply only to list, read and ack.`});return Z({id:`comment.${n??`unknown`}`,mode:`finite`,output:{formats:n===`pass`&&t.all?[`brief`,`json`,`jsonl`]:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.ask??e.group??e.round??e.threadId??e.artifact},async run(e,n){let r=YM(t);rO(t.projectDir);let i=n.effects.begin(`comment.${r.action}`,t.thread??t.ask??t.group??t.artifact);r.action===`resolve`&&t.thread&&await wM(t.projectDir,t.artifact,t.thread,!0,n.signal);let a=await XM(t,r,n.signal);if(a.status>=400&&a.status<500&&n.effects.set(i,`failed`),a.status<200||a.status>=300)throw new K({code:a.status===404&&!a.json.error?`E_SERVER_UPGRADE_REQUIRED`:`E_COMMENT_FAILED`,message:a.json.error||`HTTP ${a.status}`,httpStatus:a.status});let o=a.json;n.effects.confirm(i);let s=null,c;if(r.action===`reply`&&t.thread)try{let e=await wM(t.projectDir,t.artifact,t.thread,!1,n.signal);e&&`failed`in e?c=e.failed:s=e}catch(e){c=e instanceof Error?e.message:String(e)}let{action:l,request:u}=r,d={add:`added`,reply:`replied`,resolve:`resolved`,answer:t.clear?`cleared`:`answered`,note:`settled`,choose:t.clear?`cleared`:`recorded`,pass:`recorded`,reject:`recorded`,waive:`recorded`,submit:t.withdraw?`withdrawn`:`submitted`},f=l===`pass`&&[o.groups,o.claims].some(e=>Array.isArray(e)&&e.length===0);return f&&n.effects.set(i,`none`),J({artifact:t.artifact,operation:l,status:f?`unchanged`:d[l],by:`agent`,...typeof o.threadId==`string`?{threadId:o.threadId}:{},...typeof o.messageId==`string`?{messageId:o.messageId}:{},...t.ask?{ask:t.ask}:{},...t.group?{group:t.group}:{},...Array.isArray(o.groups)?{groups:o.groups}:{},...Array.isArray(o.claims)?{groups:o.claims}:{},...t.claim?{group:t.claim}:{},...t.gap?{group:t.gap}:{},...t.round?{round:t.round}:{},...l===`choose`?{board:u.board}:{},...l===`submit`?{submitted:!t.withdraw}:{},...l===`answer`?{choice:u.choice}:{},...s?{unread:s.unread}:{},...c?{consumeFailed:c}:{}},void 0,{effects:n.effects.snapshot()})},present:UM},e)}const KM=UE(HE),qM=/* @__PURE__ */ new Set([`pass`,`reject`]);function JM(e,t,n){let r=LE[n];if(r.commentRequest)return r.commentRequest(e,t);if(t===`waive`)throw new j(`comment waive works on verify reports only`);let i=r.commentActions?.[t];if(i)return i(e);if(t===`answer`||t===`note`)throw new j(`comment ${t} works on documents only`);if(t===`choose`||t===`submit`||qM.has(t))throw new j(`comment ${t} works on artboards only`);if(t===`add`)throw new j(`comment add does not work on ${n}`);if(!e.thread)throw new j(`comment ${t} needs --thread <threadId>`);return t===`reply`?{op:`reply`,threadId:e.thread,text:rt(e)}:{op:`resolve`,threadId:e.thread}}function YM(e){let t=tt.find(t=>t===e.action);if(!t)throw new j(`comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive`);if(!e.artifact||!KM.test(e.artifact))throw new j(`--artifact must be ${WE(HE)}`);let[n,r]=e.artifact.split(`/`);return{action:t,type:n,id:r,request:JM(e,t,n),artifact:e.artifact}}async function XM(e,t,n){let{type:r,id:i,request:a}=t,o=rO(e.projectDir),s=NO(process.env);return o.call(`POST`,`/api/agent/${r}/${i}/comments`,{...a,agent:s??`Agent`},n)}const ZM={actionOptions:{list:[`limit`,`cursor`,`snapshot`,`status`,`waiting-on`,`kind`,`choice-state`,`thread`,`hold`],read:[`limit`,`cursor`,`all`,`save`]},actionDetails:{reply:`Adds a message to the thread and marks the messages of it delivered to you as read. Without --text, reads the message from stdin.`,resolve:`Closes the thread and marks the messages of it delivered to you as read. Refused while the thread holds a message you never received, and on a reject, which only your human partner passes.`},semantic:GM,name:`comment`,summary:`Read and answer feedback on a document, artboard, whiteboard, deck, data report or verify report (needs a running server)`,usage:[`list --artifact ${GE(BE)} --sections all|<names> [--detail] [--all]`,`list --artifact ${GE(BE)} [--section threads|asks|groups|rounds] [--all]`,`read --artifact ${GE(BE)} --thread <threadId> [--snapshot <token>]`,`ack --artifact ${GE(BE)} --receipt <receipt>`,`deliver --artifact ${GE(BE)} --receipt <delivery>`,`add --artifact document/<id> --block <blockId> [--quote <text>] [--text <text>]`,`add --artifact document/<id> --block <blockId> (--node <id> | --edge "<from>-><to>[#n]") [--text <text>]`,`add --artifact artboard/<id> --board <boardId> [--x <px> --y <px>] [--text <text>]`,`add --artifact whiteboard/<id> (--element <elementId> | --x <px> --y <px> [--page <pageId>]) [--text <text>]`,`add --artifact slides/<id> --slide <slideId> [--text <text>]`,`add --artifact storyboard/<id> (--shot <shotId> [--line <lineId> | --at <seconds>] | --cut <n> --at <seconds>) [--text <text>]`,`add --artifact report/<id> --block <blockId> [--point <series>:<x> | --row <rowKey>] [--text <text>]`,`reply --artifact ${GE(HE)} --thread <threadId> [--text <text>]`,`resolve --artifact ${GE(BE)} --thread <threadId>`,`choose --artifact artboard/<id> --group <groupId> (--board <boardId> | --clear)`,`submit --artifact artboard/<id> --round <roundId> [--withdraw]`,`submit --artifact document/<id> [--withdraw]`,`answer --artifact document/<id> --ask <questionId> (--choice <value> | --text <answer> | --clear)`,`note --artifact document/<id> --ask <questionId> [--text <note>]`,`pass --artifact artboard/<id> (--group <groupId> | --all) [--text <text>]`,`reject --artifact artboard/<id> --group <groupId> [--text <text>]`,`list --artifact verify/<id>`,`pass --artifact verify/<id> (--claim <claimId> | --all)`,`reject --artifact verify/<id> --claim <claimId> [--text <text>]`,`waive --artifact verify/<id> --gap <gapId>`],details:`list returns a summary; select threads, asks, groups or rounds to read one collection. Previews deliver nothing. A complete read delivers its threads to you; reply and resolve spend what was delivered, and resolve refuses while a thread holds a message you never received. A page that continues names its cursor, a preview names its snapshot. list --hold delivers only once deliver confirms its Delivery handle. asks, groups and rounds are independent state reads. Without --text, add, reply, note and reject read the message from stdin. answer records what your human partner said in the terminal; note settles a question once its answer is applied. pass and reject record a verdict on a verify group only when your human partner asks for it; the board shows the agent recorded it.`,options:{sections:{type:`string`,value:`<all|threads,asks|threads,groups,rounds>`,help:`Read multiple bounded review collections in one request`},section:{type:`string`,value:`<threads|asks|groups|rounds>`,help:`Semantic list: select one review collection`},limit:{type:`string`,value:`<n>`,help:`Semantic reads: records per page (1–100, default 10)`},cursor:{type:`string`,value:`<cursor>`,help:`Continue a semantic snapshot page`},snapshot:{type:`string`,value:`<snapshot>`,help:`Read an existing semantic snapshot`},receipt:{type:`string`,value:`<receipt>`,help:`ack: confirm exactly the complete evidence delivered`},hold:{type:`boolean`,help:`list: record the threads as delivered only once deliver confirms the Delivery handle`},status:{type:`string`,value:`<status>`,help:`Filter the selected semantic review collection`},"waiting-on":{type:`string`,value:`<agent|human|any>`,help:`Filter unread threads by who should reply`},kind:{type:`string`,value:`<verify|choose>`,help:`Filter review groups by kind`},claim:{type:`string`,value:`<claimId>`,help:`Verify reports: the claim to pass or reject`},gap:{type:`string`,value:`<gapId>`,help:`Verify reports: the not-verified item to waive`},"choice-state":{type:`string`,value:`<chosen|empty>`,help:`Filter choice groups`},artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact whose feedback to read or answer`},all:{type:`boolean`,help:`list: every thread, not only what changed; pass: every verify group not yet passed`},block:{type:`string`,value:`<blockId>`,help:`add: the document block to comment on`},quote:{type:`string`,value:`<text>`,help:`add: the text in the block the comment is about`},node:{type:`string`,value:`<nodeId>`,help:`add: the node of the diagram in --block, by its id in the mermaid source`},edge:{type:`string`,value:`<from>-><to>[#n]`,help:`add: the edge of the diagram in --block between two node ids; #2 is the second edge between them`},board:{type:`string`,value:`<boardId>`,help:`add: the artboard board to comment on`},element:{type:`string`,value:`<elementId>`,help:`add: the whiteboard element to comment on`},page:{type:`string`,value:`<pageId>`,help:`add: the whiteboard page --x and --y are on (default main)`},slide:{type:`string`,value:`<slideId>`,help:`add: the slide of a deck to comment on`},shot:{type:`string`,value:`<shotId>`,help:`add: the shot of a storyboard to comment on`},line:{type:`string`,value:`<lineId>`,help:`add: the voice line of --shot the comment is about`},at:{type:`string`,value:`<seconds>`,help:`add: the moment of --shot, or of --cut, the comment is about`},cut:{type:`string`,value:`<n>`,help:`add: the registered cut --at is a moment of`},point:{type:`string`,value:`<series>:<x>`,help:`add: the point of a report chart in --block, by its series and x value`},row:{type:`string`,value:`<rowKey>`,help:`add: the row of a report table in --block`},x:{type:`string`,value:`<px>`,help:`add: horizontal position on the board`},y:{type:`string`,value:`<px>`,help:`add: vertical position on the board`},thread:{type:`string`,value:`<threadId>`,help:`reply, resolve: the thread`},text:{type:`string`,value:`<text>`,help:`add, reply, note: the message; answer: a written answer; reject: the reason; pass: an optional note`},group:{type:`string`,value:`<groupId>`,help:`choose: the choice group; pass, reject: the verify group`},clear:{type:`boolean`,help:`choose, answer: clear the choice or answer`},ask:{type:`string`,value:`<questionId>`,help:`answer, note: the question id`},choice:{type:`string`,value:`<value>`,help:`answer: the option value`},round:{type:`string`,value:`<roundId>`,help:`submit: the round`},withdraw:{type:`boolean`,help:`submit: withdraw the submission`}},positionals:1},QM={on:!0,off:!1,inherit:null};function $M(e,t=()=>{}){let n=yD(eD(process.env,process.platform,m.default.homedir())),r=d.default.join(d.default.dirname(Je(e.projectDir).root),`config.json`);if(e.autoPublish!==void 0){let i=QM[e.autoPublish];if(i===void 0)throw new j(`--auto-publish takes on, off, or (with --project) inherit`);if(e.project){let e=fD(r);if(e.warning)throw new j(e.warning);t(),hD(r),_D(r,i)}else if(i===null)throw new j(`inherit only applies with --project`);else SD(n,i,t)}return{global:xD(n)??null,project:fD(r).config.autoPublish??null}}const eN={name:`config`,summary:`Auto-publish changed artifacts as private cloud copies when the agent's turn ends`,usage:[`[--auto-publish on|off] [options]`,`--auto-publish on|off|inherit --project [options]`],details:`Without --auto-publish, prints the current values.`,options:{"output-format":{type:`string`,value:`<brief|json|jsonl|inherit>`,help:`Set the output protocol (inherit for project only)`},"auto-publish":{type:`string`,value:`on|off|inherit`,help:`Turn auto-publish on or off; inherit (with --project) drops the override`},project:{type:`boolean`,help:`Set it for this project only instead of every project`}},semantic:e=>Z({id:`config`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:e.values[`auto-publish`]!==void 0||e.values[`output-format`]!==void 0?[]:[`global`,`project`,`effective`,`source`,`applies`,`output`]},run(t,n){if(e.values[`auto-publish`]!==void 0&&e.values[`output-format`]!==void 0)throw new j(`Choose auto-publish or output-format.`);let r=e.values.project?`project`:`global`,i=jD(e.projectDir)[r],a,o=()=>{a=n.effects.begin(`config`,i)};typeof e.values[`output-format`]==`string`&&PD(e.projectDir,!!e.values.project,e.values[`output-format`],o);let s=$M({projectDir:e.projectDir,autoPublish:e.values[`auto-publish`],project:!!e.values.project},o);return a!==void 0&&n.effects.confirm(a),J({scope:r,projectDir:e.projectDir,file:i,...s,output:ND(e.projectDir),effective:s.project??s.global,source:s.project===null?s.global===null?`undecided`:`global`:`project`,applies:`supported_turn_end_hook`})},present:tN},e)};function tN({data:e}){let t=e.effective===null?`undecided`:e.effective?`on`:`off`;return{heading:`Config`,status:``,facts:[X(`Scope`,{key:`scope`,value:e.scope}),X(`File`,{key:`file`,value:e.file}),X(`Auto-publish`,{key:`autoPublish`,value:e.source===`undecided`?t:`${t} (${e.source})`}),X(`Output format`,{key:`output`,value:`${e.output.effective} (${e.output.source})`})],sections:[]}}function nN(e=process.env,t=m.default.homedir()){if(e.RYUGI_DAEMON_SOCKET)return e.RYUGI_DAEMON_SOCKET;let n=d.default.dirname(hk(e)),{home:r}=XD(e,t);if(Fk(r,t))return d.default.join(n,`daemon.sock`);let i=d.default.join(r,`daemon.sock`);if(Buffer.byteLength(i)<=103)return i;let a=f.default.createHash(`sha256`).update(r).digest(`hex`).slice(0,16);return d.default.join(n,`daemon-${a}.sock`)}function rN(e,{timeoutMs:t=5e3}={}){let n=(n,r)=>new Promise((i,a)=>{let o=_.default.connect(e),s=``,c=e=>{o.destroy(),a(e)},l=setTimeout(()=>c(/* @__PURE__ */ Error(`daemon ${n} timed out`)),t);o.on(`error`,e=>{clearTimeout(l),c(e)}),o.on(`connect`,()=>o.write(`${JSON.stringify({op:n,...r})}\n`)),o.on(`data`,e=>{if(s+=e.toString(`utf8`),s.length>4194304)return c(/* @__PURE__ */ Error(`daemon reply too large`));let t=s.indexOf(`
1239
+ `)}]}}const zj={threads:[`id`,`status`,`waitingOn`,`anchor`,`stale`,`changes`,`messages`,`preview`,`messageCount`,`omittedMessages`],asks:[`id`,`state`,`choice`,`text`,`byRecommendation`,`staleChoice`,`note`],groups:[`id`,`kind`,`verdict`,`choice`,`by`,`byRecommendation`,`round`,`threads`,`evidenceUpdated`,`rejectThreads`,`title`,`from`,`capturedAt`],rounds:[`id`,`state`,`title`,`groups`,`submitted`]},Bj={threads:[`id`,`status`,`waitingOn`],asks:[`id`,`state`],groups:[`id`,`kind`,`verdict`,`choice`],rounds:[`id`,`state`]},Vj=e=>e.startsWith(`document/`)?[`threads`,`asks`]:[`threads`,`groups`,`rounds`];function Hj(e,t){return e.section?`Choose section or sections, not both.`:!e.sections.length||new Set(e.sections).size!==e.sections.length||e.sections.some(e=>!Vj(t).includes(e))?`Choose distinct review sections supported by this artifact.`:e.fields||e.cursor||e.snapshot||e.thread||e.filters&&Object.values(e.filters).some(e=>e!==void 0)?`Fields, filters, thread, cursor and snapshot require a single --section. Follow each collection continuation separately.`:null}function Uj(e){let{section:t,filters:n}=e;if(!t&&(e.detail||e.cursor||e.fields||n&&Object.values(n).some(Boolean)))return`Choose a section before requesting detail, fields, filters or a cursor.`;if(t&&!(t in zj))return`Unknown review section.`;if(n&&Object.keys(n).some(e=>![`status`,`waitingOn`,`kind`,`choiceState`].includes(e)))return`Unknown review filter.`;if(n?.waitingOn&&(t!==`threads`||![`agent`,`human`,`any`].includes(n.waitingOn)))return`waitingOn applies to threads and must be agent, human or any.`;let r=t===`threads`?[`open`,`resolved`]:t===`asks`?[`draft`,`submitted`,`settled`,`orphan`]:t===`groups`?[`pending`,`pass`,`reject`]:[`open`,`submitted`,`closed`];return n?.status&&!r.includes(n.status)?`Invalid status for this section.`:n?.kind&&(t!==`groups`||![`choose`,`verify`].includes(n.kind))?`kind applies to groups.`:t===`groups`&&n?.status&&n.kind!==`verify`?`Verify status requires kind=verify.`:n?.choiceState&&(t!==`groups`||n.kind!==`choose`||![`chosen`,`empty`].includes(n.choiceState))?`choiceState requires a choice group.`:t&&e.fields?.some(e=>!zj[t].includes(e))?`Unknown field for this section.`:null}function Wj(e,t,n){let r=d.default.resolve(e),i=n?.begin(`save`,r),a;try{a=u.default.openSync(r,`wx`,384)}catch(e){throw i!==void 0&&n.set(i,`failed`),new K({code:e.code===`EEXIST`?`E_FILE_EXISTS`:`E_FILE_WRITE_FAILED`,message:`Could not create ${r}: ${e.message}`})}try{u.default.writeFileSync(a,t)}catch(e){throw u.default.closeSync(a),u.default.unlinkSync(r),i!==void 0&&n.set(i,`failed`),new K({code:`E_FILE_WRITE_FAILED`,message:`Could not save ${r}: ${e.message}`})}return u.default.closeSync(a),i!==void 0&&n.confirm(i,{bytes:typeof t==`string`?Buffer.byteLength(t):t.byteLength}),{file:r,bytes:typeof t==`string`?Buffer.byteLength(t):t.byteLength}}function Gj(e,t,n,r,i){let a=[`--artifact`,t,`--project-dir`,e.projectDir];if(n.evidence===`preview`&&n.items.length&&n.snapshot){let t=i.findIndex(e=>e.label===`Read`),o=[`status`,`waiting-on`,`kind`,`choice-state`].flatMap(t=>typeof e.values[t]==`string`?[`--${t}`,String(e.values[t])]:[]),s={...q([`comment`,`list`,...a,`--section`,`threads`,`--detail`,`--snapshot`,n.snapshot,`--limit`,String(r?.returned??n.items.length),...typeof e.values.cursor==`string`?[`--cursor`,e.values.cursor]:[],...o,...e.values.all?[`--all`]:[]],`Read`),reason:`Read the complete captured page before acting. Previews mark nothing read.`};t<0?i.push(s):i.splice(t,1,s)}let o=i.findIndex(e=>e.label===`Acknowledge`);o>=0&&i.splice(o,1)}const Q=e=>typeof e==`string`?e:``,Kj=e=>e.replaceAll(/\s*\n\s*/g,` / `).trim(),qj=(e,t)=>`${e} ${t}${e===1?``:`s`}`,Jj=e=>e[0].toUpperCase()+e.slice(1),Yj=(e,t=[])=>Object.entries(e??{}).filter(([e,n])=>e!==`waitingOnAgent`&&!t.includes(e)&&typeof n==`number`&&n>0).map(([e,t])=>`${t} ${e}`).join(`, `),Xj=e=>e?` (${e})`:``,Zj={asks:{word:`to apply`,none:`nothing to apply`,listed:[`submitted`]},groups:{word:`to act on`,none:`nothing to act on`,listed:[]},rounds:{word:`open or submitted`,none:`nothing open`,listed:[`open`,`submitted`]}};function Qj(e,t,n,r=!1){let i=n?.total??t.items.length,a=t.summary;if(r){let e=`${i} matched`;return{head:e,full:`${e}${Xj(Yj(a))}`,count:i}}if(e===`threads`){let e=Number(a?.waitingOnAgent??0),t=i?`${i} unread${e?`, ${e} waiting on you`:``}`:`nothing unread`,n=Number(a?.resolved??0);return{head:t,full:`${t}${n?` (${n} resolved)`:``}`,count:i}}let o=Zj[e],s=i?`${i} ${o.word}`:o.none,c=e===`groups`?Object.entries(a??{}).reduce((e,[t,n])=>t===`waitingOnAgent`||typeof n!=`number`?e:e+n,0)-i:0,l=e===`groups`?c>0?qj(c,`other`):``:Yj(a,o.listed);return{head:s,full:`${s}${Xj(l)}`,count:i}}function $j(e){if(!e||typeof e!=`object`)return``;let t=e;if(t.kind===`node`)return` node ${Q(t.id)}`;if(t.kind!==`edge`)return``;let n=typeof t.index==`number`&&t.index>0?` #${t.index+1}`:``;return` edge ${Q(t.from)} → ${Q(t.to)}${n}`}function eM(e){let t=e.snapshot&&typeof e.snapshot==`object`?e.snapshot:{},n=Q(t.tag),r=Q(t.title),i=e.point&&typeof e.point==`object`?e.point:null,a=t.value===void 0?``:` = ${Kj(JSON.stringify(t.value))}`,o=i?` · point ${Q(i.series)} @ ${String(i.x)}${a}`:typeof e.row==`string`?` · row ${e.row}${typeof t.value==`object`?``:a}`:``;return`${n?`${n} `:``}${String(e.block)}${r?` "${Kj(r)}"`:``}${o}${e.dataChanged?` · data changed`:``}`}const tM=e=>{let t=Math.round(e*10),n=Math.floor(t/10);return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}.${t%10}`};function nM(e){let t=Q(e.title);return`${e.deleted?`shot ${String(e.shot)} (shot deleted)`:`shot ${typeof e.number==`number`?`${e.number} `:``}${String(e.shot)}${t?` "${Kj(t)}"`:``}`}${typeof e.t==`number`?` · ${typeof e.cut==`number`?`cut ${e.cut} `:``}at ${tM(e.t)}`:``}${typeof e.line==`string`?` · line ${e.line}${Q(e.lineText)?` "${Kj(Q(e.lineText))}"`:``}`:``}${e.mark?` · marked`:``}${Q(e.cropPath)?` · crop ${Q(e.cropPath)}`:``}`}function rM(e){if(!e||typeof e!=`object`)return``;let t=e;if(typeof t.blockId==`string`){let e=Array.isArray(t.blockIds)&&t.blockIds.length>1?t.blockIds:[t.blockId];return`${e.length>1?`blocks`:`block`} ${e.join(`, `)}${$j(t.diagram)}${Q(t.quote)?` "${Kj(Q(t.quote))}"`:``}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(`, `)}`;if(typeof t.block==`string`)return eM(t);if(typeof t.shot==`string`)return nM(t);if(typeof t.slide==`string`){let e=Q(t.title),n=Q(t.text),r=Array.isArray(t.nodes)?t.nodes:[],i=r.length?` · ${r.length} node${r.length===1?``:`s`}: ${r.map(e=>`${Q(e.tag)} ${Q(e.block)} "${Kj(Q(e.text))}"`).join(`, `)}`:``;return`slide ${t.slide}${e?` "${Kj(e)}"`:``}${i||(n?` · on "${Kj(n)}"`:``)}`}let n=Q(t.page);if(typeof t.board==`string`)return`${n?`page ${n} `:``}board ${t.board}`;let r=typeof t.x==`number`&&typeof t.y==`number`?` ${Math.round(t.x)},${Math.round(t.y)}`:``;return`page ${n||`main`}${r}`}const iM={key:`id`,positional:!0,required:!0},aM={key:`line`,positional:!0,required:!0},oM={key:`tail`,positional:!0,required:!0},sM=e=>e.choice?` → ${e.choice}${e.byRecommendation?` (recommended)`:``}`:``;function cM(e,t){return e===`asks`?{columns:[iM,aM,{key:`note`,label:`note`},{key:`staleChoice`,label:`stale choice`}],rows:t.map(e=>({...e,line:`${Q(e.state)}${e.choice?sM(e):Q(e.text)?` · "${Kj(Q(e.text))}"`:`choice`in e||`text`in e?` · no answer`:``}`,note:Q(e.note)&&`"${Kj(Q(e.note))}"`}))}:e===`threads`?{columns:[iM,{key:`status`,positional:!0,required:!0},{key:`waiting`,positional:!0},{key:`where`,positional:!0},{key:`marked`,label:`marked`},{key:`stale`,label:`stale`},{key:`orphan`,label:`orphan`},{key:`messageCount`,positional:!0},{key:`preview`,positional:!0}],rows:t.map(e=>({...lM(e),messageCount:typeof e.messageCount==`number`&&e.messageCount?qj(e.messageCount,`message`):``,preview:Q(e.preview)&&`"${Kj(Q(e.preview))}"`}))}:e===`groups`?{columns:[iM,{key:`kind`,positional:!0,required:!0},aM,{key:`origin`,positional:!0},{key:`evidenceUpdated`,label:`evidence updated`},{key:`rejects`,positional:!0},{key:`threadCount`,positional:!0},oM],rows:t.map(e=>({...e,line:e.kind===`verify`?Q(e.verdict):`${e.round?`round ${e.round}`:``}${e.choice?sM(e):` · no pick`}`.replace(/^ · /,``),origin:typeof e.from==`string`&&e.from?`from ${e.from}`:``,rejects:typeof e.rejectThreads==`number`&&e.rejectThreads?qj(e.rejectThreads,`reject thread`):``,threadCount:typeof e.threads==`number`&&e.threads?qj(e.threads,`thread`):``,tail:Q(e.title)}))}:{columns:[iM,{key:`state`,positional:!0,required:!0},{key:`groupList`,positional:!0},oM],rows:t.map(e=>({...e,groupList:Array.isArray(e.groups)&&e.groups.length?`groups ${e.groups.join(`, `)}`:``,tail:Q(e.title)}))}}function lM(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:``,where:rM(e.anchor&&typeof e.anchor==`object`&&typeof e.page==`string`?{page:e.page,...e.anchor}:e.anchor),marked:Array.isArray(e.marked)?e.marked.map(Q).filter(Boolean).join(`; `):``,reject:e.anchor?.verdict===`reject`,stale:e.stale===!0,orphan:e.orphan===!0}}const uM=e=>e.status===`open`?[`reply --thread ${String(e.id)} --text <message>`,...e.reject?[]:[`resolve --thread ${String(e.id)}`]].join(`, `):``,dM=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function fM(e,t=`items`,n=!0){return{kind:`messages`,key:t,groups:e.map(e=>{let t=lM(e);return{facts:[dM(`id`,t.id),dM(`status`,t.status),dM(`waiting`,t.waiting),dM(`where`,t.where),{label:`marked`,binding:{key:`marked`,value:t.marked}},{label:`reject`,binding:{key:`reject`,value:t.reject}},{label:`stale`,binding:{key:`stale`,value:t.stale}},{label:`orphan`,binding:{key:`orphan`,value:t.orphan}},dM(`spentBy`,n?uM(t):``)],messages:(Array.isArray(e.messages)?e.messages:[]).map(e=>({facts:[dM(`message`,[e.id,`${Q(e.name)||Q(e.author)}${e.author===`agent`?` (agent)`:``}`,Q(e.at)&&lO(Q(e.at)),e.deleted?`(deleted)`:``,Q(e.editedAt)&&`edited ${lO(Q(e.editedAt))}`].filter(Boolean).join(` `))],text:typeof e.text==`string`?e.text:``}))}})}}function pM(e,t,n,r,i){let a=Qj(e,t,n,i),o={key:r?e:`items`,title:Jj(e),summary:a.full};return e===`threads`&&t.evidence===`complete`?{...fM(t.items),...o,...r?{page:n}:{}}:{kind:`records`,...cM(e,t.items),...o,...r?{page:n}:{}}}const mM=[`threads`,`asks`,`groups`,`rounds`];function hM(e,t){let n=e.summary??{},r=e=>t.find(t=>t.label===Jj(e)),i=mM.filter(e=>r(e));return{heading:`Comment list`,status:``,subject:e.artifact,facts:[],sections:i.map(e=>{let t=n[e],r=e===`threads`?Qj(`threads`,{items:[],summary:{waitingOnAgent:n.waitingOnAgent}},{total:Number(t??0)}).head:Yj(t)||`none`;return{kind:`records`,key:e,title:Jj(e),summary:r,columns:[],rows:[]}}),actions:t.filter(e=>!i.some(t=>Jj(t)===e.label))}}function gM({data:e,actions:t,coverage:n},r=`Comment list`,i=!1){if(e.section===`summary`)return hM(e,t);let a=n.page;return{heading:r,status:``,subject:e.artifact,summary:Qj(e.section,e,a,i).head,facts:[...e.evidence===`preview`&&e.snapshot&&e.items.length?[X(`Snapshot`,Y(e,`snapshot`))]:[],...e.delivery?[X(`Delivery`,Y(e,`delivery`))]:[],...e.receipt&&!e.delivery?[X(`Receipt`,Y(e,`receipt`))]:[]],sections:[pM(e.section,e,a,!1,i)]}}function _M({data:e},t=!1){let n=Object.entries(e.sections),r=n.map(([e,n])=>Qj(e,n,n.page,t)).filter(e=>e.count>0).map(e=>e.head);return{heading:`Comment list`,status:``,subject:e.artifact,summary:r.join(` · `)||`nothing new`,facts:[],sections:n.map(([e,n])=>pM(e,n,n.page,!0,t))}}const $=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,vM=[`brief`,`table`,`json`,`jsonl`,`raw`];function yM(e,t=!1){let n=$(e,`artifact`),r=t?VE:BE;if(!n||!UE(r).test(n))throw new K({code:`E_ARGUMENT_INVALID`,message:`--artifact must be ${WE(r)}.`});return n}function bM(e){let t=$(e,`limit`);if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new K({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});return{...t===void 0?{}:{limit:Number(t)},...$(e,`cursor`)?{cursor:$(e,`cursor`)}:{},...$(e,`snapshot`)?{snapshot:$(e,`snapshot`)}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...e.values.hold?{hold:!0}:{},...$(e,`fields`)?{fields:$(e,`fields`).split(`,`).map(e=>e.trim())}:{}}}function xM(e,t){let n=jO(t);return{...e,agent:NO(t)??`Agent`,...n?{session:n}:{}}}async function SM(e,t,n,r,i){let a=await rO(e.projectDir).call(`POST`,`/api/agent/v1/${n}/${r}`,xM(i,process.env),t.signal);if(t.payloads.raw=a.raw,a.json.schema!==`ryugi.review/v1`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported review response.`});if(a.status<200||a.status>=300)throw new K({code:typeof a.json.code==`string`?a.json.code:`E_REVIEW_FAILED`,message:a.json.error||`HTTP ${a.status}`,httpStatus:a.status});return a.json}const CM=/* @__PURE__ */ new Set([`artboard`,`document`,`preview`,`report`,`slides`,`storyboard`,`whiteboard`]);async function wM(e,t,n,r,i){if(!CM.has(t.split(`/`)[0]??``))return null;let a=await rO(e).call(`POST`,`/api/agent/v1/${t}/review`,xM({op:`consume`,thread:n,resolve:r},process.env),i);if(a.json.code===`E_UNDELIVERED`||a.json.code===`E_REJECT_OPEN`)throw new K({code:a.json.code,message:String(a.json.error),httpStatus:a.status});return a.status<200||a.status>=300?{failed:String(a.json.error||`HTTP ${a.status}`)}:typeof a.json.unread==`number`?{consumed:Number(a.json.consumed),unread:a.json.unread}:null}function TM(e,t){return[`--artifact`,t,`--project-dir`,e.projectDir]}function EM(e,t,n){let r=/* @__PURE__ */ new Set([...Object.keys(LD),`artifact`,`receipt`]),i=Object.keys(e.values).find(e=>!r.has(e));if(i)throw new K({code:`E_ARGUMENT_INVALID`,message:`--${i} is not supported for ack.`});let a=$(e,`receipt`);if(!a)throw new K({code:`E_ARGUMENT_INVALID`,message:`ack requires --receipt.`});return Z({id:n===`review`?`comment.ack`:`changes.ack`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){rO(e.projectDir);let o=i.effects.begin(n===`review`?`comment.ack`:`changes.ack`,a),s=await SM(e,i,t,n,{op:`ack`,receipt:a});if(![`acknowledged`,`unchanged`].includes(s.status))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported acknowledgement result; inspect unread state before retrying.`});return i.effects.set(o,s.status===`unchanged`?`none`:`confirmed`,{artifact:t}),J({artifact:t,receipt:a,status:s.status})},present:kM(n===`review`?`comment`:`changes`)},e)}function DM(e,t){let n=$(e,`receipt`);if(!n)throw new K({code:`E_ARGUMENT_INVALID`,message:`deliver requires --receipt.`});return Z({id:`comment.deliver`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){rO(e.projectDir);let a=i.effects.begin(`comment.deliver`,n);if((await SM(e,i,t,`review`,{op:`deliver`,receipt:n})).status!==`delivered`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported delivery result.`});return i.effects.confirm(a,{artifact:t}),J({artifact:t,receipt:n,status:`delivered`})},present:kM(`comment`)},e)}function OM(e,t,n){if(n!==`list`)throw new K({code:`E_ARGUMENT_INVALID`,message:`--sections applies to comment list.`});let r=bM(e),i=$(e,`sections`)?.trim(),a=i===`all`?Vj(t):(i??``).split(`,`).map(e=>e.trim()),o=Object.fromEntries([`status`,`waiting-on`,`kind`,`choice-state`].map(t=>[t,$(e,t)])),s=Hj({...r,sections:a,section:$(e,`section`),thread:$(e,`thread`),filters:o},t);if(s)throw new K({code:`E_ARGUMENT_INVALID`,message:s});return Z({id:`comment.list`,mode:`finite`,output:{formats:vM,detail:!0},async run(n,i){let o=await SM(e,i,t,`review`,{op:`list`,sections:a,...r});for(let e of a){let t=o.sections?.[e];if(!t||!Array.isArray(t.items)||typeof t.snapshot!=`string`||!t.page||typeof t.page.scope!=`string`||typeof t.page.hasMore!=`boolean`||!Number.isInteger(t.page.returned)||!(t.page.total===null||Number.isInteger(t.page.total)))throw new K({code:`E_SERVER_UPGRADE_REQUIRED`,message:`The server does not provide combined review pages. Run start --background for this project to rebuild/restart it.`});if(t.page.returned!==t.items.length||t.page.returned<0||t.page.total!==null&&t.page.total<t.page.returned||t.page.snapshot!==t.snapshot||t.page.nextCursor!==null&&typeof t.page.nextCursor!=`string`||t.page.hasMore!==(typeof t.page.nextCursor==`string`&&t.page.nextCursor.length>0))throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server returned inconsistent combined review coverage.`})}return jM(e,t,a,o,r)},present:e=>_M(e,r.all)},e)}const kM=e=>({data:t})=>({heading:e===`comment`?`Comment ack`:`Changes ack`,status:t.status,subject:t.artifact,facts:[],sections:[]});function AM({data:e}){let t=e.blocks.length;return{heading:`Changes`,status:e.saved?`saved`:``,subject:e.artifact,summary:e.empty?`no human edits`:e.diff===void 0?`${t} block${t===1?``:`s`} changed`:`complete diff`,facts:e.saved?[X(`File`,Y(e,`saved`),!0)]:[...e.receipt?[X(`Receipt`,{key:`receipt`,value:`${e.receipt} · changes ack --receipt ${e.receipt}`})]:[],...e.diff===void 0&&!e.empty&&e.snapshot?[X(`Snapshot`,Y(e,`snapshot`))]:[]],sections:e.empty||e.saved?[]:e.diff===void 0?[{kind:`records`,key:`blocks`,rows:e.blocks.map(e=>({id:e.id,size:[e.additions&&`+${e.additions}`,e.deletions&&`-${e.deletions}`].filter(Boolean).join(` `),preview:e.preview&&`"${e.preview.replaceAll(/\s*\n\s*/g,` / `)}"`})),columns:[{key:`id`,positional:!0,required:!0},{key:`size`,positional:!0},{key:`preview`,positional:!0}]}]:[{kind:`diff`,key:`diff`,text:e.diff}]}}function jM(e,t,n,r,i){let a={},o=[],s=[];for(let c of n){let n=r.sections[c],l=MM(e,t,c,n,i),{artifact:u,section:d,...f}=l.data;a[c]={...f,page:n.page},o.push(...l.actions.map(e=>e.label===`More`?{...e,label:`More (${c})`}:e)),f.evidence===`preview`&&c===`threads`&&s.push({path:`data.sections.threads.items.messages`,reason:`summary`})}return J({artifact:t,sections:a},void 0,{actions:o,coverage:{omitted:s}})}function MM(e,t,n,r,i,a){let o=r.page,s={artifact:t,section:n??`summary`,items:r.items??[],evidence:i.fields?`projected`:n&&n!==`threads`?`state`:i.detail||a?`complete`:`preview`,...r.snapshot?{snapshot:r.snapshot}:{},...r.receipt?{receipt:r.receipt}:{},...r.receipt&&e.values.hold?{delivery:r.receipt}:{},...r.summary?{summary:r.summary}:{}},c=[],l=TM(e,t);if(r.receipt&&c.push(q([`comment`,`ack`,...l,`--receipt`,r.receipt],`Acknowledge`)),o?.nextCursor&&c.push(q([`comment`,`list`,...l,`--section`,n,...i.detail?[`--detail`]:[],...Object.entries({status:$(e,`status`),"waiting-on":$(e,`waiting-on`),kind:$(e,`kind`),"choice-state":$(e,`choice-state`),fields:$(e,`fields`),limit:$(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),...i.all?[`--all`]:[],`--cursor`,o.nextCursor],`More`)),n)n===`threads`&&s.evidence===`preview`&&s.items[0]&&c.push(q([`comment`,`read`,...l,`--thread`,String(s.items[0].id),`--snapshot`,r.snapshot,`--detail`],`Read`));else{c.push(q([`comment`,`list`,...l,`--sections`,`all`,`--detail`,...i.all?[`--all`]:[],...$(e,`limit`)?[`--limit`,$(e,`limit`)]:[]],`Review all`));let n=[`threads`,...LE[t.split(`/`)[0]].review?.sections??[]];c.unshift(...n.map(e=>q([`comment`,`list`,...l,`--section`,e,...e===`asks`?[`--detail`]:[]],e[0].toUpperCase()+e.slice(1))))}if(n===`asks`)for(let e of s.items.filter(e=>e.state===`submitted`))c.push({...q([`comment`,`note`,...l,`--ask`,String(e.id),`--text`,`<what changed>`],`Settle (${e.id})`),reason:`Apply this submitted human answer, then replace the note argument with what changed. Never invent an answer.`});return n===`threads`&&Gj(e,t,s,o,c),J(s,void 0,{actions:c,coverage:{...o?{page:o}:{},...s.evidence===`preview`&&n===`threads`?{omitted:[{path:`data.items.messages`,reason:`summary`}]}:{}}})}function NM(e){let t=yM(e),n=e.positionals[0];if(n===`ack`)return EM(e,t,`review`);if(n===`deliver`)return DM(e,t);if(e.values.sections!==void 0)return OM(e,t,n);if(n!==`list`&&n!==`read`)throw new K({code:`E_ARGUMENT_INVALID`,message:`Expected list, read or ack.`});let r=bM(e),i=n===`read`?`threads`:$(e,`section`),a=$(e,`thread`);if(n===`read`&&!a)throw new K({code:`E_ARGUMENT_INVALID`,message:`read requires --thread.`});if(i&&![`threads`,`asks`,`groups`,`rounds`].includes(i))throw new K({code:`E_ARGUMENT_INVALID`,message:`Unknown review section.`});if(!i&&(r.detail||r.cursor||r.fields||[`status`,`waiting-on`,`kind`,`choice-state`].some(t=>e.values[t])))throw new K({code:`E_ARGUMENT_INVALID`,message:`Select --section before detail, fields, cursor or filters.`});let o=Object.fromEntries([[`status`,$(e,`status`)],[`waitingOn`,$(e,`waiting-on`)],[`kind`,$(e,`kind`)],[`choiceState`,$(e,`choice-state`)]].filter(([,e])=>e!==void 0)),s=Uj({...r,section:i,filters:o});if(s)throw new K({code:`E_ARGUMENT_INVALID`,message:s});return Z({id:`comment.${n}`,mode:`finite`,output:{detail:!0,formats:vM,collection:`items`,requiredFields:i?Bj[i]:[],fields:i?[...zj[i]]:[]},async run(s,c){let l=await SM(e,c,t,`review`,{op:n,...r,...i?{section:i}:{},...a?{thread:a,detail:!0}:{},...Object.keys(o).length?{filters:o}:{}});return MM(e,t,i,l,r,a)},present:t=>gM(t,n===`read`?`Comment read`:`Comment list`,r.all||!!$(e,`status`)&&(i!==`asks`||$(e,`status`)!==`submitted`)||!!$(e,`choice-state`))},e)}function PM(e){let t=yM(e,!0),n=e.positionals[0];if(n===`ack`)return EM(e,t,`changes`);if(n)throw new K({code:`E_ARGUMENT_INVALID`,message:`Expected changes or changes ack.`});let r=bM(e),i=$(e,`save`);if(i!==void 0&&!i.trim())throw new K({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});if(r.detail&&(r.fields||r.cursor||r.limit!==void 0))throw new K({code:`E_OPTION_CONFLICT`,message:`A complete diff cannot use --limit, --cursor or --fields.`});return Z({id:`changes`,mode:`finite`,output:{detail:!0,formats:i?[`brief`,`json`,`jsonl`]:vM,fields:[`artifact`,`snapshot`,`blocks`,`diff`,`empty`]},async run(n,a){let{page:o,schema:s,...c}=await SM(e,a,t,`changes`,{op:`read`,...r}),l=c;if(i&&l.empty!==!0&&typeof l.diff!=`string`)throw new K({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return complete diff evidence; no export was written.`});if(i){let e=Wj(i,l.diff??``,a.effects);l.saved=e.file,l.bytes=e.bytes,delete l.diff}let u=TM(e,t),d=l.receipt?[q([`changes`,`ack`,...u,`--receipt`,l.receipt],`Acknowledge`)]:l.empty?[]:[q([`changes`,...u,`--snapshot`,l.snapshot,...r.all?[`--all`]:[],`--detail`],`Read`)];return o?.nextCursor&&d.push(q([`changes`,...u,...r.all?[`--all`]:[],...Object.entries({fields:$(e,`fields`),limit:$(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),`--cursor`,o.nextCursor],`More`)),J(l,void 0,{actions:d,coverage:{...o?{page:o}:{},...!r.detail&&!l.empty?{omitted:[{path:`data.diff`,reason:`summary`}]}:{}}})},present:AM},e)}const FM={semantic:PM,positionals:1,name:`changes`,summary:`Show what your human partner changed in a document or a deck (needs a running server)`,usage:[`--artifact document/<id>|slides/<id> [--all] [--detail | --save <file>]`,`ack --artifact document/<id>|slides/<id> --receipt <receipt>`],details:`Previews unread document edits without marking them read. Use --detail for complete evidence, then changes ack --receipt after using it.`,options:{limit:{type:`string`,value:`<n>`,help:`Summary records per page (1–100, default 10)`},cursor:{type:`string`,value:`<cursor>`,help:`Continue a change summary snapshot`},snapshot:{type:`string`,value:`<snapshot>`,help:`Read a captured change snapshot`},receipt:{type:`string`,value:`<receipt>`,help:`ack: acknowledge the complete captured diff`},save:{type:`string`,value:`<file>`,help:`Save the complete diff without overwriting an existing file`},artifact:{type:`string`,value:`document/<id>|slides/<id>`,help:`The document or deck`},all:{type:`boolean`,help:`Show historical changes without a receipt`}}},IM={reject:0,pending:1,pass:2,checked:3},LM={reject:`rejected`,pending:`pending`,pass:`passed`,checked:`checked by agent`},RM=(e,t)=>e?`${e} ${t}`:``,zM=e=>e.filter(Boolean).join(` · `),BM=(e,t=!1)=>({key:e,positional:!0,required:t});function VM({data:e}){let{tally:t}=e,n=t=>e.claims.filter(e=>e.state===t).length,r=e.threads.filter(e=>e.status===`open`),i=zM([RM(t.needYou,`on your human partner`),RM(t.notVerified,`not verified`),RM(t.orphaned,`open reject on a claim that is gone`)]);return{heading:`Comment list`,status:``,subject:e.artifact,summary:t.done?`done`:t.rejected?`${t.rejected} to act on`:`nothing to act on`,facts:i?[X(`Waiting`,{key:`waiting`,value:i})]:[],sections:[{kind:`records`,key:`claims`,title:`Claims`,summary:zM([RM(n(`reject`),`rejected`),RM(n(`pending`),`pending`),RM(n(`pass`),`passed`),RM(n(`checked`),`checked by agent`)]),columns:[BM(`id`,!0),BM(`line`,!0),BM(`rejects`),{key:`evidenceUpdated`,label:`evidence updated`},BM(`origin`),BM(`tail`)],rows:[...e.claims].sort((e,t)=>IM[e.state]-IM[t.state]).map(e=>({...e,line:LM[e.state],rejects:e.state===`reject`&&e.rejectThreads?`${e.rejectThreads} reject thread${e.rejectThreads===1?``:`s`}`:``,evidenceUpdated:e.evidenceUpdated||void 0,origin:e.from?`from ${e.from}`:``,tail:e.title}))},...e.rows.length?[{kind:`records`,key:`rows`,title:`Artboard rows`,summary:String(e.rows.length),columns:[BM(`id`,!0),BM(`state`,!0)],rows:e.rows.map(e=>({...e,id:`${e.artboard}/${e.group}`}))}]:[],...e.reports?.length?[{kind:`records`,key:`reports`,title:`Child reports`,summary:String(e.reports.length),columns:[BM(`id`,!0),BM(`state`,!0),BM(`tail`)],rows:e.reports.map(e=>({id:`verify/${e.verify}`,state:e.state===`reject`?`rejected (${e.rejected})`:e.state===`pending`?`pending (${e.needYou})`:e.state===`pass`?`passed`:`not found`,tail:e.title}))}]:[],...e.gaps.length?[{kind:`records`,key:`gaps`,title:`Not verified`,summary:zM([RM(e.gaps.filter(e=>!e.waived).length,`open`),RM(e.gaps.filter(e=>e.waived).length,`waived`)]),columns:[BM(`id`,!0),BM(`line`,!0),BM(`tail`)],rows:e.gaps.map(e=>({...e,line:e.waived?`waived`:`not verified`,tail:e.title}))}]:[],...e.threads.length?[{kind:`messages`,key:`threads`,title:`Threads`,summary:zM([RM(r.length,`open`),RM(e.threads.length-r.length,`resolved`)]),groups:e.threads.map(e=>({facts:[{...X(`Thread`,{key:`id`,value:e.id},!0),positional:!0},X(`On`,{key:`anchor`,value:e.anchor.claim?`claim ${e.anchor.claim}`:`gap ${e.anchor.gap}`},!0),X(`Verdict`,{key:`verdict`,value:e.anchor.verdict??(e.anchor.waive?`waived`:``)}),X(`Status`,{key:`status`,value:e.status},!0),...e.stale?[X(`Stale`,{key:`stale`,value:!0})]:[]],messages:e.messages.map(e=>({facts:[{...X(`Author`,{key:`author`,value:e.author},!0),positional:!0},X(`At`,{key:`at`,value:e.at})],text:e.text}))}))}]:[]]}}function HM(e){let t=e.values.artifact,n=JE(e.projectDir,t);return Z({id:`comment.list`,mode:`finite`,output:{detail:!0,formats:[`brief`,`json`,`jsonl`],fields:[`id`,`state`,`title`,`from`],scalar:e=>e.tally.done?`done`:`open`},async run(r,i){let a=NO(process.env),o=await rO(e.projectDir).call(`POST`,`/api/agent/${t}/comments`,{op:`list`,...a?{agent:a}:{}},i.signal);if(o.status<200||o.status>=300)throw new K({code:o.status===404?`E_ARTIFACT_NOT_FOUND`:`E_COMMENT_FAILED`,message:o.json?.error||`HTTP ${o.status}`,httpStatus:o.status});let s=o.json,c=[`--artifact`,t,`--project-dir`,e.projectDir],l=s.threads.filter(e=>e.status===`open`);return J({...s,artifact:t,projectDir:e.projectDir},void 0,{actions:l.length?[{...q([`check`,...c],`Check`),reason:`After repairing the rejected claim and updating ${n.write} with real evidence. Preserve existing IDs and human edits; a human pass closes the rejection.`},...l.map(e=>({...q([`comment`,`reply`,...c,`--thread`,e.id,`--text`,`<what changed and the replacement evidence>`],`Reply (${e.id})`),reason:`Reply after the repair; leave rejected claims open for the human verdict.`}))]:[]})},present:VM},e)}function UM({data:e}){let t=e.threadId?`thread ${e.threadId}`:e.ask?`ask ${e.ask}`:e.group?`group ${e.group}${e.board?` → ${e.board}`:``}`:e.round?`round ${e.round}`:``;return{heading:`Comment ${e.operation}`,status:e.status,subject:e.artifact,summary:`${t}${e.operation===`answer`&&e.choice?` → ${e.choice}`:``}`,facts:[...e.messageId?[X(`Message`,Y(e,`messageId`))]:[],...e.unread?[X(`Unread`,Y(e,`unread`))]:[],...e.consumeFailed?[X(`Consume failed`,Y(e,`consumeFailed`))]:[],...e.groups?.length?[X(`Groups`,{key:`groups`,value:e.groups.join(`, `)})]:[]],sections:[]}}function WM(e){let t={action:e.positionals[0],artifact:e.values.artifact,projectDir:e.projectDir};for(let n of[`ask`,`at`,`block`,`board`,`choice`,`claim`,`cut`,`edge`,`element`,`gap`,`group`,`line`,`node`,`page`,`quote`,`round`,`shot`,`slide`,`text`,`thread`,`x`,`y`])t[n]=e.values[n];for(let n of[`all`,`clear`,`withdraw`])t[n]=!!e.values[n];return t}function GM(e){let t=WM(e),n=t.action;if(t.artifact?.startsWith(`verify/`)&&[`list`,`read`,`ack`,`deliver`].includes(n??``)){if(n!==`list`)throw new K({code:`E_OPTION_UNSUPPORTED`,message:`A verify report has no thread receipts: comment list shows every thread.`});return HM(e)}if([`list`,`read`,`ack`,`deliver`].includes(n??``))return NM(e);if([`section`,`sections`,`limit`,`cursor`,`snapshot`,`receipt`,`status`,`waiting-on`,`kind`,`choice-state`,`hold`].some(t=>e.values[t]!==void 0))throw new K({code:`E_OPTION_UNSUPPORTED`,message:`Review query options apply only to list, read and ack.`});return Z({id:`comment.${n??`unknown`}`,mode:`finite`,output:{formats:n===`pass`&&t.all?[`brief`,`json`,`jsonl`]:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.ask??e.group??e.round??e.threadId??e.artifact},async run(e,n){let r=YM(t);rO(t.projectDir);let i=n.effects.begin(`comment.${r.action}`,t.thread??t.ask??t.group??t.artifact);r.action===`resolve`&&t.thread&&await wM(t.projectDir,t.artifact,t.thread,!0,n.signal);let a=await XM(t,r,n.signal);if(a.status>=400&&a.status<500&&n.effects.set(i,`failed`),a.status<200||a.status>=300)throw new K({code:a.status===404&&!a.json.error?`E_SERVER_UPGRADE_REQUIRED`:`E_COMMENT_FAILED`,message:a.json.error||`HTTP ${a.status}`,httpStatus:a.status});let o=a.json;n.effects.confirm(i);let s=null,c;if(r.action===`reply`&&t.thread)try{let e=await wM(t.projectDir,t.artifact,t.thread,!1,n.signal);e&&`failed`in e?c=e.failed:s=e}catch(e){c=e instanceof Error?e.message:String(e)}let{action:l,request:u}=r,d={add:`added`,reply:`replied`,resolve:`resolved`,answer:t.clear?`cleared`:`answered`,note:`settled`,choose:t.clear?`cleared`:`recorded`,pass:`recorded`,reject:`recorded`,waive:`recorded`,submit:t.withdraw?`withdrawn`:`submitted`},f=l===`pass`&&[o.groups,o.claims].some(e=>Array.isArray(e)&&e.length===0);return f&&n.effects.set(i,`none`),J({artifact:t.artifact,operation:l,status:f?`unchanged`:d[l],by:`agent`,...typeof o.threadId==`string`?{threadId:o.threadId}:{},...typeof o.messageId==`string`?{messageId:o.messageId}:{},...t.ask?{ask:t.ask}:{},...t.group?{group:t.group}:{},...Array.isArray(o.groups)?{groups:o.groups}:{},...Array.isArray(o.claims)?{groups:o.claims}:{},...t.claim?{group:t.claim}:{},...t.gap?{group:t.gap}:{},...t.round?{round:t.round}:{},...l===`choose`?{board:u.board}:{},...l===`submit`?{submitted:!t.withdraw}:{},...l===`answer`?{choice:u.choice}:{},...s?{unread:s.unread}:{},...c?{consumeFailed:c}:{}},void 0,{effects:n.effects.snapshot()})},present:UM},e)}const KM=UE(HE),qM=/* @__PURE__ */ new Set([`pass`,`reject`]);function JM(e,t,n){let r=LE[n];if(r.commentRequest)return r.commentRequest(e,t);if(t===`waive`)throw new j(`comment waive works on verify reports only`);let i=r.commentActions?.[t];if(i)return i(e);if(t===`answer`||t===`note`)throw new j(`comment ${t} works on documents only`);if(t===`choose`||t===`submit`||qM.has(t))throw new j(`comment ${t} works on artboards only`);if(t===`add`)throw new j(`comment add does not work on ${n}`);if(!e.thread)throw new j(`comment ${t} needs --thread <threadId>`);return t===`reply`?{op:`reply`,threadId:e.thread,text:rt(e)}:{op:`resolve`,threadId:e.thread}}function YM(e){let t=tt.find(t=>t===e.action);if(!t)throw new j(`comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive`);if(!e.artifact||!KM.test(e.artifact))throw new j(`--artifact must be ${WE(HE)}`);let[n,r]=e.artifact.split(`/`);return{action:t,type:n,id:r,request:JM(e,t,n),artifact:e.artifact}}async function XM(e,t,n){let{type:r,id:i,request:a}=t,o=rO(e.projectDir),s=NO(process.env);return o.call(`POST`,`/api/agent/${r}/${i}/comments`,{...a,agent:s??`Agent`},n)}const ZM={actionOptions:{list:[`limit`,`cursor`,`snapshot`,`status`,`waiting-on`,`kind`,`choice-state`,`thread`,`hold`],read:[`limit`,`cursor`,`all`,`save`]},actionDetails:{reply:`Adds a message to the thread and marks the messages of it delivered to you as read. Without --text, reads the message from stdin.`,resolve:`Closes the thread and marks the messages of it delivered to you as read. Refused while the thread holds a message you never received, and on a reject, which only your human partner passes.`},semantic:GM,name:`comment`,summary:`Read and answer feedback on a document, artboard, whiteboard, deck, data report or verify report (needs a running server)`,usage:[`list --artifact ${GE(BE)} --sections all|<names> [--detail] [--all]`,`list --artifact ${GE(BE)} [--section threads|asks|groups|rounds] [--all]`,`read --artifact ${GE(BE)} --thread <threadId> [--snapshot <token>]`,`ack --artifact ${GE(BE)} --receipt <receipt>`,`deliver --artifact ${GE(BE)} --receipt <delivery>`,`add --artifact document/<id> --block <blockId> [--quote <text>] [--text <text>]`,`add --artifact document/<id> --block <blockId> (--node <id> | --edge "<from>-><to>[#n]") [--text <text>]`,`add --artifact artboard/<id> --board <boardId> [--x <px> --y <px>] [--text <text>]`,`add --artifact whiteboard/<id> (--element <elementId> | --x <px> --y <px> [--page <pageId>]) [--text <text>]`,`add --artifact slides/<id> --slide <slideId> [--text <text>]`,`add --artifact storyboard/<id> (--shot <shotId> [--line <lineId> | --at <seconds>] | --cut <n> --at <seconds>) [--text <text>]`,`add --artifact report/<id> --block <blockId> [--point <series>:<x> | --row <rowKey>] [--text <text>]`,`reply --artifact ${GE(HE)} --thread <threadId> [--text <text>]`,`resolve --artifact ${GE(BE)} --thread <threadId>`,`choose --artifact artboard/<id> --group <groupId> (--board <boardId> | --clear)`,`submit --artifact artboard/<id> --round <roundId> [--withdraw]`,`submit --artifact document/<id> [--withdraw]`,`answer --artifact document/<id> --ask <questionId> (--choice <value> | --text <answer> | --clear)`,`note --artifact document/<id> --ask <questionId> [--text <note>]`,`pass --artifact artboard/<id> (--group <groupId> | --all) [--text <text>]`,`reject --artifact artboard/<id> --group <groupId> [--text <text>]`,`list --artifact verify/<id>`,`pass --artifact verify/<id> (--claim <claimId> | --all) [--text <note>]`,`reject --artifact verify/<id> --claim <claimId> [--text <text>]`,`waive --artifact verify/<id> --gap <gapId> [--text <reason>]`],details:`list returns a summary; select threads, asks, groups or rounds to read one collection. Previews deliver nothing. A complete read delivers its threads to you; reply and resolve spend what was delivered, and resolve refuses while a thread holds a message you never received. A page that continues names its cursor, a preview names its snapshot. list --hold delivers only once deliver confirms its Delivery handle. asks, groups and rounds are independent state reads. Without --text, add, reply, note and reject read the message from stdin. answer records what your human partner said in the terminal; note settles a question once its answer is applied. pass and reject record a verdict on a verify group only when your human partner asks for it; the board shows the agent recorded it.`,options:{sections:{type:`string`,value:`<all|threads,asks|threads,groups,rounds>`,help:`Read multiple bounded review collections in one request`},section:{type:`string`,value:`<threads|asks|groups|rounds>`,help:`Semantic list: select one review collection`},limit:{type:`string`,value:`<n>`,help:`Semantic reads: records per page (1–100, default 10)`},cursor:{type:`string`,value:`<cursor>`,help:`Continue a semantic snapshot page`},snapshot:{type:`string`,value:`<snapshot>`,help:`Read an existing semantic snapshot`},receipt:{type:`string`,value:`<receipt>`,help:`ack: confirm exactly the complete evidence delivered`},hold:{type:`boolean`,help:`list: record the threads as delivered only once deliver confirms the Delivery handle`},status:{type:`string`,value:`<status>`,help:`Filter the selected semantic review collection`},"waiting-on":{type:`string`,value:`<agent|human|any>`,help:`Filter unread threads by who should reply`},kind:{type:`string`,value:`<verify|choose>`,help:`Filter review groups by kind`},claim:{type:`string`,value:`<claimId>`,help:`Verify reports: the claim to pass or reject`},gap:{type:`string`,value:`<gapId>`,help:`Verify reports: the not-verified item to waive`},"choice-state":{type:`string`,value:`<chosen|empty>`,help:`Filter choice groups`},artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact whose feedback to read or answer`},all:{type:`boolean`,help:`list: every thread, not only what changed; pass: every verify group not yet passed`},block:{type:`string`,value:`<blockId>`,help:`add: the document block to comment on`},quote:{type:`string`,value:`<text>`,help:`add: the text in the block the comment is about`},node:{type:`string`,value:`<nodeId>`,help:`add: the node of the diagram in --block, by its id in the mermaid source`},edge:{type:`string`,value:`<from>-><to>[#n]`,help:`add: the edge of the diagram in --block between two node ids; #2 is the second edge between them`},board:{type:`string`,value:`<boardId>`,help:`add: the artboard board to comment on`},element:{type:`string`,value:`<elementId>`,help:`add: the whiteboard element to comment on`},page:{type:`string`,value:`<pageId>`,help:`add: the whiteboard page --x and --y are on (default main)`},slide:{type:`string`,value:`<slideId>`,help:`add: the slide of a deck to comment on`},shot:{type:`string`,value:`<shotId>`,help:`add: the shot of a storyboard to comment on`},line:{type:`string`,value:`<lineId>`,help:`add: the voice line of --shot the comment is about`},at:{type:`string`,value:`<seconds>`,help:`add: the moment of --shot, or of --cut, the comment is about`},cut:{type:`string`,value:`<n>`,help:`add: the registered cut --at is a moment of`},point:{type:`string`,value:`<series>:<x>`,help:`add: the point of a report chart in --block, by its series and x value`},row:{type:`string`,value:`<rowKey>`,help:`add: the row of a report table in --block`},x:{type:`string`,value:`<px>`,help:`add: horizontal position on the board`},y:{type:`string`,value:`<px>`,help:`add: vertical position on the board`},thread:{type:`string`,value:`<threadId>`,help:`reply, resolve: the thread`},text:{type:`string`,value:`<text>`,help:`add, reply, note: the message; answer: a written answer; reject: the reason; pass: an optional note; waive: an optional reason`},group:{type:`string`,value:`<groupId>`,help:`choose: the choice group; pass, reject: the verify group`},clear:{type:`boolean`,help:`choose, answer: clear the choice or answer`},ask:{type:`string`,value:`<questionId>`,help:`answer, note: the question id`},choice:{type:`string`,value:`<value>`,help:`answer: the option value`},round:{type:`string`,value:`<roundId>`,help:`submit: the round`},withdraw:{type:`boolean`,help:`submit: withdraw the submission`}},positionals:1},QM={on:!0,off:!1,inherit:null};function $M(e,t=()=>{}){let n=yD(eD(process.env,process.platform,m.default.homedir())),r=d.default.join(d.default.dirname(Je(e.projectDir).root),`config.json`);if(e.autoPublish!==void 0){let i=QM[e.autoPublish];if(i===void 0)throw new j(`--auto-publish takes on, off, or (with --project) inherit`);if(e.project){let e=fD(r);if(e.warning)throw new j(e.warning);t(),hD(r),_D(r,i)}else if(i===null)throw new j(`inherit only applies with --project`);else SD(n,i,t)}return{global:xD(n)??null,project:fD(r).config.autoPublish??null}}const eN={name:`config`,summary:`Auto-publish changed artifacts as private cloud copies when the agent's turn ends`,usage:[`[--auto-publish on|off] [options]`,`--auto-publish on|off|inherit --project [options]`],details:`Without --auto-publish, prints the current values.`,options:{"output-format":{type:`string`,value:`<brief|json|jsonl|inherit>`,help:`Set the output protocol (inherit for project only)`},"auto-publish":{type:`string`,value:`on|off|inherit`,help:`Turn auto-publish on or off; inherit (with --project) drops the override`},project:{type:`boolean`,help:`Set it for this project only instead of every project`}},semantic:e=>Z({id:`config`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:e.values[`auto-publish`]!==void 0||e.values[`output-format`]!==void 0?[]:[`global`,`project`,`effective`,`source`,`applies`,`output`]},run(t,n){if(e.values[`auto-publish`]!==void 0&&e.values[`output-format`]!==void 0)throw new j(`Choose auto-publish or output-format.`);let r=e.values.project?`project`:`global`,i=jD(e.projectDir)[r],a,o=()=>{a=n.effects.begin(`config`,i)};typeof e.values[`output-format`]==`string`&&PD(e.projectDir,!!e.values.project,e.values[`output-format`],o);let s=$M({projectDir:e.projectDir,autoPublish:e.values[`auto-publish`],project:!!e.values.project},o);return a!==void 0&&n.effects.confirm(a),J({scope:r,projectDir:e.projectDir,file:i,...s,output:ND(e.projectDir),effective:s.project??s.global,source:s.project===null?s.global===null?`undecided`:`global`:`project`,applies:`supported_turn_end_hook`})},present:tN},e)};function tN({data:e}){let t=e.effective===null?`undecided`:e.effective?`on`:`off`;return{heading:`Config`,status:``,facts:[X(`Scope`,{key:`scope`,value:e.scope}),X(`File`,{key:`file`,value:e.file}),X(`Auto-publish`,{key:`autoPublish`,value:e.source===`undecided`?t:`${t} (${e.source})`}),X(`Output format`,{key:`output`,value:`${e.output.effective} (${e.output.source})`})],sections:[]}}function nN(e=process.env,t=m.default.homedir()){if(e.RYUGI_DAEMON_SOCKET)return e.RYUGI_DAEMON_SOCKET;let n=d.default.dirname(hk(e)),{home:r}=XD(e,t);if(Fk(r,t))return d.default.join(n,`daemon.sock`);let i=d.default.join(r,`daemon.sock`);if(Buffer.byteLength(i)<=103)return i;let a=f.default.createHash(`sha256`).update(r).digest(`hex`).slice(0,16);return d.default.join(n,`daemon-${a}.sock`)}function rN(e,{timeoutMs:t=5e3}={}){let n=(n,r)=>new Promise((i,a)=>{let o=_.default.connect(e),s=``,c=e=>{o.destroy(),a(e)},l=setTimeout(()=>c(/* @__PURE__ */ Error(`daemon ${n} timed out`)),t);o.on(`error`,e=>{clearTimeout(l),c(e)}),o.on(`connect`,()=>o.write(`${JSON.stringify({op:n,...r})}\n`)),o.on(`data`,e=>{if(s+=e.toString(`utf8`),s.length>4194304)return c(/* @__PURE__ */ Error(`daemon reply too large`));let t=s.indexOf(`
1240
1240
  `);if(!(t<0)){clearTimeout(l),o.end();try{let e=JSON.parse(s.slice(0,t));e.ok?i(e.data??null):a(Error(e.error||`daemon ${n} failed`))}catch{a(/* @__PURE__ */ Error(`daemon reply is not JSON`))}}})});return{call:n,available:()=>n(`status`,{}).then(()=>!0,()=>!1)}}const iN=()=>f.default.randomBytes(24).toString(`base64url`);function aN(e){try{return u.default.readFileSync(e,`utf8`).trim()}catch{return``}}function oN(e){let t=d.default.join(d.default.dirname(e),`host-id`),n=aN(t);if(/^[\w-]{16,64}$/.test(n))return n;let r=iN();return u.default.mkdirSync(d.default.dirname(t),{recursive:!0,mode:448}),u.default.writeFileSync(t,`${r}\n`,{mode:384}),r}async function sN(e,t){let n=XD();if(ZD(n.home),!await PA(n.lock))throw new j(`Another start is still starting the artifacts server; retry in a moment`);try{let r=FA(n);if(!r&&!t.startStopped)return`not-running`;let i=await lA(n,e);r&&(YO(n,{action:`replaced`,pid:r,running:He(n.version)??``,cli:e,reasons:[t.reason]}),await RA(r,`running artifacts server`)),u.default.rmSync(n.info,{force:!0});let a=f.default.randomBytes(24).toString(`hex`);u.default.writeFileSync(n.serverId,`${a}\n`),u.default.writeFileSync(n.version,`${e}\n`);let o=tA(n),s=o?.env.ARTIFACTS_HOST||`127.0.0.1`,c=o?.env.ARTIFACTS_URL_HOST||`localhost`,l=await mA(n,i,{args:o?iA(o,a).args:Qk(a),env:$k(s,c)},`${Qe()} start --host ${s} --url-host ${c} --foreground`);if(`failed`in l)throw new j(String(l.failed.error??`Server failed`));return r?`restarted`:`started`}finally{try{u.default.rmdirSync(n.lock)}catch{}}}const cN=e=>({binary:d.default.join(we(e),`bin`,`adeck-daemon`)});async function lN(e,t){if(!Fk(e.serverHome,e.home))return{status:`other-hub`};let n=Bk(e),r=[n,Rk(n)].find(e=>u.default.existsSync(e));if(!r)return{status:`not-installed`};let i=Vk(r);if(r===n&&Hk(i,e))return{status:`current`};let a=await Uk(e);return t?.(),zk(n,a),{status:`updated`,from:i?.version??`unknown`,to:e.version}}const uN=`session control runs on macOS and Linux`,dN=(e,t)=>e.enabled?`linger on: the hub keeps running after you log out`:`linger off (${e.error}): the hub stops when you log out; to keep it running, an admin can run: sudo loginctl enable-linger ${t}`;function fN(e){if(e.platform!==`darwin`&&e.platform!==`linux`)throw new j(uN);if(!Fk(e.serverHome,e.home))return null;let t=pk(e);if(!t)throw new j(uN);let n=t.check();if(n)throw new j(`${n}; session control needs systemd on Linux`);return t}const pN=(e,t,n)=>({autostart:n,binary:t,launch:e.launch,log:e.log,path:e.path});async function mN(e,t){let n=fN(e),r;t.binary?(r=Bk(e),zk(r,u.default.readFileSync(t.binary))):r=await e.ensureBinary().catch(e=>{throw new j(e.message)}),Yk(e.serverHome,!0);let i=n?.write(pN(e,r,!0))??null;await e.restartHub(!0);let a=n?.linger();return{binary:r,kind:n?.kind??`process`,service:i,...a?{linger:a}:{}}}async function hN(e){let t=fN(e);Yk(e.serverHome,!1);let n=Bk(e),r=null;return t&&u.default.existsSync(t.file(!0))&&(r=t.write(pN(e,n,!1)),t.disable()),await e.restartHub(!1),{service:r}}async function gN(e){let{cloud:t}=e;try{await e.daemon.call(`status`,{})}catch{throw new j(`the daemon is not running; start it with: adeck 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 j(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 _N(e,t,n,r=cN(e).binary){let i=t.filter(e=>e.state===`running`&&e.attach),a=n?i.find(e=>e.taskId===n||e.artifact===n):i.length===1?i[0]:void 0;if(!a)throw i.length===0?new j(`no daemon session is running`):n?new j(`no running daemon session ${n}`):new j(`several daemon sessions are running; name one:\n${i.map(e=>` ${e.taskId} ${e.artifact}`).join(`
1241
- `)}`);return[r,`attach`,a.attach]}const vN=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],yN=()=>ZE(process.env),bN=()=>process.env.RYUGI_ARTIFACTS_VERSION||`1.119.0`;function xN(){let e=XD();return{configHome:process.env.XDG_CONFIG_HOME||void 0,ensureBinary:()=>lA(e,bN()),home:m.default.homedir(),launch:Zk(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,restartHub:e=>sN(bN(),{reason:`session-control`,startStopped:e}),run:aA,serverHome:e.home,uid:process.getuid?.()??0}}function SN(){let e=eD(process.env,process.platform,m.default.homedir()),t=yN(),n=$E(e,t);if(!n)throw new j(`sign in to Artideck Cloud (${t}) on this computer first`);return{origin:t,token:n.token,hostId:oN(e)}}const CN=()=>rN(nN());async function wN(e){try{return await e()}catch(e){let t=e.code;throw t===`ENOENT`||t===`ECONNREFUSED`?new j(`the daemon is not running; install it with: adeck daemon install`):new j(e.message)}}async function TN(){return(await wN(()=>CN().call(`sessions.local`,{}))).sessions}async function EN(e){let[t,n,r]=e.positionals;if(!t||!vN.includes(t))throw new j(`usage: adeck daemon ${vN.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await mN(xN(),{binary:e.values.binary});return i(`installed`,[`session control on`,`binary ${t.binary}`,...t.service?[`${t.kind.padEnd(8)}${t.service}`]:[],...t.linger?[dN(t.linger,m.default.userInfo().username)]:[]])}case`uninstall`:{let e=await hN(xN());return i(`removed`,[`session control off`,...e.service?[`service ${e.service}`]:[]])}case`status`:{let e=await wN(()=>CN().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 j(`usage: adeck daemon trust <code>`);let t=await gN({code:n,cloud:SN(),daemon:CN(),fetch,label:e.values.label});return i(`trusted`,[`${t.deviceId} ${t.label}`])}case`devices`:{if(n===`revoke`){if(!r)throw new j(`usage: adeck daemon devices revoke <device-id>`);let e=SN(),t=await fetch(`${e.origin}/api/devices/${encodeURIComponent(r)}`,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok&&t.status!==404)throw new j(`Cloud refused the revoke: HTTP ${t.status}`);return await wN(()=>CN().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await wN(()=>CN().call(`trust.list`,{}));return i(`listed`,e.devices.length?e.devices.map(e=>`${e.id} ${e.label}`):[`no trusted devices; pair one from Artideck Cloud on the phone`])}case`remote`:if(n!==`on`&&n!==`off`)throw new j(`usage: adeck daemon remote on|off`);return await wN(()=>CN().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await TN();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]=_N(m.default.homedir(),await TN(),n,process.env.RYUGI_DAEMON_BIN||void 0);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
1241
+ `)}`);return[r,`attach`,a.attach]}const vN=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],yN=()=>ZE(process.env),bN=()=>process.env.RYUGI_ARTIFACTS_VERSION||`1.120.1`;function xN(){let e=XD();return{configHome:process.env.XDG_CONFIG_HOME||void 0,ensureBinary:()=>lA(e,bN()),home:m.default.homedir(),launch:Zk(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,restartHub:e=>sN(bN(),{reason:`session-control`,startStopped:e}),run:aA,serverHome:e.home,uid:process.getuid?.()??0}}function SN(){let e=eD(process.env,process.platform,m.default.homedir()),t=yN(),n=$E(e,t);if(!n)throw new j(`sign in to Artideck Cloud (${t}) on this computer first`);return{origin:t,token:n.token,hostId:oN(e)}}const CN=()=>rN(nN());async function wN(e){try{return await e()}catch(e){let t=e.code;throw t===`ENOENT`||t===`ECONNREFUSED`?new j(`the daemon is not running; install it with: adeck daemon install`):new j(e.message)}}async function TN(){return(await wN(()=>CN().call(`sessions.local`,{}))).sessions}async function EN(e){let[t,n,r]=e.positionals;if(!t||!vN.includes(t))throw new j(`usage: adeck daemon ${vN.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await mN(xN(),{binary:e.values.binary});return i(`installed`,[`session control on`,`binary ${t.binary}`,...t.service?[`${t.kind.padEnd(8)}${t.service}`]:[],...t.linger?[dN(t.linger,m.default.userInfo().username)]:[]])}case`uninstall`:{let e=await hN(xN());return i(`removed`,[`session control off`,...e.service?[`service ${e.service}`]:[]])}case`status`:{let e=await wN(()=>CN().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 j(`usage: adeck daemon trust <code>`);let t=await gN({code:n,cloud:SN(),daemon:CN(),fetch,label:e.values.label});return i(`trusted`,[`${t.deviceId} ${t.label}`])}case`devices`:{if(n===`revoke`){if(!r)throw new j(`usage: adeck daemon devices revoke <device-id>`);let e=SN(),t=await fetch(`${e.origin}/api/devices/${encodeURIComponent(r)}`,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok&&t.status!==404)throw new j(`Cloud refused the revoke: HTTP ${t.status}`);return await wN(()=>CN().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await wN(()=>CN().call(`trust.list`,{}));return i(`listed`,e.devices.length?e.devices.map(e=>`${e.id} ${e.label}`):[`no trusted devices; pair one from Artideck Cloud on the phone`])}case`remote`:if(n!==`on`&&n!==`off`)throw new j(`usage: adeck daemon remote on|off`);return await wN(()=>CN().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await TN();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]=_N(m.default.homedir(),await TN(),n,process.env.RYUGI_DAEMON_BIN||void 0);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
1242
1242
  `),i((0,p.spawnSync)(e,t,{stdio:`inherit`}).status===0?`detached`:`failed`,[])}}}function DN({data:e}){return{heading:`Daemon`,status:e.status,summary:``,facts:[],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
1243
1243
  `)}]:[]}}const ON={machine:!0,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 turns on session control: the hub (adeck-daemon, downloaded for this version and checked against its sha256, or --binary for a local build) then runs agent sessions itself, starts at login as a launchd agent on macOS or an enabled systemd user service on Linux, and turns on linger there so it keeps running after you log out. uninstall turns session control off; the hub keeps running without it. trust confirms the code shown on the phone with Artideck 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 adeck-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 EN(e);return J(t,t.status===`failed`?{kind:`failed`,error:{code:`E_DAEMON`,message:`daemon ${t.action} failed`}}:{kind:`succeeded`})},present:DN},e)},kN=`artideck`,AN=`ryugi-artifacts`,jN=[kN,AN],MN=[`npm`,`pnpm`,`yarn`,`bun`],NN=[[`npx`,[`/_npx/`]],[`pnpm dlx`,[`/pnpm/dlx/`,`/.pnpm-store/dlx/`]],[`bunx`,[`/bunx-`,`/.bun/install/cache/`]]],PN=[[`pnpm`,[`/pnpm/global/`]],[`yarn`,[`/yarn/global/`]],[`bun`,[`/.bun/install/global/`]],[`npm`,jN.flatMap(e=>[`/lib/node_modules/${e}/`,`/npm/node_modules/${e}/`])]];function FN(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/node_modules/ryugi-artifacts/`)||t.includes(`/ryugi-artifacts@`)?AN:kN}function IN(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 NN)if(i(t))return{kind:`transient`,runner:e};for(let[e,t]of PN)if(i(t))return{kind:`global`,pm:e};return r.includes(`/node_modules/`)?{kind:`unknown`}:{kind:`local`}}const LN=(e=process.env)=>e.RYUGI_INSTALL_ROOT||d.default.join(e.XDG_DATA_HOME||d.default.join(m.default.homedir(),`.local/share`),`ryugi`,`install`),RN=(e=process.env)=>e.RYUGI_BIN_DIR||d.default.join(m.default.homedir(),`.local/bin`);function zN(e,t){u.default.mkdirSync(d.default.dirname(e),{recursive:!0});let n=`${e}.${(0,f.randomUUID)()}.tmp`;try{u.default.writeFileSync(n,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`}),u.default.renameSync(n,e)}finally{u.default.rmSync(n,{force:!0})}}const BN=[`bin/ryugi.cjs`,`dist/cli.cjs`,`dist/document-engine.cjs`,`dist/loro_wasm_bg.wasm`,`dist/output-bootstrap.cjs`,`dist/viewer/index.html`,`dist/runtime/ryugi-ui.js`,`dist/runtime/ryugi-icons.js`,`dist/runtime/ryugi-mockup.js`],VN=e=>(0,f.createHash)(`sha256`).update(e).digest(`hex`);function HN(e){let t=(0,f.createHash)(`sha256`);function n(r){let i=d.default.join(e,r);if(t.update(r).update(`\0`),u.default.statSync(i).isDirectory())for(let e of u.default.readdirSync(i).sort())n(d.default.join(r,e));else t.update(u.default.readFileSync(i))}for(let e of[`bin`,`dist`,`package.json`])n(e);return t.digest(`hex`)}var UN=class{root;binDir;constructor(e=LN(),t=RN()){this.root=d.default.resolve(e),this.binDir=d.default.resolve(t)}get launcher(){return d.default.join(this.root,`launcher.cjs`)}get bin(){return d.default.join(this.binDir,process.platform===`win32`?`ryugi.cmd`:`ryugi`)}get aliasBin(){return d.default.join(this.binDir,process.platform===`win32`?`adeck.cmd`:`adeck`)}launcherSource(){return`#!/usr/bin/env node
1244
1244
  // Ryugi managed runtime launcher v1
@@ -1336,7 +1336,7 @@ Full workflow: Artifacts plus brainstorming, specs, TDD, debugging, git
1336
1336
  worktrees and verification skills. Injects the Artideck workflow into every
1337
1337
  new session. Rerun install to switch.`,`Content`,{output:n});let t=await XI({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 nI(t)?null:t},async targets(t){let r=gP.filter(t=>!e.detected.includes(t.id));if(r.length&&GI(r.map(e=>`${e.label}: ${e.command} not found`).join(`
1338
1338
  `),`Unavailable`,{output:n}),!e.detected.length)return[];let i=await BI({output:n,message:`Install into which harnesses? (empty = CLI only)`,required:!1,initialValues:t,options:gP.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 nI(i)?null:i},async review(t){GI([`CLI: ${t.root}`,`Command: ${t.binDir}`,`Content: ${t.mode}`,...t.targets.map(n=>`${n}: ${e.previous[n]?.mode||`new`} → ${t.mode}; ${gP.find(e=>e.id===n).comments}`),...t.targets.length?[`Start a new harness session after installation.`]:[`CLI only; no harness plugins.`]].join(`
1339
- `),`Installation plan`,{output:n});let r=await XI({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return nI(r)?`cancel`:r}},t);return r||VI(`Cancelled. No installation changes made.`,{output:n}),r}function eL(){return qI({output:process.stderr,onCancel:()=>{}})}function tL(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 nL(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 rL(e,t){let n=nL(t),r=[],i;try{i=Object.values(AP(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&cP(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&sP(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=tL(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!/(?:\.(?:ryugi|artideck)|\$\(ryugi_user_store\))\/hook/.test(u.default.readFileSync(i,`utf8`))})}catch{a=!1}return{plugins:r,complete:a}}function iL(e,t){return rL(e,t.run).plugins}function aL(e,t,n){let r=rL(e,t);return vF(n,r),r}function oL(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:`The hook binary for ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`adeck`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function sL(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 the hook binary for ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=eL()).start(l)},finish(){i?.stop(`Downloaded the hook binary for ${[...n.keys()].join(`, `)}`)}}}async function cL(e,t,n){let r=sL(t,n);try{return await lL({...e,progress:r.report})}finally{r.finish()}}function lL(e){return uL(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function uL(e){let t=m.default.homedir(),n=XD().home;if(d.default.resolve(n)!==d.default.join(we(t),`server`))return{status:`other-hub`};let r=aL(e.root??LN(),e.run??_P,t);return SF({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.119.0`})}const dL=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(d.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;async function fL(e,t={}){let n=[],r=new UN(e).current();if(r){let i=new UN(e,t.binDir||d.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=WN(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/document-engine.cjs`,`dist/loro_wasm_bg.wasm`,`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(AP(e).harnesses)){await t.onStep?.(`Checking ${r.harness}`);try{if(r.harness===`claude-code`){let e=d.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||d.default.join(t.home||m.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(!lP(r,t.run||_P))throw Error(`Native Claude source no longer matches the record`)}else if(TP(r,wP(r,{root:e,home:t.home})),!lP(r,t.run||_P))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=hF(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||m.default.homedir();await t.onStep?.(`Checking hook binaries`);for(let r of iL(e,{run:t.run||_P})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.artideck/hook; run adeck update to refresh it`});continue}if(!Ak(process.platform,process.arch,r.version))continue;let t=kk(r.version),a=d.default.join(Dk(i,r.version),t);n.push(u.default.existsSync(a)?{component:e,status:`ok`,message:a}:{component:e,status:`attention`,message:`no ${t} ${r.version}, so this plugin's hooks skip; run adeck hook install ${r.version}`})}return await t.onStep?.(`Checking agent-browser`),n.push(mL(t)),n.push(...pL(t.home||m.default.homedir(),t.project)),n}function pL(e,t){let n=(e,t,n)=>u.default.existsSync(d.default.join(e,`.ryugi`))?[{component:t,status:`attention`,message:u.default.existsSync(d.default.join(e,`.artideck`))?`${n}/.ryugi is left in ${e} after the move: it holds files .artideck already has; compare them, then remove .ryugi`:`${n}/.ryugi has not moved to .artideck yet; run adeck migrate`}]:[];return[...n(e,`Home store`,`~`),...t&&d.default.resolve(t)!==d.default.resolve(e)?n(t,`Project store`,t):[]]}function mL(e){let t=`agent-browser`,n=sF({env:e.env||process.env,...e.home?{home:e.home}:{},...e.agentBrowserDirs?{extraDirs:e.agentBrowserDirs}:{}});if(!n)return{component:t,status:`optional`,message:`not found: install it (npm i -g agent-browser, then agent-browser install) so artboard Check loads its boards without a browser window`};let r=lF(n);return{component:t,status:`ok`,message:r?`${n} (${r})`:n}}function hL(e,t={}){let n=AP(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||_P;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(!eP().includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=cP(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(TP(o,wP(o,{root:e,home:t.home})),!lP(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,o.registration||XN.id]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,o.registration||XN.id]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,o.registration||`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,o.registration||`ryugi`]),a===`opencode`){let e=t.env||process.env,n=d.default.join(e.XDG_CONFIG_HOME||d.default.join(t.home||m.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!u.default.existsSync(n)||u.default.readFileSync(n,`utf8`)!==dL(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],jP(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new UN(e).current();if(n){let i=new UN(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}`}),i.ownsAlias()&&u.default.unlinkSync(i.aliasBin)}}return r}function gL(e){let t=new Int32Array(new SharedArrayBuffer(4)),n=new S.Worker(`
1339
+ `),`Installation plan`,{output:n});let r=await XI({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return nI(r)?`cancel`:r}},t);return r||VI(`Cancelled. No installation changes made.`,{output:n}),r}function eL(){return qI({output:process.stderr,onCancel:()=>{}})}function tL(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 nL(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 rL(e,t){let n=nL(t),r=[],i;try{i=Object.values(AP(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&cP(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&sP(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=tL(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!/(?:\.(?:ryugi|artideck)|\$\(ryugi_user_store\))\/hook/.test(u.default.readFileSync(i,`utf8`))})}catch{a=!1}return{plugins:r,complete:a}}function iL(e,t){return rL(e,t.run).plugins}function aL(e,t,n){let r=rL(e,t);return vF(n,r),r}function oL(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:`The hook binary for ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`adeck`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function sL(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 the hook binary for ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=eL()).start(l)},finish(){i?.stop(`Downloaded the hook binary for ${[...n.keys()].join(`, `)}`)}}}async function cL(e,t,n){let r=sL(t,n);try{return await lL({...e,progress:r.report})}finally{r.finish()}}function lL(e){return uL(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function uL(e){let t=m.default.homedir(),n=XD().home;if(d.default.resolve(n)!==d.default.join(we(t),`server`))return{status:`other-hub`};let r=aL(e.root??LN(),e.run??_P,t);return SF({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.120.1`})}const dL=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(d.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;async function fL(e,t={}){let n=[],r=new UN(e).current();if(r){let i=new UN(e,t.binDir||d.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=WN(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/document-engine.cjs`,`dist/loro_wasm_bg.wasm`,`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(AP(e).harnesses)){await t.onStep?.(`Checking ${r.harness}`);try{if(r.harness===`claude-code`){let e=d.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||d.default.join(t.home||m.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(!lP(r,t.run||_P))throw Error(`Native Claude source no longer matches the record`)}else if(TP(r,wP(r,{root:e,home:t.home})),!lP(r,t.run||_P))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=hF(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||m.default.homedir();await t.onStep?.(`Checking hook binaries`);for(let r of iL(e,{run:t.run||_P})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.artideck/hook; run adeck update to refresh it`});continue}if(!Ak(process.platform,process.arch,r.version))continue;let t=kk(r.version),a=d.default.join(Dk(i,r.version),t);n.push(u.default.existsSync(a)?{component:e,status:`ok`,message:a}:{component:e,status:`attention`,message:`no ${t} ${r.version}, so this plugin's hooks skip; run adeck hook install ${r.version}`})}return await t.onStep?.(`Checking agent-browser`),n.push(mL(t)),n.push(...pL(t.home||m.default.homedir(),t.project)),n}function pL(e,t){let n=(e,t,n)=>u.default.existsSync(d.default.join(e,`.ryugi`))?[{component:t,status:`attention`,message:u.default.existsSync(d.default.join(e,`.artideck`))?`${n}/.ryugi is left in ${e} after the move: it holds files .artideck already has; compare them, then remove .ryugi`:`${n}/.ryugi has not moved to .artideck yet; run adeck migrate`}]:[];return[...n(e,`Home store`,`~`),...t&&d.default.resolve(t)!==d.default.resolve(e)?n(t,`Project store`,t):[]]}function mL(e){let t=`agent-browser`,n=sF({env:e.env||process.env,...e.home?{home:e.home}:{},...e.agentBrowserDirs?{extraDirs:e.agentBrowserDirs}:{}});if(!n)return{component:t,status:`optional`,message:`not found: install it (npm i -g agent-browser, then agent-browser install) so artboard Check loads its boards without a browser window`};let r=lF(n);return{component:t,status:`ok`,message:r?`${n} (${r})`:n}}function hL(e,t={}){let n=AP(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||_P;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(!eP().includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=cP(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(TP(o,wP(o,{root:e,home:t.home})),!lP(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,o.registration||XN.id]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,o.registration||XN.id]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,o.registration||`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,o.registration||`ryugi`]),a===`opencode`){let e=t.env||process.env,n=d.default.join(e.XDG_CONFIG_HOME||d.default.join(t.home||m.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!u.default.existsSync(n)||u.default.readFileSync(n,`utf8`)!==dL(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],jP(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new UN(e).current();if(n){let i=new UN(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}`}),i.ownsAlias()&&u.default.unlinkSync(i.aliasBin)}}return r}function gL(e){let t=new Int32Array(new SharedArrayBuffer(4)),n=new S.Worker(`
1340
1340
  const fs = require('node:fs');
1341
1341
  const { parentPort, workerData } = require('node:worker_threads');
1342
1342
  const state = new Int32Array(workerData.state);
@@ -1367,7 +1367,7 @@ if (Atomics.compareExchange(state, 0, 0, 1) === 0) {
1367
1367
  timer = setInterval(tick, 80);
1368
1368
  tick();
1369
1369
  } else parentPort.close();
1370
- `,{eval:!0,workerData:{state:t.buffer,label:e,columns:process.stderr.columns||80}});n.unref();let r=!1;return{message(e){r||n.postMessage(e)},stop(){r||(r=!0,Atomics.compareExchange(t,0,0,3)!==0&&(Atomics.store(t,0,2),Atomics.wait(t,0,2,1e3)),n.terminate())}}}const _L={machine:!0,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){return{run(t,n,r,i){let a=t.format===`brief`&&!!process.stderr.isTTY&&!process.env.CI;return Z({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},async run(t,n){let r=a?gL(`Checking installation`):null,i=`Checking installation`;try{let t=await fL(d.default.resolve(e.values[`install-dir`]||LN()),{project:e.projectDir,async onStep(e){i=e,r?r.message(e):n.progress({phase:e}),await(0,y.setImmediate)(),n.signal.throwIfAborted()},run(e,t,n){return r?.message(`${i} · waiting for ${e} ${t.join(` `)}`),_P(e,t,n)}});return J({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})}finally{r?.stop()}},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).run(t,n,r,i)}}}},vL=/<head(\s[^>]*)?>/i,yL=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,bL=/^<script>([\s\S]*?)<\/script>/,xL=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function SL(e){let t=vL.exec(e);return t?t.index+t[0].length:yL.exec(e)?.[0].length??0}function CL(e){let t=SL(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=bL.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(xL,``)}function wL(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,wL(r,t-1))):i.isFile()&&(n=Math.max(n,u.default.statSync(r).mtimeMs))}return n}const TL=e=>{let t=wL(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function EL(e){let t=/* @__PURE__ */ new Set([...Object.keys(LD),`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&&JE(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}=Je(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:[]}:Ib(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=JE(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?TL(n):{}}}return{artifact:r,...i,...n?TL(n):{}}});c.sort((e,t)=>(t.updatedAt??``).localeCompare(e.updatedAt??``));let l,p;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`),p=f.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&&Jv(m)&&h&&c[0]?.content===`existing`?LE[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 iO()},items:c,..._&&v?.rows?{[_.key]:v.rows}:{},...b===void 0?{}:{content:b,contentFormat:y===void 0?void 0:`markdown`,sha256:p}},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`}]},...fe.flatMap(t=>{let n=LE[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 DL({data:e}){let t=Jv(e.type)?LE[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:Py.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...fM(e.comments.threads,`comments`,!1),title:`Published snapshot comments`,...e.comments.threads.length?{}:{summary:`none`}}]:[]]}}const OL=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,kL=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!d.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function AL(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=>!kL(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:D,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=Wj(i,r.endsWith(`.html`)?CL(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 jL(e){let t=e.positionals[0];if(!t)return EL(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}=FL(t,ZE(process.env)),a=OL(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=OL(e,`block`),c=OL(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||OL(e,`fields`)||OL(e,`cursor`)||OL(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||OL(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=OL(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=OL(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,h){let g=$E(eD(process.env,process.platform,m.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:g?{...D,Authorization:`Bearer ${g.token}`}:D,signal:h.signal}),v=await _.text();h.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.`});h.payloads.source=y.content,a&&(b=Wj(a,y.content,h.effects),h.payloads.source=``,(e.values.source||e.values.format===`source`)&&h.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`};b&&delete T.content;let ee=u&&typeof y.content==`string`;if(ee&&delete T.outline,l){T.dir=d.default.resolve(c??d.default.join(process.env.XDG_CACHE_HOME||d.default.join(m.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await AL(y,T.dir,h)}catch(e){if(!h.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=h.effects.snapshot(),J(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=h.effects.snapshot()}let te=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),ne=[`get`,...te,`--snapshot`,y.snapshot],E=[`get`,...te,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return J(T,void 0,{coverage:{...ee?{}:{page:S},...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[q([...ne,`--detail`,`--`,t],`Details`)]:[],...!ee&&!s&&!o&&!l&&y.page?.nextCursor?[q(E,`More`)]:[]]})},present:DL},e)}const ML=/^[\w-]{1,64}$/,NL=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,PL=`Expected an Artideck Cloud link (https://<host>/a/<id>) or an artifact id.`;function FL(e,t){if(ML.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new j(PL)}let r=NL.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new j(PL);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:XE(n.origin),id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const IL={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:jL,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 LL({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[X(`Version`,Y(e,`version`))],sections:[]}}const RL={machine:!0,name:`hook`,summary:`Download the hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads the hook binary of the plugin release <version> for this platform (adeck-hook; ryugi-hook up to 1.116.0), checks its sha256 and keeps it in ~/.artideck/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 j(`Usage: adeck hook install <version>`);if(!n||!Ck(n))throw new j(`hook install needs a release version, not ${n??`nothing`}`);let r=await Pk({arch:process.arch,fetch,home:m.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??`${kk(n)} ${n} is not available here (${r.status})`}})},present:LL},e)},zL=`icons/index.json`,BL=/* @__PURE__ */ new Map;function VL(e){let t=BL.get(e);if(t===void 0){try{t=JSON.parse(u.default.readFileSync(d.default.join(e,zL),`utf8`))}catch{t=null}BL.set(e,t??null)}return t??null}const HL=e=>e.toLowerCase().match(/[a-z0-9]+/g)??[];function UL(e,t,n,r){if(t===e)return 8;if(t.split(`-`).includes(e))return 5;let i=r.indexOf(e);return i===-1?n.some(t=>t===e||t.split(`-`).includes(e))?3:t.includes(e)?2:+!!r.some(t=>HL(t).some(t=>t.startsWith(e))):i<3?4:i<8?3:2}function WL(e,t,n=10){let r=HL(t),i=t.trim().toLowerCase(),a=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(e.aliases))a.set(n,[...a.get(n)??[],t]);let o=[];for(let[t,n]of Object.entries(e.icons)){let e=a.get(t)??[],s=0,c=0;for(let i of r){let r=UL(i,t,e,n);r>0&&s++,c+=r}(t===i||e.includes(i))&&(s+=r.length),s&&o.push({icon:{name:t,aliases:e,tags:n},matched:s,score:c})}return o.sort((e,t)=>t.matched-e.matched||t.score-e.score||e.icon.name.length-t.icon.name.length||e.icon.name.localeCompare(t.icon.name)).slice(0,n).map(({icon:e})=>e)}function GL({data:e}){return{heading:`Icons`,status:e.icons.length?``:`none`,subject:e.query,summary:e.icons.length?`${e.icons.length} Lucide icons · use the first column as <ryugi-icon name>`:`no Lucide icon fits; try other English words`,facts:[],sections:[{kind:`records`,key:`icons`,rows:e.icons.map(e=>({name:e.name,aliases:e.aliases.join(` `),tags:e.tags.slice(0,8).join(`, `)})),columns:[{key:`name`,positional:!0,required:!0},{key:`tags`,positional:!0},{key:`aliases`,label:`also`}]}]}}const KL={machine:!0,name:`icons`,summary:`Find Lucide icon names for <ryugi-icon> by what the icon should show`,usage:[`<words> [--limit <1-50>] [options]`],details:"Searches the Lucide icons ryugi-icon draws by their names, earlier names and Lucide tags, in English: `adeck icons delete trash`. Icons fitting every word come first. Runs offline, without a server.",options:{limit:{type:`string`,value:`<1-50>`,help:`Maximum icons to list (default 10)`}},positionals:16,semantic:e=>{let t=e.positionals.join(` `).trim();if(!t)throw new j(`Name what the icon should show, in English: adeck icons <words> (e.g. adeck icons delete trash)`);let n=e.values.limit,r=n===void 0?10:Number(n);if(!Number.isInteger(r)||r<1||r>50)throw new j(`--limit must be a whole number from 1 to 50`);return Z({id:`icons`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`name`,`tags`,`aliases`],collection:`icons`,requiredFields:[`name`]},run:()=>{let e=d.default.join(__dirname,`runtime`),n=VL(e);if(!n)throw new j(`This install has no icon index: ${d.default.join(e,zL)}`);return J({query:t,icons:WL(n,t,r)})},present:GL},e)}},qL=qN;function JL(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function YL(e){let{command:t,args:n,shell:r}=JL(e);return(0,p.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function XL(e){let t=YL(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 ZL(){let e=YL([`--version`]);return!e.error&&e.status===0}function QL(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 $L(){let e=JSON.parse(XL([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===GN)}function eR(e){let t=JSON.parse(XL([`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 tR=e=>e===`artifacts`||e===`full`;async function nR(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&&!tR(e))return r(`--mode takes artifacts or full`);if(!ZL())return J({mode:tR(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/artideck/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||d.default.join(m.default.homedir(),`.claude`),a=QL(d.default.join(i,`settings.json`));if(!tR(e))return r(`--mode artifacts|full is required`);let o=e,s=qL[o],c=[qL[o===`artifacts`?`full`:`artifacts`],...Object.values(JN)],l=(e,t,r)=>{let i=n?.begin(e,t);XL(r),i!==void 0&&n.confirm(i)};$L()||l(`install.marketplace`,KN,[`plugin`,`marketplace`,`add`,KN,`--scope`,`user`]),l(`install.refresh`,GN,[`plugin`,`marketplace`,`update`,GN]),eR(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];for(let e of c)a[e]===!0&&(l(`install.disable`,e,[`plugin`,`disable`,e,`--scope`,`user`]),u.push(e));let f=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]]){let r=QL(d.default.join(t,`.claude`,n));for(let t of c)r[t]===!0&&(f.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${t} is still enabled at ${e} scope; enable only one Artideck entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,t,`--scope`,e],label:`Disable at ${e} scope`}))}return J({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:f,actions:p})}async function rR(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`]||LN()),s=new UN(o).current(),c=d.default.resolve(e.values[`bin-dir`]||(s?d.default.dirname(s.bin):RN())),l=AP(o);if(e.values.mode!==void 0&&![`artifacts`,`full`].includes(String(e.values.mode)))return a(`--mode takes artifacts or full`);let p=(e.values.harness===`none`?[]:vP()).filter(e=>e.detected).map(e=>e.id),h={...l.harnesses},g=d.default.join(process.env.CLAUDE_CONFIG_DIR||d.default.join(m.default.homedir(),`.claude`),`settings.json`);if(!h[`claude-code`]&&p.includes(`claude-code`)&&u.default.existsSync(g)){let e=tP(JSON.parse(u.default.readFileSync(g,`utf8`)).enabledPlugins||{});e&&(h[`claude-code`]={harness:`claude-code`,mode:e,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:p,previous:h,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=ZI({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await $I(_,t)}else v=ZI({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?eL():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=IN(__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 UN(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=WN(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&&cP(r,_P)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await nR(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=sP(a.data.installed,_P);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=mP(o,e.values[`plugin-version`]||`1.119.0`),C=!0));let r=d.default.join(o,`candidates`,(0,f.randomUUID)());try{let e=pP(S,r,v.mode);l.harnesses[n]=OP(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})}jP(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. ${gP.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);jP(o,l),t.effects.confirm(T);let ee=oL(await cL({cleanup:!1,root:o},t,n));y.push(...ee.warnings);let te=i.targets.filter(e=>e.status===`failed`),ne=te.length?[{kind:`command`,argv:[`adeck`,`install`,`--mode`,v.mode,`--harness`,te.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 ne.push(...b,...ee.actions),t.signal.aborted?J(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:ne}):J(i,te.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:te.map(e=>`${e.harness}: ${e.error}`).join(`
1370
+ `,{eval:!0,workerData:{state:t.buffer,label:e,columns:process.stderr.columns||80}});n.unref();let r=!1;return{message(e){r||n.postMessage(e)},stop(){r||(r=!0,Atomics.compareExchange(t,0,0,3)!==0&&(Atomics.store(t,0,2),Atomics.wait(t,0,2,1e3)),n.terminate())}}}const _L={machine:!0,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){return{run(t,n,r,i){let a=t.format===`brief`&&!!process.stderr.isTTY&&!process.env.CI;return Z({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},async run(t,n){let r=a?gL(`Checking installation`):null,i=`Checking installation`;try{let t=await fL(d.default.resolve(e.values[`install-dir`]||LN()),{project:e.projectDir,async onStep(e){i=e,r?r.message(e):n.progress({phase:e}),await(0,y.setImmediate)(),n.signal.throwIfAborted()},run(e,t,n){return r?.message(`${i} · waiting for ${e} ${t.join(` `)}`),_P(e,t,n)}});return J({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})}finally{r?.stop()}},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).run(t,n,r,i)}}}},vL=/<head(\s[^>]*)?>/i,yL=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,bL=/^<script>([\s\S]*?)<\/script>/,xL=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function SL(e){let t=vL.exec(e);return t?t.index+t[0].length:yL.exec(e)?.[0].length??0}function CL(e){let t=SL(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=bL.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(xL,``)}function wL(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,wL(r,t-1))):i.isFile()&&(n=Math.max(n,u.default.statSync(r).mtimeMs))}return n}const TL=e=>{let t=wL(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function EL(e){let t=/* @__PURE__ */ new Set([...Object.keys(LD),`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&&JE(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}=Je(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:[]}:Ib(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=JE(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?TL(n):{}}}return{artifact:r,...i,...n?TL(n):{}}});c.sort((e,t)=>(t.updatedAt??``).localeCompare(e.updatedAt??``));let l,p;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`),p=f.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&&Jv(m)&&h&&c[0]?.content===`existing`?LE[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 iO()},items:c,..._&&v?.rows?{[_.key]:v.rows}:{},...b===void 0?{}:{content:b,contentFormat:y===void 0?void 0:`markdown`,sha256:p}},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`}]},...fe.flatMap(t=>{let n=LE[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 DL({data:e}){let t=Jv(e.type)?LE[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:Py.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...fM(e.comments.threads,`comments`,!1),title:`Published snapshot comments`,...e.comments.threads.length?{}:{summary:`none`}}]:[]]}}const OL=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,kL=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!d.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function AL(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=>!kL(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:D,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=Wj(i,r.endsWith(`.html`)?CL(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 jL(e){let t=e.positionals[0];if(!t)return EL(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}=FL(t,ZE(process.env)),a=OL(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=OL(e,`block`),c=OL(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||OL(e,`fields`)||OL(e,`cursor`)||OL(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||OL(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=OL(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=OL(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,h){let g=$E(eD(process.env,process.platform,m.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:g?{...D,Authorization:`Bearer ${g.token}`}:D,signal:h.signal}),v=await _.text();h.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.`});h.payloads.source=y.content,a&&(b=Wj(a,y.content,h.effects),h.payloads.source=``,(e.values.source||e.values.format===`source`)&&h.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`};b&&delete T.content;let ee=u&&typeof y.content==`string`;if(ee&&delete T.outline,l){T.dir=d.default.resolve(c??d.default.join(process.env.XDG_CACHE_HOME||d.default.join(m.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await AL(y,T.dir,h)}catch(e){if(!h.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=h.effects.snapshot(),J(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=h.effects.snapshot()}let te=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),ne=[`get`,...te,`--snapshot`,y.snapshot],E=[`get`,...te,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return J(T,void 0,{coverage:{...ee?{}:{page:S},...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[q([...ne,`--detail`,`--`,t],`Details`)]:[],...!ee&&!s&&!o&&!l&&y.page?.nextCursor?[q(E,`More`)]:[]]})},present:DL},e)}const ML=/^[\w-]{1,64}$/,NL=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,PL=`Expected an Artideck Cloud link (https://<host>/a/<id>) or an artifact id.`;function FL(e,t){if(ML.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new j(PL)}let r=NL.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new j(PL);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:XE(n.origin),id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const IL={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:jL,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 LL({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[X(`Version`,Y(e,`version`))],sections:[]}}const RL={machine:!0,name:`hook`,summary:`Download the hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads the hook binary of the plugin release <version> for this platform (adeck-hook; ryugi-hook up to 1.116.0), checks its sha256 and keeps it in ~/.artideck/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 j(`Usage: adeck hook install <version>`);if(!n||!Ck(n))throw new j(`hook install needs a release version, not ${n??`nothing`}`);let r=await Pk({arch:process.arch,fetch,home:m.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??`${kk(n)} ${n} is not available here (${r.status})`}})},present:LL},e)},zL=`icons/index.json`,BL=/* @__PURE__ */ new Map;function VL(e){let t=BL.get(e);if(t===void 0){try{t=JSON.parse(u.default.readFileSync(d.default.join(e,zL),`utf8`))}catch{t=null}BL.set(e,t??null)}return t??null}const HL=e=>e.toLowerCase().match(/[a-z0-9]+/g)??[];function UL(e,t,n,r){if(t===e)return 8;if(t.split(`-`).includes(e))return 5;let i=r.indexOf(e);return i===-1?n.some(t=>t===e||t.split(`-`).includes(e))?3:t.includes(e)?2:+!!r.some(t=>HL(t).some(t=>t.startsWith(e))):i<3?4:i<8?3:2}function WL(e,t,n=10){let r=HL(t),i=t.trim().toLowerCase(),a=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(e.aliases))a.set(n,[...a.get(n)??[],t]);let o=[];for(let[t,n]of Object.entries(e.icons)){let e=a.get(t)??[],s=0,c=0;for(let i of r){let r=UL(i,t,e,n);r>0&&s++,c+=r}(t===i||e.includes(i))&&(s+=r.length),s&&o.push({icon:{name:t,aliases:e,tags:n},matched:s,score:c})}return o.sort((e,t)=>t.matched-e.matched||t.score-e.score||e.icon.name.length-t.icon.name.length||e.icon.name.localeCompare(t.icon.name)).slice(0,n).map(({icon:e})=>e)}function GL({data:e}){return{heading:`Icons`,status:e.icons.length?``:`none`,subject:e.query,summary:e.icons.length?`${e.icons.length} Lucide icons · use the first column as <ryugi-icon name>`:`no Lucide icon fits; try other English words`,facts:[],sections:[{kind:`records`,key:`icons`,rows:e.icons.map(e=>({name:e.name,aliases:e.aliases.join(` `),tags:e.tags.slice(0,8).join(`, `)})),columns:[{key:`name`,positional:!0,required:!0},{key:`tags`,positional:!0},{key:`aliases`,label:`also`}]}]}}const KL={machine:!0,name:`icons`,summary:`Find Lucide icon names for <ryugi-icon> by what the icon should show`,usage:[`<words> [--limit <1-50>] [options]`],details:"Searches the Lucide icons ryugi-icon draws by their names, earlier names and Lucide tags, in English: `adeck icons delete trash`. Icons fitting every word come first. Runs offline, without a server.",options:{limit:{type:`string`,value:`<1-50>`,help:`Maximum icons to list (default 10)`}},positionals:16,semantic:e=>{let t=e.positionals.join(` `).trim();if(!t)throw new j(`Name what the icon should show, in English: adeck icons <words> (e.g. adeck icons delete trash)`);let n=e.values.limit,r=n===void 0?10:Number(n);if(!Number.isInteger(r)||r<1||r>50)throw new j(`--limit must be a whole number from 1 to 50`);return Z({id:`icons`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`name`,`tags`,`aliases`],collection:`icons`,requiredFields:[`name`]},run:()=>{let e=d.default.join(__dirname,`runtime`),n=VL(e);if(!n)throw new j(`This install has no icon index: ${d.default.join(e,zL)}`);return J({query:t,icons:WL(n,t,r)})},present:GL},e)}},qL=qN;function JL(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function YL(e){let{command:t,args:n,shell:r}=JL(e);return(0,p.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function XL(e){let t=YL(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 ZL(){let e=YL([`--version`]);return!e.error&&e.status===0}function QL(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 $L(){let e=JSON.parse(XL([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===GN)}function eR(e){let t=JSON.parse(XL([`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 tR=e=>e===`artifacts`||e===`full`;async function nR(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&&!tR(e))return r(`--mode takes artifacts or full`);if(!ZL())return J({mode:tR(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/artideck/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||d.default.join(m.default.homedir(),`.claude`),a=QL(d.default.join(i,`settings.json`));if(!tR(e))return r(`--mode artifacts|full is required`);let o=e,s=qL[o],c=[qL[o===`artifacts`?`full`:`artifacts`],...Object.values(JN)],l=(e,t,r)=>{let i=n?.begin(e,t);XL(r),i!==void 0&&n.confirm(i)};$L()||l(`install.marketplace`,KN,[`plugin`,`marketplace`,`add`,KN,`--scope`,`user`]),l(`install.refresh`,GN,[`plugin`,`marketplace`,`update`,GN]),eR(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];for(let e of c)a[e]===!0&&(l(`install.disable`,e,[`plugin`,`disable`,e,`--scope`,`user`]),u.push(e));let f=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]]){let r=QL(d.default.join(t,`.claude`,n));for(let t of c)r[t]===!0&&(f.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${t} is still enabled at ${e} scope; enable only one Artideck entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,t,`--scope`,e],label:`Disable at ${e} scope`}))}return J({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:f,actions:p})}async function rR(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`]||LN()),s=new UN(o).current(),c=d.default.resolve(e.values[`bin-dir`]||(s?d.default.dirname(s.bin):RN())),l=AP(o);if(e.values.mode!==void 0&&![`artifacts`,`full`].includes(String(e.values.mode)))return a(`--mode takes artifacts or full`);let p=(e.values.harness===`none`?[]:vP()).filter(e=>e.detected).map(e=>e.id),h={...l.harnesses},g=d.default.join(process.env.CLAUDE_CONFIG_DIR||d.default.join(m.default.homedir(),`.claude`),`settings.json`);if(!h[`claude-code`]&&p.includes(`claude-code`)&&u.default.existsSync(g)){let e=tP(JSON.parse(u.default.readFileSync(g,`utf8`)).enabledPlugins||{});e&&(h[`claude-code`]={harness:`claude-code`,mode:e,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:p,previous:h,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=ZI({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await $I(_,t)}else v=ZI({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?eL():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=IN(__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 UN(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=WN(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&&cP(r,_P)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await nR(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=sP(a.data.installed,_P);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=mP(o,e.values[`plugin-version`]||`1.120.1`),C=!0));let r=d.default.join(o,`candidates`,(0,f.randomUUID)());try{let e=pP(S,r,v.mode);l.harnesses[n]=OP(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})}jP(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. ${gP.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);jP(o,l),t.effects.confirm(T);let ee=oL(await cL({cleanup:!1,root:o},t,n));y.push(...ee.warnings);let te=i.targets.filter(e=>e.status===`failed`),ne=te.length?[{kind:`command`,argv:[`adeck`,`install`,`--mode`,v.mode,`--harness`,te.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 ne.push(...b,...ee.actions),t.signal.aborted?J(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:ne}):J(i,te.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:te.map(e=>`${e.harness}: ${e.error}`).join(`
1371
1371
  `)}}:{kind:`succeeded`},{warnings:y,actions:ne})}function iR({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 aR={machine:!0,name:`install`,summary:`Install persistent CLI and Artifacts or full Artideck 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 Artideck 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)=>rR(e,r,t.format===`brief`&&!!process.stdin.isTTY&&!!process.stderr.isTTY&&!process.env.CI),present:iR},e).run(t,n,r,i)}}}},oR=(e,t,n)=>[e,t.length?`${t.length} file(s) in both stay in .ryugi`:``,n??``].filter(Boolean).join(` · `);function sR({data:e}){return{heading:`Migrate`,status:e.project.status===`failed`||e.home.status===`failed`?`failed`:`done`,summary:e.commit?`Commit the rename: ${e.commit}`:``,facts:[X(`Project`,Y({value:e.project.dir},`value`)),X(`.ryugi → .artideck`,Y({value:oR(e.project.status,e.project.conflicts,e.project.error)},`value`)),X(`~/.ryugi → ~/.artideck`,Y({value:oR(e.home.status,e.home.conflicts,e.home.error)},`value`))],sections:[],...e.hub===`stopped`?{actions:[],summary:`The hub stopped for the move and did not come back; run adeck start`}:{}}}const cR={name:`migrate`,summary:`Move this project from .ryugi to .artideck and the user home from ~/.ryugi to ~/.artideck`,usage:[`[--project-dir <dir>]`],details:`Opening a project with a newer CLI already moves it; migrate does it on request and reports what moved. Files that exist in both places keep the .artideck copy and stay listed under .ryugi. Running it again is safe.`,options:{},semantic:e=>Z({id:`migrate`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.project.status},async run(t,n){let r=n.effects.begin(`migrate`,`machine`),i=await UA(()=>{}),a=i.serviceStopped?await WA().catch(()=>!1)?`restarted`:`stopped`:`unchanged`,o=Ge(e.projectDir)??Pe(e.projectDir,{home:m.default.homedir()}),s=[i.status,o.status].some(e=>e===`moved`||e===`merged`);return n.effects.set(r,s?`confirmed`:`none`),J({commit:o.tracked&&o.status!==`failed`&&o.status!==`none`?`git add -A .ryugi .artideck .gitignore`:``,home:{conflicts:i.conflicts,error:i.error,status:i.status},hub:a,project:{...o,dir:e.projectDir}},o.status===`failed`||i.status===`failed`?{kind:`failed`,error:{code:`E_MIGRATE_FAILED`,message:o.error??i.error??`failed`}}:{kind:`succeeded`})},present:sR},e)},lR=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function uR(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 lR.exec(e)?.[1]??null}function dR(e){let t=uR(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function fR(e){try{return dR((0,p.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 pR=`# Module vocabulary
1372
1372
 
1373
1373
  Edit \`<project>/.artideck/modules.json\`. A module is a lasting business area, such as billing or sharing, not a file, flag, task or ticket. Your human partner and other agents edit it too; preserve unrelated modules and stable IDs.
@@ -1407,5 +1407,5 @@ Results:
1407
1407
  name_clash the directory holds something else; nothing written. Pull it under another name with --as
1408
1408
  failed a download or write failed; the local copy is as it was
1409
1409
 
1410
- 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 lB(e){for(let t of $D(e))u.default.rmSync(d.default.join(ve(t.dir),`.state`,`server-info`),{force:!0})}function uB({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 dB(){let e=XD(),t=t=>{u.default.rmSync(e.info,{force:!0}),lB(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(He(e.pid)===null)return{status:`not_running`};let n=Number(He(e.pid)),r=He(e.serverId)??``;if(!Number.isInteger(n)||n<=0||!/^[\w-]{32,64}$/.test(r)||!Be(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`),YO(e,{action:`stopped`,pid:n,running:He(e.version)??``,cli:process.env.RYUGI_ARTIFACTS_VERSION||`1.119.0`});try{process.kill(n,`SIGTERM`)}catch{}if(!await Ve(n,7e3)){sA(e)?.unload();try{process.kill(n,`SIGKILL`)}catch{}await Ve(n,1e3)}if(Ie(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 fB={machine:!0,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 dB();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:uB},e)};function pB({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 mB={machine:!0,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(kP):void 0;if(r?.some(e=>!gP.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`]||LN()),a=n.effects.begin(`uninstall`,i),o=hL(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),J(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:pB},e)};function hB(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 gB=e=>d.default.join(e.XDG_CACHE_HOME||d.default.join(m.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function _B(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{}}function vB({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`})]:[],...e.hub&&e.hub.status!==`unchanged`?[X(`Hub`,{key:`hub`,value:e.hub.status===`failed`?`restart failed: ${e.hub.error}`:e.hub.status===`kept-local`?`runs a local build; left as it is`:e.hub.status===`not-running`?`not running`:`restarted on the new version`})]:[]],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`}]}]:[]}}async function yB(e,t){if(e.cli===`current`&&e.daemon===`current`)return{status:`unchanged`};let n=t.running();if(!n)return{status:`not-running`};if(TA(n.version,e.to)===`protected`)return{status:`kept-local`};try{if(e.cli===`updated`&&e.newCli){let n=t.runCli(e.newCli,[`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir]);return n.ok?{status:`restarted`}:{status:`failed`,error:n.output||`start failed`}}return await t.restartHub(e.to),{status:`restarted`}}catch(e){return{status:`failed`,error:e.message}}}const bB={running(){let e=XD(),t=FA(e);return t?{pid:t,version:He(e.version)?.trim()??``}:null},runCli(e,t){let n=(0,p.spawnSync)(e,t,{encoding:`utf8`,shell:process.platform===`win32`,timeout:12e4});return{ok:n.status===0,output:`${n.stderr??``}${n.stdout??``}`.trim()}},async restartHub(e){await sN(e,{reason:`update`,startStopped:!1})}};function xB(e,t,n=kN){let r=`${n}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,r]:e===`yarn`?[`global`,`add`,r]:[`add`,`-g`,r]}}const SB=({cmd:e,args:t})=>[e,...t].join(` `);async function CB(e,t){let n=e.endsWith(`/`)?e:`${e}/`;try{let e=await fetch(new URL(`${t}/latest`,n),{signal:AbortSignal.timeout(1e4)}),{version:r}=await e.json();if(e.ok&&typeof r==`string`&&/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(r))return r;throw Error(`registry returned ${e.status}`)}catch(e){throw new j(`Could not get the latest ${t} version from ${n}: ${e.message}`)}}function wB(e,t){return e.kind===`transient`?`You ran ${kN} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${kN}@latest\` to get ${t}.`:e.kind===`local`?"This is a local build from an Artideck 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 TB=class extends j{};async function EB(e,t){if(!mk[process.platform]?.includes(process.arch))return;let n=m.default.homedir(),r,i=await lN({arch:process.arch,cliDir:__dirname,env:process.env,fetch,home:n,platform:process.platform,serverHome:XD().home,version:e},()=>{r=t.effects.begin(`update.daemon`,cN(n).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 DB(e,t={}){if(e.pm!==void 0&&!MN.includes(e.pm))throw new j(`--pm must be one of ${MN.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:IN(e.file,e.env),r=n.kind===`global`||n.kind===`unknown`?FN(e.file):kN,i=await CB(e.registry,r);t.beforeCache?.(),_B(gB(e.env),i,Date.now()),t.cacheRefreshed?.();let a={type:`update-check`,current:e.current,latest:i,install:n.kind};if(!hB(i,e.current))return{...a,upToDate:!0,command:null};if(n.kind===`unknown`){let t=MN.map(e=>` ${SB(xB(e,i,r))}`).join(`
1411
- `);throw new TB(`Could not tell how ${kN} was installed (${e.file}). Install ${i} with one of:\n${t}\nor run \`${kN} update --pm <${MN.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...a,upToDate:!1,command:`adeck update`};let n=LN(e.env),r=new UN(n).current();if(!r)throw new j(`Managed runtime state is missing; run adeck doctor.`);let o=new UN(n,d.default.dirname(r.bin)),s=d.default.join(n,`downloads`,`runtime-${(0,f.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(i):(u.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${kN}@${i}`),_P(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${kN}@${i}`]),n=d.default.join(s,`node_modules`,kN)),o.install(n),{type:`updated`,from:e.current,to:i,pm:`ryugi`,command:`adeck update`}}finally{u.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...a,upToDate:!1,command:null,message:wB(n,i)};let o=xB(n.pm,i,r);if(e.check)return{...a,upToDate:!1,command:SB(o)};let s=process.platform===`win32`;t.beforeInstall?.();let c=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],l=s?(0,p.spawnSync)(SB(o),{stdio:[...c],env:e.env,shell:!0}):(0,p.spawnSync)(o.cmd,o.args,{stdio:[...c],env:e.env});if(l.stdout?.length&&t.log?.(l.stdout.toString()),l.stderr?.length&&t.log?.(l.stderr.toString()),l.error)throw new j(`Could not run ${SB(o)}: ${l.error.message}`);if(l.status!==0)throw new j(`${SB(o)} exited with ${l.status??l.signal}`);return{type:`updated`,from:e.current,to:i,pm:n.pm,command:SB(o)}}const OB=[KA,JA,fB,KO,rB,cB,yj,Nj,hj,LR,ZM,FM,Lj,IL,KL,eN,{machine:!0,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`,`hub`]},async run(t,n){if(e.values[`cli-only`]&&e.values[`plugins-only`])throw new j(`Choose --cli-only or --plugins-only`);let r=e.values.check?null:RP(m.default.homedir(),process.env.RYUGI_DEV_LINK||void 0);if(r)throw new K({code:`E_DEV_LINKED`,message:`This machine runs the local build ${r.version} through a dev link, and an update would put released copies over it. Refresh the local build with \`pnpm dev:link\` in the ryugi-cloud checkout, or run \`adeck dev unlink\` first to go back to releases.`},`action_required`);let i,a,o;try{o=e.values[`plugins-only`]?{type:`update-check`,current:`1.119.0`,latest:`1.119.0`,install:IN(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await DB({current:`1.119.0`,file:__filename,env:process.env,registry:process.env.npm_config_registry||`https://registry.npmjs.org/`,check:!!e.values.check,pm:e.values.pm},{beforeCache(){a=n.effects.begin(`release-cache`,gB(process.env))},cacheRefreshed(){a!==void 0&&n.effects.confirm(a)},beforeInstall(){i=n.effects.begin(`install`,kN)},log:n.diagnostic})}catch(e){throw e instanceof TB?new K({code:`E_INSTALL_UNKNOWN`,message:e.message},`action_required`):e}o.type===`updated`&&i!==void 0&&n.effects.confirm(i,{from:o.from,to:o.to});let s=o.type===`updated`?{current:o.to,latest:o.to,install:o.pm===`ryugi`?`managed`:`global`,status:`updated`,installed:!0,command:o.command}:{current:o.current,latest:o.latest,install:o.install,status:o.upToDate?`up_to_date`:`available`,installed:!1,command:o.command,...o.message?{message:o.message}:{}},c=d.default.resolve(e.values[`install-dir`]||LN());if(!e.values.check&&!e.values[`cli-only`]){s.plugins=[];for(let t of Object.values(AP(c).harnesses)){let r=await rR({projectDir:e.projectDir,positionals:[],values:{mode:t.mode,harness:t.harness,"no-cli":!0,"install-dir":c,"plugin-source":e.values[`plugin-source`],"plugin-version":s.current}},n,!1,!0),i=r.data.targets.find(e=>e.harness===t.harness);s.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`]&&s.status!==`available`){let t=await EB(s.current,n);t&&(s.daemon=t),s.hub=await yB({cli:s.status===`updated`?`updated`:`current`,daemon:t?.status===`updated`?`updated`:`current`,from:`1.119.0`,to:s.current,newCli:s.install===`managed`?new UN(LN(process.env)).bin:s.install===`global`?`ryugi`:null,projectDir:e.projectDir},bB)}let l=e.values.check?{warnings:[],actions:[]}:oL(await cL({cleanup:!0,root:c},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return J(s,s.plugins?.some(e=>e.status!==`installed`)||s.daemon?.status===`failed`||s.hub?.status===`failed`?{kind:`partial`}:void 0,{effects:n.effects.snapshot(),warnings:l.warnings,actions:[...s.install===`launcher`&&s.status===`available`?[q([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...l.actions]})},present:vB},e)},aR,_L,cR,ON,tF,RL,mB,lz];function kB(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?uO(n):[]}}async function AB(e,t,n,r){return TO({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 jB(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:`artideck ${e.version}`,status:``,facts:[],sections:[]}:{heading:`Help`,status:``,facts:[],sections:[{kind:`content`,key:`text`,text:e.text}]}}}}async function MB(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=zD(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return zD(c,{},0),await Z(jB(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&BD(c)){l||zD(c,{},0);let e=l?WD(l,d):KD(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=zD(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=qE():typeof t.values.artifact==`string`&&(e+=`\n\n${KE(t.values.artifact)}`)}return await Z(jB(`help`,{text:e,commands:t.filter(e=>!e.hidden).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=zD(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.projectDir=Ze(t.projectDir).project,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await xA(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=zD(c,UD(l,d),l.positionals)}catch(e){throw new K({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=l.machine?Je(f.projectDir).project:Ze(f.projectDir,{quiet:l.name===`start`||l.name===`migrate`}).project,await l.semantic(f).run(i,a,o,kB(f))}catch(e){let t=e instanceof j?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`)]}),AB(l?.name??s??`browse`,t,i,a)}}function NB(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 PB(e){process.exitCode=e}const FB={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function IB(e){te(`cli`),oz(e),ie(iP());let t=Object.assign({},LD,...OB.map(e=>e.options)),n=NB(),r;try{r=kD(e,t,FD(e,t))}catch(r){return AB(e[0]??`browse`,r,kD(e,t).options,n)}if(r.error)return AB(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 MB(e,OB,FB,`1.119.0`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}IB(process.argv.slice(2)).then(PB,e=>AB(process.argv[2]??`browse`,e,{format:`brief`},NB()).then(PB));
1410
+ 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 lB(e){for(let t of $D(e))u.default.rmSync(d.default.join(ve(t.dir),`.state`,`server-info`),{force:!0})}function uB({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 dB(){let e=XD(),t=t=>{u.default.rmSync(e.info,{force:!0}),lB(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(He(e.pid)===null)return{status:`not_running`};let n=Number(He(e.pid)),r=He(e.serverId)??``;if(!Number.isInteger(n)||n<=0||!/^[\w-]{32,64}$/.test(r)||!Be(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`),YO(e,{action:`stopped`,pid:n,running:He(e.version)??``,cli:process.env.RYUGI_ARTIFACTS_VERSION||`1.120.1`});try{process.kill(n,`SIGTERM`)}catch{}if(!await Ve(n,7e3)){sA(e)?.unload();try{process.kill(n,`SIGKILL`)}catch{}await Ve(n,1e3)}if(Ie(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 fB={machine:!0,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 dB();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:uB},e)};function pB({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 mB={machine:!0,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(kP):void 0;if(r?.some(e=>!gP.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`]||LN()),a=n.effects.begin(`uninstall`,i),o=hL(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),J(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:pB},e)};function hB(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 gB=e=>d.default.join(e.XDG_CACHE_HOME||d.default.join(m.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function _B(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{}}function vB({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`})]:[],...e.hub&&e.hub.status!==`unchanged`?[X(`Hub`,{key:`hub`,value:e.hub.status===`failed`?`restart failed: ${e.hub.error}`:e.hub.status===`kept-local`?`runs a local build; left as it is`:e.hub.status===`not-running`?`not running`:`restarted on the new version`})]:[]],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`}]}]:[]}}async function yB(e,t){if(e.cli===`current`&&e.daemon===`current`)return{status:`unchanged`};let n=t.running();if(!n)return{status:`not-running`};if(TA(n.version,e.to)===`protected`)return{status:`kept-local`};try{if(e.cli===`updated`&&e.newCli){let n=t.runCli(e.newCli,[`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir]);return n.ok?{status:`restarted`}:{status:`failed`,error:n.output||`start failed`}}return await t.restartHub(e.to),{status:`restarted`}}catch(e){return{status:`failed`,error:e.message}}}const bB={running(){let e=XD(),t=FA(e);return t?{pid:t,version:He(e.version)?.trim()??``}:null},runCli(e,t){let n=(0,p.spawnSync)(e,t,{encoding:`utf8`,shell:process.platform===`win32`,timeout:12e4});return{ok:n.status===0,output:`${n.stderr??``}${n.stdout??``}`.trim()}},async restartHub(e){await sN(e,{reason:`update`,startStopped:!1})}};function xB(e,t,n=kN){let r=`${n}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,r]:e===`yarn`?[`global`,`add`,r]:[`add`,`-g`,r]}}const SB=({cmd:e,args:t})=>[e,...t].join(` `);async function CB(e,t){let n=e.endsWith(`/`)?e:`${e}/`;try{let e=await fetch(new URL(`${t}/latest`,n),{signal:AbortSignal.timeout(1e4)}),{version:r}=await e.json();if(e.ok&&typeof r==`string`&&/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(r))return r;throw Error(`registry returned ${e.status}`)}catch(e){throw new j(`Could not get the latest ${t} version from ${n}: ${e.message}`)}}function wB(e,t){return e.kind===`transient`?`You ran ${kN} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${kN}@latest\` to get ${t}.`:e.kind===`local`?"This is a local build from an Artideck 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 TB=class extends j{};async function EB(e,t){if(!mk[process.platform]?.includes(process.arch))return;let n=m.default.homedir(),r,i=await lN({arch:process.arch,cliDir:__dirname,env:process.env,fetch,home:n,platform:process.platform,serverHome:XD().home,version:e},()=>{r=t.effects.begin(`update.daemon`,cN(n).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 DB(e,t={}){if(e.pm!==void 0&&!MN.includes(e.pm))throw new j(`--pm must be one of ${MN.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:IN(e.file,e.env),r=n.kind===`global`||n.kind===`unknown`?FN(e.file):kN,i=await CB(e.registry,r);t.beforeCache?.(),_B(gB(e.env),i,Date.now()),t.cacheRefreshed?.();let a={type:`update-check`,current:e.current,latest:i,install:n.kind};if(!hB(i,e.current))return{...a,upToDate:!0,command:null};if(n.kind===`unknown`){let t=MN.map(e=>` ${SB(xB(e,i,r))}`).join(`
1411
+ `);throw new TB(`Could not tell how ${kN} was installed (${e.file}). Install ${i} with one of:\n${t}\nor run \`${kN} update --pm <${MN.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...a,upToDate:!1,command:`adeck update`};let n=LN(e.env),r=new UN(n).current();if(!r)throw new j(`Managed runtime state is missing; run adeck doctor.`);let o=new UN(n,d.default.dirname(r.bin)),s=d.default.join(n,`downloads`,`runtime-${(0,f.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(i):(u.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${kN}@${i}`),_P(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${kN}@${i}`]),n=d.default.join(s,`node_modules`,kN)),o.install(n),{type:`updated`,from:e.current,to:i,pm:`ryugi`,command:`adeck update`}}finally{u.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...a,upToDate:!1,command:null,message:wB(n,i)};let o=xB(n.pm,i,r);if(e.check)return{...a,upToDate:!1,command:SB(o)};let s=process.platform===`win32`;t.beforeInstall?.();let c=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],l=s?(0,p.spawnSync)(SB(o),{stdio:[...c],env:e.env,shell:!0}):(0,p.spawnSync)(o.cmd,o.args,{stdio:[...c],env:e.env});if(l.stdout?.length&&t.log?.(l.stdout.toString()),l.stderr?.length&&t.log?.(l.stderr.toString()),l.error)throw new j(`Could not run ${SB(o)}: ${l.error.message}`);if(l.status!==0)throw new j(`${SB(o)} exited with ${l.status??l.signal}`);return{type:`updated`,from:e.current,to:i,pm:n.pm,command:SB(o)}}const OB=[KA,JA,fB,KO,rB,cB,yj,Nj,hj,LR,ZM,FM,Lj,IL,KL,eN,{machine:!0,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`,`hub`]},async run(t,n){if(e.values[`cli-only`]&&e.values[`plugins-only`])throw new j(`Choose --cli-only or --plugins-only`);let r=e.values.check?null:RP(m.default.homedir(),process.env.RYUGI_DEV_LINK||void 0);if(r)throw new K({code:`E_DEV_LINKED`,message:`This machine runs the local build ${r.version} through a dev link, and an update would put released copies over it. Refresh the local build with \`pnpm dev:link\` in the ryugi-cloud checkout, or run \`adeck dev unlink\` first to go back to releases.`},`action_required`);let i,a,o;try{o=e.values[`plugins-only`]?{type:`update-check`,current:`1.120.1`,latest:`1.120.1`,install:IN(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await DB({current:`1.120.1`,file:__filename,env:process.env,registry:process.env.npm_config_registry||`https://registry.npmjs.org/`,check:!!e.values.check,pm:e.values.pm},{beforeCache(){a=n.effects.begin(`release-cache`,gB(process.env))},cacheRefreshed(){a!==void 0&&n.effects.confirm(a)},beforeInstall(){i=n.effects.begin(`install`,kN)},log:n.diagnostic})}catch(e){throw e instanceof TB?new K({code:`E_INSTALL_UNKNOWN`,message:e.message},`action_required`):e}o.type===`updated`&&i!==void 0&&n.effects.confirm(i,{from:o.from,to:o.to});let s=o.type===`updated`?{current:o.to,latest:o.to,install:o.pm===`ryugi`?`managed`:`global`,status:`updated`,installed:!0,command:o.command}:{current:o.current,latest:o.latest,install:o.install,status:o.upToDate?`up_to_date`:`available`,installed:!1,command:o.command,...o.message?{message:o.message}:{}},c=d.default.resolve(e.values[`install-dir`]||LN());if(!e.values.check&&!e.values[`cli-only`]){s.plugins=[];for(let t of Object.values(AP(c).harnesses)){let r=await rR({projectDir:e.projectDir,positionals:[],values:{mode:t.mode,harness:t.harness,"no-cli":!0,"install-dir":c,"plugin-source":e.values[`plugin-source`],"plugin-version":s.current}},n,!1,!0),i=r.data.targets.find(e=>e.harness===t.harness);s.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`]&&s.status!==`available`){let t=await EB(s.current,n);t&&(s.daemon=t),s.hub=await yB({cli:s.status===`updated`?`updated`:`current`,daemon:t?.status===`updated`?`updated`:`current`,from:`1.120.1`,to:s.current,newCli:s.install===`managed`?new UN(LN(process.env)).bin:s.install===`global`?`ryugi`:null,projectDir:e.projectDir},bB)}let l=e.values.check?{warnings:[],actions:[]}:oL(await cL({cleanup:!0,root:c},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return J(s,s.plugins?.some(e=>e.status!==`installed`)||s.daemon?.status===`failed`||s.hub?.status===`failed`?{kind:`partial`}:void 0,{effects:n.effects.snapshot(),warnings:l.warnings,actions:[...s.install===`launcher`&&s.status===`available`?[q([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...l.actions]})},present:vB},e)},aR,_L,cR,ON,tF,RL,mB,lz];function kB(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?uO(n):[]}}async function AB(e,t,n,r){return TO({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 jB(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:`artideck ${e.version}`,status:``,facts:[],sections:[]}:{heading:`Help`,status:``,facts:[],sections:[{kind:`content`,key:`text`,text:e.text}]}}}}async function MB(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=zD(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return zD(c,{},0),await Z(jB(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&BD(c)){l||zD(c,{},0);let e=l?WD(l,d):KD(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=zD(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=qE():typeof t.values.artifact==`string`&&(e+=`\n\n${KE(t.values.artifact)}`)}return await Z(jB(`help`,{text:e,commands:t.filter(e=>!e.hidden).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=zD(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.projectDir=Ze(t.projectDir).project,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await xA(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=zD(c,UD(l,d),l.positionals)}catch(e){throw new K({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=l.machine?Je(f.projectDir).project:Ze(f.projectDir,{quiet:l.name===`start`||l.name===`migrate`}).project,await l.semantic(f).run(i,a,o,kB(f))}catch(e){let t=e instanceof j?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`)]}),AB(l?.name??s??`browse`,t,i,a)}}function NB(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 PB(e){process.exitCode=e}const FB={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function IB(e){te(`cli`),oz(e),ie(iP());let t=Object.assign({},LD,...OB.map(e=>e.options)),n=NB(),r;try{r=kD(e,t,FD(e,t))}catch(r){return AB(e[0]??`browse`,r,kD(e,t).options,n)}if(r.error)return AB(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 MB(e,OB,FB,`1.120.1`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}IB(process.argv.slice(2)).then(PB,e=>AB(process.argv[2]??`browse`,e,{format:`brief`},NB()).then(PB));