@aventurevc/aventure-cli 0.8.19 → 0.8.20

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.
@@ -1,37 +1,37 @@
1
- import{$ as e,C as t,D as n,E as r,Ft as i,It as a,Pt as o,Q as s,Rt as c,T as l,V as u,X as d,Y as f,_ as p,at as m,b as h,c as g,et as _,f as v,g as y,h as ee,it as te,l as ne,m as re,nt as b,o as ie,ot as x,p as ae,q as oe,s as se,st as ce,tt as le,u as ue,x as de,z as fe}from"./auth-D_S3IqOC.js";import{C as S,D as pe,R as me,_ as he,a as ge,k as C,v as w}from"./person-owner-BqBLyw4S.js";import{A as _e,C as ve,D as ye,M as T,N as be,O as xe,S as Se,T as Ce,a as we,b as Te,c as Ee,d as De,g as Oe,j as ke,k as Ae,l as je,m as Me,o as Ne,r as Pe,s as Fe,t as Ie,u as Le,v as Re,w as ze,x as Be,y as Ve}from"./oauth-bearer-credential-CxdOmM7t.js";import{_ as He,a as Ue,c as We,d as Ge,f as Ke,g as qe,h as Je,l as Ye,m as Xe,n as Ze,o as E,p as Qe,r as D,s as $e,t as O,u as et}from"./openapi-commands-DxXrK79n.js";import{a as tt}from"./text-field-C6AhgJXF.js";import{a as nt,n as rt,o as it,r as at,t as ot}from"./text-response-NPhfN0Zd.js";import{n as st,r as ct,t as lt}from"./oauth-login-B-A9XcJV.js";import{spawnSync as ut}from"node:child_process";import{basename as dt,dirname as k,resolve as A,sep as j}from"node:path";import{copyFileSync as ft,existsSync as pt,lstatSync as mt,mkdirSync as ht,mkdtempSync as gt,readFileSync as _t,readlinkSync as vt,realpathSync as yt,renameSync as bt,rmdirSync as xt,unlinkSync as St,writeFileSync as Ct}from"node:fs";import M,{stderr as N,stdin as wt}from"node:process";import{TextDecoder as Tt,inspect as Et}from"node:util";import{fileURLToPath as Dt}from"node:url";import{readFile as Ot}from"node:fs/promises";import{webcrypto as kt}from"node:crypto";import{homedir as At,hostname as jt,platform as Mt}from"node:os";import{setTimeout as Nt}from"node:timers/promises";import{createInterface as Pt}from"node:readline/promises";function Ft(e,t,n){let r={...n};for(let n of t.parameter){let t=n.envName;if(t===void 0)continue;let i=process.env[t]?.trim();if(i===void 0||i.length===0)continue;let a=r[n.optionKey];if(a!==void 0&&(typeof a!=`string`||a!==i))return{...m(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return x(`Environment-bound options applied`,r)}function It(e,t,n){if(!P(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!Xt(n,r.name))continue;let a=Yt(n,r.name);if(typeof a!=`string`||a!==i)return`${e} ${r.name} in --from-file conflicts with ${t}; omit the field or use ${i}.`}return null}function Lt(e){let t=new Set(e.parameter.map(({name:e})=>e));return e.kind===`multipart`?e.requiredPath:e.requiredPath.filter(e=>!t.has(e))}function Rt(e,t,n,r=!1){if(r||!$t(t)||!Array.isArray(n))return tn(e,t,n);for(let[r,i]of n.entries()){let n=tn(e,t,i,r);if(!n.ok)return n}return x(`Body value assigned`,null)}function zt(e,t,n,r){return tn(e,t,r,n)}function Bt(e){let t=[];for(let n of e.split(`.`)){let e=rn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Vt(e,t){let n=Bt(t);if(n===null)return null;let r=Jt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:qt(r)}:null}function Ht(e,t){if($t(e.name)||e.schemaType===`array`)return x(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return x(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?x(`Scalar body option selected`,t[0]):m(`${n} was already given; pass it once.`)}var Ut=/^(?<row>\d+):(?<item>.*)$/su;function Wt(e,t){let n=Bt(e.name);if(e.schemaType!==`array`||n===null||t===void 0||typeof t==`boolean`)return null;let r=new Map,i=[];for(let e of typeof t==`string`?[t]:t){let t=Ut.exec(e)?.groups,n=t?.row,a=t?.item;if(n===void 0||a===void 0){i.push(e);continue}let o=r.get(Number(n));o===void 0?r.set(Number(n),[a]):o.push(a)}return r.size===0?null:{container:n,rows:r,plain:i}}function Gt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Bt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Kt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Vt(r,i.name);if(a===null)continue;if(a.firstHole!==null)return m(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Wt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return m(`${o} fills one ${a.path}[] row's list, so ${e} cannot also build ${a.rowCount} ${a.path}[] rows from direct options — prefix each value with its 0-based ${a.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function qt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Jt(e,t){let n=e;for(let e of t){if(!P(n))return;n=n[e]??null}return n}function Yt(e,t){if(!$t(t))return Jt(e,t.split(`.`))}function Xt(e,t){return Qt(e,t.split(`.`))}function Zt(e,t,n){if(!P(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&Xt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function Qt(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=rn(n);if(!P(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>Qt(e,r)):Qt(a,r)}function $t(e){return e.split(`.`).some(e=>rn(e).isArray)}function en(e,t){return e.parameter.length===0||!P(t)?null:on(t,[],an(e.parameter))}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=rn(o),c=e===i.length-1,l=nn(a,s,t,c,n,r);if(!l.ok||l.data===null)return m(l.summary,l.warnings);if(c)return x(`Body value assigned`,null);a=l.data}return m(`${t} is not a valid body option path.`)}function nn(e,t,n,r,i,a){let o=()=>m(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,x(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,x(`Body path created`,e)}return P(c)?x(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,x(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,x(`Body path created`,n)}return P(s)?x(`Body path stepped`,s):o()}function rn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function an(e){let t=new Set,n=new Set;for(let r of e){let e=`${r.name}${r.schemaType===`array`?`[]`:``}`;t.add(e);let i=e.split(`.`);for(let e=1;e<i.length;e+=1)n.add(i.slice(0,e).join(`.`))}return{leaf:t,prefix:n}}function on(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=on(r,t,n);if(e!==null)return e}return null}if(!P(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!sn(a,n)){if(!cn(e))continue;return{path:a,suggestion:ln(e,n)}}let o=on(i,e,n);if(o!==null)return o}return null}function sn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function cn(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function ln(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``;return[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:un(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path))[0]?.path}function un(e,t){let n=t.replace(/\[\]$/u,``).toLowerCase();return n===e?0:n.endsWith(e)||e.endsWith(n)?1:n.includes(e)||e.includes(n)?2:1/0}function dn(e,t){let n=new Map;for(let e of t){let t=e.flag?.split(` `)[0];t!==void 0&&n.set(t,t===`--from-file`?{...e,inputType:`file`}:e)}for(let t of e){let e=t.long===void 0?void 0:n.get(t.long);e!==void 0&&t.helpGroup(qe(e))}e.sort((e,t)=>{let r=e.long===void 0?void 0:n.get(e.long),i=t.long===void 0?void 0:n.get(t.long);return r!==void 0&&i!==void 0?yn(r,i):r===void 0?i===void 0?0:1:-1})}function fn(e){let t=new Map;for(let n of e)for(let e of n.parameter){let r=e.flag.split(` `)[0]??e.flag,i=t.get(r);i===void 0?t.set(r,{variant:[{descriptor:n,parameter:e}]}):t.set(r,{variant:[...i.variant,{descriptor:n,parameter:e}]})}return[...t.values()]}function pn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function mn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:_n(e,t)})),n=t[0];return n===void 0?``:t.every(({text:e})=>e===n.text)?`${n.text===``?``:`${n.text} `}Request content: ${t.map(({contentType:e})=>e).join(`, `)}.`:t.map(({contentType:e,text:t})=>`${e}: ${t}`).join(` `)}function hn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function gn(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?He(n):`${He(n)} Required JSON paths: ${r.join(`, `)}.`}function _n(e,t){let n=Xe(t.description,void 0),r=e.kind!==`multipart`&&$t(t.name),i=e.kind!==`multipart`&&t.optionKey!==t.name&&/^\w+$/u.test(t.name);return`${n}${r?` Repeat to add another value.`:``}${i?` --from-file JSON key: ${t.name}.`:``}${vn(e,t)}`}function vn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Bt(t.name);return n===null?``:` Prefix each value with its 0-based ${n}[] row index, as 0:value, to fill more than one ${n}[] row. A leading digits-and-colon is always read as that index, so name the row of a value that starts the same way, as 0:0:00 for the value 0:00.`}function yn(e,t){return Je(e)-Je(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function bn(e){let t;try{t=e===`-`?await xn():await Ot(e,`utf8`)}catch(t){return m(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return x(`No input provided`,null);let e=JSON.parse(t);return x(`Input parsed`,e)}catch(e){return m(`Input is not valid JSON: ${e.message}`)}}async function xn(){if(process.stdin.isTTY)throw Error(`--from-file - requires JSON on stdin, but stdin is a TTY`);process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}var Sn=`--content-type`;function Cn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),a=t.requestBody??[];if(a.length>1&&r(Sn)){let t=a.map(({contentType:e})=>e);e.addOption(new i(`${Sn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Tn(a)))}if(Wn(t)&&r(`--from-file`)){let n=a[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new i(`--from-file <path>`,gn(n,n.requiredPath)).argParser(Dn(`--from-file`)))}let o=fn(a).filter(e=>r(F(e.variant[0].parameter)));for(let t of o.toSorted((e,t)=>yn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],o=new i(pn(t),a.length>1?mn(t):_n(n,r));a.length===1&&r.envName!==void 0&&o.env(r.envName);let s=a.length===1?hn(n,r.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(wn):$t(r.name)||r.schemaType===`array`?o.argParser(En):o.argParser(Dn(r.flag)),e.addOption(o),o.envVar!==void 0&&e.on(`optionEnv:${o.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}Un(e,t,o)}function wn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Tn(e){return(t,r)=>{if(r!==void 0)throw new c(`${Sn} was already given; pass it once.`);let i=n(e,t);if(!i.ok)throw new c(i.summary);return t}}function En(e,t){return[...t??[],e]}function Dn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new c(`${t} was already given; pass it once.`);return e}}async function On(e,t){let r=typeof t.contentType==`string`?t.contentType:void 0,i=n(e.requestBody??[],r);if(!i.ok||i.data===null)return m(i.summary,i.warnings);let a=i.data;if(a===void 0)return x(`No body`,void 0);let o=kn(e,a,t);if(o!==null)return m(o);let s=Ft(e.operationId,a,t);if(!s.ok)return m(s.summary,s.warnings);t=s.data;let c=An(a,t);if(c!==null)return m(c);let l=await Pn(t);if(!l.ok)return m(l.summary,l.warnings);let u=Zt(e.requestBody??[],a,l.data);if(u!==null)return m(u);let d=Nn(e.operationId,a,l.data);if(!d.ok)return d;let f=It(e.operationId,a,l.data);if(f!==null)return m(f);let p=Fn(e.operationId,a,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return a.required?m(Hn(e.operationId,a)):x(`No body`,void 0);let h=Ln(e.operationId,l.data,p.data);if(!h.ok||h.data===void 0)return h;if(a.schemaType===`array`&&!Array.isArray(h.data))return m(`${e.operationId} requires a JSON array body.`);if(a.parameter.length>0&&!P(h.data)){let t=a.kind===`multipart`?` keyed by multipart part name`:` body`;return m(`${e.operationId} requires a JSON object${t}.`)}let g=Mn(a,h.data);if(g.length>0)return m(`${e.operationId} requires body option(s): ${g.join(`, `)}`);let _=h.data,v=P(_)?Lt(a).filter(e=>!Xt(_,e)):[];return v.length>0?m(jn(e.operationId,a,v)):h}function kn(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${F(t)} requires ${Sn} ${i.join(` or `)}.`}return null}function An(e,t){for(let n of e.cliConflicts??[]){let e=n.filter(e=>t[e]!==void 0);if(e.length>1)return`Options ${e.join(`, `)} cannot be used together.`}return null}function jn(e,t,n){let r=`${e} requires JSON body path(s): ${n.join(`, `)}`;return t.kind===`multipart`?`${r}. ${n.includes(`body`)?`For multipart --from-file, wrap the endpoint JSON under top-level "body".`:`For multipart --from-file, put the missing nested path(s) inside top-level "body".`}`:r}function Mn(e,t){return P(t)?e.parameter.filter(e=>e.required&&!Xt(t,e.name)).map(F):[]}function Nn(e,t,n){let r=en(t,n);if(r===null)return x(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return m(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Pn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return x(`No body file`,void 0);let n=await bn(t);if(!n.ok)return m(n.summary,n.warnings);let r=ce.safeParse(n.data);return r.success?x(`Input parsed`,r.data):m(`Input is not valid JSON value: ${r.error.message}`)}function Fn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Ht(e,n[e.optionKey]);if(!a.ok||a.data===null)return m(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=In(t,n,r,e,o);if(!s.ok)return m(s.summary,s.warnings);i=!0}if(!i)return x(`No direct body options`,void 0);let a=Kt(e,t,n,r);return a===null?x(`Direct body options parsed`,r):a}function In(e,t,n,r,i){let a=Wt(r,i);if(a===null){let e=Bn(r,i);return e.ok?Rt(n,r.name,e.data,r.schemaType===`array`):m(e.summary,e.warnings)}if(a.plain.length>0)return m(`${F(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=Gt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return m(`${F(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=Vn(r.name,r.itemSchemaType,e);if(!t.ok)return m(t.summary,t.warnings);i.push(t.data)}let a=zt(n,r.name,e,i);if(!a.ok)return a}return x(`Body value assigned`,null)}var F=e=>e.flag.split(` `)[0]??e.name;function Ln(e,t,n){if(t===void 0)return x(`Direct body parsed`,n);if(n===void 0)return x(`Input parsed`,t);if(P(t)&&P(n))try{return x(`Input parsed`,Rn(t,n))}catch(t){return m(`${e} ${t.message}`)}return m(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Rn(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Array.isArray(t)&&Array.isArray(r))throw Error(`cannot combine --from-file array '${e}' with array body options at the same key — move the per-item fields inside the matching '${e}[]' object(s) in the file body.`);if(t!==void 0&&zn(t)!==zn(r))throw Error(`cannot combine --from-file ${zn(t)} '${e}' with ${zn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=P(t)&&P(r)?Rn(t,r):r}return n}function zn(e){return Array.isArray(e)?`array`:P(e)?`object`:`scalar`}function Bn(e,t){if(typeof t==`boolean`)return x(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Vn(e.name,e.schemaType,t??``);let n=[],r=$t(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Vn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return x(`Body value parsed`,n)}function Vn(e,t,n){if(t===`boolean`)return n===`true`?x(`Body value parsed`,!0):n===`false`?x(`Body value parsed`,!1):m(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?m(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?m(`${e} must be an integer.`):x(`Body value parsed`,i)}return x(`Body value parsed`,n)}function Hn(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(F).join(`, `)}`;let r=Lt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(F).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Un(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:Sn,location:`body`}),Wn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),dn(e.options,r)}function Wn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Gn(e){let t=te(e);return er(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Kn(e){er(e);let t=ot(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
- `)?t:`${t}\n`),qn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&Xn(e.problem),qn(e)}function qn(e){e.ids.length>0&&process.stdout.write(` ids: ${e.ids.join(`, `)}\n`);for(let[t,n]of Object.entries(e.counts))process.stdout.write(` ${t}: ${n}\n`);for(let t of e.references)process.stdout.write(` ref: ${t}\n`);if(e.truncation!==void 0){let t=e.truncation.omitted.join(`, `);process.stdout.write(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${t}\n`),process.stdout.write(` recovery: ${e.truncation.recovery}\n`)}for(let t of e.warnings)process.stdout.write(` warn: ${t}\n`)}function I(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?te(t):t;er(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Jn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?Gn(t):t;e.mode===`text`&&Kn(n),n.ok||(process.exitCode=1)}function Jn(e){return typeof e!=`object`||!e||Array.isArray(e)||!Reflect.has(e,`method`)||!Reflect.has(e,`endpoint`)||!(`response`in e)||e.response===void 0?e:e.response}function Yn(e,t){let n=rt(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
3
- `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function Xn(e){typeof e.code==`string`&&process.stdout.write(` code: ${e.code}\n`),typeof e.detail==`string`&&process.stdout.write(` detail: ${e.detail}\n`),typeof e.hint==`string`&&process.stdout.write(` hint: ${e.hint}\n`),typeof e.suggestion==`string`&&process.stdout.write(` suggestion: ${e.suggestion}\n`);let t=Object.entries(e.suggestions??{});if(t.length>0){let e=t.map(([e,t])=>`${e}=${t}`).join(`; `);process.stdout.write(` suggestions: ${e}\n`)}typeof e.requiredRole==`string`&&process.stdout.write(` requiredRole: ${e.requiredRole}\n`),Zn(e),Qn(`unknownParameters`,e.unknownParameters),Qn(`validParameters`,e.validParameters),$n(e.resolution)}function Zn(e){let t=[];typeof e.limitType==`string`&&t.push(`limitType=${e.limitType}`),typeof e.used==`number`&&t.push(`used=${e.used}`),typeof e.limit==`number`&&t.push(`limit=${e.limit}`),typeof e.remaining==`number`&&t.push(`remaining=${e.remaining}`),typeof e.resetAt==`string`&&t.push(`resetAt=${e.resetAt}`),typeof e.windowSeconds==`number`&&t.push(`windowSeconds=${e.windowSeconds}`),typeof e.retryAfterSeconds==`number`&&t.push(`retryAfterSeconds=${e.retryAfterSeconds}`),t.length>0&&process.stdout.write(` meter: ${t.join(` `)}\n`)}function Qn(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function $n(e){if(e==null)return;let t=[`action=${e.action}`];typeof e.parameter==`string`&&t.push(`parameter=${e.parameter}`),typeof e.fieldPath==`string`&&t.push(`fieldPath=${e.fieldPath}`),typeof e.endpoint==`string`&&t.push(`endpoint=${e.endpoint}`),e.acceptedValue!==null&&e.acceptedValue!==void 0&&e.acceptedValue.length>0&&t.push(`acceptedValue=${e.acceptedValue.join(`, `)}`),typeof e.retryable==`boolean`&&t.push(`retryable=${e.retryable}`),process.stdout.write(` resolution: ${t.join(` `)}\n`)}function er(e){e.ok&&e.warnings.length===0||u({component:`aventure-cli`,event:e.ok?`command_warning`:`command_failed`,message:e.warnings.length>0?e.warnings.join(` | `):e.summary,fields:{warningCount:e.warnings.length,summary:e.summary}})}function tr(e,t,n=f().bin[0]){let r=e.limit===void 0?void 0:Number(e.limit);if(r!==void 0&&(e.limit?.trim()===``||!Number.isInteger(r)||r<0))return m(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=at(e.q??``,ir(t,n).filter(t=>cr(t,e)),e=>({...e,cliPath:e.cli.path,enumParameter:e.flags.map(({choices:e,location:t})=>({values:e,direct:t!==`body`})),parameterName:e.flags.flatMap(({wireName:e,optionKey:t})=>[e,t]),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),a=i.slice(0,r);return x(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function nr(e,t,n=f().bin[0]){let r=ir(t,n),i=e.operationId===void 0?rr(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let t=xr(e.command??``),i=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${t} `));return i.length>0?m(`${t} is a command group; show one of its subcommands.`,[`Run \`${n} command-catalog show --command "<subcommand>"\` with one of:`,...i]):m(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`])}return x(`Generated operation detail`,{operation:i,usage:ur(i,r)})}function rr(e,t){if(t===void 0)return;let{bin:n}=f(),r=xr(t,n);return e.find(e=>xr(e.cli.command,n)===r)}function ir(e,t){return e.map(e=>{let n=e.requestBody??[],i=[...e.parameters.map(e=>ar(e)),...n.flatMap(e=>e.parameter.map(t=>ar(t,n.length>1?e.contentType:void 0))),...or(n)],a=[t,...e.cliPath].join(` `),o=l(e.intent),s=e.method===`DELETE`||e.intent===`delete`,c=n[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:s,auth:e.auth,cli:{command:a,path:e.cliPath},mcpTool:e.binaryResponse?null:r(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&n.length>1?{contentType:c.contentType}:{},required:c?.required??!1,description:c?.description??``,requiredPath:c?.requiredPath??[]},flags:i,errorResponse:e.errorResponse,summary:e.summary,description:e.description,deprecated:e.deprecated}})}function ar(e,t){let n=e.flag.split(/\s+/u);return{name:n[0]??e.flag,optionKey:e.optionKey,wireName:e.name,location:e.location,required:e.required,placeholder:n.length<=1?null:n.slice(1).join(` `),description:e.description,choices:e.choices??[],...t===void 0?{}:{contentType:t}}}function or(e){if((e?.length??0)<=1)return[];let t=e?.map(({contentType:e})=>e)??[];return[{name:`--content-type`,optionKey:`contentType`,wireName:`Content-Type`,location:`body`,required:!1,placeholder:`<media-type>`,description:`Select the request content type; omit for ${t[0]}.`,choices:t}]}function sr(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function cr(e,t){return!(t.root!==void 0&&!lr(e,t.root)||t.scope!==void 0&&t.scope!==`all`&&t.scope!==e.scope||t.mutates!==void 0&&t.mutates!==`any`&&t.mutates===`true`!==e.mutates||t.destructive!==void 0&&t.destructive!==`any`&&t.destructive===`true`!==e.destructive||t.intent!==void 0&&t.intent!==`all`&&t.intent!==e.intent||t.method!==void 0&&t.method!==`all`&&t.method!==e.method)}function lr(e,t){let n=it(t);return n.length===0||it(e.cli.path.at(0)??``)===n}function ur(e,t){let n=sr(e),r=n.filter(e=>e.required),i=n.filter(e=>!e.required);return[`cli: ${e.cli.command}`,`${e.method} ${e.path}`,`operationId: ${e.operationId}`,`resource: ${e.resource}`,`intent: ${e.intent}`,`scope: ${e.scope}`,`mutates: ${e.mutates}`,`destructive: ${e.destructive}`,`mcpTool: ${e.mcpTool??`unavailable (binary CLI operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,L(`required path flags`,r,`path`),L(`required query flags`,r,`query`),L(`required header flags`,r,`header`),L(`required body flags`,r,`body`),L(`optional path flags`,i,`path`),L(`optional query flags`,i,`query`),L(`optional header flags`,i,`header`),L(`optional body flags`,i,`body`),...gr(e,t),...dr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
- `)}function dr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var fr=[`-id`,`-slug`,`-url`],pr=[`--id`,`--slug`,`--url`],mr=`--from-file "<path>"`;function hr(e,t,n=f().bin[0]){let r=ir(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:gr(i,r)}function gr(e,t){return[`example: ${[e.cli.command,...vr(e),`--data`].join(` `)}`,..._r(e,t)]}function _r(e,t){return sr(e).flatMap(e=>{if(!e.required||!e.optionKey.endsWith(`Id`))return[];let n=`${e.optionKey.slice(0,-2)}Slug`,r=t.find(e=>e.method===`GET`&&/\/lookup(?:-exact)?$/u.test(e.path)&&e.flags.some(e=>e.optionKey===n)),i=r?.flags.find(e=>e.optionKey===n);if(r===void 0||i===void 0)return[];let a=`${r.cli.command} ${br(i)} --data`,o=t.find(e=>e.method===`POST`&&e.path===r.path.replace(/-exact$/u,``)),s=o?.flags.find(e=>e.optionKey===`name`),c=`lookup: ${e.name} from a slug: ${a}`;return o===void 0||s===void 0?[c]:[c,`lookup: ${e.name} from a name or URL: ${o.cli.command} ${br(s)} --data, then match.owner.${e.optionKey} when status is MATCHED`]})}function vr(e){let t=sr(e).filter(e=>e.required),n=(t.length>0?t:yr(e)).map(br);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,mr]:n}function yr(e){let t=new Set;nt(t,e.resource);for(let n of fr)for(let r of t){let t=e.flags.find(e=>e.name===`--${r}${n}`);if(t!==void 0)return[t]}for(let t of pr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function br(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function L(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function xr(e,t=f().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var Sr=`dist/aventure-cli/command-catalog.compact.txt`,Cr=` · `,wr=`-`;function Tr(e=f().bin[0]){return A(Er(k(Dt(import.meta.url)),e),Sr)}function Er(e,t){let n=e;for(;;){if(pt(A(n,`package.json`)))return n;let r=k(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Dr(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Or(e,t,n,r=f().bin[0]){let i=tr(e,t,r);if(!i.ok||i.data===null){I({mode:n},i);return}Ar({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Mr(i.data,jr(e.format,`lines`)),summary:`Generated operation matches`})}function kr(e,t,n,r=f().bin[0]){let i=nr(e,t,r);if(!i.ok||i.data===null){I({mode:n},i);return}Ar({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Nr(i.data,jr(e.format,`usage`)),summary:`Generated operation detail`})}function Ar(e){let t=e.mode,n=jr(e.opts.format,e.defaultFormat),r=e.opts.text===!0||e.opts.allFields===!0;if(e.opts.output===void 0&&r&&(n===`json`||n===`ndjson`)){I({mode:t},m(`--text or --all-fields cannot be combined with --format json or ndjson`,[`Omit the text flag for machine output, or use --format lines, compact, or text.`]));return}let i=e.opts.output===void 0&&t===`text`&&`count`in e.data&&e.data.count.returned===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
5
- `)?i:`${i}\n`;if(e.opts.output!==void 0){Ct(e.opts.output,a),I({mode:t},x(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:Rr(e.data)}));return}if(t===`text`){process.stdout.write(a);return}I({mode:t},x(e.summary,e.data,{counts:Rr(e.data)}))}function jr(e,t){return e??t}function Mr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
6
- `):t===`text`?Ir(e.operation):t===`compact`?e.operation.map(Pr).join(`
7
- `):e.operation.map(Lr).join(`
8
- `)}function Nr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Lr(e.operation):t===`compact`?Pr(e.operation):e.usage}function Pr(e){let t=Fr(e);return[e.cli.command,e.summary,t.length===0?wr:t.join(` `)].join(Cr)}function Fr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Ir(e){return e.map(e=>`${e.cli.command}\n ${Lr(e)}`).join(`
9
- `)}function Lr(e){let t=Fr(e);return[R(`operationId`,e.operationId),R(`scope`,e.scope),R(`mutates`,String(e.mutates)),R(`destructive`,String(e.destructive)),R(`intent`,e.intent),R(`resource`,e.resource),R(`cli`,e.cli.command),e.mcpTool===null?``:R(`mcpTool`,e.mcpTool),R(`method`,e.method),R(`path`,e.path),R(`auth`,e.auth),R(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),R(`requiredFlags`,t.join(` `)),R(`bodyKind`,e.body.kind??``),R(`bodyRequired`,String(e.body.required)),R(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function R(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Rr(e){return`count`in e?e.count:{returned:1}}function zr(e,t,n=f().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show full documentation for a command, or ask a question`).description([`Show a command's full documentation offline. Select it by command path,`,"operationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.","`help ask <question>` or `help --ask <question>` answers a platform question."].join(`
10
- `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new Br(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Kr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),D(r),r.action(async function(r){let a=this.optsWithGlobals();if(a.help&&r.length===0){this.outputHelp();return}if(!a.help&&i!==void 0&&a.ask!==void 0){let e=E(a);if(r.length>0){I({mode:e},m(`Use either a command path or --ask, not both.`));return}I({mode:e},await Xr(i,a.ask,a.environment,e));return}let o=Yr(e,r),s=t.find(t=>o!==void 0&&Yr(e,t.cliPath)===o);if(a.help||o!==void 0&&s===void 0){o===void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),o.outputHelp();return}let c=s===void 0?Jr(r,t):x(`Resolved by command path`,{operationId:s.operationId});if(c.ok&&c.data?.command!==void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),!c.ok||c.data===null){I({mode:E(a)},c);return}kr({...a,...c.data},t,E(a,`text`),n)}),Gr(e,t,n)}var Br=class extends i{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},Vr=2,Hr=6,Ur={formatHelp(e,t){let n=n=>a.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),n));if(t.visibleCommands(e).length===0)return n({});let r=t.padWidth(e,t),i={padWidth:()=>r,visibleOptions:()=>[],showGlobalOptions:!1},o=n({...i,visibleCommands:()=>[]}),s=n({padWidth:()=>r,visibleCommands:()=>[]}).slice(o.length);return n(i)+s},visibleCommands(e){let t=a.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>!Ke.has(e.name())):t},subcommandTerm(e){let t=a.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,n,r){let i=r.helpWidth??80,o=i-t-4;return n===``||o>=r.minWidthToWrap?a.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Vr)}${e}\n${Wr(n,i,r)}`}};function Wr(e,t,n){return n.boxWrap(e,t-Hr).replace(/^/gmu,` `.repeat(Hr))}function Gr(e,t,n){for(let r of t){let i=Yr(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp();e.prepareContext({helpWidth:i.configureOutput().getOutHelpWidth?.()});let a=e.helpWidth??80,o=hr(r.operationId,t,n),[s,...c]=dr(r.errorResponse),l=c.map(t=>Wr(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Vr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
11
- `)}\n`})}}function Kr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&Zr(e)!==void 0});return n.length===0?t:void 0}var qr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Jr(e,t){let[n,...r]=e,i=y.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return x(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=v(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return x(`Resolved by route template`,{operationId:s.operationId});let c=ne({method:a,path:o});return!c.ok||c.data===null?m(c.summary,[...c.warnings,qr]):x(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function Yr(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(t===void 0)return;n=t}return n}async function Xr(e,t,n,r){let i=Zr(e);if(i===void 0)return m(`The \`${e.cliPath.join(` `)}\` operation no longer takes a single required text body; run it directly instead of \`help --ask\`.`);n!==void 0&&(process.env.API_ENV=n);let a=await On(e,{[i.optionKey]:t});return a.ok?await ue({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Ue(r)?`json`:`auto`}):a}function Zr(e){if(e.requestBody?.length!==1||e.parameters.some(e=>e.required))return;let t=(e.requestBody[0]?.parameter??[]).filter(e=>e.required);return t.length===1&&t[0]?.schemaType===`string`?t[0]:void 0}function Qr(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}var $r=e=>typeof e==`string`&&e.trim()===``;function ei(e,t){let n=new Set([...t.parameters,...(t.requestBody??[]).flatMap(({parameter:e})=>e)].filter(e=>e.required).map(e=>e.optionKey));for(let t of e.options){let r=t.attributeName(),i=e.getOptionValue(r);if(!(Array.isArray(i)?i.some($r):$r(i)))continue;let a=Array.isArray(i)?i.filter(e=>!$r(e)):[];if(a.length>0){e.setOptionValue(r,a);continue}n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0)}}function ti(e){return e.split(` `)[0]??e}function ni(e){if(e.requestBody===void 0||e.requestBody.length===0){let[t,n]=e.parameters.filter(e=>e.required);return n===void 0&&t?.schemaType===`string`?t:void 0}if(e.requestBody.length!==1||e.parameters.some(e=>e.required))return;let t=e.requestBody[0]?.parameter??[],n=t.filter(e=>e.required);if(n.length===1&&n[0]?.schemaType===`string`)return n[0];if(n.length!==0||e.intent!==`search`)return;let r=t.filter(e=>{let t=e.name.split(`.`).at(-1);return e.schemaType===`string`&&(t===`query`||t===`search`)});return r.length===1?r[0]:void 0}function ri(e,t,n){let r=t.join(` `).trim();return r.length===0?x(`No positional text`,n):n[e.optionKey]===void 0?x(`Positional text parsed`,{...n,[e.optionKey]:r}):m(`Use either the positional argument or ${ti(e.flag)}, not both.`)}function ii(e,t,n){if(e.cliPath[0]!==`lookup`||!ai(n))return null;let r=e.parameters.filter(e=>t[e.optionKey]!==void 0).map(e=>`${e.name}=${String(t[e.optionKey])}`),i=`no record for ${r.length===0?`the given input`:r.join(`, `)}`;return n.ok?m(i):m(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ai(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var oi=w({artifact:S().nullish(),group:S().nullish(),name:S().nullish(),revision:S().nullish(),time:C({offset:!0}).nullish(),version:S().nullish()}),si=w({build:oi});function z(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var ci=ge([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),li=ge([`RSA_OAEP_256_A256_GCM_V1`]),ui=w({clientLabel:S().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:ci.nullish(),encryptionAlgorithm:li.nullish(),encryptionPublicKey:S().min(344).max(12e3).nullish()}),di=32;async function fi(){let e=await kt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await kt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function pi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=mi(n,`wrapped key`,128,1024),s=mi(r,`nonce`,12,12),c=mi(i,`ciphertext`,1,65536),l=mi(a,`authentication tag`,16,16),u;try{u=await kt.subtle.decrypt({name:`RSA-OAEP`},e,o)}catch{throw Error(`broker credential key could not be decrypted`)}let d=new Uint8Array(u);try{if(d.byteLength!==di)throw Error(`broker credential used an invalid AES-256 key`);let e=await kt.subtle.importKey(`raw`,d,{name:`AES-GCM`},!1,[`decrypt`]),t=new Uint8Array(c.byteLength+l.byteLength);t.set(c),t.set(l,c.byteLength);let n;try{n=await kt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Tt(`utf-8`,{fatal:!0}).decode(n);if(r.trim().length===0)throw Error(`broker returned a blank credential`);return r}finally{d.fill(0)}}function mi(e,t,n,r){let i=e.replace(/=+$/u,``),a=Uint8Array.from(Buffer.from(e,`base64`)),o=Buffer.from(a).toString(`base64`).replace(/=+$/u,``);if(i.length===0||o!==i||a.byteLength<n||a.byteLength>r)throw Error(`broker returned an invalid ${t}`);return a}var hi=ge([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),gi=ge([`Denied by user`,`Authorization request expired`,`CLI authorization expired before acknowledgement`,`Credential issuance recovery revoked an unrecoverable key`,`Revoked by user`,`Clerk create response validation failed`,`Credential issuance failed`,`Credential issuance could not be recovered`,`API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),_i=w({approvedAt:C({offset:!0}).nullish(),clientLabel:S(),clientPlatform:ci,comparisonCode:S(),consumedAt:C({offset:!0}).nullish(),createdAt:C({offset:!0}),expiresAt:C({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),keyReadyAt:C({offset:!0}).nullish(),status:hi,terminalAt:C({offset:!0}).nullish(),terminalReason:gi.nullish(),updatedAt:C({offset:!0})}),vi=w({algorithm:li,authenticationTag:S(),ciphertext:S(),nonce:S(),wrappedKey:S()}),yi=w({delivery:vi.nullish(),expiresAt:C({offset:!0}),status:hi,terminalReason:gi.nullish()}),bi=w({comparisonCode:S(),expiresAt:C({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),pollSecret:S(),verificationUrl:S()}),B=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign in with a browser-approved aVenture API key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved aVenture API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI credential delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign out: revoke the API key and forget stored OAuth`,description:`Revokes the aVenture API key authenticating this request and returns its metadata so the CLI can confirm revocation before deleting its saved copy.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Delete the saved key even when revocation cannot be confirmed.`}]}],xi=z(B,`start`),Si=z(B,`poll`),Ci=z(B,`acknowledge`),wi=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${be(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Ai(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ti=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${T(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Ei(e){let t=await ae(_e(b()),{method:xi.method,path:p(xi.path,{},xi.operationId),headers:{},contentType:`application/json`,body:e},bi);if(!t.ok)throw new wi(`start`,t.problem);return ji(t.data)}async function Di(e,t){let n=g(Si.operationId),r=await ae(_e(b()),{method:Si.method,path:p(Si.path,{cliAuthorizationId:e},Si.operationId),headers:{[n]:t}},yi);if(!r.ok)throw new wi(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:ki(r.headers[`retry-after`])}}async function Oi(e,t){let n=g(Ci.operationId),r;try{r=await ae(_e(b()),{method:Ci.method,path:p(Ci.path,{cliAuthorizationId:e},Ci.operationId),headers:{[n]:t}},_i)}catch(e){throw new Ti(`acknowledge`,e,[t])}if(!r.ok)throw new wi(`acknowledge`,r.problem,[t]);return r.data}function ki(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Ai(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function ji(e){let{verificationUrl:t,pollSecret:n,...r}=e,i={...e},a=()=>({...r,verificationUrl:`<redacted>`,pollSecret:`<redacted>`});return Object.defineProperties(i,{verificationUrl:{enumerable:!1,get:()=>t},pollSecret:{enumerable:!1,get:()=>n},toJSON:{enumerable:!1,value:a},toString:{enumerable:!1,value:()=>`CliAuthorizationStart(${JSON.stringify(a())})`},[Et.custom]:{enumerable:!1,value:a}})}async function Mi(e){let t=await Ni(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await ve(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`),verification:t}}catch(n){return{stored:e,verification:{state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${T(n,[e.credential.secret])}`}}}}async function Ni(e){let t=_e(b()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},ze)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${T(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${be(n.problem,[e])}`}}var Pi=z(B,`revoke`);async function Fi(e){let t;try{t=Ve(b().host)}catch(e){return m(`auth logout: invalid API host — ${T(e)}`)}let n=await Ii(t),r=await zi(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],a={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?x(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...m(`auth logout: ${i[0]}`),data:a}:x(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function Ii(e){let t=await Ne(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Ri(t.stored):{revoked:!1};try{await we(e)}catch(e){return{state:`failed`,summary:T(e)}}return{state:`forgotten`,...n}}async function Li(e){let t=Reflect.get(await lt(e),`revocation_endpoint`);return typeof t==`string`?Oe(t,`revocation endpoint`,!0):void 0}async function Ri(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Li(t);if(e===void 0)return{revoked:!1};let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:r,client_id:Le(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:T(e,Me(n))}}}async function zi(e,t){let n;try{n=await Se(e)}catch(e){return m(`auth logout: stored credential could not be read — ${T(e)}`)}if(n.state===`unavailable`)return{...m(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Bi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...m(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.summary}`,[`Retry when the API is available. If an earlier response was lost after revocation, the retry can be unauthorized because revoked keys cannot authenticate.`,"Use `--forget-local` only to remove local bytes while accepting that the remote key may remain active."]),data:Vi(r,!1,!1)};try{await Te(r.host)}catch(e){return{...m(`auth logout: local credential removal failed — ${T(e,[r.credential.secret])}`,[a?"The remote key is revoked. Re-run with `--forget-local` to retry local cleanup.":`Remote revocation was not confirmed; inspect auth status before retrying.`]),data:Vi(r,a,!1)}}return x(a?`API key revoked remotely and removed locally.`:o?`Stale pending CLI credential removed; its remote key can no longer authenticate and unacknowledged keys expire at the authorization deadline.`:`API key removed locally without confirmed remote revocation.`,Vi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Bi(e){let t=_e(b());try{let n=await ae(t,{method:Pi.method,path:p(Pi.path,{},Pi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},ze);return n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:n.data.status===`REVOKED`?{outcome:`revoked`,summary:`remote key revocation confirmed`}:{outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}:{outcome:n.problem.status===401&&n.problem.type!==`about:blank`?`rejected`:`unconfirmed`,summary:be(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:T(t,[e.credential.secret])}}}function Vi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Hi=`RSA_OAEP_256_A256_GCM_V1`,Ui=1,Wi=30,V=f().bin[0],Gi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${V} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ki(e){if(!wt.isTTY)return m(`${V} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=b().host;t=Ve(e),n=Ae(e)}catch(e){return m(`auth login --key: invalid environment configuration — ${T(e)}`)}for(;;){let e;try{e=await Be(t)}catch(e){return m(`auth login --key: credential storage could not be inspected — ${T(e)}`)}if(e.state===`unavailable`)return m(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use AUTH_TOKEN from the environment.`]);if(e.state===`missing`){e.keyringFailure!==void 0&&N.write(Ce(e.keyringFailure));break}let n=await qi(e.stored);if(n!==null)return n}let r;try{r=await fi()}catch(e){return m(`auth login --key: ephemeral encryption key could not be created — ${T(e)}`)}let i=ui.safeParse({clientLabel:e.clientLabel?.trim()||(jt().trim()||V).slice(0,120),clientPlatform:Zi(),encryptionAlgorithm:Hi,encryptionPublicKey:r.publicKey});if(!i.success)return m(`auth login --key: ${me(i.error)}`);let a;try{a=await Ei(i.data)}catch(e){return m(`auth login --key: could not start browser authorization — ${T(e)}`)}let o;try{o=xe(a,n)}catch(e){return m(`auth login --key: unsafe browser authorization URL rejected — ${T(e)}`)}if(!Xi(await ye(a,n,{noBrowser:e.noBrowser}),a,o))return m(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[o]});let s;try{s=await Yi(a)}catch(e){return m(`auth login --key: authorization did not complete — ${T(e)}`,[],{references:[o]})}if(s.algorithm!==Hi)return m(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await pi(r.privateKey,s)}catch(e){return m(`auth login --key: encrypted credential could not be opened — ${T(e)}`)}let l=await Ni(c);if(l.state!==`verified`)return m(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await ve(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return m(`auth login --key: credential could not be durably stored — ${T(e)}`)}let d;try{d=await Ji(a)}catch(e){return H(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${T(e,[a.pollSecret])}`,Gi)}if(d.status!==`CONSUMED`)return H(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Gi);let f=await Ni(c);if(f.state!==`verified`||!ta(f.apiKey,u.credential.apiKey))return H(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Gi);try{let e=await ve(t,{apiKey:f.apiKey,secret:c},`active`);return x(`API key stored; authenticated identity and broker acknowledgment verified.`,ea(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return H(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${T(e)}`,Gi)}}async function qi(e){let t=await Ni(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?x(`API key is already stored and its authenticated identity was verified.`,ea(e,!0),{ids:[e.credential.apiKey.id]}):H(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${V} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&ta(t.apiKey,e.credential.apiKey))try{let n=await ve(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return x(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,ea(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return H(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${T(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${V} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return H(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${V} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Bi(e);if(n.outcome===`unconfirmed`)return H(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await Te(e.host)}catch(t){return H(e,!1,`auth login --key: stale pending credential could not be removed — ${T(t,[e.credential.secret])}`)}return N.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
1
+ import{$ as e,C as t,D as n,E as r,Ft as i,It as a,Pt as o,Q as s,Rt as c,T as l,V as u,X as d,Y as f,_ as p,at as m,b as h,c as g,et as _,f as v,g as y,h as ee,it as te,l as ne,m as re,nt as b,o as ie,ot as x,p as ae,q as oe,s as se,st as ce,tt as le,u as ue,x as de,z as fe}from"./auth-BRgX4q1I.js";import{C as S,D as pe,R as me,_ as he,a as ge,k as C,v as w}from"./person-owner-BqBLyw4S.js";import{A as _e,C as ve,D as ye,M as T,N as be,O as xe,S as Se,T as Ce,a as we,b as Te,c as Ee,d as De,g as Oe,j as ke,k as Ae,l as je,m as Me,o as Ne,r as Pe,s as Fe,t as Ie,u as Le,v as Re,w as ze,x as Be,y as Ve}from"./oauth-bearer-credential-BW_yR27w.js";import{_ as He,a as Ue,c as We,d as Ge,f as Ke,g as qe,h as Je,l as Ye,m as Xe,n as Ze,o as E,p as Qe,r as D,s as $e,t as O,u as et}from"./openapi-commands-Ce8I7fhm.js";import{a as tt}from"./text-field-CAEXuTfE.js";import{a as nt,n as rt,o as it,r as at,t as ot}from"./text-response-ChYVv0gm.js";import{n as st,r as ct,t as lt}from"./oauth-login-De1H4iDj.js";import{spawnSync as ut}from"node:child_process";import{basename as dt,dirname as k,resolve as A,sep as j}from"node:path";import{copyFileSync as ft,existsSync as pt,lstatSync as mt,mkdirSync as ht,mkdtempSync as gt,readFileSync as _t,readlinkSync as vt,realpathSync as yt,renameSync as bt,rmdirSync as xt,unlinkSync as St,writeFileSync as Ct}from"node:fs";import M,{stderr as N,stdin as wt}from"node:process";import{TextDecoder as Tt,inspect as Et}from"node:util";import{fileURLToPath as Dt}from"node:url";import{readFile as Ot}from"node:fs/promises";import{webcrypto as kt}from"node:crypto";import{homedir as At,hostname as jt,platform as Mt}from"node:os";import{setTimeout as Nt}from"node:timers/promises";import{createInterface as Pt}from"node:readline/promises";function Ft(e,t,n){let r={...n};for(let n of t.parameter){let t=n.envName;if(t===void 0)continue;let i=process.env[t]?.trim();if(i===void 0||i.length===0)continue;let a=r[n.optionKey];if(a!==void 0&&(typeof a!=`string`||a!==i))return{...m(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return x(`Environment-bound options applied`,r)}function It(e,t,n){if(!F(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!Xt(n,r.name))continue;let a=Yt(n,r.name);if(typeof a!=`string`||a!==i)return`${e} ${r.name} in --from-file conflicts with ${t}; omit the field or use ${i}.`}return null}function Lt(e){let t=new Set(e.parameter.map(({name:e})=>e));return e.kind===`multipart`?e.requiredPath:e.requiredPath.filter(e=>!t.has(e))}function Rt(e,t,n,r=!1){if(r||!P(t)||!Array.isArray(n))return en(e,t,n);for(let[r,i]of n.entries()){let n=en(e,t,i,r);if(!n.ok)return n}return x(`Body value assigned`,null)}function zt(e,t,n,r){return en(e,t,r,n)}function Bt(e){let t=[];for(let n of e.split(`.`)){let e=nn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Vt(e,t){let n=Bt(t);if(n===null)return null;let r=Jt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:qt(r)}:null}function Ht(e,t){if(P(e.name)||e.schemaType===`array`)return x(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return x(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?x(`Scalar body option selected`,t[0]):m(`${n} was already given; pass it once.`)}var Ut=/^(?<row>\d+):(?<item>.*)$/su;function Wt(e,t){let n=Bt(e.name);if(e.schemaType!==`array`||n===null||t===void 0||typeof t==`boolean`)return null;let r=new Map,i=[];for(let e of typeof t==`string`?[t]:t){let t=Ut.exec(e)?.groups,n=t?.row,a=t?.item;if(n===void 0||a===void 0){i.push(e);continue}let o=r.get(Number(n));o===void 0?r.set(Number(n),[a]):o.push(a)}return r.size===0?null:{container:n,rows:r,plain:i}}function Gt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Bt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Kt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Vt(r,i.name);if(a===null)continue;if(a.firstHole!==null)return m(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Wt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return m(`${o} fills one ${a.path}[] row's list, so ${e} cannot also build ${a.rowCount} ${a.path}[] rows from direct options — prefix each value with its 0-based ${a.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function qt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Jt(e,t){let n=e;for(let e of t){if(!F(n))return;n=n[e]??null}return n}function Yt(e,t){if(!P(t))return Jt(e,t.split(`.`))}function Xt(e,t){return Qt(e,t.split(`.`))}function Zt(e,t,n){if(!F(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&Xt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function Qt(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=nn(n);if(!F(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>Qt(e,r)):Qt(a,r)}function P(e){return e.split(`.`).some(e=>nn(e).isArray)}function $t(e,t){return e.parameter.length===0||!F(t)?null:an(t,[],rn(e.parameter))}function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function en(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=nn(o),c=e===i.length-1,l=tn(a,s,t,c,n,r);if(!l.ok||l.data===null)return m(l.summary,l.warnings);if(c)return x(`Body value assigned`,null);a=l.data}return m(`${t} is not a valid body option path.`)}function tn(e,t,n,r,i,a){let o=()=>m(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,x(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,x(`Body path created`,e)}return F(c)?x(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,x(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,x(`Body path created`,n)}return F(s)?x(`Body path stepped`,s):o()}function nn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function rn(e){let t=new Set,n=new Set;for(let r of e){let e=`${r.name}${r.schemaType===`array`?`[]`:``}`;t.add(e);let i=e.split(`.`);for(let e=1;e<i.length;e+=1)n.add(i.slice(0,e).join(`.`))}return{leaf:t,prefix:n}}function an(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=an(r,t,n);if(e!==null)return e}return null}if(!F(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!on(a,n)){if(!sn(e))continue;return{path:a,suggestion:cn(e,n)}}let o=an(i,e,n);if(o!==null)return o}return null}function on(e,t){return t.prefix.has(e)||t.leaf.has(e)}function sn(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function cn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``;return[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:ln(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path))[0]?.path}function ln(e,t){let n=t.replace(/\[\]$/u,``).toLowerCase();return n===e?0:n.endsWith(e)||e.endsWith(n)?1:n.includes(e)||e.includes(n)?2:1/0}function un(e,t){let n=new Map;for(let e of t){let t=e.flag?.split(` `)[0];t!==void 0&&n.set(t,t===`--from-file`?{...e,inputType:`file`}:e)}for(let t of e){let e=t.long===void 0?void 0:n.get(t.long);e!==void 0&&t.helpGroup(qe(e))}e.sort((e,t)=>{let r=e.long===void 0?void 0:n.get(e.long),i=t.long===void 0?void 0:n.get(t.long);return r!==void 0&&i!==void 0?vn(r,i):r===void 0?i===void 0?0:1:-1})}function dn(e){let t=new Map;for(let n of e)for(let e of n.parameter){let r=e.flag.split(` `)[0]??e.flag,i=t.get(r);i===void 0?t.set(r,{variant:[{descriptor:n,parameter:e}]}):t.set(r,{variant:[...i.variant,{descriptor:n,parameter:e}]})}return[...t.values()]}function fn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function pn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:gn(e,t)})),n=t[0];return n===void 0?``:t.every(({text:e})=>e===n.text)?`${n.text===``?``:`${n.text} `}Request content: ${t.map(({contentType:e})=>e).join(`, `)}.`:t.map(({contentType:e,text:t})=>`${e}: ${t}`).join(` `)}function mn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function hn(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?He(n):`${He(n)} Required JSON paths: ${r.join(`, `)}.`}function gn(e,t){let n=Xe(t.description,void 0),r=e.kind!==`multipart`&&P(t.name),i=e.kind!==`multipart`&&t.optionKey!==t.name&&/^\w+$/u.test(t.name);return`${n}${r?` Repeat to add another value.`:``}${i?` --from-file JSON key: ${t.name}.`:``}${_n(e,t)}`}function _n(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Bt(t.name);return n===null?``:` Prefix each value with its 0-based ${n}[] row index, as 0:value, to fill more than one ${n}[] row. A leading digits-and-colon is always read as that index, so name the row of a value that starts the same way, as 0:0:00 for the value 0:00.`}function vn(e,t){return Je(e)-Je(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function yn(e){let t;try{t=e===`-`?await bn():await Ot(e,`utf8`)}catch(t){return m(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return x(`No input provided`,null);let e=JSON.parse(t);return x(`Input parsed`,e)}catch(e){return m(`Input is not valid JSON: ${e.message}`)}}async function bn(){if(process.stdin.isTTY)throw Error(`--from-file - requires JSON on stdin, but stdin is a TTY`);process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}var xn=`--content-type`;function Sn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),a=t.requestBody??[];if(a.length>1&&r(xn)){let t=a.map(({contentType:e})=>e);e.addOption(new i(`${xn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(wn(a)))}if(Un(t)&&r(`--from-file`)){let n=a[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new i(`--from-file <path>`,hn(n,n.requiredPath)).argParser(En(`--from-file`)))}let o=dn(a).filter(e=>r(I(e.variant[0].parameter)));for(let t of o.toSorted((e,t)=>vn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],o=new i(fn(t),a.length>1?pn(t):gn(n,r));a.length===1&&r.envName!==void 0&&o.env(r.envName);let s=a.length===1?mn(n,r.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Cn):P(r.name)||r.schemaType===`array`?o.argParser(Tn):o.argParser(En(r.flag)),e.addOption(o),o.envVar!==void 0&&e.on(`optionEnv:${o.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}Hn(e,t,o)}function Cn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function wn(e){return(t,r)=>{if(r!==void 0)throw new c(`${xn} was already given; pass it once.`);let i=n(e,t);if(!i.ok)throw new c(i.summary);return t}}function Tn(e,t){return[...t??[],e]}function En(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new c(`${t} was already given; pass it once.`);return e}}async function Dn(e,t){let r=typeof t.contentType==`string`?t.contentType:void 0,i=n(e.requestBody??[],r);if(!i.ok||i.data===null)return m(i.summary,i.warnings);let a=i.data;if(a===void 0)return x(`No body`,void 0);let o=On(e,a,t);if(o!==null)return m(o);let s=Ft(e.operationId,a,t);if(!s.ok)return m(s.summary,s.warnings);t=s.data;let c=kn(a,t);if(c!==null)return m(c);let l=await Nn(t);if(!l.ok)return m(l.summary,l.warnings);let u=Zt(e.requestBody??[],a,l.data);if(u!==null)return m(u);let d=Mn(e.operationId,a,l.data);if(!d.ok)return d;let f=It(e.operationId,a,l.data);if(f!==null)return m(f);let p=Pn(e.operationId,a,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return a.required?m(Vn(e.operationId,a)):x(`No body`,void 0);let h=In(e.operationId,l.data,p.data);if(!h.ok||h.data===void 0)return h;if(a.schemaType===`array`&&!Array.isArray(h.data))return m(`${e.operationId} requires a JSON array body.`);if(a.parameter.length>0&&!F(h.data)){let t=a.kind===`multipart`?` keyed by multipart part name`:` body`;return m(`${e.operationId} requires a JSON object${t}.`)}let g=jn(a,h.data);if(g.length>0)return m(`${e.operationId} requires body option(s): ${g.join(`, `)}`);let _=h.data,v=F(_)?Lt(a).filter(e=>!Xt(_,e)):[];return v.length>0?m(An(e.operationId,a,v)):h}function On(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${xn} ${i.join(` or `)}.`}return null}function kn(e,t){for(let n of e.cliConflicts??[]){let e=n.filter(e=>t[e]!==void 0);if(e.length>1)return`Options ${e.join(`, `)} cannot be used together.`}return null}function An(e,t,n){let r=`${e} requires JSON body path(s): ${n.join(`, `)}`;return t.kind===`multipart`?`${r}. ${n.includes(`body`)?`For multipart --from-file, wrap the endpoint JSON under top-level "body".`:`For multipart --from-file, put the missing nested path(s) inside top-level "body".`}`:r}function jn(e,t){return F(t)?e.parameter.filter(e=>e.required&&!Xt(t,e.name)).map(I):[]}function Mn(e,t,n){let r=$t(t,n);if(r===null)return x(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return m(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Nn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return x(`No body file`,void 0);let n=await yn(t);if(!n.ok)return m(n.summary,n.warnings);let r=ce.safeParse(n.data);return r.success?x(`Input parsed`,r.data):m(`Input is not valid JSON value: ${r.error.message}`)}function Pn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Ht(e,n[e.optionKey]);if(!a.ok||a.data===null)return m(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Fn(t,n,r,e,o);if(!s.ok)return m(s.summary,s.warnings);i=!0}if(!i)return x(`No direct body options`,void 0);let a=Kt(e,t,n,r);return a===null?x(`Direct body options parsed`,r):a}function Fn(e,t,n,r,i){let a=Wt(r,i);if(a===null){let e=zn(r,i);return e.ok?Rt(n,r.name,e.data,r.schemaType===`array`):m(e.summary,e.warnings)}if(a.plain.length>0)return m(`${I(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=Gt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return m(`${I(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=Bn(r.name,r.itemSchemaType,e);if(!t.ok)return m(t.summary,t.warnings);i.push(t.data)}let a=zt(n,r.name,e,i);if(!a.ok)return a}return x(`Body value assigned`,null)}var I=e=>e.flag.split(` `)[0]??e.name;function In(e,t,n){if(t===void 0)return x(`Direct body parsed`,n);if(n===void 0)return x(`Input parsed`,t);if(F(t)&&F(n))try{return x(`Input parsed`,Ln(t,n))}catch(t){return m(`${e} ${t.message}`)}return m(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Ln(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Array.isArray(t)&&Array.isArray(r))throw Error(`cannot combine --from-file array '${e}' with array body options at the same key — move the per-item fields inside the matching '${e}[]' object(s) in the file body.`);if(t!==void 0&&Rn(t)!==Rn(r))throw Error(`cannot combine --from-file ${Rn(t)} '${e}' with ${Rn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=F(t)&&F(r)?Ln(t,r):r}return n}function Rn(e){return Array.isArray(e)?`array`:F(e)?`object`:`scalar`}function zn(e,t){if(typeof t==`boolean`)return x(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Bn(e.name,e.schemaType,t??``);let n=[],r=P(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Bn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return x(`Body value parsed`,n)}function Bn(e,t,n){if(t===`boolean`)return n===`true`?x(`Body value parsed`,!0):n===`false`?x(`Body value parsed`,!1):m(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?m(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?m(`${e} must be an integer.`):x(`Body value parsed`,i)}return x(`Body value parsed`,n)}function Vn(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=Lt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Hn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:xn,location:`body`}),Un(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),un(e.options,r)}function Un(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Wn(e){let t=te(e);return $n(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Gn(e){$n(e);let t=ot(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
+ `)?t:`${t}\n`),Kn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&Yn(e.problem),Kn(e)}function Kn(e){e.ids.length>0&&process.stdout.write(` ids: ${e.ids.join(`, `)}\n`);for(let[t,n]of Object.entries(e.counts))process.stdout.write(` ${t}: ${n}\n`);for(let t of e.references)process.stdout.write(` ref: ${t}\n`);if(e.truncation!==void 0){let t=e.truncation.omitted.join(`, `);process.stdout.write(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${t}\n`),process.stdout.write(` recovery: ${e.truncation.recovery}\n`)}for(let t of e.warnings)process.stdout.write(` warn: ${t}\n`)}function L(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?te(t):t;$n(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?qn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?Wn(t):t;e.mode===`text`&&Gn(n),n.ok||(process.exitCode=1)}function qn(e){return typeof e!=`object`||!e||Array.isArray(e)||!Reflect.has(e,`method`)||!Reflect.has(e,`endpoint`)||!(`response`in e)||e.response===void 0?e:e.response}function Jn(e,t){let n=rt(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
3
+ `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function Yn(e){typeof e.code==`string`&&process.stdout.write(` code: ${e.code}\n`),typeof e.detail==`string`&&process.stdout.write(` detail: ${e.detail}\n`),typeof e.hint==`string`&&process.stdout.write(` hint: ${e.hint}\n`),typeof e.suggestion==`string`&&process.stdout.write(` suggestion: ${e.suggestion}\n`);let t=Object.entries(e.suggestions??{});if(t.length>0){let e=t.map(([e,t])=>`${e}=${t}`).join(`; `);process.stdout.write(` suggestions: ${e}\n`)}typeof e.requiredRole==`string`&&process.stdout.write(` requiredRole: ${e.requiredRole}\n`),Xn(e),Zn(`unknownParameters`,e.unknownParameters),Zn(`validParameters`,e.validParameters),Qn(e.resolution)}function Xn(e){let t=[];typeof e.limitType==`string`&&t.push(`limitType=${e.limitType}`),typeof e.used==`number`&&t.push(`used=${e.used}`),typeof e.limit==`number`&&t.push(`limit=${e.limit}`),typeof e.remaining==`number`&&t.push(`remaining=${e.remaining}`),typeof e.resetAt==`string`&&t.push(`resetAt=${e.resetAt}`),typeof e.windowSeconds==`number`&&t.push(`windowSeconds=${e.windowSeconds}`),typeof e.retryAfterSeconds==`number`&&t.push(`retryAfterSeconds=${e.retryAfterSeconds}`),t.length>0&&process.stdout.write(` meter: ${t.join(` `)}\n`)}function Zn(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function Qn(e){if(e==null)return;let t=[`action=${e.action}`];typeof e.parameter==`string`&&t.push(`parameter=${e.parameter}`),typeof e.fieldPath==`string`&&t.push(`fieldPath=${e.fieldPath}`),typeof e.endpoint==`string`&&t.push(`endpoint=${e.endpoint}`),e.acceptedValue!==null&&e.acceptedValue!==void 0&&e.acceptedValue.length>0&&t.push(`acceptedValue=${e.acceptedValue.join(`, `)}`),typeof e.retryable==`boolean`&&t.push(`retryable=${e.retryable}`),process.stdout.write(` resolution: ${t.join(` `)}\n`)}function $n(e){e.ok&&e.warnings.length===0||u({component:`aventure-cli`,event:e.ok?`command_warning`:`command_failed`,message:e.warnings.length>0?e.warnings.join(` | `):e.summary,fields:{warningCount:e.warnings.length,summary:e.summary}})}function er(e,t,n=f().bin[0]){let r=e.limit===void 0?void 0:Number(e.limit);if(r!==void 0&&(e.limit?.trim()===``||!Number.isInteger(r)||r<0))return m(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=at(e.q??``,rr(t,n).filter(t=>sr(t,e)),e=>({...e,cliPath:e.cli.path,enumParameter:e.flags.map(({choices:e,location:t})=>({values:e,direct:t!==`body`})),parameterName:e.flags.flatMap(({wireName:e,optionKey:t})=>[e,t]),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),a=i.slice(0,r);return x(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function tr(e,t,n=f().bin[0]){let r=rr(t,n),i=e.operationId===void 0?nr(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let i=br(e.command??``),a=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${i} `));if(a.length>0)return m(`${i} is a command group; show one of its subcommands.`,[`Run \`${n} command-catalog show --command "<subcommand>"\` with one of:`,...a]);let o=i.split(` `),s=new Set([...[...o.keys()].map(e=>o.slice(e+1).join(` `)),...o.slice(1).map((e,t)=>o.toSpliced(t,2,`${o[t]}-${e}`).join(` `))]),c=er({q:e.command??e.operationId},t,n),l=[...r.filter(({cli:e})=>e.path.length>1&&s.has(e.path.join(` `))).toSorted((e,t)=>t.cli.path.length-e.cli.path.length),...c.data?.operation??[]];return m(`Generated operation not found`,[...[...new Set(l.map(({cli:e,operationId:t})=>`${e.command} (operationId ${t})`))].slice(0,3).map(e=>`closest: ${e}`),`List candidates with \`${n} command-catalog search "<text>"\`.`])}return x(`Generated operation detail`,{operation:i,usage:lr(i,r)})}function nr(e,t){if(t===void 0)return;let{bin:n}=f(),r=br(t,n);return e.find(e=>br(e.cli.command,n)===r)}function rr(e,t){return e.map(e=>{let n=e.requestBody??[],i=[...e.parameters.map(e=>ir(e)),...n.flatMap(e=>e.parameter.map(t=>ir(t,n.length>1?e.contentType:void 0))),...ar(n)],a=[t,...e.cliPath].join(` `),o=l(e.intent),s=e.method===`DELETE`||e.intent===`delete`,c=n[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:s,auth:e.auth,cli:{command:a,path:e.cliPath},mcpTool:e.binaryResponse?null:r(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&n.length>1?{contentType:c.contentType}:{},required:c?.required??!1,description:c?.description??``,requiredPath:c?.requiredPath??[]},flags:i,errorResponse:e.errorResponse,summary:e.summary,description:e.description,deprecated:e.deprecated}})}function ir(e,t){let n=e.flag.split(/\s+/u);return{name:n[0]??e.flag,optionKey:e.optionKey,wireName:e.name,location:e.location,required:e.required,placeholder:n.length<=1?null:n.slice(1).join(` `),description:e.description,choices:e.choices??[],...t===void 0?{}:{contentType:t}}}function ar(e){if((e?.length??0)<=1)return[];let t=e?.map(({contentType:e})=>e)??[];return[{name:`--content-type`,optionKey:`contentType`,wireName:`Content-Type`,location:`body`,required:!1,placeholder:`<media-type>`,description:`Select the request content type; omit for ${t[0]}.`,choices:t}]}function or(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function sr(e,t){return!(t.root!==void 0&&!cr(e,t.root)||t.scope!==void 0&&t.scope!==`all`&&t.scope!==e.scope||t.mutates!==void 0&&t.mutates!==`any`&&t.mutates===`true`!==e.mutates||t.destructive!==void 0&&t.destructive!==`any`&&t.destructive===`true`!==e.destructive||t.intent!==void 0&&t.intent!==`all`&&t.intent!==e.intent||t.method!==void 0&&t.method!==`all`&&t.method!==e.method)}function cr(e,t){let n=it(t);return n.length===0||it(e.cli.path.at(0)??``)===n}function lr(e,t){let n=or(e),r=n.filter(e=>e.required),i=n.filter(e=>!e.required);return[`cli: ${e.cli.command}`,`${e.method} ${e.path}`,`operationId: ${e.operationId}`,`resource: ${e.resource}`,`intent: ${e.intent}`,`scope: ${e.scope}`,`mutates: ${e.mutates}`,`destructive: ${e.destructive}`,`mcpTool: ${e.mcpTool??`unavailable (binary CLI operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,R(`required path flags`,r,`path`),R(`required query flags`,r,`query`),R(`required header flags`,r,`header`),R(`required body flags`,r,`body`),R(`optional path flags`,i,`path`),R(`optional query flags`,i,`query`),R(`optional header flags`,i,`header`),R(`optional body flags`,i,`body`),...hr(e,t),...ur(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
+ `)}function ur(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var dr=[`-id`,`-slug`,`-url`],fr=[`--id`,`--slug`,`--url`],pr=`--from-file "<path>"`;function mr(e,t,n=f().bin[0]){let r=rr(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:hr(i,r)}function hr(e,t){return[`example: ${[e.cli.command,..._r(e),`--data`].join(` `)}`,...gr(e,t)]}function gr(e,t){return or(e).flatMap(e=>{if(!e.required||!e.optionKey.endsWith(`Id`))return[];let n=`${e.optionKey.slice(0,-2)}Slug`,r=t.find(e=>e.method===`GET`&&/\/lookup(?:-exact)?$/u.test(e.path)&&e.flags.some(e=>e.optionKey===n)),i=r?.flags.find(e=>e.optionKey===n);if(r===void 0||i===void 0)return[];let a=`${r.cli.command} ${yr(i)} --data`,o=t.find(e=>e.method===`POST`&&e.path===r.path.replace(/-exact$/u,``)),s=o?.flags.find(e=>e.optionKey===`name`),c=`lookup: ${e.name} from a slug: ${a}`;return o===void 0||s===void 0?[c]:[c,`lookup: ${e.name} from a name or URL: ${o.cli.command} ${yr(s)} --data, then match.owner.${e.optionKey} when status is MATCHED`]})}function _r(e){let t=or(e).filter(e=>e.required),n=(t.length>0?t:vr(e)).map(yr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,pr]:n}function vr(e){let t=new Set;nt(t,e.resource);for(let n of dr)for(let r of t){let t=e.flags.find(e=>e.name===`--${r}${n}`);if(t!==void 0)return[t]}for(let t of fr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function yr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function R(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function br(e,t=f().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var xr=`dist/aventure-cli/command-catalog.compact.txt`,Sr=` · `,Cr=`-`;function wr(e=f().bin[0]){return A(Tr(k(Dt(import.meta.url)),e),xr)}function Tr(e,t){let n=e;for(;;){if(pt(A(n,`package.json`)))return n;let r=k(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Er(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Dr(e,t,n,r=f().bin[0]){let i=er(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}kr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:jr(i.data,Ar(e.format,`lines`)),summary:`Generated operation matches`})}function Or(e,t,n,r=f().bin[0]){let i=tr(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}kr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Mr(i.data,Ar(e.format,`usage`)),summary:`Generated operation detail`})}function kr(e){let t=e.mode,n=Ar(e.opts.format,e.defaultFormat),r=e.opts.text===!0||e.opts.allFields===!0;if(e.opts.output===void 0&&r&&(n===`json`||n===`ndjson`)){L({mode:t},m(`--text or --all-fields cannot be combined with --format json or ndjson`,[`Omit the text flag for machine output, or use --format lines, compact, or text.`]));return}let i=e.opts.output===void 0&&t===`text`&&`count`in e.data&&e.data.count.returned===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
5
+ `)?i:`${i}\n`;if(e.opts.output!==void 0){Ct(e.opts.output,a),L({mode:t},x(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:Lr(e.data)}));return}if(t===`text`){process.stdout.write(a);return}L({mode:t},x(e.summary,e.data,{counts:Lr(e.data)}))}function Ar(e,t){return e??t}function jr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
6
+ `):t===`text`?Fr(e.operation):t===`compact`?e.operation.map(Nr).join(`
7
+ `):e.operation.map(Ir).join(`
8
+ `)}function Mr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Ir(e.operation):t===`compact`?Nr(e.operation):e.usage}function Nr(e){let t=Pr(e);return[e.cli.command,e.summary,t.length===0?Cr:t.join(` `)].join(Sr)}function Pr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Fr(e){return e.map(e=>`${e.cli.command}\n ${Ir(e)}`).join(`
9
+ `)}function Ir(e){let t=Pr(e);return[z(`operationId`,e.operationId),z(`scope`,e.scope),z(`mutates`,String(e.mutates)),z(`destructive`,String(e.destructive)),z(`intent`,e.intent),z(`resource`,e.resource),z(`cli`,e.cli.command),e.mcpTool===null?``:z(`mcpTool`,e.mcpTool),z(`method`,e.method),z(`path`,e.path),z(`auth`,e.auth),z(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),z(`requiredFlags`,t.join(` `)),z(`bodyKind`,e.body.kind??``),z(`bodyRequired`,String(e.body.required)),z(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function z(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Lr(e){return`count`in e?e.count:{returned:1}}function Rr(e,t,n=f().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show full documentation for a command, or ask a question`).description([`Show a command's full documentation offline. Select it by command path,`,"operationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.","`help ask <question>` or `help --ask <question>` answers a platform question."].join(`
10
+ `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new zr(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Gr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),D(r),r.action(async function(r){let a=this.optsWithGlobals();if(a.help&&r.length===0){this.outputHelp();return}if(!a.help&&i!==void 0&&a.ask!==void 0){let e=E(a);if(r.length>0){L({mode:e},m(`Use either a command path or --ask, not both.`));return}L({mode:e},await Yr(i,a.ask,a.environment,e));return}let o=Jr(e,r),s=t.find(t=>o!==void 0&&Jr(e,t.cliPath)===o);if(a.help||o!==void 0&&s===void 0){o===void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),o.outputHelp();return}let c=s===void 0?qr(r,t):x(`Resolved by command path`,{operationId:s.operationId});if(c.ok&&c.data?.command!==void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),!c.ok||c.data===null){L({mode:E(a)},c);return}Or({...a,...c.data},t,E(a,`text`),n)}),Wr(e,t,n)}var zr=class extends i{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},Br=2,Vr=6,Hr={formatHelp(e,t){let n=n=>a.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),n));if(t.visibleCommands(e).length===0)return n({});let r=t.padWidth(e,t),i={padWidth:()=>r,visibleOptions:()=>[],showGlobalOptions:!1},o=n({...i,visibleCommands:()=>[]}),s=n({padWidth:()=>r,visibleCommands:()=>[]}).slice(o.length);return n(i)+s},visibleCommands(e){let t=a.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>!Ke.has(e.name())):t},subcommandTerm(e){let t=a.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,n,r){let i=r.helpWidth??80,o=i-t-4;return n===``||o>=r.minWidthToWrap?a.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Br)}${e}\n${Ur(n,i,r)}`}};function Ur(e,t,n){return n.boxWrap(e,t-Vr).replace(/^/gmu,` `.repeat(Vr))}function Wr(e,t,n){for(let r of t){let i=Jr(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp();e.prepareContext({helpWidth:i.configureOutput().getOutHelpWidth?.()});let a=e.helpWidth??80,o=mr(r.operationId,t,n),[s,...c]=ur(r.errorResponse),l=c.map(t=>Ur(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Br))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
11
+ `)}\n`})}}function Gr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&Xr(e)!==void 0});return n.length===0?t:void 0}var Kr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function qr(e,t){let[n,...r]=e,i=y.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return x(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=v(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return x(`Resolved by route template`,{operationId:s.operationId});let c=ne({method:a,path:o});return!c.ok||c.data===null?m(c.summary,[...c.warnings,Kr]):x(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function Jr(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(t===void 0)return;n=t}return n}async function Yr(e,t,n,r){let i=Xr(e);if(i===void 0)return m(`The \`${e.cliPath.join(` `)}\` operation no longer takes a single required text body; run it directly instead of \`help --ask\`.`);n!==void 0&&(process.env.API_ENV=n);let a=await Dn(e,{[i.optionKey]:t});return a.ok?await ue({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Ue(r)?`json`:`auto`}):a}function Xr(e){if(e.requestBody?.length!==1||e.parameters.some(e=>e.required))return;let t=(e.requestBody[0]?.parameter??[]).filter(e=>e.required);return t.length===1&&t[0]?.schemaType===`string`?t[0]:void 0}function Zr(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}var Qr=e=>typeof e==`string`&&e.trim()===``;function $r(e,t){let n=new Set([...t.parameters,...(t.requestBody??[]).flatMap(({parameter:e})=>e)].filter(e=>e.required).map(e=>e.optionKey));for(let t of e.options){let r=t.attributeName(),i=e.getOptionValue(r);if(!(Array.isArray(i)?i.some(Qr):Qr(i)))continue;let a=Array.isArray(i)?i.filter(e=>!Qr(e)):[];if(a.length>0){e.setOptionValue(r,a);continue}n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0)}}function ei(e){return e.split(` `)[0]??e}function ti(e){if(e.requestBody===void 0||e.requestBody.length===0){let[t,n]=e.parameters.filter(e=>e.required);return n===void 0&&t?.schemaType===`string`?t:void 0}if(e.requestBody.length!==1||e.parameters.some(e=>e.required))return;let t=e.requestBody[0]?.parameter??[],n=t.filter(e=>e.required);if(n.length===1&&n[0]?.schemaType===`string`)return n[0];if(n.length!==0||e.intent!==`search`)return;let r=t.filter(e=>{let t=e.name.split(`.`).at(-1);return e.schemaType===`string`&&(t===`query`||t===`search`)});return r.length===1?r[0]:void 0}function ni(e,t,n){let r=t.join(` `).trim();return r.length===0?x(`No positional text`,n):n[e.optionKey]===void 0?x(`Positional text parsed`,{...n,[e.optionKey]:r}):m(`Use either the positional argument or ${ei(e.flag)}, not both.`)}function ri(e,t,n){if(e.cliPath[0]!==`lookup`||!ii(n))return null;let r=e.parameters.filter(e=>t[e.optionKey]!==void 0).map(e=>`${e.name}=${String(t[e.optionKey])}`),i=`no record for ${r.length===0?`the given input`:r.join(`, `)}`;return n.ok?m(i):m(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ii(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var ai=w({artifact:S().nullish(),group:S().nullish(),name:S().nullish(),revision:S().nullish(),time:C({offset:!0}).nullish(),version:S().nullish()}),oi=w({build:ai});function B(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var si=ge([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),ci=ge([`RSA_OAEP_256_A256_GCM_V1`]),li=w({clientLabel:S().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:si.nullish(),encryptionAlgorithm:ci.nullish(),encryptionPublicKey:S().min(344).max(12e3).nullish()}),ui=32;async function di(){let e=await kt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await kt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function fi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=pi(n,`wrapped key`,128,1024),s=pi(r,`nonce`,12,12),c=pi(i,`ciphertext`,1,65536),l=pi(a,`authentication tag`,16,16),u;try{u=await kt.subtle.decrypt({name:`RSA-OAEP`},e,o)}catch{throw Error(`broker credential key could not be decrypted`)}let d=new Uint8Array(u);try{if(d.byteLength!==ui)throw Error(`broker credential used an invalid AES-256 key`);let e=await kt.subtle.importKey(`raw`,d,{name:`AES-GCM`},!1,[`decrypt`]),t=new Uint8Array(c.byteLength+l.byteLength);t.set(c),t.set(l,c.byteLength);let n;try{n=await kt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Tt(`utf-8`,{fatal:!0}).decode(n);if(r.trim().length===0)throw Error(`broker returned a blank credential`);return r}finally{d.fill(0)}}function pi(e,t,n,r){let i=e.replace(/=+$/u,``),a=Uint8Array.from(Buffer.from(e,`base64`)),o=Buffer.from(a).toString(`base64`).replace(/=+$/u,``);if(i.length===0||o!==i||a.byteLength<n||a.byteLength>r)throw Error(`broker returned an invalid ${t}`);return a}var mi=ge([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),hi=ge([`Denied by user`,`Authorization request expired`,`CLI authorization expired before acknowledgement`,`Credential issuance recovery revoked an unrecoverable key`,`Revoked by user`,`Clerk create response validation failed`,`Credential issuance failed`,`Credential issuance could not be recovered`,`API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),gi=w({approvedAt:C({offset:!0}).nullish(),clientLabel:S(),clientPlatform:si,comparisonCode:S(),consumedAt:C({offset:!0}).nullish(),createdAt:C({offset:!0}),expiresAt:C({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),keyReadyAt:C({offset:!0}).nullish(),status:mi,terminalAt:C({offset:!0}).nullish(),terminalReason:hi.nullish(),updatedAt:C({offset:!0})}),_i=w({algorithm:ci,authenticationTag:S(),ciphertext:S(),nonce:S(),wrappedKey:S()}),vi=w({delivery:_i.nullish(),expiresAt:C({offset:!0}),status:mi,terminalReason:hi.nullish()}),yi=w({comparisonCode:S(),expiresAt:C({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),pollSecret:S(),verificationUrl:S()}),V=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign in with a browser-approved aVenture API key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved aVenture API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI credential delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign out: revoke the API key and forget stored OAuth`,description:`Revokes the aVenture API key authenticating this request and returns its metadata so the CLI can confirm revocation before deleting its saved copy.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Delete the saved key even when revocation cannot be confirmed.`}]}],bi=B(V,`start`),xi=B(V,`poll`),Si=B(V,`acknowledge`),Ci=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${be(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ki(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},wi=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${T(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Ti(e){let t=await ae(_e(b()),{method:bi.method,path:p(bi.path,{},bi.operationId),headers:{},contentType:`application/json`,body:e},yi);if(!t.ok)throw new Ci(`start`,t.problem);return Ai(t.data)}async function Ei(e,t){let n=g(xi.operationId),r=await ae(_e(b()),{method:xi.method,path:p(xi.path,{cliAuthorizationId:e},xi.operationId),headers:{[n]:t}},vi);if(!r.ok)throw new Ci(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Oi(r.headers[`retry-after`])}}async function Di(e,t){let n=g(Si.operationId),r;try{r=await ae(_e(b()),{method:Si.method,path:p(Si.path,{cliAuthorizationId:e},Si.operationId),headers:{[n]:t}},gi)}catch(e){throw new wi(`acknowledge`,e,[t])}if(!r.ok)throw new Ci(`acknowledge`,r.problem,[t]);return r.data}function Oi(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ki(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Ai(e){let{verificationUrl:t,pollSecret:n,...r}=e,i={...e},a=()=>({...r,verificationUrl:`<redacted>`,pollSecret:`<redacted>`});return Object.defineProperties(i,{verificationUrl:{enumerable:!1,get:()=>t},pollSecret:{enumerable:!1,get:()=>n},toJSON:{enumerable:!1,value:a},toString:{enumerable:!1,value:()=>`CliAuthorizationStart(${JSON.stringify(a())})`},[Et.custom]:{enumerable:!1,value:a}})}async function ji(e){let t=await Mi(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await ve(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`),verification:t}}catch(n){return{stored:e,verification:{state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${T(n,[e.credential.secret])}`}}}}async function Mi(e){let t=_e(b()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},ze)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${T(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${be(n.problem,[e])}`}}var Ni=B(V,`revoke`);async function Pi(e){let t;try{t=Ve(b().host)}catch(e){return m(`auth logout: invalid API host — ${T(e)}`)}let n=await Fi(t),r=await Ri(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],a={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?x(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...m(`auth logout: ${i[0]}`),data:a}:x(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function Fi(e){let t=await Ne(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Li(t.stored):{revoked:!1};try{await we(e)}catch(e){return{state:`failed`,summary:T(e)}}return{state:`forgotten`,...n}}async function Ii(e){let t=Reflect.get(await lt(e),`revocation_endpoint`);return typeof t==`string`?Oe(t,`revocation endpoint`,!0):void 0}async function Li(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Ii(t);if(e===void 0)return{revoked:!1};let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:r,client_id:Le(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:T(e,Me(n))}}}async function Ri(e,t){let n;try{n=await Se(e)}catch(e){return m(`auth logout: stored credential could not be read — ${T(e)}`)}if(n.state===`unavailable`)return{...m(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await zi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...m(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.summary}`,[`Retry when the API is available. If an earlier response was lost after revocation, the retry can be unauthorized because revoked keys cannot authenticate.`,"Use `--forget-local` only to remove local bytes while accepting that the remote key may remain active."]),data:Bi(r,!1,!1)};try{await Te(r.host)}catch(e){return{...m(`auth logout: local credential removal failed — ${T(e,[r.credential.secret])}`,[a?"The remote key is revoked. Re-run with `--forget-local` to retry local cleanup.":`Remote revocation was not confirmed; inspect auth status before retrying.`]),data:Bi(r,a,!1)}}return x(a?`API key revoked remotely and removed locally.`:o?`Stale pending CLI credential removed; its remote key can no longer authenticate and unacknowledged keys expire at the authorization deadline.`:`API key removed locally without confirmed remote revocation.`,Bi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function zi(e){let t=_e(b());try{let n=await ae(t,{method:Ni.method,path:p(Ni.path,{},Ni.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},ze);return n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:n.data.status===`REVOKED`?{outcome:`revoked`,summary:`remote key revocation confirmed`}:{outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}:{outcome:n.problem.status===401&&n.problem.type!==`about:blank`?`rejected`:`unconfirmed`,summary:be(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:T(t,[e.credential.secret])}}}function Bi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Vi=`RSA_OAEP_256_A256_GCM_V1`,Hi=1,Ui=30,H=f().bin[0],Wi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${H} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Gi(e){if(!wt.isTTY)return m(`${H} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=b().host;t=Ve(e),n=Ae(e)}catch(e){return m(`auth login --key: invalid environment configuration — ${T(e)}`)}for(;;){let e;try{e=await Be(t)}catch(e){return m(`auth login --key: credential storage could not be inspected — ${T(e)}`)}if(e.state===`unavailable`)return m(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use AUTH_TOKEN from the environment.`]);if(e.state===`missing`){e.keyringFailure!==void 0&&N.write(Ce(e.keyringFailure));break}let n=await Ki(e.stored);if(n!==null)return n}let r;try{r=await di()}catch(e){return m(`auth login --key: ephemeral encryption key could not be created — ${T(e)}`)}let i=li.safeParse({clientLabel:e.clientLabel?.trim()||(jt().trim()||H).slice(0,120),clientPlatform:Xi(),encryptionAlgorithm:Vi,encryptionPublicKey:r.publicKey});if(!i.success)return m(`auth login --key: ${me(i.error)}`);let a;try{a=await Ti(i.data)}catch(e){return m(`auth login --key: could not start browser authorization — ${T(e)}`)}let o;try{o=xe(a,n)}catch(e){return m(`auth login --key: unsafe browser authorization URL rejected — ${T(e)}`)}if(!Yi(await ye(a,n,{noBrowser:e.noBrowser}),a,o))return m(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[o]});let s;try{s=await Ji(a)}catch(e){return m(`auth login --key: authorization did not complete — ${T(e)}`,[],{references:[o]})}if(s.algorithm!==Vi)return m(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await fi(r.privateKey,s)}catch(e){return m(`auth login --key: encrypted credential could not be opened — ${T(e)}`)}let l=await Mi(c);if(l.state!==`verified`)return m(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await ve(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return m(`auth login --key: credential could not be durably stored — ${T(e)}`)}let d;try{d=await qi(a)}catch(e){return U(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${T(e,[a.pollSecret])}`,Wi)}if(d.status!==`CONSUMED`)return U(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Wi);let f=await Mi(c);if(f.state!==`verified`||!ea(f.apiKey,u.credential.apiKey))return U(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Wi);try{let e=await ve(t,{apiKey:f.apiKey,secret:c},`active`);return x(`API key stored; authenticated identity and broker acknowledgment verified.`,$i(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return U(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${T(e)}`,Wi)}}async function Ki(e){let t=await Mi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?x(`API key is already stored and its authenticated identity was verified.`,$i(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${H} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&ea(t.apiKey,e.credential.apiKey))try{let n=await ve(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return x(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,$i(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return U(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${T(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${H} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return U(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${H} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await zi(e);if(n.outcome===`unconfirmed`)return U(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await Te(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${T(t,[e.credential.secret])}`)}return N.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
12
12
  `:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
13
- `),null}async function Ji(e){let t=new Date(e.expiresAt).getTime(),n=Qi(e.intervalSeconds);for(;;)try{return await Oi(e.id,e.pollSecret)}catch(e){if(e instanceof wi){if(!e.retryable)throw e;n=Qi(e.retryAfterSeconds??n)}else if(!(e instanceof Ti))throw e;if(Date.now()>=t)throw e;N.write(`Broker acknowledgment was interrupted; retrying.
14
- `),await $i(n,t)}}async function Yi(e){let t=new Date(e.expiresAt).getTime(),n=Qi(e.intervalSeconds),r;for(N.write(`Waiting for browser approval...
15
- `);Date.now()<t;){let i;try{i=await Di(e.id,e.pollSecret)}catch(e){if(e instanceof wi){if(!e.retryable)throw e;n=Qi(e.retryAfterSeconds??n)}r=e,N.write(`Authorization poll was interrupted; retrying.
16
- `),await $i(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Qi(i.retryAfterSeconds??n),await $i(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:throw Error(re(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${T(r,[e.pollSecret])}`)}function Xi(e,t,n){let r=e.state===`opened`;return!r&&!N.isTTY?!1:(N.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...N.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
17
- `)),!0)}function Zi(){switch(Mt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Qi(e){return Math.min(Wi,Math.max(Ui,e))}async function $i(e,t){let n=t-Date.now();n>0&&await Nt(Math.min(e*1e3,n))}function ea(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:re(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function H(e,t,n,r){return{...m(n,r===void 0?[]:[r]),data:ea(e,t)}}function ta(e,t){return e.expiresAt===null||e.expiresAt===void 0||t.expiresAt===null||t.expiresAt===void 0?!1:new Date(e.expiresAt)>new Date(t.expiresAt)}async function na(){return null}async function ra(e){let t=null,n=e=>{t=e};try{await Ie(e,n),await Re(n)}catch(e){return{materialized:t,failure:T(e)}}return{materialized:t,failure:null}}async function ia(e,t,n,r){if(r.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:r.failure};let i=null,a=null,o,s=e=>{o=e,a=aa(e.credential,r.materialized)};try{let t=await ue({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(oa(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=ua(t.data),e===`read`)return{scope:e,selected:a,identity:null,authorization:i,error:null};if(o===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await na(e,o);return{scope:e,selected:a,identity:n,authorization:i,error:null}}catch(r){return{scope:e,selected:a,identity:null,authorization:i,error:T(r,sa(t,n,o))}}}function aa(e,t){if(e===null)return null;let n=t??ke().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function oa(e){return[e.summary,...e.warnings].join(` — `)}function sa(e,t,n){return[b().userBearerToken,...ee(n?.headers??{}),...e.state===`found`?Me(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function ca(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:re(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:pa(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function la(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:Ee(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:De(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ua(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=h.safeParse(e.response);if(!t.success)throw t.error;return t.data}function da(e,t){let{expiresAt:n,expiresInDay:r}=ca(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with aVenture sign-in)`:``}var fa=864e5;function pa(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/fa)}var ma=7;function ha(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ma)}\u2026${e.slice(-4)}`}var ga=13,_a=14;function va(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...ba(e.oauth,e.cliName,e.refresh),...Sa(e.apiKey,e.oauth,e.cliName),``,U(`Providers`,Ta(e.providers)),U(`Environment`,Ea(e.resolved)),U(`Selected`,Da(e.resolved,e.refresh,e.cliName)),...ya(e.live),...e.systemOk?[]:[U(`System`,`uptime read failed`)]].join(`
18
- `)}function ya(e){if(e===null)return[];let t=W(`local credential provenance was captured before verification`);if(e.error!==null)return[``,U(`Live probe`,`${e.scope} permission probe failed`),t,W(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,U(`Live probe`,`${e.scope} permission probe succeeded`),t,W(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[W(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[U(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],W(`no API operation was executed or individually authorized`)]}function U(e,t){return` ${e.padEnd(ga)}${t}`}function W(e){return` ${``.padEnd(ga)}${e}`}function ba(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=De(r);return[U(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),W(xa(r,t,n))]}case`missing`:return[U(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[W(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[U(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[U(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function xa(e,t,n){return Ee(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function Sa(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[U(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[W(`stored credential invalid: ${e.error}`)]]:[U(`Signed in`,`credential storage unavailable`),W(r)]}return[U(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),W(`via ${e.provider??`unknown store`}`),U(`Key`,`${e.name??`unnamed`} ${ha(e.apiKeyId)}`),...Ca(e,n),U(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ca(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[U(`Key state`,`rejected by aVenture sign-in \u2014 ${n.summary}`),W(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[U(`Key state`,a?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[W(`no expiry recorded`)]:[W(wa(i,r,a?`expires`:`cached expiry`))],...a?[]:[W(n===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${n.summary}`)]]}function wa(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=_a?`${n} ${r}, ${t}d away`:`${n} ${r}`}function Ta(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${je(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Ea(e){return`${d.authToken}=${e.present?e.source??`resolved`:`unset`}`}function Da(e,t,n){return e.present||t.materialized===`env`?`${d.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${n} auth login\``}var Oa=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,ka=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Aa=`.aventure-cli-completion.bak`;function ja(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Ra([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Ra([`--uninstall`]))}function Ma(e,t){e.command(`setup`).summary(`configure zsh completion startup`).description(`Configure ~/.zshrc so zsh loads ${t} completion loaders.`).option(`--dry-run`,`print the managed zshrc block without writing`).option(`--yes`,`apply without prompting`).option(`--uninstall`,`remove the managed zshrc block`).action(async e=>{let t=Ia(),n=await Fa({rcFile:A(At(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Ya});M.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Ra(e.uninstall?[`--uninstall`]:[])})}function Na(e,t=`fpath-only`){return[Oa,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],ka].join(`
19
- `)}function Pa(){let e=Ra([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!za(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=Ra([],`pipe`);return t.status===0?{refreshed:!0,message:(t.stdout??``).trim()||`shell completions refreshed`}:{refreshed:!1,message:`completion refresh exited ${t.status??1}`}}async function Fa({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Ba(e),o=a.length===0?[]:a.split(`
20
- `),s=Va(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ha(o,s,t,e):Ua(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: unchanged; pass --yes to apply without a prompt`,content:a}:(Ka(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Ia(e=M.argv[1]){let t=e===void 0?``:La(e),n=A(k(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return pt(n)?n:A(k(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function La(e){try{return yt(e)}catch{return A(e)}}function Ra(e,t=`inherit`){let n=ut(M.execPath,[Ia(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(M.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function za(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Ba(e){return pt(e)?(qa(e),_t(e,`utf8`)):``}function Va(e,t){let n=Wa(e,Oa),r=Wa(e,ka);if(n.length===0&&r.length===0)return null;if(n.length!==1||r.length!==1||n[0]>=r[0])throw Error(`${t} has malformed managed completion setup markers; fix manually before retrying.`);return[n[0],r[0]]}function Ha(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Ga(i),o=Na(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
21
- `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return Ja([...i.slice(0,c),...o,...i.slice(c)])}function Ua(e,t){return Ja(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Wa(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Ga(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ka(e,t){ht(k(e),{recursive:!0}),pt(e)&&(qa(e),qa(`${e}${Aa}`),ft(e,`${e}${Aa}`));let n=A(k(e),`.${dt(e)}.${M.pid}.tmp`);qa(n),Ct(n,t,{mode:420}),bt(n,e)}function qa(e){if(pt(e)&&mt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Ja(e){let t=e.join(`
13
+ `),null}async function qi(e){let t=new Date(e.expiresAt).getTime(),n=Zi(e.intervalSeconds);for(;;)try{return await Di(e.id,e.pollSecret)}catch(e){if(e instanceof Ci){if(!e.retryable)throw e;n=Zi(e.retryAfterSeconds??n)}else if(!(e instanceof wi))throw e;if(Date.now()>=t)throw e;N.write(`Broker acknowledgment was interrupted; retrying.
14
+ `),await Qi(n,t)}}async function Ji(e){let t=new Date(e.expiresAt).getTime(),n=Zi(e.intervalSeconds),r;for(N.write(`Waiting for browser approval...
15
+ `);Date.now()<t;){let i;try{i=await Ei(e.id,e.pollSecret)}catch(e){if(e instanceof Ci){if(!e.retryable)throw e;n=Zi(e.retryAfterSeconds??n)}r=e,N.write(`Authorization poll was interrupted; retrying.
16
+ `),await Qi(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Zi(i.retryAfterSeconds??n),await Qi(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:throw Error(re(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${T(r,[e.pollSecret])}`)}function Yi(e,t,n){let r=e.state===`opened`;return!r&&!N.isTTY?!1:(N.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...N.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
17
+ `)),!0)}function Xi(){switch(Mt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Zi(e){return Math.min(Ui,Math.max(Hi,e))}async function Qi(e,t){let n=t-Date.now();n>0&&await Nt(Math.min(e*1e3,n))}function $i(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:re(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...m(n,r===void 0?[]:[r]),data:$i(e,t)}}function ea(e,t){return e.expiresAt===null||e.expiresAt===void 0||t.expiresAt===null||t.expiresAt===void 0?!1:new Date(e.expiresAt)>new Date(t.expiresAt)}async function ta(){return null}async function na(e){let t=null,n=e=>{t=e};try{await Ie(e,n),await Re(n)}catch(e){return{materialized:t,failure:T(e)}}return{materialized:t,failure:null}}async function ra(e,t,n,r){if(r.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:r.failure};let i=null,a=null,o,s=e=>{o=e,a=ia(e.credential,r.materialized)};try{let t=await ue({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(aa(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=la(t.data),e===`read`)return{scope:e,selected:a,identity:null,authorization:i,error:null};if(o===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await ta(e,o);return{scope:e,selected:a,identity:n,authorization:i,error:null}}catch(r){return{scope:e,selected:a,identity:null,authorization:i,error:T(r,oa(t,n,o))}}}function ia(e,t){if(e===null)return null;let n=t??ke().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function aa(e){return[e.summary,...e.warnings].join(` — `)}function oa(e,t,n){return[b().userBearerToken,...ee(n?.headers??{}),...e.state===`found`?Me(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function sa(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:re(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:fa(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ca(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:Ee(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:De(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function la(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=h.safeParse(e.response);if(!t.success)throw t.error;return t.data}function ua(e,t){let{expiresAt:n,expiresInDay:r}=sa(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with aVenture sign-in)`:``}var da=864e5;function fa(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/da)}var pa=7;function ma(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,pa)}\u2026${e.slice(-4)}`}var ha=13,ga=14;function _a(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...ya(e.oauth,e.cliName,e.refresh),...xa(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,wa(e.providers)),W(`Environment`,Ta(e.resolved)),W(`Selected`,Ea(e.resolved,e.refresh,e.cliName)),...va(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
18
+ `)}function va(e){if(e===null)return[];let t=G(`local credential provenance was captured before verification`);if(e.error!==null)return[``,W(`Live probe`,`${e.scope} permission probe failed`),t,G(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,W(`Live probe`,`${e.scope} permission probe succeeded`),t,G(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[G(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[W(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],G(`no API operation was executed or individually authorized`)]}function W(e,t){return` ${e.padEnd(ha)}${t}`}function G(e){return` ${``.padEnd(ha)}${e}`}function ya(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=De(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(ba(r,t,n))]}case`missing`:return[W(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[G(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[W(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[W(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function ba(e,t,n){return Ee(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function xa(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[W(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[G(`stored credential invalid: ${e.error}`)]]:[W(`Signed in`,`credential storage unavailable`),G(r)]}return[W(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),G(`via ${e.provider??`unknown store`}`),W(`Key`,`${e.name??`unnamed`} ${ma(e.apiKeyId)}`),...Sa(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Sa(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by aVenture sign-in \u2014 ${n.summary}`),G(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[W(`Key state`,a?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(Ca(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${n.summary}`)]]}function Ca(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=ga?`${n} ${r}, ${t}d away`:`${n} ${r}`}function wa(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${je(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Ta(e){return`${d.authToken}=${e.present?e.source??`resolved`:`unset`}`}function Ea(e,t,n){return e.present||t.materialized===`env`?`${d.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${n} auth login\``}var Da=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,Oa=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,ka=`.aventure-cli-completion.bak`;function Aa(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>La([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>La([`--uninstall`]))}function ja(e,t){e.command(`setup`).summary(`configure zsh completion startup`).description(`Configure ~/.zshrc so zsh loads ${t} completion loaders.`).option(`--dry-run`,`print the managed zshrc block without writing`).option(`--yes`,`apply without prompting`).option(`--uninstall`,`remove the managed zshrc block`).action(async e=>{let t=Fa(),n=await Pa({rcFile:A(At(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Ja});M.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&La(e.uninstall?[`--uninstall`]:[])})}function Ma(e,t=`fpath-only`){return[Da,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],Oa].join(`
19
+ `)}function Na(){let e=La([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!Ra(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=La([],`pipe`);return t.status===0?{refreshed:!0,message:(t.stdout??``).trim()||`shell completions refreshed`}:{refreshed:!1,message:`completion refresh exited ${t.status??1}`}}async function Pa({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=za(e),o=a.length===0?[]:a.split(`
20
+ `),s=Ba(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Va(o,s,t,e):Ha(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: unchanged; pass --yes to apply without a prompt`,content:a}:(Ga(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Fa(e=M.argv[1]){let t=e===void 0?``:Ia(e),n=A(k(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return pt(n)?n:A(k(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function Ia(e){try{return yt(e)}catch{return A(e)}}function La(e,t=`inherit`){let n=ut(M.execPath,[Fa(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(M.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function Ra(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function za(e){return pt(e)?(Ka(e),_t(e,`utf8`)):``}function Ba(e,t){let n=Ua(e,Da),r=Ua(e,Oa);if(n.length===0&&r.length===0)return null;if(n.length!==1||r.length!==1||n[0]>=r[0])throw Error(`${t} has malformed managed completion setup markers; fix manually before retrying.`);return[n[0],r[0]]}function Va(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Wa(i),o=Ma(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
21
+ `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return qa([...i.slice(0,c),...o,...i.slice(c)])}function Ha(e,t){return qa(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Ua(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Wa(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ga(e,t){ht(k(e),{recursive:!0}),pt(e)&&(Ka(e),Ka(`${e}${ka}`),ft(e,`${e}${ka}`));let n=A(k(e),`.${dt(e)}.${M.pid}.tmp`);Ka(n),Ct(n,t,{mode:420}),bt(n,e)}function Ka(e){if(pt(e)&&mt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function qa(e){let t=e.join(`
22
22
  `);return t.length===0||t.endsWith(`
23
- `)?t:`${t}\n`}async function Ya(e){if(!M.stdin.isTTY)return!1;let t=Pt({input:M.stdin,output:M.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Xa=new Intl.Collator(void 0,{numeric:!0}),Za=2e4;function Qa(e,t=f()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from npm.`;D(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(rebuild that checkout instead). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
24
- `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>I({mode:E(e)},$a()))}function $a(e,t=`apply`){let n=e;try{n??=f(process.argv[1])}catch(e){return m(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,a=n.registry===``?``:oe,o=n.registry===``&&r===`@aventurevc/aventure-cli`,s=eo([`view`,a,`version`,`--silent`,`--global`],n,{timeout:Za});if(!s.ok)return{...s,data:null};let c=(s.data??``).trim();if(c===``)return m(`npm view ${a} returned empty version`,[`empty_stdout`]);let l=o||Xa.compare(i,c)<0,u={targetPackage:a,runningPackage:r,currentVersion:i,latestVersion:c,upgradeAvailable:l,upgradeInstalled:!1};if(t===`check`)return x(`${r}@${i} → ${a}@${c} (${l?`available`:`up to date`})`,u);if(!l)return x(`${r}@${i} already matches ${a}@${c}`,u);if(n.workingTreeRoot!==null)return m(`Refusing to install over the working-tree build at ${n.workingTreeRoot}; rebuild via make instead`,["running CLI is npm-linked from the back-end checkout — `update` is for published bins"]);let d=ro(n),p=d===null?[]:[`--prefix`,d.installPrefix],h=d===null?null:A(d.installPrefix,`lib`,`node_modules`,...a.split(`/`)),g=o?to(d,a,c):[];if(o){let e=eo([`uninstall`,`-g`,...p,oe],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return m(`Cannot remove the retired ${oe}: ${e.summary}`,[...e.warnings,...g])}let _;try{_=io(n,d)}catch(e){return m(`Cannot prepare MCP-owned CLI bins: ${so(e)}`,[`npm install was not run`])}let v=eo([`install`,`-g`,...p,`${a}@${c}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!v.ok){let e=ao(_,h);return e===null?{...v,warnings:[...v.warnings,...g],data:null}:m(`${v.summary}; MCP-owned CLI bin restoration failed`,[...v.warnings,e])}let y=d===null?void 0:no(d.installPrefix,a,c);if(y?.ok===!1){let e=ao(_,h);return e===null?{...y,warnings:[...y.warnings,...g],data:null}:m(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let ee=oo(_);if(ee!==null)return m(`${a} upgraded but MCP CLI bin backup cleanup failed`,[ee]);let te=co();return x(`${a} upgraded to ${c}`,{...u,upgradeInstalled:!0,installPrefix:d?.installPrefix,verifiedVersion:y?.data??void 0,completionRefreshed:te.refreshed,completionRefreshMessage:te.message})}function eo(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=ut(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?m(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):m(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
25
- `).slice(-3).join(` | `);return m(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return x(`npm ok`,a.stdout??``)}function to(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${oe}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function no(e,t,n){let r;try{let n=f(A(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=A(e,`bin`,n.bin[0])}catch(e){return m(`updated ${t} verification failed: ${so(e)}`,[`invalid_package_metadata`])}let i=ut(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return m(`updated ${t} verification failed: ${i.error.message}`,[`spawn_error`]);let a=(i.stdout??``).trim();if(i.status!==0||a!==n){let e=(i.stderr??``).trim().split(`
26
- `).slice(-3).join(` | `);return m(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return x(`active CLI version verified`,a)}function ro(e){let t=`${j}lib${j}node_modules${j}${e.name.replace(`/`,j)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function io(e,t){if(e.name!==`@aventurevc/mcp-server`)return{backup:[],backupDirectory:null};if(t===null)throw Error(`the running MCP package is not in a verifiable global npm prefix`);if(!e.entryPath.startsWith(`${e.packageRoot}${j}`))throw Error(`the running CLI entry is outside the MCP package root`);let n=e.bin.filter(e=>e===`aventure`||e===`aventure-cli`).flatMap(n=>{let r=A(t.installPrefix,`bin`,n),i=mt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=yt(r)}catch(e){throw Error(`${r} has a missing target`,{cause:e})}if(a!==e.entryPath)throw Error(`${r} is not owned by the running MCP CLI`);return{binPath:r,linkTarget:vt(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=gt(A(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:A(r,dt(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(bt(e.binPath,e.backupPath),a.push(e),vt(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=ao({backup:a,backupDirectory:r},null);throw Error(`could not displace verified MCP CLI bins${t===null?``:`; restoration failed: ${t}`}`,{cause:e})}return{backup:a,backupDirectory:r}}function ao(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=mt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=A(k(r.binPath),vt(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${j}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);St(r.binPath)}bt(r.backupPath,r.binPath)}catch(e){n.push(so(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){n.push(so(e))}return n.length===0?null:n.join(`; `)}function oo(e){let t=[];for(let n of e.backup)try{St(n.backupPath)}catch(e){t.push(so(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){t.push(so(e))}return t.length===0?null:t.join(`; `)}function so(e){return e instanceof Error?e.message:String(e)}function co(){try{return Pa()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var lo=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers its generated status operation`},{name:`auth`,purpose:`which credential scope materialized locally, never the secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],uo=`operationFingerprint`;function fo(e,t=f().bin[0]){D(e.command(`doctor`).summary(`One-call selftest: CLI version, schemas, API host, auth scope, command catalog`).description(["Run every environment check in one call and report `{ ok, check: [...] }`:",...lo.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable)`,`does not fail the run. Each failing message names the command that fixes it.`,"--json always carries the report at `.data`; --data prints the report directly when",`every check passes and the result envelope when one fails, like every other command.`].join(`
27
- `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),I({mode:E(e)},await po(t))})}async function po(e){let t=ho(),n=go(e),[r,i]=await Promise.all([_o(e),vo(t,e)]),a=[n.check,r,i.check,await bo(e),Eo(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:mo(a,`pass`),fail:mo(a,`fail`),skip:mo(a,`skip`)},s=a.filter(e=>e.status===`fail`).map(e=>e.message),c={ok:s.length===0,check:a},l=[`doctor: ${o.pass} pass, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
28
- `);return c.ok?x(l,c,{counts:o}):{...m(l,s,{counts:o}),data:c}}function mo(e,t){return e.filter(e=>e.status===t).length}function G(e,t,n){return{name:e,status:t,message:n}}function ho(){return O.find(e=>e.intent===`status`&&e.resource===`status`)}function go(e){let t=f(),n=$a(t,`check`);if(!n.ok||n.data===null)return{check:G(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?G(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):G(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function _o(e){try{let{EntityDetailSchema:e}=await import(`./detail-D4XYLrLh.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return G(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return G(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${T(t)}.`)}}async function vo(e,t){if(e===void 0)return{check:G(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=b().host}catch(e){return{check:G(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${T(e)}.`),servedFingerprint:null}}let r=await ue({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>m(T(e)));return r.ok?{check:G(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:yo(r.data)}:{check:G(`api-host`,`fail`,r.httpStatus===401?`Replace or unset the credential ${n} rejected, or run \`${t} auth login\`, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} returned ${r.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function yo(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)return null;let{response:t}=e;if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t[uo];return typeof n==`string`&&n.length>0?n:null}async function bo(e){let t=ke(),[n,r]=await Promise.all([xo(),So()]);if(r.state===`unavailable`&&r.cause===`environment`)return G(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?G(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Ee(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?G(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&r.state!==`found`&&n.state===`unavailable`?G(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${d.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?G(`auth`,`pass`,`Credential source available: ${Co(t,n,r)}.`):r.state===`unavailable`?G(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${d.authToken} through the environment — ${r.summary}.`):G(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${d.authToken} in the environment.`)}async function xo(){let e;try{e=Pe(b().host)}catch(e){return{state:`unavailable`,summary:T(e)}}return await Fe(e)}async function So(){let e;try{e=Ve(b().host)}catch(e){return{state:`unavailable`,summary:T(e),cause:`environment`}}try{return await Be(e)}catch(e){return{state:`unavailable`,summary:T(e),cause:`storage`}}}function Co(e,t,n){return[Ea(e),`oauth=${To(t)}`,`api-key=${wo(n)}`].join(` `)}function wo(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Ve(b().host);return`${e.stored.activation}${da(t,e)}`}function To(e){switch(e.state){case`found`:return Ee(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function Eo(e,t,n,r){let i=O.length;if(e===void 0)return G(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return G(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Ze}.`);if(t===`75f58a2ed588ab9c`)return G(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Ze}).`);let a=`This catalog describes a different operation set than the API serves (${Ze} vs ${t})`;return n===!0?G(`catalog`,`fail`,`${a}: run \`${r} update\`.`):G(`catalog`,`skip`,n===!1?`${a}, and this CLI is already the latest published release: either the deployed API is older than this CLI, or a newer CLI has not been published yet.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var Do=z(B,`oauth`),Oo=[z(B,`start`),z(B,`poll`),z(B,`acknowledge`)],ko=z(B,`revoke`);function Ao(e,t=f().bin[0]){let n=Mo(e);fo(n,t);let r=[`${Do.description} Default method: OAuth in your browser.`,`With --key: ${Oo.map(({description:e})=>e).join(` `)}`].join(`
29
- `),a=async function(e){No(this);let t=E(e);if(e.providers===!0){I({mode:t},await Io());return}I({mode:t},e.key===!0?await Ki({noBrowser:!e.browser,clientLabel:e.clientLabel}):await ct({noBrowser:!e.browser}))};D(jo(n,[Do,...Oo],r)).action(a),D(jo(n,[ko],ko.description)).action(async function(e){No(this),I({mode:E(e)},await Fi({forgetLocal:e.forgetLocal===!0}))}),D(n.command(`status`).summary(`Keep saved credentials current and report them with API build and uptime`).description([`Runs the same credential materialization every command runs, then reports:`,` - auth: whether AUTH_TOKEN was already set in this shell's environment`,` - oauth: the saved OAuth identity and access-token expiry for the selected API host;`,` an expired token is renewed with its refresh token and a token the sign-in service rejects is retired`,` - api-key: the saved aVenture API key, re-verified with aVenture sign-in and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (browser sign-in and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (uptime SLA)`,``,`Saved credentials are sent only to the selected API host and aVenture sign-in, never printed.`,`--verify read|write additionally runs a live permission probe for that scope; it does not`,`execute or authorize an arbitrary API operation.`].join(`
30
- `)).addOption(new i(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){No(this),I({mode:E(e)},await Po(t,e.verify))}),n.command(`token`).summary(`Print the bearer token the next command sends`).description([`Runs the same credential materialization every command runs, then prints the selected`,`bearer token alone on stdout: ${d.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved aVenture API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
31
- `)).action(async function(){No(this);let e=await ra(t),n=process.env[d.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}I({mode:`text`},e.failure===null?Ho(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):m(`auth token: ${e.failure}`))})}function jo(e,t,n){let[r]=t,i=e.command(r.command.slice(r.command.indexOf(` `)+1)).summary(r.summary).description(n),a=new Set;for(let e of t)for(let t of[...e.bodyOption,...e.localOption])a.has(t.flag)||(a.add(t.flag),`required`in t&&t.required?i.requiredOption(t.flag,t.description):i.option(t.flag,t.description));return i}function Mo(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${Do.command}\`: ${Do.summary}; \`--key\` ${Oo[0].summary.toLowerCase()}.`,`\`${ko.command}\`: ${ko.summary}.`,"`auth status` reports local credential provenance, sign-in providers, and CLI/API build and uptime.","`auth doctor` runs the one-call selftest and prints `{ ok, check: [...] }`.","`auth token` prints the bearer token the next command sends."].join(`
32
- `))}function No(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Po(e,t){let n;try{n=Pe(b().host)}catch(e){return m(`auth status: invalid API host — ${T(e)}`)}let r=ke(),i=ra(e),[a,o,s]=await Promise.all([Vo(`/v1/status`,`GET /v1/status`),Vo(`/info`,`GET /info`),Lo()]),c=await i,[l,u]=await Promise.all([Fe(n),Fo(n)]),p=t===void 0?null:await ia(t,l,u.inspection,c),h=f().version,g=ca(n,u.inspection,u.verification),_=va({cliName:e,cliVersion:h,apiVersion:o.ok?zo(o.data):null,oauth:l,apiKey:g,providers:s,resolved:r,refresh:c,systemOk:a.ok,live:p}),v={cli:{version:h},api:o.ok?o.data??null:null,auth:{[d.authToken]:r},selected:c.materialized,oauth:la(n,l),apiKey:g,providers:s,live:p,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return c.failure===null?!o.ok&&o.httpStatus===401?{...m(`auth status: the API rejected the selected credential (401) | ${_}`,[`Replace or unset ${d.authToken}, or run \`${e} auth login\`.`]),data:v}:p!==null&&p.error!==null?{...m(`auth status: ${p.scope} permission probe failed — ${p.error}`,[p.error]),data:v}:p!==null||r.present||l.state===`found`||u.inspection.state===`found`?x(_,v):Ho(`auth status: no credentials resolved | ${_}`,v,e,{oauth:l.state===`missing`,apiKey:u.inspection.state===`missing`}):{...m(`auth status: ${c.failure} | ${_}`,[c.failure]),data:v}}async function Fo(e){let t=await Ro(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Mi(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Io(){let e=await Lo();return e.state===`found`?x(`Sign-in providers for the selected API host`,e.catalog):m(`auth login --providers: ${e.summary}`)}async function Lo(){try{return{state:`found`,catalog:await st()}}catch(e){return{state:`unavailable`,summary:T(e)}}}async function Ro(e){try{return await Be(e)}catch(e){return{state:`invalid`,summary:T(e)}}}function zo(e){if(!Bo(e))return null;let t=si.safeParse(Reflect.get(e,`response`));if(!t.success)return null;let n=t.data.build.version?.trim();return n&&n.length>0?n:null}function Bo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Vo(e,t){return await ue({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>m(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Ho(t,n,r,i){return{...m(t,[...i.apiKey?[`For an API key (works over SSH), run \`${r} auth login --key\`.`]:[],...i.oauth?[`For OAuth, run \`${r} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${d.authToken} to an aVenture API key (create one at ${e}/settings/api-keys).`]),data:n}}function Uo(e,t=O,n=f().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{M.stdout.write(Go(e,i,t))});ja(r,n),Ma(r,n)}function Wo(){return f().bin}function Go(e,t,n=O,r=Wo()){let i=es(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...qo(e),...r.map(e=>`complete -c ${K(e)} -e`),`${ps(r)} -f`,...Jo(e,r),...Yo(e,i,r),``].join(`
33
- `):Ko(e,t,i,r)}function Ko(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=rs(e,n);return[...t===`zsh`?[`#compdef ${r.join(` `)}`]:[],`# ${t} completions for ${r.join(`, `)}`,`${i}_aventure_cli_commands=(`,...o.map(e=>` ${e}`),`)`,`${i}_aventure_cli_options=(`,...s.map(e=>` ${e}`),`)`,`${i}_aventure_cli_values=(`,...c.map(e=>` ${e}`),`)`,``,...os(t),...t===`bash`?[a,``]:[``]].join(`
34
- `)}function qo(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Xo(e).filter(e=>e.required||e.optional).flatMap(e=>ls(e)??[]).map(K).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
23
+ `)?t:`${t}\n`}async function Ja(e){if(!M.stdin.isTTY)return!1;let t=Pt({input:M.stdin,output:M.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Ya=new Intl.Collator(void 0,{numeric:!0}),Xa=2e4;function Za(e,t=f()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from npm.`;D(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(rebuild that checkout instead). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
24
+ `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>L({mode:E(e)},Qa()))}function Qa(e,t=`apply`){let n=e;try{n??=f(process.argv[1])}catch(e){return m(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,a=n.registry===``?``:oe,o=n.registry===``&&r===`@aventurevc/aventure-cli`,s=$a([`view`,a,`version`,`--silent`,`--global`],n,{timeout:Xa});if(!s.ok)return{...s,data:null};let c=(s.data??``).trim();if(c===``)return m(`npm view ${a} returned empty version`,[`empty_stdout`]);let l=o||Ya.compare(i,c)<0,u={targetPackage:a,runningPackage:r,currentVersion:i,latestVersion:c,upgradeAvailable:l,upgradeInstalled:!1};if(t===`check`)return x(`${r}@${i} → ${a}@${c} (${l?`available`:`up to date`})`,u);if(!l)return x(`${r}@${i} already matches ${a}@${c}`,u);if(n.workingTreeRoot!==null)return m(`Refusing to install over the working-tree build at ${n.workingTreeRoot}; rebuild via make instead`,["running CLI is npm-linked from the back-end checkout — `update` is for published bins"]);let d=no(n),p=d===null?[]:[`--prefix`,d.installPrefix],h=d===null?null:A(d.installPrefix,`lib`,`node_modules`,...a.split(`/`)),g=o?eo(d,a,c):[];if(o){let e=$a([`uninstall`,`-g`,...p,oe],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return m(`Cannot remove the retired ${oe}: ${e.summary}`,[...e.warnings,...g])}let _;try{_=ro(n,d)}catch(e){return m(`Cannot prepare MCP-owned CLI bins: ${K(e)}`,[`npm install was not run`])}let v=$a([`install`,`-g`,...p,`${a}@${c}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!v.ok){let e=io(_,h);return e===null?{...v,warnings:[...v.warnings,...g],data:null}:m(`${v.summary}; MCP-owned CLI bin restoration failed`,[...v.warnings,e])}let y=d===null?void 0:to(d.installPrefix,a,c);if(y?.ok===!1){let e=io(_,h);return e===null?{...y,warnings:[...y.warnings,...g],data:null}:m(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let ee=ao(_);if(ee!==null)return m(`${a} upgraded but MCP CLI bin backup cleanup failed`,[ee]);let te=oo();return x(`${a} upgraded to ${c}`,{...u,upgradeInstalled:!0,installPrefix:d?.installPrefix,verifiedVersion:y?.data??void 0,completionRefreshed:te.refreshed,completionRefreshMessage:te.message})}function $a(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=ut(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?m(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):m(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
25
+ `).slice(-3).join(` | `);return m(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return x(`npm ok`,a.stdout??``)}function eo(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${oe}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function to(e,t,n){let r;try{let n=f(A(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=A(e,`bin`,n.bin[0])}catch(e){return m(`updated ${t} verification failed: ${K(e)}`,[`invalid_package_metadata`])}let i=ut(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return m(`updated ${t} verification failed: ${i.error.message}`,[`spawn_error`]);let a=(i.stdout??``).trim();if(i.status!==0||a!==n){let e=(i.stderr??``).trim().split(`
26
+ `).slice(-3).join(` | `);return m(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return x(`active CLI version verified`,a)}function no(e){let t=`${j}lib${j}node_modules${j}${e.name.replace(`/`,j)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function ro(e,t){if(e.name!==`@aventurevc/mcp-server`)return{backup:[],backupDirectory:null};if(t===null)throw Error(`the running MCP package is not in a verifiable global npm prefix`);if(!e.entryPath.startsWith(`${e.packageRoot}${j}`))throw Error(`the running CLI entry is outside the MCP package root`);let n=e.bin.filter(e=>e===`aventure`||e===`aventure-cli`).flatMap(n=>{let r=A(t.installPrefix,`bin`,n),i=mt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=yt(r)}catch(e){throw Error(`${r} has a missing target`,{cause:e})}if(a!==e.entryPath)throw Error(`${r} is not owned by the running MCP CLI`);return{binPath:r,linkTarget:vt(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=gt(A(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:A(r,dt(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(bt(e.binPath,e.backupPath),a.push(e),vt(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=io({backup:a,backupDirectory:r},null);throw Error(`could not displace verified MCP CLI bins${t===null?``:`; restoration failed: ${t}`}`,{cause:e})}return{backup:a,backupDirectory:r}}function io(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=mt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=A(k(r.binPath),vt(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${j}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);St(r.binPath)}bt(r.backupPath,r.binPath)}catch(e){n.push(K(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){n.push(K(e))}return n.length===0?null:n.join(`; `)}function ao(e){let t=[];for(let n of e.backup)try{St(n.backupPath)}catch(e){t.push(K(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){t.push(K(e))}return t.length===0?null:t.join(`; `)}function K(e){return e instanceof Error?e.message:String(e)}function oo(){try{return Na()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var so=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers its generated status operation`},{name:`auth`,purpose:`which credential scope materialized locally, never the secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],co=`operationFingerprint`;function lo(e,t=f().bin[0]){D(e.command(`doctor`).summary(`One-call selftest: CLI version, schemas, API host, auth scope, command catalog`).description(["Run every environment check in one call and report `{ ok, check: [...] }`:",...so.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable)`,`does not fail the run. Each failing message names the command that fixes it.`,"--json always carries the report at `.data`; --data prints the report directly when",`every check passes and the result envelope when one fails, like every other command.`].join(`
27
+ `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),L({mode:E(e)},await uo(t))})}async function uo(e){let t=po(),n=mo(e),[r,i]=await Promise.all([ho(e),go(t,e)]),a=[n.check,r,i.check,await vo(e),wo(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:fo(a,`pass`),fail:fo(a,`fail`),skip:fo(a,`skip`)},s=a.filter(e=>e.status===`fail`).map(e=>e.message),c={ok:s.length===0,check:a},l=[`doctor: ${o.pass} pass, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
28
+ `);return c.ok?x(l,c,{counts:o}):{...m(l,s,{counts:o}),data:c}}function fo(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function po(){return O.find(e=>e.intent===`status`&&e.resource===`status`)}function mo(e){let t=f(),n=Qa(t,`check`);if(!n.ok||n.data===null)return{check:q(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?q(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):q(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function ho(e){try{let{EntityDetailSchema:e}=await import(`./detail-D4XYLrLh.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return q(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return q(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${T(t)}.`)}}async function go(e,t){if(e===void 0)return{check:q(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=b().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${T(e)}.`),servedFingerprint:null}}let r=await ue({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>m(T(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:_o(r.data)}:{check:q(`api-host`,`fail`,r.httpStatus===401?`Replace or unset the credential ${n} rejected, or run \`${t} auth login\`, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} returned ${r.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function _o(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)return null;let{response:t}=e;if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t[co];return typeof n==`string`&&n.length>0?n:null}async function vo(e){let t=ke(),[n,r]=await Promise.all([yo(),bo()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?q(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Ee(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?q(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${d.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${xo(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${d.authToken} through the environment — ${r.summary}.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${d.authToken} in the environment.`)}async function yo(){let e;try{e=Pe(b().host)}catch(e){return{state:`unavailable`,summary:T(e)}}return await Fe(e)}async function bo(){let e;try{e=Ve(b().host)}catch(e){return{state:`unavailable`,summary:T(e),cause:`environment`}}try{return await Be(e)}catch(e){return{state:`unavailable`,summary:T(e),cause:`storage`}}}function xo(e,t,n){return[Ta(e),`oauth=${Co(t)}`,`api-key=${So(n)}`].join(` `)}function So(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Ve(b().host);return`${e.stored.activation}${ua(t,e)}`}function Co(e){switch(e.state){case`found`:return Ee(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function wo(e,t,n,r){let i=O.length;if(e===void 0)return q(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return q(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Ze}.`);if(t===`75f58a2ed588ab9c`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Ze}).`);let a=`This catalog describes a different operation set than the API serves (${Ze} vs ${t})`;return n===!0?q(`catalog`,`fail`,`${a}: run \`${r} update\`.`):q(`catalog`,`skip`,n===!1?`${a}, and this CLI is already the latest published release: either the deployed API is older than this CLI, or a newer CLI has not been published yet.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var To=B(V,`oauth`),Eo=[B(V,`start`),B(V,`poll`),B(V,`acknowledge`)],Do=B(V,`revoke`);function Oo(e,t=f().bin[0]){let n=Ao(e);lo(n,t);let r=[`${To.description} Default method: OAuth in your browser.`,`With --key: ${Eo.map(({description:e})=>e).join(` `)}`].join(`
29
+ `),a=async function(e){jo(this);let t=E(e);if(e.providers===!0){L({mode:t},await Po());return}L({mode:t},e.key===!0?await Gi({noBrowser:!e.browser,clientLabel:e.clientLabel}):await ct({noBrowser:!e.browser}))};D(ko(n,[To,...Eo],r)).action(a),D(ko(n,[Do],Do.description)).action(async function(e){jo(this),L({mode:E(e)},await Pi({forgetLocal:e.forgetLocal===!0}))}),D(n.command(`status`).summary(`Keep saved credentials current and report them with API build and uptime`).description([`Runs the same credential materialization every command runs, then reports:`,` - auth: whether AUTH_TOKEN was already set in this shell's environment`,` - oauth: the saved OAuth identity and access-token expiry for the selected API host;`,` an expired token is renewed with its refresh token and a token the sign-in service rejects is retired`,` - api-key: the saved aVenture API key, re-verified with aVenture sign-in and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (browser sign-in and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (uptime SLA)`,``,`Saved credentials are sent only to the selected API host and aVenture sign-in, never printed.`,`--verify read|write additionally runs a live permission probe for that scope; it does not`,`execute or authorize an arbitrary API operation.`].join(`
30
+ `)).addOption(new i(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){jo(this),L({mode:E(e)},await Mo(t,e.verify))}),n.command(`token`).summary(`Print the bearer token the next command sends`).description([`Runs the same credential materialization every command runs, then prints the selected`,`bearer token alone on stdout: ${d.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved aVenture API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
31
+ `)).action(async function(){jo(this);let e=await na(t),n=process.env[d.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}L({mode:`text`},e.failure===null?Bo(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):m(`auth token: ${e.failure}`))})}function ko(e,t,n){let[r]=t,i=e.command(r.command.slice(r.command.indexOf(` `)+1)).summary(r.summary).description(n),a=new Set;for(let e of t)for(let t of[...e.bodyOption,...e.localOption])a.has(t.flag)||(a.add(t.flag),`required`in t&&t.required?i.requiredOption(t.flag,t.description):i.option(t.flag,t.description));return i}function Ao(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${To.command}\`: ${To.summary}; \`--key\` ${Eo[0].summary.toLowerCase()}.`,`\`${Do.command}\`: ${Do.summary}.`,"`auth status` reports local credential provenance, sign-in providers, and CLI/API build and uptime.","`auth doctor` runs the one-call selftest and prints `{ ok, check: [...] }`.","`auth token` prints the bearer token the next command sends."].join(`
32
+ `))}function jo(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Mo(e,t){let n;try{n=Pe(b().host)}catch(e){return m(`auth status: invalid API host — ${T(e)}`)}let r=ke(),i=na(e),[a,o,s]=await Promise.all([zo(`/v1/status`,`GET /v1/status`),zo(`/info`,`GET /info`),Fo()]),c=await i,[l,u]=await Promise.all([Fe(n),No(n)]),p=t===void 0?null:await ra(t,l,u.inspection,c),h=f().version,g=sa(n,u.inspection,u.verification),_=_a({cliName:e,cliVersion:h,apiVersion:o.ok?Lo(o.data):null,oauth:l,apiKey:g,providers:s,resolved:r,refresh:c,systemOk:a.ok,live:p}),v={cli:{version:h},api:o.ok?o.data??null:null,auth:{[d.authToken]:r},selected:c.materialized,oauth:ca(n,l),apiKey:g,providers:s,live:p,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return c.failure===null?!o.ok&&o.httpStatus===401?{...m(`auth status: the API rejected the selected credential (401) | ${_}`,[`Replace or unset ${d.authToken}, or run \`${e} auth login\`.`]),data:v}:p!==null&&p.error!==null?{...m(`auth status: ${p.scope} permission probe failed — ${p.error}`,[p.error]),data:v}:p!==null||r.present||l.state===`found`||u.inspection.state===`found`?x(_,v):Bo(`auth status: no credentials resolved | ${_}`,v,e,{oauth:l.state===`missing`,apiKey:u.inspection.state===`missing`}):{...m(`auth status: ${c.failure} | ${_}`,[c.failure]),data:v}}async function No(e){let t=await Io(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await ji(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Po(){let e=await Fo();return e.state===`found`?x(`Sign-in providers for the selected API host`,e.catalog):m(`auth login --providers: ${e.summary}`)}async function Fo(){try{return{state:`found`,catalog:await st()}}catch(e){return{state:`unavailable`,summary:T(e)}}}async function Io(e){try{return await Be(e)}catch(e){return{state:`invalid`,summary:T(e)}}}function Lo(e){if(!Ro(e))return null;let t=oi.safeParse(Reflect.get(e,`response`));if(!t.success)return null;let n=t.data.build.version?.trim();return n&&n.length>0?n:null}function Ro(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function zo(e,t){return await ue({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>m(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Bo(t,n,r,i){return{...m(t,[...i.apiKey?[`For an API key (works over SSH), run \`${r} auth login --key\`.`]:[],...i.oauth?[`For OAuth, run \`${r} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${d.authToken} to an aVenture API key (create one at ${e}/settings/api-keys).`]),data:n}}function Vo(e,t=O,n=f().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{M.stdout.write(Uo(e,i,t))});Aa(r,n),ja(r,n)}function Ho(){return f().bin}function Uo(e,t,n=O,r=Ho()){let i=Qo(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Go(e),...r.map(e=>`complete -c ${J(e)} -e`),`${ds(r)} -f`,...Ko(e,r),...qo(e,i,r),``].join(`
33
+ `):Wo(e,t,i,r)}function Wo(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=ts(e,n);return[...t===`zsh`?[`#compdef ${r.join(` `)}`]:[],`# ${t} completions for ${r.join(`, `)}`,`${i}_aventure_cli_commands=(`,...o.map(e=>` ${e}`),`)`,`${i}_aventure_cli_options=(`,...s.map(e=>` ${e}`),`)`,`${i}_aventure_cli_values=(`,...c.map(e=>` ${e}`),`)`,``,...is(t),...t===`bash`?[a,``]:[``]].join(`
34
+ `)}function Go(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Jo(e).filter(e=>e.required||e.optional).flatMap(e=>ss(e)??[]).map(J).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
35
35
  set -l expected $argv
36
36
  set -l actual (__aventure_cli_command_path)
37
37
  if test (count $actual) -ne (count $expected)
@@ -48,17 +48,17 @@ import{$ as e,C as t,D as n,E as r,Ft as i,It as a,Pt as o,Q as s,Rt as c,T as l
48
48
  return 0
49
49
  end
50
50
  `].flatMap(e=>e.split(`
51
- `))}function Jo(e,t){return ns(e).map(e=>`${ps(t)} -f -n ${K(ms(e.parentPath))} -a ${K(e.name)} -d ${K(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Yo(e,t,n){return us(e).flatMap(e=>{let r=fs(e),i=r.length===0?void 0:ms(r);return Xo(e).flatMap(e=>{let a=t.get(ts(r,e));return as(a)?Zo(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Xo(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function Zo(e,t,n,r){let i=ls(e);if(i===void 0)return[];let a=e.argChoices??is(n),o=[`-l ${K(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${K(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${K(t)}`,c=e.required||e.optional?Qo(a,$o(i,n)):`-f`,l=`${ps(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${K(hs(e.description))}`]:a.map(t=>`${l} -a ${K(t)} -d ${K(hs(e.description))}`)}function Qo(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function $o(e,t){return e===`from-file`?!0:t===void 0||t.some(({location:e})=>e!==`body`)?!1:t.every(({schemaFormat:e})=>e===`binary`)?!0:t.length===1&&[`file`,`path`].includes(e.split(`-`).at(-1)??``)}function es(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...fn(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].flatMap(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[[ts(e.cliPath,n),t]]})))}function ts(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):ls(t);if(`flag`in t&&(n===void 0||n.length===0||n===t.flag))throw Error(`Cannot render completion for option flag: ${t.flag}`);return`${e.join(`\0`)}\u0000${n??``}`}function ns(e){return us(e).flatMap(e=>e.commands.map(t=>({parentPath:fs(e),name:t.name(),description:hs(t.summary()||t.description()||t.name())})))}function rs(e,t){let n=[],r=[];for(let i of us(e)){let e=fs(i);for(let a of Xo(i)){let i=ls(a);if(i===void 0)continue;let o=t.get(ts(e,a));if(!as(o))continue;let s=a.argChoices??is(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&$o(i,o)&&(c=`file`)),n.push(ss([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(ss([e.join(` `),`--${i}`,t,a.description]))}}return[ns(e).map(e=>ss([e.parentPath.join(` `),e.name,e.description])).toSorted((e,t)=>e.localeCompare(t)),n.toSorted((e,t)=>e.localeCompare(t)),r.toSorted((e,t)=>e.localeCompare(t))]}function is(e){let t=e?.[0]?.choices;if(e!==void 0&&t!==void 0)return e.every(e=>e.choices?.length===t.length&&e.choices.every((e,n)=>e===t[n]))?t:void 0}function as(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function os(e){let t=e===`bash`,n=t?`COMP_WORDS`:`words`,r=t?`COMP_CWORD`:`CURRENT`,i=t?"${path[*]}":"${(j: :)path}",a=t?'"${_aventure_cli_options[@]}"':`$_aventure_cli_options`,o=t?'"${_aventure_cli_values[@]}"':`$_aventure_cli_values`,s=t?'"${_aventure_cli_commands[@]}"':`$_aventure_cli_commands`;return[`function _aventure_cli {`,` local current="\${${n}[${r}]}" previous="\${${n}[${r}-1]}" row row_path long short description mode name value option token key prefix candidate file_current`,...t?[` COMPREPLY=()`]:[],` local index=${t?1:2} skip_next=0; local -a path names descriptions`,` while (( index < ${r} )); do`,` token="\${${n}[index]}"; (( skip_next )) && { skip_next=0; (( index++ )); continue; }`,` if [[ "$token" == -* && "$token" != "-" && "$token" != "--" ]]; then`,` option="\${token%%=*}"; key="${i}"; mode=''`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && break; mode=''; done`,` [[ -n "$mode" && "$mode" != none && "$token" != *=* ]] && skip_next=1`,` elif [[ "$token" != -* ]]; then path+=("$token"); fi`,` (( index++ ))`,` done`,` key="${i}"`,` if [[ "$current" == --*=* || ( "$previous" == -* && "$current" != -* ) ]]; then`,` option="$previous"; prefix=''; file_current="$current"; [[ "$current" == --*=* ]] && { option="\${current%%=*}"; prefix="$option="; file_current="\${current#*=}"; }`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && { option="$long"; break; }; mode=''; done`,t?` [[ "$mode" == file ]] && { while IFS= read -r candidate; do COMPREPLY+=("$prefix$candidate"); done < <(compgen -f -- "$file_current"); return 0; }`:` [[ "$mode" == file ]] && { _files; return 0; }`,t?` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { candidate="$prefix$value"; [[ "$candidate" == "$current"* ]] && COMPREPLY+=("$candidate"); }; done`:` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { names+=("$prefix$value"); descriptions+=("$description"); }; done`,` elif [[ "$current" == -* ]]; then`,` for row in ${a}; do`,` IFS='|' read -r row_path long short description mode <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$long" == "$current"* ]] && COMPREPLY+=("$long"); [[ -n "$short" && "$short" == "$current"* ]] && COMPREPLY+=("$short"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$long"); descriptions+=("$description"); [[ -n "$short" ]] && { names+=("$short"); descriptions+=("$description"); }; }`,` done`,` elif [[ "$previous" != -* ]]; then`,` for row in ${s}; do`,` IFS='|' read -r row_path name description <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$name" == "$current"* ]] && COMPREPLY+=("$name"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$name"); descriptions+=("$description"); }`,` done`,` fi`,...t?[]:[" (( ${#names} )) && compadd -d descriptions -a names"],` return 0`,`}`,...t?[]:[`_aventure_cli "$@"`]]}function ss(e){return`$'${e.map(cs).join(`|`)}'`}function cs(e){return hs(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function ls(e){return e.long?.replace(/^--/,``)}function us(e){return[e,...e.commands.filter(ds).flatMap(e=>us(e))]}var ds=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function fs(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function ps(e){return`complete ${e.map(e=>`-c ${K(e)}`).join(` `)}`}function ms(e){return[`__aventure_cli_path_is`,...e.map(K)].join(` `)}function hs(e){return e.replace(/\s+/g,` `).trim()}function K(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function gs(e,t){if(e!==t)return;let n=_s(t);n!==void 0&&t.error(`error: ${ys(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function _s(e){if(!process.argv.includes(`--`)&&e.args.some(vs))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function vs(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function ys(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function bs(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function xs(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function Ss(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function q(e){return e.flags.split(` `)[0]??e.flags}function Cs(e,t){let n=bs(t);if(n===void 0)return;let r=e.options.findIndex(e=>q(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[q(t),e.getOptionValue(t.attributeName())]).find(([,e])=>typeof e==`string`&&e.length>0)?.[0];if(i!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${i} does not replace the parent selector.`}var ws=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`]];function Ts(e){let t=new Set(e.options.map(q)),n=process.argv.slice(2).filter(e=>e.startsWith(`--`)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e)).flatMap(e=>{let n=ws.find(t=>t.includes(e))?.find(e=>t.has(e));return n===void 0?[]:[`use ${n}, not ${e}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function J(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function Es(e){return e.commands.length===0?[e]:e.commands.flatMap(Es)}function Ds(e,t){return J(t).slice(J(e).length)}function Y(e){let t=e;for(;t.parent!==null;)t=t.parent;return t}function Os(e,t){return t.toSorted((t,n)=>{let r=Ds(e,t),i=Ds(e,n),a=+![`get`,`list`].includes(r.at(-1)??``),o=+![`get`,`list`].includes(i.at(-1)??``);return r.length-i.length||a-o})[0]}function X(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function ks(e,t){let n=J(e),r=process.argv.slice(2+n.length);return[Y(e).name(),...n,...Ds(e,t),...r].map(X).join(` `)}function As(e,t){let n=xs(t);if(n===void 0||e.commands.length===0)return;let r=Os(e,Es(e).filter(e=>e.options.some(e=>q(e)===n)));if(r!==void 0)return`hint: run: ${ks(e,r)}`}function Z(e){return e!==void 0&&Object.hasOwn(et,e)}function js(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e);if(t===void 0)return;n=t}return n}function Ms(e,t){let n=J(e),r=[...n.slice(1),t];if(!Z(n.at(0))||!Z(r.at(0)))return;let i=js(Y(e),r);if(i===void 0)return;let a=i;for(let e of process.argv.slice(2+n.length+1)){if(e.startsWith(`-`))break;let t=a.commands.find(t=>t.name()===e);if(t===void 0)break;r.push(e),a=t}return r}function Ns(e,t){let[n]=J(e);if(!Z(n))return;let r=[n,t];return js(Y(e),r)?.commands.length===0?r:void 0}function Ps(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Es(Y(e)).map(J),i=n.findIndex((e,t)=>{let i=[...n.slice(0,t),e];return!r.some(e=>e.some((t,n)=>t===i[0]&&i.every((t,r)=>e[n+r]===t)))});return[t,...i<0?n:n.slice(0,i)]}function Fs(e,t){let n=process.argv.slice(2+J(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return Is(e,t)}function Is(e,t,n=[]){let r=J(e),i=Ye(O).map(e=>e.cliPath).filter(e=>e[0]!==r[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),a=i.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(i.length===1?i[0]:void 0);if(a!==void 0)return`hint: run: ${[Y(e).name(),...a,...n].map(X).join(` `)}`}function Ls(e,t,n){if(!zs(t))return;let r=e.args.slice(n.length),i=r.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${[Y(e).name(),...t,...i<0?[]:r.slice(i)].map(X).join(` `)}`}function Rs(e){let t=J(e);if(t.at(1)!==void 0&&Z(t.at(0)))return`hint: inspect generated command group: ${[Y(e).name(),...t,`--help`].map(X).join(` `)}`}function zs(e,t){let n=e.join(` `);return O.some(e=>e.cliPath.join(` `)===n?t===void 0||l(e.intent)===t:!1)}function Bs(e){let t=J(e).join(` `),n=Ye(O),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:hr(r.operationId,n,Y(e).name()).map(e=>`hint: ${e}`)}function Vs(e){let t=J(e);if(Z(t.at(0))&&zs(t))return`hint: inspect generated command: ${[Y(e).name(),...t,`--help`].map(X).join(` `)}`}function Hs(e){let t=new Set,n=[];for(let r of O){let i=js(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(q);if(l(r.intent))n.push(a);else for(let e of a)t.add(e)}let[r=[],...i]=n;return new Set(r.filter(e=>!t.has(e)&&i.every(t=>t.includes(e))))}function Us(e,t){let n=J(e);if(zs(n,!1)&&Hs(Y(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Ws(e,t,n=!0){let r=Y(e),i=r.commands.find(e=>e.name()===`command-catalog`),a=i?.commands.find(e=>e.name()===`search`);if(i===void 0||a===void 0)return;let o=[r.name(),i.name(),a.name(),t],s=J(e).at(0),c=a.options.find(e=>q(e)===`--root`),l=n&&c!==void 0&&Z(s)?s:void 0;c!==void 0&&l!==void 0&&o.push(q(c),l);let u=Ye(O),d=tr({q:t,root:l,limit:`3`},u,r.name()),f=d.ok&&d.data!==null?Mr(d.data,`compact`):``;return[`hint: search generated commands: ${o.map(X).join(` `)}`,...f===``?[]:[`hint: closest commands (command · summary · required flags):`],...f.split(`
51
+ `))}function Ko(e,t){return es(e).map(e=>`${ds(t)} -f -n ${J(fs(e.parentPath))} -a ${J(e.name)} -d ${J(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function qo(e,t,n){return cs(e).flatMap(e=>{let r=us(e),i=r.length===0?void 0:fs(r);return Jo(e).flatMap(e=>{let a=t.get($o(r,e));return rs(a)?Yo(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Jo(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function Yo(e,t,n,r){let i=ss(e);if(i===void 0)return[];let a=e.argChoices??ns(n),o=[`-l ${J(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${J(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${J(t)}`,c=e.required||e.optional?Xo(a,Zo(i,n)):`-f`,l=`${ds(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${J(ps(e.description))}`]:a.map(t=>`${l} -a ${J(t)} -d ${J(ps(e.description))}`)}function Xo(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function Zo(e,t){return e===`from-file`?!0:t===void 0||t.some(({location:e})=>e!==`body`)?!1:t.every(({schemaFormat:e})=>e===`binary`)?!0:t.length===1&&[`file`,`path`].includes(e.split(`-`).at(-1)??``)}function Qo(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...dn(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].flatMap(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[[$o(e.cliPath,n),t]]})))}function $o(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):ss(t);if(`flag`in t&&(n===void 0||n.length===0||n===t.flag))throw Error(`Cannot render completion for option flag: ${t.flag}`);return`${e.join(`\0`)}\u0000${n??``}`}function es(e){return cs(e).flatMap(e=>e.commands.map(t=>({parentPath:us(e),name:t.name(),description:ps(t.summary()||t.description()||t.name())})))}function ts(e,t){let n=[],r=[];for(let i of cs(e)){let e=us(i);for(let a of Jo(i)){let i=ss(a);if(i===void 0)continue;let o=t.get($o(e,a));if(!rs(o))continue;let s=a.argChoices??ns(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&Zo(i,o)&&(c=`file`)),n.push(as([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(as([e.join(` `),`--${i}`,t,a.description]))}}return[es(e).map(e=>as([e.parentPath.join(` `),e.name,e.description])).toSorted((e,t)=>e.localeCompare(t)),n.toSorted((e,t)=>e.localeCompare(t)),r.toSorted((e,t)=>e.localeCompare(t))]}function ns(e){let t=e?.[0]?.choices;if(e!==void 0&&t!==void 0)return e.every(e=>e.choices?.length===t.length&&e.choices.every((e,n)=>e===t[n]))?t:void 0}function rs(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function is(e){let t=e===`bash`,n=t?`COMP_WORDS`:`words`,r=t?`COMP_CWORD`:`CURRENT`,i=t?"${path[*]}":"${(j: :)path}",a=t?'"${_aventure_cli_options[@]}"':`$_aventure_cli_options`,o=t?'"${_aventure_cli_values[@]}"':`$_aventure_cli_values`,s=t?'"${_aventure_cli_commands[@]}"':`$_aventure_cli_commands`;return[`function _aventure_cli {`,` local current="\${${n}[${r}]}" previous="\${${n}[${r}-1]}" row row_path long short description mode name value option token key prefix candidate file_current`,...t?[` COMPREPLY=()`]:[],` local index=${t?1:2} skip_next=0; local -a path names descriptions`,` while (( index < ${r} )); do`,` token="\${${n}[index]}"; (( skip_next )) && { skip_next=0; (( index++ )); continue; }`,` if [[ "$token" == -* && "$token" != "-" && "$token" != "--" ]]; then`,` option="\${token%%=*}"; key="${i}"; mode=''`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && break; mode=''; done`,` [[ -n "$mode" && "$mode" != none && "$token" != *=* ]] && skip_next=1`,` elif [[ "$token" != -* ]]; then path+=("$token"); fi`,` (( index++ ))`,` done`,` key="${i}"`,` if [[ "$current" == --*=* || ( "$previous" == -* && "$current" != -* ) ]]; then`,` option="$previous"; prefix=''; file_current="$current"; [[ "$current" == --*=* ]] && { option="\${current%%=*}"; prefix="$option="; file_current="\${current#*=}"; }`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && { option="$long"; break; }; mode=''; done`,t?` [[ "$mode" == file ]] && { while IFS= read -r candidate; do COMPREPLY+=("$prefix$candidate"); done < <(compgen -f -- "$file_current"); return 0; }`:` [[ "$mode" == file ]] && { _files; return 0; }`,t?` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { candidate="$prefix$value"; [[ "$candidate" == "$current"* ]] && COMPREPLY+=("$candidate"); }; done`:` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { names+=("$prefix$value"); descriptions+=("$description"); }; done`,` elif [[ "$current" == -* ]]; then`,` for row in ${a}; do`,` IFS='|' read -r row_path long short description mode <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$long" == "$current"* ]] && COMPREPLY+=("$long"); [[ -n "$short" && "$short" == "$current"* ]] && COMPREPLY+=("$short"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$long"); descriptions+=("$description"); [[ -n "$short" ]] && { names+=("$short"); descriptions+=("$description"); }; }`,` done`,` elif [[ "$previous" != -* ]]; then`,` for row in ${s}; do`,` IFS='|' read -r row_path name description <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$name" == "$current"* ]] && COMPREPLY+=("$name"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$name"); descriptions+=("$description"); }`,` done`,` fi`,...t?[]:[" (( ${#names} )) && compadd -d descriptions -a names"],` return 0`,`}`,...t?[]:[`_aventure_cli "$@"`]]}function as(e){return`$'${e.map(os).join(`|`)}'`}function os(e){return ps(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function ss(e){return e.long?.replace(/^--/,``)}function cs(e){return[e,...e.commands.filter(ls).flatMap(e=>cs(e))]}var ls=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function us(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function ds(e){return`complete ${e.map(e=>`-c ${J(e)}`).join(` `)}`}function fs(e){return[`__aventure_cli_path_is`,...e.map(J)].join(` `)}function ps(e){return e.replace(/\s+/g,` `).trim()}function J(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function ms(e,t){if(e!==t)return;let n=hs(t);n!==void 0&&t.error(`error: ${_s(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function hs(e){if(!process.argv.includes(`--`)&&e.args.some(gs))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function gs(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function _s(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function vs(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function ys(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function bs(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function Y(e){return e.flags.split(` `)[0]??e.flags}function xs(e,t){let n=vs(t);if(n===void 0)return;let r=e.options.findIndex(e=>Y(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[Y(t),e.getOptionValue(t.attributeName())]).find(([,e])=>typeof e==`string`&&e.length>0)?.[0];if(i!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${i} does not replace the parent selector.`}var Ss=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`]];function Cs(e){let t=new Set(e.options.map(Y)),n=process.argv.slice(2).filter(e=>e.startsWith(`--`)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e)).flatMap(e=>{let n=Ss.find(t=>t.includes(e))?.find(e=>t.has(e));return n===void 0?[]:[`use ${n}, not ${e}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function X(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function ws(e){return e.commands.length===0?[e]:e.commands.flatMap(ws)}function Ts(e,t){return X(t).slice(X(e).length)}function Z(e){let t=e;for(;t.parent!==null;)t=t.parent;return t}function Es(e,t){return t.toSorted((t,n)=>{let r=Ts(e,t),i=Ts(e,n),a=+![`get`,`list`].includes(r.at(-1)??``),o=+![`get`,`list`].includes(i.at(-1)??``);return r.length-i.length||a-o})[0]}function Ds(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Os(e,t){let n=X(e),r=process.argv.slice(2+n.length);return[Z(e).name(),...n,...Ts(e,t),...r].map(Ds).join(` `)}function ks(e,t){let n=ys(t);if(n===void 0||e.commands.length===0)return;let r=Es(e,ws(e).filter(e=>e.options.some(e=>Y(e)===n)));if(r!==void 0)return`hint: run: ${Os(e,r)}`}function As(e){return e!==void 0&&Object.hasOwn(et,e)}function js(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e);if(t===void 0)return;n=t}return n}function Ms(e,t){let n=X(e),r=[...n.slice(1),t];if(!As(n.at(0))||!As(r.at(0)))return;let i=js(Z(e),r);if(i===void 0)return;let a=i;for(let e of process.argv.slice(2+n.length+1)){if(e.startsWith(`-`))break;let t=a.commands.find(t=>t.name()===e);if(t===void 0)break;r.push(e),a=t}return r}function Ns(e,t){let[n]=X(e);if(!As(n))return;let r=[n,t];return js(Z(e),r)?.commands.length===0?r:void 0}function Ps(e){let[t,...n]=e.args;if(t===void 0)return[];let r=ws(Z(e)).map(X),i=n.findIndex((e,t)=>{let i=[...n.slice(0,t),e];return!r.some(e=>e.some((t,n)=>t===i[0]&&i.every((t,r)=>e[n+r]===t)))});return[t,...i<0?n:n.slice(0,i)]}function Fs(e,t){let n=process.argv.slice(2+X(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return Is(e,t)}function Is(e,t,n=[]){let r=X(e),i=Ye(O).map(e=>e.cliPath).filter(e=>e[0]!==r[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),a=i.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(i.length===1?i[0]:void 0);if(a!==void 0)return`hint: run: ${[Z(e).name(),...a,...n].map(Ds).join(` `)}`}function Ls(e,t,n){if(!zs(t))return;let r=e.args.slice(n.length),i=r.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${[Z(e).name(),...t,...i<0?[]:r.slice(i)].map(Ds).join(` `)}`}function Rs(e){let t=X(e);if(t.at(1)!==void 0&&As(t.at(0)))return`hint: inspect generated command group: ${[Z(e).name(),...t,`--help`].map(Ds).join(` `)}`}function zs(e,t){let n=e.join(` `);return O.some(e=>e.cliPath.join(` `)===n?t===void 0||l(e.intent)===t:!1)}function Bs(e){let t=X(e).join(` `),n=Ye(O),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:mr(r.operationId,n,Z(e).name()).map(e=>`hint: ${e}`)}function Vs(e){let t=X(e);if(As(t.at(0))&&zs(t))return`hint: inspect generated command: ${[Z(e).name(),...t,`--help`].map(Ds).join(` `)}`}function Hs(e){let t=new Set,n=[];for(let r of O){let i=js(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(Y);if(l(r.intent))n.push(a);else for(let e of a)t.add(e)}let[r=[],...i]=n;return new Set(r.filter(e=>!t.has(e)&&i.every(t=>t.includes(e))))}function Us(e,t){let n=X(e);if(zs(n,!1)&&Hs(Z(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Ws(e,t,n=!0){let r=Z(e),i=r.commands.find(e=>e.name()===`command-catalog`),a=i?.commands.find(e=>e.name()===`search`);if(i===void 0||a===void 0)return;let o=[r.name(),i.name(),a.name(),t],s=X(e).at(0),c=a.options.find(e=>Y(e)===`--root`),l=n&&c!==void 0&&As(s)?s:void 0;c!==void 0&&l!==void 0&&o.push(Y(c),l);let u=Ye(O),d=er({q:t,root:l,limit:`3`},u,r.name()),f=d.ok&&d.data!==null?jr(d.data,`compact`):``;return[`hint: search generated commands: ${o.map(Ds).join(` `)}`,...f===``?[]:[`hint: closest commands (command · summary · required flags):`],...f.split(`
52
52
  `).filter(Boolean).map(e=>` ${e}`)].join(`
53
- `)}function Gs(e){if(e.commands.length>0&&!zs(J(e)))return;let t=e.options.flatMap(e=>e.hidden?[]:[q(e)]);return`hint: ${J(e).join(` `)} accepts: ${t.join(` `)}`}function Ks(e,t){let n=Ss(t);if(n===void 0||t.message.includes(`
54
- (Did you mean `))return;let r=Ps(e),i=Fs(e,r);if(i!==void 0)return i;let a=Ms(e,n);if(a!==void 0)return Ws(e,a.join(` `),!1);let o=Ns(e,n);if(o!==void 0)return Ls(e,o,r)??Ws(e,o.join(` `),!1);let s=r.join(` `)||n,c=Rs(e)??Ws(e,s),l=[...J(e),...r.slice(1)];return[l.slice(1,-1).length>0?Ls(e,l,r):void 0,c].filter(e=>e!==void 0).join(`
55
- `)||void 0}function qs(e){return t=>{if(t.code===`commander.missingMandatoryOptionValue`){let n=e.options.filter(t=>t.mandatory&&e.getOptionValue(t.attributeName())===void 0);if(n.length>1){let e=n.map(e=>e.flags.split(`, `).at(-1)??e.flags);process.stderr.write(`error: missing required options: ${e.join(`, `)}\n`)}for(let n of[Ts(e),_s(e),Cs(e,t),...Bs(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=_s(e)??Vs(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=xs(t),r=Ts(e)??As(e,t)??(n!==void 0&&!t.message.includes(`
56
- (Did you mean `)?Us(e,n)??Is(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??Gs(e)??Ws(e,J(e).slice(1).join(` `)||n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Ks(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Js=class extends i{group;constructor(e){super(`-h, --help`,`display help for command`),this.group=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.group.args.at(0);return t===void 0||t.startsWith(`-`)?!0:this.group.commands.some(e=>e.name()===t||e.aliases().includes(t))}};function Ys(e){e.showHelpAfterError(!1).exitOverride(qs(e)),e.commands.length===0?e.hook(`preAction`,gs):e.addHelpOption(new Js(e));for(let t of e.commands)Ys(t)}function Xs(e,t=new Date){let n=$s(e);return{schemaVersion:1,generatedFrom:`MCP_GENERATION_CONTRACT`,generatedAt:t.toISOString(),totalOperations:n.length,note:`Projection of MCP_GENERATION_CONTRACT - see mcp/scripts/build-unified-operations.ts header for SSOT rules.`,operations:n}}function Zs(e){return`${JSON.stringify(e,null,2)}\n`}function Qs(e,t){let n=A(e),r=Zs(t);return ht(k(n),{recursive:!0}),Ct(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function $s(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:r(e.intent),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var ec=`Match only the first canonical or CLI-alias command segment`,tc=[`text`,`lines`,`compact`,`json`,`ndjson`];function nc(e,t,n=f().bin[0]){let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
57
- `));r.addHelpText(`after`,()=>`\nShipped compact catalog of operations callable without an admin grant, greppable without\nrunning this CLI (dump --format compact lists every operation your credential reaches):\n ${Tr(n)}\n`),rc(r,t,n),ic(r,t,n),ac(r,t,n),oc(r)}function rc(e,t,n){let r=e.command(`search`).summary(`Search generated operations`).description(`Search generated operation metadata without calling the API.`).argument(`[query...]`,`Search query; same as --q.`).option(`--q <query>`,`Search generated command metadata`).option(`--root <root>`,ec).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`,`20`).addOption(new i(`--format <format>`,`Text/file render format`).choices(tc)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(e){let r=this.optsWithGlobals(),i=E(r,`text`);Or(Dr(r,e),t,i,n)})}function ic(e,t,n){let r=e.command(`show`).summary(`Show one generated operation`).description(`Show one generated operation by command path or operationId.`).option(`--command <command>`,`CLI command path, with or without ${n} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new i(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();kr(e,t,E(e,`text`),n)})}function ac(e,t,n){let r=e.command(`dump`).summary(`Dump generated operations`).description(`Dump generated operations for rg/grep/ag/ack or JSON/NDJSON tooling.`).option(`--root <root>`,ec).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new i(`--format <format>`,`Text/file render format`).choices(tc)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();Or(e,t,E(e,`text`),n)})}function oc(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);D(t),t.action(function(){let e=this.optsWithGlobals(),t=E(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){I({mode:t},x(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:tt.length}}));return}let n=Xs(tt);if(e.output!==void 0){let r=Qs(e.output,n);I({mode:t},x(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(Zs(n));return}I({mode:t},x(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var sc=f(Dt(import.meta.url)),Q=sc.bin[0];function cc(e,t){fe({component:`aventure-cli`,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof ie?{httpStatus:e.problem.status,problem:e.problem}:{};Gn({...m(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function lc(e){return Ge[Qe(e,et)??`cli`]}function uc(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:lc(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>$e(e.cliPath[0])).map(e=>e.cliPath[0]??``)),i=new Set,a=new Set;for(let{cliPath:e,deprecated:t}of n)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);i.add(r),t!==!0&&a.add(r)}for(let t of n)dc(e,t,r,a,i.has(t.cliPath.join(` `)))}function dc(e,n,r,i,a){let o=n.cliPath,s=e,c=``,u=!r.has(o[0]??``);for(let e of o.slice(0,-1)){c=c===``?e:`${c} ${e}`;let t=u&&c===e||!i.has(c);s=fc(s,e,c,t)}let d=o.at(-1)??n.operationId,f=s.commands.find(e=>e.name()===d)??s.command(d,n.deprecated===!0?{hidden:!0}:{}),p=n.requestBody?.flatMap(({parameter:e})=>e)??[];f.summary(n.summary||n.operationId).description([`${n.method} ${n.path}.`,n.summary||n.description,`Full documentation: ${Q} help ${n.cliPath.join(` `)}`,n.requestBody?.[0]?.kind===`json`||[...n.parameters,...p].some(e=>t(e.schemaType,e.itemSchemaType))?de:``].filter(Boolean).join(`
58
- `));let h=ni(n);for(let e of n.parameters)pc(f,e,a||e===h);if(Cn(f,n),l(n.intent)&&f.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),D(f),f.hook(`preAction`,e=>ei(e,n)),n.explain===!0&&f.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){f.argument(`[text...]`,h.description||`Same as ${ti(h.flag)}.`),f.action(async function(e){let t=this.optsWithGlobals(),r=E(t),i=ri(h,e,t);if(!i.ok||i.data===null)return I({mode:r},i);let a=Qr(n,i.data);if(a.length>0)return I({mode:r},m(`missing required options: ${a.join(`, `)}`));let o=await mc(n,i.data,r),s=ii(n,i.data,o);if(s!==null)return I({mode:r},s);t.explain===!0&&o.ok&&Yn(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):I({mode:r},o)});return}f.action(async function(){let e=this.optsWithGlobals(),t=E(e),r=Qr(n,e);if(r.length>0)return I({mode:t},m(`missing required options: ${r.join(`, `)}`));let i=await mc(n,e,t),a=ii(n,e,i);if(a!==null)return I({mode:t},a);e.explain===!0&&i.ok&&Yn(t,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):I({mode:t},i)})}function fc(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=et[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function pc(e,t,n=!1){let r=t.description||`${t.name} ${t.location} parameter`,a=t.defaultValue===void 0?void 0:typeof t.defaultValue==`string`||typeof t.defaultValue==`boolean`?t.defaultValue:[...t.defaultValue];if(t.legacyFlag!==void 0){let o=new i(t.flag,r);a!==void 0&&o.default(a);let s=new i(t.legacyFlag,r).conflicts(t.optionKey);e.addOption(o).addOption(s),e.hook(`preAction`,e=>{let r=e.opts(),i=r[t.optionKey],a=r[s.attributeName()];if(a!==void 0){(i===void 0||e.getOptionValueSource(t.optionKey)==="default")&&e.setOptionValueWithSource(t.optionKey,a,`cli`);return}!n&&t.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(a!==void 0){e.option(t.flag,r,a);return}if(t.required&&!n){e.requiredOption(t.flag,r);return}e.option(t.flag,r)}async function mc(e,t,n){if(t.environment!==void 0){let e=le(t.environment);if(e===null)return m(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${_().join(`, `)}`]);process.env.API_ENV=e}let r=await On(e,t);if(!r.ok)return r;let i=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),a=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),o=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]}));return await ue({method:e.method,path:se(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:typeof t.contentType==`string`?t.contentType:void 0,auth:e.auth,responseFormat:Ue(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0})}process.on(`uncaughtException`,e=>cc(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>cc(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var hc=We(process.argv.slice(2),O),gc=hc===`required`?O:Ye(O),$=new o;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Ur).version(sc.version).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description([`The aVenture research API from your terminal. Three records — companies,`,`people, and news — carry everything else: funding, publications, and tags.
53
+ `)}function Gs(e){if(e.commands.length>0&&!zs(X(e)))return;let t=e.options.flatMap(e=>e.hidden?[]:[Y(e)]);return`hint: ${X(e).join(` `)} accepts: ${t.join(` `)}`}function Ks(e,t){let n=bs(t);if(n===void 0||t.message.includes(`
54
+ (Did you mean `))return;let r=Ps(e),i=Fs(e,r);if(i!==void 0)return i;let a=X(e),o=[...a.slice(0,-1),`${a.at(-1)}-${n}`,...r.slice(1)],s=(zs(o)?o:void 0)??Ms(e,n)??Ns(e,n);if(s!==void 0)return Ls(e,s,r)??Ws(e,s.join(` `),!1);let c=r.join(` `)||n,l=Rs(e)??Ws(e,c),u=[...X(e),...r.slice(1)];return[u.slice(1,-1).length>0?Ls(e,u,r):void 0,l].filter(e=>e!==void 0).join(`
55
+ `)||void 0}function qs(e){return t=>{if(t.code===`commander.missingMandatoryOptionValue`){let n=e.options.filter(t=>t.mandatory&&e.getOptionValue(t.attributeName())===void 0);if(n.length>1){let e=n.map(e=>e.flags.split(`, `).at(-1)??e.flags);process.stderr.write(`error: missing required options: ${e.join(`, `)}\n`)}for(let n of[Cs(e),hs(e),xs(e,t),...Bs(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=hs(e)??Vs(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=ys(t),r=Cs(e)??ks(e,t)??(n!==void 0&&!t.message.includes(`
56
+ (Did you mean `)?Us(e,n)??Is(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??Gs(e)??Ws(e,X(e).slice(1).join(` `)||n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Ks(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Js=class extends i{group;constructor(e){super(`-h, --help`,`display help for command`),this.group=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.group.args.at(0);return t===void 0||t.startsWith(`-`)?!0:this.group.commands.some(e=>e.name()===t||e.aliases().includes(t))}};function Ys(e){e.showHelpAfterError(!1).exitOverride(qs(e)),e.commands.length===0?e.hook(`preAction`,ms):e.addHelpOption(new Js(e));for(let t of e.commands)Ys(t)}function Xs(e,t=new Date){let n=$s(e);return{schemaVersion:1,generatedFrom:`MCP_GENERATION_CONTRACT`,generatedAt:t.toISOString(),totalOperations:n.length,note:`Projection of MCP_GENERATION_CONTRACT - see mcp/scripts/build-unified-operations.ts header for SSOT rules.`,operations:n}}function Zs(e){return`${JSON.stringify(e,null,2)}\n`}function Qs(e,t){let n=A(e),r=Zs(t);return ht(k(n),{recursive:!0}),Ct(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function $s(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:r(e.intent),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var ec=`Match only the first canonical or CLI-alias command segment`,tc=[`text`,`lines`,`compact`,`json`,`ndjson`];function nc(e,t,n=f().bin[0]){let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
57
+ `));r.addHelpText(`after`,()=>`\nShipped compact catalog of operations callable without an admin grant, greppable without\nrunning this CLI (dump --format compact lists every operation your credential reaches):\n ${wr(n)}\n`),rc(r,t,n),ic(r,t,n),ac(r,t,n),oc(r)}function rc(e,t,n){let r=e.command(`search`).summary(`Search generated operations`).description(`Search generated operation metadata without calling the API.`).argument(`[query...]`,`Search query; same as --q.`).option(`--q <query>`,`Search generated command metadata`).option(`--root <root>`,ec).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`,`20`).addOption(new i(`--format <format>`,`Text/file render format`).choices(tc)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(e){let r=this.optsWithGlobals(),i=E(r,`text`);Dr(Er(r,e),t,i,n)})}function ic(e,t,n){let r=e.command(`show`).summary(`Show one generated operation`).description(`Show one generated operation by command path or operationId.`).option(`--command <command>`,`CLI command path, with or without ${n} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new i(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();Or(e,t,E(e,`text`),n)})}function ac(e,t,n){let r=e.command(`dump`).summary(`Dump generated operations`).description(`Dump generated operations for rg/grep/ag/ack or JSON/NDJSON tooling.`).option(`--root <root>`,ec).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new i(`--format <format>`,`Text/file render format`).choices(tc)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();Dr(e,t,E(e,`text`),n)})}function oc(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);D(t),t.action(function(){let e=this.optsWithGlobals(),t=E(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){L({mode:t},x(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:tt.length}}));return}let n=Xs(tt);if(e.output!==void 0){let r=Qs(e.output,n);L({mode:t},x(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(Zs(n));return}L({mode:t},x(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var sc=f(Dt(import.meta.url)),Q=sc.bin[0];function cc(e,t){fe({component:`aventure-cli`,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof ie?{httpStatus:e.problem.status,problem:e.problem}:{};Wn({...m(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function lc(e){return Ge[Qe(e,et)??`cli`]}function uc(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:lc(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>$e(e.cliPath[0])).map(e=>e.cliPath[0]??``)),i=new Set,a=new Set;for(let{cliPath:e,deprecated:t}of n)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);i.add(r),t!==!0&&a.add(r)}for(let t of n)dc(e,t,r,a,i.has(t.cliPath.join(` `)))}function dc(e,n,r,i,a){let o=n.cliPath,s=e,c=``,u=!r.has(o[0]??``);for(let e of o.slice(0,-1)){c=c===``?e:`${c} ${e}`;let t=u&&c===e||!i.has(c);s=fc(s,e,c,t)}let d=o.at(-1)??n.operationId,f=s.commands.find(e=>e.name()===d)??s.command(d,n.deprecated===!0?{hidden:!0}:{}),p=n.requestBody?.flatMap(({parameter:e})=>e)??[];f.summary(n.summary||n.operationId).description([`${n.method} ${n.path}.`,n.summary||n.description,`Full documentation: ${Q} help ${n.cliPath.join(` `)}`,n.requestBody?.[0]?.kind===`json`||[...n.parameters,...p].some(e=>t(e.schemaType,e.itemSchemaType))?de:``].filter(Boolean).join(`
58
+ `));let h=ti(n);for(let e of n.parameters)pc(f,e,a||e===h);if(Sn(f,n),l(n.intent)&&f.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),D(f),f.hook(`preAction`,e=>$r(e,n)),n.explain===!0&&f.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){f.argument(`[text...]`,h.description||`Same as ${ei(h.flag)}.`),f.action(async function(e){let t=this.optsWithGlobals(),r=E(t),i=ni(h,e,t);if(!i.ok||i.data===null)return L({mode:r},i);let a=Zr(n,i.data);if(a.length>0)return L({mode:r},m(`missing required options: ${a.join(`, `)}`));let o=await mc(n,i.data,r),s=ri(n,i.data,o);if(s!==null)return L({mode:r},s);t.explain===!0&&o.ok&&Jn(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):L({mode:r},o)});return}f.action(async function(){let e=this.optsWithGlobals(),t=E(e),r=Zr(n,e);if(r.length>0)return L({mode:t},m(`missing required options: ${r.join(`, `)}`));let i=await mc(n,e,t),a=ri(n,e,i);if(a!==null)return L({mode:t},a);e.explain===!0&&i.ok&&Jn(t,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):L({mode:t},i)})}function fc(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=et[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function pc(e,t,n=!1){let r=t.description||`${t.name} ${t.location} parameter`,a=t.defaultValue===void 0?void 0:typeof t.defaultValue==`string`||typeof t.defaultValue==`boolean`?t.defaultValue:[...t.defaultValue];if(t.legacyFlag!==void 0){let o=new i(t.flag,r);a!==void 0&&o.default(a);let s=new i(t.legacyFlag,r).conflicts(t.optionKey);e.addOption(o).addOption(s),e.hook(`preAction`,e=>{let r=e.opts(),i=r[t.optionKey],a=r[s.attributeName()];if(a!==void 0){(i===void 0||e.getOptionValueSource(t.optionKey)==="default")&&e.setOptionValueWithSource(t.optionKey,a,`cli`);return}!n&&t.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(a!==void 0){e.option(t.flag,r,a);return}if(t.required&&!n){e.requiredOption(t.flag,r);return}e.option(t.flag,r)}async function mc(e,t,n){if(t.environment!==void 0){let e=le(t.environment);if(e===null)return m(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${_().join(`, `)}`]);process.env.API_ENV=e}let r=await Dn(e,t);if(!r.ok)return r;let i=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),a=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),o=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]}));return await ue({method:e.method,path:se(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:typeof t.contentType==`string`?t.contentType:void 0,auth:e.auth,responseFormat:Ue(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0})}process.on(`uncaughtException`,e=>cc(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>cc(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var hc=We(process.argv.slice(2),O),gc=hc===`required`?O:Ye(O),$=new o;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Hr).version(sc.version).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description([`The aVenture research API from your terminal. Three records — companies,`,`people, and news — carry everything else: funding, publications, and tags.
59
59
  `,`Mutations execute directly; --execute is a deprecated no-op.
60
60
  The aVenture MCP server tools execute through this same CLI.`].join(`
61
- `)).addOption(new i(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${s})`).choices([..._()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),uc($,gc),Ao($,Q),Qa($,sc),Uo($,gc,Q),nc($,gc,Q),zr($,gc,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(lc(e.name()).heading);if(Ys($),hc===`required`){let e=[$];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&(await Ie(),await Re())}))}}var _c=new Set($.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));$.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find which one of that record a name, URL, or id refers to`],[`get`,` get Read one record`],[`list`,` list Read many records (news)`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>_c.has(e)?[t]:[]),``,`Account (free or paid; every command that calls aVenture needs one):`,` Create one at ${e}/sign-up, then run: ${Q} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Profile views, searches, and web searches count toward your monthly allowance.`,` Usage and upgrades: ${e}/settings/subscription`,` Plans and prices: ${Q} billing plans list`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
61
+ `)).addOption(new i(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${s})`).choices([..._()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),uc($,gc),Oo($,Q),Za($,sc),Vo($,gc,Q),nc($,gc,Q),Rr($,gc,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(lc(e.name()).heading);if(Ys($),hc===`required`){let e=[$];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&(await Ie(),await Re())}))}}var _c=new Set($.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));$.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find which one of that record a name, URL, or id refers to`],[`get`,` get Read one record`],[`list`,` list Read many records (news)`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>_c.has(e)?[t]:[]),``,`Account (free or paid; every command that calls aVenture needs one):`,` Create one at ${e}/sign-up, then run: ${Q} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Profile views, searches, and web searches count toward your monthly allowance.`,` Usage and upgrades: ${e}/settings/subscription`,` Plans and prices: ${Q} billing plans list`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
62
62
  `,`Exit codes:`,` 0 envelope.ok === true
63
63
  1 envelope.ok === false
64
64
  `,`Examples:`,` $ ${Q} auth login`,` $ ${Q} lookup "Stripe"`,` $ ${Q} search "fintech companies in Austin"`,` $ ${Q} entities lookup-exact get --url https://stripe.com\n`,`Run \`${Q} <command> --help\` for its subcommands and options,`,`or \`${Q} help <command>\` for its full documentation.`].join(`