ryugi-artifacts 1.76.0 → 1.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +411 -35
- package/dist/output-bootstrap.cjs +9 -2
- package/dist/server.cjs +302 -298
- package/dist/viewer/ArtboardLayout-BTys-6Vg.js +13 -0
- package/dist/viewer/Canvas-CWPtxXag.js +1 -0
- package/dist/viewer/{DocumentLayout-BFuBCe1z.js → DocumentLayout-Bv6Ni6pv.js} +2 -2
- package/dist/viewer/{DocumentPage-BqBUftrx.js → DocumentPage-21BkHTw9.js} +1 -1
- package/dist/viewer/PreviewLayout-Dl9CuJaY.js +2 -0
- package/dist/viewer/{SnapshotDocument-DXjajUyC.js → SnapshotDocument-Cv3OmLv4.js} +1 -1
- package/dist/viewer/channel-BtxKScqa.js +4 -0
- package/dist/viewer/index.js +2 -2
- package/dist/viewer/index4.css +64 -0
- package/dist/viewer/preview.html +2 -2
- package/dist/viewer/preview.js +1 -1
- package/dist/viewer/{printDocument-CHLL0WV9.js → printDocument-C4mixOCB.js} +1 -1
- package/dist/viewer/view-BJqsLsys.js +2 -0
- package/dist/viewer-lib/{Canvas-BwBZAQOH.js → Canvas-CCq4Ko7_.js} +445 -342
- package/dist/viewer-lib/{PhoneArtboardBar-CnuXdNK_.js → PhoneArtboardBar-Cll7l0fz.js} +1 -1
- package/dist/viewer-lib/PreviewView-D7cDFhyg.js +801 -0
- package/dist/viewer-lib/{ReadOnlyWhiteboard-BIrh4itZ.js → ReadOnlyWhiteboard-CmKjtHFJ.js} +59 -59
- package/dist/viewer-lib/{SnapshotDocument-DxFquEK9.js → SnapshotDocument-BSkLVGik.js} +15589 -15547
- package/dist/viewer-lib/{VirtualizedEditor-uWe43zaI-CkFFq0vg.js → VirtualizedEditor-uWe43zaI-BPwh1XeB.js} +2 -2
- package/dist/viewer-lib/{VirtualizedRenderer-C_d95FXi-Dsji27_T.js → VirtualizedRenderer-C_d95FXi-D_uVjc6A.js} +3 -3
- package/dist/viewer-lib/{ar-SA-G6X2FPQ2-BRnkqOuC.js → ar-SA-G6X2FPQ2-HZky6mYE.js} +1 -1
- package/dist/viewer-lib/{az-AZ-76LH7QW2-ehow0VIq.js → az-AZ-76LH7QW2-Bz6gZGXm.js} +1 -1
- package/dist/viewer-lib/{bg-BG-XCXSNQG7-BI6qziGi.js → bg-BG-XCXSNQG7-Bj6azCuS.js} +1 -1
- package/dist/viewer-lib/{bn-BD-2XOGV67Q-tpMGd2_B.js → bn-BD-2XOGV67Q-pkZSsKMV.js} +1 -1
- package/dist/viewer-lib/{ca-ES-6MX7JW3Y-BbUlsBJ3.js → ca-ES-6MX7JW3Y-DInd8tqd.js} +1 -1
- package/dist/viewer-lib/{chunk-EIO257PC-Bv-n7kZ3.js → chunk-EIO257PC-A9RZ-nRE.js} +1 -1
- package/dist/viewer-lib/core.js +3 -3
- package/dist/viewer-lib/{cs-CZ-2BRQDIVT-DSqbdlen.js → cs-CZ-2BRQDIVT-CQ0UDIDw.js} +1 -1
- package/dist/viewer-lib/{da-DK-5WZEPLOC-BjZ1R6o-.js → da-DK-5WZEPLOC-rSt6qKPe.js} +1 -1
- package/dist/viewer-lib/{de-DE-XR44H4JA-BfGPalkL.js → de-DE-XR44H4JA-DrIjWm0C.js} +1 -1
- package/dist/viewer-lib/{dist-mZ0nbNzy.js → dist--CpqpZeP.js} +2 -2
- package/dist/viewer-lib/{dist-DnQNTkTe.js → dist-B-VcBVha.js} +4 -4
- package/dist/viewer-lib/{dist-qYdH7M_t.js → dist-BIRD6yJM.js} +4 -4
- package/dist/viewer-lib/{dist-B8Fcs3nk.js → dist-By5I7Okg.js} +1 -1
- package/dist/viewer-lib/{dist-wfYzTIrG.js → dist-C_4-r-SK.js} +3 -3
- package/dist/viewer-lib/{dist-DullpK1S.js → dist-C_TzQuVj.js} +2 -2
- package/dist/viewer-lib/{dist-_LP1pOLG.js → dist-CiDxjK87.js} +3 -3
- package/dist/viewer-lib/{dist-rgz6xpXM.js → dist-D-o6TefA.js} +3 -3
- package/dist/viewer-lib/{dist-yTJLUGcc.js → dist-D4p8lcBm.js} +3 -3
- package/dist/viewer-lib/{dist-B1gf6Fa6.js → dist-D7GVdiZ_.js} +3 -3
- package/dist/viewer-lib/{dist-DhIKmABp.js → dist-DUp1l9aw.js} +1 -1
- package/dist/viewer-lib/{dist-9o61dnhF.js → dist-DiIs4Wtf.js} +2 -2
- package/dist/viewer-lib/{dist-NA5mGdqC.js → dist-DkB9uL4b.js} +3 -3
- package/dist/viewer-lib/{dist-B20oz2cZ.js → dist-DkRPb1L4.js} +3 -3
- package/dist/viewer-lib/{dist-BkAQ5CG2.js → dist-Do5FbfPB.js} +2 -2
- package/dist/viewer-lib/{dist-Mo4r-8tk.js → dist-DwPZHID8.js} +2 -2
- package/dist/viewer-lib/{dist-DIGLcVme.js → dist-MF77ZiP3.js} +3 -3
- package/dist/viewer-lib/{dist-BfpTX5QK.js → dist-OysWJvrd.js} +2 -2
- package/dist/viewer-lib/{dist-BdKPWdwp.js → dist-SWpcpLKQ.js} +2 -2
- package/dist/viewer-lib/{dist-06BdfUMU.js → dist-T-NoxEoS.js} +4 -4
- package/dist/viewer-lib/{dist-5oASkt9-.js → dist-TTrYwc3n.js} +2 -2
- package/dist/viewer-lib/{dist-Cnmv9jOf.js → dist-nttHr497.js} +3 -3
- package/dist/viewer-lib/{dist-6StWP8sP.js → dist-z5xmIJm7.js} +3 -3
- package/dist/viewer-lib/document.js +3 -3
- package/dist/viewer-lib/{el-GR-BZB4AONW-BvUZSnTi.js → el-GR-BZB4AONW-3kVOQ15p.js} +1 -1
- package/dist/viewer-lib/{en-B4ZKOASM-Dyp8KE8C.js → en-B4ZKOASM-sas4DJvS.js} +1 -1
- package/dist/viewer-lib/{es-ES-U4NZUMDT-B1PZEwLb.js → es-ES-U4NZUMDT-DF1DXGeP.js} +1 -1
- package/dist/viewer-lib/{eu-ES-A7QVB2H4-BNk6M67A.js → eu-ES-A7QVB2H4-CIu5bgjr.js} +1 -1
- package/dist/viewer-lib/{fa-IR-HGAKTJCU-CEtlDVKb.js → fa-IR-HGAKTJCU-Dg12PelN.js} +1 -1
- package/dist/viewer-lib/{fi-FI-Z5N7JZ37-CqXNLgJp.js → fi-FI-Z5N7JZ37-DGfGckr2.js} +1 -1
- package/dist/viewer-lib/{fr-FR-RHASNOE6-D7dtIipP.js → fr-FR-RHASNOE6-CB3RBQBb.js} +1 -1
- package/dist/viewer-lib/{gl-ES-HMX3MZ6V-Cgo7fAtE.js → gl-ES-HMX3MZ6V-srdgH8Yb.js} +1 -1
- package/dist/viewer-lib/{he-IL-6SHJWFNN-Bm1-H99W.js → he-IL-6SHJWFNN-C-u3aIrD.js} +1 -1
- package/dist/viewer-lib/{hi-IN-IWLTKZ5I-yK8E_0J9.js → hi-IN-IWLTKZ5I-DnRD5RwM.js} +1 -1
- package/dist/viewer-lib/{hu-HU-A5ZG7DT2-C98VrJxm.js → hu-HU-A5ZG7DT2-cHUeODPe.js} +1 -1
- package/dist/viewer-lib/{id-ID-SAP4L64H-TIdVGjhY.js → id-ID-SAP4L64H-BYp8Yosj.js} +1 -1
- package/dist/viewer-lib/{image-GAAHSSAO-Bi1NqWd6.js → image-GAAHSSAO-MaHRDtG2.js} +1 -1
- package/dist/viewer-lib/index.js +3117 -3076
- package/dist/viewer-lib/{it-IT-JPQ66NNP-627ORc6z.js → it-IT-JPQ66NNP-K76B2vDZ.js} +1 -1
- package/dist/viewer-lib/{ja-JP-DBVTYXUO-BMKJR86l.js → ja-JP-DBVTYXUO-DGtajQ1n.js} +1 -1
- package/dist/viewer-lib/{kaa-6HZHGXH3-BpSB5geq.js → kaa-6HZHGXH3-Byq6aZnP.js} +1 -1
- package/dist/viewer-lib/{kab-KAB-ZGHBKWFO-BfYd3nUy.js → kab-KAB-ZGHBKWFO-xFQx0VKj.js} +1 -1
- package/dist/viewer-lib/{kk-KZ-P5N5QNE5-B2w9l6j_.js → kk-KZ-P5N5QNE5-DqTYtjE9.js} +1 -1
- package/dist/viewer-lib/{km-KH-HSX4SM5Z-DpRvnOD3.js → km-KH-HSX4SM5Z-CmHVZ3Pg.js} +1 -1
- package/dist/viewer-lib/{ko-KR-MTYHY66A-CGrV1Spl.js → ko-KR-MTYHY66A-pItxT0ea.js} +1 -1
- package/dist/viewer-lib/{ku-TR-6OUDTVRD-DGfmXOnJ.js → ku-TR-6OUDTVRD-DJoNwVzF.js} +1 -1
- package/dist/viewer-lib/{lt-LT-XHIRWOB4-DW9cVrrY.js → lt-LT-XHIRWOB4-DG1eQnL9.js} +1 -1
- package/dist/viewer-lib/{lv-LV-5QDEKY6T-CDlwVi5d.js → lv-LV-5QDEKY6T-BAFyGSRK.js} +1 -1
- package/dist/viewer-lib/{mr-IN-CRQNXWMA-DZTsb8X7.js → mr-IN-CRQNXWMA-Dpt8RtYD.js} +1 -1
- package/dist/viewer-lib/{my-MM-5M5IBNSE-eimCGnfV.js → my-MM-5M5IBNSE-PB-QhewM.js} +1 -1
- package/dist/viewer-lib/{nb-NO-T6EIAALU-CA0qj8A_.js → nb-NO-T6EIAALU-DUOVY3a0.js} +1 -1
- package/dist/viewer-lib/{nl-NL-IS3SIHDZ-xjXdrqei.js → nl-NL-IS3SIHDZ-EvHXncDP.js} +1 -1
- package/dist/viewer-lib/{nn-NO-6E72VCQL-BFaVKUPb.js → nn-NO-6E72VCQL-DiLJJ6in.js} +1 -1
- package/dist/viewer-lib/{oc-FR-POXYY2M6-x-knw1UV.js → oc-FR-POXYY2M6-BcMNlMjU.js} +1 -1
- package/dist/viewer-lib/{pa-IN-N4M65BXN-BzuUR6mV.js → pa-IN-N4M65BXN-y8F6i_xQ.js} +1 -1
- package/dist/viewer-lib/{percentages-BXMCSKIN-DUBJl_II.js → percentages-BXMCSKIN-BcGLGIbY.js} +1 -1
- package/dist/viewer-lib/{pl-PL-T2D74RX3-GB1o6A0p.js → pl-PL-T2D74RX3-BcJAM87-.js} +1 -1
- package/dist/viewer-lib/{printDocument-DjfXK0VD.js → printDocument-Bw-KNCCN.js} +2 -2
- package/dist/viewer-lib/{pt-BR-5N22H2LF-CjKPG-dA.js → pt-BR-5N22H2LF-B6LXfMUc.js} +1 -1
- package/dist/viewer-lib/{pt-PT-UZXXM6DQ-DXKwitID.js → pt-PT-UZXXM6DQ-Bp-xUqQ8.js} +1 -1
- package/dist/viewer-lib/{ro-RO-JPDTUUEW-GXm0K0W-.js → ro-RO-JPDTUUEW-BSUxwWXI.js} +1 -1
- package/dist/viewer-lib/{ru-RU-B4JR7IUQ-C3aifH4r.js → ru-RU-B4JR7IUQ-CQdjNcBG.js} +1 -1
- package/dist/viewer-lib/{si-LK-N5RQ5JYF-CbCU4-qM.js → si-LK-N5RQ5JYF-7CAmmMro.js} +1 -1
- package/dist/viewer-lib/{sk-SK-C5VTKIMK-oq8tYd7x.js → sk-SK-C5VTKIMK-CpC5WEtb.js} +1 -1
- package/dist/viewer-lib/{sl-SI-NN7IZMDC-CqbGY6Ud.js → sl-SI-NN7IZMDC-s5Digk56.js} +1 -1
- package/dist/viewer-lib/{static-rqLqPT6F.js → static-BL_ltq0p.js} +2 -2
- package/dist/viewer-lib/{stylex-DKFn6mfl.css → stylex-B6-Q1VRZ.css} +70 -0
- package/dist/viewer-lib/subset-shared.chunk-DVeVdUoS.js +2 -0
- package/dist/viewer-lib/{subset-worker.chunk-DPMoD5NG.js → subset-worker.chunk-V92b2YKH.js} +2 -2
- package/dist/viewer-lib/{sv-SE-XGPEYMSR-Bsf1cby9.js → sv-SE-XGPEYMSR-D7xx9CF4.js} +1 -1
- package/dist/viewer-lib/{ta-IN-2NMHFXQM-eRp4M6qC.js → ta-IN-2NMHFXQM-DbRLNuGy.js} +1 -1
- package/dist/viewer-lib/{th-TH-HPSO5L25-DW9SpgaC.js → th-TH-HPSO5L25-FmDN7f8Q.js} +1 -1
- package/dist/viewer-lib/thumbnail.js +281 -1
- package/dist/viewer-lib/{tr-TR-DEFEU3FU-pOCJfq5E.js → tr-TR-DEFEU3FU-C6SMoY6h.js} +1 -1
- package/dist/viewer-lib/types/src/shared/flow.d.ts +24 -0
- package/dist/viewer-lib/types/src/shared/geometry.d.ts +7 -0
- package/dist/viewer-lib/types/src/shared/types.d.ts +7 -1
- package/dist/viewer-lib/types/src/shared/validate.d.ts +1 -0
- package/dist/viewer-lib/types/src/viewer/components/BoardPlaceholder.d.ts +1 -1
- package/dist/viewer-lib/types/src/viewer/components/BoardsOverview.d.ts +12 -0
- package/dist/viewer-lib/types/src/viewer/components/Canvas.d.ts +5 -2
- package/dist/viewer-lib/types/src/viewer/components/CanvasNotes.d.ts +6 -0
- package/dist/viewer-lib/types/src/viewer/components/DebugHud.d.ts +2 -1
- package/dist/viewer-lib/types/src/viewer/components/FlowLayer.d.ts +9 -0
- package/dist/viewer-lib/types/src/viewer/components/Labels.d.ts +2 -1
- package/dist/viewer-lib/types/src/viewer/document/tocStyles.d.ts +24 -1
- package/dist/viewer-lib/types/src/viewer/hooks/useBoardLifecycle.d.ts +3 -2
- package/dist/viewer-lib/types/src/viewer/hooks/useCulledBoards.d.ts +1 -0
- package/dist/viewer-lib/types/src/viewer/lib/board-lifecycle.d.ts +13 -1
- package/dist/viewer-lib/types/src/viewer/lib/cull.d.ts +1 -0
- package/dist/viewer-lib/types/src/viewer/lib/overview.d.ts +15 -0
- package/dist/viewer-lib/{uk-UA-QMV73CPH-DkgFEjc5.js → uk-UA-QMV73CPH-UOEzCOen.js} +1 -1
- package/dist/viewer-lib/{vi-VN-M7AON7JQ-DW2UXo4M.js → vi-VN-M7AON7JQ-Dxi27jBl.js} +1 -1
- package/dist/viewer-lib/{viewport-CFJHn_Y6-d5wzsaWt.js → viewport-CFJHn_Y6-CcY0_b0z.js} +1 -1
- package/dist/viewer-lib/{zh-CN-LNUGB5OW-APfqTduX.js → zh-CN-LNUGB5OW-BkbG5N7o.js} +1 -1
- package/dist/viewer-lib/{zh-HK-E62DVLB3-SgR07W8h.js → zh-HK-E62DVLB3-Btkkw8Q_.js} +1 -1
- package/dist/viewer-lib/{zh-TW-RAJ6MFWO-BByKMSmL.js → zh-TW-RAJ6MFWO-BeX560km.js} +1 -1
- package/package.json +1 -1
- package/dist/viewer/ArtboardLayout-LjqEYnU4.js +0 -13
- package/dist/viewer/Canvas-DhxIof5j.js +0 -1
- package/dist/viewer/PreviewLayout-Bx_Yf3rn.js +0 -2
- package/dist/viewer/channel-ieJNPeHy.js +0 -4
- package/dist/viewer/view-DK0Yp3Y_.js +0 -2
- package/dist/viewer-lib/PreviewView-DXGaELRD.js +0 -431
- package/dist/viewer-lib/subset-shared.chunk-CCczPz6Y.js +0 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,31 +1,405 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var Ss=Object.create;var kr=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var xs=Object.getPrototypeOf,As=Object.prototype.hasOwnProperty;var Es=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rs(t))!As.call(e,o)&&o!==r&&kr(e,o,{get:()=>t[o],enumerable:!(n=Cs(t,o))||n.enumerable});return e};var C=(e,t,r)=>(r=e!=null?Ss(xs(e)):{},Es(t||!e||!e.__esModule?kr(r,"default",{value:e,enumerable:!0}):r,e));var xr=require("node:util");var m=class extends Error{constructor(r,n="failed",o){super(r.message);this.error=r;this.kind=n;this.raw=o}error;kind;raw};function He(e){if(e instanceof m)return e.error;let t=e,r=t?.fields;return{code:typeof r?.code=="string"?`E_${r.code.toUpperCase().replace(/^E_/,"")}`:"E_COMMAND_FAILED",message:typeof t?.message=="string"&&t.message?t.message:typeof r?.message=="string"?r.message:String(e),...typeof r?.status=="number"?{httpStatus:r.status}:{},...r&&Object.keys(r).length?{details:r}:{}}}function be(e,t=!1){switch(e.kind){case"succeeded":return{outcome:t?"attention":"success",code:0};case"validation_failed":return{outcome:"attention",code:3};case"pending":return{outcome:"pending",code:4};case"action_required":return{outcome:"attention",code:2};case"partial":return{outcome:"partial",code:5};case"failed":return{outcome:"error",code:1};case"interrupted":return{outcome:"error",code:e.signal==="SIGINT"?130:143}}}function Sr(e,t,r,n){return!e||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).filter(([o])=>t.includes(o)?!0:(n.push({path:`${r}.${o}`,reason:"fields"}),!1)))}function Tt(e,t,r,n){let o=[...t.coverage.omitted??[]],s=t.data;if(r.fields){let i=[...new Set([...r.fields,...n.requiredFields??[]])];if(n.collection&&s&&typeof s=="object"){let a=s,c=a[n.collection];s={...a,[n.collection]:Array.isArray(c)?c.map((l,u)=>Sr(l,i,`data.${n.collection}.${u}`,o)):c}}else s=Sr(s,i,"data",o)}return{schema:"ryugi.cli/v1",command:e,outcome:be(t.completion,t.warnings.length>0).outcome,data:s,...t.coverage.page?{page:t.coverage.page}:{},...o.length?{omitted:o}:{},...t.effects.length?{effects:t.effects}:{},...t.warnings.length?{warnings:t.warnings}:{},...t.actions.length?{next:t.actions}:{},...t.completion.kind==="failed"?{error:t.completion.error}:t.completion.kind==="interrupted"?{error:{code:"E_INTERRUPTED",message:`Command interrupted by ${t.completion.signal}.`,details:{signal:t.completion.signal}}}:{}}}var Cr={format:{type:"string",value:"<brief|table|json|jsonl|raw>",help:"Output format (default: brief)"},json:{type:"boolean",help:"Shorthand for --format json"},detail:{type:"boolean",help:"Read complete evidence for the selected object or page"},fields:{type:"string",value:"<fields>",help:"Select public output fields, separated by commas"},quiet:{type:"boolean",help:"Print the command's declared scalar only"},verbose:{type:"boolean",help:"Include diagnostic details on stderr"}};function _t(e,t){let r={};for(let n=0;n<e.length;n++){let o=e[n];if(o==="--")break;if(!o.startsWith("--"))continue;let s=o.indexOf("="),i=o.slice(2,s<0?void 0:s),a=i==="source"?"boolean":t[i]?.type;a==="string"?r[i]=s<0?e[++n]??"":o.slice(s+1):a==="boolean"&&(r[i]=!0)}return r}function $t(e,t,r=process.env){let n=_t(e,t),o=["format","json","quiet","source"].filter(d=>n[d]!==void 0),s=r.RYUGI_ARTIFACTS_FORMAT??"brief",i=n.format??(n.json?"json":n.quiet?"quiet":n.source?"source":s),c=["brief","table","json","jsonl","raw","source","quiet"].includes(i),l={format:c?i:"brief",detail:!!n.detail||!!n.source,verbose:!!n.verbose},u;return o.length>1?u=new m({code:"E_OPTION_CONFLICT",message:"Choose one of --format, --json, --quiet or --source."}):(!c||!o.length&&!["brief","json","jsonl"].includes(s))&&(u=new m({code:"E_FORMAT_UNSUPPORTED",message:`Unknown output format: ${String(i)}`})),typeof n.fields=="string"&&(l.fields=n.fields.split(",").map(d=>d.trim()),l.fields.some(d=>!d)&&(u=new m({code:"E_ARGUMENT_INVALID",message:"--fields requires comma-separated field names."}))),{options:l,...u?{error:u}:{}}}var we=C(require("node:fs"),1),Rr=C(require("node:os"),1),V=C(require("node:path"),1),w=class extends Error{constructor(r,n={},o=1){super(r);this.fields=n;this.code=o}fields;code};function Is(e){let t="";try{t=we.default.realpathSync(Rr.default.homedir())}catch{}let r=[];for(let n=e;r.push(n),!(we.default.existsSync(V.default.join(n,".git"))&&(n!==t||e===t));n=V.default.dirname(n))if(V.default.dirname(n)===n)return e;return r.find(n=>we.default.existsSync(V.default.join(n,".ryugi","artifacts")))??r.at(-1)}function U(e){let t;try{if(t=we.default.realpathSync(V.default.resolve(e)),!we.default.statSync(t).isDirectory())throw new Error("Not a directory")}catch{throw new w(`Project directory not found: ${e}`)}t=Is(t);let r=V.default.join(t,".ryugi","artifacts"),n=V.default.join(r,".state");return{project:t,root:r,state:n,pid:V.default.join(n,"server.pid"),log:V.default.join(n,"server.log"),serverId:V.default.join(n,"server-instance-id"),info:V.default.join(n,"server-info"),version:V.default.join(n,"server-version"),owners:V.default.join(n,"owners"),agent:V.default.join(n,"agent"),stopped:V.default.join(n,"server-stopped"),lock:V.default.join(n,"start.lock")}}var Oe=()=>process.env.RYUGI_ARTIFACTS_COMMAND||"ryugi",Y=/^(artboard|document|html|whiteboard|verify)\/[a-z0-9][a-z0-9-]*$/,re="--artifact must be <type>/<id>: type artboard, document, whiteboard, html or verify; id of lowercase letters, digits and hyphens";var Be="ryugi",J={...Cr,"project-dir":{type:"string",value:"<path>",help:"Project directory (default: current directory)"}},Ar={help:{type:"boolean",short:"h",help:"Show this help"}};function fe(e,t,r=0){let n={...J,...t},o=Object.fromEntries(Object.entries({...J,...t}).map(([s,{type:i,short:a}])=>[s,a?{type:i,short:a}:{type:i}]));try{let s=[];for(let a=0;a<e.length;a++){let c=e[a];if(c==="--"){s.push(...e.slice(a));break}let l=e[a+1],u=l==="-h"||Object.values(n).some(d=>d.short&&l===`-${d.short}`);c.startsWith("--")&&n[c.slice(2)]?.type==="string"&&l?.startsWith("-")&&!l.startsWith("--")&&!u?(s.push(`${c}=${l}`),a++):s.push(c)}let i=(0,xr.parseArgs)({args:s,options:o,allowPositionals:r>0,strict:!0});if(i.positionals.length>r)throw new w(`Unknown argument: ${i.positionals[r]}`);return{values:i.values,positionals:i.positionals,projectDir:i.values["project-dir"]??process.cwd()}}catch(s){if(s instanceof w)throw s;if(s.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"){let i=/'([^']+)'/.exec(s.message)?.[1];if(i)throw new w(`Unknown argument: ${i}`)}throw new w(s.message)}}function Er(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).some(r=>r==="--help"||r==="-h")}function Pt(e){let t=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,n])=>` ${r.padEnd(t)}${n.replaceAll(`
|
|
3
3
|
`,`
|
|
4
4
|
${" ".repeat(t)}`)}`.trimEnd()).join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`),"",e.summary,...e.details?["",e.details]:[],"","Options:",
|
|
7
|
-
`)}function
|
|
8
|
-
`)}var Ee={claude:"Claude Code","claude-code":"Claude Code",cowork:"Claude Cowork",codex:"Codex",cursor:"Cursor","cursor-cli":"Cursor",gemini:"Gemini CLI","gemini-cli":"Gemini CLI",grok:"Grok","grok-cli":"Grok","github-copilot":"GitHub Copilot","github-copilot-cli":"GitHub Copilot",kilo:"Kilo Code",omp:"OMP","oh-my-pi":"OMP",opencode:"OpenCode","qwen-code":"Qwen Code",antigravity:"Antigravity",augment:"Augment","augment-cli":"Augment",goose:"Goose",amp:"Amp",cline:"Cline",roo:"Roo Code",devin:"Devin",replit:"Replit",v0:"v0"},_a=[...new Set(Object.values(Ee))],es=[["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)]],Sr=["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"],vr=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0;function ge(e){if(e.CLAUDE_CODE_IS_COWORK)return Ee.cowork;let t=vr(e.AI_AGENT);if(t)return Ee[t]??t;let r=es.find(([,o])=>o(e))?.[0];if(r)return Ee[r];let n=vr(e.AGENT);if(n&&!/^(?:1|true|yes)$/.test(n))return Ee[n]??n}var Fe={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"]},Rr={threads:["id","status","waitingOn"],asks:["id","state"],groups:["id","kind","verdict","choice"],rounds:["id","state"]},It=e=>e.startsWith("document/")?["threads","asks"]:["threads","groups","rounds"];function Cr(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(r=>!It(t).includes(r))?"Choose distinct review sections supported by this artifact.":e.fields||e.cursor||e.snapshot||e.thread||e.filters&&Object.values(e.filters).some(r=>r!==void 0)?"Fields, filters, thread, cursor and snapshot require a single --section. Follow each collection continuation separately.":null}function kr(e){let{section:t,filters:r}=e;if(!t&&(e.detail||e.cursor||e.fields||r&&Object.values(r).some(Boolean)))return"Choose a section before requesting detail, fields, filters or a cursor.";if(t&&!(t in Fe))return"Unknown review section.";if(r&&Object.keys(r).some(o=>!["status","waitingOn","kind","choiceState"].includes(o)))return"Unknown review filter.";if(r?.waitingOn&&(t!=="threads"||!["agent","human","any"].includes(r.waitingOn)))return"waitingOn applies to threads and must be agent, human or any.";let n=t==="threads"?["open","resolved"]:t==="asks"?["draft","submitted","settled","orphan"]:t==="groups"?["pending","pass","reject"]:["open","submitted","closed"];return r?.status&&!n.includes(r.status)?"Invalid status for this section.":r?.kind&&(t!=="groups"||!["choose","verify"].includes(r.kind))?"kind applies to groups.":t==="groups"&&r?.status&&r.kind!=="verify"?"Verify status requires kind=verify.":r?.choiceState&&(t!=="groups"||r.kind!=="choose"||!["chosen","empty"].includes(r.choiceState))?"choiceState requires a choice group.":t&&e.fields?.some(o=>!Fe[t].includes(o))?"Unknown field for this section.":null}function E(e,t={kind:"succeeded"},r={}){return{data:e,completion:t,coverage:{},effects:[],warnings:[],actions:[],...r}}var Ue=class{entries=[];begin(t,r){return this.entries.push({operation:t,target:r,state:"unknown"}),this.entries.length-1}confirm(t,r){this.set(t,"confirmed",r)}set(t,r,n){let o=this.entries[t];if(!o)throw new Error("Unknown effect");this.entries[t]={...o,state:r,...n===void 0?{}:{details:n}}}snapshot(){return this.entries.map(t=>({...t}))}};var ts=/^\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)$/,he=e=>String(e).padStart(2,"0"),Er=e=>typeof e=="string"&&ts.test(e)&&!Number.isNaN(Date.parse(e));function Ae(e,t=new Date){let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let n=`${he(r.getHours())}:${he(r.getMinutes())}`;return r.getFullYear()!==t.getFullYear()?`${r.getFullYear()}-${he(r.getMonth()+1)}-${he(r.getDate())}`:r.getMonth()===t.getMonth()&&r.getDate()===t.getDate()?n:`${he(r.getMonth()+1)}-${he(r.getDate())} ${n}`}function Ge(e,t){let r=e.details;return!r||typeof r!="object"||Array.isArray(r)?[]:Object.entries(r).flatMap(([n,o])=>typeof o=="string"&&/^https?:\/\/\S+$/i.test(o)?[{kind:"url",label:t?`${t} ${n}`:n,url:o}]:[])}var I=(e,t)=>({key:t,value:e[t]}),S=(e,t,r=!1)=>({label:e,binding:t,required:r});var L=e=>e.replaceAll(new RegExp("\\p{Cc}","gu")," ");function rs(e,t=160){let r=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)];return r.length>t?`${r.slice(0,t).map(n=>n.segment).join("")}\u2026`:e}function We(e,t=!1){if(e==null)return"";if(Array.isArray(e))return e.map(r=>We(r,!0)).join(", ");if(typeof e=="object"){let r=Object.entries(e).filter(([,n])=>!Ve(n)).map(([n,o])=>`${n} ${We(o,!0)}`).join(t?", ":" \xB7 ");return t?`(${r})`:r}return Er(e)?Ae(e):String(e)}var ns=(e,t,r)=>{if(e!==null&&typeof e=="object"){if(!r)throw new Error(`Brief cannot print the object at ${t}; flatten it in the view.`);return We(e)}return We(e)},Ve=(e,t)=>e==null||e===""||e===!1||t!==void 0&&e===t,os={1:"FAILED",2:"NEEDS YOU",3:"ISSUES",4:"INCOMPLETE",5:"PARTIAL",130:"INTERRUPTED",143:"INTERRUPTED"},ss={E_ARTIFACT_NOT_FOUND:"check --artifact and --project-dir; artifacts live in <project>/.ryugi/artifacts/<type>/<id>/",E_ARGUMENT_INVALID:"run the command with --help for its options",E_CURSOR_EXPIRED:"run the read again without --cursor or --snapshot",E_CURSOR_MISMATCH:"run the read again without --cursor or --snapshot"},is=(e,t)=>t?os[t]??"FAILED":L(e).replaceAll("_"," ").toUpperCase(),as=e=>{let t=e.replaceAll(/[._]/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):"Command"};function cs(e){let t=e.offset??0;if(!e.hasMore&&t===0)return null;let r=e.total===null?"":` of ${e.total}`;return e.offset===void 0?`${e.returned}${r} shown${e.total===null&&e.hasMore?" \xB7 more available":""}`:`${e.returned?`${t+1}\u2013${t+e.returned}`:"none"}${r}`}var us=e=>/^[\w./:@=+-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`;function qe(e){return e.kind==="command"?e.argv.map(us).join(" "):e.url}var ls=e=>e.map(t=>`Effect: ${L(t.operation)} ${L(t.target)} \xB7 ${t.state}`),ds=e=>e.split(".").filter(Boolean).at(-1)??e;function Ot(e,t,r,n,o=[],s=0){let i=[is(e.status,s),e.subject&&L(e.subject),e.summary&&L(e.summary)].filter(Boolean),a=[i.length?`${L(e.heading)}: ${i.join(" \xB7 ")}`:L(e.heading)],c=[...t.omitted??[]],d=(u,y=!1)=>y||o.includes(u)||!r.fields||r.fields.includes(u),l=(u,y,g=!1)=>{let h=L(ns(u,y,g)),C=r.detail?h:rs(h);return C!==h&&c.push({path:y,reason:"preview"}),C},p=(u,y,g,h,C,P,_=!1)=>{if(Ve(g,P))return null;let T=L(u??y);if(g===!0)return T;let D=l(g,h,_);return C?D:`${T} ${D}`},f=(u,y=!1)=>{for(let g of u){if(!n&&!d(g.binding.key,g.required)||Ve(g.binding.value))continue;let h=g.binding.value===!0?"yes":l(g.binding.value,`data.${g.binding.key}`,y);a.push(`${L(g.label)}: ${h}`)}},k=(u,y)=>u.map(g=>p(g.label,g.binding.key,g.binding.value,`${y}.${g.binding.key}`,g.positional)).filter(g=>g!==null).join(" \xB7 "),R=(u,y)=>{u&&a.push(y?`${L(u)} \xB7 ${L(y)}`:L(u))},j=u=>{let y=u&&cs(u);y&&a.push(y)};f(e.facts);let N=t.error?Ge(t.error):[];if(t.error){a.push(`${L(t.error.code)}: ${L(t.error.message)}`),t.error.httpStatus!==void 0&&t.error.httpStatus>=500&&a.push(`HTTP: ${t.error.httpStatus}`);let u=ss[t.error.code];u&&a.push(`Next: ${u}`);let y=t.error.details;if(y&&typeof y=="object"&&!Array.isArray(y))for(let[g,h]of Object.entries(y))N.some(C=>C.label===g)||f([{label:g,binding:{key:g,value:h},required:!0}],!0);else y!==void 0&&f([{label:"Details",binding:{key:"details",value:y},required:!0}],!0)}if(!n&&r.fields&&t.data&&typeof t.data=="object"){let u=new Set([...e.facts.map(g=>g.binding.key),...e.sections.flatMap(g=>g.kind==="fields"?g.facts.map(h=>h.binding.key):[g.key])]),y=t.data;f([...new Set([...r.fields,...o])].filter(g=>!u.has(g)&&Object.hasOwn(y,g)).map(g=>({label:g,binding:{key:g,value:y[g]}})),!0)}for(let u of e.sections){if(u.kind==="fields"){f(u.facts);continue}if(!n&&!d(u.key))continue;let y="title"in u&&u.title?u.title:void 0;if(u.kind==="records"){R(y??(u.page?u.key:void 0),u.summary);let g=new Set(u.columns.map(_=>_.key)),h=u.key===n?[...new Set([...r.fields??[],...r.fields?o:[]])].filter(_=>!g.has(_)).map(_=>({key:_,label:_})):[],C=new Set(h.map(_=>_.key)),P=[...u.columns,...h].filter(_=>u.key!==n||d(_.key,_.required));if(r.format==="table"){let _=P.map(K=>K.label??K.key),T=u.rows.map((K,de)=>P.map(X=>Ve(K[X.key],X.default)?"":l(K[X.key],`data.${u.key}.${de}.${X.key}`,C.has(X.key)))),D=_.map((K,de)=>Math.max(K.length,...T.map(X=>X[de]?.length??0)));a.push(...[_,...T].map(K=>K.map((de,X)=>de.padEnd(D[X]??de.length)).join(" ").trimEnd()))}else for(let[_,T]of u.rows.entries())a.push(` ${P.map(D=>p(D.label,D.key,T[D.key],`data.${u.key}.${_}.${D.key}`,D.positional,D.default,C.has(D.key))).filter(D=>D!==null).join(" \xB7 ")}`);!u.rows.length&&!y&&!u.page&&a.push("No records."),j(u.page)}else if(u.kind==="messages"){R(y,u.summary);for(let[g,h]of u.groups.entries()){a.push(` ${k(h.facts,`data.${u.key}.${g}`)}`);for(let[C,P]of h.messages.entries())a.push(` ${k(P.facts,`data.${u.key}.${g}.messages.${C}`)}`),a.push(...P.text.split(`
|
|
9
|
-
`).map(
|
|
10
|
-
`).map(g=>` ${g.replaceAll(new RegExp("\\p{Cc}","gu"),
|
|
11
|
-
`?
|
|
5
|
+
`)}function Ir(e){return Object.entries(e).filter(([,t])=>t.help!==void 0).map(([t,r])=>[`${r.short?`-${r.short}, `:""}--${t}${r.value?` ${r.value}`:""}`,r.help])}function Nt(e,t){if(!t)return e.options;let r=e.usage?.filter(o=>o.split(/\s/)[0]===t)??[];if(!r.length)throw new w(`Unknown ${e.name} action: ${t}`);let n=new Set([...r.flatMap(o=>[...o.matchAll(/--([\w-]+)/g)].map(s=>s[1])),...e.actionOptions?.[t]??[]]);return Object.fromEntries(Object.entries(e.options).filter(([o])=>n.has(o)))}function Or(e,t){let r=Nt(e,t);return[(e.usage??["[options]"]).filter(o=>!t||o.split(/\s/)[0]===t).map((o,s)=>`${s?" ":"Usage: "}${Be} ${e.name} ${o}`).join(`
|
|
6
|
+
`),"",e.summary,...e.details?["",e.details]:[],"","Options:",Pt(Ir({...r,...J,...Ar}))].join(`
|
|
7
|
+
`)}function jr(e,t={}){return[`Usage: ${Be} [project-directory] [--no-open]`,` ${Be} <command> [options]`,"","Without a command, opens the project's artifacts in your browser and keeps the server","running until Ctrl+C.","","Commands:",Pt(e.map(r=>[r.name,r.summary])),"","Tasks:"," Write or edit: start --background --no-open --artifact <type>/<id>, edit the returned file, then check."," Find or read: get --project-dir <path> (local); get <link-or-id> (cloud); scene for a whiteboard."," Apply feedback: comment list --artifact <type>/<id> --sections all --detail; changes for document edits."," Organize and share: modules, config, publish. Prepare the environment: install, update, start, stop."," Automation: start is finite by default; use --foreground for a live process. JSON uses ryugi.cli/v1.","",`Run \`${Be} <command> --help\` for a command's options.`,"","Options:",Pt(Ir({...J,...t,version:{type:"boolean",short:"v",help:"Print the version"},...Ar}))].join(`
|
|
8
|
+
`)}var je={claude:"Claude Code","claude-code":"Claude Code",cowork:"Claude Cowork",codex:"Codex",cursor:"Cursor","cursor-cli":"Cursor",gemini:"Gemini CLI","gemini-cli":"Gemini CLI",grok:"Grok","grok-cli":"Grok","github-copilot":"GitHub Copilot","github-copilot-cli":"GitHub Copilot",kilo:"Kilo Code",omp:"OMP","oh-my-pi":"OMP",opencode:"OpenCode","qwen-code":"Qwen Code",antigravity:"Antigravity",augment:"Augment","augment-cli":"Augment",goose:"Goose",amp:"Amp",cline:"Cline",roo:"Roo Code",devin:"Devin",replit:"Replit",v0:"v0"},dc=[...new Set(Object.values(je))],Os=[["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)]],_r=["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"],Tr=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0;function ve(e){if(e.CLAUDE_CODE_IS_COWORK)return je.cowork;let t=Tr(e.AI_AGENT);if(t)return je[t]??t;let r=Os.find(([,o])=>o(e))?.[0];if(r)return je[r];let n=Tr(e.AGENT);if(n&&!/^(?:1|true|yes)$/.test(n))return je[n]??n}var Je={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"]},$r={threads:["id","status","waitingOn"],asks:["id","state"],groups:["id","kind","verdict","choice"],rounds:["id","state"]},Dt=e=>e.startsWith("document/")?["threads","asks"]:["threads","groups","rounds"];function Pr(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(r=>!Dt(t).includes(r))?"Choose distinct review sections supported by this artifact.":e.fields||e.cursor||e.snapshot||e.thread||e.filters&&Object.values(e.filters).some(r=>r!==void 0)?"Fields, filters, thread, cursor and snapshot require a single --section. Follow each collection continuation separately.":null}function Nr(e){let{section:t,filters:r}=e;if(!t&&(e.detail||e.cursor||e.fields||r&&Object.values(r).some(Boolean)))return"Choose a section before requesting detail, fields, filters or a cursor.";if(t&&!(t in Je))return"Unknown review section.";if(r&&Object.keys(r).some(o=>!["status","waitingOn","kind","choiceState"].includes(o)))return"Unknown review filter.";if(r?.waitingOn&&(t!=="threads"||!["agent","human","any"].includes(r.waitingOn)))return"waitingOn applies to threads and must be agent, human or any.";let n=t==="threads"?["open","resolved"]:t==="asks"?["draft","submitted","settled","orphan"]:t==="groups"?["pending","pass","reject"]:["open","submitted","closed"];return r?.status&&!n.includes(r.status)?"Invalid status for this section.":r?.kind&&(t!=="groups"||!["choose","verify"].includes(r.kind))?"kind applies to groups.":t==="groups"&&r?.status&&r.kind!=="verify"?"Verify status requires kind=verify.":r?.choiceState&&(t!=="groups"||r.kind!=="choose"||!["chosen","empty"].includes(r.choiceState))?"choiceState requires a choice group.":t&&e.fields?.some(o=>!Je[t].includes(o))?"Unknown field for this section.":null}function x(e,t={kind:"succeeded"},r={}){return{data:e,completion:t,coverage:{},effects:[],warnings:[],actions:[],...r}}var Ye=class{entries=[];begin(t,r){return this.entries.push({operation:t,target:r,state:"unknown"}),this.entries.length-1}confirm(t,r){this.set(t,"confirmed",r)}set(t,r,n){let o=this.entries[t];if(!o)throw new Error("Unknown effect");this.entries[t]={...o,state:r,...n===void 0?{}:{details:n}}}snapshot(){return this.entries.map(t=>({...t}))}};var js=/^\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)$/,ke=e=>String(e).padStart(2,"0"),Dr=e=>typeof e=="string"&&js.test(e)&&!Number.isNaN(Date.parse(e));function Te(e,t=new Date){let r=new Date(e);if(Number.isNaN(r.getTime()))return e;let n=`${ke(r.getHours())}:${ke(r.getMinutes())}`;return r.getFullYear()!==t.getFullYear()?`${r.getFullYear()}-${ke(r.getMonth()+1)}-${ke(r.getDate())}`:r.getMonth()===t.getMonth()&&r.getDate()===t.getDate()?n:`${ke(r.getMonth()+1)}-${ke(r.getDate())} ${n}`}function Se(e,t){let r=e.details;return!r||typeof r!="object"||Array.isArray(r)?[]:Object.entries(r).flatMap(([n,o])=>typeof o=="string"&&/^https?:\/\/\S+$/i.test(o)?[{kind:"url",label:t?`${t} ${n}`:n,url:o}]:[])}var A=(e,t)=>({key:t,value:e[t]}),b=(e,t,r=!1)=>({label:e,binding:t,required:r});var L=e=>e.replaceAll(new RegExp("\\p{Cc}","gu")," ");function Ts(e,t=160){let r=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)];return r.length>t?`${r.slice(0,t).map(n=>n.segment).join("")}\u2026`:e}function Ke(e,t=!1){if(e==null)return"";if(Array.isArray(e))return e.map(r=>Ke(r,!0)).join(", ");if(typeof e=="object"){let r=Object.entries(e).filter(([,n])=>!ze(n)).map(([n,o])=>`${n} ${Ke(o,!0)}`).join(t?", ":" \xB7 ");return t?`(${r})`:r}return Dr(e)?Te(e):String(e)}var _s=(e,t,r)=>{if(e!==null&&typeof e=="object"){if(!r)throw new Error(`Brief cannot print the object at ${t}; flatten it in the view.`);return Ke(e)}return Ke(e)},ze=(e,t)=>e==null||e===""||e===!1||t!==void 0&&e===t,$s={1:"FAILED",2:"NEEDS YOU",3:"ISSUES",4:"INCOMPLETE",5:"PARTIAL",130:"INTERRUPTED",143:"INTERRUPTED"},Ps={E_ARTIFACT_NOT_FOUND:"check --artifact and --project-dir; artifacts live in <project>/.ryugi/artifacts/<type>/<id>/",E_ARGUMENT_INVALID:"run the command with --help for its options",E_CURSOR_EXPIRED:"run the read again without --cursor or --snapshot",E_CURSOR_MISMATCH:"run the read again without --cursor or --snapshot"},Ns=(e,t)=>t?$s[t]??"FAILED":L(e).replaceAll("_"," ").toUpperCase(),Ds=e=>{let t=e.replaceAll(/[._]/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):"Command"};function Ls(e){let t=e.offset??0;if(!e.hasMore&&t===0)return null;let r=e.total===null?"":` of ${e.total}`;return e.offset===void 0?`${e.returned}${r} shown${e.total===null&&e.hasMore?" \xB7 more available":""}`:`${e.returned?`${t+1}\u2013${t+e.returned}`:"none"}${r}`}var Ms=e=>/^[\w./:@=+-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`;function Ce(e){return e.kind==="command"?e.argv.map(Ms).join(" "):e.url}var Us=e=>e.map(t=>`Effect: ${L(t.operation)} ${L(t.target)} \xB7 ${t.state}`),Fs=e=>e.split(".").filter(Boolean).at(-1)??e;function Lt(e,t,r,n,o=[],s=0){let i=[Ns(e.status,s),e.subject&&L(e.subject),e.summary&&L(e.summary)].filter(Boolean),a=[i.length?`${L(e.heading)}: ${i.join(" \xB7 ")}`:L(e.heading)],c=[...t.omitted??[]],l=(p,h=!1)=>h||o.includes(p)||!r.fields||r.fields.includes(p),u=(p,h,g=!1)=>{let v=L(_s(p,h,g)),$=r.detail?v:Ts(v);return $!==v&&c.push({path:h,reason:"preview"}),$},d=(p,h,g,v,$,W,P=!1)=>{if(ze(g,W))return null;let N=L(p??h);if(g===!0)return N;let D=u(g,v,P);return $?D:`${N} ${D}`},f=(p,h=!1)=>{for(let g of p){if(!n&&!l(g.binding.key,g.required)||ze(g.binding.value))continue;let v=g.binding.value===!0?"yes":u(g.binding.value,`data.${g.binding.key}`,h);a.push(`${L(g.label)}: ${v}`)}},k=(p,h)=>p.map(g=>d(g.label,g.binding.key,g.binding.value,`${h}.${g.binding.key}`,g.positional)).filter(g=>g!==null).join(" \xB7 "),S=(p,h)=>{p&&a.push(h?`${L(p)} \xB7 ${L(h)}`:L(p))},O=p=>{let h=p&&Ls(p);h&&a.push(h)};f(e.facts);let T=t.error?Se(t.error):[];if(t.error){a.push(`${L(t.error.code)}: ${L(t.error.message)}`),t.error.httpStatus!==void 0&&t.error.httpStatus>=500&&a.push(`HTTP: ${t.error.httpStatus}`);let p=Ps[t.error.code];p&&a.push(`Next: ${p}`);let h=t.error.details;if(h&&typeof h=="object"&&!Array.isArray(h))for(let[g,v]of Object.entries(h))T.some($=>$.label===g)||f([{label:g,binding:{key:g,value:v},required:!0}],!0);else h!==void 0&&f([{label:"Details",binding:{key:"details",value:h},required:!0}],!0)}if(!n&&r.fields&&t.data&&typeof t.data=="object"){let p=new Set([...e.facts.map(g=>g.binding.key),...e.sections.flatMap(g=>g.kind==="fields"?g.facts.map(v=>v.binding.key):[g.key])]),h=t.data;f([...new Set([...r.fields,...o])].filter(g=>!p.has(g)&&Object.hasOwn(h,g)).map(g=>({label:g,binding:{key:g,value:h[g]}})),!0)}for(let p of e.sections){if(p.kind==="fields"){f(p.facts);continue}if(!n&&!l(p.key))continue;let h="title"in p&&p.title?p.title:void 0;if(p.kind==="records"){S(h??(p.page?p.key:void 0),p.summary);let g=new Set(p.columns.map(P=>P.key)),v=p.key===n?[...new Set([...r.fields??[],...r.fields?o:[]])].filter(P=>!g.has(P)).map(P=>({key:P,label:P})):[],$=new Set(v.map(P=>P.key)),W=[...p.columns,...v].filter(P=>p.key!==n||l(P.key,P.required));if(r.format==="table"){let P=W.map(ee=>ee.label??ee.key),N=p.rows.map((ee,ye)=>W.map(te=>ze(ee[te.key],te.default)?"":u(ee[te.key],`data.${p.key}.${ye}.${te.key}`,$.has(te.key)))),D=P.map((ee,ye)=>Math.max(ee.length,...N.map(te=>te[ye]?.length??0)));a.push(...[P,...N].map(ee=>ee.map((ye,te)=>ye.padEnd(D[te]??ye.length)).join(" ").trimEnd()))}else for(let[P,N]of p.rows.entries())a.push(` ${W.map(D=>d(D.label,D.key,N[D.key],`data.${p.key}.${P}.${D.key}`,D.positional,D.default,$.has(D.key))).filter(D=>D!==null).join(" \xB7 ")}`);!p.rows.length&&!h&&!p.page&&a.push("No records."),O(p.page)}else if(p.kind==="messages"){S(h,p.summary);for(let[g,v]of p.groups.entries()){a.push(` ${k(v.facts,`data.${p.key}.${g}`)}`);for(let[$,W]of v.messages.entries())a.push(` ${k(W.facts,`data.${p.key}.${g}.messages.${$}`)}`),a.push(...W.text.split(`
|
|
9
|
+
`).map(P=>` ${P.replaceAll(new RegExp("\\p{Cc}","gu"),N=>N===" "?N:"")}`))}!p.groups.length&&!h&&!p.page&&a.push("No messages."),O(p.page)}else if(p.kind==="diagnostics"){let g=r.detail?p.items.length:p.preview??3;for(let v of p.items.slice(0,g))a.push(` ${v.location?`${L(v.location)} `:""}${L(v.code)}: ${u(v.message,`data.${p.key}`)}`);g<p.items.length&&c.push({path:`data.${p.key}`,reason:"preview",count:p.items.length-g})}else S(h&&`${h}:`,p.summary),a.push(...p.text.trimEnd().split(`
|
|
10
|
+
`).map(g=>` ${g.replaceAll(new RegExp("\\p{Cc}","gu"),v=>v===" "||v===`
|
|
11
|
+
`?v:"")}`))}t.page&&O(t.page),(s||(t.effects??[]).some(p=>p.state!=="confirmed"))&&a.push(...Us(t.effects??[]));for(let p of t.warnings??[])a.push(`Warning: ${L(p.message)}`);let G=e.actions??t.next??[],R=[...G,...T.filter(p=>!G.some(h=>Ce(h)===Ce(p)))],_=new Set,y=R.find(p=>p.label==="Details");for(let p of c){if(p.count===void 0)continue;let h=`${p.count} more ${Fs(p.path)}`;y&&!_.has(y)?(_.add(y),a.push(`${h} \xB7 Details: ${Ce(y)}`)):a.push(h)}!y&&!r.detail&&c.some(p=>p.reason==="preview"&&p.count===void 0)&&a.push("Some values are clipped; add --detail to see them in full.");for(let p of R)_.has(p)||a.push(`${L(p.label??"Next")}: ${p.reason?`${L(p.reason)} \xB7 `:""}${Ce(p)}`);return`${a.join(`
|
|
12
12
|
`)}
|
|
13
|
-
`}function
|
|
14
|
-
`)},diagnostic(
|
|
15
|
-
`)}};function
|
|
16
|
-
`}function
|
|
17
|
-
`);else if(r.format==="jsonl"){let
|
|
18
|
-
`)}else await
|
|
19
|
-
`:
|
|
20
|
-
`)}catch(
|
|
21
|
-
`).slice(1).join(" ").trim();return n?n.split(/\s+/):null}var
|
|
22
|
-
`,{mode:384}),
|
|
13
|
+
`}function Lr(e,t,r=1){return Lt({heading:Ds(e.command),status:"",facts:[],sections:[]},e,{...t,fields:void 0},void 0,[],r)}function I(e,t){return{run:(r,n,o,s)=>Mt(e,t,r,n,o,s)}}async function Mt(e,t,r,n,o,s){let i=0,a=Promise.resolve(),c,l=!1,u=[],d=new AbortController,f=()=>d.abort(o?.reason);o?.addEventListener("abort",f,{once:!0}),o?.aborted&&f();let k={signal:d.signal,effects:new Ye,payloads:{},progress(y){l||O(r.format==="jsonl"?"stdout":"stderr",r.format==="jsonl"?S("progress",y):`${y.phase}${y.current===void 0?"":` ${y.current}${y.total===void 0?"":`/${y.total}`}`}
|
|
14
|
+
`)},diagnostic(y){O("stderr",`${y.trimEnd()}
|
|
15
|
+
`)}};function S(y,p){return`${JSON.stringify({schema:"ryugi.cli/v1",...p,seq:i++,kind:y})}
|
|
16
|
+
`}function O(y,p){a=a.then(()=>n.write(y,p)).catch(h=>{c=h,d.abort(h)})}async function T(){if(await a,c)throw c}let G=8*1024*1024;async function R(y,p){if((typeof p=="string"?new TextEncoder().encode(p).byteLength:p.byteLength)>G)throw new m({code:"E_RESULT_TOO_LARGE",message:"Result exceeds 8 MiB; read one object or save it to a file."});await T(),await n.write(y,p)}async function _(y,p="result"){let h={...y,effects:y.effects.length?y.effects:k.effects.snapshot()};h.effects.some(v=>v.state==="unknown")&&(h.actions=[...h.actions,...s?.(e.id,void 0,h.effects)??[]]),u=h.effects;let g=Tt(e.id,h,r,e.output);if(r.format==="json")await R("stdout",`${JSON.stringify(g)}
|
|
17
|
+
`);else if(r.format==="jsonl"){let v=g,$=e.output.collection;if($&&p==="result"){let W=g.data,P=W[$];if(Array.isArray(P)){for(let D of P)await R("stdout",S("item",{collection:$,data:D}));let N={...W};delete N[$],v={...g,data:N}}}await R("stdout",S(p,v))}else if(r.format==="raw"||r.format==="source"){let v=k.payloads[r.format];if(v===void 0)throw new m({code:"E_PAYLOAD_UNAVAILABLE",message:`No ${r.format} payload was returned.`});await R("stdout",v)}else if(r.format==="quiet"){if(!e.output.scalar)throw new m({code:"E_FORMAT_UNSUPPORTED",message:"This command has no scalar output."});await R("stdout",`${e.output.scalar(h.data)}
|
|
18
|
+
`)}else await R(h.completion.kind==="failed"?"stderr":"stdout",Lt(e.present(h),g,r,e.output.collection,e.output.requiredFields,be(h.completion).code));return be(h.completion).code}try{if(!e.output.formats.includes(r.format)||e.mode==="live"&&["json","quiet","raw","source","table"].includes(r.format))throw new m({code:"E_FORMAT_UNSUPPORTED",message:`${r.format} is not supported for ${e.id}. Supported: ${e.output.formats.join(", ")}`});if(r.detail&&!e.output.detail)throw new m({code:"E_OPTION_UNSUPPORTED",message:"--detail is not supported for this operation."});let y=r.fields?.find(g=>!e.output.fields?.includes(g));if(y)throw new m({code:"E_FIELD_UNKNOWN",message:`Unknown output field: ${y}`});if(r.format==="jsonl"&&await R("stdout",S("meta",{command:e.id})),e.mode==="finite"){let g=await e.run(t,k);return l=!0,await _(g)}let p=!1,h;for await(let g of e.run(t,k)){if(h||g.kind==="ready"&&p)throw new m({code:"E_LIFECYCLE_INVALID",message:"Invalid command lifecycle."});if(g.kind==="ready"){p=!0;try{await _(g.result,"ready")}catch(v){throw d.abort(v),v}}else h=g.result,l=!0}if(!h)throw new m({code:"E_LIFECYCLE_INCOMPLETE",message:"Command ended without a terminal result."});return await _(h)}catch(y){if(l=!0,y instanceof m&&y.raw!==void 0&&(k.payloads.raw=y.raw),y?.code==="EPIPE")return 141;let p=d.signal.aborted&&(d.signal.reason==="SIGINT"||d.signal.reason==="SIGTERM")?d.signal.reason:void 0,h=p?{code:"E_INTERRUPTED",message:`Command interrupted by ${p}.`,details:{signal:p}}:He(y),g=y instanceof m?y.kind==="action_required":y?.code===2,v=k.effects.snapshot(),$=x(null,p?{kind:"interrupted",signal:p}:g?{kind:"action_required",reason:h.message}:{kind:"failed",error:h},{effects:v.length?v:u,actions:[...s?.(e.id,h,v.length?v:u)??[],...y?.actions??[]]}),W={...Tt(e.id,$,{...r,fields:void 0},{}),error:h};try{await T(),r.format==="json"||r.format==="jsonl"?await n.write("stdout",r.format==="json"?`${JSON.stringify(W)}
|
|
19
|
+
`:S("result",W)):r.format==="raw"&&k.payloads.raw!==void 0&&h.code!=="E_RESULT_TOO_LARGE"&&Buffer.byteLength(k.payloads.raw)<=G?await n.write("stdout",k.payloads.raw):await n.write("stderr",Lr(W,r,be($.completion).code)),r.verbose&&y instanceof Error&&y.stack&&await n.write("stderr",`${y.stack}
|
|
20
|
+
`)}catch(P){if(P?.code==="EPIPE")return 141}return be($.completion).code}finally{o?.removeEventListener("abort",f)}}var Xe=C(require("node:fs"),1),Mr=C(require("node:os"),1),B=C(require("node:path"),1),Rc=10080*60*1e3;function ne(e=process.env,t=Mr.default.homedir()){let r=e.RYUGI_SERVER_HOME||B.default.join(t,".ryugi","server");return{home:r,pid:B.default.join(r,"server.pid"),serverId:B.default.join(r,"server-instance-id"),info:B.default.join(r,"server-info"),log:B.default.join(r,"server.log"),version:B.default.join(r,"server-version"),lock:B.default.join(r,"start.lock"),key:B.default.join(r,"key"),projects:B.default.join(r,"projects.json"),settings:B.default.join(r,"settings.json"),stopped:B.default.join(r,"server-stopped")}}function Ur(e){Xe.default.mkdirSync(e,{recursive:!0,mode:448}),Xe.default.chmodSync(e,448)}var Gs=e=>{let t=e;return!!t&&typeof t.dir=="string"&&B.default.isAbsolute(t.dir)&&Number.isFinite(t.registeredAt)&&Number.isFinite(t.lastUsedAt)};function Re(e){try{let t=JSON.parse(Xe.default.readFileSync(e,"utf8"));return Array.isArray(t.projects)?t.projects.filter(Gs):[]}catch{return[]}}var Fr=e=>B.default.join(e,".ryugi","artifacts");var Qe=require("node:child_process"),Ut=C(require("node:fs"),1),xe=e=>new Promise(t=>setTimeout(t,e));function oe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Ws(e){try{return Ut.default.readFileSync(`/proc/${e}/cmdline`,"utf8").split("\0")}catch{}let t=(0,Qe.spawnSync)("ps",["-ww","-p",String(e),"-o","command="],{encoding:"utf8"});if(t.status===0&&t.stdout.trim())return t.stdout.trim().split(/\s+/);let r=(0,Qe.spawnSync)("ps",["-f","-p",String(e)],{encoding:"utf8"});if(r.status!==0)return null;let n=r.stdout.split(`
|
|
21
|
+
`).slice(1).join(" ").trim();return n?n.split(/\s+/):null}var Vs=e=>/^"node\.exe"/i.test(e.trim());function qs(e){let t=(0,Qe.spawnSync)("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return t.status===0&&Vs(t.stdout)}function _e(e,t){return oe(e)?process.platform==="win32"?qs(e):Ws(e)?.includes(`--artifacts-server-id=${t}`)??!1:!1}async function me(e,t){for(let r=0;r<t&&oe(e);r+=100)await xe(100);return!oe(e)}var H=e=>{try{return Ut.default.readFileSync(e,"utf8").replace(/[\r\n]+$/,"")}catch{return null}};var Gr=e=>`No artifacts server is running for this project. Start it with \`${Oe()} start --project-dir ${e}\`, then run this again.`,Ft=e=>{try{let{url:t}=JSON.parse(H(e)??"");return typeof t=="string"?t:null}catch{return null}};function Hs(e,t){let r=ne(),n=Ft(r.info);return n?Re(r.projects).some(s=>s.dir===e)?n:null:Ft(t)}function M(e){let t=U(e),r=Hs(t.project,t.info);if(!r)throw new m({code:"E_SERVER_NOT_RUNNING",message:Gr(t.project)});let n=new URL(r),o=n.searchParams.get("key")??"";return n.hostname==="localhost"&&(n.hostname="127.0.0.1"),{project:t.project,async call(s,i,a,c){let l;try{let f=new URL(`${n.origin}${i}`);f.searchParams.set("key",o),l=await fetch(f,{method:s,signal:c,headers:{"X-Ryugi-Project":encodeURIComponent(t.project),...a?{"Content-Type":"application/json"}:{}},body:a?JSON.stringify(a):void 0})}catch{throw new m({code:"E_SERVER_UNREACHABLE",message:Gr(t.project)})}let u=new Uint8Array(await l.arrayBuffer()),d;try{d=JSON.parse(new TextDecoder().decode(u))}catch{}if(!d||typeof d!="object"||Array.isArray(d))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an invalid JSON response; the operation result is unknown.",httpStatus:l.status},"failed",u);return{status:l.status,json:d,raw:u}}}}async function Wr(){let e=ne(),t=Ft(e.info),r={scope:"machine",version:H(e.version)};if(!t)return{...r,status:"not_running"};try{let n=new URL("/api/status",t);n.search=new URL(t).search;let o=await fetch(n,{signal:AbortSignal.timeout(1e3)}),s=await o.json();return{...r,status:o.ok&&typeof s.pid=="number"?"running":"unreachable",pid:typeof s.pid=="number"?s.pid:void 0}}catch{return{...r,status:"unreachable"}}}var it=C(require("node:fs"),1),rn=C(require("node:os"),1),st=C(require("node:path"),1);var le=C(require("node:fs"),1),$e=C(require("node:path"),1);function Vr(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.phase!="string"||!["waiting","preparing","uploading","publishing","not-ready","failed","published"].includes(t.phase)||t.publishedAt!==null&&(typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt)))||typeof t.autoPublish!="boolean"||t.message!==void 0&&typeof t.message!="string"||t.reasons!==void 0&&(!Array.isArray(t.reasons)||!t.reasons.every(r=>typeof r=="string"))?null:t}var Bs=["1d","7d","30d","never"],qr=e=>Bs.includes(e);var Gt=e=>e==="private"||e==="public";var et=C(require("node:fs"),1),Br=C(require("node:path"),1);var Ze=["artboard","document","html","whiteboard","verify"],Wt={artboard:"canvas.json",document:"doc.xml",html:"index.html",whiteboard:"scene.excalidraw",verify:"report.xml"};var Hr=["x","y","w","h"],Gc=["file","page",...Hr],Wc=["src","page",...Hr];function se(e,t){et.default.mkdirSync(Br.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.tmp`;et.default.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
22
|
+
`,{mode:384}),et.default.renameSync(r,e)}var Pe=()=>({version:1,artifacts:{}});function Jr(e){try{let t=JSON.parse(le.default.readFileSync(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a config object");return t}catch(t){if(t.code==="ENOENT")return Pe();throw t}}var Yr=e=>Array.isArray(e)&&e.every(t=>typeof t=="string");function Ys(e){if(typeof e!="object"||e===null)return!1;let{id:t,url:r,publishedAt:n,visibility:o}=e;return typeof t=="string"&&typeof r=="string"&&(typeof n=="string"||n===null)&&Gt(o)}function zr({id:e,url:t,publishedAt:r,visibility:n,fingerprint:o,onProfile:s,keyed:i,modulesSynced:a}){return{id:e,url:t,publishedAt:r,visibility:n,...typeof o=="string"?{fingerprint:o}:{},...typeof s=="boolean"?{onProfile:s}:{},...i===!0?{keyed:i}:{},...Yr(a)?{modulesSynced:a}:{}}}function zs(e){let t=Pe();if(typeof e!="object"||e===null)return t;let r=e.output;r&&typeof r=="object"&&"format"in r&&["brief","json","jsonl"].includes(String(r.format))&&(t.output={format:r.format});let{autoPublish:n,modulesSynced:o}=e;typeof n=="boolean"&&(t.autoPublish=n),typeof o=="string"&&(t.modulesSynced=o);let s=e.artifacts;if(typeof s!="object"||s===null)return t;for(let[i,a]of Object.entries(s)){if(typeof a!="object"||a===null)continue;let{visibility:c,cloud:l,autoPublish:u,modules:d}=a;if(c!==void 0&&!Gt(c))continue;let f={};c&&(f.visibility=c),Ys(l)&&(f.cloud=zr(l)),u===!1&&(f.autoPublish=!1),Yr(d)&&(f.modules=d),t.artifacts[i]=f}return t}function ie(e){let t;try{t=le.default.readFileSync(e,"utf8")}catch{return{config:Pe()}}try{return{config:zs(JSON.parse(t))}}catch(r){return{config:Pe(),warning:`config.json is not valid JSON: ${r.message}`}}}var Ks=["config.json","artifacts/*","!artifacts/document/","artifacts/document/*/.artifact-id"];function Xs(e){let t=$e.default.join(e,".gitignore"),r="";try{r=le.default.readFileSync(t,"utf8")}catch{}let n=new Set(r.split(/\r?\n/).map(s=>s.trim())),o=Ks.filter(s=>!n.has(s));o.length!==0&&le.default.writeFileSync(t,`${r}${r===""||r.endsWith(`
|
|
23
23
|
`)?"":`
|
|
24
24
|
`}${o.join(`
|
|
25
25
|
`)}
|
|
26
|
-
`)}function ve(e){ue.default.mkdirSync(Ie.default.dirname(e),{recursive:!0}),Cs(Ie.default.dirname(e)),ue.default.existsSync(e)||Q(e,Je())}function Dr(e,t,r){let{config:n,warning:o}=Z(e);if(o)throw new Error(o);let s={...n.artifacts[t]};if(r.visibility&&(s.visibility=r.visibility),r.cloud===null)delete s.cloud;else if(r.cloud){let i=s.cloud?.id===r.cloud.id?s.cloud.modulesSynced:void 0;s.cloud={...i?{modulesSynced:i}:{},...r.cloud}}return r.autoPublish===null?delete s.autoPublish:r.autoPublish===!1&&(s.autoPublish=!1),r.modules===null?delete s.modules:r.modules&&(s.modules=r.modules),n.artifacts[t]=s,Q(e,n),s}function Lr(e,t){let{config:r,warning:n}=Z(e);if(n)throw new Error(n);t===null?delete r.autoPublish:r.autoPublish=t,ue.default.mkdirSync(Ie.default.dirname(e),{recursive:!0}),Q(e,r)}var Mr=w(require("node:fs"),1),Ke=w(require("node:path"),1);function ne(e,t,r){return t==="win32"&&e.APPDATA?Ke.default.join(e.APPDATA,"ryugi","credentials.json"):Ke.default.join(e.XDG_CONFIG_HOME||Ke.default.join(r,".config"),"ryugi","credentials.json")}function Xe(e,t){let r;try{r=JSON.parse(Mr.default.readFileSync(e,"utf8"))}catch{return null}if(typeof r!="object"||r===null)return null;let{origin:n,token:o,login:s}=r;return typeof n!="string"||typeof o!="string"||typeof s!="string"||n!==t?null:{origin:n,token:o,login:s}}var Pt=w(require("node:fs"),1),ze=w(require("node:path"),1);var Qe=e=>ze.default.join(ze.default.dirname(e),"config.json");function Fr(e){try{let t=JSON.parse(Pt.default.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}function Ur(e){let t=Fr(e).autoPublish;return typeof t=="boolean"?t:void 0}function Gr(e,t){Pt.default.mkdirSync(ze.default.dirname(e),{recursive:!0,mode:448}),Q(e,{...Fr(e),autoPublish:t})}var Nt=["brief","json","jsonl"];function Wr(e){return{global:Qe(ne(process.env,process.platform,Vr.default.homedir())),project:Ze.default.join(Ze.default.dirname(W(e).root),"config.json")}}function qr(e){try{let t=JSON.parse(et.default.readFileSync(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected an object");return t}catch(t){if(t.code==="ENOENT")return{};throw new m({code:"E_CONFIG_INVALID",message:`Cannot read ${e}: ${t.message}`})}}function Oe(e){let t=Wr(e),r=s=>{let i=qr(s).output;if(i?.format!==void 0&&!Nt.includes(i.format))throw new m({code:"E_FORMAT_UNSUPPORTED",message:`Unsupported output format in ${s}: ${String(i.format)}`});return i&&Nt.includes(i.format)?i.format:null},n=r(t.global),o=r(t.project);return{global:n,project:o,effective:o??n??"brief",source:o?"project":n?"global":"default"}}function Hr(e,t,r){if(r==="inherit"&&!t||r!=="inherit"&&!Nt.includes(r))throw new m({code:"E_ARGUMENT_INVALID",message:"--output-format takes brief, json, jsonl, or inherit with --project."});let n=Wr(e),o=t?n.project:n.global,s=qr(o);r==="inherit"?delete s.output:s.output={format:r},t?ve(o):et.default.mkdirSync(Ze.default.dirname(o),{recursive:!0,mode:448}),Q(o,s)}function Br(e,t,r=process.env){if(r.RYUGI_ARTIFACTS_FORMAT!==void 0)return r;let n=Et(e,t);if(["format","json","quiet","source"].some(i=>n[i]!==void 0))return r;let o=typeof n["project-dir"]=="string"?n["project-dir"]:process.cwd();if(!n["project-dir"]&&e[0]&&!e[0].startsWith("-"))try{et.default.statSync(e[0]).isDirectory()&&(o=e[0])}catch{}let s=Oe(o);return{...r,RYUGI_ARTIFACTS_FORMAT:s.effective}}var ks=e=>[...e.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(t=>t[1]??t[2]??t[3]);function Es(){let e=process.env.RYUGI_ARTIFACTS_COMMAND?.trim();return e?ks(e):[process.execPath,process.argv[1]]}function As(e){if(process.env.RYUGI_ARTIFACTS_FORMAT)return process.env.RYUGI_ARTIFACTS_FORMAT;let t=e.indexOf("--project-dir");try{return Oe(t>=0&&e[t+1]?e[t+1]:process.cwd()).effective}catch{return"brief"}}function $(e,t="Details"){let n=e.some(o=>["--format","--source","--quiet"].includes(o))||As(e)==="brief"?[]:["--format","brief"];return{kind:"command",argv:[...Es(),...e,...n],label:t}}var Se=w(require("node:fs"),1),Yr=w(require("node:path"),1);function je(e,t){let r=Yr.default.resolve(e),n;try{n=Se.default.openSync(r,"wx",384)}catch(o){throw new m({code:o.code==="EEXIST"?"E_FILE_EXISTS":"E_FILE_WRITE_FAILED",message:`Could not create ${r}: ${o.message}`})}try{Se.default.writeFileSync(n,t)}catch(o){throw Se.default.closeSync(n),Se.default.unlinkSync(r),new m({code:"E_FILE_WRITE_FAILED",message:`Could not save ${r}: ${o.message}`})}return Se.default.closeSync(n),{file:r,bytes:typeof t=="string"?Buffer.byteLength(t):t.byteLength}}var F=e=>typeof e=="string"?e:"",rt=e=>e.replaceAll(/\s*\n\s*/g," / ").trim(),nt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ot=e=>e[0].toUpperCase()+e.slice(1),Dt=(e,t=[])=>Object.entries(e??{}).filter(([r,n])=>r!=="waitingOnAgent"&&!t.includes(r)&&typeof n=="number"&&n>0).map(([r,n])=>`${n} ${r}`).join(", "),Jr=e=>e?` (${e})`:"",xs={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 st(e,t,r,n=!1){let o=r?.total??t.items.length,s=t.summary;if(n){let l=`${o} matched`;return{head:l,full:`${l}${Jr(Dt(s))}`,count:o}}if(e==="threads"){let l=Number(s?.waitingOnAgent??0),p=o?`${o} unread${l?`, ${l} waiting on you`:""}`:"nothing unread",f=Number(s?.resolved??0);return{head:p,full:`${p}${f?` (${f} resolved)`:""}`,count:o}}let i=xs[e],a=o?`${o} ${i.word}`:i.none,c=e==="groups"?Object.entries(s??{}).reduce((l,[p,f])=>p==="waitingOnAgent"||typeof f!="number"?l:l+f,0)-o:0,d=e==="groups"?c>0?nt(c,"other"):"":Dt(s,i.listed);return{head:a,full:`${a}${Jr(d)}`,count:o}}function Is(e){if(!e||typeof e!="object")return"";let t=e;if(typeof t.blockId=="string"){let o=Array.isArray(t.blockIds)&&t.blockIds.length>1?t.blockIds:[t.blockId];return`${o.length>1?"blocks":"block"} ${o.join(", ")}${F(t.quote)?` "${rt(F(t.quote))}"`:""}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(", ")}`;let r=F(t.page);if(typeof t.board=="string")return`${r?`page ${r} `:""}board ${t.board}`;let n=typeof t.x=="number"&&typeof t.y=="number"?` ${Math.round(t.x)},${Math.round(t.y)}`:"";return`page ${r||"main"}${n}`}var tt={key:"id",positional:!0,required:!0},Kr={key:"line",positional:!0,required:!0},Xr={key:"tail",positional:!0,required:!0},zr=e=>e.choice?` \u2192 ${e.choice}${e.byRecommendation?" (recommended)":""}`:"";function Os(e,t){return e==="asks"?{columns:[tt,Kr,{key:"note",label:"note"},{key:"staleChoice",label:"stale choice"}],rows:t.map(r=>({...r,line:`${F(r.state)}${r.choice?zr(r):F(r.text)?` \xB7 "${rt(F(r.text))}"`:"choice"in r||"text"in r?" \xB7 no answer":""}`,note:F(r.note)&&`"${rt(F(r.note))}"`}))}:e==="threads"?{columns:[tt,{key:"status",positional:!0,required:!0},{key:"waiting",positional:!0},{key:"where",positional:!0},{key:"stale",label:"stale"},{key:"orphan",label:"orphan"},{key:"draft",label:"draft"},{key:"messageCount",positional:!0},{key:"preview",positional:!0}],rows:t.map(r=>({...Qr(r),messageCount:typeof r.messageCount=="number"&&r.messageCount?nt(r.messageCount,"message"):"",preview:F(r.preview)&&`"${rt(F(r.preview))}"`}))}:e==="groups"?{columns:[tt,{key:"kind",positional:!0,required:!0},Kr,{key:"origin",positional:!0},{key:"evidenceUpdated",label:"evidence updated"},{key:"rejects",positional:!0},{key:"threadCount",positional:!0},Xr],rows:t.map(r=>({...r,line:r.kind==="verify"?F(r.verdict):`${r.round?`round ${r.round}`:""}${r.choice?zr(r):" \xB7 no pick"}`.replace(/^ · /,""),origin:typeof r.from=="string"&&r.from?`from ${r.from}`:"",rejects:typeof r.rejectThreads=="number"&&r.rejectThreads?nt(r.rejectThreads,"reject thread"):"",threadCount:typeof r.threads=="number"&&r.threads?nt(r.threads,"thread"):"",tail:F(r.title)}))}:{columns:[tt,{key:"state",positional:!0,required:!0},{key:"groupList",positional:!0},Xr],rows:t.map(r=>({...r,groupList:Array.isArray(r.groups)&&r.groups.length?`groups ${r.groups.join(", ")}`:"",tail:F(r.title)}))}}function Qr(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:"",where:Is(e.anchor&&typeof e.anchor=="object"&&typeof e.page=="string"?{page:e.page,...e.anchor}:e.anchor),stale:e.stale===!0,orphan:e.orphan===!0,draft:e.draft===!0}}var _e=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function Lt(e,t="items"){return{kind:"messages",key:t,groups:e.map(r=>{let n=Qr(r);return{facts:[_e("id",n.id),_e("status",n.status),_e("waiting",n.waiting),_e("where",n.where),{label:"stale",binding:{key:"stale",value:n.stale}},{label:"orphan",binding:{key:"orphan",value:n.orphan}},{label:"draft",binding:{key:"draft",value:n.draft}}],messages:(Array.isArray(r.messages)?r.messages:[]).map(o=>({facts:[_e("message",[o.id,`${F(o.name)||F(o.author)}${o.author==="agent"?" (agent)":""}`,F(o.at)&&Ae(F(o.at)),o.deleted?"(deleted)":"",F(o.editedAt)&&`edited ${Ae(F(o.editedAt))}`].filter(Boolean).join(" "))],text:typeof o.text=="string"?o.text:""}))}})}}function Zr(e,t,r,n,o){let s=st(e,t,r,o),i={key:n?e:"items",title:ot(e),summary:s.full};return e==="threads"&&t.evidence==="complete"?{...Lt(t.items),...i,...n?{page:r}:{}}:{kind:"records",...Os(e,t.items),...i,...n?{page:r}:{}}}var js=["threads","asks","groups","rounds"];function _s(e,t){let r=e.summary??{},n=s=>t.find(i=>i.label===ot(s)),o=js.filter(s=>n(s));return{heading:"Comment list",status:"",subject:e.artifact,facts:[],sections:o.map(s=>{let i=r[s],a=s==="threads"?st("threads",{items:[],summary:{waitingOnAgent:r.waitingOnAgent}},{total:Number(i??0)}).head:Dt(i)||"none";return{kind:"records",key:s,title:ot(s),summary:`${a} \xB7 ${qe(n(s))}`,columns:[],rows:[]}}),actions:t.filter(s=>!o.some(i=>ot(i)===s.label))}}function en({data:e,actions:t,coverage:r},n="Comment list",o=!1){if(e.section==="summary")return _s(e,t);let s=r.page;return{heading:n,status:"",subject:e.artifact,summary:st(e.section,e,s,o).head,facts:[],sections:[Zr(e.section,e,s,!1,o)]}}function tn({data:e},t=!1){let r=Object.entries(e.sections),n=r.map(([o,s])=>st(o,s,s.page,t)).filter(o=>o.count>0).map(o=>o.head);return{heading:"Comment list",status:"",subject:e.artifact,summary:n.join(" \xB7 ")||"nothing new",facts:[],sections:r.map(([o,s])=>Zr(o,s,s.page,!0,t))}}var O=(e,t)=>typeof e.values[t]=="string"?e.values[t]:void 0,Mt=["brief","table","json","jsonl","raw"];function rn(e,t=!1){let r=O(e,"artifact");if(!r||!(t?/^document\/[a-z0-9][a-z0-9-]*$/:/^(document|artboard|whiteboard)\/[a-z0-9][a-z0-9-]*$/).test(r))throw new m({code:"E_ARGUMENT_INVALID",message:t?"--artifact must be document/<id>.":"--artifact must be document/<id>, artboard/<id> or whiteboard/<id>."});return r}function Ft(e){let t=O(e,"limit");if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});return{...t===void 0?{}:{limit:Number(t)},...O(e,"cursor")?{cursor:O(e,"cursor")}:{},...O(e,"snapshot")?{snapshot:O(e,"snapshot")}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...O(e,"fields")?{fields:O(e,"fields").split(",").map(r=>r.trim())}:{}}}async function it(e,t,r,n,o){let s=await V(e.projectDir).call("POST",`/api/agent/v1/${r}/${n}`,{...o,agent:ge(process.env)??"Agent"},t.signal);if(t.payloads.raw=s.raw,s.json.schema!=="ryugi.review/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported review response."});if(s.status<200||s.status>=300)throw new m({code:typeof s.json.code=="string"?s.json.code:"E_REVIEW_FAILED",message:s.json.error||`HTTP ${s.status}`,httpStatus:s.status});return s.json}function nn(e,t){return["--artifact",t,"--project-dir",e.projectDir]}function on(e,t,r){let n=new Set([...Object.keys(ae),"artifact","receipt"]),o=Object.keys(e.values).find(i=>!n.has(i));if(o)throw new m({code:"E_ARGUMENT_INVALID",message:`--${o} is not supported for ack.`});let s=O(e,"receipt");if(!s)throw new m({code:"E_ARGUMENT_INVALID",message:"ack requires --receipt."});return x({id:r==="review"?"comment.ack":"changes.ack",mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:i=>i.receipt},async run(i,a){let c=await it(e,a,t,r,{op:"ack",receipt:s});return E({artifact:t,receipt:s,status:c.status})},present:$s(r==="review"?"comment":"changes")},e)}function Ts(e,t,r){if(r!=="list")throw new m({code:"E_ARGUMENT_INVALID",message:"--sections applies to comment list."});let n=Ft(e),o=O(e,"sections")?.trim(),s=o==="all"?It(t):(o??"").split(",").map(c=>c.trim()),i=Object.fromEntries(["status","waiting-on","kind","choice-state"].map(c=>[c,O(e,c)])),a=Cr({...n,sections:s,section:O(e,"section"),thread:O(e,"thread"),filters:i},t);if(a)throw new m({code:"E_ARGUMENT_INVALID",message:a});return x({id:"comment.list",mode:"finite",output:{formats:Mt,detail:!0},async run(c,d){let l=await it(e,d,t,"review",{op:"list",sections:s,...n});for(let p of s){let f=l.sections?.[p];if(!f||!Array.isArray(f.items)||typeof f.snapshot!="string"||!f.page||typeof f.page.scope!="string"||typeof f.page.hasMore!="boolean"||!Number.isInteger(f.page.returned)||!(f.page.total===null||Number.isInteger(f.page.total)))throw new m({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(f.page.returned!==f.items.length||f.page.returned<0||f.page.total!==null&&f.page.total<f.page.returned||f.page.snapshot!==f.snapshot||!(f.page.nextCursor===null||typeof f.page.nextCursor=="string")||f.page.hasMore!==(typeof f.page.nextCursor=="string"&&f.page.nextCursor.length>0))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned inconsistent combined review coverage."})}return Ns(e,t,s,l,n)},present:c=>tn(c,n.all)},e)}var $s=e=>({data:t})=>({heading:e==="comment"?"Comment ack":"Changes ack",status:t.status,subject:t.artifact,facts:[],sections:[]});function Ps({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?[S("File",I(e,"saved"),!0)]:[],sections:e.empty||e.saved?[]:e.diff===void 0?[{kind:"records",key:"blocks",rows:e.blocks.map(r=>({id:r.id,size:[r.additions&&`+${r.additions}`,r.deletions&&`-${r.deletions}`].filter(Boolean).join(" "),preview:r.preview&&`"${r.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 Ns(e,t,r,n,o){let s={},i=[],a=[];for(let c of r){let d=n.sections[c],l=sn(e,t,c,d,o),{artifact:p,section:f,...k}=l.data;s[c]={...k,page:d.page},i.push(...l.actions.map(R=>R.label==="More"?{...R,label:`More (${c})`}:R)),k.evidence==="preview"&&c==="threads"&&a.push({path:"data.sections.threads.items.messages",reason:"summary"})}return E({artifact:t,sections:s},void 0,{actions:i,coverage:{omitted:a}})}function sn(e,t,r,n,o,s){let i=n.page,a={artifact:t,section:r??"summary",items:n.items??[],evidence:o.fields?"projected":r&&r!=="threads"?"state":o.detail||s?"complete":"preview",...n.snapshot?{snapshot:n.snapshot}:{},...n.receipt?{receipt:n.receipt}:{},...n.summary?{summary:n.summary}:{}},c=[],d=nn(e,t);if(n.receipt&&c.push($(["comment","ack",...d,"--receipt",n.receipt],"Acknowledge")),i?.nextCursor&&c.push($(["comment","list",...d,"--section",r,...o.detail?["--detail"]:[],...Object.entries({status:O(e,"status"),"waiting-on":O(e,"waiting-on"),kind:O(e,"kind"),"choice-state":O(e,"choice-state"),fields:O(e,"fields"),limit:O(e,"limit")}).flatMap(([l,p])=>p?[`--${l}`,p]:[]),...o.all?["--all"]:[],"--cursor",i.nextCursor],"More")),r)r==="threads"&&a.evidence==="preview"&&a.items[0]&&c.push($(["comment","read",...d,"--thread",String(a.items[0].id),"--snapshot",n.snapshot,"--detail"],"Read"));else{c.push($(["comment","list",...d,"--sections","all","--detail",...o.all?["--all"]:[],...O(e,"limit")?["--limit",O(e,"limit")]:[]],"Review all"));let l=t.startsWith("document/")?["threads","asks"]:t.startsWith("artboard/")?["threads","groups","rounds"]:["threads"];c.unshift(...l.map(p=>$(["comment","list",...d,"--section",p,...p==="asks"?["--detail"]:[]],p[0].toUpperCase()+p.slice(1))))}return r==="asks"&&a.items.some(l=>l.state==="submitted")&&c.unshift({...$(["comment","note",...d,"--ask","<id>"],"Next"),reason:"apply each answer, then settle it"}),r==="groups"&&a.items.some(l=>l.kind==="choose"&&l.choice||l.verdict==="reject")&&c.unshift({...$(["comment","list",...d,"--section","threads","--detail"],"Next"),reason:"read the threads on these groups too, then act on each"}),E(a,void 0,{actions:c,coverage:{...i?{page:i}:{},...a.evidence==="preview"&&r==="threads"?{omitted:[{path:"data.items.messages",reason:"summary"}]}:{}}})}function an(e){let t=rn(e),r=e.positionals[0];if(r==="ack")return on(e,t,"review");if(e.values.sections!==void 0)return Ts(e,t,r);if(r!=="list"&&r!=="read")throw new m({code:"E_ARGUMENT_INVALID",message:"Expected list, read or ack."});let n=Ft(e),o=r==="read"?"threads":O(e,"section"),s=O(e,"thread");if(r==="read"&&!s)throw new m({code:"E_ARGUMENT_INVALID",message:"read requires --thread."});if(o&&!["threads","asks","groups","rounds"].includes(o))throw new m({code:"E_ARGUMENT_INVALID",message:"Unknown review section."});if(!o&&(n.detail||n.cursor||n.fields||["status","waiting-on","kind","choice-state"].some(c=>e.values[c])))throw new m({code:"E_ARGUMENT_INVALID",message:"Select --section before detail, fields, cursor or filters."});let i=Object.fromEntries([["status",O(e,"status")],["waitingOn",O(e,"waiting-on")],["kind",O(e,"kind")],["choiceState",O(e,"choice-state")]].filter(([,c])=>c!==void 0)),a=kr({...n,section:o,filters:i});if(a)throw new m({code:"E_ARGUMENT_INVALID",message:a});return x({id:`comment.${r}`,mode:"finite",output:{detail:!0,formats:Mt,collection:"items",requiredFields:o?Rr[o]:[],fields:o?[...Fe[o]]:[]},async run(c,d){let l=await it(e,d,t,"review",{op:r,...n,...o?{section:o}:{},...s?{thread:s,detail:!0}:{},...Object.keys(i).length?{filters:i}:{}});return sn(e,t,o,l,n,s)},present:c=>en(c,r==="read"?"Comment read":"Comment list",n.all||!!O(e,"status")&&!(o==="asks"&&O(e,"status")==="submitted")||!!O(e,"choice-state"))},e)}function cn(e){let t=rn(e,!0),r=e.positionals[0];if(r==="ack")return on(e,t,"changes");if(r)throw new m({code:"E_ARGUMENT_INVALID",message:"Expected changes or changes ack."});let n=Ft(e),o=O(e,"save");if(n.detail&&(n.fields||n.cursor||n.limit!==void 0))throw new m({code:"E_OPTION_CONFLICT",message:"A complete diff cannot use --limit, --cursor or --fields."});return x({id:"changes",mode:"finite",output:{detail:!0,formats:o?["brief","json","jsonl"]:Mt,fields:["artifact","snapshot","blocks","diff","empty"]},async run(s,i){let a=await it(e,i,t,"changes",{op:"read",...n}),{page:c,schema:d,...l}=a,p=l;if(o){let R=je(o,p.diff??"");p.saved=R.file,p.bytes=R.bytes,delete p.diff}let f=nn(e,t),k=p.receipt?[$(["changes","ack",...f,"--receipt",p.receipt],"Acknowledge")]:p.empty?[]:[$(["changes",...f,"--snapshot",p.snapshot,...n.all?["--all"]:[],"--detail"],"Read")];return c?.nextCursor&&k.push($(["changes",...f,...n.all?["--all"]:[],...Object.entries({fields:O(e,"fields"),limit:O(e,"limit")}).flatMap(([R,j])=>j?[`--${R}`,j]:[]),"--cursor",c.nextCursor],"More")),E(p,void 0,{actions:k,coverage:{...c?{page:c}:{},...!n.detail&&!p.empty?{omitted:[{path:"data.diff",reason:"summary"}]}:{}}})},present:Ps},e)}var un={semantic:cn,positionals:1,name:"changes",summary:"Show what your human partner changed in a document (needs a running server)",usage:["--artifact document/<id> [--all] [--detail | --save <file>]","ack --artifact document/<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\u2013100, 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>",help:"The document"},all:{type:"boolean",help:"Show historical changes without a receipt"}}};function ln(e){let t=n=>!!n&&typeof n=="object"&&!Array.isArray(n),r=n=>Array.isArray(n)&&n.every(o=>typeof o=="string");if(!t(e)||!r(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&&!r(e.pending)||e.provenance!==void 0&&!r(e.provenance)||e.modules!==void 0&&!r(e.modules)||e.checkedAt!==void 0&&typeof e.checkedAt!="string")return!1;for(let n of["ran","merging"])if(e[n]!==void 0&&typeof e[n]!="boolean")return!1;return!(e.dynamic!==void 0&&(!t(e.dynamic)||Object.values(e.dynamic).some(n=>!t(n)||n.ran!==void 0&&typeof n.ran!="boolean"))||e.recordings!==void 0&&(!t(e.recordings)||Object.values(e.recordings).some(n=>!t(n)||["status","warning"].some(o=>n[o]!==void 0&&typeof n[o]!="string"))))}var Ds=new Set(["W_PROVENANCE","W_MODULES"]);function dn(e,t){let r=(t.warnings??[]).map(f=>({code:"W_ARTIFACT",severity:"warning",message:f}));for(let f of t.provenance??[])r.push({code:"W_PROVENANCE",severity:"warning",message:f});for(let f of t.modules??[])r.push({code:"W_MODULES",severity:"warning",message:f});let n=[...t.pending??[]];t.merging&&n.push("merging");for(let[f,k]of Object.entries(t.recordings??{}))k.warning&&r.push({code:"W_RECORDING",severity:"warning",message:k.warning,location:f}),k.status==="processing"&&n.push(`recording:${f}`);let o=Object.entries(t.dynamic??{}),s=t.evidence?.required??(e.startsWith("html/")||e.startsWith("artboard/")||o.length>0),i=t.evidence?.observed===!1||t.ran===!1||o.some(([,f])=>f.ran===!1);s&&i&&n.push("browser_not_run");let a=t.evidence?.observed??(t.ran===!0||o.length>0&&o.every(([,f])=>f.ran===!0)),c=s?i?"not_run":a&&t.evidence?.fresh===!0?"clean":"unknown":"not_required",d=r.filter(f=>!Ds.has(f.code)),l=d.length?"issues":n.length?"pending":c==="unknown"||t.evidence?.fresh===!1?"unknown":"clean",p={artifact:e,status:l,static:d.length?"issues":"clean",runtime:c,issues:r,pending:n,evidence:t};return E(p,l==="issues"?{kind:"validation_failed"}:l==="pending"||l==="unknown"?{kind:"pending",reasons:n.length?n:["evidence_unknown"]}:{kind:"succeeded"})}async function Ls(e,t,r){if(!e.artifact||!re.test(e.artifact))throw new b(me);let o=await V(e.projectDir).call("POST",`/api/agent/${e.artifact}/check${e.page?`?page=${encodeURIComponent(e.page)}`:""}`,void 0,t);r?.(o.raw);let{status:s,json:i}=o;if(s<200||s>=300)throw new b(i?.error||`HTTP ${s}`);if(!ln(i))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned invalid check evidence; validation could not be established."});return{...o,json:i}}var pn={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=>x({id:"check",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","raw","quiet"],fields:["artifact","status","static","runtime","issues","pending","evidence"],scalar:t=>t.status},async run(t,r){let n=await Ls({projectDir:e.projectDir,artifact:e.values.artifact,page:e.values.page},r.signal,s=>{r.payloads.raw=s});r.payloads.raw=n.raw;let o=dn(e.values.artifact,n.json);return o.actions=[$(["check","--artifact",o.data.artifact,...e.values.page?["--page",e.values.page]:[],"--project-dir",e.projectDir,"--detail"])],o},present:Ms},e)};function Ms({data:e}){let t=e.issues.length;return{heading:"Check",status:e.status,subject:e.artifact,summary:t?`${t} issue${t===1?"":"s"}`:"",facts:[...e.runtime==="not_run"||e.runtime==="unknown"?[S("Browser",{key:"runtime",value:e.runtime.replaceAll("_"," ")})]:[],...e.pending.length?[S("Pending",{key:"pending",value:e.pending.join(", ")})]:[]],sections:[{kind:"diagnostics",key:"issues",items:e.issues,preview:3}]}}var wn=w(require("node:fs"),1);function fn(e,t,r,n){if(e==="submit")return{op:"submit",submit:!t.withdraw};if(!t.ask)throw new b(`comment ${e} needs --ask <questionId>`);if(e==="note")return{op:"note",ask:t.ask,text:r()};let o=n?.trim();if(!t.clear&&!t.choice&&!o)throw new b("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:o??null}}var mn={reject:0,pending:1,pass:2,checked:3},Fs={reject:"rejected",pending:"pending",pass:"passed",checked:"checked by agent"},Y=(e,t)=>e?`${e} ${t}`:"",at=e=>e.filter(Boolean).join(" \xB7 "),H=(e,t=!1)=>({key:e,positional:!0,required:t});function Us({data:e}){let{tally:t}=e,r=s=>e.claims.filter(i=>i.state===s).length,n=e.threads.filter(s=>s.status==="open"),o=at([Y(t.needYou,"on your human partner"),Y(t.notVerified,"not verified"),Y(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:o?[S("Waiting",{key:"waiting",value:o})]:[],sections:[{kind:"records",key:"claims",title:"Claims",summary:at([Y(r("reject"),"rejected"),Y(r("pending"),"pending"),Y(r("pass"),"passed"),Y(r("checked"),"checked by agent")]),columns:[H("id",!0),H("line",!0),H("rejects"),{key:"evidenceUpdated",label:"evidence updated"},H("origin"),H("tail")],rows:[...e.claims].sort((s,i)=>mn[s.state]-mn[i.state]).map(s=>({...s,line:Fs[s.state],rejects:s.state==="reject"&&s.rejectThreads?`${s.rejectThreads} reject thread${s.rejectThreads===1?"":"s"}`:"",evidenceUpdated:s.evidenceUpdated||void 0,origin:s.from?`from ${s.from}`:"",tail:s.title}))},...e.rows.length?[{kind:"records",key:"rows",title:"Artboard rows",summary:String(e.rows.length),columns:[H("id",!0),H("state",!0)],rows:e.rows.map(s=>({...s,id:`${s.artboard}/${s.group}`}))}]:[],...e.gaps.length?[{kind:"records",key:"gaps",title:"Not verified",summary:at([Y(e.gaps.filter(s=>!s.waived).length,"open"),Y(e.gaps.filter(s=>s.waived).length,"waived")]),columns:[H("id",!0),H("line",!0),H("tail")],rows:e.gaps.map(s=>({...s,line:s.waived?"waived":"not verified",tail:s.title}))}]:[],...e.threads.length?[{kind:"records",key:"threads",title:"Threads",summary:at([Y(n.length,"open"),Y(e.threads.length-n.length,"resolved")]),columns:[H("id",!0),H("on",!0),H("what"),{key:"stale",label:"stale"},H("last")],rows:e.threads.map(s=>{let i=s.messages.at(-1);return{id:s.id,on:s.anchor.claim?`claim ${s.anchor.claim}`:`gap ${s.anchor.gap}`,what:s.anchor.verdict??(s.anchor.waive?"waived":""),stale:s.stale||void 0,last:i?`${i.author}: ${i.text}`:""}})}]:[]]}}function gn(e){let t=e.values.artifact;return x({id:"comment.list",mode:"finite",output:{formats:["brief","json","jsonl"],fields:["id","state","title","from"],scalar:r=>r.tally.done?"done":"open"},async run(r,n){let o=ge(process.env),s=await V(e.projectDir).call("POST",`/api/agent/${t}/comments`,{op:"list",...o?{agent:o}:{}},n.signal);if(s.status<200||s.status>=300)throw new m({code:s.status===404?"E_ARTIFACT_NOT_FOUND":"E_COMMENT_FAILED",message:s.json?.error||`HTTP ${s.status}`,httpStatus:s.status});let i=s.json;return E({...i,artifact:t,projectDir:e.projectDir})},present:Us},e)}function Gs({data:e}){let t=e.threadId?`thread ${e.threadId}`:e.ask?`ask ${e.ask}`:e.group?`group ${e.group}${e.board?` \u2192 ${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?` \u2192 ${e.choice}`:""}`,facts:[...e.messageId?[S("Message",I(e,"messageId"))]:[],...e.groups?.length?[S("Groups",{key:"groups",value:e.groups.join(", ")})]:[]],sections:[]}}function Vs(e){let t={action:e.positionals[0],artifact:e.values.artifact,projectDir:e.projectDir};for(let r of["ask","block","board","choice","claim","element","gap","group","page","quote","round","text","thread","x","y"])t[r]=e.values[r];for(let r of["all","clear","withdraw"])t[r]=!!e.values[r];return t}function hn(e){let t=Vs(e),r=t.action;if(t.artifact?.startsWith("verify/")&&["list","read","ack"].includes(r??"")){if(r!=="list")throw new m({code:"E_OPTION_UNSUPPORTED",message:"A verify report has no thread receipts: comment list shows every thread."});return gn(e)}if(["list","read","ack"].includes(r??""))return an(e);if(["section","sections","limit","cursor","snapshot","receipt","status","waiting-on","kind","choice-state"].some(n=>e.values[n]!==void 0))throw new m({code:"E_OPTION_UNSUPPORTED",message:"Review query options apply only to list, read and ack."});return x({id:`comment.${r??"unknown"}`,mode:"finite",output:{formats:r==="pass"&&t.all?["brief","json","jsonl"]:["brief","json","jsonl","quiet"],scalar:n=>n.ask??n.group??n.round??n.threadId??n.artifact},async run(n,o){let s=yn(t),i=o.effects.begin(`comment.${s.action}`,t.thread??t.ask??t.group??t.artifact),a=await bn(t,s,o.signal);if(a.status>=400&&a.status<500&&o.effects.set(i,"failed"),a.status<200||a.status>=300)throw new m({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 c=a.json;o.effects.confirm(i);let{action:d,request:l}=s,p={add:"added",reply:"replied",resolve:"resolved",answer:t.clear?"cleared":"answered",note:"settled",choose:t.clear?"cleared":"recorded",pass:"recorded",reject:"recorded",waive:"recorded",submit:t.withdraw?"withdrawn":"submitted"},f=d==="pass"&&[c.groups,c.claims].some(R=>Array.isArray(R)&&R.length===0);f&&o.effects.set(i,"none");let k={artifact:t.artifact,operation:d,status:f?"unchanged":p[d],by:"agent",...typeof c.threadId=="string"?{threadId:c.threadId}:{},...typeof c.messageId=="string"?{messageId:c.messageId}:{},...t.ask?{ask:t.ask}:{},...t.group?{group:t.group}:{},...Array.isArray(c.groups)?{groups:c.groups}:{},...Array.isArray(c.claims)?{groups:c.claims}:{},...t.claim?{group:t.claim}:{},...t.gap?{group:t.gap}:{},...t.round?{round:t.round}:{},...d==="choose"?{board:l.board}:{},...d==="submit"?{submitted:!t.withdraw}:{},...d==="answer"?{choice:l.choice}:{}};return E(k,void 0,{effects:o.effects.snapshot()})},present:Gs},e)}var Ws=["add","reply","resolve","choose","submit","answer","note","pass","reject","waive"],qs=/^(?:document|artboard|whiteboard|verify)\/[a-z0-9][a-z0-9-]*$/,Hs=new Set(["pass","reject"]);function Bs(){if(process.stdin.isTTY)return"";try{return wn.default.readFileSync(0,"utf8")}catch{return""}}function ee(e){let t=(e.text??Bs()).trim();if(!t)throw new b("The message is empty: pass --text <text> or pipe it on stdin");return t}function ct(e,t){if(e===void 0)return;let r=Number(e);if(!Number.isFinite(r))throw new b(`${t} must be a number`);return r}function Ys(e,t){if(t==="pass"||t==="reject"){let r=t==="pass"&&!!e.all;if(!r&&!e.claim)throw new b(t==="pass"?"comment pass on a report needs --claim <claimId>, or --all":"comment reject on a report needs --claim <claimId>");let n=t==="reject"?ee(e):e.text?.trim();return{op:"verdict",verdict:t,...r?{all:!0}:{claim:e.claim},...n?{text:n}:{}}}if(t==="waive"){if(!e.gap)throw new b("comment waive needs --gap <gapId>");return{op:"waive",gap:e.gap}}if(t==="reply"){if(!e.thread)throw new b("comment reply needs --thread <threadId>");return{op:"reply",threadId:e.thread,text:ee(e)}}throw new b(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}function Js(e,t,r){if(r==="verify")return Ys(e,t);if(t==="waive")throw new b("comment waive works on verify reports only");if(r==="document"&&(t==="submit"||t==="answer"||t==="note"))return fn(t,e,()=>ee(e),e.text);if((t==="answer"||t==="note")&&r!=="document")throw new b(`comment ${t} works on documents only`);if((t==="choose"||t==="submit"||Hs.has(t))&&r!=="artboard")throw new b(`comment ${t} works on artboards only`);if(t==="pass"||t==="reject"){let n=t==="pass"&&!!e.all;if(!n&&!e.group)throw new b(t==="pass"?"comment pass needs --group <groupId>, or --all":"comment reject needs --group <groupId>");let o=t==="reject"?ee(e):e.text?.trim();return{op:"verdict",verdict:t,...n?{all:!0}:{group:e.group},...o?{text:o}:{}}}if(t==="choose"){if(!e.group)throw new b("comment choose needs --group <groupId>");if(!e.clear&&!e.board)throw new b("comment choose needs --board <boardId>, or --clear");return{op:"choose",group:e.group,board:e.clear?null:e.board}}if(t==="submit"){if(!e.round)throw new b("comment submit needs --round <roundId>");return{op:"submit",round:e.round,submit:!e.withdraw}}if(t==="add"&&r==="artboard"){if(!e.board)throw new b("comment add on an artboard needs --board <boardId>");let n=ct(e.x,"--x"),o=ct(e.y,"--y");return{op:"add",board:e.board,...n!==void 0?{x:n}:{},...o!==void 0?{y:o}:{},text:ee(e)}}if(t==="add"&&r==="whiteboard"){let n=ct(e.x,"--x"),o=ct(e.y,"--y");if(e.element)return{op:"add",element:e.element,text:ee(e)};if(n===void 0||o===void 0)throw new b("comment add on a whiteboard needs --element <id>, or --x and --y");return{op:"add",x:n,y:o,...e.page?{page:e.page}:{},text:ee(e)}}if(t==="add"){if(!e.block)throw new b("comment add needs --block <blockId>");return{op:"add",blockId:e.block,...e.quote?{quote:e.quote}:{},text:ee(e)}}if(!e.thread)throw new b(`comment ${t} needs --thread <threadId>`);return t==="reply"?{op:"reply",threadId:e.thread,text:ee(e)}:{op:"resolve",threadId:e.thread}}function yn(e){let t=Ws.find(s=>s===e.action);if(!t)throw new b("comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive");if(!e.artifact||!qs.test(e.artifact))throw new b("--artifact must be document/<id>, artboard/<id>, whiteboard/<id> or verify/<id>");let[r,n]=e.artifact.split("/"),o=Js(e,t,r);return{action:t,type:r,id:n,request:o,artifact:e.artifact}}async function bn(e,t,r){let{type:n,id:o,request:s}=t,i=V(e.projectDir),a=ge(process.env);return i.call("POST",`/api/agent/${n}/${o}/comments`,{...s,...a?{agent:a}:{}},r)}var vn={semantic:hn,name:"comment",summary:"Read and answer comments on a document, artboard or whiteboard (needs a running server)",usage:["list --artifact <document|artboard|whiteboard>/<id> --sections all|<names> [--detail] [--all]","list --artifact <document|artboard|whiteboard>/<id> [--section threads|asks|groups|rounds] [--all]","read --artifact <document|artboard|whiteboard>/<id> --thread <threadId> [--snapshot <token>]","ack --artifact <document|artboard|whiteboard>/<id> --receipt <receipt>","add --artifact document/<id> --block <blockId> [--quote <text>] [--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>]","reply --artifact <document|artboard|whiteboard>/<id> --thread <threadId> [--text <text>]","resolve --artifact <document|artboard|whiteboard>/<id> --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\u2013100, 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 document or artboard"},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"},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)"},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};var Sn=w(require("node:os"),1),Ut=w(require("node:path"),1);var Ks={on:!0,off:!1,inherit:null};function Xs(e){let t=Qe(ne(process.env,process.platform,Sn.default.homedir())),r=Ut.default.join(Ut.default.dirname(W(e.projectDir).root),"config.json");if(e.autoPublish!==void 0){let n=Ks[e.autoPublish];if(n===void 0)throw new b("--auto-publish takes on, off, or (with --project) inherit");if(e.project)ve(r),Lr(r,n);else{if(n===null)throw new b("inherit only applies with --project");Gr(t,n)}}return{global:Ur(t)??null,project:Z(r).config.autoPublish??null}}var Rn={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=>x({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(){if(e.values["auto-publish"]!==void 0&&e.values["output-format"]!==void 0)throw new b("Choose auto-publish or output-format.");typeof e.values["output-format"]=="string"&&Hr(e.projectDir,!!e.values.project,e.values["output-format"]);let t=Xs({projectDir:e.projectDir,autoPublish:e.values["auto-publish"],project:!!e.values.project});return E({...t,output:Oe(e.projectDir),effective:t.project??t.global,source:t.project!==null?"project":t.global!==null?"global":"undecided",applies:"supported_turn_end_hook"})},present:zs},e)};function zs({data:e}){let t=e.effective===null?"undecided":e.effective?"on":"off";return{heading:"Config",status:"",facts:[S("Auto-publish",{key:"autoPublish",value:e.source==="undecided"?t:`${t} (${e.source})`}),S("Output format",{key:"output",value:`${e.output.effective} (${e.output.source})`})],sections:[]}}var Te=w(require("node:fs"),1),Gt=w(require("node:os"),1),oe=w(require("node:path"),1);var Qs=/<head(\s[^>]*)?>/i,Zs=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,Cn="<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>",ei=/^<script>([\s\S]*?)<\/script>/,ti=/^(?:<script defer src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui)\.js"><\/script>)+/;function ri(e){let t=Qs.exec(e);return t?t.index+t[0].length:Zs.exec(e)?.[0].length??0}function kn(e){let t=ri(e),r=e.slice(t);r.startsWith(Cn)&&(r=r.slice(Cn.length));let n=ei.exec(r);return!n||!n[1].includes("ryugi:")?e:e.slice(0,t)+r.slice(n[0].length).replace(ti,"")}function ni({data:e}){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(" \xB7 "),facts:[S("Title",I(e,"title")),...e.dir?[S("Downloaded",I(e,"dir"),!0)]:e.files?[S("Files available",{key:"files",value:e.files.join(", ")})]:[]],sections:[...e.outline?[{kind:"records",key:"outline",rows:e.outline,columns:[{key:"id",positional:!0,required:!0},{key:"type",positional:!0},{key:"preview",positional:!0}]}]:[],...e.content!==void 0?[{kind:"content",key:"content",title:"LiteXML",text:e.content}]:[],...e.comments?[{...Lt(e.comments.threads,"comments"),title:"Published snapshot comments"}]:[]]}}var te=(e,t)=>typeof e.values[t]=="string"?e.values[t]:void 0,oi=e=>!!e&&!e.includes("\\")&&!e.includes("\0")&&!oe.default.posix.isAbsolute(e)&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..");async function si(e,t,r){if(!e.contentBase||!Array.isArray(e.files))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server did not return a complete download manifest."});if(e.files.some(n=>!oi(n)))throw new m({code:"E_FILE_PATH_UNSAFE",message:"The manifest contains an unsafe file path."});if(Te.default.existsSync(t))throw new m({code:"E_FILE_EXISTS",message:`Download directory already exists: ${t}`});Te.default.mkdirSync(oe.default.dirname(t),{recursive:!0}),Te.default.mkdirSync(t,{mode:448});for(let n of e.files){let o=oe.default.join(t,...n.split("/")),s=r.effects.begin("download",o);try{let i=await fetch(`${e.contentBase}${n.split("/").map(encodeURIComponent).join("/")}`,{signal:r.signal});if(!i.ok)throw new Error(`HTTP ${i.status}`);Te.default.mkdirSync(oe.default.dirname(o),{recursive:!0});let a=Buffer.from(await i.arrayBuffer()),c=je(o,n.endsWith(".html")?kn(a.toString("utf8")):a);r.effects.confirm(s,{bytes:c.bytes})}catch(i){throw r.effects.set(s,"failed",{message:i.message}),new m({code:"E_DOWNLOAD_FAILED",message:`Could not download ${n}: ${i.message}`})}}}function En(e){let t=e.positionals[0];if(!t)throw new m({code:"E_ARGUMENT_INVALID",message:"Give a Cloud link or artifact ID."});let{origin:r,id:n,grant:o}=An(t,(process.env.RYUGI_CLOUD_ORIGIN||"https://ryugi.innei.dev").replace(/\/+$/,"")),s=!!e.values.source||e.values.format==="source",i=te(e,"save"),a=te(e,"block"),c=te(e,"out"),d=!!e.values.download||!!c,l=!!e.values.detail||s;if(i&&!s)throw new m({code:"E_OPTION_CONFLICT",message:"--save requires --source."});if(s&&(a||d||te(e,"fields")||te(e,"cursor")||te(e,"limit")))throw new m({code:"E_OPTION_CONFLICT",message:"Source must be a complete document; use --snapshot to pin its version."});if(a&&(d||l||te(e,"cursor")))throw new m({code:"E_OPTION_CONFLICT",message:"--block reads one complete block and cannot combine with detail, cursor or download."});let p=te(e,"limit");if(p&&(!/^\d+$/.test(p)||+p<1||+p>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});let f=new URLSearchParams({semantic:"1"});for(let k of["snapshot","cursor","fields","limit","section","page"]){let R=te(e,k);R&&f.set(k,R)}return l&&f.set("detail","1"),a&&f.set("block",a),d&&f.set("download","1"),(e.values["no-comments"]||s)&&f.set("no-comments","1"),x({id:"get",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","source","quiet"],requiredFields:["id","type","visibility","version","status",...d?["dir"]:[]],fields:["id","type","title","visibility","version","updatedAt","outline","files","content","comments"],scalar:k=>k.id},async run(k,R){let j=Xe(ne(process.env,process.platform,Gt.default.homedir()),r),N=await fetch(`${r}/api/a/${n}?${new URLSearchParams([...f,...Object.entries(o??{})])}`,{headers:j?{Authorization:`Bearer ${j.token}`}:{},signal:R.signal}),M=await N.text();R.payloads.raw=M;let A;try{A=JSON.parse(M)}catch{throw new m({code:"E_PROTOCOL_MISMATCH",message:"The Cloud server returned an unsupported read response."})}if(!N.ok)throw new m({code:N.status===404?"E_NOT_FOUND":"E_CLOUD_FAILED",httpStatus:N.status,message:A.error||`HTTP ${N.status}`});if(A.schema!=="ryugi.cloud-read/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The Cloud server returned an unsupported read response."});if(s){if(A.type!=="document"||typeof A.content!="string")throw new m({code:"E_FORMAT_UNSUPPORTED",message:"Source is available for documents only."});if(R.payloads.source=A.content,i){let T=je(i,A.content);R.payloads.source="",R.diagnostic(`Saved ${T.file} (${T.bytes} bytes)`)}}let{schema:v,page:u,contentBase:y,...g}=A,h={...g,status:d?"downloaded":l||a?"read":"available"};if(d){h.dir=oe.default.resolve(c??oe.default.join(process.env.XDG_CACHE_HOME||oe.default.join(Gt.default.homedir(),".cache"),"ryugi","get",n,`v${A.version}`));try{await si(A,h.dir,R)}catch(T){if(!R.effects.snapshot().some(D=>D.state==="confirmed"))throw T;return h.status="partial",h.downloads=R.effects.snapshot(),E(h,{kind:"partial"},{warnings:[{code:"W_DOWNLOAD_PARTIAL",message:T.message}]})}h.downloads=R.effects.snapshot()}let C=[...f.entries()].filter(([T])=>!["semantic","cursor","snapshot","detail","download"].includes(T)).flatMap(([T,D])=>T==="no-comments"?[`--${T}`]:[`--${T}`,D]),P=["get",t,...C,"--snapshot",A.snapshot],_=["get",t,...C,...l?["--detail"]:[],"--cursor",A.page?.nextCursor??""];return E(h,void 0,{coverage:{page:u,...!l&&!a?{omitted:[{path:"data.content",reason:"summary"}]}:{}},actions:[...!l&&!a?[$([...P,"--detail"],"Details")]:[],...!a&&!s&&!d&&A.page?.nextCursor?[$(_,"More")]:[]]})},present:ni},e)}var ii=/^[\w-]{1,64}$/,ai=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,xn="Expected a Ryugi Cloud link (https://<host>/a/<id>) or an artifact id.";function An(e,t){if(ii.test(e))return{origin:t,id:e};let r;try{r=new URL(e)}catch{throw new b(xn)}let n=ai.exec(r.pathname)?.[1];if(!n||r.protocol!=="https:"&&r.protocol!=="http:")throw new b(xn);let o=r.searchParams.get("key"),s=r.searchParams.get("via");return{origin:r.origin,id:n,...o?{grant:{key:o,...s?{via:s}:{}}}:{}}}var In={name:"get",summary:"Read a published Ryugi Cloud artifact by link or id, signed in as this machine's cloud account",usage:["<link-or-id> [--out <dir>] [--no-comments] [options]"],details:"Shows a published outline or manifest. Use --detail, --source or --download to fetch more.",semantic:En,options:{section:{type:"string",value:"<outline|files>",help:"Choose the independently paginated collection"},source:{type:"boolean",help:"Print complete LiteXML only (semantic protocol)"},download:{type:"boolean",help:"Download the complete published manifest"},save:{type:"string",value:"<file>",help:"Save complete source to a new file"},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};var _n=require("node:child_process"),qt=w(require("node:fs"),1),Tn=w(require("node:os"),1),ut=w(require("node:path"),1),$n=w(require("node:readline/promises"),1);var ci="Innei/ryugi",Vt={artifacts:"ryugi-artifacts@ryugi-dev",full:"ryugi@ryugi-dev"},ui="https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only";function li(e,t=process.platform){return t==="win32"?{command:["claude",...e].join(" "),args:[],shell:!0}:{command:"claude",args:e,shell:!1}}function Pn(e){let{command:t,args:r,shell:n}=li(e);return(0,_n.spawnSync)(t,r,{encoding:"utf8",stdio:["ignore","pipe","pipe"],shell:n})}function $e(e){let t=Pn(e);if(t.error||t.status!==0)throw new Error(`claude ${e.join(" ")} failed: ${(t.stderr||t.stdout||t.error?.message||"").trim()}`);return t.stdout}function di(){let e=Pn(["--version"]);return!e.error&&e.status===0}function On(e){if(!qt.default.existsSync(e))return{};let r=JSON.parse(qt.default.readFileSync(e,"utf8")).enabledPlugins;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function pi(){let e=JSON.parse($e(["plugin","marketplace","list","--json"]));if(!Array.isArray(e))throw new Error("claude plugin marketplace list returned no list");return e.some(t=>t?.name==="ryugi-dev")}var Wt=e=>e==="artifacts"||e==="full";async function jn(e){let t=$n.default.createInterface({input:process.stdin,output:process.stderr});try{return(await t.question(e)).trim().toLowerCase()}finally{t.close()}}async function fi(e){let t=e?"full":"artifacts",r=await jn(`Install artifacts only, or the full Ryugi workflow? [artifacts/full] (${t}) `),n=r===""?t:r.startsWith("a")?"artifacts":r.startsWith("f")?"full":null;return n!=="artifacts"||!e||(await jn("This turns off the brainstorming, spec and TDD skills. Continue? [y/N] ")).startsWith("y")?n:null}async function mi(e,t){let r=p=>E({mode:null,harness:"claude-code",installed:null,disabled:[]},{kind:"validation_failed"},{warnings:[{code:"W_INSTALL_MODE",message:p,severity:"error"}]});if(e!==void 0&&!Wt(e))return r("--mode takes artifacts or full");if(!di())return E({mode:Wt(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:ui}]});let n=process.env.CLAUDE_CONFIG_DIR||ut.default.join(Tn.default.homedir(),".claude"),o=On(ut.default.join(n,"settings.json")),s;if(Wt(e))s=e;else if(process.stdin.isTTY&&process.stderr.isTTY)s=await fi(o[Vt.full]===!0);else return r("--mode artifacts|full is required without a terminal to ask in");if(s===null)return r("Nothing installed: no mode chosen");let i=Vt[s],a=Vt[s==="artifacts"?"full":"artifacts"];pi()||$e(["plugin","marketplace","add",ci,"--scope","user"]),$e(["plugin","marketplace","update","ryugi-dev"]),$e(["plugin","install",i,"--scope","user"]);let c=[];o[a]===!0&&($e(["plugin","disable",a,"--scope","user"]),c.push(a));let d=[],l=[];for(let[p,f]of[["project","settings.json"],["local","settings.local.json"]])On(ut.default.join(t,".claude",f))[a]===!0&&(d.push({code:"W_OTHER_VARIANT_ENABLED",message:`${a} is still enabled at ${p} scope; enable only one Ryugi entry`,severity:"warning"}),l.push({kind:"command",argv:["claude","plugin","disable",a,"--scope",p],label:`Disable at ${p} scope`}));return E({mode:s,harness:"claude-code",installed:i,disabled:c},{kind:"succeeded"},{warnings:d,actions:l})}function gi({data:e}){return{heading:"Install",status:e.installed?"installed":"unchanged",summary:e.installed?`${e.mode} \xB7 Claude Code`:"",facts:[S("Installed",I(e,"installed")),S("Disabled",{key:"disabled",value:e.disabled.join(", ")||null})],sections:[]}}var Nn={name:"install",summary:"Install Ryugi into Claude Code: artifacts only, or the full workflow",usage:["[--mode artifacts|full] [options]"],details:"Without --mode, asks in the terminal. The two entries are never enabled together: installing one disables the other at user scope.",options:{mode:{type:"string",value:"artifacts|full",help:"What to install"}},semantic:e=>x({id:"install",mode:"finite",output:{formats:["brief","json","jsonl","quiet"]},run:()=>mi(e.values.mode,e.projectDir),present:gi},e)};var Dn=require("node:child_process"),Ht=w(require("node:path"),1),hi=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function yi(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 hi.exec(e)?.[1]??null}function bi(e){let t=yi(e.trim());if(!t)return null;let r=t.replace(/\.git\/?$/,"").split("/").filter(Boolean);return r.length<2?null:r.join("/").toLowerCase()}function lt(e){try{let t=(0,Dn.execFileSync)("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return bi(t)??Ht.default.basename(e)}catch{return Ht.default.basename(e)}}var Kn=w(require("node:fs"),1),ft=w(require("node:path"),1);var qn=w(require("node:fs"),1),Hn=w(require("node:path"),1);var Bt="modules.json",Yt=3,Ln=100,Mn=60,Fn=200,Un=20,Gn=/^[a-z0-9-]{1,40}$/,Vn="1 to 40 lowercase letters, digits and dashes",Wn=e=>e===void 0?[]:Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null;function wi(e,t){if(typeof e!="object"||e===null)return`module ${t+1} must be an object`;let{id:r,name:n,description:o="",paths:s,aliases:i}=e;if(typeof r!="string"||!Gn.test(r))return`module id ${JSON.stringify(r)} must be ${Vn}`;if(typeof n!="string"||n.trim()==="")return`${r} needs a name`;if(n.length>Mn)return`${r}: a name is at most ${Mn} characters`;if(typeof o!="string")return`${r}: description must be text`;if(o.length>Fn)return`${r}: a description is at most ${Fn} characters`;let a=Wn(s);if(!a)return`${r}: paths must be a list of globs`;let c=Wn(i);if(!c)return`${r}: aliases must be a list of retired ids`;if(c.length>Un)return`${r} has more than ${Un} aliases`;let d=c.find(l=>!Gn.test(l));return d!==void 0?`alias ${JSON.stringify(d)} of ${r} must be ${Vn}`:{id:r,name:n,description:o,paths:a,aliases:c}}function vi(e){let t;try{t=JSON.parse(e)}catch(s){return{state:"invalid",reason:`modules.json is not valid JSON: ${s.message}`}}let r=t?.modules;if(!Array.isArray(r))return{state:"invalid",reason:'"modules" must be a list'};if(r.length>Ln)return{state:"invalid",reason:`a vocabulary has at most ${Ln} modules`};let n=[],o=new Set;for(let[s,i]of r.entries()){let a=wi(i,s);if(typeof a=="string")return{state:"invalid",reason:a};if(o.has(a.id))return{state:"invalid",reason:`duplicate module id: ${a.id}`};o.add(a.id),n.push(a)}for(let{id:s,aliases:i}of n){let a=i.find(c=>o.has(c));if(a!==void 0)return{state:"invalid",reason:`alias ${JSON.stringify(a)} of ${s} is a live module id`}}return{state:"ok",modules:n}}function Jt(e){let t;try{t=qn.default.readFileSync(Hn.default.join(e,Bt),"utf8")}catch{return{state:"missing"}}return vi(t)}function Bn(e,t){let r=new Set,n=[];for(let o of t){let s=e.some(i=>i.id===o)?[o]:e.filter(i=>i.aliases.includes(o)).map(i=>i.id);s.length===0&&n.push(o);for(let i of s)r.add(i)}return n.length?{unknown:n}:{ids:[...r].sort()}}var pt=`.ryugi/${Bt}`,Yn=20,Si=20,Kt=e=>ft.default.dirname(W(e).root),Xt=e=>ft.default.join(Kt(e),"config.json");function Xn(e,t){if(!re.test(t))throw new b(me);if(!Kn.default.existsSync(ft.default.join(W(e).root,t)))throw new b(`No such artifact: ${t}`)}function Ri(e){let t=Jt(Kt(e));if(t.state==="missing")throw new b(`This project has no vocabulary. Create ${pt} first.`);if(t.state==="invalid")throw new b(`${pt} is invalid: ${t.reason}`);return t.modules}function zn(e,t,r){Xn(e,t);let n=Ri(e),o=r.split(",").map(a=>a.trim()).filter(Boolean),s=Bn(n,o);if("unknown"in s)throw new b(`Unknown module: ${s.unknown.join(", ")}. Choose from: ${n.map(({id:a})=>a).join(", ")}.`);if(s.ids.length>Yt)throw new b(`An artifact has at most ${Yt} modules; pick the ones it is mainly about.`);let i=Xt(e);return ve(i),Dr(i,t,{modules:s.ids}),{artifact:t,modules:s.ids}}function Ci(e){let t=new Map,r=0;for(let{modules:n}of Object.values(Z(Xt(e)).config.artifacts))if(n?.length){r+=1;for(let o of n)t.set(o,(t.get(o)??0)+1)}return{counts:t,tagged:r}}var dt=e=>e.replace(/\/?\*+$/,"").replace(/\/$/,""),Jn=(e,t)=>e===t||e.startsWith(`${t}/`);function ki(e){let t=[];for(let[r,n]of e.entries())for(let o of e.slice(r+1)){let s=n.paths.flatMap(i=>o.paths.map(a=>[i,a])).find(([i,a])=>Jn(dt(i),dt(a))||Jn(dt(a),dt(i)));s&&t.push(`paths overlap: ${n.id} and ${o.id} (${s[0]} and ${s[1]})`)}return t}function Ei(e,t,r){let n=e.filter(({id:o})=>!t.get(o)).map(({id:o})=>o);return[...e.length>Yn?[`${e.length} modules, more than ${Yn}: merge the ones that are always chosen together`]:[],...r>=Si&&n.length?[`no artifacts: ${n.join(", ")} \u2014 merge them into a neighbour or remove them`]:[],...ki(e)]}function Qn(e,{cloud:t,artifact:r}={}){r&&Xn(e,r);let n=r?{current:Z(Xt(e)).config.artifacts[r]?.modules??null}:{},o=Jt(Kt(e)),s=t?"cloud":"local";if(o.state!=="ok")return{file:pt,state:o.state,...o.state==="invalid"?{reason:o.reason}:{},modules:[],counts:s,hints:[],...r?{artifact:r}:{},...n};let i=Ci(e),a=t?new Map(t.modules.map(({id:d,count:l})=>[d,l])):i.counts,c=t?t.tagged:i.tagged;return{file:pt,state:"ok",modules:o.modules.map(d=>({...d,count:a.get(d.id)??0})),counts:s,hints:Ei(o.modules,a,c),...r?{artifact:r}:{},...n}}async function Ai(e,t){try{let{status:r,json:n}=await V(e).call("GET","/api/cloud/artifacts",void 0,t);if(r!==200)return;let o=lt(W(e).project);return n.vocabularies?.[o]}catch{return}}function xi({data:e}){let t=e.state==="missing"?`no vocabulary: create ${e.file}`:e.state==="invalid"?`invalid: ${e.reason}`:"";return{heading:"Modules",status:e.state==="ok"?"":e.state,subject:e.artifact,summary:t||`${e.modules.length} \xB7 ${e.file} \xB7 counts from ${e.counts==="cloud"?"Cloud":"this checkout only"}`,facts:e.current===void 0?[]:[S("Current",{key:"current",value:e.current===null?"never tagged":e.current.length?e.current.join(", "):"cleared"})],sections:[{kind:"records",key:"modules",rows:e.modules.map(r=>({...r,paths:r.paths.join(" ")})),columns:[{key:"id",positional:!0,required:!0},{key:"count",positional:!0,required:!0},{key:"name",positional:!0},{key:"description",positional:!0},{key:"paths",positional:!0}]},{kind:"diagnostics",key:"hints",items:e.hints.map(r=>({code:"W_MODULES_MAINTENANCE",message:r,severity:"warning"}))}]}}function Ii({data:e}){return{heading:"Modules",status:"SET",subject:e.artifact,summary:e.modules.length?e.modules.join(", "):"cleared",facts:[],sections:[]}}var Zn={name:"modules",summary:"List the project's business modules, or set the modules an artifact serves",usage:["[--artifact <type>/<id>] [options]","--artifact <type>/<id> --set <id>[,<id>...]"],details:'Modules come from .ryugi/modules.json. --set takes ids from that file, at most 3; --set "" clears.',options:{artifact:{type:"string",value:"<type>/<id>",help:"The artifact to show or tag"},set:{type:"string",value:"<id>[,<id>...]",help:"Replace the artifact\u2019s modules with these ids"}},semantic:e=>{let t=e.values.artifact,r=e.values.set;if(r!==void 0){if(!t)throw new b("--set needs --artifact <type>/<id>");return x({id:"modules.set",mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:n=>n.modules.join(",")},run:()=>E(zn(e.projectDir,t,r)),present:Ii},e)}return x({id:"modules",mode:"finite",output:{formats:["brief","table","json","jsonl"],fields:["id","count","name","description","paths","aliases"],collection:"modules",requiredFields:["id","count"]},async run(n,o){let s=await Ai(e.projectDir,o.signal);return E(Qn(e.projectDir,{cloud:s,artifact:t}))},present:xi},e)}};function se(e){if(e.status>=200&&e.status<300)return e.json;let t=e.json;throw new m({code:e.status===401?"E_LOGIN_REQUIRED":typeof t.code=="string"?`E_${t.code.toUpperCase()}`:`E_HTTP_${e.status}`,message:typeof t.error=="string"?t.error:`Cloud request failed: HTTP ${e.status}`,httpStatus:e.status,details:{...t.loginUrl?{loginUrl:t.loginUrl}:{},...t.upgradeUrl?{upgradeUrl:t.upgradeUrl}:{},...t.limit?{limit:t.limit}:{},...t.plan?{plan:t.plan}:{},...t.reasons?{reasons:t.reasons}:{}}},e.status===401||e.status===402&&(t.code==="plan_limit"||t.code==="plan_required")?"action_required":"failed")}function Oi({data:e}){return{heading:"Publish",status:e.status,subject:e.artifact,facts:[S("ID",I(e,"id"),!0),S("URL",I(e,"url"),!0),S("Visibility",{key:"visibility",value:`${e.visibility} (${e.visibilitySource})`},!0),...e.visibility==="public"?[S("Profile",{key:"onProfile",value:e.onProfile?"listed":"not listed"},!0)]:[],...e.shareKey?[S("Key",{key:"shareKey.key",value:e.shareKey.key},!0),S("Expires",{key:"shareKey.expiresAt",value:e.shareKey.expiresAt??"never"},!0)]:[],...e.version===void 0?[]:[S("Version",I(e,"version"))]],sections:e.references.length?[{kind:"records",key:"references",title:"Referenced artifacts",rows:e.references.map(t=>({artifact:t.artifact,status:t.status,via:t.via?`via ${t.via}`:"",error:t.error?`${t.error.code}: ${t.error.message}`:"",recovery:t.status==="unknown"?"inspect the remote artifact before retrying":""})),columns:[{key:"artifact",positional:!0,required:!0},{key:"status",positional:!0,required:!0},{key:"via",positional:!0},{key:"error",positional:!0},{key:"recovery",positional:!0}]}]:[]}}function ji({data:e,coverage:t}){return{heading:"Cloud artifacts",status:"",summary:`${t.page?.total??e.artifacts.length} on account`,facts:[],sections:[{kind:"records",key:"artifacts",rows:e.artifacts.map(n=>({...n,version:n.version===void 0?"":`v${n.version}`})),columns:[{key:"id",positional:!0,required:!0},{key:"type",positional:!0},{key:"visibility",positional:!0,required:!0},{key:"version",positional:!0},{key:"updatedAt",positional:!0},{key:"title",positional:!0}]}]}}var eo=["brief","json","jsonl","quiet"];function _i(e){let{values:t}=e,r=["unpublish","revoke-key","list","delete","login","logout"].filter(a=>t[a]),n=!!(t.key||t["new-key"]);if(r.length>1||t.public&&t.private||t.public&&n||t.profile&&t["no-profile"]||n&&t["revoke-key"])throw new m({code:"E_OPTION_CONFLICT",message:"Choose one publish action and one visibility."});let o=r[0]??"publish";if(o!=="list"&&["visibility","type","project","module","limit","cursor"].some(a=>t[a]!==void 0))throw new m({code:"E_OPTION_UNSUPPORTED",message:"List filters and paging apply only to --list."});let s=t.artifact;if(["publish","unpublish","revoke-key"].includes(o)&&(!s||!re.test(s)))throw new m({code:"E_ARGUMENT_INVALID",message:"--artifact must be <type>/<id>."});if(o==="delete"&&!/^[\w-]{1,64}$/.test(String(t.delete??"")))throw new m({code:"E_ARGUMENT_INVALID",message:"--delete requires a Cloud artifact ID."});if(o!=="publish"&&(t.public||t.private||t["no-refs"]||t.profile||t["no-profile"]))throw new m({code:"E_OPTION_UNSUPPORTED",message:"Visibility, profile listing and --no-refs apply only to publishing."});if(t.expires!==void 0&&!n)throw new m({code:"E_OPTION_UNSUPPORTED",message:"--expires applies only with --key or --new-key."});if(t.expires!==void 0&&!Tr(t.expires))throw new m({code:"E_ARGUMENT_INVALID",message:"--expires must be 1d, 7d, 30d or never."});let i=n?{...t.expires?{expires:t.expires}:{},...t["new-key"]?{regenerate:!0}:{}}:void 0;return{action:o,artifact:s,key:i,onProfile:t.profile?!0:t["no-profile"]?!1:void 0,visibility:t.public?"public":t.private||i?"private":void 0}}async function Ti(e,t,r,n,o,s){let i=V(e.projectDir),c=await(async(u,y)=>{let g=t.effects.begin("publish",u),h={...y?{visibility:y}:{},...o===void 0?{}:{onProfile:o}},C=await i.call("POST",`/api/cloud/publish/${u}`,Object.keys(h).length?h:void 0,t.signal);C.status>=400&&C.status<500&&t.effects.set(g,"failed",C.json);let P=se(C);return t.effects.confirm(g,{url:P.url,visibility:P.visibility,version:P.version}),P})(r,n),d=s||c.keyed?se(await i.call(s?"PUT":"GET",`/api/cloud/share-key/${r}`,s,t.signal)).shareKey??void 0:void 0,l=se(await i.call("GET",`/api/cloud/refs/${r}?visibility=${c.visibility}&referrers=0`,void 0,t.signal)),p=e.values["no-refs"]?[]:l.items.filter(u=>u.checked&&u.state!=="private"),f=new Map;if(p.length){let u=new Map(p.map(h=>[h.artifact,t.effects.begin("publish",h.artifact)])),y=await i.call("POST",`/api/cloud/publish-refs/${r}`,{visibility:c.visibility,refs:p.map(h=>h.artifact),makePublic:[]},t.signal),g=se(y);for(let h of g.results){f.set(h.artifact,h);let C=u.get(h.artifact);C!==void 0&&(h.status==="published"?t.effects.confirm(C,{}):h.status==="failed"?t.effects.set(C,"failed",h.error):h.status==="not_attempted"&&t.effects.set(C,"not_attempted"))}}let k=u=>{try{se({status:u.error?.httpStatus??500,json:u.error??{}})}catch(y){return Le(y)}},R={publish:"published",update:"updated","make-public":"made_public"},j=l.items.map(u=>{let y={artifact:u.artifact,state:u.state,via:u.via},g=f.get(u.artifact);if(g){let h=g.status==="published"?void 0:k(g);return{...y,status:g.status==="published"?R[g.action]:g.status,...h?{error:h}:{}}}return u.reason==="upstream"?{...y,status:"unreachable"}:u.state==="unpublished"||u.state==="stale"?{...y,status:"skipped"}:{...y,status:u.state}}),N=j.some(u=>["failed","unknown","not_attempted"].includes(u.status)),M={status:N?"partial":"published",artifact:r,id:c.id??new URL(c.url).pathname.split("/").filter(Boolean).at(-1),url:d?.url??c.url,visibility:c.visibility,...c.version===void 0?{}:{version:c.version},visibilitySource:n?"requested":"preserved",onProfile:c.onProfile===!0,onProfileSource:o===void 0?"preserved":"requested",...d?{shareKey:{key:d.key,expiresAt:d.expiresAt}}:{},references:j},A=j.filter(u=>u.status==="private"),v=j.filter(u=>u.status==="skipped");return E(M,N?{kind:"partial"}:{kind:"succeeded"},{effects:t.effects.snapshot(),warnings:[...o&&c.visibility!=="public"?[{code:"W_PROFILE_NEEDS_PUBLIC",message:"It will show on your profile once it is public."}]:[],...A.length?[{code:"W_REFERENCES_PRIVATE",message:`${A.length} referenced artifacts are private; visitors see a locked label.`}]:[],...v.length?[{code:"W_REFERENCES_UNPUBLISHED",message:`${v.length} referenced artifacts were left as they are (--no-refs).`}]:[]],actions:[...j.flatMap(u=>u.error?Ge(u.error,u.artifact):[]),...A.map(u=>$(["publish","--artifact",u.artifact,"--project-dir",e.projectDir,"--public"],"Next")),...v.length&&!N?[$(["publish","--artifact",r,"--project-dir",e.projectDir],"Next")]:[]]})}function to(e){let{action:t,artifact:r,visibility:n,onProfile:o,key:s}=_i(e);if(t==="publish")return x({id:"publish.publish",mode:"finite",output:{formats:eo,scalar:i=>i.id},run:(i,a)=>Ti(e,a,r,n,o,s),present:Oi},e);if(t==="list"){let i=new URLSearchParams({semantic:"1"});for(let a of["visibility","type","project","limit","cursor","fields"]){let c=e.values[a];typeof c=="string"&&i.set(a,c)}if(typeof e.values.module=="string"){i.has("project")||i.set("project",lt(W(e.projectDir).project));let a=e.values.module.split(",").map(c=>c.trim());for(let c of new Set(a))i.append("module",c)}if(i.has("limit")&&(!/^\d+$/.test(i.get("limit"))||+i.get("limit")<1||+i.get("limit")>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});if(i.has("visibility")&&!["public","private"].includes(i.get("visibility"))||i.has("type")&&!["document","artboard","html"].includes(i.get("type")))throw new m({code:"E_ARGUMENT_INVALID",message:"Invalid Cloud list filter."});return x({id:"publish.list",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","raw"],fields:["id","type","title","project","modules","visibility","url","updatedAt","version"],collection:"artifacts",requiredFields:["id","type","visibility","version"]},async run(a,c){let d=await V(e.projectDir).call("GET",`/api/cloud/artifacts?${i}`,void 0,c.signal);c.payloads.raw=d.raw;let l=se(d);if(l.schema!=="ryugi.cloud-list/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported Cloud list response."});return E({artifacts:l.artifacts},void 0,{coverage:{page:l.page},actions:l.page?.nextCursor?[$(["publish","--list","--project-dir",e.projectDir,...[...new Set(i.keys())].filter(p=>!["semantic","cursor"].includes(p)).flatMap(p=>[`--${p}`,i.getAll(p).join(",")]),"--cursor",l.page.nextCursor],"More")]:[]})},present:ji},e)}return x({id:`publish.${t}`,mode:"finite",output:{formats:t==="login"?["brief","json","jsonl"]:eo,scalar:i=>i.id},async run(i,a){let c=t==="delete"?String(e.values.delete):r,d=["login","logout"].includes(t)?"POST":"DELETE",l=t==="delete"?`/api/cloud/artifacts/${c}`:t==="unpublish"?`/api/cloud/publish/${c}`:t==="revoke-key"?`/api/cloud/share-key/${c}`:`/api/cloud/${t}`,p=t==="login"?void 0:a.effects.begin(t,c??"cloud-account"),f=typeof e.values.from=="string"?e.values.from:"cli",k=await V(e.projectDir).call(d,l,t==="login"?{source:f}:void 0,a.signal);p!==void 0&&k.status>=400&&k.status<500&&a.effects.set(p,"failed");let R=se(k);p!==void 0&&a.effects.confirm(p);let j=t==="login"&&!R.signedIn?{kind:"pending",reasons:["sign_in_in_browser"]}:t==="logout"&&R.remoteRevoked!==!0?{kind:"partial"}:{kind:"succeeded"};return E({id:t==="logout"?"signed-out":R.id??c??"cloud-account",artifact:c,status:t==="login"?R.signedIn?"signed_in":"pending":t==="logout"?"signed_out":t==="delete"?"deleted":t==="revoke-key"?"key_removed":"unpublished",...R.url?{url:R.url}:{},...t==="logout"?{localCredentials:"cleared",remoteSession:R.remoteRevoked===!0?"revoked":"unknown"}:{}},j,{effects:a.effects.snapshot(),actions:R.url?[{kind:"url",url:R.url,label:"Open"}]:[]})},present({data:i}){return{heading:t==="login"?"Login":t==="logout"?"Logout":"Cloud artifact",status:i.status,subject:i.id,facts:[...i.artifact?[S("Artifact",I(i,"artifact"))]:[],...i.url?[S("URL",I(i,"url"))]:[],...i.remoteSession?[S("Remote session",I(i,"remoteSession"))]:[]],sections:[]}}},e)}var ro={semantic:to,name:"publish",summary:"Publish an artifact to the Ryugi cloud (needs a running server)",usage:["--artifact <type>/<id> [--public | --private | --key] [--profile | --no-profile] [options]","--artifact <type>/<id> --unpublish | --revoke-key [options]","--list | --delete <cloud-id> | --login | --logout [options]"],options:{visibility:{type:"string",value:"<public|private>",help:"Filter published list visibility"},type:{type:"string",value:"<document|artboard|html>",help:"Filter published list type"},project:{type:"string",value:"<project>",help:"Filter published list project"},module:{type:"string",value:"<id>[,<id>...]",help:'Filter published list by module ("" for untagged); the project defaults to this one'},limit:{type:"string",value:"<1-100>",help:"Maximum list rows"},cursor:{type:"string",value:"<token>",help:"Continue a stable list snapshot"},artifact:{type:"string",value:"<type>/<id>",help:"The artifact to publish or unpublish"},public:{type:"boolean",help:"Anyone with the link can open it"},private:{type:"boolean",help:"Only you can open it"},key:{type:"boolean",help:"Only people with the key can open it; prints a link that carries the key"},expires:{type:"string",value:"<1d|7d|30d|never>",help:"With --key or --new-key: when the key stops working (7d for a new key)"},"new-key":{type:"boolean",help:"Replace the key; links with the old key stop opening"},"revoke-key":{type:"boolean",help:"Remove the key; only you can open it"},profile:{type:"boolean",help:"Show it on your public profile once it is public"},"no-profile":{type:"boolean",help:"Take it off your public profile"},unpublish:{type:"boolean",help:"Remove the artifact's cloud copy"},list:{type:"boolean",help:"List your cloud artifacts"},delete:{type:"string",value:"<cloud-id>",help:"Delete a cloud artifact by its id from --list"},"no-refs":{type:"boolean",help:"Publish only this artifact; leave the artifacts it references as they are"},login:{type:"boolean",help:"Sign in to the Ryugi cloud"},from:{type:"string",value:"<tag>",help:"With --login: where this sign-in started, recorded by Ryugi Cloud"},logout:{type:"boolean",help:"Sign out of the Ryugi cloud"}}};var $i=/^whiteboard\/[a-z0-9][a-z0-9-]*$/,Pi=e=>{let t=e;return typeof e=="object"&&e!==null&&typeof t.artifact=="string"&&typeof t.sceneVersion=="number"&&Array.isArray(t.lines)&&["none","current","stale"].includes(t.render)},no={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=>x({id:"scene",mode:"finite",output:{detail:!1,formats:["brief","json","jsonl","raw"],fields:["artifact","page","pages","sceneVersion","render","renderPath","lines","conflicts"],scalar:t=>t.render},async run(t,r){let n=e.values.artifact;if(!n||!$i.test(n))throw new b("--artifact must be whiteboard/<id>");let o=e.values.frame,s=e.values.page,i=await V(e.projectDir).call("POST",`/api/agent/${n}/scene`,{...o?{frame:o}:{},...s?{page:s}:{}},r.signal);if(r.payloads.raw=i.raw,i.status<200||i.status>=300)throw new b(i.json?.error||`HTTP ${i.status}`);if(!Pi(i.json))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an invalid scene report."});let a=i.json;return E(a,{kind:"succeeded"},{actions:(a.pages??[]).map(c=>$(["scene","--artifact",n,"--page",c.id,"--project-dir",e.projectDir],`Read ${c.id}`))})},present:Ni},e)};function Ni({data:e}){return{heading:"Scene",status:e.problem?"invalid":"",subject:e.artifact,facts:[...e.page?[S("Page",I(e,"page"))]:[],S("Version",I(e,"sceneVersion")),S("Render",I(e,"render")),...e.renderPath?[S("Image",I(e,"renderPath"))]:[],...e.problem?[S("Problem",I(e,"problem"))]:[],S("Conflicts",{key:"conflicts",value:e.conflicts.join(", ")})],sections:[{kind:"content",key:"lines",text:e.lines.join(`
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
`)}function Ae(e){le.default.mkdirSync($e.default.dirname(e),{recursive:!0}),Xs($e.default.dirname(e)),le.default.existsSync(e)||se(e,Pe())}function Kr(e,t,r){let{config:n,warning:o}=ie(e);if(o)throw new Error(o);let s={...n.artifacts[t]};if(r.visibility&&(s.visibility=r.visibility),r.cloud===null)delete s.cloud;else if(r.cloud){let c=s.cloud?.id===r.cloud.id?s.cloud.modulesSynced:void 0;s.cloud={...c?{modulesSynced:c}:{},...r.cloud}}r.autoPublish===null?delete s.autoPublish:r.autoPublish===!1&&(s.autoPublish=!1),r.modules===null?delete s.modules:r.modules&&(s.modules=r.modules);let i=Jr(e);i.artifacts??={};let a={...i.artifacts[t]};if(r.visibility&&(a.visibility=s.visibility),r.cloud){let c={...a.cloud?.id===r.cloud.id?a.cloud:{}};for(let l of Object.keys(zr(c)))delete c[l];a.cloud={...c,...s.cloud}}return r.autoPublish===!1&&(a.autoPublish=!1),r.modules&&(a.modules=r.modules),r.cloud===null&&delete a.cloud,r.autoPublish===null&&delete a.autoPublish,r.modules===null&&delete a.modules,i.artifacts[t]=a,se(e,i),s}function Xr(e,t){let r=Jr(e);t===null?delete r.autoPublish:r.autoPublish=t,le.default.mkdirSync($e.default.dirname(e),{recursive:!0}),se(e,r)}var Qr=C(require("node:fs"),1),tt=C(require("node:path"),1);function ue(e,t,r){return t==="win32"&&e.APPDATA?tt.default.join(e.APPDATA,"ryugi","credentials.json"):tt.default.join(e.XDG_CONFIG_HOME||tt.default.join(r,".config"),"ryugi","credentials.json")}function rt(e,t){let r;try{r=JSON.parse(Qr.default.readFileSync(e,"utf8"))}catch{return null}if(typeof r!="object"||r===null)return null;let{origin:n,token:o,login:s}=r;return typeof n!="string"||typeof o!="string"||typeof s!="string"||n!==t?null:{origin:n,token:o,login:s}}var Vt=C(require("node:fs"),1),nt=C(require("node:path"),1);var ot=e=>nt.default.join(nt.default.dirname(e),"config.json");function Zr(e,t=!1){try{let r=JSON.parse(Vt.default.readFileSync(e,"utf8"));if(typeof r=="object"&&r!==null&&!Array.isArray(r))return r;if(t)throw new Error(`Expected a configuration object: ${e}`);return{}}catch(r){if(t&&r.code!=="ENOENT")throw r;return{}}}function en(e){let t=Zr(e).autoPublish;return typeof t=="boolean"?t:void 0}function tn(e,t,r=()=>{}){let n=Zr(e,!0);r(),Vt.default.mkdirSync(nt.default.dirname(e),{recursive:!0,mode:448}),se(e,{...n,autoPublish:t})}var qt=["brief","json","jsonl"];function at(e){return{global:ot(ue(process.env,process.platform,rn.default.homedir())),project:st.default.join(st.default.dirname(U(e).root),"config.json")}}function nn(e){try{let t=JSON.parse(it.default.readFileSync(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected an object");return t}catch(t){if(t.code==="ENOENT")return{};throw new m({code:"E_CONFIG_INVALID",message:`Cannot read ${e}: ${t.message}`})}}function Ne(e){let t=at(e),r=s=>{let i=nn(s).output;if(i?.format!==void 0&&!qt.includes(i.format))throw new m({code:"E_FORMAT_UNSUPPORTED",message:`Unsupported output format in ${s}: ${String(i.format)}`});return i&&qt.includes(i.format)?i.format:null},n=r(t.global),o=r(t.project);return{global:n,project:o,effective:o??n??"brief",source:o?"project":n?"global":"default"}}function on(e,t,r,n=()=>{}){if(r==="inherit"&&!t||r!=="inherit"&&!qt.includes(r))throw new m({code:"E_ARGUMENT_INVALID",message:"--output-format takes brief, json, jsonl, or inherit with --project."});let o=at(e),s=t?o.project:o.global,i=nn(s);if(i.output!==void 0&&(!i.output||typeof i.output!="object"||Array.isArray(i.output)))throw new m({code:"E_CONFIG_INVALID",message:`Expected an output configuration object in ${s}.`});let a={...i.output};r==="inherit"?delete a.format:a.format=r,Object.keys(a).length?i.output=a:delete i.output,n(),t?Ae(s):it.default.mkdirSync(st.default.dirname(s),{recursive:!0,mode:448}),se(s,i)}function sn(e,t,r=process.env){if(r.RYUGI_ARTIFACTS_FORMAT!==void 0)return r;let n=_t(e,t);if(["format","json","quiet","source"].some(i=>n[i]!==void 0))return r;let o=typeof n["project-dir"]=="string"?n["project-dir"]:process.cwd();if(!n["project-dir"]&&e[0]&&!e[0].startsWith("-"))try{it.default.statSync(e[0]).isDirectory()&&(o=e[0])}catch{}let s=Ne(o);return{...r,RYUGI_ARTIFACTS_FORMAT:s.effective}}var Qs=e=>[...e.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(t=>t[1]??t[2]??t[3]);function Zs(){let e=process.env.RYUGI_ARTIFACTS_COMMAND?.trim();return e?Qs(e):[process.execPath,process.argv[1]]}function ei(e){if(process.env.RYUGI_ARTIFACTS_FORMAT)return process.env.RYUGI_ARTIFACTS_FORMAT;let t=e.indexOf("--project-dir");try{return Ne(t>=0&&e[t+1]?e[t+1]:process.cwd()).effective}catch{return"brief"}}function E(e,t="Details"){let r=e.indexOf("--"),n=r<0?e:e.slice(0,r),o=r<0?[]:e.slice(r),s={...J,...De.find(l=>l.name===e[0])?.options},i=[],a=!1;for(let l=0;l<n.length;l++){let u=n[l];if(["--format","--source","--quiet"].includes(u.split("=")[0])&&(a=!0),u.startsWith("--")&&!u.includes("=")&&s[u.slice(2)]?.type==="string"&&n[l+1]!==void 0){let d=n[++l];i.push(d.startsWith("-")?`${u}=${d}`:u,...d.startsWith("-")?[]:[d])}else i.push(u)}let c=a||ei(n)==="brief"?[]:["--format","brief"];return{kind:"command",argv:[...Zs(),...i,...c,...o],label:t}}var Ee=C(require("node:fs"),1),an=C(require("node:path"),1);function Le(e,t,r){let n=an.default.resolve(e),o=r?.begin("save",n),s;try{s=Ee.default.openSync(n,"wx",384)}catch(i){throw o!==void 0&&r.set(o,"failed"),new m({code:i.code==="EEXIST"?"E_FILE_EXISTS":"E_FILE_WRITE_FAILED",message:`Could not create ${n}: ${i.message}`})}try{Ee.default.writeFileSync(s,t)}catch(i){throw Ee.default.closeSync(s),Ee.default.unlinkSync(n),o!==void 0&&r.set(o,"failed"),new m({code:"E_FILE_WRITE_FAILED",message:`Could not save ${n}: ${i.message}`})}return Ee.default.closeSync(s),o!==void 0&&r.confirm(o,{bytes:typeof t=="string"?Buffer.byteLength(t):t.byteLength}),{file:n,bytes:typeof t=="string"?Buffer.byteLength(t):t.byteLength}}var fn=C(require("node:fs"),1),mn=C(require("node:path"),1);var cn=`# Artboard writing
|
|
27
|
+
|
|
28
|
+
Write \`canvas.json\` and self-contained board HTML/media under \`pages/\`. Pages are areas, groups are questions, boards are options or evidence. Re-read canvas immediately before editing: humans move boards/notes; patch intended fields and preserve stable IDs and positions. The server protects human moves. Never edit comments.json or \`.state/\`.
|
|
29
|
+
|
|
30
|
+
\`\`\`json
|
|
31
|
+
{
|
|
32
|
+
"version": 1,
|
|
33
|
+
"title": "Delivery settings",
|
|
34
|
+
"activePage": "settings",
|
|
35
|
+
"pages": [{ "id": "settings", "name": "Settings" }],
|
|
36
|
+
"boards": {
|
|
37
|
+
"q1-a": {
|
|
38
|
+
"file": "pages/settings/a.html",
|
|
39
|
+
"page": "settings",
|
|
40
|
+
"x": 0,
|
|
41
|
+
"y": 0,
|
|
42
|
+
"w": 640,
|
|
43
|
+
"h": 400,
|
|
44
|
+
"title": "Fixed delay"
|
|
45
|
+
},
|
|
46
|
+
"q1-b": {
|
|
47
|
+
"file": "pages/settings/b.html",
|
|
48
|
+
"page": "settings",
|
|
49
|
+
"x": 720,
|
|
50
|
+
"y": 0,
|
|
51
|
+
"w": 640,
|
|
52
|
+
"h": 400,
|
|
53
|
+
"title": "Exponential"
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"groups": {
|
|
57
|
+
"q1": {
|
|
58
|
+
"title": "Retry strategy",
|
|
59
|
+
"boards": ["q1-a", "q1-b"],
|
|
60
|
+
"choose": true,
|
|
61
|
+
"recommend": "q1-b"
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"notes": {
|
|
65
|
+
"round-one": {
|
|
66
|
+
"kind": "title",
|
|
67
|
+
"page": "settings",
|
|
68
|
+
"x": 0,
|
|
69
|
+
"y": -300,
|
|
70
|
+
"text": "Retry strategy"
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
\`\`\`
|
|
75
|
+
|
|
76
|
+
Canvas title is readable and distinct from slug. Each board requires page/x/y/w/h and file; optional title/interactive. Image/video boards use type:"image"|"video" and src instead of file. All resources stay under pages/ and use relative paths; other artifact directories are not served. Media <=8MB each, whole artboard <=20MB. Video mp4(H.264)/webm; verify clips trim idle ends with one second context, originals retained; trim:false preserves original timing/narration. Check recordings/pending before handoff.
|
|
77
|
+
|
|
78
|
+
Groups list board IDs all on one page. Normal groups organize; choose:true + recommend:<member> asks a choice; verify:true + from:<environment/build> + capturedAt:<real ISO capture time> asks a verdict. Never combine choose and verify. Notes: kind title, sticky or condition (see Flows), page/x/y/text; title size default96, optional w wraps; sticky w default240, optional #RGB/#RRGGBB color. activePage selects initial page, not an already-open reader's page. focus \`{target:<board/group/note>,at:<fresh ISO time>}\` guides first ready content/phone question; updates preserve open camera/drafts. Share ?page=<id> for a new area.
|
|
79
|
+
|
|
80
|
+
Layout is explicit: 80px horizontal board gap, 160px row gap; group frame 144px above and 48px outside boards. Leave 240px vertically/200px horizontally between groups; notes >=80px clear. Read \`.state/artboard/<id>/layout.json\` for actual group/note rectangles and page bounds before appending. New round starts below maxY, title at maxY+120 then boards below title+80+144. Common sizes desktop1280x800, phone390x844, tablet834x1194, component640x400. Frame height clips without warning: size h to content.
|
|
81
|
+
|
|
82
|
+
## Flows
|
|
83
|
+
|
|
84
|
+
When screens follow one another (an app's UI/UX chain: this action leads there, this condition forks), connect them. \`edges\` draws an arrowed line from one board or condition to another with an optional \`label\` naming the action. A note with \`kind: "condition"\` is a capsule on the line holding the question; each line leaving it carries a short label for its answer. The viewer picks the sides and routes the lines; your human partner can move boards and conditions and the lines follow. Nobody edits a line in the viewer: change \`edges\` to change it.
|
|
85
|
+
|
|
86
|
+
\`\`\`json
|
|
87
|
+
{
|
|
88
|
+
"version": 1,
|
|
89
|
+
"title": "Publish flow",
|
|
90
|
+
"pages": [{ "id": "flow", "name": "Flow" }],
|
|
91
|
+
"boards": {
|
|
92
|
+
"artboard": {
|
|
93
|
+
"file": "pages/flow/artboard.html",
|
|
94
|
+
"page": "flow",
|
|
95
|
+
"x": 0,
|
|
96
|
+
"y": 0,
|
|
97
|
+
"w": 1280,
|
|
98
|
+
"h": 800,
|
|
99
|
+
"title": "Artboard"
|
|
100
|
+
},
|
|
101
|
+
"sign-in": {
|
|
102
|
+
"file": "pages/flow/sign-in.html",
|
|
103
|
+
"page": "flow",
|
|
104
|
+
"x": 2308,
|
|
105
|
+
"y": 1200,
|
|
106
|
+
"w": 1280,
|
|
107
|
+
"h": 800,
|
|
108
|
+
"title": "Sign in"
|
|
109
|
+
},
|
|
110
|
+
"share": {
|
|
111
|
+
"file": "pages/flow/share.html",
|
|
112
|
+
"page": "flow",
|
|
113
|
+
"x": 4068,
|
|
114
|
+
"y": 0,
|
|
115
|
+
"w": 1280,
|
|
116
|
+
"h": 800,
|
|
117
|
+
"title": "Share panel"
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
"notes": {
|
|
121
|
+
"signed-in": { "kind": "condition", "page": "flow", "x": 1760, "y": 328, "text": "Signed in?" }
|
|
122
|
+
},
|
|
123
|
+
"edges": {
|
|
124
|
+
"publish": { "from": "artboard", "to": "signed-in", "label": "Click Publish" },
|
|
125
|
+
"yes": { "from": "signed-in", "to": "share", "label": "Yes" },
|
|
126
|
+
"no": { "from": "signed-in", "to": "sign-in", "label": "No" },
|
|
127
|
+
"done": { "from": "sign-in", "to": "share", "label": "Signed in" }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
\`\`\`
|
|
131
|
+
|
|
132
|
+
Edge \`from\`/\`to\` are board IDs or condition note IDs on one page; \`label\` is one line, at most 32 characters. A condition has \`page/x/y/text\` only: 96px tall, as wide as its text, never wrapped. It needs one line in and at least two out, each outgoing line labelled. Boards and notes share one ID space for edges.
|
|
133
|
+
|
|
134
|
+
Lines run straight between things that face each other and turn once otherwise, so lay a flow out on a grid. Leave 480px between two connected boards, and 480px on each side of a condition placed between them: a label is cut short when its line is shorter than its text, and it grows on screen as the canvas zooms out, so a long chain viewed whole needs the room. A board's rectangle includes the 48px name strip above it: to sit level with a board at \`y\`, a condition goes at \`y + (h - 48) / 2 - 48\`. Put the main path on one row and send the other branch to a row below, clear of the boards the main path passes. Flow boards may still belong to groups.
|
|
135
|
+
|
|
136
|
+
Check reports \`edge "<id>" crosses board "<id>"\` when a line runs through a board that is not one of its ends. It does not block; fix it by moving boards or conditions, since lines cannot be routed by hand. A condition placed on a board is a warning.
|
|
137
|
+
|
|
138
|
+
Board HTML is a complete document ending \`</html>\` (write closing marker last when streaming), inline CSS and scripts, html/body margin0. Build native HTML/CSS/JS with accessible labelled controls and visible state changes. Static by default; interactive:true exposes PLAY for real prototypes. Each board/expanded view has independent iframe state; use in-memory state, no localStorage/sessionStorage/cookies. Keep a shared-state flow in one board; relative links navigate inside its iframe. Replay, HTML edit, page change/reload resets prototype state; selected/playing/tweaked frames stay mounted on same page. \`ryugi-icon name="copy" size="18"\` supplies Lucide icons without imports; label actions. For JS-only icons add meta name="ryugi-icons" content="1" and await custom element definition.
|
|
139
|
+
|
|
140
|
+
Choice lifecycle: title notes define rounds. Write canvas first with all groups/boards/notes/focus, then board files starting with focus. Read comment list --sections threads,groups,rounds --detail; act only on submitted rounds and read their threads. If human answered in terminal, record actual picks with comment choose and comment submit --round <id>. Withdrawal means wait. Add next round below, not over the old one. Documents can reference groups/boards using inline ref; preserve referenced keys.
|
|
141
|
+
|
|
142
|
+
Verify lifecycle: screen evidence belongs in new verify groups, with real from/capturedAt and language-matched titles/stickies. Record pass/reject only on the human's instruction. A reject is a group thread: repair requested behavior, replace evidence (resets pending), reply and leave open; passing closes it. Do not change passed evidence unless asked. Command-output claims/gaps belong in a verify report. Check must have no pending/warnings before claiming ready; inspect actual screenshots/recordings for visual claims. Missing/unfinished board files are pending, never success.
|
|
143
|
+
|
|
144
|
+
## Selection and node IDs
|
|
145
|
+
|
|
146
|
+
Your human partner can point at elements instead of describing them: they
|
|
147
|
+
select nodes in the viewer, tweak CSS in the Inspector, or name a node by
|
|
148
|
+
the ID the viewer shows on hover, \`<board id>#<n>\` (\`hero-2#7\`).
|
|
149
|
+
\`selection.json\` holds the selection as it is right now:
|
|
150
|
+
|
|
151
|
+
- \`selected\`: the selected nodes, each with its \`file\`, a CSS \`path\` from
|
|
152
|
+
\`body\`, \`text\`, \`html\`, and its \`tweaks\` (\`property\`, \`from\`, \`value\`);
|
|
153
|
+
\`more\` counts selected nodes left out.
|
|
154
|
+
- \`boards\`, \`notes\`: the ids of the boards and notes they selected on the
|
|
155
|
+
canvas, left out when none is.
|
|
156
|
+
- \`tweaks\`: Inspector changes on nodes that are not selected.
|
|
157
|
+
- \`nodes\`: every node's ID, \`file\` and \`path\`, for IDs they type.
|
|
158
|
+
|
|
159
|
+
Read it before you act whenever they say "here", "this", "the selected
|
|
160
|
+
ones", name an ID, or refer to what they tweaked. Read only what you need:
|
|
161
|
+
\`nodes\` lists every node on every board and runs to tens of thousands of
|
|
162
|
+
tokens.
|
|
163
|
+
|
|
164
|
+
\`\`\`bash
|
|
165
|
+
jq '{selected, more, boards, notes, tweaks}' '.ryugi/artifacts/.state/artboard/<id>/selection.json'
|
|
166
|
+
\`\`\`
|
|
167
|
+
|
|
168
|
+
Look up \`nodes\` only for an ID they typed:
|
|
169
|
+
\`jq '.nodes[] | select(.id == "hero-2#7")' \u2026/selection.json\`.
|
|
170
|
+
|
|
171
|
+
Some harnesses attach the selection to their message already; the file is
|
|
172
|
+
the same either way. Edit the element at \`path\` in \`file\`. Inspector tweaks are preview only: they exist
|
|
173
|
+
in the source once you write them.
|
|
174
|
+
|
|
175
|
+
IDs are renumbered when a board reloads, which happens after every edit to
|
|
176
|
+
it. Resolve an ID against the current \`nodes\`, and before you change a board
|
|
177
|
+
again, ask for the ID again rather than reusing an old one.
|
|
178
|
+
|
|
179
|
+
## Author-declared parameters
|
|
180
|
+
|
|
181
|
+
Expose a few deliberate levers, such as accent, density, item count or a
|
|
182
|
+
preview scenario. The viewer puts **Parameters** in that board's label and
|
|
183
|
+
opens a floating panel at its right edge. The panel follows canvas pan/zoom
|
|
184
|
+
while its controls keep their screen size. Opening can pan the board and
|
|
185
|
+
panel together to reveal the controls. Expanded view has the same
|
|
186
|
+
Parameters control. The phone viewer currently renders defaults without a
|
|
187
|
+
parameter editor. Inspector's existing Tweaks tab still means CSS overrides.
|
|
188
|
+
|
|
189
|
+
Put one JSON declaration in the HTML, before any JS that reads its values:
|
|
190
|
+
|
|
191
|
+
\`\`\`html
|
|
192
|
+
<script type="application/json" data-ryugi-tweaks>
|
|
193
|
+
{
|
|
194
|
+
"controls": {
|
|
195
|
+
"accent": {
|
|
196
|
+
"type": "color",
|
|
197
|
+
"label": "Accent",
|
|
198
|
+
"default": "#b45309",
|
|
199
|
+
"options": ["#b45309", "#355ecb", "#24775a"],
|
|
200
|
+
"section": "Appearance"
|
|
201
|
+
},
|
|
202
|
+
"density": {
|
|
203
|
+
"type": "enum",
|
|
204
|
+
"label": "Density",
|
|
205
|
+
"default": "comfortable",
|
|
206
|
+
"options": [
|
|
207
|
+
{ "value": "comfortable", "label": "Comfortable" },
|
|
208
|
+
{ "value": "compact", "label": "Compact" }
|
|
209
|
+
],
|
|
210
|
+
"section": "Appearance"
|
|
211
|
+
},
|
|
212
|
+
"count": {
|
|
213
|
+
"type": "range",
|
|
214
|
+
"label": "Item count",
|
|
215
|
+
"default": 2,
|
|
216
|
+
"min": 0,
|
|
217
|
+
"max": 4,
|
|
218
|
+
"step": 1,
|
|
219
|
+
"section": "Preview data"
|
|
220
|
+
},
|
|
221
|
+
"showLoops": {
|
|
222
|
+
"type": "boolean",
|
|
223
|
+
"label": "Show loops",
|
|
224
|
+
"default": true,
|
|
225
|
+
"section": "Preview data"
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
"version": 1
|
|
229
|
+
}
|
|
230
|
+
</script>
|
|
231
|
+
\`\`\`
|
|
232
|
+
|
|
233
|
+
Every control needs \`type\` and \`default\`. \`label\` defaults to its key;
|
|
234
|
+
\`section\` groups related controls. Use stable keys starting with a letter,
|
|
235
|
+
then letters, digits, underscores or hyphens (at most 64 characters). Keys
|
|
236
|
+
must be unique ignoring case because HTML attribute names ignore case.
|
|
237
|
+
|
|
238
|
+
| Type | Values and extra fields |
|
|
239
|
+
| --------- | ----------------------------------------------------------------- |
|
|
240
|
+
| \`color\` | Six-digit hex; optional \`options\` list supplies swatches |
|
|
241
|
+
| \`range\` | Number; requires \`min\` and \`max\`; \`step\` defaults to 1 |
|
|
242
|
+
| \`number\` | Finite number; optional \`min\`, \`max\`, \`step\` |
|
|
243
|
+
| \`boolean\` | \`true\` or \`false\` |
|
|
244
|
+
| \`enum\` | String; \`options\` is a list of strings or \`{value,label}\` objects |
|
|
245
|
+
| \`text\` | String, at most 512 characters |
|
|
246
|
+
|
|
247
|
+
Defaults and updates must match their type, bounds, step and options.
|
|
248
|
+
There are at most 32 controls and 32 choices per control. Malformed JSON,
|
|
249
|
+
duplicate declarations or invalid defaults show an error in Parameters.
|
|
250
|
+
|
|
251
|
+
### Consume values with normal CSS and JS
|
|
252
|
+
|
|
253
|
+
Each parameter sets \`--tweak-<key>\` and \`data-tweak-<key>\` on \`<html>\`.
|
|
254
|
+
Numbers stay unitless: use \`calc(var(--tweak-radius, 12) * 1px)\` for a length.
|
|
255
|
+
|
|
256
|
+
\`\`\`css
|
|
257
|
+
button {
|
|
258
|
+
background: var(--tweak-accent, #b45309);
|
|
259
|
+
}
|
|
260
|
+
html[data-tweak-density='compact'] article {
|
|
261
|
+
padding: 10px;
|
|
262
|
+
}
|
|
263
|
+
\`\`\`
|
|
264
|
+
|
|
265
|
+
\`window.ryugiTweaks\` reads a snapshot of the current typed values. Defaults
|
|
266
|
+
are available when the declaration precedes your logic. Listen on \`document\`
|
|
267
|
+
for \`ryugi-tweaks\`; \`event.detail\` contains the complete updated values:
|
|
268
|
+
|
|
269
|
+
\`\`\`js
|
|
270
|
+
function render() {
|
|
271
|
+
const { count, showLoops } = window.ryugiTweaks;
|
|
272
|
+
cards.forEach((card, index) => {
|
|
273
|
+
card.hidden = index >= count;
|
|
274
|
+
});
|
|
275
|
+
loopsButton.hidden = !showLoops;
|
|
276
|
+
}
|
|
277
|
+
document.addEventListener('ryugi-tweaks', render);
|
|
278
|
+
render();
|
|
279
|
+
\`\`\`
|
|
280
|
+
|
|
281
|
+
Keep ordinary copy literal and editable; expose text controls only for real
|
|
282
|
+
cross-cutting parameters or when your human partner asks for editable copy.
|
|
283
|
+
|
|
284
|
+
### Parameter lifetime
|
|
285
|
+
|
|
286
|
+
- Changing a control or Reset updates the running frame through CSS and the
|
|
287
|
+
JS event, without reloading it. Unrelated application state stays intact.
|
|
288
|
+
- Replay, source edits and canvas-page switches retain valid overrides in
|
|
289
|
+
this viewer session. Untouched defaults follow new author defaults;
|
|
290
|
+
removed or newly invalid overrides fall back to the new defaults.
|
|
291
|
+
- Canvas and expanded instances share a board's parameter values. Other
|
|
292
|
+
boards keep their own values.
|
|
293
|
+
- Refreshing the whole viewer starts with defaults. Reset affects declared
|
|
294
|
+
parameters only. Nothing writes to HTML or publishes these preview values.
|
|
295
|
+
|
|
296
|
+
Before calling a parameterized board working, test its host Parameters
|
|
297
|
+
control, each exposed value, Reset, Replay and expanded view. Check that
|
|
298
|
+
changing appearance does not silently discard an in-progress interaction.
|
|
299
|
+
`;var ln='# Document writing\n\nWrite `doc.xml` under the returned artifact directory; put assets in `assets/`. Re-read immediately before each edit: the human and server edit this file too. Patch intended blocks, preserve existing IDs and human text; new blocks omit IDs and receive them from the server. Never edit `comments.json` or `.state/`. The server normalizes aliases and indentation after saving. Finish with `check`; pending merging or browser work means check again, not success.\n\nUse a closed `<doc>`. Choose blocks for the reader: diagrams show relationships, charts compare numbers, tables map exact attributes, prose explains reasons. A first draft can contain `<pending intent="What remains to investigate"/>`; fill every pending before claiming completion. Diagrams use native mermaid/excalidraw, never pictures of text or box drawing in code blocks.\n\nComplete block and inline vocabulary:\n\n- `h1`\u2013`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; `excalidraw`: relative `.excalidraw` asset path. `math`: inline LaTeX, `display="block"` for a block.\n- `img src="assets/image.png" alt="\u2026" caption="\u2026" width="640"`: real images.\n- `alert type="note|tip|important|warning|caution"`: block children. `details summary="\u2026" open="true"`: collapsed depth; omit open for collapsed. `steps` contains `step title="\u2026"` 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}]`.\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="\u2026"`, inline `ask`/`option` and `ref` (below). 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 html="slug">label</ref>`, `<ref artboard="slug" group="q1"/>` (or board), `<ref whiteboard="slug" frame="f1"/>` (or page). Exactly one kind, at most one allowed subtarget, lowercase slug. Optional plain text label; server adds `to` when resolved, preserve it. Missing targets 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\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';var un='# HTML writing\n\nWrite one complete `index.html` with a descriptive `<title>`, inline or relative styles/scripts/images. The page reloads on edits. Native HTML/CSS/JavaScript works; use labelled controls and visible results. Assets stay inside this artifact directory; CDN fonts/scripts work, absolute local paths do not. The iframe is sandboxed: localStorage/sessionStorage/cookies throw; keep state in DOM/variables. Popups, forms, downloads and clipboard work.\n\n```html\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>Retry explorer</title>\n </head>\n <body>\n <label>Attempts <input id="attempts" type="range" min="1" max="5" value="3" /></label>\n <output id="result"></output>\n <script>\n const input = document.getElementById(\'attempts\');\n const render = () =>\n (document.getElementById(\'result\').textContent = input.value + \' attempts\');\n input.addEventListener(\'input\', render);\n render();\n </script>\n </body>\n</html>\n```\n\nStable control IDs preserve human input, checks, details and scroll across rewrites. Restoration fires input/change: render from those events. Script-only state resets. Use one surface for one investigation; comparison across independent screens belongs on an artboard. Re-read files before editing; never edit comments or `.state/`.\n\nBundled UI elements require no imports. Use native HTML/CSS for layout. `ryugi-icon name="message-square" size="18"` provides Lucide kebab-case icons (stroke-width defaults 2, color currentColor); label the button, icons are decorative. Unknown names become runtime warnings. For JS-only icons add `<meta name="ryugi-icons" content="1">` and await customElements.whenDefined(\'ryugi-icon\'). Preview glyphs map to the app\'s existing business icons when implementing the design.\n\nRun Check after edits. It distinguishes current static evidence from browser runtime. A closed/unloaded tab means runtime pending; open the returned URL and check again. Uncaught exceptions, rejected promises and missing relative assets are warnings; no browser run is not proof that a page works.\n\n# UI components\n\nHTML artifacts can use a small set of Lobe UI components through Web\nComponents. The artifacts server loads the runtime automatically when the page\ncontains a `<ryugi-\u2026>` 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\u2026</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';var dn=`# Verify report writing
|
|
300
|
+
|
|
301
|
+
Write \`report.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.
|
|
302
|
+
|
|
303
|
+
\`\`\`xml
|
|
304
|
+
<report title="Delivery survives reconnect">
|
|
305
|
+
<p>Verified against local build.</p>
|
|
306
|
+
<claim id="delivery" judge="agent" from="local build @ COMMIT" capturedAt="2026-11-13T10:00:00Z">
|
|
307
|
+
<title>Three attempts preserve the delivery</title>
|
|
308
|
+
<output src="evidence/delivery.txt"/>
|
|
309
|
+
</claim>
|
|
310
|
+
<gap id="production"><title>Production run</title><why>No production credentials</why><needs>A test key</needs></gap>
|
|
311
|
+
</report>
|
|
312
|
+
\`\`\`
|
|
313
|
+
|
|
314
|
+
Required report title; optional one introductory p first; only claim/gap/ref after it, no top-level headings. 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, never retype or summarize. \`output src="evidence/\u2026"\` displays it; no HTML output files. Over 200,000 characters is explicitly truncated. Claim notes may use p/ul/ol/codeblock/img/alert/details and inline marks.
|
|
315
|
+
|
|
316
|
+
judge="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 rejected agent claim remains human-owned until the human passes it, even after new evidence.
|
|
317
|
+
|
|
318
|
+
Gap needs id/title/why/needs (one specific unblock). \`<ref artboard="slug" group="v2"/>\` links a screen claim. 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.
|
|
319
|
+
`;var pn=`# Whiteboard writing
|
|
320
|
+
|
|
321
|
+
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.
|
|
322
|
+
|
|
323
|
+
\`\`\`json
|
|
324
|
+
{
|
|
325
|
+
"type": "excalidraw",
|
|
326
|
+
"version": 2,
|
|
327
|
+
"source": "ryugi",
|
|
328
|
+
"appState": { "name": "Delivery flow", "viewBackgroundColor": "#ffffff" },
|
|
329
|
+
"files": {},
|
|
330
|
+
"elements": [
|
|
331
|
+
{
|
|
332
|
+
"id": "f-flow",
|
|
333
|
+
"type": "frame",
|
|
334
|
+
"name": "Delivery",
|
|
335
|
+
"children": ["n-queue", "n-worker", "a-deliver"]
|
|
336
|
+
},
|
|
337
|
+
{
|
|
338
|
+
"id": "n-queue",
|
|
339
|
+
"type": "rectangle",
|
|
340
|
+
"x": 0,
|
|
341
|
+
"y": 0,
|
|
342
|
+
"width": 180,
|
|
343
|
+
"height": 80,
|
|
344
|
+
"label": { "text": "Queue" }
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
"id": "n-worker",
|
|
348
|
+
"type": "rectangle",
|
|
349
|
+
"x": 320,
|
|
350
|
+
"y": 0,
|
|
351
|
+
"width": 180,
|
|
352
|
+
"height": 80,
|
|
353
|
+
"label": { "text": "Worker" }
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
"id": "a-deliver",
|
|
357
|
+
"type": "arrow",
|
|
358
|
+
"x": 180,
|
|
359
|
+
"y": 40,
|
|
360
|
+
"width": 140,
|
|
361
|
+
"height": 0,
|
|
362
|
+
"start": { "id": "n-queue" },
|
|
363
|
+
"end": { "id": "n-worker" }
|
|
364
|
+
}
|
|
365
|
+
]
|
|
366
|
+
}
|
|
367
|
+
\`\`\`
|
|
368
|
+
|
|
369
|
+
Standard Excalidraw elements work. New elements may use skeleton shorthand: id/type/x/y/width/height plus label for shape/arrow text, text for free text, start/end \`{id}\` for bindings, children for frames. Browser completes/measures skeletons and writes full elements. A frame without bounds fits its children; on later edits resize existing frame bounds explicitly to fit. \`frameId\` adds an element to an existing frame; null removes it. Inter-frame arrows belong to neither frame. Arrow width/height may be negative/zero; startArrowhead:"arrow" gives two-way arrows. Sticky = rectangle with backgroundColor:"#ffec99", fillStyle:"solid", label. Images use Excalidraw files dataURLs; keep total scene under 5MB. Give appState.name a readable title distinct from slug. IDs are unique across every live page and remain stable for comments/refs.
|
|
370
|
+
|
|
371
|
+
For pages write \`{"pages":[{"id":"main","name":"Overview"},{"id":"p-detail","name":"Detail"}]}\`. main is first and undeletable; extra IDs lowercase letters/digits/hyphens, filenames pages/<id>.excalidraw. Missing page file means empty. Names/order live in pages.json; appState.name remains board title. Preserve human pages on reread. Delete with deleted:true, retain file; deleted pages are excluded from check/render/publish and their comments become orphans. Arrows cannot cross pages. Move by copying the full element including customData to the new page and tombstoning it on the old one; comments/refs follow.
|
|
372
|
+
|
|
373
|
+
Run Check after edits; skeleton_not_completed/browser_not_run needs the board open in a browser. Check covers every page; --page narrows it. Fix duplicate IDs, conflicts, missing arrow targets, overflow/overlap and clipping. \`scene --artifact whiteboard/<id>\` returns page/frame structure and render paths; inspect a current render as well as validation. Never edit comments.json or \`.state/\`; the state directory contains render.png, geometry, selection, backlinks and warnings maintained by the server.
|
|
374
|
+
`;var ii={artboard:cn,document:ln,html:un,verify:dn,whiteboard:pn};function ct(e){if(!Y.test(e))throw new w(re);return ii[e.split("/")[0]].trim()}function z(e,t){if(!Y.test(t))throw new w(re);let r=t.split("/")[0],n=mn.default.join(e,".ryugi","artifacts",t,Wt[r]);return{write:n,content:fn.default.existsSync(n)?"existing":"missing"}}function gn(e,t,r,n,o){let s=e.projectDir,i=["--artifact",t,"--project-dir",s];if(r.evidence==="preview"&&r.items.length&&r.snapshot){let l=o.findIndex(f=>f.label==="Read"),u=["status","waiting-on","kind","choice-state"].flatMap(f=>typeof e.values[f]=="string"?[`--${f}`,String(e.values[f])]:[]),d={...E(["comment","list",...i,"--section","threads","--detail","--snapshot",r.snapshot,"--limit",String(n?.returned??r.items.length),...typeof e.values.cursor=="string"?["--cursor",e.values.cursor]:[],...u,...e.values.all?["--all"]:[]],"Read"),reason:"Read the complete captured page before acting. Previews mark nothing read."};l<0?o.push(d):o.splice(l,1,d)}if(r.evidence!=="complete")return;let a=r.items.filter(l=>l.status==="open");if(a.length){let{write:l}=z(s,t);o.push({...E(["check",...i],"Check"),reason:`After editing ${l} in place. Re-read before editing; preserve human changes and existing IDs. comments.json is server-owned.`});for(let u of a)o.push({...E(["comment","reply",...i,"--thread",String(u.id),"--text","<what changed or your answer>"],`Reply (${u.id})`),reason:"Replace the message argument after applying this request."}),u.anchor?.verdict!=="reject"&&o.push({...E(["comment","resolve",...i,"--thread",String(u.id)],`Resolve (${u.id})`),reason:"Only once this thread is settled."})}let c=o.findIndex(l=>l.label==="Acknowledge");if(c>=0){let[l]=o.splice(c,1);o.push({...l,reason:"After using every delivered message. This resolves nothing and leaves later replies unread."})}}var F=e=>typeof e=="string"?e:"",ut=e=>e.replaceAll(/\s*\n\s*/g," / ").trim(),dt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,pt=e=>e[0].toUpperCase()+e.slice(1),Ht=(e,t=[])=>Object.entries(e??{}).filter(([r,n])=>r!=="waitingOnAgent"&&!t.includes(r)&&typeof n=="number"&&n>0).map(([r,n])=>`${n} ${r}`).join(", "),hn=e=>e?` (${e})`:"",ai={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 ft(e,t,r,n=!1){let o=r?.total??t.items.length,s=t.summary;if(n){let u=`${o} matched`;return{head:u,full:`${u}${hn(Ht(s))}`,count:o}}if(e==="threads"){let u=Number(s?.waitingOnAgent??0),d=o?`${o} unread${u?`, ${u} waiting on you`:""}`:"nothing unread",f=Number(s?.resolved??0);return{head:d,full:`${d}${f?` (${f} resolved)`:""}`,count:o}}let i=ai[e],a=o?`${o} ${i.word}`:i.none,c=e==="groups"?Object.entries(s??{}).reduce((u,[d,f])=>d==="waitingOnAgent"||typeof f!="number"?u:u+f,0)-o:0,l=e==="groups"?c>0?dt(c,"other"):"":Ht(s,i.listed);return{head:a,full:`${a}${hn(l)}`,count:o}}function ci(e){if(!e||typeof e!="object")return"";let t=e;if(typeof t.blockId=="string"){let o=Array.isArray(t.blockIds)&&t.blockIds.length>1?t.blockIds:[t.blockId];return`${o.length>1?"blocks":"block"} ${o.join(", ")}${F(t.quote)?` "${ut(F(t.quote))}"`:""}`}if(Array.isArray(t.elements)&&t.elements.length)return`element ${t.elements.join(", ")}`;let r=F(t.page);if(typeof t.board=="string")return`${r?`page ${r} `:""}board ${t.board}`;let n=typeof t.x=="number"&&typeof t.y=="number"?` ${Math.round(t.x)},${Math.round(t.y)}`:"";return`page ${r||"main"}${n}`}var lt={key:"id",positional:!0,required:!0},yn={key:"line",positional:!0,required:!0},bn={key:"tail",positional:!0,required:!0},wn=e=>e.choice?` \u2192 ${e.choice}${e.byRecommendation?" (recommended)":""}`:"";function li(e,t){return e==="asks"?{columns:[lt,yn,{key:"note",label:"note"},{key:"staleChoice",label:"stale choice"}],rows:t.map(r=>({...r,line:`${F(r.state)}${r.choice?wn(r):F(r.text)?` \xB7 "${ut(F(r.text))}"`:"choice"in r||"text"in r?" \xB7 no answer":""}`,note:F(r.note)&&`"${ut(F(r.note))}"`}))}:e==="threads"?{columns:[lt,{key:"status",positional:!0,required:!0},{key:"waiting",positional:!0},{key:"where",positional:!0},{key:"stale",label:"stale"},{key:"orphan",label:"orphan"},{key:"draft",label:"draft"},{key:"messageCount",positional:!0},{key:"preview",positional:!0}],rows:t.map(r=>({...vn(r),messageCount:typeof r.messageCount=="number"&&r.messageCount?dt(r.messageCount,"message"):"",preview:F(r.preview)&&`"${ut(F(r.preview))}"`}))}:e==="groups"?{columns:[lt,{key:"kind",positional:!0,required:!0},yn,{key:"origin",positional:!0},{key:"evidenceUpdated",label:"evidence updated"},{key:"rejects",positional:!0},{key:"threadCount",positional:!0},bn],rows:t.map(r=>({...r,line:r.kind==="verify"?F(r.verdict):`${r.round?`round ${r.round}`:""}${r.choice?wn(r):" \xB7 no pick"}`.replace(/^ · /,""),origin:typeof r.from=="string"&&r.from?`from ${r.from}`:"",rejects:typeof r.rejectThreads=="number"&&r.rejectThreads?dt(r.rejectThreads,"reject thread"):"",threadCount:typeof r.threads=="number"&&r.threads?dt(r.threads,"thread"):"",tail:F(r.title)}))}:{columns:[lt,{key:"state",positional:!0,required:!0},{key:"groupList",positional:!0},bn],rows:t.map(r=>({...r,groupList:Array.isArray(r.groups)&&r.groups.length?`groups ${r.groups.join(", ")}`:"",tail:F(r.title)}))}}function vn(e){return{id:e.id,status:e.status,waiting:e.waitingOn?`waiting on ${e.waitingOn}`:"",where:ci(e.anchor&&typeof e.anchor=="object"&&typeof e.page=="string"?{page:e.page,...e.anchor}:e.anchor),stale:e.stale===!0,orphan:e.orphan===!0,draft:e.draft===!0}}var Me=(e,t)=>({label:e,binding:{key:e,value:t},positional:!0});function Bt(e,t="items"){return{kind:"messages",key:t,groups:e.map(r=>{let n=vn(r);return{facts:[Me("id",n.id),Me("status",n.status),Me("waiting",n.waiting),Me("where",n.where),{label:"stale",binding:{key:"stale",value:n.stale}},{label:"orphan",binding:{key:"orphan",value:n.orphan}},{label:"draft",binding:{key:"draft",value:n.draft}}],messages:(Array.isArray(r.messages)?r.messages:[]).map(o=>({facts:[Me("message",[o.id,`${F(o.name)||F(o.author)}${o.author==="agent"?" (agent)":""}`,F(o.at)&&Te(F(o.at)),o.deleted?"(deleted)":"",F(o.editedAt)&&`edited ${Te(F(o.editedAt))}`].filter(Boolean).join(" "))],text:typeof o.text=="string"?o.text:""}))}})}}function kn(e,t,r,n,o){let s=ft(e,t,r,o),i={key:n?e:"items",title:pt(e),summary:s.full};return e==="threads"&&t.evidence==="complete"?{...Bt(t.items),...i,...n?{page:r}:{}}:{kind:"records",...li(e,t.items),...i,...n?{page:r}:{}}}var ui=["threads","asks","groups","rounds"];function di(e,t){let r=e.summary??{},n=s=>t.find(i=>i.label===pt(s)),o=ui.filter(s=>n(s));return{heading:"Comment list",status:"",subject:e.artifact,facts:[],sections:o.map(s=>{let i=r[s],a=s==="threads"?ft("threads",{items:[],summary:{waitingOnAgent:r.waitingOnAgent}},{total:Number(i??0)}).head:Ht(i)||"none";return{kind:"records",key:s,title:pt(s),summary:`${a} \xB7 ${Ce(n(s))}`,columns:[],rows:[]}}),actions:t.filter(s=>!o.some(i=>pt(i)===s.label))}}function Sn({data:e,actions:t,coverage:r},n="Comment list",o=!1){if(e.section==="summary")return di(e,t);let s=r.page;return{heading:n,status:"",subject:e.artifact,summary:ft(e.section,e,s,o).head,facts:[],sections:[kn(e.section,e,s,!1,o)]}}function Cn({data:e},t=!1){let r=Object.entries(e.sections),n=r.map(([o,s])=>ft(o,s,s.page,t)).filter(o=>o.count>0).map(o=>o.head);return{heading:"Comment list",status:"",subject:e.artifact,summary:n.join(" \xB7 ")||"nothing new",facts:[],sections:r.map(([o,s])=>kn(o,s,s.page,!0,t))}}var j=(e,t)=>typeof e.values[t]=="string"?e.values[t]:void 0,Jt=["brief","table","json","jsonl","raw"];function Rn(e,t=!1){let r=j(e,"artifact");if(!r||!(t?/^document\/[a-z0-9][a-z0-9-]*$/:/^(document|artboard|whiteboard)\/[a-z0-9][a-z0-9-]*$/).test(r))throw new m({code:"E_ARGUMENT_INVALID",message:t?"--artifact must be document/<id>.":"--artifact must be document/<id>, artboard/<id> or whiteboard/<id>."});return r}function Yt(e){let t=j(e,"limit");if(t!==void 0&&(!/^\d+$/.test(t)||Number(t)<1||Number(t)>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});return{...t===void 0?{}:{limit:Number(t)},...j(e,"cursor")?{cursor:j(e,"cursor")}:{},...j(e,"snapshot")?{snapshot:j(e,"snapshot")}:{},all:!!e.values.all,detail:!!e.values.detail||!!e.values.save,...j(e,"fields")?{fields:j(e,"fields").split(",").map(r=>r.trim())}:{}}}async function mt(e,t,r,n,o){let s=await M(e.projectDir).call("POST",`/api/agent/v1/${r}/${n}`,{...o,agent:ve(process.env)??"Agent"},t.signal);if(t.payloads.raw=s.raw,s.json.schema!=="ryugi.review/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported review response."});if(s.status<200||s.status>=300)throw new m({code:typeof s.json.code=="string"?s.json.code:"E_REVIEW_FAILED",message:s.json.error||`HTTP ${s.status}`,httpStatus:s.status});return s.json}function xn(e,t){return["--artifact",t,"--project-dir",e.projectDir]}function An(e,t,r){let n=new Set([...Object.keys(J),"artifact","receipt"]),o=Object.keys(e.values).find(i=>!n.has(i));if(o)throw new m({code:"E_ARGUMENT_INVALID",message:`--${o} is not supported for ack.`});let s=j(e,"receipt");if(!s)throw new m({code:"E_ARGUMENT_INVALID",message:"ack requires --receipt."});return I({id:r==="review"?"comment.ack":"changes.ack",mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:i=>i.receipt},async run(i,a){M(e.projectDir);let c=a.effects.begin(r==="review"?"comment.ack":"changes.ack",s),l=await mt(e,a,t,r,{op:"ack",receipt:s});if(!["acknowledged","unchanged"].includes(l.status))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported acknowledgement result; inspect unread state before retrying."});return a.effects.set(c,l.status==="unchanged"?"none":"confirmed",{artifact:t}),x({artifact:t,receipt:s,status:l.status})},present:fi(r==="review"?"comment":"changes")},e)}function pi(e,t,r){if(r!=="list")throw new m({code:"E_ARGUMENT_INVALID",message:"--sections applies to comment list."});let n=Yt(e),o=j(e,"sections")?.trim(),s=o==="all"?Dt(t):(o??"").split(",").map(c=>c.trim()),i=Object.fromEntries(["status","waiting-on","kind","choice-state"].map(c=>[c,j(e,c)])),a=Pr({...n,sections:s,section:j(e,"section"),thread:j(e,"thread"),filters:i},t);if(a)throw new m({code:"E_ARGUMENT_INVALID",message:a});return I({id:"comment.list",mode:"finite",output:{formats:Jt,detail:!0},async run(c,l){let u=await mt(e,l,t,"review",{op:"list",sections:s,...n});for(let d of s){let f=u.sections?.[d];if(!f||!Array.isArray(f.items)||typeof f.snapshot!="string"||!f.page||typeof f.page.scope!="string"||typeof f.page.hasMore!="boolean"||!Number.isInteger(f.page.returned)||!(f.page.total===null||Number.isInteger(f.page.total)))throw new m({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(f.page.returned!==f.items.length||f.page.returned<0||f.page.total!==null&&f.page.total<f.page.returned||f.page.snapshot!==f.snapshot||!(f.page.nextCursor===null||typeof f.page.nextCursor=="string")||f.page.hasMore!==(typeof f.page.nextCursor=="string"&&f.page.nextCursor.length>0))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned inconsistent combined review coverage."})}return gi(e,t,s,u,n)},present:c=>Cn(c,n.all)},e)}var fi=e=>({data:t})=>({heading:e==="comment"?"Comment ack":"Changes ack",status:t.status,subject:t.artifact,facts:[],sections:[]});function mi({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?[b("File",A(e,"saved"),!0)]:[],sections:e.empty||e.saved?[]:e.diff===void 0?[{kind:"records",key:"blocks",rows:e.blocks.map(r=>({id:r.id,size:[r.additions&&`+${r.additions}`,r.deletions&&`-${r.deletions}`].filter(Boolean).join(" "),preview:r.preview&&`"${r.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 gi(e,t,r,n,o){let s={},i=[],a=[];for(let c of r){let l=n.sections[c],u=En(e,t,c,l,o),{artifact:d,section:f,...k}=u.data;s[c]={...k,page:l.page},i.push(...u.actions.map(S=>S.label==="More"?{...S,label:`More (${c})`}:S)),k.evidence==="preview"&&c==="threads"&&a.push({path:"data.sections.threads.items.messages",reason:"summary"})}return x({artifact:t,sections:s},void 0,{actions:i,coverage:{omitted:a}})}function En(e,t,r,n,o,s){let i=n.page,a={artifact:t,section:r??"summary",items:n.items??[],evidence:o.fields?"projected":r&&r!=="threads"?"state":o.detail||s?"complete":"preview",...n.snapshot?{snapshot:n.snapshot}:{},...n.receipt?{receipt:n.receipt}:{},...n.summary?{summary:n.summary}:{}},c=[],l=xn(e,t);if(n.receipt&&c.push(E(["comment","ack",...l,"--receipt",n.receipt],"Acknowledge")),i?.nextCursor&&c.push(E(["comment","list",...l,"--section",r,...o.detail?["--detail"]:[],...Object.entries({status:j(e,"status"),"waiting-on":j(e,"waiting-on"),kind:j(e,"kind"),"choice-state":j(e,"choice-state"),fields:j(e,"fields"),limit:j(e,"limit")}).flatMap(([u,d])=>d?[`--${u}`,d]:[]),...o.all?["--all"]:[],"--cursor",i.nextCursor],"More")),r)r==="threads"&&a.evidence==="preview"&&a.items[0]&&c.push(E(["comment","read",...l,"--thread",String(a.items[0].id),"--snapshot",n.snapshot,"--detail"],"Read"));else{c.push(E(["comment","list",...l,"--sections","all","--detail",...o.all?["--all"]:[],...j(e,"limit")?["--limit",j(e,"limit")]:[]],"Review all"));let u=t.startsWith("document/")?["threads","asks"]:t.startsWith("artboard/")?["threads","groups","rounds"]:["threads"];c.unshift(...u.map(d=>E(["comment","list",...l,"--section",d,...d==="asks"?["--detail"]:[]],d[0].toUpperCase()+d.slice(1))))}if(r==="asks")for(let u of a.items.filter(d=>d.state==="submitted"))c.push({...E(["comment","note",...l,"--ask",String(u.id),"--text","<what changed>"],`Settle (${u.id})`),reason:"Apply this submitted human answer, then replace the note argument with what changed. Never invent an answer."});return r==="groups"&&a.items.some(u=>u.kind==="choose"&&u.choice||u.verdict==="reject")&&c.unshift({...E(["comment","list",...l,"--section","threads","--detail"],"Next"),reason:"read the threads on these groups too, then act on each"}),r==="threads"&&gn(e,t,a,i,c),x(a,void 0,{actions:c,coverage:{...i?{page:i}:{},...a.evidence==="preview"&&r==="threads"?{omitted:[{path:"data.items.messages",reason:"summary"}]}:{}}})}function In(e){let t=Rn(e),r=e.positionals[0];if(r==="ack")return An(e,t,"review");if(e.values.sections!==void 0)return pi(e,t,r);if(r!=="list"&&r!=="read")throw new m({code:"E_ARGUMENT_INVALID",message:"Expected list, read or ack."});let n=Yt(e),o=r==="read"?"threads":j(e,"section"),s=j(e,"thread");if(r==="read"&&!s)throw new m({code:"E_ARGUMENT_INVALID",message:"read requires --thread."});if(o&&!["threads","asks","groups","rounds"].includes(o))throw new m({code:"E_ARGUMENT_INVALID",message:"Unknown review section."});if(!o&&(n.detail||n.cursor||n.fields||["status","waiting-on","kind","choice-state"].some(c=>e.values[c])))throw new m({code:"E_ARGUMENT_INVALID",message:"Select --section before detail, fields, cursor or filters."});let i=Object.fromEntries([["status",j(e,"status")],["waitingOn",j(e,"waiting-on")],["kind",j(e,"kind")],["choiceState",j(e,"choice-state")]].filter(([,c])=>c!==void 0)),a=Nr({...n,section:o,filters:i});if(a)throw new m({code:"E_ARGUMENT_INVALID",message:a});return I({id:`comment.${r}`,mode:"finite",output:{detail:!0,formats:Jt,collection:"items",requiredFields:o?$r[o]:[],fields:o?[...Je[o]]:[]},async run(c,l){let u=await mt(e,l,t,"review",{op:r,...n,...o?{section:o}:{},...s?{thread:s,detail:!0}:{},...Object.keys(i).length?{filters:i}:{}});return En(e,t,o,u,n,s)},present:c=>Sn(c,r==="read"?"Comment read":"Comment list",n.all||!!j(e,"status")&&!(o==="asks"&&j(e,"status")==="submitted")||!!j(e,"choice-state"))},e)}function On(e){let t=Rn(e,!0),r=e.positionals[0];if(r==="ack")return An(e,t,"changes");if(r)throw new m({code:"E_ARGUMENT_INVALID",message:"Expected changes or changes ack."});let n=Yt(e),o=j(e,"save");if(o!==void 0&&!o.trim())throw new m({code:"E_ARGUMENT_INVALID",message:"--save requires a nonempty file path."});if(n.detail&&(n.fields||n.cursor||n.limit!==void 0))throw new m({code:"E_OPTION_CONFLICT",message:"A complete diff cannot use --limit, --cursor or --fields."});return I({id:"changes",mode:"finite",output:{detail:!0,formats:o?["brief","json","jsonl"]:Jt,fields:["artifact","snapshot","blocks","diff","empty"]},async run(s,i){let a=await mt(e,i,t,"changes",{op:"read",...n}),{page:c,schema:l,...u}=a,d=u;if(o&&d.empty!==!0&&typeof d.diff!="string")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server did not return complete diff evidence; no export was written."});if(o){let S=Le(o,d.diff??"",i.effects);d.saved=S.file,d.bytes=S.bytes,delete d.diff}let f=xn(e,t),k=d.receipt?[E(["changes","ack",...f,"--receipt",d.receipt],"Acknowledge")]:d.empty?[]:[E(["changes",...f,"--snapshot",d.snapshot,...n.all?["--all"]:[],"--detail"],"Read")];return c?.nextCursor&&k.push(E(["changes",...f,...n.all?["--all"]:[],...Object.entries({fields:j(e,"fields"),limit:j(e,"limit")}).flatMap(([S,O])=>O?[`--${S}`,O]:[]),"--cursor",c.nextCursor],"More")),x(d,void 0,{actions:k,coverage:{...c?{page:c}:{},...!n.detail&&!d.empty?{omitted:[{path:"data.diff",reason:"summary"}]}:{}}})},present:mi},e)}var jn={semantic:On,positionals:1,name:"changes",summary:"Show what your human partner changed in a document (needs a running server)",usage:["--artifact document/<id> [--all] [--detail | --save <file>]","ack --artifact document/<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\u2013100, 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>",help:"The document"},all:{type:"boolean",help:"Show historical changes without a receipt"}}};function Tn(e){let t=n=>!!n&&typeof n=="object"&&!Array.isArray(n),r=n=>Array.isArray(n)&&n.every(o=>typeof o=="string");if(!t(e)||!r(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&&!r(e.pending)||e.provenance!==void 0&&!r(e.provenance)||e.modules!==void 0&&!r(e.modules)||e.checkedAt!==void 0&&typeof e.checkedAt!="string")return!1;for(let n of["ran","merging"])if(e[n]!==void 0&&typeof e[n]!="boolean")return!1;return!(e.dynamic!==void 0&&(!t(e.dynamic)||Object.values(e.dynamic).some(n=>!t(n)||n.ran!==void 0&&typeof n.ran!="boolean"))||e.recordings!==void 0&&(!t(e.recordings)||Object.values(e.recordings).some(n=>!t(n)||["status","warning"].some(o=>n[o]!==void 0&&typeof n[o]!="string"))))}var hi=new Set(["W_PROVENANCE","W_MODULES"]);function _n(e,t){let r=(t.warnings??[]).map(f=>({code:"W_ARTIFACT",severity:"warning",message:f}));for(let f of t.provenance??[])r.push({code:"W_PROVENANCE",severity:"warning",message:f});for(let f of t.modules??[])r.push({code:"W_MODULES",severity:"warning",message:f});let n=[...t.pending??[]];t.merging&&n.push("merging");for(let[f,k]of Object.entries(t.recordings??{}))k.warning&&r.push({code:"W_RECORDING",severity:"warning",message:k.warning,location:f}),k.status==="processing"&&n.push(`recording:${f}`);let o=Object.entries(t.dynamic??{}),s=t.evidence?.required??(e.startsWith("html/")||e.startsWith("artboard/")||o.length>0),i=t.evidence?.observed===!1||t.ran===!1||o.some(([,f])=>f.ran===!1);s&&i&&n.push("browser_not_run");let a=t.evidence?.observed??(t.ran===!0||o.length>0&&o.every(([,f])=>f.ran===!0)),c=s?i?"not_run":a&&t.evidence?.fresh===!0?"clean":"unknown":"not_required",l=r.filter(f=>!hi.has(f.code)),u=l.length?"issues":n.length?"pending":c==="unknown"||t.evidence?.fresh===!1?"unknown":"clean",d={artifact:e,status:u,static:l.length?"issues":"clean",runtime:c,issues:r,pending:n,evidence:t};return x(d,u==="issues"?{kind:"validation_failed"}:u==="pending"||u==="unknown"?{kind:"pending",reasons:n.length?n:["evidence_unknown"]}:{kind:"succeeded"})}async function yi(e,t,r){if(!e.artifact||!Y.test(e.artifact))throw new w(re);let o=await M(e.projectDir).call("POST",`/api/agent/${e.artifact}/check${e.page?`?page=${encodeURIComponent(e.page)}`:""}`,void 0,t);r?.(o.raw);let{status:s,json:i}=o;if(s<200||s>=300)throw new w(i?.error||`HTTP ${s}`);if(!Tn(i))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned invalid check evidence; validation could not be established."});return{...o,json:i}}var $n={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=>I({id:"check",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","raw","quiet"],fields:["artifact","file","status","static","runtime","issues","pending","evidence"],scalar:t=>t.status},async run(t,r){let n=await yi({projectDir:e.projectDir,artifact:e.values.artifact,page:e.values.page},r.signal,s=>{r.payloads.raw=s});r.payloads.raw=n.raw;let o=_n(e.values.artifact,n.json);return o.data.file=z(e.projectDir,o.data.artifact).write,o.actions=[E(["check","--artifact",o.data.artifact,...e.values.page?["--page",e.values.page]:[],"--project-dir",e.projectDir,"--detail"])],o},present:bi},e)};function bi({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?[b("File",{key:"file",value:e.file})]:[],...e.runtime==="not_run"||e.runtime==="unknown"?[b("Browser",{key:"runtime",value:e.runtime.replaceAll("_"," ")})]:[],...e.pending.length?[b("Pending",{key:"pending",value:e.pending.join(", ")})]:[]],sections:[{kind:"diagnostics",key:"issues",items:e.issues,preview:3}]}}var Fn=C(require("node:fs"),1);function Pn(e,t,r,n){if(e==="submit")return{op:"submit",submit:!t.withdraw};if(!t.ask)throw new w(`comment ${e} needs --ask <questionId>`);if(e==="note")return{op:"note",ask:t.ask,text:r()};let o=n?.trim();if(!t.clear&&!t.choice&&!o)throw new w("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:o??null}}var Nn={reject:0,pending:1,pass:2,checked:3},wi={reject:"rejected",pending:"pending",pass:"passed",checked:"checked by agent"},K=(e,t)=>e?`${e} ${t}`:"",gt=e=>e.filter(Boolean).join(" \xB7 "),X=(e,t=!1)=>({key:e,positional:!0,required:t});function vi({data:e}){let{tally:t}=e,r=s=>e.claims.filter(i=>i.state===s).length,n=e.threads.filter(s=>s.status==="open"),o=gt([K(t.needYou,"on your human partner"),K(t.notVerified,"not verified"),K(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:o?[b("Waiting",{key:"waiting",value:o})]:[],sections:[{kind:"records",key:"claims",title:"Claims",summary:gt([K(r("reject"),"rejected"),K(r("pending"),"pending"),K(r("pass"),"passed"),K(r("checked"),"checked by agent")]),columns:[X("id",!0),X("line",!0),X("rejects"),{key:"evidenceUpdated",label:"evidence updated"},X("origin"),X("tail")],rows:[...e.claims].sort((s,i)=>Nn[s.state]-Nn[i.state]).map(s=>({...s,line:wi[s.state],rejects:s.state==="reject"&&s.rejectThreads?`${s.rejectThreads} reject thread${s.rejectThreads===1?"":"s"}`:"",evidenceUpdated:s.evidenceUpdated||void 0,origin:s.from?`from ${s.from}`:"",tail:s.title}))},...e.rows.length?[{kind:"records",key:"rows",title:"Artboard rows",summary:String(e.rows.length),columns:[X("id",!0),X("state",!0)],rows:e.rows.map(s=>({...s,id:`${s.artboard}/${s.group}`}))}]:[],...e.gaps.length?[{kind:"records",key:"gaps",title:"Not verified",summary:gt([K(e.gaps.filter(s=>!s.waived).length,"open"),K(e.gaps.filter(s=>s.waived).length,"waived")]),columns:[X("id",!0),X("line",!0),X("tail")],rows:e.gaps.map(s=>({...s,line:s.waived?"waived":"not verified",tail:s.title}))}]:[],...e.threads.length?[{kind:"messages",key:"threads",title:"Threads",summary:gt([K(n.length,"open"),K(e.threads.length-n.length,"resolved")]),groups:e.threads.map(s=>({facts:[{...b("Thread",{key:"id",value:s.id},!0),positional:!0},b("On",{key:"anchor",value:s.anchor.claim?`claim ${s.anchor.claim}`:`gap ${s.anchor.gap}`},!0),b("Verdict",{key:"verdict",value:s.anchor.verdict??(s.anchor.waive?"waived":"")}),b("Status",{key:"status",value:s.status},!0),...s.stale?[b("Stale",{key:"stale",value:!0})]:[]],messages:s.messages.map(i=>({facts:[{...b("Author",{key:"author",value:i.author},!0),positional:!0},b("At",{key:"at",value:i.at})],text:i.text}))}))}]:[]]}}function Dn(e){let t=e.values.artifact,r=z(e.projectDir,t);return I({id:"comment.list",mode:"finite",output:{detail:!0,formats:["brief","json","jsonl"],fields:["id","state","title","from"],scalar:n=>n.tally.done?"done":"open"},async run(n,o){let s=ve(process.env),i=await M(e.projectDir).call("POST",`/api/agent/${t}/comments`,{op:"list",...s?{agent:s}:{}},o.signal);if(i.status<200||i.status>=300)throw new m({code:i.status===404?"E_ARTIFACT_NOT_FOUND":"E_COMMENT_FAILED",message:i.json?.error||`HTTP ${i.status}`,httpStatus:i.status});let a=i.json,c=["--artifact",t,"--project-dir",e.projectDir],l=a.threads.filter(u=>u.status==="open");return x({...a,artifact:t,projectDir:e.projectDir},void 0,{actions:l.length?[{...E(["check",...c],"Check"),reason:`After repairing the rejected claim and updating ${r.write} with real evidence. Preserve existing IDs and human edits; a human pass closes the rejection.`},...l.map(u=>({...E(["comment","reply",...c,"--thread",u.id,"--text","<what changed and the replacement evidence>"],`Reply (${u.id})`),reason:"Reply after the repair; leave rejected claims open for the human verdict."}))]:[]})},present:vi},e)}function ki({data:e}){let t=e.threadId?`thread ${e.threadId}`:e.ask?`ask ${e.ask}`:e.group?`group ${e.group}${e.board?` \u2192 ${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?` \u2192 ${e.choice}`:""}`,facts:[...e.messageId?[b("Message",A(e,"messageId"))]:[],...e.groups?.length?[b("Groups",{key:"groups",value:e.groups.join(", ")})]:[]],sections:[]}}function Si(e){let t={action:e.positionals[0],artifact:e.values.artifact,projectDir:e.projectDir};for(let r of["ask","block","board","choice","claim","element","gap","group","page","quote","round","text","thread","x","y"])t[r]=e.values[r];for(let r of["all","clear","withdraw"])t[r]=!!e.values[r];return t}function Ln(e){let t=Si(e),r=t.action;if(t.artifact?.startsWith("verify/")&&["list","read","ack"].includes(r??"")){if(r!=="list")throw new m({code:"E_OPTION_UNSUPPORTED",message:"A verify report has no thread receipts: comment list shows every thread."});return Dn(e)}if(["list","read","ack"].includes(r??""))return In(e);if(["section","sections","limit","cursor","snapshot","receipt","status","waiting-on","kind","choice-state"].some(n=>e.values[n]!==void 0))throw new m({code:"E_OPTION_UNSUPPORTED",message:"Review query options apply only to list, read and ack."});return I({id:`comment.${r??"unknown"}`,mode:"finite",output:{formats:r==="pass"&&t.all?["brief","json","jsonl"]:["brief","json","jsonl","quiet"],scalar:n=>n.ask??n.group??n.round??n.threadId??n.artifact},async run(n,o){let s=Mn(t);M(t.projectDir);let i=o.effects.begin(`comment.${s.action}`,t.thread??t.ask??t.group??t.artifact),a=await Un(t,s,o.signal);if(a.status>=400&&a.status<500&&o.effects.set(i,"failed"),a.status<200||a.status>=300)throw new m({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 c=a.json;o.effects.confirm(i);let{action:l,request:u}=s,d={add:"added",reply:"replied",resolve:"resolved",answer:t.clear?"cleared":"answered",note:"settled",choose:t.clear?"cleared":"recorded",pass:"recorded",reject:"recorded",waive:"recorded",submit:t.withdraw?"withdrawn":"submitted"},f=l==="pass"&&[c.groups,c.claims].some(S=>Array.isArray(S)&&S.length===0);f&&o.effects.set(i,"none");let k={artifact:t.artifact,operation:l,status:f?"unchanged":d[l],by:"agent",...typeof c.threadId=="string"?{threadId:c.threadId}:{},...typeof c.messageId=="string"?{messageId:c.messageId}:{},...t.ask?{ask:t.ask}:{},...t.group?{group:t.group}:{},...Array.isArray(c.groups)?{groups:c.groups}:{},...Array.isArray(c.claims)?{groups:c.claims}:{},...t.claim?{group:t.claim}:{},...t.gap?{group:t.gap}:{},...t.round?{round:t.round}:{},...l==="choose"?{board:u.board}:{},...l==="submit"?{submitted:!t.withdraw}:{},...l==="answer"?{choice:u.choice}:{}};return x(k,void 0,{effects:o.effects.snapshot()})},present:ki},e)}var Ci=["add","reply","resolve","choose","submit","answer","note","pass","reject","waive"],Ri=/^(?:document|artboard|whiteboard|verify)\/[a-z0-9][a-z0-9-]*$/,xi=new Set(["pass","reject"]);function Ai(){if(process.stdin.isTTY)return"";try{return Fn.default.readFileSync(0,"utf8")}catch{return""}}function ae(e){let t=(e.text??Ai()).trim();if(!t)throw new w("The message is empty: pass --text <text> or pipe it on stdin");return t}function ht(e,t){if(e===void 0)return;let r=Number(e);if(!Number.isFinite(r))throw new w(`${t} must be a number`);return r}function Ei(e,t){if(t==="pass"||t==="reject"){let r=t==="pass"&&!!e.all;if(!r&&!e.claim)throw new w(t==="pass"?"comment pass on a report needs --claim <claimId>, or --all":"comment reject on a report needs --claim <claimId>");let n=t==="reject"?ae(e):e.text?.trim();return{op:"verdict",verdict:t,...r?{all:!0}:{claim:e.claim},...n?{text:n}:{}}}if(t==="waive"){if(!e.gap)throw new w("comment waive needs --gap <gapId>");return{op:"waive",gap:e.gap}}if(t==="reply"){if(!e.thread)throw new w("comment reply needs --thread <threadId>");return{op:"reply",threadId:e.thread,text:ae(e)}}throw new w(`comment ${t} does not work on verify reports: use list, pass, reject, waive or reply`)}function Ii(e,t,r){if(r==="verify")return Ei(e,t);if(t==="waive")throw new w("comment waive works on verify reports only");if(r==="document"&&(t==="submit"||t==="answer"||t==="note"))return Pn(t,e,()=>ae(e),e.text);if((t==="answer"||t==="note")&&r!=="document")throw new w(`comment ${t} works on documents only`);if((t==="choose"||t==="submit"||xi.has(t))&&r!=="artboard")throw new w(`comment ${t} works on artboards only`);if(t==="pass"||t==="reject"){let n=t==="pass"&&!!e.all;if(!n&&!e.group)throw new w(t==="pass"?"comment pass needs --group <groupId>, or --all":"comment reject needs --group <groupId>");let o=t==="reject"?ae(e):e.text?.trim();return{op:"verdict",verdict:t,...n?{all:!0}:{group:e.group},...o?{text:o}:{}}}if(t==="choose"){if(!e.group)throw new w("comment choose needs --group <groupId>");if(!e.clear&&!e.board)throw new w("comment choose needs --board <boardId>, or --clear");return{op:"choose",group:e.group,board:e.clear?null:e.board}}if(t==="submit"){if(!e.round)throw new w("comment submit needs --round <roundId>");return{op:"submit",round:e.round,submit:!e.withdraw}}if(t==="add"&&r==="artboard"){if(!e.board)throw new w("comment add on an artboard needs --board <boardId>");let n=ht(e.x,"--x"),o=ht(e.y,"--y");return{op:"add",board:e.board,...n!==void 0?{x:n}:{},...o!==void 0?{y:o}:{},text:ae(e)}}if(t==="add"&&r==="whiteboard"){let n=ht(e.x,"--x"),o=ht(e.y,"--y");if(e.element)return{op:"add",element:e.element,text:ae(e)};if(n===void 0||o===void 0)throw new w("comment add on a whiteboard needs --element <id>, or --x and --y");return{op:"add",x:n,y:o,...e.page?{page:e.page}:{},text:ae(e)}}if(t==="add"){if(!e.block)throw new w("comment add needs --block <blockId>");return{op:"add",blockId:e.block,...e.quote?{quote:e.quote}:{},text:ae(e)}}if(!e.thread)throw new w(`comment ${t} needs --thread <threadId>`);return t==="reply"?{op:"reply",threadId:e.thread,text:ae(e)}:{op:"resolve",threadId:e.thread}}function Mn(e){let t=Ci.find(s=>s===e.action);if(!t)throw new w("comment needs an action: list, add, reply, resolve, choose, submit, answer, note, pass, reject or waive");if(!e.artifact||!Ri.test(e.artifact))throw new w("--artifact must be document/<id>, artboard/<id>, whiteboard/<id> or verify/<id>");let[r,n]=e.artifact.split("/"),o=Ii(e,t,r);return{action:t,type:r,id:n,request:o,artifact:e.artifact}}async function Un(e,t,r){let{type:n,id:o,request:s}=t,i=M(e.projectDir),a=ve(process.env);return i.call("POST",`/api/agent/${n}/${o}/comments`,{...s,...a?{agent:a}:{}},r)}var Gn={actionOptions:{list:["limit","cursor","snapshot","status","waiting-on","kind","choice-state","thread"],read:["limit","cursor","all","save"]},semantic:Ln,name:"comment",summary:"Read and answer feedback on a document, artboard, whiteboard or verify report (needs a running server)",usage:["list --artifact <document|artboard|whiteboard>/<id> --sections all|<names> [--detail] [--all]","list --artifact <document|artboard|whiteboard>/<id> [--section threads|asks|groups|rounds] [--all]","read --artifact <document|artboard|whiteboard>/<id> --thread <threadId> [--snapshot <token>]","ack --artifact <document|artboard|whiteboard>/<id> --receipt <receipt>","add --artifact document/<id> --block <blockId> [--quote <text>] [--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>]","reply --artifact <document|artboard|whiteboard>/<id> --thread <threadId> [--text <text>]","resolve --artifact <document|artboard|whiteboard>/<id> --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\u2013100, 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 document or artboard"},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"},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)"},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};var Wn=C(require("node:os"),1),zt=C(require("node:path"),1);var Oi={on:!0,off:!1,inherit:null};function ji(e,t=()=>{}){let r=ot(ue(process.env,process.platform,Wn.default.homedir())),n=zt.default.join(zt.default.dirname(U(e.projectDir).root),"config.json");if(e.autoPublish!==void 0){let o=Oi[e.autoPublish];if(o===void 0)throw new w("--auto-publish takes on, off, or (with --project) inherit");if(e.project){let s=ie(n);if(s.warning)throw new w(s.warning);t(),Ae(n),Xr(n,o)}else{if(o===null)throw new w("inherit only applies with --project");tn(r,o,t)}}return{global:en(r)??null,project:ie(n).config.autoPublish??null}}var Vn={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=>I({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,r){if(e.values["auto-publish"]!==void 0&&e.values["output-format"]!==void 0)throw new w("Choose auto-publish or output-format.");let n=e.values.project?"project":"global",o=at(e.projectDir)[n],s,i=()=>{s=r.effects.begin("config",o)};typeof e.values["output-format"]=="string"&&on(e.projectDir,!!e.values.project,e.values["output-format"],i);let a=ji({projectDir:e.projectDir,autoPublish:e.values["auto-publish"],project:!!e.values.project},i);return s!==void 0&&r.effects.confirm(s),x({scope:n,projectDir:e.projectDir,file:o,...a,output:Ne(e.projectDir),effective:a.project??a.global,source:a.project!==null?"project":a.global!==null?"global":"undecided",applies:"supported_turn_end_hook"})},present:Ti},e)};function Ti({data:e}){let t=e.effective===null?"undecided":e.effective?"on":"off";return{heading:"Config",status:"",facts:[b("Scope",{key:"scope",value:e.scope}),b("File",{key:"file",value:e.file}),b("Auto-publish",{key:"autoPublish",value:e.source==="undecided"?t:`${t} (${e.source})`}),b("Output format",{key:"output",value:`${e.output.effective} (${e.output.source})`})],sections:[]}}var Fe=C(require("node:fs"),1),Zt=C(require("node:os"),1),de=C(require("node:path"),1);var _i=/<head(\s[^>]*)?>/i,$i=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,qn="<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>",Pi=/^<script>([\s\S]*?)<\/script>/,Ni=/^(?:<script defer src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui)\.js"><\/script>)+/;function Di(e){let t=_i.exec(e);return t?t.index+t[0].length:$i.exec(e)?.[0].length??0}function Hn(e){let t=Di(e),r=e.slice(t);r.startsWith(qn)&&(r=r.slice(qn.length));let n=Pi.exec(r);return!n||!n[1].includes("ryugi:")?e:e.slice(0,t)+r.slice(n[0].length).replace(Ni,"")}var eo=C(require("node:crypto"),1),yt=C(require("node:fs"),1),to=C(require("node:path"),1);var Qn=C(require("node:fs"),1),Xt=C(require("node:path"),1);var Jn="[a-z0-9][a-z0-9-]*",Yn="(?:[\\w-]{21}|[a-f0-9]{32})",ed=`(?:${Jn}|${Yn})`,Li=new RegExp(`^${Jn}$`),Mi=new RegExp(`^${Yn}$`),Bn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",zn=21,td=new RegExp(`^[a-z0-9]{${zn}}$`,"i"),Ui=248;function Fi(e){let t="",r=new Uint8Array(e*2);for(;t.length<e;){crypto.getRandomValues(r);for(let n of r)if(!(n>=Ui)&&(t+=Bn[n%Bn.length],t.length===e))break}return t}var Kn=()=>Fi(zn);var Ue=e=>Li.test(e),Kt=e=>Mi.test(e);var ge=e=>Ze.includes(e);function Xn(e){try{return Qn.default.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort()}catch{return[]}}function Qt(e){let t=[],r=[];for(let n of Xn(e))if(!n.startsWith(".")){if(!ge(n)){r.push(`unknown artifact type directory: ${n}/ (known: ${Ze.join(", ")})`);continue}for(let o of Xn(Xt.default.join(e,n)))Ue(o)?t.push({type:n,id:o,dir:Xt.default.join(e,n,o)}):r.push(`invalid artifact id: ${n}/${o} (use lowercase letters, digits and hyphens)`)}return{artifacts:t,warnings:r}}function Zn(e,t=Ue){let[r,n]=e.split("/");return!r||!n||!ge(r)||!t(n)?null:{type:r,id:n}}function ro(e){let t=new Set([...Object.keys(J),"artifact","source"]),r=Object.keys(e.values).find(a=>!t.has(a));if(r)throw new m({code:"E_ARGUMENT_INVALID",message:`--${r} applies to Cloud reads only. Local reads accept --artifact, --detail or --source.`});let n=e.values.artifact;n&&z(e.projectDir,n);let o=!!e.values.source||e.values.format==="source";if(o&&!n)throw new m({code:"E_ARGUMENT_INVALID",message:"Local --source requires --artifact <type>/<id>."});let{project:s,root:i}=U(e.projectDir);return I({id:"get",mode:"finite",output:{formats:["brief","table","json","jsonl",...n?["source"]:[]],detail:!0},async run(a,c){let l=n?{artifacts:[{type:n.split("/")[0],id:n.split("/")[1]}],warnings:[]}:Qt(i),u=l.artifacts.map(({type:k,id:S})=>{let O=`${k}/${S}`,T=z(s,O);if(T.content==="existing"){let G=yt.default.realpathSync(T.write);if(!G.startsWith(`${i}${to.default.sep}`))throw new m({code:"E_FILE_PATH_UNSAFE",message:`Artifact source escapes its project: ${T.write}`});let R=yt.default.statSync(G);if(!R.isFile())throw new m({code:"E_FILE_PATH_UNSAFE",message:`Artifact source is not a regular file: ${T.write}`});return{artifact:O,...T,bytes:R.size,modifiedAt:R.mtime.toISOString()}}return{artifact:O,...T}}),d,f;if(n&&(o||e.values.detail)){if(u[0]?.content!=="existing")throw new m({code:"E_ARTIFACT_NOT_FOUND",message:`Content not written yet: ${u[0]?.write}`});let k=yt.default.readFileSync(u[0].write);d=k.toString("utf8"),f=eo.default.createHash("sha256").update(k).digest("hex"),c.payloads.source=d}return x({origin:"local",project:s,complete:!0,...n?{}:{server:await Wr()},items:u,...d!==void 0?{content:d,sha256:f}:{}},void 0,{warnings:l.warnings.map(k=>({code:"W_ARTIFACT_DISCOVERY",message:k})),actions:n?[E(["check","--project-dir",s,"--artifact",n],"Check")]:[],coverage:n&&d===void 0?{omitted:[{path:"data.content",reason:"summary"}]}:{}})},present({data:a}){return{heading:"Local artifacts",status:"complete",subject:a.project,facts:a.server?[{label:"Server",binding:{key:"server",value:`${a.server.status}${a.server.version?` \xB7 ${a.server.version}`:""}`}}]:[],sections:[{kind:"records",key:"items",rows:a.items,columns:[{key:"artifact",required:!0,positional:!0},{key:"content",positional:!0},{key:"write",label:"Edit",required:!0},{key:"bytes"}]},...a.content!==void 0?[{kind:"content",key:"content",text:a.content,title:"Complete source"}]:[]]}}},e)}function Gi({data:e}){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(" \xB7 "),facts:[b("Title",A(e,"title")),...e.saved?[b("Saved",A(e,"saved"),!0),b("Bytes",A(e,"bytes"))]:[],...e.dir?[b("Downloaded",A(e,"dir"),!0)]:e.files?[b("Files available",{key:"files",value:e.files.join(", ")})]:[]],sections:[...e.outline?[{kind:"records",key:"outline",rows:e.outline,columns:[{key:"id",positional:!0,required:!0},{key:"type",positional:!0},{key:"preview",positional:!0}]}]:[],...e.content!==void 0?[{kind:"content",key:"content",title:"LiteXML",text:e.content}]:[],...e.comments?[{...Bt(e.comments.threads,"comments"),title:"Published snapshot comments"}]:[]]}}var ce=(e,t)=>typeof e.values[t]=="string"?e.values[t]:void 0,Wi=e=>!!e&&!e.includes("\\")&&!e.includes("\0")&&!de.default.posix.isAbsolute(e)&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..");async function Vi(e,t,r){if(!e.contentBase||!Array.isArray(e.files))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server did not return a complete download manifest."});if(e.files.some(n=>!Wi(n)))throw new m({code:"E_FILE_PATH_UNSAFE",message:"The manifest contains an unsafe file path."});if(Fe.default.existsSync(t))throw new m({code:"E_FILE_EXISTS",message:`Download directory already exists: ${t}`});Fe.default.mkdirSync(de.default.dirname(t),{recursive:!0}),Fe.default.mkdirSync(t,{mode:448});for(let n of e.files){let o=de.default.join(t,...n.split("/")),s=r.effects.begin("download",o);try{let i=await fetch(`${e.contentBase}${n.split("/").map(encodeURIComponent).join("/")}`,{signal:r.signal});if(!i.ok)throw new Error(`HTTP ${i.status}`);Fe.default.mkdirSync(de.default.dirname(o),{recursive:!0});let a=Buffer.from(await i.arrayBuffer()),c=Le(o,n.endsWith(".html")?Hn(a.toString("utf8")):a);r.effects.confirm(s,{bytes:c.bytes})}catch(i){throw r.effects.set(s,"failed",{message:i.message}),new m({code:"E_DOWNLOAD_FAILED",message:`Could not download ${n}: ${i.message}`})}}}function no(e){let t=e.positionals[0];if(!t)return ro(e);if(e.values.artifact)throw new m({code:"E_OPTION_CONFLICT",message:"Choose a local --artifact or a Cloud link/id, not both."});let{origin:r,id:n,grant:o}=oo(t,(process.env.RYUGI_CLOUD_ORIGIN||"https://ryugi.innei.dev").replace(/\/+$/,"")),s=ce(e,"save");if(s!==void 0&&!s.trim())throw new m({code:"E_ARGUMENT_INVALID",message:"--save requires a nonempty file path."});let i=!!e.values.source||e.values.format==="source"||s!==void 0,a=ce(e,"block"),c=ce(e,"out"),l=!!e.values.download||!!c,u=!!e.values.detail||i;if(i&&(a||l||ce(e,"fields")||ce(e,"cursor")||ce(e,"limit")))throw new m({code:"E_OPTION_CONFLICT",message:"Source must be a complete document; use --snapshot to pin its version."});if(a&&(l||u||ce(e,"cursor")))throw new m({code:"E_OPTION_CONFLICT",message:"--block reads one complete block and cannot combine with detail, cursor or download."});let d=ce(e,"limit");if(d&&(!/^\d+$/.test(d)||+d<1||+d>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});let f=new URLSearchParams({semantic:"1"});for(let k of["snapshot","cursor","fields","limit","section","page"]){let S=ce(e,k);S&&f.set(k,S)}return u&&f.set("detail","1"),a&&f.set("block",a),l&&f.set("download","1"),(e.values["no-comments"]||i)&&f.set("no-comments","1"),I({id:"get",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","source","quiet"],requiredFields:["id","type","visibility","version","status",...l?["dir"]:[],...s?["saved","bytes"]:[]],fields:["id","type","title","visibility","version","updatedAt","outline","files","content","comments","saved","bytes"],scalar:k=>k.saved??k.id},async run(k,S){let O=rt(ue(process.env,process.platform,Zt.default.homedir()),r),T=await fetch(`${r}/api/a/${n}?${new URLSearchParams([...f,...Object.entries(o??{})])}`,{headers:O?{Authorization:`Bearer ${O.token}`}:{},signal:S.signal}),G=await T.text();S.payloads.raw=G;let R;try{R=JSON.parse(G)}catch{throw new m({code:"E_PROTOCOL_MISMATCH",message:"The Cloud server returned an unsupported read response."})}if(!T.ok)throw new m({code:T.status===404?"E_NOT_FOUND":"E_CLOUD_FAILED",httpStatus:T.status,message:R.error||`HTTP ${T.status}`});if(R.schema!=="ryugi.cloud-read/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The Cloud server returned an unsupported read response."});let _;if(i){if(R.type!=="document"||typeof R.content!="string")throw new m({code:"E_FORMAT_UNSUPPORTED",message:"Source is available for documents only."});S.payloads.source=R.content,s&&(_=Le(s,R.content,S.effects),S.payloads.source="",(e.values.source||e.values.format==="source")&&S.diagnostic(`Saved ${_.file} (${_.bytes} bytes)`))}let{schema:y,page:p,contentBase:h,...g}=R,v={...g,..._?{saved:_.file,bytes:_.bytes}:{},status:l?"downloaded":u||a?"read":"available"};if(_&&delete v.content,l){v.dir=de.default.resolve(c??de.default.join(process.env.XDG_CACHE_HOME||de.default.join(Zt.default.homedir(),".cache"),"ryugi","get",n,`v${R.version}`));try{await Vi(R,v.dir,S)}catch(N){if(!S.effects.snapshot().some(D=>D.state==="confirmed"))throw N;return v.status="partial",v.downloads=S.effects.snapshot(),x(v,{kind:"partial"},{warnings:[{code:"W_DOWNLOAD_PARTIAL",message:N.message}]})}v.downloads=S.effects.snapshot()}let $=[...f.entries()].filter(([N])=>!["semantic","cursor","snapshot","detail","download"].includes(N)).flatMap(([N,D])=>N==="no-comments"?[`--${N}`]:[`--${N}`,D]),W=["get",...$,"--snapshot",R.snapshot],P=["get",...$,...u?["--detail"]:[],"--cursor",R.page?.nextCursor??"","--",t];return x(v,void 0,{coverage:{page:p,...!u&&!a?{omitted:[{path:"data.content",reason:"summary"}]}:{}},actions:[...!u&&!a?[E([...W,"--detail","--",t],"Details")]:[],...!a&&!i&&!l&&R.page?.nextCursor?[E(P,"More")]:[]]})},present:Gi},e)}var qi=/^[\w-]{1,64}$/,Hi=/^\/a\/([\w-]{1,64})(?:\/(?:view|preview))?\/?$/,so="Expected a Ryugi Cloud link (https://<host>/a/<id>) or an artifact id.";function oo(e,t){if(qi.test(e))return{origin:t,id:e};let r;try{r=new URL(e)}catch{throw new w(so)}let n=Hi.exec(r.pathname)?.[1];if(!n||r.protocol!=="https:"&&r.protocol!=="http:")throw new w(so);let o=r.searchParams.get("key"),s=r.searchParams.get("via");return{origin:r.origin,id:n,...o?{grant:{key:o,...s?{via:s}:{}}}:{}}}var io={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. Cloud reads show a published outline/manifest; use --detail, --source or --download for more. Local reads never consume feedback.",semantic:no,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};var uo=require("node:child_process"),rr=C(require("node:fs"),1),po=C(require("node:os"),1),bt=C(require("node:path"),1),fo=C(require("node:readline/promises"),1);var ao="Innei/ryugi",er={artifacts:"ryugi-artifacts@ryugi-dev",full:"ryugi@ryugi-dev"},Bi="https://github.com/Innei/ryugi/blob/main/docs/install.md#artifacts-only";function Ji(e,t=process.platform){return t==="win32"?{command:["claude",...e].join(" "),args:[],shell:!0}:{command:"claude",args:e,shell:!1}}function mo(e){let{command:t,args:r,shell:n}=Ji(e);return(0,uo.spawnSync)(t,r,{encoding:"utf8",stdio:["ignore","pipe","pipe"],shell:n})}function go(e){let t=mo(e);if(t.error||t.status!==0)throw new Error(`claude ${e.join(" ")} failed: ${(t.stderr||t.stdout||t.error?.message||"").trim()}`);return t.stdout}function Yi(){let e=mo(["--version"]);return!e.error&&e.status===0}function co(e){if(!rr.default.existsSync(e))return{};let r=JSON.parse(rr.default.readFileSync(e,"utf8")).enabledPlugins;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function zi(){let e=JSON.parse(go(["plugin","marketplace","list","--json"]));if(!Array.isArray(e))throw new Error("claude plugin marketplace list returned no list");return e.some(t=>t?.name==="ryugi-dev")}var tr=e=>e==="artifacts"||e==="full";async function lo(e){let t=fo.default.createInterface({input:process.stdin,output:process.stderr});try{return(await t.question(e)).trim().toLowerCase()}finally{t.close()}}async function Ki(e){let t=e?"full":"artifacts",r=await lo(`Install artifacts only, or the full Ryugi workflow? [artifacts/full] (${t}) `),n=r===""?t:r.startsWith("a")?"artifacts":r.startsWith("f")?"full":null;return n!=="artifacts"||!e||(await lo("This turns off the brainstorming, spec and TDD skills. Continue? [y/N] ")).startsWith("y")?n:null}async function Xi(e,t,r){let n=k=>x({mode:null,harness:"claude-code",installed:null,disabled:[]},{kind:"validation_failed"},{warnings:[{code:"W_INSTALL_MODE",message:k,severity:"error"}]});if(e!==void 0&&!tr(e))return n("--mode takes artifacts or full");if(!Yi())return x({mode:tr(e)?e:null,harness:"none",installed:null,disabled:[]},{kind:"succeeded"},{warnings:[{code:"W_NO_CLAUDE_CODE",message:"Claude Code was not found; artifacts only is Claude Code only. Install the full plugin by hand on other harnesses.",severity:"warning"}],actions:[{kind:"url",label:"Install guide",url:Bi}]});let o=process.env.CLAUDE_CONFIG_DIR||bt.default.join(po.default.homedir(),".claude"),s=co(bt.default.join(o,"settings.json")),i;if(tr(e))i=e;else if(process.stdin.isTTY&&process.stderr.isTTY)i=await Ki(s[er.full]===!0);else return n("--mode artifacts|full is required without a terminal to ask in");if(i===null)return n("Nothing installed: no mode chosen");let a=er[i],c=er[i==="artifacts"?"full":"artifacts"],l=(k,S,O)=>{let T=r?.begin(k,S);go(O),T!==void 0&&r.confirm(T)};zi()||l("install.marketplace",ao,["plugin","marketplace","add",ao,"--scope","user"]),l("install.refresh","ryugi-dev",["plugin","marketplace","update","ryugi-dev"]),l("install.plugin",a,["plugin","install",a,"--scope","user"]);let u=[];s[c]===!0&&(l("install.disable",c,["plugin","disable",c,"--scope","user"]),u.push(c));let d=[],f=[];for(let[k,S]of[["project","settings.json"],["local","settings.local.json"]])co(bt.default.join(t,".claude",S))[c]===!0&&(d.push({code:"W_OTHER_VARIANT_ENABLED",message:`${c} is still enabled at ${k} scope; enable only one Ryugi entry`,severity:"warning"}),f.push({kind:"command",argv:["claude","plugin","disable",c,"--scope",k],label:`Disable at ${k} scope`}));return x({mode:i,harness:"claude-code",installed:a,disabled:u},{kind:"succeeded"},{warnings:d,actions:f})}function Qi({data:e}){return{heading:"Install",status:e.installed?"installed":"unchanged",summary:e.installed?`${e.mode} \xB7 Claude Code`:"",facts:[b("Installed",A(e,"installed")),b("Disabled",{key:"disabled",value:e.disabled.join(", ")||null})],sections:[]}}var ho={name:"install",summary:"Install Ryugi into Claude Code: artifacts only, or the full workflow",usage:["[--mode artifacts|full] [options]"],details:"Without --mode, asks in the terminal. The two entries are never enabled together: installing one disables the other at user scope.",options:{mode:{type:"string",value:"artifacts|full",help:"What to install"}},semantic:e=>I({id:"install",mode:"finite",output:{formats:["brief","json","jsonl","quiet"]},run:(t,r)=>Xi(e.values.mode,e.projectDir,r.effects),present:Qi},e)};var Po=C(require("node:path"),1);var yo=require("node:child_process"),nr=C(require("node:path"),1),Zi=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function ea(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 Zi.exec(e)?.[1]??null}function ta(e){let t=ea(e.trim());if(!t)return null;let r=t.replace(/\.git\/?$/,"").split("/").filter(Boolean);return r.length<2?null:r.join("/").toLowerCase()}function wt(e){try{let t=(0,yo.execFileSync)("git",["-C",e,"remote","get-url","origin"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return ta(t)??nr.default.basename(e)}catch{return nr.default.basename(e)}}var or=`# Module vocabulary
|
|
375
|
+
|
|
376
|
+
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.
|
|
377
|
+
|
|
378
|
+
\`\`\`json
|
|
379
|
+
{
|
|
380
|
+
"version": 1,
|
|
381
|
+
"modules": [
|
|
382
|
+
{
|
|
383
|
+
"id": "billing",
|
|
384
|
+
"name": "Billing",
|
|
385
|
+
"description": "Plans, quotas and invoices.",
|
|
386
|
+
"paths": ["src/billing/**"],
|
|
387
|
+
"aliases": []
|
|
388
|
+
}
|
|
389
|
+
]
|
|
390
|
+
}
|
|
391
|
+
\`\`\`
|
|
392
|
+
|
|
393
|
+
Use readable lowercase IDs. Give modules descriptions and repository path globs so an agent can choose by the artifact's subject. Start from the repository's structure, docs and existing artifact titles; do not invent a business decision the human needs to make. A vocabulary normally has 5\u201315 lasting areas, rather than one module per current task.
|
|
394
|
+
|
|
395
|
+
\`modules\` lists current modules, counts and maintenance hints. \`modules --artifact <type>/<id> --set billing,sharing\` replaces that artifact's tags, at most 3; \`--set ""\` clears. Choose IDs from this file. A new subject may need different tags; a missing/retired ID needs retagging. The artifact directory must already exist.
|
|
396
|
+
|
|
397
|
+
Before adding a module, read counts and hints. Add only when no description fits and the area will outlive the task. Rename by changing name while keeping id. Merge B into A by removing B and adding B's ID to A.aliases. Split A into A1/A2 by adding A's old ID to both new aliases. Removing without an alias leaves a retired label on old artifacts. Never reuse or change an ID. Fix clear maintenance hints, leave business judgments to the human, and report edits to this vocabulary explicitly.
|
|
398
|
+
|
|
399
|
+
The CLI writes artifact tags to project configuration and preserves other settings. Do not edit server state or Cloud metadata to assign tags.
|
|
400
|
+
`;var jo=C(require("node:fs"),1),St=C(require("node:path"),1);var xo=C(require("node:fs"),1),Ao=C(require("node:path"),1);var sr="modules.json",ir=3,bo=100,wo=60,vo=200,ko=20,So=/^[a-z0-9-]{1,40}$/,Co="1 to 40 lowercase letters, digits and dashes",Ro=e=>e===void 0?[]:Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null;function na(e,t){if(typeof e!="object"||e===null)return`module ${t+1} must be an object`;let{id:r,name:n,description:o="",paths:s,aliases:i}=e;if(typeof r!="string"||!So.test(r))return`module id ${JSON.stringify(r)} must be ${Co}`;if(typeof n!="string"||n.trim()==="")return`${r} needs a name`;if(n.length>wo)return`${r}: a name is at most ${wo} characters`;if(typeof o!="string")return`${r}: description must be text`;if(o.length>vo)return`${r}: a description is at most ${vo} characters`;let a=Ro(s);if(!a)return`${r}: paths must be a list of globs`;let c=Ro(i);if(!c)return`${r}: aliases must be a list of retired ids`;if(c.length>ko)return`${r} has more than ${ko} aliases`;let l=c.find(u=>!So.test(u));return l!==void 0?`alias ${JSON.stringify(l)} of ${r} must be ${Co}`:{id:r,name:n,description:o,paths:a,aliases:c}}function oa(e){let t;try{t=JSON.parse(e)}catch(s){return{state:"invalid",reason:`modules.json is not valid JSON: ${s.message}`}}let r=t?.modules;if(!Array.isArray(r))return{state:"invalid",reason:'"modules" must be a list'};if(r.length>bo)return{state:"invalid",reason:`a vocabulary has at most ${bo} modules`};let n=[],o=new Set;for(let[s,i]of r.entries()){let a=na(i,s);if(typeof a=="string")return{state:"invalid",reason:a};if(o.has(a.id))return{state:"invalid",reason:`duplicate module id: ${a.id}`};o.add(a.id),n.push(a)}for(let{id:s,aliases:i}of n){let a=i.find(c=>o.has(c));if(a!==void 0)return{state:"invalid",reason:`alias ${JSON.stringify(a)} of ${s} is a live module id`}}return{state:"ok",modules:n}}function ar(e){let t;try{t=xo.default.readFileSync(Ao.default.join(e,sr),"utf8")}catch{return{state:"missing"}}return oa(t)}function Eo(e,t){let r=new Set,n=[];for(let o of t){let s=e.some(i=>i.id===o)?[o]:e.filter(i=>i.aliases.includes(o)).map(i=>i.id);s.length===0&&n.push(o);for(let i of s)r.add(i)}return n.length?{unknown:n}:{ids:[...r].sort()}}var kt=`.ryugi/${sr}`,Io=20,sa=20,cr=e=>St.default.dirname(U(e).root),lr=e=>St.default.join(cr(e),"config.json");function To(e,t){if(!Y.test(t))throw new w(re);if(!jo.default.existsSync(St.default.join(U(e).root,t)))throw new w(`No such artifact: ${t}`)}function ia(e){let t=ar(cr(e));if(t.state==="missing")throw new w(`This project has no vocabulary. Create ${kt} first.`);if(t.state==="invalid")throw new w(`${kt} is invalid: ${t.reason}`);return t.modules}function _o(e,t,r,n=()=>{}){To(e,t);let o=ia(e),s=r.split(",").map(c=>c.trim()).filter(Boolean),i=Eo(o,s);if("unknown"in i)throw new w(`Unknown module: ${i.unknown.join(", ")}. Choose from: ${o.map(({id:c})=>c).join(", ")}.`);if(i.ids.length>ir)throw new w(`An artifact has at most ${ir} modules; pick the ones it is mainly about.`);let a=lr(e);return n(),Ae(a),Kr(a,t,{modules:i.ids}),{artifact:t,modules:i.ids}}function aa(e){let t=new Map,r=0;for(let{modules:n}of Object.values(ie(lr(e)).config.artifacts))if(n?.length){r+=1;for(let o of n)t.set(o,(t.get(o)??0)+1)}return{counts:t,tagged:r}}var vt=e=>e.replace(/\/?\*+$/,"").replace(/\/$/,""),Oo=(e,t)=>e===t||e.startsWith(`${t}/`);function ca(e){let t=[];for(let[r,n]of e.entries())for(let o of e.slice(r+1)){let s=n.paths.flatMap(i=>o.paths.map(a=>[i,a])).find(([i,a])=>Oo(vt(i),vt(a))||Oo(vt(a),vt(i)));s&&t.push(`paths overlap: ${n.id} and ${o.id} (${s[0]} and ${s[1]})`)}return t}function la(e,t,r){let n=e.filter(({id:o})=>!t.get(o)).map(({id:o})=>o);return[...e.length>Io?[`${e.length} modules, more than ${Io}: merge the ones that are always chosen together`]:[],...r>=sa&&n.length?[`no artifacts: ${n.join(", ")} \u2014 merge them into a neighbour or remove them`]:[],...ca(e)]}function $o(e,{cloud:t,artifact:r}={}){r&&To(e,r);let n=r?{current:ie(lr(e)).config.artifacts[r]?.modules??null}:{},o=ar(cr(e)),s=t?"cloud":"local";if(o.state!=="ok")return{file:kt,state:o.state,...o.state==="invalid"?{reason:o.reason}:{},modules:[],counts:s,hints:[],...r?{artifact:r}:{},...n};let i=aa(e),a=t?new Map(t.modules.map(({id:l,count:u})=>[l,u])):i.counts,c=t?t.tagged:i.tagged;return{file:kt,state:"ok",modules:o.modules.map(l=>({...l,count:a.get(l.id)??0})),counts:s,hints:la(o.modules,a,c),...r?{artifact:r}:{},...n}}async function ua(e,t){try{let{status:r,json:n}=await M(e).call("GET","/api/cloud/artifacts",void 0,t);if(r!==200)return;let o=wt(U(e).project);return n.vocabularies?.[o]}catch{return}}function da({data:e}){let t=e.state==="missing"?`no vocabulary: create ${e.file}`:e.state==="invalid"?`invalid: ${e.reason}`:"";return{heading:"Modules",status:e.state==="ok"?"":e.state,subject:e.artifact,summary:t||`${e.modules.length} \xB7 ${e.file} \xB7 counts from ${e.counts==="cloud"?"Cloud":"this checkout only"}`,facts:e.current===void 0?[]:[b("Current",{key:"current",value:e.current===null?"never tagged":e.current.length?e.current.join(", "):"cleared"})],sections:[...e.writing?[{kind:"content",key:"writing",title:"Writing",text:e.writing}]:[],{kind:"records",key:"modules",rows:e.modules.map(r=>({...r,paths:r.paths.join(" ")})),columns:[{key:"id",positional:!0,required:!0},{key:"count",positional:!0,required:!0},{key:"name",positional:!0},{key:"description",positional:!0},{key:"paths",positional:!0}]},{kind:"diagnostics",key:"hints",items:e.hints.map(r=>({code:"W_MODULES_MAINTENANCE",message:r,severity:"warning"}))}]}}function pa({data:e}){return{heading:"Modules",status:"SET",subject:e.artifact,summary:e.modules.length?e.modules.join(", "):"cleared",facts:[],sections:[]}}var No={name:"modules",summary:"List the project's business modules, or set the modules an artifact serves",usage:["[--artifact <type>/<id>] [options]","--artifact <type>/<id> --set <id>[,<id>...]"],details:or.trim(),options:{artifact:{type:"string",value:"<type>/<id>",help:"The artifact to show or tag"},set:{type:"string",value:"<id>[,<id>...]",help:"Replace the artifact\u2019s modules with these ids"}},semantic:e=>{let t=e.values.artifact,r=e.values.set;if(r!==void 0){if(!t)throw new w("--set needs --artifact <type>/<id>");return I({id:"modules.set",mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:n=>n.modules.join(",")},run:(n,o)=>{let s,i=_o(e.projectDir,t,r,()=>{s=o.effects.begin("modules.set",t)});return s!==void 0&&o.effects.confirm(s),x(i)},present:pa},e)}return I({id:"modules",mode:"finite",output:{formats:["brief","table","json","jsonl"],fields:["id","count","name","description","paths","aliases"],collection:"modules",requiredFields:["id","count"]},async run(n,o){let s=await ua(e.projectDir,o.signal),i=$o(e.projectDir,{cloud:s,artifact:t});return x({...i,project:e.projectDir,write:Po.default.join(e.projectDir,i.file),...i.state!=="ok"?{writing:or.trim()}:{}})},present:da},e)}};function Q(e){if(e.status>=200&&e.status<300)return e.json;let t=e.json;throw new m({code:e.status===401?"E_LOGIN_REQUIRED":typeof t.code=="string"?`E_${t.code.toUpperCase()}`:`E_HTTP_${e.status}`,message:typeof t.error=="string"?t.error:`Cloud request failed: HTTP ${e.status}`,httpStatus:e.status,details:{...t.loginUrl?{loginUrl:t.loginUrl}:{},...t.upgradeUrl?{upgradeUrl:t.upgradeUrl}:{},...t.limit?{limit:t.limit}:{},...t.plan?{plan:t.plan}:{},...t.reasons?{reasons:t.reasons}:{}}},e.status===401||e.status===402&&(t.code==="plan_limit"||t.code==="plan_required")?"action_required":"failed")}function fa({data:e}){return{heading:"Publish",status:e.status,subject:e.artifact,facts:[b("ID",A(e,"id"),!0),b("URL",A(e,"url"),!0),b("Visibility",{key:"visibility",value:`${e.visibility} (${e.visibilitySource})`},!0),...e.visibility==="public"?[b("Profile",{key:"onProfile",value:e.onProfile?"listed":"not listed"},!0)]:[],...e.shareKey?[b("Key",{key:"shareKey.key",value:e.shareKey.key},!0),b("Expires",{key:"shareKey.expiresAt",value:e.shareKey.expiresAt??"never"},!0)]:[],...e.version===void 0?[]:[b("Version",A(e,"version"))]],sections:e.references.length?[{kind:"records",key:"references",title:"Referenced artifacts",rows:e.references.map(t=>({artifact:t.artifact,status:t.status,via:t.via?`via ${t.via}`:"",error:t.error?`${t.error.code}: ${t.error.message}`:"",recovery:t.status==="unknown"?"inspect the remote artifact before retrying":""})),columns:[{key:"artifact",positional:!0,required:!0},{key:"status",positional:!0,required:!0},{key:"via",positional:!0},{key:"error",positional:!0},{key:"recovery",positional:!0}]}]:[]}}function ma({data:e,coverage:t}){return{heading:"Cloud artifacts",status:"",summary:`${t.page?.total??e.artifacts.length} on account`,facts:[],sections:[{kind:"records",key:"artifacts",rows:e.artifacts.map(n=>({...n,version:n.version===void 0?"":`v${n.version}`})),columns:[{key:"id",positional:!0,required:!0},{key:"type",positional:!0},{key:"visibility",positional:!0,required:!0},{key:"version",positional:!0},{key:"updatedAt",positional:!0},{key:"title",positional:!0}]}]}}var Do=["brief","json","jsonl","quiet"];function ga(e){let{values:t}=e,r=["unpublish","revoke-key","list","delete","login","logout"].filter(a=>t[a]),n=!!(t.key||t["new-key"]);if(r.length>1||t.public&&t.private||t.public&&n||t.profile&&t["no-profile"]||n&&t["revoke-key"])throw new m({code:"E_OPTION_CONFLICT",message:"Choose one publish action and one visibility."});let o=r[0]??"publish";if(o!=="publish"&&n||t.key&&t["new-key"]||t.artifact!==void 0&&!["publish","unpublish","revoke-key","list"].includes(o)||t.from!==void 0&&o!=="login")throw new m({code:"E_OPTION_UNSUPPORTED",message:"Key creation applies only to publishing; artifact targets apply to publishing, key revocation or targeted --list; --from applies only to --login. Choose either --key or --new-key."});if(o!=="list"&&["visibility","type","project","module","limit","cursor"].some(a=>t[a]!==void 0))throw new m({code:"E_OPTION_UNSUPPORTED",message:"List filters and paging apply only to --list."});let s=t.artifact;if((["publish","unpublish","revoke-key"].includes(o)||o==="list"&&s!==void 0)&&(!s||!Y.test(s)))throw new m({code:"E_ARGUMENT_INVALID",message:"--artifact must be <type>/<id>."});if(o==="list"&&s&&["visibility","type","project","module","limit","cursor","fields"].some(a=>t[a]!==void 0))throw new m({code:"E_OPTION_UNSUPPORTED",message:"Targeted --list --artifact reads publication and key state; collection filters and paging apply only without --artifact."});if(o==="delete"&&!/^[\w-]{1,64}$/.test(String(t.delete??"")))throw new m({code:"E_ARGUMENT_INVALID",message:"--delete requires a Cloud artifact ID."});if(o!=="publish"&&(t.public||t.private||t["no-refs"]||t.profile||t["no-profile"]))throw new m({code:"E_OPTION_UNSUPPORTED",message:"Visibility, profile listing and --no-refs apply only to publishing."});if(t.expires!==void 0&&!n)throw new m({code:"E_OPTION_UNSUPPORTED",message:"--expires applies only with --key or --new-key."});if(t.expires!==void 0&&!qr(t.expires))throw new m({code:"E_ARGUMENT_INVALID",message:"--expires must be 1d, 7d, 30d or never."});let i=n?{...t.expires?{expires:t.expires}:{},...t["new-key"]?{regenerate:!0}:{}}:void 0;return{action:o,artifact:s,key:i,onProfile:t.profile?!0:t["no-profile"]?!1:void 0,visibility:t.public?"public":t.private||i?"private":void 0}}async function ha(e,t,r,n,o,s){let i=M(e.projectDir),c=await(async(y,p)=>{let h=t.effects.begin("publish",y),g={...p?{visibility:p}:{},...o===void 0?{}:{onProfile:o}},v=await i.call("POST",`/api/cloud/publish/${y}`,Object.keys(g).length?g:void 0,t.signal);v.status>=400&&v.status<500&&t.effects.set(h,"failed",v.json);let $=Q(v);return t.effects.confirm(h,{url:$.url,visibility:$.visibility,version:$.version}),$})(r,n),l;if(s||c.keyed){let y=s?t.effects.begin("share-key",r):void 0,p=await i.call(s?"PUT":"GET",`/api/cloud/share-key/${r}`,s,t.signal);y!==void 0&&p.status>=400&&p.status<500&&t.effects.set(y,"failed");let h=Q(p);if(h.shareKey===void 0||s&&!h.shareKey)throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server did not confirm the share-key state."});l=h.shareKey??void 0,y!==void 0&&t.effects.confirm(y,{expiresAt:l?.expiresAt})}let u=Q(await i.call("GET",`/api/cloud/refs/${r}?visibility=${c.visibility}&referrers=0`,void 0,t.signal)),d=e.values["no-refs"]?[]:u.items.filter(y=>y.checked&&y.state!=="private"),f=new Map;if(d.length){let y=new Map(d.map(g=>[g.artifact,t.effects.begin("publish",g.artifact)])),p=await i.call("POST",`/api/cloud/publish-refs/${r}`,{visibility:c.visibility,refs:d.map(g=>g.artifact),makePublic:[]},t.signal),h=Q(p);for(let g of h.results){f.set(g.artifact,g);let v=y.get(g.artifact);v!==void 0&&(g.status==="published"?t.effects.confirm(v,{}):g.status==="failed"?t.effects.set(v,"failed",g.error):g.status==="not_attempted"&&t.effects.set(v,"not_attempted"))}}let k=y=>{try{Q({status:y.error?.httpStatus??500,json:y.error??{}})}catch(p){return He(p)}},S={publish:"published",update:"updated","make-public":"made_public"},O=u.items.map(y=>{let p={artifact:y.artifact,state:y.state,via:y.via},h=f.get(y.artifact);if(h){let g=h.status==="published"?void 0:k(h);return{...p,status:h.status==="published"?S[h.action]:h.status,...g?{error:g}:{}}}return y.reason==="upstream"?{...p,status:"unreachable"}:y.state==="unpublished"||y.state==="stale"?{...p,status:"skipped"}:{...p,status:y.state}}),T=O.some(y=>["failed","unknown","not_attempted"].includes(y.status)),G={status:T?"partial":"published",artifact:r,id:c.id??new URL(c.url).pathname.split("/").filter(Boolean).at(-1),url:l?.url??c.url,visibility:c.visibility,...c.version===void 0?{}:{version:c.version},visibilitySource:n?"requested":"preserved",onProfile:c.onProfile===!0,onProfileSource:o===void 0?"preserved":"requested",...l?{shareKey:{key:l.key,expiresAt:l.expiresAt}}:{},references:O},R=O.filter(y=>y.status==="private"),_=O.filter(y=>y.status==="skipped");return x(G,T?{kind:"partial"}:{kind:"succeeded"},{effects:t.effects.snapshot(),warnings:[...o&&c.visibility!=="public"?[{code:"W_PROFILE_NEEDS_PUBLIC",message:"It will show on your profile once it is public."}]:[],...R.length?[{code:"W_REFERENCES_PRIVATE",message:`${R.length} referenced artifacts are private; visitors see a locked label.`}]:[],..._.length?[{code:"W_REFERENCES_UNPUBLISHED",message:`${_.length} referenced artifacts were left as they are (--no-refs).`}]:[]],actions:[...O.flatMap(y=>y.error?Se(y.error,y.artifact):[]),...R.map(y=>E(["publish","--artifact",y.artifact,"--project-dir",e.projectDir,"--public"],"Next")),..._.length&&!T?[E(["publish","--artifact",r,"--project-dir",e.projectDir],"Next")]:[]]})}function Lo(e){let{action:t,artifact:r,visibility:n,onProfile:o,key:s}=ga(e);if(t==="list"&&r)return I({id:"publish.list",mode:"finite",output:{formats:["brief","json","jsonl"]},async run(i,a){let c=M(e.projectDir),l=Vr(Q(await c.call("GET",`/api/cloud/publication/${r}`,void 0,a.signal)));if(!l)throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported publication state."});let{shareKey:u}=Q(await c.call("GET",`/api/cloud/share-key/${r}`,void 0,a.signal));if(u===void 0)throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server did not return the current share-key state."});return x({artifact:r,publication:l,shareKey:u})},present({data:i}){return{heading:"Cloud artifact",status:i.publication.phase,subject:r,facts:[b("Published at",{key:"publication.publishedAt",value:i.publication.publishedAt}),b("Key",{key:"shareKey.key",value:i.shareKey?.key??"none"},!0),...i.shareKey?[b("URL",{key:"shareKey.url",value:i.shareKey.url},!0),b("Expires",{key:"shareKey.expiresAt",value:i.shareKey.expiresAt??"never"},!0)]:[]],sections:[]}}},e);if(t==="publish")return I({id:"publish.publish",mode:"finite",output:{formats:Do,scalar:i=>i.id},run:(i,a)=>ha(e,a,r,n,o,s),present:fa},e);if(t==="list"){let i=new URLSearchParams({semantic:"1"});for(let a of["visibility","type","project","limit","cursor","fields"]){let c=e.values[a];typeof c=="string"&&i.set(a,c)}if(typeof e.values.module=="string"){i.has("project")||i.set("project",wt(U(e.projectDir).project));let a=e.values.module.split(",").map(c=>c.trim());for(let c of new Set(a))i.append("module",c)}if(i.has("limit")&&(!/^\d+$/.test(i.get("limit"))||+i.get("limit")<1||+i.get("limit")>100))throw new m({code:"E_ARGUMENT_INVALID",message:"--limit must be between 1 and 100."});if(i.has("visibility")&&!["public","private"].includes(i.get("visibility"))||i.has("type")&&!ge(i.get("type")))throw new m({code:"E_ARGUMENT_INVALID",message:"Invalid Cloud list filter."});return I({id:"publish.list",mode:"finite",output:{detail:!0,formats:["brief","table","json","jsonl","raw"],fields:["id","type","title","project","modules","visibility","url","updatedAt","version"],collection:"artifacts",requiredFields:["id","type","visibility","version"]},async run(a,c){let l=await M(e.projectDir).call("GET",`/api/cloud/artifacts?${i}`,void 0,c.signal);c.payloads.raw=l.raw;let u=Q(l);if(u.schema!=="ryugi.cloud-list/v1")throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an unsupported Cloud list response."});return x({artifacts:u.artifacts},void 0,{coverage:{page:u.page},actions:u.page?.nextCursor?[E(["publish","--list","--project-dir",e.projectDir,...[...new Set(i.keys())].filter(d=>!["semantic","cursor"].includes(d)).flatMap(d=>[`--${d}`,i.getAll(d).join(",")]),"--cursor",u.page.nextCursor],"More")]:[]})},present:ma},e)}return I({id:`publish.${t}`,mode:"finite",output:{formats:t==="login"?["brief","json","jsonl"]:Do,scalar:i=>i.id},async run(i,a){let c=t==="delete"?String(e.values.delete):r,l=["login","logout"].includes(t)?"POST":"DELETE",u=t==="delete"?`/api/cloud/artifacts/${c}`:t==="unpublish"?`/api/cloud/publish/${c}`:t==="revoke-key"?`/api/cloud/share-key/${c}`:`/api/cloud/${t}`,d=t==="login"?void 0:a.effects.begin(t,c??"cloud-account"),f=typeof e.values.from=="string"?e.values.from:"cli",k=await M(e.projectDir).call(l,u,t==="login"?{source:f}:void 0,a.signal);d!==void 0&&k.status>=400&&k.status<500&&a.effects.set(d,"failed");let S=Q(k);d!==void 0&&a.effects.confirm(d);let O=t==="login"&&!S.signedIn?{kind:"pending",reasons:["sign_in_in_browser"]}:t==="logout"&&S.remoteRevoked!==!0?{kind:"partial"}:{kind:"succeeded"};return x({id:t==="logout"?"signed-out":S.id??c??"cloud-account",artifact:c,status:t==="login"?S.signedIn?"signed_in":"pending":t==="logout"?"signed_out":t==="delete"?"deleted":t==="revoke-key"?"key_removed":"unpublished",...S.url?{url:S.url}:{},...t==="logout"?{localCredentials:"cleared",remoteSession:S.remoteRevoked===!0?"revoked":"unknown"}:{}},O,{effects:a.effects.snapshot(),actions:S.url?[{kind:"url",url:S.url,label:"Open"}]:[]})},present({data:i}){return{heading:t==="login"?"Login":t==="logout"?"Logout":"Cloud artifact",status:i.status,subject:i.id,facts:[...i.artifact?[b("Artifact",A(i,"artifact"))]:[],...i.url?[b("URL",A(i,"url"))]:[],...i.remoteSession?[b("Remote session",A(i,"remoteSession"))]:[]],sections:[]}}},e)}var Mo={semantic:Lo,name:"publish",summary:"Publish an artifact to the Ryugi cloud (needs a running server)",usage:["--artifact <type>/<id> [--public | --private | --key] [--profile | --no-profile] [options]","--artifact <type>/<id> --unpublish | --revoke-key [options]","--list | --delete <cloud-id> | --login | --logout [options]","--list --artifact <type>/<id> (read publication and current key state without changing either)"],options:{visibility:{type:"string",value:"<public|private>",help:"Filter published list visibility"},type:{type:"string",value:"<document|artboard|whiteboard|html|verify>",help:"Filter published list type"},project:{type:"string",value:"<project>",help:"Filter published list project"},module:{type:"string",value:"<id>[,<id>...]",help:'Filter published list by module ("" for untagged); the project defaults to this one'},limit:{type:"string",value:"<1-100>",help:"Maximum list rows"},cursor:{type:"string",value:"<token>",help:"Continue a stable list snapshot"},artifact:{type:"string",value:"<type>/<id>",help:"The artifact to publish, unpublish, revoke a key, or inspect with --list"},public:{type:"boolean",help:"Anyone with the link can open it"},private:{type:"boolean",help:"Only you can open it"},key:{type:"boolean",help:"Only people with the key can open it; prints a link that carries the key"},expires:{type:"string",value:"<1d|7d|30d|never>",help:"With --key or --new-key: when the key stops working (7d for a new key)"},"new-key":{type:"boolean",help:"Replace the key; links with the old key stop opening"},"revoke-key":{type:"boolean",help:"Remove the key; only you can open it"},profile:{type:"boolean",help:"Show it on your public profile once it is public"},"no-profile":{type:"boolean",help:"Take it off your public profile"},unpublish:{type:"boolean",help:"Remove the artifact's cloud copy"},list:{type:"boolean",help:"List your cloud artifacts; with --artifact, read its publication and current key state"},delete:{type:"string",value:"<cloud-id>",help:"Delete a cloud artifact by its id from --list"},"no-refs":{type:"boolean",help:"Publish only this artifact; leave the artifacts it references as they are"},login:{type:"boolean",help:"Sign in to the Ryugi cloud"},from:{type:"string",value:"<tag>",help:"With --login: where this sign-in started, recorded by Ryugi Cloud"},logout:{type:"boolean",help:"Sign out of the Ryugi cloud"}}};var ya=/^whiteboard\/[a-z0-9][a-z0-9-]*$/,ba=e=>{let t=e;return typeof e=="object"&&e!==null&&typeof t.artifact=="string"&&typeof t.sceneVersion=="number"&&Array.isArray(t.lines)&&["none","current","stale"].includes(t.render)},Uo={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=>I({id:"scene",mode:"finite",output:{detail:!1,formats:["brief","json","jsonl","raw"],fields:["artifact","page","pages","sceneVersion","render","renderPath","lines","conflicts"],scalar:t=>t.render},async run(t,r){let n=e.values.artifact;if(!n||!ya.test(n))throw new w("--artifact must be whiteboard/<id>");let o=e.values.frame,s=e.values.page,i=await M(e.projectDir).call("POST",`/api/agent/${n}/scene`,{...o?{frame:o}:{},...s?{page:s}:{}},r.signal);if(r.payloads.raw=i.raw,i.status<200||i.status>=300)throw new w(i.json?.error||`HTTP ${i.status}`);if(!ba(i.json))throw new m({code:"E_PROTOCOL_MISMATCH",message:"The server returned an invalid scene report."});let a=i.json;return x(a,{kind:"succeeded"},{actions:(a.pages??[]).map(c=>E(["scene","--artifact",n,"--page",c.id,"--project-dir",e.projectDir],`Read ${c.id}`))})},present:wa},e)};function wa({data:e}){return{heading:"Scene",status:e.problem?"invalid":"",subject:e.artifact,facts:[...e.page?[b("Page",A(e,"page"))]:[],b("Version",A(e,"sceneVersion")),b("Render",A(e,"render")),...e.renderPath?[b("Image",A(e,"renderPath"))]:[],...e.problem?[b("Problem",A(e,"problem"))]:[],b("Conflicts",{key:"conflicts",value:e.conflicts.join(", ")})],sections:[{kind:"content",key:"lines",text:e.lines.join(`
|
|
401
|
+
`)}]}}var Ve=require("node:child_process"),is=C(require("node:crypto"),1),q=C(require("node:fs"),1),At=C(require("node:path"),1),gr=C(require("node:readline"),1);var Ct=C(require("node:fs"),1),ur=C(require("node:path"),1);function Fo(e){let t=ur.default.join(e,".artifact-id"),r;try{r=Ct.default.readFileSync(t,"utf8").trim()}catch(n){if(n.code!=="ENOENT")throw n;r=Kn();try{Ct.default.writeFileSync(t,`${r}
|
|
402
|
+
`,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;return Fo(e)}}if(!Kt(r))throw new Error(`Invalid artifact ID in ${t}`);return r}function Go(e,t,r){if(!ge(t)||!Ue(r))throw new Error("Invalid artifact locator");let n=ur.default.join(e,t,r);return Ct.default.mkdirSync(n,{recursive:!0}),`/${t}/${Fo(n)}`}var qo=require("node:child_process"),Ho=require("node:util");var va={html:"text/html; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",json:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",mp4:"video/mp4",webm:"video/webm"},ka=va.json;function Wo(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}var Vo=(0,Ho.promisify)(qo.execFile),Sa=String.raw`
|
|
29
403
|
function run(urls) {
|
|
30
404
|
function key(url) {
|
|
31
405
|
return String(url).split(/[?#]/)[0].replace(/^(https?:\/\/)127\.0\.0\.1:/, '$1localhost:').replace(/\/$/, '');
|
|
@@ -57,17 +431,19 @@ function run(urls) {
|
|
|
57
431
|
} catch (e) { unknown = true; }
|
|
58
432
|
}
|
|
59
433
|
return unknown ? 'unknown' : 'missing';
|
|
60
|
-
}`;async function
|
|
61
|
-
`,{flag:"wx",mode:384})}catch(o){if(o.code==="EEXIST")return}return{message:"Recommended: sign in to Ryugi Cloud to share artifacts and review them from other devices. Sign-in is optional; local work can continue.",command:`${process.env.RYUGI_ARTIFACTS_COMMAND||"npx ryugi-artifacts"} publish --login --from hint`,projectDir:e,agentInstruction:"Briefly pass this recommendation to your human partner and offer to run command in projectDir to obtain the sign-in URL. Continue the current task without waiting for sign-in."}}var
|
|
62
|
-
`)}function
|
|
63
|
-
`).find(t=>t.includes('"server-started"')),
|
|
64
|
-
`).find(t=>t.includes('"server-error"'));async function
|
|
65
|
-
`);let o=process.env.RYUGI_ARTIFACTS_VERSION||"1.
|
|
66
|
-
`),
|
|
67
|
-
`);let k=[
|
|
68
|
-
`);let
|
|
69
|
-
`);for(let
|
|
70
|
-
`)};if(
|
|
71
|
-
`);throw new
|
|
72
|
-
${
|
|
73
|
-
or run \`${
|
|
434
|
+
}`;async function dr(e,t=[]){if(process.platform==="darwin"){let{stdout:n,stderr:o}=await Vo("osascript",["-l","JavaScript","-e",Sa,e,...t],{timeout:5e3});if(o.trim()&&console.error(o.trim()),n.trim()==="found")return;if(n.trim()!=="missing")throw new Error("Could not inspect existing browser tabs; open the artifact link manually.")}let r=Wo(process.platform,e);r&&await Vo(r.bin,r.args)}var Bo=C(require("node:crypto"),1),Ge=C(require("node:fs"),1),Jo=C(require("node:os"),1),he=C(require("node:path"),1);function Yo(e=process.env,t=process.platform,r=process.getuid?.()??-1,n=Jo.default.tmpdir()){return e.RYUGI_RUNTIME_DIR?he.default.join(e.RYUGI_RUNTIME_DIR,"servers"):t==="win32"?he.default.join(n,"ryugi","servers"):`/tmp/ryugi-${r}/servers`}var Ca=(e,t)=>he.default.join(e,`${Bo.default.createHash("sha256").update(t).digest("hex").slice(0,16)}.json`);function Ra(e){if(process.platform!=="win32")for(let t of[he.default.dirname(e),e]){let r=Ge.default.lstatSync(t);if(!r.isDirectory()||r.uid!==process.getuid()||r.mode&18)throw new Error(`Unsafe registry directory: ${t}`)}}function zo(e){try{let t=JSON.parse(Ge.default.readFileSync(e,"utf8"));return typeof t.project!="string"||typeof t.root!="string"||typeof t.serverId!="string"||!Number.isInteger(t.pid)||!Number.isFinite(t.startedAt)||t.root!==he.default.join(t.project,".ryugi","artifacts")?null:t}catch{return null}}function Ko(e){let t;try{Ra(e),t=Ge.default.readdirSync(e)}catch{return[]}return t.filter(r=>r.endsWith(".json")).flatMap(r=>zo(he.default.join(e,r))??[])}function Xo(e,t){let r=Ca(e,t.project);zo(r)?.serverId===t.serverId&&Ge.default.rmSync(r,{force:!0})}var pr=C(require("node:fs"),1),Qo=C(require("node:os"),1),Rt=C(require("node:path"),1);function Zo(e){let t=ue(process.env,process.platform,Qo.default.homedir()),r=(process.env.RYUGI_CLOUD_ORIGIN||"https://ryugi.innei.dev").replace(/\/+$/,"");if(rt(t,r))return;let n=Rt.default.join(Rt.default.dirname(t),"login-hint-shown");try{pr.default.mkdirSync(Rt.default.dirname(n),{recursive:!0,mode:448}),pr.default.writeFileSync(n,`1
|
|
435
|
+
`,{flag:"wx",mode:384})}catch(o){if(o.code==="EEXIST")return}return{message:"Recommended: sign in to Ryugi Cloud to share artifacts and review them from other devices. Sign-in is optional; local work can continue.",command:`${process.env.RYUGI_ARTIFACTS_COMMAND||"npx ryugi-artifacts"} publish --login --from hint`,projectDir:e,agentInstruction:"Briefly pass this recommendation to your human partner and offer to run command in projectDir to obtain the sign-in URL. Continue the current task without waiting for sign-in."}}var We=C(require("node:path"),1);function xa(e){let t=e.values;if(t.foreground&&t.background)throw new m({code:"E_OPTION_CONFLICT",message:"Choose --foreground or --background."});if(t.open&&t["no-open"])throw new m({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}}function fr(e,t){let r=t?We.default.dirname(We.default.dirname(t.root)):e.projectDir,n=e.artifact?z(r,e.artifact):void 0;return{cliVersion:"1.78.0",serverVersion:H(ne().version),status:t?"running":"stopped",scope:"machine",project:r,...n,...n?.content==="missing"?{writing:ct(e.artifact)}:{},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 es({data:e}){return{heading:"Server",status:e.status,subject:e.reused?"reused":void 0,facts:[b("Scope",A(e,"scope")),b("CLI version",A(e,"cliVersion")),b("Server version",A(e,"serverVersion")),b("Project",A(e,"project"),!0),...e.artifact?[b("Artifact",A(e,"artifact"),!0)]:[],...e.write?[b("Write",A(e,"write"),!0),b("Content",A(e,"content"),!0)]:[],...e.url?[b("Open",A(e,"url"),!0)]:[],...e.localUrl&&e.localUrl!==e.url?[b("Local",A(e,"localUrl"),!0)]:[],b("Cloud",A(e,"cloud"))],sections:e.writing?[{kind:"content",key:"writing",title:"Writing",text:e.writing}]:[]}}function ts(e,t){let r=t.cloudLimit?.upgradeUrl?[{kind:"url",url:t.cloudLimit.upgradeUrl,label:"Upgrade"}]:[];return e.artifact&&r.push(E(["check","--project-dir",We.default.dirname(We.default.dirname(t.root)),"--artifact",e.artifact],"Check")),t.loginHint&&r.push(E(["publish","--login","--from","hint","--project-dir",e.projectDir],"Sign in")),x(fr(e,t),void 0,{actions:r,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*Aa(e,t){let r=[],n,o=!1,s,i,a,c=t.effects.begin("start",e.projectDir),l=d=>{r.push(d),n?.()},u=mr(e,{signal:t.signal,ready(d){i=d,t.effects.confirm(c,{reused:!!d.reused}),l({kind:"ready",result:ts(e,d)})},failure(d){a=String(d.error??"Server failed")},log:d=>t.diagnostic(d)}).then(d=>{if(t.signal.aborted){let f=t.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";l({kind:"result",result:x({...fr(e,i),status:"stopped"},{kind:"interrupted",signal:f},{effects:t.effects.snapshot()})})}else{if(d!==0||a)throw new m({code:"E_SERVER_FAILED",message:a??`Server exited with ${d}.`});l({kind:"result",result:x({...fr(e,i),status:i?.reused?"running":"stopped"},void 0,{effects:t.effects.snapshot()})})}}).catch(d=>{s=d}).finally(()=>{o=!0,n?.()});try{for(;!o||r.length;)r.length?yield r.shift():await new Promise(d=>{n=d});if(s)throw s}finally{await u}}function xt(e,t="start"){let r=xa(e);return r.library=t==="browse",r.foreground?I({id:t,mode:"live",output:{formats:["brief","jsonl"]},run:(o,s)=>Aa(r,s),present:es},e):I({id:t,mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:o=>o.url},async run(o,s){let i,a,c=s.effects.begin("start",r.projectDir);if(await mr(r,{signal:s.signal,ready(u){i=u,s.effects.confirm(c,{reused:!!u.reused})},failure(u){a=String(u.error??"Server failed")},log:u=>s.diagnostic(u)})!==0||!i)throw new m({code:"E_SERVER_FAILED",message:a??"Server did not become ready."});return ts(r,i)},present:es},e)}function rs(e,t){return e&&t&&e===t?"keep":"replace"}var as="https://ryugi.innei.dev",Ea=5e3,Ia=15e3,Oa=1e3,ns=1e4,cs=(e,t)=>{let r=process.env[e]?Number(process.env[e]):NaN;return Number.isFinite(r)&&r>=0?r:t},ja=cs("RYUGI_START_SETTLE_MS",6e3),Ta=cs("RYUGI_STOP_GRACE_MS",7e3),_a=e=>(e.RYUGI_CLOUD_ORIGIN||as).replace(/\/+$/,""),$a=e=>{let t=new URL(e);return t.hostname==="localhost"&&(t.hostname="127.0.0.1"),t},hr=(e,t)=>{let r=$a(e.url),n=new URL(t,r.origin),o=r.searchParams.get("key");return o&&n.searchParams.set("key",o),n.toString()};function Pa(e,t,r){let n={type:"server-started",url:e.url,port:e.port,root:t.root};if(r){let o=new URL(e.url),s=Zn(r),i=o.searchParams.get("key");n.link=`${o.origin}${Go(t.root,s.type,s.id)}${i?`?key=${i}`:""}`}return n}async function Na(e,t,r,n){if(!n)return e;try{let o=await fetch(hr(t,`/api/cloud/reserve/${n}`),{method:"POST",headers:{"X-Ryugi-Project":encodeURIComponent(r.project)},signal:AbortSignal.timeout(Ea)}),{url:s,limit:i}=await o.json();return typeof s=="string"?{...e,cloudLink:s}:typeof i?.upgradeUrl=="string"?{...e,cloudLimit:{message:i.message,upgradeUrl:i.upgradeUrl}}:e}catch{return e}}async function Da(e){for(let t=0;t<150;t++){try{return q.default.mkdirSync(e),!0}catch{}try{if(Date.now()-q.default.statSync(e).mtimeMs>6e4){q.default.rmdirSync(e);continue}}catch{}await xe(100)}return!1}function La(e){let t=Number(H(e.pid)),r=H(e.serverId);return!Number.isInteger(t)||t<=0||!r?null:_e(t,r)?t:null}function os(e){try{let t=JSON.parse(H(e.info)??"");return typeof t.url=="string"&&Number.isInteger(t.port)?t:null}catch{return null}}async function Ma(e){try{return(await fetch(hr(e,"/api/status"),{signal:AbortSignal.timeout(Oa)})).ok}catch{return!1}}async function ss(e,t){try{process.kill(e,"SIGTERM")}catch{}if(!await me(e,Ta)){try{process.kill(e,"SIGKILL")}catch{}if(!await me(e,2e3))throw new w(`The ${t} (pid ${e}) did not stop; stop it with \`${Oe()} stop\` and retry`)}}async function Ua(){let e=Yo();for(let t of Ko(e)){if(_e(t.pid,t.serverId)){try{process.kill(t.pid,"SIGTERM")}catch{}await me(t.pid,5e3)}try{Xo(e,t)}catch{}}}function Fa(e){let t=Object.fromEntries(_r.flatMap(r=>process.env[r]?[[r,process.env[r]]]:[]));Object.keys(t).length&&q.default.writeFileSync(e.agent,`${JSON.stringify(t)}
|
|
436
|
+
`)}function Ga(e){let t={...process.env,ARTIFACTS_HOST:e.host,ARTIFACTS_URL_HOST:e.urlHost};process.env.RYUGI_ARTIFACTS_COMMAND&&(t.RYUGI_ARTIFACTS_LAUNCHER=process.env.RYUGI_ARTIFACTS_COMMAND);for(let r of["RYUGI_ARTIFACTS_OWNER","RYUGI_ARTIFACTS_VERSION","RYUGI_ARTIFACTS_COMMAND","ARTIFACTS_OPEN_CMD","ARTIFACTS_ROOT"])delete t[r];return t}var Wa=e=>e.split(`
|
|
437
|
+
`).find(t=>t.includes('"server-started"')),Va=e=>e.split(`
|
|
438
|
+
`).find(t=>t.includes('"server-error"'));async function qa(e,t,r){let n=await fetch(hr(e,"/api/hub/projects"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:t.project,...r?{open:r}:{},...r&&process.env.ARTIFACTS_OPEN_CMD?{openCmd:process.env.ARTIFACTS_OPEN_CMD}:{}}),signal:AbortSignal.timeout(Ia)});if(!n.ok)throw new w(`The artifacts server refused this project: ${await n.text()}`)}async function mr(e,t){if(t.signal?.throwIfAborted(),e.artifact!==void 0&&!Y.test(e.artifact))throw new w(re);if(e.port!==void 0&&(!/^\d+$/.test(e.port)||Number(e.port)<1||Number(e.port)>65535))throw new w("--port must be a port number");e.urlHost||=e.host==="127.0.0.1"||e.host==="localhost"?"localhost":e.host,process.umask(63);let r=U(e.projectDir),n=ne();Ur(n.home),q.default.mkdirSync(r.state,{recursive:!0}),q.default.existsSync(At.default.join(r.state,".gitignore"))||q.default.writeFileSync(At.default.join(r.state,".gitignore"),`*
|
|
439
|
+
`);let o=process.env.RYUGI_ARTIFACTS_VERSION||"1.78.0",s=Re(n.projects).some(l=>l.dir===r.project),i=async(l,u)=>{Fa(r);let d=e.open&&!e.library&&(!u||!s);await qa(l,r,d?e.artifact??!0:void 0);let f=Pa(l,r,e.artifact);u&&(f.reused=!0);let k=await Na(f,l,r,e.artifact),S=Zo(r.project);if(t.signal?.throwIfAborted(),e.library&&e.open&&(process.env.ARTIFACTS_OPEN_CMD?await new Promise(O=>(0,Ve.execFile)(process.env.ARTIFACTS_OPEN_CMD,[l.url],()=>O())):await dr(l.url,[l.url]).catch(O=>t.log(O.message,"stderr"))),await t.ready(S?{...k,loginHint:S}:k),u&&s&&process.platform==="darwin"&&e.open&&e.openExisting&&e.artifact&&!process.env.ARTIFACTS_OPEN_CMD){let O=k.link;await dr(typeof k.cloudLink=="string"?k.cloudLink:O,[O]).catch(T=>t.log(T.message,"stderr"))}};if(!await Da(n.lock))throw new w("Another start is still starting the artifacts server; retry in a moment");let a=!0,c=()=>{if(a){a=!1;try{q.default.rmdirSync(n.lock)}catch{}}};try{t.signal?.throwIfAborted();let l=La(n),u=os(n);if(l&&!u){for(let R=0;R<ja&&oe(l)&&!u;R+=100)await xe(100),u=os(n);!u&&oe(l)&&await ss(l,"stopping artifacts server")}if(l&&u){let R=H(n.version)??"",_=rs(R,o),y=(u.host??"127.0.0.1")!==e.host||(u.urlHost??"localhost")!==e.urlHost||(u.cloudOrigin??as)!==_a(process.env)||e.port!==void 0&&String(u.port)!==e.port;if(_!=="replace"&&!y&&await Ma(u))return c(),await i(u,!0),0;await ss(l,"running artifacts server")}await Ua(),q.default.rmSync(n.info,{force:!0});let d=is.default.randomBytes(24).toString("hex");q.default.writeFileSync(n.serverId,`${d}
|
|
440
|
+
`),q.default.writeFileSync(n.version,`${o}
|
|
441
|
+
`);let k=[At.default.join(__dirname,"server.cjs"),`--artifacts-server-id=${d}`,...e.port?[`--port=${e.port}`]:[]],S=Ga(e);if(e.foreground){let R=(0,Ve.spawn)(process.execPath,k,{env:S,stdio:["ignore","pipe","pipe"]});q.default.writeFileSync(n.pid,`${R.pid}
|
|
442
|
+
`);let _=()=>{R.kill("SIGTERM")};if(t.signal)t.signal.addEventListener("abort",_,{once:!0});else for(let g of["SIGINT","SIGTERM"])process.on(g,_);gr.default.createInterface({input:R.stderr}).on("line",g=>t.log(g,"stderr"));let y=new Promise(g=>R.on("close",v=>g(v??1))),p=!1,h;gr.default.createInterface({input:R.stdout}).on("line",g=>{let v;try{v=JSON.parse(g)}catch{t.log(g,"stdout");return}if(v.type!=="server-started"||p){t.event?t.event(v):v.type==="server-error"||v.type==="error"?t.failure(v):t.log(JSON.stringify(v),"stderr");return}p=!0,c(),h=i(v,!1),h.catch(()=>_())});try{let g=await y;return await h,g}finally{if(t.signal)t.signal.removeEventListener("abort",_);else for(let g of["SIGINT","SIGTERM"])process.removeListener(g,_)}}try{q.default.renameSync(n.log,`${n.log}.1`)}catch{}let T=q.default.openSync(n.log,"w"),G=(0,Ve.spawn)(process.execPath,k,{env:S,detached:!0,windowsHide:!0,stdio:["ignore",T,T]});q.default.closeSync(T),G.unref(),q.default.writeFileSync(n.pid,`${G.pid}
|
|
443
|
+
`);for(let R=0;R<ns;R+=100){let _=H(n.log)??"",y=Wa(_);if(y){for(let h=0;h<10;h++){if(!oe(G.pid))throw new w(`Server started but was killed. Retry in a persistent terminal with: ${Oe()} start --project-dir ${r.project}${e.artifact?` --artifact ${e.artifact}`:""} --host ${e.host} --url-host ${e.urlHost} --foreground`);await xe(100)}return c(),await i(JSON.parse(y),!1),0}let p=Va(_);if(p)return t.failure(JSON.parse(p)),1;await xe(100)}throw new w(`Server failed to start within ${ns/1e3} seconds`)}finally{c()}}var ls={semantic:xt,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)"}}};var pe=C(require("node:fs"),1),us=C(require("node:path"),1);function Ha(e){for(let t of Re(e))pe.default.rmSync(us.default.join(Fr(t.dir),".state","server-info"),{force:!0})}function Ba({data:e}){return{heading:"Server",status:e.status,summary:e.status===e.reason?"":e.reason.replaceAll("_"," "),facts:[b("Scope",A(e,"scope")),b("Artifacts",A(e,"artifacts"))],sections:[]}}async function Ja(){let e=ne(),t=o=>{pe.default.rmSync(e.info,{force:!0}),Ha(e.projects),pe.default.mkdirSync(e.home,{recursive:!0,mode:448}),pe.default.writeFileSync(e.stopped,`${JSON.stringify({reason:o,timestamp:Math.floor(Date.now()/1e3)})}
|
|
444
|
+
`)};if(H(e.pid)===null)return{status:"not_running"};let r=Number(H(e.pid)),n=H(e.serverId)??"";if(!Number.isInteger(r)||r<=0||!/^[\w-]{32,64}$/.test(n)||!_e(r,n))return pe.default.rmSync(e.pid,{force:!0}),pe.default.rmSync(e.serverId,{force:!0}),t("stale_pid"),{status:"stale_pid"};try{process.kill(r,"SIGTERM")}catch{}if(!await me(r,7e3)){try{process.kill(r,"SIGKILL")}catch{}await me(r,1e3)}if(oe(r))return{status:"failed",error:"process still running"};for(let o of[e.pid,e.serverId])pe.default.rmSync(o,{force:!0});return t("stop"),{status:"stopped"}}var ds={name:"stop",summary:"Stop this machine's artifacts server; the artifacts are kept",usage:["[options]"],options:{},semantic:e=>I({id:"stop",mode:"finite",output:{formats:["brief","json","jsonl","quiet"],scalar:t=>t.status},async run(t,r){let n=r.effects.begin("stop","machine"),o=await Ja();return o.status!=="failed"&&r.effects.set(n,o.status==="not_running"?"none":"confirmed"),x({status:o.status==="stopped"?"stopped":o.status==="failed"?"failed":"unchanged",reason:o.status,scope:"machine",artifacts:"kept"},o.status==="failed"?{kind:"failed",error:{code:"E_SERVER_STOP_FAILED",message:o.error}}:{kind:"succeeded"})},present:Ba},e)};var br=require("node:child_process"),hs=C(require("node:fs"),1);var Et=C(require("node:fs"),1),ps=C(require("node:os"),1),It=C(require("node:path"),1);function fs(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let o=0;o<3;o++)if(r[o]!==n[o])return r[o]>n[o];return!1}var yr=e=>It.default.join(e.XDG_CACHE_HOME||It.default.join(ps.default.homedir(),".cache"),"ryugi","artifacts","latest.json");function ms(e,t,r){try{Et.default.mkdirSync(It.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}`;Et.default.writeFileSync(n,JSON.stringify({version:t,checkedAt:r})),Et.default.renameSync(n,e)}catch{}}var Z="ryugi-artifacts",Ot=["npm","pnpm","yarn","bun"],Ya=[["npx",["/_npx/"]],["pnpm dlx",["/pnpm/dlx/","/.pnpm-store/dlx/"]],["bunx",["/bunx-","/.bun/install/cache/"]]],za=[["pnpm",["/pnpm/global/"]],["yarn",["/yarn/global/"]],["bun",["/.bun/install/global/"]],["npm",[`/lib/node_modules/${Z}/`,`/npm/node_modules/${Z}/`]]];function Ka(e,t){if(t.RYUGI_ARTIFACTS_COMMAND)return{kind:"launcher"};let r=e;try{r=hs.default.realpathSync(e)}catch{}let n=r.replaceAll("\\","/").toLowerCase(),o=s=>s.some(i=>n.includes(i));for(let[s,i]of Ya)if(o(i))return{kind:"transient",runner:s};for(let[s,i]of za)if(o(i))return{kind:"global",pm:s};return n.includes("/node_modules/")?{kind:"unknown"}:{kind:"local"}}function gs(e,t){let r=`${Z}@${t}`;return{cmd:e,args:e==="npm"?["install","-g",r]:e==="yarn"?["global","add",r]:["add","-g",r]}}var Ie=({cmd:e,args:t})=>[e,...t].join(" ");async function Xa(e){let t=e.endsWith("/")?e:`${e}/`;try{let r=await fetch(new URL(`${Z}/latest`,t),{signal:AbortSignal.timeout(1e4)}),{version:n}=await r.json();if(r.ok&&typeof n=="string"&&/^\d+\.\d+\.\d+/.test(n))return n;throw new Error(`registry returned ${r.status}`)}catch(r){throw new w(`Could not get the latest ${Z} version from ${t}: ${r.message}`)}}function Qa(e,t){return e.kind==="transient"?`You ran ${Z} through ${e.runner}, which keeps no install to update. Run \`${e.runner} ${Z}@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 jt=class extends w{};async function Za(e,t={}){if(e.pm!==void 0&&!Ot.includes(e.pm))throw new w(`--pm must be one of ${Ot.join(", ")}`);let r=e.pm?{kind:"global",pm:e.pm}:Ka(e.file,e.env),n=await Xa(e.registry);t.beforeCache?.(),ms(yr(e.env),n,Date.now()),t.cacheRefreshed?.();let o={type:"update-check",current:e.current,latest:n,install:r.kind};if(!fs(n,e.current))return{...o,upToDate:!0,command:null};if(r.kind==="unknown"){let l=Ot.map(u=>` ${Ie(gs(u,n))}`).join(`
|
|
445
|
+
`);throw new jt(`Could not tell how ${Z} was installed (${e.file}). Install ${n} with one of:
|
|
446
|
+
${l}
|
|
447
|
+
or run \`${Z} update --pm <${Ot.join("|")}>\`.`)}if(r.kind!=="global")return{...o,upToDate:!1,command:null,message:Qa(r,n)};let s=gs(r.pm,n);if(e.check)return{...o,upToDate:!1,command:Ie(s)};let i=process.platform==="win32";t.beforeInstall?.();let a=t.log?["inherit","pipe","pipe"]:["inherit",2,2],c=i?(0,br.spawnSync)(Ie(s),{stdio:[...a],env:e.env,shell:!0}):(0,br.spawnSync)(s.cmd,s.args,{stdio:[...a],env:e.env});if(c.stdout?.length&&t.log?.(c.stdout.toString()),c.stderr?.length&&t.log?.(c.stderr.toString()),c.error)throw new w(`Could not run ${Ie(s)}: ${c.error.message}`);if(c.status!==0)throw new w(`${Ie(s)} exited with ${c.status??c.signal}`);return{type:"updated",from:e.current,to:n,pm:r.pm,command:Ie(s)}}var ys={name:"update",summary:"Install the newest ryugi-artifacts release with the package manager that installed this one",options:{check:{type:"boolean",help:"Compare versions only; do not install"},pm:{type:"string",value:"<npm|pnpm|yarn|bun>",help:"Use this package manager instead of detecting it"}},semantic:e=>I({id:"update",mode:"finite",output:{formats:["brief","json","jsonl"],fields:["current","latest","install","status","installed","message","command"]},async run(t,r){let n,o,s;try{s=await Za({current:"1.78.0",file:__filename,env:process.env,registry:process.env.npm_config_registry||"https://registry.npmjs.org/",check:!!e.values.check,pm:e.values.pm},{beforeCache(){o=r.effects.begin("release-cache",yr(process.env))},cacheRefreshed(){o!==void 0&&r.effects.confirm(o)},beforeInstall(){n=r.effects.begin("install",Z)},log:r.diagnostic})}catch(a){throw a instanceof jt?new m({code:"E_INSTALL_UNKNOWN",message:a.message},"action_required"):a}s.type==="updated"&&n!==void 0&&r.effects.confirm(n,{from:s.from,to:s.to});let i=s.type==="updated"?{current:s.to,latest:s.to,install:"global",status:"updated",installed:!0,command:s.command}:{current:s.current,latest:s.latest,install:s.install,status:s.upToDate?"up_to_date":"available",installed:!1,command:s.command,...s.message?{message:s.message}:{}};return x(i,void 0,{effects:r.effects.snapshot(),actions:i.install==="launcher"&&i.status==="available"?[E(["start","--background","--no-open","--project-dir",e.projectDir],"Restart server")]:[]})},present:ec},e)};function ec({data:e}){return{heading:"Update",status:e.status,facts:[b("Current",A(e,"current"),!0),b("Latest",A(e,"latest")),b("Install",A(e,"install")),...e.message?[b("Advice",A(e,"message"))]:[]],sections:[]}}var De=[ls,ds,$n,Mo,No,Gn,jn,Uo,io,Vn,ys,ho];function wr(e=process.stdout,t=process.stderr){let r=new WeakMap;for(let n of[e,t])n.on("error",o=>r.set(n,o));return{write(n,o){let s=n==="stdout"?e:t,i=r.get(s);return i?Promise.reject(i):new Promise((a,c)=>s.write(o,l=>l?c(l):a()))}}}function vr(e){process.exitCode=e}var vs=C(require("node:fs"),1);function bs(e){return(t,r,n)=>{let o=["--project-dir",e.projectDir],s=typeof e.values.artifact=="string"?e.values.artifact:void 0,i=[...o,...s?["--artifact",s]:[]];if(n.some(a=>a.state==="unknown")){let a;if(t.startsWith("comment")&&s)a=["comment","list",...i,...s.startsWith("verify/")?[]:["--sections","all",...t.endsWith(".ack")?[]:["--all"],"--detail"]];else if(t.startsWith("changes"))a=["changes",...i,"--detail"];else if(t.startsWith("publish"))a=["publish","--list",...o,...s&&n.some(c=>["share-key","revoke-key"].includes(c.operation)&&c.state==="unknown")?["--artifact",s]:[]];else if(t==="config")a=["config",...o];else if(t.startsWith("modules"))a=["modules",...i];else if(t==="update")a=["--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."}];a=["get",...o]}return[{...E(a,"Verify state"),reason:"Inspect current state before any retry; an operation may already have completed."}]}return r?.code==="E_SERVER_NOT_RUNNING"||r?.code==="E_SERVER_UNREACHABLE"?[E(["start","--background","--no-open",...i],"Start server")]:r?.code==="E_ARGUMENT_INVALID"||r?.code==="E_OPTION_CONFLICT"?[E([t.split(".")[0],...e.positionals[0]&&t.startsWith("comment")?[e.positionals[0]]:[],"--help"],"Help")]:r?Se(r):[]}}async function qe(e,t,r,n){return Mt({id:e,mode:"finite",output:{formats:[r.format]},run(){throw t},present(){return{heading:"Error",status:"failed",facts:[],sections:[]}}},void 0,{...r,fields:void 0,detail:!1},n)}function ws(e,t){return{id:e,mode:"finite",output:{formats:["brief","json","jsonl"],fields:["text","version","capabilities","commands"]},run(){return x(t)},present({data:r}){return r.version?{heading:`ryugi ${r.version}`,status:"",facts:[],sections:[]}:{heading:"Help",status:"",facts:[],sections:[{kind:"content",key:"text",text:r.text}]}}}}async function ks(e,t,r,n,o,s,i){let[a,...c]=e,l=t.find(d=>d.name===a),u;try{if(l?.positionals&&l.usage?.some(f=>/^[a-z]+\s/.test(f))&&(u=fe(c.filter(f=>f!=="--help"&&f!=="-h"),l.options,l.positionals).positionals[0]),a==="--version"||a==="-v")return fe(c,{},0),await I(ws("version",{text:n,version:n,capabilities:["reviewBundlesV1"]}),void 0).run(o,s);if(a==="--help"||a==="-h"||l&&Er(c)){l||fe(c,{},0);let f=l?Or(l,u):jr(t,r);if(l&&["start","check"].includes(l.name)){let k=fe(c.filter(S=>S!=="--help"&&S!=="-h"),l.options,l.positionals);typeof k.values.artifact=="string"&&(f+=`
|
|
448
|
+
|
|
449
|
+
${ct(k.values.artifact)}`)}return await I(ws("help",{text:f,commands:t.map(({name:k,summary:S})=>({name:k,summary:S}))}),void 0).run(o,s)}if(!l&&(!a||a.startsWith("-")||(()=>{try{return vs.default.statSync(a).isDirectory()}catch{return!1}})())){let f=fe(e,r,1);if(f.positionals.length&&f.values["project-dir"])throw new m({code:"E_ARGUMENT_INVALID",message:"Specify one project directory."});return f.projectDir=f.values["project-dir"]??f.positionals[0]??f.projectDir,f.values.foreground=!0,f.values.open=!f.values["no-open"],await xt(f,"browse").run(o,s,i)}if(!l)throw new m({code:a?.includes("/")?"E_PROJECT_NOT_FOUND":"E_UNKNOWN_COMMAND",message:a?`Unknown command: ${a}`:"Use start --foreground to browse with semantic output."});let d;try{d=fe(c,Nt(l,u),l.positionals)}catch(f){throw new m({code:"E_ARGUMENT_INVALID",message:f.message})}return d.projectDir=U(d.projectDir).project,await l.semantic(d).run(o,s,i,bs(d))}catch(d){let f=d instanceof w?new m({code:"E_ARGUMENT_INVALID",message:d.message}):d;return f instanceof Error&&Object.assign(f,{actions:[E([...l?[l.name,...u&&l.usage?.some(k=>k.startsWith(`${u} `))?[u]:[]]:[],"--help"],"Help")]}),qe(l?.name??a??"browse",f,o,s)}}var tc={"no-open":{type:"boolean",help:"Print the URL without opening a browser"}};async function rc(e){let t=Object.assign({},J,...De.map(a=>a.options)),r=wr(),n;try{n=$t(e,t,sn(e,t))}catch(a){return qe(e[0]??"browse",a,$t(e,t).options,r)}if(n.error)return qe(e[0]??"browse",n.error,n.options,r);let o=new AbortController,s=()=>o.abort("SIGINT"),i=()=>o.abort("SIGTERM");process.on("SIGINT",s),process.on("SIGTERM",i);try{return await ks(e,De,tc,"1.78.0",n.options,r,o.signal)}finally{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",i)}}rc(process.argv.slice(2)).then(vr,e=>qe(process.argv[2]??"browse",e,{format:"brief"},wr()).then(vr));
|