artideck 1.113.1 → 1.113.2

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 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.113.1`,S=`3fb61bfe80dc`;const C=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Ryugi ${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(`
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.113.2`,S=`3fb61bfe80dc`;const C=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Ryugi ${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`
@@ -71,7 +71,7 @@ function run(urls) {
71
71
  </dict>
72
72
  </plist>
73
73
  `}const kt=e=>`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`%`,`%%`)}"`;function At(e){let t=e.log.replaceAll(`%`,`%%`);return`[Unit]
74
- Description=Ryugi hub
74
+ Description=Artideck hub
75
75
 
76
76
  [Service]
77
77
  ExecStart=${kt(e.binary)} hub ${kt(`${Et}${e.launch}`)}
@@ -222,7 +222,7 @@ getElementsByTagNameNS(e,t){return this.getElementsByTagName(t)}createAttributeN
222
222
  `),r_=(e,t)=>e.split(`
223
223
  `).map(e=>e&&`${t}${e}`).join(`
224
224
  `);function i_(e){let t;try{t=JSON.parse(e)}catch{return`[chart]`}let n=t.x??``,r=t.series??[],i=e=>`| ${e.map(e=>String(e??``)).join(` | `)} |`,a=[i([n,...r.map(e=>e.label??e.key)]),i(Array.from({length:r.length+1},()=>`---`)),...(t.data??[]).map(e=>i([e[n],...r.map(t=>e[t.key])]))].join(`
