@aventurevc/aventure-cli 0.7.297 → 0.7.302

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,66 +0,0 @@
1
- import{C as e,D as t,_ as n,a as r,k as i,v as a,x as o}from"./person-owner-ChqQWHII.js";import{$ as s,C as c,Ct as l,E as u,J as d,L as f,M as p,N as m,O as h,P as ee,Q as te,S as ne,T as re,U as g,X as _,Y as v,Z as ie,b as ae,c as oe,et as y,f as se,g as ce,h as le,it as b,j as ue,k as x,l as S,m as de,nt as fe,o as pe,p as me,q as C,rt as w,s as he,v as ge,w as _e,z as ve}from"./auth-D_KyooBG.js";import{E as ye,T,_ as be,a as xe,c as Se,f as Ce,i as we,l as Te,m as Ee,o as De,r as Oe,t as ke,w as Ae,x as je}from"./oauth-credential-De9MML57.js";import{C as Me,S as Ne,_ as Pe,a as Fe,b as Ie,c as Le,d as Re,f as ze,g as Be,h as Ve,l as He,m as Ue,n as We,o as E,p as Ge,r as D,s as Ke,t as O,u as qe,v as Je,x as Ye,y as Xe}from"./openapi-commands-DmQ4uKIS.js";import{a as Ze,f as Qe,i as $e,l as et,n as tt,r as nt,s as rt,t as it}from"./mcp-generation-contract-BbfS1mJz.js";import{a as at,n as ot,o as st,r as ct,t as lt}from"./oauth-login-oAtCenVf.js";import{spawnSync as ut}from"node:child_process";import{createHash as dt,webcrypto as ft}from"node:crypto";import{readFile as pt}from"node:fs/promises";import{homedir as mt,hostname as ht,platform as gt}from"node:os";import{basename as _t,dirname as k,join as A,resolve as j,sep as vt}from"node:path";import M,{stderr as N,stdin as yt}from"node:process";import{appendFileSync as bt,copyFileSync as xt,existsSync as P,lstatSync as St,mkdirSync as Ct,mkdtempSync as wt,readFileSync as F,readlinkSync as Tt,realpathSync as Et,renameSync as Dt,rmSync as Ot,rmdirSync as kt,unlinkSync as At,writeFileSync as I}from"node:fs";import{fileURLToPath as jt}from"node:url";import{TextDecoder as Mt,inspect as Nt}from"node:util";import{setTimeout as Pt}from"node:timers/promises";import{createInterface as Ft}from"node:readline/promises";function It(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{...w(`${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 b(`Environment-bound options applied`,r)}function Lt(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||!Zt(n,r.name))continue;let a=Xt(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 Rt(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 zt(e,t,n,r=!1){if(r||!en(t)||!Array.isArray(n))return nn(e,t,n);for(let[r,i]of n.entries()){let n=nn(e,t,i,r);if(!n.ok)return n}return b(`Body value assigned`,null)}function Bt(e,t,n,r){return nn(e,t,r,n)}function Vt(e){let t=[];for(let n of e.split(`.`)){let e=an(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Ht(e,t){let n=Vt(t);if(n===null)return null;let r=Yt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Jt(r)}:null}function Ut(e,t){if(en(e.name)||e.schemaType===`array`)return b(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return b(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?b(`Scalar body option selected`,t[0]):w(`${n} was already given; pass it once.`)}var Wt=/^(?<row>\d+):(?<item>.*)$/su;function Gt(e,t){let n=Vt(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=Wt.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 Kt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Vt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function qt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Ht(r,i.name);if(a===null)continue;if(a.firstHole!==null)return w(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Gt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return w(`${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 Jt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Yt(e,t){let n=e;for(let e of t){if(!L(n))return;n=n[e]??null}return n}function Xt(e,t){if(!en(t))return Yt(e,t.split(`.`))}function Zt(e,t){return $t(e,t.split(`.`))}function Qt(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)&&Zt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function $t(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=an(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=>$t(e,r)):$t(a,r)}function en(e){return e.split(`.`).some(e=>an(e).isArray)}function tn(e,t){return e.parameter.length===0||!L(t)?null:sn(t,[],on(e.parameter))}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=an(o),c=e===i.length-1,l=rn(a,s,t,c,n,r);if(!l.ok||l.data===null)return w(l.summary,l.warnings);if(c)return b(`Body value assigned`,null);a=l.data}return w(`${t} is not a valid body option path.`)}function rn(e,t,n,r,i,a){let o=()=>w(`${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,b(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,b(`Body path created`,e)}return L(c)?b(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,b(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,b(`Body path created`,n)}return L(s)?b(`Body path stepped`,s):o()}function an(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function on(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 sn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=sn(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(!cn(a,n)){if(!ln(e))continue;return{path:a,suggestion:un(e,n)}}let o=sn(i,e,n);if(o!==null)return o}return null}function cn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function ln(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function un(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:dn(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 dn(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 fn(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(Ge(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?bn(r,i):r===void 0?i===void 0?0:1:-1})}function pn(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 mn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function hn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:vn(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 gn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function _n(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?Ue(n):`${Ue(n)} Required JSON paths: ${r.join(`, `)}.`}function vn(e,t){return`${Re(t.description,void 0)}${e.kind!==`multipart`&&en(t.name)?` Repeat to add another value.`:``}${yn(e,t)}`}function yn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Vt(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 bn(e,t){return ze(e)-ze(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function xn(e){let t;try{t=e===`-`?await Sn():await pt(e,`utf8`)}catch(t){return w(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return b(`No input provided`,null);let e=JSON.parse(t);return b(`Input parsed`,e)}catch(e){return w(`Input is not valid JSON: ${e.message}`)}}async function Sn(){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 Cn=`--content-type`;function wn(e,t){let n=t.requestBody??[];if(n.length>1){let t=n.map(({contentType:e})=>e);e.addOption(new u(`${Cn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(En(n)))}if(Kn(t)){let r=n[0];if(r===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new u(`--from-file <path>`,_n(r,r.requiredPath)).argParser(On(`--from-file`)))}let r=pn(n);for(let t of r.toSorted((e,t)=>bn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=t.variant[0],a=new u(mn(t),n.length>1?hn(t):vn(r,i));n.length===1&&i.envName!==void 0&&a.env(i.envName);let o=n.length===1?gn(r,i.optionKey):[];o.length>0&&a.conflicts(o),n.length>1?a.argParser(Tn):en(i.name)||i.schemaType===`array`?a.argParser(Dn):a.argParser(On(i.flag)),e.addOption(a)}Gn(e,t,r)}function Tn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function En(e){return(t,n)=>{if(n!==void 0)throw new h(`${Cn} was already given; pass it once.`);let r=_e(e,t);if(!r.ok)throw new h(r.summary);return t}}function Dn(e,t){return[...t??[],e]}function On(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new h(`${t} was already given; pass it once.`);return e}}async function kn(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,r=_e(e.requestBody??[],n);if(!r.ok||r.data===null)return w(r.summary,r.warnings);let i=r.data;if(i===void 0)return b(`No body`,void 0);let a=An(e,i,t);if(a!==null)return w(a);let o=It(e.operationId,i,t);if(!o.ok)return w(o.summary,o.warnings);t=o.data;let s=jn(i,t);if(s!==null)return w(s);let c=await Fn(t);if(!c.ok)return w(c.summary,c.warnings);let l=Qt(e.requestBody??[],i,c.data);if(l!==null)return w(l);let u=Pn(e.operationId,i,c.data);if(!u.ok)return u;let d=Lt(e.operationId,i,c.data);if(d!==null)return w(d);let f=In(e.operationId,i,t);if(!f.ok)return f;if(c.data===void 0&&f.data===void 0)return i.required?w(Wn(e.operationId,i)):b(`No body`,void 0);let p=zn(e.operationId,c.data,f.data);if(!p.ok||p.data===void 0)return p;if(i.schemaType===`array`&&!Array.isArray(p.data))return w(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!L(p.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return w(`${e.operationId} requires a JSON object${t}.`)}let m=Nn(i,p.data);if(m.length>0)return w(`${e.operationId} requires body option(s): ${m.join(`, `)}`);let h=p.data,ee=L(h)?Rt(i).filter(e=>!Zt(h,e)):[];return ee.length>0?w(Mn(e.operationId,i,ee)):p}function An(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`${Rn(t)} requires ${Cn} ${i.join(` or `)}.`}return null}function jn(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 Mn(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 Nn(e,t){return L(t)?e.parameter.filter(e=>e.required&&!Zt(t,e.name)).map(Rn):[]}function Pn(e,t,n){let r=tn(t,n);if(r===null)return b(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion.path} (${r.suggestion.flag}).`;return w(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Fn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return b(`No body file`,void 0);let n=await xn(t);if(!n.ok)return w(n.summary,n.warnings);let r=l.safeParse(n.data);return r.success?b(`Input parsed`,r.data):w(`Input is not valid JSON value: ${r.error.message}`)}function In(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Ut(e,n[e.optionKey]);if(!a.ok||a.data===null)return w(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Ln(t,n,r,e,o);if(!s.ok)return w(s.summary,s.warnings);i=!0}if(!i)return b(`No direct body options`,void 0);let a=qt(e,t,n,r);return a===null?b(`Direct body options parsed`,r):a}function Ln(e,t,n,r,i){let a=Gt(r,i);if(a===null){let e=Hn(r,i);return e.ok?zt(n,r.name,e.data,r.schemaType===`array`):w(e.summary,e.warnings)}if(a.plain.length>0)return w(`${Rn(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=Kt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return w(`${Rn(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=Un(r.name,r.itemSchemaType,e);if(!t.ok)return w(t.summary,t.warnings);i.push(t.data)}let a=Bt(n,r.name,e,i);if(!a.ok)return a}return b(`Body value assigned`,null)}function Rn(e){return e.flag.split(` `)[0]??e.name}function zn(e,t,n){if(t===void 0)return b(`Direct body parsed`,n);if(n===void 0)return b(`Input parsed`,t);if(L(t)&&L(n))try{return b(`Input parsed`,Bn(t,n))}catch(t){return w(`${e} ${t.message}`)}return w(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Bn(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&&Vn(t)!==Vn(r))throw Error(`cannot combine --from-file ${Vn(t)} '${e}' with ${Vn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=L(t)&&L(r)?Bn(t,r):r}return n}function Vn(e){return Array.isArray(e)?`array`:L(e)?`object`:`scalar`}function Hn(e,t){if(typeof t==`boolean`)return b(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Un(e.name,e.schemaType,t??``);let n=[],r=en(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Un(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return b(`Body value parsed`,n)}function Un(e,t,n){if(t===`boolean`)return n===`true`?b(`Body value parsed`,!0):n===`false`?b(`Body value parsed`,!1):w(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?w(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?w(`${e} must be an integer.`):b(`Body value parsed`,i)}return b(`Body value parsed`,n)}function Wn(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(Rn).join(`, `)}`;let r=Rt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(Rn).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Gn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:Cn,location:`body`}),Kn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),fn(e.options,r)}function Kn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function qn(e){let t=fe(e);return er(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Jn(e){er(e);let t=tt(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
- `)?t:`${t}\n`),Yn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&Zn(e.problem),Yn(e)}function Yn(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`?fe(t):t;er(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Xn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?qn(t):t;e.mode===`text`&&Jn(n),n.ok||(process.exitCode=1)}function Xn(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 Zn(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`)}Qn(`unknownParameters`,e.unknownParameters),Qn(`validParameters`,e.validParameters),$n(e.resolution)}function Qn(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function $n(e){if(e==null)return;let t=[`action=${e.action}`];typeof e.parameter==`string`&&t.push(`parameter=${e.parameter}`),typeof e.fieldPath==`string`&&t.push(`fieldPath=${e.fieldPath}`),typeof e.endpoint==`string`&&t.push(`endpoint=${e.endpoint}`),e.acceptedValue!==null&&e.acceptedValue!==void 0&&e.acceptedValue.length>0&&t.push(`acceptedValue=${e.acceptedValue.join(`, `)}`),typeof e.retryable==`boolean`&&t.push(`retryable=${e.retryable}`),process.stdout.write(` resolution: ${t.join(` `)}\n`)}function er(e){e.ok&&e.warnings.length===0||ve({component:`aventure-cli`,event:e.ok?`command_warning`:`command_failed`,message:e.warnings.length>0?e.warnings.join(` | `):e.summary,fields:{warningCount:e.warnings.length,summary:e.summary}})}function tr(e,t,n=C().bin[0]){let r=t.length,i=rt(e.q?.trim()??``),a=Ze(i),o=et(i),s=ir(t,n).filter(t=>cr(t,e)).map(e=>({operation:e,score:ur(i,a,o,e)})).filter(({score:e})=>i===``||e>0).toSorted((e,t)=>t.score-e.score||e.operation.cli.command.localeCompare(t.operation.cli.command)||e.operation.operationId.localeCompare(t.operation.operationId)).map(({operation:e})=>e),c=hr(e.limit,s.length),l=s.slice(0,c);return b(`Operation catalog matches`,{operation:l,count:{totalOperations:r,matched:s.length,returned:l.length}})}function nr(e,t,n=C().bin[0]){let r=ir(t,n),i=e.operationId===void 0?rr(r,e.command):r.find(t=>t.operationId===e.operationId);return i===void 0?w(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`]):b(`Generated operation detail`,{operation:i,usage:gr(i)})}function rr(e,t){if(t===void 0)return;let n=Tr(t);return e.find(e=>Tr(e.cli.command)===n||e.cli.alias!==null&&Tr(e.cli.alias)===n)}function ir(e,t){return e.map(e=>{let n=e.requestBody??[],r=[...e.parameters.map(e=>ar(e)),...n.flatMap(e=>e.parameter.map(t=>ar(t,n.length>1?e.contentType:void 0))),...or(n)],i=`${t} ${e.cliPath.join(` `)}`,a=e.cliAliasPath===void 0?null:`${t} ${e.cliAliasPath.join(` `)}`,o=ne(e.intent),s=e.method===`DELETE`||e.intent===`delete`,l=n[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:s,auth:e.auth,cli:{command:i,path:e.cliPath,alias:a,aliasPath:e.cliAliasPath??null},mcpTool:e.binaryResponse?null:c(e.intent),body:{hasBody:l!==void 0,kind:l?.kind??null,...l!==void 0&&n.length>1?{contentType:l.contentType}:{},required:l?.required??!1,description:l?.description??``,requiredPath:l?.requiredPath??[]},flags:r,errorResponse:e.errorResponse,summary:e.summary,description:e.description}})}function ar(e,t){let n=e.flag.split(/\s+/u);return{name:n[0]??e.flag,optionKey:e.optionKey,wireName:e.name,location:e.location,required:e.required,placeholder:n.length<=1?null:n.slice(1).join(` `),description:e.description,choices:e.choices??[],...t===void 0?{}:{contentType:t}}}function or(e){if((e?.length??0)<=1)return[];let t=e?.map(({contentType:e})=>e)??[];return[{name:`--content-type`,optionKey:`contentType`,wireName:`Content-Type`,location:`body`,required:!1,placeholder:`<media-type>`,description:`Select the request content type; omit for ${t[0]}.`,choices:t}]}function sr(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function cr(e,t){return!(t.root!==void 0&&!lr(e,t.root)||t.scope!==void 0&&t.scope!==`all`&&t.scope!==e.scope||t.mutates!==void 0&&t.mutates!==`any`&&t.mutates===`true`!==e.mutates||t.destructive!==void 0&&t.destructive!==`any`&&t.destructive===`true`!==e.destructive||t.intent!==void 0&&t.intent!==`all`&&t.intent!==e.intent||t.method!==void 0&&t.method!==`all`&&t.method!==e.method)}function lr(e,t){let n=rt(t);return n.length===0||rt(e.cli.path.at(0)??``)===n||rt(e.cli.aliasPath?.at(0)??``)===n}function ur(e,t,n,r){if(e.length===0)return 1;let i=fr(r),a=dr(e,t,i,{exactQuery:120,partialQuery:60,exactToken:18,partialToken:6})+dr(e,t,pr(r),{exactQuery:12,partialQuery:6,exactToken:2,partialToken:1});$e(n,i)&&(a+=200);for(let e of r.cli.path){let n=new Set;nt(n,e),[...n].some(e=>t.has(e))&&(a+=15)}return rt(r.cli.command).endsWith(e)&&(a+=40),a}function dr(e,t,n,r){let i=0;n.includes(e)&&(i+=r.exactQuery),n.some(t=>t.includes(e))&&(i+=r.partialQuery);for(let e of t)n.includes(e)?i+=r.exactToken:n.some(t=>t.includes(e))&&(i+=r.partialToken);return i}function fr(e){return mr([e.operationId,e.cli.command,e.cli.alias??``,e.summary])}function pr(e){return mr([e.method,e.path,e.resource,e.intent,e.scope,e.mutates?`mutates mutation write`:`read only no mutation`,e.destructive?`destructive delete`:`non destructive`,e.mcpTool??``,e.body.kind??``,e.body.description,e.body.requiredPath.join(` `),e.description,...e.flags.flatMap(e=>[e.name,e.optionKey,e.wireName,e.description,e.choices.join(` `)])])}function mr(e){return e.map(rt).filter(e=>e.length>0)}function hr(e,t){if(e===void 0)return t;let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function gr(e){let t=sr(e),n=t.filter(e=>e.required),r=t.filter(e=>!e.required);return[`cli: ${e.cli.command}`,e.cli.alias===null?``:`alias: ${e.cli.alias}`,`${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`,n,`path`),z(`required query flags`,n,`query`),z(`required header flags`,n,`header`),z(`required body flags`,n,`body`),z(`optional path flags`,r,`path`),z(`optional query flags`,r,`query`),z(`optional header flags`,r,`header`),z(`optional body flags`,r,`body`),...xr(e),..._r(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
3
- `)}function _r(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var vr=[`-id`,`-slug`,`-url`],yr=[`--id`,`--slug`,`--url`],br=`--from-file "<path>"`;function xr(e){return[`example: ${[e.cli.command,...Sr(e),`--data`].join(` `)}`]}function Sr(e){let t=sr(e).filter(e=>e.required),n=(t.length>0?t:Cr(e)).map(wr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,br]:n}function Cr(e){let t=new Set;nt(t,e.resource);for(let n of vr)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 yr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function wr(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 Tr(e){return e.trim().replace(/^aventure(?:-cli)?\s+/u,``).replaceAll(/\s+/gu,` `)}function Er(e,t,n=C().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show command help, or ask the platform a grounded question`).description([`Show local --help output for a command path (deterministic, offline),`,`or answer a natural-language platform question with --ask via the grounded`,"help operation (the same generated operation as `help ask`)."].join(`
4
- `)).argument(`[command...]`,"command path to show help for, e.g. `help search entities`"),r.addOption(new Dr(r));let i=kr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),D(r),r.action(async function(t){let r=this.optsWithGlobals();if(r.help&&t.length===0){this.outputHelp();return}if(!r.help&&i!==void 0&&r.ask!==void 0){let e=E(r);if(t.length>0){R({mode:e},w(`Use either a command path or --ask, not both.`));return}R({mode:e},await jr(i,r.ask,r.environment,e));return}let a=Ar(e,t);a===void 0&&this.error(`unknown command '${t.join(` `)}' (run \`${n} --help\` for the command tree)`),a.outputHelp()}),Or(e,t)}var Dr=class extends u{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))}};function Or(e,t){let n=new Set;for(let r of t){let t=_r(r.errorResponse);if(t.length!==0)for(let i of[r.cliPath,r.cliAliasPath]){let r=i===void 0?void 0:Ar(e,i);r===void 0||n.has(r)||(n.add(r),r.addHelpText(`after`,`\n${t.join(`
5
- `)}\n`))}}}function kr(e){let[t,...n]=e.filter(e=>{let[t,n,r]=e.cliPath;return t===`help`&&n!==void 0&&r===void 0&&Mr(e)!==void 0});return n.length===0?t:void 0}function Ar(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 jr(e,t,n,r){let i=Mr(e);if(i===void 0)return w(`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 kn(e,{[i.optionKey]:t});return a.ok?await S({method:e.method,path:pe(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Fe(r)?`json`:`auto`}):a}function Mr(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}var Nr=`search`,Pr=`mode`,Fr=`--mode`;function Ir(e,t){let n=e.commands.find(e=>e.name()===Nr);if(n===void 0)return;let r=new Map;for(let e of t){let[t,n,i]=e.cliPath;if(t!==Nr||n===void 0||i!==void 0)continue;let a=[...e.parameters,...e.requestBody?.flatMap(({parameter:e})=>e)??[]].find(e=>e.optionKey===Pr);a?.choices!==void 0&&r.set(n,a.choices)}if(r.size===0)return;let i=[...new Set([...r.values()].flat())];n.addOption(new u(`${Fr} <mode>`,`search strategy, forwarded to the scope command's generated --mode option`).choices(i).argParser((e,t)=>{if(t!==void 0)throw new h(`${Fr} was already given; pass it once.`);if(!i.includes(e))throw new h(`${Fr} must be one of: ${i.join(`, `)}.`);return e})),n.hook(`preSubcommand`,(e,t)=>{let n=e.opts()[Pr];typeof n==`string`&&(r.has(t.name())||e.error(`${Fr} is not supported by 'search ${t.name()}'`),t.setOptionValueWithSource(Pr,n,`cli`))})}var Lr=a({artifact:e().nullish(),group:e().nullish(),name:e().nullish(),revision:e().nullish(),time:i({offset:!0}).nullish(),version:e().nullish()}),Rr=a({build:Lr});function B(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var zr=r([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),Br=r([`RSA_OAEP_256_A256_GCM_V1`]),Vr=a({clientLabel:e().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:zr.nullish(),encryptionAlgorithm:Br.nullish(),encryptionPublicKey:e().min(344).max(12e3).nullish()}),Hr=32;async function Ur(){let e=await ft.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await ft.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function Wr(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=Gr(n,`wrapped key`,128,1024),s=Gr(r,`nonce`,12,12),c=Gr(i,`ciphertext`,1,65536),l=Gr(a,`authentication tag`,16,16),u;try{u=await ft.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!==Hr)throw Error(`broker credential used an invalid AES-256 key`);let e=await ft.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 ft.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Mt(`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 Gr(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 Kr=r([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),qr=r([`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`,`Personal API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),Jr=a({approvedAt:i({offset:!0}).nullish(),clientLabel:e(),clientPlatform:zr,comparisonCode:e(),consumedAt:i({offset:!0}).nullish(),createdAt:i({offset:!0}),expiresAt:i({offset:!0}),id:t(),intervalSeconds:n().int().min(1),keyReadyAt:i({offset:!0}).nullish(),status:Kr,terminalAt:i({offset:!0}).nullish(),terminalReason:qr.nullish(),updatedAt:i({offset:!0})}),Yr=a({algorithm:Br,authenticationTag:e(),ciphertext:e(),nonce:e(),wrappedKey:e()}),Xr=a({delivery:Yr.nullish(),expiresAt:i({offset:!0}),status:Kr,terminalReason:qr.nullish()}),Zr=a({comparisonCode:e(),expiresAt:i({offset:!0}),id:t(),intervalSeconds:n().int().min(1),pollSecret:e(),verificationUrl:e()}),V=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`start`,summary:`Sign in with a browser-approved personal 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 personal 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 personal 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 personal key and forget stored OAuth`,description:`Revokes the stored personal key and returns provider metadata so the CLI can confirm remote revocation before removing local bytes.`,operationId:`revokeCurrentPersonalApiKey`,method:`DELETE`,path:`/v1/auth/personal-api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Remove local bytes even when remote revocation cannot be confirmed.`}]}],Qr=B(V,`start`),$r=B(V,`poll`),ei=B(V,`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=si(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},ni=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${T(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function ri(e){let t=await le(Ae(y()),{method:Qr.method,path:me(Qr.path,{},Qr.operationId),headers:{},contentType:`application/json`,body:e},Zr);if(!t.ok)throw new ti(`start`,t.problem);return ci(t.data)}async function ii(e,t){let n=he($r.operationId),r=await le(Ae(y()),{method:$r.method,path:me($r.path,{cliAuthorizationId:e},$r.operationId),headers:{[n]:t}},Xr);if(!r.ok)throw new ti(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:oi(r.headers[`retry-after`])}}async function ai(e,t){let n=he(ei.operationId),r;try{r=await le(Ae(y()),{method:ei.method,path:me(ei.path,{cliAuthorizationId:e},ei.operationId),headers:{[n]:t}},Jr)}catch(e){throw new ni(`acknowledge`,e,[t])}if(!r.ok)throw new ti(`acknowledge`,r.problem,[t]);return r.data}function oi(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function si(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function ci(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())})`},[Nt.custom]:{enumerable:!1,value:a}})}async function li(e){let t=Ae(y()),n;try{n=await le(t,{method:`GET`,path:pe(`getCurrentPersonalApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Ne)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${T(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`personal API-key metadata verified`,apiKey:n.data}:{state:`invalid`,summary:`personal API-key self metadata is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${ye(n.problem,[e])}`}}var ui=B(V,`revoke`);async function di(e){let t;try{t=Pe(y().host)}catch(e){return w(`auth logout: invalid API host — ${T(e)}`)}let[n,r]=await Promise.all([fi(t),hi(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`?b(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...w(`auth logout: ${i[0]}`),data:a}:b(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function fi(e){let t=await we(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await mi(t.stored):{revoked:!1};try{await Oe(e)}catch(e){return{state:`failed`,summary:T(e)}}return{state:`forgotten`,...n}}async function pi(e){let t=Reflect.get(await lt(e),`revocation_endpoint`);return typeof t==`string`?Ee(t,`revocation endpoint`,!0):void 0}async function mi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await pi(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:Te(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:T(e,Ce(n))}}}async function hi(e,t){let n;try{n=await Ie(e)}catch(e){return w(`auth logout: stored credential could not be read — ${T(e)}`)}if(n.state===`unavailable`)return{...w(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await gi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...w(`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:_i(r,!1,!1)};try{await Je(r.host)}catch(e){return{...w(`auth logout: local credential removal failed — ${T(e,[r.credential.secret])}`,[a?"The remote key is revoked. Re-run with `--forget-local` to retry local cleanup.":`Remote revocation was not confirmed; inspect auth status before retrying.`]),data:_i(r,a,!1)}}return b(a?`Personal CLI credential 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.`:`Personal CLI credential removed locally without confirmed remote revocation.`,_i(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the personal key may remain active.`]})}async function gi(e){let t=Ae(y());try{let n=await le(t,{method:ui.method,path:me(ui.path,{},ui.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Ne);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 personal 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:T(t,[e.credential.secret])}}}function _i(e,t,n){return{host:e.host,personalApiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var vi=`RSA_OAEP_256_A256_GCM_V1`,yi=1,bi=30,xi=C().bin[0],Si=`The local record remains pending and unavailable to ordinary commands. Re-run \`${xi} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ci(e){if(!yt.isTTY)return w(`${xi} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject CLIENT_SECRET, ADMIN_API_KEY, or AUTH_TOKEN through the environment or configured Doppler source.`]);let t,n;try{let e=y().host;t=Pe(e),n=je(e)}catch(e){return w(`auth login --key: invalid environment configuration — ${T(e)}`)}for(;;){let e;try{e=await Xe(t)}catch(e){return w(`auth login --key: credential storage could not be inspected — ${T(e)}`)}if(e.state===`unavailable`)return w(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use CLIENT_SECRET, ADMIN_API_KEY, or AUTH_TOKEN from the environment.`]);if(e.state===`missing`){e.keyringFailure!==void 0&&N.write(be(e.keyringFailure));break}let n=await wi(e.stored);if(n!==null)return n}let r;try{r=await Ur()}catch(e){return w(`auth login --key: ephemeral encryption key could not be created — ${T(e)}`)}let i=Vr.safeParse({clientLabel:e.clientLabel?.trim()||(ht().trim()||`aventure-cli`).slice(0,120),clientPlatform:Oi(),encryptionAlgorithm:vi,encryptionPublicKey:r.publicKey});if(!i.success)return w(`auth login --key: local authorization input is invalid`);let a;try{a=await ri(i.data)}catch(e){return w(`auth login --key: could not start browser authorization — ${T(e)}`)}let o;try{o=st(a,n)}catch(e){return w(`auth login --key: unsafe browser authorization URL rejected — ${T(e)}`)}if(!Di(await at(a,n,{noBrowser:e.noBrowser}),a,o))return w(`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 Ei(a)}catch(e){return w(`auth login --key: authorization did not complete — ${T(e)}`,[],{references:[o]})}if(s.algorithm!==vi)return w(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await Wr(r.privateKey,s)}catch(e){return w(`auth login --key: encrypted credential could not be opened — ${T(e)}`)}let l=await li(c);if(l.state!==`verified`)return w(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await Ye(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return w(`auth login --key: credential could not be durably stored — ${T(e)}`)}let d;try{d=await Ti(a)}catch(e){return H(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${T(e,[a.pollSecret])}`,Si)}if(d.status!==`CONSUMED`)return H(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Si);let f=await li(c);if(f.state!==`verified`||!Mi(f.apiKey,u.credential.apiKey))return H(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Si);try{let e=await Ye(t,{apiKey:f.apiKey,secret:c},`active`);return b(`Personal CLI credential stored; authenticated identity and broker acknowledgment verified.`,ji(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return H(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${T(e)}`,Si)}}async function wi(e){let t=await li(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?b(`Personal CLI credential is already stored and its authenticated identity was verified.`,ji(e,!0),{ids:[e.credential.apiKey.id]}):H(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${xi} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&Mi(t.apiKey,e.credential.apiKey))try{let n=await Ye(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return b(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,ji(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return H(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${T(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${xi} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return H(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${xi} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await gi(e);if(n.outcome===`unconfirmed`)return H(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await Je(e.host)}catch(t){return H(e,!1,`auth login --key: stale pending credential could not be removed — ${T(t,[e.credential.secret])}`)}return N.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
6
- `:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
7
- `),null}async function Ti(e){let t=new Date(e.expiresAt).getTime(),n=ki(e.intervalSeconds);for(;;)try{return await ai(e.id,e.pollSecret)}catch(e){if(e instanceof ti){if(!e.retryable)throw e;n=ki(e.retryAfterSeconds??n)}else if(!(e instanceof ni))throw e;if(Date.now()>=t)throw e;N.write(`Broker acknowledgment was interrupted; retrying.
8
- `),await Ai(n,t)}}async function Ei(e){let t=new Date(e.expiresAt).getTime(),n=ki(e.intervalSeconds),r;for(N.write(`Waiting for browser approval...
9
- `);Date.now()<t;){let i;try{i=await ii(e.id,e.pollSecret)}catch(e){if(e instanceof ti){if(!e.retryable)throw e;n=ki(e.retryAfterSeconds??n)}r=e,N.write(`Authorization poll was interrupted; retrying.
10
- `),await Ai(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=ki(i.retryAfterSeconds??n),await Ai(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(ce(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${T(r,[e.pollSecret])}`)}function Di(e,t,n){let r=e.state===`opened`;return!r&&!N.isTTY?!1:(N.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...N.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
11
- `)),!0)}function Oi(){switch(gt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function ki(e){return Math.min(bi,Math.max(yi,e))}async function Ai(e,t){let n=t-Date.now();n>0&&await Pt(Math.min(e*1e3,n))}function ji(e,t){return{host:e.host,provider:e.provider,personalApiKeyId:e.credential.apiKey.id,name:ce(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function H(e,t,n,r){return{...w(n,r===void 0?[]:[r]),data:ji(e,t)}}function Mi(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)}function Ni(e,t){let n=t.state===`found`?t.stored:void 0,r=n?.credential.apiKey.expiresAt??null;return{host:e,present:n!==void 0,provider:n?.provider??null,activation:n?.activation??null,apiKeyId:n?.credential.apiKey.id??null,subject:n?.credential.apiKey.subject??null,scope:n?.credential.apiKey.scopes??[],name:n===void 0?null:ce(n.credential.apiKey.name,[n.credential.secret]),status:n?.credential.apiKey.status??null,expiresAt:r,metadataSource:n===void 0?null:`store-cache`,expiresInDay:Fi(r),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}var Pi=864e5;function Fi(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/Pi)}var Ii=7;function Li(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,Ii)}\u2026${e.slice(-4)}`}var Ri=13,zi=14;function Bi(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.personal.host}`+(e.apiVersion===null?` (api unreachable)`:` (api ${e.apiVersion})`),``,...Vi(e.oauth,e.cliName),...Hi(e.personal,e.oauth,e.cliName),``,U(`Providers`,Gi(e.providers)),...Ki(e.resolved,e.config),...e.systemOk?[]:[U(`System`,`uptime read failed`)]].join(`
12
- `)}function U(e,t){return` ${e.padEnd(Ri)}${t}`}function W(e){return` ${``.padEnd(Ri)}${e}`}function Vi(e,t){switch(e.state){case`found`:return[U(`OAuth`,`stored via ${e.stored.provider}; identity is not cached`),W(De(e.stored.credential)?e.stored.credential.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:`access token expired — the next command renews it with the refresh token`:`cached expiry ${e.stored.credential.expiresAt}`)];case`missing`:return[U(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[W(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[U(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[U(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function Hi(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[U(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[W(`stored credential invalid: ${e.error}`)]]:[U(`Signed in`,`credential storage unavailable`),W(r)]}return[U(t.state===`found`?`Personal key`:`Signed in`,e.subject??`unknown subject`),W(`via ${e.provider??`unknown store`}`),U(`Key`,`${e.name??`unnamed`} ${Li(e.apiKeyId)}`),...Ui(e,n),U(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ui(e,t){let n=`${e.status??`unknown`} when stored`,r=e.expiresInDay,i=e.expiresAt===null?null:e.expiresAt.slice(0,10);return[U(`Key state`,n),...i===null||r===null?[W(`no expiry recorded`)]:[W(Wi(i,r))],W(`Clerk owns the live verdict \u2014 \`${t} auth login --key\` refreshes this cache`)]}function Wi(e,t){return t<0?`cached expiry ${e} passed ${Math.abs(t)}d ago`:t<=zi?`cached expiry ${e}, ${t}d away`:`cached expiry ${e}`}function Gi(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 ${Se(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Ki(e,t){return[U(`Secrets`,v.map(t=>Ji(t,e)).join(` `)),U(`Config`,t===null?`none`:`doppler ${t.project}/${t.config}`)]}function qi(e){return v.map(t=>Ji(t,e)).join(` `)}function Ji(e,t){let n=t[e];return n.present?`${e}=${n.source??`resolved`}`:`${e}=${n.source===`config`?`config (unresolved)`:`unset`}`}var Yi=r([`PROMPT`,`SKILL`,`AGENT`]),Xi=a({kind:Yi,name:e(),version:e()}),Zi=a({content:e(),core:Xi}),Qi=a({key:e(),version:e()}),$i=a({agent:o(e(),Qi),prompt:o(e(),Qi),skill:o(e(),Qi)}),G=`aventure`,ea=`SKILL.md`,ta=`.aventure-skills.json`,na=`claude`,ra=2e4,ia=2,aa=[{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 oa(e){return P(sa(e))}function sa(e){return A(ua(e),...e.detect)}function ca(e){return e.skill===null?null:A(ua(e),...e.skill)}function la(e){return A(ua(e),...e.mcp.file)}function ua(e){return e.base===`home`?fa(`HOME`)??mt():da()}function da(){return fa(`XDG_CONFIG_HOME`)??A(fa(`HOME`)??mt(),`.config`)}function fa(e){let t=process.env[e]?.trim();return t===void 0||t.length===0?void 0:t}function pa(e){return A(k(e),ta)}function ma(e){if(!P(e))return{};try{let t=$i.safeParse(JSON.parse(F(e,`utf8`)));return t.success?t.data.skill:{}}catch{return{}}}function ha(e,t,n){let r=pa(e),i={...ma(r)};for(let e of n){let n=t.skill[e];n!==void 0&&(i[e]=n)}return _a(r,`${JSON.stringify({prompt:{},skill:i,agent:{}},null,ia)}\n`)}function ga(e,t,n){let r=A(e,t,ea);return k(k(r))===e?_a(r,n):`refusing to install ${t}: it does not name one directory inside ${e}`}function _a(e,t){try{va(e,t)}catch(t){return`cannot write ${e}: ${T(t)}`}return null}function va(e,t){Ct(k(e),{recursive:!0});let n=`${e}.aventure-tmp`;try{I(n,t,`utf8`),Dt(n,e)}finally{Ot(n,{force:!0})}}var ya=RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*"?${G}"?[ \\t]*\\]`),ba=/^[ \t]*mcp_servers[ \t]*=/m;function xa(e){let t=la(e);if(!P(t))return null;try{let n=F(t,`utf8`);if(e.mcp.shape===`toml`)return Ca(n);let r=Oa(n)?.[e.mcp.key],i=(r!==void 0&&ka(r)?r:void 0)?.[G];return i===void 0||!ka(i)?null:typeof i.url==`string`?i.url:Sa}catch{return null}}var Sa=`unknown`;function Ca(e){let t=e.split(`
13
- `),n=t.findIndex(e=>ya.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 Sa}function wa(e,t){let n=e.mcp,r=la(e);if(n.shape===`claude-cli`)return Da(t);try{if(n.shape===`toml`)return Ta(r,t);Ea(r,n.key,n.entry(t))}catch(e){return`cannot write ${r}: ${T(e)}`}return null}function Ta(e,t){let n=P(e)?F(e,`utf8`):``,r=`[mcp_servers.${G}]\nurl = "${t}"\n`;return ba.test(n)?`${e} declares mcp_servers as an inline table, which this command cannot extend; add by hand:\n${r}`:_a(e,`${n}${n.length===0||n.endsWith(`
14
- `)?``:`
15
- `}\n${r}`)}function Ea(e,t,n){let r=Oa(P(e)?F(e,`utf8`):`{}`);if(r===null)throw Error(`${e} is not a JSON object`);let i={...r},a=i[t];i[t]={...a!==void 0&&ka(a)?a:{},[G]:n},va(e,`${JSON.stringify(i,null,ia)}\n`)}function Da(e){let t=[`mcp`,`add`,`--transport`,`http`,`-s`,`user`,G,e],n=ut(na,t,{encoding:`utf8`,timeout:ra}),r=`${na} ${t.join(` `)}`;if(n.error!==void 0)return`run \`${r}\`: ${n.error.message}`;if(n.status!==0){let e=(n.stderr??``).trim().split(`
16
- `).slice(-2).join(` | `);return`\`${r}\` exited ${n.status}: ${e||`no stderr`}`}return null}function Oa(e){let t=l.safeParse(JSON.parse(e));return t.success&&ka(t.data)?t.data:null}function ka(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Aa=`aventure`;function ja(e,t=C().bin[0]){D(Ma(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 (${aa.map(e=>e.name).join(`, `)}),`,`install or refresh the published ${Aa}* skill bundle into each runtime's own`,`skill directory, and register the ${G} 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(`
17
- `)).addOption(new u(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`).default(!1)).addOption(new u(`--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:E(e)},await Na(e))})}function Ma(e){let t=`agents`,n=e.commands.find(e=>e.name()===t);if(n!==void 0)return n;let r=Ve[t]?.summary??t;return e.command(t).summary(r).description(r)}async function Na(e){let t=Ga();if(!t.ok||t.data===null)return{...t,data:null};let n=await Ua(`getAgentInstructionManifest`,$i);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(Aa)).toSorted();if(a.length===0)return w(`The agent instruction manifest carries no ${Aa}* skill; nothing to install.`);let o=aa.map(e=>La(e,r,a,i));return Pa({runtime:e.status===!0?o:await za(o,r,i)},e,i)}function Pa(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(Fa)].join(`
18
- `);if(r.length===0){let t=aa.map(e=>`${e.name}: no ${sa(e)}`);return{...w(s,t,{counts:o}),data:e}}let c=a.length>0?a:t.status===!0?i:[];return c.length===0?b(s,e,{counts:o}):{...w(s,c.map(Ia),{counts:o}),data:e}}function Fa(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(Ia).join(`; `)}`}function Ia(e){return`${e.kind} ${e.name} ${e.state}: ${e.detail}`}function K(e,t,n,r){return{kind:e,name:t,state:n,detail:r}}function La(e,t,n,r){let i=ca(e),a=la(e),o={name:e.name,skillDir:i,mcpConfig:a};if(!oa(e))return{...o,detected:!1,action:[]};let s=xa(e),c=s===null?K(`mcp`,G,`install`,`register ${r} in ${a}`):K(`mcp`,G,`current`,`${s} in ${a}`);return{...o,detected:!0,action:[...i===null?[]:Ra(i,t,n),c]}}function Ra(e,t,n){let r=ma(pa(e));return n.map(n=>{let i=t.skill[n]?.version??``,a=r[n]?.version,o=A(e,n,ea);return a===void 0||!P(o)?K(`skill`,n,`install`,`write ${o} at version ${i}`):a===i?K(`skill`,n,`current`,`${o} at version ${i}`):K(`skill`,n,`update`,`${o} ${a} -> ${i}`)})}async function za(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 Ha(e));return e.map(e=>{let r=aa.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 Ba(r,e.mcpConfig,n);let o=Va(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:ha(e.skillDir,t,a),c=s===null?[]:[K(`skill`,ta,`failed`,s)];return{...e,action:[...o,...c]}})}function Ba(e,t,n){let r=wa(e,n);return r===null?K(`mcp`,G,`current`,`registered ${n} in ${t}`):K(`mcp`,G,`failed`,r)}function Va(e,t,n){if(e===null||n===void 0||!n.ok||n.data===null)return K(`skill`,t,`failed`,n?.summary??`no document fetched for ${t}`);let r=ga(e,t,n.data.content);return r===null?K(`skill`,t,`current`,`${A(e,t,ea)} at version ${n.data.core.version}`):K(`skill`,t,`failed`,r)}async function Ha(e){return await Ua(`getAgentInstruction`,Zi,{kind:Yi.enum.SKILL,name:e})}async function Ua(e,t,n={}){let r=Wa(e);if(r===void 0)return w(`The generated command catalog carries no ${e} operation; regenerate it with \`make mcp-generate-contracts\` and reinstall.`);let i;try{i=pe(r.operationId,n)}catch(t){return w(`Cannot address ${e}: ${T(t)}`)}let a=await S({method:r.method,path:i,auth:r.auth,responseFormat:`json`}).catch(e=>w(T(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?b(`${r.method} ${i} answered`,s.data):w(`${i} returned an unexpected body: ${s.error.message}`)}function Wa(e){return O.find(t=>t.operationId===e)}function Ga(){try{return b(`MCP host derived`,Qe(y().host,`/mcp`).href)}catch(e){return w(`Correct API_ENV or pass \`--environment <name>\` — ${T(e)}.`)}}var Ka=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,qa=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Ja=`.aventure-cli-completion.bak`;function Ya(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>no([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>no([`--uninstall`]))}function Xa(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=eo(),n=await $a({rcFile:j(mt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:mo});M.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&no(e.uninstall?[`--uninstall`]:[])})}function Za(e,t=`fpath-only`){return[Ka,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],qa].join(`
19
- `)}function Qa(){let e=no([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!ro(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=no([],`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 $a({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=io(e),o=a.length===0?[]:a.split(`
20
- `),s=ao(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?oo(o,s,t,e):so(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}:(uo(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function eo(e=M.argv[1]){let t=e===void 0?``:to(e),n=j(k(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return P(n)?n:j(k(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function to(e){try{return Et(e)}catch{return j(e)}}function no(e,t=`inherit`){let n=ut(M.execPath,[eo(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(M.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function ro(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function io(e){return P(e)?(fo(e),F(e,`utf8`)):``}function ao(e,t){let n=co(e,Ka),r=co(e,qa);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 oo(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=lo(i),o=Za(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
21
- `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return po([...i.slice(0,c),...o,...i.slice(c)])}function so(e,t){return po(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function co(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function lo(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function uo(e,t){Ct(k(e),{recursive:!0}),P(e)&&(fo(e),fo(`${e}${Ja}`),xt(e,`${e}${Ja}`));let n=j(k(e),`.${_t(e)}.${M.pid}.tmp`);fo(n),I(n,t,{mode:420}),Dt(n,e)}function fo(e){if(P(e)&&St(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function po(e){let t=e.join(`
22
- `);return t.length===0||t.endsWith(`
23
- `)?t:`${t}\n`}async function mo(e){let t=Ft({input:M.stdin,output:M.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var ho=new Intl.Collator(void 0,{numeric:!0}),go=2e4;function _o(e,t=C()){let n=t.bin[0],r=t.registry===`https://npm.pkg.github.com/`?`Requires npm authentication for @aventurevc packages.`:`Installs from the public npm registry; no credential required.`;D(e.command(`update`).summary(`Check for or install the latest ${n} 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). ${r}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
24
- `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>R({mode:E(e)},vo()))}function vo(e,t=`apply`){let n=e;try{n??=C(process.argv[1])}catch(e){return w(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,a=yo([`view`,g,`version`,`--silent`,`--global`],n,{timeout:go});if(!a.ok)return{...a,data:null};let o=(a.data??``).trim();if(o===``)return w(`npm view ${g} returned empty version`,[`empty_stdout`]);let s=ho.compare(i,o)<0,c={targetPackage:g,runningPackage:r,currentVersion:i,latestVersion:o,upgradeAvailable:s,upgradeInstalled:!1};if(t===`check`)return b(`${r}@${i} → ${g}@${o} (${s?`available`:`up to date`})`,c);if(!s)return b(`${r}@${i} already matches ${g}@${o}`,c);if(n.workingTreeRoot!==null)return w(`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 l=xo(n),u;try{u=So(n,l)}catch(e){return w(`Cannot prepare MCP-owned CLI bins: ${To(e)}`,[`npm install was not run`])}let d=[`install`,`-g`];l!==null&&d.push(`--prefix`,l.installPrefix),d.push(`${g}@${o}`);let f=yo(d,n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!f.ok){let e=Co(u,l?.installPrefix??null);return e===null?{...f,data:null}:w(`${f.summary}; MCP-owned CLI bin restoration failed`,[...f.warnings,e])}let p=l===null?void 0:bo(l.entryPath,o);if(p?.ok===!1){let e=Co(u,l?.installPrefix??null);return e===null?{...p,data:null}:w(`${p.summary}; MCP-owned CLI bin restoration failed`,[...p.warnings,e])}let m=wo(u);if(m!==null)return w(`${g} upgraded but MCP CLI bin backup cleanup failed`,[m]);let h=Eo();return b(`${g} upgraded to ${o}`,{...c,upgradeInstalled:!0,installPrefix:l?.installPrefix,verifiedVersion:p?.data??void 0,completionRefreshed:h.refreshed,completionRefreshMessage:h.message})}function yo(e,t,n={}){let r={...process.env};t.registry===`https://npm.pkg.github.com/`?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=ut(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?w(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):w(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
25
- `).slice(-3).join(` | `);return w(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return b(`npm ok`,a.stdout??``)}function bo(e,t){let n=ut(process.execPath,[e,`--version`],{encoding:`utf8`});if(n.error)return w(`updated ${g} verification failed: ${n.error.message}`,[`spawn_error`]);let r=(n.stdout??``).trim();if(n.status!==0||r!==t){let i=(n.stderr??``).trim().split(`
26
- `).slice(-3).join(` | `);return w(`updated ${g} verification expected ${t} but active bin reported ${r||`empty output`}`,[i||`active bin: ${e}`])}return b(`active CLI version verified`,r)}function xo(e){let t=`${vt}lib${vt}node_modules${vt}${e.name.replace(`/`,vt)}`,n=e.packageRoot.lastIndexOf(t),r=e.bin.includes(`aventure-cli`)?`aventure-cli`:e.bin[0];return n<0?null:{entryPath:j(e.packageRoot.slice(0,n),`bin`,r),installPrefix:e.packageRoot.slice(0,n)}}function So(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}${vt}`))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=j(t.installPrefix,`bin`,n),i=St(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=Et(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:Tt(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=wt(j(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:j(r,_t(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(Dt(e.binPath,e.backupPath),a.push(e),Tt(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=Co({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 Co(e,t){let n=t===null?null:j(t,`lib`,`node_modules`,...g.split(`/`)),r=[];for(let t of e.backup.toReversed())try{let e=St(t.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${t.binPath} is not a symlink`);let r=j(k(t.binPath),Tt(t.binPath));if(n===null||r!==n&&!r.startsWith(`${n}${vt}`))throw Error(`${t.binPath} is not owned by the standalone CLI package`);At(t.binPath)}Dt(t.backupPath,t.binPath)}catch(e){r.push(To(e))}if(e.backupDirectory!==null)try{kt(e.backupDirectory)}catch(e){r.push(To(e))}return r.length===0?null:r.join(`; `)}function wo(e){let t=[];for(let n of e.backup)try{At(n.backupPath)}catch(e){t.push(To(e))}if(e.backupDirectory!==null)try{kt(e.backupDirectory)}catch(e){t.push(To(e))}return t.length===0?null:t.join(`; `)}function To(e){return e instanceof Error?e.message:String(e)}function Eo(){try{return Qa()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var Do=[{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`}],Oo=`operationFingerprint`;function ko(e,t=C().bin[0]){D(e.command(`doctor`).summary(`One-call selftest: CLI version, schemas, API host, auth scope, command catalog`).description(["Run every environment check in one call and report `{ ok, check: [...] }`:",...Do.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable)`,`does not fail the run. Each failing message names the command that fixes it.`,"--json always carries the report at `.data`; --data prints the report directly when",`every check passes and the result envelope when one fails, like every other command.`].join(`
27
- `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),R({mode:E(e)},await Ao(t))})}async function Ao(e){let t=Mo(),n=No(e),[r,i]=await Promise.all([Po(e),Fo(t,e)]),a=[n.check,r,i.check,await Lo(e),Wo(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:jo(a,`pass`),fail:jo(a,`fail`),skip:jo(a,`skip`)},s=a.filter(e=>e.status===`fail`).map(e=>e.message),c={ok:s.length===0,check:a},l=[`doctor: ${o.pass} pass, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
28
- `);return c.ok?b(l,c,{counts:o}):{...w(l,s,{counts:o}),data:c}}function jo(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function Mo(){return O.find(e=>e.intent===`status`&&e.resource===`status`)}function No(e){let t=C(),n=vo(t,`check`);if(!n.ok||n.data===null)return{check:q(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?q(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):q(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function Po(e){try{let{EntityDetailSchema:e}=await import(`./detail-DeMsv_6C.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return q(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return q(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${T(t)}.`)}}async function Fo(e,t){if(e===void 0)return{check:q(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=y().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${T(e)}.`),servedFingerprint:null}}let r=await S({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>w(T(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:Io(r.data)}:{check:q(`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 Io(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[Oo];return typeof n==`string`&&n.length>0?n:null}async function Lo(e){await ue();let t;try{t=m(await p())}catch(t){return q(`auth`,`fail`,`Repair or remove ${x()} and run \`${e} auth init\` — ${T(t)}.`)}let[n,r]=await Promise.all([Ro(),zo()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t[d.authToken].present,a=v.some(e=>t[e].present);return!i&&n.state===`invalid`?q(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&De(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?q(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!a&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${d.authToken} through the environment — ${n.summary}.`):a||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${Bo(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${v.join(`/`)} through the environment — ${r.summary}.`):v.some(e=>t[e].source===`config`)?q(`auth`,`fail`,`The Doppler source in ${x()} resolved no credential: confirm your access to that project and config, or inject ${v.join(`/`)} through the environment.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth, \`${e} auth login --key\` for a personal credential, or \`${e} auth init\` to select a Doppler source.`)}async function Ro(){let e;try{e=ke(y().host)}catch(e){return{state:`unavailable`,summary:T(e)}}return await xe(e)}async function zo(){let e;try{e=Pe(y().host)}catch(e){return{state:`unavailable`,summary:T(e),cause:`environment`}}try{return await Xe(e)}catch(e){return{state:`unavailable`,summary:T(e),cause:`storage`}}}function Bo(e,t,n){return[...v.map(t=>`${t}=${Vo(e,t)}`),`oauth=${Uo(t)}`,`personal=${Ho(n)}`].join(` `)}function Vo(e,t){let n=e[t];return n.present?n.source??`resolved`:n.source===`config`?`config (unresolved)`:`unset`}function Ho(e){return e.state===`found`?e.stored.activation:e.state===`missing`?`unset`:`unavailable`}function Uo(e){switch(e.state){case`found`:return De(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function Wo(e,t,n,r){let i=O.length;if(e===void 0)return q(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return q(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${We}.`);if(t===`c978c45f5233b6b9`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${We}).`);let a=`This catalog describes a different operation set than the API serves (${We} vs ${t})`;return n===!0?q(`catalog`,`fail`,`${a}: run \`${r} update\`.`):q(`catalog`,`skip`,n===!1?`${a}, and this CLI is already the latest published release: either the deployed API is older than this CLI, or a newer CLI has not been published yet.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var Go=B(V,`oauth`),Ko=[B(V,`start`),B(V,`poll`),B(V,`acknowledge`)],qo=B(V,`revoke`),Jo=`personal-login`,Yo=`personal-logout`;function Xo(e,t=C().bin[0]){let n=Qo(e);ko(n,t),ja(e,t);let r=[`${Go.description} Default method: OAuth in your browser.`,`With --key: ${Ko.map(({description:e})=>e).join(` `)}`].join(`
29
- `),i=async function(e){$o(this),R({mode:E(e)},e.key===!0?await Ci({noBrowser:!e.browser,clientLabel:e.clientLabel}):await ct({noBrowser:!e.browser},t))};D(Zo(n,[Go,...Ko],r)).action(i),D(Zo(n,[...Ko],r,Jo)).action(async function(e){await i.call(this,{...e,key:!0})});let a=async function(e){$o(this),R({mode:E(e)},await di({forgetLocal:e.forgetLocal===!0}))};D(Zo(n,[qo],qo.description)).action(a),D(Zo(n,[qo],qo.description,Yo)).action(a),D(n.command(`init`).summary(`Interactive credential setup`).description([`Interactively record the Doppler project/config used by ${t} + the MCP server.`,`Credentials resolve from the injected environment first, then Doppler; auth init never writes credentials to disk.`,``,`Prompts go to stderr so stdout stays reserved for the result envelope.`].join(`
30
- `))).action(async function(e){$o(this),R({mode:E(e)},await ss(t))}),D(n.command(`status`).summary(`Local credential provenance, API build, and server uptime`).description([`Reports local credentials plus two independent remote health signals:`,` - auth: per-credential local provenance (env vs ~/.config/aventure/config.json vs unset)`,` - oauth: stored OAuth access-token metadata for the selected API host, without the token`,` - personal: stored personal-key metadata for the selected API host, without the secret`,` - 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)`,``,`No headers are sent to the server. Credential provenance is computed locally; this`,`answers whether service credentials, OAuth, or a personal CLI credential are wired without exposing them.`,`To prove a credential survives transit, call any real endpoint that requires it.`].join(`
31
- `))).action(async function(e){$o(this),R({mode:E(e)},await es(t))})}function Zo(e,t,n,r){let[i]=t,a=e.command(r??i.command.slice(i.command.indexOf(` `)+1),{hidden:r!==void 0}).summary(i.summary).description(n),o=new Set;for(let e of t)for(let t of[...e.bodyOption,...e.localOption])o.has(t.flag)||(o.add(t.flag),`required`in t&&t.required?a.requiredOption(t.flag,t.description):a.option(t.flag,t.description));return a}function Qo(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Authentication, credential setup, API build, and uptime`).description([`\`${Go.command}\`: ${Go.summary}; \`--key\` ${Ko[0].summary.toLowerCase()}.`,`\`${qo.command}\`: ${qo.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 init` configures the local Doppler source used by generated API commands."].join(`
32
- `))}function $o(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function es(e){let t;try{t=await p()}catch(t){return w(`auth status: cannot read ${x()} — ${t instanceof Error?t.message:String(t)}`,[`configPath=${x()}`,`errorName=${t instanceof Error?t.name:`Error`}`,...gs(e)])}let n;try{n=ke(y().host)}catch(e){return w(`auth status: invalid API host — ${T(e)}`)}let[r,i,a,o,s]=await Promise.all([os(`/v1/status`,`GET /v1/status`),os(`/info`,`GET /info`),xe(n),rs(n),ns()]),c=m(t),l=C().version,u=Ni(n,o),d=Bi({cliName:e,cliVersion:l,apiVersion:i.ok?is(i.data):null,oauth:a,personal:u,providers:s,resolved:c,config:t,systemOk:r.ok}),f={cli:{version:l},api:i.ok?i.data??null:null,auth:ds(t,c),oauth:ts(n,a),personal:u,providers:s,system:r.ok?r.data??null:null,...i.ok?{}:{apiError:i.summary},...r.ok?{}:{systemError:r.summary}};return fs(c)||a.state===`found`||o.state===`found`?b(d,f):ps(`auth status: no credentials resolved | ${d}`,f,e,{oauth:a.state===`missing`,personal:o.state===`missing`})}function ts(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:De(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}async function ns(){try{return{state:`found`,catalog:await ot()}}catch(e){return{state:`unavailable`,summary:T(e)}}}async function rs(e){try{return await Xe(e)}catch(e){return{state:`invalid`,summary:T(e)}}}function is(e){if(!as(e))return null;let t=Rr.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 as(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function os(e,t){return await S({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>w(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}async function ss(e){if(!yt.isTTY)return w(`${e} auth init requires an interactive TTY on stdin`,["non-interactive caller: hand-write `~/.config/aventure/config.json` directly",...gs(e)]);let t=Ft({input:yt,output:N});try{N.write(`${e} auth init\n\n`);let n=await cs(t);try{await ee(n)}catch(t){return w(`auth init: cannot write ${x()} — ${t instanceof Error?t.message:String(t)}`,[`configPath=${x()}`,`errorName=${t instanceof Error?t.name:`Error`}`,...gs(e)])}return await ue(),us(`saved`,n,e)}finally{t.close()}}async function cs(e){return{source:`doppler`,project:await ls(e,`Doppler project: `),config:await ls(e,`Doppler config (e.g. staging): `)}}async function ls(e,t){for(;;){let n=(await e.question(t)).trim();if(n.length>0)return n;N.write(` required
33
- `)}}function us(e,t,n){let r=m(t),i=`${hs(e,t,r)} | ${ms()}`,a=ds(t,r);return fs(r)?b(i,a):ps(`no credentials resolved | ${i}`,a,n)}function ds(e,t){return{configPath:x(),configSource:e?.source??null,...e?.source===`doppler`?{configProject:e.project,configConfig:e.config}:{},resolved:t}}function fs(e){return v.some(t=>e[t].present)}function ps(e,t,n,r={oauth:!0,personal:!0}){return{...w(e,[...r.personal?[`For a personal key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\` in an interactive terminal.`]:[],C().registry===`https://registry.npmjs.org/`?`For non-interactive use, set AUTH_TOKEN to a personal API key in the environment.`:`Run \`${n} auth init\` to select Doppler, or inject credentials through the environment.`]),data:t}}function ms(){return`read=${s(`read`).ok?`available`:`unavailable`} write=${s(`write`).ok?`available`:`unavailable`}`}function hs(e,t,n){return`${e}: ${qi(n)} | ${t===null?`no config`:`doppler ${t.project}/${t.config}`}`}function gs(e){return[`no config at the path above — run \`${e} auth init\` in an interactive terminal, or write a non-secret Doppler source config:`,` {"auth":{"source":"doppler","project":"<project>","config":"<config>"}}`,`legacy inline configs are rejected; move credentials to Doppler or the environment before replacing the config.`]}function _s(e,t,n=C().bin[0]){let r=Tr(t),i=e.find(e=>e.cliPath.join(` `)===r||e.cliAliasPath?.join(` `)===r||e.operationId===r);return i===void 0?w(`No generated operation matches "${t}"`,[`Resolve the exact command with \`${n} command-catalog search "<query>"\`.`]):b(`Resolved ${i.operationId}`,i)}function vs(e){return e.parameters.some(e=>e.location===`path`)?w(`${e.operationId} has path parameters and cannot be batch-driven`,[e.path]):b(`no path parameters`,null)}function ys(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)return w(`--query expects key=value, got "${n}"`);t[n.slice(0,e)]=n.slice(e+1)}return b(`query parsed`,t)}function bs(e,t,n,r){let i=Number(t);return!Number.isInteger(i)||i<n||i>r?w(`${e} must be an integer between ${n} and ${r}, got "${t}"`):b(`${e} parsed`,i)}function xs(e){let t=l.safeParse(e);return t.success?t.data:void 0}function Ss(e,t){let n=xs(e);for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function Cs(e){let t=xs(e);return typeof t!=`object`||!t||Array.isArray(t)?null:t}function ws(e){return typeof e==`object`&&e&&`response`in e?xs(e.response):xs(e)}function Ts(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Es(e){if(!P(e))return w(`--input file not found: ${e}`);let t=F(e,`utf8`),n=[],r=t.split(`
34
- `);for(let[e,t]of r.entries()){if(t.trim()===``)continue;let r=l.safeParse(As(t));if(!r.success)return w(`--input line ${e+1} is not valid JSON`,[t.slice(0,120)]);n.push(r.data)}return n.length===0?w(`--input has no NDJSON rows: ${e}`):b(`input parsed`,{row:n,digest:js(t)})}function Ds(e,t,n){let r={inputDigest:t,chunkSize:n,completedChunk:[]};if(e===void 0||!P(e))return b(`no checkpoint`,r);let i=As(F(e,`utf8`));if(i===void 0)return w(`--checkpoint file is not valid JSON: ${e}`);let a=Ss(i,`inputDigest`),o=Ss(i,`chunkSize`),s=Ss(i,`completedChunk`);if(a!==t||o!==n)return w(`--checkpoint ${e} was written for different input or chunk size`,[`Delete the checkpoint to start over, or restore the original input file.`]);if(!Array.isArray(s))return w(`--checkpoint ${e} has an invalid completedChunk list`);let c=s.filter(e=>Number.isInteger(e));return c.length===s.length?b(`checkpoint loaded`,{inputDigest:t,chunkSize:n,completedChunk:c}):w(`--checkpoint ${e} has an invalid completedChunk list`)}function Os(e,t,n,r){if(e===void 0)return;let i={inputDigest:t,chunkSize:n,completedChunk:[...r].toSorted((e,t)=>e-t)};I(e,`${JSON.stringify(i)}\n`)}function ks(e,t){return[...t,e]}function As(e){try{return JSON.parse(e)}catch{return}}function js(e){return dt(`sha256`).update(e).digest(`hex`)}function Ms(e,t,n=C().bin[0]){let r=e.command(`batch`).summary(`Export reads to NDJSON files and run bulk NDJSON writes`).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.`);Ns(r,t,n),Ps(r,t,`preview`,n),Ps(r,t,`run`,n)}function Ns(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(`
35
- `)).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`,ks,[]).requiredOption(`--out <path>`,`NDJSON output file; overwritten at start`).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`);D(r),r.action(async function(){let e=this.optsWithGlobals();R({mode:E(e)},await Fs(t,e,n))})}function Ps(e,t,n,r){let i=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(`
36
- `):`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`,ks,[]).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 u(`--no-halt-on-failure`,`keep sending remaining chunks after a failed chunk`));n===`run`&&i.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),D(i),i.action(async function(){let e=this.optsWithGlobals();R({mode:E(e)},await Is(t,e,n,r))})}async function Fs(e,t,n){let r=_s(e,t.command,n);if(!r.ok||r.data===null)return r;if(ne(r.data.intent))return w(`${t.command} is a write operation; use \`batch run\``,[r.data.path]);let i=vs(r.data);if(!i.ok)return i;let a=ys(t.query??[]);if(!a.ok||a.data===null)return a;let o=bs(`--max-pages`,t.maxPages,1,1e6);if(!o.ok||o.data===null)return o;let s=t.fromFile===void 0?void 0:await xn(t.fromFile);if(s!==void 0&&!s.ok)return s;let c=s===void 0?void 0:Cs(s.data);if(s!==void 0&&c===null)return w(`--from-file must contain a JSON object`,[t.fromFile??``]);I(t.out,``);let l=t.cursor,u=0,d=0,f=!1;for(;u<o.data;){let e={...a.data,...l===void 0?{}:{[t.cursorParam]:l}},n=await S({method:r.data.method,path:r.data.path,searchParams:e,body:c??void 0,auth:r.data.auth,responseFormat:`json`});if(!n.ok)return w(`page ${u+1} failed: ${n.summary}`,[`rows already written to ${t.out}: ${d}`,...l===void 0?[]:[`resume with --cursor "${l}"`]]);let i=ws(n.data),o=Ss(i,t.rowsPath);if(!Array.isArray(o))return w(`response has no array at --rows-path "${t.rowsPath}"`,[`page ${u+1}`]);bt(t.out,o.map(e=>`${JSON.stringify(e)}\n`).join(``)),u+=1,d+=o.length;let s=Ss(i,t.nextCursorPath);if(typeof s!=`string`||s===``||s===l){f=!0;break}l=s}return b(`${d} rows across ${u} pages written to ${t.out}${f?``:`; PARTIAL export — hit --max-pages ${o.data}, resume with --cursor "${l}"`}`,{outPath:t.out,exhausted:f,lastCursor:l},{counts:{pageCount:u,rowCount:d}})}async function Is(e,t,n,r){let i=_s(e,t.command,r);if(!i.ok||i.data===null)return i;if(!ne(i.data.intent))return w(`${t.command} is not a write operation; use \`batch export\``,[i.data.path]);let a=vs(i.data);if(!a.ok)return a;let o=ys(t.query??[]);if(!o.ok||o.data===null)return o;let s=bs(`--chunk-size`,t.chunkSize,1,1e4);if(!s.ok||s.data===null)return s;let c=bs(`--concurrency`,t.concurrency,1,8);if(!c.ok||c.data===null)return c;let l=t.base===void 0?void 0:await xn(t.base);if(l!==void 0&&!l.ok)return l;let u=Cs(l?.data??{});if(u===null)return w(`--base must contain a JSON object`,[t.base??``]);let d=Es(t.input);if(!d.ok||d.data===null)return d;let f=Ts(d.data.row,s.data),p=Ds(t.checkpoint,d.data.digest,s.data);if(!p.ok||p.data===null)return p;let m=new Set(p.data.completedChunk),h=[...f.keys()].filter(e=>!m.has(e));if(n===`preview`)return b(`PREVIEW — nothing sent. ${h.length} of ${f.length} chunks (${d.data.row.length} rows) would ${i.data.method} ${i.data.path}. Run ${r} batch run to send.`,{mode:`preview`,method:i.data.method,endpoint:i.data.path,arrayField:t.arrayField,outPath:t.out},{counts:{rowCount:d.data.row.length,chunkCount:f.length,pendingChunkCount:h.length,skippedChunkCount:m.size}});I(t.out,``,{flag:m.size>0?`a`:`w`});let ee=i.data,te=o.data,re=d.data.digest,g=s.data,_=[],v=!1,ie=0,ae=async e=>{let n=f[e]??[],r={...u,[t.arrayField]:n},i=await S({method:ee.method,path:ee.path,searchParams:te,body:r,auth:ee.auth,responseFormat:`json`}),a=i.ok?ws(i.data):null;return bt(t.out,`${JSON.stringify({chunk:e,rowCount:n.length,ok:i.ok,summary:i.summary,response:a??i.data??null})}\n`),i.ok?(m.add(e),Os(t.checkpoint,re,g,m),!0):(_.push(e),!1)};await Promise.all(Array.from({length:c.data},async()=>{for(;!v;){let e=h[ie];if(ie+=1,e===void 0)return;!await ae(e)&&t.haltOnFailure&&(v=!0)}}));let oe={rowCount:d.data.row.length,chunkCount:f.length,completedChunkCount:m.size,failedChunkCount:_.length,remainingChunkCount:f.length-m.size-_.length},y={outPath:t.out,checkpointPath:t.checkpoint,failedChunk:_,halted:v};return _.length>0?w(`${_.length} chunk(s) failed; responses in ${t.out}${t.checkpoint===void 0?``:`, resume via --checkpoint ${t.checkpoint}`}`,[JSON.stringify({...y,...oe})]):b(`${m.size}/${f.length} chunks sent; responses in ${t.out}`,y,{counts:oe})}function Ls(e,t=O,n=C().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{M.stdout.write(zs(e,i,t))});Ya(r,n),Xa(r,n)}function Rs(){return C().bin}function zs(e,t,n=O,r=Rs()){let i=Js(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Vs(e),...r.map(e=>`complete -c ${J(e)} -e`),`${oc(r)} -f`,...Hs(e,r),...Us(e,i,r),``].join(`
37
- `):Bs(e,t,i,r)}function Bs(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=Zs(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}`),`)`,``,...ec(t),...t===`bash`?[a,``]:[``]].join(`
38
- `)}function Vs(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Ws(e).filter(e=>e.required||e.optional).flatMap(e=>rc(e)??[]).map(J).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
39
- set -l expected $argv
40
- set -l actual (__aventure_cli_command_path)
41
- if test (count $actual) -ne (count $expected)
42
- return 1
43
- end
44
- if test (count $expected) -eq 0
45
- return 0
46
- end
47
- for index in (seq (count $expected))
48
- if test $actual[$index] != $expected[$index]
49
- return 1
50
- end
51
- end
52
- return 0
53
- end
54
- `].flatMap(e=>e.split(`
55
- `))}function Hs(e,t){return Xs(e).map(e=>`${oc(t)} -f -n ${J(sc(e.parentPath))} -a ${J(e.name)} -d ${J(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Us(e,t,n){return ic(e).flatMap(e=>{let r=ac(e),i=r.length===0?void 0:sc(r);return Ws(e).flatMap(e=>{let a=t.get(Ys(r,e));return $s(a)?Gs(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Ws(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function Gs(e,t,n,r){let i=rc(e);if(i===void 0)return[];let a=e.argChoices??Qs(n),o=[`-l ${J(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${J(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${J(t)}`,c=e.required||e.optional?Ks(a,qs(i,n)):`-f`,l=`${oc(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${J(cc(e.description))}`]:a.map(t=>`${l} -a ${J(t)} -d ${J(cc(e.description))}`)}function Ks(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function qs(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 Js(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...pn(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].map(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[Ys(e.cliPath,n),t]})))}function Ys(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):rc(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 Xs(e){return ic(e).flatMap(e=>e.commands.map(t=>({parentPath:ac(e),name:t.name(),description:cc(t.summary()||t.description()||t.name())})))}function Zs(e,t){let n=[],r=[];for(let i of ic(e)){let e=ac(i);for(let a of Ws(i)){let i=rc(a);if(i===void 0)continue;let o=t.get(Ys(e,a));if(!$s(o))continue;let s=a.argChoices??Qs(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&qs(i,o)&&(c=`file`)),n.push(tc([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(tc([e.join(` `),`--${i}`,t,a.description]))}}return[Xs(e).map(e=>tc([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 Qs(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 $s(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function ec(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 tc(e){return`$'${e.map(nc).join(`|`)}'`}function nc(e){return cc(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function rc(e){return e.long?.replace(/^--/,``)}function ic(e){return[e,...e.commands.flatMap(e=>ic(e))]}function ac(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function oc(e){return`complete ${e.map(e=>`-c ${J(e)}`).join(` `)}`}function sc(e){return[`__aventure_cli_path_is`,...e.map(J)].join(` `)}function cc(e){return e.replace(/\s+/g,` `).trim()}function J(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function lc(e,t){if(e!==t)return;let n=uc(t);n!==void 0&&t.error(`error: ${fc(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function uc(e){if(!process.argv.includes(`--`)&&e.args.some(dc))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function dc(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function fc(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function pc(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function mc(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function hc(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function gc(e){return e.flags.split(` `)[0]??e.flags}function _c(e,t){let n=pc(t);if(n===void 0)return;let r=e.options.findIndex(e=>gc(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[gc(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 Y(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function vc(e){return e.commands.length===0?[e]:e.commands.flatMap(vc)}function yc(e,t){return Y(t).slice(Y(e).length)}function X(e){let t=e;for(;t.parent!==null;)t=t.parent;return t}function bc(e,t){return t.toSorted((t,n)=>{let r=yc(e,t),i=yc(e,n),a=r.at(-1)===`get`?0:1,o=i.at(-1)===`get`?0:1;return r.length-i.length||a-o})[0]}function xc(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Sc(e,t){let n=Y(e),r=process.argv.slice(2+n.length);return[X(e).name(),...n,...yc(e,t),...r].map(xc).join(` `)}function Cc(e,t){let n=mc(t);if(n===void 0||e.commands.length===0)return;let r=bc(e,vc(e).filter(e=>e.options.some(e=>gc(e)===n)));if(r!==void 0)return`hint: run: ${Sc(e,r)}`}function wc(e){return e!==void 0&&Object.hasOwn(Ve,e)}function Tc(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 Ec(e,t){let n=Y(e),r=[...n.slice(1),t];if(!wc(n.at(0))||!wc(r.at(0)))return;let i=Tc(X(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 Dc(e,t){let[n]=Y(e);if(!wc(n))return;let r=[n,t];return Tc(X(e),r)?.commands.length===0?r:void 0}function Oc(e){let[t,...n]=e.args;if(t===void 0)return[];let r=vc(X(e)).map(Y),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 kc(e,t){let n=Y(e),r=process.argv.slice(2+n.length);if(t.length===0||t.some((e,t)=>r[t]!==e))return;let i=Le(O).map(e=>e.cliPath).filter(e=>e[0]!==n[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: ${[X(e).name(),...a].map(xc).join(` `)}`}function Ac(e,t,n){if(!Mc(t))return;let r=e.args.slice(n.length),i=r.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${[X(e).name(),...t,...i<0?[]:r.slice(i)].map(xc).join(` `)}`}function jc(e){let t=Y(e);if(t.at(1)!==void 0&&wc(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(xc).join(` `)}`}function Mc(e,t){let n=e.join(` `);return O.some(e=>{let r=`cliAliasPath`in e?e.cliAliasPath:void 0;return e.cliPath.join(` `)!==n&&r?.join(` `)!==n?!1:t===void 0||ne(e.intent)===t})}function Nc(e){let t=Y(e);if(wc(t.at(0))&&Mc(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(xc).join(` `)}`}function Pc(e){let t=new Set,n=[];for(let r of O){let i=Tc(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(gc);if(ne(r.intent))n.push(a);else for(let e of a)t.add(e)}let[r=[],...i]=n;return new Set(r.filter(e=>!t.has(e)&&i.every(t=>t.includes(e))))}function Fc(e,t){let n=Y(e);if(Mc(n,!1)&&Pc(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Ic(e,t,n=!0){let r=X(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=Y(e).at(0),c=a.options.find(e=>gc(e)===`--root`);return n&&s!==void 0&&c!==void 0&&wc(s)&&o.push(gc(c),s),`hint: search generated commands: ${o.map(xc).join(` `)}`}function Lc(e,t){let n=hc(t);if(n===void 0||t.message.includes(`
56
- (Did you mean `))return;let r=Oc(e),i=kc(e,r);if(i!==void 0)return i;let a=Ec(e,n);if(a!==void 0)return Ic(e,a.join(` `),!1);let o=Dc(e,n);if(o!==void 0)return Ac(e,o,r)??Ic(e,o.join(` `),!1);let s=r.join(` `)||n;return jc(e)??Ic(e,s)}function Rc(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[uc(e),_c(e,t)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=uc(e)??Nc(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=mc(t),r=Cc(e,t)??(n!==void 0&&!t.message.includes(`
57
- (Did you mean `)?Fc(e,n)??Ic(e,n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Lc(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var zc=class extends u{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 Bc(e){e.showHelpAfterError(!1).exitOverride(Rc(e)),e.commands.length===0?e.hook(`preAction`,lc):e.addHelpOption(new zc(e));for(let t of e.commands)Bc(t)}var Vc=`dist/aventure-cli/command-catalog.compact.txt`,Hc=` · `,Uc=`-`;function Wc(e=C().bin[0]){return j(Gc(k(jt(import.meta.url)),e),Vc)}function Gc(e,t){let n=e;for(;;){if(P(j(n,`package.json`)))return n;let r=k(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Kc(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function qc(e,t,n,r=C().bin[0]){let i=tr(e,t,r);if(!i.ok){R({mode:n},i);return}Yc({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Zc(i.data,Xc(e.format,`lines`)),summary:`Generated operation matches`})}function Jc(e,t,n,r=C().bin[0]){let i=nr(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Yc({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Qc(i.data,Xc(e.format,`usage`)),summary:`Generated operation detail`})}function Yc(e){let t=e.mode,n=e.rendered.endsWith(`
58
- `)?e.rendered:`${e.rendered}\n`;if(e.opts.output!==void 0){I(e.opts.output,n),R({mode:t},b(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(n,`utf8`),format:Xc(e.opts.format,e.defaultFormat)},{counts:rl(e.data)}));return}if(t===`text`){process.stdout.write(n);return}R({mode:t},b(e.summary,e.data,{counts:rl(e.data)}))}function Xc(e,t){return e??t}function Zc(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
59
- `):t===`text`?tl(e.operation):t===`compact`?e.operation.map($c).join(`
60
- `):e.operation.map(nl).join(`
61
- `)}function Qc(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?nl(e.operation):t===`compact`?$c(e.operation):e.usage}function $c(e){let t=el(e);return[e.cli.command,e.summary,t.length===0?Uc:t.join(` `)].join(Hc)}function el(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function tl(e){return e.map(e=>`${e.cli.command}\n ${nl(e)}`).join(`
62
- `)}function nl(e){let t=el(e);return[Z(`operationId`,e.operationId),Z(`scope`,e.scope),Z(`mutates`,String(e.mutates)),Z(`destructive`,String(e.destructive)),Z(`intent`,e.intent),Z(`resource`,e.resource),Z(`cli`,e.cli.command),e.cli.alias===null?``:Z(`alias`,e.cli.alias),e.mcpTool===null?``:Z(`mcpTool`,e.mcpTool),Z(`method`,e.method),Z(`path`,e.path),Z(`auth`,e.auth),Z(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),Z(`requiredFlags`,t.join(` `)),Z(`bodyKind`,e.body.kind??``),Z(`bodyRequired`,String(e.body.required)),Z(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function Z(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function rl(e){return`count`in e?e.count:{returned:1}}function il(e,t=new Date){let n=sl(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 al(e){return`${JSON.stringify(e,null,2)}\n`}function ol(e,t){let n=j(e),r=al(t);return Ct(k(n),{recursive:!0}),I(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function sl(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,cliAliasCommand:e.projection.cliAliasPath?.join(` `)??null,cliAliasPath:e.projection.cliAliasPath??null,mcpTool:c(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 cl=`Match only the first canonical or CLI-alias command segment`;function ll(e,t,n=C().bin[0]){dl(e,t,n);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(`
63
- `));r.addHelpText(`after`,()=>`\nShipped compact catalog, greppable without running this CLI:\n ${Wc(n)}\n`),ul(r,t,n),ml(r,t,n),hl(r,t,n),gl(r)}function ul(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>`,cl).addOption(new u(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new u(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new u(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new u(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new u(`--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 u(`--format <format>`,`Text/file render format`).choices([`text`,`lines`,`compact`,`json`,`ndjson`]).default(`lines`)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(e){let r=this.optsWithGlobals(),i=E(r,`text`),a=r.limit?.trim()??``,o=a===``?NaN:Number(a);if(!Number.isInteger(o)||o<0){R({mode:i},w(`Invalid --limit value: ${JSON.stringify(r.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`; omit the flag for the default of 20."]));return}qc(Kc(r,e),t,i,n)})}function dl(e,t,n){let r=e.command(`docs`).summary(`Look up generated API documentation offline`).description(`Print generated operation documentation without calling the API.`).command(`api`).summary(`Show documentation for one operation`).description([`Print one operation's summary, description, flags, example, and error contract.`,"Select it by `<METHOD> <path>` (route template or concrete path), by operationId,",`or by CLI command path, e.g. "entities get".`].join(`
64
- `)).argument(`<selector...>`,`METHOD and path, an operationId, or a CLI command path`);D(r),r.action(function(e){let r=this.optsWithGlobals(),i=E(r),a=pl(e,t);if(!a.ok||a.data===null){R({mode:i},a);return}Jc({...r,...a.data},t,i,n)})}var fl='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function pl(e,t){let[n,...r]=e,i=se.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return b(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=de(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return b(`Resolved by route template`,{operationId:s.operationId});let c=oe({method:a,path:o});return!c.ok||c.data===null?w(c.summary,[...c.warnings,fl]):b(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function ml(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 u(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();Jc(e,t,E(e,`text`),n)})}function hl(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>`,cl).addOption(new u(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new u(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new u(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new u(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new u(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new u(`--format <format>`,`Text/file render format`).choices([`text`,`lines`,`compact`,`json`,`ndjson`]).default(`lines`)).option(`--output <path>`,`Write rendered output to a file`);D(r),r.action(function(){let e=this.optsWithGlobals();qc(e,t,E(e,`text`),n)})}function gl(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);D(t),t.action(function(){let e=this.optsWithGlobals(),t=E(e,`text`),n=il(it);if(e.output!==void 0){let r=ol(e.output,n);R({mode:t},b(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(al(n));return}R({mode:t},b(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var _l=C(jt(import.meta.url)),Q=_l.bin[0];function vl(e,t){f({component:`aventure-cli`,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`),qn({...w(`${Q} ${t}: ${e.message}`,[e.name||`Error`]),counts:{exitCode:1}}),process.exit(1)}function yl(e){return He[qe(e)??`cli`]}function bl(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:yl(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec);for(let t of n)xl(e,t,t.cliPath),t.cliAliasPath!==void 0&&t.cliAliasPath.join(` `)!==t.cliPath.join(` `)&&xl(e,t,t.cliAliasPath)}function xl(e,t,n){let r=e,i=``;for(let e of n.slice(0,-1))i=i===``?e:`${i} ${e}`,r=Tl(r,e,i);let a=n.at(-1)??t.operationId,o=r.commands.find(e=>e.name()===a)??r.command(a),s=t.requestBody?.flatMap(({parameter:e})=>e)??[];o.summary(t.summary||t.operationId).description([`${t.method} ${t.path}.`,t.summary||t.description,`Full API documentation: ${Q} docs api ${t.operationId}`,t.requestBody?.[0]?.kind===`json`||[...t.parameters,...s].some(e=>ae(e.schemaType,e.itemSchemaType))?ge:``].filter(Boolean).join(`
65
- `));for(let e of t.parameters)El(o,e);wn(o,t),ne(t.intent)&&o.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),D(o);let c=Sl(t);if(c!==void 0){o.argument(`[text...]`,c.description||`Same as ${wl(c.flag)}.`),o.action(async function(e){let n=this.optsWithGlobals(),r=E(n),i=Cl(c,e,n);return R({mode:r},i.ok&&i.data!==null?await Dl(t,i.data,r):i)});return}o.action(async function(){let e=this.optsWithGlobals(),n=E(e),r=await Dl(t,e,n);r.ok&&r.data instanceof Uint8Array?process.stdout.write(r.data):R({mode:n},r)})}function Sl(e){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.cliPath[0]!==`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 Cl(e,t,n){let r=t.join(` `).trim();return r.length===0?b(`No positional text`,n):n[e.optionKey]===void 0?b(`Positional text parsed`,{...n,[e.optionKey]:r}):w(`Use either the positional argument or ${wl(e.flag)}, not both.`)}function wl(e){return e.split(` `)[0]??e}function Tl(e,t,n){let r=e.commands.find(e=>e.name()===t);if(r!==void 0)return r;let i=Ve[n],a=e.command(t);return i!==void 0&&a.summary(i.summary).description(i.summary),a}function El(e,t){let n=t.description||`${t.name} ${t.location} parameter`,r=t.defaultValue===void 0?void 0:typeof t.defaultValue==`string`||typeof t.defaultValue==`boolean`?t.defaultValue:[...t.defaultValue];if(t.legacyFlag!==void 0){let i=new u(t.flag,n);r!==void 0&&i.default(r);let a=new u(t.legacyFlag,n).conflicts(t.optionKey);e.addOption(i).addOption(a),e.hook(`preAction`,e=>{let n=e.opts(),r=n[t.optionKey],o=n[a.attributeName()];if(o!==void 0){(r===void 0||e.getOptionValueSource(t.optionKey)==="default")&&e.setOptionValueWithSource(t.optionKey,o,`cli`);return}t.required&&r===void 0&&e.error(`error: required option '${i.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(r!==void 0){e.option(t.flag,n,r);return}if(t.required){e.requiredOption(t.flag,n);return}e.option(t.flag,n)}async function Dl(e,t,n){if(t.environment!==void 0){let e=te(t.environment);if(e===null)return w(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${ie().join(`, `)}`]);process.env.API_ENV=e}let r=await kn(e,t);if(!r.ok)return r;let i=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),a=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),o=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]}));return await S({method:e.method,path:pe(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:typeof t.contentType==`string`?t.contentType:void 0,auth:e.auth,responseFormat:Fe(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0})}process.on(`uncaughtException`,e=>vl(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>vl(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var Ol=Ke(process.argv.slice(2),O),kl=Ol===`required`?O:Le(O),$=new re;$.name(Q).configureHelp({helpWidth:1/0}).version(_l.version).summary(`CLI for the aVenture API: read and maintain venture-research data — entities, people, funding, news, media, and search`).description(`Read and maintain venture-research data. Mutations execute directly; --execute is a deprecated no-op. The aventure-mcp-server tools execute through this same CLI.`).addOption(new u(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${_})`).choices([...ie()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),bl($,kl),Xo($,Q),_o($,_l),Ms($,kl,Q),Ls($,kl,Q),ll($,kl,Q),Er($,kl,Q),Ir($,kl);for(let e of $.commands)e.helpGroup()||e.helpGroup(yl(e.name()).heading);if(Bc($),Ol===`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 ue(),await Me(),await Be())}))}}$.addHelpText(`after`,[``,`Environment (credentials by command group):`,` CLIENT_SECRET client access to authenticated reads, search, and lookups`,` ADMIN_API_KEY admin and write commands (mutations, media, jobs, harness)`,` AUTH_TOKEN signed-in session or personal API key; reads and permitted writes`,` Public reads also work without credentials. Saved sign-in is used when available.`,` Check what this shell holds with: ${Q} auth status`,``,`Output modes (per command):`,` --text (compact; default on a terminal), --data (response data JSON; default when piped/non-TTY), --json (full envelope);`,` --data-full is uncapped, for bounded programmatic consumers only — never LLM agents.`,``,`Exit codes:`,` 0 envelope.ok === true`,` 1 envelope.ok === false`,``,`Examples:`,` $ ${Q} auth status`,` $ ${Q} entities get --entity-slug acme`].join(`
66
- `));try{await $.parseAsync()}catch(e){vl(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};