ryugi-artifacts 1.113.2 → 1.114.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +65 -65
- package/dist/document-engine.cjs +1 -1
- package/dist/viewer/{AgentDock-DO3wjCT6.js → AgentDock-CDC42MYW.js} +1 -1
- package/dist/viewer/{ArtboardLayout-CWx1_DVU.js → ArtboardLayout-xxRqCrgL.js} +4 -4
- package/dist/viewer/ArtifactList-BmTQrxlv.js +2 -0
- package/dist/viewer/{ArtifactModal-DfZqI4AY.js → ArtifactModal-lbwt_kHc.js} +1 -1
- package/dist/viewer/{BottomSheet-DHasPJPu.js → BottomSheet-B411Uz-m.js} +1 -1
- package/dist/viewer/{RyugiMark-Dyu4ej9h.js → BrandingMark-C4Mwov-Z.js} +1 -1
- package/dist/viewer/{Canvas-C5NJh3wF.js → Canvas-JTxptPpb.js} +1 -1
- package/dist/viewer/{CommentPopover-GqGMqaHP.js → CommentPopover-CyFGfP2x.js} +1 -1
- package/dist/viewer/{DocumentExportMenu-8sZID_nO.js → DocumentExportMenu-D0DMnSWz.js} +1 -1
- package/dist/viewer/DocumentLayout-46dXdTHt.js +2 -0
- package/dist/viewer/{DocumentPage-CcmkTxH-.js → DocumentPage-DvWmw1Vl.js} +3 -3
- package/dist/viewer/{DraggablePanel-BuFi6njZ.js → DraggablePanel-Cm5kvE5J.js} +1 -1
- package/dist/viewer/{DropdownMenu-CM7q1CMp.js → DropdownMenu-CM_lj_mp.js} +1 -1
- package/dist/viewer/{GroupVerdict-DeeQUfkG.js → GroupVerdict-Bq7go5Dw.js} +1 -1
- package/dist/viewer/{HtmlLayout-vlPq4J9Y.js → HtmlLayout-D7QQPpys.js} +1 -1
- package/dist/viewer/{Input-CVcfIqt2.js → Input-ChdGr9Fa.js} +1 -1
- package/dist/viewer/{MenuSubmenuTrigger-BczoxS9k.js → MenuSubmenuTrigger-CTC0R6dC.js} +1 -1
- package/dist/viewer/{PhoneArtboardBar-BK3M_psy.js → PhoneArtboardBar-Cfv4CxlL.js} +1 -1
- package/dist/viewer/{Popover-O6mMCn1S.js → Popover-DW_nm51-.js} +1 -1
- package/dist/viewer/PreviewArtifactLayout-DQaOmm6G.js +1 -0
- package/dist/viewer/{PreviewLayout-C5knCbv-.js → PreviewLayout-BxoUaQZk.js} +2 -2
- package/dist/viewer/{ReportLayout-BD1bNPfi.js → ReportLayout-CrPY-ne6.js} +2 -2
- package/dist/viewer/{Segmented-Clhtb1CD.js → Segmented-CIN3ad9Q.js} +1 -1
- package/dist/viewer/{SelectScrollUpArrow-CTGOrluu.js → SelectScrollUpArrow-CpNOzSFI.js} +1 -1
- package/dist/viewer/{SlidesLayout-8j14xYA-.js → SlidesLayout-C25N3SSh.js} +4 -4
- package/dist/viewer/{SnapshotDocument-CnqXgo4y.js → SnapshotDocument-BHVzE8LV.js} +1 -1
- package/dist/viewer/{SplitFrame-CQ3lXrch.js → SplitFrame-D5Ardg20.js} +1 -1
- package/dist/viewer/StoryboardLayout-DYD80T-k.js +1 -0
- package/dist/viewer/{StoryboardRender--NOzkhyN.js → StoryboardRender-BJrKmvdM.js} +1 -1
- package/dist/viewer/{ThreadView-OBDIwTkP.js → ThreadView-DIXaEds9.js} +1 -1
- package/dist/viewer/{Tooltip-DX1QlxEQ.js → Tooltip-CMAfTGdh.js} +1 -1
- package/dist/viewer/{VerifyLayout-Usn3NkOU.js → VerifyLayout-DJ9FlYRd.js} +1 -1
- package/dist/viewer/{VirtualizedEditor-uWe43zaI-C5Sahl_l.js → VirtualizedEditor-uWe43zaI-TLPHNI-C.js} +1 -1
- package/dist/viewer/{VirtualizedRenderer-C_d95FXi-BpaHPQz0.js → VirtualizedRenderer-C_d95FXi-aRBTgCqJ.js} +1 -1
- package/dist/viewer/{WarningsBadge-DGnz2zmy.js → WarningsBadge-Bh_CkFek.js} +1 -1
- package/dist/viewer/{WhiteboardEditor-DrHOvXez-JWa5PVHK.js → WhiteboardEditor-DrHOvXez-BwHscwim.js} +1 -1
- package/dist/viewer/WhiteboardLayout-D9LlBMNj.js +4 -0
- package/dist/viewer/{WritingCursor-CRzyzaVO.js → WritingCursor-BtUzGhWJ.js} +1 -1
- package/dist/viewer/{agentLook-CU806djA.js → agentLook-Cprxr_R1.js} +1 -1
- package/dist/viewer/{artifact-list-B9KTDzUh.js → artifact-list-DfWvMvBX.js} +1 -1
- package/dist/viewer/{auto-publish-GJrN3H-Y.js → auto-publish-D2Sdw8k6.js} +1 -1
- package/dist/viewer/{channel-CF9EHtSL.js → channel-BiD51VhO.js} +3 -3
- package/dist/viewer/{crop-encode-C1SdKlik.js → crop-encode-8FGWjkRa.js} +1 -1
- package/dist/viewer/{dist-CJucIoCR.js → dist-B8trFwGf.js} +1 -1
- package/dist/viewer/{dist-BaGZx4vf.js → dist-BIxIhkrY.js} +1 -1
- package/dist/viewer/{dist-DTD3yXBi.js → dist-Ba21C_mV.js} +1 -1
- package/dist/viewer/{dist-B_dCTH8c.js → dist-BfrSmPDU.js} +1 -1
- package/dist/viewer/{dist-D4as0PD-.js → dist-Bgg1tHz7.js} +1 -1
- package/dist/viewer/{dist-CiMWQRhQ.js → dist-BqDVBIIH.js} +1 -1
- package/dist/viewer/{dist-DxngwfWH.js → dist-BvrTRRD6.js} +1 -1
- package/dist/viewer/{dist-Dfck1z2n.js → dist-BxF64KGt.js} +1 -1
- package/dist/viewer/{dist-Bgia1wnJ.js → dist-Bzhm1KUn.js} +1 -1
- package/dist/viewer/{dist-Cj74Rdec.js → dist-C0NUbcXW.js} +1 -1
- package/dist/viewer/{dist-Dn_o36dG.js → dist-C6amI52I.js} +1 -1
- package/dist/viewer/{dist-CzD--XrY.js → dist-CPtGSowx.js} +1 -1
- package/dist/viewer/{dist-B0qXxOuX.js → dist-CSuSzSPo.js} +1 -1
- package/dist/viewer/{dist-_D5xLBBO.js → dist-Cl318o9k.js} +1 -1
- package/dist/viewer/dist-DYC6-wbF.js +1 -0
- package/dist/viewer/{dist-Dmr_aVAS.js → dist-DZcYa0Km.js} +1 -1
- package/dist/viewer/{dist-B3-vnt93.js → dist-De7Ddld5.js} +1 -1
- package/dist/viewer/{dist-CsBIrCGx.js → dist-DhCx8KqI.js} +1 -1
- package/dist/viewer/{dist-BHga6o7i.js → dist-Dn1dKREw.js} +1 -1
- package/dist/viewer/{dist-vsF0cCGK.js → dist-DpUkQ0Ox.js} +1 -1
- package/dist/viewer/{dist-C4H1ECie.js → dist-LBfk012X.js} +1 -1
- package/dist/viewer/{dist-BNB-dtd1.js → dist-ObBt5Dp1.js} +1 -1
- package/dist/viewer/{dist-BWDri6GH.js → dist-jQ7-OojG.js} +1 -1
- package/dist/viewer/{dist-BDGp5lli.js → dist-spYdtL1K.js} +1 -1
- package/dist/viewer/{editor-DHJQC-c0.js → editor-DrmCUAHn.js} +4 -4
- package/dist/viewer/{fit-BgVy5mbn.js → fit-C207_s7h.js} +1 -1
- package/dist/viewer/{icons-BwlHhLMH.js → icons-FDIjBpMw.js} +1 -1
- package/dist/viewer/{imperative-D1UIq_CR.js → imperative-vWs1QrC-.js} +1 -1
- package/dist/viewer/index.html +12 -12
- package/dist/viewer/index.js +2 -2
- package/dist/viewer/index5.css +164 -106
- package/dist/viewer/{local-CvTEMav_.js → local-5_OoB550.js} +1 -1
- package/dist/viewer/{local-split-host-DOfRlsgx.js → local-split-host-CigbXofU.js} +1 -1
- package/dist/viewer/plugin-_bGVeqI0-BjaaNEVp.js +2 -0
- package/dist/viewer/preview.html +3 -3
- package/dist/viewer/preview.js +1 -1
- package/dist/viewer/{printDocument-CUNshxwb.js → printDocument-5qz1CDkd.js} +1 -1
- package/dist/viewer/{ref-Bj5JiHki.js → ref-Cb-K9axF.js} +1 -1
- package/dist/viewer/{route-Csi4PU7w.js → route-D8zY0lFu.js} +10 -10
- package/dist/viewer/{route-messages-DeWSMVNI.js → route-messages-Bp-ieAIM.js} +1 -1
- package/dist/viewer/{settings-Ccw15Eyz.js → settings-liAY1Fk5.js} +1 -1
- package/dist/viewer/{snap-B7T8Fi-t.js → snap-DC2WWHJQ.js} +1 -1
- package/dist/viewer/{split-DYwwKqIa.js → split-HmiZnula.js} +2 -2
- package/dist/viewer/{stable-CwENW2fR.js → stable-B9eifbbY.js} +1 -1
- package/dist/viewer/{styles-clvPUBbJ.js → styles-HfB4YGR3.js} +1 -1
- package/dist/viewer/{transport-CSbo3sV6.js → transport-PHP3C7d_.js} +1 -1
- package/dist/viewer/{url-D8qiZRqE.js → url-DnEeE4_q.js} +1 -1
- package/dist/viewer/{useArtifactFeed-1e4jVUAL.js → useArtifactFeed-C_WoMYlQ.js} +1 -1
- package/dist/viewer/{useArtifactSocket-wqYKSfgz.js → useArtifactSocket-BlSfHQ61.js} +1 -1
- package/dist/viewer/{useLayerZIndex-D4jsmz12.js → useLayerZIndex-DmwslOGG.js} +1 -1
- package/dist/viewer/{useStoryboardData-aWqqHGVH.js → useStoryboardData-CLEi4bxr.js} +1 -1
- package/dist/viewer/{view-ClWzCAjM.js → view-DqCvnMlV.js} +1 -1
- package/dist/viewer/{viewport-CFJHn_Y6--n1vZkKz.js → viewport-CFJHn_Y6-CqJugTRB.js} +1 -1
- package/package.json +2 -2
- package/dist/viewer/ArtifactList-DtgRku6l.js +0 -2
- package/dist/viewer/DocumentLayout-CJ59MGXp.js +0 -2
- package/dist/viewer/PreviewArtifactLayout-KGeS-A9y.js +0 -1
- package/dist/viewer/StoryboardLayout-ayS9S6Ff.js +0 -1
- package/dist/viewer/WhiteboardLayout-Dd8Uh61C.js +0 -4
- package/dist/viewer/dist-CyHqzrxc.js +0 -1
- package/dist/viewer/plugin-_bGVeqI0-DZgj9wju.js +0 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r=Object.setPrototypeOf({},null);for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n&1||t(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("node:crypto");u=l(u,1);let d=require("node:fs");d=l(d,1);let f=require("node:path");f=l(f,1);let p=require("node:child_process"),m=require("node:readline");m=l(m,1);let h=require("node:os");h=l(h,1);let g=require("node:util"),_=require("node:net");_=l(_,1);let v=require("node:url"),y=require("node:process");y=l(y,1);let b=require("node:tty");var x=`1.
|
|
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:crypto");u=l(u,1);let d=require("node:fs");d=l(d,1);let f=require("node:path");f=l(f,1);let p=require("node:child_process"),m=require("node:readline");m=l(m,1);let h=require("node:os");h=l(h,1);let g=require("node:util"),_=require("node:net");_=l(_,1);let v=require("node:url"),y=require("node:process");y=l(y,1);let b=require("node:tty");var x=`1.114.0`,S=`1a2779b19258`;const C=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Artideck ${e} (${x}${t?` · ${t}`:``})`},w=process.platform!==`win32`;function T(e,...t){w&&(process.title=[C(e),...t].join(` `))}const E=/^(\s*<doc) ryugi-attribution="([A-Za-z0-9_-]+)"(?=[\s>])/,ee=e=>(0,u.createHash)(`sha256`).update(e).digest(`hex`);function te(e){let t=E.exec(e);if(!t)return{};try{let n=JSON.parse(Buffer.from(t[2],`base64url`).toString()),r=n.digest===ee(e.replace(E,`$1`));return{...typeof n.createdBy==`string`&&{createdBy:n.createdBy},...r&&typeof n.modifiedBy==`string`&&{modifiedBy:n.modifiedBy},...r&&typeof n.model==`string`&&{model:n.model}}}catch{return{}}}function ne(e,t){let n=e.replace(E,`$1`);if(!t.createdBy&&!t.modifiedBy)return n;if(!/^\s*<doc[\s>]/.test(n))throw Error(`Expected a <doc> root.`);let r=Buffer.from(JSON.stringify({...t,digest:ee(n)})).toString(`base64url`);return n.replace(/^(\s*<doc)/,`$1 ryugi-attribution="`+r+`"`)}const re=[`https://ryugi.innei.dev`];function D(e){let t=e.replace(/\/+$/,``);return re.includes(t)?`https://artideck.dev`:t}const ie=e=>D(e.RYUGI_CLOUD_ORIGIN||`https://artideck.dev`);function ae(){return process.platform===`win32`?``:((0,p.spawnSync)(`ps`,[`-o`,`command=`,`-p`,String(process.ppid)],{encoding:`utf8`}).stdout??``).trim()}function O(e,t){try{let n=JSON.stringify({at:(/* @__PURE__ */ new Date()).toISOString(),...t,by:{pid:process.pid,ppid:process.ppid,parent:ae(),cwd:process.cwd(),argv:process.argv.slice(2)}});if(d.default.mkdirSync(e.home,{recursive:!0,mode:448}),d.default.appendFileSync(e.events,`${n}\n`),d.default.statSync(e.events).size>524288){let t=d.default.readFileSync(e.events,`utf8`).trim().split(`
|
|
3
3
|
`).slice(-1e3);d.default.writeFileSync(e.events,`${t.join(`
|
|
4
4
|
`)}\n`)}}catch{}}const k=[`artboard`,`document`,`html`,`whiteboard`,`verify`,`slides`,`report`,`storyboard`],A={artboard:`canvas.json`,document:`doc.xml`,html:`index.html`,whiteboard:`scene.excalidraw`,verify:`verify.xml`,slides:`index.html`,report:`report.tsx`,storyboard:`storyboard.xml`};({...A});const oe=[`html`,`image`,`video`],j=e=>e.type===`image`||e.type===`video`;var M=class extends Error{fields;code;constructor(e,t={},n=1){super(e),this.fields=t,this.code=n}};function se(e){let t=``;try{t=d.default.realpathSync(h.default.homedir())}catch{}let n=[];for(let r=e;n.push(r),!d.default.existsSync(f.default.join(r,`.git`))||r===t&&e!==t;r=f.default.dirname(r))if(f.default.dirname(r)===r)return e;return n.find(e=>d.default.existsSync(f.default.join(e,`.ryugi`,`artifacts`)))??n.at(-1)}function ce(e){let t;try{if(t=d.default.realpathSync(f.default.resolve(e)),!d.default.statSync(t).isDirectory())throw Error(`Not a directory`)}catch{throw new M(`Project directory not found: ${e}`)}t=se(t);let n=f.default.join(t,`.ryugi`,`artifacts`),r=f.default.join(n,`.state`);return{project:t,root:n,state:r,pid:f.default.join(r,`server.pid`),log:f.default.join(r,`server.log`),serverId:f.default.join(r,`server-instance-id`),info:f.default.join(r,`server-info`),version:f.default.join(r,`server-version`),owners:f.default.join(r,`owners`),stopped:f.default.join(r,`server-stopped`),lock:f.default.join(r,`start.lock`)}}const le=()=>process.env.RYUGI_ARTIFACTS_COMMAND||`adeck`,ue=RegExp(`^(${k.join(`|`)})/[a-z0-9][a-z0-9-]*$`),de=`--artifact must be <type>/<id>: type ${k.slice(0,-1).join(`, `)} or ${k.at(-1)}; id of lowercase letters, digits and hyphens`,fe=e=>new Promise(t=>setTimeout(t,e));function pe(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function me(e){try{return d.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(`
|
|
5
5
|
`).slice(1).join(` `).trim();return r?r.split(/\s+/):null}const he=e=>/^"(?:node|ryugi-daemon(?:-[\w-]+)?)\.exe"/i.test(e.trim());function ge(e){let t=(0,p.spawnSync)(`tasklist`,[`/FI`,`PID eq ${e}`,`/FO`,`CSV`,`/NH`],{encoding:`utf8`,windowsHide:!0});return t.status===0?t.stdout:``}function _e(e,t,n={platform:process.platform,tasklist:ge}){return pe(e)?n.platform===`win32`?he(n.tasklist(e)):me(e)?.includes(`--artifacts-server-id=${t}`)??!1:!1}async function N(e,t){for(let n=0;n<t&&pe(e);n+=100)await fe(100);return!pe(e)}const P=e=>{try{return d.default.readFileSync(e,`utf8`).replace(/[\r\n]+$/,``)}catch{return null}},F={claude:`Claude Code`,"claude-code":`Claude Code`,cowork:`Claude Cowork`,codex:`Codex`,cursor:`Cursor`,"cursor-cli":`Cursor`,gemini:`Gemini CLI`,"gemini-cli":`Gemini CLI`,grok:`Grok`,"grok-cli":`Grok`,"github-copilot":`GitHub Copilot`,"github-copilot-cli":`GitHub Copilot`,kilo:`Kilo Code`,omp:`OMP`,"oh-my-pi":`OMP`,pi:`Pi`,dsh:`DeepSeek Harness`,opencode:`OpenCode`,"qwen-code":`Qwen Code`,antigravity:`Antigravity`,augment:`Augment`,"augment-cli":`Augment`,goose:`Goose`,amp:`Amp`,cline:`Cline`,roo:`Roo Code`,devin:`Devin`,replit:`Replit`,v0:`v0`};[...new Set(Object.values(F))];const ve=[[`omp`,e=>!!e.OMPCODE],[`grok`,e=>!!(e.GROK_AGENT||e.GROK_SESSION_ID)],[`cowork`,e=>!!e.CLAUDE_CODE_IS_COWORK],[`kilo`,e=>!!e.KILO],[`codex`,e=>!!(e.CODEX_THREAD_ID||e.CODEX_SANDBOX||e.CODEX_CI)],[`cursor`,e=>!!(e.CURSOR_AGENT||e.CURSOR_TRACE_ID)],[`gemini`,e=>!!e.GEMINI_CLI],[`github-copilot`,e=>!!e.COPILOT_CLI],[`opencode`,e=>e.OPENCODE===`1`||!!e.OPENCODE_CLIENT],[`qwen-code`,e=>!!e.QWEN_CODE],[`antigravity`,e=>!!e.ANTIGRAVITY_AGENT],[`augment`,e=>!!e.AUGMENT_AGENT],[`cline`,e=>!!e.CLINE_ACTIVE],[`roo`,e=>!!e.ROO_ACTIVE],[`claude`,e=>!!(e.CLAUDECODE||e.CLAUDE_CODE)]],ye=[`RYUGI_WRITER_AGENT`,`AI_AGENT`,`AGENT`,`OMPCODE`,`GROK_AGENT`,`GROK_SESSION_ID`,`CLAUDE_CODE_IS_COWORK`,`KILO`,`CODEX_THREAD_ID`,`CODEX_SANDBOX`,`CODEX_CI`,`CURSOR_AGENT`,`CURSOR_TRACE_ID`,`GEMINI_CLI`,`COPILOT_CLI`,`OPENCODE`,`OPENCODE_CLIENT`,`QWEN_CODE`,`ANTIGRAVITY_AGENT`,`AUGMENT_AGENT`,`CLINE_ACTIVE`,`ROO_ACTIVE`,`CLAUDECODE`,`CLAUDE_CODE`],be=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Se(e){let t=I(e),n=t===F.claude?`claude`:t===F.codex?`codex`:t===F.antigravity?`antigravity`:null;if(!n)return null;let r=n===`claude`?e.CLAUDE_CODE_SESSION_ID:n===`codex`?e.CODEX_THREAD_ID||e.CODEX_SESSION_ID:e.ANTIGRAVITY_CONVERSATION_ID;return!r||!xe.test(r)?null:{host:n,id:r}}function Ce(e,t){if(e!==`pi`)return F[e]??e;let n=be(t.AI_AGENT);return n===`dsh`?F.dsh:n===`omp`||n===`oh-my-pi`||t.OMPCODE?F.omp:F.pi}function I(e){if(e.RYUGI_WRITER_AGENT)return e.RYUGI_WRITER_AGENT;if(e.RYUGI_WRITER_HOST)return Ce(e.RYUGI_WRITER_HOST,e);let t=e.RYUGI_ARTIFACTS_COMMAND?.match(/ --ryugi-session ([0-9a-f-]{36}):[0-9a-f-]{36}(?: |$)/i)?.[1];if(t&&t===e.CODEX_THREAD_ID)return F.codex;if(e.CLAUDE_CODE_IS_COWORK)return F.cowork;let n=be(e.AI_AGENT);if(n)return F[n]??n;let r=ve.find(([,t])=>t(e))?.[0];if(r)return F[r];let i=be(e.AGENT);if(i&&!/^(?:1|true|yes)$/.test(i))return F[i]??i}const we=/* @__PURE__ */ RegExp(`^[a-z0-9][a-z0-9-]*$`),Te=/* @__PURE__ */ RegExp(`^(?:[\\w-]{21}|[a-f0-9]{32})$`);function Ee(e){let t=``,n=new Uint8Array(e*2);for(;t.length<e;){crypto.getRandomValues(n);for(let r of n)if(!(r>=248)&&(t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[r%62],t.length===e))break}return t}const De=()=>Ee(21),Oe=e=>we.test(e),ke=e=>Te.test(e),Ae=e=>k.includes(e);function je(e,t,n){if(!Ae(t)||!Oe(n))return null;let r=f.default.join(e,t,n);try{return d.default.statSync(r).isDirectory()?r:null}catch{return null}}function Me(e){let t=f.default.join(e,`.artifact-id`),n;try{n=d.default.readFileSync(t,`utf8`).trim()}catch(r){if(r.code!==`ENOENT`)throw r;n=De();try{d.default.writeFileSync(t,`${n}\n`,{flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;return Me(e)}}if(!ke(n))throw Error(`Invalid artifact ID in ${t}`);return n}function Ne(e){try{return d.default.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function Pe(e){let t=[],n=[];for(let r of Ne(e))if(!r.startsWith(`.`)){if(!Ae(r))n.push(`unknown artifact type directory: ${r}/ (known: ${k.join(`, `)})`);else for(let i of Ne(f.default.join(e,r)))Oe(i)?t.push({type:r,id:i,dir:f.default.join(e,r,i)}):n.push(`invalid artifact id: ${r}/${i} (use lowercase letters, digits and hyphens)`)}return{artifacts:t,warnings:n}}function Fe(e,t=Oe){let[n,r]=e.split(`/`);return!n||!r||!Ae(n)||!t(r)?null:{type:n,id:r}}function Ie(e,t){let n=0,r;try{r=d.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.name===t)continue;let r=f.default.join(e,i.name);try{n=Math.max(n,i.isDirectory()?Ie(r):d.default.statSync(r).mtimeMs)}catch{continue}}return n}function Le(e,t,n){if(!Ae(t)||!Oe(n))throw Error(`Invalid artifact locator`);let r=f.default.join(e,t,n);return d.default.mkdirSync(r,{recursive:!0}),`/${t}/${Me(r)}`}const Re=(0,g.promisify)(p.execFile);function ze(e,t){return e===`darwin`?{bin:`open`,args:[t]}:e===`win32`?{bin:`cmd`,args:[`/c`,`start`,`""`,t]}:e===`linux`||e===`freebsd`||e===`openbsd`?{bin:`xdg-open`,args:[t]}:null}const Be=String.raw`
|
|
@@ -839,33 +839,33 @@ Run Check after edits; skeleton_not_completed/browser_not_run needs the board op
|
|
|
839
839
|
`)}function nw(e){return Object.entries(e).filter(([,e])=>e.help!==void 0).map(([e,t])=>[`${t.short?`-${t.short}, `:``}--${e}${t.value?` ${t.value}`:``}`,t.help])}function rw(e,t){if(!t)return e.options;let n=e.usage?.filter(e=>e.split(/\s/)[0]===t)??[];if(!n.length)throw new M(`Unknown ${e.name} action: ${t}`);let r=/* @__PURE__ */ new Set([...n.flatMap(e=>[...e.matchAll(/--([\w-]+)/g)].map(e=>e[1])),...e.actionOptions?.[t]??[]]);return Object.fromEntries(Object.entries(e.options).filter(([e])=>r.has(e)))}function iw(e,t){let n=rw(e,t);return[(e.usage??[`[options]`]).filter(e=>!t||e.split(/\s/)[0]===t).map((t,n)=>`${n?` `:`Usage: `}${XC} ${e.name} ${t}`).join(`
|
|
840
840
|
`),``,e.summary,...e.details?[``,e.details]:[],``,`Options:`,tw(nw({...n,...ZC,...QC}))].join(`
|
|
841
841
|
`)}function aw(e,t={}){return[`Usage: ${XC} [project-directory] [--no-open]`,` ${XC} <command> [options]`,``,`Without a command, opens the project's artifacts in your browser and keeps the server`,`running until Ctrl+C.`,``,`Commands:`,tw(e.map(e=>[e.name,e.summary])),``,`Tasks:`,` Write or edit: start --background --no-open --artifact <type>/<id>, edit the returned file, then check.`,` Find or read: get --project-dir <path> (local); get <link-or-id> (cloud); scene for a whiteboard.`,` Apply feedback: comment list --artifact <type>/<id> --sections all --detail; changes for document edits.`,` Organize and share: modules, config, publish. Prepare the environment: install, update, start, stop.`,` Automation: start is finite by default; use --foreground for a live process. JSON uses ryugi.cli/v1.`,``,`Run \`${XC} <command> --help\` for a command's options.`,``,`Options:`,tw(nw({...ZC,...t,version:{type:`boolean`,short:`v`,help:`Print the version`},...QC}))].join(`
|
|
842
|
-
`)}const ow=e=>[...e.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(e=>e[1]??e[2]??e[3]);function sw(){let e=process.env.RYUGI_ARTIFACTS_COMMAND?.trim();return e?ow(e):[process.execPath,process.argv[1]]}function cw(e){if(process.env.RYUGI_ARTIFACTS_FORMAT)return process.env.RYUGI_ARTIFACTS_FORMAT;let t=e.indexOf(`--project-dir`);try{return qC(t>=0&&e[t+1]?e[t+1]:process.cwd()).effective}catch{return`brief`}}function lw(e,t=`Details`){let n=e.indexOf(`--`),r=n<0?e:e.slice(0,n),i=n<0?[]:e.slice(n),a={...ZC,...
|
|
842
|
+
`)}const ow=e=>[...e.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(e=>e[1]??e[2]??e[3]);function sw(){let e=process.env.RYUGI_ARTIFACTS_COMMAND?.trim();return e?ow(e):[process.execPath,process.argv[1]]}function cw(e){if(process.env.RYUGI_ARTIFACTS_FORMAT)return process.env.RYUGI_ARTIFACTS_FORMAT;let t=e.indexOf(`--project-dir`);try{return qC(t>=0&&e[t+1]?e[t+1]:process.cwd()).effective}catch{return`brief`}}function lw(e,t=`Details`){let n=e.indexOf(`--`),r=n<0?e:e.slice(0,n),i=n<0?[]:e.slice(n),a={...ZC,...sP.find(t=>t.name===e[0])?.options},o=[],s=!1;for(let e=0;e<r.length;e++){let t=r[e];if([`--format`,`--source`,`--quiet`].includes(t.split(`=`)[0])&&(s=!0),t.startsWith(`--`)&&!t.includes(`=`)&&a[t.slice(2)]?.type===`string`&&r[e+1]!==void 0){let n=r[++e];o.push(n.startsWith(`-`)?`${t}=${n}`:t,...n.startsWith(`-`)?[]:[n])}else o.push(t)}let c=s||cw(r)===`brief`?[]:[`--format`,`brief`];return{kind:`command`,argv:[...sw(),...o,...c,...i],label:t}}function Y(e,t={kind:`succeeded`},n={}){return{data:e,completion:t,coverage:{},effects:[],warnings:[],actions:[],...n}}var uw=class{entries=[];begin(e,t){return this.entries.push({operation:e,target:t,state:`unknown`}),this.entries.length-1}confirm(e,t){this.set(e,`confirmed`,t)}set(e,t,n){let r=this.entries[e];if(!r)throw Error(`Unknown effect`);this.entries[e]={...r,state:t,...n===void 0?{}:{details:n}}}snapshot(){return this.entries.map(e=>({...e}))}};const dw=/^\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)$/,fw=e=>String(e).padStart(2,`0`),pw=e=>typeof e==`string`&&dw.test(e)&&!Number.isNaN(Date.parse(e));function mw(e,t=/* @__PURE__ */ new Date){let n=new Date(e);if(Number.isNaN(n.getTime()))return e;let r=`${fw(n.getHours())}:${fw(n.getMinutes())}`;return n.getFullYear()===t.getFullYear()?n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?r:`${fw(n.getMonth()+1)}-${fw(n.getDate())} ${r}`:`${n.getFullYear()}-${fw(n.getMonth()+1)}-${fw(n.getDate())}`}function hw(e,t){let n=e.details;return!n||typeof n!=`object`||Array.isArray(n)?[]:Object.entries(n).flatMap(([e,n])=>typeof n==`string`&&/^https?:\/\/\S+$/i.test(n)?[{kind:`url`,label:t?`${t} ${e}`:e,url:n}]:[])}const X=(e,t)=>({key:t,value:e[t]}),Z=(e,t,n=!1)=>({label:e,binding:t,required:n}),gw=e=>e.replaceAll(/\p{Cc}/gu,` `);function _w(e,t=!1){if(e==null)return``;if(Array.isArray(e))return e.map(e=>_w(e,!0)).join(`, `);if(typeof e==`object`){let n=Object.entries(e).filter(([,e])=>!yw(e)).map(([e,t])=>`${e} ${_w(t,!0)}`).join(t?`, `:` · `);return t?`(${n})`:n}return pw(e)?mw(e):String(e)}const vw=(e,t,n)=>{if(typeof e==`object`&&e){if(!n)throw Error(`Brief cannot print the object at ${t}; flatten it in the view.`);return _w(e)}return _w(e)},yw=(e,t)=>e==null||e===``||e===!1||t!==void 0&&e===t,bw={1:`FAILED`,2:`NEEDS YOU`,3:`ISSUES`,4:`INCOMPLETE`,5:`PARTIAL`,130:`INTERRUPTED`,143:`INTERRUPTED`},xw={E_ARTIFACT_NOT_FOUND:`check --artifact and --project-dir; artifacts live in <project>/.ryugi/artifacts/<type>/<id>/`,E_ARGUMENT_INVALID:`run the command with --help for its options`,E_CURSOR_EXPIRED:`run the read again without --cursor or --snapshot`,E_CURSOR_MISMATCH:`run the read again without --cursor or --snapshot`},Sw=(e,t)=>t?bw[t]??`FAILED`:gw(e).replaceAll(`_`,` `).toUpperCase(),Cw=e=>{let t=e.replaceAll(/[._]/g,` `).trim();return t?t[0].toUpperCase()+t.slice(1):`Command`};function ww(e){let t=e.offset??0;if(!e.hasMore&&t===0)return null;let n=e.total===null?``:` of ${e.total}`;return e.offset===void 0?`${e.returned}${n} shown${e.total===null&&e.hasMore?` · more available`:``}`:`${e.returned?`${t+1}–${t+e.returned}`:`none`}${n}`}const Tw=e=>/^[\w./:@=+-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`;function Ew(e){return e.kind===`command`?e.argv.map(Tw).join(` `):e.url}const Dw=e=>e.map(e=>`Effect: ${gw(e.operation)} ${gw(e.target)} · ${e.state}`),Ow=e=>e.split(`.`).filter(Boolean).at(-1)??e;function kw(e,t,n,r,i=[],a=0){let o=[Sw(e.status,a),e.subject&&gw(e.subject),e.summary&&gw(e.summary)].filter(Boolean),s=[o.length?`${gw(e.heading)}: ${o.join(` · `)}`:gw(e.heading)],c=[...t.omitted??[]],l=(e,t=!1)=>t||i.includes(e)||!n.fields||n.fields.includes(e),u=(e,t,n=!1)=>gw(vw(e,t,n)),d=(e,t,n,r,i,a,o=!1)=>{if(yw(n,a))return null;let s=gw(e??t);if(n===!0)return s;let c=u(n,r,o);return i?c:`${s} ${c}`},f=(e,t=!1)=>{for(let n of e){if(!r&&!l(n.binding.key,n.required)||yw(n.binding.value))continue;let e=n.binding.value===!0?`yes`:u(n.binding.value,`data.${n.binding.key}`,t);s.push(`${gw(n.label)}: ${e}`)}},p=(e,t)=>e.map(e=>d(e.label,e.binding.key,e.binding.value,`${t}.${e.binding.key}`,e.positional)).filter(e=>e!==null).join(` · `),m=(e,t)=>{e&&s.push(t?`${gw(e)} · ${gw(t)}`:gw(e))},h=e=>{let t=e&&ww(e);t&&s.push(t)};f(e.facts);let g=t.error?hw(t.error):[];if(t.error){s.push(`${gw(t.error.code)}: ${gw(t.error.message)}`),t.error.httpStatus!==void 0&&t.error.httpStatus>=500&&s.push(`HTTP: ${t.error.httpStatus}`);let e=xw[t.error.code];e&&s.push(`Next: ${e}`);let n=t.error.details;if(n&&typeof n==`object`&&!Array.isArray(n))for(let[e,t]of Object.entries(n))g.some(t=>t.label===e)||f([{label:e,binding:{key:e,value:t},required:!0}],!0);else n!==void 0&&f([{label:`Details`,binding:{key:`details`,value:n},required:!0}],!0)}if(!r&&n.fields&&t.data&&typeof t.data==`object`){let r=/* @__PURE__ */ new Set([...e.facts.map(e=>e.binding.key),...e.sections.flatMap(e=>e.kind===`fields`?e.facts.map(e=>e.binding.key):[e.key])]),a=t.data;f([.../* @__PURE__ */ new Set([...n.fields,...i])].filter(e=>!r.has(e)&&Object.hasOwn(a,e)).map(e=>({label:e,binding:{key:e,value:a[e]}})),!0)}for(let t of e.sections){if(t.kind===`fields`){f(t.facts);continue}if(!r&&!l(t.key))continue;let e=`title`in t&&t.title?t.title:void 0;if(t.kind===`records`){m(e??(t.page?t.key:void 0),t.summary);let a=new Set(t.columns.map(e=>e.key)),o=t.key===r?[.../* @__PURE__ */ new Set([...n.fields??[],...n.fields?i:[]])].filter(e=>!a.has(e)).map(e=>({key:e,label:e})):[],c=new Set(o.map(e=>e.key)),f=[...t.columns,...o].filter(e=>t.key!==r||l(e.key,e.required));if(n.format===`table`){let e=f.map(e=>e.label??e.key),n=t.rows.map((e,n)=>f.map(r=>yw(e[r.key],r.default)?``:u(e[r.key],`data.${t.key}.${n}.${r.key}`,c.has(r.key)))),r=e.map((e,t)=>Math.max(e.length,...n.map(e=>e[t]?.length??0)));s.push(...[e,...n].map(e=>e.map((e,t)=>e.padEnd(r[t]??e.length)).join(` `).trimEnd()))}else for(let[e,n]of t.rows.entries())s.push(` ${f.map(r=>d(r.label,r.key,n[r.key],`data.${t.key}.${e}.${r.key}`,r.positional,r.default,c.has(r.key))).filter(e=>e!==null).join(` · `)}`);t.rows.length||e||t.page||s.push(`No records.`),h(t.page)}else if(t.kind===`messages`){m(e,t.summary);for(let[e,n]of t.groups.entries()){s.push(` ${p(n.facts,`data.${t.key}.${e}`)}`);for(let[r,i]of n.messages.entries())s.push(` ${p(i.facts,`data.${t.key}.${e}.messages.${r}`)}`),s.push(...i.text.split(`
|
|
843
843
|
`).map(e=>` ${e.replaceAll(/\p{Cc}/gu,e=>e===` `?e:``)}`))}t.groups.length||e||t.page||s.push(`No messages.`),h(t.page)}else if(t.kind===`diagnostics`){let e=n.detail?t.items.length:t.preview??3;for(let n of t.items.slice(0,e))s.push(` ${n.location?`${gw(n.location)} `:``}${gw(n.code)}: ${u(n.message,`data.${t.key}`)}`);e<t.items.length&&c.push({path:`data.${t.key}`,reason:`preview`,count:t.items.length-e})}else m(e&&`${e}:`,t.summary),s.push(...t.text.trimEnd().split(`
|
|
844
844
|
`).map(e=>` ${e.replaceAll(/\p{Cc}/gu,e=>e===` `||e===`
|
|
845
845
|
`?e:``)}`))}t.page&&h(t.page),(a||(t.effects??[]).some(e=>e.state!==`confirmed`))&&s.push(...Dw(t.effects??[]));for(let e of t.warnings??[])s.push(`Warning: ${gw(e.message)}`);let _=e.actions??t.next??[],v=[..._,...g.filter(e=>!_.some(t=>Ew(t)===Ew(e)))],y=/* @__PURE__ */ new Set,b=v.find(e=>e.label===`Details`);for(let e of c){if(e.count===void 0)continue;let t=`${e.count} more ${Ow(e.path)}`;b&&!y.has(b)?(y.add(b),s.push(`${t} · Details: ${Ew(b)}`)):s.push(t)}for(let e of v)y.has(e)||s.push(`${gw(e.label??`Next`)}: ${e.reason?`${gw(e.reason)} · `:``}${Ew(e)}`);return`${s.join(`
|
|
846
|
-
`)}\n`}function Aw(e,t,n=1){return kw({heading:Cw(e.command),status:``,facts:[],sections:[]},e,{...t,fields:void 0},void 0,[],n)}function Q(e,t){return{run:(n,r,i,a)=>jw(e,t,n,r,i,a)}}async function jw(e,t,n,r,i,a){let o=0,s=Promise.resolve(),c,l=!1,u=[],d=new AbortController,f=()=>d.abort(i?.reason);i?.addEventListener(`abort`,f,{once:!0}),i?.aborted&&f();let p={signal:d.signal,effects:new uw,payloads:{},progress(e){l||h(n.format===`jsonl`?`stdout`:`stderr`,n.format===`jsonl`?m(`progress`,e):`${e.phase}${e.current===void 0?``:` ${e.current}${e.total===void 0?``:`/${e.total}`}`}\n`)},diagnostic(e){h(`stderr`,`${e.trimEnd()}\n`)}};function m(e,t){return`${JSON.stringify({schema:`ryugi.cli/v1`,...t,seq:o++,kind:e})}\n`}function h(e,t){s=s.then(()=>r.write(e,t)).catch(e=>{c=e,d.abort(e)})}async function g(){if(await s,c)throw c}let _=8388608;async function v(e,t){if((typeof t==`string`?new TextEncoder().encode(t).byteLength:t.byteLength)>_)throw new J({code:`E_RESULT_TOO_LARGE`,message:`Result exceeds 8 MiB; read one object or save it to a file.`});await g(),await r.write(e,t)}async function y(t,r=`result`){let i={...t,effects:t.effects.length?t.effects:p.effects.snapshot()};i.effects.some(e=>e.state===`unknown`)&&(i.actions=[...i.actions,...a?.(e.id,void 0,i.effects)??[]]),u=i.effects;let o=BC(e.id,i,n,e.output);if(n.format===`json`)await v(`stdout`,`${JSON.stringify(o)}\n`);else if(n.format===`jsonl`){let t=o,n=e.output.collection;if(n&&r===`result`){let e=o.data,r=e[n];if(Array.isArray(r)){for(let e of r)await v(`stdout`,m(`item`,{collection:n,data:e}));let i={...e};delete i[n],t={...o,data:i}}}await v(`stdout`,m(r,t))}else if(n.format===`raw`||n.format===`source`){let e=p.payloads[n.format];if(e===void 0)throw new J({code:`E_PAYLOAD_UNAVAILABLE`,message:`No ${n.format} payload was returned.`});await v(`stdout`,e)}else if(n.format===`quiet`){if(!e.output.scalar)throw new J({code:`E_FORMAT_UNSUPPORTED`,message:`This command has no scalar output.`});await v(`stdout`,`${e.output.scalar(i.data)}\n`)}else await v(i.completion.kind===`failed`?`stderr`:`stdout`,kw(e.present(i),o,n,e.output.collection,e.output.requiredFields,RC(i.completion).code));return RC(i.completion).code}try{if(!e.output.formats.includes(n.format)||e.mode===`live`&&[`json`,`quiet`,`raw`,`source`,`table`].includes(n.format))throw new J({code:`E_FORMAT_UNSUPPORTED`,message:`${n.format} is not supported for ${e.id}. Supported: ${e.output.formats.join(`, `)}`});if(n.detail&&!e.output.detail)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--detail is not supported for this operation.`});let r=n.fields?.find(t=>!e.output.fields?.includes(t));if(r)throw new J({code:`E_FIELD_UNKNOWN`,message:`Unknown output field: ${r}`});if(n.format===`jsonl`&&await v(`stdout`,m(`meta`,{command:e.id})),e.mode===`finite`){let n=await e.run(t,p);return l=!0,await y(n)}let i=!1,a;for await(let n of e.run(t,p)){if(a||n.kind===`ready`&&i)throw new J({code:`E_LIFECYCLE_INVALID`,message:`Invalid command lifecycle.`});if(n.kind===`ready`){i=!0;try{await y(n.result,`ready`)}catch(e){throw d.abort(e),e}}else a=n.result,l=!0}if(!a)throw new J({code:`E_LIFECYCLE_INCOMPLETE`,message:`Command ended without a terminal result.`});return await y(a)}catch(t){if(l=!0,t instanceof J&&t.raw!==void 0&&(p.payloads.raw=t.raw),t?.code===`EPIPE`)return 141;let i=d.signal.aborted&&(d.signal.reason===`SIGINT`||d.signal.reason===`SIGTERM`)?d.signal.reason:void 0,o=i?{code:`E_INTERRUPTED`,message:`Command interrupted by ${i}.`,details:{signal:i}}:LC(t),s=t instanceof J?t.kind===`action_required`:t?.code===2,c=p.effects.snapshot(),f=Y(null,i?{kind:`interrupted`,signal:i}:s?{kind:`action_required`,reason:o.message}:{kind:`failed`,error:o},{effects:c.length?c:u,actions:[...a?.(e.id,o,c.length?c:u)??[],...t?.actions??[]]}),h={...BC(e.id,f,{...n,fields:void 0},{}),error:o};try{await g(),n.format===`json`||n.format===`jsonl`?await r.write(`stdout`,n.format===`json`?`${JSON.stringify(h)}\n`:m(`result`,h)):n.format===`raw`&&p.payloads.raw!==void 0&&o.code!==`E_RESULT_TOO_LARGE`&&Buffer.byteLength(p.payloads.raw)<=_?await r.write(`stdout`,p.payloads.raw):await r.write(`stderr`,Aw(h,n,RC(f.completion).code)),n.verbose&&t instanceof Error&&t.stack&&await r.write(`stderr`,`${t.stack}\n`)}catch(e){if(e?.code===`EPIPE`)return 141}return RC(f.completion).code}finally{i?.removeEventListener(`abort`,f)}}function Mw(e){let t=e.values;if(t.foreground&&t.background)throw new J({code:`E_OPTION_CONFLICT`,message:`Choose --foreground or --background.`});if(t.open&&t[`no-open`])throw new J({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 Nw(e,t){let n=t?f.default.dirname(f.default.dirname(t.root)):e.projectDir,r=e.artifact?hC(n,e.artifact):void 0;return{cliVersion:`1.113.2`,serverVersion:P(He().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:pC(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 Pw({data:e}){return{heading:`Server`,status:e.status,subject:e.reused?`reused`:void 0,facts:[Z(`Scope`,X(e,`scope`)),Z(`CLI version`,X(e,`cliVersion`)),Z(`Server version`,X(e,`serverVersion`)),Z(`Project`,X(e,`project`),!0),...e.artifact?[Z(`Artifact`,X(e,`artifact`),!0)]:[],...e.write?[Z(e.artifact?.startsWith(`document/`)?`Source`:`Write`,X(e,`write`),!0),Z(`Content`,X(e,`content`),!0)]:[],...e.url?[Z(`Open`,X(e,`url`),!0)]:[],...e.localUrl&&e.localUrl!==e.url?[Z(`Local`,X(e,`localUrl`),!0)]:[],Z(`Cloud`,X(e,`cloud`))],sections:e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[]}}function Fw(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&Ae(n)?iC[n].onStart:void 0;r&&r(f.default.join(f.default.dirname(f.default.dirname(t.root)),`.ryugi`,`artifacts`,e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[],a=Nw(e,t);return a.artifact?.startsWith(`document/`)&&i.push(lw([`write-document`,`--project-dir`,a.project,`--artifact`,a.artifact,`--input`,`<edited.xml>`,...a.content===`existing`?[`--base`,`<original.xml>`]:[]],`Save`)),e.artifact&&i.push(lw([`check`,`--project-dir`,f.default.dirname(f.default.dirname(t.root)),`--artifact`,e.artifact],`Check`)),t.loginHint&&i.push(lw([`publish`,`--login`,`--from`,`hint`,`--project-dir`,e.projectDir],`Sign in`)),Y(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*Iw(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=iT(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:Fw(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:Y({...Nw(e,o),status:`stopped`},{kind:`interrupted`,signal:n},{effects:t.effects.snapshot()})})}else if(n!==0||s)throw new J({code:`E_SERVER_FAILED`,message:s??`Server exited with ${n}.`});else l({kind:`result`,result:Y({...Nw(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 Lw(e,t=`start`){let n=Mw(e);return n.library=t===`browse`,n.foreground?Q({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>Iw(n,t),present:Pw},e):Q({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 iT(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 J({code:`E_SERVER_FAILED`,message:i??`Server did not become ready.`});return Fw(n,r)},present:Pw},e)}const Rw=e=>e.startsWith(`local-`),zw=e=>/^\d+\.\d+\.\d+$/.test(e)?e.split(`.`).map(Number):null;function Bw(e,t){let n=zw(e),r=zw(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 Vw(e,t){return e&&t&&e===t?`keep`:Rw(e)&&t&&!Rw(t)||Bw(t,e)?`protected`:`replace`}const Hw=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},Uw=Hw(`RYUGI_START_SETTLE_MS`,6e3),Ww=Hw(`RYUGI_STOP_GRACE_MS`,7e3),Gw=e=>ie(e),Kw=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},qw=(e,t)=>{let n=Kw(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function Jw(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=Fe(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${Le(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function Yw(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(qw(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 Xw(e){for(let t=0;t<150;t++){try{return d.default.mkdirSync(e),!0}catch{}try{if(Date.now()-d.default.statSync(e).mtimeMs>6e4){d.default.rmdirSync(e);continue}}catch{}await fe(100)}return!1}function Zw(e){let t=Number(P(e.pid)),n=P(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:_e(t,n)?t:null}function Qw(e){try{let t=JSON.parse(P(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function $w(e){try{return(await fetch(qw(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function eT(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await N(e,Ww)){try{process.kill(e,`SIGKILL`)}catch{}if(!await N(e,2e3))throw new M(`The ${t} (pid ${e}) did not stop; stop it with \`${le()} stop\` and retry`)}}async function tT(){let e=qe();for(let t of Ze(e)){if(_e(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await N(t.pid,5e3)}try{Qe(e,t)}catch{}}}function nT(e,t){if(!t||t.startsWith(`document/`))return;let n=Object.fromEntries(ye.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]));if(!Object.keys(n).length)return;let r=f.default.join(e.state,t);d.default.mkdirSync(r,{recursive:!0}),d.default.writeFileSync(f.default.join(r,`agent`),`${JSON.stringify(n)}\n`)}async function rT(e,t,n){let r=await fetch(qw(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 M(`The artifacts server refused this project: ${await r.text()}`)}async function iT(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!ue.test(e.artifact))throw new M(de);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new M(`--port must be a port number`);e.urlHost||=e.host===`127.0.0.1`||e.host===`localhost`?`localhost`:e.host,process.umask(63);let n=ce(e.projectDir),r=He();Ue(r.home),d.default.mkdirSync(n.state,{recursive:!0}),d.default.existsSync(f.default.join(n.state,`.gitignore`))||d.default.writeFileSync(f.default.join(n.state,`.gitignore`),`*
|
|
847
|
-
`);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.
|
|
846
|
+
`)}\n`}function Aw(e,t,n=1){return kw({heading:Cw(e.command),status:``,facts:[],sections:[]},e,{...t,fields:void 0},void 0,[],n)}function Q(e,t){return{run:(n,r,i,a)=>jw(e,t,n,r,i,a)}}async function jw(e,t,n,r,i,a){let o=0,s=Promise.resolve(),c,l=!1,u=[],d=new AbortController,f=()=>d.abort(i?.reason);i?.addEventListener(`abort`,f,{once:!0}),i?.aborted&&f();let p={signal:d.signal,effects:new uw,payloads:{},progress(e){l||h(n.format===`jsonl`?`stdout`:`stderr`,n.format===`jsonl`?m(`progress`,e):`${e.phase}${e.current===void 0?``:` ${e.current}${e.total===void 0?``:`/${e.total}`}`}\n`)},diagnostic(e){h(`stderr`,`${e.trimEnd()}\n`)}};function m(e,t){return`${JSON.stringify({schema:`ryugi.cli/v1`,...t,seq:o++,kind:e})}\n`}function h(e,t){s=s.then(()=>r.write(e,t)).catch(e=>{c=e,d.abort(e)})}async function g(){if(await s,c)throw c}let _=8388608;async function v(e,t){if((typeof t==`string`?new TextEncoder().encode(t).byteLength:t.byteLength)>_)throw new J({code:`E_RESULT_TOO_LARGE`,message:`Result exceeds 8 MiB; read one object or save it to a file.`});await g(),await r.write(e,t)}async function y(t,r=`result`){let i={...t,effects:t.effects.length?t.effects:p.effects.snapshot()};i.effects.some(e=>e.state===`unknown`)&&(i.actions=[...i.actions,...a?.(e.id,void 0,i.effects)??[]]),u=i.effects;let o=BC(e.id,i,n,e.output);if(n.format===`json`)await v(`stdout`,`${JSON.stringify(o)}\n`);else if(n.format===`jsonl`){let t=o,n=e.output.collection;if(n&&r===`result`){let e=o.data,r=e[n];if(Array.isArray(r)){for(let e of r)await v(`stdout`,m(`item`,{collection:n,data:e}));let i={...e};delete i[n],t={...o,data:i}}}await v(`stdout`,m(r,t))}else if(n.format===`raw`||n.format===`source`){let e=p.payloads[n.format];if(e===void 0)throw new J({code:`E_PAYLOAD_UNAVAILABLE`,message:`No ${n.format} payload was returned.`});await v(`stdout`,e)}else if(n.format===`quiet`){if(!e.output.scalar)throw new J({code:`E_FORMAT_UNSUPPORTED`,message:`This command has no scalar output.`});await v(`stdout`,`${e.output.scalar(i.data)}\n`)}else await v(i.completion.kind===`failed`?`stderr`:`stdout`,kw(e.present(i),o,n,e.output.collection,e.output.requiredFields,RC(i.completion).code));return RC(i.completion).code}try{if(!e.output.formats.includes(n.format)||e.mode===`live`&&[`json`,`quiet`,`raw`,`source`,`table`].includes(n.format))throw new J({code:`E_FORMAT_UNSUPPORTED`,message:`${n.format} is not supported for ${e.id}. Supported: ${e.output.formats.join(`, `)}`});if(n.detail&&!e.output.detail)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--detail is not supported for this operation.`});let r=n.fields?.find(t=>!e.output.fields?.includes(t));if(r)throw new J({code:`E_FIELD_UNKNOWN`,message:`Unknown output field: ${r}`});if(n.format===`jsonl`&&await v(`stdout`,m(`meta`,{command:e.id})),e.mode===`finite`){let n=await e.run(t,p);return l=!0,await y(n)}let i=!1,a;for await(let n of e.run(t,p)){if(a||n.kind===`ready`&&i)throw new J({code:`E_LIFECYCLE_INVALID`,message:`Invalid command lifecycle.`});if(n.kind===`ready`){i=!0;try{await y(n.result,`ready`)}catch(e){throw d.abort(e),e}}else a=n.result,l=!0}if(!a)throw new J({code:`E_LIFECYCLE_INCOMPLETE`,message:`Command ended without a terminal result.`});return await y(a)}catch(t){if(l=!0,t instanceof J&&t.raw!==void 0&&(p.payloads.raw=t.raw),t?.code===`EPIPE`)return 141;let i=d.signal.aborted&&(d.signal.reason===`SIGINT`||d.signal.reason===`SIGTERM`)?d.signal.reason:void 0,o=i?{code:`E_INTERRUPTED`,message:`Command interrupted by ${i}.`,details:{signal:i}}:LC(t),s=t instanceof J?t.kind===`action_required`:t?.code===2,c=p.effects.snapshot(),f=Y(null,i?{kind:`interrupted`,signal:i}:s?{kind:`action_required`,reason:o.message}:{kind:`failed`,error:o},{effects:c.length?c:u,actions:[...a?.(e.id,o,c.length?c:u)??[],...t?.actions??[]]}),h={...BC(e.id,f,{...n,fields:void 0},{}),error:o};try{await g(),n.format===`json`||n.format===`jsonl`?await r.write(`stdout`,n.format===`json`?`${JSON.stringify(h)}\n`:m(`result`,h)):n.format===`raw`&&p.payloads.raw!==void 0&&o.code!==`E_RESULT_TOO_LARGE`&&Buffer.byteLength(p.payloads.raw)<=_?await r.write(`stdout`,p.payloads.raw):await r.write(`stderr`,Aw(h,n,RC(f.completion).code)),n.verbose&&t instanceof Error&&t.stack&&await r.write(`stderr`,`${t.stack}\n`)}catch(e){if(e?.code===`EPIPE`)return 141}return RC(f.completion).code}finally{i?.removeEventListener(`abort`,f)}}function Mw(e){let t=e.values;if(t.foreground&&t.background)throw new J({code:`E_OPTION_CONFLICT`,message:`Choose --foreground or --background.`});if(t.open&&t[`no-open`])throw new J({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 Nw(e,t){let n=t?f.default.dirname(f.default.dirname(t.root)):e.projectDir,r=e.artifact?hC(n,e.artifact):void 0;return{cliVersion:`1.114.0`,serverVersion:P(He().version),status:t?`running`:`stopped`,scope:`machine`,project:n,...r,...r?.content===`missing`?{writing:pC(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 Pw({data:e}){return{heading:`Server`,status:e.status,subject:e.reused?`reused`:void 0,facts:[Z(`Scope`,X(e,`scope`)),Z(`CLI version`,X(e,`cliVersion`)),Z(`Server version`,X(e,`serverVersion`)),Z(`Project`,X(e,`project`),!0),...e.artifact?[Z(`Artifact`,X(e,`artifact`),!0)]:[],...e.write?[Z(e.artifact?.startsWith(`document/`)?`Source`:`Write`,X(e,`write`),!0),Z(`Content`,X(e,`content`),!0)]:[],...e.url?[Z(`Open`,X(e,`url`),!0)]:[],...e.localUrl&&e.localUrl!==e.url?[Z(`Local`,X(e,`localUrl`),!0)]:[],Z(`Cloud`,X(e,`cloud`))],sections:e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[]}}function Fw(e,t){let n=e.artifact?.includes(`/`)?e.artifact.split(`/`)[0]:void 0,r=n&&Ae(n)?iC[n].onStart:void 0;r&&r(f.default.join(f.default.dirname(f.default.dirname(t.root)),`.ryugi`,`artifacts`,e.artifact));let i=t.cloudLimit?.upgradeUrl?[{kind:`url`,url:t.cloudLimit.upgradeUrl,label:`Upgrade`}]:[],a=Nw(e,t);return a.artifact?.startsWith(`document/`)&&i.push(lw([`write-document`,`--project-dir`,a.project,`--artifact`,a.artifact,`--input`,`<edited.xml>`,...a.content===`existing`?[`--base`,`<original.xml>`]:[]],`Save`)),e.artifact&&i.push(lw([`check`,`--project-dir`,f.default.dirname(f.default.dirname(t.root)),`--artifact`,e.artifact],`Check`)),t.loginHint&&i.push(lw([`publish`,`--login`,`--from`,`hint`,`--project-dir`,e.projectDir],`Sign in`)),Y(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*Iw(e,t){let n=[],r,i=!1,a,o,s,c=t.effects.begin(`start`,e.projectDir),l=e=>{n.push(e),r?.()},u=iT(e,{signal:t.signal,ready(n){o=n,t.effects.confirm(c,{reused:!!n.reused}),l({kind:`ready`,result:Fw(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:Y({...Nw(e,o),status:`stopped`},{kind:`interrupted`,signal:n},{effects:t.effects.snapshot()})})}else if(n!==0||s)throw new J({code:`E_SERVER_FAILED`,message:s??`Server exited with ${n}.`});else l({kind:`result`,result:Y({...Nw(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 Lw(e,t=`start`){let n=Mw(e);return n.library=t===`browse`,n.foreground?Q({id:t,mode:`live`,output:{formats:[`brief`,`jsonl`]},run:(e,t)=>Iw(n,t),present:Pw},e):Q({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 iT(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 J({code:`E_SERVER_FAILED`,message:i??`Server did not become ready.`});return Fw(n,r)},present:Pw},e)}const Rw=e=>e.startsWith(`local-`),zw=e=>/^\d+\.\d+\.\d+$/.test(e)?e.split(`.`).map(Number):null;function Bw(e,t){let n=zw(e),r=zw(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 Vw(e,t){return e&&t&&e===t?`keep`:Rw(e)&&t&&!Rw(t)||Bw(t,e)?`protected`:`replace`}const Hw=(e,t)=>{let n=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(n)&&n>=0?n:t},Uw=Hw(`RYUGI_START_SETTLE_MS`,6e3),Ww=Hw(`RYUGI_STOP_GRACE_MS`,7e3),Gw=e=>ie(e),Kw=e=>{let t=new URL(e);return t.hostname===`localhost`&&(t.hostname=`127.0.0.1`),t},qw=(e,t)=>{let n=Kw(e.url),r=new URL(t,n.origin),i=n.searchParams.get(`key`);return i&&r.searchParams.set(`key`,i),r.toString()};function Jw(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=Fe(n),o=i.searchParams.get(`key`);r.link=`${i.origin}${Le(t.root,a.type,a.id)}${o?`?key=${o}`:``}`}return r}async function Yw(e,t,n,r){if(!r)return e;try{let{url:i,limit:a}=await(await fetch(qw(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 Xw(e){for(let t=0;t<150;t++){try{return d.default.mkdirSync(e),!0}catch{}try{if(Date.now()-d.default.statSync(e).mtimeMs>6e4){d.default.rmdirSync(e);continue}}catch{}await fe(100)}return!1}function Zw(e){let t=Number(P(e.pid)),n=P(e.serverId);return!Number.isInteger(t)||t<=0||!n?null:_e(t,n)?t:null}function Qw(e){try{let t=JSON.parse(P(e.info)??``);return typeof t.url==`string`&&Number.isInteger(t.port)?t:null}catch{return null}}async function $w(e){try{return(await fetch(qw(e,`/api/status`),{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async function eT(e,t){try{process.kill(e,`SIGTERM`)}catch{}if(!await N(e,Ww)){try{process.kill(e,`SIGKILL`)}catch{}if(!await N(e,2e3))throw new M(`The ${t} (pid ${e}) did not stop; stop it with \`${le()} stop\` and retry`)}}async function tT(){let e=qe();for(let t of Ze(e)){if(_e(t.pid,t.serverId)){try{process.kill(t.pid,`SIGTERM`)}catch{}await N(t.pid,5e3)}try{Qe(e,t)}catch{}}}function nT(e,t){if(!t||t.startsWith(`document/`))return;let n=Object.fromEntries(ye.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]));if(!Object.keys(n).length)return;let r=f.default.join(e.state,t);d.default.mkdirSync(r,{recursive:!0}),d.default.writeFileSync(f.default.join(r,`agent`),`${JSON.stringify(n)}\n`)}async function rT(e,t,n){let r=await fetch(qw(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 M(`The artifacts server refused this project: ${await r.text()}`)}async function iT(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!ue.test(e.artifact))throw new M(de);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new M(`--port must be a port number`);e.urlHost||=e.host===`127.0.0.1`||e.host===`localhost`?`localhost`:e.host,process.umask(63);let n=ce(e.projectDir),r=He();Ue(r.home),d.default.mkdirSync(n.state,{recursive:!0}),d.default.existsSync(f.default.join(n.state,`.gitignore`))||d.default.writeFileSync(f.default.join(n.state,`.gitignore`),`*
|
|
847
|
+
`);let i=process.env.RYUGI_ARTIFACTS_VERSION||`1.114.0`,a=Ge(r.projects).some(e=>e.dir===n.project),o=async(r,i)=>{nT(n,e.artifact);let o=e.open&&!e.library&&(!i||!a);await rT(r,n,o?e.artifact??!0:void 0);let s=Jw(r,n,e.artifact);i&&(s.reused=!0);let c=await Yw(s,r,n,e.artifact),l=Xn(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 Ve(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 Ve(typeof c.cloudLink==`string`?c.cloudLink:e,[e]).catch(e=>t.log(e.message,`stderr`))}};if(!await Xw(r.lock))throw new M(`Another start is still starting the artifacts server; retry in a moment`);let s=!0,c=()=>{if(s){s=!1;try{d.default.rmdirSync(r.lock)}catch{}}};try{t.signal?.throwIfAborted();let a=Zw(r),s=Qw(r),l=null;if(a&&!s){for(let e=0;e<Uw&&pe(a)&&!s;e+=100)await fe(100),s=Qw(r);!s&&pe(a)&&(l={label:`stopping artifacts server`,pid:a,reasons:[`no-info`],running:P(r.version)??``})}if(a&&s){let t=P(r.version)??``,n=Vw(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`)===Gw(process.env)?[]:[`cloudOrigin`],...e.port!==void 0&&String(s.port)!==e.port?[`port`]:[],...Pn(r,An(e.host,e.urlHost))?[`launch`]:[]],d={pid:a,running:t,cli:i},f=n===`protected`||u.length===0;if(f&&await $w(s))return u.length&&O(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 f=await Bn(r,i);l&&(O(r,{action:`replaced`,cli:i,pid:l.pid,reasons:l.reasons,running:l.running}),await eT(l.pid,l.label)),await tT(),d.default.rmSync(r.info,{force:!0});let h=u.default.randomBytes(24).toString(`hex`);d.default.writeFileSync(r.serverId,`${h}\n`),d.default.writeFileSync(r.version,`${i}\n`);let g={args:kn(h,e.port),env:An(e.host,e.urlHost)};if(e.foreground){jn(r,g);let e=(0,p.spawn)(f,g.args,{env:g.env,stdio:[`ignore`,`pipe`,`pipe`]});d.default.writeFileSync(r.pid,`${e.pid}\n`);let n=()=>{e.kill(`SIGTERM`)};if(t.signal)t.signal.addEventListener(`abort`,n,{once:!0});else for(let e of[`SIGINT`,`SIGTERM`])process.on(e,n);m.default.createInterface({input:e.stderr}).on(`line`,e=>t.log(e,`stderr`));let i=new Promise(t=>e.on(`close`,e=>t(e??1))),a=!1,s;m.default.createInterface({input:e.stdout}).on(`line`,e=>{let r;try{r=JSON.parse(e)}catch{t.log(e,`stdout`);return}r.type!==`server-started`||a?t.event?t.event(r):r.type===`server-error`||r.type===`error`?t.failure(r):t.log(JSON.stringify(r),`stderr`):(a=!0,c(),s=o(r,!1),s.catch(()=>n()))});try{let e=await i;return await s,e}finally{if(t.signal)t.signal.removeEventListener(`abort`,n);else for(let e of[`SIGINT`,`SIGTERM`])process.removeListener(e,n)}}let _=await Gn(r,f,g,`${le()} 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 aT={semantic:Lw,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`}}},oT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sT(e,t){let n;try{n=d.default.openSync(e,`r`);let r=d.default.fstatSync(n).size,i=Math.min(r,t),a=Buffer.alloc(i);return d.default.readSync(n,a,0,i,r-i),a.toString(`utf8`).split(`
|
|
848
848
|
`).reverse()}catch{return[]}finally{n!==void 0&&d.default.closeSync(n)}}function cT(e,t){if(e)return lT(sT(e,2097152),t)??lT(sT(e,67108864),t)}function lT(e,t){for(let n of e)if(n.startsWith(`{`))try{let e=t(JSON.parse(n));if(typeof e==`string`&&e&&!e.startsWith(`<`))return e}catch{}}function uT(e,t,n){let r=f.default.join(t.CLAUDE_CONFIG_DIR||f.default.join(n,`.claude`),`projects`);try{for(let t of d.default.readdirSync(r)){let n=f.default.join(r,t,e+`.jsonl`);if(d.default.existsSync(n))return n}}catch{return}}function dT(e,t,n){let r=f.default.join(t.CODEX_HOME||f.default.join(n,`.codex`),`sessions`),i=e=>{try{return d.default.readdirSync(e).sort().reverse()}catch{return[]}};for(let t of i(r))for(let n of i(f.default.join(r,t)))for(let a of i(f.default.join(r,t,n))){let o=f.default.join(r,t,n,a),s=i(o).find(t=>t.endsWith(`-`+e+`.jsonl`));if(s)return f.default.join(o,s)}}function fT(e,t,n=h.default.homedir()){if(e===`Claude Code`||e===`Claude Cowork`){let e=t.CLAUDE_CODE_SESSION_ID;return!e||!oT.test(e)?void 0:cT(uT(e,t,n),e=>e.type===`assistant`?e.message?.model:void 0)}if(e===`Codex`){let e=t.CODEX_THREAD_ID;return!e||!oT.test(e)?void 0:cT(dT(e,t,n),e=>e.type===`turn_context`?e.payload?.model:void 0)}}async function pT(e,t,n,r,i){d.default.mkdirSync(f.default.dirname(e),{recursive:!0});let a=f.default.join(f.default.dirname(e),`.`+f.default.basename(e)),o=a+`.`+(0,u.randomUUID)()+`.tmp`,s=a+`.write-lock`;if(!await Xw(s))throw new M(`Another document save is in progress. Retry after it finishes.`);try{let a=null;try{a=d.default.readFileSync(e,`utf8`)}catch(e){if(e.code!==`ENOENT`)throw e}if(a!==t)throw new M(`Document changed. Re-read it and reapply the edit.`);if(n===a)return;let s=a===null?r:te(a).createdBy;d.default.writeFileSync(o,ne(n,{createdBy:s,modifiedBy:r,...i&&{model:i}}),{mode:a===null?384:d.default.statSync(e).mode&511}),d.default.renameSync(o,e)}finally{d.default.rmSync(o,{force:!0}),d.default.rmdirSync(s)}}const mT={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=>Q({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/`)||!ue.test(t)||typeof r!=`string`)throw new M(`Supply --artifact document/<id> and --input <file>.`);let i=I(process.env);if(!i)throw new M(`No agent identity in the writing process environment.`);return await pT(f.default.join(ce(e.projectDir).root,t,`doc.xml`),typeof n==`string`?d.default.readFileSync(n,`utf8`):null,d.default.readFileSync(r,`utf8`),i,fT(i,process.env)),Y({artifact:t,author:i})},present:({data:e})=>({heading:`Document`,status:`SAVED`,subject:e.artifact,summary:e.author,facts:[],sections:[]})},e)},hT=[`desktop`,`laptop`,`tablet`,`mobile`],gT=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),_T=4096;function vT(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(!gT.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 yT(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=vT(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function bT(e){if(typeof e==`string`)return hT.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<=_T&&n>=240&&n<=_T)return{w:t,h:n}}return null}function xT(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function ST(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=vT(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=xT(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=bT(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${hT.join(`, `)} or { w, h } (240..${_T})`)}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 CT=e=>`No artifacts server is running for this project. Start it with \`${le()} start --project-dir ${e}\`, then run this again.`,wT=e=>{try{let{url:t}=JSON.parse(P(e)??``);return typeof t==`string`?t:null}catch{return null}};function TT(e,t){let n=He(),r=wT(n.info);return r?Ge(n.projects).some(t=>t.dir===e)?r:null:wT(t)}function ET(e){let t=ce(e),n=TT(t.project,t.info);if(!n)throw new J({code:`E_SERVER_NOT_RUNNING`,message:CT(t.project)});let r=new URL(n),i=r.searchParams.get(`key`)??``;return r.hostname===`localhost`&&(r.hostname=`127.0.0.1`),{project:t.project,async call(e,n,a,o){let s;try{let c=new URL(`${r.origin}${n}`);c.searchParams.set(`key`,i);let l=Kn(process.env);s=await fetch(c,{method:e,signal:o,headers:{"X-Ryugi-Client":`cli`,"X-Ryugi-Project":encodeURIComponent(t.project),...l?{"x-ryugi-cloud-token":l}:{},...a?{"Content-Type":`application/json`}:{}},body:a?JSON.stringify(a):void 0})}catch{throw new J({code:`E_SERVER_UNREACHABLE`,message:CT(t.project)})}let c=new Uint8Array(await s.arrayBuffer()),l;try{l=JSON.parse(new TextDecoder().decode(c))}catch{}if(!l||typeof l!=`object`||Array.isArray(l))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid JSON response; the operation result is unknown.`,httpStatus:s.status},`failed`,c);return{status:s.status,json:l,raw:c}}}}async function DT(){let e=He(),t=wT(e.info),n={scope:`machine`,version:P(e.version)};if(!t)return{...n,status:`not_running`};try{let e=new URL(`/api/status`,t);e.search=new URL(t).search;let r=await fetch(e,{signal:AbortSignal.timeout(1e3)}),i=await r.json();return{...n,status:r.ok&&typeof i.pid==`number`?`running`:`unreachable`,pid:typeof i.pid==`number`?i.pid:void 0}}catch{return{...n,status:`unreachable`}}}const OT=`preview.json`,kT=/^[a-z0-9][a-z0-9-]{0,63}$/;function AT(e){return f.default.join(f.default.dirname(e),`preview`)}function jT(e,t){return kT.test(t)?f.default.join(AT(e),t):null}function MT(e){let t=AT(e),n;try{n=d.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!kT.test(e))continue;let n=f.default.join(t,e);d.default.existsSync(f.default.join(n,OT))&&r.push({id:e,payload:NT(n,e)})}return r}function NT(e,t,n){let r=f.default.join(e,OT),i,a=1;try{let e=d.default.statSync(r);a=Math.trunc(e.mtimeMs)||1,i=d.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}=ST(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function PT(e,t){d.default.mkdirSync(e,{recursive:!0}),Sn(f.default.join(e,OT),t)}function FT(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 IT(e,t=800){let n=vT(e);if(!n)return!1;if(n.hostname!==`localhost`)return FT(n.hostname,n.port,t);let r=await Promise.all([FT(`127.0.0.1`,n.port,t),FT(`::1`,n.port,t)]);return r[0]||r[1]}function LT(e){let t=typeof e==`string`&&e.trim()?e.trim():`dev`;if(!kT.test(t))throw new M(`Preview --id must use lowercase letters, digits, and hyphens.`);return t}function RT(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 zT({data:e}){return{heading:`Preview ${e.action}`,status:e.action===`open`?`ready`:`ok`,subject:e.id?`preview/${e.id}`:void 0,facts:[...e.url?[Z(`Target`,{key:`url`,value:e.url})]:[],...e.upstreamAlive===void 0?[]:[Z(`Upstream`,{key:`upstreamAlive`,value:e.upstreamAlive?`online`:`offline`})],...e.open?[Z(`Open`,{key:`open`,value:e.open},!0)]:[],...e.receipt?[Z(`Receipt`,{key:`receipt`,value:e.receipt})]:[]],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
|
|
849
849
|
`)}]:[]}}const BT={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=>Q({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=ce(e.projectDir);if(r===`list`){let e=MT(i.root);return Y({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=LT(e.values.id),r=e.values.url;if(!r)throw new M(`Pass --url http://localhost:<port>`);let a=yT(r);if(!a)throw new M(`--url must be a local loopback http URL (e.g. http://localhost:5182)`);let o=jT(i.root,t),s=null;try{s=ST(d.default.readFileSync(f.default.join(o,`preview.json`),`utf8`)).config}catch{}PT(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 iT({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 M(String(e.error??`Failed to start Hub`))},log(e){n.diagnostic(e)}})!==0||!c)throw new M(`Hub did not start.`);let l=`${new URL(c).origin}/preview/${encodeURIComponent(t)}?project=${encodeURIComponent(i.project)}`,u=await IT(a.url);return Y({action:`open`,id:t,url:a.url,upstreamAlive:u,open:l,lines:u?[]:[`Upstream ${a.url} is not listening yet; start your dev server and reload.`]})}let a=LT(e.values.id),o=ET(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 M(t.json?.error||`HTTP ${t.status}`);let r=Array.isArray(t.json?.items)?t.json.items:[];return Y({action:`comments`,id:a,lines:r.length?r.flatMap(RT):[`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 M(`Pass --thread <id> for preview ${r}`);let i=e.values.text;if(r===`reply`&&!i?.trim())throw new M(`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 M(c.json?.error||`HTTP ${c.status}`);return Y({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 M(`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 M(r.json?.error||`HTTP ${r.status}`);return Y({action:`ack`,id:a,receipt:t,lines:[`Acknowledged receipt ${t}`]})}throw new M(`Unknown preview action "${r}". Use open, list, comments, reply, resolve, or ack.`)},present:zT},e)},VT=/^report\/[a-z0-9][a-z0-9-]*$/,HT=e=>typeof e==`object`&&!!e&&Array.isArray(e.sources),UT=({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`}`),WT={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=>Q({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 M(`usage: ryugi report refresh --artifact report/<id>`);let r=e.values.artifact;if(!r||!VT.test(r))throw new M(`--artifact must be report/<id>`);let i=e.values.only,a=await ET(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 M(a.json?.error||`HTTP ${a.status}`);if(!HT(a.json))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid refresh report.`});let o={...a.json,artifact:r,lines:UT(a.json)},s=o.sources.filter(e=>!e.ok);return Y(o,s.length?s.length===o.sources.length?{kind:`failed`,error:{code:`E_REPORT_SOURCE_FAILED`,message:UT({sources:s}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:GT},e)};function GT({data:e}){return{heading:`Refresh`,status:e.sources.every(e=>e.ok)?``:`failed`,subject:e.artifact??``,facts:[Z(`Sources`,{key:`sources`,value:String(e.sources.length)})],sections:[{kind:`content`,key:`lines`,text:(e.lines??UT(e)).join(`
|
|
850
850
|
`)},...e.issues?.length?[{kind:`content`,key:`issues`,text:e.issues.join(`
|
|
851
851
|
`)}]:[]]}}const KT=/^storyboard\/[a-z0-9][a-z0-9-]*$/,qT=e=>typeof e==`object`&&!!e&&Array.isArray(e.lines),JT=e=>typeof e==`object`&&!!e&&typeof e.n==`number`&&Array.isArray(e.shots),YT=({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`}`),XT=e=>{let t=Math.round(e);return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},ZT=e=>[`cut ${e.n}: ${e.file} · ${e.shots.length} shot${e.shots.length===1?``:`s`}, ${XT(e.shots.at(-1)?.end??0)} · timing from the ${e.mapped===`map`?`map`:`storyboard's durations`}`],QT=(e,t)=>f.default.resolve(e,t),$T=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 eE(e,t,n){let r=f.default.join(e,`.ryugi`,`artifacts`,...t.split(`/`));if(!d.default.existsSync(r))throw new M(`${t} not found in ${e}`);return YS(r,n)?[`wrote ${JS}`]:[`${JS} is already there; pass --force to replace it with the latest template`]}const tE=e=>typeof e==`object`&&!!e&&typeof e.state==`string`,nE=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(r),n()})});function rE(e,t){if(t!==void 0)try{return JSON.parse(d.default.readFileSync(QT(e,t),`utf8`))}catch(e){throw new M(`--map ${t} is not readable JSON: ${e.message}`)}}const iE={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=>Q({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 M(`usage: ryugi storyboard voice|cut|export|template --artifact storyboard/<id>`);let i=e.values.artifact;if(!i||!KT.test(i))throw new M(`--artifact must be storyboard/<id>`);if(r===`template`)return Y({action:r,artifact:i,lines:[],summary:eE(e.projectDir,i,!!e.values.force)},{kind:`succeeded`});let a=ET(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||!tE(t.json))throw new M(t.json?.error||`HTTP ${t.status}`);let o=t.json,s=[];for(;e.values.wait&&o.state===`running`&&!n.signal?.aborted;){let e=$T(o)[0];s.at(-1)!==e&&s.push(e),await nE(1e3,n.signal);let t=await a.call(`GET`,`/api/${i}/export`,void 0,n.signal);tE(t.json)&&(o=t.json)}return Y({action:r,artifact:i,export:o,lines:[],summary:[...s,...$T(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 M(`storyboard cut needs --file <1080p.mp4>`);let o=rE(e.projectDir,e.values.map),s=e.values.master,c=await a.call(`POST`,`/api/${i}/cut`,{file:QT(e.projectDir,t),...o===void 0?{}:{map:o},...s?{master:QT(e.projectDir,s)}:{}},n.signal);if(n.payloads.raw=c.raw,c.status<200||c.status>=300)throw new M(c.json?.error||`HTTP ${c.status}`);if(!JT(c.json))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid cut.`});let l=c.json;return Y({action:r,artifact:i,cut:l,lines:[],summary:ZT(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,!qT(s.json))throw s.status<200||s.status>=300?new M(s.json?.error||`HTTP ${s.status}`):new J({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:YT(s.json)};if(c.error)return Y(c,{kind:`failed`,error:{code:`E_STORYBOARD_VOICE`,message:c.error}});let l=c.lines.filter(e=>!e.ok);return Y(c,l.length?l.length===c.lines.length?{kind:`failed`,error:{code:`E_STORYBOARD_VOICE`,message:YT({lines:l}).join(`; `)}}:{kind:`partial`}:{kind:`succeeded`})},present:aE},e)};function aE({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?[Z(`Version`,{key:`cut`,value:String(e.cut?.n??``)})]:e.action===`export`?[Z(`Version`,{key:`export`,value:String(e.export?.n??``)})]:e.action===`voice`?[Z(`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(`
|
|
852
852
|
`)}]}}const oE=/^whiteboard\/[a-z0-9][a-z0-9-]*$/,sE=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)},cE={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=>Q({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||!oE.test(r))throw new M(`--artifact must be whiteboard/<id>`);let i=e.values.frame,a=e.values.page,o=await ET(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 M(o.json?.error||`HTTP ${o.status}`);if(!sE(o.json))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an invalid scene report.`});let s=o.json;return Y(s,{kind:`succeeded`},{actions:(s.pages??[]).map(t=>lw([`scene`,`--artifact`,r,`--page`,t.id,`--project-dir`,e.projectDir],`Read ${t.id}`))})},present:lE},e)};function lE({data:e}){return{heading:`Scene`,status:e.problem?`invalid`:``,subject:e.artifact,facts:[...e.page?[Z(`Page`,X(e,`page`))]:[],Z(`Version`,X(e,`sceneVersion`)),Z(`Render`,X(e,`render`)),...e.renderPath?[Z(`Image`,X(e,`renderPath`))]:[],...e.problem?[Z(`Problem`,X(e,`problem`))]:[],Z(`Conflicts`,{key:`conflicts`,value:e.conflicts.join(`, `)})],sections:[{kind:`content`,key:`lines`,text:e.lines.join(`
|
|
853
|
-
`)}]}}const uE={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`]},dE={threads:[`id`,`status`,`waitingOn`],asks:[`id`,`state`],groups:[`id`,`kind`,`verdict`,`choice`],rounds:[`id`,`state`]},fE=e=>e.startsWith(`document/`)?[`threads`,`asks`]:[`threads`,`groups`,`rounds`];function pE(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=>!fE(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 mE(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 uE))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=>!uE[t].includes(e))?`Unknown field for this section.`:null}function hE(e,t,n){let r=f.default.resolve(e),i=n?.begin(`save`,r),a;try{a=d.default.openSync(r,`wx`,384)}catch(e){throw i!==void 0&&n.set(i,`failed`),new J({code:e.code===`EEXIST`?`E_FILE_EXISTS`:`E_FILE_WRITE_FAILED`,message:`Could not create ${r}: ${e.message}`})}try{d.default.writeFileSync(a,t)}catch(e){throw d.default.closeSync(a),d.default.unlinkSync(r),i!==void 0&&n.set(i,`failed`),new J({code:`E_FILE_WRITE_FAILED`,message:`Could not save ${r}: ${e.message}`})}return d.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 gE(e,t,n,r,i){let a=e.projectDir,o=[`--artifact`,t,`--project-dir`,a];if(n.evidence===`preview`&&n.items.length&&n.snapshot){let t=i.findIndex(e=>e.label===`Read`),a=[`status`,`waiting-on`,`kind`,`choice-state`].flatMap(t=>typeof e.values[t]==`string`?[`--${t}`,String(e.values[t])]:[]),s={...lw([`comment`,`list`,...o,`--section`,`threads`,`--detail`,`--snapshot`,n.snapshot,`--limit`,String(r?.returned??n.items.length),...typeof e.values.cursor==`string`?[`--cursor`,e.values.cursor]:[],...a,...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)}if(n.evidence!==`complete`)return;let s=n.items.filter(e=>e.status===`open`);if(s.length){let{write:e}=hC(a,t);i.push({...lw([`check`,...o],`Check`),reason:`After editing ${e} in place. Re-read before editing; preserve human changes and existing IDs. comments.json is server-owned.`});for(let e of s)i.push({...lw([`comment`,`reply`,...o,`--thread`,String(e.id),`--text`,`<what changed or your answer>`],`Reply (${e.id})`),reason:`Replace the message argument after applying this request.`}),e.anchor?.verdict!==`reject`&&i.push({...lw([`comment`,`resolve`,...o,`--thread`,String(e.id)],`Resolve (${e.id})`),reason:`Only once this thread is settled.`})}let c=i.findIndex(e=>e.label===`Acknowledge`);if(c>=0){let[e]=i.splice(c,1);i.push({...e,reason:`After using every delivered message. This resolves nothing and leaves later replies unread.`})}}const $=e=>typeof e==`string`?e:``,_E=e=>e.replaceAll(/\s*\n\s*/g,` / `).trim(),vE=(e,t)=>`${e} ${t}${e===1?``:`s`}`,yE=e=>e[0].toUpperCase()+e.slice(1),bE=(e,t=[])=>Object.entries(e??{}).filter(([e,n])=>e!==`waitingOnAgent`&&!t.includes(e)&&typeof n==`number`&&n>0).map(([e,t])=>`${t} ${e}`).join(`, `),xE=e=>e?` (${e})`:``,SE={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 CE(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}${xE(bE(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=SE[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?vE(c,`other`):``:bE(a,o.listed);return{head:s,full:`${s}${xE(l)}`,count:i}}function wE(e){if(!e||typeof e!=`object`)return``;let t=e;if(t.kind===`node`)return` node ${$(t.id)}`;if(t.kind!==`edge`)return``;let n=typeof t.index==`number`&&t.index>0?` #${t.index+1}`:``;return` edge ${$(t.from)} → ${$(t.to)}${n}`}function TE(e){let t=e.snapshot&&typeof e.snapshot==`object`?e.snapshot:{},n=$(t.tag),r=$(t.title),i=e.point&&typeof e.point==`object`?e.point:null,a=t.value===void 0?``:` = ${_E(JSON.stringify(t.value))}`,o=i?` · point ${$(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?` "${_E(r)}"`:``}${o}${e.dataChanged?` · data changed`:``}`}const EE=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 DE(e){let t=$(e.title);return`${e.deleted?`shot ${String(e.shot)} (shot deleted)`:`shot ${typeof e.number==`number`?`${e.number} `:``}${String(e.shot)}${t?` "${_E(t)}"`:``}`}${typeof e.t==`number`?` · ${typeof e.cut==`number`?`cut ${e.cut} `:``}at ${EE(e.t)}`:``}${typeof e.line==`string`?` · line ${e.line}${$(e.lineText)?` "${_E($(e.lineText))}"`:``}`:``}${e.mark?` · marked`:``}${$(e.cropPath)?` · crop ${$(e.cropPath)}`:``}`}function OE(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(`, `)}${wE(t.diagram)}${$(t.quote)?` "${_E($(t.quote))}"`:``}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(`, `)}`;if(typeof t.block==`string`)return TE(t);if(typeof t.shot==`string`)return DE(t);if(typeof t.slide==`string`){let e=$(t.title),n=$(t.text),r=Array.isArray(t.nodes)?t.nodes:[],i=r.length?` · ${r.length} node${r.length===1?``:`s`}: ${r.map(e=>`${$(e.tag)} ${$(e.block)} "${_E($(e.text))}"`).join(`, `)}`:``;return`slide ${t.slide}${e?` "${_E(e)}"`:``}${i||(n?` · on "${_E(n)}"`:``)}`}let n=$(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 kE={key:`id`,positional:!0,required:!0},AE={key:`line`,positional:!0,required:!0},jE={key:`tail`,positional:!0,required:!0},ME=e=>e.choice?` → ${e.choice}${e.byRecommendation?` (recommended)`:``}`:``;function NE(e,t){return e===`asks`?{columns:[kE,AE,{key:`note`,label:`note`},{key:`staleChoice`,label:`stale choice`}],rows:t.map(e=>({...e,line:`${$(e.state)}${e.choice?ME(e):$(e.text)?` · "${_E($(e.text))}"`:`choice`in e||`text`in e?` · no answer`:``}`,note:$(e.note)&&`"${_E($(e.note))}"`}))}:e===`threads`?{columns:[kE,{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=>({...PE(e),messageCount:typeof e.messageCount==`number`&&e.messageCount?vE(e.messageCount,`message`):``,preview:$(e.preview)&&`"${_E($(e.preview))}"`}))}:e===`groups`?{columns:[kE,{key:`kind`,positional:!0,required:!0},AE,{key:`origin`,positional:!0},{key:`evidenceUpdated`,label:`evidence updated`},{key:`rejects`,positional:!0},{key:`threadCount`,positional:!0},jE],rows:t.map(e=>({...e,line:e.kind===`verify`?$(e.verdict):`${e.round?`round ${e.round}`:``}${e.choice?ME(e):` · no pick`}`.replace(/^ · /,``),origin:typeof e.from==`string`&&e.from?`from ${e.from}`:``,rejects:typeof e.rejectThreads==`number`&&e.rejectThreads?vE(e.rejectThreads,`reject thread`):``,threadCount:typeof e.threads==`number`&&e.threads?vE(e.threads,`thread`):``,tail:$(e.title)}))}:{columns:[kE,{key:`state`,positional:!0,required:!0},{key:`groupList`,positional:!0},jE],rows:t.map(e=>({...e,groupList:Array.isArray(e.groups)&&e.groups.length?`groups ${e.groups.join(`, `)}`:``,tail:$(e.title)}))}}function PE(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:``,where:OE(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($).filter(Boolean).join(`; `):``,stale:e.stale===!0,orphan:e.orphan===!0}}const FE=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function IE(e,t=`items`){return{kind:`messages`,key:t,groups:e.map(e=>{let t=PE(e);return{facts:[FE(`id`,t.id),FE(`status`,t.status),FE(`waiting`,t.waiting),FE(`where`,t.where),{label:`marked`,binding:{key:`marked`,value:t.marked}},{label:`stale`,binding:{key:`stale`,value:t.stale}},{label:`orphan`,binding:{key:`orphan`,value:t.orphan}}],messages:(Array.isArray(e.messages)?e.messages:[]).map(e=>({facts:[FE(`message`,[e.id,`${$(e.name)||$(e.author)}${e.author===`agent`?` (agent)`:``}`,$(e.at)&&mw($(e.at)),e.deleted?`(deleted)`:``,$(e.editedAt)&&`edited ${mw($(e.editedAt))}`].filter(Boolean).join(` `))],text:typeof e.text==`string`?e.text:``}))}})}}function LE(e,t,n,r,i){let a=CE(e,t,n,i),o={key:r?e:`items`,title:yE(e),summary:a.full};return e===`threads`&&t.evidence===`complete`?{...IE(t.items),...o,...r?{page:n}:{}}:{kind:`records`,...NE(e,t.items),...o,...r?{page:n}:{}}}const RE=[`threads`,`asks`,`groups`,`rounds`];function zE(e,t){let n=e.summary??{},r=e=>t.find(t=>t.label===yE(e)),i=RE.filter(e=>r(e));return{heading:`Comment list`,status:``,subject:e.artifact,facts:[],sections:i.map(e=>{let t=n[e],i=e===`threads`?CE(`threads`,{items:[],summary:{waitingOnAgent:n.waitingOnAgent}},{total:Number(t??0)}).head:bE(t)||`none`;return{kind:`records`,key:e,title:yE(e),summary:`${i} · ${Ew(r(e))}`,columns:[],rows:[]}}),actions:t.filter(e=>!i.some(t=>yE(t)===e.label))}}function BE({data:e,actions:t,coverage:n},r=`Comment list`,i=!1){if(e.section===`summary`)return zE(e,t);let a=n.page;return{heading:r,status:``,subject:e.artifact,summary:CE(e.section,e,a,i).head,facts:[],sections:[LE(e.section,e,a,!1,i)]}}function VE({data:e},t=!1){let n=Object.entries(e.sections),r=n.map(([e,n])=>CE(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])=>LE(e,n,n.page,!0,t))}}const HE=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,UE=[`brief`,`table`,`json`,`jsonl`,`raw`];function WE(e,t=!1){let n=HE(e,`artifact`),r=t?cC:sC;if(!n||!uC(r).test(n))throw new J({code:`E_ARGUMENT_INVALID`,message:`--artifact must be ${dC(r)}.`});return n}function GE(e){let t=HE(e,`limit`);if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new J({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});return{...t===void 0?{}:{limit:Number(t)},...HE(e,`cursor`)?{cursor:HE(e,`cursor`)}:{},...HE(e,`snapshot`)?{snapshot:HE(e,`snapshot`)}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...HE(e,`fields`)?{fields:HE(e,`fields`).split(`,`).map(e=>e.trim())}:{}}}function KE(e,t){let n=Se(t);return{...e,agent:I(t)??`Agent`,...n?{session:n}:{}}}async function qE(e,t,n,r,i){let a=await ET(e.projectDir).call(`POST`,`/api/agent/v1/${n}/${r}`,KE(i,process.env),t.signal);if(t.payloads.raw=a.raw,a.json.schema!==`ryugi.review/v1`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported review response.`});if(a.status<200||a.status>=300)throw new J({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}function JE(e,t){return[`--artifact`,t,`--project-dir`,e.projectDir]}function YE(e,t,n){let r=/* @__PURE__ */ new Set([...Object.keys(ZC),`artifact`,`receipt`]),i=Object.keys(e.values).find(e=>!r.has(e));if(i)throw new J({code:`E_ARGUMENT_INVALID`,message:`--${i} is not supported for ack.`});let a=HE(e,`receipt`);if(!a)throw new J({code:`E_ARGUMENT_INVALID`,message:`ack requires --receipt.`});return Q({id:n===`review`?`comment.ack`:`changes.ack`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){ET(e.projectDir);let o=i.effects.begin(n===`review`?`comment.ack`:`changes.ack`,a),s=await qE(e,i,t,n,{op:`ack`,receipt:a});if(![`acknowledged`,`unchanged`].includes(s.status))throw new J({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}),Y({artifact:t,receipt:a,status:s.status})},present:ZE(n===`review`?`comment`:`changes`)},e)}function XE(e,t,n){if(n!==`list`)throw new J({code:`E_ARGUMENT_INVALID`,message:`--sections applies to comment list.`});let r=GE(e),i=HE(e,`sections`)?.trim(),a=i===`all`?fE(t):(i??``).split(`,`).map(e=>e.trim()),o=Object.fromEntries([`status`,`waiting-on`,`kind`,`choice-state`].map(t=>[t,HE(e,t)])),s=pE({...r,sections:a,section:HE(e,`section`),thread:HE(e,`thread`),filters:o},t);if(s)throw new J({code:`E_ARGUMENT_INVALID`,message:s});return Q({id:`comment.list`,mode:`finite`,output:{formats:UE,detail:!0},async run(n,i){let o=await qE(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 J({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 J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned inconsistent combined review coverage.`})}return $E(e,t,a,o,r)},present:e=>VE(e,r.all)},e)}const ZE=e=>({data:t})=>({heading:e===`comment`?`Comment ack`:`Changes ack`,status:t.status,subject:t.artifact,facts:[],sections:[]});function QE({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?[Z(`File`,X(e,`saved`),!0)]:[],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 $E(e,t,n,r,i){let a={},o=[],s=[];for(let c of n){let n=r.sections[c],l=eD(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 Y({artifact:t,sections:a},void 0,{actions:o,coverage:{omitted:s}})}function eD(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.summary?{summary:r.summary}:{}},c=[],l=JE(e,t);if(r.receipt&&c.push(lw([`comment`,`ack`,...l,`--receipt`,r.receipt],`Acknowledge`)),o?.nextCursor&&c.push(lw([`comment`,`list`,...l,`--section`,n,...i.detail?[`--detail`]:[],...Object.entries({status:HE(e,`status`),"waiting-on":HE(e,`waiting-on`),kind:HE(e,`kind`),"choice-state":HE(e,`choice-state`),fields:HE(e,`fields`),limit:HE(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(lw([`comment`,`read`,...l,`--thread`,String(s.items[0].id),`--snapshot`,r.snapshot,`--detail`],`Read`));else{c.push(lw([`comment`,`list`,...l,`--sections`,`all`,`--detail`,...i.all?[`--all`]:[],...HE(e,`limit`)?[`--limit`,HE(e,`limit`)]:[]],`Review all`));let n=[`threads`,...iC[t.split(`/`)[0]].review?.sections??[]];c.unshift(...n.map(e=>lw([`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({...lw([`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`&&gE(e,t,s,o,c),Y(s,void 0,{actions:c,coverage:{...o?{page:o}:{},...s.evidence===`preview`&&n===`threads`?{omitted:[{path:`data.items.messages`,reason:`summary`}]}:{}}})}function tD(e){let t=WE(e),n=e.positionals[0];if(n===`ack`)return YE(e,t,`review`);if(e.values.sections!==void 0)return XE(e,t,n);if(n!==`list`&&n!==`read`)throw new J({code:`E_ARGUMENT_INVALID`,message:`Expected list, read or ack.`});let r=GE(e),i=n===`read`?`threads`:HE(e,`section`),a=HE(e,`thread`);if(n===`read`&&!a)throw new J({code:`E_ARGUMENT_INVALID`,message:`read requires --thread.`});if(i&&![`threads`,`asks`,`groups`,`rounds`].includes(i))throw new J({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 J({code:`E_ARGUMENT_INVALID`,message:`Select --section before detail, fields, cursor or filters.`});let o=Object.fromEntries([[`status`,HE(e,`status`)],[`waitingOn`,HE(e,`waiting-on`)],[`kind`,HE(e,`kind`)],[`choiceState`,HE(e,`choice-state`)]].filter(([,e])=>e!==void 0)),s=mE({...r,section:i,filters:o});if(s)throw new J({code:`E_ARGUMENT_INVALID`,message:s});return Q({id:`comment.${n}`,mode:`finite`,output:{detail:!0,formats:UE,collection:`items`,requiredFields:i?dE[i]:[],fields:i?[...uE[i]]:[]},async run(s,c){let l=await qE(e,c,t,`review`,{op:n,...r,...i?{section:i}:{},...a?{thread:a,detail:!0}:{},...Object.keys(o).length?{filters:o}:{}});return eD(e,t,i,l,r,a)},present:t=>BE(t,n===`read`?`Comment read`:`Comment list`,r.all||!!HE(e,`status`)&&(i!==`asks`||HE(e,`status`)!==`submitted`)||!!HE(e,`choice-state`))},e)}function nD(e){let t=WE(e,!0),n=e.positionals[0];if(n===`ack`)return YE(e,t,`changes`);if(n)throw new J({code:`E_ARGUMENT_INVALID`,message:`Expected changes or changes ack.`});let r=GE(e),i=HE(e,`save`);if(i!==void 0&&!i.trim())throw new J({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});if(r.detail&&(r.fields||r.cursor||r.limit!==void 0))throw new J({code:`E_OPTION_CONFLICT`,message:`A complete diff cannot use --limit, --cursor or --fields.`});return Q({id:`changes`,mode:`finite`,output:{detail:!0,formats:i?[`brief`,`json`,`jsonl`]:UE,fields:[`artifact`,`snapshot`,`blocks`,`diff`,`empty`]},async run(n,a){let{page:o,schema:s,...c}=await qE(e,a,t,`changes`,{op:`read`,...r}),l=c;if(i&&l.empty!==!0&&typeof l.diff!=`string`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return complete diff evidence; no export was written.`});if(i){let e=hE(i,l.diff??``,a.effects);l.saved=e.file,l.bytes=e.bytes,delete l.diff}let u=JE(e,t),d=l.receipt?[lw([`changes`,`ack`,...u,`--receipt`,l.receipt],`Acknowledge`)]:l.empty?[]:[lw([`changes`,...u,`--snapshot`,l.snapshot,...r.all?[`--all`]:[],`--detail`],`Read`)];return o?.nextCursor&&d.push(lw([`changes`,...u,...r.all?[`--all`]:[],...Object.entries({fields:HE(e,`fields`),limit:HE(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),`--cursor`,o.nextCursor],`More`)),Y(l,void 0,{actions:d,coverage:{...o?{page:o}:{},...!r.detail&&!l.empty?{omitted:[{path:`data.diff`,reason:`summary`}]}:{}}})},present:QE},e)}const rD={semantic:nD,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`}}};function iD(e){let t=e=>!!e&&typeof e==`object`&&!Array.isArray(e),n=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`);if(!t(e)||!n(e.warnings)||!t(e.evidence)||typeof e.evidence.required!=`boolean`||typeof e.evidence.fresh!=`boolean`||e.evidence.observed!==void 0&&typeof e.evidence.observed!=`boolean`||e.pending!==void 0&&!n(e.pending)||e.provenance!==void 0&&!n(e.provenance)||e.modules!==void 0&&!n(e.modules)||e.checkedAt!==void 0&&typeof e.checkedAt!=`string`||e.structure!==void 0&&typeof e.structure!=`number`||e.unvisited!==void 0&&!(Array.isArray(e.unvisited)&&e.unvisited.every(e=>t(e)&&typeof e.page==`string`&&n(e.boards)))||e.sheet!==void 0&&e.sheet!==null&&(!t(e.sheet)||typeof e.sheet.version!=`number`||!n(e.sheet.files)||e.sheet.unavailable!==void 0&&typeof e.sheet.unavailable!=`string`)||e.diagnostics!==void 0&&!(Array.isArray(e.diagnostics)&&e.diagnostics.every(e=>t(e)&&typeof e.code==`string`&&typeof e.message==`string`&&(e.location===void 0||typeof e.location==`string`)&&(e.severity===`error`||e.severity===`warning`))))return!1;for(let t of[`ran`,`merging`])if(e[t]!==void 0&&typeof e[t]!=`boolean`)return!1;return!(e.dynamic!==void 0&&(!t(e.dynamic)||Object.values(e.dynamic).some(e=>!t(e)||e.ran!==void 0&&typeof e.ran!=`boolean`))||e.recordings!==void 0&&(!t(e.recordings)||Object.values(e.recordings).some(e=>!t(e)||[`status`,`warning`].some(t=>e[t]!==void 0&&typeof e[t]!=`string`))))}const aD=/* @__PURE__ */ new Set([`W_PROVENANCE`,`W_MODULES`,`W_HUMAN_EDIT_OVERWRITTEN`,`W_BOARD_CLIPPED`]);function oD(e,t){let n=(t.warnings??[]).map(e=>({code:`W_ARTIFACT`,severity:`warning`,message:e}));n.push(...t.diagnostics??[]);for(let e of t.provenance??[])n.push({code:`W_PROVENANCE`,severity:`warning`,message:e});for(let e of t.modules??[])n.push({code:`W_MODULES`,severity:`warning`,message:e});let r=[...t.pending??[]];t.merging&&r.push(`merging`);for(let[e,i]of Object.entries(t.recordings??{}))i.warning&&n.push({code:`W_RECORDING`,severity:`warning`,message:i.warning,location:e}),i.status===`processing`&&r.push(`recording:${e}`);let i=Object.entries(t.dynamic??{}),a=t.evidence?.required??(e.startsWith(`html/`)||e.startsWith(`artboard/`)||i.length>0),o=t.evidence?.observed===!1||t.ran===!1||i.some(([,e])=>e.ran===!1);a&&o&&r.push(`browser_not_run`);let s=t.evidence?.observed??(t.ran===!0||i.length>0&&i.every(([,e])=>e.ran===!0)),c=a?o?`not_run`:s&&t.evidence?.fresh===!0?`clean`:`unknown`:`not_required`,l=n.filter(e=>!aD.has(e.code)),u=l.length?`issues`:r.length?`pending`:c===`unknown`||t.evidence?.fresh===!1?`unknown`:`clean`;return Y({artifact:e,status:u,static:l.length?`issues`:`clean`,runtime:c,issues:n,pending:r,...t.sheet?.unavailable?{sheetUnavailable:t.sheet.unavailable}:t.sheet?{sheet:t.sheet.files}:{},...t.structure?{structure:t.structure}:{},...t.unvisited?.length?{unvisited:t.unvisited}:{},evidence:t},u===`issues`?{kind:`validation_failed`}:u===`pending`||u===`unknown`?{kind:`pending`,reasons:r.length?r:[`evidence_unknown`]}:{kind:`succeeded`})}async function sD(e,t,n){if(!e.artifact||!ue.test(e.artifact))throw new M(de);let r=await ET(e.projectDir).call(`POST`,`/api/agent/${e.artifact}/check${e.page?`?page=${encodeURIComponent(e.page)}`:``}`,void 0,t);n?.(r.raw);let{status:i,json:a}=r;if(i<200||i>=300)throw new M(a?.error||`HTTP ${i}`);if(!iD(a))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned invalid check evidence; validation could not be established.`});return{...r,json:a}}const cD={name:`check`,summary:`Wait until the server has checked the latest write, then print its warnings (needs a running server)`,usage:[`--artifact <type>/<id> [options]`],options:{artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to check`},page:{type:`string`,value:`<page-id>`,help:`Whiteboards: check only this page and the board-wide warnings`}},semantic:e=>Q({id:`check`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`raw`,`quiet`],fields:[`artifact`,`file`,`status`,`static`,`runtime`,`issues`,`pending`,`sheet`,`sheetUnavailable`,`structure`,`unvisited`,`evidence`],scalar:e=>e.status},async run(t,n){let r=await sD({projectDir:e.projectDir,artifact:e.values.artifact,page:e.values.page},n.signal,e=>{n.payloads.raw=e});n.payloads.raw=r.raw;let i=oD(e.values.artifact,r.json);return i.data.file=hC(e.projectDir,i.data.artifact).write,i.actions=[lw([`check`,`--artifact`,i.data.artifact,...e.values.page?[`--page`,e.values.page]:[],`--project-dir`,e.projectDir,`--detail`])],i},present:lD},e)};function lD({data:e}){let t=e.issues.length;return{heading:`Check`,status:e.status,subject:e.artifact,summary:t?`${t} issue${t===1?``:`s`}`:``,facts:[...t&&e.file?[Z(`File`,{key:`file`,value:e.file})]:[],...e.runtime===`not_run`||e.runtime===`unknown`?[Z(`Browser`,{key:`runtime`,value:e.runtime.replaceAll(`_`,` `)})]:[],...e.pending.length?[Z(`Pending`,{key:`pending`,value:e.pending.join(`, `)})]:[],...e.unvisited?.length?[Z(`Show`,{key:`unvisited`,value:`${e.unvisited.map(({page:e,boards:t})=>`page ${e}: ${t.join(`, `)}`).join(` · `)}. Open the artboard in a browser, bring these boards into view, then check again; with agent-browser installed (see adeck doctor) Check loads them itself`})]:[],...e.sheet?.length?[Z(`Sheet`,{key:`sheet`,value:e.sheet.join(`, `)})]:e.sheetUnavailable?[Z(`Sheet`,{key:`sheetUnavailable`,value:`unavailable (${e.sheetUnavailable})`})]:[],...e.structure?[Z(`Structure`,{key:`structure`,value:`${e.structure} change${e.structure===1?``:`s`} by your human partner since you last read — run changes --artifact ${e.artifact}`})]:[]],sections:[{kind:`diagnostics`,key:`issues`,items:e.issues,preview:3}]}}const uD={reject:0,pending:1,pass:2,checked:3},dD={reject:`rejected`,pending:`pending`,pass:`passed`,checked:`checked by agent`},fD=(e,t)=>e?`${e} ${t}`:``,pD=e=>e.filter(Boolean).join(` · `),mD=(e,t=!1)=>({key:e,positional:!0,required:t});function hD({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=pD([fD(t.needYou,`on your human partner`),fD(t.notVerified,`not verified`),fD(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?[Z(`Waiting`,{key:`waiting`,value:i})]:[],sections:[{kind:`records`,key:`claims`,title:`Claims`,summary:pD([fD(n(`reject`),`rejected`),fD(n(`pending`),`pending`),fD(n(`pass`),`passed`),fD(n(`checked`),`checked by agent`)]),columns:[mD(`id`,!0),mD(`line`,!0),mD(`rejects`),{key:`evidenceUpdated`,label:`evidence updated`},mD(`origin`),mD(`tail`)],rows:[...e.claims].sort((e,t)=>uD[e.state]-uD[t.state]).map(e=>({...e,line:dD[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:[mD(`id`,!0),mD(`state`,!0)],rows:e.rows.map(e=>({...e,id:`${e.artboard}/${e.group}`}))}]:[],...e.gaps.length?[{kind:`records`,key:`gaps`,title:`Not verified`,summary:pD([fD(e.gaps.filter(e=>!e.waived).length,`open`),fD(e.gaps.filter(e=>e.waived).length,`waived`)]),columns:[mD(`id`,!0),mD(`line`,!0),mD(`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:pD([fD(r.length,`open`),fD(e.threads.length-r.length,`resolved`)]),groups:e.threads.map(e=>({facts:[{...Z(`Thread`,{key:`id`,value:e.id},!0),positional:!0},Z(`On`,{key:`anchor`,value:e.anchor.claim?`claim ${e.anchor.claim}`:`gap ${e.anchor.gap}`},!0),Z(`Verdict`,{key:`verdict`,value:e.anchor.verdict??(e.anchor.waive?`waived`:``)}),Z(`Status`,{key:`status`,value:e.status},!0),...e.stale?[Z(`Stale`,{key:`stale`,value:!0})]:[]],messages:e.messages.map(e=>({facts:[{...Z(`Author`,{key:`author`,value:e.author},!0),positional:!0},Z(`At`,{key:`at`,value:e.at})],text:e.text}))}))}]:[]]}}function gD(e){let t=e.values.artifact,n=hC(e.projectDir,t);return Q({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=I(process.env),o=await ET(e.projectDir).call(`POST`,`/api/agent/${t}/comments`,{op:`list`,...a?{agent:a}:{}},i.signal);if(o.status<200||o.status>=300)throw new J({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 Y({...s,artifact:t,projectDir:e.projectDir},void 0,{actions:l.length?[{...lw([`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=>({...lw([`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:hD},e)}function _D({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?[Z(`Message`,X(e,`messageId`))]:[],...e.groups?.length?[Z(`Groups`,{key:`groups`,value:e.groups.join(`, `)})]:[]],sections:[]}}function vD(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 yD(e){let t=vD(e),n=t.action;if(t.artifact?.startsWith(`verify/`)&&[`list`,`read`,`ack`].includes(n??``)){if(n!==`list`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`A verify report has no thread receipts: comment list shows every thread.`});return gD(e)}if([`list`,`read`,`ack`].includes(n??``))return tD(e);if([`section`,`sections`,`limit`,`cursor`,`snapshot`,`receipt`,`status`,`waiting-on`,`kind`,`choice-state`].some(t=>e.values[t]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Review query options apply only to list, read and ack.`});return Q({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=CD(t);ET(t.projectDir);let i=n.effects.begin(`comment.${r.action}`,t.thread??t.ask??t.group??t.artifact),a=await wD(t,r,n.signal);if(a.status>=400&&a.status<500&&n.effects.set(i,`failed`),a.status<200||a.status>=300)throw new J({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{action:s,request:c}=r,l={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`},u=s===`pass`&&[o.groups,o.claims].some(e=>Array.isArray(e)&&e.length===0);return u&&n.effects.set(i,`none`),Y({artifact:t.artifact,operation:s,status:u?`unchanged`:l[s],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}:{},...s===`choose`?{board:c.board}:{},...s===`submit`?{submitted:!t.withdraw}:{},...s===`answer`?{choice:c.choice}:{}},void 0,{effects:n.effects.snapshot()})},present:_D},e)}const bD=uC(lC),xD=/* @__PURE__ */ new Set([`pass`,`reject`]);function SD(e,t,n){let r=iC[n];if(r.commentRequest)return r.commentRequest(e,t);if(t===`waive`)throw new M(`comment waive works on verify reports only`);let i=r.commentActions?.[t];if(i)return i(e);if(t===`answer`||t===`note`)throw new M(`comment ${t} works on documents only`);if(t===`choose`||t===`submit`||xD.has(t))throw new M(`comment ${t} works on artboards only`);if(t===`add`)throw new M(`comment add does not work on ${n}`);if(!e.thread)throw new M(`comment ${t} needs --thread <threadId>`);return t===`reply`?{op:`reply`,threadId:e.thread,text:$n(e)}:{op:`resolve`,threadId:e.thread}}function CD(e){let t=Zn.find(t=>t===e.action);if(!t)throw new M(`comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive`);if(!e.artifact||!bD.test(e.artifact))throw new M(`--artifact must be ${dC(lC)}`);let[n,r]=e.artifact.split(`/`);return{action:t,type:n,id:r,request:SD(e,t,n),artifact:e.artifact}}async function wD(e,t,n){let{type:r,id:i,request:a}=t,o=ET(e.projectDir),s=I(process.env);return o.call(`POST`,`/api/agent/${r}/${i}/comments`,{...a,agent:s??`Agent`},n)}const TD={actionOptions:{list:[`limit`,`cursor`,`snapshot`,`status`,`waiting-on`,`kind`,`choice-state`,`thread`],read:[`limit`,`cursor`,`all`,`save`]},semantic:yD,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 ${fC(sC)} --sections all|<names> [--detail] [--all]`,`list --artifact ${fC(sC)} [--section threads|asks|groups|rounds] [--all]`,`read --artifact ${fC(sC)} --thread <threadId> [--snapshot <token>]`,`ack --artifact ${fC(sC)} --receipt <receipt>`,`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 ${fC(lC)} --thread <threadId> [--text <text>]`,`resolve --artifact ${fC(sC)} --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 do not consume evidence. read returns a complete thread and receipt; use ack after applying that evidence. asks, groups and rounds are independent state reads without receipts. 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`},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},ED={on:!0,off:!1,inherit:null};function DD(e,t=()=>{}){let n=NC(Jn(process.env,process.platform,h.default.homedir())),r=f.default.join(f.default.dirname(ce(e.projectDir).root),`config.json`);if(e.autoPublish!==void 0){let i=ED[e.autoPublish];if(i===void 0)throw new M(`--auto-publish takes on, off, or (with --project) inherit`);if(e.project){let e=EC(r);if(e.warning)throw new M(e.warning);t(),kC(r),jC(r,i)}else if(i===null)throw new M(`inherit only applies with --project`);else IC(n,i,t)}return{global:FC(n)??null,project:EC(r).config.autoPublish??null}}const OD={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=>Q({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 M(`Choose auto-publish or output-format.`);let r=e.values.project?`project`:`global`,i=GC(e.projectDir)[r],a,o=()=>{a=n.effects.begin(`config`,i)};typeof e.values[`output-format`]==`string`&&JC(e.projectDir,!!e.values.project,e.values[`output-format`],o);let s=DD({projectDir:e.projectDir,autoPublish:e.values[`auto-publish`],project:!!e.values.project},o);return a!==void 0&&n.effects.confirm(a),Y({scope:r,projectDir:e.projectDir,file:i,...s,output:qC(e.projectDir),effective:s.project??s.global,source:s.project===null?s.global===null?`undecided`:`global`:`project`,applies:`supported_turn_end_hook`})},present:kD},e)};function kD({data:e}){let t=e.effective===null?`undecided`:e.effective?`on`:`off`;return{heading:`Config`,status:``,facts:[Z(`Scope`,{key:`scope`,value:e.scope}),Z(`File`,{key:`file`,value:e.file}),Z(`Auto-publish`,{key:`autoPublish`,value:e.source===`undecided`?t:`${t} (${e.source})`}),Z(`Output format`,{key:`output`,value:`${e.output.effective} (${e.output.source})`})],sections:[]}}function AD(e=process.env,t=h.default.homedir()){if(e.RYUGI_DAEMON_SOCKET)return e.RYUGI_DAEMON_SOCKET;let n=f.default.dirname(qe(e)),{home:r}=He(e,t);if(ht(r,t))return f.default.join(n,`daemon.sock`);let i=f.default.join(r,`daemon.sock`);if(Buffer.byteLength(i)<=103)return i;let a=u.default.createHash(`sha256`).update(r).digest(`hex`).slice(0,16);return f.default.join(n,`daemon-${a}.sock`)}function jD(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(`
|
|
854
|
-
`);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
|
|
855
|
-
`)}`);return[r,`attach`,a.attach]}const
|
|
856
|
-
`),i((0,p.spawnSync)(e,t,{stdio:`inherit`}).status===0?`detached`:`failed`,[])}}}function
|
|
857
|
-
`)}]:[]}}const
|
|
853
|
+
`)}]}}const uE={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`]},dE={threads:[`id`,`status`,`waitingOn`],asks:[`id`,`state`],groups:[`id`,`kind`,`verdict`,`choice`],rounds:[`id`,`state`]},fE=e=>e.startsWith(`document/`)?[`threads`,`asks`]:[`threads`,`groups`,`rounds`];function pE(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=>!fE(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 mE(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 uE))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=>!uE[t].includes(e))?`Unknown field for this section.`:null}function hE(e,t,n){let r=f.default.resolve(e),i=n?.begin(`save`,r),a;try{a=d.default.openSync(r,`wx`,384)}catch(e){throw i!==void 0&&n.set(i,`failed`),new J({code:e.code===`EEXIST`?`E_FILE_EXISTS`:`E_FILE_WRITE_FAILED`,message:`Could not create ${r}: ${e.message}`})}try{d.default.writeFileSync(a,t)}catch(e){throw d.default.closeSync(a),d.default.unlinkSync(r),i!==void 0&&n.set(i,`failed`),new J({code:`E_FILE_WRITE_FAILED`,message:`Could not save ${r}: ${e.message}`})}return d.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 gE(e,t,n,r,i){let a=e.projectDir,o=[`--artifact`,t,`--project-dir`,a];if(n.evidence===`preview`&&n.items.length&&n.snapshot){let t=i.findIndex(e=>e.label===`Read`),a=[`status`,`waiting-on`,`kind`,`choice-state`].flatMap(t=>typeof e.values[t]==`string`?[`--${t}`,String(e.values[t])]:[]),s={...lw([`comment`,`list`,...o,`--section`,`threads`,`--detail`,`--snapshot`,n.snapshot,`--limit`,String(r?.returned??n.items.length),...typeof e.values.cursor==`string`?[`--cursor`,e.values.cursor]:[],...a,...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)}if(n.evidence!==`complete`)return;let s=n.items.filter(e=>e.status===`open`);if(s.length){let{write:e}=hC(a,t);i.push({...lw([`check`,...o],`Check`),reason:`After editing ${e} in place. Re-read before editing; preserve human changes and existing IDs. comments.json is server-owned.`});for(let e of s)i.push({...lw([`comment`,`reply`,...o,`--thread`,String(e.id),`--text`,`<what changed or your answer>`],`Reply (${e.id})`),reason:`Replace the message argument after applying this request.`}),e.anchor?.verdict!==`reject`&&i.push({...lw([`comment`,`resolve`,...o,`--thread`,String(e.id)],`Resolve (${e.id})`),reason:`Only once this thread is settled.`})}let c=i.findIndex(e=>e.label===`Acknowledge`);if(c>=0){let[e]=i.splice(c,1);i.push({...e,reason:`After using every delivered message. This resolves nothing and leaves later replies unread.`})}}const $=e=>typeof e==`string`?e:``,_E=e=>e.replaceAll(/\s*\n\s*/g,` / `).trim(),vE=(e,t)=>`${e} ${t}${e===1?``:`s`}`,yE=e=>e[0].toUpperCase()+e.slice(1),bE=(e,t=[])=>Object.entries(e??{}).filter(([e,n])=>e!==`waitingOnAgent`&&!t.includes(e)&&typeof n==`number`&&n>0).map(([e,t])=>`${t} ${e}`).join(`, `),xE=e=>e?` (${e})`:``,SE={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 CE(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}${xE(bE(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=SE[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?vE(c,`other`):``:bE(a,o.listed);return{head:s,full:`${s}${xE(l)}`,count:i}}function wE(e){if(!e||typeof e!=`object`)return``;let t=e;if(t.kind===`node`)return` node ${$(t.id)}`;if(t.kind!==`edge`)return``;let n=typeof t.index==`number`&&t.index>0?` #${t.index+1}`:``;return` edge ${$(t.from)} → ${$(t.to)}${n}`}function TE(e){let t=e.snapshot&&typeof e.snapshot==`object`?e.snapshot:{},n=$(t.tag),r=$(t.title),i=e.point&&typeof e.point==`object`?e.point:null,a=t.value===void 0?``:` = ${_E(JSON.stringify(t.value))}`,o=i?` · point ${$(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?` "${_E(r)}"`:``}${o}${e.dataChanged?` · data changed`:``}`}const EE=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 DE(e){let t=$(e.title);return`${e.deleted?`shot ${String(e.shot)} (shot deleted)`:`shot ${typeof e.number==`number`?`${e.number} `:``}${String(e.shot)}${t?` "${_E(t)}"`:``}`}${typeof e.t==`number`?` · ${typeof e.cut==`number`?`cut ${e.cut} `:``}at ${EE(e.t)}`:``}${typeof e.line==`string`?` · line ${e.line}${$(e.lineText)?` "${_E($(e.lineText))}"`:``}`:``}${e.mark?` · marked`:``}${$(e.cropPath)?` · crop ${$(e.cropPath)}`:``}`}function OE(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(`, `)}${wE(t.diagram)}${$(t.quote)?` "${_E($(t.quote))}"`:``}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(`, `)}`;if(typeof t.block==`string`)return TE(t);if(typeof t.shot==`string`)return DE(t);if(typeof t.slide==`string`){let e=$(t.title),n=$(t.text),r=Array.isArray(t.nodes)?t.nodes:[],i=r.length?` · ${r.length} node${r.length===1?``:`s`}: ${r.map(e=>`${$(e.tag)} ${$(e.block)} "${_E($(e.text))}"`).join(`, `)}`:``;return`slide ${t.slide}${e?` "${_E(e)}"`:``}${i||(n?` · on "${_E(n)}"`:``)}`}let n=$(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 kE={key:`id`,positional:!0,required:!0},AE={key:`line`,positional:!0,required:!0},jE={key:`tail`,positional:!0,required:!0},ME=e=>e.choice?` → ${e.choice}${e.byRecommendation?` (recommended)`:``}`:``;function NE(e,t){return e===`asks`?{columns:[kE,AE,{key:`note`,label:`note`},{key:`staleChoice`,label:`stale choice`}],rows:t.map(e=>({...e,line:`${$(e.state)}${e.choice?ME(e):$(e.text)?` · "${_E($(e.text))}"`:`choice`in e||`text`in e?` · no answer`:``}`,note:$(e.note)&&`"${_E($(e.note))}"`}))}:e===`threads`?{columns:[kE,{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=>({...PE(e),messageCount:typeof e.messageCount==`number`&&e.messageCount?vE(e.messageCount,`message`):``,preview:$(e.preview)&&`"${_E($(e.preview))}"`}))}:e===`groups`?{columns:[kE,{key:`kind`,positional:!0,required:!0},AE,{key:`origin`,positional:!0},{key:`evidenceUpdated`,label:`evidence updated`},{key:`rejects`,positional:!0},{key:`threadCount`,positional:!0},jE],rows:t.map(e=>({...e,line:e.kind===`verify`?$(e.verdict):`${e.round?`round ${e.round}`:``}${e.choice?ME(e):` · no pick`}`.replace(/^ · /,``),origin:typeof e.from==`string`&&e.from?`from ${e.from}`:``,rejects:typeof e.rejectThreads==`number`&&e.rejectThreads?vE(e.rejectThreads,`reject thread`):``,threadCount:typeof e.threads==`number`&&e.threads?vE(e.threads,`thread`):``,tail:$(e.title)}))}:{columns:[kE,{key:`state`,positional:!0,required:!0},{key:`groupList`,positional:!0},jE],rows:t.map(e=>({...e,groupList:Array.isArray(e.groups)&&e.groups.length?`groups ${e.groups.join(`, `)}`:``,tail:$(e.title)}))}}function PE(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:``,where:OE(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($).filter(Boolean).join(`; `):``,stale:e.stale===!0,orphan:e.orphan===!0}}const FE=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function IE(e,t=`items`){return{kind:`messages`,key:t,groups:e.map(e=>{let t=PE(e);return{facts:[FE(`id`,t.id),FE(`status`,t.status),FE(`waiting`,t.waiting),FE(`where`,t.where),{label:`marked`,binding:{key:`marked`,value:t.marked}},{label:`stale`,binding:{key:`stale`,value:t.stale}},{label:`orphan`,binding:{key:`orphan`,value:t.orphan}}],messages:(Array.isArray(e.messages)?e.messages:[]).map(e=>({facts:[FE(`message`,[e.id,`${$(e.name)||$(e.author)}${e.author===`agent`?` (agent)`:``}`,$(e.at)&&mw($(e.at)),e.deleted?`(deleted)`:``,$(e.editedAt)&&`edited ${mw($(e.editedAt))}`].filter(Boolean).join(` `))],text:typeof e.text==`string`?e.text:``}))}})}}function LE(e,t,n,r,i){let a=CE(e,t,n,i),o={key:r?e:`items`,title:yE(e),summary:a.full};return e===`threads`&&t.evidence===`complete`?{...IE(t.items),...o,...r?{page:n}:{}}:{kind:`records`,...NE(e,t.items),...o,...r?{page:n}:{}}}const RE=[`threads`,`asks`,`groups`,`rounds`];function zE(e,t){let n=e.summary??{},r=e=>t.find(t=>t.label===yE(e)),i=RE.filter(e=>r(e));return{heading:`Comment list`,status:``,subject:e.artifact,facts:[],sections:i.map(e=>{let t=n[e],i=e===`threads`?CE(`threads`,{items:[],summary:{waitingOnAgent:n.waitingOnAgent}},{total:Number(t??0)}).head:bE(t)||`none`;return{kind:`records`,key:e,title:yE(e),summary:`${i} · ${Ew(r(e))}`,columns:[],rows:[]}}),actions:t.filter(e=>!i.some(t=>yE(t)===e.label))}}function BE({data:e,actions:t,coverage:n},r=`Comment list`,i=!1){if(e.section===`summary`)return zE(e,t);let a=n.page;return{heading:r,status:``,subject:e.artifact,summary:CE(e.section,e,a,i).head,facts:[],sections:[LE(e.section,e,a,!1,i)]}}function VE({data:e},t=!1){let n=Object.entries(e.sections),r=n.map(([e,n])=>CE(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])=>LE(e,n,n.page,!0,t))}}const HE=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,UE=[`brief`,`table`,`json`,`jsonl`,`raw`];function WE(e,t=!1){let n=HE(e,`artifact`),r=t?cC:sC;if(!n||!uC(r).test(n))throw new J({code:`E_ARGUMENT_INVALID`,message:`--artifact must be ${dC(r)}.`});return n}function GE(e){let t=HE(e,`limit`);if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new J({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});return{...t===void 0?{}:{limit:Number(t)},...HE(e,`cursor`)?{cursor:HE(e,`cursor`)}:{},...HE(e,`snapshot`)?{snapshot:HE(e,`snapshot`)}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...HE(e,`fields`)?{fields:HE(e,`fields`).split(`,`).map(e=>e.trim())}:{}}}function KE(e,t){let n=Se(t);return{...e,agent:I(t)??`Agent`,...n?{session:n}:{}}}async function qE(e,t,n,r,i){let a=await ET(e.projectDir).call(`POST`,`/api/agent/v1/${n}/${r}`,KE(i,process.env),t.signal);if(t.payloads.raw=a.raw,a.json.schema!==`ryugi.review/v1`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported review response.`});if(a.status<200||a.status>=300)throw new J({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}function JE(e,t){return[`--artifact`,t,`--project-dir`,e.projectDir]}function YE(e,t,n){let r=/* @__PURE__ */ new Set([...Object.keys(ZC),`artifact`,`receipt`]),i=Object.keys(e.values).find(e=>!r.has(e));if(i)throw new J({code:`E_ARGUMENT_INVALID`,message:`--${i} is not supported for ack.`});let a=HE(e,`receipt`);if(!a)throw new J({code:`E_ARGUMENT_INVALID`,message:`ack requires --receipt.`});return Q({id:n===`review`?`comment.ack`:`changes.ack`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.receipt},async run(r,i){ET(e.projectDir);let o=i.effects.begin(n===`review`?`comment.ack`:`changes.ack`,a),s=await qE(e,i,t,n,{op:`ack`,receipt:a});if(![`acknowledged`,`unchanged`].includes(s.status))throw new J({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}),Y({artifact:t,receipt:a,status:s.status})},present:ZE(n===`review`?`comment`:`changes`)},e)}function XE(e,t,n){if(n!==`list`)throw new J({code:`E_ARGUMENT_INVALID`,message:`--sections applies to comment list.`});let r=GE(e),i=HE(e,`sections`)?.trim(),a=i===`all`?fE(t):(i??``).split(`,`).map(e=>e.trim()),o=Object.fromEntries([`status`,`waiting-on`,`kind`,`choice-state`].map(t=>[t,HE(e,t)])),s=pE({...r,sections:a,section:HE(e,`section`),thread:HE(e,`thread`),filters:o},t);if(s)throw new J({code:`E_ARGUMENT_INVALID`,message:s});return Q({id:`comment.list`,mode:`finite`,output:{formats:UE,detail:!0},async run(n,i){let o=await qE(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 J({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 J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned inconsistent combined review coverage.`})}return $E(e,t,a,o,r)},present:e=>VE(e,r.all)},e)}const ZE=e=>({data:t})=>({heading:e===`comment`?`Comment ack`:`Changes ack`,status:t.status,subject:t.artifact,facts:[],sections:[]});function QE({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?[Z(`File`,X(e,`saved`),!0)]:[],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 $E(e,t,n,r,i){let a={},o=[],s=[];for(let c of n){let n=r.sections[c],l=eD(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 Y({artifact:t,sections:a},void 0,{actions:o,coverage:{omitted:s}})}function eD(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.summary?{summary:r.summary}:{}},c=[],l=JE(e,t);if(r.receipt&&c.push(lw([`comment`,`ack`,...l,`--receipt`,r.receipt],`Acknowledge`)),o?.nextCursor&&c.push(lw([`comment`,`list`,...l,`--section`,n,...i.detail?[`--detail`]:[],...Object.entries({status:HE(e,`status`),"waiting-on":HE(e,`waiting-on`),kind:HE(e,`kind`),"choice-state":HE(e,`choice-state`),fields:HE(e,`fields`),limit:HE(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(lw([`comment`,`read`,...l,`--thread`,String(s.items[0].id),`--snapshot`,r.snapshot,`--detail`],`Read`));else{c.push(lw([`comment`,`list`,...l,`--sections`,`all`,`--detail`,...i.all?[`--all`]:[],...HE(e,`limit`)?[`--limit`,HE(e,`limit`)]:[]],`Review all`));let n=[`threads`,...iC[t.split(`/`)[0]].review?.sections??[]];c.unshift(...n.map(e=>lw([`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({...lw([`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`&&gE(e,t,s,o,c),Y(s,void 0,{actions:c,coverage:{...o?{page:o}:{},...s.evidence===`preview`&&n===`threads`?{omitted:[{path:`data.items.messages`,reason:`summary`}]}:{}}})}function tD(e){let t=WE(e),n=e.positionals[0];if(n===`ack`)return YE(e,t,`review`);if(e.values.sections!==void 0)return XE(e,t,n);if(n!==`list`&&n!==`read`)throw new J({code:`E_ARGUMENT_INVALID`,message:`Expected list, read or ack.`});let r=GE(e),i=n===`read`?`threads`:HE(e,`section`),a=HE(e,`thread`);if(n===`read`&&!a)throw new J({code:`E_ARGUMENT_INVALID`,message:`read requires --thread.`});if(i&&![`threads`,`asks`,`groups`,`rounds`].includes(i))throw new J({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 J({code:`E_ARGUMENT_INVALID`,message:`Select --section before detail, fields, cursor or filters.`});let o=Object.fromEntries([[`status`,HE(e,`status`)],[`waitingOn`,HE(e,`waiting-on`)],[`kind`,HE(e,`kind`)],[`choiceState`,HE(e,`choice-state`)]].filter(([,e])=>e!==void 0)),s=mE({...r,section:i,filters:o});if(s)throw new J({code:`E_ARGUMENT_INVALID`,message:s});return Q({id:`comment.${n}`,mode:`finite`,output:{detail:!0,formats:UE,collection:`items`,requiredFields:i?dE[i]:[],fields:i?[...uE[i]]:[]},async run(s,c){let l=await qE(e,c,t,`review`,{op:n,...r,...i?{section:i}:{},...a?{thread:a,detail:!0}:{},...Object.keys(o).length?{filters:o}:{}});return eD(e,t,i,l,r,a)},present:t=>BE(t,n===`read`?`Comment read`:`Comment list`,r.all||!!HE(e,`status`)&&(i!==`asks`||HE(e,`status`)!==`submitted`)||!!HE(e,`choice-state`))},e)}function nD(e){let t=WE(e,!0),n=e.positionals[0];if(n===`ack`)return YE(e,t,`changes`);if(n)throw new J({code:`E_ARGUMENT_INVALID`,message:`Expected changes or changes ack.`});let r=GE(e),i=HE(e,`save`);if(i!==void 0&&!i.trim())throw new J({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});if(r.detail&&(r.fields||r.cursor||r.limit!==void 0))throw new J({code:`E_OPTION_CONFLICT`,message:`A complete diff cannot use --limit, --cursor or --fields.`});return Q({id:`changes`,mode:`finite`,output:{detail:!0,formats:i?[`brief`,`json`,`jsonl`]:UE,fields:[`artifact`,`snapshot`,`blocks`,`diff`,`empty`]},async run(n,a){let{page:o,schema:s,...c}=await qE(e,a,t,`changes`,{op:`read`,...r}),l=c;if(i&&l.empty!==!0&&typeof l.diff!=`string`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return complete diff evidence; no export was written.`});if(i){let e=hE(i,l.diff??``,a.effects);l.saved=e.file,l.bytes=e.bytes,delete l.diff}let u=JE(e,t),d=l.receipt?[lw([`changes`,`ack`,...u,`--receipt`,l.receipt],`Acknowledge`)]:l.empty?[]:[lw([`changes`,...u,`--snapshot`,l.snapshot,...r.all?[`--all`]:[],`--detail`],`Read`)];return o?.nextCursor&&d.push(lw([`changes`,...u,...r.all?[`--all`]:[],...Object.entries({fields:HE(e,`fields`),limit:HE(e,`limit`)}).flatMap(([e,t])=>t?[`--${e}`,t]:[]),`--cursor`,o.nextCursor],`More`)),Y(l,void 0,{actions:d,coverage:{...o?{page:o}:{},...!r.detail&&!l.empty?{omitted:[{path:`data.diff`,reason:`summary`}]}:{}}})},present:QE},e)}const rD={semantic:nD,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`}}};function iD(e){let t=e=>!!e&&typeof e==`object`&&!Array.isArray(e),n=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`);if(!t(e)||!n(e.warnings)||!t(e.evidence)||typeof e.evidence.required!=`boolean`||typeof e.evidence.fresh!=`boolean`||e.evidence.observed!==void 0&&typeof e.evidence.observed!=`boolean`||e.pending!==void 0&&!n(e.pending)||e.provenance!==void 0&&!n(e.provenance)||e.modules!==void 0&&!n(e.modules)||e.checkedAt!==void 0&&typeof e.checkedAt!=`string`||e.structure!==void 0&&typeof e.structure!=`number`||e.unvisited!==void 0&&!(Array.isArray(e.unvisited)&&e.unvisited.every(e=>t(e)&&typeof e.page==`string`&&n(e.boards)))||e.sheet!==void 0&&e.sheet!==null&&(!t(e.sheet)||typeof e.sheet.version!=`number`||!n(e.sheet.files)||e.sheet.unavailable!==void 0&&typeof e.sheet.unavailable!=`string`)||e.diagnostics!==void 0&&!(Array.isArray(e.diagnostics)&&e.diagnostics.every(e=>t(e)&&typeof e.code==`string`&&typeof e.message==`string`&&(e.location===void 0||typeof e.location==`string`)&&(e.severity===`error`||e.severity===`warning`))))return!1;for(let t of[`ran`,`merging`])if(e[t]!==void 0&&typeof e[t]!=`boolean`)return!1;return!(e.dynamic!==void 0&&(!t(e.dynamic)||Object.values(e.dynamic).some(e=>!t(e)||e.ran!==void 0&&typeof e.ran!=`boolean`))||e.recordings!==void 0&&(!t(e.recordings)||Object.values(e.recordings).some(e=>!t(e)||[`status`,`warning`].some(t=>e[t]!==void 0&&typeof e[t]!=`string`))))}const aD=/* @__PURE__ */ new Set([`W_PROVENANCE`,`W_MODULES`,`W_HUMAN_EDIT_OVERWRITTEN`,`W_BOARD_CLIPPED`]);function oD(e,t){let n=(t.warnings??[]).map(e=>({code:`W_ARTIFACT`,severity:`warning`,message:e}));n.push(...t.diagnostics??[]);for(let e of t.provenance??[])n.push({code:`W_PROVENANCE`,severity:`warning`,message:e});for(let e of t.modules??[])n.push({code:`W_MODULES`,severity:`warning`,message:e});let r=[...t.pending??[]];t.merging&&r.push(`merging`);for(let[e,i]of Object.entries(t.recordings??{}))i.warning&&n.push({code:`W_RECORDING`,severity:`warning`,message:i.warning,location:e}),i.status===`processing`&&r.push(`recording:${e}`);let i=Object.entries(t.dynamic??{}),a=t.evidence?.required??(e.startsWith(`html/`)||e.startsWith(`artboard/`)||i.length>0),o=t.evidence?.observed===!1||t.ran===!1||i.some(([,e])=>e.ran===!1);a&&o&&r.push(`browser_not_run`);let s=t.evidence?.observed??(t.ran===!0||i.length>0&&i.every(([,e])=>e.ran===!0)),c=a?o?`not_run`:s&&t.evidence?.fresh===!0?`clean`:`unknown`:`not_required`,l=n.filter(e=>!aD.has(e.code)),u=l.length?`issues`:r.length?`pending`:c===`unknown`||t.evidence?.fresh===!1?`unknown`:`clean`;return Y({artifact:e,status:u,static:l.length?`issues`:`clean`,runtime:c,issues:n,pending:r,...t.sheet?.unavailable?{sheetUnavailable:t.sheet.unavailable}:t.sheet?{sheet:t.sheet.files}:{},...t.structure?{structure:t.structure}:{},...t.unvisited?.length?{unvisited:t.unvisited}:{},evidence:t},u===`issues`?{kind:`validation_failed`}:u===`pending`||u===`unknown`?{kind:`pending`,reasons:r.length?r:[`evidence_unknown`]}:{kind:`succeeded`})}async function sD(e,t,n){if(!e.artifact||!ue.test(e.artifact))throw new M(de);let r=await ET(e.projectDir).call(`POST`,`/api/agent/${e.artifact}/check${e.page?`?page=${encodeURIComponent(e.page)}`:``}`,void 0,t);n?.(r.raw);let{status:i,json:a}=r;if(i<200||i>=300)throw new M(a?.error||`HTTP ${i}`);if(!iD(a))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned invalid check evidence; validation could not be established.`});return{...r,json:a}}function cD(e,t,n){return ET(e).call(`POST`,`/api/cloud/checked/${t}`,void 0,n).catch(()=>null)}const lD={name:`check`,summary:`Wait until the server has checked the latest write, then print its warnings (needs a running server)`,usage:[`--artifact <type>/<id> [options]`],options:{artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to check`},page:{type:`string`,value:`<page-id>`,help:`Whiteboards: check only this page and the board-wide warnings`}},semantic:e=>Q({id:`check`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`raw`,`quiet`],fields:[`artifact`,`file`,`status`,`static`,`runtime`,`issues`,`pending`,`sheet`,`sheetUnavailable`,`structure`,`unvisited`,`evidence`],scalar:e=>e.status},async run(t,n){let r=await sD({projectDir:e.projectDir,artifact:e.values.artifact,page:e.values.page},n.signal,e=>{n.payloads.raw=e});n.payloads.raw=r.raw;let i=oD(e.values.artifact,r.json);return i.data.status===`clean`&&await cD(e.projectDir,i.data.artifact,n.signal),i.data.file=hC(e.projectDir,i.data.artifact).write,i.actions=[lw([`check`,`--artifact`,i.data.artifact,...e.values.page?[`--page`,e.values.page]:[],`--project-dir`,e.projectDir,`--detail`])],i},present:uD},e)};function uD({data:e}){let t=e.issues.length;return{heading:`Check`,status:e.status,subject:e.artifact,summary:t?`${t} issue${t===1?``:`s`}`:``,facts:[...t&&e.file?[Z(`File`,{key:`file`,value:e.file})]:[],...e.runtime===`not_run`||e.runtime===`unknown`?[Z(`Browser`,{key:`runtime`,value:e.runtime.replaceAll(`_`,` `)})]:[],...e.pending.length?[Z(`Pending`,{key:`pending`,value:e.pending.join(`, `)})]:[],...e.unvisited?.length?[Z(`Show`,{key:`unvisited`,value:`${e.unvisited.map(({page:e,boards:t})=>`page ${e}: ${t.join(`, `)}`).join(` · `)}. Open the artboard in a browser, bring these boards into view, then check again; with agent-browser installed (see adeck doctor) Check loads them itself`})]:[],...e.sheet?.length?[Z(`Sheet`,{key:`sheet`,value:e.sheet.join(`, `)})]:e.sheetUnavailable?[Z(`Sheet`,{key:`sheetUnavailable`,value:`unavailable (${e.sheetUnavailable})`})]:[],...e.structure?[Z(`Structure`,{key:`structure`,value:`${e.structure} change${e.structure===1?``:`s`} by your human partner since you last read — run changes --artifact ${e.artifact}`})]:[]],sections:[{kind:`diagnostics`,key:`issues`,items:e.issues,preview:3}]}}const dD={reject:0,pending:1,pass:2,checked:3},fD={reject:`rejected`,pending:`pending`,pass:`passed`,checked:`checked by agent`},pD=(e,t)=>e?`${e} ${t}`:``,mD=e=>e.filter(Boolean).join(` · `),hD=(e,t=!1)=>({key:e,positional:!0,required:t});function gD({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=mD([pD(t.needYou,`on your human partner`),pD(t.notVerified,`not verified`),pD(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?[Z(`Waiting`,{key:`waiting`,value:i})]:[],sections:[{kind:`records`,key:`claims`,title:`Claims`,summary:mD([pD(n(`reject`),`rejected`),pD(n(`pending`),`pending`),pD(n(`pass`),`passed`),pD(n(`checked`),`checked by agent`)]),columns:[hD(`id`,!0),hD(`line`,!0),hD(`rejects`),{key:`evidenceUpdated`,label:`evidence updated`},hD(`origin`),hD(`tail`)],rows:[...e.claims].sort((e,t)=>dD[e.state]-dD[t.state]).map(e=>({...e,line:fD[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:[hD(`id`,!0),hD(`state`,!0)],rows:e.rows.map(e=>({...e,id:`${e.artboard}/${e.group}`}))}]:[],...e.gaps.length?[{kind:`records`,key:`gaps`,title:`Not verified`,summary:mD([pD(e.gaps.filter(e=>!e.waived).length,`open`),pD(e.gaps.filter(e=>e.waived).length,`waived`)]),columns:[hD(`id`,!0),hD(`line`,!0),hD(`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:mD([pD(r.length,`open`),pD(e.threads.length-r.length,`resolved`)]),groups:e.threads.map(e=>({facts:[{...Z(`Thread`,{key:`id`,value:e.id},!0),positional:!0},Z(`On`,{key:`anchor`,value:e.anchor.claim?`claim ${e.anchor.claim}`:`gap ${e.anchor.gap}`},!0),Z(`Verdict`,{key:`verdict`,value:e.anchor.verdict??(e.anchor.waive?`waived`:``)}),Z(`Status`,{key:`status`,value:e.status},!0),...e.stale?[Z(`Stale`,{key:`stale`,value:!0})]:[]],messages:e.messages.map(e=>({facts:[{...Z(`Author`,{key:`author`,value:e.author},!0),positional:!0},Z(`At`,{key:`at`,value:e.at})],text:e.text}))}))}]:[]]}}function _D(e){let t=e.values.artifact,n=hC(e.projectDir,t);return Q({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=I(process.env),o=await ET(e.projectDir).call(`POST`,`/api/agent/${t}/comments`,{op:`list`,...a?{agent:a}:{}},i.signal);if(o.status<200||o.status>=300)throw new J({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 Y({...s,artifact:t,projectDir:e.projectDir},void 0,{actions:l.length?[{...lw([`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=>({...lw([`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:gD},e)}function vD({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?[Z(`Message`,X(e,`messageId`))]:[],...e.groups?.length?[Z(`Groups`,{key:`groups`,value:e.groups.join(`, `)})]:[]],sections:[]}}function yD(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 bD(e){let t=yD(e),n=t.action;if(t.artifact?.startsWith(`verify/`)&&[`list`,`read`,`ack`].includes(n??``)){if(n!==`list`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`A verify report has no thread receipts: comment list shows every thread.`});return _D(e)}if([`list`,`read`,`ack`].includes(n??``))return tD(e);if([`section`,`sections`,`limit`,`cursor`,`snapshot`,`receipt`,`status`,`waiting-on`,`kind`,`choice-state`].some(t=>e.values[t]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Review query options apply only to list, read and ack.`});return Q({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=wD(t);ET(t.projectDir);let i=n.effects.begin(`comment.${r.action}`,t.thread??t.ask??t.group??t.artifact),a=await TD(t,r,n.signal);if(a.status>=400&&a.status<500&&n.effects.set(i,`failed`),a.status<200||a.status>=300)throw new J({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{action:s,request:c}=r,l={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`},u=s===`pass`&&[o.groups,o.claims].some(e=>Array.isArray(e)&&e.length===0);return u&&n.effects.set(i,`none`),Y({artifact:t.artifact,operation:s,status:u?`unchanged`:l[s],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}:{},...s===`choose`?{board:c.board}:{},...s===`submit`?{submitted:!t.withdraw}:{},...s===`answer`?{choice:c.choice}:{}},void 0,{effects:n.effects.snapshot()})},present:vD},e)}const xD=uC(lC),SD=/* @__PURE__ */ new Set([`pass`,`reject`]);function CD(e,t,n){let r=iC[n];if(r.commentRequest)return r.commentRequest(e,t);if(t===`waive`)throw new M(`comment waive works on verify reports only`);let i=r.commentActions?.[t];if(i)return i(e);if(t===`answer`||t===`note`)throw new M(`comment ${t} works on documents only`);if(t===`choose`||t===`submit`||SD.has(t))throw new M(`comment ${t} works on artboards only`);if(t===`add`)throw new M(`comment add does not work on ${n}`);if(!e.thread)throw new M(`comment ${t} needs --thread <threadId>`);return t===`reply`?{op:`reply`,threadId:e.thread,text:$n(e)}:{op:`resolve`,threadId:e.thread}}function wD(e){let t=Zn.find(t=>t===e.action);if(!t)throw new M(`comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive`);if(!e.artifact||!xD.test(e.artifact))throw new M(`--artifact must be ${dC(lC)}`);let[n,r]=e.artifact.split(`/`);return{action:t,type:n,id:r,request:CD(e,t,n),artifact:e.artifact}}async function TD(e,t,n){let{type:r,id:i,request:a}=t,o=ET(e.projectDir),s=I(process.env);return o.call(`POST`,`/api/agent/${r}/${i}/comments`,{...a,agent:s??`Agent`},n)}const ED={actionOptions:{list:[`limit`,`cursor`,`snapshot`,`status`,`waiting-on`,`kind`,`choice-state`,`thread`],read:[`limit`,`cursor`,`all`,`save`]},semantic:bD,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 ${fC(sC)} --sections all|<names> [--detail] [--all]`,`list --artifact ${fC(sC)} [--section threads|asks|groups|rounds] [--all]`,`read --artifact ${fC(sC)} --thread <threadId> [--snapshot <token>]`,`ack --artifact ${fC(sC)} --receipt <receipt>`,`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 ${fC(lC)} --thread <threadId> [--text <text>]`,`resolve --artifact ${fC(sC)} --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 do not consume evidence. read returns a complete thread and receipt; use ack after applying that evidence. asks, groups and rounds are independent state reads without receipts. 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`},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},DD={on:!0,off:!1,inherit:null};function OD(e,t=()=>{}){let n=NC(Jn(process.env,process.platform,h.default.homedir())),r=f.default.join(f.default.dirname(ce(e.projectDir).root),`config.json`);if(e.autoPublish!==void 0){let i=DD[e.autoPublish];if(i===void 0)throw new M(`--auto-publish takes on, off, or (with --project) inherit`);if(e.project){let e=EC(r);if(e.warning)throw new M(e.warning);t(),kC(r),jC(r,i)}else if(i===null)throw new M(`inherit only applies with --project`);else IC(n,i,t)}return{global:FC(n)??null,project:EC(r).config.autoPublish??null}}const kD={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=>Q({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 M(`Choose auto-publish or output-format.`);let r=e.values.project?`project`:`global`,i=GC(e.projectDir)[r],a,o=()=>{a=n.effects.begin(`config`,i)};typeof e.values[`output-format`]==`string`&&JC(e.projectDir,!!e.values.project,e.values[`output-format`],o);let s=OD({projectDir:e.projectDir,autoPublish:e.values[`auto-publish`],project:!!e.values.project},o);return a!==void 0&&n.effects.confirm(a),Y({scope:r,projectDir:e.projectDir,file:i,...s,output:qC(e.projectDir),effective:s.project??s.global,source:s.project===null?s.global===null?`undecided`:`global`:`project`,applies:`supported_turn_end_hook`})},present:AD},e)};function AD({data:e}){let t=e.effective===null?`undecided`:e.effective?`on`:`off`;return{heading:`Config`,status:``,facts:[Z(`Scope`,{key:`scope`,value:e.scope}),Z(`File`,{key:`file`,value:e.file}),Z(`Auto-publish`,{key:`autoPublish`,value:e.source===`undecided`?t:`${t} (${e.source})`}),Z(`Output format`,{key:`output`,value:`${e.output.effective} (${e.output.source})`})],sections:[]}}function jD(e=process.env,t=h.default.homedir()){if(e.RYUGI_DAEMON_SOCKET)return e.RYUGI_DAEMON_SOCKET;let n=f.default.dirname(qe(e)),{home:r}=He(e,t);if(ht(r,t))return f.default.join(n,`daemon.sock`);let i=f.default.join(r,`daemon.sock`);if(Buffer.byteLength(i)<=103)return i;let a=u.default.createHash(`sha256`).update(r).digest(`hex`).slice(0,16);return f.default.join(n,`daemon-${a}.sock`)}function MD(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(`
|
|
854
|
+
`);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 ND=()=>u.default.randomBytes(24).toString(`base64url`);function PD(e){try{return d.default.readFileSync(e,`utf8`).trim()}catch{return``}}function FD(e){let t=f.default.join(f.default.dirname(e),`host-id`),n=PD(t);if(/^[\w-]{16,64}$/.test(n))return n;let r=ND();return d.default.mkdirSync(f.default.dirname(t),{recursive:!0,mode:448}),d.default.writeFileSync(t,`${r}\n`,{mode:384}),r}async function ID(e,t){let n=He();if(Ue(n.home),!await Xw(n.lock))throw new M(`Another start is still starting the artifacts server; retry in a moment`);try{let r=Zw(n);if(!r&&!t.startStopped)return`not-running`;let i=await Bn(n,e);r&&(O(n,{action:`replaced`,pid:r,running:P(n.version)??``,cli:e,reasons:[t.reason]}),await eT(r,`running artifacts server`)),d.default.rmSync(n.info,{force:!0});let a=u.default.randomBytes(24).toString(`hex`);d.default.writeFileSync(n.serverId,`${a}\n`),d.default.writeFileSync(n.version,`${e}\n`);let o=Mn(n),s=o?.env.ARTIFACTS_HOST||`127.0.0.1`,c=o?.env.ARTIFACTS_URL_HOST||`localhost`,l=await Gn(n,i,{args:o?Fn(o,a).args:kn(a),env:An(s,c)},`${le()} start --host ${s} --url-host ${c} --foreground`);if(`failed`in l)throw new M(String(l.failed.error??`Server failed`));return r?`restarted`:`started`}finally{try{d.default.rmdirSync(n.lock)}catch{}}}const LD=e=>({binary:f.default.join(e,`.ryugi`,`bin`,`ryugi-daemon`)});async function RD(e,t){if(!ht(e.serverHome,e.home))return{status:`other-hub`};let n=vt(e);if(!d.default.existsSync(n))return{status:`not-installed`};let r=yt(n);if(bt(r,e))return{status:`current`};let i=await xt(e);return t?.(),st(n,i),{status:`updated`,from:r?.version??`unknown`,to:e.version}}const zD=`session control runs on macOS and Linux`,BD=(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 VD(e){if(e.platform!==`darwin`&&e.platform!==`linux`)throw new M(zD);if(!ht(e.serverHome,e.home))return null;let t=Lt(e);if(!t)throw new M(zD);let n=t.check();if(n)throw new M(`${n}; session control needs systemd on Linux`);return t}const HD=(e,t,n)=>({autostart:n,binary:t,launch:e.launch,log:e.log,path:e.path});async function UD(e,t){let n=VD(e),r;t.binary?(r=vt(e),st(r,d.default.readFileSync(t.binary))):r=await e.ensureBinary().catch(e=>{throw new M(e.message)}),En(e.serverHome,!0);let i=n?.write(HD(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 WD(e){let t=VD(e);En(e.serverHome,!1);let n=vt(e),r=null;return t&&d.default.existsSync(t.file(!0))&&(r=t.write(HD(e,n,!1)),t.disable()),await e.restartHub(!1),{service:r}}async function GD(e){let{cloud:t}=e;try{await e.daemon.call(`status`,{})}catch{throw new M(`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 M(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 KD(e,t,n,r=LD(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 M(`no daemon session is running`):n?new M(`no running daemon session ${n}`):new M(`several daemon sessions are running; name one:\n${i.map(e=>` ${e.taskId} ${e.artifact}`).join(`
|
|
855
|
+
`)}`);return[r,`attach`,a.attach]}const qD=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],JD=()=>ie(process.env),YD=()=>process.env.RYUGI_ARTIFACTS_VERSION||`1.114.0`;function XD(){let e=He();return{configHome:process.env.XDG_CONFIG_HOME||void 0,ensureBinary:()=>Bn(e,YD()),home:h.default.homedir(),launch:On(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,restartHub:e=>ID(YD(),{reason:`session-control`,startStopped:e}),run:In,serverHome:e.home,uid:process.getuid?.()??0}}function ZD(){let e=Jn(process.env,process.platform,h.default.homedir()),t=JD(),n=qn(e,t);if(!n)throw new M(`sign in to Artideck Cloud (${t}) on this computer first`);return{origin:t,token:n.token,hostId:FD(e)}}const QD=()=>MD(jD());async function $D(e){try{return await e()}catch(e){let t=e.code;throw t===`ENOENT`||t===`ECONNREFUSED`?new M(`the daemon is not running; install it with: adeck daemon install`):new M(e.message)}}async function eO(){return(await $D(()=>QD().call(`sessions.local`,{}))).sessions}async function tO(e){let[t,n,r]=e.positionals;if(!t||!qD.includes(t))throw new M(`usage: adeck daemon ${qD.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await UD(XD(),{binary:e.values.binary});return i(`installed`,[`session control on`,`binary ${t.binary}`,...t.service?[`${t.kind.padEnd(8)}${t.service}`]:[],...t.linger?[BD(t.linger,h.default.userInfo().username)]:[]])}case`uninstall`:{let e=await WD(XD());return i(`removed`,[`session control off`,...e.service?[`service ${e.service}`]:[]])}case`status`:{let e=await $D(()=>QD().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 M(`usage: adeck daemon trust <code>`);let t=await GD({code:n,cloud:ZD(),daemon:QD(),fetch,label:e.values.label});return i(`trusted`,[`${t.deviceId} ${t.label}`])}case`devices`:{if(n===`revoke`){if(!r)throw new M(`usage: adeck daemon devices revoke <device-id>`);let e=ZD(),t=await fetch(`${e.origin}/api/devices/${encodeURIComponent(r)}`,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok&&t.status!==404)throw new M(`Cloud refused the revoke: HTTP ${t.status}`);return await $D(()=>QD().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await $D(()=>QD().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 M(`usage: adeck daemon remote on|off`);return await $D(()=>QD().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await eO();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]=KD(h.default.homedir(),await eO(),n,process.env.RYUGI_DAEMON_BIN||void 0);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
|
|
856
|
+
`),i((0,p.spawnSync)(e,t,{stdio:`inherit`}).status===0?`detached`:`failed`,[])}}}function nO({data:e}){return{heading:`Daemon`,status:e.status,summary:``,facts:[],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
|
|
857
|
+
`)}]:[]}}const rO={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 (ryugi-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 ryugi-daemon build instead of downloading one`},label:{type:`string`,value:`<name>`,help:`Name for the trusted device`}},semantic:e=>Q({id:`daemon`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},async run(){let t=await tO(e);return Y(t,t.status===`failed`?{kind:`failed`,error:{code:`E_DAEMON`,message:`daemon ${t.action} failed`}}:{kind:`succeeded`})},present:nO},e)};function iO(e,t){try{return d.default.realpathSync(e)===d.default.realpathSync(t)}catch{return f.default.resolve(e)===f.default.resolve(t)}}function aO(e,t){let n=JSON.parse(t(`claude`,[`plugin`,`list`,`--json`]));if(!Array.isArray(n))throw Error(`Claude returned an unknown plugin list`);let r=n.find(t=>t.id===e&&t.scope===`user`);return!r||typeof r.installPath!=`string`?null:{path:r.installPath,source:typeof r.readFromFolder==`string`?r.readFromFolder:r.installPath,version:String(r.version||`unknown`)}}function oO(e,t){let n=aO(e,t);if(!n)throw Error(`Native Claude plugin not found: ${e}`);return n}function sO(e,t){if(!e.nativeSource||!e.registration)return`foreign`;let n=aO(e.registration,t);if(!n)return`missing`;if(iO(n.source,e.nativeSource))return`owned`;let[r,i]=e.registration.split(`@`),a=f.default.dirname(n.path);return n.source===n.path&&f.default.basename(a)===r&&f.default.basename(f.default.dirname(a))===i&&iO(a,f.default.dirname(e.nativeSource))?`owned`:`foreign`}function cO(e,t){let n=e.path;if(e.harness===`claude-code`){let n=sO(e,t);if(n===`missing`)throw Error(`Native Claude plugin not found: ${e.registration}`);return n===`owned`}if(e.harness===`codex`){let e=JSON.parse(t(`codex`,[`plugin`,`list`,`--json`]));return Array.isArray(e.installed)&&e.installed.some(e=>e.pluginId===`ryugi@ryugi-managed`&&typeof e.source?.path==`string`&&iO(e.source.path,n))}if(e.harness===`pi`)return t(`pi`,[`list`]).split(/\r?\n/).some(e=>f.default.isAbsolute(e.trim())&&iO(e.trim(),n));if(e.harness===`gemini`){let e=JSON.parse(t(`gemini`,[`extensions`,`list`,`--output-format`,`json`]));return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.installMetadata?.type===`link`&&typeof e.installMetadata.source==`string`&&iO(e.installMetadata.source,n)&&typeof e.path==`string`&&iO(e.path,n))}if(e.harness===`copilot`){let e=JSON.parse(t(`copilot`,[`plugin`,`list`,`--json`]));return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.marketplace===`ryugi-managed`&&typeof e.installedFrom==`string`&&iO(e.installedFrom,f.default.dirname(n)))}if(e.harness===`agy`){let e=JSON.parse(t(`agy`,[`plugin`,`list`,`--json`])),r=JSON.parse(d.default.readFileSync(f.default.join(n,`.antigravity-plugin/plugin.json`),`utf8`)).version;return Array.isArray(e)&&e.some(e=>e.name===`ryugi`&&e.enabled!==!1&&e.version===r)}return!0}function lO(e,t,n){let r=JSON.parse(n(e,[`plugin`,`marketplace`,`list`,`--json`])),i=e===`codex`?r.marketplaces:r;if(!Array.isArray(i))throw Error(`${e} returned an unknown marketplace list`);return i.some(n=>n.name===`ryugi-managed`&&(e===`codex`?typeof n.root==`string`&&iO(n.root,t):typeof n.source==`string`&&iO(n.source.replace(/^Local:\s*/i,``),t)))}function uO(e,t){let n=JSON.parse(t(e,[`plugin`,`marketplace`,`list`,`--json`])),r=e===`codex`?n.marketplaces:n;if(!Array.isArray(r))throw Error(`${e} returned an unknown marketplace list`);return r.some(e=>e.name===`ryugi-managed`)}function dO(e){let t=(0,u.createHash)(`sha256`);function n(r){for(let i of d.default.readdirSync(r).sort()){let a=f.default.join(r,i),o=d.default.lstatSync(a);if(o.isSymbolicLink())throw Error(`Plugin contains an unexpected symlink: ${a}`);t.update(f.default.relative(e,a)),t.update(o.isDirectory()?`\0dir\0`:`\0file\0`),o.isDirectory()?n(a):t.update(d.default.readFileSync(a))}}return n(e),t.digest(`hex`)}function fO(e,t,n){if(d.default.existsSync(t))throw Error(`Candidate already exists: ${t}`);d.default.mkdirSync(t,{recursive:!0});try{for(let n of[`skills`,`hooks`,`lib`,`assets`,`index.js`,`package.json`,`LICENSE`,`GEMINI.md`,`gemini-extension.json`,`.pi`,`.opencode`,`.antigravity-plugin`,`.claude-plugin`,`.codex-plugin`,`.cursor-plugin`]){let r=f.default.join(e,n);d.default.existsSync(r)&&d.default.cpSync(r,f.default.join(t,n),{recursive:!0,filter(t){let n=f.default.relative(e,t).replaceAll(`\\`,`/`);if(/^skills\/artifacts\/app\/(cli\.cjs|server\.cjs|document-engine\.cjs|document-host\.cjs|loro_wasm_bg\.wasm|ryugi-daemon(\.exe)?|viewer|runtime)(\/|$)/.test(n))return!1;if(d.default.lstatSync(t).isSymbolicLink())throw Error(`Plugin source symlink is not supported: ${t}`);return!0}})}for(let e of[`artifacts`,`interface-craft`,...n===`full`?[`using-ryugi`]:[]])if(!d.default.existsSync(f.default.join(t,`skills`,e,`SKILL.md`)))throw Error(`Incomplete Artideck plugin: missing ${e}`);if(n===`artifacts`){for(let e of d.default.readdirSync(f.default.join(t,`skills`)))[`artifacts`,`interface-craft`].includes(e)||d.default.rmSync(f.default.join(t,`skills`,e),{recursive:!0,force:!0});d.default.writeFileSync(f.default.join(t,`GEMINI.md`),`# Artideck
|
|
858
858
|
Use the artifacts and interface-craft skills when requested.
|
|
859
859
|
`);let e=f.default.join(t,`hooks/session-start`);d.default.existsSync(e)&&(d.default.renameSync(e,`${e}-implementation`),d.default.writeFileSync(e,`#!/usr/bin/env bash
|
|
860
860
|
exec bash "\${0%/*}/session-start-implementation" "$@" > /dev/null
|
|
861
|
-
`,{mode:493}))}let r=f.default.join(t,`package.json`),i=JSON.parse(d.default.readFileSync(r,`utf8`));if(i.name!==`ryugi`||typeof i.version!=`string`)throw Error(`Not an Artideck plugin package`);delete i.scripts,delete i.devDependencies,delete i[`simple-git-hooks`],delete i[`lint-staged`],d.default.writeFileSync(r,JSON.stringify(i,null,2));let a=
|
|
861
|
+
`,{mode:493}))}let r=f.default.join(t,`package.json`),i=JSON.parse(d.default.readFileSync(r,`utf8`));if(i.name!==`ryugi`||typeof i.version!=`string`)throw Error(`Not an Artideck plugin package`);delete i.scripts,delete i.devDependencies,delete i[`simple-git-hooks`],delete i[`lint-staged`],d.default.writeFileSync(r,JSON.stringify(i,null,2));let a=dO(t).slice(0,12);for(let e of[`.codex-plugin/plugin.json`,`.cursor-plugin/plugin.json`,`.antigravity-plugin/plugin.json`,`.claude-plugin/plugin.json`,`gemini-extension.json`]){let r=f.default.join(t,e);if(!d.default.existsSync(r))continue;let o=JSON.parse(d.default.readFileSync(r,`utf8`));o.version=`${i.version}-${n}.${a}`,d.default.writeFileSync(r,JSON.stringify(o,null,2))}return{root:t,mode:n,version:i.version,digest:dO(t)}}catch(e){throw d.default.rmSync(t,{recursive:!0,force:!0}),e}}function pO(e,t,n=process.env.RYUGI_PLUGIN_REPO||`https://github.com/Innei/ryugi.git`){let r=f.default.join(e,`downloads`,(0,u.randomUUID)());d.default.mkdirSync(f.default.dirname(r),{recursive:!0});let i=`v${t}`,a=(0,p.spawnSync)(`git`,[`clone`,`--depth`,`1`,`--branch`,i,`--config`,`advice.detachedHead=false`,n,r],{encoding:`utf8`,timeout:12e4});if(a.error||a.status!==0)throw d.default.rmSync(r,{recursive:!0,force:!0}),Error(`Could not download the Artideck plugin release ${i} that matches this CLI (Git required): ${a.stderr||a.error?.message}`);return r}function mO(e,t,n){let r=/* @__PURE__ */ new Set,i=(n,a=!0)=>{let o=f.default.resolve(e,n),s=f.default.relative(e,o);if(!s||s.startsWith(`..`)||f.default.isAbsolute(s)||!d.default.existsSync(o))throw Error(`Incomplete ${t} plugin: missing or invalid ${n}`);if(r.has(o))return o;if(r.add(o),a&&d.default.statSync(o).isFile()&&/\.(?:[cm]?js|ts)$/.test(o)){let r=d.default.readFileSync(o,`utf8`);for(let a of r.matchAll(/(?:require\(\s*|from\s*)['"](\.{1,2}\/[^'"]+)['"]/g)){let r=f.default.resolve(f.default.dirname(o),a[1]),s=[r,`${r}.cjs`,`${r}.js`,`${r}.json`].find(e=>d.default.existsSync(e)&&d.default.statSync(e).isFile());if(!s)throw Error(`Incomplete ${t} plugin: missing dependency ${a[1]} from ${n}`);i(f.default.relative(e,s))}}return o},a=e=>JSON.parse(d.default.readFileSync(i(e,!1),`utf8`));for(let e of[`artifacts`,`interface-craft`,...n===`full`?[`using-ryugi`,`brainstorming`,`executing-specs`,`systematic-debugging`,`test-driven-development`,`using-git-worktrees`,`verifying`]:[]])i(`skills/${e}/SKILL.md`,!1);if(i(`skills/artifacts/app/ryugi.cjs`),i(`skills/artifacts/app/output-bootstrap.cjs`),t===`pi`){let e=a(`package.json`);if(!Array.isArray(e.pi?.extensions)||!e.pi.extensions.length)throw Error(`Incomplete pi plugin: missing native extension declaration`);for(let t of e.pi.extensions)i(t);i(`.pi/extensions/ryugi.ts`)}if((t===`codex`||t===`agy`)&&i(`skills/artifacts/app/hook-bin.sh`,!1),t===`codex`||t===`cursor`){let e=a(`.${t}-plugin/plugin.json`);if(typeof e.hooks!=`string`)throw Error(`Incomplete ${t} plugin: missing native hooks declaration`);let n=a(e.hooks),r=e=>{if(Array.isArray(e))e.forEach(r);else if(e&&typeof e==`object`)Object.values(e).forEach(r);else if(typeof e==`string`){for(let t of e.matchAll(/\$\{(?:PLUGIN_ROOT|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}\/([^\s"']+)/g))i(t[1]);e.startsWith(`./hooks/`)&&i(e.split(/\s/)[0])}};r(n),t===`cursor`&&(i(`hooks/run-hook.cmd`,!1),i(`hooks/session-start`,!1))}if(t===`gemini`&&i(a(`gemini-extension.json`).contextFileName||`GEMINI.md`,!1),t===`opencode`&&i(`.opencode/plugins/ryugi.js`),t===`copilot`&&a(`.claude-plugin/plugin.json`),t===`agy`){a(`.antigravity-plugin/plugin.json`),a(`hooks/hooks-antigravity.json`);for(let e of[`run-hook.cmd`,`session-start`,`user-prompt-submit`,`stop`,`agent-event`,`project-root.sh`])i(`hooks/${e}`,!1)}}const hO=[{id:`claude-code`,command:`claude`,label:`Claude Code`,comments:`native monitor`},{id:`codex`,command:`codex`,label:`Codex`,comments:`native hooks; trust them in Codex Settings → Hooks`},{id:`cursor`,command:`cursor`,label:`Cursor`,comments:`read comments on request`},{id:`gemini`,command:`gemini`,label:`Gemini CLI`,comments:`read comments on request`},{id:`opencode`,command:`opencode`,label:`OpenCode`,comments:`read comments on request`},{id:`pi`,command:`pi`,label:`Pi`,comments:`native extension`},{id:`copilot`,command:`copilot`,label:`GitHub Copilot CLI`,comments:`read comments on request`},{id:`agy`,command:`agy`,label:`Antigravity`,comments:`native hooks + LS watch`}],gO=(e,t,n=9e4)=>{if(process.platform===`win32`&&[e,...t].some(e=>/["%\r\n&|<>^]/.test(e)))throw Error(`Unsupported character in Windows native command argument`);let r=process.platform===`win32`?(0,p.spawnSync)([e,...t].map(e=>`"${e}"`).join(` `),{shell:!0,encoding:`utf8`,timeout:n,stdio:[`ignore`,`pipe`,`pipe`]}):(0,p.spawnSync)(e,t,{encoding:`utf8`,timeout:n,stdio:[`ignore`,`pipe`,`pipe`]});if(r.error||r.status!==0)throw Error(`${e} ${t.join(` `)} failed: ${(r.stderr||r.stdout||r.error?.message||``).trim()}`);return r.stdout};function _O(e=h.default.homedir(),t=gO){return hO.map(n=>{let r=!1;try{t(n.command,[`--version`],2e3),r=!0}catch{}return n.id===`cursor`&&d.default.existsSync(f.default.join(e,`.cursor`))&&(r=!0),{...n,detected:r,reason:r?null:`${n.command} not found on PATH`}})}const vO=e=>{try{return d.default.lstatSync(e),!0}catch{return!1}};function yO(e,t){return e===`cursor`?f.default.join(t.home||h.default.homedir(),`.cursor/plugins/local/ryugi`):f.default.join(t.root,`plugins`,e,`plugin`)}function bO(e,t){if(f.default.resolve(e.path)!==f.default.resolve(t))throw Error(`Installation path no longer matches owned ${e.harness} path`);if(!d.default.existsSync(e.path)||dO(e.path)!==e.digest)throw Error(`Installed ${e.harness} files changed; preserving user edits at ${e.path}`)}function xO(e,t,n){mO(t.root,e,t.mode);let r=yO(e,n),i=n.previous,a=n.run||gO,o=n.env||process.env,s=n.home||h.default.homedir();if(vO(r)){if(!i)throw Error(`Plugin already exists and is not owned by this installer: ${r}`);bO(i,r)}else if(i)throw Error(`Owned plugin is missing at ${r}; run doctor before reinstalling`);if(!i&&[`codex`,`gemini`,`pi`,`copilot`,`agy`].includes(e)){let t=e===`codex`?[`plugin`,`list`,`--json`]:e===`gemini`?[`extensions`,`list`]:e===`pi`?[`list`]:e===`agy`?[`plugin`,`list`,`--json`]:[`plugin`,`list`];if(/\bryugi\b/i.test(a(hO.find(t=>t.id===e).command,t)))throw Error(`An existing Artideck ${e} install is managed elsewhere. Remove it with that harness before installing here.`)}if(i&&!cO(i,a))throw Error(`Native ${e} source changed or is no longer registered; preserving it`);if(!i&&(e===`codex`||e===`copilot`)&&uO(e,a))throw Error(`Native ${e} marketplace ryugi-managed is owned elsewhere`);let c=f.default.dirname(r);d.default.mkdirSync(c,{recursive:!0});let l=f.default.join(c,`.candidate-${(0,u.randomUUID)()}`),p=f.default.join(c,`.previous-${(0,u.randomUUID)()}`);d.default.cpSync(t.root,l,{recursive:!0});let m=i?.registration,g=!1,_=!1,y=(e,t,r,i)=>{let o=n.effects?.begin(e,i),s=a(t,r);return o!==void 0&&n.effects.confirm(o),s};try{if(vO(r)&&(d.default.renameSync(r,p),g=!0),d.default.renameSync(l,r),e===`copilot`){d.default.mkdirSync(f.default.join(r,`hooks`),{recursive:!0});let e=f.default.join(r,`hooks/managed-bootstrap.cjs`);d.default.writeFileSync(e,`const fs = require('node:fs');
|
|
862
862
|
const path = require('node:path');
|
|
863
863
|
const skill = path.join(__dirname, '../skills/using-ryugi/SKILL.md');
|
|
864
864
|
console.log(JSON.stringify(fs.existsSync(skill) ? { additionalContext: fs.readFileSync(skill, 'utf8') } : {}));
|
|
865
|
-
`),d.default.writeFileSync(f.default.join(r,`hooks/hooks.json`),JSON.stringify({version:1,hooks:{sessionStart:[{type:`command`,exec:`node`,args:[e]}]}}))}if(e===`codex`||e===`copilot`){let t=f.default.dirname(r),n=e===`codex`?`.agents/plugins/marketplace.json`:`.claude-plugin/marketplace.json`,a=f.default.join(t,n);d.default.mkdirSync(f.default.dirname(a),{recursive:!0}),d.default.writeFileSync(a,JSON.stringify({name:`ryugi-managed`,owner:{name:`Innei`},plugins:[{name:`ryugi`,source:e===`codex`?{source:`local`,path:`./plugin`}:`./plugin`,policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`}}]})),i||(y(`install.native-marketplace`,e,[`plugin`,`marketplace`,`add`,t],t),_=!0),y(`install.native-plugin`,e,[`plugin`,e===`codex`?`add`:`install`,`ryugi@ryugi-managed`],`ryugi@ryugi-managed`),m=`ryugi@ryugi-managed`}else if(e===`pi`)i||y(`install.native-package`,`pi`,[`install`,r],r),m=r;else if(e===`gemini`)i||y(`install.native-extension`,`gemini`,[`extensions`,`link`,r,`--consent`],r),m=`ryugi`;else if(e===`agy`){d.default.copyFileSync(f.default.join(r,`hooks/hooks-antigravity.json`),f.default.join(r,`hooks.json`)),t.mode===`artifacts`&&
|
|
865
|
+
`),d.default.writeFileSync(f.default.join(r,`hooks/hooks.json`),JSON.stringify({version:1,hooks:{sessionStart:[{type:`command`,exec:`node`,args:[e]}]}}))}if(e===`codex`||e===`copilot`){let t=f.default.dirname(r),n=e===`codex`?`.agents/plugins/marketplace.json`:`.claude-plugin/marketplace.json`,a=f.default.join(t,n);d.default.mkdirSync(f.default.dirname(a),{recursive:!0}),d.default.writeFileSync(a,JSON.stringify({name:`ryugi-managed`,owner:{name:`Innei`},plugins:[{name:`ryugi`,source:e===`codex`?{source:`local`,path:`./plugin`}:`./plugin`,policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`}}]})),i||(y(`install.native-marketplace`,e,[`plugin`,`marketplace`,`add`,t],t),_=!0),y(`install.native-plugin`,e,[`plugin`,e===`codex`?`add`:`install`,`ryugi@ryugi-managed`],`ryugi@ryugi-managed`),m=`ryugi@ryugi-managed`}else if(e===`pi`)i||y(`install.native-package`,`pi`,[`install`,r],r),m=r;else if(e===`gemini`)i||y(`install.native-extension`,`gemini`,[`extensions`,`link`,r,`--consent`],r),m=`ryugi`;else if(e===`agy`){d.default.copyFileSync(f.default.join(r,`hooks/hooks-antigravity.json`),f.default.join(r,`hooks.json`)),t.mode===`artifacts`&&vO(f.default.join(r,`hooks/session-start-implementation`))&&d.default.writeFileSync(f.default.join(r,`hooks/session-start`),`#!/usr/bin/env bash
|
|
866
866
|
bash "\${0%/*}/session-start-implementation" "$@" > /dev/null
|
|
867
867
|
printf "{}\\n"
|
|
868
|
-
`,{mode:493});for(let e of[`hooks/hooks.json`,`hooks/hooks-cursor.json`,`hooks/hooks-antigravity.json`,`GEMINI.md`,`gemini-extension.json`,`AGENTS.md`])d.default.rmSync(f.default.join(r,e),{recursive:!0,force:!0});y(`install.native-plugin`,`agy`,[`plugin`,`install`,r],r),m=`ryugi`}else if(e===`opencode`){let e=f.default.join(o.XDG_CONFIG_HOME||f.default.join(s,`.config`),`opencode/plugins/ryugi.js`),t=`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(f.default.join(r,`.opencode/plugins/ryugi.js`)).href)};\n`;if(
|
|
868
|
+
`,{mode:493});for(let e of[`hooks/hooks.json`,`hooks/hooks-cursor.json`,`hooks/hooks-antigravity.json`,`GEMINI.md`,`gemini-extension.json`,`AGENTS.md`])d.default.rmSync(f.default.join(r,e),{recursive:!0,force:!0});y(`install.native-plugin`,`agy`,[`plugin`,`install`,r],r),m=`ryugi`}else if(e===`opencode`){let e=f.default.join(o.XDG_CONFIG_HOME||f.default.join(s,`.config`),`opencode/plugins/ryugi.js`),t=`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(f.default.join(r,`.opencode/plugins/ryugi.js`)).href)};\n`;if(vO(e)&&(!i||d.default.readFileSync(e,`utf8`)!==t))throw Error(`OpenCode plugin entry is not owned: ${e}`);d.default.mkdirSync(f.default.dirname(e),{recursive:!0}),d.default.writeFileSync(e,t),m=e}let n={harness:e,mode:t.mode,path:r,digest:dO(r),version:t.version,registration:m};if(!cO(n,a))throw Error(`Native ${e} did not recognize the installed source`);return n}catch(t){if(_&&(e===`codex`||e===`copilot`))try{if(!lO(e,c,a))throw Error(`Marketplace source no longer matches`,{cause:t});y(`install.native-marketplace-remove`,e,[`plugin`,`marketplace`,`remove`,`ryugi-managed`],c)}catch(e){throw Error(`${t.message}; marketplace registration remains and its candidate is retained at ${r}: ${e.message}`,{cause:e})}throw d.default.rmSync(r,{recursive:!0,force:!0}),g&&d.default.renameSync(p,r),t}finally{d.default.rmSync(l,{recursive:!0,force:!0}),vO(r)&&d.default.rmSync(p,{recursive:!0,force:!0})}}const SO=`artideck`,CO=`ryugi-artifacts`,wO=[SO,CO],TO=[`npm`,`pnpm`,`yarn`,`bun`],EO=[[`npx`,[`/_npx/`]],[`pnpm dlx`,[`/pnpm/dlx/`,`/.pnpm-store/dlx/`]],[`bunx`,[`/bunx-`,`/.bun/install/cache/`]]],DO=[[`pnpm`,[`/pnpm/global/`]],[`yarn`,[`/yarn/global/`]],[`bun`,[`/.bun/install/global/`]],[`npm`,wO.flatMap(e=>[`/lib/node_modules/${e}/`,`/npm/node_modules/${e}/`])]];function OO(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/node_modules/ryugi-artifacts/`)||t.includes(`/ryugi-artifacts@`)?CO:SO}function kO(e,t){if(t.RYUGI_MANAGED_RUNTIME===`1`&&t.RYUGI_INSTALL_ROOT){let n=f.default.relative(f.default.join(t.RYUGI_INSTALL_ROOT,`versions`),e);if(n&&!n.startsWith(`..`)&&!f.default.isAbsolute(n))return{kind:`managed`}}if(t.RYUGI_ARTIFACTS_COMMAND)return{kind:`launcher`};let n=e;try{n=d.default.realpathSync(e)}catch{}let r=n.replaceAll(`\\`,`/`).toLowerCase(),i=e=>e.some(e=>r.includes(e));for(let[e,t]of EO)if(i(t))return{kind:`transient`,runner:e};for(let[e,t]of DO)if(i(t))return{kind:`global`,pm:e};return r.includes(`/node_modules/`)?{kind:`unknown`}:{kind:`local`}}const AO=(e=process.env)=>e.RYUGI_INSTALL_ROOT||f.default.join(e.XDG_DATA_HOME||f.default.join(h.default.homedir(),`.local/share`),`ryugi`,`install`),jO=(e=process.env)=>e.RYUGI_BIN_DIR||f.default.join(h.default.homedir(),`.local/bin`);function MO(e,t){d.default.mkdirSync(f.default.dirname(e),{recursive:!0});let n=`${e}.${(0,u.randomUUID)()}.tmp`;try{d.default.writeFileSync(n,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`}),d.default.renameSync(n,e)}finally{d.default.rmSync(n,{force:!0})}}const NO=[`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`],PO=e=>(0,u.createHash)(`sha256`).update(e).digest(`hex`);function FO(e){let t=(0,u.createHash)(`sha256`);function n(r){let i=f.default.join(e,r);if(t.update(r).update(`\0`),d.default.statSync(i).isDirectory())for(let e of d.default.readdirSync(i).sort())n(f.default.join(r,e));else t.update(d.default.readFileSync(i))}for(let e of[`bin`,`dist`,`package.json`])n(e);return t.digest(`hex`)}var IO=class{root;binDir;constructor(e=AO(),t=jO()){this.root=f.default.resolve(e),this.binDir=f.default.resolve(t)}get launcher(){return f.default.join(this.root,`launcher.cjs`)}get bin(){return f.default.join(this.binDir,process.platform===`win32`?`ryugi.cmd`:`ryugi`)}get aliasBin(){return f.default.join(this.binDir,process.platform===`win32`?`adeck.cmd`:`adeck`)}launcherSource(){return`#!/usr/bin/env node
|
|
869
869
|
// Ryugi managed runtime launcher v1
|
|
870
870
|
const fs = require('node:fs');
|
|
871
871
|
const path = require('node:path');
|
|
@@ -878,80 +878,80 @@ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw E
|
|
|
878
878
|
process.env.RYUGI_INSTALL_ROOT = root;
|
|
879
879
|
process.env.RYUGI_MANAGED_RUNTIME = '1';
|
|
880
880
|
require(path.join(current.packageRoot, 'dist/cli.cjs'));
|
|
881
|
-
`}shimSource(){return`@echo off\r\nnode "${this.launcher}" %*\r\n`}owns(e){try{return process.platform===`win32`?d.default.readFileSync(e,`utf8`)===this.shimSource():d.default.lstatSync(e).isSymbolicLink()&&d.default.realpathSync(e)===d.default.realpathSync(this.launcher)}catch{return!1}}ownsBin(){return this.owns(this.bin)}ownsAlias(){return this.owns(this.aliasBin)}linkAlias(){if(!this.ownsAlias())try{process.platform===`win32`?d.default.writeFileSync(this.aliasBin,this.shimSource(),{flag:`wx`}):d.default.symlinkSync(this.launcher,this.aliasBin)}catch{}}preflight(){let e=!1;try{d.default.lstatSync(this.bin),e=!0}catch(e){if(e.code!==`ENOENT`)throw e}if(e&&!this.ownsBin())throw Error(`Command already exists at ${this.bin}; choose --bin-dir or keep its original package manager.`);if(d.default.existsSync(this.launcher)){let e=d.default.readFileSync(this.launcher,`utf8`);if(e!==this.launcherSource()&&NO(e)!==this.current()?.launcherDigest)throw Error(`Foreign launcher already exists at ${this.launcher}`)}}current(){let e=f.default.join(this.root,`current.json`);if(!d.default.existsSync(e))return null;let t=JSON.parse(d.default.readFileSync(e,`utf8`)),n=f.default.relative(d.default.realpathSync(f.default.join(this.root,`versions`)),d.default.realpathSync(t.packageRoot));if(!n||n.startsWith(`..`)||f.default.isAbsolute(n))throw Error(`Invalid runtime state at ${e}`);return t}install(e){this.preflight();let t=JSON.parse(d.default.readFileSync(f.default.join(e,`package.json`),`utf8`));if(!CO.includes(t.name)||!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(t.version))throw Error(`Invalid Artideck runtime package`);for(let t of MO)if(!d.default.existsSync(f.default.join(e,t)))throw Error(`Incomplete Artideck runtime: missing ${t}. Build or reinstall the complete package.`);let n=PO(e),r=this.current();if(r&&r.version===t.version&&r.digest===n&&this.ownsBin())try{if(PO(r.packageRoot)===n)return this.linkAlias(),r}catch{}let i=f.default.join(this.root,`versions`,`${t.version}-${(0,u.randomUUID)()}`);d.default.mkdirSync(i,{recursive:!0});try{for(let t of[`package.json`,`bin`,`dist`])d.default.cpSync(f.default.join(e,t),f.default.join(i,t),{recursive:!0,dereference:!0});let r=(0,p.spawnSync)(process.execPath,[f.default.join(i,`dist/cli.cjs`),`--version`,`--format`,`brief`],{encoding:`utf8`,timeout:15e3,env:{...process.env,RYUGI_NO_UPDATE_CHECK:`1`}});if(r.error||r.status!==0||![t.version,`artideck ${t.version}`,`ryugi ${t.version}`].includes(r.stdout.trim()))throw Error(`Runtime validation failed: ${r.stderr||r.error?.message||`version mismatch`}`);d.default.writeFileSync(this.launcher,this.launcherSource(),{mode:493}),d.default.mkdirSync(this.binDir,{recursive:!0}),this.ownsBin()||(process.platform===`win32`?d.default.writeFileSync(this.bin,this.shimSource(),{flag:`wx`}):d.default.symlinkSync(this.launcher,this.bin)),this.linkAlias();let a={version:t.version,digest:n,launcherDigest:NO(this.launcherSource()),packageRoot:i,launcher:this.launcher,bin:this.bin};return jO(f.default.join(this.root,`current.json`),a),a}catch(e){throw d.default.rmSync(i,{recursive:!0,force:!0}),e}}};function IO(e,t=process.env){return(t.PATH||``).split(f.default.delimiter).some(t=>f.default.resolve(t)===f.default.resolve(e))?null:(t.SHELL||``).endsWith(`/fish`)?`Run: fish_add_path ${JSON.stringify(e)}`:process.platform===`win32`?`Add ${e} to your user PATH, then open a new terminal.`:`Add to your shell profile: export PATH=${JSON.stringify(e)}:"$PATH"`}const LO=e=>e===`antigravity`?`agy`:e;function RO(e){let t=f.default.join(e,`installation.json`);if(!d.default.existsSync(t))return{schema:1,harnesses:{}};let n=JSON.parse(d.default.readFileSync(t,`utf8`));if(n.schema!==1||!n.harnesses||typeof n.harnesses!=`object`)throw Error(`Unsupported installation state: ${t}`);return n}function zO(e,t){jO(f.default.join(e,`installation.json`),t)}function BO(e,t,n={}){let r=RO(e),i=[];for(let a of Object.values(r.harnesses)){if(!a||a.harness===`claude-code`)continue;let o=f.default.join(e,`candidates`,(0,u.randomUUID)());try{let s=dO(t,o,a.mode);if(s.digest===(a.sealed??a.digest)){i.push({harness:a.harness,status:`current`});continue}let c=bO(a.harness,s,{...n,root:e,previous:a});r.harnesses[a.harness]={...c,sealed:s.digest},zO(e,r),i.push({harness:a.harness,status:`refreshed`})}catch(e){i.push({harness:a.harness,status:`failed`,error:e.message})}finally{d.default.rmSync(o,{recursive:!0,force:!0})}}return i}const VO=e=>[`cli.cjs`,`document-engine.cjs`,`loro_wasm_bg.wasm`,e===`win32`?`ryugi-daemon.exe`:`ryugi-daemon`,`output-bootstrap.cjs`],HO=[`viewer`,`runtime`],UO=e=>f.default.join(e,`.ryugi`,`dev.json`),WO=e=>f.default.join(e,`.ryugi`,`dev`,`builds`),GO=e=>f.default.join(e,`.ryugi`,`dev`,`bin`,`ryugi-daemon`);function KO(e,t=UO(e)){try{let e=JSON.parse(d.default.readFileSync(t,`utf8`)),n=[`build`,`plugin`,`version`,`linkedAt`];return n.every(t=>typeof e?.[t]==`string`)?Object.fromEntries(n.map(t=>[t,e[t]])):null}catch{return null}}function qO(e,t){let n=[...VO(t),...HO].filter(t=>!d.default.existsSync(f.default.join(e,t)));if(n.length)throw Error(`${e} is not a complete build: it has no ${n.join(`, `)}`);let r=[...VO(t)];for(let t of HO)for(let n of d.default.readdirSync(f.default.join(e,t),{recursive:!0}).map(String))d.default.statSync(f.default.join(e,t,n)).isFile()&&r.push(f.default.join(t,n));return r.sort()}function JO(e,t){let n=(0,u.createHash)(`sha256`);for(let r of t)n.update(`${r.split(f.default.sep).join(`/`)}\0`),n.update(d.default.readFileSync(f.default.join(e,r)));return n.digest(`hex`).slice(0,12)}function YO(e,t,n){if(d.default.existsSync(n)){let e=/* @__PURE__ */ new Date;d.default.utimesSync(n,e,e);return}let r=f.default.join(f.default.dirname(n),`.staging-${(0,u.randomUUID)()}`);try{for(let n of t)d.default.mkdirSync(f.default.dirname(f.default.join(r,n)),{recursive:!0}),d.default.copyFileSync(f.default.join(e,n),f.default.join(r,n)),d.default.chmodSync(f.default.join(r,n),d.default.statSync(f.default.join(e,n)).mode);d.default.renameSync(r,n)}catch(e){if(d.default.rmSync(r,{recursive:!0,force:!0}),!d.default.existsSync(n))throw e}}function XO(e,t,n){let r=GO(t),i=d.default.readFileSync(e),a=(0,u.createHash)(`sha256`).update(i).digest(`hex`),o=`${r}.source`;if(d.default.existsSync(r)&&d.default.existsSync(o)&&d.default.readFileSync(o,`utf8`).trim()===a)return r;d.default.mkdirSync(f.default.dirname(r),{recursive:!0});let s=`${r}.${(0,u.randomUUID)()}`;try{d.default.writeFileSync(s,i),d.default.chmodSync(s,493),n?.(s),d.default.renameSync(s,r)}catch(e){throw d.default.rmSync(s,{force:!0}),e}return d.default.writeFileSync(o,`${a}\n`),r}function ZO(e){try{return d.default.readlinkSync(e)}catch{return null}}function QO(e,t){let n=f.default.join(e,`ryugi-daemon`);if(ZO(n)===t)return;let r=`${n}.${(0,u.randomUUID)()}`;d.default.symlinkSync(t,r),d.default.renameSync(r,n)}function $O(e){try{let t=JSON.parse(d.default.readFileSync(f.default.join(e,`launch.json`),`utf8`))?.env?.RYUGI_DOCUMENT_ENGINE;return typeof t==`string`?f.default.basename(f.default.dirname(t)):null}catch{return null}}function ek(e,t){let n=WO(e),r=d.default.readdirSync(n).filter(e=>!e.startsWith(`.`)).map(e=>({name:e,at:d.default.statSync(f.default.join(n,e)).mtimeMs})).sort((e,t)=>t.at-e.at),i=/* @__PURE__ */ new Set([...t,...r.slice(0,3).map(e=>e.name)]);for(let{name:e}of r)i.has(e)||d.default.rmSync(f.default.join(n,e),{recursive:!0,force:!0})}function tk(e,t){let n=UO(e);d.default.mkdirSync(f.default.dirname(n),{recursive:!0,mode:448});let r=`${n}.${process.pid}.${(0,u.randomUUID)()}`;d.default.writeFileSync(r,`${JSON.stringify(t,null,2)}\n`),d.default.renameSync(r,n)}function nk(e){let t=f.default.resolve(e.source),n=qO(t,e.platform),r=JO(t,n);d.default.mkdirSync(WO(e.home),{recursive:!0});let i=f.default.join(WO(e.home),r);YO(t,n,i),e.platform===`darwin`&&QO(i,XO(f.default.join(t,`ryugi-daemon`),e.home,e.sign));let a={build:i,plugin:f.default.resolve(e.plugin),version:`local-${r}`,linkedAt:(/* @__PURE__ */ new Date()).toISOString()};return tk(e.home,a),ek(e.home,[r,$O(e.serverHome),$O(f.default.join(e.home,`.ryugi`,`server`))]),a}function rk(e){try{return d.default.unlinkSync(UO(e)),!0}catch{return!1}}function ik(){let e=(0,p.spawnSync)(`security`,[`find-identity`,`-v`,`-p`,`codesigning`],{encoding:`utf8`});return/"(Developer ID Application: [^"]+)"/.exec(e.stdout??``)?.[1]}function ak(e,t){if(t!==`darwin`)return;let n=e.RYUGI_DEV_SIGN_IDENTITY??ik();if(n)return e=>{let t=(0,p.spawnSync)(`codesign`,[`--force`,`--sign`,n,`--identifier`,`dev.ryugi.daemon`,`--timestamp=none`,e],{encoding:`utf8`});if(t.status!==0)throw Error(`codesign could not sign the daemon with "${n}": ${(t.stderr||t.error?.message||``).trim()}. Set RYUGI_DEV_SIGN_IDENTITY to another identity, or to an empty value to link it unsigned.`)}}function ok(e){let t=h.default.homedir(),n=e.values.plugin??KO(t)?.plugin??void 0;if(!n)throw new M(`name the Artideck plugin checkout: adeck dev link --plugin <dir>`);if(!d.default.existsSync(f.default.join(n,`skills/artifacts/app/ryugi.cjs`)))throw new M(`${n} is not an Artideck plugin checkout: it has no skills/artifacts/app/ryugi.cjs`);try{return nk({source:e.positionals[1]??__dirname,plugin:n,home:t,platform:process.platform,serverHome:He().home,sign:ak(process.env,process.platform)})}catch(e){throw new M(e.message)}}function sk(e){let t=e.positionals[0]??`status`;if(t===`link`){let n=ok(e);return{action:t,status:`linked`,link:n,refreshed:BO(kO(),n.plugin,{run:hO})}}if(t===`unlink`)return{action:t,status:rk(h.default.homedir())?`unlinked`:`none`,link:null,refreshed:[]};if(t===`status`){let e=KO(h.default.homedir());return{action:t,status:e?`linked`:`none`,link:e,refreshed:[]}}throw new M(`usage: adeck dev link|unlink|status`)}function ck({data:e}){return{heading:`Dev link`,status:e.status,summary:e.link?e.link.version:`every agent runs its own CLI or an npm release`,facts:[],sections:e.link?[{kind:`content`,key:`link`,text:[`build ${e.link.build}`,`plugin ${e.link.plugin}`,...e.refreshed.map(e=>`copy ${e.harness} ${e.status}${e.error?`: ${e.error}`:``}`)].join(`
|
|
882
|
-
`)}]:[]}}const
|
|
883
|
-
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){
|
|
884
|
-
`){a&&(r+=
|
|
885
|
-
`&&(i&&
|
|
886
|
-
`)}const
|
|
881
|
+
`}shimSource(){return`@echo off\r\nnode "${this.launcher}" %*\r\n`}owns(e){try{return process.platform===`win32`?d.default.readFileSync(e,`utf8`)===this.shimSource():d.default.lstatSync(e).isSymbolicLink()&&d.default.realpathSync(e)===d.default.realpathSync(this.launcher)}catch{return!1}}ownsBin(){return this.owns(this.bin)}ownsAlias(){return this.owns(this.aliasBin)}linkAlias(){if(!this.ownsAlias())try{process.platform===`win32`?d.default.writeFileSync(this.aliasBin,this.shimSource(),{flag:`wx`}):d.default.symlinkSync(this.launcher,this.aliasBin)}catch{}}preflight(){let e=!1;try{d.default.lstatSync(this.bin),e=!0}catch(e){if(e.code!==`ENOENT`)throw e}if(e&&!this.ownsBin())throw Error(`Command already exists at ${this.bin}; choose --bin-dir or keep its original package manager.`);if(d.default.existsSync(this.launcher)){let e=d.default.readFileSync(this.launcher,`utf8`);if(e!==this.launcherSource()&&PO(e)!==this.current()?.launcherDigest)throw Error(`Foreign launcher already exists at ${this.launcher}`)}}current(){let e=f.default.join(this.root,`current.json`);if(!d.default.existsSync(e))return null;let t=JSON.parse(d.default.readFileSync(e,`utf8`)),n=f.default.relative(d.default.realpathSync(f.default.join(this.root,`versions`)),d.default.realpathSync(t.packageRoot));if(!n||n.startsWith(`..`)||f.default.isAbsolute(n))throw Error(`Invalid runtime state at ${e}`);return t}install(e){this.preflight();let t=JSON.parse(d.default.readFileSync(f.default.join(e,`package.json`),`utf8`));if(!wO.includes(t.name)||!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(t.version))throw Error(`Invalid Artideck runtime package`);for(let t of NO)if(!d.default.existsSync(f.default.join(e,t)))throw Error(`Incomplete Artideck runtime: missing ${t}. Build or reinstall the complete package.`);let n=FO(e),r=this.current();if(r&&r.version===t.version&&r.digest===n&&this.ownsBin())try{if(FO(r.packageRoot)===n)return this.linkAlias(),r}catch{}let i=f.default.join(this.root,`versions`,`${t.version}-${(0,u.randomUUID)()}`);d.default.mkdirSync(i,{recursive:!0});try{for(let t of[`package.json`,`bin`,`dist`])d.default.cpSync(f.default.join(e,t),f.default.join(i,t),{recursive:!0,dereference:!0});let r=(0,p.spawnSync)(process.execPath,[f.default.join(i,`dist/cli.cjs`),`--version`,`--format`,`brief`],{encoding:`utf8`,timeout:15e3,env:{...process.env,RYUGI_NO_UPDATE_CHECK:`1`}});if(r.error||r.status!==0||![t.version,`artideck ${t.version}`,`ryugi ${t.version}`].includes(r.stdout.trim()))throw Error(`Runtime validation failed: ${r.stderr||r.error?.message||`version mismatch`}`);d.default.writeFileSync(this.launcher,this.launcherSource(),{mode:493}),d.default.mkdirSync(this.binDir,{recursive:!0}),this.ownsBin()||(process.platform===`win32`?d.default.writeFileSync(this.bin,this.shimSource(),{flag:`wx`}):d.default.symlinkSync(this.launcher,this.bin)),this.linkAlias();let a={version:t.version,digest:n,launcherDigest:PO(this.launcherSource()),packageRoot:i,launcher:this.launcher,bin:this.bin};return MO(f.default.join(this.root,`current.json`),a),a}catch(e){throw d.default.rmSync(i,{recursive:!0,force:!0}),e}}};function LO(e,t=process.env){return(t.PATH||``).split(f.default.delimiter).some(t=>f.default.resolve(t)===f.default.resolve(e))?null:(t.SHELL||``).endsWith(`/fish`)?`Run: fish_add_path ${JSON.stringify(e)}`:process.platform===`win32`?`Add ${e} to your user PATH, then open a new terminal.`:`Add to your shell profile: export PATH=${JSON.stringify(e)}:"$PATH"`}const RO=e=>e===`antigravity`?`agy`:e;function zO(e){let t=f.default.join(e,`installation.json`);if(!d.default.existsSync(t))return{schema:1,harnesses:{}};let n=JSON.parse(d.default.readFileSync(t,`utf8`));if(n.schema!==1||!n.harnesses||typeof n.harnesses!=`object`)throw Error(`Unsupported installation state: ${t}`);return n}function BO(e,t){MO(f.default.join(e,`installation.json`),t)}function VO(e,t,n={}){let r=zO(e),i=[];for(let a of Object.values(r.harnesses)){if(!a||a.harness===`claude-code`)continue;let o=f.default.join(e,`candidates`,(0,u.randomUUID)());try{let s=fO(t,o,a.mode);if(s.digest===(a.sealed??a.digest)){i.push({harness:a.harness,status:`current`});continue}let c=xO(a.harness,s,{...n,root:e,previous:a});r.harnesses[a.harness]={...c,sealed:s.digest},BO(e,r),i.push({harness:a.harness,status:`refreshed`})}catch(e){i.push({harness:a.harness,status:`failed`,error:e.message})}finally{d.default.rmSync(o,{recursive:!0,force:!0})}}return i}const HO=e=>[`cli.cjs`,`document-engine.cjs`,`loro_wasm_bg.wasm`,e===`win32`?`ryugi-daemon.exe`:`ryugi-daemon`,`output-bootstrap.cjs`],UO=[`viewer`,`runtime`],WO=e=>f.default.join(e,`.ryugi`,`dev.json`),GO=e=>f.default.join(e,`.ryugi`,`dev`,`builds`),KO=e=>f.default.join(e,`.ryugi`,`dev`,`bin`,`ryugi-daemon`);function qO(e,t=WO(e)){try{let e=JSON.parse(d.default.readFileSync(t,`utf8`)),n=[`build`,`plugin`,`version`,`linkedAt`];return n.every(t=>typeof e?.[t]==`string`)?Object.fromEntries(n.map(t=>[t,e[t]])):null}catch{return null}}function JO(e,t){let n=[...HO(t),...UO].filter(t=>!d.default.existsSync(f.default.join(e,t)));if(n.length)throw Error(`${e} is not a complete build: it has no ${n.join(`, `)}`);let r=[...HO(t)];for(let t of UO)for(let n of d.default.readdirSync(f.default.join(e,t),{recursive:!0}).map(String))d.default.statSync(f.default.join(e,t,n)).isFile()&&r.push(f.default.join(t,n));return r.sort()}function YO(e,t){let n=(0,u.createHash)(`sha256`);for(let r of t)n.update(`${r.split(f.default.sep).join(`/`)}\0`),n.update(d.default.readFileSync(f.default.join(e,r)));return n.digest(`hex`).slice(0,12)}function XO(e,t,n){if(d.default.existsSync(n)){let e=/* @__PURE__ */ new Date;d.default.utimesSync(n,e,e);return}let r=f.default.join(f.default.dirname(n),`.staging-${(0,u.randomUUID)()}`);try{for(let n of t)d.default.mkdirSync(f.default.dirname(f.default.join(r,n)),{recursive:!0}),d.default.copyFileSync(f.default.join(e,n),f.default.join(r,n)),d.default.chmodSync(f.default.join(r,n),d.default.statSync(f.default.join(e,n)).mode);d.default.renameSync(r,n)}catch(e){if(d.default.rmSync(r,{recursive:!0,force:!0}),!d.default.existsSync(n))throw e}}function ZO(e,t,n){let r=KO(t),i=d.default.readFileSync(e),a=(0,u.createHash)(`sha256`).update(i).digest(`hex`),o=`${r}.source`;if(d.default.existsSync(r)&&d.default.existsSync(o)&&d.default.readFileSync(o,`utf8`).trim()===a)return r;d.default.mkdirSync(f.default.dirname(r),{recursive:!0});let s=`${r}.${(0,u.randomUUID)()}`;try{d.default.writeFileSync(s,i),d.default.chmodSync(s,493),n?.(s),d.default.renameSync(s,r)}catch(e){throw d.default.rmSync(s,{force:!0}),e}return d.default.writeFileSync(o,`${a}\n`),r}function QO(e){try{return d.default.readlinkSync(e)}catch{return null}}function $O(e,t){let n=f.default.join(e,`ryugi-daemon`);if(QO(n)===t)return;let r=`${n}.${(0,u.randomUUID)()}`;d.default.symlinkSync(t,r),d.default.renameSync(r,n)}function ek(e){try{let t=JSON.parse(d.default.readFileSync(f.default.join(e,`launch.json`),`utf8`))?.env?.RYUGI_DOCUMENT_ENGINE;return typeof t==`string`?f.default.basename(f.default.dirname(t)):null}catch{return null}}function tk(e,t){let n=GO(e),r=d.default.readdirSync(n).filter(e=>!e.startsWith(`.`)).map(e=>({name:e,at:d.default.statSync(f.default.join(n,e)).mtimeMs})).sort((e,t)=>t.at-e.at),i=/* @__PURE__ */ new Set([...t,...r.slice(0,3).map(e=>e.name)]);for(let{name:e}of r)i.has(e)||d.default.rmSync(f.default.join(n,e),{recursive:!0,force:!0})}function nk(e,t){let n=WO(e);d.default.mkdirSync(f.default.dirname(n),{recursive:!0,mode:448});let r=`${n}.${process.pid}.${(0,u.randomUUID)()}`;d.default.writeFileSync(r,`${JSON.stringify(t,null,2)}\n`),d.default.renameSync(r,n)}function rk(e){let t=f.default.resolve(e.source),n=JO(t,e.platform),r=YO(t,n);d.default.mkdirSync(GO(e.home),{recursive:!0});let i=f.default.join(GO(e.home),r);XO(t,n,i),e.platform===`darwin`&&$O(i,ZO(f.default.join(t,`ryugi-daemon`),e.home,e.sign));let a={build:i,plugin:f.default.resolve(e.plugin),version:`local-${r}`,linkedAt:(/* @__PURE__ */ new Date()).toISOString()};return nk(e.home,a),tk(e.home,[r,ek(e.serverHome),ek(f.default.join(e.home,`.ryugi`,`server`))]),a}function ik(e){try{return d.default.unlinkSync(WO(e)),!0}catch{return!1}}function ak(){let e=(0,p.spawnSync)(`security`,[`find-identity`,`-v`,`-p`,`codesigning`],{encoding:`utf8`});return/"(Developer ID Application: [^"]+)"/.exec(e.stdout??``)?.[1]}function ok(e,t){if(t!==`darwin`)return;let n=e.RYUGI_DEV_SIGN_IDENTITY??ak();if(n)return e=>{let t=(0,p.spawnSync)(`codesign`,[`--force`,`--sign`,n,`--identifier`,`dev.ryugi.daemon`,`--timestamp=none`,e],{encoding:`utf8`});if(t.status!==0)throw Error(`codesign could not sign the daemon with "${n}": ${(t.stderr||t.error?.message||``).trim()}. Set RYUGI_DEV_SIGN_IDENTITY to another identity, or to an empty value to link it unsigned.`)}}function sk(e){let t=h.default.homedir(),n=e.values.plugin??qO(t)?.plugin??void 0;if(!n)throw new M(`name the Artideck plugin checkout: adeck dev link --plugin <dir>`);if(!d.default.existsSync(f.default.join(n,`skills/artifacts/app/ryugi.cjs`)))throw new M(`${n} is not an Artideck plugin checkout: it has no skills/artifacts/app/ryugi.cjs`);try{return rk({source:e.positionals[1]??__dirname,plugin:n,home:t,platform:process.platform,serverHome:He().home,sign:ok(process.env,process.platform)})}catch(e){throw new M(e.message)}}function ck(e){let t=e.positionals[0]??`status`;if(t===`link`){let n=sk(e);return{action:t,status:`linked`,link:n,refreshed:VO(AO(),n.plugin,{run:gO})}}if(t===`unlink`)return{action:t,status:ik(h.default.homedir())?`unlinked`:`none`,link:null,refreshed:[]};if(t===`status`){let e=qO(h.default.homedir());return{action:t,status:e?`linked`:`none`,link:e,refreshed:[]}}throw new M(`usage: adeck dev link|unlink|status`)}function lk({data:e}){return{heading:`Dev link`,status:e.status,summary:e.link?e.link.version:`every agent runs its own CLI or an npm release`,facts:[],sections:e.link?[{kind:`content`,key:`link`,text:[`build ${e.link.build}`,`plugin ${e.link.plugin}`,...e.refreshed.map(e=>`copy ${e.harness} ${e.status}${e.error?`: ${e.error}`:``}`)].join(`
|
|
882
|
+
`)}]:[]}}const uk={name:`dev`,summary:`Point every agent on this machine at a local development build`,usage:[`link [<build dir>] [--plugin <checkout>]`,`unlink`,`status`],details:`link freezes a complete build (the directory of this CLI by default) under ~/.ryugi/dev/builds/<fingerprint> and records it in ~/.ryugi/dev.json with the plugin checkout; every Ryugi launcher then runs that CLI and hub, and the plugin checkout's ryugi-hook build. unlink removes the record; launchers go back to their own CLI or npm releases.`,positionals:2,options:{plugin:{type:`string`,value:`<checkout>`,help:`Artideck plugin checkout to link`}},semantic:e=>Q({id:`dev`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},run:()=>Y(ck(e)),present:lk},e)},dk=[`/opt/homebrew/bin`,`/usr/local/bin`],fk=process.platform===`win32`?[`agent-browser.cmd`,`agent-browser.exe`]:[`agent-browser`],pk=e=>{try{return d.default.accessSync(e,d.default.constants.X_OK),d.default.statSync(e).isFile()}catch{return!1}},mk=e=>{let t=f.default.join(e,`.nvm`,`versions`,`node`);try{return d.default.readdirSync(t).sort().reverse().map(e=>f.default.join(t,e,`bin`))}catch{return[]}};function hk(e,t,n,r){return[...(e.PATH??``).split(f.default.delimiter),r,e.PNPM_HOME??``,f.default.join(t,`Library`,`pnpm`,`bin`),f.default.join(t,`.local`,`share`,`pnpm`),f.default.join(t,`.local`,`bin`),f.default.join(t,`.bun`,`bin`),f.default.join(t,`.npm-global`,`bin`),f.default.join(t,`.volta`,`bin`),f.default.join(t,`.asdf`,`shims`),f.default.join(t,`.local`,`share`,`mise`,`shims`),...mk(t),...n].filter(Boolean)}function gk({env:e=process.env,home:t=h.default.homedir(),extraDirs:n=dk,nodeDir:r=f.default.dirname(process.execPath)}={}){let i=e.RYUGI_AGENT_BROWSER;if(i)return pk(i)?i:null;for(let i of hk(e,t,n,r))for(let e of fk){let t=f.default.join(i,e);if(pk(t))return t}return null}const _k=(e=process.env)=>({...e,PATH:[f.default.dirname(process.execPath),e.PATH??``].filter(Boolean).join(f.default.delimiter)});function vk(e){let t=(0,p.spawnSync)(e,[`--version`],{encoding:`utf8`,timeout:5e3,env:_k()});return/(\d+\.\d+\.\d+\S*)/.exec(t.stdout??``)?.[1]??null}const yk=e=>{let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(e)),t};function bk(e){let t=(0,u.createHash)(`sha256`).update(`codex-plugin-bundle-v1`),n=[e];for(;n.length;){let r=n.pop(),i=f.default.relative(e,r),a=i?f.default.basename(i):``;if(a&&(a===`__pycache__`||a===`.venv`||a.endsWith(`.pyc`)||a.endsWith(`.egg-info`)))continue;let o=Buffer.from(i);t.update(yk(o.length)).update(o);let s=d.default.lstatSync(r);if(s.isDirectory()){t.update(`directory`);let e=d.default.readdirSync(r).sort((e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t)));for(let t=e.length-1;t>=0;t--)n.push(f.default.join(r,e[t]))}else if(s.isFile())t.update(`file`).update(yk(s.size)).update(d.default.readFileSync(r));else throw Error(`Unsupported Codex plugin entry: ${r}`)}return`sha256:${t.digest(`hex`)}`}const xk=e=>e.replaceAll(/(?<=[a-z\d])([A-Z])/g,`_$1`).toLowerCase();function Sk(e,t){let n=JSON.parse(d.default.readFileSync(f.default.join(e,`.codex-plugin/plugin.json`),`utf8`));if(typeof n.hooks!=`string`)return[];let r=f.default.posix.normalize(n.hooks.replaceAll(`\\`,`/`)),i=JSON.parse(d.default.readFileSync(f.default.join(e,r),`utf8`)).hooks??{},a=[];for(let[e,n]of Object.entries(i))n.forEach((n,i)=>(n.hooks??[]).forEach((n,o)=>a.push(`${t}:${r}:${xk(e)}:${i}:${o}`)));return a}function Ck(e){let t=/* @__PURE__ */ new Map,n;for(let r of e.split(/\r?\n/)){let e=r.match(/^\s*\[\s*hooks\.state\."((?:[^"\\]|\\.)*)"\s*\]\s*$/);if(e){n={},t.set(JSON.parse(`"${e[1]}"`),n);continue}if(/^\s*\[/.test(r)){n=void 0;continue}let i=r.match(/^\s*([\w-]+)\s*=\s*(.+?)\s*$/);n&&i&&(n[i[1]]=i[2].replace(/^"(.*)"$/,`$1`))}return t}function wk(e,t,n,r=h.default.homedir()){let i=Sk(e,t),a=f.default.join(n.CODEX_HOME||f.default.join(r,`.codex`),`config.toml`),o=Ck(d.default.existsSync(a)?d.default.readFileSync(a,`utf8`):``),s=bk(e),c=i.filter(e=>{let t=o.get(e);return t?.trusted_content_hash!==s||t.enabled===`false`});return{declared:i.length,blocked:c.length}}const Tk=12096e5,Ek=e=>f.default.join(ct(e),`plugins.json`);function Dk(e,t){d.default.mkdirSync(ct(e),{recursive:!0,mode:448});let n=`${Ek(e)}.${process.pid}.tmp`;d.default.writeFileSync(n,JSON.stringify(t)),d.default.renameSync(n,Ek(e))}function Ok(e){try{let t=JSON.parse(d.default.readFileSync(Ek(e),`utf8`));return Array.isArray(t?.plugins)?{complete:t.complete===!0,plugins:t.plugins.filter(e=>typeof e?.version==`string`&&at(e.version))}:null}catch{return null}}const kk=e=>{try{return d.default.statSync(e).mtimeMs}catch{return null}};function Ak(e){let t=ct(e.home),n=[],r=[];try{r=d.default.readdirSync(t)}catch{}for(let i of r){if(!at(i)||e.keep.has(i))continue;let r=f.default.join(t,i),a=kk(f.default.join(r,`last-used`)),o=kk(r),s=kk(f.default.join(r,`.lock`)),c=(t,n)=>t!==null&&e.now-t<n;c(a,Tk)||a===null&&c(o,Tk)||c(s,3e5)||(d.default.rmSync(r,{recursive:!0,force:!0}),n.push(i))}let i=f.default.join(t,`.legacy-removed`);if(!e.legacyInUse&&!d.default.existsSync(i)){let n=e.env.XDG_CACHE_HOME||f.default.join(e.home,`.cache`);d.default.rmSync(f.default.join(n,`ryugi`,`hook`),{recursive:!0,force:!0}),d.default.mkdirSync(t,{recursive:!0,mode:448}),d.default.writeFileSync(i,``)}return n}async function jk(e){if(f.default.resolve(e.serverHome)!==f.default.join(e.home,`.ryugi`,`server`))return{status:`other-hub`};let t=e.now??Date.now(),n=e.installed??Ok(e.home),r=n?.plugins??[],i=/* @__PURE__ */ new Set([e.version,...r.filter(e=>!e.legacy).map(e=>e.version)]),a=[],o=[],{progress:s}=e,c=await Promise.all([...i].map(n=>mt({...e,version:n,now:t,onProgress:s&&((e,t)=>s(n,e,t))})));return[...i].forEach((e,t)=>{let n=c[t];n.status===`installed`&&a.push(e),(n.status===`failed`||n.status===`skipped`&&n.error)&&o.push({version:e,error:n.error??`failed`})}),{status:`done`,prefetched:a,failed:o,removed:e.cleanup?Ak({env:e.env,home:e.home,keep:i,legacyInUse:!n?.complete||r.some(e=>e.legacy),now:t}):[]}}const Mk=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Nk=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Pk=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Fk=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ik=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Lk=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Rk=/\t{1,1000}/y,zk=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Bk=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Vk=/\p{M}+/gu,Hk={limit:1/0,ellipsis:``},Uk=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Uk(i,Hk,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Bk,l],[Fk,0],[Ik,o],[Rk,s],[zk,c],[Lk,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Vk,``)){let t=e.codePointAt(0)||0;if(S=Nk(t)?2:Pk(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Lk?Mk(e.slice(p,n.lastIndex)):n===zk?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Wk={limit:1/0,ellipsis:``,ellipsisWidth:0},Gk=(e,t={})=>Uk(e,Wk,t).width,Kk=`]8;;`,qk=RegExp(`(?:\\[(?<code>\\d+)m|\\${Kk}(?<uri>.*))`,`y`),Jk=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Yk=e=>`[${e}m`,Xk=e=>`${Kk}${e}`,Zk=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Gk(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Gk(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Kk,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Qk=e=>{let t=e.split(` `),n=t.length;for(;n&&!Gk(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},$k=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Gk(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Gk(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Zk(s,r,t),c=Gk(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Zk(s,r,t),c=Gk(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Zk(s,r,t),c=Gk(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Qk(e)));let l=s.join(`
|
|
883
|
+
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){qk.lastIndex=e+1;let t=qk.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
884
|
+
`){a&&(r+=Xk(``));let e=i?Jk(i):void 0;i&&e&&(r+=Yk(e))}else t===`
|
|
885
|
+
`&&(i&&Jk(i)&&(r+=Yk(i)),a&&(r+=Xk(a)))}return r},eA=/\r?\n/;function tA(e,t,n){return String(e).normalize().split(eA).map(e=>$k(e,t,n)).join(`
|
|
886
|
+
`)}const nA={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`},rA={screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let n=0;n<e;n++)t+=this.line+(n<e-1?nA.up():``);return e&&(t+=nA.left),t}};function iA(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a]?.disabled?iA(a,t<0?-1:1,n):a}const aA={actions:/* @__PURE__ */ new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:/* @__PURE__ */ new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,accessible:void 0,date:{monthNames:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function oA(e){if(e!==void 0)return e;if(aA.accessible!==void 0)return aA.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==``&&t!==`0`&&t!==`false`}function sA(e,t){if(typeof e==`string`)return aA.aliases.get(e)===t;for(let n of e)if(n!==void 0&&sA(n,t))return!0;return!1}function cA(e,t){if(e===t)return;let n=e.split(`
|
|
887
887
|
`),r=t.split(`
|
|
888
|
-
`),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const
|
|
888
|
+
`),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const lA=globalThis.process.platform.startsWith(`win`),uA=Symbol(`clack:cancel`);function dA(e){return e===uA}function fA(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function pA({input:e=y.stdin,output:t=y.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let i=m.createInterface({input:e,output:t,prompt:``,tabSize:1});m.emitKeypressEvents(e,i),e instanceof b.ReadStream&&e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(sA([String(i),o,s],`cancel`)){r&&t.write(nA.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;m.moveCursor(t,c,l,()=>{m.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(nA.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(nA.show),e instanceof b.ReadStream&&e.isTTY&&!lA&&e.setRawMode(!1),i.terminal=!1,i.close()}}const mA=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,hA=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function gA(e,t,n,r=n,i=n,a){return tA(t,mA(e??y.stdout)-Gk(n),{hard:!0,trim:!1}).split(`
|
|
889
889
|
`).map((e,t,o)=>{let s=a?a(e,t):e;return t===0?`${r}${s}`:t===o.length-1?`${i}${s}`:`${n}${s}`}).join(`
|
|
890
|
-
`)}function
|
|
891
|
-
`),
|
|
892
|
-
`).length-1;this.output.write(
|
|
893
|
-
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(
|
|
890
|
+
`)}function _A(e,t){if(`~standard`in e){let n=e[`~standard`].validate(t);return n instanceof Promise?n.then(e=>e.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}let vA=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=/* @__PURE__ */ new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;get accessible(){return oA(this.opts.accessible)}constructor(e,t=!0){let{input:n=y.stdin,output:r=y.stdout,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(uA);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=m.default.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),fA(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(nA.show),this.output.off(`resize`,this.render),fA(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(nA.show),this.output.off(`resize`,this.render),fA(this.input,!1),e(uA)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}async onKeypress(e,t){if(this.state!==`validating`){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&aA.aliases.has(t.name)&&this.emit(`cursor`,aA.aliases.get(t.name)),aA.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e,t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=_A(this.opts.validate,this.value),t;e instanceof Promise?(this.state=`validating`,this.render(),t=await e):t=e,t&&(this.error=t instanceof Error?t.message:t,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}sA([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
891
|
+
`),fA(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=tA(this._prevFrame,mA(this.output),{hard:!0,trim:!1}).split(`
|
|
892
|
+
`).length-1;this.output.write(nA.move(-999,e*-1))}render(){let e=tA(this._render(this)??``,mA(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(nA.hide);else{let t=cA(this._prevFrame,e),n=hA(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(nA.move(0,a-i)),this.output.write(rA.lines(1));let t=e.split(`
|
|
893
|
+
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(nA.move(0,t.length-a-1));return}if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(nA.move(0,e))}this.output.write(rA.down());let t=e.split(`
|
|
894
894
|
`).slice(a);this.output.write(t.join(`
|
|
895
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
896
|
-
`);return n&&i.push((0,g.styleText)(`cyan`,
|
|
897
|
-
`);_.push(a),v+=a.length}if(v>u){let t=0,n=0,r=v,i=e-y,a=u,o=()=>
|
|
895
|
+
`)),this._prevFrame=e;return}}this.output.write(rA.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var yA=class extends vA{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(e=>e.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(t=>!e.includes(t.value));this.value=t.map(e=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[t]?.disabled?iA(t,1,this.options):t,this.on(`key`,(e,t)=>{t.name===`a`&&this.toggleAll(),t.name===`i`&&this.toggleInvert(),t.name===void 0&&e===` `&&this.toggleValue()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=iA(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=iA(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let bA=class extends vA{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n]?.disabled?iA(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=iA(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=iA(this.cursor,1,this.options)}this.changeValue()})}};function xA(){return y.default.platform===`win32`?!!y.default.env.CI||!!y.default.env.WT_SESSION||!!y.default.env.TERMINUS_SUBLIME||y.default.env.ConEmuTask===`{cmd::Cmder}`||y.default.env.TERM_PROGRAM===`Terminus-Sublime`||y.default.env.TERM_PROGRAM===`vscode`||y.default.env.TERM===`xterm-256color`||y.default.env.TERM===`alacritty`||y.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:y.default.env.TERM!==`linux`}const SA=xA(),CA=()=>process.env.CI===`true`,wA=(e,t)=>SA?e:t,TA=wA(`◆`,`*`),EA=wA(`■`,`x`),DA=wA(`▲`,`x`),OA=wA(`◇`,`o`),kA=wA(`┌`,`T`),AA=wA(`│`,`|`),jA=wA(`└`,`—`),MA=wA(`●`,`>`),NA=wA(`○`,` `),PA=wA(`◻`,`[•]`),FA=wA(`◼`,`[+]`),IA=wA(`◻`,`[ ]`),LA=wA(`─`,`-`),RA=wA(`╮`,`+`),zA=wA(`├`,`+`),BA=wA(`╯`,`+`),VA=wA(`╰`,`+`),HA=e=>{switch(e){case`initial`:case`active`:return(0,g.styleText)(`cyan`,TA);case`cancel`:return(0,g.styleText)(`red`,EA);case`error`:return(0,g.styleText)(`yellow`,DA);case`submit`:return(0,g.styleText)(`green`,OA);case`validating`:return(0,g.styleText)(`dim`,TA)}},UA=e=>{switch(e){case`initial`:case`active`:return(0,g.styleText)(`cyan`,AA);case`cancel`:return(0,g.styleText)(`red`,AA);case`error`:return(0,g.styleText)(`yellow`,AA);case`submit`:return(0,g.styleText)(`green`,AA)}};function WA(e,t,n){let r=n?`${(0,g.styleText)(`cyan`,AA)} `:``,i=gA(e,t.join(` • `),r).split(`
|
|
896
|
+
`);return n&&i.push((0,g.styleText)(`cyan`,jA)),i}const GA=(e,t,n,r,i,a=!1)=>{let o=t,s=0;if(a)for(let t=r-1;t>=n;t--){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}else for(let t=n;t<r;t++){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}return{lineCount:o,removals:s}},KA=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:a=0,rowPadding:o=4})=>{let s=mA(r)-a,c=hA(r),l=(0,g.styleText)(`dim`,`...`),u=Math.max(c-o,0),d=Math.max(Math.min(i,u),5),f=0;e>=d-3&&(f=Math.max(Math.min(e-d+3,t.length-d),0));let p=d<t.length&&f>0,m=d<t.length&&f+d<t.length,h=Math.min(f+d,t.length),_=[],v=0;p&&v++,m&&v++;let y=f+ +!!p,b=h-+!!m;for(let r=y;r<b;r++){let i=t[r],a=tA(i===void 0?``:n(i,r===e),s,{hard:!0,trim:!1}).split(`
|
|
897
|
+
`);_.push(a),v+=a.length}if(v>u){let t=0,n=0,r=v,i=e-y,a=u,o=()=>GA(_,r,0,i,a),s=()=>GA(_,r,i+1,_.length,a,!0);p?({lineCount:r,removals:t}=o(),r>a&&(m||--a,{lineCount:r,removals:n}=s())):(m||--a,{lineCount:r,removals:n}=s(),r>a&&(--a,{lineCount:r,removals:t}=o())),t>0&&(p=!0,_.splice(0,t)),n>0&&(m=!0,_.splice(_.length-n,n))}let x=[];p&&x.push(l);for(let e of _)for(let t of e)x.push(t);return m&&x.push(l),x},qA=[`${(0,g.styleText)(`dim`,`↑/↓`)} to navigate`,`${(0,g.styleText)(`dim`,`Space:`)} select`,`${(0,g.styleText)(`dim`,`Enter:`)} confirm`],JA=(e,t)=>e.split(`
|
|
898
898
|
`).map(e=>t(e)).join(`
|
|
899
|
-
`),
|
|
900
|
-
${(0,g.styleText)(`reset`,(0,g.styleText)(`dim`,`Press ${(0,g.styleText)([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${(0,g.styleText)(`gray`,(0,g.styleText)(`bgWhite`,(0,g.styleText)(`inverse`,` enter `)))} to submit`))}`},render(){let n=e.withGuide??
|
|
899
|
+
`),YA=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`disabled`?`${(0,g.styleText)(`gray`,IA)} ${JA(n,e=>(0,g.styleText)([`strikethrough`,`gray`],e))}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${(0,g.styleText)(`cyan`,PA)} ${n}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${(0,g.styleText)(`green`,FA)} ${JA(n,e=>(0,g.styleText)(`dim`,e))}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${JA(n,e=>(0,g.styleText)([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${(0,g.styleText)(`green`,FA)} ${n}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${JA(n,e=>(0,g.styleText)(`dim`,e))}`:`${(0,g.styleText)(`dim`,IA)} ${JA(n,e=>(0,g.styleText)(`dim`,e))}`},n=e.required??!0,r=e.showInstructions??!0;return new yA({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(e){if(n&&(e===void 0||e.length===0))return`Please select at least one option.
|
|
900
|
+
${(0,g.styleText)(`reset`,(0,g.styleText)(`dim`,`Press ${(0,g.styleText)([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${(0,g.styleText)(`gray`,(0,g.styleText)(`bgWhite`,(0,g.styleText)(`inverse`,` enter `)))} to submit`))}`},render(){let n=e.withGuide??aA.withGuide,i=gA(e.output,e.message,n?`${UA(this.state)} `:``,`${HA(this.state)} `),a=`${n?`${(0,g.styleText)(`gray`,AA)}
|
|
901
901
|
`:``}${i}
|
|
902
|
-
`,o=this.value??[],s=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=o.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`submitted`)).join((0,g.styleText)(`dim`,`, `))||(0,g.styleText)(`dim`,`none`);return`${a}${
|
|
903
|
-
${(0,g.styleText)(`gray`,
|
|
904
|
-
`).map((e,t)=>t===0?`${n?`${(0,g.styleText)(`yellow`,
|
|
902
|
+
`,o=this.value??[],s=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=o.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`submitted`)).join((0,g.styleText)(`dim`,`, `))||(0,g.styleText)(`dim`,`none`);return`${a}${gA(e.output,r,n?`${(0,g.styleText)(`gray`,AA)} `:``)}`}case`cancel`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`cancelled`)).join((0,g.styleText)(`dim`,`, `));return r.trim()===``?`${a}${(0,g.styleText)(`gray`,AA)}`:`${a}${gA(e.output,r,n?`${(0,g.styleText)(`gray`,AA)} `:``)}${n?`
|
|
903
|
+
${(0,g.styleText)(`gray`,AA)}`:``}`}case`error`:{let t=n?`${(0,g.styleText)(`yellow`,AA)} `:``,r=this.error.split(`
|
|
904
|
+
`).map((e,t)=>t===0?`${n?`${(0,g.styleText)(`yellow`,jA)} `:``}${(0,g.styleText)(`yellow`,e)}`:` ${e}`).join(`
|
|
905
905
|
`),i=a.split(`
|
|
906
906
|
`).length,o=r.split(`
|
|
907
|
-
`).length+1;return`${a}${t}${
|
|
907
|
+
`).length+1;return`${a}${t}${KA({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:i+o,style:s}).join(`
|
|
908
908
|
${t}`)}
|
|
909
909
|
${r}
|
|
910
|
-
`}default:{let t=n?`${(0,g.styleText)(`cyan`,
|
|
911
|
-
`).length,o=r?
|
|
912
|
-
`),l=o.length+1;return`${a}${t}${
|
|
910
|
+
`}default:{let t=n?`${(0,g.styleText)(`cyan`,AA)} `:``,i=a.split(`
|
|
911
|
+
`).length,o=r?WA(e.output,qA,n):n?[(0,g.styleText)(`cyan`,jA)]:[],c=o.join(`
|
|
912
|
+
`),l=o.length+1;return`${a}${t}${KA({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:i+l,style:s}).join(`
|
|
913
913
|
${t}`)}
|
|
914
914
|
${c}
|
|
915
|
-
`}}}}).prompt()},
|
|
916
|
-
|
|
917
|
-
`)},
|
|
918
|
-
`)},
|
|
919
|
-
`),a=i.reduce((e,t)=>Math.max(
|
|
920
|
-
`).map(a),``],s=
|
|
921
|
-
`),u=i?`${(0,g.styleText)(`gray`,
|
|
922
|
-
`:``,d=i?
|
|
915
|
+
`}}}}).prompt()},XA=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??aA.withGuide?`${(0,g.styleText)(`gray`,jA)} `:``;n.write(`${r}${(0,g.styleText)(`red`,e)}
|
|
916
|
+
|
|
917
|
+
`)},ZA=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??aA.withGuide?`${(0,g.styleText)(`gray`,kA)} `:``;n.write(`${r}${e}
|
|
918
|
+
`)},QA=e=>e,$A=(e,t,n)=>{let r={hard:!0,trim:!1},i=tA(e,t,r).split(`
|
|
919
|
+
`),a=i.reduce((e,t)=>Math.max(Gk(t),e),0);return tA(e,t-(i.map(n).reduce((e,t)=>Math.max(Gk(t),e),0)-a),r)},ej=(e=``,t=``,n)=>{let r=n?.output??y.default.stdout,i=n?.withGuide??aA.withGuide,a=n?.format??QA,o=[``,...$A(e,mA(r)-6,a).split(`
|
|
920
|
+
`).map(a),``],s=Gk(t),c=Math.max(o.reduce((e,t)=>{let n=Gk(t);return n>e?n:e},0),s)+2,l=o.map(e=>`${(0,g.styleText)(`gray`,AA)} ${e}${` `.repeat(c-Gk(e))}${(0,g.styleText)(`gray`,AA)}`).join(`
|
|
921
|
+
`),u=i?`${(0,g.styleText)(`gray`,AA)}
|
|
922
|
+
`:``,d=i?zA:VA;r.write(`${u}${(0,g.styleText)(`green`,OA)} ${(0,g.styleText)(`reset`,t)} ${(0,g.styleText)(`gray`,LA.repeat(Math.max(c-s-1,1))+RA)}
|
|
923
923
|
${l}
|
|
924
|
-
${(0,g.styleText)(`gray`,d+
|
|
925
|
-
`)},
|
|
926
|
-
`);let e=
|
|
927
|
-
`);e.length>1&&n.write(
|
|
924
|
+
${(0,g.styleText)(`gray`,d+LA.repeat(c+2)+BA)}
|
|
925
|
+
`)},tj=e=>(0,g.styleText)(`magenta`,e),nj=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:a=SA?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:o=SA?80:120,signal:s,...c}={})=>{let l=CA(),u=oA(c.accessible),d,f,p=!1,m=!1,h=``,_,v=performance.now(),y=mA(n),b=c?.styleFrame??tj,x=e=>{let n=e>1?i??aA.messages.error:r??aA.messages.cancel;m=e===1,p&&(D(n,e),m&&typeof t==`function`&&t())},S=()=>x(2),C=()=>x(1),w=()=>{process.on(`uncaughtExceptionMonitor`,S),process.on(`unhandledRejection`,S),process.on(`SIGINT`,C),process.on(`SIGTERM`,C),process.on(`exit`,x),s&&s.addEventListener(`abort`,C)},T=()=>{process.removeListener(`uncaughtExceptionMonitor`,S),process.removeListener(`unhandledRejection`,S),process.removeListener(`SIGINT`,C),process.removeListener(`SIGTERM`,C),process.removeListener(`exit`,x),s&&s.removeEventListener(`abort`,C)},E=()=>{if(_===void 0)return;l&&n.write(`
|
|
926
|
+
`);let e=tA(_,y,{hard:!0,trim:!1}).split(`
|
|
927
|
+
`);e.length>1&&n.write(nA.up(e.length-1)),n.write(nA.to(0)),n.write(rA.down())},ee=e=>e.replace(/\.+$/,``),te=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},ne=c.withGuide??aA.withGuide,re=(t=``)=>{if(p=!0,m=!1,h=ee(t),v=performance.now(),w(),u){h!==``&&n.write(`${h}
|
|
928
928
|
`),f=setInterval(()=>{n.write(h===``?`still working
|
|
929
929
|
`:`still working: ${h}
|
|
930
|
-
`)},3e4);return}d=
|
|
931
|
-
`);let r=0,i=0;f=setInterval(()=>{if(l&&h===_)return;E(),_=h;let t=b(a[r]),o;if(l)o=`${t} ${h}...`;else if(e===`timer`)o=`${t} ${h} ${te(v)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);o=`${t} ${h}${e}`}let s=
|
|
930
|
+
`)},3e4);return}d=pA({output:n}),ne&&n.write(`${(0,g.styleText)(`gray`,AA)}
|
|
931
|
+
`);let r=0,i=0;f=setInterval(()=>{if(l&&h===_)return;E(),_=h;let t=b(a[r]),o;if(l)o=`${t} ${h}...`;else if(e===`timer`)o=`${t} ${h} ${te(v)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);o=`${t} ${h}${e}`}let s=tA(o,y,{hard:!0,trim:!1});n.write(s),r=r+1<a.length?r+1:0,i=i<4?i+.125:0},o)},D=(t=``,a=0,o=!1)=>{if(p){if(p=!1,m=a===1,clearInterval(f),u||E(),h=t??h,!o){if(u){let t=a===1?r??aA.messages.cancel:a===2?i??aA.messages.error:`Done`,o=h||t;e===`timer`?n.write(`${o} ${te(v)}
|
|
932
932
|
`):n.write(`${o}
|
|
933
|
-
`)}else{let t=a===0?(0,g.styleText)(`green`,
|
|
933
|
+
`)}else{let t=a===0?(0,g.styleText)(`green`,OA):a===1?(0,g.styleText)(`red`,EA):(0,g.styleText)(`red`,DA);e===`timer`?n.write(`${t} ${h} ${te(v)}
|
|
934
934
|
`):n.write(`${t} ${h}
|
|
935
|
-
`)}}T(),d?.()}};return{start:re,stop:(e=``)=>D(e,0),message:(e=``)=>{h=ee(e??h)},cancel:(e=``)=>D(e,1),error:(e=``)=>D(e,2),clear:()=>D(``,0,!0),get isCancelled(){return m}}},
|
|
935
|
+
`)}}T(),d?.()}};return{start:re,stop:(e=``)=>D(e,0),message:(e=``)=>{h=ee(e??h)},cancel:(e=``)=>D(e,1),error:(e=``)=>D(e,2),clear:()=>D(``,0,!0),get isCancelled(){return m}}},rj=[`${(0,g.styleText)(`dim`,`↑/↓`)} to navigate`,`${(0,g.styleText)(`dim`,`Enter:`)} confirm`],ij=(e,t)=>e.includes(`
|
|
936
936
|
`)?e.split(`
|
|
937
937
|
`).map(e=>t(e)).join(`
|
|
938
|
-
`):t(e),
|
|
938
|
+
`):t(e),aj=e=>{let t=(e,t)=>{if(e===void 0)return``;let n=e.label??String(e.value);switch(t){case`disabled`:return`${(0,g.styleText)(`gray`,NA)} ${ij(n,e=>(0,g.styleText)(`gray`,e))}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${ij(n,e=>(0,g.styleText)(`dim`,e))}`;case`active`:return`${(0,g.styleText)(`green`,MA)} ${n}${e.hint?` ${(0,g.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${ij(n,e=>(0,g.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,g.styleText)(`dim`,NA)} ${ij(n,e=>(0,g.styleText)(`dim`,e))}`}},n=e.showInstructions??!0;return new bA({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??aA.withGuide,i=`${HA(this.state)} `,a=`${UA(this.state)} `,o=gA(e.output,e.message,a,i),s=`${r?`${(0,g.styleText)(`gray`,AA)}
|
|
939
939
|
`:``}${o}
|
|
940
|
-
`;switch(this.state){case`submit`:{let n=r?`${(0,g.styleText)(`gray`,
|
|
941
|
-
${(0,g.styleText)(`gray`,
|
|
942
|
-
`).length,o=n?
|
|
943
|
-
`),l=o.length+1;return`${s}${i}${
|
|
940
|
+
`;switch(this.state){case`submit`:{let n=r?`${(0,g.styleText)(`gray`,AA)} `:``;return`${s}${gA(e.output,t(this.options[this.cursor],`selected`),n)}`}case`cancel`:{let n=r?`${(0,g.styleText)(`gray`,AA)} `:``;return`${s}${gA(e.output,t(this.options[this.cursor],`cancelled`),n)}${r?`
|
|
941
|
+
${(0,g.styleText)(`gray`,AA)}`:``}`}default:{let i=r?`${(0,g.styleText)(`cyan`,AA)} `:``,a=s.split(`
|
|
942
|
+
`).length,o=n?WA(e.output,rj,r):r?[(0,g.styleText)(`cyan`,jA)]:[],c=o.join(`
|
|
943
|
+
`),l=o.length+1;return`${s}${i}${KA({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:a+l,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
|
|
944
944
|
${i}`)}
|
|
945
945
|
${c}
|
|
946
|
-
`}}}}).prompt()};`${(0,g.styleText)(`gray`,
|
|
946
|
+
`}}}}).prompt()};`${(0,g.styleText)(`gray`,AA)}`;function oj(e,t){let n=e.harness===void 0?t.selection?.targets||Object.keys(t.previous):e.harness===`none`?[]:e.harness.split(`,`).map(RO);if(e.harness===void 0&&!t.selection&&!n.length)throw Error(`--harness <claude-code,codex,cursor,gemini,opencode,pi,copilot,agy|none> is required. Use --harness none for CLI only.`);for(let e of n){if(!hO.some(t=>t.id===e))throw Error(`Unknown harness: ${e}`);if(!t.detected.includes(e))throw Error(`${e} not detected; install its CLI first or use --harness none.`)}let r=new Set(n.map(e=>t.previous[e]?.mode).filter(Boolean)),i=e.mode||(e.harness===void 0?t.selection?.mode:void 0)||(r.size===1?[...r][0]:void 0);if(i!==`artifacts`&&i!==`full`)throw Error(`--mode artifacts|full is required without an interactive terminal.`);return{root:t.root,binDir:t.binDir,mode:i,targets:[...new Set(n)]}}async function sj(e,t,n){let r=n?.mode||e.selection?.mode||Object.values(e.previous)[0]?.mode||`artifacts`,i=n?.targets||e.selection?.targets||Object.keys(e.previous),a=!!n,o=n?`review`:`mode`;for(;;){if(o===`mode`){let e=await t.mode(r);if(e===null)return null;r=e,o=a?`review`:`targets`}if(o===`targets`){let e=await t.targets(i);if(e===null)return null;i=e,a=!0,o=`review`}let n=oj({mode:r,harness:i.join(`,`)||`none`},e),s=await t.review(n);if(s===`cancel`)return null;if(s===`apply`)return n;o=s}}async function cj(e,t){let n=process.stderr;ZA(`Artideck · Install`,{output:n});let r=await sj(e,{async mode(e){ej(`Artifacts: the artifacts and interface-craft skills. Documents, artboards,
|
|
947
947
|
whiteboards and HTML pages with comments. Your agent sessions start as before.
|
|
948
948
|
|
|
949
949
|
Full workflow: Artifacts plus brainstorming, specs, TDD, debugging, git
|
|
950
950
|
worktrees and verification skills. Injects the Artideck workflow into every
|
|
951
|
-
new session. Rerun install to switch.`,`Content`,{output:n});let t=await
|
|
952
|
-
`),`Unavailable`,{output:n}),!e.detected.length)return[];let i=await
|
|
953
|
-
`),`Installation plan`,{output:n});let r=await ij({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return uA(r)?`cancel`:r}},t);return r||YA(`Cancelled. No installation changes made.`,{output:n}),r}function cj(){return tj({output:process.stderr,onCancel:()=>{}})}function lj(e){for(let t of[`package.json`,`.codex-plugin/plugin.json`])try{let n=JSON.parse(d.default.readFileSync(f.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 uj(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 dj(e,t){let n=uj(t),r=[],i;try{i=Object.values(RO(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&oO(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&aO(e.registration,n).path:e.path;if(!t)continue;let i=f.default.join(t,`skills/artifacts/app/hook-bin.sh`);if(!d.default.existsSync(i))continue;let a=lj(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!d.default.readFileSync(i,`utf8`).includes(`.ryugi/hook`)})}catch{a=!1}return{plugins:r,complete:a}}function fj(e,t){return dj(e,t.run).plugins}function pj(e,t,n){let r=dj(e,t);return Ek(n,r),r}function mj(e){let t=[],n=[];if(e.status!==`done`)return{warnings:t,actions:n};for(let r of e.failed)t.push({code:`W_HOOK_BINARY`,severity:`warning`,message:`ryugi-hook ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`adeck`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function hj(e,t){let n=/* @__PURE__ */ new Map,r=t?1:25,i=null;return{report(a,o,s){let c=s?` ${Math.floor(Math.floor(o/s*100)/r)*r}%`:t?` ${(o/1048576).toFixed(1)} MB`:``;if(n.get(a)===c)return;n.set(a,c);let l=`Downloading ryugi-hook ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=cj()).start(l)},finish(){i?.stop(`Downloaded ryugi-hook ${[...n.keys()].join(`, `)}`)}}}async function gj(e,t,n){let r=hj(t,n);try{return await _j({...e,progress:r.report})}finally{r.finish()}}function _j(e){return vj(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function vj(e){let t=h.default.homedir(),n=He().home;if(f.default.resolve(n)!==f.default.join(t,`.ryugi`,`server`))return{status:`other-hub`};let r=pj(e.root??kO(),e.run??hO,t);return Ak({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.113.2`})}const yj=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(f.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;function bj(e,t={}){let n=[],r=new FO(e).current();if(r){let i=new FO(e,t.binDir||f.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=IO(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:d.default.existsSync(f.default.join(r.packageRoot,e))?`ok`:`attention`,message:f.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(RO(e).harnesses))try{if(r.harness===`claude-code`){let e=f.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||f.default.join(t.home||h.default.homedir(),`.claude`),`settings.json`);if(!JSON.parse(d.default.readFileSync(e,`utf8`)).enabledPlugins?.[r.registration])throw Error(`Recorded Claude plugin is not enabled at user scope`);if(!sO(r,t.run||hO))throw Error(`Native Claude source no longer matches the record`)}else if(yO(r,vO(r.harness,{root:e,home:t.home})),!sO(r,t.run||hO))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=Ck(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||h.default.homedir(),a=ut(process.platform,process.arch);for(let r of fj(e,{run:t.run||hO})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.ryugi/hook; run adeck update to refresh it`});continue}if(!a)continue;let t=f.default.join(lt(i,r.version),`ryugi-hook`);n.push(d.default.existsSync(t)?{component:e,status:`ok`,message:t}:{component:e,status:`attention`,message:`no ryugi-hook ${r.version}, so this plugin's hooks skip; run adeck hook install ${r.version}`})}return n.push(xj(t)),n}function xj(e){let t=`agent-browser`,n=hk({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=_k(n);return{component:t,status:`ok`,message:r?`${n} (${r})`:n}}function Sj(e,t={}){let n=RO(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||hO;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(![`ryugi@ryugi-dev`,`ryugi-artifacts@ryugi-dev`].includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=oO(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(yO(o,vO(a,{root:e,home:t.home})),!sO(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,`ryugi@ryugi-managed`]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,`ryugi@ryugi-managed`]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,`ryugi`]),a===`opencode`){let e=t.env||process.env,n=f.default.join(e.XDG_CONFIG_HOME||f.default.join(t.home||h.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!d.default.existsSync(n)||d.default.readFileSync(n,`utf8`)!==yj(o.path))throw Error(`Plugin entry was changed; preserving ${n}`);d.default.unlinkSync(n)}d.default.rmSync(o.path,{recursive:!0})}delete n.harnesses[a],zO(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new FO(e).current();if(n){let i=new FO(e,t.binDir||f.default.dirname(n.bin));i.ownsBin()?(d.default.unlinkSync(i.bin),r.removed.push(`CLI command`)):r.failures.push({component:`CLI command`,message:`Command changed; preserving ${i.bin}`}),i.ownsAlias()&&d.default.unlinkSync(i.aliasBin)}}return r}const Cj={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=>Q({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(){let t=bj(f.default.resolve(e.values[`install-dir`]||kO()));return Y({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})},present:({data:e})=>({heading:`Doctor`,status:e.checks.some(e=>e.status===`attention`)?`attention`:`ok`,facts:[],sections:[{kind:`records`,key:`checks`,rows:e.checks.map(e=>({...e})),columns:[{key:`component`,required:!0},{key:`status`,required:!0},{key:`message`,required:!0}]}]})},e)},wj=/<head(\s[^>]*)?>/i,Tj=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,Ej=/^<script>([\s\S]*?)<\/script>/,Dj=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function Oj(e){let t=wj.exec(e);return t?t.index+t[0].length:Tj.exec(e)?.[0].length??0}function kj(e){let t=Oj(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=Ej.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(Dj,``)}function Aj(e,t=4){let n=0,r;try{r=d.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.isSymbolicLink())continue;let r=f.default.join(e,i.name);i.isDirectory()?t>0&&(n=Math.max(n,Aj(r,t-1))):i.isFile()&&(n=Math.max(n,d.default.statSync(r).mtimeMs))}return n}const jj=e=>{let t=Aj(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function Mj(e){let t=/* @__PURE__ */ new Set([...Object.keys(ZC),`artifact`,`source`]),n=Object.keys(e.values).find(e=>!t.has(e));if(n)throw new J({code:`E_ARGUMENT_INVALID`,message:`--${n} applies to Cloud reads only. Local reads accept --artifact, --detail or --source.`});let r=e.values.artifact;r&&hC(e.projectDir,r);let i=!!e.values.source||e.values.format===`source`;if(i&&!r)throw new J({code:`E_ARGUMENT_INVALID`,message:`Local --source requires --artifact <type>/<id>.`});let{project:a,root:o}=ce(e.projectDir);return Q({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:[]}:Pe(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=hC(a,r);if(i.content===`existing`){let e=d.default.realpathSync(i.write);if(!e.startsWith(`${o}${f.default.sep}`))throw new J({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source escapes its project: ${i.write}`});let t=d.default.statSync(e);if(!t.isFile())throw new J({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?jj(n):{}}}return{artifact:r,...i,...n?jj(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 J({code:`E_ARTIFACT_NOT_FOUND`,message:`Content not written yet: ${c[0]?.write}`});let e=d.default.readFileSync(c[0].write);l=e.toString(`utf8`),p=u.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&&Ae(m)&&h&&c[0]?.content===`existing`?iC[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 Y({origin:`local`,project:a,complete:!0,...r?{}:{server:await DT()},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?[lw([`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`}]},...k.flatMap(t=>{let n=iC[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 Nj({data:e}){let t=Ae(e.type)?iC[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:[Z(`Title`,X(e,`title`)),...e.saved?[Z(`Saved`,X(e,`saved`),!0),Z(`Bytes`,X(e,`bytes`))]:[],...e.dir?[Z(`Downloaded`,X(e,`dir`),!0)]:e.files?[Z(`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:Kg.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...IE(e.comments.threads,`comments`),title:`Published snapshot comments`}]:[]]}}const Pj=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,Fj=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!f.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function Ij(e,t,n){if(!e.contentBase||!Array.isArray(e.files))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return a complete download manifest.`});if(e.files.some(e=>!Fj(e)))throw new J({code:`E_FILE_PATH_UNSAFE`,message:`The manifest contains an unsafe file path.`});if(d.default.existsSync(t))throw new J({code:`E_FILE_EXISTS`,message:`Download directory already exists: ${t}`});d.default.mkdirSync(f.default.dirname(t),{recursive:!0}),d.default.mkdirSync(t,{mode:448});for(let r of e.files){let i=f.default.join(t,...r.split(`/`)),a=n.effects.begin(`download`,i);try{let t=await fetch(`${e.contentBase}${r.split(`/`).map(encodeURIComponent).join(`/`)}`,{headers:nt,signal:n.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);d.default.mkdirSync(f.default.dirname(i),{recursive:!0});let o=Buffer.from(await t.arrayBuffer()),s=hE(i,r.endsWith(`.html`)?kj(o.toString(`utf8`)):o);n.effects.confirm(a,{bytes:s.bytes})}catch(e){throw n.effects.set(a,`failed`,{message:e.message}),new J({code:`E_DOWNLOAD_FAILED`,message:`Could not download ${r}: ${e.message}`})}}}function Lj(e){let t=e.positionals[0];if(!t)return Mj(e);if(e.values.artifact)throw new J({code:`E_OPTION_CONFLICT`,message:`Choose a local --artifact or a Cloud link/id, not both.`});let{origin:n,id:r,grant:i}=Vj(t,ie(process.env)),a=Pj(e,`save`);if(a!==void 0&&!a.trim())throw new J({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});let o=!!e.values.source||e.values.format===`source`||a!==void 0,s=Pj(e,`block`),c=Pj(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||Pj(e,`fields`)||Pj(e,`cursor`)||Pj(e,`limit`)))throw new J({code:`E_OPTION_CONFLICT`,message:`Source must be a complete document; use --snapshot to pin its version.`});if(s&&(l||u||Pj(e,`cursor`)))throw new J({code:`E_OPTION_CONFLICT`,message:`--block reads one complete block and cannot combine with detail, cursor or download.`});let d=Pj(e,`limit`);if(d&&(!/^\d+$/.test(d)||+d<1||+d>100))throw new J({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=Pj(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`),Q({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(d,m){let g=qn(Jn(process.env,process.platform,h.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:g?{...nt,Authorization:`Bearer ${g.token}`}:nt,signal:m.signal}),v=await _.text();m.payloads.raw=v;let y;try{y=JSON.parse(v)}catch{throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`})}if(!_.ok)throw new J({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 J({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 J({code:`E_FORMAT_UNSUPPORTED`,message:`Source is available for documents only.`});m.payloads.source=y.content,a&&(b=hE(a,y.content,m.effects),m.payloads.source=``,(e.values.source||e.values.format===`source`)&&m.diagnostic(`Saved ${b.file} (${b.bytes} bytes)`))}let{schema:x,page:S,contentBase:C,...w}=y,T={...w,...b?{saved:b.file,bytes:b.bytes}:{},status:l?`downloaded`:u||s?`read`:`available`};if(b&&delete T.content,l){T.dir=f.default.resolve(c??f.default.join(process.env.XDG_CACHE_HOME||f.default.join(h.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await Ij(y,T.dir,m)}catch(e){if(!m.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=m.effects.snapshot(),Y(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=m.effects.snapshot()}let E=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),ee=[`get`,...E,`--snapshot`,y.snapshot],te=[`get`,...E,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return Y(T,void 0,{coverage:{page:S,...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[lw([...ee,`--detail`,`--`,t],`Details`)]:[],...!s&&!o&&!l&&y.page?.nextCursor?[lw(te,`More`)]:[]]})},present:Nj},e)}const Rj=/^[\w-]{1,64}$/,zj=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,Bj=`Expected an Artideck Cloud link (https://<host>/a/<id>) or an artifact id.`;function Vj(e,t){if(Rj.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new M(Bj)}let r=zj.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new M(Bj);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:D(n.origin),id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const Hj={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:Lj,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 Uj({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[Z(`Version`,X(e,`version`))],sections:[]}}const Wj={name:`hook`,summary:`Download the ryugi-hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads ryugi-hook for this platform from the plugin release of <version>, checks its sha256 and keeps it in ~/.ryugi/hook/<version>. The plugin launcher runs it with --background when a hook finds no binary; that waits out the retry delay after a failed download, which a person running it skips.`,positionals:2,options:{background:{type:`boolean`,help:`Wait out the retry delay after a failed download`}},semantic:e=>Q({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 M(`Usage: adeck hook install <version>`);if(!n||!at(n))throw new M(`hook install needs a release version, not ${n??`nothing`}`);let r=await mt({arch:process.arch,fetch,home:h.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),Y(a,i?{kind:`succeeded`}:{kind:`failed`,error:{code:`E_HOOK_INSTALL`,message:r.error??`ryugi-hook ${n} is not available here (${r.status})`}})},present:Uj},e)},Gj=`icons/index.json`,Kj=/* @__PURE__ */ new Map;function qj(e){let t=Kj.get(e);if(t===void 0){try{t=JSON.parse(d.default.readFileSync(f.default.join(e,Gj),`utf8`))}catch{t=null}Kj.set(e,t??null)}return t??null}const Jj=e=>e.toLowerCase().match(/[a-z0-9]+/g)??[];function Yj(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=>Jj(t).some(t=>t.startsWith(e))):i<3?4:i<8?3:2}function Xj(e,t,n=10){let r=Jj(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=Yj(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 Zj({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 Qj={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 M(`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 M(`--limit must be a whole number from 1 to 50`);return Q({id:`icons`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`name`,`tags`,`aliases`],collection:`icons`,requiredFields:[`name`]},run:()=>{let e=f.default.join(__dirname,`runtime`),n=qj(e);if(!n)throw new M(`This install has no icon index: ${f.default.join(e,Gj)}`);return Y({query:t,icons:Xj(n,t,r)})},present:Zj},e)}},$j=`Innei/ryugi`,eM={artifacts:`ryugi-artifacts@ryugi-dev`,full:`ryugi@ryugi-dev`};function tM(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function nM(e){let{command:t,args:n,shell:r}=tM(e);return(0,p.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function rM(e){let t=nM(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 iM(){let e=nM([`--version`]);return!e.error&&e.status===0}function aM(e){if(!d.default.existsSync(e))return{};let t=JSON.parse(d.default.readFileSync(e,`utf8`)).enabledPlugins;return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function oM(){let e=JSON.parse(rM([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===`ryugi-dev`)}function sM(e){let t=JSON.parse(rM([`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 cM=e=>e===`artifacts`||e===`full`;async function lM(e,t,n){let r=e=>Y({mode:null,harness:`claude-code`,installed:null,disabled:[]},{kind:`validation_failed`},{warnings:[{code:`W_INSTALL_MODE`,message:e,severity:`error`}]});if(e!==void 0&&!cM(e))return r(`--mode takes artifacts or full`);if(!iM())return Y({mode:cM(e)?e:null,harness:`none`,installed:null,disabled:[]},{kind:`succeeded`},{warnings:[{code:`W_NO_CLAUDE_CODE`,message:`Claude Code was not found; artifacts only is Claude Code only. Install the full plugin by hand on other harnesses.`,severity:`warning`}],actions:[{kind:`url`,label:`Install guide`,url:`https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||f.default.join(h.default.homedir(),`.claude`),a=aM(f.default.join(i,`settings.json`));if(!cM(e))return r(`--mode artifacts|full is required`);let o=e,s=eM[o],c=eM[o===`artifacts`?`full`:`artifacts`],l=(e,t,r)=>{let i=n?.begin(e,t);rM(r),i!==void 0&&n.confirm(i)};oM()||l(`install.marketplace`,$j,[`plugin`,`marketplace`,`add`,$j,`--scope`,`user`]),l(`install.refresh`,`ryugi-dev`,[`plugin`,`marketplace`,`update`,`ryugi-dev`]),sM(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];a[c]===!0&&(l(`install.disable`,c,[`plugin`,`disable`,c,`--scope`,`user`]),u.push(c));let d=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]])aM(f.default.join(t,`.claude`,n))[c]===!0&&(d.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${c} is still enabled at ${e} scope; enable only one Artideck entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,c,`--scope`,e],label:`Disable at ${e} scope`}));return Y({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:d,actions:p})}async function uM(e,t,n=!1,r=!1){let i={bin:null,mode:null,owner:null,targets:[]},a=e=>Y(i,{kind:`validation_failed`},{warnings:[{code:`E_INSTALL_PLAN`,message:e,severity:`error`}]}),o=f.default.resolve(e.values[`install-dir`]||kO()),s=new FO(o).current(),c=f.default.resolve(e.values[`bin-dir`]||(s?f.default.dirname(s.bin):AO())),l=RO(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`?[]:gO()).filter(e=>e.detected).map(e=>e.id),m={...l.harnesses},g=f.default.join(process.env.CLAUDE_CONFIG_DIR||f.default.join(h.default.homedir(),`.claude`),`settings.json`);if(!m[`claude-code`]&&p.includes(`claude-code`)&&d.default.existsSync(g)){let e=JSON.parse(d.default.readFileSync(g,`utf8`)).enabledPlugins||{},t=e[`ryugi@ryugi-dev`]===!0?`full`:e[`ryugi-artifacts@ryugi-dev`]===!0?`artifacts`:null;t&&(m[`claude-code`]={harness:`claude-code`,mode:t,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:p,previous:m,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=aj({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await sj(_,t)}else v=aj({mode:e.values.mode,harness:e.values.harness},_)}catch(e){return a(e.message)}if(!v)return Y(i,{kind:`interrupted`,signal:`SIGINT`});i.mode=v.mode;let y=[],b=[],x=n?cj():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=OO(__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 FO(o,c);e.preflight();let n=t.effects.begin(`install.runtime`,o),r=e.install(f.default.resolve(__dirname,`..`));t.effects.confirm(n,r),i.bin=r.bin,i.owner=`ryugi`,x?.stop(`Persistent CLI installed`);let a=IO(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&&oO(r,hO)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await lM(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=aO(a.data.installed,hO);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=fO(o,e.values[`plugin-version`]||`1.113.2`),C=!0));let r=f.default.join(o,`candidates`,(0,u.randomUUID)());try{let e=dO(S,r,v.mode);l.harnesses[n]=bO(n,e,{root:o,previous:l.harnesses[n],effects:t.effects})}finally{d.default.rmSync(r,{recursive:!0,force:!0})}i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:l.harnesses[n].path})}zO(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. ${mO.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&&d.default.rmSync(S,{recursive:!0,force:!0})}r||(l.selection={mode:v.mode,targets:v.targets});let T=t.effects.begin(`install.selection`,o);zO(o,l),t.effects.confirm(T);let E=mj(await gj({cleanup:!1,root:o},t,n));y.push(...E.warnings);let ee=i.targets.filter(e=>e.status===`failed`),te=ee.length?[{kind:`command`,argv:[`adeck`,`install`,`--mode`,v.mode,`--harness`,ee.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 te.push(...b,...E.actions),t.signal.aborted?Y(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:te}):Y(i,ee.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:ee.map(e=>`${e.harness}: ${e.error}`).join(`
|
|
954
|
-
`)}}:{kind:`succeeded`},{warnings:y,actions:te})}function
|
|
951
|
+
new session. Rerun install to switch.`,`Content`,{output:n});let t=await aj({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 dA(t)?null:t},async targets(t){let r=hO.filter(t=>!e.detected.includes(t.id));if(r.length&&ej(r.map(e=>`${e.label}: ${e.command} not found`).join(`
|
|
952
|
+
`),`Unavailable`,{output:n}),!e.detected.length)return[];let i=await YA({output:n,message:`Install into which harnesses? (empty = CLI only)`,required:!1,initialValues:t,options:hO.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 dA(i)?null:i},async review(t){ej([`CLI: ${t.root}`,`Command: ${t.binDir}`,`Content: ${t.mode}`,...t.targets.map(n=>`${n}: ${e.previous[n]?.mode||`new`} → ${t.mode}; ${hO.find(e=>e.id===n).comments}`),...t.targets.length?[`Start a new harness session after installation.`]:[`CLI only; no harness plugins.`]].join(`
|
|
953
|
+
`),`Installation plan`,{output:n});let r=await aj({output:n,message:`Continue?`,options:[{value:`apply`,label:`Install`},{value:`mode`,label:`Change content`},{value:`targets`,label:`Change targets`},{value:`cancel`,label:`Cancel`}]});return dA(r)?`cancel`:r}},t);return r||XA(`Cancelled. No installation changes made.`,{output:n}),r}function lj(){return nj({output:process.stderr,onCancel:()=>{}})}function uj(e){for(let t of[`package.json`,`.codex-plugin/plugin.json`])try{let n=JSON.parse(d.default.readFileSync(f.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 dj(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 fj(e,t){let n=dj(t),r=[],i;try{i=Object.values(zO(e).harnesses)}catch{return{plugins:r,complete:!1}}let a=!0;for(let e of i)try{if(e.harness===`claude-code`&&sO(e,n)!==`owned`)continue;let t=e.harness===`claude-code`?e.registration&&oO(e.registration,n).path:e.path;if(!t)continue;let i=f.default.join(t,`skills/artifacts/app/hook-bin.sh`);if(!d.default.existsSync(i))continue;let a=uj(t);if(!a)continue;r.push({harness:e.harness,version:a,legacy:!d.default.readFileSync(i,`utf8`).includes(`.ryugi/hook`)})}catch{a=!1}return{plugins:r,complete:a}}function pj(e,t){return fj(e,t.run).plugins}function mj(e,t,n){let r=fj(e,t);return Dk(n,r),r}function hj(e){let t=[],n=[];if(e.status!==`done`)return{warnings:t,actions:n};for(let r of e.failed)t.push({code:`W_HOOK_BINARY`,severity:`warning`,message:`ryugi-hook ${r.version} was not downloaded (${r.error}); plugin hooks skip until it is.`}),r.version!==`unknown`&&n.push({kind:`command`,argv:[`adeck`,`hook`,`install`,r.version],label:`Download the hook binary`});return{warnings:t,actions:n}}function gj(e,t){let n=/* @__PURE__ */ new Map,r=t?1:25,i=null;return{report(a,o,s){let c=s?` ${Math.floor(Math.floor(o/s*100)/r)*r}%`:t?` ${(o/1048576).toFixed(1)} MB`:``;if(n.get(a)===c)return;n.set(a,c);let l=`Downloading ryugi-hook ${[...n].map(([e,t])=>e+t).join(` · `)}`;if(!t)return e.progress({phase:l});i?i.message(l):(i=lj()).start(l)},finish(){i?.stop(`Downloaded ryugi-hook ${[...n.keys()].join(`, `)}`)}}}async function _j(e,t,n){let r=gj(t,n);try{return await vj({...e,progress:r.report})}finally{r.finish()}}function vj(e){return yj(e).catch(e=>({status:`done`,failed:[{version:`unknown`,error:e.message}],prefetched:[],removed:[]}))}async function yj(e){let t=h.default.homedir(),n=He().home;if(f.default.resolve(n)!==f.default.join(t,`.ryugi`,`server`))return{status:`other-hub`};let r=mj(e.root??AO(),e.run??gO,t);return jk({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.114.0`})}const bj=e=>`export { default, RyugiPlugin } from ${JSON.stringify((0,v.pathToFileURL)(f.default.join(e,`.opencode/plugins/ryugi.js`)).href)};\n`;function xj(e,t={}){let n=[],r=new IO(e).current();if(r){let i=new IO(e,t.binDir||f.default.dirname(r.bin));n.push({component:`CLI command`,status:i.ownsBin()?`ok`:`attention`,message:i.bin});let a=LO(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:d.default.existsSync(f.default.join(r.packageRoot,e))?`ok`:`attention`,message:f.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(zO(e).harnesses))try{if(r.harness===`claude-code`){let e=f.default.join((t.env||process.env).CLAUDE_CONFIG_DIR||f.default.join(t.home||h.default.homedir(),`.claude`),`settings.json`);if(!JSON.parse(d.default.readFileSync(e,`utf8`)).enabledPlugins?.[r.registration])throw Error(`Recorded Claude plugin is not enabled at user scope`);if(!cO(r,t.run||gO))throw Error(`Native Claude source no longer matches the record`)}else if(bO(r,yO(r.harness,{root:e,home:t.home})),!cO(r,t.run||gO))throw Error(`Native registration does not match the owned source`);let i=`${r.mode} · ${r.version}`;if(r.harness===`codex`){let e=wk(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||h.default.homedir(),a=ut(process.platform,process.arch);for(let r of pj(e,{run:t.run||gO})){let e=`${r.harness} hook`;if(r.legacy){n.push({component:e,status:`attention`,message:`plugin ${r.version} predates ~/.ryugi/hook; run adeck update to refresh it`});continue}if(!a)continue;let t=f.default.join(lt(i,r.version),`ryugi-hook`);n.push(d.default.existsSync(t)?{component:e,status:`ok`,message:t}:{component:e,status:`attention`,message:`no ryugi-hook ${r.version}, so this plugin's hooks skip; run adeck hook install ${r.version}`})}return n.push(Sj(t)),n}function Sj(e){let t=`agent-browser`,n=gk({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=vk(n);return{component:t,status:`ok`,message:r?`${n} (${r})`:n}}function Cj(e,t={}){let n=zO(e),r={removed:[],failures:[],preserved:[`Project artifacts, comments, harness plugin data and runtime caches are retained.`]},i=t.run||gO;for(let a of t.targets||Object.keys(n.harnesses)){let o=n.harnesses[a];if(o)try{if(a===`claude-code`){if(![`ryugi@ryugi-dev`,`ryugi-artifacts@ryugi-dev`].includes(o.registration||``))throw Error(`Unknown native Claude plugin identity`);let e=sO(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(bO(o,yO(a,{root:e,home:t.home})),!cO(o,i))throw Error(`Native plugin source changed; preserving it`);if(a===`codex`&&i(`codex`,[`plugin`,`remove`,`ryugi@ryugi-managed`]),a===`copilot`&&i(`copilot`,[`plugin`,`uninstall`,`ryugi@ryugi-managed`]),a===`pi`&&i(`pi`,[`remove`,o.path]),a===`gemini`&&i(`gemini`,[`extensions`,`uninstall`,`ryugi`]),a===`agy`&&i(`agy`,[`plugin`,`uninstall`,`ryugi`]),a===`opencode`){let e=t.env||process.env,n=f.default.join(e.XDG_CONFIG_HOME||f.default.join(t.home||h.default.homedir(),`.config`),`opencode/plugins/ryugi.js`);if(!d.default.existsSync(n)||d.default.readFileSync(n,`utf8`)!==bj(o.path))throw Error(`Plugin entry was changed; preserving ${n}`);d.default.unlinkSync(n)}d.default.rmSync(o.path,{recursive:!0})}delete n.harnesses[a],BO(e,n),r.removed.push(a)}catch(e){r.failures.push({component:a,message:e.message})}}if(!t.targets){let n=new IO(e).current();if(n){let i=new IO(e,t.binDir||f.default.dirname(n.bin));i.ownsBin()?(d.default.unlinkSync(i.bin),r.removed.push(`CLI command`)):r.failures.push({component:`CLI command`,message:`Command changed; preserving ${i.bin}`}),i.ownsAlias()&&d.default.unlinkSync(i.aliasBin)}}return r}const wj={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=>Q({id:`doctor`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(){let t=xj(f.default.resolve(e.values[`install-dir`]||AO()));return Y({checks:t},t.some(e=>e.status===`attention`)?{kind:`action_required`,reason:`Some installation components need attention`}:{kind:`succeeded`})},present:({data:e})=>({heading:`Doctor`,status:e.checks.some(e=>e.status===`attention`)?`attention`:`ok`,facts:[],sections:[{kind:`records`,key:`checks`,rows:e.checks.map(e=>({...e})),columns:[{key:`component`,required:!0},{key:`status`,required:!0},{key:`message`,required:!0}]}]})},e)},Tj=/<head(\s[^>]*)?>/i,Ej=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,Dj=/^<script>([\s\S]*?)<\/script>/,Oj=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function kj(e){let t=Tj.exec(e);return t?t.index+t[0].length:Ej.exec(e)?.[0].length??0}function Aj(e){let t=kj(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=Dj.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(Oj,``)}function jj(e,t=4){let n=0,r;try{r=d.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.isSymbolicLink())continue;let r=f.default.join(e,i.name);i.isDirectory()?t>0&&(n=Math.max(n,jj(r,t-1))):i.isFile()&&(n=Math.max(n,d.default.statSync(r).mtimeMs))}return n}const Mj=e=>{let t=jj(e);return t?{updatedAt:new Date(t).toISOString()}:{}};function Nj(e){let t=/* @__PURE__ */ new Set([...Object.keys(ZC),`artifact`,`source`]),n=Object.keys(e.values).find(e=>!t.has(e));if(n)throw new J({code:`E_ARGUMENT_INVALID`,message:`--${n} applies to Cloud reads only. Local reads accept --artifact, --detail or --source.`});let r=e.values.artifact;r&&hC(e.projectDir,r);let i=!!e.values.source||e.values.format===`source`;if(i&&!r)throw new J({code:`E_ARGUMENT_INVALID`,message:`Local --source requires --artifact <type>/<id>.`});let{project:a,root:o}=ce(e.projectDir);return Q({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:[]}:Pe(o),c=s.artifacts.map(({type:e,id:t,dir:n})=>{let r=`${e}/${t}`,i=hC(a,r);if(i.content===`existing`){let e=d.default.realpathSync(i.write);if(!e.startsWith(`${o}${f.default.sep}`))throw new J({code:`E_FILE_PATH_UNSAFE`,message:`Artifact source escapes its project: ${i.write}`});let t=d.default.statSync(e);if(!t.isFile())throw new J({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?Mj(n):{}}}return{artifact:r,...i,...n?Mj(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 J({code:`E_ARTIFACT_NOT_FOUND`,message:`Content not written yet: ${c[0]?.write}`});let e=d.default.readFileSync(c[0].write);l=e.toString(`utf8`),p=u.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&&Ae(m)&&h&&c[0]?.content===`existing`?iC[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 Y({origin:`local`,project:a,complete:!0,...r?{}:{server:await DT()},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?[lw([`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`}]},...k.flatMap(t=>{let n=iC[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 Pj({data:e}){let t=Ae(e.type)?iC[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:[Z(`Title`,X(e,`title`)),...e.saved?[Z(`Saved`,X(e,`saved`),!0),Z(`Bytes`,X(e,`bytes`))]:[],...e.dir?[Z(`Downloaded`,X(e,`dir`),!0)]:e.files?[Z(`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:Kg.replace(/[::]$/,``),text:e.prompt}],...e.content===void 0?[]:[{kind:`content`,key:`content`,title:`LiteXML`,text:e.content}],...e.comments?[{...IE(e.comments.threads,`comments`),title:`Published snapshot comments`}]:[]]}}const Fj=(e,t)=>typeof e.values[t]==`string`?e.values[t]:void 0,Ij=e=>!!e&&!e.includes(`\\`)&&!e.includes(`\0`)&&!f.default.posix.isAbsolute(e)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`);async function Lj(e,t,n){if(!e.contentBase||!Array.isArray(e.files))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return a complete download manifest.`});if(e.files.some(e=>!Ij(e)))throw new J({code:`E_FILE_PATH_UNSAFE`,message:`The manifest contains an unsafe file path.`});if(d.default.existsSync(t))throw new J({code:`E_FILE_EXISTS`,message:`Download directory already exists: ${t}`});d.default.mkdirSync(f.default.dirname(t),{recursive:!0}),d.default.mkdirSync(t,{mode:448});for(let r of e.files){let i=f.default.join(t,...r.split(`/`)),a=n.effects.begin(`download`,i);try{let t=await fetch(`${e.contentBase}${r.split(`/`).map(encodeURIComponent).join(`/`)}`,{headers:nt,signal:n.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);d.default.mkdirSync(f.default.dirname(i),{recursive:!0});let o=Buffer.from(await t.arrayBuffer()),s=hE(i,r.endsWith(`.html`)?Aj(o.toString(`utf8`)):o);n.effects.confirm(a,{bytes:s.bytes})}catch(e){throw n.effects.set(a,`failed`,{message:e.message}),new J({code:`E_DOWNLOAD_FAILED`,message:`Could not download ${r}: ${e.message}`})}}}function Rj(e){let t=e.positionals[0];if(!t)return Nj(e);if(e.values.artifact)throw new J({code:`E_OPTION_CONFLICT`,message:`Choose a local --artifact or a Cloud link/id, not both.`});let{origin:n,id:r,grant:i}=Hj(t,ie(process.env)),a=Fj(e,`save`);if(a!==void 0&&!a.trim())throw new J({code:`E_ARGUMENT_INVALID`,message:`--save requires a nonempty file path.`});let o=!!e.values.source||e.values.format===`source`||a!==void 0,s=Fj(e,`block`),c=Fj(e,`out`),l=!!e.values.download||!!c,u=!!e.values.detail||o;if(o&&(s||l||Fj(e,`fields`)||Fj(e,`cursor`)||Fj(e,`limit`)))throw new J({code:`E_OPTION_CONFLICT`,message:`Source must be a complete document; use --snapshot to pin its version.`});if(s&&(l||u||Fj(e,`cursor`)))throw new J({code:`E_OPTION_CONFLICT`,message:`--block reads one complete block and cannot combine with detail, cursor or download.`});let d=Fj(e,`limit`);if(d&&(!/^\d+$/.test(d)||+d<1||+d>100))throw new J({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=Fj(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`),Q({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(d,m){let g=qn(Jn(process.env,process.platform,h.default.homedir()),n),_=await fetch(`${n}/api/a/${r}?${new URLSearchParams([...p,...Object.entries(i??{})])}`,{headers:g?{...nt,Authorization:`Bearer ${g.token}`}:nt,signal:m.signal}),v=await _.text();m.payloads.raw=v;let y;try{y=JSON.parse(v)}catch{throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The Cloud server returned an unsupported read response.`})}if(!_.ok)throw new J({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 J({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 J({code:`E_FORMAT_UNSUPPORTED`,message:`Source is available for documents only.`});m.payloads.source=y.content,a&&(b=hE(a,y.content,m.effects),m.payloads.source=``,(e.values.source||e.values.format===`source`)&&m.diagnostic(`Saved ${b.file} (${b.bytes} bytes)`))}let{schema:x,page:S,contentBase:C,...w}=y,T={...w,...b?{saved:b.file,bytes:b.bytes}:{},status:l?`downloaded`:u||s?`read`:`available`};if(b&&delete T.content,l){T.dir=f.default.resolve(c??f.default.join(process.env.XDG_CACHE_HOME||f.default.join(h.default.homedir(),`.cache`),`ryugi`,`get`,r,`v${y.version}`));try{await Lj(y,T.dir,m)}catch(e){if(!m.effects.snapshot().some(e=>e.state===`confirmed`))throw e;return T.status=`partial`,T.downloads=m.effects.snapshot(),Y(T,{kind:`partial`},{warnings:[{code:`W_DOWNLOAD_PARTIAL`,message:e.message}]})}T.downloads=m.effects.snapshot()}let E=[...p.entries()].filter(([e])=>![`semantic`,`cursor`,`snapshot`,`detail`,`download`].includes(e)).flatMap(([e,t])=>e===`no-comments`?[`--${e}`]:[`--${e}`,t]),ee=[`get`,...E,`--snapshot`,y.snapshot],te=[`get`,...E,...u?[`--detail`]:[],`--cursor`,y.page?.nextCursor??``,`--`,t];return Y(T,void 0,{coverage:{page:S,...!u&&!s?{omitted:[{path:`data.content`,reason:`summary`}]}:{}},actions:[...!u&&!s?[lw([...ee,`--detail`,`--`,t],`Details`)]:[],...!s&&!o&&!l&&y.page?.nextCursor?[lw(te,`More`)]:[]]})},present:Pj},e)}const zj=/^[\w-]{1,64}$/,Bj=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,Vj=`Expected an Artideck Cloud link (https://<host>/a/<id>) or an artifact id.`;function Hj(e,t){if(zj.test(e))return{origin:t,id:e};let n;try{n=new URL(e)}catch{throw new M(Vj)}let r=Bj.exec(n.pathname)?.[1];if(!r||n.protocol!==`https:`&&n.protocol!==`http:`)throw new M(Vj);let i=n.searchParams.get(`key`),a=n.searchParams.get(`via`);return{origin:D(n.origin),id:r,...i?{grant:{key:i,...a?{via:a}:{}}}:{}}}const Uj={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:Rj,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 Wj({data:e}){return{heading:`Hook`,status:e.status,summary:e.error??``,facts:[Z(`Version`,X(e,`version`))],sections:[]}}const Gj={name:`hook`,summary:`Download the ryugi-hook binary a plugin version runs its hooks with`,usage:[`install <version> [--background]`],details:`install downloads ryugi-hook for this platform from the plugin release of <version>, checks its sha256 and keeps it in ~/.ryugi/hook/<version>. The plugin launcher runs it with --background when a hook finds no binary; that waits out the retry delay after a failed download, which a person running it skips.`,positionals:2,options:{background:{type:`boolean`,help:`Wait out the retry delay after a failed download`}},semantic:e=>Q({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 M(`Usage: adeck hook install <version>`);if(!n||!at(n))throw new M(`hook install needs a release version, not ${n??`nothing`}`);let r=await mt({arch:process.arch,fetch,home:h.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),Y(a,i?{kind:`succeeded`}:{kind:`failed`,error:{code:`E_HOOK_INSTALL`,message:r.error??`ryugi-hook ${n} is not available here (${r.status})`}})},present:Wj},e)},Kj=`icons/index.json`,qj=/* @__PURE__ */ new Map;function Jj(e){let t=qj.get(e);if(t===void 0){try{t=JSON.parse(d.default.readFileSync(f.default.join(e,Kj),`utf8`))}catch{t=null}qj.set(e,t??null)}return t??null}const Yj=e=>e.toLowerCase().match(/[a-z0-9]+/g)??[];function Xj(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=>Yj(t).some(t=>t.startsWith(e))):i<3?4:i<8?3:2}function Zj(e,t,n=10){let r=Yj(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=Xj(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 Qj({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 $j={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 M(`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 M(`--limit must be a whole number from 1 to 50`);return Q({id:`icons`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`name`,`tags`,`aliases`],collection:`icons`,requiredFields:[`name`]},run:()=>{let e=f.default.join(__dirname,`runtime`),n=Jj(e);if(!n)throw new M(`This install has no icon index: ${f.default.join(e,Kj)}`);return Y({query:t,icons:Zj(n,t,r)})},present:Qj},e)}},eM=`Innei/ryugi`,tM={artifacts:`ryugi-artifacts@ryugi-dev`,full:`ryugi@ryugi-dev`};function nM(e,t=process.platform){return t===`win32`?{command:[`claude`,...e].join(` `),args:[],shell:!0}:{command:`claude`,args:e,shell:!1}}function rM(e){let{command:t,args:n,shell:r}=nM(e);return(0,p.spawnSync)(t,n,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],shell:r})}function iM(e){let t=rM(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 aM(){let e=rM([`--version`]);return!e.error&&e.status===0}function oM(e){if(!d.default.existsSync(e))return{};let t=JSON.parse(d.default.readFileSync(e,`utf8`)).enabledPlugins;return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function sM(){let e=JSON.parse(iM([`plugin`,`marketplace`,`list`,`--json`]));if(!Array.isArray(e))throw Error(`claude plugin marketplace list returned no list`);return e.some(e=>e?.name===`ryugi-dev`)}function cM(e){let t=JSON.parse(iM([`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 lM=e=>e===`artifacts`||e===`full`;async function uM(e,t,n){let r=e=>Y({mode:null,harness:`claude-code`,installed:null,disabled:[]},{kind:`validation_failed`},{warnings:[{code:`W_INSTALL_MODE`,message:e,severity:`error`}]});if(e!==void 0&&!lM(e))return r(`--mode takes artifacts or full`);if(!aM())return Y({mode:lM(e)?e:null,harness:`none`,installed:null,disabled:[]},{kind:`succeeded`},{warnings:[{code:`W_NO_CLAUDE_CODE`,message:`Claude Code was not found; artifacts only is Claude Code only. Install the full plugin by hand on other harnesses.`,severity:`warning`}],actions:[{kind:`url`,label:`Install guide`,url:`https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only`}]});let i=process.env.CLAUDE_CONFIG_DIR||f.default.join(h.default.homedir(),`.claude`),a=oM(f.default.join(i,`settings.json`));if(!lM(e))return r(`--mode artifacts|full is required`);let o=e,s=tM[o],c=tM[o===`artifacts`?`full`:`artifacts`],l=(e,t,r)=>{let i=n?.begin(e,t);iM(r),i!==void 0&&n.confirm(i)};sM()||l(`install.marketplace`,eM,[`plugin`,`marketplace`,`add`,eM,`--scope`,`user`]),l(`install.refresh`,`ryugi-dev`,[`plugin`,`marketplace`,`update`,`ryugi-dev`]),cM(s)?l(`install.update`,s,[`plugin`,`update`,s,`--scope`,`user`]):l(`install.plugin`,s,[`plugin`,`install`,s,`--scope`,`user`]);let u=[];a[c]===!0&&(l(`install.disable`,c,[`plugin`,`disable`,c,`--scope`,`user`]),u.push(c));let d=[],p=[];for(let[e,n]of[[`project`,`settings.json`],[`local`,`settings.local.json`]])oM(f.default.join(t,`.claude`,n))[c]===!0&&(d.push({code:`W_OTHER_VARIANT_ENABLED`,message:`${c} is still enabled at ${e} scope; enable only one Artideck entry`,severity:`warning`}),p.push({kind:`command`,argv:[`claude`,`plugin`,`disable`,c,`--scope`,e],label:`Disable at ${e} scope`}));return Y({mode:o,harness:`claude-code`,installed:s,disabled:u},{kind:`succeeded`},{warnings:d,actions:p})}async function dM(e,t,n=!1,r=!1){let i={bin:null,mode:null,owner:null,targets:[]},a=e=>Y(i,{kind:`validation_failed`},{warnings:[{code:`E_INSTALL_PLAN`,message:e,severity:`error`}]}),o=f.default.resolve(e.values[`install-dir`]||AO()),s=new IO(o).current(),c=f.default.resolve(e.values[`bin-dir`]||(s?f.default.dirname(s.bin):jO())),l=zO(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`?[]:_O()).filter(e=>e.detected).map(e=>e.id),m={...l.harnesses},g=f.default.join(process.env.CLAUDE_CONFIG_DIR||f.default.join(h.default.homedir(),`.claude`),`settings.json`);if(!m[`claude-code`]&&p.includes(`claude-code`)&&d.default.existsSync(g)){let e=JSON.parse(d.default.readFileSync(g,`utf8`)).enabledPlugins||{},t=e[`ryugi@ryugi-dev`]===!0?`full`:e[`ryugi-artifacts@ryugi-dev`]===!0?`artifacts`:null;t&&(m[`claude-code`]={harness:`claude-code`,mode:t,digest:``,path:``,version:`native-marketplace`})}let _={root:o,binDir:c,detected:p,previous:m,selection:l.selection},v;try{if(n&&!e.values.yes){let t;e.values.mode&&e.values.harness&&(t=oj({mode:String(e.values.mode),harness:String(e.values.harness)},_)),v=await cj(_,t)}else v=oj({mode:e.values.mode,harness:e.values.harness},_)}catch(e){return a(e.message)}if(!v)return Y(i,{kind:`interrupted`,signal:`SIGINT`});i.mode=v.mode;let y=[],b=[],x=n?lj():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=kO(__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 IO(o,c);e.preflight();let n=t.effects.begin(`install.runtime`,o),r=e.install(f.default.resolve(__dirname,`..`));t.effects.confirm(n,r),i.bin=r.bin,i.owner=`ryugi`,x?.stop(`Persistent CLI installed`);let a=LO(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&&sO(r,gO)===`foreign`)throw Error(`Native Claude source changed; preserving it`);let a=await uM(v.mode,e.projectDir,t.effects);if(!a.data.installed)throw Error(`Claude Code plugin was not installed`);let o=oO(a.data.installed,gO);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=pO(o,e.values[`plugin-version`]||`1.114.0`),C=!0));let r=f.default.join(o,`candidates`,(0,u.randomUUID)());try{let e=fO(S,r,v.mode);l.harnesses[n]=xO(n,e,{root:o,previous:l.harnesses[n],effects:t.effects})}finally{d.default.rmSync(r,{recursive:!0,force:!0})}i.targets.push({harness:n,mode:v.mode,status:`installed`,installed:l.harnesses[n].path})}BO(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. ${hO.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&&d.default.rmSync(S,{recursive:!0,force:!0})}r||(l.selection={mode:v.mode,targets:v.targets});let T=t.effects.begin(`install.selection`,o);BO(o,l),t.effects.confirm(T);let E=hj(await _j({cleanup:!1,root:o},t,n));y.push(...E.warnings);let ee=i.targets.filter(e=>e.status===`failed`),te=ee.length?[{kind:`command`,argv:[`adeck`,`install`,`--mode`,v.mode,`--harness`,ee.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 te.push(...b,...E.actions),t.signal.aborted?Y(i,{kind:`interrupted`,signal:`SIGINT`},{warnings:y,actions:te}):Y(i,ee.length?i.bin||i.targets.some(e=>e.status===`installed`)?{kind:`partial`}:{kind:`failed`,error:{code:`E_HARNESS_INSTALL`,message:ee.map(e=>`${e.harness}: ${e.error}`).join(`
|
|
954
|
+
`)}}:{kind:`succeeded`},{warnings:y,actions:te})}function fM({data:e}){return{heading:`Install`,status:e.targets.some(e=>e.status===`failed`)?`partial`:`installed`,summary:e.mode||``,facts:[Z(`Command`,X(e,`bin`)),Z(`Owner`,X(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 pM={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 Q({id:`install`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.bin},run:(n,r)=>dM(e,r,t.format===`brief`&&!!process.stdin.isTTY&&!!process.stderr.isTTY&&!process.env.CI),present:fM},e).run(t,n,r,i)}}}},mM=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function hM(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 mM.exec(e)?.[1]??null}function gM(e){let t=hM(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function _M(e){try{return gM((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`}}))??f.default.basename(e)}catch{return f.default.basename(e)}}var vM=`# Module vocabulary
|
|
955
955
|
|
|
956
956
|
Edit \`<project>/.ryugi/modules.json\`. A module is a lasting business area, such as billing or sharing, not a file, flag, task or ticket. Read the file immediately before edits and preserve unrelated modules and stable IDs.
|
|
957
957
|
|
|
@@ -977,8 +977,8 @@ Use readable lowercase IDs. Give modules descriptions and repository path globs
|
|
|
977
977
|
Before adding a module, read counts and hints. Add only when no description fits and the area will outlive the task. Rename by changing name while keeping id. Merge B into A by removing B and adding B's ID to A.aliases. Split A into A1/A2 by adding A's old ID to both new aliases. Removing without an alias leaves a retired label on old artifacts. Never reuse or change an ID. Fix clear maintenance hints, leave business judgments to the human, and report edits to this vocabulary explicitly.
|
|
978
978
|
|
|
979
979
|
The CLI writes artifact tags to project configuration and preserves other settings. Do not edit server state or Cloud metadata to assign tags.
|
|
980
|
-
`;const vM=`modules.json`,yM=/^[a-z0-9-]{1,40}$/,bM=`1 to 40 lowercase letters, digits and dashes`,xM=e=>e===void 0?[]:Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null;function SM(e,t){if(typeof e!=`object`||!e)return`module ${t+1} must be an object`;let{id:n,name:r,description:i=``,paths:a,aliases:o}=e;if(typeof n!=`string`||!yM.test(n))return`module id ${JSON.stringify(n)} must be ${bM}`;if(typeof r!=`string`||r.trim()===``)return`${n} needs a name`;if(r.length>60)return`${n}: a name is at most 60 characters`;if(typeof i!=`string`)return`${n}: description must be text`;if(i.length>200)return`${n}: a description is at most 200 characters`;let s=xM(a);if(!s)return`${n}: paths must be a list of globs`;let c=xM(o);if(!c)return`${n}: aliases must be a list of retired ids`;if(c.length>20)return`${n} has more than 20 aliases`;let l=c.find(e=>!yM.test(e));return l===void 0?{id:n,name:r,description:i,paths:s,aliases:c}:`alias ${JSON.stringify(l)} of ${n} must be ${bM}`}function CM(e){let t;try{t=JSON.parse(e)}catch(e){return{state:`invalid`,reason:`modules.json is not valid JSON: ${e.message}`}}let n=t?.modules;if(!Array.isArray(n))return{state:`invalid`,reason:`"modules" must be a list`};if(n.length>100)return{state:`invalid`,reason:`a vocabulary has at most 100 modules`};let r=[],i=/* @__PURE__ */ new Set;for(let[e,t]of n.entries()){let n=SM(t,e);if(typeof n==`string`)return{state:`invalid`,reason:n};if(i.has(n.id))return{state:`invalid`,reason:`duplicate module id: ${n.id}`};i.add(n.id),r.push(n)}for(let{id:e,aliases:t}of r){let n=t.find(e=>i.has(e));if(n!==void 0)return{state:`invalid`,reason:`alias ${JSON.stringify(n)} of ${e} is a live module id`}}return{state:`ok`,modules:r}}function wM(e){let t;try{t=d.default.readFileSync(f.default.join(e,vM),`utf8`)}catch{return{state:`missing`}}return CM(t)}function TM(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let i of t){let t=e.some(e=>e.id===i)?[i]:e.filter(e=>e.aliases.includes(i)).map(e=>e.id);t.length===0&&r.push(i);for(let e of t)n.add(e)}return r.length?{unknown:r}:{ids:[...n].sort()}}const EM=`.ryugi/${vM}`,DM=e=>f.default.dirname(ce(e).root),OM=e=>f.default.join(DM(e),`config.json`);function kM(e,t){if(!ue.test(t))throw new M(de);if(!d.default.existsSync(f.default.join(ce(e).root,t)))throw new M(`No such artifact: ${t}`)}function AM(e){let t=wM(DM(e));if(t.state===`missing`)throw new M(`This project has no vocabulary. Create ${EM} first.`);if(t.state===`invalid`)throw new M(`${EM} is invalid: ${t.reason}`);return t.modules}function jM(e,t,n,r=()=>{}){kM(e,t);let i=AM(e),a=TM(i,n.split(`,`).map(e=>e.trim()).filter(Boolean));if(`unknown`in a)throw new M(`Unknown module: ${a.unknown.join(`, `)}. Choose from: ${i.map(({id:e})=>e).join(`, `)}.`);if(a.ids.length>3)throw new M(`An artifact has at most 3 modules; pick the ones it is mainly about.`);let o=OM(e);return r(),kC(o),AC(o,t,{modules:a.ids}),{artifact:t,modules:a.ids}}function MM(e){let t=/* @__PURE__ */ new Map,n=0;for(let{modules:r}of Object.values(EC(OM(e)).config.artifacts))if(r?.length){n+=1;for(let e of r)t.set(e,(t.get(e)??0)+1)}return{counts:t,tagged:n}}const NM=e=>e.replace(/\/?\*+$/,``).replace(/\/$/,``),PM=(e,t)=>e===t||e.startsWith(`${t}/`);function FM(e){let t=[];for(let[n,r]of e.entries())for(let i of e.slice(n+1)){let e=r.paths.flatMap(e=>i.paths.map(t=>[e,t])).find(([e,t])=>PM(NM(e),NM(t))||PM(NM(t),NM(e)));e&&t.push(`paths overlap: ${r.id} and ${i.id} (${e[0]} and ${e[1]})`)}return t}function IM(e,t,n){let r=e.filter(({id:e})=>!t.get(e)).map(({id:e})=>e);return[...e.length>20?[`${e.length} modules, more than 20: merge the ones that are always chosen together`]:[],...n>=20&&r.length?[`no artifacts: ${r.join(`, `)} — merge them into a neighbour or remove them`]:[],...FM(e)]}function LM(e,{cloud:t,artifact:n}={}){n&&kM(e,n);let r=n?{current:EC(OM(e)).config.artifacts[n]?.modules??null}:{},i=wM(DM(e)),a=t?`cloud`:`local`;if(i.state!==`ok`)return{file:EM,state:i.state,...i.state===`invalid`?{reason:i.reason}:{},modules:[],counts:a,hints:[],...n?{artifact:n}:{},...r};let o=MM(e),s=t?new Map(t.modules.map(({id:e,count:t})=>[e,t])):o.counts,c=t?t.tagged:o.tagged;return{file:EM,state:`ok`,modules:i.modules.map(e=>({...e,count:s.get(e.id)??0})),counts:a,hints:IM(i.modules,s,c),...n?{artifact:n}:{},...r}}async function RM(e,t){try{let{status:n,json:r}=await ET(e).call(`GET`,`/api/cloud/artifacts`,void 0,t);if(n!==200)return;let i=gM(ce(e).project);return r.vocabularies?.[i]}catch{return}}function zM({data:e}){let t=e.state===`missing`?`no vocabulary: create ${e.file}`:e.state===`invalid`?`invalid: ${e.reason}`:``;return{heading:`Modules`,status:e.state===`ok`?``:e.state,subject:e.artifact,summary:t||`${e.modules.length} · ${e.file} · counts from ${e.counts===`cloud`?`Cloud`:`this checkout only`}`,facts:e.current===void 0?[]:[Z(`Current`,{key:`current`,value:e.current===null?`never tagged`:e.current.length?e.current.join(`, `):`cleared`})],sections:[...e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[],{kind:`records`,key:`modules`,rows:e.modules.map(e=>({...e,paths:e.paths.join(` `)})),columns:[{key:`id`,positional:!0,required:!0},{key:`count`,positional:!0,required:!0},{key:`name`,positional:!0},{key:`description`,positional:!0},{key:`paths`,positional:!0}]},{kind:`diagnostics`,key:`hints`,items:e.hints.map(e=>({code:`W_MODULES_MAINTENANCE`,message:e,severity:`warning`}))}]}}function BM({data:e}){return{heading:`Modules`,status:`SET`,subject:e.artifact,summary:e.modules.length?e.modules.join(`, `):`cleared`,facts:[],sections:[]}}const VM={name:`modules`,summary:`List the project's business modules, or set the modules an artifact serves`,usage:[`[--artifact <type>/<id>] [options]`,`--artifact <type>/<id> --set <id>[,<id>...]`],details:_M.trim(),options:{artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to show or tag`},set:{type:`string`,value:`<id>[,<id>...]`,help:`Replace the artifact’s modules with these ids`}},semantic:e=>{let t=e.values.artifact,n=e.values.set;if(n!==void 0){if(!t)throw new M(`--set needs --artifact <type>/<id>`);return Q({id:`modules.set`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.modules.join(`,`)},run:(r,i)=>{let a,o=jM(e.projectDir,t,n,()=>{a=i.effects.begin(`modules.set`,t)});return a!==void 0&&i.effects.confirm(a),Y(o)},present:BM},e)}return Q({id:`modules`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`id`,`count`,`name`,`description`,`paths`,`aliases`],collection:`modules`,requiredFields:[`id`,`count`]},async run(n,r){let i=await RM(e.projectDir,r.signal),a=LM(e.projectDir,{cloud:i,artifact:t});return Y({...a,project:e.projectDir,write:f.default.join(e.projectDir,a.file),...a.state===`ok`?{}:{writing:_M.trim()}})},present:zM},e)}};var HM=/* @__PURE__ */ (e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(HM||{});const UM=[0,1],WM=[1,0],GM=[2,3],KM=[3,2],qM={L:UM,M:WM,Q:GM,H:KM},JM=/^\d*$/,YM=/^[A-Z0-9 $%*+./:-]*$/,XM=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,ZM=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],QM=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];var $M=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<1||e>40)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,HM.Timing),this.setFunctionModule(e,6,e%2==0,HM.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,tN(r,e));this.setFunctionModule(8,7,tN(r,6)),this.setFunctionModule(8,8,tN(r,7)),this.setFunctionModule(7,8,tN(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,tN(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,tN(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,tN(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=tN(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,HM.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,HM.Alignment)}setFunctionModule(e,t,n,r=HM.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==gN(t,n))throw RangeError(`Invalid argument`);let r=QM[n[0]][t],i=ZM[n[0]][t],a=Math.floor(hN(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=_N(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=vN(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(hN(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=tN(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=3:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*40),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*40}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=3:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*40),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*40}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=3)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*10,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function eN(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function tN(e,t){return!!(e>>>t&1)}var nN=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}};const rN=[1,10,12,14],iN=[2,9,11,13],aN=[4,8,16,16];function oN(e,t){return e[Math.floor((t+7)/17)+1]}function sN(e){let t=[];for(let n of e)eN(n,8,t);return new nN(aN,e.length,t)}function cN(e){if(!dN(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);eN(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new nN(rN,e.length,t)}function lN(e){if(!fN(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=XM.indexOf(e.charAt(n))*45;r+=XM.indexOf(e.charAt(n+1)),eN(r,11,t)}return n<e.length&&eN(XM.indexOf(e.charAt(n)),6,t),new nN(iN,e.length,t)}function uN(e){return e===``?[]:dN(e)?[cN(e)]:fN(e)?[lN(e)]:[sN(mN(e))]}function dN(e){return JM.test(e)}function fN(e){return YM.test(e)}function pN(e,t){let n=0;for(let r of e){let e=oN(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function mN(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function hN(e){if(e<1||e>40)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function gN(e,t){return Math.floor(hN(e)/8)-ZM[t[0]][e]*QM[t[0]][e]}function _N(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=yN(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=yN(n,2)}return t}function vN(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=yN(t,e))}return n}function yN(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function bN(e,t,n=1,r=40,i=-1,a=!0){if(!(1<=n&&n<=r&&r<=40)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=gN(o,t)*8,i=pN(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[WM,GM,KM])a&&s<=gN(o,e)*8&&(t=e);let c=[];for(let t of e){eN(t.mode[0],4,c),eN(t.numChars,oN(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=gN(o,t)*8;eN(0,Math.min(4,l-c.length),c),eN(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)eN(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new $M(o,t,u,i)}function xN(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?uN(e):Array.isArray(e)?[sN(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=bN(c,qM[n],i,a,o,r),u=SN({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function SN(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=HM.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}function CN(e,t,n,r=!1){return t<0||n<0||t>=e.length||n>=e.length?r:e[n][t]}function wN(e,t={}){let n={WHITE_ALL:`█`,WHITE_BLACK:`▀`,BLACK_WHITE:`▄`,BLACK_ALL:` `},r=xN(e,t),i=(e,t)=>CN(r.data,e,t,!0),a=[],o=``;for(let e=0;e<r.size;e+=2){for(let t=0;t<r.size;t++)i(t,e)===!1&&i(t,e+1)===!1?o+=n.WHITE_ALL:i(t,e)===!1&&i(t,e+1)===!0?o+=n.WHITE_BLACK:i(t,e)===!0&&i(t,e+1)===!1?o+=n.BLACK_WHITE:o+=n.BLACK_ALL;a.push(o),o=``}return a.join(`
|
|
981
|
-
`)}const TN=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&typeof e.url==`string`;function EN(e){if(e.status>=200&&e.status<300)return e.json;let t=e.json;throw new J({code:e.status===401?`E_LOGIN_REQUIRED`:typeof t.code==`string`?`E_${t.code.toUpperCase()}`:`E_HTTP_${e.status}`,message:typeof t.error==`string`?t.error:`Cloud request failed: HTTP ${e.status}`,httpStatus:e.status,details:{...t.loginUrl?{loginUrl:t.loginUrl}:{},...TN(t.login)?{loginUrl:t.login.url,signInCode:t.login.code}:{},...t.upgradeUrl?{upgradeUrl:t.upgradeUrl}:{},...t.limit?{limit:t.limit}:{},...t.plan?{plan:t.plan}:{},...t.reasons?{reasons:t.reasons}:{}}},e.status===401||e.status===402&&(t.code===`plan_limit`||t.code===`plan_required`)?`action_required`:`failed`)}const DN=[`brief`,`json`,`jsonl`,`quiet`],ON=/^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/i;function kN(e){let{values:t}=e,n=[`unpublish`,`revoke-key`,`list`,`delete`,`login`,`logout`,`move-to`].filter(e=>t[e]),r=!!(t.key||t[`new-key`]);if(n.length>1||t.public&&t.private||t.public&&r||t.profile&&t[`no-profile`]||r&&t[`revoke-key`])throw new J({code:`E_OPTION_CONFLICT`,message:`Choose one publish action and one visibility.`});let i=n[0]??`publish`;if(i!==`publish`&&r||t.key&&t[`new-key`]||t.artifact!==void 0&&![`publish`,`unpublish`,`revoke-key`,`list`].includes(i)||t.from!==void 0&&i!==`login`||t[`with-token`]&&i!==`login`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Key creation applies only to publishing; artifact targets apply to publishing, key revocation or targeted --list; --from and --with-token apply only to --login. Choose either --key or --new-key.`});if(i!==`list`&&[`visibility`,`type`,`project`,`module`,`limit`,`cursor`].some(e=>t[e]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`List filters and paging apply only to --list.`});let a=t.artifact;if(([`publish`,`unpublish`,`revoke-key`].includes(i)||i===`list`&&a!==void 0)&&(!a||!ue.test(a)))throw new J({code:`E_ARGUMENT_INVALID`,message:`--artifact must be <type>/<id>.`});if(i===`list`&&a&&[`visibility`,`type`,`project`,`module`,`limit`,`cursor`,`fields`].some(e=>t[e]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Targeted --list --artifact reads publication and key state; collection filters and paging apply only without --artifact.`});if(i===`delete`&&!/^[\w-]{1,64}$/.test(String(t.delete??``)))throw new J({code:`E_ARGUMENT_INVALID`,message:`--delete requires a Cloud artifact ID.`});if(i!==`publish`&&(t.public||t.private||t[`no-refs`]||t.profile||t[`no-profile`]))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Visibility, profile listing and --no-refs apply only to publishing.`});if(t.expires!==void 0&&!r)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--expires applies only with --key or --new-key.`});if(i===`move-to`&&(!ON.test(String(t[`move-to`]))||String(t[`move-to`]).toLowerCase()===`personal`))throw new J({code:`E_ARGUMENT_INVALID`,message:`--move-to requires the slug of a team you belong to.`});let o=t.space;if(o!==void 0&&i!==`publish`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--space applies only to publishing.`});if(o!==void 0&&!ON.test(o))throw new J({code:`E_ARGUMENT_INVALID`,message:`--space must be a team slug or "personal".`});if(t.expires!==void 0&&!vC(t.expires))throw new J({code:`E_ARGUMENT_INVALID`,message:`--expires must be 1d, 7d, 30d or never.`});let s=r?{...t.expires?{expires:t.expires}:{},...t[`new-key`]?{regenerate:!0}:{}}:void 0;return{action:i,artifact:a,key:s,space:o?.toLowerCase(),onProfile:t.profile?!0:!t[`no-profile`]&&void 0,visibility:t.public?`public`:t.private||s?`private`:void 0}}function AN(e,t,n){return Q({id:`publish.${t}`,mode:`finite`,output:{formats:t===`login`?[`brief`,`json`,`jsonl`]:DN,scalar:e=>e.id},async run(r,i){let a=t===`delete`?String(e.values.delete):n,o=[`login`,`logout`,`move-to`].includes(t)?`POST`:`DELETE`,s=t===`delete`?`/api/cloud/artifacts/${a}`:t===`unpublish`?`/api/cloud/publish/${a}`:t===`revoke-key`?`/api/cloud/share-key/${a}`:t===`move-to`?`/api/cloud/transfer`:`/api/cloud/${t}`,c=t===`login`?void 0:i.effects.begin(t,a??`cloud-account`),l=typeof e.values.from==`string`?e.values.from:`cli`,u;if(t===`login`){if(e.values[`with-token`]){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));let t=Buffer.concat(e).toString(`utf8`).trim();if(!t)throw new J({code:`E_ARGUMENT_INVALID`,message:`Pass an access token on stdin when using --login --with-token.`});u={token:t}}else u={source:l}}let d=await ET(e.projectDir).call(o,s,t===`move-to`?{space:String(e.values[`move-to`]).toLowerCase()}:u,i.signal);c!==void 0&&d.status>=400&&d.status<500&&i.effects.set(c,`failed`);let f=EN(d);c!==void 0&&i.effects.confirm(c);let p=t===`login`&&TN(f.pending)?f.pending:null,m=t===`login`&&!f.signedIn?{kind:`pending`,reasons:[`sign_in_code_unconfirmed`]}:t===`logout`&&f.remoteRevoked!==!0?{kind:`partial`}:{kind:`succeeded`};return Y({id:t===`logout`?`signed-out`:f.id??a??`cloud-account`,artifact:a,status:t===`login`?f.signedIn?`signed_in`:`pending`:t===`logout`?`signed_out`:t===`move-to`?`moved`:t===`delete`?`deleted`:t===`revoke-key`?`key_removed`:`unpublished`,...f.url?{url:f.url}:{},...p?{code:p.code,url:p.url,expiresAt:p.expiresAt,autoPublish:f.autoPublish===!0?`on`:`off until you turn it on: ${process.env.RYUGI_ARTIFACTS_COMMAND||`npx artideck`} config --auto-publish on`}:{},...t===`logout`?{localCredentials:`cleared`,remoteSession:f.remoteRevoked===!0?`revoked`:`unknown`}:{}},m,{effects:i.effects.snapshot(),actions:p?[{kind:`url`,url:p.url,label:`Confirm the code`}]:f.url?[{kind:`url`,url:f.url,label:`Open`}]:[]})},present({data:e}){return{heading:t===`login`?`Login`:t===`logout`?`Logout`:`Cloud artifact`,status:e.status,subject:e.id,facts:[...e.artifact?[Z(`Artifact`,X(e,`artifact`))]:[],...e.code?[Z(`Code`,X(e,`code`))]:[],...e.url?[Z(`URL`,X(e,`url`))]:[],...e.expiresAt?[Z(`Expires`,X(e,`expiresAt`))]:[],...e.autoPublish?[Z(`Auto-publish`,X(e,`autoPublish`))]:[],...e.remoteSession?[Z(`Remote session`,X(e,`remoteSession`))]:[]],sections:e.url&&e.code?[{kind:`content`,key:`qr`,text:wN(e.url)}]:[]}}},e)}async function jN(e,t,n,r,i,a){let o=ET(e.projectDir),s=await(async(e,n)=>{let r=t.effects.begin(`publish`,e),a={...n?{visibility:n}:{},...i===void 0?{}:{onProfile:i}},s=await o.call(`POST`,`/api/cloud/publish/${e}`,Object.keys(a).length?a:void 0,t.signal);s.status>=400&&s.status<500&&t.effects.set(r,`failed`,s.json);let c=EN(s);return t.effects.confirm(r,{url:c.url,visibility:c.visibility,version:c.version}),c})(n,r),c;if(a||s.keyed){let e=a?t.effects.begin(`share-key`,n):void 0,r=await o.call(a?`PUT`:`GET`,`/api/cloud/share-key/${n}`,a,t.signal);e!==void 0&&r.status>=400&&r.status<500&&t.effects.set(e,`failed`);let i=EN(r);if(i.shareKey===void 0||a&&!i.shareKey)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not confirm the share-key state.`});c=i.shareKey??void 0,e!==void 0&&t.effects.confirm(e,{expiresAt:c?.expiresAt})}let l=EN(await o.call(`GET`,`/api/cloud/refs/${n}?visibility=${s.visibility}&referrers=0`,void 0,t.signal)),u=e.values[`no-refs`]?[]:l.items.filter(e=>e.checked&&e.state!==`private`),d=/* @__PURE__ */ new Map;if(u.length){let e=new Map(u.map(e=>[e.artifact,t.effects.begin(`publish`,e.artifact)])),r=EN(await o.call(`POST`,`/api/cloud/publish-refs/${n}`,{visibility:s.visibility,refs:u.map(e=>e.artifact),makePublic:[]},t.signal));for(let n of r.results){d.set(n.artifact,n);let r=e.get(n.artifact);r!==void 0&&(n.status===`published`?t.effects.confirm(r,{}):n.status===`failed`?t.effects.set(r,`failed`,n.error):n.status===`not_attempted`&&t.effects.set(r,`not_attempted`))}}let f=e=>{try{EN({status:e.error?.httpStatus??500,json:e.error??{}})}catch(e){return LC(e)}},p={publish:`published`,update:`updated`,"make-public":`made_public`},m=l.items.map(e=>{let t={artifact:e.artifact,state:e.state,via:e.via},n=d.get(e.artifact);if(n){let e=n.status===`published`?void 0:f(n);return{...t,status:n.status===`published`?p[n.action]:n.status,...e?{error:e}:{}}}return e.reason===`upstream`?{...t,status:`unreachable`}:e.state===`unpublished`||e.state===`stale`?{...t,status:`skipped`}:{...t,status:e.state}}),h=m.some(e=>[`failed`,`unknown`,`not_attempted`].includes(e.status)),g={status:h?`partial`:`published`,artifact:n,id:s.id??new URL(s.url).pathname.split(`/`).filter(Boolean).at(-1),url:c?.url??s.url,visibility:s.visibility,...s.version===void 0?{}:{version:s.version},visibilitySource:r?`requested`:`preserved`,onProfile:s.onProfile===!0,onProfileSource:i===void 0?`preserved`:`requested`,...c?{shareKey:{key:c.key,expiresAt:c.expiresAt}}:{},references:m},_=m.filter(e=>e.status===`private`),v=m.filter(e=>e.status===`skipped`);return Y(g,h?{kind:`partial`}:{kind:`succeeded`},{effects:t.effects.snapshot(),warnings:[...(Array.isArray(s.notes)?s.notes:[]).filter(e=>typeof e==`string`).map(e=>({code:`W_CUT_NOT_PUBLISHED`,message:e})),...i&&s.visibility!==`public`?[{code:`W_PROFILE_NEEDS_PUBLIC`,message:`It will show on your profile once it is public.`}]:[],..._.length?[{code:`W_REFERENCES_PRIVATE`,message:`${_.length} referenced artifacts are private; visitors see a locked label.`}]:[],...v.length?[{code:`W_REFERENCES_UNPUBLISHED`,message:`${v.length} referenced artifacts were left as they are (--no-refs).`}]:[]],actions:[...m.flatMap(e=>e.error?hw(e.error,e.artifact):[]),..._.map(t=>lw([`publish`,`--artifact`,t.artifact,`--project-dir`,e.projectDir,`--public`],`Next`)),...v.length&&!h?[lw([`publish`,`--artifact`,n,`--project-dir`,e.projectDir],`Next`)]:[]]})}function MN({data:e}){return{heading:`Publish`,status:e.status,subject:e.artifact,facts:[Z(`ID`,X(e,`id`),!0),Z(`URL`,X(e,`url`),!0),Z(`Visibility`,{key:`visibility`,value:`${e.visibility} (${e.visibilitySource})`},!0),...e.visibility===`public`?[Z(`Profile`,{key:`onProfile`,value:e.onProfile?`listed`:`not listed`},!0)]:[],...e.shareKey?[Z(`Key`,{key:`shareKey.key`,value:e.shareKey.key},!0),Z(`Expires`,{key:`shareKey.expiresAt`,value:e.shareKey.expiresAt??`never`},!0)]:[],...e.version===void 0?[]:[Z(`Version`,X(e,`version`))]],sections:e.references.length?[{kind:`records`,key:`references`,title:`Referenced artifacts`,rows:e.references.map(e=>({artifact:e.artifact,status:e.status,via:e.via?`via ${e.via}`:``,error:e.error?`${e.error.code}: ${e.error.message}`:``,recovery:e.status===`unknown`?`inspect the remote artifact before retrying`:``})),columns:[{key:`artifact`,positional:!0,required:!0},{key:`status`,positional:!0,required:!0},{key:`via`,positional:!0},{key:`error`,positional:!0},{key:`recovery`,positional:!0}]}]:[]}}function NN({data:e,coverage:t}){return{heading:`Cloud artifacts`,status:``,summary:`${t.page?.total??e.artifacts.length} on account`,facts:[],sections:[{kind:`records`,key:`artifacts`,rows:e.artifacts.map(e=>({...e,version:e.version===void 0?``:`v${e.version}`})),columns:[{key:`id`,positional:!0,required:!0},{key:`type`,positional:!0},{key:`visibility`,positional:!0,required:!0},{key:`version`,positional:!0},{key:`updatedAt`,positional:!0},{key:`title`,positional:!0}]}]}}function PN(e){let{action:t,artifact:n,visibility:r,onProfile:i,key:a,space:o}=kN(e);if(t===`list`&&n)return Q({id:`publish.list`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},async run(t,r){let i=ET(e.projectDir),a=gC(EN(await i.call(`GET`,`/api/cloud/publication/${n}`,void 0,r.signal)));if(!a)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported publication state.`});let{shareKey:o}=EN(await i.call(`GET`,`/api/cloud/share-key/${n}`,void 0,r.signal));if(o===void 0)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return the current share-key state.`});return Y({artifact:n,publication:a,shareKey:o})},present({data:e}){return{heading:`Cloud artifact`,status:e.publication.phase,subject:n,facts:[Z(`Published at`,{key:`publication.publishedAt`,value:e.publication.publishedAt}),Z(`Key`,{key:`shareKey.key`,value:e.shareKey?.key??`none`},!0),...e.shareKey?[Z(`URL`,{key:`shareKey.url`,value:e.shareKey.url},!0),Z(`Expires`,{key:`shareKey.expiresAt`,value:e.shareKey.expiresAt??`never`},!0)]:[]],sections:[]}}},e);if(t===`publish`)return Q({id:`publish.publish`,mode:`finite`,output:{formats:DN,scalar:e=>e.id},run:(t,s)=>(o&&MC(f.default.join(f.default.dirname(ce(e.projectDir).root),`config.json`),o),jN(e,s,n,r,i,a)),present:MN},e);if(t===`list`){let t=new URLSearchParams({semantic:`1`});for(let n of[`visibility`,`type`,`project`,`limit`,`cursor`,`fields`]){let r=e.values[n];typeof r==`string`&&t.set(n,r)}if(typeof e.values.module==`string`){t.has(`project`)||t.set(`project`,gM(ce(e.projectDir).project));let n=e.values.module.split(`,`).map(e=>e.trim());for(let e of new Set(n))t.append(`module`,e)}if(t.has(`limit`)&&(!/^\d+$/.test(t.get(`limit`))||+t.get(`limit`)<1||+t.get(`limit`)>100))throw new J({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});if(t.has(`visibility`)&&![`public`,`private`].includes(t.get(`visibility`))||t.has(`type`)&&!Ae(t.get(`type`)))throw new J({code:`E_ARGUMENT_INVALID`,message:`Invalid Cloud list filter.`});return Q({id:`publish.list`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`raw`],fields:[`id`,`type`,`title`,`project`,`modules`,`visibility`,`url`,`updatedAt`,`version`],collection:`artifacts`,requiredFields:[`id`,`type`,`visibility`,`version`]},async run(n,r){let i=await ET(e.projectDir).call(`GET`,`/api/cloud/artifacts?${t}`,void 0,r.signal);r.payloads.raw=i.raw;let a=EN(i);if(a.schema!==`ryugi.cloud-list/v1`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported Cloud list response.`});return Y({artifacts:a.artifacts},void 0,{coverage:{page:a.page},actions:a.page?.nextCursor?[lw([`publish`,`--list`,`--project-dir`,e.projectDir,...[...new Set(t.keys())].filter(e=>![`semantic`,`cursor`].includes(e)).flatMap(e=>[`--${e}`,t.getAll(e).join(`,`)]),`--cursor`,a.page.nextCursor],`More`)]:[]})},present:NN},e)}return AN(e,t,n)}const FN={semantic:PN,name:`publish`,summary:`Publish an artifact to the Artideck Cloud (needs a running server)`,usage:[`--artifact <type>/<id> [--public | --private | --key] [--profile | --no-profile] [options]`,`--artifact <type>/<id> --unpublish | --revoke-key [options]`,`--list | --delete <cloud-id> | --login | --logout [options]`,`--move-to <team-slug> (move this project into a team)`,`--list --artifact <type>/<id> (read publication and current key state without changing either)`],options:{visibility:{type:`string`,value:`<public|private>`,help:`Filter published list visibility`},type:{type:`string`,value:`<${k.join(`|`)}>`,help:`Filter published list type`},project:{type:`string`,value:`<project>`,help:`Filter published list project`},module:{type:`string`,value:`<id>[,<id>...]`,help:`Filter published list by module ("" for untagged); the project defaults to this one`},limit:{type:`string`,value:`<1-100>`,help:`Maximum list rows`},cursor:{type:`string`,value:`<token>`,help:`Continue a stable list snapshot`},artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to publish, unpublish, revoke a key, or inspect with --list`},public:{type:`boolean`,help:`Anyone with the link can open it`},private:{type:`boolean`,help:`Only you can open it`},key:{type:`boolean`,help:`Only people with the key can open it; prints a link that carries the key`},expires:{type:`string`,value:`<1d|7d|30d|never>`,help:`With --key or --new-key: when the key stops working (7d for a new key)`},"new-key":{type:`boolean`,help:`Replace the key; links with the old key stop opening`},"revoke-key":{type:`boolean`,help:`Remove the key; only you can open it`},profile:{type:`boolean`,help:`Show it on your public profile once it is public`},"no-profile":{type:`boolean`,help:`Take it off your public profile`},unpublish:{type:`boolean`,help:`Remove the artifact's cloud copy`},list:{type:`boolean`,help:`List your cloud artifacts; with --artifact, read its publication and current key state`},delete:{type:`string`,value:`<cloud-id>`,help:`Delete a cloud artifact by its id from --list`},space:{type:`string`,value:`<team-slug|personal>`,help:`Where this project's new artifacts publish; already published ones stay where they are`},"move-to":{type:`string`,value:`<team-slug>`,help:`Move every artifact of this project from your personal space into a team; links stay the same`},"no-refs":{type:`boolean`,help:`Publish only this artifact; leave the artifacts it references as they are`},login:{type:`boolean`,help:`Sign in to the Artideck Cloud`},"with-token":{type:`boolean`,help:`With --login: read an access token from stdin instead of opening a browser`},from:{type:`string`,value:`<tag>`,help:`With --login: where this sign-in started, recorded by Artideck Cloud`},logout:{type:`boolean`,help:`Sign out of the Artideck Cloud`}}},IN=/* @__PURE__ */ new Set([`created`,`updated`,`bound`]),LN=/* @__PURE__ */ new Set([`conflict`,`name_clash`]);function RN({data:e}){let t=/* @__PURE__ */ new Map;for(let n of e.results)t.set(n.outcome,(t.get(n.outcome)??0)+1);return{heading:`Pull`,status:``,subject:e.project,summary:e.results.length?[...t].map(([e,t])=>`${t} ${e}`).join(` · `):`no Cloud artifacts in this project`,facts:[Z(`Project`,X(e,`project`))],sections:[{kind:`records`,key:`results`,rows:e.results.map(e=>({...e,note:e.message??e.notes?.join(`; `)??``})),columns:[{key:`key`,positional:!0,required:!0},{key:`outcome`,positional:!0,required:!0},{key:`url`,positional:!0},{key:`note`,positional:!0}]}]}}function zN(e){let t=e.values.artifact,n=e.positionals[0];if(t&&n)throw new J({code:`E_OPTION_CONFLICT`,message:`Give --artifact or a Cloud link, not both.`});let r=t??n,i=e.values.as;if(i&&!r)throw new J({code:`E_ARGUMENT_INVALID`,message:`--as needs one target: --artifact <type>/<id> or a Cloud link.`});let a=e.values[`dry-run`]===!0,o=e.values.force===!0,s=e.values.project;return Q({id:`pull`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],collection:`results`,fields:[`key`,`outcome`,`cloudId`,`url`,`dir`,`message`,`notes`],requiredFields:[`key`,`outcome`]},async run(t,n){let c=EN(await ET(e.projectDir).call(`POST`,`/api/cloud/pull`,{target:r,project:s,as:i,dryRun:a,force:o},n.signal));if(!Array.isArray(c.results))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported pull response.`});if(!a)for(let e of c.results){if(!IN.has(e.outcome)&&e.outcome!==`failed`)continue;let t=n.effects.begin(`pull.${e.outcome}`,e.key);e.outcome===`failed`?n.effects.set(t,`failed`,{message:e.message}):n.effects.confirm(t)}let l=c.results.some(e=>e.outcome===`failed`)?{kind:`partial`}:c.results.some(e=>LN.has(e.outcome))?{kind:`validation_failed`}:{kind:`succeeded`},u=[`--project-dir`,e.projectDir];return Y(c,l,{effects:n.effects.snapshot(),actions:c.results.flatMap(e=>e.outcome===`conflict`?[lw([`get`,e.url],`Compare`),lw([`pull`,e.cloudId,`--force`,...u],`Take Cloud`)]:e.outcome===`name_clash`?[lw([`pull`,e.cloudId,`--as`,`${e.key.split(`/`)[1]}-cloud`,...u],`Pull as`)]:[])})},present:RN},e)}const BN={semantic:zN,name:`pull`,summary:`Pull this project's Cloud artifacts into the local artifacts folder (needs a running server)`,usage:[`[--project <owner/repo>] [--dry-run] [--force] [options]`,`--artifact <type>/<id> | <link-or-cloud-id> [--as <id>] [--dry-run] [--force] [options]`],positionals:1,details:`Each Cloud artifact of the project lands in .ryugi/artifacts/<type>/<slug> and stays bound to its Cloud link, so publish updates it instead of creating a new one.
|
|
980
|
+
`;const yM=`modules.json`,bM=/^[a-z0-9-]{1,40}$/,xM=`1 to 40 lowercase letters, digits and dashes`,SM=e=>e===void 0?[]:Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null;function CM(e,t){if(typeof e!=`object`||!e)return`module ${t+1} must be an object`;let{id:n,name:r,description:i=``,paths:a,aliases:o}=e;if(typeof n!=`string`||!bM.test(n))return`module id ${JSON.stringify(n)} must be ${xM}`;if(typeof r!=`string`||r.trim()===``)return`${n} needs a name`;if(r.length>60)return`${n}: a name is at most 60 characters`;if(typeof i!=`string`)return`${n}: description must be text`;if(i.length>200)return`${n}: a description is at most 200 characters`;let s=SM(a);if(!s)return`${n}: paths must be a list of globs`;let c=SM(o);if(!c)return`${n}: aliases must be a list of retired ids`;if(c.length>20)return`${n} has more than 20 aliases`;let l=c.find(e=>!bM.test(e));return l===void 0?{id:n,name:r,description:i,paths:s,aliases:c}:`alias ${JSON.stringify(l)} of ${n} must be ${xM}`}function wM(e){let t;try{t=JSON.parse(e)}catch(e){return{state:`invalid`,reason:`modules.json is not valid JSON: ${e.message}`}}let n=t?.modules;if(!Array.isArray(n))return{state:`invalid`,reason:`"modules" must be a list`};if(n.length>100)return{state:`invalid`,reason:`a vocabulary has at most 100 modules`};let r=[],i=/* @__PURE__ */ new Set;for(let[e,t]of n.entries()){let n=CM(t,e);if(typeof n==`string`)return{state:`invalid`,reason:n};if(i.has(n.id))return{state:`invalid`,reason:`duplicate module id: ${n.id}`};i.add(n.id),r.push(n)}for(let{id:e,aliases:t}of r){let n=t.find(e=>i.has(e));if(n!==void 0)return{state:`invalid`,reason:`alias ${JSON.stringify(n)} of ${e} is a live module id`}}return{state:`ok`,modules:r}}function TM(e){let t;try{t=d.default.readFileSync(f.default.join(e,yM),`utf8`)}catch{return{state:`missing`}}return wM(t)}function EM(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let i of t){let t=e.some(e=>e.id===i)?[i]:e.filter(e=>e.aliases.includes(i)).map(e=>e.id);t.length===0&&r.push(i);for(let e of t)n.add(e)}return r.length?{unknown:r}:{ids:[...n].sort()}}const DM=`.ryugi/${yM}`,OM=e=>f.default.dirname(ce(e).root),kM=e=>f.default.join(OM(e),`config.json`);function AM(e,t){if(!ue.test(t))throw new M(de);if(!d.default.existsSync(f.default.join(ce(e).root,t)))throw new M(`No such artifact: ${t}`)}function jM(e){let t=TM(OM(e));if(t.state===`missing`)throw new M(`This project has no vocabulary. Create ${DM} first.`);if(t.state===`invalid`)throw new M(`${DM} is invalid: ${t.reason}`);return t.modules}function MM(e,t,n,r=()=>{}){AM(e,t);let i=jM(e),a=EM(i,n.split(`,`).map(e=>e.trim()).filter(Boolean));if(`unknown`in a)throw new M(`Unknown module: ${a.unknown.join(`, `)}. Choose from: ${i.map(({id:e})=>e).join(`, `)}.`);if(a.ids.length>3)throw new M(`An artifact has at most 3 modules; pick the ones it is mainly about.`);let o=kM(e);return r(),kC(o),AC(o,t,{modules:a.ids}),{artifact:t,modules:a.ids}}function NM(e){let t=/* @__PURE__ */ new Map,n=0;for(let{modules:r}of Object.values(EC(kM(e)).config.artifacts))if(r?.length){n+=1;for(let e of r)t.set(e,(t.get(e)??0)+1)}return{counts:t,tagged:n}}const PM=e=>e.replace(/\/?\*+$/,``).replace(/\/$/,``),FM=(e,t)=>e===t||e.startsWith(`${t}/`);function IM(e){let t=[];for(let[n,r]of e.entries())for(let i of e.slice(n+1)){let e=r.paths.flatMap(e=>i.paths.map(t=>[e,t])).find(([e,t])=>FM(PM(e),PM(t))||FM(PM(t),PM(e)));e&&t.push(`paths overlap: ${r.id} and ${i.id} (${e[0]} and ${e[1]})`)}return t}function LM(e,t,n){let r=e.filter(({id:e})=>!t.get(e)).map(({id:e})=>e);return[...e.length>20?[`${e.length} modules, more than 20: merge the ones that are always chosen together`]:[],...n>=20&&r.length?[`no artifacts: ${r.join(`, `)} — merge them into a neighbour or remove them`]:[],...IM(e)]}function RM(e,{cloud:t,artifact:n}={}){n&&AM(e,n);let r=n?{current:EC(kM(e)).config.artifacts[n]?.modules??null}:{},i=TM(OM(e)),a=t?`cloud`:`local`;if(i.state!==`ok`)return{file:DM,state:i.state,...i.state===`invalid`?{reason:i.reason}:{},modules:[],counts:a,hints:[],...n?{artifact:n}:{},...r};let o=NM(e),s=t?new Map(t.modules.map(({id:e,count:t})=>[e,t])):o.counts,c=t?t.tagged:o.tagged;return{file:DM,state:`ok`,modules:i.modules.map(e=>({...e,count:s.get(e.id)??0})),counts:a,hints:LM(i.modules,s,c),...n?{artifact:n}:{},...r}}async function zM(e,t){try{let{status:n,json:r}=await ET(e).call(`GET`,`/api/cloud/artifacts`,void 0,t);if(n!==200)return;let i=_M(ce(e).project);return r.vocabularies?.[i]}catch{return}}function BM({data:e}){let t=e.state===`missing`?`no vocabulary: create ${e.file}`:e.state===`invalid`?`invalid: ${e.reason}`:``;return{heading:`Modules`,status:e.state===`ok`?``:e.state,subject:e.artifact,summary:t||`${e.modules.length} · ${e.file} · counts from ${e.counts===`cloud`?`Cloud`:`this checkout only`}`,facts:e.current===void 0?[]:[Z(`Current`,{key:`current`,value:e.current===null?`never tagged`:e.current.length?e.current.join(`, `):`cleared`})],sections:[...e.writing?[{kind:`content`,key:`writing`,title:`Writing`,text:e.writing}]:[],{kind:`records`,key:`modules`,rows:e.modules.map(e=>({...e,paths:e.paths.join(` `)})),columns:[{key:`id`,positional:!0,required:!0},{key:`count`,positional:!0,required:!0},{key:`name`,positional:!0},{key:`description`,positional:!0},{key:`paths`,positional:!0}]},{kind:`diagnostics`,key:`hints`,items:e.hints.map(e=>({code:`W_MODULES_MAINTENANCE`,message:e,severity:`warning`}))}]}}function VM({data:e}){return{heading:`Modules`,status:`SET`,subject:e.artifact,summary:e.modules.length?e.modules.join(`, `):`cleared`,facts:[],sections:[]}}const HM={name:`modules`,summary:`List the project's business modules, or set the modules an artifact serves`,usage:[`[--artifact <type>/<id>] [options]`,`--artifact <type>/<id> --set <id>[,<id>...]`],details:vM.trim(),options:{artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to show or tag`},set:{type:`string`,value:`<id>[,<id>...]`,help:`Replace the artifact’s modules with these ids`}},semantic:e=>{let t=e.values.artifact,n=e.values.set;if(n!==void 0){if(!t)throw new M(`--set needs --artifact <type>/<id>`);return Q({id:`modules.set`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.modules.join(`,`)},run:(r,i)=>{let a,o=MM(e.projectDir,t,n,()=>{a=i.effects.begin(`modules.set`,t)});return a!==void 0&&i.effects.confirm(a),Y(o)},present:VM},e)}return Q({id:`modules`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],fields:[`id`,`count`,`name`,`description`,`paths`,`aliases`],collection:`modules`,requiredFields:[`id`,`count`]},async run(n,r){let i=await zM(e.projectDir,r.signal),a=RM(e.projectDir,{cloud:i,artifact:t});return Y({...a,project:e.projectDir,write:f.default.join(e.projectDir,a.file),...a.state===`ok`?{}:{writing:vM.trim()}})},present:BM},e)}};var UM=/* @__PURE__ */ (e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(UM||{});const WM=[0,1],GM=[1,0],KM=[2,3],qM=[3,2],JM={L:WM,M:GM,Q:KM,H:qM},YM=/^\d*$/,XM=/^[A-Z0-9 $%*+./:-]*$/,ZM=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,QM=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],$M=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];var eN=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<1||e>40)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,UM.Timing),this.setFunctionModule(e,6,e%2==0,UM.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,nN(r,e));this.setFunctionModule(8,7,nN(r,6)),this.setFunctionModule(8,8,nN(r,7)),this.setFunctionModule(7,8,nN(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,nN(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,nN(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,nN(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=nN(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,UM.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,UM.Alignment)}setFunctionModule(e,t,n,r=UM.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==_N(t,n))throw RangeError(`Invalid argument`);let r=$M[n[0]][t],i=QM[n[0]][t],a=Math.floor(gN(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=vN(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=yN(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(gN(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=nN(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=3:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*40),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*40}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=3:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*40),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*40}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=3)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*10,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function tN(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function nN(e,t){return!!(e>>>t&1)}var rN=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}};const iN=[1,10,12,14],aN=[2,9,11,13],oN=[4,8,16,16];function sN(e,t){return e[Math.floor((t+7)/17)+1]}function cN(e){let t=[];for(let n of e)tN(n,8,t);return new rN(oN,e.length,t)}function lN(e){if(!fN(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);tN(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new rN(iN,e.length,t)}function uN(e){if(!pN(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=ZM.indexOf(e.charAt(n))*45;r+=ZM.indexOf(e.charAt(n+1)),tN(r,11,t)}return n<e.length&&tN(ZM.indexOf(e.charAt(n)),6,t),new rN(aN,e.length,t)}function dN(e){return e===``?[]:fN(e)?[lN(e)]:pN(e)?[uN(e)]:[cN(hN(e))]}function fN(e){return YM.test(e)}function pN(e){return XM.test(e)}function mN(e,t){let n=0;for(let r of e){let e=sN(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function hN(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function gN(e){if(e<1||e>40)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function _N(e,t){return Math.floor(gN(e)/8)-QM[t[0]][e]*$M[t[0]][e]}function vN(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=bN(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=bN(n,2)}return t}function yN(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=bN(t,e))}return n}function bN(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function xN(e,t,n=1,r=40,i=-1,a=!0){if(!(1<=n&&n<=r&&r<=40)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=_N(o,t)*8,i=mN(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[GM,KM,qM])a&&s<=_N(o,e)*8&&(t=e);let c=[];for(let t of e){tN(t.mode[0],4,c),tN(t.numChars,sN(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=_N(o,t)*8;tN(0,Math.min(4,l-c.length),c),tN(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)tN(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new eN(o,t,u,i)}function SN(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?dN(e):Array.isArray(e)?[cN(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=xN(c,JM[n],i,a,o,r),u=CN({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function CN(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=UM.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}function wN(e,t,n,r=!1){return t<0||n<0||t>=e.length||n>=e.length?r:e[n][t]}function TN(e,t={}){let n={WHITE_ALL:`█`,WHITE_BLACK:`▀`,BLACK_WHITE:`▄`,BLACK_ALL:` `},r=SN(e,t),i=(e,t)=>wN(r.data,e,t,!0),a=[],o=``;for(let e=0;e<r.size;e+=2){for(let t=0;t<r.size;t++)i(t,e)===!1&&i(t,e+1)===!1?o+=n.WHITE_ALL:i(t,e)===!1&&i(t,e+1)===!0?o+=n.WHITE_BLACK:i(t,e)===!0&&i(t,e+1)===!1?o+=n.BLACK_WHITE:o+=n.BLACK_ALL;a.push(o),o=``}return a.join(`
|
|
981
|
+
`)}const EN=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&typeof e.url==`string`;function DN(e){if(e.status>=200&&e.status<300)return e.json;let t=e.json;throw new J({code:e.status===401?`E_LOGIN_REQUIRED`:typeof t.code==`string`?`E_${t.code.toUpperCase()}`:`E_HTTP_${e.status}`,message:typeof t.error==`string`?t.error:`Cloud request failed: HTTP ${e.status}`,httpStatus:e.status,details:{...t.loginUrl?{loginUrl:t.loginUrl}:{},...EN(t.login)?{loginUrl:t.login.url,signInCode:t.login.code}:{},...t.upgradeUrl?{upgradeUrl:t.upgradeUrl}:{},...t.limit?{limit:t.limit}:{},...t.plan?{plan:t.plan}:{},...t.reasons?{reasons:t.reasons}:{}}},e.status===401||e.status===402&&(t.code===`plan_limit`||t.code===`plan_required`)?`action_required`:`failed`)}const ON=[`brief`,`json`,`jsonl`,`quiet`],kN=/^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/i;function AN(e){let{values:t}=e,n=[`unpublish`,`revoke-key`,`list`,`delete`,`login`,`logout`,`move-to`].filter(e=>t[e]),r=!!(t.key||t[`new-key`]);if(n.length>1||t.public&&t.private||t.public&&r||t.profile&&t[`no-profile`]||r&&t[`revoke-key`])throw new J({code:`E_OPTION_CONFLICT`,message:`Choose one publish action and one visibility.`});let i=n[0]??`publish`;if(i!==`publish`&&r||t.key&&t[`new-key`]||t.artifact!==void 0&&![`publish`,`unpublish`,`revoke-key`,`list`].includes(i)||t.from!==void 0&&i!==`login`||t[`with-token`]&&i!==`login`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Key creation applies only to publishing; artifact targets apply to publishing, key revocation or targeted --list; --from and --with-token apply only to --login. Choose either --key or --new-key.`});if(i!==`list`&&[`visibility`,`type`,`project`,`module`,`limit`,`cursor`].some(e=>t[e]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`List filters and paging apply only to --list.`});let a=t.artifact;if(([`publish`,`unpublish`,`revoke-key`].includes(i)||i===`list`&&a!==void 0)&&(!a||!ue.test(a)))throw new J({code:`E_ARGUMENT_INVALID`,message:`--artifact must be <type>/<id>.`});if(i===`list`&&a&&[`visibility`,`type`,`project`,`module`,`limit`,`cursor`,`fields`].some(e=>t[e]!==void 0))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Targeted --list --artifact reads publication and key state; collection filters and paging apply only without --artifact.`});if(i===`delete`&&!/^[\w-]{1,64}$/.test(String(t.delete??``)))throw new J({code:`E_ARGUMENT_INVALID`,message:`--delete requires a Cloud artifact ID.`});if(i!==`publish`&&(t.public||t.private||t[`no-refs`]||t.profile||t[`no-profile`]))throw new J({code:`E_OPTION_UNSUPPORTED`,message:`Visibility, profile listing and --no-refs apply only to publishing.`});if(t.expires!==void 0&&!r)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--expires applies only with --key or --new-key.`});if(i===`move-to`&&(!kN.test(String(t[`move-to`]))||String(t[`move-to`]).toLowerCase()===`personal`))throw new J({code:`E_ARGUMENT_INVALID`,message:`--move-to requires the slug of a team you belong to.`});let o=t.space;if(o!==void 0&&i!==`publish`)throw new J({code:`E_OPTION_UNSUPPORTED`,message:`--space applies only to publishing.`});if(o!==void 0&&!kN.test(o))throw new J({code:`E_ARGUMENT_INVALID`,message:`--space must be a team slug or "personal".`});if(t.expires!==void 0&&!vC(t.expires))throw new J({code:`E_ARGUMENT_INVALID`,message:`--expires must be 1d, 7d, 30d or never.`});let s=r?{...t.expires?{expires:t.expires}:{},...t[`new-key`]?{regenerate:!0}:{}}:void 0;return{action:i,artifact:a,key:s,space:o?.toLowerCase(),onProfile:t.profile?!0:!t[`no-profile`]&&void 0,visibility:t.public?`public`:t.private||s?`private`:void 0}}function jN(e,t,n){return Q({id:`publish.${t}`,mode:`finite`,output:{formats:t===`login`?[`brief`,`json`,`jsonl`]:ON,scalar:e=>e.id},async run(r,i){let a=t===`delete`?String(e.values.delete):n,o=[`login`,`logout`,`move-to`].includes(t)?`POST`:`DELETE`,s=t===`delete`?`/api/cloud/artifacts/${a}`:t===`unpublish`?`/api/cloud/publish/${a}`:t===`revoke-key`?`/api/cloud/share-key/${a}`:t===`move-to`?`/api/cloud/transfer`:`/api/cloud/${t}`,c=t===`login`?void 0:i.effects.begin(t,a??`cloud-account`),l=typeof e.values.from==`string`?e.values.from:`cli`,u;if(t===`login`){if(e.values[`with-token`]){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));let t=Buffer.concat(e).toString(`utf8`).trim();if(!t)throw new J({code:`E_ARGUMENT_INVALID`,message:`Pass an access token on stdin when using --login --with-token.`});u={token:t}}else u={source:l}}let d=await ET(e.projectDir).call(o,s,t===`move-to`?{space:String(e.values[`move-to`]).toLowerCase()}:u,i.signal);c!==void 0&&d.status>=400&&d.status<500&&i.effects.set(c,`failed`);let f=DN(d);c!==void 0&&i.effects.confirm(c);let p=t===`login`&&EN(f.pending)?f.pending:null,m=t===`login`&&!f.signedIn?{kind:`pending`,reasons:[`sign_in_code_unconfirmed`]}:t===`logout`&&f.remoteRevoked!==!0?{kind:`partial`}:{kind:`succeeded`};return Y({id:t===`logout`?`signed-out`:f.id??a??`cloud-account`,artifact:a,status:t===`login`?f.signedIn?`signed_in`:`pending`:t===`logout`?`signed_out`:t===`move-to`?`moved`:t===`delete`?`deleted`:t===`revoke-key`?`key_removed`:`unpublished`,...f.url?{url:f.url}:{},...p?{code:p.code,url:p.url,expiresAt:p.expiresAt,autoPublish:f.autoPublish===!0?`on`:`off until you turn it on: ${process.env.RYUGI_ARTIFACTS_COMMAND||`npx artideck`} config --auto-publish on`}:{},...t===`logout`?{localCredentials:`cleared`,remoteSession:f.remoteRevoked===!0?`revoked`:`unknown`}:{}},m,{effects:i.effects.snapshot(),actions:p?[{kind:`url`,url:p.url,label:`Confirm the code`}]:f.url?[{kind:`url`,url:f.url,label:`Open`}]:[]})},present({data:e}){return{heading:t===`login`?`Login`:t===`logout`?`Logout`:`Cloud artifact`,status:e.status,subject:e.id,facts:[...e.artifact?[Z(`Artifact`,X(e,`artifact`))]:[],...e.code?[Z(`Code`,X(e,`code`))]:[],...e.url?[Z(`URL`,X(e,`url`))]:[],...e.expiresAt?[Z(`Expires`,X(e,`expiresAt`))]:[],...e.autoPublish?[Z(`Auto-publish`,X(e,`autoPublish`))]:[],...e.remoteSession?[Z(`Remote session`,X(e,`remoteSession`))]:[]],sections:e.url&&e.code?[{kind:`content`,key:`qr`,text:TN(e.url)}]:[]}}},e)}async function MN(e,t,n,r,i,a){let o=ET(e.projectDir),s=await(async(e,n)=>{let r=t.effects.begin(`publish`,e),a={...n?{visibility:n}:{},...i===void 0?{}:{onProfile:i}},s=await o.call(`POST`,`/api/cloud/publish/${e}`,Object.keys(a).length?a:void 0,t.signal);s.status>=400&&s.status<500&&t.effects.set(r,`failed`,s.json);let c=DN(s);return t.effects.confirm(r,{url:c.url,visibility:c.visibility,version:c.version}),c})(n,r),c;if(a||s.keyed){let e=a?t.effects.begin(`share-key`,n):void 0,r=await o.call(a?`PUT`:`GET`,`/api/cloud/share-key/${n}`,a,t.signal);e!==void 0&&r.status>=400&&r.status<500&&t.effects.set(e,`failed`);let i=DN(r);if(i.shareKey===void 0||a&&!i.shareKey)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not confirm the share-key state.`});c=i.shareKey??void 0,e!==void 0&&t.effects.confirm(e,{expiresAt:c?.expiresAt})}let l=DN(await o.call(`GET`,`/api/cloud/refs/${n}?visibility=${s.visibility}&referrers=0`,void 0,t.signal)),u=e.values[`no-refs`]?[]:l.items.filter(e=>e.checked&&e.state!==`private`),d=/* @__PURE__ */ new Map;if(u.length){let e=new Map(u.map(e=>[e.artifact,t.effects.begin(`publish`,e.artifact)])),r=DN(await o.call(`POST`,`/api/cloud/publish-refs/${n}`,{visibility:s.visibility,refs:u.map(e=>e.artifact),makePublic:[]},t.signal));for(let n of r.results){d.set(n.artifact,n);let r=e.get(n.artifact);r!==void 0&&(n.status===`published`?t.effects.confirm(r,{}):n.status===`failed`?t.effects.set(r,`failed`,n.error):n.status===`not_attempted`&&t.effects.set(r,`not_attempted`))}}let f=e=>{try{DN({status:e.error?.httpStatus??500,json:e.error??{}})}catch(e){return LC(e)}},p={publish:`published`,update:`updated`,"make-public":`made_public`},m=l.items.map(e=>{let t={artifact:e.artifact,state:e.state,via:e.via},n=d.get(e.artifact);if(n){let e=n.status===`published`?void 0:f(n);return{...t,status:n.status===`published`?p[n.action]:n.status,...e?{error:e}:{}}}return e.reason===`upstream`?{...t,status:`unreachable`}:e.state===`unpublished`||e.state===`stale`?{...t,status:`skipped`}:{...t,status:e.state}}),h=m.some(e=>[`failed`,`unknown`,`not_attempted`].includes(e.status)),g={status:h?`partial`:`published`,artifact:n,id:s.id??new URL(s.url).pathname.split(`/`).filter(Boolean).at(-1),url:c?.url??s.url,visibility:s.visibility,...s.version===void 0?{}:{version:s.version},visibilitySource:r?`requested`:`preserved`,onProfile:s.onProfile===!0,onProfileSource:i===void 0?`preserved`:`requested`,...c?{shareKey:{key:c.key,expiresAt:c.expiresAt}}:{},references:m},_=m.filter(e=>e.status===`private`),v=m.filter(e=>e.status===`skipped`);return Y(g,h?{kind:`partial`}:{kind:`succeeded`},{effects:t.effects.snapshot(),warnings:[...(Array.isArray(s.notes)?s.notes:[]).filter(e=>typeof e==`string`).map(e=>({code:`W_CUT_NOT_PUBLISHED`,message:e})),...i&&s.visibility!==`public`?[{code:`W_PROFILE_NEEDS_PUBLIC`,message:`It will show on your profile once it is public.`}]:[],..._.length?[{code:`W_REFERENCES_PRIVATE`,message:`${_.length} referenced artifacts are private; visitors see a locked label.`}]:[],...v.length?[{code:`W_REFERENCES_UNPUBLISHED`,message:`${v.length} referenced artifacts were left as they are (--no-refs).`}]:[]],actions:[...m.flatMap(e=>e.error?hw(e.error,e.artifact):[]),..._.map(t=>lw([`publish`,`--artifact`,t.artifact,`--project-dir`,e.projectDir,`--public`],`Next`)),...v.length&&!h?[lw([`publish`,`--artifact`,n,`--project-dir`,e.projectDir],`Next`)]:[]]})}function NN({data:e}){return{heading:`Publish`,status:e.status,subject:e.artifact,facts:[Z(`ID`,X(e,`id`),!0),Z(`URL`,X(e,`url`),!0),Z(`Visibility`,{key:`visibility`,value:`${e.visibility} (${e.visibilitySource})`},!0),...e.visibility===`public`?[Z(`Profile`,{key:`onProfile`,value:e.onProfile?`listed`:`not listed`},!0)]:[],...e.shareKey?[Z(`Key`,{key:`shareKey.key`,value:e.shareKey.key},!0),Z(`Expires`,{key:`shareKey.expiresAt`,value:e.shareKey.expiresAt??`never`},!0)]:[],...e.version===void 0?[]:[Z(`Version`,X(e,`version`))]],sections:e.references.length?[{kind:`records`,key:`references`,title:`Referenced artifacts`,rows:e.references.map(e=>({artifact:e.artifact,status:e.status,via:e.via?`via ${e.via}`:``,error:e.error?`${e.error.code}: ${e.error.message}`:``,recovery:e.status===`unknown`?`inspect the remote artifact before retrying`:``})),columns:[{key:`artifact`,positional:!0,required:!0},{key:`status`,positional:!0,required:!0},{key:`via`,positional:!0},{key:`error`,positional:!0},{key:`recovery`,positional:!0}]}]:[]}}function PN({data:e,coverage:t}){return{heading:`Cloud artifacts`,status:``,summary:`${t.page?.total??e.artifacts.length} on account`,facts:[],sections:[{kind:`records`,key:`artifacts`,rows:e.artifacts.map(e=>({...e,version:e.version===void 0?``:`v${e.version}`})),columns:[{key:`id`,positional:!0,required:!0},{key:`type`,positional:!0},{key:`visibility`,positional:!0,required:!0},{key:`version`,positional:!0},{key:`updatedAt`,positional:!0},{key:`title`,positional:!0}]}]}}function FN(e){let{action:t,artifact:n,visibility:r,onProfile:i,key:a,space:o}=AN(e);if(t===`list`&&n)return Q({id:`publish.list`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},async run(t,r){let i=ET(e.projectDir),a=gC(DN(await i.call(`GET`,`/api/cloud/publication/${n}`,void 0,r.signal)));if(!a)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported publication state.`});let{shareKey:o}=DN(await i.call(`GET`,`/api/cloud/share-key/${n}`,void 0,r.signal));if(o===void 0)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server did not return the current share-key state.`});return Y({artifact:n,publication:a,shareKey:o})},present({data:e}){return{heading:`Cloud artifact`,status:e.publication.phase,subject:n,facts:[Z(`Published at`,{key:`publication.publishedAt`,value:e.publication.publishedAt}),Z(`Key`,{key:`shareKey.key`,value:e.shareKey?.key??`none`},!0),...e.shareKey?[Z(`URL`,{key:`shareKey.url`,value:e.shareKey.url},!0),Z(`Expires`,{key:`shareKey.expiresAt`,value:e.shareKey.expiresAt??`never`},!0)]:[]],sections:[]}}},e);if(t===`publish`)return Q({id:`publish.publish`,mode:`finite`,output:{formats:ON,scalar:e=>e.id},run:(t,s)=>(o&&MC(f.default.join(f.default.dirname(ce(e.projectDir).root),`config.json`),o),MN(e,s,n,r,i,a)),present:NN},e);if(t===`list`){let t=new URLSearchParams({semantic:`1`});for(let n of[`visibility`,`type`,`project`,`limit`,`cursor`,`fields`]){let r=e.values[n];typeof r==`string`&&t.set(n,r)}if(typeof e.values.module==`string`){t.has(`project`)||t.set(`project`,_M(ce(e.projectDir).project));let n=e.values.module.split(`,`).map(e=>e.trim());for(let e of new Set(n))t.append(`module`,e)}if(t.has(`limit`)&&(!/^\d+$/.test(t.get(`limit`))||+t.get(`limit`)<1||+t.get(`limit`)>100))throw new J({code:`E_ARGUMENT_INVALID`,message:`--limit must be between 1 and 100.`});if(t.has(`visibility`)&&![`public`,`private`].includes(t.get(`visibility`))||t.has(`type`)&&!Ae(t.get(`type`)))throw new J({code:`E_ARGUMENT_INVALID`,message:`Invalid Cloud list filter.`});return Q({id:`publish.list`,mode:`finite`,output:{detail:!0,formats:[`brief`,`table`,`json`,`jsonl`,`raw`],fields:[`id`,`type`,`title`,`project`,`modules`,`visibility`,`url`,`updatedAt`,`version`],collection:`artifacts`,requiredFields:[`id`,`type`,`visibility`,`version`]},async run(n,r){let i=await ET(e.projectDir).call(`GET`,`/api/cloud/artifacts?${t}`,void 0,r.signal);r.payloads.raw=i.raw;let a=DN(i);if(a.schema!==`ryugi.cloud-list/v1`)throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported Cloud list response.`});return Y({artifacts:a.artifacts},void 0,{coverage:{page:a.page},actions:a.page?.nextCursor?[lw([`publish`,`--list`,`--project-dir`,e.projectDir,...[...new Set(t.keys())].filter(e=>![`semantic`,`cursor`].includes(e)).flatMap(e=>[`--${e}`,t.getAll(e).join(`,`)]),`--cursor`,a.page.nextCursor],`More`)]:[]})},present:PN},e)}return jN(e,t,n)}const IN={semantic:FN,name:`publish`,summary:`Publish an artifact to the Artideck Cloud (needs a running server)`,usage:[`--artifact <type>/<id> [--public | --private | --key] [--profile | --no-profile] [options]`,`--artifact <type>/<id> --unpublish | --revoke-key [options]`,`--list | --delete <cloud-id> | --login | --logout [options]`,`--move-to <team-slug> (move this project into a team)`,`--list --artifact <type>/<id> (read publication and current key state without changing either)`],options:{visibility:{type:`string`,value:`<public|private>`,help:`Filter published list visibility`},type:{type:`string`,value:`<${k.join(`|`)}>`,help:`Filter published list type`},project:{type:`string`,value:`<project>`,help:`Filter published list project`},module:{type:`string`,value:`<id>[,<id>...]`,help:`Filter published list by module ("" for untagged); the project defaults to this one`},limit:{type:`string`,value:`<1-100>`,help:`Maximum list rows`},cursor:{type:`string`,value:`<token>`,help:`Continue a stable list snapshot`},artifact:{type:`string`,value:`<type>/<id>`,help:`The artifact to publish, unpublish, revoke a key, or inspect with --list`},public:{type:`boolean`,help:`Anyone with the link can open it`},private:{type:`boolean`,help:`Only you can open it`},key:{type:`boolean`,help:`Only people with the key can open it; prints a link that carries the key`},expires:{type:`string`,value:`<1d|7d|30d|never>`,help:`With --key or --new-key: when the key stops working (7d for a new key)`},"new-key":{type:`boolean`,help:`Replace the key; links with the old key stop opening`},"revoke-key":{type:`boolean`,help:`Remove the key; only you can open it`},profile:{type:`boolean`,help:`Show it on your public profile once it is public`},"no-profile":{type:`boolean`,help:`Take it off your public profile`},unpublish:{type:`boolean`,help:`Remove the artifact's cloud copy`},list:{type:`boolean`,help:`List your cloud artifacts; with --artifact, read its publication and current key state`},delete:{type:`string`,value:`<cloud-id>`,help:`Delete a cloud artifact by its id from --list`},space:{type:`string`,value:`<team-slug|personal>`,help:`Where this project's new artifacts publish; already published ones stay where they are`},"move-to":{type:`string`,value:`<team-slug>`,help:`Move every artifact of this project from your personal space into a team; links stay the same`},"no-refs":{type:`boolean`,help:`Publish only this artifact; leave the artifacts it references as they are`},login:{type:`boolean`,help:`Sign in to the Artideck Cloud`},"with-token":{type:`boolean`,help:`With --login: read an access token from stdin instead of opening a browser`},from:{type:`string`,value:`<tag>`,help:`With --login: where this sign-in started, recorded by Artideck Cloud`},logout:{type:`boolean`,help:`Sign out of the Artideck Cloud`}}},LN=/* @__PURE__ */ new Set([`created`,`updated`,`bound`]),RN=/* @__PURE__ */ new Set([`conflict`,`name_clash`]);function zN({data:e}){let t=/* @__PURE__ */ new Map;for(let n of e.results)t.set(n.outcome,(t.get(n.outcome)??0)+1);return{heading:`Pull`,status:``,subject:e.project,summary:e.results.length?[...t].map(([e,t])=>`${t} ${e}`).join(` · `):`no Cloud artifacts in this project`,facts:[Z(`Project`,X(e,`project`))],sections:[{kind:`records`,key:`results`,rows:e.results.map(e=>({...e,note:e.message??e.notes?.join(`; `)??``})),columns:[{key:`key`,positional:!0,required:!0},{key:`outcome`,positional:!0,required:!0},{key:`url`,positional:!0},{key:`note`,positional:!0}]}]}}function BN(e){let t=e.values.artifact,n=e.positionals[0];if(t&&n)throw new J({code:`E_OPTION_CONFLICT`,message:`Give --artifact or a Cloud link, not both.`});let r=t??n,i=e.values.as;if(i&&!r)throw new J({code:`E_ARGUMENT_INVALID`,message:`--as needs one target: --artifact <type>/<id> or a Cloud link.`});let a=e.values[`dry-run`]===!0,o=e.values.force===!0,s=e.values.project;return Q({id:`pull`,mode:`finite`,output:{formats:[`brief`,`table`,`json`,`jsonl`],collection:`results`,fields:[`key`,`outcome`,`cloudId`,`url`,`dir`,`message`,`notes`],requiredFields:[`key`,`outcome`]},async run(t,n){let c=DN(await ET(e.projectDir).call(`POST`,`/api/cloud/pull`,{target:r,project:s,as:i,dryRun:a,force:o},n.signal));if(!Array.isArray(c.results))throw new J({code:`E_PROTOCOL_MISMATCH`,message:`The server returned an unsupported pull response.`});if(!a)for(let e of c.results){if(!LN.has(e.outcome)&&e.outcome!==`failed`)continue;let t=n.effects.begin(`pull.${e.outcome}`,e.key);e.outcome===`failed`?n.effects.set(t,`failed`,{message:e.message}):n.effects.confirm(t)}let l=c.results.some(e=>e.outcome===`failed`)?{kind:`partial`}:c.results.some(e=>RN.has(e.outcome))?{kind:`validation_failed`}:{kind:`succeeded`},u=[`--project-dir`,e.projectDir];return Y(c,l,{effects:n.effects.snapshot(),actions:c.results.flatMap(e=>e.outcome===`conflict`?[lw([`get`,e.url],`Compare`),lw([`pull`,e.cloudId,`--force`,...u],`Take Cloud`)]:e.outcome===`name_clash`?[lw([`pull`,e.cloudId,`--as`,`${e.key.split(`/`)[1]}-cloud`,...u],`Pull as`)]:[])})},present:zN},e)}const VN={semantic:BN,name:`pull`,summary:`Pull this project's Cloud artifacts into the local artifacts folder (needs a running server)`,usage:[`[--project <owner/repo>] [--dry-run] [--force] [options]`,`--artifact <type>/<id> | <link-or-cloud-id> [--as <id>] [--dry-run] [--force] [options]`],positionals:1,details:`Each Cloud artifact of the project lands in .ryugi/artifacts/<type>/<slug> and stays bound to its Cloud link, so publish updates it instead of creating a new one.
|
|
982
982
|
|
|
983
983
|
Results:
|
|
984
984
|
created no local copy; downloaded and bound
|
|
@@ -990,5 +990,5 @@ Results:
|
|
|
990
990
|
name_clash the directory holds something else; nothing written. Pull it under another name with --as
|
|
991
991
|
failed a download or write failed; the local copy is as it was
|
|
992
992
|
|
|
993
|
-
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
|
|
994
|
-
`);throw new rP(`Could not tell how ${xO} was installed (${e.file}). Install ${i} with one of:\n${t}\nor run \`${xO} update --pm <${wO.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...a,upToDate:!1,command:`adeck update`};let n=kO(e.env),r=new FO(n).current();if(!r)throw new M(`Managed runtime state is missing; run adeck doctor.`);let o=new FO(n,f.default.dirname(r.bin)),s=f.default.join(n,`downloads`,`runtime-${(0,u.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(i):(d.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${xO}@${i}`),hO(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${xO}@${i}`]),n=f.default.join(s,`node_modules`,xO)),o.install(n),{type:`updated`,from:e.current,to:i,pm:`ryugi`,command:`adeck update`}}finally{d.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...a,upToDate:!1,command:null,message:nP(n,i)};let o=$N(n.pm,i,r);if(e.check)return{...a,upToDate:!1,command:eP(o)};let s=process.platform===`win32`;t.beforeInstall?.();let c=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],l=s?(0,p.spawnSync)(eP(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 M(`Could not run ${eP(o)}: ${l.error.message}`);if(l.status!==0)throw new M(`${eP(o)} exited with ${l.status??l.signal}`);return{type:`updated`,from:e.current,to:i,pm:n.pm,command:eP(o)}}const oP=[aT,mT,WN,cD,FN,BN,WT,iE,BT,VM,TD,rD,cE,Hj,Qj,OD,{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=>Q({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 M(`Choose --cli-only or --plugins-only`);let r=e.values.check?null:KO(h.default.homedir(),process.env.RYUGI_DEV_LINK||void 0);if(r)throw new J({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.113.2`,latest:`1.113.2`,install:OO(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await aP({current:`1.113.2`,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`,JN(process.env))},cacheRefreshed(){a!==void 0&&n.effects.confirm(a)},beforeInstall(){i=n.effects.begin(`install`,xO)},log:n.diagnostic})}catch(e){throw e instanceof rP?new J({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=f.default.resolve(e.values[`install-dir`]||kO());if(!e.values.check&&!e.values[`cli-only`]){s.plugins=[];for(let t of Object.values(RO(c).harnesses)){let r=await uM({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 iP(s.current,n);t&&(s.daemon=t),s.hub=await ZN({cli:s.status===`updated`?`updated`:`current`,daemon:t?.status===`updated`?`updated`:`current`,from:`1.113.2`,to:s.current,newCli:s.install===`managed`?new FO(kO(process.env)).bin:s.install===`global`?`ryugi`:null,projectDir:e.projectDir},QN)}let l=e.values.check?{warnings:[],actions:[]}:mj(await gj({cleanup:!0,root:c},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return Y(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`?[lw([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...l.actions]})},present:XN},e)},fM,Cj,nO,lk,Wj,KN];function sP(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[{...lw(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`?[lw([`start`,`--background`,`--no-open`,...o],`Start server`)]:n?.code===`E_ARGUMENT_INVALID`||n?.code===`E_OPTION_CONFLICT`?[lw([t.split(`.`)[0],...e.positionals[0]&&t.startsWith(`comment`)?[e.positionals[0]]:[],`--help`],`Help`)]:n?hw(n):[]}}async function cP(e,t,n,r){return jw({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 lP(e,t){return{id:e,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`text`,`version`,`capabilities`,`commands`]},run(){return Y(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 uP(e,t,n,r,i,a,o){let[s,...c]=e,l=t.find(e=>e.name===s),u;try{if(l?.positionals&&l.usage?.some(e=>/^[a-z]+\s/.test(e))&&(u=$C(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return $C(c,{},0),await Q(lP(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&ew(c)){l||$C(c,{},0);let e=l?iw(l,u):aw(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=$C(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=mC():typeof t.values.artifact==`string`&&(e+=`\n\n${pC(t.values.artifact)}`)}return await Q(lP(`help`,{text:e,commands:t.map(({name:e,summary:t})=>({name:e,summary:t}))}),void 0).run(i,a)}if(!l&&(!s||s.startsWith(`-`)||(()=>{try{return d.default.statSync(s).isDirectory()}catch{return!1}})())){let t=$C(e,n,1);if(t.positionals.length&&t.values[`project-dir`])throw new J({code:`E_ARGUMENT_INVALID`,message:`Specify one project directory.`});return t.projectDir=t.values[`project-dir`]??t.positionals[0]??t.projectDir,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await Lw(t,`browse`).run(i,a,o)}if(!l)throw new J({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=$C(c,rw(l,u),l.positionals)}catch(e){throw new J({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=ce(f.projectDir).project,await l.semantic(f).run(i,a,o,sP(f))}catch(e){let t=e instanceof M?new J({code:`E_ARGUMENT_INVALID`,message:e.message}):e;return t instanceof Error&&Object.assign(t,{actions:[lw([...l?[l.name,...u&&l.usage?.some(e=>e.startsWith(`${u} `))?[u]:[]]:[],`--help`],`Help`)]}),cP(l?.name??s??`browse`,t,i,a)}}function dP(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 fP(e){process.exitCode=e}const pP={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function mP(e){T(`cli`);let t=Object.assign({},ZC,...oP.map(e=>e.options)),n=dP(),r;try{r=UC(e,t,YC(e,t))}catch(r){return cP(e[0]??`browse`,r,UC(e,t).options,n)}if(r.error)return cP(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 uP(e,oP,pP,`1.113.2`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}mP(process.argv.slice(2)).then(fP,e=>cP(process.argv[2]??`browse`,e,{format:`brief`},dP()).then(fP));
|
|
993
|
+
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 HN(e){for(let t of Ge(e))d.default.rmSync(f.default.join(Ke(t.dir),`.state`,`server-info`),{force:!0})}function UN({data:e}){return{heading:`Server`,status:e.status,summary:e.status===e.reason?``:e.reason.replaceAll(`_`,` `),facts:[Z(`Scope`,X(e,`scope`)),Z(`Artifacts`,X(e,`artifacts`))],sections:[]}}async function WN(){let e=He(),t=t=>{d.default.rmSync(e.info,{force:!0}),HN(e.projects),d.default.mkdirSync(e.home,{recursive:!0,mode:448}),d.default.writeFileSync(e.stopped,`${JSON.stringify({reason:t,timestamp:Math.floor(Date.now()/1e3)})}\n`)};if(P(e.pid)===null)return{status:`not_running`};let n=Number(P(e.pid)),r=P(e.serverId)??``;if(!Number.isInteger(n)||n<=0||!/^[\w-]{32,64}$/.test(r)||!_e(n,r))return d.default.rmSync(e.pid,{force:!0}),d.default.rmSync(e.serverId,{force:!0}),t(`stale_pid`),{status:`stale_pid`};t(`stop`),O(e,{action:`stopped`,pid:n,running:P(e.version)??``,cli:process.env.RYUGI_ARTIFACTS_VERSION||`1.114.0`});try{process.kill(n,`SIGTERM`)}catch{}if(!await N(n,7e3)){Rn(e)?.unload();try{process.kill(n,`SIGKILL`)}catch{}await N(n,1e3)}if(pe(n))return d.default.rmSync(e.stopped,{force:!0}),{status:`failed`,error:`process still running`};for(let t of[e.pid,e.serverId])d.default.rmSync(t,{force:!0});return t(`stop`),{status:`stopped`}}const GN={name:`stop`,summary:`Stop this machine's artifacts server; the artifacts are kept`,usage:[`[options]`],options:{},semantic:e=>Q({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 WN();return r.status!==`failed`&&t.effects.set(n,r.status===`not_running`?`none`:`confirmed`),Y({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:UN},e)};function KN({data:e}){return{heading:`Uninstall`,status:e.failures.length?`partial`:`removed`,facts:[Z(`Removed`,{key:`removed`,value:e.removed.join(`, `)}),Z(`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 qN={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=>Q({id:`uninstall`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`]},run(t,n){let r=typeof e.values.harness==`string`?e.values.harness.split(`,`).map(RO):void 0;if(r?.some(e=>!hO.some(t=>t.id===e)))return Y({removed:[],preserved:[],failures:[]},{kind:`validation_failed`},{warnings:[{code:`E_HARNESS`,severity:`error`,message:`Unknown harness selection`}]});let i=f.default.resolve(e.values[`install-dir`]||AO()),a=n.effects.begin(`uninstall`,i),o=Cj(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),Y(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:KN},e)};function JN(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 YN=e=>f.default.join(e.XDG_CACHE_HOME||f.default.join(h.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function XN(e,t,n){try{d.default.mkdirSync(f.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}`;d.default.writeFileSync(r,JSON.stringify({version:t,checkedAt:n})),d.default.renameSync(r,e)}catch{}}function ZN({data:e}){return{heading:`Update`,status:e.status,facts:[Z(`Current`,X(e,`current`),!0),Z(`Latest`,X(e,`latest`)),Z(`Install`,X(e,`install`)),...e.message?[Z(`Advice`,X(e,`message`))]:[],...e.daemon?[Z(`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`?[Z(`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 QN(e,t){if(e.cli===`current`&&e.daemon===`current`)return{status:`unchanged`};let n=t.running();if(!n)return{status:`not-running`};if(Vw(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 $N={running(){let e=He(),t=Zw(e);return t?{pid:t,version:P(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 ID(e,{reason:`update`,startStopped:!1})}};function eP(e,t,n=SO){let r=`${n}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,r]:e===`yarn`?[`global`,`add`,r]:[`add`,`-g`,r]}}const tP=({cmd:e,args:t})=>[e,...t].join(` `);async function nP(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 M(`Could not get the latest ${t} version from ${n}: ${e.message}`)}}function rP(e,t){return e.kind===`transient`?`You ran ${SO} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${SO}@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 iP=class extends M{};async function aP(e,t){if(!Rt[process.platform]?.includes(process.arch))return;let n=h.default.homedir(),r,i=await RD({arch:process.arch,cliDir:__dirname,env:process.env,fetch,home:n,platform:process.platform,serverHome:He().home,version:e},()=>{r=t.effects.begin(`update.daemon`,LD(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 oP(e,t={}){if(e.pm!==void 0&&!TO.includes(e.pm))throw new M(`--pm must be one of ${TO.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:kO(e.file,e.env),r=n.kind===`global`||n.kind===`unknown`?OO(e.file):SO,i=await nP(e.registry,r);t.beforeCache?.(),XN(YN(e.env),i,Date.now()),t.cacheRefreshed?.();let a={type:`update-check`,current:e.current,latest:i,install:n.kind};if(!JN(i,e.current))return{...a,upToDate:!0,command:null};if(n.kind===`unknown`){let t=TO.map(e=>` ${tP(eP(e,i,r))}`).join(`
|
|
994
|
+
`);throw new iP(`Could not tell how ${SO} was installed (${e.file}). Install ${i} with one of:\n${t}\nor run \`${SO} update --pm <${TO.join(`|`)}>\`.`)}if(n.kind===`managed`){if(e.check)return{...a,upToDate:!1,command:`adeck update`};let n=AO(e.env),r=new IO(n).current();if(!r)throw new M(`Managed runtime state is missing; run adeck doctor.`);let o=new IO(n,f.default.dirname(r.bin)),s=f.default.join(n,`downloads`,`runtime-${(0,u.randomUUID)()}`);try{t.beforeInstall?.();let n;return t.downloadRuntime?n=await t.downloadRuntime(i):(d.default.mkdirSync(s,{recursive:!0}),t.log?.(`Downloading ${SO}@${i}`),gO(`npm`,[`install`,`--prefix`,s,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--omit=dev`,`--legacy-peer-deps`,`--registry`,e.registry,`${SO}@${i}`]),n=f.default.join(s,`node_modules`,SO)),o.install(n),{type:`updated`,from:e.current,to:i,pm:`ryugi`,command:`adeck update`}}finally{d.default.rmSync(s,{recursive:!0,force:!0})}}if(n.kind!==`global`)return{...a,upToDate:!1,command:null,message:rP(n,i)};let o=eP(n.pm,i,r);if(e.check)return{...a,upToDate:!1,command:tP(o)};let s=process.platform===`win32`;t.beforeInstall?.();let c=t.log?[`inherit`,`pipe`,`pipe`]:[`inherit`,2,2],l=s?(0,p.spawnSync)(tP(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 M(`Could not run ${tP(o)}: ${l.error.message}`);if(l.status!==0)throw new M(`${tP(o)} exited with ${l.status??l.signal}`);return{type:`updated`,from:e.current,to:i,pm:n.pm,command:tP(o)}}const sP=[aT,mT,GN,lD,IN,VN,WT,iE,BT,HM,ED,rD,cE,Uj,$j,kD,{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=>Q({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 M(`Choose --cli-only or --plugins-only`);let r=e.values.check?null:qO(h.default.homedir(),process.env.RYUGI_DEV_LINK||void 0);if(r)throw new J({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.114.0`,latest:`1.114.0`,install:kO(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await oP({current:`1.114.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`,YN(process.env))},cacheRefreshed(){a!==void 0&&n.effects.confirm(a)},beforeInstall(){i=n.effects.begin(`install`,SO)},log:n.diagnostic})}catch(e){throw e instanceof iP?new J({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=f.default.resolve(e.values[`install-dir`]||AO());if(!e.values.check&&!e.values[`cli-only`]){s.plugins=[];for(let t of Object.values(zO(c).harnesses)){let r=await dM({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 aP(s.current,n);t&&(s.daemon=t),s.hub=await QN({cli:s.status===`updated`?`updated`:`current`,daemon:t?.status===`updated`?`updated`:`current`,from:`1.114.0`,to:s.current,newCli:s.install===`managed`?new IO(AO(process.env)).bin:s.install===`global`?`ryugi`:null,projectDir:e.projectDir},$N)}let l=e.values.check?{warnings:[],actions:[]}:hj(await _j({cleanup:!0,root:c},n,!!process.stdin.isTTY&&!!process.stderr.isTTY));return Y(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`?[lw([`start`,`--background`,`--no-open`,`--project-dir`,e.projectDir],`Restart server`)]:[],...l.actions]})},present:ZN},e)},pM,wj,rO,uk,Gj,qN];function cP(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[{...lw(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`?[lw([`start`,`--background`,`--no-open`,...o],`Start server`)]:n?.code===`E_ARGUMENT_INVALID`||n?.code===`E_OPTION_CONFLICT`?[lw([t.split(`.`)[0],...e.positionals[0]&&t.startsWith(`comment`)?[e.positionals[0]]:[],`--help`],`Help`)]:n?hw(n):[]}}async function lP(e,t,n,r){return jw({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 uP(e,t){return{id:e,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`],fields:[`text`,`version`,`capabilities`,`commands`]},run(){return Y(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 dP(e,t,n,r,i,a,o){let[s,...c]=e,l=t.find(e=>e.name===s),u;try{if(l?.positionals&&l.usage?.some(e=>/^[a-z]+\s/.test(e))&&(u=$C(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals).positionals[0]),s===`--version`||s===`-v`)return $C(c,{},0),await Q(uP(`version`,{text:r,version:r,capabilities:[`reviewBundlesV1`]}),void 0).run(i,a);if(s===`--help`||s===`-h`||l&&ew(c)){l||$C(c,{},0);let e=l?iw(l,u):aw(t,n);if(l&&[`start`,`check`].includes(l.name)){let t=$C(c.filter(e=>e!==`--help`&&e!==`-h`),l.options,l.positionals);t.values.mockup?e=mC():typeof t.values.artifact==`string`&&(e+=`\n\n${pC(t.values.artifact)}`)}return await Q(uP(`help`,{text:e,commands:t.map(({name:e,summary:t})=>({name:e,summary:t}))}),void 0).run(i,a)}if(!l&&(!s||s.startsWith(`-`)||(()=>{try{return d.default.statSync(s).isDirectory()}catch{return!1}})())){let t=$C(e,n,1);if(t.positionals.length&&t.values[`project-dir`])throw new J({code:`E_ARGUMENT_INVALID`,message:`Specify one project directory.`});return t.projectDir=t.values[`project-dir`]??t.positionals[0]??t.projectDir,t.values.foreground=!0,t.values.open=!t.values[`no-open`],await Lw(t,`browse`).run(i,a,o)}if(!l)throw new J({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=$C(c,rw(l,u),l.positionals)}catch(e){throw new J({code:`E_ARGUMENT_INVALID`,message:e.message})}return f.projectDir=ce(f.projectDir).project,await l.semantic(f).run(i,a,o,cP(f))}catch(e){let t=e instanceof M?new J({code:`E_ARGUMENT_INVALID`,message:e.message}):e;return t instanceof Error&&Object.assign(t,{actions:[lw([...l?[l.name,...u&&l.usage?.some(e=>e.startsWith(`${u} `))?[u]:[]]:[],`--help`],`Help`)]}),lP(l?.name??s??`browse`,t,i,a)}}function fP(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 pP(e){process.exitCode=e}const mP={"no-open":{type:`boolean`,help:`Print the URL without opening a browser`}};async function hP(e){T(`cli`);let t=Object.assign({},ZC,...sP.map(e=>e.options)),n=fP(),r;try{r=UC(e,t,YC(e,t))}catch(r){return lP(e[0]??`browse`,r,UC(e,t).options,n)}if(r.error)return lP(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 dP(e,sP,mP,`1.114.0`,r.options,n,i.signal)}finally{process.removeListener(`SIGINT`,a),process.removeListener(`SIGTERM`,o)}}hP(process.argv.slice(2)).then(pP,e=>lP(process.argv[2]??`browse`,e,{format:`brief`},fP()).then(pP));
|