225
- `);return t.title?`**${t.title}**\n\n${a}`:a}const a_=e=>e.root;function o_(e,t){return new e_(new Map(t.map(e=>[e.id,e]))).document(a_(e).children)}const s_=e=>[...e.replaceAll(/\s/g,``)].length;function c_(e,t=[]){let n=new e_(new Map(t.map(e=>[e.id,e]))),r=[];for(let t of a_(e).children??[])t.type===`heading`?r.push({id:Yg(t.$?.blockId),level:Number(Yg(t.tag).slice(1))||1,title:n.inline(t.children),chars:0}):r.length&&(r.at(-1).chars+=s_(n.block(t)));return r}function l_(e){try{return Cr(xr(d.default.readFileSync(f.default.join(e,`comments.json`),`utf8`))).threads}catch{return[]}}function u_(e){let t=Gg(d.default.readFileSync(f.default.join(e,`doc.xml`),`utf8`)),n=mr(sr(t),l_(e)),r=Er(e);return{markdown:(r?`${Kg}\n\n${r.markdown}\n\n---\n\n`:``)+o_(t,n),outline:c_(t,n)}}function d_(e,t,n,r){if(e===`submit`)return{op:`submit`,submit:!t.withdraw};if(!t.ask)throw new M(`comment ${e} needs --ask <questionId>`);if(e===`note`)return{op:`note`,ask:t.ask,text:n()};let i=r?.trim();if(!t.clear&&!t.choice&&!i)throw new M(`comment answer needs --choice <value>, --text <answer>, or --clear`);return{op:`answer`,ask:t.ask,choice:t.clear?null:t.choice??null,answer:t.clear?null:i??null}}var f_='# Document writing\n\nCreate a working copy of the LiteXML outside the artifact directory. For an edit, also keep an untouched copy of the current doc.xml. Save via `write-document --artifact document/<id> --input <edited.xml>`, adding `--base <original.xml>` for edits. This records the writer at the mutation; put assets in `assets/`. Re-read immediately before each edit: the human and server edit this file too. Patch intended blocks, preserve existing IDs and human text; new blocks omit IDs and receive them from the server. Never edit `comments.json` or `.state/`. The server normalizes aliases and indentation after saving. Finish with `check`; pending merging or browser work means check again, not success.\n\nUse a closed `<doc>`. Choose blocks for the reader: diagrams show relationships, charts compare numbers, tables map exact attributes, prose explains reasons. A first draft can contain `<pending intent="What remains to investigate"/>`; fill every pending before claiming completion. Diagrams use native mermaid, or a whiteboard of this project embedded with a reference (below); never pictures of text or box drawing in code blocks.\n\nComplete block and inline vocabulary:\n\n- `h1`–`h6`, `p`, `blockquote`, `ul`/`ol` with `li`, `table`/`tr`/`th`/`td`, `hr`.\n- Inline `b i u s code sub sup mark a br`; aliases `strong em del strike`. Links use `href`. Ordered lists accept `start`; checklists use `<ul type="check"><li checked="true">Done</li></ul>`.\n- `codeblock lang="ts"`: code; use CDATA for literal XML/angle brackets. `mermaid`: native flowcharts/sequences/states. `math`: inline LaTeX, `display="block"` for a block.\n- `img src="assets/image.png" alt="…" caption="…" width="640"`: real images.\n- `alert type="note|tip|important|warning|caution"`: block children. `details summary="…" open="true"`: collapsed depth; omit open for collapsed. `steps` contains `step title="…"` with block children; titles omit numbering.\n- `footnote ref="1"` inline; `footnote-section` contains `def ref="1"` definitions.\n- `chart`: CDATA ChartSpec JSON. Required `version:1`, `type:bar|line|area|pie`, `x` category field, `series:[{key,label?}]`, `data` rows containing x and every series key. Values numbers/null, pie nonnegative. At most 6 series and 6 pie rows. Optional title/subtitle/note/source/xLabel/stacked/donut/highlight, format `{unit,compact,decimals,signed}`, y `{min,max}`, refs `[{y,label}]`. `highlight` is a `series.key` and highlights that entire series; omit it when unnecessary. With `series:[{key:"failures"}]` and rows `[{phase:"Before",failures:12},{phase:"After",failures:4}]`, `highlight:"failures"` is valid; `highlight:"After"` is invalid because it is a row/category value.\n- `dynamic url="assets/demo.html" initial-height="240"`: CDATA JSON becomes `window.ryugiProps`. Self-contained sandboxed HTML, inline scripts/styles, size by content, transparent body. Browser controls persist on HTML rewrite; changing props resets them. Runtime is incomplete until the block has run. Native HTML/CSS/JS and `ryugi-icon` work; storage/cookies do not.\n- `pending intent="…"`, inline `ask`/`option` and `ref` (below; a whiteboard `ref` can also embed as a block). Other tags are rejected.\n\n```xml\n<doc>\n <h1>Retry policy</h1>\n <p>Retry failed delivery at most <b>3</b> times.</p>\n <mermaid><![CDATA[flowchart LR\n ingress --> queue --> worker]]></mermaid>\n <p>Choose a strategy: <ask id="retry-strategy" recommend="exponential"><option value="fixed">Fixed delay</option><option value="exponential">Exponential backoff</option></ask></p>\n <details summary="Evidence"><codeblock lang="text"><![CDATA[attempts: 3]]></codeblock></details>\n</doc>\n```\n\nQuestions: `ask` is inline in p/li/table-cell paragraphs, never directly under doc. Its unique stable id is lowercase letters/digits/hyphens; never reuse an old question ID. Options contain plain text and distinct `value`s; `recommend` must name an option. No options makes an open question: `<ask id="other" placeholder="Describe it"/>`. Human picks are drafts until submitted. Read `comment list --sections threads,asks --detail`. Apply submitted answers, then `comment note --ask <id> --text <what changed>`. Every submitted question needs a note, even unanswered ones (state what was left or assumed). Record terminal answers only when actually supplied via `comment answer --ask <id> --choice <value>` or `--text`, then `comment submit`. Never invent an answer; wait after withdrawal. Changed settled answers require a human instruction and a fresh note.\n\nReferences: inline `<ref document="slug"/>`, `<ref document="slug" block="block-id"/>` (one top-level block of a document: the `id` of its `h2`, `p`, list…; name this document\'s own slug to jump within it), `<ref html="slug">label</ref>`, `<ref artboard="slug" group="q1"/>` (or board), `<ref whiteboard="slug" frame="f1"/>` (or page), `<ref slides="slug" slide="slide-id"/>` (a deck, or one slide of it). Exactly one kind, at most one allowed subtarget, lowercase slug. Optional plain text label; server adds `to` when resolved, preserve it. Missing targets, including a block the document no longer has, are warnings; clear before handoff. Keep referenced IDs stable; when changing a target, update the reference too. A reference under its section heading connects that section to its companion canvas. Live choices/verdicts belong in refs, not duplicated prose.\n\nEmbedded whiteboards: `<ref whiteboard="slug" frame="f1" embed="true"/>` draws the whiteboard in the document instead of a chip. Write it as a paragraph of its own directly under `<doc>`, e.g. `<p><ref whiteboard="sync-flow" frame="f-steps" embed="true"/></p>`; never beside text, in a list, table or quote. `frame` shows that frame cut to its box, `page` one page, neither the main page. Only whiteboard references embed. The drawing follows the whiteboard live: draw and change it on the whiteboard, not in the document; a reader clicks it to open the whole whiteboard. A missing whiteboard or frame is the same check warning as any reference.\n\nAfter editing, run the returned Check command. It names invalid blocks, chart/math/diagram errors, unresolved refs and pending dynamic work. Read complete feedback before acting; reply/resolve and acknowledge only the receipt for evidence actually used.\n';const p_=/^(.+?)->(.+?)(?:#([1-9]\d*))?$/;function m_(e){if(e.node&&e.edge)throw new M(`comment add takes --node or --edge, not both`);if(e.node)return{kind:`node`,id:e.node};if(!e.edge)return;let t=p_.exec(e.edge);if(!t)throw new M(`comment add --edge needs "<from>-><to>", with #n for the nth edge between them`);return{kind:`edge`,from:t[1],to:t[2],index:t[3]?Number(t[3])-1:0}}const h_=e=>t=>d_(e,t,()=>$n(t),t.text);function g_(e,t,n){try{let e=u_(f.default.dirname(n));return{markdown:e.markdown,rows:e.outline}}catch(e){return{warnings:[{code:`W_DOCUMENT_MARKDOWN`,message:`could not read the document as markdown, so it is shown as LiteXML: ${e.message}`}]}}}const __={authoring:f_,localGet:{key:`outline`,read:g_,columns:[{key:`id`,required:!0,positional:!0},{key:`level`,positional:!0},{key:`title`,positional:!0},{key:`chars`}]},changes:!0,review:{sections:[`asks`]},commentActions:{submit:h_(`submit`),answer:h_(`answer`),note:h_(`note`),add:e=>{if(!e.block)throw new M(`comment add needs --block <blockId>`);let t=m_(e);return{op:`add`,blockId:e.block,...t?{diagram:t}:{},...e.quote?{quote:e.quote}:{},text:$n(e)}}}},v_={authoring:'# HTML writing\n\nWrite one complete `index.html` with a descriptive `<title>`, inline or relative styles/scripts/images. The page reloads on edits. Native HTML/CSS/JavaScript works; use labelled controls and visible results. Assets stay inside this artifact directory; CDN fonts/scripts work, absolute local paths do not. Any npm library loads from a CDN with its version pinned; nothing is preloaded, so use one instead of hand-writing its equivalent. The iframe is sandboxed: localStorage/sessionStorage/cookies throw; keep state in DOM/variables. Popups, forms, downloads and clipboard work.\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Retry explorer</title>\n </head>\n <body>\n <label>Attempts <input id="attempts" type="range" min="1" max="5" value="3" /></label>\n <output id="result"></output>\n <script>\n const input = document.getElementById(\'attempts\');\n const render = () =>\n (document.getElementById(\'result\').textContent = input.value + \' attempts\');\n input.addEventListener(\'input\', render);\n render();\n <\/script>\n </body>\n</html>\n```\n\nStable control IDs preserve human input, checks, details and scroll across rewrites. Restoration fires input/change: render from those events. Script-only state resets. Use one surface for one investigation; comparison across independent screens belongs on an artboard. Re-read files before editing; never edit comments or `.state/`.\n\nBundled UI elements require no imports. Use native HTML/CSS for layout. `ryugi-icon name="message-square" size="18"` provides Lucide kebab-case icons (stroke-width defaults 2, color currentColor); label the button, icons are decorative. Find names with `adeck icons <english words>`; unknown names become runtime warnings. For JS-only icons add `<meta name="ryugi-icons" content="1">` and await customElements.whenDefined(\'ryugi-icon\'). Preview glyphs map to the app\'s existing business icons when implementing the design.\n\nRun Check after edits. It distinguishes current static evidence from browser runtime. A closed/unloaded tab means runtime pending; open the returned URL and check again. Uncaught exceptions, rejected promises and missing relative assets are warnings; no browser run is not proof that a page works.\n\n# UI components\n\nHTML artifacts can use a small set of Lobe UI components through Web\nComponents. The artifacts server loads the runtime automatically when the page\ncontains a `<ryugi-…>` element:\n\n```html\n<ryugi-button variant="primary">Save</ryugi-button>\n```\n\nNo script tag is needed. If you create components dynamically, add\n`<meta name="ryugi-ui" content="1">` to the page so the runtime is loaded.\n\nThe runtime loads with `defer`. A page script that needs the components should\nwait for the document event:\n\n```js\ndocument.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n // custom elements are defined\n },\n { once: true },\n);\n```\n\nUse these for controls and basic display. Use plain HTML and CSS for layout;\nthere is no layout wrapper to learn.\n\n## Rules\n\n- Give every interactive control a stable `id`. The viewer restores custom\n controls across rewrites by `id`, the same way it restores native inputs.\n- Listen for `ryugi-change` on controls:\n\n ```js\n document.addEventListener(\'ryugi-change\', (event) => {\n const { value, checked } = event.detail;\n console.log(event.target.id, value, checked);\n });\n ```\n\n It bubbles. `value` is a string, number, boolean, or `null`; `checked` is\n present for checkboxes and switches.\n\n- `value` / `checked` attributes set the initial state. Read the current state\n from the element\'s `value` / `checked` property after `ryugi-ui:ready`, and\n listen for `ryugi-change` for later updates.\n- `class` styles the host; `style` is forwarded to the component as well, so\n `style="width:100%"` works. Style the host, not the component\'s internal\n classes.\n- Keep children simple. For `ryugi-button`, `ryugi-card`, `ryugi-text`,\n `ryugi-tag`, `ryugi-checkbox`, and `ryugi-badge`, the original children are\n moved into the component. `ryugi-select`, `ryugi-segmented`, and\n `ryugi-radio-group` use option children instead.\n- Do not invent a `ryugi-` tag. If a component is not listed here, use HTML.\n- `ryugi-card` already paints a surface. Do not put a background, border and\n padding on both the host and the card: pick one. For a floating panel,\n either position the host and let the card paint its own surface, or make the\n host the surface and use `variant="borderless"` without `glass`/`shadow`.\n- Components follow `prefers-color-scheme`. Set `<html data-theme="light">`\n or `data-theme="dark"` before the runtime loads to pin the whole page.\n Without an explicit theme, the runtime follows OS theme changes.\n Lobe tokens such as `--lobe-color-primary` can be overridden on the host or\n page.\n\n## Controls\n\n### Button\n\n```html\n<ryugi-button variant="primary" size="middle" icon="plus">Add</ryugi-button>\n<ryugi-button variant="outlined" loading>Working…</ryugi-button>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `size`\n(`small`, `middle`, `large`), `block`, `loading`, `disabled`, `shape`, `type`,\n`icon` (any Lucide kebab-case name; `refresh` and `trash` remain aliases).\nRun `node app/ryugi.cjs guide icons` for standalone icons and mapping the preview\'s\nactions to business icons when implementing the app.\n\nUses the native `click` event.\n\n### Action icon\n\n```html\n<ryugi-action-icon icon="settings" title="Settings" aria-label="Settings"></ryugi-action-icon>\n```\n\nAttributes: `icon` (same set as Button), `size`, `disabled`, `title`,\n`aria-label`. Uses the native `click` event.\n\n### Tooltip and popover\n\n```html\n<ryugi-tooltip content="Copy a private link" placement="top">\n <ryugi-icon name="copy" size="14"></ryugi-icon> Copy\n</ryugi-tooltip>\n<ryugi-popover id="sharing" content="Only people you invite can open this link.">\n Sharing details\n</ryugi-popover>\n```\n\nBoth provide a native button trigger; children are its label and decorative\nicons, not nested buttons or controls. `content` is plain text, `placement`\nsets the floating position. Tooltip opens on hover/focus; Popover opens on\nclick (`trigger="hover"` opts into hover). Tooltip also accepts `open` for\na controlled preview. Native trigger clicks still reach your handlers.\n\n### Action menu\n\n```html\n<ryugi-menu id="actions" label="More" icon="ellipsis">\n <ryugi-menu-item value="copy" icon="copy">Copy link</ryugi-menu-item>\n <ryugi-menu-item value="delete" icon="trash-2" disabled>Delete</ryugi-menu-item>\n</ryugi-menu>\n```\n\nAttributes: `label`, `icon`, `placement`, `disabled`. Items accept `value`,\n`icon`, `disabled`; their text is the label. Selecting an enabled item emits\n`ryugi-change` with its action in `event.detail.value`. Actions are not\nrestored as control values on reload.\n\n### Input\n\n```html\n<ryugi-input id="title" placeholder="Title" value="Ryugi" style="width:100%"></ryugi-input>\n```\n\nAttributes: `type`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`, `borderless`), `allowClear`, `placeholder`, `value`,\n`disabled`, `name`, `aria-label`.\n\n### Textarea\n\n```html\n<ryugi-textarea id="notes" rows="4" placeholder="Notes" style="width:100%"></ryugi-textarea>\n```\n\nAttributes: `rows`, `size`, `variant`, `placeholder`, `value`, `disabled`,\n`name`.\n\n### Number\n\n```html\n<ryugi-input-number id="count" value="12" min="0" max="100" step="1"></ryugi-input-number>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `precision`, `controls`, `size`,\n`variant`, `placeholder`, `disabled`.\n\n### Slider\n\n```html\n<ryugi-slider id="size" value="32" min="0" max="100" step="1"></ryugi-slider>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `disabled`.\n\n### Slider with number input\n\nThe most useful control for tuning an exact value.\n\n```html\n<ryugi-slider-input id="radius" value="8" min="0" max="32" step="1"></ryugi-slider-input>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `controls`, `size`, `variant`,\n`disabled`.\n\n### Switch\n\n```html\n<ryugi-switch id="dark" checked></ryugi-switch>\n```\n\nAttributes: `checked`, `loading`, `size`, `disabled`, `name`.\n\n### Checkbox\n\n```html\n<ryugi-checkbox id="compact">Compact</ryugi-checkbox>\n```\n\nAttributes: `checked`, `shape`, `size`, `disabled`, `name`. Children are the\nlabel.\n\n### Segmented\n\n```html\n<ryugi-segmented id="mode" value="grid">\n <ryugi-segment value="list">List</ryugi-segment>\n <ryugi-segment value="grid">Grid</ryugi-segment>\n <ryugi-segment value="masonry">Masonry</ryugi-segment>\n</ryugi-segmented>\n```\n\nAttributes: `value`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`), `block`, `glass`, `shadow`, `vertical`, `disabled`.\n\n### Select\n\n```html\n<ryugi-select id="layout" value="a" placeholder="Choose layout">\n <ryugi-option value="a">Sidebar</ryugi-option>\n <ryugi-option value="b">Top tabs</ryugi-option>\n <ryugi-option value="c">Bottom rail</ryugi-option>\n</ryugi-select>\n```\n\nAttributes: `value`, `placeholder`, `size`, `variant`, `allowClear`,\n`showSearch`, `loading`, `mode` (`multiple`, `tags`), `disabled`.\n\n### Radio group\n\n```html\n<ryugi-radio-group id="density" value="comfortable">\n <ryugi-radio value="compact">Compact</ryugi-radio>\n <ryugi-radio value="comfortable">Comfortable</ryugi-radio>\n <ryugi-radio value="spacious">Spacious</ryugi-radio>\n</ryugi-radio-group>\n```\n\nAttributes: `value`, `horizontal`, `gap`, `size`, `disabled`.\n\n### Colour picker\n\n```html\n<ryugi-color-picker id="accent" value="#c56473" trigger="field"></ryugi-color-picker>\n```\n\nAttributes: `value`, `alpha`, `defaultFormat` (`hex`, `rgb`, `hsl`),\n`trigger` (`swatch`, `field`, `chip`), `size`, `disabled`.\n\n## Display\n\n### Toast\n\nHTML artifacts can call the bundled Lobe UI toast API as `window.ryugiToast`.\nIf the page has no `ryugi-` UI controls, opt in with the meta tag. Wait for\n`ryugi-ui:ready` before calling it:\n\n```html\n<meta name="ryugi-ui" content="1" />\n<button id="save" type="button">Save</button>\n<script>\n document.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n document.getElementById(\'save\').addEventListener(\'click\', async () => {\n try {\n await saveDraft(); // the page\'s own operation\n window.ryugiToast.success({ id: \'save-result\', title: \'Saved\' });\n } catch {\n window.ryugiToast.error({\n id: \'save-result\',\n title: \'Save failed\',\n description: \'Try again.\',\n });\n }\n });\n },\n { once: true },\n );\n<\/script>\n```\n\nMethods: `success`, `error`, `info`, `warning`, `loading`. Each takes a string\nmessage or `{ title, description, id, duration }`. Text is rendered as text,\nnot HTML. A stable `id` refreshes the same notification instead of stacking\ncopies. The default duration is 5000ms; `duration: 0` stays until closed.\n`loading` stays until closed by default.\n\nCalls return a handle with `id` and `close()`. Use\n`window.ryugiToast.dismiss(id)` to close one, or `dismiss()` to close all.\nToasts appear at the bottom right and follow the page\'s theme. They are\ntransient: rewriting the page does not restore them. No `ryugi-toast` tag is\nneeded. Artboard pages do not load this UI runtime.\n\n### Tag\n\n```html\n<ryugi-tag variant="outlined">New</ryugi-tag>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`, `solid`), `size`,\n`shape` (`normal`, `round`), `color`, `closable`.\n\n### Alert\n\n```html\n<ryugi-alert\n type="info"\n title="Streaming"\n description="Pending boards draw as skeletons."\n></ryugi-alert>\n```\n\nAttributes: `type` (`success`, `info`, `warning`, `error`, `secondary`),\n`variant` (`soft`, `outlined`, `plain`), `title`, `description`, `showIcon`,\n`closable`. Text children are used as the title when `title` is absent.\n\n### Progress\n\n```html\n<ryugi-progress percent="64" size="small"></ryugi-progress>\n```\n\nAttributes: `percent`, `size`, `status`.\n\n### Badge\n\n```html\n<ryugi-badge count="3" status="processing"></ryugi-badge>\n<ryugi-badge count="3">\n <ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n</ryugi-badge>\n```\n\nAttributes: `count`, `dot`, `status`, `text`, `showZero`, `size`, `color`.\n\n### Avatar\n\n```html\n<ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n```\n\nAttributes: `src`, `alt`, `size`, `shape`.\n\n### Divider\n\n```html\n<ryugi-divider dashed></ryugi-divider>\n```\n\nAttributes: `orientation`, `dashed`.\n\n### Card\n\n```html\n<ryugi-card variant="outlined" shadow>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Supporting copy.</ryugi-text>\n</ryugi-card>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `shadow`,\n`glass`, `clickable`. Children are preserved, including nested components.\n`glass`, `shadow` and `variant` paint the inner Block surface, not the host.\nIf the host supplies the panel background and padding, omit `glass`/`shadow`\nand use `variant="borderless"` so there is only one visible container.\n\n### Text\n\n```html\n<ryugi-text type="secondary">Secondary body text</ryugi-text>\n<ryugi-text strong>Strong label</ryugi-text>\n<ryugi-text code>const x = 1</ryugi-text>\n```\n\nAttributes: `type` (`secondary`, `success`, `warning`, `danger`, `info`),\n`strong`, `code`, `italic`, `underline`, `delete`, `mark`, `align`, `weight`.\n\n## Complete tuning panel\n\n```html\n<ryugi-card>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Tune the reading column.</ryugi-text>\n\n <ryugi-slider-input id="measure" value="64" min="40" max="90" step="1"></ryugi-slider-input>\n\n <ryugi-segmented id="density" value="comfortable">\n <ryugi-segment value="compact">Compact</ryugi-segment>\n <ryugi-segment value="comfortable">Comfortable</ryugi-segment>\n <ryugi-segment value="spacious">Spacious</ryugi-segment>\n </ryugi-segmented>\n\n <ryugi-switch id="dark"></ryugi-switch>\n <ryugi-tag>Live preview</ryugi-tag>\n</ryugi-card>\n\n<script>\n document.addEventListener(\'ryugi-change\', (event) => {\n document.body.dataset[event.target.id] = event.detail.value;\n });\n<\/script>\n```\n\n## Not included in the first version\n\nTabs, Modal, Drawer, Table, DatePicker, and layout\ncomponents. Use plain HTML/CSS or a later component if one is added.\n',phoneScreens:!0};var y_='## Mockup components\n\n`<ryugi-ios-shell>` draws the device and nothing else: the screen (402×874, iPhone 17), status bar, Dynamic Island, home indicator and, with `bezel`, the frame (442×914). Size phone boards to match. Never hand-draw those parts. Three system controls are built in as well: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` draw the iOS switch, segmented control and slider, with the frosted knob that opens into clear glass while it is pressed, dragged or travelling; use them wherever the product shows one of these controls instead of drawing your own. Everything else on the screen (navigation bar, glass buttons, tab bar, cards, lists, inputs, sheets, a floating composer) is the product\'s own design system: write it by hand in HTML/CSS from the variables of `tokens.css`, in the product\'s own style, including its own Liquid Glass where the product uses it. Do not imitate iOS Settings rows unless the product\'s own screens look like that. The shell renders in light DOM, so selection, comments and the Inspector reach every part. The server loads it when the page contains the tag; for a shell created by script add `<meta name="ryugi-mockup" content="1">` and wait for `ryugi-mockup:ready` on `document`.\n\n```html\n<!doctype html>\n<html lang="zh">\n <head>\n <meta charset="utf-8" />\n <link rel="stylesheet" href="../tokens.css" />\n <style>\n html,\n body {\n margin: 0;\n }\n .nav {\n display: flex;\n align-items: center;\n justify-content: space-between;\n height: 44px;\n padding: 0 16px;\n }\n .mark {\n font: 700 26px/32px var(--font-display);\n color: var(--color-text);\n }\n .glass {\n display: flex;\n border-radius: 22px;\n background: var(--color-glass);\n backdrop-filter: blur(16px) saturate(1.8);\n color: var(--color-text);\n }\n .glass > * {\n display: grid;\n place-items: center;\n width: 44px;\n height: 44px;\n }\n .card {\n margin: 8px 16px;\n padding: 16px;\n border-radius: var(--radius-card);\n background: var(--color-surface);\n }\n </style>\n </head>\n <body>\n <ryugi-ios-shell>\n <div class="nav">\n <span class="mark">喵旅</span>\n <span class="glass">\n <span\n ><ryugi-icon symbol="person.crop.circle" name="circle-user" size="22"></ryugi-icon\n ></span>\n <span><ryugi-icon symbol="plus" name="plus" size="22"></ryugi-icon></span>\n </span>\n </div>\n <section class="card">…</section>\n </ryugi-ios-shell>\n </body>\n</html>\n```\n\nThe variable names in the example (`--font-display`, `--radius-card`, `--color-glass`) stand for roles; use the names the product\'s own `tokens.css` defines.\n\n| Element | Attributes | Children |\n| ------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `ryugi-ios-shell` | `bezel`, `time` (9:41), `hide="status island home all"` (any of them) | the screen content: it flows from below the status bar (`--safe-top`, 62px); absolutely positioned content measures from the screen\'s top edge. `--safe-bottom` is 34px. Both stay when parts are hidden |\n| `ryugi-token-sheet` | `appearance` to show one set only | one `<script type="application/json">` |\n\nAll of them take `appearance="light|dark"`, otherwise follow the nearest `[data-appearance]`, then the system. Unknown attribute values raise a runtime warning.\n\n### iOS controls\n\n```html\n<div class="row">\n <span>自动暂停</span>\n <ryugi-ios-switch id="auto-pause" checked></ryugi-ios-switch>\n</div>\n<ryugi-ios-segmented id="range" value="week" block>\n <ryugi-ios-segment value="day">日</ryugi-ios-segment>\n <ryugi-ios-segment value="week">周</ryugi-ios-segment>\n <ryugi-ios-segment value="month">月</ryugi-ios-segment>\n</ryugi-ios-segmented>\n<ryugi-ios-slider\n id="volume"\n label="播报音量"\n value="65"\n start-icon="volume-1"\n end-icon="volume-2"\n></ryugi-ios-slider>\n```\n\n| Element | Attributes | Events |\n| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |\n| `ryugi-ios-switch` | `checked`, `disabled`, `size="sm md lg"` (track 22, 28, 36px; md), `color`, `label` and `description` beside it, `label-side="left"` | `change`, `detail.checked` |\n| `ryugi-ios-segmented` | `value`, `size="sm md lg"` (28, 32, 40px; md), `block` to fill the width; children are `<ryugi-ios-segment value>`, whose content (text, a `ryugi-icon`) is the label | `change`, `detail.value` |\n| `ryugi-ios-slider` | `value`, `min`, `max`, `step` (0, 100, 1), `size="sm md lg xl"` (track 8, 12, 18, 26px; md), `color`, `label` above with the value unless `hide-value`, `start-icon` and `end-icon` (Lucide names) | `input` while dragging, `change` when it lands, `detail.value` |\n\nThey are interactive: a tap flips the switch, the knob drags, the segmented lens can be held and dragged to another option, the slider follows the pointer, and the keyboard works. Their state is reflected in the `checked` and `value` attributes, and setting those from a script moves the control. The on colour of the switch and the filled part of the slider read `--color-accent` unless `color` names one (`#34c759`). The track, the segmented background and the selected pill follow the appearance; labels read `--color-text` and `--color-text-secondary`.\n\nIcons: `<ryugi-icon name>` is a Lucide icon; find names with `adeck icons <english words>`. Add `symbol`, an SF Symbol name (`wallet.bifold.fill`): when the local server runs on macOS it draws the symbol through the system and shows it at the symbol\'s own proportions, tinted with `currentColor`; anywhere else (other systems, Artideck Cloud, published links) the Lucide icon shows. Write both. Use `symbol` only in mockups of apps for Apple platforms; that is the condition of Apple\'s license. Symbol images are never part of `pages/` and are never published.\n\nProduct tokens live in one stylesheet (on an artboard `pages/tokens.css`), light on `:root`, dark on `[data-appearance="dark"]`. The shell\'s root carries `data-appearance`, so light and dark phones sit side by side and your content under `[data-appearance="dark"]` flips with them. The shell reads `--color-bg` (screen), `--color-text` (status bar, home indicator) and `--font-body`, falling back to iOS system values; the token sheet also reads `--color-text-secondary`, `--color-separator`, `--color-surface`, `--color-fill` and `--color-accent`. Your content reads the same variables plus the product\'s own (radius, spacing, type, glass).\n\n`ryugi-token-sheet` draws the token table from JSON that names tokens, never values; values come from the stylesheet in both appearances:\n\n```json\n{\n "groups": [\n {\n "name": "Text",\n "kind": "color",\n "tokens": [\n {\n "name": "--color-text-secondary",\n "use": "行右侧的值",\n "on": "--color-surface",\n "board": "t-color-a"\n }\n ]\n },\n {\n "name": "Type",\n "kind": "type",\n "tokens": [{ "name": "--type-body", "use": "正文", "sample": "招商银行储蓄卡" }]\n }\n ]\n}\n```\n\nKinds: `color` (swatches; with `on`, WCAG contrast per appearance flagged under 4.5:1, or 3:1 with `"large": true`), `type` (a `font` shorthand), `space`, `radius`, `size`, `shadow`, `motion` (`<duration> <easing>`, click to play). Token and group names are English; `use` and `sample` follow the product\'s language. Missing variables and broken JSON show inline errors.\n',b_="## Phone mockups\n\nEvery phone screen is a `<ryugi-ios-shell>`: it draws the 402×874 screen, status bar, Dynamic Island and home indicator, and `bezel` adds the 442×914 frame. Never hand-draw those parts, nor a switch, segmented control or slider: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` are built in. Everything else on the screen is the product's own design from its `tokens.css`. Before the first phone screen or `<ryugi-token-sheet>`, read the mockup guide: `start --artifact <artifact> --help --mockup`.\n",x_='# Report writing\n\nA report is data and presentation kept apart. Each data source is a Node script that prints JSON; the report is `report.tsx`, one default-exported component built only from `@ryugi/report` that imports the data it draws.\n\n```\nreport/<id>/\n report.tsx\n sources/<source-id>/source.json\n sources/<source-id>/<script>.mjs\n data/<source-id>.json written by the hub when a source runs; never write it by hand\n assets/<file>.png images the report shows (png, jpg, gif, webp, avif, svg)\n```\n\n## Data sources\n\n`sources/<source-id>/source.json`: `{ "title": "Commits per day", "description": "main branch, last 30 days", "input": "git history of the repo", "script": "collect.mjs", "args": ["--days", "30"] }`. `title` and `script` are required; the script is a `.mjs`, `.js` or `.cjs` file in the same folder. Source ids are kebab-case.\n\nThe script runs with the project root as cwd and Node from the hub, so it can use the project\'s `node_modules`. Its env is the hub\'s env with the project\'s `.env` and `.env.local` laid over it; read secrets and machine paths from env or `args`, never write them into the script. It must print one JSON value on stdout (at most 2 MB; the whole report\'s data at most 10 MB) and exit 0 within 60 s. Do the aggregation in the script: the report only draws. A stderr line `ryugi:input <text>` replaces the input shown in the panel for that run, such as the commit the data was read at; other stderr is shown when the run fails.\n\nRun sources with `ryugi report refresh --artifact report/<id>` (all) or with `--only <source-id>` (one). The hub runs them, one run per source at a time, and writes `data/<source-id>.json`. Refresh after adding or changing a source, and before `check`. Reports fetched from someone else\'s Cloud link are read-only: never run their scripts.\n\n## report.tsx\n\n```tsx\nimport {\n BarChart,\n Grid,\n Report,\n Section,\n Stat,\n Table,\n useMemo,\n useState,\n Param,\n} from \'@ryugi/report\';\nimport days from \'./data/commits-per-day.json\';\n\nexport default function Commits() {\n const [span, setSpan] = useState(14);\n const shown = useMemo(() => days.slice(-span), [span]);\n return (\n <Report title="Ryugi commits" caption="main branch">\n <Param label="Window" min={7} max={30} unit="days" value={span} onChange={setSpan} />\n <Grid columns={3}>\n <Stat\n id="total"\n source="commits-per-day"\n title="Commits"\n value={shown.reduce((sum, day) => sum + day.commits, 0)}\n />\n </Grid>\n <Section id="daily" title="Per day">\n <BarChart\n id="per-day"\n source="commits-per-day"\n title="Commits per day"\n data={shown}\n x="date"\n series={[{ key: \'commits\', label: \'Commits\' }]}\n />\n <Table\n id="days"\n source="commits-per-day"\n title="Days"\n rows={shown}\n rowKey="date"\n columns={[{ key: \'date\' }, { key: \'commits\', align: \'right\' }]}\n />\n </Section>\n </Report>\n );\n}\n```\n\nImports come only from `@ryugi/report` and `./data/<source-id>.json` (default import; the source must exist). JSX uses SDK components only: no `div`, `img`, `a` or other native elements, no network calls, `document` / `window` / `location` / `navigator` / storage access, `globalThis`, `eval`, `Function`, `.constructor`, `import()` / `require()` or timers. Words in text and strings are fine; the check reads code. The page cannot reach the network either way. `report.tsx` stays under 64 KB; put data in a source. Derive with `useMemo` and plain expressions; keep state in `useState`.\n\nEvery Stat, chart, Table, Callout, Image and Section needs an `id`: kebab-case, unique in the report, and stable across edits, since comments and references hold on to it. Stat, charts and Table also need `source`: the source id, or a list of them, that the block\'s numbers come from; the hover chip and the sources panel read it. Write `id`, `source` and `title` as string literals.\n\nComponents:\n\n- `Report` `{ title, caption? }`: the root; `title` is the artifact\'s title.\n- `Section` `{ id?, title? }`, `Grid` `{ columns?: 1 | 2 | 3 | 4 }`, `Card`, `Stack` `{ gap? }`, `Divider`.\n- `H2`, `H3`, `Text` `{ tone?: \'muted\' }`, `List` `{ items }`, `Callout` `{ id, title?, tone?: \'info\' | \'success\' | \'warning\' | \'error\' }`.\n- `Stat` `{ id, source, title, value, unit?, delta?, format?, note? }`; `delta` is signed and shown up or down.\n- `Table` `{ id, source, title?, rows, rowKey, columns: { key, label?, align?, format? }[] }`; every row prints; a click on a row starts a comment on it.\n- `LineChart`, `BarChart`, `AreaChart`, `PieChart`, `ScatterChart` `{ id, source, title, data, x, series: { key, label?, color? }[], subtitle?, stacked?, donut?, highlight?, refs?: { label, y }[], format?, note? }`: the same chart renderer as a document\'s chart block. A `ScatterChart` needs a numeric `x` in every row. A reader clicks a point to pin it and comments on that point.\n- `Param` `{ label, value, onChange, min?, max?, step?, unit? }` (a slider with a number field when min and max are set), `Select` `{ label?, value, options, onChange }`, `Toggle` `{ label, checked, onChange }`. Printed, they show the value the reader set; a comment on a point or row records them too.\n- `Image` `{ id, src, alt, caption?, width? }`: an image file from the report folder, `src` written as a string such as `"assets/sources-panel.png"`; `alt` describes it. Copy screenshots and figures into `assets/` first; remote URLs are not allowed. Comments anchor to the image as a block.\n- `useState`, `useMemo` from `@ryugi/report`.\n\n`format` is `{ unit?, decimals?, compact?, signed? }`.\n\n## Check, comments, references\n\n`adeck check --artifact report/<id>` reports static issues (imports, native elements, missing or repeated ids, unknown sources, missing data files) and, once a browser has opened the report, render errors.\n\nComments anchor to a block, a table row or a chart point: `adeck comment add --artifact report/<id> --block <block-id> [--point <series>:<x> | --row <rowKey>]`. A comment keeps the value it was made on and which data it saw; after a refresh changes that data it is marked data changed and stays where it was.\n\nReference a report from a document with `<ref report="<id>"/>`, or one block with `<ref report="<id>" block="<block-id>"/>`. A deck names it inline with the same `<ref>`, and shows one block on a slide with `<embed report="<id>" block="<block-id>"/>`; give the blocks a deck shows a stable `id`.\n\nPublishing includes `report.tsx`, `sources/**`, `data/**` and the images under `assets/` with the report\'s visibility. Publishing is refused while a script, `report.tsx` or the data holds an absolute machine path (`/Users/…`, `/home/…`, `C:\\\\…`, not checked in data) or something that looks like a secret (`sk-…`, `ghp_…`, `AKIA…`, a private key, a value from `.env`); the refusal names the file and line.\n';function S_(e){if(!e.block)throw new M(`comment add on a report needs --block <blockId>`);if(e.point!==void 0&&e.row!==void 0)throw new M(`comment add takes --point or --row, not both`);let t;if(e.point!==void 0){let n=e.point.indexOf(`:`);if(n<=0||n===e.point.length-1)throw new M(`--point needs <series>:<x>, such as commits:Nov 2`);t={series:e.point.slice(0,n),x:e.point.slice(n+1)}}return{op:`add`,block:e.block,...t?{point:t}:{},...e.row===void 0?{}:{row:e.row},text:$n(e)}}const C_={authoring:x_,review:{sections:[]},commentActions:{add:S_}};var w_='# Slides writing\n\nWrite one complete `deck.xml` under the returned artifact directory; put images in `assets/` and reference them with relative paths. The deck is for an audience: your human partner presents it. Re-read before each edit; never edit `comments.json` or `.state/`. Finish with `check`.\n\nThe file holds what the slides say. The server compiles it into the page and adds the presentation engine, theme, code highlighting, diagrams and formulas. Only the tags and attributes below exist: there is no `class` and no `style`, and `check` reports anything else by slide and tag.\n\n```xml\n<deck title="Retry policy" lang="en">\n <slide id="cover" layout="cover">\n <kicker>Delivery · Q3</kicker>\n <h1>Retry policy</h1>\n <subtitle>Why failed deliveries now retry three times</subtitle>\n <notes>Open with last month\'s incident.</notes>\n </slide>\n\n <slide id="what-changes">\n <h2>What changes</h2>\n <ol steps="true">\n <li>At most three attempts</li>\n <li>Exponential backoff</li>\n </ol>\n </slide>\n\n <slide id="backoff" layout="code">\n <h2>Backoff</h2>\n <codeblock lang="ts" lines="1|2-3"><![CDATA[\n const delay = (attempt: number) =>\n Math.min(30_000,\n 500 * 2 ** attempt);\n ]]></codeblock>\n </slide>\n</deck>\n```\n\n## Slides\n\n- One slide is one `<slide>` directly inside `<deck>`. The deck\'s `title` is required; `lang` is optional.\n- Every slide needs a unique, stable `id` of lowercase letters, digits and hyphens. Comments and document references find a slide by its id: keep the id when you rewrite a slide, and only change it when the slide becomes a different slide. Deleting a slide orphans its comments.\n- The canvas is fixed at 1280×720. Content that leaves that box is reported by `check` as overflow, naming the slide. Fix it by cutting or splitting the slide; `zoom="0.8"` on the slide (0.3 to 1) is for the one dense slide that must stay whole.\n- While the deck is open in the viewer, `check` also names contact sheet images (`Sheet:`) that show every slide at its last step, twelve to an image, with overflowing and hidden slides marked. After editing, run `check`, open those images, and look for slides that are too full or that all look like the same template. `sheet_not_drawn` under `Pending` means the open viewer has not drawn this version yet. `Sheet: unavailable (…)` means it cannot be drawn, as for a deck holding a video or an iframe: go on without it.\n- `hidden="true"` keeps a slide in the file and out of the talk: it shows, marked, only while the deck is worked on; presenting, the audience window, the PDF and a published link never get it, and it takes no page number.\n- `<group id="evidence" title="What the data says">` inside `<deck>` gathers the slides of one part of the talk. It holds only `<slide>` and `<include>`, never another group; its `id` follows the slide id rules and is unique among slides and groups, and `title` is required. The grid view shows each group as a titled row; the audience sees nothing of it. Slides outside any group are fine, before, between or after groups.\n- `cover="<slide id>"` on `<deck>` names the slide that stands for the deck in lists and links. `check` warns when it names a slide that is missing or hidden.\n- Write XML: close every tag, quote every attribute, write `&lt;` and `&amp;` in text; common names such as `&nbsp;`, `&mdash;` and `&rarr;` work, any other is an error, so write the character itself. Code, diagrams and formulas go in `<![CDATA[ … ]]>` so nothing in them needs escaping. CDATA ends at the first `]]>`: code that contains `]]>` comes from a file with `src`. End the file with `</deck>`.\n\n## Layouts\n\nPick the layout that fits what the slide says, and vary them: a deck of identical title-and-bullets slides reads as a template. Each layout adds a few places of its own; a place used in another layout is reported. The theme adds the page number itself.\n\n| `layout` | Use it for | Inside the slide |\n| ----------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------- |\n| `default` | A title with text, a list, a table or code | Optional `<label>`, an `<h2>`, then blocks. Omitting `layout` gives this one |\n| `cover` | The first slide | `<kicker>`, `<h1>`, `<subtitle>` |\n| `section` | The start of a new part | Optional `<label>`, then an `<h1>` or `<h2>` |\n| `statement` | One sentence the audience should remember | Optional `<label>`, an `<h2>` with the key words in `<mark>`, optional `<subtitle>` |\n| `two-cols` | Two things side by side | An `<h2>`, then exactly two `<col>`, each holding blocks |\n| `image` | Text beside a picture | One `<col>` holding the text and one `<img>`; whichever comes first is on the left |\n| `quote` | A quotation | `<quote>` and `<cite>` |\n| `fact` | One number that matters | `<big value="10–12" unit="working days"/>`, then up to three `<fact value="5 days" label="API"/>` |\n| `code` | Code as the subject of the slide | Optional `<label>`, an `<h2>` and one `<codeblock>` or one `<magic>` |\n| `end` | The last slide | An `<h1>` |\n| `none` | A slide you lay out yourself | `src` naming an HTML file; see Free HTML. No padding and no page number |\n\n```xml\n<slide id="numbers" layout="fact">\n <big value="13" unit="harnesses supported"/>\n <fact value="5" label="artifact types"/>\n <fact value="0" label="subscriptions"/>\n</slide>\n<slide id="before-after" layout="two-cols">\n <h2>Before and after</h2>\n <col>\n <h3>Before</h3>\n <p>One attempt, then a page.</p>\n </col>\n <col>\n <h3>After</h3>\n <p>Three attempts, then a page.</p>\n </col>\n</slide>\n<slide id="dashboard" layout="image">\n <col>\n <label>Result</label>\n <h2>Failures fell by half</h2>\n </col>\n <img src="assets/dashboard.png" alt="Failure rate before and after the change" frame="true"/>\n</slide>\n```\n\n## Blocks and text\n\nBlocks sit in a slide or a `<col>`: `<h1>`, `<h2>`, `<h3>`, `<p>`, `<ul>` and `<ol>` of `<li>` (a list may nest in an item), `<table>` of `<tr>` holding `<th>` or `<td>`, `<blockquote>`, `<hr/>`, `<alert type="note|tip|important|warning|caution">` holding blocks, `<img>`, `<icon>`, `<codeblock>`, `<magic>`, `<mermaid>`, `<math>`, `<html>`, `<embed>` and `<notes>`.\n\nBlocks and inline tags a document also has carry the same names here. Inside text: `<b>`/`<strong>`, `<i>`/`<em>`, `<u>`, `<s>`/`<del>`, `<sub>`, `<sup>`, `<code>`, `<mark>`, `<a href="…">`, `<br/>`, `<math>`, `<icon>` and `<ref>`.\n\n- `<img src="assets/chart.png" alt="…"/>` shows a file of the artifact directory. `frame="true"` gives a screenshot rounded corners and a shadow.\n- `<icon name="check" size="32"/>` draws an icon; `size` is in pixels.\n- `<mermaid>` holds a Mermaid diagram and `<math>` a LaTeX formula, both in CDATA. `<math>` inside text is an inline formula.\n- `<notes>` holds speaker notes, shown only to the presenter. One per slide, plain text with `<br/>` between lines.\n\n```xml\n<h2>How a delivery flows</h2>\n<mermaid><![CDATA[\n flowchart LR\n A["ingress<br/>edge"] --> B[queue] --> C[worker]\n]]></mermaid>\n<table>\n <tr><th>Attempt</th><th>Delay</th></tr>\n <tr><td>1</td><td><math>500 \\cdot 2^1</math> ms</td></tr>\n</table>\n<p><icon name="check" size="24"/> Shipped behind a flag, see <a href="https://example.com/rfc">the RFC</a>.</p>\n```\n\n## Code\n\n`<codeblock lang="ts">` is a code block, named as in a document; `<code>` is inline code inside text. Write the code in CDATA; the indentation it shares with the XML is taken off.\n\n- `lines`: stepped line highlight. Parts are separated by `|`, each one step, lines count from 1: `1`, `2-3`, `2-3,5`; `all` lights every line and `hide` hides the block for that step.\n- `src="src/retry.ts#L10-24"`: take the code from a file of the project instead of writing it, optionally only those lines. The path is relative to the project root; files outside the project, dot-files such as `.env`, and files over 512 KB are refused, and so are files named like secrets (`secrets.*`, `credentials.*`, `*.pem`, `*.key`, `*.tfstate`, `*.tfvars`, SSH keys) and files git ignores. Never show a file that holds a secret under another name. What a deck shows is published with it.\n- `numbers="true"`: line numbers. `title="src/retry.ts"`: a title above the block. `max-height="320"`: a height in pixels past which the block scrolls, following the highlighted lines. `diff="true"`: lines starting with `+` or `-` are drawn as added or removed.\n- `<magic lang="ts">` holds two or more `<step>`, each the whole code at one step, in CDATA; what stays moves into place, and each step after the first is a step of the slide.\n\n```xml\n<codeblock lang="ts" src="src/retry.ts#L10-24" numbers="true" title="src/retry.ts" lines="all|3-5"/>\n<codeblock lang="ts" diff="true"><![CDATA[\n const attempts =\n - 1;\n + 3;\n]]></codeblock>\n<magic lang="ts">\n <step><![CDATA[const delay = 500;]]></step>\n <step><![CDATA[const delay = (attempt: number) => 500 * 2 ** attempt;]]></step>\n</magic>\n```\n\n## Steps and marks\n\n- `step="true"` on a block or a list item: it appears on the next step. `steps="true"` on a `<ul>`, `<ol>`, `<table>` or `<col>` makes each item, row or block a step.\n- `step="2"` places a step by number, and `step="with"` makes it appear together with the step before it.\n- `<mark>` highlights words. `type="highlight"`, `underline`, `circle` or `strike` draws that mark; with `step` the words are there from the start and the mark is drawn on its step.\n- `morph="title"` on a block in two consecutive slides moves it from one to the other; a name is used once per slide and the pair should hold the same text.\n\n```xml\n<h2 morph="title">The <mark type="underline" step="true">retry budget</mark> is per delivery</h2>\n<p step="true">Three attempts in total.</p>\n<p step="with">The first one counts.</p>\n<ul steps="true">\n <li>500 ms</li>\n <li>1 s</li>\n</ul>\n```\n\n## Several files and free HTML\n\n- `<include src="parts/appendix.xml"/>` inside `<deck>` puts the slides of another file of the artifact directory there. That file starts with `<slides>`, holds only `<slide>`, and cannot include further files. Ids stay unique across all files.\n- `<html src="parts/demo.html"/>` is a block of HTML you write yourself, in a file of the artifact directory.\n- `<slide id="demo" layout="none" src="parts/demo.html"/>` is a whole slide of your own HTML: you own every pixel of 1280×720. It may hold `<notes>` and nothing else.\n- A free HTML file is a fragment: no page wrapper, every `<div>` closed. `data-step` on an element inside it makes that element a step. It runs in the deck\'s sandbox: no localStorage, sessionStorage or cookies.\n\n```xml\n<deck title="Retry policy">\n <slide id="live-demo" layout="none" src="parts/demo.html">\n <notes>Click through the three states.</notes>\n </slide>\n <slide id="curve">\n <h2>The backoff curve</h2>\n <html src="parts/curve.html"/>\n </slide>\n <include src="parts/appendix.xml"/>\n</deck>\n```\n\n## Other artifacts\n\n`<embed>` puts another artifact of this project on the slide. Name the target by its slug, as a document\'s `<ref>` does:\n\n- `<embed artboard="settings-page" board="q1-b"/>` shows one board of an artboard, in a box of the board\'s shape.\n- `<embed whiteboard="sync-flow" frame="f1"/>` shows one frame of a whiteboard; `page="<page id>"` instead of `frame` shows a whole page. The box takes the shape of the frame or of what is drawn on the page.\n- `<embed report="q3-revenue" block="by-month"/>` shows one block of a report at the slide\'s width and at the block\'s own height, in the deck\'s light or dark.\n- `<embed slides="launch" slide="pricing"/>` shows one slide of another deck at 1280×720, at its last step, in that deck\'s own theme. Embeds on that slide hold their place under their names: decks nest one level.\n- `<embed html="spring-curve"/>` shows an html page, at 1280×720.\n\nAn embed is live: it shows the target as it is now, changes when the target does, and can be scrolled and clicked during the talk. Its corner button opens the target nearly full screen at the embedded part, and Esc closes it. In thumbnails, PNG and PDF export and the contact sheet every embed is a picture of the target.\n\n`<ref>` names another artifact inside text, as a chip: `<ref document="retry-policy">the design</ref>`, `<ref report="q3-revenue" block="by-month"/>`, `<ref whiteboard="sync-flow" frame="f1"/>`. Every kind a document can reference can be named, with the same attributes; with no text of its own the chip shows the target\'s title. Clicking it opens the target nearly full screen; nothing opens while the slide is edited or the pen or laser is on.\n\nPublished, a deck shows the published versions of what it embeds and names. A target that is private, unpublished or gone shows to visitors as its chip text or as an unpublished artifact, never its title or a picture of it; its owner sees it. Publishing the deck offers what it embeds and names to publish with it.\n\nAn embed takes `step` and `morph` like any block. `check` warns, naming the slide, when the artifact or the part it names (board, frame, page, block, slide) is not there, and the slide shows the target\'s name in its place. A `<ref>` to a missing target is warned about the same way.\n\n```xml\n<slide id="settings" layout="two-cols">\n <h2>The settings page</h2>\n <col>\n <p>Option B keeps billing on the first screen.</p>\n </col>\n <col>\n <embed artboard="settings-page" board="q1-b"/>\n </col>\n</slide>\n```\n\n## Theme, motion and glow\n\nChange the look for the whole deck with one `<theme>` before the first slide. `name` picks the theme: `paper` (the default: warm paper, one seal-coloured accent, glow) or `mono` (black on white, monospace labels, emphasis by weight, no glow). `appearance` is `light`, `dark` or `auto`; `auto`, the default, follows the system of whoever opens the deck and prints light, so write `light` or `dark` when the room decides. Every other attribute overrides one variable of the theme, in both appearances. A deck that sets its own `paper`, `surface` or `ink` is `light` unless it names an appearance: those colours suit one appearance only. Do not restyle slide by slide.\n\n```xml\n<deck title="Retry policy">\n <theme name="paper" appearance="dark" accent="#0a7cff" transition="slide-left" fragment="rise" glow-opacity="0.6"/>\n <slide id="cover" layout="cover" transition="fade" glow="top-right" glow-seed="launch">\n <h1>Retry policy</h1>\n </slide>\n</deck>\n```\n\n| `<theme>` attribute | Values | Paper |\n| ----------------------------- | ------------------------------------------------------------ | ------------------------------- |\n| `paper`, `surface` | the slide\'s background, and that of code and cards | |\n| `ink`, `ink-2`, `ink-3` | text, secondary text, labels | |\n| `accent`, `on-accent`, `info` | the accent colour, text on it, and the second accent | |\n| `rule`, `rule-strong` | hairlines | |\n| `font`, `font-mono` | font families | |\n| `transition` | `view`, `fade-out`, `fade`, `slide-left`, `slide-up`, `none` | `view` |\n| `transition-duration` | a time | `500ms` |\n| `transition-blur` | a length | `5px` |\n| `fragment` | `blur`, `fade`, `rise` | `blur` |\n| `fragment-duration` | a time | `500ms` |\n| `fragment-blur` | a length | `3px` |\n| `glow` | `on`, `off` | `on` |\n| `glow-1`, `glow-2`, `glow-3` | colours of the three shapes | `#9440e3`, `#41d1ff`, `#dce354` |\n| `glow-fade` | the colour each shape fades to | `rgb(255 255 255 / 0.1)` |\n| `glow-opacity` | 0 to 1 | `1` |\n| `glow-blur` | a length | `70px` |\n| `glow-drift` | how long the glow takes to move to the next slide\'s place | `2500ms` |\n| `glow-hue` | an angle | `0deg` |\n| `glow-at` | a glow place | `full` |\n\nTransitions:\n\n- `view`: the slide fades out, then the next fades in, both blurred; blocks with the same `morph` on both slides move and resize between them.\n- `fade-out`: the same fade out then in, without moving blocks.\n- `fade`: both slides cross-fade.\n- `slide-left`, `slide-up`: the next slide pushes in from the right or from below; going back reverses it.\n- `none`: the slide changes at once.\n\nSteps: `blur` fades a step in from a blur, `rise` also lifts it 12px, `fade` only fades it.\n\nOn a `<slide>`:\n\n- `transition`: the transition into this slide, one of the values above.\n- `glow`: where this slide\'s glow sits: `full`, `top`, `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`, or `none` for no glow. Left out, the place follows the layout and changes from slide to slide.\n- `glow-seed`: any text; the same seed on the same page number always gives the same shapes.\n- `glow-opacity`: 0 to 1, this slide only.\n- `glow-hue`: degrees, this slide only.\n\n`check` reports an unknown transition or glow place and a `morph` name used twice in one slide. With reduced motion, turns are instant and the glow does not move.\n\n## Placing blocks freely\n\nA layout arranges a slide for you. When a slide must sit exactly as drawn, put `free="true"` on it: every block it holds, inside a `<col>` too, then takes `x`, `y` and `w` in slide pixels of the 1280×720 canvas, and `h` when its height matters (pictures, embeds, diagrams). The layout stays named, so its type sizes still apply, and removing `free` with the coordinates brings the layout back. A block on a free slide without `x`, `y` and `w` is reported, and so are coordinates on a slide that is not free. Later blocks sit on top of earlier ones.\n\n```xml\n<slide id="library" layout="two-cols" free="true">\n <h2 id="b4k2qz" x="96" y="80" w="520">The library</h2>\n <col>\n <p x="96" y="180" w="420" align="center" color="muted">Every artifact, one server.</p>\n </col>\n <col>\n <img x="640" y="120" w="560" h="380" src="assets/library.png" alt="The library page" frame="true"/>\n </col>\n</slide>\n```\n\n- `align="left|center|right|justify"` and `color` work on text blocks on any slide. `color` takes a theme colour, `ink|muted|faint|accent|info`, which follows the theme and its light and dark appearances, or a fixed `#RRGGBB` / `#RRGGBBAA`, which does not. Prefer the theme colours.\n- On a free slide, `w="fill"` stretches a block from its `x` to the right safe margin, and a text block may take `h`: what does not fit is clipped, unless the block also has `fit="shrink"`, which shrinks its text until it fits.\n\n### Look attributes\n\nYour human partner tunes blocks in the viewer\'s tweak panel. Each setting is one attribute on the block, on any slide; `check` reports a value outside its range and an attribute on a block that does not take it.\n\n| Attribute | Blocks | Value |\n| --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- |\n| `size="32"` | text | font size, 8–400 px |\n| `weight="600"` | text | 100–900 in steps of 100 |\n| `font="Avenir Next"` | text | `mono` or a font name; a font missing on another machine falls back to the theme font |\n| `leading="1.4"` | text | line height, 0.8–3 |\n| `tracking="-0.5"` | text | letter spacing, -20–100 px |\n| `pad="16"` | text, table, codeblock, code, alert, big, fact | padding, 0–200 px |\n| `fill="surface"` | all but hr, icon and html | a theme colour (`surface`, `paper`, `ink`, `muted`, `faint`, `accent`, `info`) or hex |\n| `opacity="80"` | all but html | 0–100 |\n| `radius="12"` | all but hr, icon and html | 0–360 px |\n| `border="solid"` | all but hr, icon and html | `solid`, `dashed` or `dotted`, 1 px in the theme\'s rule colour |\n| `shadow="0 8 24 #00000040"` | all but hr, icon and html | x, y, blur in px and a colour |\n\n```xml\n<slide id="promise" free="true">\n <p x="96" y="180" w="fill" h="120" fit="shrink" size="32" weight="600" fill="surface" radius="12" pad="16">Every artifact, one server.</p>\n</slide>\n```\n\nThese are deliberate choices: keep these attributes when you rewrite a block, unless changing them is the point.\n\n- An `id` on a block (letters, digits, `_` and `-`, at most 32) is how the viewer and comments know that block again. Your human partner\'s edits give blocks ids: keep every block id when you rewrite a slide, as you keep slide ids.\n\n## Rules\n\n- A talk is given offline: keep fonts, scripts and images inside the artifact directory and avoid CDNs.\n- Notes are not secret: they are hidden from viewers in the interface but remain in the page source.\n- Your human partner can edit notes in the viewer. Saving writes that slide\'s `<notes>` back as plain text lines joined by `<br/>`, replacing any markup inside it, in the file the slide is written in.\n- Keep the whole artifact under 20 MB.\n- Your human partner can edit slides in the viewer: select blocks, drag and resize them (which makes a slide `free="true"`), type into them, change their tag, alignment, colour and every look attribute, restack blocks, change a slide\'s layout, add text boxes, copy, paste and delete. Each edit rewrites the slide in `deck.xml` or its include file in place and is listed by `changes`. Re-read the file before every edit. When you write over one of their edits before you have read it, `check` warns with `W_HUMAN_EDIT_OVERWRITTEN`, naming the slide, the block and what they had set: put their edit back unless you meant to change it.\n- Your human partner can restructure the deck in the viewer\'s grid: reorder and duplicate slides, skip them, add placeholder slides, delete them, and create, rename or move groups. Each change rewrites `deck.xml` (and an include file, for a slide written there) in place, keeping the rest of the text as it was. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact slides/<id>` and read them before editing the deck, so you build on their order instead of writing it back.\n\n## Feedback\n\nComments are anchored to a slide, usually to a point on it. `comment list --sections threads --detail` shows the slide id, its title, the text under the pin and the message. A comment made on selected blocks lists them as `nodes`, each with its block (`#id`, or its position on the slide) and its text: change those blocks. Edit that slide, keep its id, run `check`, then reply with what changed. A comment whose slide was deleted is listed as an orphan.\n\nRun the returned Check command after every edit. Without a browser it reports XML that does not parse, tags, attributes and values the deck cannot take, files it cannot read, missing or duplicate ids, unknown layouts, missing assets and embeds whose target is not there, each naming its slide. Slides that overflow and code, diagram or formula errors come from the browser: with no browser open the result is pending, not clean.\n';const T_=[`default`,`cover`,`section`,`statement`,`two-cols`,`image`,`quote`,`fact`,`code`,`end`,`none`],E_=/^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/,D_=e=>{let t=e.trim();return t===`all`||t===`hide`?t:null};function O_(e){let t=[];for(let n of e.split(`|`)){let e=D_(n);if(e){t.push(e);continue}let r=/* @__PURE__ */ new Set;for(let e of n.split(`,`)){let t=E_.exec(e);if(!t)continue;let n=Number(t[1]),i=t[2]===void 0?n:Number(t[2]),a=Math.max(n,i);for(let e=Math.max(1,Math.min(n,i));e<=a&&!(r.size>=2e3);e++)r.add(e)}r.size&&t.push([...r].sort((e,t)=>e-t))}return t}const k_=e=>e.split(`|`).every(e=>D_(e)!==null||e.split(`,`).every(e=>{let t=E_.exec(e);return t!==null&&Number(t[1])>=1&&Number(t[2]??1)>=1})),A_=[`view`,`fade-out`,`fade`,`slide-left`,`slide-up`,`none`],j_=[`full`,`top`,`bottom`,`left`,`right`,`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`,`none`],M_=e=>A_.includes(e),N_=e=>j_.includes(e),P_=/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i;function F_(e){let t=e?.trim();return!t||P_.test(t)?null:t.split(/[?#]/)[0]||null}const I_=/^[a-z0-9][a-z0-9-]*$/,L_=`((?:"[^"]*"|'[^']*'|[^'">])*)`,R_=RegExp(`<!--[\\s\\S]*?(?:-->|$)|<(script|style|textarea|template|title)\\b${L_}>([\\s\\S]*?)(?:<\\/\\1\\s*>|$)|<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)${L_}>`,`gi`),z_=/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,B_=/reveal(?:\.min)?(?:\.esm)?\.m?js(?:[?#]|$)/i,V_={lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,amp:`&`};function H_(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(z_)){let e=n[1].toLowerCase();t.has(e)||t.set(e,n[2]??n[3]??n[4]??``)}return t}function U_(e){return e.replaceAll(/<[^>]*>/g,``).replaceAll(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi,(e,t,n,r)=>t?String.fromCodePoint(Number(t)):n?String.fromCodePoint(Number.parseInt(n,16)):V_[String(r).toLowerCase()]??e).replaceAll(/\s+/g,` `).trim().slice(0,200)}function W_(e){let t=e.toLowerCase(),n=[],r=[],i=null,a=null,o=!1,s=!1,c=0,l=/* @__PURE__ */ new Set,u=e=>{let t=F_(e);t&&l.add(t)},d=e=>{for(let t=n.length-1;t>=0;t--)if(n[t].tag===e){for(let e of n.splice(t))e.kind===`slide`&&(i=null),e.kind===`notes`&&--c;return}};R_.lastIndex=0;for(let l=R_.exec(e);l;l=R_.exec(e)){let[,f,p=``,m=``,h,g,_=``]=l;if(f){let e=f.toLowerCase();e===`title`&&!i&&a===null&&(a=U_(m)||null);let t=e===`script`?H_(p).get(`src`):void 0;u(t),e===`script`&&(B_.test(t??``)||m.includes(`Reveal.initialize`))&&(s=!0);let r=n.at(-1);e===`template`&&i&&!c&&r?.kind===`magic`&&(r.templates=(r.templates??0)+1,r.templates>1&&(i.steps+=1));continue}if(!g)continue;let v=g.toLowerCase();if(h){(v===`div`||v===`section`||v===`aside`)&&d(v);continue}let y=H_(_);u(y.get(`src`)),v===`link`&&u(y.get(`href`));let b=(y.get(`class`)??``).split(/\s+/).filter(Boolean),x=n.at(-1)?.kind;if(i&&!c){let n=y.get(`data-morph`)?.trim();if(n&&(i.morphs.has(n)&&!i.morphRepeats.includes(n)&&i.morphRepeats.push(n),i.morphs.add(n)),b.includes(`fragment`)){let e=y.get(`data-fragment-index`);e!==void 0&&i.positions.has(e)||(i.steps+=1),e!==void 0&&i.positions.add(e)}if(v===`code`&&(i.steps+=Math.max(0,O_(y.get(`data-lines`)??``).length-1)),!i.titled&&/^h[1-3]$/.test(v)){let n=t.indexOf(`</${v}`,R_.lastIndex);i.title=U_(e.slice(R_.lastIndex,n===-1?void 0:n)),i.titled=!0}}if(v===`div`){let e=`other`;!o&&x===`reveal`&&b.includes(`slides`)?(e=`slides`,o=!0):!o&&b.includes(`reveal`)?e=`reveal`:i&&b.includes(`magic-move`)&&(e=`magic`),n.push({tag:v,kind:e})}else if(v===`section`){if(x===`slides`){let e=b.find(e=>e.startsWith(`l-`)),t=e?e.slice(2):`default`;i={id:y.get(`id`)||null,layout:t,title:``,steps:0,notes:!1,nested:!1,titled:!1,unknownLayout:T_.includes(t)?null:t,transition:y.get(`data-transition`)?.trim()??null,glow:y.get(`data-glow`)?.trim()??null,morphs:/* @__PURE__ */ new Set,morphRepeats:[],positions:/* @__PURE__ */ new Set,...y.has(`data-deck-hidden`)?{hidden:!0}:{},...y.get(`data-deck-group`)?{group:y.get(`data-deck-group`)}:{}},r.push(i),n.push({tag:v,kind:`slide`})}else i&&(i.nested=!0),n.push({tag:v,kind:`other`})}else if(v===`aside`){let e=i!==null&&b.includes(`notes`);e&&(i.notes=!0,c+=1),n.push({tag:v,kind:e?`notes`:`other`})}}let f=[],p=/* @__PURE__ */ new Set,m=r.map(({nested:e,titled:t,unknownLayout:n,transition:r,glow:i,morphs:a,morphRepeats:o,positions:s,...c},l)=>{let u=c.id??void 0;c.id?I_.test(c.id)?p.has(c.id)&&f.push({code:`duplicate_id`,slide:l,id:u}):f.push({code:`invalid_id`,slide:l,id:u}):f.push({code:`missing_id`,slide:l}),c.id&&p.add(c.id),e&&f.push({code:`nested_slide`,slide:l,...u?{id:u}:{}}),n&&f.push({code:`unknown_layout`,slide:l,...u?{id:u}:{},detail:n});let d={slide:l,...u?{id:u}:{}};r!==null&&!M_(r)&&f.push({code:`unknown_transition`,...d,detail:r}),i!==null&&!N_(i)&&f.push({code:`unknown_glow`,...d,detail:i});for(let e of o)f.push({code:`duplicate_morph`,...d,detail:e});return c});return s&&f.push({code:`own_reveal`,slide:-1}),{complete:/<\/html\s*>\s*$/i.test(e),hasDeck:o,title:a,slides:m,issues:f,assets:[...l]}}const G_=new Map(Object.entries({lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`,nbsp:`\xA0`,mdash:`—`,ndash:`–`,hellip:`…`,rarr:`→`,larr:`←`,uarr:`↑`,darr:`↓`,harr:`↔`,copy:`©`,reg:`®`,trade:`™`,times:`×`,divide:`÷`,middot:`·`,bull:`•`,laquo:`«`,raquo:`»`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`,deg:`°`,plusmn:`±`,le:`≤`,ge:`≥`,ne:`≠`,euro:`€`,pound:`£`,yen:`¥`})),K_=/[A-Za-z_][\w.-]*/y,q_=/\s*/y,J_=e=>`name`in e;function Y_(e,t){return e.replaceAll(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]*));/g,(e,n,r,i,a)=>{let o=n?Number(n):r?Number.parseInt(r,16):null;if(o!==null)return o>0&&o<=1114111?String.fromCodePoint(o):e;let s=G_.get(i);return s===void 0&&t?.(i,a),s??e})}function X_(e){return J_(e)?e.children.map(X_).join(``):e.text}function Z_(e){let t=[],n=null,r=t=>{if(!n){n=[];for(let t=e.indexOf(`
225
+ `);return t.title?`**${t.title}**\n\n${a}`:a}const a_=e=>e.root;function o_(e,t){return new e_(new Map(t.map(e=>[e.id,e]))).document(a_(e).children)}const s_=e=>[...e.replaceAll(/\s/g,``)].length;function c_(e,t=[]){let n=new e_(new Map(t.map(e=>[e.id,e]))),r=[];for(let t of a_(e).children??[])t.type===`heading`?r.push({id:Yg(t.$?.blockId),level:Number(Yg(t.tag).slice(1))||1,title:n.inline(t.children),chars:0}):r.length&&(r.at(-1).chars+=s_(n.block(t)));return r}function l_(e){try{return Cr(xr(d.default.readFileSync(f.default.join(e,`comments.json`),`utf8`))).threads}catch{return[]}}function u_(e){let t=Gg(d.default.readFileSync(f.default.join(e,`doc.xml`),`utf8`)),n=mr(sr(t),l_(e)),r=Er(e);return{markdown:(r?`${Kg}\n\n${r.markdown}\n\n---\n\n`:``)+o_(t,n),outline:c_(t,n)}}function d_(e,t,n,r){if(e===`submit`)return{op:`submit`,submit:!t.withdraw};if(!t.ask)throw new M(`comment ${e} needs --ask <questionId>`);if(e===`note`)return{op:`note`,ask:t.ask,text:n()};let i=r?.trim();if(!t.clear&&!t.choice&&!i)throw new M(`comment answer needs --choice <value>, --text <answer>, or --clear`);return{op:`answer`,ask:t.ask,choice:t.clear?null:t.choice??null,answer:t.clear?null:i??null}}var f_='# Document writing\n\nCreate a working copy of the LiteXML outside the artifact directory. For an edit, also keep an untouched copy of the current doc.xml. Save via `write-document --artifact document/<id> --input <edited.xml>`, adding `--base <original.xml>` for edits. This records the writer at the mutation; put assets in `assets/`. Re-read immediately before each edit: the human and server edit this file too. Patch intended blocks, preserve existing IDs and human text; new blocks omit IDs and receive them from the server. Never edit `comments.json` or `.state/`. The server normalizes aliases and indentation after saving. Finish with `check`; pending merging or browser work means check again, not success.\n\nUse a closed `<doc>`. Choose blocks for the reader: diagrams show relationships, charts compare numbers, tables map exact attributes, prose explains reasons. A first draft can contain `<pending intent="What remains to investigate"/>`; fill every pending before claiming completion. Diagrams use native mermaid, or a whiteboard of this project embedded with a reference (below); never pictures of text or box drawing in code blocks.\n\nComplete block and inline vocabulary:\n\n- `h1`–`h6`, `p`, `blockquote`, `ul`/`ol` with `li`, `table`/`tr`/`th`/`td`, `hr`.\n- Inline `b i u s code sub sup mark a br`; aliases `strong em del strike`. Links use `href`. Ordered lists accept `start`; checklists use `<ul type="check"><li checked="true">Done</li></ul>`.\n- `codeblock lang="ts"`: code; use CDATA for literal XML/angle brackets. `mermaid`: native flowcharts/sequences/states. `math`: inline LaTeX, `display="block"` for a block.\n- `img src="assets/image.png" alt="…" caption="…" width="640"`: real images.\n- `alert type="note|tip|important|warning|caution"`: block children. `details summary="…" open="true"`: collapsed depth; omit open for collapsed. `steps` contains `step title="…"` with block children; titles omit numbering.\n- `footnote ref="1"` inline; `footnote-section` contains `def ref="1"` definitions.\n- `chart`: CDATA ChartSpec JSON. Required `version:1`, `type:bar|line|area|pie`, `x` category field, `series:[{key,label?}]`, `data` rows containing x and every series key. Values numbers/null, pie nonnegative. At most 6 series and 6 pie rows. Optional title/subtitle/note/source/xLabel/stacked/donut/highlight, format `{unit,compact,decimals,signed}`, y `{min,max}`, refs `[{y,label}]`. `highlight` is a `series.key` and highlights that entire series; omit it when unnecessary. With `series:[{key:"failures"}]` and rows `[{phase:"Before",failures:12},{phase:"After",failures:4}]`, `highlight:"failures"` is valid; `highlight:"After"` is invalid because it is a row/category value.\n- `dynamic url="assets/demo.html" initial-height="240"`: CDATA JSON becomes `window.ryugiProps`. Self-contained sandboxed HTML, inline scripts/styles, size by content, transparent body. Browser controls persist on HTML rewrite; changing props resets them. Runtime is incomplete until the block has run. Native HTML/CSS/JS and `ryugi-icon` work; storage/cookies do not.\n- `pending intent="…"`, inline `ask`/`option` and `ref` (below; a whiteboard `ref` can also embed as a block). Other tags are rejected.\n\n```xml\n<doc>\n <h1>Retry policy</h1>\n <p>Retry failed delivery at most <b>3</b> times.</p>\n <mermaid><![CDATA[flowchart LR\n ingress --> queue --> worker]]></mermaid>\n <p>Choose a strategy: <ask id="retry-strategy" recommend="exponential"><option value="fixed">Fixed delay</option><option value="exponential">Exponential backoff</option></ask></p>\n <details summary="Evidence"><codeblock lang="text"><![CDATA[attempts: 3]]></codeblock></details>\n</doc>\n```\n\nQuestions: `ask` is inline in p/li/table-cell paragraphs, never directly under doc. Its unique stable id is lowercase letters/digits/hyphens; never reuse an old question ID. Options contain plain text and distinct `value`s; `recommend` must name an option. No options makes an open question: `<ask id="other" placeholder="Describe it"/>`. Human picks are drafts until submitted. Read `comment list --sections threads,asks --detail`. Apply submitted answers, then `comment note --ask <id> --text <what changed>`. Every submitted question needs a note, even unanswered ones (state what was left or assumed). Record terminal answers only when actually supplied via `comment answer --ask <id> --choice <value>` or `--text`, then `comment submit`. Never invent an answer; wait after withdrawal. Changed settled answers require a human instruction and a fresh note.\n\nReferences: inline `<ref document="slug"/>`, `<ref document="slug" block="block-id"/>` (one top-level block of a document: the `id` of its `h2`, `p`, list…; name this document\'s own slug to jump within it), `<ref html="slug">label</ref>`, `<ref artboard="slug" group="q1"/>` (or board), `<ref whiteboard="slug" frame="f1"/>` (or page), `<ref slides="slug" slide="slide-id"/>` (a deck, or one slide of it). Exactly one kind, at most one allowed subtarget, lowercase slug. Optional plain text label; server adds `to` when resolved, preserve it. Missing targets, including a block the document no longer has, are warnings; clear before handoff. Keep referenced IDs stable; when changing a target, update the reference too. A reference under its section heading connects that section to its companion canvas. Live choices/verdicts belong in refs, not duplicated prose.\n\nEmbedded whiteboards: `<ref whiteboard="slug" frame="f1" embed="true"/>` draws the whiteboard in the document instead of a chip. Write it as a paragraph of its own directly under `<doc>`, e.g. `<p><ref whiteboard="sync-flow" frame="f-steps" embed="true"/></p>`; never beside text, in a list, table or quote. `frame` shows that frame cut to its box, `page` one page, neither the main page. Only whiteboard references embed. The drawing follows the whiteboard live: draw and change it on the whiteboard, not in the document; a reader clicks it to open the whole whiteboard. A missing whiteboard or frame is the same check warning as any reference.\n\nAfter editing, run the returned Check command. It names invalid blocks, chart/math/diagram errors, unresolved refs and pending dynamic work. Read complete feedback before acting; reply/resolve and acknowledge only the receipt for evidence actually used.\n';const p_=/^(.+?)->(.+?)(?:#([1-9]\d*))?$/;function m_(e){if(e.node&&e.edge)throw new M(`comment add takes --node or --edge, not both`);if(e.node)return{kind:`node`,id:e.node};if(!e.edge)return;let t=p_.exec(e.edge);if(!t)throw new M(`comment add --edge needs "<from>-><to>", with #n for the nth edge between them`);return{kind:`edge`,from:t[1],to:t[2],index:t[3]?Number(t[3])-1:0}}const h_=e=>t=>d_(e,t,()=>$n(t),t.text);function g_(e,t,n){try{let e=u_(f.default.dirname(n));return{markdown:e.markdown,rows:e.outline}}catch(e){return{warnings:[{code:`W_DOCUMENT_MARKDOWN`,message:`could not read the document as markdown, so it is shown as LiteXML: ${e.message}`}]}}}const __={authoring:f_,localGet:{key:`outline`,read:g_,columns:[{key:`id`,required:!0,positional:!0},{key:`level`,positional:!0},{key:`title`,positional:!0},{key:`chars`}]},changes:!0,review:{sections:[`asks`]},commentActions:{submit:h_(`submit`),answer:h_(`answer`),note:h_(`note`),add:e=>{if(!e.block)throw new M(`comment add needs --block <blockId>`);let t=m_(e);return{op:`add`,blockId:e.block,...t?{diagram:t}:{},...e.quote?{quote:e.quote}:{},text:$n(e)}}}},v_={authoring:'# HTML writing\n\nWrite one complete `index.html` with a descriptive `<title>`, inline or relative styles/scripts/images. The page reloads on edits. Native HTML/CSS/JavaScript works; use labelled controls and visible results. Assets stay inside this artifact directory; CDN fonts/scripts work, absolute local paths do not. Any npm library loads from a CDN with its version pinned; nothing is preloaded, so use one instead of hand-writing its equivalent. The iframe is sandboxed: localStorage/sessionStorage/cookies throw; keep state in DOM/variables. Popups, forms, downloads and clipboard work.\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Retry explorer</title>\n </head>\n <body>\n <label>Attempts <input id="attempts" type="range" min="1" max="5" value="3" /></label>\n <output id="result"></output>\n <script>\n const input = document.getElementById(\'attempts\');\n const render = () =>\n (document.getElementById(\'result\').textContent = input.value + \' attempts\');\n input.addEventListener(\'input\', render);\n render();\n <\/script>\n </body>\n</html>\n```\n\nStable control IDs preserve human input, checks, details and scroll across rewrites. Restoration fires input/change: render from those events. Script-only state resets. Use one surface for one investigation; comparison across independent screens belongs on an artboard. Re-read files before editing; never edit comments or `.state/`.\n\nBundled UI elements require no imports. Use native HTML/CSS for layout. `ryugi-icon name="message-square" size="18"` provides Lucide kebab-case icons (stroke-width defaults 2, color currentColor); label the button, icons are decorative. Find names with `adeck icons <english words>`; unknown names become runtime warnings. For JS-only icons add `<meta name="ryugi-icons" content="1">` and await customElements.whenDefined(\'ryugi-icon\'). Preview glyphs map to the app\'s existing business icons when implementing the design.\n\nRun Check after edits. It distinguishes current static evidence from browser runtime. A closed/unloaded tab means runtime pending; open the returned URL and check again. Uncaught exceptions, rejected promises and missing relative assets are warnings; no browser run is not proof that a page works.\n\n# UI components\n\nHTML artifacts can use a small set of Lobe UI components through Web\nComponents. The artifacts server loads the runtime automatically when the page\ncontains a `<ryugi-…>` element:\n\n```html\n<ryugi-button variant="primary">Save</ryugi-button>\n```\n\nNo script tag is needed. If you create components dynamically, add\n`<meta name="ryugi-ui" content="1">` to the page so the runtime is loaded.\n\nThe runtime loads with `defer`. A page script that needs the components should\nwait for the document event:\n\n```js\ndocument.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n // custom elements are defined\n },\n { once: true },\n);\n```\n\nUse these for controls and basic display. Use plain HTML and CSS for layout;\nthere is no layout wrapper to learn.\n\n## Rules\n\n- Give every interactive control a stable `id`. The viewer restores custom\n controls across rewrites by `id`, the same way it restores native inputs.\n- Listen for `ryugi-change` on controls:\n\n ```js\n document.addEventListener(\'ryugi-change\', (event) => {\n const { value, checked } = event.detail;\n console.log(event.target.id, value, checked);\n });\n ```\n\n It bubbles. `value` is a string, number, boolean, or `null`; `checked` is\n present for checkboxes and switches.\n\n- `value` / `checked` attributes set the initial state. Read the current state\n from the element\'s `value` / `checked` property after `ryugi-ui:ready`, and\n listen for `ryugi-change` for later updates.\n- `class` styles the host; `style` is forwarded to the component as well, so\n `style="width:100%"` works. Style the host, not the component\'s internal\n classes.\n- Keep children simple. For `ryugi-button`, `ryugi-card`, `ryugi-text`,\n `ryugi-tag`, `ryugi-checkbox`, and `ryugi-badge`, the original children are\n moved into the component. `ryugi-select`, `ryugi-segmented`, and\n `ryugi-radio-group` use option children instead.\n- Do not invent a `ryugi-` tag. If a component is not listed here, use HTML.\n- `ryugi-card` already paints a surface. Do not put a background, border and\n padding on both the host and the card: pick one. For a floating panel,\n either position the host and let the card paint its own surface, or make the\n host the surface and use `variant="borderless"` without `glass`/`shadow`.\n- Components follow `prefers-color-scheme`. Set `<html data-theme="light">`\n or `data-theme="dark"` before the runtime loads to pin the whole page.\n Without an explicit theme, the runtime follows OS theme changes.\n Lobe tokens such as `--lobe-color-primary` can be overridden on the host or\n page.\n\n## Controls\n\n### Button\n\n```html\n<ryugi-button variant="primary" size="middle" icon="plus">Add</ryugi-button>\n<ryugi-button variant="outlined" loading>Working…</ryugi-button>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `size`\n(`small`, `middle`, `large`), `block`, `loading`, `disabled`, `shape`, `type`,\n`icon` (any Lucide kebab-case name; `refresh` and `trash` remain aliases).\nRun `node app/ryugi.cjs guide icons` for standalone icons and mapping the preview\'s\nactions to business icons when implementing the app.\n\nUses the native `click` event.\n\n### Action icon\n\n```html\n<ryugi-action-icon icon="settings" title="Settings" aria-label="Settings"></ryugi-action-icon>\n```\n\nAttributes: `icon` (same set as Button), `size`, `disabled`, `title`,\n`aria-label`. Uses the native `click` event.\n\n### Tooltip and popover\n\n```html\n<ryugi-tooltip content="Copy a private link" placement="top">\n <ryugi-icon name="copy" size="14"></ryugi-icon> Copy\n</ryugi-tooltip>\n<ryugi-popover id="sharing" content="Only people you invite can open this link.">\n Sharing details\n</ryugi-popover>\n```\n\nBoth provide a native button trigger; children are its label and decorative\nicons, not nested buttons or controls. `content` is plain text, `placement`\nsets the floating position. Tooltip opens on hover/focus; Popover opens on\nclick (`trigger="hover"` opts into hover). Tooltip also accepts `open` for\na controlled preview. Native trigger clicks still reach your handlers.\n\n### Action menu\n\n```html\n<ryugi-menu id="actions" label="More" icon="ellipsis">\n <ryugi-menu-item value="copy" icon="copy">Copy link</ryugi-menu-item>\n <ryugi-menu-item value="delete" icon="trash-2" disabled>Delete</ryugi-menu-item>\n</ryugi-menu>\n```\n\nAttributes: `label`, `icon`, `placement`, `disabled`. Items accept `value`,\n`icon`, `disabled`; their text is the label. Selecting an enabled item emits\n`ryugi-change` with its action in `event.detail.value`. Actions are not\nrestored as control values on reload.\n\n### Input\n\n```html\n<ryugi-input id="title" placeholder="Title" value="Ryugi" style="width:100%"></ryugi-input>\n```\n\nAttributes: `type`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`, `borderless`), `allowClear`, `placeholder`, `value`,\n`disabled`, `name`, `aria-label`.\n\n### Textarea\n\n```html\n<ryugi-textarea id="notes" rows="4" placeholder="Notes" style="width:100%"></ryugi-textarea>\n```\n\nAttributes: `rows`, `size`, `variant`, `placeholder`, `value`, `disabled`,\n`name`.\n\n### Number\n\n```html\n<ryugi-input-number id="count" value="12" min="0" max="100" step="1"></ryugi-input-number>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `precision`, `controls`, `size`,\n`variant`, `placeholder`, `disabled`.\n\n### Slider\n\n```html\n<ryugi-slider id="size" value="32" min="0" max="100" step="1"></ryugi-slider>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `disabled`.\n\n### Slider with number input\n\nThe most useful control for tuning an exact value.\n\n```html\n<ryugi-slider-input id="radius" value="8" min="0" max="32" step="1"></ryugi-slider-input>\n```\n\nAttributes: `value`, `min`, `max`, `step`, `controls`, `size`, `variant`,\n`disabled`.\n\n### Switch\n\n```html\n<ryugi-switch id="dark" checked></ryugi-switch>\n```\n\nAttributes: `checked`, `loading`, `size`, `disabled`, `name`.\n\n### Checkbox\n\n```html\n<ryugi-checkbox id="compact">Compact</ryugi-checkbox>\n```\n\nAttributes: `checked`, `shape`, `size`, `disabled`, `name`. Children are the\nlabel.\n\n### Segmented\n\n```html\n<ryugi-segmented id="mode" value="grid">\n <ryugi-segment value="list">List</ryugi-segment>\n <ryugi-segment value="grid">Grid</ryugi-segment>\n <ryugi-segment value="masonry">Masonry</ryugi-segment>\n</ryugi-segmented>\n```\n\nAttributes: `value`, `size` (`small`, `middle`, `large`), `variant`\n(`filled`, `outlined`), `block`, `glass`, `shadow`, `vertical`, `disabled`.\n\n### Select\n\n```html\n<ryugi-select id="layout" value="a" placeholder="Choose layout">\n <ryugi-option value="a">Sidebar</ryugi-option>\n <ryugi-option value="b">Top tabs</ryugi-option>\n <ryugi-option value="c">Bottom rail</ryugi-option>\n</ryugi-select>\n```\n\nAttributes: `value`, `placeholder`, `size`, `variant`, `allowClear`,\n`showSearch`, `loading`, `mode` (`multiple`, `tags`), `disabled`.\n\n### Radio group\n\n```html\n<ryugi-radio-group id="density" value="comfortable">\n <ryugi-radio value="compact">Compact</ryugi-radio>\n <ryugi-radio value="comfortable">Comfortable</ryugi-radio>\n <ryugi-radio value="spacious">Spacious</ryugi-radio>\n</ryugi-radio-group>\n```\n\nAttributes: `value`, `horizontal`, `gap`, `size`, `disabled`.\n\n### Colour picker\n\n```html\n<ryugi-color-picker id="accent" value="#c56473" trigger="field"></ryugi-color-picker>\n```\n\nAttributes: `value`, `alpha`, `defaultFormat` (`hex`, `rgb`, `hsl`),\n`trigger` (`swatch`, `field`, `chip`), `size`, `disabled`.\n\n## Display\n\n### Toast\n\nHTML artifacts can call the bundled Lobe UI toast API as `window.ryugiToast`.\nIf the page has no `ryugi-` UI controls, opt in with the meta tag. Wait for\n`ryugi-ui:ready` before calling it:\n\n```html\n<meta name="ryugi-ui" content="1" />\n<button id="save" type="button">Save</button>\n<script>\n document.addEventListener(\n \'ryugi-ui:ready\',\n () => {\n document.getElementById(\'save\').addEventListener(\'click\', async () => {\n try {\n await saveDraft(); // the page\'s own operation\n window.ryugiToast.success({ id: \'save-result\', title: \'Saved\' });\n } catch {\n window.ryugiToast.error({\n id: \'save-result\',\n title: \'Save failed\',\n description: \'Try again.\',\n });\n }\n });\n },\n { once: true },\n );\n<\/script>\n```\n\nMethods: `success`, `error`, `info`, `warning`, `loading`. Each takes a string\nmessage or `{ title, description, id, duration }`. Text is rendered as text,\nnot HTML. A stable `id` refreshes the same notification instead of stacking\ncopies. The default duration is 5000ms; `duration: 0` stays until closed.\n`loading` stays until closed by default.\n\nCalls return a handle with `id` and `close()`. Use\n`window.ryugiToast.dismiss(id)` to close one, or `dismiss()` to close all.\nToasts appear at the bottom right and follow the page\'s theme. They are\ntransient: rewriting the page does not restore them. No `ryugi-toast` tag is\nneeded. Artboard pages do not load this UI runtime.\n\n### Tag\n\n```html\n<ryugi-tag variant="outlined">New</ryugi-tag>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`, `solid`), `size`,\n`shape` (`normal`, `round`), `color`, `closable`.\n\n### Alert\n\n```html\n<ryugi-alert\n type="info"\n title="Streaming"\n description="Pending boards draw as skeletons."\n></ryugi-alert>\n```\n\nAttributes: `type` (`success`, `info`, `warning`, `error`, `secondary`),\n`variant` (`soft`, `outlined`, `plain`), `title`, `description`, `showIcon`,\n`closable`. Text children are used as the title when `title` is absent.\n\n### Progress\n\n```html\n<ryugi-progress percent="64" size="small"></ryugi-progress>\n```\n\nAttributes: `percent`, `size`, `status`.\n\n### Badge\n\n```html\n<ryugi-badge count="3" status="processing"></ryugi-badge>\n<ryugi-badge count="3">\n <ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n</ryugi-badge>\n```\n\nAttributes: `count`, `dot`, `status`, `text`, `showZero`, `size`, `color`.\n\n### Avatar\n\n```html\n<ryugi-avatar src="avatar.png" alt="Innei" size="32"></ryugi-avatar>\n```\n\nAttributes: `src`, `alt`, `size`, `shape`.\n\n### Divider\n\n```html\n<ryugi-divider dashed></ryugi-divider>\n```\n\nAttributes: `orientation`, `dashed`.\n\n### Card\n\n```html\n<ryugi-card variant="outlined" shadow>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Supporting copy.</ryugi-text>\n</ryugi-card>\n```\n\nAttributes: `variant` (`filled`, `outlined`, `borderless`), `shadow`,\n`glass`, `clickable`. Children are preserved, including nested components.\n`glass`, `shadow` and `variant` paint the inner Block surface, not the host.\nIf the host supplies the panel background and padding, omit `glass`/`shadow`\nand use `variant="borderless"` so there is only one visible container.\n\n### Text\n\n```html\n<ryugi-text type="secondary">Secondary body text</ryugi-text>\n<ryugi-text strong>Strong label</ryugi-text>\n<ryugi-text code>const x = 1</ryugi-text>\n```\n\nAttributes: `type` (`secondary`, `success`, `warning`, `danger`, `info`),\n`strong`, `code`, `italic`, `underline`, `delete`, `mark`, `align`, `weight`.\n\n## Complete tuning panel\n\n```html\n<ryugi-card>\n <ryugi-text strong>Header</ryugi-text>\n <ryugi-text type="secondary">Tune the reading column.</ryugi-text>\n\n <ryugi-slider-input id="measure" value="64" min="40" max="90" step="1"></ryugi-slider-input>\n\n <ryugi-segmented id="density" value="comfortable">\n <ryugi-segment value="compact">Compact</ryugi-segment>\n <ryugi-segment value="comfortable">Comfortable</ryugi-segment>\n <ryugi-segment value="spacious">Spacious</ryugi-segment>\n </ryugi-segmented>\n\n <ryugi-switch id="dark"></ryugi-switch>\n <ryugi-tag>Live preview</ryugi-tag>\n</ryugi-card>\n\n<script>\n document.addEventListener(\'ryugi-change\', (event) => {\n document.body.dataset[event.target.id] = event.detail.value;\n });\n<\/script>\n```\n\n## Not included in the first version\n\nTabs, Modal, Drawer, Table, DatePicker, and layout\ncomponents. Use plain HTML/CSS or a later component if one is added.\n',phoneScreens:!0};var y_='## Mockup components\n\n`<ryugi-ios-shell>` draws the device and nothing else: the screen (402×874, iPhone 17), status bar, Dynamic Island, home indicator and, with `bezel`, the frame (442×914). Size phone boards to match. Never hand-draw those parts. Three system controls are built in as well: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` draw the iOS switch, segmented control and slider, with the frosted knob that opens into clear glass while it is pressed, dragged or travelling; use them wherever the product shows one of these controls instead of drawing your own. Everything else on the screen (navigation bar, glass buttons, tab bar, cards, lists, inputs, sheets, a floating composer) is the product\'s own design system: write it by hand in HTML/CSS from the variables of `tokens.css`, in the product\'s own style, including its own Liquid Glass where the product uses it. Do not imitate iOS Settings rows unless the product\'s own screens look like that. The shell renders in light DOM, so selection, comments and the Inspector reach every part. The server loads it when the page contains the tag; for a shell created by script add `<meta name="ryugi-mockup" content="1">` and wait for `ryugi-mockup:ready` on `document`.\n\n```html\n<!doctype html>\n<html lang="zh">\n <head>\n <meta charset="utf-8" />\n <link rel="stylesheet" href="../tokens.css" />\n <style>\n html,\n body {\n margin: 0;\n }\n .nav {\n display: flex;\n align-items: center;\n justify-content: space-between;\n height: 44px;\n padding: 0 16px;\n }\n .mark {\n font: 700 26px/32px var(--font-display);\n color: var(--color-text);\n }\n .glass {\n display: flex;\n border-radius: 22px;\n background: var(--color-glass);\n backdrop-filter: blur(16px) saturate(1.8);\n color: var(--color-text);\n }\n .glass > * {\n display: grid;\n place-items: center;\n width: 44px;\n height: 44px;\n }\n .card {\n margin: 8px 16px;\n padding: 16px;\n border-radius: var(--radius-card);\n background: var(--color-surface);\n }\n </style>\n </head>\n <body>\n <ryugi-ios-shell>\n <div class="nav">\n <span class="mark">喵旅</span>\n <span class="glass">\n <span\n ><ryugi-icon symbol="person.crop.circle" name="circle-user" size="22"></ryugi-icon\n ></span>\n <span><ryugi-icon symbol="plus" name="plus" size="22"></ryugi-icon></span>\n </span>\n </div>\n <section class="card">…</section>\n </ryugi-ios-shell>\n </body>\n</html>\n```\n\nThe variable names in the example (`--font-display`, `--radius-card`, `--color-glass`) stand for roles; use the names the product\'s own `tokens.css` defines.\n\n| Element | Attributes | Children |\n| ------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `ryugi-ios-shell` | `bezel`, `time` (9:41), `hide="status island home all"` (any of them) | the screen content: it flows from below the status bar (`--safe-top`, 62px); absolutely positioned content measures from the screen\'s top edge. `--safe-bottom` is 34px. Both stay when parts are hidden |\n| `ryugi-token-sheet` | `appearance` to show one set only | one `<script type="application/json">` |\n\nAll of them take `appearance="light|dark"`, otherwise follow the nearest `[data-appearance]`, then the system. Unknown attribute values raise a runtime warning.\n\n### iOS controls\n\n```html\n<div class="row">\n <span>自动暂停</span>\n <ryugi-ios-switch id="auto-pause" checked></ryugi-ios-switch>\n</div>\n<ryugi-ios-segmented id="range" value="week" block>\n <ryugi-ios-segment value="day">日</ryugi-ios-segment>\n <ryugi-ios-segment value="week">周</ryugi-ios-segment>\n <ryugi-ios-segment value="month">月</ryugi-ios-segment>\n</ryugi-ios-segmented>\n<ryugi-ios-slider\n id="volume"\n label="播报音量"\n value="65"\n start-icon="volume-1"\n end-icon="volume-2"\n></ryugi-ios-slider>\n```\n\n| Element | Attributes | Events |\n| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |\n| `ryugi-ios-switch` | `checked`, `disabled`, `size="sm md lg"` (track 22, 28, 36px; md), `color`, `label` and `description` beside it, `label-side="left"` | `change`, `detail.checked` |\n| `ryugi-ios-segmented` | `value`, `size="sm md lg"` (28, 32, 40px; md), `block` to fill the width; children are `<ryugi-ios-segment value>`, whose content (text, a `ryugi-icon`) is the label | `change`, `detail.value` |\n| `ryugi-ios-slider` | `value`, `min`, `max`, `step` (0, 100, 1), `size="sm md lg xl"` (track 8, 12, 18, 26px; md), `color`, `label` above with the value unless `hide-value`, `start-icon` and `end-icon` (Lucide names) | `input` while dragging, `change` when it lands, `detail.value` |\n\nThey are interactive: a tap flips the switch, the knob drags, the segmented lens can be held and dragged to another option, the slider follows the pointer, and the keyboard works. Their state is reflected in the `checked` and `value` attributes, and setting those from a script moves the control. The on colour of the switch and the filled part of the slider read `--color-accent` unless `color` names one (`#34c759`). The track, the segmented background and the selected pill follow the appearance; labels read `--color-text` and `--color-text-secondary`.\n\nIcons: `<ryugi-icon name>` is a Lucide icon; find names with `adeck icons <english words>`. Add `symbol`, an SF Symbol name (`wallet.bifold.fill`): when the local server runs on macOS it draws the symbol through the system and shows it at the symbol\'s own proportions, tinted with `currentColor`; anywhere else (other systems, Artideck Cloud, published links) the Lucide icon shows. Write both. Use `symbol` only in mockups of apps for Apple platforms; that is the condition of Apple\'s license. Symbol images are never part of `pages/` and are never published.\n\nProduct tokens live in one stylesheet (on an artboard `pages/tokens.css`), light on `:root`, dark on `[data-appearance="dark"]`. The shell\'s root carries `data-appearance`, so light and dark phones sit side by side and your content under `[data-appearance="dark"]` flips with them. The shell reads `--color-bg` (screen), `--color-text` (status bar, home indicator) and `--font-body`, falling back to iOS system values; the token sheet also reads `--color-text-secondary`, `--color-separator`, `--color-surface`, `--color-fill` and `--color-accent`. Your content reads the same variables plus the product\'s own (radius, spacing, type, glass).\n\n`ryugi-token-sheet` draws the token table from JSON that names tokens, never values; values come from the stylesheet in both appearances:\n\n```json\n{\n "groups": [\n {\n "name": "Text",\n "kind": "color",\n "tokens": [\n {\n "name": "--color-text-secondary",\n "use": "行右侧的值",\n "on": "--color-surface",\n "board": "t-color-a"\n }\n ]\n },\n {\n "name": "Type",\n "kind": "type",\n "tokens": [{ "name": "--type-body", "use": "正文", "sample": "招商银行储蓄卡" }]\n }\n ]\n}\n```\n\nKinds: `color` (swatches; with `on`, WCAG contrast per appearance flagged under 4.5:1, or 3:1 with `"large": true`), `type` (a `font` shorthand), `space`, `radius`, `size`, `shadow`, `motion` (`<duration> <easing>`, click to play). Token and group names are English; `use` and `sample` follow the product\'s language. Missing variables and broken JSON show inline errors.\n',b_="## Phone mockups\n\nEvery phone screen is a `<ryugi-ios-shell>`: it draws the 402×874 screen, status bar, Dynamic Island and home indicator, and `bezel` adds the 442×914 frame. Never hand-draw those parts, nor a switch, segmented control or slider: `<ryugi-ios-switch>`, `<ryugi-ios-segmented>` and `<ryugi-ios-slider>` are built in. Everything else on the screen is the product's own design from its `tokens.css`. Before the first phone screen or `<ryugi-token-sheet>`, read the mockup guide: `start --artifact <artifact> --help --mockup`.\n",x_='# Report writing\n\nA report is data and presentation kept apart. Each data source is a Node script that prints JSON; the report is `report.tsx`, one default-exported component built only from `@ryugi/report` that imports the data it draws.\n\n```\nreport/<id>/\n report.tsx\n sources/<source-id>/source.json\n sources/<source-id>/<script>.mjs\n data/<source-id>.json written by the hub when a source runs; never write it by hand\n assets/<file>.png images the report shows (png, jpg, gif, webp, avif, svg)\n```\n\n## Data sources\n\n`sources/<source-id>/source.json`: `{ "title": "Commits per day", "description": "main branch, last 30 days", "input": "git history of the repo", "script": "collect.mjs", "args": ["--days", "30"] }`. `title` and `script` are required; the script is a `.mjs`, `.js` or `.cjs` file in the same folder. Source ids are kebab-case.\n\nThe script runs with the project root as cwd and Node from the hub, so it can use the project\'s `node_modules`. Its env is the hub\'s env with the project\'s `.env` and `.env.local` laid over it; read secrets and machine paths from env or `args`, never write them into the script. It must print one JSON value on stdout (at most 2 MB; the whole report\'s data at most 10 MB) and exit 0 within 60 s. Do the aggregation in the script: the report only draws. A stderr line `ryugi:input <text>` replaces the input shown in the panel for that run, such as the commit the data was read at; other stderr is shown when the run fails.\n\nRun sources with `adeck report refresh --artifact report/<id>` (all) or with `--only <source-id>` (one). The hub runs them, one run per source at a time, and writes `data/<source-id>.json`. Refresh after adding or changing a source, and before `check`. Reports fetched from someone else\'s Cloud link are read-only: never run their scripts.\n\n## report.tsx\n\n```tsx\nimport {\n BarChart,\n Grid,\n Report,\n Section,\n Stat,\n Table,\n useMemo,\n useState,\n Param,\n} from \'@ryugi/report\';\nimport days from \'./data/commits-per-day.json\';\n\nexport default function Commits() {\n const [span, setSpan] = useState(14);\n const shown = useMemo(() => days.slice(-span), [span]);\n return (\n <Report title="Ryugi commits" caption="main branch">\n <Param label="Window" min={7} max={30} unit="days" value={span} onChange={setSpan} />\n <Grid columns={3}>\n <Stat\n id="total"\n source="commits-per-day"\n title="Commits"\n value={shown.reduce((sum, day) => sum + day.commits, 0)}\n />\n </Grid>\n <Section id="daily" title="Per day">\n <BarChart\n id="per-day"\n source="commits-per-day"\n title="Commits per day"\n data={shown}\n x="date"\n series={[{ key: \'commits\', label: \'Commits\' }]}\n />\n <Table\n id="days"\n source="commits-per-day"\n title="Days"\n rows={shown}\n rowKey="date"\n columns={[{ key: \'date\' }, { key: \'commits\', align: \'right\' }]}\n />\n </Section>\n </Report>\n );\n}\n```\n\nImports come only from `@ryugi/report` and `./data/<source-id>.json` (default import; the source must exist). JSX uses SDK components only: no `div`, `img`, `a` or other native elements, no network calls, `document` / `window` / `location` / `navigator` / storage access, `globalThis`, `eval`, `Function`, `.constructor`, `import()` / `require()` or timers. Words in text and strings are fine; the check reads code. The page cannot reach the network either way. `report.tsx` stays under 64 KB; put data in a source. Derive with `useMemo` and plain expressions; keep state in `useState`.\n\nEvery Stat, chart, Table, Callout, Image and Section needs an `id`: kebab-case, unique in the report, and stable across edits, since comments and references hold on to it. Stat, charts and Table also need `source`: the source id, or a list of them, that the block\'s numbers come from; the hover chip and the sources panel read it. Write `id`, `source` and `title` as string literals.\n\nComponents:\n\n- `Report` `{ title, caption? }`: the root; `title` is the artifact\'s title.\n- `Section` `{ id?, title? }`, `Grid` `{ columns?: 1 | 2 | 3 | 4 }`, `Card`, `Stack` `{ gap? }`, `Divider`.\n- `H2`, `H3`, `Text` `{ tone?: \'muted\' }`, `List` `{ items }`, `Callout` `{ id, title?, tone?: \'info\' | \'success\' | \'warning\' | \'error\' }`.\n- `Stat` `{ id, source, title, value, unit?, delta?, format?, note? }`; `delta` is signed and shown up or down.\n- `Table` `{ id, source, title?, rows, rowKey, columns: { key, label?, align?, format? }[] }`; every row prints; a click on a row starts a comment on it.\n- `LineChart`, `BarChart`, `AreaChart`, `PieChart`, `ScatterChart` `{ id, source, title, data, x, series: { key, label?, color? }[], subtitle?, stacked?, donut?, highlight?, refs?: { label, y }[], format?, note? }`: the same chart renderer as a document\'s chart block. A `ScatterChart` needs a numeric `x` in every row. A reader clicks a point to pin it and comments on that point.\n- `Param` `{ label, value, onChange, min?, max?, step?, unit? }` (a slider with a number field when min and max are set), `Select` `{ label?, value, options, onChange }`, `Toggle` `{ label, checked, onChange }`. Printed, they show the value the reader set; a comment on a point or row records them too.\n- `Image` `{ id, src, alt, caption?, width? }`: an image file from the report folder, `src` written as a string such as `"assets/sources-panel.png"`; `alt` describes it. Copy screenshots and figures into `assets/` first; remote URLs are not allowed. Comments anchor to the image as a block.\n- `useState`, `useMemo` from `@ryugi/report`.\n\n`format` is `{ unit?, decimals?, compact?, signed? }`.\n\n## Check, comments, references\n\n`adeck check --artifact report/<id>` reports static issues (imports, native elements, missing or repeated ids, unknown sources, missing data files) and, once a browser has opened the report, render errors.\n\nComments anchor to a block, a table row or a chart point: `adeck comment add --artifact report/<id> --block <block-id> [--point <series>:<x> | --row <rowKey>]`. A comment keeps the value it was made on and which data it saw; after a refresh changes that data it is marked data changed and stays where it was.\n\nReference a report from a document with `<ref report="<id>"/>`, or one block with `<ref report="<id>" block="<block-id>"/>`. A deck names it inline with the same `<ref>`, and shows one block on a slide with `<embed report="<id>" block="<block-id>"/>`; give the blocks a deck shows a stable `id`.\n\nPublishing includes `report.tsx`, `sources/**`, `data/**` and the images under `assets/` with the report\'s visibility. Publishing is refused while a script, `report.tsx` or the data holds an absolute machine path (`/Users/…`, `/home/…`, `C:\\\\…`, not checked in data) or something that looks like a secret (`sk-…`, `ghp_…`, `AKIA…`, a private key, a value from `.env`); the refusal names the file and line.\n';function S_(e){if(!e.block)throw new M(`comment add on a report needs --block <blockId>`);if(e.point!==void 0&&e.row!==void 0)throw new M(`comment add takes --point or --row, not both`);let t;if(e.point!==void 0){let n=e.point.indexOf(`:`);if(n<=0||n===e.point.length-1)throw new M(`--point needs <series>:<x>, such as commits:Nov 2`);t={series:e.point.slice(0,n),x:e.point.slice(n+1)}}return{op:`add`,block:e.block,...t?{point:t}:{},...e.row===void 0?{}:{row:e.row},text:$n(e)}}const C_={authoring:x_,review:{sections:[]},commentActions:{add:S_}};var w_='# Slides writing\n\nWrite one complete `deck.xml` under the returned artifact directory; put images in `assets/` and reference them with relative paths. The deck is for an audience: your human partner presents it. Re-read before each edit; never edit `comments.json` or `.state/`. Finish with `check`.\n\nThe file holds what the slides say. The server compiles it into the page and adds the presentation engine, theme, code highlighting, diagrams and formulas. Only the tags and attributes below exist: there is no `class` and no `style`, and `check` reports anything else by slide and tag.\n\n```xml\n<deck title="Retry policy" lang="en">\n <slide id="cover" layout="cover">\n <kicker>Delivery · Q3</kicker>\n <h1>Retry policy</h1>\n <subtitle>Why failed deliveries now retry three times</subtitle>\n <notes>Open with last month\'s incident.</notes>\n </slide>\n\n <slide id="what-changes">\n <h2>What changes</h2>\n <ol steps="true">\n <li>At most three attempts</li>\n <li>Exponential backoff</li>\n </ol>\n </slide>\n\n <slide id="backoff" layout="code">\n <h2>Backoff</h2>\n <codeblock lang="ts" lines="1|2-3"><![CDATA[\n const delay = (attempt: number) =>\n Math.min(30_000,\n 500 * 2 ** attempt);\n ]]></codeblock>\n </slide>\n</deck>\n```\n\n## Slides\n\n- One slide is one `<slide>` directly inside `<deck>`. The deck\'s `title` is required; `lang` is optional.\n- Every slide needs a unique, stable `id` of lowercase letters, digits and hyphens. Comments and document references find a slide by its id: keep the id when you rewrite a slide, and only change it when the slide becomes a different slide. Deleting a slide orphans its comments.\n- The canvas is fixed at 1280×720. Content that leaves that box is reported by `check` as overflow, naming the slide. Fix it by cutting or splitting the slide; `zoom="0.8"` on the slide (0.3 to 1) is for the one dense slide that must stay whole.\n- While the deck is open in the viewer, `check` also names contact sheet images (`Sheet:`) that show every slide at its last step, twelve to an image, with overflowing and hidden slides marked. After editing, run `check`, open those images, and look for slides that are too full or that all look like the same template. `sheet_not_drawn` under `Pending` means the open viewer has not drawn this version yet. `Sheet: unavailable (…)` means it cannot be drawn, as for a deck holding a video or an iframe: go on without it.\n- `hidden="true"` keeps a slide in the file and out of the talk: it shows, marked, only while the deck is worked on; presenting, the audience window, the PDF and a published link never get it, and it takes no page number.\n- `<group id="evidence" title="What the data says">` inside `<deck>` gathers the slides of one part of the talk. It holds only `<slide>` and `<include>`, never another group; its `id` follows the slide id rules and is unique among slides and groups, and `title` is required. The grid view shows each group as a titled row; the audience sees nothing of it. Slides outside any group are fine, before, between or after groups.\n- `cover="<slide id>"` on `<deck>` names the slide that stands for the deck in lists and links. `check` warns when it names a slide that is missing or hidden.\n- Write XML: close every tag, quote every attribute, write `&lt;` and `&amp;` in text; common names such as `&nbsp;`, `&mdash;` and `&rarr;` work, any other is an error, so write the character itself. Code, diagrams and formulas go in `<![CDATA[ … ]]>` so nothing in them needs escaping. CDATA ends at the first `]]>`: code that contains `]]>` comes from a file with `src`. End the file with `</deck>`.\n\n## Layouts\n\nPick the layout that fits what the slide says, and vary them: a deck of identical title-and-bullets slides reads as a template. Each layout adds a few places of its own; a place used in another layout is reported. The theme adds the page number itself.\n\n| `layout` | Use it for | Inside the slide |\n| ----------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------- |\n| `default` | A title with text, a list, a table or code | Optional `<label>`, an `<h2>`, then blocks. Omitting `layout` gives this one |\n| `cover` | The first slide | `<kicker>`, `<h1>`, `<subtitle>` |\n| `section` | The start of a new part | Optional `<label>`, then an `<h1>` or `<h2>` |\n| `statement` | One sentence the audience should remember | Optional `<label>`, an `<h2>` with the key words in `<mark>`, optional `<subtitle>` |\n| `two-cols` | Two things side by side | An `<h2>`, then exactly two `<col>`, each holding blocks |\n| `image` | Text beside a picture | One `<col>` holding the text and one `<img>`; whichever comes first is on the left |\n| `quote` | A quotation | `<quote>` and `<cite>` |\n| `fact` | One number that matters | `<big value="10–12" unit="working days"/>`, then up to three `<fact value="5 days" label="API"/>` |\n| `code` | Code as the subject of the slide | Optional `<label>`, an `<h2>` and one `<codeblock>` or one `<magic>` |\n| `end` | The last slide | An `<h1>` |\n| `none` | A slide you lay out yourself | `src` naming an HTML file; see Free HTML. No padding and no page number |\n\n```xml\n<slide id="numbers" layout="fact">\n <big value="13" unit="harnesses supported"/>\n <fact value="5" label="artifact types"/>\n <fact value="0" label="subscriptions"/>\n</slide>\n<slide id="before-after" layout="two-cols">\n <h2>Before and after</h2>\n <col>\n <h3>Before</h3>\n <p>One attempt, then a page.</p>\n </col>\n <col>\n <h3>After</h3>\n <p>Three attempts, then a page.</p>\n </col>\n</slide>\n<slide id="dashboard" layout="image">\n <col>\n <label>Result</label>\n <h2>Failures fell by half</h2>\n </col>\n <img src="assets/dashboard.png" alt="Failure rate before and after the change" frame="true"/>\n</slide>\n```\n\n## Blocks and text\n\nBlocks sit in a slide or a `<col>`: `<h1>`, `<h2>`, `<h3>`, `<p>`, `<ul>` and `<ol>` of `<li>` (a list may nest in an item), `<table>` of `<tr>` holding `<th>` or `<td>`, `<blockquote>`, `<hr/>`, `<alert type="note|tip|important|warning|caution">` holding blocks, `<img>`, `<icon>`, `<codeblock>`, `<magic>`, `<mermaid>`, `<math>`, `<html>`, `<embed>` and `<notes>`.\n\nBlocks and inline tags a document also has carry the same names here. Inside text: `<b>`/`<strong>`, `<i>`/`<em>`, `<u>`, `<s>`/`<del>`, `<sub>`, `<sup>`, `<code>`, `<mark>`, `<a href="…">`, `<br/>`, `<math>`, `<icon>` and `<ref>`.\n\n- `<img src="assets/chart.png" alt="…"/>` shows a file of the artifact directory. `frame="true"` gives a screenshot rounded corners and a shadow.\n- `<icon name="check" size="32"/>` draws an icon; `size` is in pixels.\n- `<mermaid>` holds a Mermaid diagram and `<math>` a LaTeX formula, both in CDATA. `<math>` inside text is an inline formula.\n- `<notes>` holds speaker notes, shown only to the presenter. One per slide, plain text with `<br/>` between lines.\n\n```xml\n<h2>How a delivery flows</h2>\n<mermaid><![CDATA[\n flowchart LR\n A["ingress<br/>edge"] --> B[queue] --> C[worker]\n]]></mermaid>\n<table>\n <tr><th>Attempt</th><th>Delay</th></tr>\n <tr><td>1</td><td><math>500 \\cdot 2^1</math> ms</td></tr>\n</table>\n<p><icon name="check" size="24"/> Shipped behind a flag, see <a href="https://example.com/rfc">the RFC</a>.</p>\n```\n\n## Code\n\n`<codeblock lang="ts">` is a code block, named as in a document; `<code>` is inline code inside text. Write the code in CDATA; the indentation it shares with the XML is taken off.\n\n- `lines`: stepped line highlight. Parts are separated by `|`, each one step, lines count from 1: `1`, `2-3`, `2-3,5`; `all` lights every line and `hide` hides the block for that step.\n- `src="src/retry.ts#L10-24"`: take the code from a file of the project instead of writing it, optionally only those lines. The path is relative to the project root; files outside the project, dot-files such as `.env`, and files over 512 KB are refused, and so are files named like secrets (`secrets.*`, `credentials.*`, `*.pem`, `*.key`, `*.tfstate`, `*.tfvars`, SSH keys) and files git ignores. Never show a file that holds a secret under another name. What a deck shows is published with it.\n- `numbers="true"`: line numbers. `title="src/retry.ts"`: a title above the block. `max-height="320"`: a height in pixels past which the block scrolls, following the highlighted lines. `diff="true"`: lines starting with `+` or `-` are drawn as added or removed.\n- `<magic lang="ts">` holds two or more `<step>`, each the whole code at one step, in CDATA; what stays moves into place, and each step after the first is a step of the slide.\n\n```xml\n<codeblock lang="ts" src="src/retry.ts#L10-24" numbers="true" title="src/retry.ts" lines="all|3-5"/>\n<codeblock lang="ts" diff="true"><![CDATA[\n const attempts =\n - 1;\n + 3;\n]]></codeblock>\n<magic lang="ts">\n <step><![CDATA[const delay = 500;]]></step>\n <step><![CDATA[const delay = (attempt: number) => 500 * 2 ** attempt;]]></step>\n</magic>\n```\n\n## Steps and marks\n\n- `step="true"` on a block or a list item: it appears on the next step. `steps="true"` on a `<ul>`, `<ol>`, `<table>` or `<col>` makes each item, row or block a step.\n- `step="2"` places a step by number, and `step="with"` makes it appear together with the step before it.\n- `<mark>` highlights words. `type="highlight"`, `underline`, `circle` or `strike` draws that mark; with `step` the words are there from the start and the mark is drawn on its step.\n- `morph="title"` on a block in two consecutive slides moves it from one to the other; a name is used once per slide and the pair should hold the same text.\n\n```xml\n<h2 morph="title">The <mark type="underline" step="true">retry budget</mark> is per delivery</h2>\n<p step="true">Three attempts in total.</p>\n<p step="with">The first one counts.</p>\n<ul steps="true">\n <li>500 ms</li>\n <li>1 s</li>\n</ul>\n```\n\n## Several files and free HTML\n\n- `<include src="parts/appendix.xml"/>` inside `<deck>` puts the slides of another file of the artifact directory there. That file starts with `<slides>`, holds only `<slide>`, and cannot include further files. Ids stay unique across all files.\n- `<html src="parts/demo.html"/>` is a block of HTML you write yourself, in a file of the artifact directory.\n- `<slide id="demo" layout="none" src="parts/demo.html"/>` is a whole slide of your own HTML: you own every pixel of 1280×720. It may hold `<notes>` and nothing else.\n- A free HTML file is a fragment: no page wrapper, every `<div>` closed. `data-step` on an element inside it makes that element a step. It runs in the deck\'s sandbox: no localStorage, sessionStorage or cookies.\n\n```xml\n<deck title="Retry policy">\n <slide id="live-demo" layout="none" src="parts/demo.html">\n <notes>Click through the three states.</notes>\n </slide>\n <slide id="curve">\n <h2>The backoff curve</h2>\n <html src="parts/curve.html"/>\n </slide>\n <include src="parts/appendix.xml"/>\n</deck>\n```\n\n## Other artifacts\n\n`<embed>` puts another artifact of this project on the slide. Name the target by its slug, as a document\'s `<ref>` does:\n\n- `<embed artboard="settings-page" board="q1-b"/>` shows one board of an artboard, in a box of the board\'s shape.\n- `<embed whiteboard="sync-flow" frame="f1"/>` shows one frame of a whiteboard; `page="<page id>"` instead of `frame` shows a whole page. The box takes the shape of the frame or of what is drawn on the page.\n- `<embed report="q3-revenue" block="by-month"/>` shows one block of a report at the slide\'s width and at the block\'s own height, in the deck\'s light or dark.\n- `<embed slides="launch" slide="pricing"/>` shows one slide of another deck at 1280×720, at its last step, in that deck\'s own theme. Embeds on that slide hold their place under their names: decks nest one level.\n- `<embed html="spring-curve"/>` shows an html page, at 1280×720.\n\nAn embed is live: it shows the target as it is now, changes when the target does, and can be scrolled and clicked during the talk. Its corner button opens the target nearly full screen at the embedded part, and Esc closes it. In thumbnails, PNG and PDF export and the contact sheet every embed is a picture of the target.\n\n`<ref>` names another artifact inside text, as a chip: `<ref document="retry-policy">the design</ref>`, `<ref report="q3-revenue" block="by-month"/>`, `<ref whiteboard="sync-flow" frame="f1"/>`. Every kind a document can reference can be named, with the same attributes; with no text of its own the chip shows the target\'s title. Clicking it opens the target nearly full screen; nothing opens while the slide is edited or the pen or laser is on.\n\nPublished, a deck shows the published versions of what it embeds and names. A target that is private, unpublished or gone shows to visitors as its chip text or as an unpublished artifact, never its title or a picture of it; its owner sees it. Publishing the deck offers what it embeds and names to publish with it.\n\nAn embed takes `step` and `morph` like any block. `check` warns, naming the slide, when the artifact or the part it names (board, frame, page, block, slide) is not there, and the slide shows the target\'s name in its place. A `<ref>` to a missing target is warned about the same way.\n\n```xml\n<slide id="settings" layout="two-cols">\n <h2>The settings page</h2>\n <col>\n <p>Option B keeps billing on the first screen.</p>\n </col>\n <col>\n <embed artboard="settings-page" board="q1-b"/>\n </col>\n</slide>\n```\n\n## Theme, motion and glow\n\nChange the look for the whole deck with one `<theme>` before the first slide. `name` picks the theme: `paper` (the default: warm paper, one seal-coloured accent, glow) or `mono` (black on white, monospace labels, emphasis by weight, no glow). `appearance` is `light`, `dark` or `auto`; `auto`, the default, follows the system of whoever opens the deck and prints light, so write `light` or `dark` when the room decides. Every other attribute overrides one variable of the theme, in both appearances. A deck that sets its own `paper`, `surface` or `ink` is `light` unless it names an appearance: those colours suit one appearance only. Do not restyle slide by slide.\n\n```xml\n<deck title="Retry policy">\n <theme name="paper" appearance="dark" accent="#0a7cff" transition="slide-left" fragment="rise" glow-opacity="0.6"/>\n <slide id="cover" layout="cover" transition="fade" glow="top-right" glow-seed="launch">\n <h1>Retry policy</h1>\n </slide>\n</deck>\n```\n\n| `<theme>` attribute | Values | Paper |\n| ----------------------------- | ------------------------------------------------------------ | ------------------------------- |\n| `paper`, `surface` | the slide\'s background, and that of code and cards | |\n| `ink`, `ink-2`, `ink-3` | text, secondary text, labels | |\n| `accent`, `on-accent`, `info` | the accent colour, text on it, and the second accent | |\n| `rule`, `rule-strong` | hairlines | |\n| `font`, `font-mono` | font families | |\n| `transition` | `view`, `fade-out`, `fade`, `slide-left`, `slide-up`, `none` | `view` |\n| `transition-duration` | a time | `500ms` |\n| `transition-blur` | a length | `5px` |\n| `fragment` | `blur`, `fade`, `rise` | `blur` |\n| `fragment-duration` | a time | `500ms` |\n| `fragment-blur` | a length | `3px` |\n| `glow` | `on`, `off` | `on` |\n| `glow-1`, `glow-2`, `glow-3` | colours of the three shapes | `#9440e3`, `#41d1ff`, `#dce354` |\n| `glow-fade` | the colour each shape fades to | `rgb(255 255 255 / 0.1)` |\n| `glow-opacity` | 0 to 1 | `1` |\n| `glow-blur` | a length | `70px` |\n| `glow-drift` | how long the glow takes to move to the next slide\'s place | `2500ms` |\n| `glow-hue` | an angle | `0deg` |\n| `glow-at` | a glow place | `full` |\n\nTransitions:\n\n- `view`: the slide fades out, then the next fades in, both blurred; blocks with the same `morph` on both slides move and resize between them.\n- `fade-out`: the same fade out then in, without moving blocks.\n- `fade`: both slides cross-fade.\n- `slide-left`, `slide-up`: the next slide pushes in from the right or from below; going back reverses it.\n- `none`: the slide changes at once.\n\nSteps: `blur` fades a step in from a blur, `rise` also lifts it 12px, `fade` only fades it.\n\nOn a `<slide>`:\n\n- `transition`: the transition into this slide, one of the values above.\n- `glow`: where this slide\'s glow sits: `full`, `top`, `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`, or `none` for no glow. Left out, the place follows the layout and changes from slide to slide.\n- `glow-seed`: any text; the same seed on the same page number always gives the same shapes.\n- `glow-opacity`: 0 to 1, this slide only.\n- `glow-hue`: degrees, this slide only.\n\n`check` reports an unknown transition or glow place and a `morph` name used twice in one slide. With reduced motion, turns are instant and the glow does not move.\n\n## Placing blocks freely\n\nA layout arranges a slide for you. When a slide must sit exactly as drawn, put `free="true"` on it: every block it holds, inside a `<col>` too, then takes `x`, `y` and `w` in slide pixels of the 1280×720 canvas, and `h` when its height matters (pictures, embeds, diagrams). The layout stays named, so its type sizes still apply, and removing `free` with the coordinates brings the layout back. A block on a free slide without `x`, `y` and `w` is reported, and so are coordinates on a slide that is not free. Later blocks sit on top of earlier ones.\n\n```xml\n<slide id="library" layout="two-cols" free="true">\n <h2 id="b4k2qz" x="96" y="80" w="520">The library</h2>\n <col>\n <p x="96" y="180" w="420" align="center" color="muted">Every artifact, one server.</p>\n </col>\n <col>\n <img x="640" y="120" w="560" h="380" src="assets/library.png" alt="The library page" frame="true"/>\n </col>\n</slide>\n```\n\n- `align="left|center|right|justify"` and `color` work on text blocks on any slide. `color` takes a theme colour, `ink|muted|faint|accent|info`, which follows the theme and its light and dark appearances, or a fixed `#RRGGBB` / `#RRGGBBAA`, which does not. Prefer the theme colours.\n- On a free slide, `w="fill"` stretches a block from its `x` to the right safe margin, and a text block may take `h`: what does not fit is clipped, unless the block also has `fit="shrink"`, which shrinks its text until it fits.\n\n### Look attributes\n\nYour human partner tunes blocks in the viewer\'s tweak panel. Each setting is one attribute on the block, on any slide; `check` reports a value outside its range and an attribute on a block that does not take it.\n\n| Attribute | Blocks | Value |\n| --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- |\n| `size="32"` | text | font size, 8–400 px |\n| `weight="600"` | text | 100–900 in steps of 100 |\n| `font="Avenir Next"` | text | `mono` or a font name; a font missing on another machine falls back to the theme font |\n| `leading="1.4"` | text | line height, 0.8–3 |\n| `tracking="-0.5"` | text | letter spacing, -20–100 px |\n| `pad="16"` | text, table, codeblock, code, alert, big, fact | padding, 0–200 px |\n| `fill="surface"` | all but hr, icon and html | a theme colour (`surface`, `paper`, `ink`, `muted`, `faint`, `accent`, `info`) or hex |\n| `opacity="80"` | all but html | 0–100 |\n| `radius="12"` | all but hr, icon and html | 0–360 px |\n| `border="solid"` | all but hr, icon and html | `solid`, `dashed` or `dotted`, 1 px in the theme\'s rule colour |\n| `shadow="0 8 24 #00000040"` | all but hr, icon and html | x, y, blur in px and a colour |\n\n```xml\n<slide id="promise" free="true">\n <p x="96" y="180" w="fill" h="120" fit="shrink" size="32" weight="600" fill="surface" radius="12" pad="16">Every artifact, one server.</p>\n</slide>\n```\n\nThese are deliberate choices: keep these attributes when you rewrite a block, unless changing them is the point.\n\n- An `id` on a block (letters, digits, `_` and `-`, at most 32) is how the viewer and comments know that block again. Your human partner\'s edits give blocks ids: keep every block id when you rewrite a slide, as you keep slide ids.\n\n## Rules\n\n- A talk is given offline: keep fonts, scripts and images inside the artifact directory and avoid CDNs.\n- Notes are not secret: they are hidden from viewers in the interface but remain in the page source.\n- Your human partner can edit notes in the viewer. Saving writes that slide\'s `<notes>` back as plain text lines joined by `<br/>`, replacing any markup inside it, in the file the slide is written in.\n- Keep the whole artifact under 20 MB.\n- Your human partner can edit slides in the viewer: select blocks, drag and resize them (which makes a slide `free="true"`), type into them, change their tag, alignment, colour and every look attribute, restack blocks, change a slide\'s layout, add text boxes, copy, paste and delete. Each edit rewrites the slide in `deck.xml` or its include file in place and is listed by `changes`. Re-read the file before every edit. When you write over one of their edits before you have read it, `check` warns with `W_HUMAN_EDIT_OVERWRITTEN`, naming the slide, the block and what they had set: put their edit back unless you meant to change it.\n- Your human partner can restructure the deck in the viewer\'s grid: reorder and duplicate slides, skip them, add placeholder slides, delete them, and create, rename or move groups. Each change rewrites `deck.xml` (and an include file, for a slide written there) in place, keeping the rest of the text as it was. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact slides/<id>` and read them before editing the deck, so you build on their order instead of writing it back.\n\n## Feedback\n\nComments are anchored to a slide, usually to a point on it. `comment list --sections threads --detail` shows the slide id, its title, the text under the pin and the message. A comment made on selected blocks lists them as `nodes`, each with its block (`#id`, or its position on the slide) and its text: change those blocks. Edit that slide, keep its id, run `check`, then reply with what changed. A comment whose slide was deleted is listed as an orphan.\n\nRun the returned Check command after every edit. Without a browser it reports XML that does not parse, tags, attributes and values the deck cannot take, files it cannot read, missing or duplicate ids, unknown layouts, missing assets and embeds whose target is not there, each naming its slide. Slides that overflow and code, diagram or formula errors come from the browser: with no browser open the result is pending, not clean.\n';const T_=[`default`,`cover`,`section`,`statement`,`two-cols`,`image`,`quote`,`fact`,`code`,`end`,`none`],E_=/^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/,D_=e=>{let t=e.trim();return t===`all`||t===`hide`?t:null};function O_(e){let t=[];for(let n of e.split(`|`)){let e=D_(n);if(e){t.push(e);continue}let r=/* @__PURE__ */ new Set;for(let e of n.split(`,`)){let t=E_.exec(e);if(!t)continue;let n=Number(t[1]),i=t[2]===void 0?n:Number(t[2]),a=Math.max(n,i);for(let e=Math.max(1,Math.min(n,i));e<=a&&!(r.size>=2e3);e++)r.add(e)}r.size&&t.push([...r].sort((e,t)=>e-t))}return t}const k_=e=>e.split(`|`).every(e=>D_(e)!==null||e.split(`,`).every(e=>{let t=E_.exec(e);return t!==null&&Number(t[1])>=1&&Number(t[2]??1)>=1})),A_=[`view`,`fade-out`,`fade`,`slide-left`,`slide-up`,`none`],j_=[`full`,`top`,`bottom`,`left`,`right`,`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`,`none`],M_=e=>A_.includes(e),N_=e=>j_.includes(e),P_=/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i;function F_(e){let t=e?.trim();return!t||P_.test(t)?null:t.split(/[?#]/)[0]||null}const I_=/^[a-z0-9][a-z0-9-]*$/,L_=`((?:"[^"]*"|'[^']*'|[^'">])*)`,R_=RegExp(`<!--[\\s\\S]*?(?:-->|$)|<(script|style|textarea|template|title)\\b${L_}>([\\s\\S]*?)(?:<\\/\\1\\s*>|$)|<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)${L_}>`,`gi`),z_=/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,B_=/reveal(?:\.min)?(?:\.esm)?\.m?js(?:[?#]|$)/i,V_={lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,amp:`&`};function H_(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(z_)){let e=n[1].toLowerCase();t.has(e)||t.set(e,n[2]??n[3]??n[4]??``)}return t}function U_(e){return e.replaceAll(/<[^>]*>/g,``).replaceAll(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi,(e,t,n,r)=>t?String.fromCodePoint(Number(t)):n?String.fromCodePoint(Number.parseInt(n,16)):V_[String(r).toLowerCase()]??e).replaceAll(/\s+/g,` `).trim().slice(0,200)}function W_(e){let t=e.toLowerCase(),n=[],r=[],i=null,a=null,o=!1,s=!1,c=0,l=/* @__PURE__ */ new Set,u=e=>{let t=F_(e);t&&l.add(t)},d=e=>{for(let t=n.length-1;t>=0;t--)if(n[t].tag===e){for(let e of n.splice(t))e.kind===`slide`&&(i=null),e.kind===`notes`&&--c;return}};R_.lastIndex=0;for(let l=R_.exec(e);l;l=R_.exec(e)){let[,f,p=``,m=``,h,g,_=``]=l;if(f){let e=f.toLowerCase();e===`title`&&!i&&a===null&&(a=U_(m)||null);let t=e===`script`?H_(p).get(`src`):void 0;u(t),e===`script`&&(B_.test(t??``)||m.includes(`Reveal.initialize`))&&(s=!0);let r=n.at(-1);e===`template`&&i&&!c&&r?.kind===`magic`&&(r.templates=(r.templates??0)+1,r.templates>1&&(i.steps+=1));continue}if(!g)continue;let v=g.toLowerCase();if(h){(v===`div`||v===`section`||v===`aside`)&&d(v);continue}let y=H_(_);u(y.get(`src`)),v===`link`&&u(y.get(`href`));let b=(y.get(`class`)??``).split(/\s+/).filter(Boolean),x=n.at(-1)?.kind;if(i&&!c){let n=y.get(`data-morph`)?.trim();if(n&&(i.morphs.has(n)&&!i.morphRepeats.includes(n)&&i.morphRepeats.push(n),i.morphs.add(n)),b.includes(`fragment`)){let e=y.get(`data-fragment-index`);e!==void 0&&i.positions.has(e)||(i.steps+=1),e!==void 0&&i.positions.add(e)}if(v===`code`&&(i.steps+=Math.max(0,O_(y.get(`data-lines`)??``).length-1)),!i.titled&&/^h[1-3]$/.test(v)){let n=t.indexOf(`</${v}`,R_.lastIndex);i.title=U_(e.slice(R_.lastIndex,n===-1?void 0:n)),i.titled=!0}}if(v===`div`){let e=`other`;!o&&x===`reveal`&&b.includes(`slides`)?(e=`slides`,o=!0):!o&&b.includes(`reveal`)?e=`reveal`:i&&b.includes(`magic-move`)&&(e=`magic`),n.push({tag:v,kind:e})}else if(v===`section`){if(x===`slides`){let e=b.find(e=>e.startsWith(`l-`)),t=e?e.slice(2):`default`;i={id:y.get(`id`)||null,layout:t,title:``,steps:0,notes:!1,nested:!1,titled:!1,unknownLayout:T_.includes(t)?null:t,transition:y.get(`data-transition`)?.trim()??null,glow:y.get(`data-glow`)?.trim()??null,morphs:/* @__PURE__ */ new Set,morphRepeats:[],positions:/* @__PURE__ */ new Set,...y.has(`data-deck-hidden`)?{hidden:!0}:{},...y.get(`data-deck-group`)?{group:y.get(`data-deck-group`)}:{}},r.push(i),n.push({tag:v,kind:`slide`})}else i&&(i.nested=!0),n.push({tag:v,kind:`other`})}else if(v===`aside`){let e=i!==null&&b.includes(`notes`);e&&(i.notes=!0,c+=1),n.push({tag:v,kind:e?`notes`:`other`})}}let f=[],p=/* @__PURE__ */ new Set,m=r.map(({nested:e,titled:t,unknownLayout:n,transition:r,glow:i,morphs:a,morphRepeats:o,positions:s,...c},l)=>{let u=c.id??void 0;c.id?I_.test(c.id)?p.has(c.id)&&f.push({code:`duplicate_id`,slide:l,id:u}):f.push({code:`invalid_id`,slide:l,id:u}):f.push({code:`missing_id`,slide:l}),c.id&&p.add(c.id),e&&f.push({code:`nested_slide`,slide:l,...u?{id:u}:{}}),n&&f.push({code:`unknown_layout`,slide:l,...u?{id:u}:{},detail:n});let d={slide:l,...u?{id:u}:{}};r!==null&&!M_(r)&&f.push({code:`unknown_transition`,...d,detail:r}),i!==null&&!N_(i)&&f.push({code:`unknown_glow`,...d,detail:i});for(let e of o)f.push({code:`duplicate_morph`,...d,detail:e});return c});return s&&f.push({code:`own_reveal`,slide:-1}),{complete:/<\/html\s*>\s*$/i.test(e),hasDeck:o,title:a,slides:m,issues:f,assets:[...l]}}const G_=new Map(Object.entries({lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`,nbsp:`\xA0`,mdash:`—`,ndash:`–`,hellip:`…`,rarr:`→`,larr:`←`,uarr:`↑`,darr:`↓`,harr:`↔`,copy:`©`,reg:`®`,trade:`™`,times:`×`,divide:`÷`,middot:`·`,bull:`•`,laquo:`«`,raquo:`»`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`,deg:`°`,plusmn:`±`,le:`≤`,ge:`≥`,ne:`≠`,euro:`€`,pound:`£`,yen:`¥`})),K_=/[A-Za-z_][\w.-]*/y,q_=/\s*/y,J_=e=>`name`in e;function Y_(e,t){return e.replaceAll(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]*));/g,(e,n,r,i,a)=>{let o=n?Number(n):r?Number.parseInt(r,16):null;if(o!==null)return o>0&&o<=1114111?String.fromCodePoint(o):e;let s=G_.get(i);return s===void 0&&t?.(i,a),s??e})}function X_(e){return J_(e)?e.children.map(X_).join(``):e.text}function Z_(e){let t=[],n=null,r=t=>{if(!n){n=[];for(let t=e.indexOf(`
226
226
  `);t!==-1;t=e.indexOf(`
