@aventurevc/aventure-cli 0.7.329 → 0.7.332

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,44 +1,44 @@
1
- import{$ as e,A as t,B as n,E as r,Ft as i,G as a,It as o,J as s,M as c,O as l,Pt as u,Q as d,R as f,Rt as p,T as m,Y as h,Z as g,_,at as v,b as y,c as b,et as x,f as ee,it as S,j as te,l as ne,nt as re,o as ie,p as ae,q as oe,rt as C,s as se,u as w,v as ce,y as le}from"./auth-DD_CIwsI.js";import{C as T,D as ue,R as de,_ as fe,a as pe,k as E,v as D,x as me}from"./person-owner-BqBLyw4S.js";import{A as he,C as ge,D as _e,M as O,N as ve,O as ye,S as be,T as xe,a as Se,b as Ce,c as we,d as Te,g as Ee,j as De,k as Oe,l as ke,m as Ae,o as je,r as Me,s as Ne,t as Pe,u as Fe,v as Ie,w as Le,x as Re,y as ze}from"./oauth-bearer-credential-BY_6si5M.js";import{a as Be,c as Ve,d as He,f as Ue,g as We,h as Ge,l as Ke,m as qe,n as Je,o as k,p as Ye,r as A,s as Xe,t as j,u as Ze}from"./openapi-commands-DaOeLWGQ.js";import{a as Qe}from"./text-field-B07jcQqx.js";import{a as $e,n as et,o as tt,r as nt,t as rt}from"./text-response-DniH6EiG.js";import{n as it,r as at,t as ot}from"./oauth-login-BqLx-GNi.js";import{spawnSync as st}from"node:child_process";import{basename as ct,dirname as M,join as lt,resolve as N,sep as ut}from"node:path";import{appendFileSync as dt,copyFileSync as ft,existsSync as P,lstatSync as pt,mkdirSync as mt,mkdtempSync as ht,readFileSync as gt,readlinkSync as _t,realpathSync as vt,renameSync as yt,rmSync as bt,rmdirSync as xt,statSync as St,unlinkSync as Ct,writeFileSync as wt}from"node:fs";import F,{stderr as I,stdin as Tt}from"node:process";import{TextDecoder as Et,inspect as Dt}from"node:util";import{fileURLToPath as Ot}from"node:url";import{readFile as kt}from"node:fs/promises";import{createHash as At,webcrypto as jt}from"node:crypto";import{homedir as Mt,hostname as Nt,platform as Pt}from"node:os";import{setTimeout as Ft}from"node:timers/promises";import{createInterface as It}from"node:readline/promises";function Lt(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{...C(`${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 S(`Environment-bound options applied`,r)}function Rt(e,t,n){if(!L(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||!Qt(n,r.name))continue;let a=Zt(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 zt(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 Bt(e,t,n,r=!1){if(r||!tn(t)||!Array.isArray(n))return rn(e,t,n);for(let[r,i]of n.entries()){let n=rn(e,t,i,r);if(!n.ok)return n}return S(`Body value assigned`,null)}function Vt(e,t,n,r){return rn(e,t,r,n)}function Ht(e){let t=[];for(let n of e.split(`.`)){let e=on(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Ut(e,t){let n=Ht(t);if(n===null)return null;let r=Xt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Yt(r)}:null}function Wt(e,t){if(tn(e.name)||e.schemaType===`array`)return S(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return S(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?S(`Scalar body option selected`,t[0]):C(`${n} was already given; pass it once.`)}var Gt=/^(?<row>\d+):(?<item>.*)$/su;function Kt(e,t){let n=Ht(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=Gt.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 qt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Ht(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Jt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Ut(r,i.name);if(a===null)continue;if(a.firstHole!==null)return C(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Kt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return C(`${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 Yt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Xt(e,t){let n=e;for(let e of t){if(!L(n))return;n=n[e]??null}return n}function Zt(e,t){if(!tn(t))return Xt(e,t.split(`.`))}function Qt(e,t){return en(e,t.split(`.`))}function $t(e,t,n){if(!L(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)&&Qt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function en(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=on(n);if(!L(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>en(e,r)):en(a,r)}function tn(e){return e.split(`.`).some(e=>on(e).isArray)}function nn(e,t){return e.parameter.length===0||!L(t)?null:cn(t,[],sn(e.parameter))}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=on(o),c=e===i.length-1,l=an(a,s,t,c,n,r);if(!l.ok||l.data===null)return C(l.summary,l.warnings);if(c)return S(`Body value assigned`,null);a=l.data}return C(`${t} is not a valid body option path.`)}function an(e,t,n,r,i,a){let o=()=>C(`${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,S(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,S(`Body path created`,e)}return L(c)?S(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,S(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,S(`Body path created`,n)}return L(s)?S(`Body path stepped`,s):o()}function on(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function sn(e){let t=new Set,n=new Set,r=new Map;for(let i of e){let e=`${i.name}${i.schemaType===`array`?`[]`:``}`;t.add(e),r.set(e,i.flag.split(` `)[0]??i.name);let a=e.split(`.`);for(let e=1;e<a.length;e+=1)n.add(a.slice(0,e).join(`.`))}return{leaf:t,prefix:n,flagByLeaf:r}}function cn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=cn(r,t,n);if(e!==null)return e}return null}if(!L(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!ln(a,n)){if(!un(e))continue;return{path:a,suggestion:dn(e,n)}}let o=cn(i,e,n);if(o!==null)return o}return null}function ln(e,t){return t.prefix.has(e)||t.leaf.has(e)}function un(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function dn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``,[i]=[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:fn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path));if(i!==void 0)return{path:i.path,flag:t.flagByLeaf.get(i.path)??i.path}}function fn(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 pn(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?xn(r,i):r===void 0?i===void 0?0:1:-1})}function mn(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 hn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function gn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:yn(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 _n(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function vn(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?Ge(n):`${Ge(n)} Required JSON paths: ${r.join(`, `)}.`}function yn(e,t){return`${Ue(t.description,void 0)}${e.kind!==`multipart`&&tn(t.name)?` Repeat to add another value.`:``}${bn(e,t)}`}function bn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Ht(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 xn(e,t){return Ye(e)-Ye(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function Sn(e){let t;try{t=e===`-`?await Cn():await kt(e,`utf8`)}catch(t){return C(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return S(`No input provided`,null);let e=JSON.parse(t);return S(`Input parsed`,e)}catch(e){return C(`Input is not valid JSON: ${e.message}`)}}async function Cn(){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 wn=`--content-type`;function Tn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),a=t.requestBody??[];if(a.length>1&&r(wn)){let t=a.map(({contentType:e})=>e);e.addOption(new i(`${wn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Dn(a)))}if(qn(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>`,vn(n,n.requiredPath)).argParser(kn(`--from-file`)))}let o=mn(a).filter(e=>r(zn(e.variant[0].parameter)));for(let t of o.toSorted((e,t)=>xn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],o=new i(hn(t),a.length>1?gn(t):yn(n,r));a.length===1&&r.envName!==void 0&&o.env(r.envName);let s=a.length===1?_n(n,r.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(En):tn(r.name)||r.schemaType===`array`?o.argParser(On):o.argParser(kn(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`)})}Kn(e,t,o)}function En(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Dn(e){return(t,n)=>{if(n!==void 0)throw new p(`${wn} was already given; pass it once.`);let r=c(e,t);if(!r.ok)throw new p(r.summary);return t}}function On(e,t){return[...t??[],e]}function kn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new p(`${t} was already given; pass it once.`);return e}}async function An(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,r=c(e.requestBody??[],n);if(!r.ok||r.data===null)return C(r.summary,r.warnings);let i=r.data;if(i===void 0)return S(`No body`,void 0);let a=jn(e,i,t);if(a!==null)return C(a);let o=Lt(e.operationId,i,t);if(!o.ok)return C(o.summary,o.warnings);t=o.data;let s=Mn(i,t);if(s!==null)return C(s);let l=await In(t);if(!l.ok)return C(l.summary,l.warnings);let u=$t(e.requestBody??[],i,l.data);if(u!==null)return C(u);let d=Fn(e.operationId,i,l.data);if(!d.ok)return d;let f=Rt(e.operationId,i,l.data);if(f!==null)return C(f);let p=Ln(e.operationId,i,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return i.required?C(Gn(e.operationId,i)):S(`No body`,void 0);let m=Bn(e.operationId,l.data,p.data);if(!m.ok||m.data===void 0)return m;if(i.schemaType===`array`&&!Array.isArray(m.data))return C(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!L(m.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return C(`${e.operationId} requires a JSON object${t}.`)}let h=Pn(i,m.data);if(h.length>0)return C(`${e.operationId} requires body option(s): ${h.join(`, `)}`);let g=m.data,_=L(g)?zt(i).filter(e=>!Qt(g,e)):[];return _.length>0?C(Nn(e.operationId,i,_)):m}function jn(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`${zn(t)} requires ${wn} ${i.join(` or `)}.`}return null}function Mn(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 Nn(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 Pn(e,t){return L(t)?e.parameter.filter(e=>e.required&&!Qt(t,e.name)).map(zn):[]}function Fn(e,t,n){let r=nn(t,n);if(r===null)return S(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion.path} (${r.suggestion.flag}).`;return C(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function In(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return S(`No body file`,void 0);let n=await Sn(t);if(!n.ok)return C(n.summary,n.warnings);let r=v.safeParse(n.data);return r.success?S(`Input parsed`,r.data):C(`Input is not valid JSON value: ${r.error.message}`)}function Ln(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Wt(e,n[e.optionKey]);if(!a.ok||a.data===null)return C(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Rn(t,n,r,e,o);if(!s.ok)return C(s.summary,s.warnings);i=!0}if(!i)return S(`No direct body options`,void 0);let a=Jt(e,t,n,r);return a===null?S(`Direct body options parsed`,r):a}function Rn(e,t,n,r,i){let a=Kt(r,i);if(a===null){let e=Un(r,i);return e.ok?Bt(n,r.name,e.data,r.schemaType===`array`):C(e.summary,e.warnings)}if(a.plain.length>0)return C(`${zn(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=qt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return C(`${zn(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=Wn(r.name,r.itemSchemaType,e);if(!t.ok)return C(t.summary,t.warnings);i.push(t.data)}let a=Vt(n,r.name,e,i);if(!a.ok)return a}return S(`Body value assigned`,null)}var zn=e=>e.flag.split(` `)[0]??e.name;function Bn(e,t,n){if(t===void 0)return S(`Direct body parsed`,n);if(n===void 0)return S(`Input parsed`,t);if(L(t)&&L(n))try{return S(`Input parsed`,Vn(t,n))}catch(t){return C(`${e} ${t.message}`)}return C(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Vn(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&&Hn(t)!==Hn(r))throw Error(`cannot combine --from-file ${Hn(t)} '${e}' with ${Hn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=L(t)&&L(r)?Vn(t,r):r}return n}function Hn(e){return Array.isArray(e)?`array`:L(e)?`object`:`scalar`}function Un(e,t){if(typeof t==`boolean`)return S(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Wn(e.name,e.schemaType,t??``);let n=[],r=tn(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Wn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return S(`Body value parsed`,n)}function Wn(e,t,n){if(t===`boolean`)return n===`true`?S(`Body value parsed`,!0):n===`false`?S(`Body value parsed`,!1):C(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?C(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?C(`${e} must be an integer.`):S(`Body value parsed`,i)}return S(`Body value parsed`,n)}function Gn(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(zn).join(`, `)}`;let r=zt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(zn).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Kn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:wn,location:`body`}),qn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),pn(e.options,r)}function qn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Jn(e){let t=re(e);return rr(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Yn(e){rr(e);let t=rt(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
- `)?t:`${t}\n`),Xn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&$n(e.problem),Xn(e)}function Xn(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 R(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?re(t):t;rr(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Zn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?Jn(t):t;e.mode===`text`&&Yn(n),n.ok||(process.exitCode=1)}function Zn(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 Qn(e,t){let n=et(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 $n(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`),er(e),tr(`unknownParameters`,e.unknownParameters),tr(`validParameters`,e.validParameters),nr(e.resolution)}function er(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 tr(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function nr(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 rr(e){e.ok&&e.warnings.length===0||n({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 ir(e,t,n=s().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 C(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=nt(e.q??``,sr(t,n).filter(t=>dr(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 S(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function ar(e,t,n=s().bin[0]){let r=sr(t,n),i=e.operationId===void 0?or(r,e.command):r.find(t=>t.operationId===e.operationId);return i===void 0?C(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`]):S(`Generated operation detail`,{operation:i,usage:pr(i,r)})}function or(e,t){if(t===void 0)return;let{bin:n}=s(),r=wr(t,n);return e.find(e=>wr(e.cli.command,n)===r)}function sr(e,n){return e.map(e=>{let r=e.requestBody??[],i=[...e.parameters.map(e=>cr(e)),...r.flatMap(e=>e.parameter.map(t=>cr(t,r.length>1?e.contentType:void 0))),...lr(r)],a=[n,...e.cliPath].join(` `),o=t(e.intent),s=e.method===`DELETE`||e.intent===`delete`,c=r[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:te(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&r.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}})}function cr(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 lr(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 ur(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function dr(e,t){return!(t.root!==void 0&&!fr(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 fr(e,t){let n=tt(t);return n.length===0||tt(e.cli.path.at(0)??``)===n}function pr(e,t){let n=ur(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`,z(`required path flags`,r,`path`),z(`required query flags`,r,`query`),z(`required header flags`,r,`header`),z(`required body flags`,r,`body`),z(`optional path flags`,i,`path`),z(`optional query flags`,i,`query`),z(`optional header flags`,i,`header`),z(`optional body flags`,i,`body`),...yr(e,t),...mr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
- `)}function mr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var hr=[`-id`,`-slug`,`-url`],gr=[`--id`,`--slug`,`--url`],_r=`--from-file "<path>"`;function vr(e,t,n=s().bin[0]){let r=sr(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:yr(i,r)}function yr(e,t){return[`example: ${[e.cli.command,...xr(e),`--data`].join(` `)}`,...br(e,t)]}function br(e,t){return ur(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`&&e.path.endsWith(`/lookup`)&&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} ${Cr(i)} --data`;return[`lookup: ${e.name} from a slug or name: ${a}`]})}function xr(e){let t=ur(e).filter(e=>e.required),n=(t.length>0?t:Sr(e)).map(Cr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,_r]:n}function Sr(e){let t=new Set;$e(t,e.resource);for(let n of hr)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 gr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function Cr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function z(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function wr(e,t=s().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var Tr=`dist/aventure-cli/command-catalog.compact.txt`,Er=` · `,Dr=`-`;function Or(e=s().bin[0]){return N(kr(M(Ot(import.meta.url)),e),Tr)}function kr(e,t){let n=e;for(;;){if(P(N(n,`package.json`)))return n;let r=M(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Ar(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function jr(e,t,n,r=s().bin[0]){let i=ir(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Nr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Fr(i.data,Pr(e.format,`lines`)),summary:`Generated operation matches`})}function Mr(e,t,n,r=s().bin[0]){let i=ar(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Nr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Ir(i.data,Pr(e.format,`usage`)),summary:`Generated operation detail`})}function Nr(e){let t=e.mode,n=Pr(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`)){R({mode:t},C(`--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(`
1
+ import{$ as e,A as t,B as n,E as r,Ft as i,G as a,It as o,J as s,M as c,O as l,Pt as u,Q as d,R as f,Rt as p,T as m,Y as h,Z as g,_,at as v,b as y,c as b,et as x,f as ee,it as S,j as te,l as ne,nt as re,o as ie,p as ae,q as oe,rt as C,s as se,u as ce,v as le,y as ue}from"./auth-Dz_A-dL_.js";import{C as w,D as de,R as fe,_ as pe,a as me,k as T,v as E,x as he}from"./person-owner-BqBLyw4S.js";import{A as ge,C as _e,D as ve,M as D,N as ye,O as be,S as xe,T as Se,a as Ce,b as we,c as Te,d as Ee,g as De,j as Oe,k as ke,l as Ae,m as je,o as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./oauth-bearer-credential-1WZWSwji.js";import{a as Ve,c as He,d as Ue,f as We,g as Ge,h as Ke,l as qe,m as Je,n as Ye,o as O,p as Xe,r as k,s as Ze,t as A,u as Qe}from"./openapi-commands-DQaPv5E_.js";import{a as $e}from"./text-field-CwDIzxGg.js";import{a as et,n as tt,o as nt,r as rt,t as it}from"./text-response-DEelXkk9.js";import{n as at,r as ot,t as st}from"./oauth-login-DSNKOKUf.js";import{spawnSync as ct}from"node:child_process";import{basename as lt,dirname as j,join as M,resolve as N,sep as ut}from"node:path";import{appendFileSync as dt,copyFileSync as ft,existsSync as P,lstatSync as pt,mkdirSync as mt,mkdtempSync as ht,readFileSync as gt,readlinkSync as _t,realpathSync as vt,renameSync as yt,rmSync as bt,rmdirSync as xt,statSync as St,unlinkSync as Ct,writeFileSync as wt}from"node:fs";import F,{stderr as I,stdin as Tt}from"node:process";import{TextDecoder as Et,inspect as Dt}from"node:util";import{fileURLToPath as Ot}from"node:url";import{readFile as kt}from"node:fs/promises";import{createHash as At,webcrypto as jt}from"node:crypto";import{homedir as Mt,hostname as Nt,platform as Pt}from"node:os";import{setTimeout as Ft}from"node:timers/promises";import{createInterface as It}from"node:readline/promises";function Lt(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{...C(`${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 S(`Environment-bound options applied`,r)}function Rt(e,t,n){if(!L(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||!Qt(n,r.name))continue;let a=Zt(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 zt(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 Bt(e,t,n,r=!1){if(r||!tn(t)||!Array.isArray(n))return rn(e,t,n);for(let[r,i]of n.entries()){let n=rn(e,t,i,r);if(!n.ok)return n}return S(`Body value assigned`,null)}function Vt(e,t,n,r){return rn(e,t,r,n)}function Ht(e){let t=[];for(let n of e.split(`.`)){let e=on(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Ut(e,t){let n=Ht(t);if(n===null)return null;let r=Xt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Yt(r)}:null}function Wt(e,t){if(tn(e.name)||e.schemaType===`array`)return S(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return S(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?S(`Scalar body option selected`,t[0]):C(`${n} was already given; pass it once.`)}var Gt=/^(?<row>\d+):(?<item>.*)$/su;function Kt(e,t){let n=Ht(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=Gt.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 qt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Ht(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Jt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Ut(r,i.name);if(a===null)continue;if(a.firstHole!==null)return C(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Kt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return C(`${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 Yt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Xt(e,t){let n=e;for(let e of t){if(!L(n))return;n=n[e]??null}return n}function Zt(e,t){if(!tn(t))return Xt(e,t.split(`.`))}function Qt(e,t){return en(e,t.split(`.`))}function $t(e,t,n){if(!L(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)&&Qt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function en(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=on(n);if(!L(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>en(e,r)):en(a,r)}function tn(e){return e.split(`.`).some(e=>on(e).isArray)}function nn(e,t){return e.parameter.length===0||!L(t)?null:cn(t,[],sn(e.parameter))}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=on(o),c=e===i.length-1,l=an(a,s,t,c,n,r);if(!l.ok||l.data===null)return C(l.summary,l.warnings);if(c)return S(`Body value assigned`,null);a=l.data}return C(`${t} is not a valid body option path.`)}function an(e,t,n,r,i,a){let o=()=>C(`${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,S(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,S(`Body path created`,e)}return L(c)?S(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,S(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,S(`Body path created`,n)}return L(s)?S(`Body path stepped`,s):o()}function on(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function sn(e){let t=new Set,n=new Set,r=new Map;for(let i of e){let e=`${i.name}${i.schemaType===`array`?`[]`:``}`;t.add(e),r.set(e,i.flag.split(` `)[0]??i.name);let a=e.split(`.`);for(let e=1;e<a.length;e+=1)n.add(a.slice(0,e).join(`.`))}return{leaf:t,prefix:n,flagByLeaf:r}}function cn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=cn(r,t,n);if(e!==null)return e}return null}if(!L(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!ln(a,n)){if(!un(e))continue;return{path:a,suggestion:dn(e,n)}}let o=cn(i,e,n);if(o!==null)return o}return null}function ln(e,t){return t.prefix.has(e)||t.leaf.has(e)}function un(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function dn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``,[i]=[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:fn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path));if(i!==void 0)return{path:i.path,flag:t.flagByLeaf.get(i.path)??i.path}}function fn(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 pn(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(Ke(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?xn(r,i):r===void 0?i===void 0?0:1:-1})}function mn(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 hn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function gn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:yn(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 _n(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function vn(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?Ge(n):`${Ge(n)} Required JSON paths: ${r.join(`, `)}.`}function yn(e,t){return`${Xe(t.description,void 0)}${e.kind!==`multipart`&&tn(t.name)?` Repeat to add another value.`:``}${bn(e,t)}`}function bn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Ht(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 xn(e,t){return Je(e)-Je(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function Sn(e){let t;try{t=e===`-`?await Cn():await kt(e,`utf8`)}catch(t){return C(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return S(`No input provided`,null);let e=JSON.parse(t);return S(`Input parsed`,e)}catch(e){return C(`Input is not valid JSON: ${e.message}`)}}async function Cn(){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 wn=`--content-type`;function Tn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),a=t.requestBody??[];if(a.length>1&&r(wn)){let t=a.map(({contentType:e})=>e);e.addOption(new i(`${wn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Dn(a)))}if(qn(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>`,vn(n,n.requiredPath)).argParser(kn(`--from-file`)))}let o=mn(a).filter(e=>r(zn(e.variant[0].parameter)));for(let t of o.toSorted((e,t)=>xn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],o=new i(hn(t),a.length>1?gn(t):yn(n,r));a.length===1&&r.envName!==void 0&&o.env(r.envName);let s=a.length===1?_n(n,r.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(En):tn(r.name)||r.schemaType===`array`?o.argParser(On):o.argParser(kn(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`)})}Kn(e,t,o)}function En(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Dn(e){return(t,n)=>{if(n!==void 0)throw new p(`${wn} was already given; pass it once.`);let r=c(e,t);if(!r.ok)throw new p(r.summary);return t}}function On(e,t){return[...t??[],e]}function kn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new p(`${t} was already given; pass it once.`);return e}}async function An(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,r=c(e.requestBody??[],n);if(!r.ok||r.data===null)return C(r.summary,r.warnings);let i=r.data;if(i===void 0)return S(`No body`,void 0);let a=jn(e,i,t);if(a!==null)return C(a);let o=Lt(e.operationId,i,t);if(!o.ok)return C(o.summary,o.warnings);t=o.data;let s=Mn(i,t);if(s!==null)return C(s);let l=await In(t);if(!l.ok)return C(l.summary,l.warnings);let u=$t(e.requestBody??[],i,l.data);if(u!==null)return C(u);let d=Fn(e.operationId,i,l.data);if(!d.ok)return d;let f=Rt(e.operationId,i,l.data);if(f!==null)return C(f);let p=Ln(e.operationId,i,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return i.required?C(Gn(e.operationId,i)):S(`No body`,void 0);let m=Bn(e.operationId,l.data,p.data);if(!m.ok||m.data===void 0)return m;if(i.schemaType===`array`&&!Array.isArray(m.data))return C(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!L(m.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return C(`${e.operationId} requires a JSON object${t}.`)}let h=Pn(i,m.data);if(h.length>0)return C(`${e.operationId} requires body option(s): ${h.join(`, `)}`);let g=m.data,_=L(g)?zt(i).filter(e=>!Qt(g,e)):[];return _.length>0?C(Nn(e.operationId,i,_)):m}function jn(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`${zn(t)} requires ${wn} ${i.join(` or `)}.`}return null}function Mn(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 Nn(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 Pn(e,t){return L(t)?e.parameter.filter(e=>e.required&&!Qt(t,e.name)).map(zn):[]}function Fn(e,t,n){let r=nn(t,n);if(r===null)return S(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion.path} (${r.suggestion.flag}).`;return C(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function In(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return S(`No body file`,void 0);let n=await Sn(t);if(!n.ok)return C(n.summary,n.warnings);let r=v.safeParse(n.data);return r.success?S(`Input parsed`,r.data):C(`Input is not valid JSON value: ${r.error.message}`)}function Ln(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Wt(e,n[e.optionKey]);if(!a.ok||a.data===null)return C(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Rn(t,n,r,e,o);if(!s.ok)return C(s.summary,s.warnings);i=!0}if(!i)return S(`No direct body options`,void 0);let a=Jt(e,t,n,r);return a===null?S(`Direct body options parsed`,r):a}function Rn(e,t,n,r,i){let a=Kt(r,i);if(a===null){let e=Un(r,i);return e.ok?Bt(n,r.name,e.data,r.schemaType===`array`):C(e.summary,e.warnings)}if(a.plain.length>0)return C(`${zn(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=qt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return C(`${zn(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=Wn(r.name,r.itemSchemaType,e);if(!t.ok)return C(t.summary,t.warnings);i.push(t.data)}let a=Vt(n,r.name,e,i);if(!a.ok)return a}return S(`Body value assigned`,null)}var zn=e=>e.flag.split(` `)[0]??e.name;function Bn(e,t,n){if(t===void 0)return S(`Direct body parsed`,n);if(n===void 0)return S(`Input parsed`,t);if(L(t)&&L(n))try{return S(`Input parsed`,Vn(t,n))}catch(t){return C(`${e} ${t.message}`)}return C(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Vn(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&&Hn(t)!==Hn(r))throw Error(`cannot combine --from-file ${Hn(t)} '${e}' with ${Hn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=L(t)&&L(r)?Vn(t,r):r}return n}function Hn(e){return Array.isArray(e)?`array`:L(e)?`object`:`scalar`}function Un(e,t){if(typeof t==`boolean`)return S(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Wn(e.name,e.schemaType,t??``);let n=[],r=tn(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Wn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return S(`Body value parsed`,n)}function Wn(e,t,n){if(t===`boolean`)return n===`true`?S(`Body value parsed`,!0):n===`false`?S(`Body value parsed`,!1):C(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?C(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?C(`${e} must be an integer.`):S(`Body value parsed`,i)}return S(`Body value parsed`,n)}function Gn(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(zn).join(`, `)}`;let r=zt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(zn).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Kn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:wn,location:`body`}),qn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),pn(e.options,r)}function qn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Jn(e){let t=re(e);return rr(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Yn(e){rr(e);let t=it(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
+ `)?t:`${t}\n`),Xn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&$n(e.problem),Xn(e)}function Xn(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 R(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?re(t):t;rr(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Zn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?Jn(t):t;e.mode===`text`&&Yn(n),n.ok||(process.exitCode=1)}function Zn(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 Qn(e,t){let n=tt(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 $n(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`),er(e),tr(`unknownParameters`,e.unknownParameters),tr(`validParameters`,e.validParameters),nr(e.resolution)}function er(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 tr(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function nr(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 rr(e){e.ok&&e.warnings.length===0||n({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 ir(e,t,n=s().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 C(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=rt(e.q??``,sr(t,n).filter(t=>dr(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 S(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function ar(e,t,n=s().bin[0]){let r=sr(t,n),i=e.operationId===void 0?or(r,e.command):r.find(t=>t.operationId===e.operationId);return i===void 0?C(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`]):S(`Generated operation detail`,{operation:i,usage:pr(i,r)})}function or(e,t){if(t===void 0)return;let{bin:n}=s(),r=wr(t,n);return e.find(e=>wr(e.cli.command,n)===r)}function sr(e,n){return e.map(e=>{let r=e.requestBody??[],i=[...e.parameters.map(e=>cr(e)),...r.flatMap(e=>e.parameter.map(t=>cr(t,r.length>1?e.contentType:void 0))),...lr(r)],a=[n,...e.cliPath].join(` `),o=t(e.intent),s=e.method===`DELETE`||e.intent===`delete`,c=r[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:te(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&r.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}})}function cr(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 lr(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 ur(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function dr(e,t){return!(t.root!==void 0&&!fr(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 fr(e,t){let n=nt(t);return n.length===0||nt(e.cli.path.at(0)??``)===n}function pr(e,t){let n=ur(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`,z(`required path flags`,r,`path`),z(`required query flags`,r,`query`),z(`required header flags`,r,`header`),z(`required body flags`,r,`body`),z(`optional path flags`,i,`path`),z(`optional query flags`,i,`query`),z(`optional header flags`,i,`header`),z(`optional body flags`,i,`body`),...yr(e,t),...mr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
+ `)}function mr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var hr=[`-id`,`-slug`,`-url`],gr=[`--id`,`--slug`,`--url`],_r=`--from-file "<path>"`;function vr(e,t,n=s().bin[0]){let r=sr(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:yr(i,r)}function yr(e,t){return[`example: ${[e.cli.command,...xr(e),`--data`].join(` `)}`,...br(e,t)]}function br(e,t){return ur(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`&&e.path.endsWith(`/lookup`)&&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} ${Cr(i)} --data`;return[`lookup: ${e.name} from a slug or name: ${a}`]})}function xr(e){let t=ur(e).filter(e=>e.required),n=(t.length>0?t:Sr(e)).map(Cr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,_r]:n}function Sr(e){let t=new Set;et(t,e.resource);for(let n of hr)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 gr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function Cr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function z(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function wr(e,t=s().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var Tr=`dist/aventure-cli/command-catalog.compact.txt`,Er=` · `,Dr=`-`;function Or(e=s().bin[0]){return N(kr(j(Ot(import.meta.url)),e),Tr)}function kr(e,t){let n=e;for(;;){if(P(N(n,`package.json`)))return n;let r=j(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Ar(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function jr(e,t,n,r=s().bin[0]){let i=ir(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Nr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Fr(i.data,Pr(e.format,`lines`)),summary:`Generated operation matches`})}function Mr(e,t,n,r=s().bin[0]){let i=ar(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Nr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Ir(i.data,Pr(e.format,`usage`)),summary:`Generated operation detail`})}function Nr(e){let t=e.mode,n=Pr(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`)){R({mode:t},C(`--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
5
  `)?i:`${i}\n`;if(e.opts.output!==void 0){wt(e.opts.output,a),R({mode:t},S(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:Vr(e.data)}));return}if(t===`text`){process.stdout.write(a);return}R({mode:t},S(e.summary,e.data,{counts:Vr(e.data)}))}function Pr(e,t){return e??t}function Fr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
6
6
  `):t===`text`?zr(e.operation):t===`compact`?e.operation.map(Lr).join(`
7
7
  `):e.operation.map(Br).join(`
8
8
  `)}function Ir(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Br(e.operation):t===`compact`?Lr(e.operation):e.usage}function Lr(e){let t=Rr(e);return[e.cli.command,e.summary,t.length===0?Dr:t.join(` `)].join(Er)}function Rr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function zr(e){return e.map(e=>`${e.cli.command}\n ${Br(e)}`).join(`
9
9
  `)}function Br(e){let t=Rr(e);return[B(`operationId`,e.operationId),B(`scope`,e.scope),B(`mutates`,String(e.mutates)),B(`destructive`,String(e.destructive)),B(`intent`,e.intent),B(`resource`,e.resource),B(`cli`,e.cli.command),e.mcpTool===null?``:B(`mcpTool`,e.mcpTool),B(`method`,e.method),B(`path`,e.path),B(`auth`,e.auth),B(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),B(`requiredFlags`,t.join(` `)),B(`bodyKind`,e.body.kind??``),B(`bodyRequired`,String(e.body.required)),B(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function B(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Vr(e){return`count`in e?e.count:{returned:1}}function Hr(e,t,n=s().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 Ur(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Yr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),A(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=k(a);if(r.length>0){R({mode:e},C(`Use either a command path or --ask, not both.`));return}R({mode:e},await $r(i,a.ask,a.environment,e));return}let o=Qr(e,r),s=t.find(t=>o!==void 0&&Qr(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?Zr(r,t):S(`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){R({mode:k(a)},c);return}Mr({...a,...c.data},t,k(a,`text`),n)}),Jr(e,t,n)}var Ur=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))}},Wr=2,Gr=6,Kr={subcommandTerm(e){let t=o.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,a=i-t-4;return n===``||a>=r.minWidthToWrap?o.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Wr)}${e}\n${qr(n,i,r)}`}};function qr(e,t,n){return n.boxWrap(e,t-Gr).replace(/^/gmu,` `.repeat(Gr))}function Jr(e,t,n){for(let r of t){let i=Qr(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=vr(r.operationId,t,n),[s,...c]=mr(r.errorResponse),l=c.map(t=>qr(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Wr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
11
- `)}\n`})}}function Yr(e){let[t,...n]=e.filter(e=>e.cliPath.at(-2)===`help`&&ei(e)!==void 0);return n.length===0?t:void 0}var Xr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Zr(e,t){let[n,...r]=e,i=le.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return S(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=ee(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return S(`Resolved by route template`,{operationId:s.operationId});let c=ne({method:a,path:o});return!c.ok||c.data===null?C(c.summary,[...c.warnings,Xr]):S(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function Qr(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 $r(e,t,n,r){let i=ei(e);if(i===void 0)return C(`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 An(e,{[i.optionKey]:t});return a.ok?await w({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Be(r)?`json`:`auto`}):a}function ei(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 ti(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}function ni(e){return e.split(` `)[0]??e}function ri(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 ii(e,t,n){let r=t.join(` `).trim();return r.length===0?S(`No positional text`,n):n[e.optionKey]===void 0?S(`Positional text parsed`,{...n,[e.optionKey]:r}):C(`Use either the positional argument or ${ni(e.flag)}, not both.`)}function ai(e,t,n){if(e.cliPath[0]!==`lookup`||!oi(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?C(i):C(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function oi(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var si=D({artifact:T().nullish(),group:T().nullish(),name:T().nullish(),revision:T().nullish(),time:E({offset:!0}).nullish(),version:T().nullish()}),ci=D({build:si});function V(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 li=pe([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),ui=pe([`RSA_OAEP_256_A256_GCM_V1`]),di=D({clientLabel:T().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:li.nullish(),encryptionAlgorithm:ui.nullish(),encryptionPublicKey:T().min(344).max(12e3).nullish()}),fi=32;async function pi(){let e=await jt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await jt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function mi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=hi(n,`wrapped key`,128,1024),s=hi(r,`nonce`,12,12),c=hi(i,`ciphertext`,1,65536),l=hi(a,`authentication tag`,16,16),u;try{u=await jt.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!==fi)throw Error(`broker credential used an invalid AES-256 key`);let e=await jt.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 jt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Et(`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 hi(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 gi=pe([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),_i=pe([`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`]),vi=D({approvedAt:E({offset:!0}).nullish(),clientLabel:T(),clientPlatform:li,comparisonCode:T(),consumedAt:E({offset:!0}).nullish(),createdAt:E({offset:!0}),expiresAt:E({offset:!0}),id:ue(),intervalSeconds:fe().int().min(1),keyReadyAt:E({offset:!0}).nullish(),status:gi,terminalAt:E({offset:!0}).nullish(),terminalReason:_i.nullish(),updatedAt:E({offset:!0})}),yi=D({algorithm:ui,authenticationTag:T(),ciphertext:T(),nonce:T(),wrappedKey:T()}),bi=D({delivery:yi.nullish(),expiresAt:E({offset:!0}),status:gi,terminalReason:_i.nullish()}),xi=D({comparisonCode:T(),expiresAt:E({offset:!0}),id:ue(),intervalSeconds:fe().int().min(1),pollSecret:T(),verificationUrl:T()}),H=[{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 Clerk 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 Clerk 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 stored API key and returns provider metadata so the CLI can confirm remote revocation before removing local bytes.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Remove local bytes even when remote revocation cannot be confirmed.`}]}],Si=V(H,`start`),Ci=V(H,`poll`),wi=V(H,`acknowledge`),Ti=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${ve(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ji(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ei=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${O(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Di(e){let t=await ae(he(x()),{method:Si.method,path:y(Si.path,{},Si.operationId),headers:{},contentType:`application/json`,body:e},xi);if(!t.ok)throw new Ti(`start`,t.problem);return Mi(t.data)}async function Oi(e,t){let n=b(Ci.operationId),r=await ae(he(x()),{method:Ci.method,path:y(Ci.path,{cliAuthorizationId:e},Ci.operationId),headers:{[n]:t}},bi);if(!r.ok)throw new Ti(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Ai(r.headers[`retry-after`])}}async function ki(e,t){let n=b(wi.operationId),r;try{r=await ae(he(x()),{method:wi.method,path:y(wi.path,{cliAuthorizationId:e},wi.operationId),headers:{[n]:t}},vi)}catch(e){throw new Ei(`acknowledge`,e,[t])}if(!r.ok)throw new Ti(`acknowledge`,r.problem,[t]);return r.data}function Ai(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ji(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Mi(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())})`},[Dt.custom]:{enumerable:!1,value:a}})}async function Ni(e){let t=await Pi(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await ge(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 — ${O(n,[e.credential.secret])}`}}}}async function Pi(e){let t=he(x()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Le)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${O(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by Clerk`,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: ${ve(n.problem,[e])}`}}var Fi=V(H,`revoke`);async function Ii(e){let t;try{t=ze(x().host)}catch(e){return C(`auth logout: invalid API host — ${O(e)}`)}let n=await Li(t),r=await Bi(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`?S(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...C(`auth logout: ${i[0]}`),data:a}:S(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 Li(e){let t=await je(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await zi(t.stored):{revoked:!1};try{await Se(e)}catch(e){return{state:`failed`,summary:O(e)}}return{state:`forgotten`,...n}}async function Ri(e){let t=Reflect.get(await ot(e),`revocation_endpoint`);return typeof t==`string`?Ee(t,`revocation endpoint`,!0):void 0}async function zi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Ri(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:Fe(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:O(e,Ae(n))}}}async function Bi(e,t){let n;try{n=await be(e)}catch(e){return C(`auth logout: stored credential could not be read — ${O(e)}`)}if(n.state===`unavailable`)return{...C(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Vi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...C(`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:Hi(r,!1,!1)};try{await Ce(r.host)}catch(e){return{...C(`auth logout: local credential removal failed — ${O(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:Hi(r,a,!1)}}return S(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.`,Hi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Vi(e){let t=he(x());try{let n=await ae(t,{method:Fi.method,path:y(Fi.path,{},Fi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Le);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:ve(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:O(t,[e.credential.secret])}}}function Hi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Ui=`RSA_OAEP_256_A256_GCM_V1`,Wi=1,Gi=30,Ki=s().bin[0],qi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${Ki} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ji(e){if(!Tt.isTTY)return C(`${Ki} 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=x().host;t=ze(e),n=Oe(e)}catch(e){return C(`auth login --key: invalid environment configuration — ${O(e)}`)}for(;;){let e;try{e=await Re(t)}catch(e){return C(`auth login --key: credential storage could not be inspected — ${O(e)}`)}if(e.state===`unavailable`)return C(`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&&I.write(xe(e.keyringFailure));break}let n=await Yi(e.stored);if(n!==null)return n}let r;try{r=await pi()}catch(e){return C(`auth login --key: ephemeral encryption key could not be created — ${O(e)}`)}let i=di.safeParse({clientLabel:e.clientLabel?.trim()||(Nt().trim()||Ki).slice(0,120),clientPlatform:$i(),encryptionAlgorithm:Ui,encryptionPublicKey:r.publicKey});if(!i.success)return C(`auth login --key: ${de(i.error)}`);let a;try{a=await Di(i.data)}catch(e){return C(`auth login --key: could not start browser authorization — ${O(e)}`)}let o;try{o=ye(a,n)}catch(e){return C(`auth login --key: unsafe browser authorization URL rejected — ${O(e)}`)}if(!Qi(await _e(a,n,{noBrowser:e.noBrowser}),a,o))return C(`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 Zi(a)}catch(e){return C(`auth login --key: authorization did not complete — ${O(e)}`,[],{references:[o]})}if(s.algorithm!==Ui)return C(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await mi(r.privateKey,s)}catch(e){return C(`auth login --key: encrypted credential could not be opened — ${O(e)}`)}let l=await Pi(c);if(l.state!==`verified`)return C(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await ge(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return C(`auth login --key: credential could not be durably stored — ${O(e)}`)}let d;try{d=await Xi(a)}catch(e){return U(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${O(e,[a.pollSecret])}`,qi)}if(d.status!==`CONSUMED`)return U(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,qi);let f=await Pi(c);if(f.state!==`verified`||!ra(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}`,qi);try{let e=await ge(t,{apiKey:f.apiKey,secret:c},`active`);return S(`API key stored; authenticated identity and broker acknowledgment verified.`,na(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 — ${O(e)}`,qi)}}async function Yi(e){let t=await Pi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?S(`API key is already stored and its authenticated identity was verified.`,na(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${Ki} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&ra(t.apiKey,e.credential.apiKey))try{let n=await ge(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return S(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,na(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 — ${O(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${Ki} 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 \`${Ki} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Vi(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 Ce(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${O(t,[e.credential.secret])}`)}return I.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
10
+ `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new Ur(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Yr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),k(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=O(a);if(r.length>0){R({mode:e},C(`Use either a command path or --ask, not both.`));return}R({mode:e},await $r(i,a.ask,a.environment,e));return}let o=Qr(e,r),s=t.find(t=>o!==void 0&&Qr(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?Zr(r,t):S(`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){R({mode:O(a)},c);return}Mr({...a,...c.data},t,O(a,`text`),n)}),Jr(e,t,n)}var Ur=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))}},Wr=2,Gr=6,Kr={subcommandTerm(e){let t=o.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,a=i-t-4;return n===``||a>=r.minWidthToWrap?o.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Wr)}${e}\n${qr(n,i,r)}`}};function qr(e,t,n){return n.boxWrap(e,t-Gr).replace(/^/gmu,` `.repeat(Gr))}function Jr(e,t,n){for(let r of t){let i=Qr(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=vr(r.operationId,t,n),[s,...c]=mr(r.errorResponse),l=c.map(t=>qr(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Wr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
11
+ `)}\n`})}}function Yr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&ei(e)!==void 0});return n.length===0?t:void 0}var Xr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Zr(e,t){let[n,...r]=e,i=ue.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return S(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=ee(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return S(`Resolved by route template`,{operationId:s.operationId});let c=ne({method:a,path:o});return!c.ok||c.data===null?C(c.summary,[...c.warnings,Xr]):S(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function Qr(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 $r(e,t,n,r){let i=ei(e);if(i===void 0)return C(`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 An(e,{[i.optionKey]:t});return a.ok?await ce({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Ve(r)?`json`:`auto`}):a}function ei(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 ti(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}function ni(e){return e.split(` `)[0]??e}function ri(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 ii(e,t,n){let r=t.join(` `).trim();return r.length===0?S(`No positional text`,n):n[e.optionKey]===void 0?S(`Positional text parsed`,{...n,[e.optionKey]:r}):C(`Use either the positional argument or ${ni(e.flag)}, not both.`)}function ai(e,t,n){if(e.cliPath[0]!==`lookup`||!oi(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?C(i):C(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function oi(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var si=E({artifact:w().nullish(),group:w().nullish(),name:w().nullish(),revision:w().nullish(),time:T({offset:!0}).nullish(),version:w().nullish()}),ci=E({build:si});function V(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 li=me([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),ui=me([`RSA_OAEP_256_A256_GCM_V1`]),di=E({clientLabel:w().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:li.nullish(),encryptionAlgorithm:ui.nullish(),encryptionPublicKey:w().min(344).max(12e3).nullish()}),fi=32;async function pi(){let e=await jt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await jt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function mi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=hi(n,`wrapped key`,128,1024),s=hi(r,`nonce`,12,12),c=hi(i,`ciphertext`,1,65536),l=hi(a,`authentication tag`,16,16),u;try{u=await jt.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!==fi)throw Error(`broker credential used an invalid AES-256 key`);let e=await jt.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 jt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Et(`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 hi(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 gi=me([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),_i=me([`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`]),vi=E({approvedAt:T({offset:!0}).nullish(),clientLabel:w(),clientPlatform:li,comparisonCode:w(),consumedAt:T({offset:!0}).nullish(),createdAt:T({offset:!0}),expiresAt:T({offset:!0}),id:de(),intervalSeconds:pe().int().min(1),keyReadyAt:T({offset:!0}).nullish(),status:gi,terminalAt:T({offset:!0}).nullish(),terminalReason:_i.nullish(),updatedAt:T({offset:!0})}),yi=E({algorithm:ui,authenticationTag:w(),ciphertext:w(),nonce:w(),wrappedKey:w()}),bi=E({delivery:yi.nullish(),expiresAt:T({offset:!0}),status:gi,terminalReason:_i.nullish()}),xi=E({comparisonCode:w(),expiresAt:T({offset:!0}),id:de(),intervalSeconds:pe().int().min(1),pollSecret:w(),verificationUrl:w()}),H=[{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 Clerk 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 Clerk 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 Clerk API key authenticating this request and returns provider metadata so the CLI can confirm remote revocation before removing local bytes.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Remove local bytes even when remote revocation cannot be confirmed.`}]}],Si=V(H,`start`),Ci=V(H,`poll`),wi=V(H,`acknowledge`),Ti=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${ye(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ji(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ei=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${D(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Di(e){let t=await ae(ge(x()),{method:Si.method,path:y(Si.path,{},Si.operationId),headers:{},contentType:`application/json`,body:e},xi);if(!t.ok)throw new Ti(`start`,t.problem);return Mi(t.data)}async function Oi(e,t){let n=b(Ci.operationId),r=await ae(ge(x()),{method:Ci.method,path:y(Ci.path,{cliAuthorizationId:e},Ci.operationId),headers:{[n]:t}},bi);if(!r.ok)throw new Ti(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Ai(r.headers[`retry-after`])}}async function ki(e,t){let n=b(wi.operationId),r;try{r=await ae(ge(x()),{method:wi.method,path:y(wi.path,{cliAuthorizationId:e},wi.operationId),headers:{[n]:t}},vi)}catch(e){throw new Ei(`acknowledge`,e,[t])}if(!r.ok)throw new Ti(`acknowledge`,r.problem,[t]);return r.data}function Ai(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ji(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Mi(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())})`},[Dt.custom]:{enumerable:!1,value:a}})}async function Ni(e){let t=await Pi(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await _e(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 — ${D(n,[e.credential.secret])}`}}}}async function Pi(e){let t=ge(x()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Re)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${D(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by Clerk`,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: ${ye(n.problem,[e])}`}}var Fi=V(H,`revoke`);async function Ii(e){let t;try{t=Be(x().host)}catch(e){return C(`auth logout: invalid API host — ${D(e)}`)}let n=await Li(t),r=await Bi(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`?S(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...C(`auth logout: ${i[0]}`),data:a}:S(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 Li(e){let t=await Me(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await zi(t.stored):{revoked:!1};try{await Ce(e)}catch(e){return{state:`failed`,summary:D(e)}}return{state:`forgotten`,...n}}async function Ri(e){let t=Reflect.get(await st(e),`revocation_endpoint`);return typeof t==`string`?De(t,`revocation endpoint`,!0):void 0}async function zi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Ri(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:Ie(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:D(e,je(n))}}}async function Bi(e,t){let n;try{n=await xe(e)}catch(e){return C(`auth logout: stored credential could not be read — ${D(e)}`)}if(n.state===`unavailable`)return{...C(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Vi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...C(`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:Hi(r,!1,!1)};try{await we(r.host)}catch(e){return{...C(`auth logout: local credential removal failed — ${D(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:Hi(r,a,!1)}}return S(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.`,Hi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Vi(e){let t=ge(x());try{let n=await ae(t,{method:Fi.method,path:y(Fi.path,{},Fi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Re);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:ye(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:D(t,[e.credential.secret])}}}function Hi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Ui=`RSA_OAEP_256_A256_GCM_V1`,Wi=1,Gi=30,Ki=s().bin[0],qi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${Ki} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ji(e){if(!Tt.isTTY)return C(`${Ki} 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=x().host;t=Be(e),n=ke(e)}catch(e){return C(`auth login --key: invalid environment configuration — ${D(e)}`)}for(;;){let e;try{e=await ze(t)}catch(e){return C(`auth login --key: credential storage could not be inspected — ${D(e)}`)}if(e.state===`unavailable`)return C(`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&&I.write(Se(e.keyringFailure));break}let n=await Yi(e.stored);if(n!==null)return n}let r;try{r=await pi()}catch(e){return C(`auth login --key: ephemeral encryption key could not be created — ${D(e)}`)}let i=di.safeParse({clientLabel:e.clientLabel?.trim()||(Nt().trim()||Ki).slice(0,120),clientPlatform:$i(),encryptionAlgorithm:Ui,encryptionPublicKey:r.publicKey});if(!i.success)return C(`auth login --key: ${fe(i.error)}`);let a;try{a=await Di(i.data)}catch(e){return C(`auth login --key: could not start browser authorization — ${D(e)}`)}let o;try{o=be(a,n)}catch(e){return C(`auth login --key: unsafe browser authorization URL rejected — ${D(e)}`)}if(!Qi(await ve(a,n,{noBrowser:e.noBrowser}),a,o))return C(`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 Zi(a)}catch(e){return C(`auth login --key: authorization did not complete — ${D(e)}`,[],{references:[o]})}if(s.algorithm!==Ui)return C(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await mi(r.privateKey,s)}catch(e){return C(`auth login --key: encrypted credential could not be opened — ${D(e)}`)}let l=await Pi(c);if(l.state!==`verified`)return C(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await _e(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return C(`auth login --key: credential could not be durably stored — ${D(e)}`)}let d;try{d=await Xi(a)}catch(e){return U(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${D(e,[a.pollSecret])}`,qi)}if(d.status!==`CONSUMED`)return U(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,qi);let f=await Pi(c);if(f.state!==`verified`||!ra(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}`,qi);try{let e=await _e(t,{apiKey:f.apiKey,secret:c},`active`);return S(`API key stored; authenticated identity and broker acknowledgment verified.`,na(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 — ${D(e)}`,qi)}}async function Yi(e){let t=await Pi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?S(`API key is already stored and its authenticated identity was verified.`,na(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${Ki} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&ra(t.apiKey,e.credential.apiKey))try{let n=await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return S(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,na(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 — ${D(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${Ki} 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 \`${Ki} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Vi(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 we(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${D(t,[e.credential.secret])}`)}return I.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
13
  `),null}async function Xi(e){let t=new Date(e.expiresAt).getTime(),n=ea(e.intervalSeconds);for(;;)try{return await ki(e.id,e.pollSecret)}catch(e){if(e instanceof Ti){if(!e.retryable)throw e;n=ea(e.retryAfterSeconds??n)}else if(!(e instanceof Ei))throw e;if(Date.now()>=t)throw e;I.write(`Broker acknowledgment was interrupted; retrying.
14
14
  `),await ta(n,t)}}async function Zi(e){let t=new Date(e.expiresAt).getTime(),n=ea(e.intervalSeconds),r;for(I.write(`Waiting for browser approval...
15
15
  `);Date.now()<t;){let i;try{i=await Oi(e.id,e.pollSecret)}catch(e){if(e instanceof Ti){if(!e.retryable)throw e;n=ea(e.retryAfterSeconds??n)}r=e,I.write(`Authorization poll was interrupted; retrying.
16
- `),await ta(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=ea(i.retryAfterSeconds??n),await ta(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(_(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: ${O(r,[e.pollSecret])}`)}function Qi(e,t,n){let r=e.state===`opened`;return!r&&!I.isTTY?!1:(I.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...I.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 $i(){switch(Pt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function ea(e){return Math.min(Gi,Math.max(Wi,e))}async function ta(e,t){let n=t-Date.now();n>0&&await Ft(Math.min(e*1e3,n))}function na(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:_(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...C(n,r===void 0?[]:[r]),data:na(e,t)}}function ra(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 ia(){return null}async function aa(e){let t=null,n=e=>{t=e};try{await Pe(e,n),await Ie(n)}catch(e){return{materialized:t,failure:O(e)}}return{materialized:t,failure:null}}async function oa(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=sa(e.credential,r.materialized)};try{let t=await w({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(ca(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=fa(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 ia(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:O(r,la(t,n,o))}}}function sa(e,t){if(e===null)return null;let n=t??De().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function ca(e){return[e.summary,...e.warnings].join(` — `)}function la(e,t,n){return[x().userBearerToken,...ce(n?.headers??{}),...e.state===`found`?Ae(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function ua(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:_(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:ha(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function da(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:we(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:Te(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 fa(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=m.safeParse(e.response);if(!t.success)throw t.error;return t.data}function pa(e,t){let{expiresAt:n,expiresInDay:r}=ua(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 Clerk)`:``}var ma=864e5;function ha(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/ma)}var ga=7;function _a(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ga)}\u2026${e.slice(-4)}`}var va=13,ya=14;function ba(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api unreachable)`:` (api ${e.apiVersion})`),``,...Sa(e.oauth,e.cliName,e.refresh),...wa(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,Da(e.providers)),W(`Environment`,Oa(e.resolved)),W(`Selected`,ka(e.resolved,e.refresh,e.cliName)),...xa(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
18
- `)}function xa(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(va)}${t}`}function G(e){return` ${``.padEnd(va)}${e}`}function Sa(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=Te(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(Ca(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 Ca(e,t,n){return we(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 wa(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`} ${_a(e.apiKeyId)}`),...Ta(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ta(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by Clerk \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 Clerk now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(Ea(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"Clerk owns the live verdict — `auth status` re-checks it":`Clerk could not be asked \u2014 ${n.summary}`)]]}function Ea(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<=ya?`${n} ${r}, ${t}d away`:`${n} ${r}`}function Da(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`clerk browser sign-in`:`no browser sign-in`,t?`oauth ${ke(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Oa(e){return`${h.authToken}=${e.present?e.source??`resolved`:`unset`}`}function ka(e,t,n){return e.present||t.materialized===`env`?`${h.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:t.failure===null?`none — public reads only`:`none \u2014 sign in with \`${n} auth login\``}var Aa=pe([`PROMPT`,`SKILL`,`AGENT`]),ja=D({kind:Aa,name:T(),version:T()}),Ma=D({content:T(),core:ja}),Na=D({key:T(),version:T()}),Pa=D({agent:me(T(),Na),prompt:me(T(),Na),skill:me(T(),Na)}),K=`aventure`,Fa=`SKILL.md`,Ia=`.aventure-skills.json`,La=`claude`,Ra=2e4,za=2,Ba=[{name:`claude-code`,base:`home`,detect:[`.claude`],skill:[`.claude`,`skills`],mcp:{shape:`claude-cli`,file:[`.claude.json`],key:`mcpServers`}},{name:`codex`,base:`home`,detect:[`.codex`],skill:[`.agents`,`skills`],mcp:{shape:`toml`,file:[`.codex`,`config.toml`]}},{name:`cursor`,base:`home`,detect:[`.cursor`],skill:null,mcp:{shape:`json`,file:[`.cursor`,`mcp.json`],key:`mcpServers`,entry:e=>({type:`http`,url:e})}},{name:`opencode`,base:`config`,detect:[`opencode`],skill:[`opencode`,`skills`],mcp:{shape:`json`,file:[`opencode`,`opencode.json`],key:`mcp`,entry:e=>({type:`remote`,url:e,enabled:!0})}}];function Va(e){return P(Ha(e))}function Ha(e){return lt(Ga(e),...e.detect)}function Ua(e){return e.skill===null?null:lt(Ga(e),...e.skill)}function Wa(e){return lt(Ga(e),...e.mcp.file)}function Ga(e){return e.base===`home`?qa(`HOME`)??Mt():Ka()}function Ka(){return qa(`XDG_CONFIG_HOME`)??lt(qa(`HOME`)??Mt(),`.config`)}function qa(e){let t=process.env[e]?.trim();return t===void 0||t.length===0?void 0:t}function Ja(e){return lt(M(e),Ia)}function Ya(e){if(!P(e))return{};try{let t=Pa.safeParse(JSON.parse(gt(e,`utf8`)));return t.success?t.data.skill:{}}catch{return{}}}function Xa(e,t,n){let r=Ja(e),i={...Ya(r)};for(let e of n){let n=t.skill[e];n!==void 0&&(i[e]=n)}return Qa(r,`${JSON.stringify({prompt:{},skill:i,agent:{}},null,za)}\n`)}function Za(e,t,n){let r=lt(e,t,Fa);return M(M(r))===e?Qa(r,n):`refusing to install ${t}: it does not name one directory inside ${e}`}function Qa(e,t){try{$a(e,t)}catch(t){return`cannot write ${e}: ${O(t)}`}return null}function $a(e,t){mt(M(e),{recursive:!0});let n=`${e}.aventure-tmp`;try{wt(n,t,`utf8`),yt(n,e)}finally{bt(n,{force:!0})}}var eo=RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*"?${K}"?[ \\t]*\\]`),to=/^[ \t]*mcp_servers[ \t]*=/m;function no(e){let t=Wa(e);if(!P(t))return null;try{let n=gt(t,`utf8`);if(e.mcp.shape===`toml`)return io(n);let r=lo(n)?.[e.mcp.key],i=(r!==void 0&&uo(r)?r:void 0)?.[K];return i===void 0||!uo(i)?null:typeof i.url==`string`?i.url:ro}catch{return null}}var ro=`unknown`;function io(e){let t=e.split(`
19
- `),n=t.findIndex(e=>eo.test(e));if(n<0)return null;for(let e of t.slice(n+1)){if(e.trimStart().startsWith(`[`))break;let t=/^[ \t]*url[ \t]*=[ \t]*"([^"]*)"/.exec(e);if(t?.[1]!==void 0)return t[1]}return ro}function ao(e,t){let n=e.mcp,r=Wa(e);if(n.shape===`claude-cli`)return co(t);try{if(n.shape===`toml`)return oo(r,t);so(r,n.key,n.entry(t))}catch(e){return`cannot write ${r}: ${O(e)}`}return null}function oo(e,t){let n=P(e)?gt(e,`utf8`):``,r=`[mcp_servers.${K}]\nurl = "${t}"\n`;return to.test(n)?`${e} declares mcp_servers as an inline table, which this command cannot extend; add by hand:\n${r}`:Qa(e,`${n}${n.length===0||n.endsWith(`
16
+ `),await ta(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=ea(i.retryAfterSeconds??n),await ta(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(_(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: ${D(r,[e.pollSecret])}`)}function Qi(e,t,n){let r=e.state===`opened`;return!r&&!I.isTTY?!1:(I.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...I.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 $i(){switch(Pt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function ea(e){return Math.min(Gi,Math.max(Wi,e))}async function ta(e,t){let n=t-Date.now();n>0&&await Ft(Math.min(e*1e3,n))}function na(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:_(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...C(n,r===void 0?[]:[r]),data:na(e,t)}}function ra(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 ia(){return null}async function aa(e){let t=null,n=e=>{t=e};try{await Fe(e,n),await Le(n)}catch(e){return{materialized:t,failure:D(e)}}return{materialized:t,failure:null}}async function oa(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=sa(e.credential,r.materialized)};try{let t=await ce({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(ca(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=fa(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 ia(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:D(r,la(t,n,o))}}}function sa(e,t){if(e===null)return null;let n=t??Oe().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function ca(e){return[e.summary,...e.warnings].join(` — `)}function la(e,t,n){return[x().userBearerToken,...le(n?.headers??{}),...e.state===`found`?je(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function ua(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:_(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:ha(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function da(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:Te(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:Ee(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 fa(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=m.safeParse(e.response);if(!t.success)throw t.error;return t.data}function pa(e,t){let{expiresAt:n,expiresInDay:r}=ua(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 Clerk)`:``}var ma=864e5;function ha(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/ma)}var ga=7;function _a(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ga)}\u2026${e.slice(-4)}`}var va=13,ya=14;function ba(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api unreachable)`:` (api ${e.apiVersion})`),``,...Sa(e.oauth,e.cliName,e.refresh),...wa(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,Da(e.providers)),W(`Environment`,Oa(e.resolved)),W(`Selected`,ka(e.resolved,e.refresh,e.cliName)),...xa(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
18
+ `)}function xa(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(va)}${t}`}function G(e){return` ${``.padEnd(va)}${e}`}function Sa(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=Ee(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(Ca(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 Ca(e,t,n){return Te(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 wa(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`} ${_a(e.apiKeyId)}`),...Ta(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ta(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by Clerk \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 Clerk now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(Ea(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"Clerk owns the live verdict — `auth status` re-checks it":`Clerk could not be asked \u2014 ${n.summary}`)]]}function Ea(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<=ya?`${n} ${r}, ${t}d away`:`${n} ${r}`}function Da(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`clerk browser sign-in`:`no browser sign-in`,t?`oauth ${Ae(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Oa(e){return`${h.authToken}=${e.present?e.source??`resolved`:`unset`}`}function ka(e,t,n){return e.present||t.materialized===`env`?`${h.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:t.failure===null?`none — public reads only`:`none \u2014 sign in with \`${n} auth login\``}var Aa=me([`PROMPT`,`SKILL`,`AGENT`]),ja=E({kind:Aa,name:w(),version:w()}),Ma=E({content:w(),core:ja}),Na=E({key:w(),version:w()}),Pa=E({agent:he(w(),Na),prompt:he(w(),Na),skill:he(w(),Na)}),K=`aventure`,Fa=`SKILL.md`,Ia=`.aventure-skills.json`,La=`claude`,Ra=2e4,za=2,Ba=[{name:`claude-code`,base:`home`,detect:[`.claude`],skill:[`.claude`,`skills`],mcp:{shape:`claude-cli`,file:[`.claude.json`],key:`mcpServers`}},{name:`codex`,base:`home`,detect:[`.codex`],skill:[`.agents`,`skills`],mcp:{shape:`toml`,file:[`.codex`,`config.toml`]}},{name:`cursor`,base:`home`,detect:[`.cursor`],skill:null,mcp:{shape:`json`,file:[`.cursor`,`mcp.json`],key:`mcpServers`,entry:e=>({type:`http`,url:e})}},{name:`opencode`,base:`config`,detect:[`opencode`],skill:[`opencode`,`skills`],mcp:{shape:`json`,file:[`opencode`,`opencode.json`],key:`mcp`,entry:e=>({type:`remote`,url:e,enabled:!0})}}];function Va(e){return P(Ha(e))}function Ha(e){return M(Ga(e),...e.detect)}function Ua(e){return e.skill===null?null:M(Ga(e),...e.skill)}function Wa(e){return M(Ga(e),...e.mcp.file)}function Ga(e){return e.base===`home`?qa(`HOME`)??Mt():Ka()}function Ka(){return qa(`XDG_CONFIG_HOME`)??M(qa(`HOME`)??Mt(),`.config`)}function qa(e){let t=process.env[e]?.trim();return t===void 0||t.length===0?void 0:t}function Ja(e){return M(j(e),Ia)}function Ya(e){if(!P(e))return{};try{let t=Pa.safeParse(JSON.parse(gt(e,`utf8`)));return t.success?t.data.skill:{}}catch{return{}}}function Xa(e,t,n){let r=Ja(e),i={...Ya(r)};for(let e of n){let n=t.skill[e];n!==void 0&&(i[e]=n)}return Qa(r,`${JSON.stringify({prompt:{},skill:i,agent:{}},null,za)}\n`)}function Za(e,t,n){let r=M(e,t,Fa);return j(j(r))===e?Qa(r,n):`refusing to install ${t}: it does not name one directory inside ${e}`}function Qa(e,t){try{$a(e,t)}catch(t){return`cannot write ${e}: ${D(t)}`}return null}function $a(e,t){mt(j(e),{recursive:!0});let n=`${e}.aventure-tmp`;try{wt(n,t,`utf8`),yt(n,e)}finally{bt(n,{force:!0})}}var eo=RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*"?${K}"?[ \\t]*\\]`),to=/^[ \t]*mcp_servers[ \t]*=/m;function no(e){let t=Wa(e);if(!P(t))return null;try{let n=gt(t,`utf8`);if(e.mcp.shape===`toml`)return io(n);let r=lo(n)?.[e.mcp.key],i=(r!==void 0&&uo(r)?r:void 0)?.[K];return i===void 0||!uo(i)?null:typeof i.url==`string`?i.url:ro}catch{return null}}var ro=`unknown`;function io(e){let t=e.split(`
19
+ `),n=t.findIndex(e=>eo.test(e));if(n<0)return null;for(let e of t.slice(n+1)){if(e.trimStart().startsWith(`[`))break;let t=/^[ \t]*url[ \t]*=[ \t]*"([^"]*)"/.exec(e);if(t?.[1]!==void 0)return t[1]}return ro}function ao(e,t){let n=e.mcp,r=Wa(e);if(n.shape===`claude-cli`)return co(t);try{if(n.shape===`toml`)return oo(r,t);so(r,n.key,n.entry(t))}catch(e){return`cannot write ${r}: ${D(e)}`}return null}function oo(e,t){let n=P(e)?gt(e,`utf8`):``,r=`[mcp_servers.${K}]\nurl = "${t}"\n`;return to.test(n)?`${e} declares mcp_servers as an inline table, which this command cannot extend; add by hand:\n${r}`:Qa(e,`${n}${n.length===0||n.endsWith(`
20
20
  `)?``:`
21
- `}\n${r}`)}function so(e,t,n){let r=lo(P(e)?gt(e,`utf8`):`{}`);if(r===null)throw Error(`${e} is not a JSON object`);let i={...r},a=i[t];i[t]={...a!==void 0&&uo(a)?a:{},[K]:n},$a(e,`${JSON.stringify(i,null,za)}\n`)}function co(e){let t=[`mcp`,`add`,`--transport`,`http`,`-s`,`user`,K,e],n=st(La,t,{encoding:`utf8`,timeout:Ra}),r=`${La} ${t.join(` `)}`;if(n.error!==void 0)return`run \`${r}\`: ${n.error.message}`;if(n.status!==0){let e=(n.stderr??``).trim().split(`
22
- `).slice(-2).join(` | `);return`\`${r}\` exited ${n.status}: ${e||`no stderr`}`}return null}function lo(e){let t=v.safeParse(JSON.parse(e));return t.success&&uo(t.data)?t.data:null}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fo=`aventure`;function po(e,t=s().bin[0]){A(mo(e).command(`setup`).summary(`Install the aventure skill bundle and MCP server into your agent runtimes`).description([`Detect the agent runtimes installed for this user (${Ba.map(e=>e.name).join(`, `)}),`,`install or refresh the published ${fo}* skill bundle into each runtime's own`,`skill directory, and register the ${K} MCP server in each runtime's own config.`,``,` ${t} agents setup # write the skills and the MCP registration`,` ${t} agents setup --status # compare what is installed; exit 1 on drift`,`--execute is deprecated, accepted, and ignored; setup executes by its verb.`].join(`
23
- `)).addOption(new i(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`).default(!1)).addOption(new i(`--status`,`report installed skill versions against the manifest and exit 1 on drift; compares recorded versions, not file content, and writes nothing`).default(!1))).action(async function(e){let t=this.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment),R({mode:k(e)},await ho(e))})}function mo(e){let t=`agents`,n=e.commands.find(e=>e.name()===t);if(n!==void 0)return n;let r=We[t]?.summary??t;return e.command(t).summary(r).description(r)}async function ho(e){let t=await Do();if(!t.ok||t.data===null)return{...t,data:null};let n=await To(`getAgentInstructionManifest`,Pa);if(!n.ok||n.data===null)return{...n,data:null};let r=n.data,i=t.data,a=Object.keys(r.skill).filter(e=>e.startsWith(fo)).toSorted();if(a.length===0)return C(`The agent instruction manifest carries no ${fo}* skill; nothing to install.`);let o=Ba.map(e=>yo(e,r,a,i));return go({runtime:e.status===!0?o:await xo(o,r,i)},e,i)}function go(e,t,n){let r=e.runtime.filter(e=>e.detected),i=r.flatMap(e=>e.action.filter(e=>e.state!==`current`)),a=i.filter(e=>e.state===`failed`),o={runtimeDetected:r.length,actionPending:i.length,actionFailed:a.length},s=[`agents setup: ${r.length} runtime detected, ${i.length} action pending, mcp ${n}`,...e.runtime.map(_o)].join(`
24
- `);if(r.length===0){let t=Ba.map(e=>`${e.name}: no ${Ha(e)}`);return{...C(s,t,{counts:o}),data:e}}let c=a.length>0?a:t.status===!0?i:[];return c.length===0?S(s,e,{counts:o}):{...C(s,c.map(vo),{counts:o}),data:e}}function _o(e){if(!e.detected)return` ${e.name} not installed`;let t=e.action.filter(e=>e.state!==`current`);return t.length===0?` ${e.name} current (${e.action.length} item)`:` ${e.name} ${t.length} pending — ${t.map(vo).join(`; `)}`}function vo(e){return`${e.kind} ${e.name} ${e.state}: ${e.detail}`}function q(e,t,n,r){return{kind:e,name:t,state:n,detail:r}}function yo(e,t,n,r){let i=Ua(e),a=Wa(e),o={name:e.name,skillDir:i,mcpConfig:a};if(!Va(e))return{...o,detected:!1,action:[]};let s=no(e),c=s===null?q(`mcp`,K,`install`,`register ${r} in ${a}`):q(`mcp`,K,`current`,`${s} in ${a}`);return{...o,detected:!0,action:[...i===null?[]:bo(i,t,n),c]}}function bo(e,t,n){let r=Ya(Ja(e));return n.map(n=>{let i=t.skill[n]?.version??``,a=r[n]?.version,o=lt(e,n,Fa);return a===void 0||!P(o)?q(`skill`,n,`install`,`write ${o} at version ${i}`):a===i?q(`skill`,n,`current`,`${o} at version ${i}`):q(`skill`,n,`update`,`${o} ${a} -> ${i}`)})}async function xo(e,t,n){let r=e.flatMap(e=>e.action.filter(e=>e.kind===`skill`&&e.state!==`current`).map(e=>e.name)),i=new Map;for(let e of[...new Set(r)].toSorted())i.set(e,await wo(e));return e.map(e=>{let r=Ba.find(t=>t.name===e.name);if(!e.detected||r===void 0)return e;let a=[],o=e.action.map(t=>{if(t.state===`current`)return t;if(t.kind===`mcp`)return So(r,e.mcpConfig,n);let o=Co(e.skillDir,t.name,i.get(t.name));return o.state===`current`&&a.push(t.name),o}),s=e.skillDir===null||a.length===0?null:Xa(e.skillDir,t,a),c=s===null?[]:[q(`skill`,Ia,`failed`,s)];return{...e,action:[...o,...c]}})}function So(e,t,n){let r=ao(e,n);return r===null?q(`mcp`,K,`current`,`registered ${n} in ${t}`):q(`mcp`,K,`failed`,r)}function Co(e,t,n){if(e===null||n===void 0||!n.ok||n.data===null)return q(`skill`,t,`failed`,n?.summary??`no document fetched for ${t}`);let r=Za(e,t,n.data.content);return r===null?q(`skill`,t,`current`,`${lt(e,t,Fa)} at version ${n.data.core.version}`):q(`skill`,t,`failed`,r)}async function wo(e){return await To(`getAgentInstruction`,Ma,{kind:Aa.enum.SKILL,name:e})}async function To(e,t,n={}){let r=Eo(e);if(r===void 0)return C(`The generated command catalog carries no ${e} operation; regenerate it with \`make mcp-generate-contracts\` and reinstall.`);let i;try{i=se(r.operationId,n)}catch(t){return C(`Cannot address ${e}: ${O(t)}`)}let a=await w({method:r.method,path:i,auth:r.auth,responseFormat:`json`}).catch(e=>C(O(e)));if(!a.ok)return{...a,summary:`${r.method} ${i} failed: ${a.summary}`,data:null};let o=a.data,s=t.safeParse(typeof o==`object`&&o&&`response`in o?o.response:void 0);return s.success?S(`${r.method} ${i} answered`,s.data):C(`${i} returned an unexpected body: ${s.error.message}`)}function Eo(e){return j.find(t=>t.operationId===e)}async function Do(){try{let e=(await it()).oauthClient;if(e==null)return C(`The API published no OAuth client, so its MCP server URL is unknown.`);let t=e.mcpResource;return t==null?C(`The API published no MCP resource indicator, so its MCP server URL is unknown.`):S(`MCP host read from the API`,new URL(t).href)}catch(e){return C(`Correct API_ENV or pass \`--environment <name>\` — ${O(e)}.`)}}var Oo=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,ko=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Ao=`.aventure-cli-completion.bak`;function jo(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Ro([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Ro([`--uninstall`]))}function Mo(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=Io(),n=await Fo({rcFile:N(Mt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Yo});F.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Ro(e.uninstall?[`--uninstall`]:[])})}function No(e,t=`fpath-only`){return[Oo,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],ko].join(`
21
+ `}\n${r}`)}function so(e,t,n){let r=lo(P(e)?gt(e,`utf8`):`{}`);if(r===null)throw Error(`${e} is not a JSON object`);let i={...r},a=i[t];i[t]={...a!==void 0&&uo(a)?a:{},[K]:n},$a(e,`${JSON.stringify(i,null,za)}\n`)}function co(e){let t=[`mcp`,`add`,`--transport`,`http`,`-s`,`user`,K,e],n=ct(La,t,{encoding:`utf8`,timeout:Ra}),r=`${La} ${t.join(` `)}`;if(n.error!==void 0)return`run \`${r}\`: ${n.error.message}`;if(n.status!==0){let e=(n.stderr??``).trim().split(`
22
+ `).slice(-2).join(` | `);return`\`${r}\` exited ${n.status}: ${e||`no stderr`}`}return null}function lo(e){let t=v.safeParse(JSON.parse(e));return t.success&&uo(t.data)?t.data:null}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fo=`aventure`;function po(e,t=s().bin[0]){k(mo(e).command(`setup`).summary(`Install the aventure skill bundle and MCP server into your agent runtimes`).description([`Detect the agent runtimes installed for this user (${Ba.map(e=>e.name).join(`, `)}),`,`install or refresh the published ${fo}* skill bundle into each runtime's own`,`skill directory, and register the ${K} MCP server in each runtime's own config.`,``,` ${t} agents setup # write the skills and the MCP registration`,` ${t} agents setup --status # compare what is installed; exit 1 on drift`,`--execute is deprecated, accepted, and ignored; setup executes by its verb.`].join(`
23
+ `)).addOption(new i(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`).default(!1)).addOption(new i(`--status`,`report installed skill versions against the manifest and exit 1 on drift; compares recorded versions, not file content, and writes nothing`).default(!1))).action(async function(e){let t=this.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment),R({mode:O(e)},await ho(e))})}function mo(e){let t=`agents`,n=e.commands.find(e=>e.name()===t);if(n!==void 0)return n;let r=Qe[t]?.summary??t;return e.command(t).summary(r).description(r)}async function ho(e){let t=await Do();if(!t.ok||t.data===null)return{...t,data:null};let n=await To(`getAgentInstructionManifest`,Pa);if(!n.ok||n.data===null)return{...n,data:null};let r=n.data,i=t.data,a=Object.keys(r.skill).filter(e=>e.startsWith(fo)).toSorted();if(a.length===0)return C(`The agent instruction manifest carries no ${fo}* skill; nothing to install.`);let o=Ba.map(e=>yo(e,r,a,i));return go({runtime:e.status===!0?o:await xo(o,r,i)},e,i)}function go(e,t,n){let r=e.runtime.filter(e=>e.detected),i=r.flatMap(e=>e.action.filter(e=>e.state!==`current`)),a=i.filter(e=>e.state===`failed`),o={runtimeDetected:r.length,actionPending:i.length,actionFailed:a.length},s=[`agents setup: ${r.length} runtime detected, ${i.length} action pending, mcp ${n}`,...e.runtime.map(_o)].join(`
24
+ `);if(r.length===0){let t=Ba.map(e=>`${e.name}: no ${Ha(e)}`);return{...C(s,t,{counts:o}),data:e}}let c=a.length>0?a:t.status===!0?i:[];return c.length===0?S(s,e,{counts:o}):{...C(s,c.map(vo),{counts:o}),data:e}}function _o(e){if(!e.detected)return` ${e.name} not installed`;let t=e.action.filter(e=>e.state!==`current`);return t.length===0?` ${e.name} current (${e.action.length} item)`:` ${e.name} ${t.length} pending — ${t.map(vo).join(`; `)}`}function vo(e){return`${e.kind} ${e.name} ${e.state}: ${e.detail}`}function q(e,t,n,r){return{kind:e,name:t,state:n,detail:r}}function yo(e,t,n,r){let i=Ua(e),a=Wa(e),o={name:e.name,skillDir:i,mcpConfig:a};if(!Va(e))return{...o,detected:!1,action:[]};let s=no(e),c=s===null?q(`mcp`,K,`install`,`register ${r} in ${a}`):q(`mcp`,K,`current`,`${s} in ${a}`);return{...o,detected:!0,action:[...i===null?[]:bo(i,t,n),c]}}function bo(e,t,n){let r=Ya(Ja(e));return n.map(n=>{let i=t.skill[n]?.version??``,a=r[n]?.version,o=M(e,n,Fa);return a===void 0||!P(o)?q(`skill`,n,`install`,`write ${o} at version ${i}`):a===i?q(`skill`,n,`current`,`${o} at version ${i}`):q(`skill`,n,`update`,`${o} ${a} -> ${i}`)})}async function xo(e,t,n){let r=e.flatMap(e=>e.action.filter(e=>e.kind===`skill`&&e.state!==`current`).map(e=>e.name)),i=new Map;for(let e of[...new Set(r)].toSorted())i.set(e,await wo(e));return e.map(e=>{let r=Ba.find(t=>t.name===e.name);if(!e.detected||r===void 0)return e;let a=[],o=e.action.map(t=>{if(t.state===`current`)return t;if(t.kind===`mcp`)return So(r,e.mcpConfig,n);let o=Co(e.skillDir,t.name,i.get(t.name));return o.state===`current`&&a.push(t.name),o}),s=e.skillDir===null||a.length===0?null:Xa(e.skillDir,t,a),c=s===null?[]:[q(`skill`,Ia,`failed`,s)];return{...e,action:[...o,...c]}})}function So(e,t,n){let r=ao(e,n);return r===null?q(`mcp`,K,`current`,`registered ${n} in ${t}`):q(`mcp`,K,`failed`,r)}function Co(e,t,n){if(e===null||n===void 0||!n.ok||n.data===null)return q(`skill`,t,`failed`,n?.summary??`no document fetched for ${t}`);let r=Za(e,t,n.data.content);return r===null?q(`skill`,t,`current`,`${M(e,t,Fa)} at version ${n.data.core.version}`):q(`skill`,t,`failed`,r)}async function wo(e){return await To(`getAgentInstruction`,Ma,{kind:Aa.enum.SKILL,name:e})}async function To(e,t,n={}){let r=Eo(e);if(r===void 0)return C(`The generated command catalog carries no ${e} operation; regenerate it with \`make mcp-generate-contracts\` and reinstall.`);let i;try{i=se(r.operationId,n)}catch(t){return C(`Cannot address ${e}: ${D(t)}`)}let a=await ce({method:r.method,path:i,auth:r.auth,responseFormat:`json`}).catch(e=>C(D(e)));if(!a.ok)return{...a,summary:`${r.method} ${i} failed: ${a.summary}`,data:null};let o=a.data,s=t.safeParse(typeof o==`object`&&o&&`response`in o?o.response:void 0);return s.success?S(`${r.method} ${i} answered`,s.data):C(`${i} returned an unexpected body: ${s.error.message}`)}function Eo(e){return A.find(t=>t.operationId===e)}async function Do(){try{let e=(await at()).oauthClient;if(e==null)return C(`The API published no OAuth client, so its MCP server URL is unknown.`);let t=e.mcpResource;return t==null?C(`The API published no MCP resource indicator, so its MCP server URL is unknown.`):S(`MCP host read from the API`,new URL(t).href)}catch(e){return C(`Correct API_ENV or pass \`--environment <name>\` — ${D(e)}.`)}}var Oo=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,ko=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Ao=`.aventure-cli-completion.bak`;function jo(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Ro([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Ro([`--uninstall`]))}function Mo(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=Io(),n=await Fo({rcFile:N(Mt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Yo});F.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Ro(e.uninstall?[`--uninstall`]:[])})}function No(e,t=`fpath-only`){return[Oo,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],ko].join(`
25
25
  `)}function Po(){let e=Ro([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!zo(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=Ro([],`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 Fo({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Bo(e),o=a.length===0?[]:a.split(`
26
- `),s=Vo(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ho(o,s,t,e):Uo(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}: cancelled`,content:a}:(Ko(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Io(e=F.argv[1]){let t=e===void 0?``:Lo(e),n=N(M(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return P(n)?n:N(M(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function Lo(e){try{return vt(e)}catch{return N(e)}}function Ro(e,t=`inherit`){let n=st(F.execPath,[Io(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(F.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function zo(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Bo(e){return P(e)?(qo(e),gt(e,`utf8`)):``}function Vo(e,t){let n=Wo(e,Oo),r=Wo(e,ko);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 Ho(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Go(i),o=No(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
27
- `),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 Jo([...i.slice(0,c),...o,...i.slice(c)])}function Uo(e,t){return Jo(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Wo(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Go(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ko(e,t){mt(M(e),{recursive:!0}),P(e)&&(qo(e),qo(`${e}${Ao}`),ft(e,`${e}${Ao}`));let n=N(M(e),`.${ct(e)}.${F.pid}.tmp`);qo(n),wt(n,t,{mode:420}),yt(n,e)}function qo(e){if(P(e)&&pt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Jo(e){let t=e.join(`
26
+ `),s=Vo(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ho(o,s,t,e):Uo(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}: cancelled`,content:a}:(Ko(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Io(e=F.argv[1]){let t=e===void 0?``:Lo(e),n=N(j(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return P(n)?n:N(j(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function Lo(e){try{return vt(e)}catch{return N(e)}}function Ro(e,t=`inherit`){let n=ct(F.execPath,[Io(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(F.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function zo(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Bo(e){return P(e)?(qo(e),gt(e,`utf8`)):``}function Vo(e,t){let n=Wo(e,Oo),r=Wo(e,ko);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 Ho(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Go(i),o=No(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
27
+ `),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 Jo([...i.slice(0,c),...o,...i.slice(c)])}function Uo(e,t){return Jo(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Wo(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Go(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ko(e,t){mt(j(e),{recursive:!0}),P(e)&&(qo(e),qo(`${e}${Ao}`),ft(e,`${e}${Ao}`));let n=N(j(e),`.${lt(e)}.${F.pid}.tmp`);qo(n),wt(n,t,{mode:420}),yt(n,e)}function qo(e){if(P(e)&&pt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Jo(e){let t=e.join(`
28
28
  `);return t.length===0||t.endsWith(`
29
- `)?t:`${t}\n`}async function Yo(e){let t=It({input:F.stdin,output:F.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Xo=new Intl.Collator(void 0,{numeric:!0}),Zo=2e4;function Qo(e,t=s()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from the public npm registry; no credential required.`;A(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`,`(use \`make\` to rebuild that). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
30
- `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>R({mode:k(e)},$o()))}function $o(e,t=`apply`){let n=e;try{n??=s(process.argv[1])}catch(e){return C(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,o=n.registry===``?oe:a,c=n.registry===``&&r===`@aventurevc/aventure-cli`,l=es([`view`,o,`version`,`--silent`,`--global`],n,{timeout:Zo});if(!l.ok)return{...l,data:null};let u=(l.data??``).trim();if(u===``)return C(`npm view ${o} returned empty version`,[`empty_stdout`]);let d=c||Xo.compare(i,u)<0,f={targetPackage:o,runningPackage:r,currentVersion:i,latestVersion:u,upgradeAvailable:d,upgradeInstalled:!1};if(t===`check`)return S(`${r}@${i} → ${o}@${u} (${d?`available`:`up to date`})`,f);if(!d)return S(`${r}@${i} already matches ${o}@${u}`,f);if(n.workingTreeRoot!==null)return C(`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 p=rs(n),m=p===null?[]:[`--prefix`,p.installPrefix],h=p===null?null:N(p.installPrefix,`lib`,`node_modules`,...o.split(`/`)),g=c?ts(p,o,u):[];if(c){let e=es([`uninstall`,`-g`,...m,a],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return C(`Cannot remove the retired ${a}: ${e.summary}`,[...e.warnings,...g])}let _;try{_=is(n,p)}catch(e){return C(`Cannot prepare MCP-owned CLI bins: ${ss(e)}`,[`npm install was not run`])}let v=es([`install`,`-g`,...m,`${o}@${u}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!v.ok){let e=as(_,h);return e===null?{...v,warnings:[...v.warnings,...g],data:null}:C(`${v.summary}; MCP-owned CLI bin restoration failed`,[...v.warnings,e])}let y=p===null?void 0:ns(p.installPrefix,o,u);if(y?.ok===!1){let e=as(_,h);return e===null?{...y,warnings:[...y.warnings,...g],data:null}:C(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let b=os(_);if(b!==null)return C(`${o} upgraded but MCP CLI bin backup cleanup failed`,[b]);let x=cs();return S(`${o} upgraded to ${u}`,{...f,upgradeInstalled:!0,installPrefix:p?.installPrefix,verifiedVersion:y?.data??void 0,completionRefreshed:x.refreshed,completionRefreshMessage:x.message})}function es(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=st(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?C(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):C(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
31
- `).slice(-3).join(` | `);return C(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return S(`npm ok`,a.stdout??``)}function ts(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${a}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function ns(e,t,n){let r;try{let n=s(N(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=N(e,`bin`,n.bin[0])}catch(e){return C(`updated ${t} verification failed: ${ss(e)}`,[`invalid_package_metadata`])}let i=st(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return C(`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(`
32
- `).slice(-3).join(` | `);return C(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return S(`active CLI version verified`,a)}function rs(e){let t=`${ut}lib${ut}node_modules${ut}${e.name.replace(`/`,ut)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function is(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}${ut}`))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=N(t.installPrefix,`bin`,n),i=pt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=vt(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:_t(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=ht(N(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:N(r,ct(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(yt(e.binPath,e.backupPath),a.push(e),_t(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=as({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 as(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=pt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=N(M(r.binPath),_t(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${ut}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);Ct(r.binPath)}yt(r.backupPath,r.binPath)}catch(e){n.push(ss(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){n.push(ss(e))}return n.length===0?null:n.join(`; `)}function os(e){let t=[];for(let n of e.backup)try{Ct(n.backupPath)}catch(e){t.push(ss(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){t.push(ss(e))}return t.length===0?null:t.join(`; `)}function ss(e){return e instanceof Error?e.message:String(e)}function cs(){try{return Po()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var ls=[{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 catalog was generated from the operation set the API serves`}],us=`operationFingerprint`;function ds(e,t=s().bin[0]){A(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: [...] }`:",...ls.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(`
33
- `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),R({mode:k(e)},await fs(t))})}async function fs(e){let t=ms(),n=hs(e),[r,i]=await Promise.all([gs(e),_s(t,e)]),a=[n.check,r,i.check,await ys(e),Ts(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:ps(a,`pass`),fail:ps(a,`fail`),skip:ps(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(`
34
- `);return c.ok?S(l,c,{counts:o}):{...C(l,s,{counts:o}),data:c}}function ps(e,t){return e.filter(e=>e.status===t).length}function J(e,t,n){return{name:e,status:t,message:n}}function ms(){return j.find(e=>e.intent===`status`&&e.resource===`status`)}function hs(e){let t=s(),n=$o(t,`check`);if(!n.ok||n.data===null)return{check:J(`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?J(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):J(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function gs(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 J(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return J(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${O(t)}.`)}}async function _s(e,t){if(e===void 0)return{check:J(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=x().host}catch(e){return{check:J(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${O(e)}.`),servedFingerprint:null}}let r=await w({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>C(O(e)));return r.ok?{check:J(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:vs(r.data)}:{check:J(`api-host`,`fail`,`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 vs(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[us];return typeof n==`string`&&n.length>0?n:null}async function ys(e){let t=De(),[n,r]=await Promise.all([bs(),xs()]);if(r.state===`unavailable`&&r.cause===`environment`)return J(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?J(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&we(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?J(`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`?J(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${h.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?J(`auth`,`pass`,`Credential source available: ${Ss(t,n,r)}.`):r.state===`unavailable`?J(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${h.authToken} through the environment — ${r.summary}.`):J(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${h.authToken} in the environment.`)}async function bs(){let e;try{e=Me(x().host)}catch(e){return{state:`unavailable`,summary:O(e)}}return await Ne(e)}async function xs(){let e;try{e=ze(x().host)}catch(e){return{state:`unavailable`,summary:O(e),cause:`environment`}}try{return await Re(e)}catch(e){return{state:`unavailable`,summary:O(e),cause:`storage`}}}function Ss(e,t,n){return[Oa(e),`oauth=${ws(t)}`,`api-key=${Cs(n)}`].join(` `)}function Cs(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=ze(x().host);return`${e.stored.activation}${pa(t,e)}`}function ws(e){switch(e.state){case`found`:return we(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 Ts(e,t,n,r){let i=j.length;if(e===void 0)return J(`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 J(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Je}.`);if(t===`f67164de1825aa38`)return J(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Je}).`);let a=`This catalog describes a different operation set than the API serves (${Je} vs ${t})`;return n===!0?J(`catalog`,`fail`,`${a}: run \`${r} update\`.`):J(`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 Es=V(H,`oauth`),Ds=[V(H,`start`),V(H,`poll`),V(H,`acknowledge`)],Os=V(H,`revoke`);function ks(e,t=s().bin[0]){let n=js(e);ds(n,t),po(e,t);let r=[`${Es.description} Default method: OAuth in your browser.`,`With --key: ${Ds.map(({description:e})=>e).join(` `)}`].join(`
35
- `),a=async function(e){Ms(this);let t=k(e);if(e.providers===!0){R({mode:t},await Fs());return}R({mode:t},e.key===!0?await Ji({noBrowser:!e.browser,clientLabel:e.clientLabel}):await at({noBrowser:!e.browser}))};A(As(n,[Es,...Ds],r)).action(a),A(As(n,[Os],Os.description)).action(async function(e){Ms(this),R({mode:k(e)},await Ii({forgetLocal:e.forgetLocal===!0}))}),A(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 Clerk rejects is retired`,` - api-key: the saved Clerk API key, re-verified with Clerk and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (Clerk instance and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (Better Stack uptime SLA)`,``,`Saved credentials are sent only to the selected API host and Clerk, 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(`
36
- `)).addOption(new i(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){Ms(this),R({mode:k(e)},await Ns(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: ${h.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved Clerk API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
29
+ `)?t:`${t}\n`}async function Yo(e){let t=It({input:F.stdin,output:F.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Xo=new Intl.Collator(void 0,{numeric:!0}),Zo=2e4;function Qo(e,t=s()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from the public npm registry; no credential required.`;k(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`,`(use \`make\` to rebuild that). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
30
+ `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>R({mode:O(e)},$o()))}function $o(e,t=`apply`){let n=e;try{n??=s(process.argv[1])}catch(e){return C(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,o=n.registry===``?oe:a,c=n.registry===``&&r===`@aventurevc/aventure-cli`,l=es([`view`,o,`version`,`--silent`,`--global`],n,{timeout:Zo});if(!l.ok)return{...l,data:null};let u=(l.data??``).trim();if(u===``)return C(`npm view ${o} returned empty version`,[`empty_stdout`]);let d=c||Xo.compare(i,u)<0,f={targetPackage:o,runningPackage:r,currentVersion:i,latestVersion:u,upgradeAvailable:d,upgradeInstalled:!1};if(t===`check`)return S(`${r}@${i} → ${o}@${u} (${d?`available`:`up to date`})`,f);if(!d)return S(`${r}@${i} already matches ${o}@${u}`,f);if(n.workingTreeRoot!==null)return C(`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 p=rs(n),m=p===null?[]:[`--prefix`,p.installPrefix],h=p===null?null:N(p.installPrefix,`lib`,`node_modules`,...o.split(`/`)),g=c?ts(p,o,u):[];if(c){let e=es([`uninstall`,`-g`,...m,a],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return C(`Cannot remove the retired ${a}: ${e.summary}`,[...e.warnings,...g])}let _;try{_=is(n,p)}catch(e){return C(`Cannot prepare MCP-owned CLI bins: ${ss(e)}`,[`npm install was not run`])}let v=es([`install`,`-g`,...m,`${o}@${u}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!v.ok){let e=as(_,h);return e===null?{...v,warnings:[...v.warnings,...g],data:null}:C(`${v.summary}; MCP-owned CLI bin restoration failed`,[...v.warnings,e])}let y=p===null?void 0:ns(p.installPrefix,o,u);if(y?.ok===!1){let e=as(_,h);return e===null?{...y,warnings:[...y.warnings,...g],data:null}:C(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let b=os(_);if(b!==null)return C(`${o} upgraded but MCP CLI bin backup cleanup failed`,[b]);let x=cs();return S(`${o} upgraded to ${u}`,{...f,upgradeInstalled:!0,installPrefix:p?.installPrefix,verifiedVersion:y?.data??void 0,completionRefreshed:x.refreshed,completionRefreshMessage:x.message})}function es(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=ct(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?C(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):C(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
31
+ `).slice(-3).join(` | `);return C(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return S(`npm ok`,a.stdout??``)}function ts(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${a}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function ns(e,t,n){let r;try{let n=s(N(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=N(e,`bin`,n.bin[0])}catch(e){return C(`updated ${t} verification failed: ${ss(e)}`,[`invalid_package_metadata`])}let i=ct(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return C(`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(`
32
+ `).slice(-3).join(` | `);return C(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return S(`active CLI version verified`,a)}function rs(e){let t=`${ut}lib${ut}node_modules${ut}${e.name.replace(`/`,ut)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function is(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}${ut}`))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=N(t.installPrefix,`bin`,n),i=pt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=vt(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:_t(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=ht(N(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:N(r,lt(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(yt(e.binPath,e.backupPath),a.push(e),_t(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=as({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 as(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=pt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=N(j(r.binPath),_t(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${ut}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);Ct(r.binPath)}yt(r.backupPath,r.binPath)}catch(e){n.push(ss(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){n.push(ss(e))}return n.length===0?null:n.join(`; `)}function os(e){let t=[];for(let n of e.backup)try{Ct(n.backupPath)}catch(e){t.push(ss(e))}if(e.backupDirectory!==null)try{xt(e.backupDirectory)}catch(e){t.push(ss(e))}return t.length===0?null:t.join(`; `)}function ss(e){return e instanceof Error?e.message:String(e)}function cs(){try{return Po()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var ls=[{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 catalog was generated from the operation set the API serves`}],us=`operationFingerprint`;function ds(e,t=s().bin[0]){k(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: [...] }`:",...ls.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(`
33
+ `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),R({mode:O(e)},await fs(t))})}async function fs(e){let t=ms(),n=hs(e),[r,i]=await Promise.all([gs(e),_s(t,e)]),a=[n.check,r,i.check,await ys(e),Ts(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:ps(a,`pass`),fail:ps(a,`fail`),skip:ps(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(`
34
+ `);return c.ok?S(l,c,{counts:o}):{...C(l,s,{counts:o}),data:c}}function ps(e,t){return e.filter(e=>e.status===t).length}function J(e,t,n){return{name:e,status:t,message:n}}function ms(){return A.find(e=>e.intent===`status`&&e.resource===`status`)}function hs(e){let t=s(),n=$o(t,`check`);if(!n.ok||n.data===null)return{check:J(`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?J(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):J(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function gs(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 J(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return J(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${D(t)}.`)}}async function _s(e,t){if(e===void 0)return{check:J(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=x().host}catch(e){return{check:J(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${D(e)}.`),servedFingerprint:null}}let r=await ce({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>C(D(e)));return r.ok?{check:J(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:vs(r.data)}:{check:J(`api-host`,`fail`,`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 vs(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[us];return typeof n==`string`&&n.length>0?n:null}async function ys(e){let t=Oe(),[n,r]=await Promise.all([bs(),xs()]);if(r.state===`unavailable`&&r.cause===`environment`)return J(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?J(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Te(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?J(`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`?J(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${h.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?J(`auth`,`pass`,`Credential source available: ${Ss(t,n,r)}.`):r.state===`unavailable`?J(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${h.authToken} through the environment — ${r.summary}.`):J(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${h.authToken} in the environment.`)}async function bs(){let e;try{e=Ne(x().host)}catch(e){return{state:`unavailable`,summary:D(e)}}return await Pe(e)}async function xs(){let e;try{e=Be(x().host)}catch(e){return{state:`unavailable`,summary:D(e),cause:`environment`}}try{return await ze(e)}catch(e){return{state:`unavailable`,summary:D(e),cause:`storage`}}}function Ss(e,t,n){return[Oa(e),`oauth=${ws(t)}`,`api-key=${Cs(n)}`].join(` `)}function Cs(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Be(x().host);return`${e.stored.activation}${pa(t,e)}`}function ws(e){switch(e.state){case`found`:return Te(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 Ts(e,t,n,r){let i=A.length;if(e===void 0)return J(`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 J(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Ye}.`);if(t===`67e3e8f0f259c2c0`)return J(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Ye}).`);let a=`This catalog describes a different operation set than the API serves (${Ye} vs ${t})`;return n===!0?J(`catalog`,`fail`,`${a}: run \`${r} update\`.`):J(`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 Es=V(H,`oauth`),Ds=[V(H,`start`),V(H,`poll`),V(H,`acknowledge`)],Os=V(H,`revoke`);function ks(e,t=s().bin[0]){let n=js(e);ds(n,t),po(e,t);let r=[`${Es.description} Default method: OAuth in your browser.`,`With --key: ${Ds.map(({description:e})=>e).join(` `)}`].join(`
35
+ `),a=async function(e){Ms(this);let t=O(e);if(e.providers===!0){R({mode:t},await Fs());return}R({mode:t},e.key===!0?await Ji({noBrowser:!e.browser,clientLabel:e.clientLabel}):await ot({noBrowser:!e.browser}))};k(As(n,[Es,...Ds],r)).action(a),k(As(n,[Os],Os.description)).action(async function(e){Ms(this),R({mode:O(e)},await Ii({forgetLocal:e.forgetLocal===!0}))}),k(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 Clerk rejects is retired`,` - api-key: the saved Clerk API key, re-verified with Clerk and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (Clerk instance and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (Better Stack uptime SLA)`,``,`Saved credentials are sent only to the selected API host and Clerk, 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(`
36
+ `)).addOption(new i(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){Ms(this),R({mode:O(e)},await Ns(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: ${h.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved Clerk API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
37
37
  `)).action(async function(){Ms(this);let e=await aa(t),n=process.env[h.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}R({mode:`text`},e.failure===null?Vs(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):C(`auth token: ${e.failure}`))})}function As(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 js(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${Es.command}\`: ${Es.summary}; \`--key\` ${Ds[0].summary.toLowerCase()}.`,`\`${Os.command}\`: ${Os.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(`
38
- `))}function Ms(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Ns(e,t){let n;try{n=Me(x().host)}catch(e){return C(`auth status: invalid API host — ${O(e)}`)}let r=De(),i=aa(e),[a,o,c]=await Promise.all([Bs(`/v1/status`,`GET /v1/status`),Bs(`/info`,`GET /info`),Is()]),l=await i,[u,d]=await Promise.all([Ne(n),Ps(n)]),f=t===void 0?null:await oa(t,u,d.inspection,l),p=s().version,m=ua(n,d.inspection,d.verification),g=ba({cliName:e,cliVersion:p,apiVersion:o.ok?Rs(o.data):null,oauth:u,apiKey:m,providers:c,resolved:r,refresh:l,systemOk:a.ok,live:f}),_={cli:{version:p},api:o.ok?o.data??null:null,auth:{[h.authToken]:r},selected:l.materialized,oauth:da(n,u),apiKey:m,providers:c,live:f,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return l.failure===null?f!==null&&f.error!==null?{...C(`auth status: ${f.scope} permission probe failed — ${f.error}`,[f.error]),data:_}:f!==null||r.present||u.state===`found`||d.inspection.state===`found`?S(g,_):Vs(`auth status: no credentials resolved | ${g}`,_,e,{oauth:u.state===`missing`,apiKey:d.inspection.state===`missing`}):{...C(`auth status: ${l.failure} | ${g}`,[l.failure]),data:_}}async function Ps(e){let t=await Ls(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Ni(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Fs(){let e=await Is();return e.state===`found`?S(`Sign-in providers for the selected API host`,e.catalog):C(`auth login --providers: ${e.summary}`)}async function Is(){try{return{state:`found`,catalog:await it()}}catch(e){return{state:`unavailable`,summary:O(e)}}}async function Ls(e){try{return await Re(e)}catch(e){return{state:`invalid`,summary:O(e)}}}function Rs(e){if(!zs(e))return null;let t=ci.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 zs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Bs(e,t){return await w({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>C(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Vs(e,t,n,r){return{...C(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${h.authToken} to a Clerk API key in the environment.`]),data:t}}var Hs=pe({VALIDATION_FAILED:`https://api.aventure.vc/errors/validation-failed`,MISSING_PARAMETER:`https://api.aventure.vc/errors/missing-parameter`,INVALID_PARAMETER_TYPE:`https://api.aventure.vc/errors/invalid-parameter-type`,UNKNOWN_PARAMETER:`https://api.aventure.vc/errors/unknown-parameter`,INVALID_ARGUMENT:`https://api.aventure.vc/errors/invalid-argument`,INVALID_REQUEST:`https://api.aventure.vc/errors/invalid-request`,INVALID_TOKEN:`https://api.aventure.vc/errors/invalid-token`,TOKEN_EXPIRED:`https://api.aventure.vc/errors/token-expired`,INVALID_AUTHENTICATION:`https://api.aventure.vc/errors/invalid-authentication`,CLIENT_CLOSED_REQUEST:`https://api.aventure.vc/errors/client-closed-request`,INVALID_JSON:`https://api.aventure.vc/errors/invalid-json`,METHOD_NOT_ALLOWED:`https://api.aventure.vc/errors/method-not-allowed`,NOT_ACCEPTABLE:`https://api.aventure.vc/errors/not-acceptable`,UNSUPPORTED_MEDIA_TYPE:`https://api.aventure.vc/errors/unsupported-media-type`,INTERNAL_ERROR:`https://api.aventure.vc/errors/internal-error`,UNEXPECTED_ERROR:`https://api.aventure.vc/errors/unexpected-error`,NOT_IMPLEMENTED:`https://api.aventure.vc/errors/not-implemented`,AUTHENTICATION_REQUIRED:`https://api.aventure.vc/errors/authentication-required`,AUTH_DOCS_REQUIRED:`https://api.aventure.vc/errors/auth.docs-required`,AUTH_ADMIN_KEY_NOT_CONFIGURED:`https://api.aventure.vc/errors/auth.admin-key-not-configured`,AUTH_EMPTY_ADMIN_KEY:`https://api.aventure.vc/errors/auth.empty-admin-key`,AUTH_EMPTY_ADMIN_BEARER:`https://api.aventure.vc/errors/auth.empty-admin-bearer`,AUTH_INVALID_ADMIN_KEY:`https://api.aventure.vc/errors/auth.invalid-admin-key`,AUTH_MISSING_ADMIN_KEY:`https://api.aventure.vc/errors/auth.missing-admin-key`,AUTH_METRICS_UNAUTHORIZED:`https://api.aventure.vc/errors/auth.metrics-unauthorized`,ACCESS_DENIED:`https://api.aventure.vc/errors/access-denied`,NOT_FOUND:`https://api.aventure.vc/errors/not-found`,GONE:`https://api.aventure.vc/errors/gone`,RATE_LIMITED:`https://api.aventure.vc/errors/rate-limited`,PRECONDITION_FAILED:`https://api.aventure.vc/errors/precondition-failed`,PRECONDITION_REQUIRED:`https://api.aventure.vc/errors/precondition-required`,BILLING_ALLOWANCE_EXHAUSTED:`https://api.aventure.vc/errors/billing-allowance-exhausted`,BILLING_ADDITIONAL_USAGE_CAP_REACHED:`https://api.aventure.vc/errors/billing-additional-usage-cap-reached`,SUBSCRIPTION_REQUIRED:`https://api.aventure.vc/errors/subscription-required`,SERVICE_UNAVAILABLE:`https://api.aventure.vc/errors/service-unavailable`,MALFORMED_FORM_BODY:`https://api.aventure.vc/errors/malformed-form-body`,STATE_CONFLICT:`https://api.aventure.vc/errors/state-conflict`,SLUG_HELD_BY_RECORD:`https://api.aventure.vc/errors/slug-held-by-record`,SLUG_HELD_BY_REDIRECT:`https://api.aventure.vc/errors/slug-held-by-redirect`,SLUG_AMBIGUOUS:`https://api.aventure.vc/errors/slug-ambiguous`,DUPLICATE:`https://api.aventure.vc/errors/duplicate`,DUPLICATE_KEY:`https://api.aventure.vc/errors/duplicate-key`,INTEGRITY_VIOLATION:`https://api.aventure.vc/errors/integrity-violation`,CIRCUIT_BREAKER_OPEN:`https://api.aventure.vc/errors/circuit-breaker-open`,BULKHEAD_FULL:`https://api.aventure.vc/errors/bulkhead-full`,WRITE_LANE_BUSY:`https://api.aventure.vc/errors/write-lane-busy`,DATABASE_UNAVAILABLE:`https://api.aventure.vc/errors/database-unavailable`,DATABASE_ERROR:`https://api.aventure.vc/errors/database-error`,FILE_TOO_LARGE:`https://api.aventure.vc/errors/file-too-large`,MISSING_FILE_PART:`https://api.aventure.vc/errors/missing-file-part`,INVALID_MULTIPART_BOUNDARY:`https://api.aventure.vc/errors/invalid-multipart-boundary`,MULTIPART_PARSE_ERROR:`https://api.aventure.vc/errors/multipart-parse-error`,NON_ENGLISH_ARTICLE:`https://api.aventure.vc/errors/non-english-article`,INVALID_IMAGE:`https://api.aventure.vc/errors/invalid-image`,UPSTREAM_EDGE_CHALLENGED:`https://api.aventure.vc/errors/upstream-edge-challenged`,ACCELERATOR_DETAIL_RESTATES_TARGET:`https://api.aventure.vc/errors/accelerator-detail-restates-target`});function Us(e,t,n=s().bin[0]){let r=wr(t),i=e.find(e=>e.cliPath.join(` `)===r||e.operationId===r);return i===void 0?C(`No generated operation matches "${t}"`,[`Resolve the exact command with \`${n} command-catalog search "<query>"\`.`]):S(`Resolved ${i.operationId}`,i)}function Ws(e){return e.parameters.some(e=>e.location===`path`)?C(`${e.operationId} has path parameters and cannot be batch-driven`,[e.path]):S(`no path parameters`,null)}function Gs(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)return C(`--query expects key=value, got "${n}"`);t[n.slice(0,e)]=n.slice(e+1)}return S(`query parsed`,t)}function Ks(e,t,n,r){let i=Number(t);return!Number.isInteger(i)||i<n||i>r?C(`${e} must be an integer between ${n} and ${r}, got "${t}"`):S(`${e} parsed`,i)}function qs(e){let t=v.safeParse(e);return t.success?t.data:void 0}function Js(e,t){let n=qs(e);for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function Ys(e){let t=qs(e);return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Xs(e){return typeof e==`object`&&e&&`response`in e?qs(e.response):qs(e)}function Zs(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Qs(e){if(!P(e))return C(`--input file not found: ${e}`);let t=gt(e,`utf8`),n=[],r=t.split(`
39
- `);for(let[e,t]of r.entries()){if(t.trim()===``)continue;let r=v.safeParse(nc(t));if(!r.success)return C(`--input line ${e+1} is not valid JSON`,[t.slice(0,120)]);n.push(r.data)}return n.length===0?C(`--input has no NDJSON rows: ${e}`):S(`input parsed`,{row:n,digest:rc(t)})}function $s(e,t,n){let r={...t,outputBytes:0,completedChunk:[]};if(e===void 0||!P(e))return S(`no checkpoint`,r);let i=nc(gt(e,`utf8`));if(i===void 0)return C(`--checkpoint file is not valid JSON: ${e}`);if(Js(i,`requestDigest`)===void 0)return C(`--checkpoint ${e} predates request identity checks; no chunks were sent`,[`Preserve the checkpoint and response file; reconcile completed chunks before restarting a write.`]);let a=Js(i,`completedChunk`),o=Js(i,`outputBytes`);if(Object.entries(t).some(([e,t])=>Js(i,e)!==t))return C(`--checkpoint ${e} was written for a different batch request or output`,[`Use the original request and output file, or a new checkpoint for a new batch.`]);if(!Array.isArray(a))return C(`--checkpoint ${e} has an invalid completedChunk list`);let s=a.filter(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<n);return s.length!==a.length||new Set(s).size!==s.length?C(`--checkpoint ${e} has an invalid completedChunk list`):s.length>0&&!P(t.outputPath)?C(`--checkpoint ${e} requires its previous output file: ${t.outputPath}`):typeof o!=`number`||!Number.isSafeInteger(o)||o<0||s.length>0&&St(t.outputPath).size<o?C(`--checkpoint ${e} disagrees with its previous output file`):S(`checkpoint loaded`,{...t,outputBytes:o,completedChunk:s})}function ec(e,t,n){if(e===void 0)return;let r={...t,outputBytes:St(t.outputPath).size,completedChunk:[...n].toSorted((e,t)=>e-t)};wt(e,`${JSON.stringify(r)}\n`)}function tc(e,t){return[...t,e]}function nc(e){try{return JSON.parse(e)}catch{return}}function rc(e){return At(`sha256`).update(e).digest(`hex`)}var ic=new Set([Hs.enum.SUBSCRIPTION_REQUIRED,Hs.enum.BILLING_ALLOWANCE_EXHAUSTED]);function ac(e,t,n=s().bin[0]){let r=e.command(`batch`).summary(`Export reads and run bulk writes as NDJSON`).description(`batch export pages a cursor read into an NDJSON file; batch preview reports a chunk plan; batch run sends chunked NDJSON writes with bounded concurrency and checkpoint/resume. Resolve targets with command-catalog search|show first.`);oc(r,t,n),sc(r,t,`preview`,n),sc(r,t,`run`,n)}function oc(e,t,n){let r=e.command(`export`).summary(`Page a cursor read operation into an NDJSON row file`).description([`Repeatedly call one generated cursor-paginated read operation and append`,`every returned row to --out as NDJSON while stdout stays a compact summary.`,` ${n} batch export --command "<resource> <area> <operation>" \\`,` --from-file filter.json --query size=200 --out rows.ndjson`].join(`
40
- `)).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).option(`--from-file <path>`,`JSON request body sent on every page`).option(`--query <key=value>`,`Query parameter, repeatable`,tc,[]).requiredOption(`--out <path>`,`NDJSON output file; overwritten unless --append`).option(`--append`,`Append resumed pages to --out; requires --cursor`).option(`--cursor <cursor>`,`Starting cursor value`).option(`--cursor-param <name>`,`Cursor query parameter name`,`cursor`).option(`--rows-path <path>`,`Dot path to the row array in the response`,`row`).option(`--next-cursor-path <path>`,`Dot path to the next cursor in the response`,`nextCursor`).option(`--max-pages <count>`,`Safety cap on pages fetched`,`1000`);A(r),r.action(async function(){let e=this.optsWithGlobals();R({mode:k(e)},await cc(t,e,n))})}function sc(e,t,n,r){let a=e.command(n).summary(n===`run`?`Send NDJSON rows through a batched write operation`:`Preview one batched write operation without sending rows`).description(n===`run`?[`Chunk NDJSON rows into batched request bodies for one generated write`,`operation and send them with bounded concurrency. Every chunk response is`,`appended to --out as NDJSON; --checkpoint records completed chunks so an`,`interrupted run resumes without resending them.`,`Use batch preview to inspect the chunk plan before sending rows.`,`--execute is deprecated, accepted, and ignored; run executes by its verb.`].join(`
41
- `):`Build the same chunk plan as batch run without sending rows or writing --out.`).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).requiredOption(`--input <path>`,`NDJSON file; each line is one batch row`).requiredOption(`--array-field <name>`,`Body field receiving each chunk of rows`).option(`--base <path>`,`JSON file with fixed body fields merged into every chunk`).option(`--query <key=value>`,`Query parameter, repeatable`,tc,[]).requiredOption(`--out <path>`,`NDJSON file receiving one response line per chunk`).option(`--chunk-size <count>`,`Rows per request body`,`25`).option(`--concurrency <count>`,`Concurrent requests, 1-8`,`2`).option(`--checkpoint <path>`,`JSON checkpoint file for resume`).addOption(new i(`--no-halt-on-failure`,`keep sending remaining chunks after a failed chunk; a subscription or allowance refusal still stops the run`));n===`run`&&a.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),A(a),a.action(async function(){let e=this.optsWithGlobals();R({mode:k(e)},await lc(t,e,n,r))})}async function cc(e,n,r){let i=Us(e,n.command,r);if(!i.ok||i.data===null)return i;if(t(i.data.intent))return C(`${n.command} is a write operation; use \`batch run\``,[i.data.path]);let a=Ws(i.data);if(!a.ok)return a;let o=Gs(n.query??[]);if(!o.ok||o.data===null)return o;let s=Ks(`--max-pages`,n.maxPages,1,1e6);if(!s.ok||s.data===null)return s;let c=n.fromFile===void 0?void 0:await Sn(n.fromFile);if(c!==void 0&&!c.ok)return c;let l=c===void 0?void 0:Ys(c.data);if(c!==void 0&&l===null)return C(`--from-file must contain a JSON object`,[n.fromFile??``]);if(n.append&&n.cursor===void 0)return C(`--append requires --cursor from the previous export`);if(n.cursor!==void 0&&!n.append&&P(n.out))return C(`--cursor with an existing --out requires --append to preserve earlier rows`);if(n.append&&!P(n.out))return C(`--append requires the previous output file: ${n.out}`);wt(n.out,``,{flag:n.append?`a`:`w`});let u=n.cursor,d=0,f=0,p=!1;for(;d<s.data;){let e={...o.data,...u===void 0?{}:{[n.cursorParam]:u}},t=await w({method:i.data.method,path:i.data.path,searchParams:e,body:l??void 0,auth:i.data.auth,responseFormat:`json`});if(!t.ok)return C(`page ${d+1} failed: ${t.summary}`,[`rows already written to ${n.out}: ${f}`,...u===void 0?[]:[`resume with --cursor "${u}" --append`]]);let r=Xs(t.data),a=Js(r,n.rowsPath);if(!Array.isArray(a))return C(`response has no array at --rows-path "${n.rowsPath}"`,[`page ${d+1}`]);dt(n.out,a.map(e=>`${JSON.stringify(e)}\n`).join(``)),d+=1,f+=a.length;let s=Js(r,n.nextCursorPath);if(typeof s!=`string`||s===``||s===u){p=!0;break}u=s}return S(`${f} rows across ${d} pages written to ${n.out}${p?``:`; PARTIAL export — hit --max-pages ${s.data}, resume with --cursor "${u}" --append`}`,{outPath:n.out,exhausted:p,lastCursor:u},{counts:{pageCount:d,rowCount:f}})}async function lc(e,n,r,i){let a=Us(e,n.command,i);if(!a.ok||a.data===null)return a;if(!t(a.data.intent))return C(`${n.command} is not a write operation; use \`batch export\``,[a.data.path]);let o=Ws(a.data);if(!o.ok)return o;let s=Gs(n.query??[]);if(!s.ok||s.data===null)return s;let c=Ks(`--chunk-size`,n.chunkSize,1,1e4);if(!c.ok||c.data===null)return c;let l=Ks(`--concurrency`,n.concurrency,1,8);if(!l.ok||l.data===null)return l;let u=n.base===void 0?void 0:await Sn(n.base);if(u!==void 0&&!u.ok)return u;let d=Ys(u?.data??{});if(d===null)return C(`--base must contain a JSON object`,[n.base??``]);let f=Qs(n.input);if(!f.ok||f.data===null)return f;let p=Zs(f.data.row,c.data),m={inputDigest:f.data.digest,chunkSize:c.data,requestDigest:rc(JSON.stringify({host:x().host,method:a.data.method,path:a.data.path,auth:a.data.auth,searchParams:s.data,baseBody:d,arrayField:n.arrayField})),outputPath:N(n.out)},h=$s(n.checkpoint,m,p.length);if(!h.ok||h.data===null)return h;let g=new Set(h.data.completedChunk),_=[...p.keys()].filter(e=>!g.has(e));if(r===`preview`)return S(`PREVIEW — nothing sent. ${_.length} of ${p.length} chunks (${f.data.row.length} rows) would ${a.data.method} ${a.data.path}. Run ${i} batch run to send.`,{mode:`preview`,method:a.data.method,endpoint:a.data.path,arrayField:n.arrayField,outPath:n.out},{counts:{rowCount:f.data.row.length,chunkCount:p.length,pendingChunkCount:_.length,skippedChunkCount:g.size}});wt(n.out,``,{flag:g.size>0?`a`:`w`});let v=a.data,y=s.data,b=[],ee=!1,te,ne=0,re=async e=>{let t=p[e]??[],r={...d,[n.arrayField]:t},i=await w({method:v.method,path:v.path,searchParams:y,body:r,auth:v.auth,responseFormat:`json`}),a=i.ok?Xs(i.data):null;return dt(n.out,`${JSON.stringify({chunk:e,rowCount:t.length,ok:i.ok,summary:i.summary,problem:i.ok?null:i.problem??null,response:a??i.data??null})}\n`),i.ok?(g.add(e),ec(n.checkpoint,m,g),!0):(b.push(e),ic.has(i.problem?.type??``)&&(te=i.problem?.title),!1)};await Promise.all(Array.from({length:l.data},async()=>{for(;!ee;){let e=_[ne];if(ne+=1,e===void 0)return;!await re(e)&&(n.haltOnFailure||te!==void 0)&&(ee=!0)}}));let ie={rowCount:f.data.row.length,chunkCount:p.length,completedChunkCount:g.size,failedChunkCount:b.length,remainingChunkCount:p.length-g.size-b.length},ae={outPath:n.out,checkpointPath:n.checkpoint,failedChunk:b,halted:ee,...te===void 0?{}:{haltReason:te}};return b.length>0?C(`${b.length} chunk(s) failed${te===void 0?``:`; stopped: ${te}`}; responses in ${n.out}${n.checkpoint===void 0?``:`, resume via --checkpoint ${n.checkpoint}`}`,[JSON.stringify({...ae,...ie})]):S(`${g.size}/${p.length} chunks sent; responses in ${n.out}`,ae,{counts:ie})}function uc(e,t=j,n=s().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(()=>{F.stdout.write(fc(e,i,t))});jo(r,n),Mo(r,n)}function dc(){return s().bin}function fc(e,t,n=j,r=dc()){let i=xc(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...mc(e),...r.map(e=>`complete -c ${Y(e)} -e`),`${Pc(r)} -f`,...hc(e,r),...gc(e,i,r),``].join(`
38
+ `))}function Ms(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Ns(e,t){let n;try{n=Ne(x().host)}catch(e){return C(`auth status: invalid API host — ${D(e)}`)}let r=Oe(),i=aa(e),[a,o,c]=await Promise.all([Bs(`/v1/status`,`GET /v1/status`),Bs(`/info`,`GET /info`),Is()]),l=await i,[u,d]=await Promise.all([Pe(n),Ps(n)]),f=t===void 0?null:await oa(t,u,d.inspection,l),p=s().version,m=ua(n,d.inspection,d.verification),g=ba({cliName:e,cliVersion:p,apiVersion:o.ok?Rs(o.data):null,oauth:u,apiKey:m,providers:c,resolved:r,refresh:l,systemOk:a.ok,live:f}),_={cli:{version:p},api:o.ok?o.data??null:null,auth:{[h.authToken]:r},selected:l.materialized,oauth:da(n,u),apiKey:m,providers:c,live:f,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return l.failure===null?f!==null&&f.error!==null?{...C(`auth status: ${f.scope} permission probe failed — ${f.error}`,[f.error]),data:_}:f!==null||r.present||u.state===`found`||d.inspection.state===`found`?S(g,_):Vs(`auth status: no credentials resolved | ${g}`,_,e,{oauth:u.state===`missing`,apiKey:d.inspection.state===`missing`}):{...C(`auth status: ${l.failure} | ${g}`,[l.failure]),data:_}}async function Ps(e){let t=await Ls(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Ni(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Fs(){let e=await Is();return e.state===`found`?S(`Sign-in providers for the selected API host`,e.catalog):C(`auth login --providers: ${e.summary}`)}async function Is(){try{return{state:`found`,catalog:await at()}}catch(e){return{state:`unavailable`,summary:D(e)}}}async function Ls(e){try{return await ze(e)}catch(e){return{state:`invalid`,summary:D(e)}}}function Rs(e){if(!zs(e))return null;let t=ci.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 zs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Bs(e,t){return await ce({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>C(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Vs(e,t,n,r){return{...C(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${h.authToken} to a Clerk API key in the environment.`]),data:t}}var Hs=me({VALIDATION_FAILED:`https://api.aventure.vc/errors/validation-failed`,MISSING_PARAMETER:`https://api.aventure.vc/errors/missing-parameter`,INVALID_PARAMETER_TYPE:`https://api.aventure.vc/errors/invalid-parameter-type`,UNKNOWN_PARAMETER:`https://api.aventure.vc/errors/unknown-parameter`,INVALID_ARGUMENT:`https://api.aventure.vc/errors/invalid-argument`,INVALID_REQUEST:`https://api.aventure.vc/errors/invalid-request`,INVALID_TOKEN:`https://api.aventure.vc/errors/invalid-token`,TOKEN_EXPIRED:`https://api.aventure.vc/errors/token-expired`,INVALID_AUTHENTICATION:`https://api.aventure.vc/errors/invalid-authentication`,CLIENT_CLOSED_REQUEST:`https://api.aventure.vc/errors/client-closed-request`,INVALID_JSON:`https://api.aventure.vc/errors/invalid-json`,METHOD_NOT_ALLOWED:`https://api.aventure.vc/errors/method-not-allowed`,NOT_ACCEPTABLE:`https://api.aventure.vc/errors/not-acceptable`,UNSUPPORTED_MEDIA_TYPE:`https://api.aventure.vc/errors/unsupported-media-type`,INTERNAL_ERROR:`https://api.aventure.vc/errors/internal-error`,UNEXPECTED_ERROR:`https://api.aventure.vc/errors/unexpected-error`,NOT_IMPLEMENTED:`https://api.aventure.vc/errors/not-implemented`,AUTHENTICATION_REQUIRED:`https://api.aventure.vc/errors/authentication-required`,AUTH_DOCS_REQUIRED:`https://api.aventure.vc/errors/auth.docs-required`,AUTH_ADMIN_KEY_NOT_CONFIGURED:`https://api.aventure.vc/errors/auth.admin-key-not-configured`,AUTH_EMPTY_ADMIN_KEY:`https://api.aventure.vc/errors/auth.empty-admin-key`,AUTH_EMPTY_ADMIN_BEARER:`https://api.aventure.vc/errors/auth.empty-admin-bearer`,AUTH_INVALID_ADMIN_KEY:`https://api.aventure.vc/errors/auth.invalid-admin-key`,AUTH_MISSING_ADMIN_KEY:`https://api.aventure.vc/errors/auth.missing-admin-key`,AUTH_METRICS_UNAUTHORIZED:`https://api.aventure.vc/errors/auth.metrics-unauthorized`,ACCESS_DENIED:`https://api.aventure.vc/errors/access-denied`,NOT_FOUND:`https://api.aventure.vc/errors/not-found`,GONE:`https://api.aventure.vc/errors/gone`,RATE_LIMITED:`https://api.aventure.vc/errors/rate-limited`,PRECONDITION_FAILED:`https://api.aventure.vc/errors/precondition-failed`,PRECONDITION_REQUIRED:`https://api.aventure.vc/errors/precondition-required`,BILLING_ALLOWANCE_EXHAUSTED:`https://api.aventure.vc/errors/billing-allowance-exhausted`,BILLING_ADDITIONAL_USAGE_CAP_REACHED:`https://api.aventure.vc/errors/billing-additional-usage-cap-reached`,SUBSCRIPTION_REQUIRED:`https://api.aventure.vc/errors/subscription-required`,SERVICE_UNAVAILABLE:`https://api.aventure.vc/errors/service-unavailable`,MALFORMED_FORM_BODY:`https://api.aventure.vc/errors/malformed-form-body`,STATE_CONFLICT:`https://api.aventure.vc/errors/state-conflict`,SLUG_HELD_BY_RECORD:`https://api.aventure.vc/errors/slug-held-by-record`,SLUG_HELD_BY_REDIRECT:`https://api.aventure.vc/errors/slug-held-by-redirect`,SLUG_AMBIGUOUS:`https://api.aventure.vc/errors/slug-ambiguous`,DUPLICATE:`https://api.aventure.vc/errors/duplicate`,DUPLICATE_KEY:`https://api.aventure.vc/errors/duplicate-key`,INTEGRITY_VIOLATION:`https://api.aventure.vc/errors/integrity-violation`,CIRCUIT_BREAKER_OPEN:`https://api.aventure.vc/errors/circuit-breaker-open`,BULKHEAD_FULL:`https://api.aventure.vc/errors/bulkhead-full`,WRITE_LANE_BUSY:`https://api.aventure.vc/errors/write-lane-busy`,DATABASE_UNAVAILABLE:`https://api.aventure.vc/errors/database-unavailable`,DATABASE_ERROR:`https://api.aventure.vc/errors/database-error`,FILE_TOO_LARGE:`https://api.aventure.vc/errors/file-too-large`,MISSING_FILE_PART:`https://api.aventure.vc/errors/missing-file-part`,INVALID_MULTIPART_BOUNDARY:`https://api.aventure.vc/errors/invalid-multipart-boundary`,MULTIPART_PARSE_ERROR:`https://api.aventure.vc/errors/multipart-parse-error`,NON_ENGLISH_ARTICLE:`https://api.aventure.vc/errors/non-english-article`,INVALID_IMAGE:`https://api.aventure.vc/errors/invalid-image`,UPSTREAM_EDGE_CHALLENGED:`https://api.aventure.vc/errors/upstream-edge-challenged`,ACCELERATOR_DETAIL_RESTATES_TARGET:`https://api.aventure.vc/errors/accelerator-detail-restates-target`});function Us(e,t,n=s().bin[0]){let r=wr(t),i=e.find(e=>e.cliPath.join(` `)===r||e.operationId===r);return i===void 0?C(`No generated operation matches "${t}"`,[`Resolve the exact command with \`${n} command-catalog search "<query>"\`.`]):S(`Resolved ${i.operationId}`,i)}function Ws(e){return e.parameters.some(e=>e.location===`path`)?C(`${e.operationId} has path parameters and cannot be batch-driven`,[e.path]):S(`no path parameters`,null)}function Gs(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)return C(`--query expects key=value, got "${n}"`);t[n.slice(0,e)]=n.slice(e+1)}return S(`query parsed`,t)}function Ks(e,t,n,r){let i=Number(t);return!Number.isInteger(i)||i<n||i>r?C(`${e} must be an integer between ${n} and ${r}, got "${t}"`):S(`${e} parsed`,i)}function qs(e){let t=v.safeParse(e);return t.success?t.data:void 0}function Js(e,t){let n=qs(e);for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function Ys(e){let t=qs(e);return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Xs(e){return typeof e==`object`&&e&&`response`in e?qs(e.response):qs(e)}function Zs(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Qs(e){if(!P(e))return C(`--input file not found: ${e}`);let t=gt(e,`utf8`),n=[],r=t.split(`
39
+ `);for(let[e,t]of r.entries()){if(t.trim()===``)continue;let r=v.safeParse(nc(t));if(!r.success)return C(`--input line ${e+1} is not valid JSON`,[t.slice(0,120)]);n.push(r.data)}return n.length===0?C(`--input has no NDJSON rows: ${e}`):S(`input parsed`,{row:n,digest:rc(t)})}function $s(e,t,n){let r={...t,outputBytes:0,completedChunk:[]};if(e===void 0||!P(e))return S(`no checkpoint`,r);let i=nc(gt(e,`utf8`));if(i===void 0)return C(`--checkpoint file is not valid JSON: ${e}`);if(Js(i,`requestDigest`)===void 0)return C(`--checkpoint ${e} predates request identity checks; no chunks were sent`,[`Preserve the checkpoint and response file; reconcile completed chunks before restarting a write.`]);let a=Js(i,`completedChunk`),o=Js(i,`outputBytes`);if(Object.entries(t).some(([e,t])=>Js(i,e)!==t))return C(`--checkpoint ${e} was written for a different batch request or output`,[`Use the original request and output file, or a new checkpoint for a new batch.`]);if(!Array.isArray(a))return C(`--checkpoint ${e} has an invalid completedChunk list`);let s=a.filter(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<n);return s.length!==a.length||new Set(s).size!==s.length?C(`--checkpoint ${e} has an invalid completedChunk list`):s.length>0&&!P(t.outputPath)?C(`--checkpoint ${e} requires its previous output file: ${t.outputPath}`):typeof o!=`number`||!Number.isSafeInteger(o)||o<0||s.length>0&&St(t.outputPath).size<o?C(`--checkpoint ${e} disagrees with its previous output file`):S(`checkpoint loaded`,{...t,outputBytes:o,completedChunk:s})}function ec(e,t,n){if(e===void 0)return;let r={...t,outputBytes:St(t.outputPath).size,completedChunk:[...n].toSorted((e,t)=>e-t)};wt(e,`${JSON.stringify(r)}\n`)}function tc(e,t){return[...t,e]}function nc(e){try{return JSON.parse(e)}catch{return}}function rc(e){return At(`sha256`).update(e).digest(`hex`)}var ic=new Set([Hs.enum.SUBSCRIPTION_REQUIRED,Hs.enum.BILLING_ALLOWANCE_EXHAUSTED]);function ac(e,t,n=s().bin[0]){let r=e.command(`batch`).summary(`Export reads and run bulk writes as NDJSON`).description(`batch export pages a cursor read into an NDJSON file; batch preview reports a chunk plan; batch run sends chunked NDJSON writes with bounded concurrency and checkpoint/resume. Resolve targets with command-catalog search|show first.`);oc(r,t,n),sc(r,t,`preview`,n),sc(r,t,`run`,n)}function oc(e,t,n){let r=e.command(`export`).summary(`Page a cursor read operation into an NDJSON row file`).description([`Repeatedly call one generated cursor-paginated read operation and write`,`every returned row to --out as NDJSON while stdout stays a compact summary.`,` ${n} batch export --command "<resource> <area> <operation>" \\`,` --from-file filter.json --query size=200 --out rows.ndjson`].join(`
40
+ `)).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).option(`--from-file <path>`,`JSON request body sent on every page`).option(`--query <key=value>`,`Query parameter, repeatable`,tc,[]).requiredOption(`--out <path>`,`NDJSON output file; overwritten unless --append`).option(`--append`,`Append resumed pages to --out; requires --cursor`).option(`--cursor <cursor>`,`Starting cursor value`).option(`--cursor-param <name>`,`Cursor query parameter name`,`cursor`).option(`--rows-path <path>`,`Dot path to the row array in the response`,`row`).option(`--next-cursor-path <path>`,`Dot path to the next cursor in the response`,`nextCursor`).option(`--max-pages <count>`,`Safety cap on pages fetched`,`1000`);k(r),r.action(async function(){let e=this.optsWithGlobals();R({mode:O(e)},await cc(t,e,n))})}function sc(e,t,n,r){let a=e.command(n).summary(n===`run`?`Send NDJSON rows through a batched write operation`:`Preview one batched write operation without sending rows`).description(n===`run`?[`Chunk NDJSON rows into batched request bodies for one generated write`,`operation and send them with bounded concurrency. Every chunk response is`,`appended to --out as NDJSON; --checkpoint records completed chunks so an`,`interrupted run resumes without resending them.`,`Use batch preview to inspect the chunk plan before sending rows.`,`--execute is deprecated, accepted, and ignored; run executes by its verb.`].join(`
41
+ `):`Build the same chunk plan as batch run without sending rows or writing --out.`).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).requiredOption(`--input <path>`,`NDJSON file; each line is one batch row`).requiredOption(`--array-field <name>`,`Body field receiving each chunk of rows`).option(`--base <path>`,`JSON file with fixed body fields merged into every chunk`).option(`--query <key=value>`,`Query parameter, repeatable`,tc,[]).requiredOption(`--out <path>`,`NDJSON file receiving one response line per chunk`).option(`--chunk-size <count>`,`Rows per request body`,`25`).option(`--concurrency <count>`,`Concurrent requests, 1-8`,`2`).option(`--checkpoint <path>`,`JSON checkpoint file for resume; refused unless --input, the request, --chunk-size, and --out all match the run that wrote it`).addOption(new i(`--no-halt-on-failure`,`keep sending remaining chunks after a failed chunk; a subscription or allowance refusal still stops the run`));n===`run`&&a.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),k(a),a.action(async function(){let e=this.optsWithGlobals();R({mode:O(e)},await lc(t,e,n,r))})}async function cc(e,n,r){let i=Us(e,n.command,r);if(!i.ok||i.data===null)return i;if(t(i.data.intent))return C(`${n.command} is a write operation; use \`batch run\``,[i.data.path]);let a=Ws(i.data);if(!a.ok)return a;let o=Gs(n.query??[]);if(!o.ok||o.data===null)return o;let s=Ks(`--max-pages`,n.maxPages,1,1e6);if(!s.ok||s.data===null)return s;let c=n.fromFile===void 0?void 0:await Sn(n.fromFile);if(c!==void 0&&!c.ok)return c;let l=c===void 0?void 0:Ys(c.data);if(c!==void 0&&l===null)return C(`--from-file must contain a JSON object`,[n.fromFile??``]);if(n.append&&n.cursor===void 0)return C(`--append requires --cursor from the previous export`);if(n.cursor!==void 0&&!n.append&&P(n.out))return C(`--cursor with an existing --out requires --append to preserve earlier rows`);if(n.append&&!P(n.out))return C(`--append requires the previous output file: ${n.out}`);wt(n.out,``,{flag:n.append?`a`:`w`});let u=n.cursor,d=0,f=0,p=!1;for(;d<s.data;){let e={...o.data,...u===void 0?{}:{[n.cursorParam]:u}},t=await ce({method:i.data.method,path:i.data.path,searchParams:e,body:l??void 0,auth:i.data.auth,responseFormat:`json`});if(!t.ok)return C(`page ${d+1} failed: ${t.summary}`,[`rows already written to ${n.out}: ${f}`,...u===void 0?[]:[`resume with --cursor "${u}" --append`]]);let r=Xs(t.data),a=Js(r,n.rowsPath);if(!Array.isArray(a))return C(`response has no array at --rows-path "${n.rowsPath}"`,[`page ${d+1}`]);dt(n.out,a.map(e=>`${JSON.stringify(e)}\n`).join(``)),d+=1,f+=a.length;let s=Js(r,n.nextCursorPath);if(typeof s!=`string`||s===``||s===u){p=!0;break}u=s}return S(`${f} rows across ${d} pages written to ${n.out}${p?``:`; PARTIAL export — hit --max-pages ${s.data}, resume with --cursor "${u}" --append`}`,{outPath:n.out,exhausted:p,lastCursor:u},{counts:{pageCount:d,rowCount:f}})}async function lc(e,n,r,i){let a=Us(e,n.command,i);if(!a.ok||a.data===null)return a;if(!t(a.data.intent))return C(`${n.command} is not a write operation; use \`batch export\``,[a.data.path]);let o=Ws(a.data);if(!o.ok)return o;let s=Gs(n.query??[]);if(!s.ok||s.data===null)return s;let c=Ks(`--chunk-size`,n.chunkSize,1,1e4);if(!c.ok||c.data===null)return c;let l=Ks(`--concurrency`,n.concurrency,1,8);if(!l.ok||l.data===null)return l;let u=n.base===void 0?void 0:await Sn(n.base);if(u!==void 0&&!u.ok)return u;let d=Ys(u?.data??{});if(d===null)return C(`--base must contain a JSON object`,[n.base??``]);let f=Qs(n.input);if(!f.ok||f.data===null)return f;let p=Zs(f.data.row,c.data),m={inputDigest:f.data.digest,chunkSize:c.data,requestDigest:rc(JSON.stringify({host:x().host,method:a.data.method,path:a.data.path,auth:a.data.auth,searchParams:s.data,baseBody:d,arrayField:n.arrayField})),outputPath:N(n.out)},h=$s(n.checkpoint,m,p.length);if(!h.ok||h.data===null)return h;let g=new Set(h.data.completedChunk),_=[...p.keys()].filter(e=>!g.has(e));if(r===`preview`)return S(`PREVIEW — nothing sent. ${_.length} of ${p.length} chunks (${f.data.row.length} rows) would ${a.data.method} ${a.data.path}. Run ${i} batch run to send.`,{mode:`preview`,method:a.data.method,endpoint:a.data.path,arrayField:n.arrayField,outPath:n.out},{counts:{rowCount:f.data.row.length,chunkCount:p.length,pendingChunkCount:_.length,skippedChunkCount:g.size}});wt(n.out,``,{flag:g.size>0?`a`:`w`});let v=a.data,y=s.data,b=[],ee=!1,te,ne=0,re=async e=>{let t=p[e]??[],r={...d,[n.arrayField]:t},i=await ce({method:v.method,path:v.path,searchParams:y,body:r,auth:v.auth,responseFormat:`json`}),a=i.ok?Xs(i.data):null;return dt(n.out,`${JSON.stringify({chunk:e,rowCount:t.length,ok:i.ok,summary:i.summary,problem:i.ok?null:i.problem??null,response:a??i.data??null})}\n`),i.ok?(g.add(e),ec(n.checkpoint,m,g),!0):(b.push(e),ic.has(i.problem?.type??``)&&(te=i.problem?.title),!1)};await Promise.all(Array.from({length:l.data},async()=>{for(;!ee;){let e=_[ne];if(ne+=1,e===void 0)return;!await re(e)&&(n.haltOnFailure||te!==void 0)&&(ee=!0)}}));let ie={rowCount:f.data.row.length,chunkCount:p.length,completedChunkCount:g.size,failedChunkCount:b.length,remainingChunkCount:p.length-g.size-b.length},ae={outPath:n.out,checkpointPath:n.checkpoint,failedChunk:b,halted:ee,...te===void 0?{}:{haltReason:te}};return b.length>0?C(`${b.length} chunk(s) failed${te===void 0?``:`; stopped: ${te}`}; responses in ${n.out}${n.checkpoint===void 0?``:`, resume via --checkpoint ${n.checkpoint}`}`,[JSON.stringify({...ae,...ie})]):S(`${g.size}/${p.length} chunks sent; responses in ${n.out}`,ae,{counts:ie})}function uc(e,t=A,n=s().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(()=>{F.stdout.write(fc(e,i,t))});jo(r,n),Mo(r,n)}function dc(){return s().bin}function fc(e,t,n=A,r=dc()){let i=xc(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...mc(e),...r.map(e=>`complete -c ${Y(e)} -e`),`${Pc(r)} -f`,...hc(e,r),...gc(e,i,r),``].join(`
42
42
  `):pc(e,t,i,r)}function pc(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=wc(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}`),`)`,``,...Dc(t),...t===`bash`?[a,``]:[``]].join(`
43
43
  `)}function mc(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${_c(e).filter(e=>e.required||e.optional).flatMap(e=>Ac(e)??[]).map(Y).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
44
44
  set -l expected $argv
@@ -57,15 +57,15 @@ import{$ as e,A as t,B as n,E as r,Ft as i,G as a,It as o,J as s,M as c,O as l,P
57
57
  return 0
58
58
  end
59
59
  `].flatMap(e=>e.split(`
60
- `))}function hc(e,t){return Cc(e).map(e=>`${Pc(t)} -f -n ${Y(Fc(e.parentPath))} -a ${Y(e.name)} -d ${Y(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function gc(e,t,n){return jc(e).flatMap(e=>{let r=Nc(e),i=r.length===0?void 0:Fc(r);return _c(e).flatMap(e=>{let a=t.get(Sc(r,e));return Ec(a)?vc(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function _c(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function vc(e,t,n,r){let i=Ac(e);if(i===void 0)return[];let a=e.argChoices??Tc(n),o=[`-l ${Y(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${Y(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${Y(t)}`,c=e.required||e.optional?yc(a,bc(i,n)):`-f`,l=`${Pc(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${Y(Ic(e.description))}`]:a.map(t=>`${l} -a ${Y(t)} -d ${Y(Ic(e.description))}`)}function yc(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function bc(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 xc(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...mn(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[[Sc(e.cliPath,n),t]]})))}function Sc(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):Ac(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 Cc(e){return jc(e).flatMap(e=>e.commands.map(t=>({parentPath:Nc(e),name:t.name(),description:Ic(t.summary()||t.description()||t.name())})))}function wc(e,t){let n=[],r=[];for(let i of jc(e)){let e=Nc(i);for(let a of _c(i)){let i=Ac(a);if(i===void 0)continue;let o=t.get(Sc(e,a));if(!Ec(o))continue;let s=a.argChoices??Tc(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&bc(i,o)&&(c=`file`)),n.push(Oc([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(Oc([e.join(` `),`--${i}`,t,a.description]))}}return[Cc(e).map(e=>Oc([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 Tc(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 Ec(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function Dc(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 Oc(e){return`$'${e.map(kc).join(`|`)}'`}function kc(e){return Ic(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function Ac(e){return e.long?.replace(/^--/,``)}function jc(e){return[e,...e.commands.filter(Mc).flatMap(e=>jc(e))]}var Mc=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function Nc(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function Pc(e){return`complete ${e.map(e=>`-c ${Y(e)}`).join(` `)}`}function Fc(e){return[`__aventure_cli_path_is`,...e.map(Y)].join(` `)}function Ic(e){return e.replace(/\s+/g,` `).trim()}function Y(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function Lc(e,t){if(e!==t)return;let n=Rc(t);n!==void 0&&t.error(`error: ${Bc(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function Rc(e){if(!process.argv.includes(`--`)&&e.args.some(zc))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function zc(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function Bc(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function Vc(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function Hc(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function Uc(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function Wc(e){return e.flags.split(` `)[0]??e.flags}function Gc(e,t){let n=Vc(t);if(n===void 0)return;let r=e.options.findIndex(e=>Wc(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[Wc(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.`}function X(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function Kc(e){return e.commands.length===0?[e]:e.commands.flatMap(Kc)}function qc(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 Jc(e,t){return t.toSorted((t,n)=>{let r=qc(e,t),i=qc(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 Yc(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Xc(e,t){let n=X(e),r=process.argv.slice(2+n.length);return[Z(e).name(),...n,...qc(e,t),...r].map(Yc).join(` `)}function Zc(e,t){let n=Hc(t);if(n===void 0||e.commands.length===0)return;let r=Jc(e,Kc(e).filter(e=>e.options.some(e=>Wc(e)===n)));if(r!==void 0)return`hint: run: ${Xc(e,r)}`}function Qc(e){return e!==void 0&&Object.hasOwn(We,e)}function $c(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 el(e,t){let n=X(e),r=[...n.slice(1),t];if(!Qc(n.at(0))||!Qc(r.at(0)))return;let i=$c(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 tl(e,t){let[n]=X(e);if(!Qc(n))return;let r=[n,t];return $c(Z(e),r)?.commands.length===0?r:void 0}function nl(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Kc(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 rl(e,t){let n=process.argv.slice(2+X(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return il(e,t)}function il(e,t,n=[]){let r=X(e),i=Ke(j).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(Yc).join(` `)}`}function al(e,t,n){if(!sl(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(Yc).join(` `)}`}function ol(e){let t=X(e);if(t.at(1)!==void 0&&Qc(t.at(0)))return`hint: inspect generated command group: ${[Z(e).name(),...t,`--help`].map(Yc).join(` `)}`}function sl(e,n){let r=e.join(` `);return j.some(e=>e.cliPath.join(` `)===r?n===void 0||t(e.intent)===n:!1)}function cl(e){let t=X(e).join(` `),n=Ke(j),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:vr(r.operationId,n,Z(e).name()).map(e=>`hint: ${e}`)}function ll(e){let t=X(e);if(Qc(t.at(0))&&sl(t))return`hint: inspect generated command: ${[Z(e).name(),...t,`--help`].map(Yc).join(` `)}`}function ul(e){let n=new Set,r=[];for(let i of j){let a=$c(e,i.cliPath);if(a===void 0)continue;let o=a.options.map(Wc);if(t(i.intent))r.push(o);else for(let e of o)n.add(e)}let[i=[],...a]=r;return new Set(i.filter(e=>!n.has(e)&&a.every(t=>t.includes(e))))}function dl(e,t){let n=X(e);if(sl(n,!1)&&ul(Z(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function fl(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=>Wc(e)===`--root`);return n&&s!==void 0&&c!==void 0&&Qc(s)&&o.push(Wc(c),s),`hint: search generated commands: ${o.map(Yc).join(` `)}`}function pl(e,t){let n=Uc(t);if(n===void 0||t.message.includes(`
60
+ `))}function hc(e,t){return Cc(e).map(e=>`${Pc(t)} -f -n ${Y(Fc(e.parentPath))} -a ${Y(e.name)} -d ${Y(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function gc(e,t,n){return jc(e).flatMap(e=>{let r=Nc(e),i=r.length===0?void 0:Fc(r);return _c(e).flatMap(e=>{let a=t.get(Sc(r,e));return Ec(a)?vc(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function _c(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function vc(e,t,n,r){let i=Ac(e);if(i===void 0)return[];let a=e.argChoices??Tc(n),o=[`-l ${Y(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${Y(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${Y(t)}`,c=e.required||e.optional?yc(a,bc(i,n)):`-f`,l=`${Pc(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${Y(Ic(e.description))}`]:a.map(t=>`${l} -a ${Y(t)} -d ${Y(Ic(e.description))}`)}function yc(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function bc(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 xc(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...mn(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[[Sc(e.cliPath,n),t]]})))}function Sc(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):Ac(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 Cc(e){return jc(e).flatMap(e=>e.commands.map(t=>({parentPath:Nc(e),name:t.name(),description:Ic(t.summary()||t.description()||t.name())})))}function wc(e,t){let n=[],r=[];for(let i of jc(e)){let e=Nc(i);for(let a of _c(i)){let i=Ac(a);if(i===void 0)continue;let o=t.get(Sc(e,a));if(!Ec(o))continue;let s=a.argChoices??Tc(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&bc(i,o)&&(c=`file`)),n.push(Oc([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(Oc([e.join(` `),`--${i}`,t,a.description]))}}return[Cc(e).map(e=>Oc([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 Tc(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 Ec(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function Dc(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 Oc(e){return`$'${e.map(kc).join(`|`)}'`}function kc(e){return Ic(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function Ac(e){return e.long?.replace(/^--/,``)}function jc(e){return[e,...e.commands.filter(Mc).flatMap(e=>jc(e))]}var Mc=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function Nc(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function Pc(e){return`complete ${e.map(e=>`-c ${Y(e)}`).join(` `)}`}function Fc(e){return[`__aventure_cli_path_is`,...e.map(Y)].join(` `)}function Ic(e){return e.replace(/\s+/g,` `).trim()}function Y(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function Lc(e,t){if(e!==t)return;let n=Rc(t);n!==void 0&&t.error(`error: ${Bc(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function Rc(e){if(!process.argv.includes(`--`)&&e.args.some(zc))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function zc(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function Bc(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function Vc(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function Hc(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function Uc(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function Wc(e){return e.flags.split(` `)[0]??e.flags}function Gc(e,t){let n=Vc(t);if(n===void 0)return;let r=e.options.findIndex(e=>Wc(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[Wc(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.`}function X(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function Kc(e){return e.commands.length===0?[e]:e.commands.flatMap(Kc)}function qc(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 Jc(e,t){return t.toSorted((t,n)=>{let r=qc(e,t),i=qc(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 Yc(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Xc(e,t){let n=X(e),r=process.argv.slice(2+n.length);return[Z(e).name(),...n,...qc(e,t),...r].map(Yc).join(` `)}function Zc(e,t){let n=Hc(t);if(n===void 0||e.commands.length===0)return;let r=Jc(e,Kc(e).filter(e=>e.options.some(e=>Wc(e)===n)));if(r!==void 0)return`hint: run: ${Xc(e,r)}`}function Qc(e){return e!==void 0&&Object.hasOwn(Qe,e)}function $c(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 el(e,t){let n=X(e),r=[...n.slice(1),t];if(!Qc(n.at(0))||!Qc(r.at(0)))return;let i=$c(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 tl(e,t){let[n]=X(e);if(!Qc(n))return;let r=[n,t];return $c(Z(e),r)?.commands.length===0?r:void 0}function nl(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Kc(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 rl(e,t){let n=process.argv.slice(2+X(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return il(e,t)}function il(e,t,n=[]){let r=X(e),i=qe(A).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(Yc).join(` `)}`}function al(e,t,n){if(!sl(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(Yc).join(` `)}`}function ol(e){let t=X(e);if(t.at(1)!==void 0&&Qc(t.at(0)))return`hint: inspect generated command group: ${[Z(e).name(),...t,`--help`].map(Yc).join(` `)}`}function sl(e,n){let r=e.join(` `);return A.some(e=>e.cliPath.join(` `)===r?n===void 0||t(e.intent)===n:!1)}function cl(e){let t=X(e).join(` `),n=qe(A),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:vr(r.operationId,n,Z(e).name()).map(e=>`hint: ${e}`)}function ll(e){let t=X(e);if(Qc(t.at(0))&&sl(t))return`hint: inspect generated command: ${[Z(e).name(),...t,`--help`].map(Yc).join(` `)}`}function ul(e){let n=new Set,r=[];for(let i of A){let a=$c(e,i.cliPath);if(a===void 0)continue;let o=a.options.map(Wc);if(t(i.intent))r.push(o);else for(let e of o)n.add(e)}let[i=[],...a]=r;return new Set(i.filter(e=>!n.has(e)&&a.every(t=>t.includes(e))))}function dl(e,t){let n=X(e);if(sl(n,!1)&&ul(Z(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function fl(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=>Wc(e)===`--root`);return n&&s!==void 0&&c!==void 0&&Qc(s)&&o.push(Wc(c),s),`hint: search generated commands: ${o.map(Yc).join(` `)}`}function pl(e,t){let n=Uc(t);if(n===void 0||t.message.includes(`
61
61
  (Did you mean `))return;let r=nl(e),i=rl(e,r);if(i!==void 0)return i;let a=el(e,n);if(a!==void 0)return fl(e,a.join(` `),!1);let o=tl(e,n);if(o!==void 0)return al(e,o,r)??fl(e,o.join(` `),!1);let s=r.join(` `)||n,c=ol(e)??fl(e,s),l=[...X(e),...r.slice(1)];return[l.slice(1,-1).length>0?al(e,l,r):void 0,c].filter(e=>e!==void 0).join(`
62
62
  `)||void 0}function ml(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[Rc(e),Gc(e,t),...cl(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=Rc(e)??ll(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=Hc(t),r=Zc(e,t)??(n!==void 0&&!t.message.includes(`
63
- (Did you mean `)?dl(e,n)??il(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??fl(e,n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=pl(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var hl=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 gl(e){e.showHelpAfterError(!1).exitOverride(ml(e)),e.commands.length===0?e.hook(`preAction`,Lc):e.addHelpOption(new hl(e));for(let t of e.commands)gl(t)}function _l(e,t=new Date){let n=bl(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 vl(e){return`${JSON.stringify(e,null,2)}\n`}function yl(e,t){let n=N(e),r=vl(t);return mt(M(n),{recursive:!0}),wt(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function bl(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:te(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 xl=`Match only the first canonical or CLI-alias command segment`,Sl=[`text`,`lines`,`compact`,`json`,`ndjson`];function Cl(e,t,n=s().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(`
64
- `));r.addHelpText(`after`,()=>`\nShipped compact catalog, greppable without running this CLI:\n ${Or(n)}\n`),wl(r,t,n),Tl(r,t,n),El(r,t,n),Dl(r)}function wl(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>`,xl).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(Sl)).option(`--output <path>`,`Write rendered output to a file`);A(r),r.action(function(e){let r=this.optsWithGlobals(),i=k(r,`text`);jr(Ar(r,e),t,i,n)})}function Tl(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`);A(r),r.action(function(){let e=this.optsWithGlobals();Mr(e,t,k(e,`text`),n)})}function El(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>`,xl).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(Sl)).option(`--output <path>`,`Write rendered output to a file`);A(r),r.action(function(){let e=this.optsWithGlobals();jr(e,t,k(e,`text`),n)})}function Dl(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`);A(t),t.action(function(){let e=this.optsWithGlobals(),t=k(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){R({mode:t},S(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:Qe.length}}));return}let n=_l(Qe);if(e.output!==void 0){let r=yl(e.output,n);R({mode:t},S(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(vl(n));return}R({mode:t},S(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var Ol=s(Ot(import.meta.url)),Q=Ol.bin[0];function kl(e,t){f({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}:{};Jn({...C(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function Al(e){return Ze[He(e)??`cli`]}function jl(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:Al(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>Xe(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)Ml(e,t,r,a,i.has(t.cliPath.join(` `)))}function Ml(e,n,i,a,o){let s=n.cliPath,c=e,u=``,d=!i.has(s[0]??``);for(let e of s.slice(0,-1)){u=u===``?e:`${u} ${e}`;let t=d&&u===e||!a.has(u);c=Nl(c,e,u,t)}let f=s.at(-1)??n.operationId,p=c.commands.find(e=>e.name()===f)??c.command(f,n.deprecated===!0?{hidden:!0}:{}),m=n.requestBody?.flatMap(({parameter:e})=>e)??[];p.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,...m].some(e=>l(e.schemaType,e.itemSchemaType))?r:``].filter(Boolean).join(`
65
- `));let h=ri(n);for(let e of n.parameters)Pl(p,e,o||e===h);if(Tn(p,n),t(n.intent)&&p.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),A(p),n.explain===!0&&p.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){p.argument(`[text...]`,h.description||`Same as ${ni(h.flag)}.`),p.action(async function(e){let t=this.optsWithGlobals(),r=k(t),i=ii(h,e,t);if(!i.ok||i.data===null)return R({mode:r},i);let a=ti(n,i.data);if(a.length>0)return R({mode:r},C(`missing required options: ${a.join(`, `)}`));let o=await Fl(n,i.data,r),s=ai(n,i.data,o);if(s!==null)return R({mode:r},s);t.explain===!0&&o.ok&&Qn(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):R({mode:r},o)});return}p.action(async function(){let e=this.optsWithGlobals(),t=k(e),r=ti(n,e);if(r.length>0)return R({mode:t},C(`missing required options: ${r.join(`, `)}`));let i=await Fl(n,e,t),a=ai(n,e,i);if(a!==null)return R({mode:t},a);e.explain===!0&&i.ok&&Qn(t,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):R({mode:t},i)})}function Nl(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=We[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function Pl(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 Fl(t,n,r){if(n.environment!==void 0){let t=e(n.environment);if(t===null)return C(`Unknown aVenture environment '${n.environment}'`,[`Use one of: ${d().join(`, `)}`]);process.env.API_ENV=t}let i=await An(t,n);if(!i.ok)return i;let a=Object.fromEntries(t.parameters.filter(e=>e.location===`path`).map(e=>{let t=n[e.optionKey];if(Array.isArray(t))return[e.name,t.at(0)??``];if(t===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(t)]})),o=Object.fromEntries(t.parameters.filter(e=>e.location===`query`).flatMap(e=>{let t=n[e.optionKey];if(t===void 0||Array.isArray(t)&&t.length===0)return[];let r=Array.isArray(t)||typeof t==`boolean`?t:String(t);return[[e.name,r]]})),s=Object.fromEntries(t.parameters.filter(e=>e.location===`header`).flatMap(e=>{let t=n[e.optionKey];return t===void 0||Array.isArray(t)&&t.length===0?[]:[[e.name,Array.isArray(t)?t.join(`,`):String(t)]]}));return await w({method:t.method,path:se(t.operationId,a),searchParams:o,headers:s,body:i.data,contentType:typeof n.contentType==`string`?n.contentType:void 0,auth:t.auth,responseFormat:Be(r)?`json`:`auto`,responseBytes:t.binaryResponse===!0})}process.on(`uncaughtException`,e=>kl(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>kl(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var Il=Ve(process.argv.slice(2),j),Ll=Il===`required`?j:Ke(j),$=new u;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Kr).version(Ol.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.
63
+ (Did you mean `)?dl(e,n)??il(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??fl(e,n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=pl(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var hl=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 gl(e){e.showHelpAfterError(!1).exitOverride(ml(e)),e.commands.length===0?e.hook(`preAction`,Lc):e.addHelpOption(new hl(e));for(let t of e.commands)gl(t)}function _l(e,t=new Date){let n=bl(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 vl(e){return`${JSON.stringify(e,null,2)}\n`}function yl(e,t){let n=N(e),r=vl(t);return mt(j(n),{recursive:!0}),wt(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function bl(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:te(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 xl=`Match only the first canonical or CLI-alias command segment`,Sl=[`text`,`lines`,`compact`,`json`,`ndjson`];function Cl(e,t,n=s().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(`
64
+ `));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 ${Or(n)}\n`),wl(r,t,n),Tl(r,t,n),El(r,t,n),Dl(r)}function wl(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>`,xl).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(Sl)).option(`--output <path>`,`Write rendered output to a file`);k(r),r.action(function(e){let r=this.optsWithGlobals(),i=O(r,`text`);jr(Ar(r,e),t,i,n)})}function Tl(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`);k(r),r.action(function(){let e=this.optsWithGlobals();Mr(e,t,O(e,`text`),n)})}function El(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>`,xl).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(Sl)).option(`--output <path>`,`Write rendered output to a file`);k(r),r.action(function(){let e=this.optsWithGlobals();jr(e,t,O(e,`text`),n)})}function Dl(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`);k(t),t.action(function(){let e=this.optsWithGlobals(),t=O(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){R({mode:t},S(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:$e.length}}));return}let n=_l($e);if(e.output!==void 0){let r=yl(e.output,n);R({mode:t},S(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(vl(n));return}R({mode:t},S(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var Ol=s(Ot(import.meta.url)),Q=Ol.bin[0];function kl(e,t){f({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}:{};Jn({...C(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function Al(e){return Ue[We(e,Qe)??`cli`]}function jl(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:Al(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>Ze(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)Ml(e,t,r,a,i.has(t.cliPath.join(` `)))}function Ml(e,n,i,a,o){let s=n.cliPath,c=e,u=``,d=!i.has(s[0]??``);for(let e of s.slice(0,-1)){u=u===``?e:`${u} ${e}`;let t=d&&u===e||!a.has(u);c=Nl(c,e,u,t)}let f=s.at(-1)??n.operationId,p=c.commands.find(e=>e.name()===f)??c.command(f,n.deprecated===!0?{hidden:!0}:{}),m=n.requestBody?.flatMap(({parameter:e})=>e)??[];p.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,...m].some(e=>l(e.schemaType,e.itemSchemaType))?r:``].filter(Boolean).join(`
65
+ `));let h=ri(n);for(let e of n.parameters)Pl(p,e,o||e===h);if(Tn(p,n),t(n.intent)&&p.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),k(p),n.explain===!0&&p.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){p.argument(`[text...]`,h.description||`Same as ${ni(h.flag)}.`),p.action(async function(e){let t=this.optsWithGlobals(),r=O(t),i=ii(h,e,t);if(!i.ok||i.data===null)return R({mode:r},i);let a=ti(n,i.data);if(a.length>0)return R({mode:r},C(`missing required options: ${a.join(`, `)}`));let o=await Fl(n,i.data,r),s=ai(n,i.data,o);if(s!==null)return R({mode:r},s);t.explain===!0&&o.ok&&Qn(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):R({mode:r},o)});return}p.action(async function(){let e=this.optsWithGlobals(),t=O(e),r=ti(n,e);if(r.length>0)return R({mode:t},C(`missing required options: ${r.join(`, `)}`));let i=await Fl(n,e,t),a=ai(n,e,i);if(a!==null)return R({mode:t},a);e.explain===!0&&i.ok&&Qn(t,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):R({mode:t},i)})}function Nl(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=Qe[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function Pl(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 Fl(t,n,r){if(n.environment!==void 0){let t=e(n.environment);if(t===null)return C(`Unknown aVenture environment '${n.environment}'`,[`Use one of: ${d().join(`, `)}`]);process.env.API_ENV=t}let i=await An(t,n);if(!i.ok)return i;let a=Object.fromEntries(t.parameters.filter(e=>e.location===`path`).map(e=>{let t=n[e.optionKey];if(Array.isArray(t))return[e.name,t.at(0)??``];if(t===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(t)]})),o=Object.fromEntries(t.parameters.filter(e=>e.location===`query`).flatMap(e=>{let t=n[e.optionKey];if(t===void 0||Array.isArray(t)&&t.length===0)return[];let r=Array.isArray(t)||typeof t==`boolean`?t:String(t);return[[e.name,r]]})),s=Object.fromEntries(t.parameters.filter(e=>e.location===`header`).flatMap(e=>{let t=n[e.optionKey];return t===void 0||Array.isArray(t)&&t.length===0?[]:[[e.name,Array.isArray(t)?t.join(`,`):String(t)]]}));return await ce({method:t.method,path:se(t.operationId,a),searchParams:o,headers:s,body:i.data,contentType:typeof n.contentType==`string`?n.contentType:void 0,auth:t.auth,responseFormat:Ve(r)?`json`:`auto`,responseBytes:t.binaryResponse===!0})}process.on(`uncaughtException`,e=>kl(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>kl(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var Il=He(process.argv.slice(2),A),Ll=Il===`required`?A:qe(A),$=new u;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Kr).version(Ol.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.
66
66
  `,`Mutations execute directly; --execute is a deprecated no-op.
67
67
  The aVenture MCP server tools execute through this same CLI.`].join(`
68
- `)).addOption(new i(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${g})`).choices([...d()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),jl($,Ll),ks($,Q),Qo($,Ol),ac($,Ll,Q),uc($,Ll,Q),Cl($,Ll,Q),Hr($,Ll,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(Al(e.name()).heading);if(gl($),Il===`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 Pe(),await Ie())}))}}$.addHelpText(`after`,[``,`Subcommands, the same under entities, people, and news:`,` search Find many of that record from a plain-English query or a filter`,` lookup Find which one of that record a name, URL, or id refers to`,` get Read one record`,` list Read many records`,` suggest Read proposed values for a field`,` create, update, delete Write; each needs a credential that permits it
68
+ `)).addOption(new i(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${g})`).choices([...d()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),jl($,Ll),ks($,Q),Qo($,Ol),ac($,Ll,Q),uc($,Ll,Q),Cl($,Ll,Q),Hr($,Ll,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(Al(e.name()).heading);if(gl($),Il===`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 Fe(),await Le())}))}}$.addHelpText(`after`,[``,`Subcommands, the same under entities, people, and news:`,` search Find many of that record from a plain-English query or a filter`,` lookup Find which one of that record a name, URL, or id refers to`,` get Read one record`,` list Read many records`,` suggest Read proposed values for a field`,` create, update, delete Write; each needs a credential that permits it
69
69
  `,`Environment (the one API credential):`,` AUTH_TOKEN Clerk API key or session token for every authenticated call`,` Public reads work with no credential; a saved sign-in is used when present.`,` 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
70
70
  `,`Exit codes:`,` 0 envelope.ok === true
71
71
  1 envelope.ok === false