227
227
  `,t+1))n.push(t)}let r=0,i=n.length;for(;r<i;){let e=r+i>>1;n[e]<t?r=e+1:i=e}return r+1},i=(e,n)=>t.push({line:r(e),message:n}),a=[],o=[],s=()=>o.at(-1)?.children??a,c=/* @__PURE__ */ new Set,l=e=>(t,n)=>{c.has(t)||(c.add(t),i(e+n,`&${t}; is not an entity a deck knows: write the character itself, or &amp; for a plain &`))},u=(t,n,r)=>{if(n<=t)return;let a=e.slice(t,n),o=r?-1:a.indexOf(`]]>`);o!==-1&&i(t+o,`a ]]> outside CDATA: the section before it ended early. Split it as ]]]]><![CDATA[> or take the code from a file`),s().push({start:t,end:n,cdata:r,text:r?a:Y_(a,l(t))})},d=0;for(;d<e.length;){let n=e.indexOf(`<`,d);if(n===-1){u(d,e.length,!1);break}if(u(d,n,!1),e.startsWith(`<!--`,n)){let t=e.indexOf(`-->`,n+4);if(t===-1){i(n,`a comment is never closed with -->`);break}d=t+3;continue}if(e.startsWith(`<![CDATA[`,n)){let t=e.indexOf(`]]>`,n+9);if(t===-1){i(n,`a CDATA section is never closed with ]]>`);break}u(n+9,t,!0),d=t+3;continue}if(e.startsWith(`<?`,n)||e.startsWith(`<!`,n)){let t=e.indexOf(`>`,n);d=t===-1?e.length:t+1;continue}if(e[n+1]===`/`){K_.lastIndex=n+2;let t=K_.exec(e)?.[0],r=e.indexOf(`>`,n);if(!t||r===-1){i(n,`a closing tag is not finished`);break}d=r+1;let a=o.length-1;for(;a>=0&&o[a].name!==t;)--a;if(a===-1&&o.length===0){i(n,`</${t}> closes nothing that is open`);continue}a!==o.length-1&&i(n,`</${t}> closes <${o.at(-1).name}>, which is still open`);for(let e of o.splice(a===-1?o.length-1:a))e.innerEnd=n,e.end=d;continue}K_.lastIndex=n+1;let a=K_.exec(e)?.[0];if(!a){i(n,`a "<" that starts no tag: write &lt; or use CDATA`),d=n+1;continue}let c=/* @__PURE__ */ new Map,f=n+1+a.length,p=!1,m=!1;for(;f<e.length;){if(q_.lastIndex=f,f+=q_.exec(e)[0].length,e[f]===`>`){f+=1,m=!0;break}if(e.startsWith(`/>`,f)){f+=2,p=!0,m=!0;break}K_.lastIndex=f;let t=K_.exec(e)?.[0],n=t?e[f+t.length+1]:void 0;if(!t||e[f+t.length]!==`=`||n!==`"`&&n!==`'`){i(f,`<${a}> has an attribute that is not name="value"`);break}let r=f+t.length+2,o=e.indexOf(n,r);if(o===-1){i(f,`<${a}> has an attribute value that is never closed`);break}c.has(t)||c.set(t,Y_(e.slice(r,o),l(r))),f=o+1}if(!m){let r=e.indexOf(`>`,f);if((t.length===0||r===-1)&&i(n,`<${a}> is not finished`),r===-1)break;f=r+1}let h={name:a,attrs:c,children:[],start:n,end:f,innerStart:f,innerEnd:f,line:r(n),selfClosing:p};if(s().push(h),d=f,!p){if(o.length>=100){i(n,`elements are nested more than 100 deep`);break}o.push(h)}}let f=t.length>0&&d<e.length;for(let t of o)f||i(t.start,`<${t.name}> is never closed`),t.innerEnd=e.length,t.end=e.length;let p=a.filter(J_),m=a.find(e=>!J_(e)&&e.text.trim()!==``);return p.length>1?i(p[1].start,`only one root element is allowed`):m&&i(m.start,`text outside the root element`),{root:p[0]??null,errors:t}}const Q_=/* @__PURE__ */ `h1.h2.h3.p.blockquote.ul.ol.table.img.icon.alert.hr.codeblock.code.magic.mermaid.math.chart.embed.html.kicker.subtitle.label.quote.cite.big.fact`.split(`.`),$_=[`h1`,`h2`,`h3`,`p`,`blockquote`,`ul`,`ol`,`kicker`,`subtitle`,`label`,`quote`,`cite`],ev=[`ink`,`muted`,`faint`,`accent`,`info`],tv=[`left`,`center`,`right`],nv=[`x`,`y`,`w`,`h`],rv=/^[A-Za-z0-9_-]{1,32}$/,iv=e=>Q_.includes(e);function av(e){let t=/* @__PURE__ */ new Map;return e.children.filter(J_).forEach((e,n)=>{e.name===`col`?e.children.filter(J_).forEach((e,r)=>{iv(e.name)&&t.set(e,`${n}.${r}`)}):iv(e.name)&&t.set(e,String(n))}),t}const ov=ev,sv=[`surface`,`paper`,`ink`,`muted`,`faint`,`accent`,`info`],cv=[`solid`,`dashed`,`dotted`],lv=[...tv,`justify`],uv={ink:`ink`,muted:`ink-2`,faint:`ink-3`,accent:`accent`,info:`info`,surface:`surface`,paper:`paper`},dv=e=>`var(--deck-${uv[e]??e})`,fv=[`img`,`embed`,`chart`,`mermaid`,`math`,`magic`],pv=[`table`,`codeblock`,`code`,`alert`,`big`,`fact`],mv=[`hr`,`icon`],hv=[`fill`,`opacity`,`radius`,`border`,`shadow`],gv=[`font`,`weight`,`size`,`leading`,`tracking`,`fit`];function _v(e){return $_.includes(e)?[`pad`,...gv,`align`,`color`,...hv]:fv.includes(e)?[...hv]:pv.includes(e)?[`pad`,...hv]:mv.includes(e)?[`opacity`]:[]}const vv=/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i,yv=/^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,63}$/u,bv=(e,t,n)=>/^-?\d+$/.test(e)&&Number(e)>=t&&Number(e)<=n,xv=(e,t,n,r)=>RegExp(`^-?\\d+(?:\\.\\d{1,${r}})?$`).test(e)&&Number(e)>=t&&Number(e)<=n,Sv=(e,t)=>t.includes(e)||vv.test(e);function Cv(e){let t=e.split(` `);if(t.length!==4)return null;let[n,r,i,a]=t;return bv(n,-200,200)&&bv(r,-200,200)&&bv(i,0,200)&&Sv(a,sv)?[n,r,i,a]:null}const wv={pad:[e=>bv(e,0,200),`must be whole pixels from 0 to 200`],font:[e=>e===`mono`||yv.test(e),`must be mono or a font name: letters, digits, spaces, - _ . (at most 64)`],weight:[e=>bv(e,100,900)&&Number(e)%100==0,`must be 100, 200 … 900`],size:[e=>bv(e,8,400),`must be whole pixels from 8 to 400`],leading:[e=>xv(e,.8,3,2),`must be 0.8 to 3, at most two decimals`],tracking:[e=>xv(e,-20,100,1),`must be -20 to 100 pixels, at most one decimal`],fit:[e=>e===`shrink`,`must be shrink`],fill:[e=>Sv(e,sv),`must be #RRGGBB, #RRGGBBAA or ${sv.join(`, `)}`],opacity:[e=>bv(e,0,100),`must be 0 to 100`],radius:[e=>bv(e,0,360),`must be whole pixels from 0 to 360`],border:[e=>cv.includes(e),`must be ${cv.join(`, `)}`],shadow:[e=>Cv(e)!==null,`must be "x y blur colour": x and y -200 to 200, blur 0 to 200`],align:[e=>lv.includes(e),`must be ${lv.join(`, `)}`],color:[e=>Sv(e,ov),`must be #RRGGBB, #RRGGBBAA or a theme colour: ${ov.join(`, `)}`]};function Tv(e,t,n){let r=Object.hasOwn(wv,t)?wv[t]:void 0;return r?_v(e).includes(t)?r[0](n)?null:`${t}="${n}" ${r[1]}`:`<${e}> takes no ${t}`:`${t} is not a look attribute`}const Ev=e=>vv.test(e)?e:dv(e);function Dv(e,t){switch(e){case`pad`:return[[`padding`,`${t}px`]];case`font`:return[[`font-family`,t===`mono`?`var(--deck-font-mono)`:`"${t}", var(--deck-font)`]];case`weight`:return[[`font-weight`,t]];case`size`:return[[`font-size`,`${t}px`]];case`leading`:return[[`line-height`,t]];case`tracking`:return[[`letter-spacing`,`${t}px`]];case`fill`:return[[`background-color`,Ev(t)]];case`opacity`:return[[`opacity`,String(Number(t)/100)]];case`radius`:return[[`border-radius`,`${t}px`]];case`border`:return[[`border`,`1px ${t} var(--deck-rule-strong)`]];case`shadow`:{let e=Cv(t);if(!e)return[];let[n,r,i,a]=e;return[[`box-shadow`,`${n}px ${r}px ${i}px ${Ev(a)}`]]}case`color`:return[[`color`,Ev(t)]];case`align`:return[[`text-align`,t]];default:return[]}}const Ov={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},kv=/^[1-9]\d?$/,Av=(e,t)=>e.name===`col`||(e.name===`ul`||e.name===`ol`)&&t.name===`li`||e.name===`table`&&t.name===`tr`&&t.children.some(e=>J_(e)&&e.name===`td`);function jv(e){return e.name===`codeblock`?Math.max(0,O_(e.attrs.get(`lines`)??``).length-1):e.name===`magic`?Math.max(0,e.children.filter(e=>J_(e)&&e.name===`step`).length-1):0}function Mv(e){let t=/* @__PURE__ */ new Set,n=e=>{let r=e.attrs.get(`step`)??``;kv.test(r)&&t.add(Number(r)-1);for(let t of e.children)J_(t)&&n(t)};return n(e),t}function Nv(e,t){let n={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},r=Mv(e),i=0,a=null,o=()=>{for(;r.has(i);)i+=1;return i+=1,i-1},s=(e,r)=>{if(e.name===`notes`)return;let c=e.attrs.get(`step`)??(r?`true`:`false`),l=null;c===`true`?l=o():c===`with`?(n.explicit=!0,a===null?t.bad(e,`step`,`has no step before it to appear with`):l=a):kv.test(c)?(n.explicit=!0,l=Number(c)-1):c!==`false`&&t.bad(e,`step`,`must be true, with, or a step number from 1`),l!==null&&(n.index.set(e,l),a=l);let u=jv(e);if(u>0){n.from.set(e,o());for(let e=1;e<u;e+=1)o();a=i-1}if(e.name===`codeblock`||e.name===`magic`)return;let d=e.attrs.get(`steps`);d!==void 0&&d!==`true`&&d!==`false`&&t.bad(e,`steps`,`must be true or false`);for(let t of e.children)J_(t)&&s(t,d===`true`&&Av(e,t))};for(let t of e.children)J_(t)&&s(t,!1);return n}const Pv=/^[a-z0-9-]{1,16}$/,Fv=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,Iv={readFile:(e,t)=>({error:`${t} cannot be read here`})},Lv=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`);function Rv(e){let t=e.filter(([e,t])=>e===`style`&&t!==!0);if(t.length<2)return e;let n=t.map(([,e])=>e).join(`;`),r=e.findIndex(([e])=>e===`style`);return e.flatMap((e,t)=>e[0]===`style`?t===r?[[`style`,n]]:[]:[e])}function zv(e,{classes:t,attrs:n},r){return`<${[e,...r===void 0?[]:[`id="${Lv(r)}"`],...t.length?[`class="${t.join(` `)}"`]:[],...Rv(n).map(([e,t])=>t===!0?e:`${e}="${Lv(t)}"`)].join(` `)}>`}const Bv=/^[a-z0-9][a-z0-9-]*$/;var Vv=class{env;audience;sources;deps=[];embeds=[];issues=[];refs=[];warnings=[];id;free=!1;placed=/* @__PURE__ */ new Map;blockIds=/* @__PURE__ */ new Set;slide=-1;steps=Ov;constructor(e,t=!1,n=!1){this.env=e,this.audience=t,this.sources=n}issue(e,t,n){return{code:e,slide:this.slide,...this.id?{id:this.id}:{},...n?{tag:n}:{},detail:t}}report(e,t,n){this.issues.push(this.issue(e,t,n))}warn(e,t,n){this.warnings.push(this.issue(e,t,n))}read(e,t,n){let r=this.env.readFile(e,t);if(typeof r!=`string`)return this.report(`file`,r.error,n.name),null;let i=`${e}:${t}`;return this.deps.includes(i)||this.deps.push(i),r}bad(e,t,n){this.report(`bad_value`,`${t}="${e.attrs.get(t)??``}" ${n}`,e.name)}flag(e,t){let n=e.attrs.get(t);return n===void 0||n===`false`?!1:n===`true`||(this.bad(e,t,`must be true or false`),!1)}decor(e,t=[]){let n=this.attrs(e,[...t,`morph`,`step`,...this.blockAttrs(e)]),r=this.plain(e),i=this.steps.index.get(e);i!==void 0&&(r.classes.push(`fragment`),this.steps.explicit&&r.attrs.push([`data-fragment-index`,String(i)]));let a=e.attrs.get(`step`);this.sources&&a!==void 0&&Pv.test(a)&&r.attrs.push([`data-deck-step`,a]);let o=n.get(`morph`);return o!==void 0&&(Bv.test(o)?r.attrs.push([`data-morph`,o]):this.bad(e,`morph`,`must be lowercase letters, digits and hyphens`)),r}blockAttrs(e){return this.placed.has(e)?[`id`,...nv,..._v(e.name)]:[]}plain(e){let t={classes:[],attrs:[]},n=this.placed.get(e);if(n===void 0)return t;this.id&&this.sources&&t.attrs.push([`data-deck-src`,`${this.id}:${n}`],[`data-deck-tag`,e.name]);let r=e.attrs.get(`id`);r!==void 0&&(rv.test(r)?this.blockIds.has(r)?this.report(`bad_value`,`id="${r}" is used by another block on this slide`,e.name):(this.blockIds.add(r),this.sources&&t.attrs.push([`data-deck-id`,r])):this.bad(e,`id`,`must be letters, digits, _ and -, at most 32`));let i=this.place(e,t),a={},o=t.attrs.some(([e])=>e===`data-deck-placed`);for(let t of[`w`,`h`]){let n=e.attrs.get(t);o&&n!==void 0&&(t===`h`||n===`fill`)&&(a[t]=n)}o&&a.h!==void 0&&$_.includes(e.name)&&i.push(`overflow:hidden`);for(let n of _v(e.name)){let r=e.attrs.get(n);if(r===void 0)continue;let o=Tv(e.name,n,r);o?this.report(`bad_value`,o,e.name):n===`fit`&&!e.attrs.has(`h`)?this.report(`bad_value`,`fit="shrink" needs h on a free="true" slide`,e.name):(a[n]=r,n===`align`?t.attrs.push([`data-align`,r]):n===`color`&&ev.includes(r)?t.attrs.push([`data-color`,r]):n===`fit`?t.attrs.push([`data-deck-fit`,r]):i.push(...Dv(n,r).map(([e,t])=>`${e}:${t}`)))}return i.length&&t.attrs.push([`style`,i.join(`;`)]),this.sources&&Object.keys(a).length&&t.attrs.push([`data-deck-look`,JSON.stringify(a)]),t}place(e,t){let n=nv.filter(t=>e.attrs.has(t));if(!this.free)return n.length&&this.report(`bad_value`,`${n.join(`, `)} only work on a slide with free="true"`,e.name),[];if(![`x`,`y`,`w`].every(t=>e.attrs.has(t)))return this.report(`misplaced`,`<${e.name}> on a free="true" slide needs x, y and w`,e.name),[];let r={},i=!0;for(let t of n){let n=e.attrs.get(t);if(t===`w`&&n===`fill`)continue;let a=Number(n),o=t===`w`||t===`h`;!/^-?\d+$/.test(n)||Math.abs(a)>4e3||o&&a<=0?(this.bad(e,t,o?`must be a whole number of pixels above 0`:`must be a whole number of pixels`),i=!1):r[t]=a}if(!i)return[];let a=r.w??Math.max(1,1184-r.x),o=[`left:${r.x}px`,`top:${r.y}px`,`width:${a}px`];return r.h!==void 0&&o.push(`height:${r.h}px`),t.attrs.push([`data-deck-placed`,!0]),o}attrs(e,t){for(let n of e.attrs.keys())t.includes(n)||this.report(`unknown_attr`,n,e.name);return e.attrs}};const Hv=/^([^#]+?)(?:#L(\d+)(?:-(\d+))?)?$/,Uv=/<\/?(?:section|html|body|head)\b|<!doctype/i,Wv=/<(\/?)div\b/gi;function Gv(e,t){let n=e.attrs.get(`src`).trim(),r=Hv.exec(n);if(!r)return t.bad(e,`src`,`must be a path, optionally followed by #L10 or #L10-24`),null;let[,i,a,o]=r,s=t.read(`project`,i,e);if(s===null)return null;let c=s.replaceAll(`\r
228
228
  `,`
@@ -767,7 +767,7 @@ if (ffmpeg.status !== 0) {
767
767
  process.exit(1);
768
768
  }
769
769
  console.log(JSON.stringify({ duration: pcm.length / 2 / RATE }));
770
- `];function QS(e){let t=f.default.join(e,`voice/voice.mjs`);return d.default.existsSync(t)?(ZS.includes(d.default.readFileSync(t,`utf8`))&&d.default.writeFileSync(t,XS),!1):(d.default.mkdirSync(f.default.dirname(t),{recursive:!0}),d.default.writeFileSync(t,XS,{flag:`wx`}),!0)}var $S='# Storyboard writing\n\nA storyboard plans a product demo video and plays it back before anything is recorded: shots in order, each with a duration, what happens on screen, and voiceover lines that are synthesized and spoken with captions. Write `storyboard.xml` under the returned artifact directory first, with no shot pictures at all: every shot without `src` plays as a title card, so your human partner can hear the pacing within minutes. Add moving pictures, recorded takes, music and sound effects afterwards. On this machine the hub opens a storyboard in an editor: a monitor, a bin and a multitrack timeline (captions, overlay, picture, voice, music, effects) where your human partner trims, splits, reorders, adds transitions, speed, keys and sounds, and exports the next cut.\n\nRe-read `storyboard.xml` and the shot pages immediately before each edit: your human partner edits the timeline, and the server writes those edits into the same file, and moving an overlay rewrites the times of `sb-cursor`, `sb-type` or `sb-clip` in the shot page. Patch only the shots and lines you mean to change and keep every id. Never edit `comments.json`, `audio/`, `cuts/` or `.state/`. Finish with `check`; lines still being voiced are pending, not done.\n\n```xml\n<storyboard title="Shared albums" aspect="16:9" lang="en" voice="Kore" target="10-15">\n <lexicon>\n <say word="Ryugi" as="Lyu-ghee" hint="lyu as in the Chinese name Liu, never an English r; hard g"/>\n </lexicon>\n <music id="bed" src="sound/bed.mp3" at="0" gain="-18" duck="-10" fade-in="1" fade-out="2"/>\n <shot id="hook" title="A wall of text" dur="4">\n <action>The terminal fills with a 300-line plan</action>\n <action>Cut away before anyone could read it</action>\n <line id="hook-1" at="0.4">Your agent wrote 300 lines. Now read them.</line>\n </shot>\n <shot id="sketch" title="Sketch it together" dur="8" src="shots/sketch.html" transition="dissolve" transition-dur="0.4">\n <action>You draw a box; the agent completes the flow</action>\n <key prop="scale" at="2" value="1"/>\n <key prop="scale" at="5" value="1.18" ease="in-out"/>\n <sfx id="click" src="sound/click.wav" at="2.6" gain="-6"/>\n <line id="sketch-1" caption="Sketch it together.">Sketch the structure together, right in the page.</line>\n </shot>\n</storyboard>\n```\n\n## Elements\n\n- `<storyboard>`: `title`; `aspect` is `16:9` (default), `9:16` or `1:1`; `lang`; `voice` is the voice name passed to the voice script; `target` is the intended length as a range of seconds (`"65-80"`), and a total outside it is a warning.\n- `<lexicon>` with `<say word="…" as="…" hint="…"/>`: pronunciations. Before synthesis every whole-word `word` is replaced by `as`; captions keep the original words. A respelling alone is often read wrong, so a line holding the word also tells the speech model that `as` is how `word` is said, followed by `hint` (optional: how it sounds, in plain words). Give every made-up or borrowed name a `hint`.\n- `<shot>`: `id`, `title`, `dur` (seconds, required, one decimal is fine). Optional `src` (a shot page under `shots/`), `take` (a recorded clip under `takes/`) and `take-in` (the second of the take to start from). A shot starts where the shots before it end; never write start times.\n- `<action>`: one thing that happens on screen, one sentence each. Title cards and the script column show them.\n- `<line>`: one voiceover line. `at` is seconds from the shot\'s start; without it the line follows the previous line by 0.3s (the first line starts 0.3s in). `caption` replaces the words shown on screen; without it the caption is the line itself. `gain` is its volume in dB (default 0).\n\nShot and line ids are lowercase letters, digits and hyphens, unique across the whole file; comments are anchored to them.\n\n## Tracks\n\nShots are the spine: everything below is optional, and a storyboard without it is a picture, voice and caption timeline. Times on a shot are seconds from its start on the timeline; music uses whole-video seconds.\n\n- On `<shot>`: `speed` (0.25 to 4, default 1) runs the page clock and the take faster or slower while `dur` stays its length on the timeline; voice, keys and effects are not sped up. `src-in` is the second of the shot page to start from. `transition` is `cut` (default), `dissolve` or `black`, centred on the seam before this shot and `transition-dur` seconds long (default 0.4, at most half the shorter shot); it never changes the total length. `gain` in dB plays a take\'s own sound, which is otherwise muted.\n- `<key prop="…" at="…" value="…" ease="…"/>` inside a shot animates the picture layer: `x` and `y` in design pixels, `scale` as a factor, `opacity` 0 to 1, and `gain` in dB for a take\'s sound. `ease` is `linear` (default), `in`, `out` or `in-out`, easing into that key. One key holds its value for the whole shot; captions do not move.\n- `<sfx id src at gain fade-in fade-out/>` inside a shot plays a sound effect `at` seconds into the shot.\n- `<music id src at from to gain duck fade-in fade-out>` at the top level plays a file from `at` seconds into the video, starting `from` seconds into the file and ending at `to` (default: the end of the video). `duck` lowers it by that many dB while a voice line plays (down in 0.2s, back in 0.4s). Gain `<key prop="gain">` elements inside it change its volume over time, in seconds from `at`.\n- On `<storyboard>`: `mute="music sfx"` silences any of `voice`, `music` and `sfx`, and `captions="off"` hides captions; both carry into the export.\n\nSound files live in `sound/` (mp3, wav, m4a or ogg). Put them there yourself, or your human partner drops them into the editor. `check` reports a track that names a file that is not there.\n\n## Voice\n\nEvery line is synthesized on its own by `voice/voice.mjs` in the artifact directory, which `start` copies from a template the first time and keeps up to date while it is unedited (OpenRouter text-to-speech; it reads `OPENROUTER_API_KEY` from the project\'s `.env` and needs ffmpeg). It reads `{text, voice, lang, out, direction?}` on stdin; `direction` carries the lexicon\'s pronunciations for that line. The hub runs it a second after `storyboard.xml` changes, only for lines whose words, voice or lexicon changed. Run `ryugi storyboard voice --artifact storyboard/<id>` to synthesize and print each line\'s length, then fit shot durations to the voice: `check` reports a voiced line that runs past its shot or overlaps the line before it. `--line <id>` voices one line; `--force` re-voices everything after you change the script.\n\n## Shot pages\n\nA shot page is plain HTML with CSS animations, drawn the way the product looks, laid out at 1920×1080 (1080×1920 for `aspect="9:16"`, 1080×1080 for `1:1`) and scaled to fit the player. Time 0 is the shot\'s start; the viewer pauses every animation and seeks it, so scrubbing and frame-by-frame capture show exactly the same frame. Animate only with CSS animations or the Web Animations API, never with `setTimeout`, `setInterval` or `requestAnimationFrame`, and give every animation a finite iteration count. Three elements cover what CSS cannot seek:\n\n- `<sb-clip src="../takes/raw.mp4" from="3.2" to="11.2" at="0.5">` plays part of a recorded video, muted, starting `at` seconds into the shot.\n- `<sb-cursor path="420,300@0 610,340@1.2 click@1.3 700,420@2.4">` moves a pointer through `x,y@seconds` points and ripples on each `click@seconds`.\n- `<sb-type at="2.3" cps="28">text</sb-type>` types its text from `at`, `cps` characters a second.\n\n`sb-cursor` covers the page, so its points are page pixels. Pages cannot reach the network; keep images under `assets/` and refer to them relatively. `check` warns about timers and endless animations, and counts a shot as not yet run until the viewer has shown it.\n\nThe page `…/storyboard/<id>/render` draws only the picture and captions, with transitions, speed and keys, exactly as the editor\'s monitor does (`?captions=0` drops captions, `?from=&to=` draws only that stretch). Its `window.ryugiStoryboard.seek(t)` resolves once that frame is painted, `duration` is the length in seconds, `audio()` lists every voiced line\'s file URL and start, and `mix()` lists every sound with its file, start, end, gain, fades, keys and duck, so any capture tool can step frame by frame and mix the sound in.\n\n## Takes, export and the cut\n\nPut recorded clips in `takes/` and name them with `take` on their shot; the shot then plays the clip under the voiceover, muted unless the shot has a `gain`, and its shot page and overlays are not drawn (put a clip in the page with `sb-clip` to draw over it).\n\nExport renders the timeline into the next cut on this machine. `start` copies an export script to `render/render.mjs` the first time; it drives Chrome over the DevTools protocol and ffmpeg, with no packages to install, renders each shot from the render page frame by frame, reuses shots that did not change, mixes voice, music and effects and writes 1080p H.264. The hub hands it the timeline as JSON on stdin and registers what it writes as the next cut, with a hash of every shot so the editor marks the shots that changed. Run `ryugi storyboard export --artifact storyboard/<id> [--wait]` to export from the command line; lines not yet voiced are voiced first. `ryugi storyboard template --artifact storyboard/<id> --force` replaces `render/render.mjs` with the latest template; without `--force` a script you changed is kept. A project can replace the script with its own kit that reads the same JSON.\n\nWhen a finished video comes from somewhere else, register it with `ryugi storyboard cut --artifact storyboard/<id> --file <1080p.mp4> [--map <map.json>] [--master <4k.mp4>]`. Without `--map` each shot\'s range comes from the storyboard\'s current durations; pass a map (`{"shots":[{"id":"hook","start":0,"end":4.2}]}`) when the cut\'s timing differs. Encode the cut as H.264 1080p at about 1.5 Mbps so it fits the Cloud allowance.\n\n## Comments and references\n\nRead feedback with `comment list`. Comments are anchored to a shot, a line, a moment of a shot (`--at <seconds>`) or a moment of a cut (`--cut <n> --at <seconds>`), which maps to its shot; `comment list` names each thread\'s shot, moment or line, and for an area marked on a recorded take or the cut, the path of its crop. A thread whose shot was deleted stays, marked `shot deleted`. Your human partner can reorder, trim, split and join shots, rewrite titles, actions and voice lines, add, duplicate or delete shots, and set transitions, speed, keys, sounds and mutes in the editor; each edit rewrites only its part of `storyboard.xml`. A split gives the second half the id `<id>-b` and leaves its comments on the first half. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact storyboard/<id>` and read them before editing the file, so you build on their version instead of writing it back. A document or deck links a shot with `<ref storyboard="<id>" shot="<shot-id>"/>`.\n';function eC(e){if(!e.shot&&!e.cut)throw new M(`comment add on a storyboard needs --shot <shotId>, or --cut <n> --at <seconds>`);if(e.line&&e.at!==void 0)throw new M(`comment add takes --line or --at, not both`);let t=er(e.at,`--at`);if(t!==void 0&&t<0)throw new M(`--at must be seconds from 0`);let n;if(e.cut!==void 0){if(n=Number(e.cut),!Number.isInteger(n)||n<1)throw new M(`--cut must be a cut number from 1`);if(t===void 0)throw new M(`a comment on a cut needs --at <seconds>`);if(e.line)throw new M(`comment add takes --line or --cut, not both`)}return{op:`add`,...e.shot?{shot:e.shot}:{},...e.line?{line:e.line}:{},...n===void 0?{}:{cut:n},...t===void 0?{}:{at:t},text:$n(e)}}const tC={authoring:$S,changes:!0,review:{sections:[]},commentActions:{add:eC},onStart:e=>{QS(e),YS(e)}};var nC='# Verify report writing\n\nWrite `verify.xml` and captured files in `evidence/`. Reports cover command output, counts, API behavior, deploy evidence and evals. Claims judged by looking at a screen go in artboard verify groups; reference those groups from the report. Never invent captured output or human verdicts. Report prose uses the human\'s language; IDs/commands/raw logs retain their form.\n\n```xml\n<verify title="Delivery survives reconnect">\n <p>Verified against local build.</p>\n <claim id="delivery" judge="agent" from="local build @ COMMIT" capturedAt="2026-11-13T10:00:00Z">\n <title>Three attempts preserve the delivery</title>\n <result><code>3</code> attempts, <code>1</code> delivery kept</result>\n <table>\n <tr><th>Measured</th><th>Got</th><th>Expected</th></tr>\n <tr><td>Attempts</td><td><code>3</code></td><td>3</td></tr>\n <tr><td>Deliveries kept</td><td><code>1</code></td><td>1</td></tr>\n </table>\n <output src="evidence/delivery.txt"/>\n </claim>\n <gap id="production"><title>Production run</title><why>No production credentials</why><needs>A test key</needs></gap>\n</verify>\n```\n\nRequired report title; optional one introductory p first; only claim/gap/ref after it, no top-level headings. The page reads as one column: a status line, then what waits on the human (gaps, rejected and pending claims), then the agent\'s checks one line each, grouped by environment. Claim needs unique stable id, judge, title and evidence. `from` identifies actual environment/build; capturedAt is the real ISO capture time, not a future/example timestamp. Update both with replaced evidence. Capture command output directly to evidence/*.txt and never edit it. `output src="evidence/…"` keeps it one click away; no HTML output files. Over 200,000 characters is explicitly truncated.\n\nEvery agent claim has one `<result>`: inline, one line, what it proved (`<result><code>897 passed (897)</code></result>`); it is the claim\'s whole line on the page, and Check notes an agent claim without one. Its `code` values follow the copied-value rule below. Claims from the same environment and build use the identical `from` string: the page groups checks by exact `from` and writes it once per group. Above the output, write the result for the person reading: nobody should have to read a log to see what it proved. A claim may hold p, ul/ol, table (tr/th/td), steps (`step title="…"` with block children), codeblock, img, alert, details and inline marks. A table or steps directly inside the claim folds its raw output behind one line. Inside a table or steps, inline `code` means "copied from this claim\'s output": write the value exactly as the output prints it, with no rounding and no unit change. Check and the page name any such value the output does not contain, and that claim then waits on the human. Expected values, ordinals and your own wording stay outside `code`; commands go in a codeblock.\n\njudge="agent" means a command decided the stated predicate, ran in the claimed environment, passed and has raw output plus from. Missing evidence/from needs human judgment. A failed check is a fix or gap, never a passed agent claim. judge="human" requires an ask explaining what would make the judgment wrong; use for unresolved nonscreen tradeoffs, not to re-ask approved decisions. A human claim holding a long table (rulings, decisions) marks each row `<tr cost="change|small|none">`: change (wrong means behavior must change), small (a small cost), none (no effect). Only change rows show; small and none fold behind a count. Check notes a human-claim table over 12 rows without cost. A rejected agent claim remains human-owned until the human passes it, even after new evidence.\n\nGap needs id/title/why/needs (one specific unblock). `<ref artboard="slug" group="v2"/>` counts a screen claim toward done; the page sums the groups per artboard in one status-line sentence with a link, not as rows, so the verdict is given on the artboard. Read via comment list; record pass/reject/waive only if requested by the human, reply on rejection threads and replace evidence after a repair. Stable IDs preserve verdicts/comments. Never edit comments.json or `.state/`. Run the returned Check command before sharing.\n';function rC(e,t){if(t===`pass`||t===`reject`){let n=t===`pass`&&!!e.all;if(!n&&!e.claim)throw new M(t===`pass`?`comment pass on a report needs --claim <claimId>, or --all`:`comment reject on a report needs --claim <claimId>`);let r=t===`reject`?$n(e):e.text?.trim();return{op:`verdict`,verdict:t,...n?{all:!0}:{claim:e.claim},...r?{text:r}:{}}}if(t===`waive`){if(!e.gap)throw new M(`comment waive needs --gap <gapId>`);return{op:`waive`,gap:e.gap}}if(t===`reply`){if(!e.thread)throw new M(`comment reply needs --thread <threadId>`);return{op:`reply`,threadId:e.thread,text:$n(e)}}throw new M(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}const iC={artboard:rr,document:__,html:v_,whiteboard:{authoring:`# Whiteboard writing
770
+ `];function QS(e){let t=f.default.join(e,`voice/voice.mjs`);return d.default.existsSync(t)?(ZS.includes(d.default.readFileSync(t,`utf8`))&&d.default.writeFileSync(t,XS),!1):(d.default.mkdirSync(f.default.dirname(t),{recursive:!0}),d.default.writeFileSync(t,XS,{flag:`wx`}),!0)}var $S='# Storyboard writing\n\nA storyboard plans a product demo video and plays it back before anything is recorded: shots in order, each with a duration, what happens on screen, and voiceover lines that are synthesized and spoken with captions. Write `storyboard.xml` under the returned artifact directory first, with no shot pictures at all: every shot without `src` plays as a title card, so your human partner can hear the pacing within minutes. Add moving pictures, recorded takes, music and sound effects afterwards. On this machine the hub opens a storyboard in an editor: a monitor, a bin and a multitrack timeline (captions, overlay, picture, voice, music, effects) where your human partner trims, splits, reorders, adds transitions, speed, keys and sounds, and exports the next cut.\n\nRe-read `storyboard.xml` and the shot pages immediately before each edit: your human partner edits the timeline, and the server writes those edits into the same file, and moving an overlay rewrites the times of `sb-cursor`, `sb-type` or `sb-clip` in the shot page. Patch only the shots and lines you mean to change and keep every id. Never edit `comments.json`, `audio/`, `cuts/` or `.state/`. Finish with `check`; lines still being voiced are pending, not done.\n\n```xml\n<storyboard title="Shared albums" aspect="16:9" lang="en" voice="Kore" target="10-15">\n <lexicon>\n <say word="Ryugi" as="Lyu-ghee" hint="lyu as in the Chinese name Liu, never an English r; hard g"/>\n </lexicon>\n <music id="bed" src="sound/bed.mp3" at="0" gain="-18" duck="-10" fade-in="1" fade-out="2"/>\n <shot id="hook" title="A wall of text" dur="4">\n <action>The terminal fills with a 300-line plan</action>\n <action>Cut away before anyone could read it</action>\n <line id="hook-1" at="0.4">Your agent wrote 300 lines. Now read them.</line>\n </shot>\n <shot id="sketch" title="Sketch it together" dur="8" src="shots/sketch.html" transition="dissolve" transition-dur="0.4">\n <action>You draw a box; the agent completes the flow</action>\n <key prop="scale" at="2" value="1"/>\n <key prop="scale" at="5" value="1.18" ease="in-out"/>\n <sfx id="click" src="sound/click.wav" at="2.6" gain="-6"/>\n <line id="sketch-1" caption="Sketch it together.">Sketch the structure together, right in the page.</line>\n </shot>\n</storyboard>\n```\n\n## Elements\n\n- `<storyboard>`: `title`; `aspect` is `16:9` (default), `9:16` or `1:1`; `lang`; `voice` is the voice name passed to the voice script; `target` is the intended length as a range of seconds (`"65-80"`), and a total outside it is a warning.\n- `<lexicon>` with `<say word="…" as="…" hint="…"/>`: pronunciations. Before synthesis every whole-word `word` is replaced by `as`; captions keep the original words. A respelling alone is often read wrong, so a line holding the word also tells the speech model that `as` is how `word` is said, followed by `hint` (optional: how it sounds, in plain words). Give every made-up or borrowed name a `hint`.\n- `<shot>`: `id`, `title`, `dur` (seconds, required, one decimal is fine). Optional `src` (a shot page under `shots/`), `take` (a recorded clip under `takes/`) and `take-in` (the second of the take to start from). A shot starts where the shots before it end; never write start times.\n- `<action>`: one thing that happens on screen, one sentence each. Title cards and the script column show them.\n- `<line>`: one voiceover line. `at` is seconds from the shot\'s start; without it the line follows the previous line by 0.3s (the first line starts 0.3s in). `caption` replaces the words shown on screen; without it the caption is the line itself. `gain` is its volume in dB (default 0).\n\nShot and line ids are lowercase letters, digits and hyphens, unique across the whole file; comments are anchored to them.\n\n## Tracks\n\nShots are the spine: everything below is optional, and a storyboard without it is a picture, voice and caption timeline. Times on a shot are seconds from its start on the timeline; music uses whole-video seconds.\n\n- On `<shot>`: `speed` (0.25 to 4, default 1) runs the page clock and the take faster or slower while `dur` stays its length on the timeline; voice, keys and effects are not sped up. `src-in` is the second of the shot page to start from. `transition` is `cut` (default), `dissolve` or `black`, centred on the seam before this shot and `transition-dur` seconds long (default 0.4, at most half the shorter shot); it never changes the total length. `gain` in dB plays a take\'s own sound, which is otherwise muted.\n- `<key prop="…" at="…" value="…" ease="…"/>` inside a shot animates the picture layer: `x` and `y` in design pixels, `scale` as a factor, `opacity` 0 to 1, and `gain` in dB for a take\'s sound. `ease` is `linear` (default), `in`, `out` or `in-out`, easing into that key. One key holds its value for the whole shot; captions do not move.\n- `<sfx id src at gain fade-in fade-out/>` inside a shot plays a sound effect `at` seconds into the shot.\n- `<music id src at from to gain duck fade-in fade-out>` at the top level plays a file from `at` seconds into the video, starting `from` seconds into the file and ending at `to` (default: the end of the video). `duck` lowers it by that many dB while a voice line plays (down in 0.2s, back in 0.4s). Gain `<key prop="gain">` elements inside it change its volume over time, in seconds from `at`.\n- On `<storyboard>`: `mute="music sfx"` silences any of `voice`, `music` and `sfx`, and `captions="off"` hides captions; both carry into the export.\n\nSound files live in `sound/` (mp3, wav, m4a or ogg). Put them there yourself, or your human partner drops them into the editor. `check` reports a track that names a file that is not there.\n\n## Voice\n\nEvery line is synthesized on its own by `voice/voice.mjs` in the artifact directory, which `start` copies from a template the first time and keeps up to date while it is unedited (OpenRouter text-to-speech; it reads `OPENROUTER_API_KEY` from the project\'s `.env` and needs ffmpeg). It reads `{text, voice, lang, out, direction?}` on stdin; `direction` carries the lexicon\'s pronunciations for that line. The hub runs it a second after `storyboard.xml` changes, only for lines whose words, voice or lexicon changed. Run `adeck storyboard voice --artifact storyboard/<id>` to synthesize and print each line\'s length, then fit shot durations to the voice: `check` reports a voiced line that runs past its shot or overlaps the line before it. `--line <id>` voices one line; `--force` re-voices everything after you change the script.\n\n## Shot pages\n\nA shot page is plain HTML with CSS animations, drawn the way the product looks, laid out at 1920×1080 (1080×1920 for `aspect="9:16"`, 1080×1080 for `1:1`) and scaled to fit the player. Time 0 is the shot\'s start; the viewer pauses every animation and seeks it, so scrubbing and frame-by-frame capture show exactly the same frame. Animate only with CSS animations or the Web Animations API, never with `setTimeout`, `setInterval` or `requestAnimationFrame`, and give every animation a finite iteration count. Three elements cover what CSS cannot seek:\n\n- `<sb-clip src="../takes/raw.mp4" from="3.2" to="11.2" at="0.5">` plays part of a recorded video, muted, starting `at` seconds into the shot.\n- `<sb-cursor path="420,300@0 610,340@1.2 click@1.3 700,420@2.4">` moves a pointer through `x,y@seconds` points and ripples on each `click@seconds`.\n- `<sb-type at="2.3" cps="28">text</sb-type>` types its text from `at`, `cps` characters a second.\n\n`sb-cursor` covers the page, so its points are page pixels. Pages cannot reach the network; keep images under `assets/` and refer to them relatively. `check` warns about timers and endless animations, and counts a shot as not yet run until the viewer has shown it.\n\nThe page `…/storyboard/<id>/render` draws only the picture and captions, with transitions, speed and keys, exactly as the editor\'s monitor does (`?captions=0` drops captions, `?from=&to=` draws only that stretch). Its `window.ryugiStoryboard.seek(t)` resolves once that frame is painted, `duration` is the length in seconds, `audio()` lists every voiced line\'s file URL and start, and `mix()` lists every sound with its file, start, end, gain, fades, keys and duck, so any capture tool can step frame by frame and mix the sound in.\n\n## Takes, export and the cut\n\nPut recorded clips in `takes/` and name them with `take` on their shot; the shot then plays the clip under the voiceover, muted unless the shot has a `gain`, and its shot page and overlays are not drawn (put a clip in the page with `sb-clip` to draw over it).\n\nExport renders the timeline into the next cut on this machine. `start` copies an export script to `render/render.mjs` the first time; it drives Chrome over the DevTools protocol and ffmpeg, with no packages to install, renders each shot from the render page frame by frame, reuses shots that did not change, mixes voice, music and effects and writes 1080p H.264. The hub hands it the timeline as JSON on stdin and registers what it writes as the next cut, with a hash of every shot so the editor marks the shots that changed. Run `adeck storyboard export --artifact storyboard/<id> [--wait]` to export from the command line; lines not yet voiced are voiced first. `adeck storyboard template --artifact storyboard/<id> --force` replaces `render/render.mjs` with the latest template; without `--force` a script you changed is kept. A project can replace the script with its own kit that reads the same JSON.\n\nWhen a finished video comes from somewhere else, register it with `adeck storyboard cut --artifact storyboard/<id> --file <1080p.mp4> [--map <map.json>] [--master <4k.mp4>]`. Without `--map` each shot\'s range comes from the storyboard\'s current durations; pass a map (`{"shots":[{"id":"hook","start":0,"end":4.2}]}`) when the cut\'s timing differs. Encode the cut as H.264 1080p at about 1.5 Mbps so it fits the Cloud allowance.\n\n## Comments and references\n\nRead feedback with `comment list`. Comments are anchored to a shot, a line, a moment of a shot (`--at <seconds>`) or a moment of a cut (`--cut <n> --at <seconds>`), which maps to its shot; `comment list` names each thread\'s shot, moment or line, and for an area marked on a recorded take or the cut, the path of its crop. A thread whose shot was deleted stays, marked `shot deleted`. Your human partner can reorder, trim, split and join shots, rewrite titles, actions and voice lines, add, duplicate or delete shots, and set transitions, speed, keys, sounds and mutes in the editor; each edit rewrites only its part of `storyboard.xml`. A split gives the second half the id `<id>-b` and leaves its comments on the first half. When `check` reports `Structure: N changes by your human partner`, run `changes --artifact storyboard/<id>` and read them before editing the file, so you build on their version instead of writing it back. A document or deck links a shot with `<ref storyboard="<id>" shot="<shot-id>"/>`.\n';function eC(e){if(!e.shot&&!e.cut)throw new M(`comment add on a storyboard needs --shot <shotId>, or --cut <n> --at <seconds>`);if(e.line&&e.at!==void 0)throw new M(`comment add takes --line or --at, not both`);let t=er(e.at,`--at`);if(t!==void 0&&t<0)throw new M(`--at must be seconds from 0`);let n;if(e.cut!==void 0){if(n=Number(e.cut),!Number.isInteger(n)||n<1)throw new M(`--cut must be a cut number from 1`);if(t===void 0)throw new M(`a comment on a cut needs --at <seconds>`);if(e.line)throw new M(`comment add takes --line or --cut, not both`)}return{op:`add`,...e.shot?{shot:e.shot}:{},...e.line?{line:e.line}:{},...n===void 0?{}:{cut:n},...t===void 0?{}:{at:t},text:$n(e)}}const tC={authoring:$S,changes:!0,review:{sections:[]},commentActions:{add:eC},onStart:e=>{QS(e),YS(e)}};var nC='# Verify report writing\n\nWrite `verify.xml` and captured files in `evidence/`. Reports cover command output, counts, API behavior, deploy evidence and evals. Claims judged by looking at a screen go in artboard verify groups; reference those groups from the report. Never invent captured output or human verdicts. Report prose uses the human\'s language; IDs/commands/raw logs retain their form.\n\n```xml\n<verify title="Delivery survives reconnect">\n <p>Verified against local build.</p>\n <claim id="delivery" judge="agent" from="local build @ COMMIT" capturedAt="2026-11-13T10:00:00Z">\n <title>Three attempts preserve the delivery</title>\n <result><code>3</code> attempts, <code>1</code> delivery kept</result>\n <table>\n <tr><th>Measured</th><th>Got</th><th>Expected</th></tr>\n <tr><td>Attempts</td><td><code>3</code></td><td>3</td></tr>\n <tr><td>Deliveries kept</td><td><code>1</code></td><td>1</td></tr>\n </table>\n <output src="evidence/delivery.txt"/>\n </claim>\n <gap id="production"><title>Production run</title><why>No production credentials</why><needs>A test key</needs></gap>\n</verify>\n```\n\nRequired report title; optional one introductory p first; only claim/gap/ref after it, no top-level headings. The page reads as one column: a status line, then what waits on the human (gaps, rejected and pending claims), then the agent\'s checks one line each, grouped by environment. Claim needs unique stable id, judge, title and evidence. `from` identifies actual environment/build; capturedAt is the real ISO capture time, not a future/example timestamp. Update both with replaced evidence. Capture command output directly to evidence/*.txt and never edit it. `output src="evidence/…"` keeps it one click away; no HTML output files. Over 200,000 characters is explicitly truncated.\n\nEvery agent claim has one `<result>`: inline, one line, what it proved (`<result><code>897 passed (897)</code></result>`); it is the claim\'s whole line on the page, and Check notes an agent claim without one. Its `code` values follow the copied-value rule below. Claims from the same environment and build use the identical `from` string: the page groups checks by exact `from` and writes it once per group. Above the output, write the result for the person reading: nobody should have to read a log to see what it proved. A claim may hold p, ul/ol, table (tr/th/td), steps (`step title="…"` with block children), codeblock, img, alert, details and inline marks. A table or steps directly inside the claim folds its raw output behind one line. Inside a table or steps, inline `code` means "copied from this claim\'s output": write the value exactly as the output prints it, with no rounding and no unit change. Check and the page name any such value the output does not contain, and that claim then waits on the human. Expected values, ordinals and your own wording stay outside `code`; commands go in a codeblock.\n\njudge="agent" means a command decided the stated predicate, ran in the claimed environment, passed and has raw output plus from. Missing evidence/from needs human judgment. A failed check is a fix or gap, never a passed agent claim. judge="human" requires an ask explaining what would make the judgment wrong; use for unresolved nonscreen tradeoffs, not to re-ask approved decisions. A human claim holding a long table (rulings, decisions) marks each row `<tr cost="change|small|none">`: change (wrong means behavior must change), small (a small cost), none (no effect). Only change rows show; small and none fold behind a count. Check notes a human-claim table over 12 rows without cost. A rejected agent claim remains human-owned until the human passes it, even after new evidence.\n\nGap needs id/title/why/needs (one specific unblock). `<ref artboard="slug" group="v2"/>` counts a screen claim toward done; the page sums the groups per artboard in one status-line sentence with a link, not as rows, so the verdict is given on the artboard. Read via comment list; record pass/reject/waive only if requested by the human, reply on rejection threads and replace evidence after a repair. Stable IDs preserve verdicts/comments. Never edit comments.json or `.state/`. Run the returned Check command before sharing.\n';function rC(e,t){if(t===`pass`||t===`reject`){let n=t===`pass`&&!!e.all;if(!n&&!e.claim)throw new M(t===`pass`?`comment pass on a report needs --claim <claimId>, or --all`:`comment reject on a report needs --claim <claimId>`);let r=t===`reject`?$n(e):e.text?.trim();return{op:`verdict`,verdict:t,...n?{all:!0}:{claim:e.claim},...r?{text:r}:{}}}if(t===`waive`){if(!e.gap)throw new M(`comment waive needs --gap <gapId>`);return{op:`waive`,gap:e.gap}}if(t===`reply`){if(!e.thread)throw new M(`comment reply needs --thread <threadId>`);return{op:`reply`,threadId:e.thread,text:$n(e)}}throw new M(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}const iC={artboard:rr,document:__,html:v_,whiteboard:{authoring:`# Whiteboard writing
771
771
 
772
772
  Write \`scene.excalidraw\` (main page); optional \`pages.json\` and \`pages/<id>.excalidraw\`. The browser and agent collaborate live. Re-read immediately before edits, preserve IDs and all customData (\`ryugiAuthor\`, \`ryugiRev\`, \`ryugiLastBy\`). Never manufacture revision fields or force over a conflict; read again and apply on top of the human version. Missing elements are not deletion; retain the element and set \`isDeleted:true\`. Bound labels are separate text elements: edit text and originalText.
773
773
 
@@ -843,8 +843,8 @@ Run Check after edits; skeleton_not_completed/browser_not_run needs the board op
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.1`,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.113.1`,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(`
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.113.2`,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(`
@@ -852,13 +852,13 @@ Run Check after edits; skeleton_not_completed/browser_not_run needs the board op
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
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
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 MD=()=>u.default.randomBytes(24).toString(`base64url`);function ND(e){try{return d.default.readFileSync(e,`utf8`).trim()}catch{return``}}function PD(e){let t=f.default.join(f.default.dirname(e),`host-id`),n=ND(t);if(/^[\w-]{16,64}$/.test(n))return n;let r=MD();return d.default.mkdirSync(f.default.dirname(t),{recursive:!0,mode:448}),d.default.writeFileSync(t,`${r}\n`,{mode:384}),r}async function FD(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 ID=e=>({binary:f.default.join(e,`.ryugi`,`bin`,`ryugi-daemon`)});async function LD(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 RD=`session control runs on macOS and Linux`,zD=(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 BD(e){if(e.platform!==`darwin`&&e.platform!==`linux`)throw new M(RD);if(!ht(e.serverHome,e.home))return null;let t=Lt(e);if(!t)throw new M(RD);let n=t.check();if(n)throw new M(`${n}; session control needs systemd on Linux`);return t}const VD=(e,t,n)=>({autostart:n,binary:t,launch:e.launch,log:e.log,path:e.path});async function HD(e,t){let n=BD(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(VD(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 UD(e){let t=BD(e);En(e.serverHome,!1);let n=vt(e),r=null;return t&&d.default.existsSync(t.file(!0))&&(r=t.write(VD(e,n,!1)),t.disable()),await e.restartHub(!1),{service:r}}async function WD(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 GD(e,t,n,r=ID(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 KD=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],qD=()=>ie(process.env),JD=()=>process.env.RYUGI_ARTIFACTS_VERSION||`1.113.1`;function YD(){let e=He();return{configHome:process.env.XDG_CONFIG_HOME||void 0,ensureBinary:()=>Bn(e,JD()),home:h.default.homedir(),launch:On(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,restartHub:e=>FD(JD(),{reason:`session-control`,startStopped:e}),run:In,serverHome:e.home,uid:process.getuid?.()??0}}function XD(){let e=Jn(process.env,process.platform,h.default.homedir()),t=qD(),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:PD(e)}}const ZD=()=>jD(AD());async function QD(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 $D(){return(await QD(()=>ZD().call(`sessions.local`,{}))).sessions}async function eO(e){let[t,n,r]=e.positionals;if(!t||!KD.includes(t))throw new M(`usage: adeck daemon ${KD.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await HD(YD(),{binary:e.values.binary});return i(`installed`,[`session control on`,`binary ${t.binary}`,...t.service?[`${t.kind.padEnd(8)}${t.service}`]:[],...t.linger?[zD(t.linger,h.default.userInfo().username)]:[]])}case`uninstall`:{let e=await UD(YD());return i(`removed`,[`session control off`,...e.service?[`service ${e.service}`]:[]])}case`status`:{let e=await QD(()=>ZD().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 WD({code:n,cloud:XD(),daemon:ZD(),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=XD(),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 QD(()=>ZD().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await QD(()=>ZD().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 QD(()=>ZD().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await $D();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]=GD(h.default.homedir(),await $D(),n,process.env.RYUGI_DAEMON_BIN||void 0);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
855
+ `)}`);return[r,`attach`,a.attach]}const KD=[`install`,`uninstall`,`status`,`trust`,`devices`,`remote`,`sessions`,`attach`],qD=()=>ie(process.env),JD=()=>process.env.RYUGI_ARTIFACTS_VERSION||`1.113.2`;function YD(){let e=He();return{configHome:process.env.XDG_CONFIG_HOME||void 0,ensureBinary:()=>Bn(e,JD()),home:h.default.homedir(),launch:On(e),log:e.log,path:process.env.PATH??`/usr/bin:/bin`,platform:process.platform,restartHub:e=>FD(JD(),{reason:`session-control`,startStopped:e}),run:In,serverHome:e.home,uid:process.getuid?.()??0}}function XD(){let e=Jn(process.env,process.platform,h.default.homedir()),t=qD(),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:PD(e)}}const ZD=()=>jD(AD());async function QD(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 $D(){return(await QD(()=>ZD().call(`sessions.local`,{}))).sessions}async function eO(e){let[t,n,r]=e.positionals;if(!t||!KD.includes(t))throw new M(`usage: adeck daemon ${KD.join(`|`)}`);let i=(e,n)=>({action:t,status:e,lines:n});switch(t){case`install`:{let t=await HD(YD(),{binary:e.values.binary});return i(`installed`,[`session control on`,`binary ${t.binary}`,...t.service?[`${t.kind.padEnd(8)}${t.service}`]:[],...t.linger?[zD(t.linger,h.default.userInfo().username)]:[]])}case`uninstall`:{let e=await UD(YD());return i(`removed`,[`session control off`,...e.service?[`service ${e.service}`]:[]])}case`status`:{let e=await QD(()=>ZD().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 WD({code:n,cloud:XD(),daemon:ZD(),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=XD(),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 QD(()=>ZD().call(`trust.remove`,{deviceId:r})),i(`revoked`,[r])}let e=await QD(()=>ZD().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 QD(()=>ZD().call(`remote.set`,{on:n===`on`})),i(n,[`remote mode ${n}`]);case`sessions`:{let e=await $D();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]=GD(h.default.homedir(),await $D(),n,process.env.RYUGI_DAEMON_BIN||void 0);return process.stderr.write(`This is a daemon session: it runs with permission checks bypassed.
856
856
  `),i((0,p.spawnSync)(e,t,{stdio:`inherit`}).status===0?`detached`:`failed`,[])}}}function tO({data:e}){return{heading:`Daemon`,status:e.status,summary:``,facts:[],sections:e.lines.length?[{kind:`content`,key:`lines`,text:e.lines.join(`
857
- `)}]:[]}}const nO={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 eO(e);return Y(t,t.status===`failed`?{kind:`failed`,error:{code:`E_DAEMON`,message:`daemon ${t.action} failed`}}:{kind:`succeeded`})},present:tO},e)};function rO(e,t){try{return d.default.realpathSync(e)===d.default.realpathSync(t)}catch{return f.default.resolve(e)===f.default.resolve(t)}}function iO(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 aO(e,t){let n=iO(e,t);if(!n)throw Error(`Native Claude plugin not found: ${e}`);return n}function oO(e,t){if(!e.nativeSource||!e.registration)return`foreign`;let n=iO(e.registration,t);if(!n)return`missing`;if(rO(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&&rO(a,f.default.dirname(e.nativeSource))?`owned`:`foreign`}function sO(e,t){let n=e.path;if(e.harness===`claude-code`){let n=oO(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`&&rO(e.source.path,n))}if(e.harness===`pi`)return t(`pi`,[`list`]).split(/\r?\n/).some(e=>f.default.isAbsolute(e.trim())&&rO(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`&&rO(e.installMetadata.source,n)&&typeof e.path==`string`&&rO(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`&&rO(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 cO(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`&&rO(n.root,t):typeof n.source==`string`&&rO(n.source.replace(/^Local:\s*/i,``),t)))}function lO(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 uO(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 dO(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 Ryugi 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`),`# Ryugi Artifacts
857
+ `)}]:[]}}const nO={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 eO(e);return Y(t,t.status===`failed`?{kind:`failed`,error:{code:`E_DAEMON`,message:`daemon ${t.action} failed`}}:{kind:`succeeded`})},present:tO},e)};function rO(e,t){try{return d.default.realpathSync(e)===d.default.realpathSync(t)}catch{return f.default.resolve(e)===f.default.resolve(t)}}function iO(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 aO(e,t){let n=iO(e,t);if(!n)throw Error(`Native Claude plugin not found: ${e}`);return n}function oO(e,t){if(!e.nativeSource||!e.registration)return`foreign`;let n=iO(e.registration,t);if(!n)return`missing`;if(rO(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&&rO(a,f.default.dirname(e.nativeSource))?`owned`:`foreign`}function sO(e,t){let n=e.path;if(e.harness===`claude-code`){let n=oO(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`&&rO(e.source.path,n))}if(e.harness===`pi`)return t(`pi`,[`list`]).split(/\r?\n/).some(e=>f.default.isAbsolute(e.trim())&&rO(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`&&rO(e.installMetadata.source,n)&&typeof e.path==`string`&&rO(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`&&rO(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 cO(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`&&rO(n.root,t):typeof n.source==`string`&&rO(n.source.replace(/^Local:\s*/i,``),t)))}function lO(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 uO(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 dO(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 a Ryugi 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=uO(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:uO(t)}}catch(e){throw d.default.rmSync(t,{recursive:!0,force:!0}),e}}function fO(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 Ryugi plugin release ${i} that matches this CLI (Git required): ${a.stderr||a.error?.message}`);return r}function pO(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 mO=[{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`}],hO=(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 gO(e=h.default.homedir(),t=hO){return mO.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 _O=e=>{try{return d.default.lstatSync(e),!0}catch{return!1}};function vO(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 yO(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)||uO(e.path)!==e.digest)throw Error(`Installed ${e.harness} files changed; preserving user edits at ${e.path}`)}function bO(e,t,n){pO(t.root,e,t.mode);let r=vO(e,n),i=n.previous,a=n.run||hO,o=n.env||process.env,s=n.home||h.default.homedir();if(_O(r)){if(!i)throw Error(`Plugin already exists and is not owned by this installer: ${r}`);yO(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(mO.find(t=>t.id===e).command,t)))throw Error(`An existing Ryugi ${e} install is managed elsewhere. Remove it with that harness before installing here.`)}if(i&&!sO(i,a))throw Error(`Native ${e} source changed or is no longer registered; preserving it`);if(!i&&(e===`codex`||e===`copilot`)&&lO(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(_O(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');
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=uO(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:uO(t)}}catch(e){throw d.default.rmSync(t,{recursive:!0,force:!0}),e}}function fO(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 pO(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 mO=[{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`}],hO=(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 gO(e=h.default.homedir(),t=hO){return mO.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 _O=e=>{try{return d.default.lstatSync(e),!0}catch{return!1}};function vO(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 yO(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)||uO(e.path)!==e.digest)throw Error(`Installed ${e.harness} files changed; preserving user edits at ${e.path}`)}function bO(e,t,n){pO(t.root,e,t.mode);let r=vO(e,n),i=n.previous,a=n.run||hO,o=n.env||process.env,s=n.home||h.default.homedir();if(_O(r)){if(!i)throw Error(`Plugin already exists and is not owned by this installer: ${r}`);yO(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(mO.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&&!sO(i,a))throw Error(`Native ${e} source changed or is no longer registered; preserving it`);if(!i&&(e===`codex`||e===`copilot`)&&lO(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(_O(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') } : {}));
@@ -870,16 +870,16 @@ printf "{}\\n"
870
870
  const fs = require('node:fs');
871
871
  const path = require('node:path');
872
872
  const [major, minor] = process.versions.node.split('.').map(Number);
873
- if (major < 20 || (major === 20 && minor < 12)) throw Error('Ryugi requires Node.js 20.12 or newer. Upgrade Node and retry.');
873
+ if (major < 20 || (major === 20 && minor < 12)) throw Error('Artideck requires Node.js 20.12 or newer. Upgrade Node and retry.');
874
874
  const root = __dirname;
875
875
  const current = JSON.parse(fs.readFileSync(path.join(root, 'current.json'), 'utf8'));
876
876
  const relative = path.relative(fs.realpathSync(path.join(root, 'versions')), fs.realpathSync(current.packageRoot));
877
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw Error('Invalid Ryugi runtime record');
877
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw Error('Invalid Artideck runtime record');
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 Ryugi runtime package`);for(let t of MO)if(!d.default.existsSync(f.default.join(e,t)))throw Error(`Incomplete Ryugi 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,`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 Ryugi 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 a Ryugi 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 lk={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:`Ryugi plugin checkout to link`}},semantic:e=>Q({id:`dev`,mode:`finite`,output:{formats:[`brief`,`json`,`quiet`],scalar:e=>e.status},run:()=>Y(sk(e)),present:ck},e)},uk=[`/opt/homebrew/bin`,`/usr/local/bin`],dk=process.platform===`win32`?[`agent-browser.cmd`,`agent-browser.exe`]:[`agent-browser`],fk=e=>{try{return d.default.accessSync(e,d.default.constants.X_OK),d.default.statSync(e).isFile()}catch{return!1}},pk=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 mk(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`),...pk(t),...n].filter(Boolean)}function hk({env:e=process.env,home:t=h.default.homedir(),extraDirs:n=uk,nodeDir:r=f.default.dirname(process.execPath)}={}){let i=e.RYUGI_AGENT_BROWSER;if(i)return fk(i)?i:null;for(let i of mk(e,t,n,r))for(let e of dk){let t=f.default.join(i,e);if(fk(t))return t}return null}const gk=(e=process.env)=>({...e,PATH:[f.default.dirname(process.execPath),e.PATH??``].filter(Boolean).join(f.default.delimiter)});function _k(e){let t=(0,p.spawnSync)(e,[`--version`],{encoding:`utf8`,timeout:5e3,env:gk()});return/(\d+\.\d+\.\d+\S*)/.exec(t.stdout??``)?.[1]??null}const vk=e=>{let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(e)),t};function yk(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(vk(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(vk(s.size)).update(d.default.readFileSync(r));else throw Error(`Unsupported Codex plugin entry: ${r}`)}return`sha256:${t.digest(`hex`)}`}const bk=e=>e.replaceAll(/(?<=[a-z\d])([A-Z])/g,`_$1`).toLowerCase();function xk(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}:${bk(e)}:${i}:${o}`)));return a}function Sk(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 Ck(e,t,n,r=h.default.homedir()){let i=xk(e,t),a=f.default.join(n.CODEX_HOME||f.default.join(r,`.codex`),`config.toml`),o=Sk(d.default.existsSync(a)?d.default.readFileSync(a,`utf8`):``),s=yk(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 wk=12096e5,Tk=e=>f.default.join(ct(e),`plugins.json`);function Ek(e,t){d.default.mkdirSync(ct(e),{recursive:!0,mode:448});let n=`${Tk(e)}.${process.pid}.tmp`;d.default.writeFileSync(n,JSON.stringify(t)),d.default.renameSync(n,Tk(e))}function Dk(e){try{let t=JSON.parse(d.default.readFileSync(Tk(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 Ok=e=>{try{return d.default.statSync(e).mtimeMs}catch{return null}};function kk(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=Ok(f.default.join(r,`last-used`)),o=Ok(r),s=Ok(f.default.join(r,`.lock`)),c=(t,n)=>t!==null&&e.now-t<n;c(a,wk)||a===null&&c(o,wk)||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 Ak(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??Dk(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?kk({env:e.env,home:e.home,keep:i,legacyInUse:!n?.complete||r.some(e=>e.legacy),now:t}):[]}}const jk=(()=>{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}})(),Mk=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Nk=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,Pk=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Fk=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ik=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Lk=/\t{1,1000}/y,Rk=/[\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,zk=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Bk=/\p{M}+/gu,Vk={limit:1/0,ellipsis:``},Hk=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Hk(i,Vk,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[zk,l],[Pk,0],[Fk,o],[Lk,s],[Rk,c],[Ik,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(Bk,``)){let t=e.codePointAt(0)||0;if(S=Mk(t)?2:Nk(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===Ik?jk(e.slice(p,n.lastIndex)):n===Rk?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}},Uk={limit:1/0,ellipsis:``,ellipsisWidth:0},Wk=(e,t={})=>Hk(e,Uk,t).width,Gk=`]8;;`,Kk=RegExp(`(?:\\[(?<code>\\d+)m|\\${Gk}(?<uri>.*))`,`y`),qk=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},Jk=e=>`[${e}m`,Yk=e=>`${Gk}${e}`,Xk=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Wk(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Wk(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Gk,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())},Zk=e=>{let t=e.split(` `),n=t.length;for(;n&&!Wk(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Qk=(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=Wk(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=Wk(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(``),Xk(s,r,t),c=Wk(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Xk(s,r,t),c=Wk(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Xk(s,r,t),c=Wk(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Zk(e)));let l=s.join(`
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 lk={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(sk(e)),present:ck},e)},uk=[`/opt/homebrew/bin`,`/usr/local/bin`],dk=process.platform===`win32`?[`agent-browser.cmd`,`agent-browser.exe`]:[`agent-browser`],fk=e=>{try{return d.default.accessSync(e,d.default.constants.X_OK),d.default.statSync(e).isFile()}catch{return!1}},pk=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 mk(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`),...pk(t),...n].filter(Boolean)}function hk({env:e=process.env,home:t=h.default.homedir(),extraDirs:n=uk,nodeDir:r=f.default.dirname(process.execPath)}={}){let i=e.RYUGI_AGENT_BROWSER;if(i)return fk(i)?i:null;for(let i of mk(e,t,n,r))for(let e of dk){let t=f.default.join(i,e);if(fk(t))return t}return null}const gk=(e=process.env)=>({...e,PATH:[f.default.dirname(process.execPath),e.PATH??``].filter(Boolean).join(f.default.delimiter)});function _k(e){let t=(0,p.spawnSync)(e,[`--version`],{encoding:`utf8`,timeout:5e3,env:gk()});return/(\d+\.\d+\.\d+\S*)/.exec(t.stdout??``)?.[1]??null}const vk=e=>{let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(e)),t};function yk(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(vk(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(vk(s.size)).update(d.default.readFileSync(r));else throw Error(`Unsupported Codex plugin entry: ${r}`)}return`sha256:${t.digest(`hex`)}`}const bk=e=>e.replaceAll(/(?<=[a-z\d])([A-Z])/g,`_$1`).toLowerCase();function xk(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}:${bk(e)}:${i}:${o}`)));return a}function Sk(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 Ck(e,t,n,r=h.default.homedir()){let i=xk(e,t),a=f.default.join(n.CODEX_HOME||f.default.join(r,`.codex`),`config.toml`),o=Sk(d.default.existsSync(a)?d.default.readFileSync(a,`utf8`):``),s=yk(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 wk=12096e5,Tk=e=>f.default.join(ct(e),`plugins.json`);function Ek(e,t){d.default.mkdirSync(ct(e),{recursive:!0,mode:448});let n=`${Tk(e)}.${process.pid}.tmp`;d.default.writeFileSync(n,JSON.stringify(t)),d.default.renameSync(n,Tk(e))}function Dk(e){try{let t=JSON.parse(d.default.readFileSync(Tk(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 Ok=e=>{try{return d.default.statSync(e).mtimeMs}catch{return null}};function kk(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=Ok(f.default.join(r,`last-used`)),o=Ok(r),s=Ok(f.default.join(r,`.lock`)),c=(t,n)=>t!==null&&e.now-t<n;c(a,wk)||a===null&&c(o,wk)||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 Ak(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??Dk(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?kk({env:e.env,home:e.home,keep:i,legacyInUse:!n?.complete||r.some(e=>e.legacy),now:t}):[]}}const jk=(()=>{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}})(),Mk=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Nk=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,Pk=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Fk=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ik=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Lk=/\t{1,1000}/y,Rk=/[\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,zk=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Bk=/\p{M}+/gu,Vk={limit:1/0,ellipsis:``},Hk=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Hk(i,Vk,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[zk,l],[Pk,0],[Fk,o],[Lk,s],[Rk,c],[Ik,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(Bk,``)){let t=e.codePointAt(0)||0;if(S=Mk(t)?2:Nk(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===Ik?jk(e.slice(p,n.lastIndex)):n===Rk?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}},Uk={limit:1/0,ellipsis:``,ellipsisWidth:0},Wk=(e,t={})=>Hk(e,Uk,t).width,Gk=`]8;;`,Kk=RegExp(`(?:\\[(?<code>\\d+)m|\\${Gk}(?<uri>.*))`,`y`),qk=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},Jk=e=>`[${e}m`,Yk=e=>`${Gk}${e}`,Xk=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Wk(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Wk(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Gk,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())},Zk=e=>{let t=e.split(` `),n=t.length;for(;n&&!Wk(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Qk=(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=Wk(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=Wk(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(``),Xk(s,r,t),c=Wk(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Xk(s,r,t),c=Wk(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Xk(s,r,t),c=Wk(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Zk(e)));let l=s.join(`
883
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===`›`){Kk.lastIndex=e+1;let t=Kk.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
884
  `){a&&(r+=Yk(``));let e=i?qk(i):void 0;i&&e&&(r+=Jk(e))}else t===`
885
885
  `&&(i&&qk(i)&&(r+=Jk(i)),a&&(r+=Yk(a)))}return r},$k=/\r?\n/;function eA(e,t,n){return String(e).normalize().split($k).map(e=>Qk(e,t,n)).join(`
@@ -943,15 +943,15 @@ ${(0,g.styleText)(`gray`,kA)}`:``}`}default:{let i=r?`${(0,g.styleText)(`cyan`,k
943
943
  `),l=o.length+1;return`${s}${i}${GA({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`,kA)}`;function aj(e,t){let n=e.harness===void 0?t.selection?.targets||Object.keys(t.previous):e.harness===`none`?[]:e.harness.split(`,`).map(LO);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(!mO.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 oj(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=aj({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 sj(e,t){let n=process.stderr;XA(`Ryugi · Install`,{output:n});let r=await oj(e,{async mode(e){$A(`Artifacts: the artifacts and interface-craft skills. Documents, artboards,
946
+ `}}}}).prompt()};`${(0,g.styleText)(`gray`,kA)}`;function aj(e,t){let n=e.harness===void 0?t.selection?.targets||Object.keys(t.previous):e.harness===`none`?[]:e.harness.split(`,`).map(LO);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(!mO.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 oj(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=aj({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 sj(e,t){let n=process.stderr;XA(`Artideck · Install`,{output:n});let r=await oj(e,{async mode(e){$A(`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
- worktrees and verification skills. Injects the Ryugi workflow into every
950
+ worktrees and verification skills. Injects the Artideck workflow into every
951
951
  new session. Rerun install to switch.`,`Content`,{output:n});let t=await ij({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 uA(t)?null:t},async targets(t){let r=mO.filter(t=>!e.detected.includes(t.id));if(r.length&&$A(r.map(e=>`${e.label}: ${e.command} not found`).join(`
952
952
  `),`Unavailable`,{output:n}),!e.detected.length)return[];let i=await JA({output:n,message:`Install into which harnesses? (empty = CLI only)`,required:!1,initialValues:t,options:mO.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 uA(i)?null:i},async review(t){$A([`CLI: ${t.root}`,`Command: ${t.binDir}`,`Content: ${t.mode}`,...t.targets.map(n=>`${n}: ${e.previous[n]?.mode||`new`} → ${t.mode}; ${mO.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 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.1`})}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 Ryugi 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.1`),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 dM({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 fM={name:`install`,summary:`Install persistent CLI and Artifacts or full Ryugi into selected harnesses`,usage:[`[--mode artifacts|full] [--harness <targets|none>] [options]`],details:`Interactive terminal wizard; automation requires explicit mode and targets (or reuses recorded selections). --harness none installs only the CLI.`,options:{mode:{type:`string`,value:`artifacts|full`,help:`Content mode`},harness:{type:`string`,value:`<targets|none>`,help:`Comma-separated claude-code,codex,cursor,gemini,opencode,pi,copilot,agy; none for CLI only`},yes:{type:`boolean`,help:`Apply an explicit or recorded plan without terminal confirmation`},"no-cli":{type:`boolean`,help:`Keep the current CLI; install only harness plugins`},"install-dir":{type:`string`,value:`<path>`,help:`Managed runtime and installation state directory`},"bin-dir":{type:`string`,value:`<path>`,help:`Command directory (default ~/.local/bin)`},"plugin-source":{type:`string`,value:`<path>`,help:`Use an existing Ryugi plugin checkout (offline or development)`}},semantic(e){return{run(t,n,r,i){return Q({id:`install`,mode:`finite`,output:{formats:[`brief`,`json`,`jsonl`,`quiet`],scalar:e=>e.bin},run:(n,r)=>uM(e,r,t.format===`brief`&&!!process.stdin.isTTY&&!!process.stderr.isTTY&&!process.env.CI),present:dM},e).run(t,n,r,i)}}}},pM=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function mM(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 pM.exec(e)?.[1]??null}function hM(e){let t=mM(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function gM(e){try{return hM((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 _M=`# Module vocabulary
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 dM({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 fM={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)=>uM(e,r,t.format===`brief`&&!!process.stdin.isTTY&&!!process.stderr.isTTY&&!process.env.CI),present:dM},e).run(t,n,r,i)}}}},pM=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function mM(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 pM.exec(e)?.[1]??null}function hM(e){let t=mM(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function gM(e){try{return hM((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 _M=`# 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
 
@@ -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 VN(e){for(let t of Ge(e))d.default.rmSync(f.default.join(Ke(t.dir),`.state`,`server-info`),{force:!0})}function HN({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 UN(){let e=He(),t=t=>{d.default.rmSync(e.info,{force:!0}),VN(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.113.1`});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 WN={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 UN();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:HN},e)};function GN({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 KN={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(LO):void 0;if(r?.some(e=>!mO.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`]||kO()),a=n.effects.begin(`uninstall`,i),o=Sj(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),Y(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:GN},e)};function qN(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 JN=e=>f.default.join(e.XDG_CACHE_HOME||f.default.join(h.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function YN(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 XN({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 ZN(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 QN={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 FD(e,{reason:`update`,startStopped:!1})}};function $N(e,t,n=xO){let r=`${n}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,r]:e===`yarn`?[`global`,`add`,r]:[`add`,`-g`,r]}}const eP=({cmd:e,args:t})=>[e,...t].join(` `);async function tP(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 nP(e,t){return e.kind===`transient`?`You ran ${xO} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${xO}@latest\` to get ${t}.`:e.kind===`local`?"This is a local build from a Ryugi checkout. Update it with `git pull`, then `pnpm build` in artifacts/.":e.kind===`launcher`?`Release cache refreshed to ${t}. Run the returned start command through the launcher to install it and replace the running server.`:null}var rP=class extends M{};async function iP(e,t){if(!Rt[process.platform]?.includes(process.arch))return;let n=h.default.homedir(),r,i=await LD({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`,ID(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 aP(e,t={}){if(e.pm!==void 0&&!wO.includes(e.pm))throw new M(`--pm must be one of ${wO.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:OO(e.file,e.env),r=n.kind===`global`||n.kind===`unknown`?DO(e.file):xO,i=await tP(e.registry,r);t.beforeCache?.(),YN(JN(e.env),i,Date.now()),t.cacheRefreshed?.();let a={type:`update-check`,current:e.current,latest:i,install:n.kind};if(!qN(i,e.current))return{...a,upToDate:!0,command:null};if(n.kind===`unknown`){let t=wO.map(e=>` ${eP($N(e,i,r))}`).join(`
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.1`,latest:`1.113.1`,install:OO(__filename,process.env).kind,upToDate:!0,command:null,message:`CLI unchanged; refreshing recorded plugins.`}:await aP({current:`1.113.1`,file:__filename,env:process.env,registry:process.env.npm_config_registry||`https://registry.npmjs.org/`,check:!!e.values.check,pm:e.values.pm},{beforeCache(){a=n.effects.begin(`release-cache`,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.1`,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:`ryugi ${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.1`,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 VN(e){for(let t of Ge(e))d.default.rmSync(f.default.join(Ke(t.dir),`.state`,`server-info`),{force:!0})}function HN({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 UN(){let e=He(),t=t=>{d.default.rmSync(e.info,{force:!0}),VN(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.113.2`});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 WN={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 UN();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:HN},e)};function GN({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 KN={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(LO):void 0;if(r?.some(e=>!mO.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`]||kO()),a=n.effects.begin(`uninstall`,i),o=Sj(i,{targets:r});return o.failures.length||n.effects.confirm(a,o.removed),Y(o,o.failures.length?{kind:`partial`}:{kind:`succeeded`})},present:GN},e)};function qN(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 JN=e=>f.default.join(e.XDG_CACHE_HOME||f.default.join(h.default.homedir(),`.cache`),`ryugi`,`artifacts`,`latest.json`);function YN(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 XN({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 ZN(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 QN={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 FD(e,{reason:`update`,startStopped:!1})}};function $N(e,t,n=xO){let r=`${n}@${t}`;return{cmd:e,args:e===`npm`?[`install`,`-g`,r]:e===`yarn`?[`global`,`add`,r]:[`add`,`-g`,r]}}const eP=({cmd:e,args:t})=>[e,...t].join(` `);async function tP(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 nP(e,t){return e.kind===`transient`?`You ran ${xO} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${xO}@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 rP=class extends M{};async function iP(e,t){if(!Rt[process.platform]?.includes(process.arch))return;let n=h.default.homedir(),r,i=await LD({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`,ID(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 aP(e,t={}){if(e.pm!==void 0&&!wO.includes(e.pm))throw new M(`--pm must be one of ${wO.join(`, `)}`);let n=e.pm?{kind:`global`,pm:e.pm}:OO(e.file,e.env),r=n.kind===`global`||n.kind===`unknown`?DO(e.file):xO,i=await tP(e.registry,r);t.beforeCache?.(),YN(JN(e.env),i,Date.now()),t.cacheRefreshed?.();let a={type:`update-check`,current:e.current,latest:i,install:n.kind};if(!qN(i,e.current))return{...a,upToDate:!0,command:null};if(n.kind===`unknown`){let t=wO.map(e=>` ${eP($N(e,i,r))}`).join(`
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));