@aventurevc/aventure-cli 0.7.288 → 0.7.295

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,67 +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,A as c,C as l,E as u,H as d,I as f,J as p,K as m,M as h,N as g,O as _,Q as ee,R as te,S as ne,St as v,T as re,X as ie,Y as ae,Z as oe,_ as se,b as ce,c as le,f as ue,g as de,h as fe,i as pe,j as me,k as y,l as b,m as he,n as ge,nt as x,o as _e,p as ve,q as ye,r as be,rt as S,s as xe,t as Se,tt as Ce,u as we,v as Te,w as Ee}from"./auth-BLOLziUK.js";import{A as De,C as Oe,D as ke,E as Ae,F as C,I as je,M as Me,N as Ne,O as Pe,P as Fe,S as Ie,T as Le,_ as Re,a as ze,b as Be,c as Ve,d as He,f as Ue,g as We,h as Ge,j as Ke,k as qe,l as Je,m as Ye,n as Xe,o as w,p as Ze,r as T,s as Qe,t as E,u as $e,v as et,w as tt,x as nt,y as rt}from"./openapi-commands-B4YzaiPU.js";import{F as it,a as at,f as ot,i as st,l as ct,m as lt,n as ut,ot as dt,p as ft,r as pt,s as mt,st as ht,t as gt}from"./mcp-generation-contract-DwvMQfv2.js";import{execFile as _t,spawnSync as vt}from"node:child_process";import{createHash as yt,randomBytes as bt,timingSafeEqual as xt,webcrypto as St}from"node:crypto";import{readFile as Ct}from"node:fs/promises";import{homedir as wt,hostname as Tt,platform as Et}from"node:os";import{basename as Dt,dirname as D,join as O,resolve as k,sep as Ot}from"node:path";import A,{stderr as j,stdin as kt}from"node:process";import{appendFileSync as At,copyFileSync as jt,existsSync as M,lstatSync as Mt,mkdirSync as Nt,mkdtempSync as Pt,readFileSync as N,readlinkSync as Ft,realpathSync as It,renameSync as Lt,rmSync as Rt,rmdirSync as zt,unlinkSync as Bt,writeFileSync as P}from"node:fs";import{fileURLToPath as Vt}from"node:url";import{once as Ht}from"node:events";import{TextDecoder as Ut,inspect as Wt}from"node:util";import{createServer as Gt}from"node:http";import{setTimeout as Kt}from"node:timers/promises";import{createInterface as qt}from"node:readline/promises";function Jt(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{...x(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return S(`Environment-bound options applied`,r)}function Yt(e,t,n){if(!F(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!un(n,r.name))continue;let a=ln(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 Xt(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||!pn(t)||!Array.isArray(n))return hn(e,t,n);for(let[r,i]of n.entries()){let n=hn(e,t,i,r);if(!n.ok)return n}return S(`Body value assigned`,null)}function Qt(e,t,n,r){return hn(e,t,r,n)}function $t(e){let t=[];for(let n of e.split(`.`)){let e=_n(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function en(e,t){let n=$t(t);if(n===null)return null;let r=cn(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:sn(r)}:null}function tn(e,t){if(pn(e.name)||e.schemaType===`array`)return S(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return S(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?S(`Scalar body option selected`,t[0]):x(`${n} was already given; pass it once.`)}var nn=/^(?<row>\d+):(?<item>.*)$/su;function rn(e,t){let n=$t(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=nn.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 an(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&$t(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function on(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=en(r,i.name);if(a===null)continue;if(a.firstHole!==null)return x(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||rn(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return x(`${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 sn(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function cn(e,t){let n=e;for(let e of t){if(!F(n))return;n=n[e]??null}return n}function ln(e,t){if(!pn(t))return cn(e,t.split(`.`))}function un(e,t){return fn(e,t.split(`.`))}function dn(e,t,n){if(!F(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&un(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function fn(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=_n(n);if(!F(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>fn(e,r)):fn(a,r)}function pn(e){return e.split(`.`).some(e=>_n(e).isArray)}function mn(e,t){return e.parameter.length===0||!F(t)?null:yn(t,[],vn(e.parameter))}function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=_n(o),c=e===i.length-1,l=gn(a,s,t,c,n,r);if(!l.ok||l.data===null)return x(l.summary,l.warnings);if(c)return S(`Body value assigned`,null);a=l.data}return x(`${t} is not a valid body option path.`)}function gn(e,t,n,r,i,a){let o=()=>x(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,S(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,S(`Body path created`,e)}return F(c)?S(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,S(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,S(`Body path created`,n)}return F(s)?S(`Body path stepped`,s):o()}function _n(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function vn(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 yn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=yn(r,t,n);if(e!==null)return e}return null}if(!F(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!bn(a,n)){if(!xn(e))continue;return{path:a,suggestion:Sn(e,n)}}let o=yn(i,e,n);if(o!==null)return o}return null}function bn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function xn(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function Sn(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:Cn(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 Cn(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 wn(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(Ze(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?Mn(r,i):r===void 0?i===void 0?0:1:-1})}function Tn(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 En(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function Dn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:An(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 On(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function kn(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?Ye(n):`${Ye(n)} Required JSON paths: ${r.join(`, `)}.`}function An(e,t){return`${He(t.description,void 0)}${e.kind!==`multipart`&&pn(t.name)?` Repeat to add another value.`:``}${jn(e,t)}`}function jn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=$t(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 Mn(e,t){return Ue(e)-Ue(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function Nn(e){let t;try{t=e===`-`?await Pn():await Ct(e,`utf8`)}catch(t){return x(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return S(`No input provided`,null);let e=JSON.parse(t);return S(`Input parsed`,e)}catch(e){return x(`Input is not valid JSON: ${e.message}`)}}async function Pn(){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 Fn=`--content-type`;function In(e,t){let n=t.requestBody??[];if(n.length>1){let t=n.map(({contentType:e})=>e);e.addOption(new u(`${Fn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Rn(n)))}if(rr(t)){let r=n[0];if(r===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new u(`--from-file <path>`,kn(r,r.requiredPath)).argParser(Bn(`--from-file`)))}let r=Tn(n);for(let t of r.toSorted((e,t)=>Mn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=t.variant[0],a=new u(En(t),n.length>1?Dn(t):An(r,i));n.length===1&&i.envName!==void 0&&a.env(i.envName);let o=n.length===1?On(r,i.optionKey):[];o.length>0&&a.conflicts(o),n.length>1?a.argParser(Ln):pn(i.name)||i.schemaType===`array`?a.argParser(zn):a.argParser(Bn(i.flag)),e.addOption(a)}nr(e,t,r)}function Ln(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Rn(e){return(t,n)=>{if(n!==void 0)throw new _(`${Fn} was already given; pass it once.`);let r=Ee(e,t);if(!r.ok)throw new _(r.summary);return t}}function zn(e,t){return[...t??[],e]}function Bn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new _(`${t} was already given; pass it once.`);return e}}async function Vn(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,r=Ee(e.requestBody??[],n);if(!r.ok||r.data===null)return x(r.summary,r.warnings);let i=r.data;if(i===void 0)return S(`No body`,void 0);let a=Hn(e,i,t);if(a!==null)return x(a);let o=Jt(e.operationId,i,t);if(!o.ok)return x(o.summary,o.warnings);t=o.data;let s=Un(i,t);if(s!==null)return x(s);let c=await qn(t);if(!c.ok)return x(c.summary,c.warnings);let l=dn(e.requestBody??[],i,c.data);if(l!==null)return x(l);let u=Kn(e.operationId,i,c.data);if(!u.ok)return u;let d=Yt(e.operationId,i,c.data);if(d!==null)return x(d);let f=Jn(e.operationId,i,t);if(!f.ok)return f;if(c.data===void 0&&f.data===void 0)return i.required?x(tr(e.operationId,i)):S(`No body`,void 0);let p=Xn(e.operationId,c.data,f.data);if(!p.ok||p.data===void 0)return p;if(i.schemaType===`array`&&!Array.isArray(p.data))return x(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!F(p.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return x(`${e.operationId} requires a JSON object${t}.`)}let m=Gn(i,p.data);if(m.length>0)return x(`${e.operationId} requires body option(s): ${m.join(`, `)}`);let h=p.data,g=F(h)?Xt(i).filter(e=>!un(h,e)):[];return g.length>0?x(Wn(e.operationId,i,g)):p}function Hn(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${Fn} ${i.join(` or `)}.`}return null}function Un(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 Wn(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 Gn(e,t){return F(t)?e.parameter.filter(e=>e.required&&!un(t,e.name)).map(I):[]}function Kn(e,t,n){let r=mn(t,n);if(r===null)return S(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion.path} (${r.suggestion.flag}).`;return x(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function qn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return S(`No body file`,void 0);let n=await Nn(t);if(!n.ok)return x(n.summary,n.warnings);let r=v.safeParse(n.data);return r.success?S(`Input parsed`,r.data):x(`Input is not valid JSON value: ${r.error.message}`)}function Jn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=tn(e,n[e.optionKey]);if(!a.ok||a.data===null)return x(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Yn(t,n,r,e,o);if(!s.ok)return x(s.summary,s.warnings);i=!0}if(!i)return S(`No direct body options`,void 0);let a=on(e,t,n,r);return a===null?S(`Direct body options parsed`,r):a}function Yn(e,t,n,r,i){let a=rn(r,i);if(a===null){let e=$n(r,i);return e.ok?Zt(n,r.name,e.data,r.schemaType===`array`):x(e.summary,e.warnings)}if(a.plain.length>0)return x(`${I(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=an(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return x(`${I(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=er(r.name,r.itemSchemaType,e);if(!t.ok)return x(t.summary,t.warnings);i.push(t.data)}let a=Qt(n,r.name,e,i);if(!a.ok)return a}return S(`Body value assigned`,null)}function I(e){return e.flag.split(` `)[0]??e.name}function Xn(e,t,n){if(t===void 0)return S(`Direct body parsed`,n);if(n===void 0)return S(`Input parsed`,t);if(F(t)&&F(n))try{return S(`Input parsed`,Zn(t,n))}catch(t){return x(`${e} ${t.message}`)}return x(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Zn(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&&Qn(t)!==Qn(r))throw Error(`cannot combine --from-file ${Qn(t)} '${e}' with ${Qn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=F(t)&&F(r)?Zn(t,r):r}return n}function Qn(e){return Array.isArray(e)?`array`:F(e)?`object`:`scalar`}function $n(e,t){if(typeof t==`boolean`)return S(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return er(e.name,e.schemaType,t??``);let n=[],r=pn(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=er(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return S(`Body value parsed`,n)}function er(e,t,n){if(t===`boolean`)return n===`true`?S(`Body value parsed`,!0):n===`false`?S(`Body value parsed`,!1):x(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?x(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?x(`${e} must be an integer.`):S(`Body value parsed`,i)}return S(`Body value parsed`,n)}function tr(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=Xt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function nr(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:Fn,location:`body`}),rr(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),wn(e.options,r)}function rr(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function ir(e){let t=Ce(e);return dr(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function ar(e){dr(e);let t=ut(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
- `)?t:`${t}\n`),or(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&cr(e.problem),or(e)}function or(e){e.ids.length>0&&process.stdout.write(` ids: ${e.ids.join(`, `)}\n`);for(let[t,n]of Object.entries(e.counts))process.stdout.write(` ${t}: ${n}\n`);for(let t of e.references)process.stdout.write(` ref: ${t}\n`);if(e.truncation!==void 0){let t=e.truncation.omitted.join(`, `);process.stdout.write(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${t}\n`),process.stdout.write(` recovery: ${e.truncation.recovery}\n`)}for(let t of e.warnings)process.stdout.write(` warn: ${t}\n`)}function L(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?Ce(t):t;dr(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?sr(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?ir(t):t;e.mode===`text`&&ar(n),n.ok||(process.exitCode=1)}function sr(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 cr(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`)}lr(`unknownParameters`,e.unknownParameters),lr(`validParameters`,e.validParameters),ur(e.resolution)}function lr(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function ur(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 dr(e){e.ok&&e.warnings.length===0||te({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 fr(e,t,n=m().bin[0]){let r=t.length,i=mt(e.q?.trim()??``),a=at(i),o=ct(i),s=hr(t,n).filter(t=>yr(t,e)).map(e=>({operation:e,score:xr(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=Er(e.limit,s.length),l=s.slice(0,c);return S(`Operation catalog matches`,{operation:l,count:{totalOperations:r,matched:s.length,returned:l.length}})}function pr(e,t,n=m().bin[0]){let r=hr(t,n),i=e.operationId===void 0?mr(r,e.command):r.find(t=>t.operationId===e.operationId);return i===void 0?x(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`]):S(`Generated operation detail`,{operation:i,usage:Dr(i)})}function mr(e,t){if(t===void 0)return;let n=Ir(t);return e.find(e=>Ir(e.cli.command)===n||e.cli.alias!==null&&Ir(e.cli.alias)===n)}function hr(e,t){return e.map(e=>{let n=e.requestBody??[],r=[...e.parameters.map(e=>gr(e)),...n.flatMap(e=>e.parameter.map(t=>gr(t,n.length>1?e.contentType:void 0))),..._r(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`,c=n[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:s,auth:e.auth,cli:{command:i,path:e.cliPath,alias:a,aliasPath:e.cliAliasPath??null},mcpTool:e.binaryResponse?null:l(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&n.length>1?{contentType:c.contentType}:{},required:c?.required??!1,description:c?.description??``,requiredPath:c?.requiredPath??[]},flags:r,errorResponse:e.errorResponse,summary:e.summary,description:e.description}})}function gr(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 _r(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 vr(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function yr(e,t){return!(t.root!==void 0&&!br(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 br(e,t){let n=mt(t);return n.length===0||mt(e.cli.path.at(0)??``)===n||mt(e.cli.aliasPath?.at(0)??``)===n}function xr(e,t,n,r){if(e.length===0)return 1;let i=Cr(r),a=Sr(e,t,i,{exactQuery:120,partialQuery:60,exactToken:18,partialToken:6})+Sr(e,t,wr(r),{exactQuery:12,partialQuery:6,exactToken:2,partialToken:1});st(n,i)&&(a+=200);for(let e of r.cli.path){let n=new Set;pt(n,e),[...n].some(e=>t.has(e))&&(a+=15)}return mt(r.cli.command).endsWith(e)&&(a+=40),a}function Sr(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 Cr(e){return Tr([e.operationId,e.cli.command,e.cli.alias??``,e.summary])}function wr(e){return Tr([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 Tr(e){return e.map(mt).filter(e=>e.length>0)}function Er(e,t){if(e===void 0)return t;let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function Dr(e){let t=vr(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`,R(`required path flags`,n,`path`),R(`required query flags`,n,`query`),R(`required header flags`,n,`header`),R(`required body flags`,n,`body`),R(`optional path flags`,r,`path`),R(`optional query flags`,r,`query`),R(`optional header flags`,r,`header`),R(`optional body flags`,r,`body`),...Mr(e),...Or(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
3
- `)}function Or(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var kr=[`-id`,`-slug`,`-url`],Ar=[`--id`,`--slug`,`--url`],jr=`--from-file "<path>"`;function Mr(e){return[`example: ${[e.cli.command,...Nr(e),`--data`].join(` `)}`]}function Nr(e){let t=vr(e).filter(e=>e.required),n=(t.length>0?t:Pr(e)).map(Fr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,jr]:n}function Pr(e){let t=new Set;pt(t,e.resource);for(let n of kr)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 Ar){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function Fr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function R(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function Ir(e){return e.trim().replace(/^aventure(?:-cli)?\s+/u,``).replaceAll(/\s+/gu,` `)}function Lr(e,t,n=m().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 Rr(r));let i=Br(t);i!==void 0&&r.option(`--ask <question>`,i.summary),T(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=w(r);if(t.length>0){L({mode:e},x(`Use either a command path or --ask, not both.`));return}L({mode:e},await Hr(i,r.ask,r.environment,e));return}let a=Vr(e,t);a===void 0&&this.error(`unknown command '${t.join(` `)}' (run \`${n} --help\` for the command tree)`),a.outputHelp()}),zr(e,t)}var Rr=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 zr(e,t){let n=new Set;for(let r of t){let t=Or(r.errorResponse);if(t.length!==0)for(let i of[r.cliPath,r.cliAliasPath]){let r=i===void 0?void 0:Vr(e,i);r===void 0||n.has(r)||(n.add(r),r.addHelpText(`after`,`\n${t.join(`
5
- `)}\n`))}}}function Br(e){let[t,...n]=e.filter(e=>{let[t,n,r]=e.cliPath;return t===`help`&&n!==void 0&&r===void 0&&Ur(e)!==void 0});return n.length===0?t:void 0}function Vr(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 Hr(e,t,n,r){let i=Ur(e);if(i===void 0)return x(`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 Vn(e,{[i.optionKey]:t});return a.ok?await b({method:e.method,path:_e(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:ze(r)?`json`:`auto`}):a}function Ur(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 Wr=`search`,Gr=`mode`,Kr=`--mode`;function qr(e,t){let n=e.commands.find(e=>e.name()===Wr);if(n===void 0)return;let r=new Map;for(let e of t){let[t,n,i]=e.cliPath;if(t!==Wr||n===void 0||i!==void 0)continue;let a=[...e.parameters,...e.requestBody?.flatMap(({parameter:e})=>e)??[]].find(e=>e.optionKey===Gr);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(`${Kr} <mode>`,`search strategy, forwarded to the scope command's generated --mode option`).choices(i).argParser((e,t)=>{if(t!==void 0)throw new _(`${Kr} was already given; pass it once.`);if(!i.includes(e))throw new _(`${Kr} must be one of: ${i.join(`, `)}.`);return e})),n.hook(`preSubcommand`,(e,t)=>{let n=e.opts()[Gr];typeof n==`string`&&(r.has(t.name())||e.error(`${Kr} is not supported by 'search ${t.name()}'`),t.setOptionValueWithSource(Gr,n,`cli`))})}var Jr=a({artifact:e().nullish(),group:e().nullish(),name:e().nullish(),revision:e().nullish(),time:i({offset:!0}).nullish(),version:e().nullish()}),Yr=a({build:Jr});function z(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var Xr=r([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),Zr=r([`RSA_OAEP_256_A256_GCM_V1`]),Qr=a({clientLabel:e().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:Xr.nullish(),encryptionAlgorithm:Zr.nullish(),encryptionPublicKey:e().min(344).max(12e3).nullish()}),$r=32;async function ei(){let e=await St.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await St.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function ti(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=ni(n,`wrapped key`,128,1024),s=ni(r,`nonce`,12,12),c=ni(i,`ciphertext`,1,65536),l=ni(a,`authentication tag`,16,16),u;try{u=await St.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!==$r)throw Error(`broker credential used an invalid AES-256 key`);let e=await St.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 St.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Ut(`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 ni(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 ri=2;function ii(e,t){return si(e,t).redactedUrl}async function ai(e,t,n){let r=si(e,t);return await oi(new URL(r.openerUrl),n)}async function oi(e,t){let n=t.environment??process.env,r=t.operatingSystem??Et(),i=ci(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=li(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await ui(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function si(e,t){let{id:n,verificationUrl:r,pollSecret:i}=e,a,o;try{a=new URL(r),o=new URL(t)}catch{throw Error(`broker returned an invalid browser verification URL`)}if(o.username.length>0||o.password.length>0||o.pathname!==`/`||o.search.length>0||o.hash.length>0)throw Error(`configured browser origin must contain only an origin`);let s=Ne(o.hostname);if(o.protocol!==`https:`&&!(o.protocol===`http:`&&s))throw Error(`configured browser origin must use HTTPS except for loopback development`);let c=new URLSearchParams(a.hash.slice(1)),l=[...c.keys()],u=c.getAll(`cliAuthorizationId`),d=c.getAll(`browserSecret`),f=d[0]??``;if(a.origin!==o.origin||a.protocol!==o.protocol||a.username.length>0||a.password.length>0||a.pathname!==`/settings/developer`||a.search.length>0||l.length!==ri||u.length!==1||u[0]!==n||d.length!==1||f.length===0||i.length===0||f===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let p;try{p=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||p.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m=new URL(a);return m.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:m.toString()}}function ci(e,t,n){return e?`--no-browser was set`:n===`darwin`&&t.CODEX_SESSION_ID?`macOS Codex browser process boundary`:t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY?`SSH/headless session detected`:(n===`linux`||n===`freebsd`)&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?`no graphical display detected`:null}function li(e,t){return e===`darwin`?{command:`open`,arguments:[t]}:e===`win32`?{command:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,t]}:e===`linux`||e===`freebsd`?{command:`xdg-open`,arguments:[t]}:null}function ui(e,t){return new Promise((n,r)=>{_t(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var di=r([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),fi=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`]),pi=a({approvedAt:i({offset:!0}).nullish(),clientLabel:e(),clientPlatform:Xr,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:di,terminalAt:i({offset:!0}).nullish(),terminalReason:fi.nullish(),updatedAt:i({offset:!0})}),mi=a({algorithm:Zr,authenticationTag:e(),ciphertext:e(),nonce:e(),wrappedKey:e()}),hi=a({delivery:mi.nullish(),expiresAt:i({offset:!0}),status:di,terminalReason:fi.nullish()}),gi=a({comparisonCode:e(),expiresAt:i({offset:!0}),id:t(),intervalSeconds:n().int().min(1),pollSecret:e(),verificationUrl:e()}),B=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the OS credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the authorization URL without opening a browser.`}]},{command:`auth personal-login`,role:`start`,summary:`Approve a personal CLI 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:`browser`,flag:`--no-browser`,description:`Print the approval URL without launching a browser.`}]},{command:`auth personal-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 personal-login`,role:`acknowledge`,summary:`Acknowledge CLI credential delivery`,description:`Confirms the CLI stored the delivered personal key in its OS credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth personal-logout`,role:`revoke`,summary:`Revoke current personal API key`,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.`}]}],_i=z(B,`start`),vi=z(B,`poll`),yi=z(B,`acknowledge`),bi=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${je(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Ei(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},xi=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${C(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Si(e){let t=await fe(Fe(s()),{method:_i.method,path:ve(_i.path,{},_i.operationId),headers:{},contentType:`application/json`,body:e},gi);if(!t.ok)throw new bi(`start`,t.problem);return Di(t.data)}async function Ci(e,t){let n=xe(vi.operationId),r=await fe(Fe(s()),{method:vi.method,path:ve(vi.path,{cliAuthorizationId:e},vi.operationId),headers:{[n]:t}},hi);if(!r.ok)throw new bi(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Ti(r.headers[`retry-after`])}}async function wi(e,t){let n=xe(yi.operationId),r;try{r=await fe(Fe(s()),{method:yi.method,path:ve(yi.path,{cliAuthorizationId:e},yi.operationId),headers:{[n]:t}},pi)}catch(e){throw new xi(`acknowledge`,e,[t])}if(!r.ok)throw new bi(`acknowledge`,r.problem,[t]);return r.data}function Ti(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Ei(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Di(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())})`},[Wt.custom]:{enumerable:!1,value:a}})}async function Oi(e){let t=Fe(s()),n;try{n=await fe(t,{method:`GET`,path:_e(`getCurrentPersonalApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Ie)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${C(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: ${je(n.problem,[e])}`}}var ki=z(B,`revoke`);async function Ai(e){let t;try{t=Re(s().host)}catch(e){return x(`auth personal-logout: invalid API host — ${C(e)}`)}let n;try{n=await Be(t)}catch(e){return x(`auth personal-logout: stored credential could not be read — ${C(e)}`)}if(n.state===`unavailable`)return x(`auth personal-logout: ${n.summary}`);if(n.state===`missing`)return S(`No personal CLI credential is stored for this API host.`,{host:t,revoked:!1,forgotten:!1});let r=n.stored,i=await ji(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!e.forgetLocal)return{...x(`auth personal-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:Mi(r,!1,!1)};try{await et(r.host)}catch(e){return{...x(`auth personal-logout: local credential removal failed — ${C(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:Mi(r,a,!1)}}return S(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.`,Mi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the personal key may remain active.`]})}async function ji(e){let t=Fe(s());try{let n=await fe(t,{method:ki.method,path:ve(ki.path,{},ki.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Ie);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:je(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:C(t,[e.credential.secret])}}}function Mi(e,t,n){return{host:e.host,personalApiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Ni=`RSA_OAEP_256_A256_GCM_V1`,Pi=1,Fi=30,Ii=m().bin[0],Li=`The local record remains pending and unavailable to ordinary commands. Re-run \`${Ii} auth personal-login\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ri(e){if(!kt.isTTY)return x(`${Ii} auth personal-login 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=s().host;t=Re(e),n=Me(e)}catch(e){return x(`auth personal-login: invalid environment configuration — ${C(e)}`)}for(;;){let e;try{e=await rt(t)}catch(e){return x(`auth personal-login: credential storage could not be inspected — ${C(e)}`)}if(e.state===`unavailable`)return x(`auth personal-login: ${e.summary}`,[`Unlock OS credential storage, or use CLIENT_SECRET, ADMIN_API_KEY, or AUTH_TOKEN from the environment in a headless session.`]);if(e.state===`missing`)break;let n=await zi(e.stored);if(n!==null)return n}let r;try{r=await ei()}catch(e){return x(`auth personal-login: ephemeral encryption key could not be created — ${C(e)}`)}let i=Qr.safeParse({clientLabel:e.clientLabel?.trim()||(Tt().trim()||`aventure-cli`).slice(0,120),clientPlatform:Ui(),encryptionAlgorithm:Ni,encryptionPublicKey:r.publicKey});if(!i.success)return x(`auth personal-login: local authorization input is invalid`);let a;try{a=await Si(i.data)}catch(e){return x(`auth personal-login: could not start browser authorization — ${C(e)}`)}let o;try{o=ii(a,n)}catch(e){return x(`auth personal-login: unsafe browser authorization URL rejected — ${C(e)}`)}if(!Hi(await ai(a,n,{noBrowser:e.noBrowser}),a,o))return x(`auth personal-login: 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 c;try{c=await Vi(a)}catch(e){return x(`auth personal-login: authorization did not complete — ${C(e)}`,[],{references:[o]})}if(c.algorithm!==Ni)return x(`auth personal-login: broker selected an unsupported encryption algorithm`);let l;try{l=await ti(r.privateKey,c)}catch(e){return x(`auth personal-login: encrypted credential could not be opened — ${C(e)}`)}let u=await Oi(l);if(u.state!==`verified`)return x(`auth personal-login: decrypted credential was neither stored nor acknowledged — ${u.summary}`);let d;try{d=await nt(t,{apiKey:u.apiKey,secret:l},`pending`)}catch(e){return x(`auth personal-login: credential could not be durably stored — ${C(e)}`)}let f;try{f=await Bi(a)}catch(e){return V(d,!0,`auth personal-login: credential was stored and verified, but broker acknowledgment was not confirmed — ${C(e,[a.pollSecret])}`,Li)}if(f.status!==`CONSUMED`)return V(d,!0,`auth personal-login: broker returned ${f.status} after acknowledgment`,Li);let p=await Oi(l);if(p.state!==`verified`||!qi(p.apiKey,d.credential.apiKey))return V(d,!0,`auth personal-login: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${p.summary}`,Li);try{let e=await nt(t,{apiKey:p.apiKey,secret:l},`active`);return S(`Personal CLI credential stored; authenticated identity and broker acknowledgment verified.`,Ki(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return V(d,!0,`auth personal-login: remote acknowledgment succeeded, but local activation could not be confirmed — ${C(e)}`,Li)}}async function zi(e){let t=await Oi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?S(`Personal CLI credential is already stored and its authenticated identity was verified.`,Ki(e,!0),{ids:[e.credential.apiKey.id]}):V(e,!1,`auth personal-login: stored credential ${t.state} — ${t.summary}`,`Run \`${Ii} auth personal-logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&qi(t.apiKey,e.credential.apiKey))try{let n=await nt(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return S(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,Ki(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return V(e,!0,`auth personal-login: credential is valid but could not be promoted locally — ${C(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${Ii} auth personal-login\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return V(e,t.state===`verified`,`auth personal-login: 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 \`${Ii} auth personal-login\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await ji(e);if(n.outcome===`unconfirmed`)return V(e,!1,`auth personal-login: 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 et(e.host)}catch(t){return V(e,!1,`auth personal-login: stale pending credential could not be removed — ${C(t,[e.credential.secret])}`)}return j.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 Bi(e){let t=new Date(e.expiresAt).getTime(),n=Wi(e.intervalSeconds);for(;;)try{return await wi(e.id,e.pollSecret)}catch(e){if(e instanceof bi){if(!e.retryable)throw e;n=Wi(e.retryAfterSeconds??n)}else if(!(e instanceof xi))throw e;if(Date.now()>=t)throw e;j.write(`Broker acknowledgment was interrupted; retrying.
8
- `),await Gi(n,t)}}async function Vi(e){let t=new Date(e.expiresAt).getTime(),n=Wi(e.intervalSeconds),r;for(j.write(`Waiting for browser approval...
9
- `);Date.now()<t;){let i;try{i=await Ci(e.id,e.pollSecret)}catch(e){if(e instanceof bi){if(!e.retryable)throw e;n=Wi(e.retryAfterSeconds??n)}r=e,j.write(`Authorization poll was interrupted; retrying.
10
- `),await Gi(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Wi(i.retryAfterSeconds??n),await Gi(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(de(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: ${C(r,[e.pollSecret])}`)}function Hi(e,t,n){let r=e.state===`opened`;return!r&&!j.isTTY?!1:(j.write([...r?[`Browser approval opened for this request.`,`Approval reference: ${n}`]:[`Browser not opened automatically (${e.reason}).`,`Open this one-time approval URL in your browser:`,t.verificationUrl],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
11
- `)),!0)}function Ui(){switch(Et()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Wi(e){return Math.min(Fi,Math.max(Pi,e))}async function Gi(e,t){let n=t-Date.now();n>0&&await Kt(Math.min(e*1e3,n))}function Ki(e,t){return{host:e.host,provider:`keyring`,personalApiKeyId:e.credential.apiKey.id,name:de(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function V(e,t,n,r){return{...x(n,r===void 0?[]:[r]),data:Ki(e,t)}}function qi(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 Ji(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var Yi=`code`,Xi=`S256`;function Zi(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Ji(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Qi(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:$i(i,a,n);return;case`client_secret_post`:ea(i,a,r);return;case`none`:ta(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function $i(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function ea(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function ta(e,t){t.set(`client_id`,e)}async function na(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=Se.parse(JSON.parse(n));return new(ft[e]||lt)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new lt(r)}}async function ra(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?ra(e,void 0,n):void 0;throw r}}function ia(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function aa(e,{fetchFn:t=fetch,protocolVersion:n=it}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=ia(e);for(let{url:e,type:n}of i){let i=await ra(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?ge.parse(await i.json()):pe.parse(await i.json())}}}async function oa(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Yi))throw Error(`Incompatible auth server: does not support response type ${Yi}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xi))throw Error(`Incompatible auth server: does not support code challenge method ${Xi}`)}else s=new URL(`/authorize`,e);let c=await ot(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Yi),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Xi),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function sa(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function ca(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Qi(Zi(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await na(l);return be.parse(await l.json())}async function la(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return ca(e,{metadata:t,tokenRequestParams:sa(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ua(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await ca(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var da=3e5;async function fa(e,t){if(!kt.isTTY){let e=t??m().bin[0];return x(`${e} auth login requires an interactive TTY on stdin`,[`Use AUTH_TOKEN for non-interactive automation.`])}let n;try{n=tt(s().host)}catch(e){return x(`auth login: invalid API host — ${C(e)}`)}let r=await Ae(n);if(r.state===`missing`)return H(n,e);if(r.state===`unavailable`)return x(`auth login: ${r.summary}`);if(r.state===`invalid`)return H(n,e,`Saved OAuth credential cannot be read — ${r.summary}`);let{stored:i}=r;if(Pe(i.credential))return await pa(i,e);let a;try{a=await we(i.credential.tokens.access_token,va(i.credential.client))!==null}catch(t){return t instanceof se?H(n,e,`Saved OAuth credential was rejected`):x(`auth login: saved OAuth credential could not be verified — ${C(t,qe(i.credential.tokens))}`)}return a?S(`OAuth CLI access token is already stored and verified.`,wa(i)):H(n,e,`Saved OAuth credential was rejected`)}async function pa(e,t){let n=await De(e.host);if(n.state===`unavailable`)return x(`auth login: ${n.summary}`);let{client:r,tokens:i}=e.credential;if(i.refresh_token===void 0)return H(e.host,t,`Saved OAuth access token expired`,n);let a;try{let e=await ma(r);a=await ua(_a(r),{metadata:e,clientInformation:{client_id:xa(r)},refreshToken:i.refresh_token,resource:va(r)})}catch(r){return H(e.host,t,`Saved OAuth credential could not be renewed — ${C(r,qe(i))}`,n)}let o=await ha(r,a);return o.state===`failed`?x(`auth login: ${o.summary}`):o.state===`rejected`?H(e.host,t,`Renewed OAuth access token was rejected`,n):await ga(e.host,o.credential,`OAuth CLI access token renewed and verified.`)}async function H(e,t,n,r){let i=r??await De(e);if(i.state===`unavailable`)return x(`auth login: ${i.summary}`);n!==void 0&&j.write(`${n}; continuing to browser sign-in.\n`);let a;try{let e=await fe(Fe(s()),{method:`GET`,path:_e(`getAuthProviderCatalog`,{}),headers:{}},ht);if(!e.ok)throw Error(`provider catalog request failed: ${je(e.problem)}`);let t=e.data.oauthClient;if(t==null)throw Error(`the API does not advertise an OAuth CLI client`);a=t}catch(e){return x(`auth login: OAuth configuration is unavailable — ${C(e)}`)}let o;try{o=await ma(a)}catch(e){return x(`auth login: OAuth authorization-server discovery failed — ${C(e)}`)}let c=bt(32).toString(`base64url`),l;try{l=await Ca(ba(a),c);let n=await oa(_a(a),{metadata:o,clientInformation:{client_id:xa(a)},redirectUrl:l.redirectUri,resource:va(a),scope:Sa(a).join(` `),state:c}),r=await oi(n.authorizationUrl,{noBrowser:t.noBrowser});if(r.state!==`opened`&&!j.isTTY)return x(`auth login: browser authorization requires an interactive terminal for manual handoff`);j.write(r.state===`opened`?`Browser sign-in opened. Waiting for the loopback callback...
12
- `:`Browser not opened automatically (${r.reason}).\nOpen this OAuth sign-in URL in your browser:\n${n.authorizationUrl.toString()}\n\n`);let i=await l.waitForAuthorizationCode();if(i.state===`timed-out`)return x(`auth login: browser authorization timed out before the loopback callback arrived`);if(i.state===`failed`)return x(`auth login: ${i.message}`);let s;try{s=await la(_a(a),{metadata:o,clientInformation:{client_id:xa(a)},authorizationCode:i.authorizationCode,codeVerifier:n.codeVerifier,redirectUri:l.redirectUri,resource:va(a)})}catch(e){return x(`auth login: OAuth token exchange failed — ${C(e,[i.authorizationCode,n.codeVerifier])}`)}let u=await ha(a,s);return u.state===`failed`?x(`auth login: ${u.summary}`):u.state===`rejected`?x(`auth login: OAuth access token was rejected and was not stored`):await ga(e,u.credential,`OAuth CLI access token stored and verified.`)}catch(e){return x(`auth login: OAuth browser authorization failed — ${C(e)}`)}finally{await l?.close()}}async function ma(e){let t=await aa(_a(e));if(t===void 0||t.issuer!==e.authorizationServer)throw Error(`OAuth authorization-server metadata issuer must match its configured server`);if(!t.response_types_supported.includes(`code`)||t.code_challenge_methods_supported?.includes(`S256`)!==!0)throw Error(`OAuth authorization-server metadata must advertise authorization-code and PKCE S256 support`);return ya(t.authorization_endpoint,`authorization endpoint`,!0),ya(t.token_endpoint,`token endpoint`,!0),t}async function ha(e,t){let n;try{n=Le(e,t)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${C(e,qe(t))}`}}let r;try{r=await we(n.tokens.access_token,va(n.client))!==null}catch(e){return e instanceof se?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${C(e,qe(n.tokens))}`}}return r?{state:`accepted`,credential:n}:{state:`rejected`}}async function ga(e,t,n){try{let r=await Ke(e,t);return S(n,wa(r))}catch(e){return x(`auth login: OAuth credential could not be durably stored — ${C(e,qe(t.tokens))}`)}}function _a(e){return ya(e.authorizationServer,`authorization server`)}function va(e){return ya(e.resource,`resource`)}function ya(e,t,n=!1){let r;try{r=new URL(e)}catch(e){throw Error(`OAuth ${t} is not a valid URL`,{cause:e})}if(r.protocol!==`https:`||r.username.length>0||r.password.length>0||!n&&r.search.length>0||r.hash.length>0)throw Error(`OAuth ${t} must be an HTTPS URL without credentials${n?``:`, query`} or fragment`);return r}function ba(e){let t;try{t=new URL(e.redirectUri)}catch(e){throw Error(`OAuth callback configuration is not a valid URL`,{cause:e})}if(t.protocol!==`http:`||t.hostname!==`127.0.0.1`||t.port.length>0||t.pathname!==`/callback`||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0)throw Error(`OAuth callback configuration must be http://127.0.0.1/callback without a port, query, or fragment`);return t}function xa(e){if(e.clientId.trim()!==e.clientId||e.clientId.length===0)throw Error(`OAuth client ID must not be blank`);return e.clientId}function Sa(e){if(e.scope.length===0||e.scope.some(e=>e.trim()!==e||e.length===0)||new Set(e.scope).size!==e.scope.length)throw Error(`OAuth scope must contain unique non-blank values`);return e.scope}async function Ca(e,t){let n,r=new Promise(e=>{n=e}),i=Gt((r,i)=>{i.setHeader(`Cache-Control`,`no-store`),i.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let a=new URL(r.url??`/`,e);if(r.method!==`GET`||a.pathname!==e.pathname){i.statusCode=404,i.end(`OAuth callback not found.`);return}let o=a.searchParams.getAll(`state`),s=Buffer.from(o[0]??``),c=Buffer.from(t);if(o.length!==1||s.length!==c.length||!xt(s,c)){i.statusCode=400,i.end(`OAuth callback state did not match. Return to the CLI and retry.`);return}if(a.searchParams.has(`error`)){i.statusCode=400,i.end(`OAuth authorization was not completed. Return to the CLI.`),n({state:`failed`,message:`OAuth authorization server returned an error`});return}let l=a.searchParams.getAll(`code`),u=l[0]?.trim();if(l.length!==1||u===void 0||u.length===0){i.statusCode=400,i.end(`OAuth callback did not include an authorization code.`);return}i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u})});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${C(e)}`}));try{let t=Ht(i,`listening`);i.listen({host:`127.0.0.1`,port:0}),await t;let n=i.address();if(n===null||typeof n==`string`||n.port<=0)throw Error(`OAuth callback listener did not receive an ephemeral loopback port`);let a=new URL(e);return a.port=String(n.port),{redirectUri:a,waitForAuthorizationCode:async()=>{let e;return await Promise.race([r,new Promise(t=>{e=setTimeout(()=>t({state:`timed-out`}),da)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await Ta(i)}}catch(e){throw i.listening&&await Ta(i),e}}function wa(e){return{host:e.host,provider:`keyring`,expiresAt:e.credential.expiresAt,client:e.credential.client}}function Ta(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}function Ea(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===void 0?null:`keyring`,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:de(n.credential.apiKey.name,[n.credential.secret]),status:n?.credential.apiKey.status??null,expiresAt:r,metadataSource:n===void 0?null:`keyring-cache`,expiresInDay:Oa(r),keyringFailure:t.state===`unavailable`?t.summary:null,error:t.state===`invalid`?t.summary:null}}var Da=864e5;function Oa(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/Da)}var ka=7;function Aa(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ka)}\u2026${e.slice(-4)}`}var ja=13,Ma=14;function Na(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.personal.host}`+(e.apiVersion===null?` (api unreachable)`:` (api ${e.apiVersion})`),``,...Pa(e.oauth,e.cliName),...Fa(e.personal,e.oauth,e.cliName),``,...Ra(e.resolved,e.config),...e.systemOk?[]:[U(`System`,`uptime read failed`)]].join(`
13
- `)}function U(e,t){return` ${e.padEnd(ja)}${t}`}function W(e){return` ${``.padEnd(ja)}${e}`}function Pa(e,t){switch(e.state){case`found`:return[U(`OAuth`,`stored via keyring; identity is not cached`),W(Pe(e.stored.credential)?`access token expired — run \`${t} auth login\``:`cached expiry ${e.stored.credential.expiresAt}`)];case`missing`:return[U(`OAuth`,`none stored`)];case`unavailable`:return[U(`OAuth`,`keyring unavailable: ${e.summary}`)];case`invalid`:return[U(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function Fa(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.keyringFailure??(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`} ${Aa(e.apiKeyId)}`),...Ia(e,n),U(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ia(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(La(i,r))],W(`Clerk owns the live verdict \u2014 \`${t} auth personal-login\` refreshes this cache`)]}function La(e,t){return t<0?`cached expiry ${e} passed ${Math.abs(t)}d ago`:t<=Ma?`cached expiry ${e}, ${t}d away`:`cached expiry ${e}`}function Ra(e,t){return[U(`Secrets`,p.map(t=>Ba(t,e)).join(` `)),U(`Config`,t===null?`none`:`doppler ${t.project}/${t.config}`)]}function za(e){return p.map(t=>Ba(t,e)).join(` `)}function Ba(e,t){let n=t[e];return n.present?`${e}=${n.source??`resolved`}`:`${e}=${n.source===`config`?`config (unresolved)`:`unset`}`}var Va=r([`PROMPT`,`SKILL`,`AGENT`]),Ha=a({kind:Va,name:e(),version:e()}),Ua=a({content:e(),core:Ha}),Wa=a({key:e(),version:e()}),Ga=a({agent:o(e(),Wa),prompt:o(e(),Wa),skill:o(e(),Wa)}),G=`aventure`,Ka=`SKILL.md`,qa=`.aventure-skills.json`,Ja=`claude`,Ya=2e4,Xa=2,Za=[{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 Qa(e){return M($a(e))}function $a(e){return O(no(e),...e.detect)}function eo(e){return e.skill===null?null:O(no(e),...e.skill)}function to(e){return O(no(e),...e.mcp.file)}function no(e){return e.base===`home`?io(`HOME`)??wt():ro()}function ro(){return io(`XDG_CONFIG_HOME`)??O(io(`HOME`)??wt(),`.config`)}function io(e){let t=process.env[e]?.trim();return t===void 0||t.length===0?void 0:t}function ao(e){return O(D(e),qa)}function oo(e){if(!M(e))return{};try{let t=Ga.safeParse(JSON.parse(N(e,`utf8`)));return t.success?t.data.skill:{}}catch{return{}}}function so(e,t,n){let r=ao(e),i={...oo(r)};for(let e of n){let n=t.skill[e];n!==void 0&&(i[e]=n)}return lo(r,`${JSON.stringify({prompt:{},skill:i,agent:{}},null,Xa)}\n`)}function co(e,t,n){let r=O(e,t,Ka);return D(D(r))===e?lo(r,n):`refusing to install ${t}: it does not name one directory inside ${e}`}function lo(e,t){try{uo(e,t)}catch(t){return`cannot write ${e}: ${C(t)}`}return null}function uo(e,t){Nt(D(e),{recursive:!0});let n=`${e}.aventure-tmp`;try{P(n,t,`utf8`),Lt(n,e)}finally{Rt(n,{force:!0})}}var fo=RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*"?${G}"?[ \\t]*\\]`),po=/^[ \t]*mcp_servers[ \t]*=/m;function mo(e){let t=to(e);if(!M(t))return null;try{let n=N(t,`utf8`);if(e.mcp.shape===`toml`)return go(n);let r=xo(n)?.[e.mcp.key],i=(r!==void 0&&So(r)?r:void 0)?.[G];return i===void 0||!So(i)?null:typeof i.url==`string`?i.url:ho}catch{return null}}var ho=`unknown`;function go(e){let t=e.split(`
14
- `),n=t.findIndex(e=>fo.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 ho}function _o(e,t){let n=e.mcp,r=to(e);if(n.shape===`claude-cli`)return bo(t);try{if(n.shape===`toml`)return vo(r,t);yo(r,n.key,n.entry(t))}catch(e){return`cannot write ${r}: ${C(e)}`}return null}function vo(e,t){let n=M(e)?N(e,`utf8`):``,r=`[mcp_servers.${G}]\nurl = "${t}"\n`;return po.test(n)?`${e} declares mcp_servers as an inline table, which this command cannot extend; add by hand:\n${r}`:lo(e,`${n}${n.length===0||n.endsWith(`
15
- `)?``:`
16
- `}\n${r}`)}function yo(e,t,n){let r=xo(M(e)?N(e,`utf8`):`{}`);if(r===null)throw Error(`${e} is not a JSON object`);let i={...r},a=i[t];i[t]={...a!==void 0&&So(a)?a:{},[G]:n},uo(e,`${JSON.stringify(i,null,Xa)}\n`)}function bo(e){let t=[`mcp`,`add`,`--transport`,`http`,`-s`,`user`,G,e],n=vt(Ja,t,{encoding:`utf8`,timeout:Ya}),r=`${Ja} ${t.join(` `)}`;if(n.error!==void 0)return`run \`${r}\`: ${n.error.message}`;if(n.status!==0){let e=(n.stderr??``).trim().split(`
17
- `).slice(-2).join(` | `);return`\`${r}\` exited ${n.status}: ${e||`no stderr`}`}return null}function xo(e){let t=v.safeParse(JSON.parse(e));return t.success&&So(t.data)?t.data:null}function So(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Co=`aventure`;function wo(e,t=m().bin[0]){T(To(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 (${Za.map(e=>e.name).join(`, `)}),`,`install or refresh the published ${Co}* 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(`
18
- `)).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),L({mode:w(e)},await Eo(e))})}function To(e){let t=`agents`,n=e.commands.find(e=>e.name()===t);if(n!==void 0)return n;let r=Ge[t]?.summary??t;return e.command(t).summary(r).description(r)}async function Eo(e){let t=Ro();if(!t.ok||t.data===null)return{...t,data:null};let n=await Io(`getAgentInstructionManifest`,Ga);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(Co)).toSorted();if(a.length===0)return x(`The agent instruction manifest carries no ${Co}* skill; nothing to install.`);let o=Za.map(e=>Ao(e,r,a,i));return Do({runtime:e.status===!0?o:await Mo(o,r,i)},e,i)}function Do(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(Oo)].join(`
19
- `);if(r.length===0){let t=Za.map(e=>`${e.name}: no ${$a(e)}`);return{...x(s,t,{counts:o}),data:e}}let c=a.length>0?a:t.status===!0?i:[];return c.length===0?S(s,e,{counts:o}):{...x(s,c.map(ko),{counts:o}),data:e}}function Oo(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(ko).join(`; `)}`}function ko(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 Ao(e,t,n,r){let i=eo(e),a=to(e),o={name:e.name,skillDir:i,mcpConfig:a};if(!Qa(e))return{...o,detected:!1,action:[]};let s=mo(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?[]:jo(i,t,n),c]}}function jo(e,t,n){let r=oo(ao(e));return n.map(n=>{let i=t.skill[n]?.version??``,a=r[n]?.version,o=O(e,n,Ka);return a===void 0||!M(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 Mo(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 Fo(e));return e.map(e=>{let r=Za.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 No(r,e.mcpConfig,n);let o=Po(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:so(e.skillDir,t,a),c=s===null?[]:[K(`skill`,qa,`failed`,s)];return{...e,action:[...o,...c]}})}function No(e,t,n){let r=_o(e,n);return r===null?K(`mcp`,G,`current`,`registered ${n} in ${t}`):K(`mcp`,G,`failed`,r)}function Po(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=co(e,t,n.data.content);return r===null?K(`skill`,t,`current`,`${O(e,t,Ka)} at version ${n.data.core.version}`):K(`skill`,t,`failed`,r)}async function Fo(e){return await Io(`getAgentInstruction`,Ua,{kind:Va.enum.SKILL,name:e})}async function Io(e,t,n={}){let r=Lo(e);if(r===void 0)return x(`The generated command catalog carries no ${e} operation; regenerate it with \`make mcp-generate-contracts\` and reinstall.`);let i;try{i=_e(r.operationId,n)}catch(t){return x(`Cannot address ${e}: ${C(t)}`)}let a=await b({method:r.method,path:i,auth:r.auth,responseFormat:`json`}).catch(e=>x(C(e)));if(!a.ok)return{...a,summary:`${r.method} ${i} failed: ${a.summary}`,data:null};let o=a.data,s=t.safeParse(typeof o==`object`&&o&&`response`in o?o.response:void 0);return s.success?S(`${r.method} ${i} answered`,s.data):x(`${i} returned an unexpected body: ${s.error.message}`)}function Lo(e){return E.find(t=>t.operationId===e)}function Ro(){try{return S(`MCP host derived`,dt(s().host,`/mcp`).href)}catch(e){return x(`Correct API_ENV or pass \`--environment <name>\` — ${C(e)}.`)}}var zo=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,Bo=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Vo=`.aventure-cli-completion.bak`;function Ho(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Yo([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Yo([`--uninstall`]))}function Uo(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=qo(),n=await Ko({rcFile:k(wt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:os});A.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Yo(e.uninstall?[`--uninstall`]:[])})}function Wo(e,t=`fpath-only`){return[zo,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],Bo].join(`
20
- `)}function Go(){let e=Yo([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!Xo(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=Yo([],`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 Ko({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Zo(e),o=a.length===0?[]:a.split(`
21
- `),s=Qo(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?$o(o,s,t,e):es(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}:(rs(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function qo(e=A.argv[1]){let t=e===void 0?``:Jo(e),n=k(D(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return M(n)?n:k(D(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function Jo(e){try{return It(e)}catch{return k(e)}}function Yo(e,t=`inherit`){let n=vt(A.execPath,[qo(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(A.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function Xo(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Zo(e){return M(e)?(is(e),N(e,`utf8`)):``}function Qo(e,t){let n=ts(e,zo),r=ts(e,Bo);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 $o(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=ns(i),o=Wo(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
22
- `),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 as([...i.slice(0,c),...o,...i.slice(c)])}function es(e,t){return as(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function ts(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function ns(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function rs(e,t){Nt(D(e),{recursive:!0}),M(e)&&(is(e),is(`${e}${Vo}`),jt(e,`${e}${Vo}`));let n=k(D(e),`.${Dt(e)}.${A.pid}.tmp`);is(n),P(n,t,{mode:420}),Lt(n,e)}function is(e){if(M(e)&&Mt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function as(e){let t=e.join(`
23
- `);return t.length===0||t.endsWith(`
24
- `)?t:`${t}\n`}async function os(e){let t=qt({input:A.stdin,output:A.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var ss=new Intl.Collator(void 0,{numeric:!0}),cs=2e4;function ls(e,t=m()){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.`;T(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(`
25
- `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>L({mode:w(e)},us()))}function us(e,t=`apply`){let n=e;try{n??=m(process.argv[1])}catch(e){return x(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,a=ds([`view`,d,`version`,`--silent`,`--global`],n,{timeout:cs});if(!a.ok)return{...a,data:null};let o=(a.data??``).trim();if(o===``)return x(`npm view ${d} returned empty version`,[`empty_stdout`]);let s=ss.compare(i,o)<0,c={targetPackage:d,runningPackage:r,currentVersion:i,latestVersion:o,upgradeAvailable:s,upgradeInstalled:!1};if(t===`check`)return S(`${r}@${i} → ${d}@${o} (${s?`available`:`up to date`})`,c);if(!s)return S(`${r}@${i} already matches ${d}@${o}`,c);if(n.workingTreeRoot!==null)return x(`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=ps(n),u;try{u=ms(n,l)}catch(e){return x(`Cannot prepare MCP-owned CLI bins: ${_s(e)}`,[`npm install was not run`])}let f=[`install`,`-g`];l!==null&&f.push(`--prefix`,l.installPrefix),f.push(`${d}@${o}`);let p=ds(f,n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!p.ok){let e=hs(u,l?.installPrefix??null);return e===null?{...p,data:null}:x(`${p.summary}; MCP-owned CLI bin restoration failed`,[...p.warnings,e])}let h=l===null?void 0:fs(l.entryPath,o);if(h?.ok===!1){let e=hs(u,l?.installPrefix??null);return e===null?{...h,data:null}:x(`${h.summary}; MCP-owned CLI bin restoration failed`,[...h.warnings,e])}let g=gs(u);if(g!==null)return x(`${d} upgraded but MCP CLI bin backup cleanup failed`,[g]);let _=vs();return S(`${d} upgraded to ${o}`,{...c,upgradeInstalled:!0,installPrefix:l?.installPrefix,verifiedVersion:h?.data??void 0,completionRefreshed:_.refreshed,completionRefreshMessage:_.message})}function ds(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=vt(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?x(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):x(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
26
- `).slice(-3).join(` | `);return x(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return S(`npm ok`,a.stdout??``)}function fs(e,t){let n=vt(process.execPath,[e,`--version`],{encoding:`utf8`});if(n.error)return x(`updated ${d} verification failed: ${n.error.message}`,[`spawn_error`]);let r=(n.stdout??``).trim();if(n.status!==0||r!==t){let i=(n.stderr??``).trim().split(`
27
- `).slice(-3).join(` | `);return x(`updated ${d} verification expected ${t} but active bin reported ${r||`empty output`}`,[i||`active bin: ${e}`])}return S(`active CLI version verified`,r)}function ps(e){let t=`${Ot}lib${Ot}node_modules${Ot}${e.name.replace(`/`,Ot)}`,n=e.packageRoot.lastIndexOf(t),r=e.bin.includes(`aventure-cli`)?`aventure-cli`:e.bin[0];return n<0?null:{entryPath:k(e.packageRoot.slice(0,n),`bin`,r),installPrefix:e.packageRoot.slice(0,n)}}function ms(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}${Ot}`))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=k(t.installPrefix,`bin`,n),i=Mt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=It(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:Ft(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=Pt(k(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:k(r,Dt(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(Lt(e.binPath,e.backupPath),a.push(e),Ft(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=hs({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 hs(e,t){let n=t===null?null:k(t,`lib`,`node_modules`,...d.split(`/`)),r=[];for(let t of e.backup.toReversed())try{let e=Mt(t.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${t.binPath} is not a symlink`);let r=k(D(t.binPath),Ft(t.binPath));if(n===null||r!==n&&!r.startsWith(`${n}${Ot}`))throw Error(`${t.binPath} is not owned by the standalone CLI package`);Bt(t.binPath)}Lt(t.backupPath,t.binPath)}catch(e){r.push(_s(e))}if(e.backupDirectory!==null)try{zt(e.backupDirectory)}catch(e){r.push(_s(e))}return r.length===0?null:r.join(`; `)}function gs(e){let t=[];for(let n of e.backup)try{Bt(n.backupPath)}catch(e){t.push(_s(e))}if(e.backupDirectory!==null)try{zt(e.backupDirectory)}catch(e){t.push(_s(e))}return t.length===0?null:t.join(`; `)}function _s(e){return e instanceof Error?e.message:String(e)}function vs(){try{return Go()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var ys=[{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`}],bs=`operationFingerprint`;function xs(e,t=m().bin[0]){T(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: [...] }`:",...ys.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(`
28
- `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),L({mode:w(e)},await Ss(t))})}async function Ss(e){let t=ws(),n=Ts(e),[r,i]=await Promise.all([Es(e),Ds(t,e)]),a=[n.check,r,i.check,await ks(e),Is(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:Cs(a,`pass`),fail:Cs(a,`fail`),skip:Cs(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(`
29
- `);return c.ok?S(l,c,{counts:o}):{...x(l,s,{counts:o}),data:c}}function Cs(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function ws(){return E.find(e=>e.intent===`status`&&e.resource===`status`)}function Ts(e){let t=m(),n=us(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 Es(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\` — ${C(t)}.`)}}async function Ds(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=s().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${C(e)}.`),servedFingerprint:null}}let r=await b({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>x(C(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:Os(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 Os(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[bs];return typeof n==`string`&&n.length>0?n:null}async function ks(e){await c();let t;try{t=h(await me())}catch(t){return q(`auth`,`fail`,`Repair or remove ${y()} and run \`${e} auth init\` — ${C(t)}.`)}let[n,r]=await Promise.all([As(),js()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t[ye.authToken].present,a=p.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`&&Pe(n.stored.credential)?q(`auth`,`fail`,`Saved OAuth access token is expired; run \`${e} auth login\` to renew it or sign in again.`):!a&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Unlock OS OAuth credential storage before \`${e} auth login\`, or inject ${ye.authToken} through the environment — ${n.summary}.`):a||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${Ms(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Unlock OS credential storage before \`${e} auth personal-login\`, or inject ${p.join(`/`)} through the environment — ${r.summary}.`):p.some(e=>t[e].source===`config`)?q(`auth`,`fail`,`The Doppler source in ${y()} resolved no credential: confirm your access to that project and config, or inject ${p.join(`/`)} through the environment.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth, \`${e} auth personal-login\` for a personal credential, or \`${e} auth init\` to select a Doppler source.`)}async function As(){let e;try{e=tt(s().host)}catch(e){return{state:`unavailable`,summary:C(e)}}return await ke(e)}async function js(){let e;try{e=Re(s().host)}catch(e){return{state:`unavailable`,summary:C(e),cause:`environment`}}try{return await rt(e)}catch(e){return{state:`unavailable`,summary:C(e),cause:`keyring`}}}function Ms(e,t,n){return[...p.map(t=>`${t}=${Ns(e,t)}`),`oauth=${Fs(t)}`,`personal=${Ps(n)}`].join(` `)}function Ns(e,t){let n=e[t];return n.present?n.source??`resolved`:n.source===`config`?`config (unresolved)`:`unset`}function Ps(e){return e.state===`found`?e.stored.activation:e.state===`missing`?`unset`:`unavailable`}function Fs(e){switch(e.state){case`found`:return Pe(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 Is(e,t,n,r){let i=E.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 ${Xe}.`);if(t===`cd82b96a230a21a8`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Xe}).`);let a=`This catalog describes a different operation set than the API serves (${Xe} 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 Ls=z(B,`oauth`),Rs=z(B,`start`),zs=z(B,`poll`),Bs=z(B,`acknowledge`),Vs=z(B,`revoke`);function Hs(e,t=m().bin[0]){let n=Ws(e);xs(n,t),wo(e,t),T(Us(n,Ls,Ls.description)).action(async function(e){Gs(this),L({mode:w(e)},await fa({noBrowser:!e.browser},t))}),T(Us(n,Rs,[Rs,zs,Bs].map(({description:e})=>e).join(`
30
- `))).action(async function(e){Gs(this),L({mode:w(e)},await Ri({noBrowser:!e.browser,clientLabel:e.clientLabel}))}),T(Us(n,Vs,Vs.description)).action(async function(e){Gs(this),L({mode:w(e)},await Ai({forgetLocal:e.forgetLocal===!0}))}),T(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(`
31
- `))).action(async function(e){Gs(this),L({mode:w(e)},await Qs(t))}),T(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: OS-keyring OAuth access-token metadata for the selected API host, without the token`,` - personal: OS-keyring metadata for the selected API host, without the secret`,` - 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(`
32
- `))).action(async function(e){Gs(this),L({mode:w(e)},await Ks(t))})}function Us(e,t,n){let r=e.command(t.command.slice(t.command.indexOf(` `)+1)).summary(t.summary).description(n);for(let e of t.bodyOption)e.required?r.requiredOption(e.flag,e.description):r.option(e.flag,e.description);for(let e of t.localOption)r.option(e.flag,e.description);return r}function Ws(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Authentication, credential setup, API build, and uptime`).description([`\`${Ls.command}\`: ${Ls.summary}.`,`\`${Rs.command}\`: ${Rs.summary}.`,`\`${Vs.command}\`: ${Vs.summary}.`,"`auth status` reports local credential provenance plus 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(`
33
- `))}function Gs(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Ks(e){let t;try{t=await me()}catch(t){return x(`auth status: cannot read ${y()} — ${t instanceof Error?t.message:String(t)}`,[`configPath=${y()}`,`errorName=${t instanceof Error?t.name:`Error`}`,...sc(e)])}let n;try{n=tt(s().host)}catch(e){return x(`auth status: invalid API host — ${C(e)}`)}let[r,i,a,o]=await Promise.all([Zs(`/v1/status`,`GET /v1/status`),Zs(`/info`,`GET /info`),ke(n),Js(n)]),c=h(t),l=m().version,u=Ea(n,o),d=Na({cliName:e,cliVersion:l,apiVersion:i.ok?Ys(i.data):null,oauth:a,personal:u,resolved:c,config:t,systemOk:r.ok}),f={cli:{version:l},api:i.ok?i.data??null:null,auth:nc(t,c),oauth:qs(n,a),personal:u,system:r.ok?r.data??null:null,...i.ok?{}:{apiError:i.summary},...r.ok?{}:{systemError:r.summary}};return rc(c)||a.state===`found`||o.state===`found`?S(d,f):ic(`auth status: no credentials resolved | ${d}`,f,e,{oauth:a.state===`missing`,personal:o.state===`missing`})}function qs(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n===void 0?null:`keyring`,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:Pe(n.credential),client:n?.credential.client??null,keyringFailure:t.state===`unavailable`?t.summary:null,error:t.state===`invalid`?t.summary:null}}async function Js(e){try{return await rt(e)}catch(e){return{state:`invalid`,summary:C(e)}}}function Ys(e){if(!Xs(e))return null;let t=Yr.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 Xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Zs(e,t){return await b({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>x(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}async function Qs(e){if(!kt.isTTY)return x(`${e} auth init requires an interactive TTY on stdin`,["non-interactive caller: hand-write `~/.config/aventure/config.json` directly",...sc(e)]);let t=qt({input:kt,output:j});try{j.write(`${e} auth init\n\n`);let n=await $s(t);try{await g(n)}catch(t){return x(`auth init: cannot write ${y()} — ${t instanceof Error?t.message:String(t)}`,[`configPath=${y()}`,`errorName=${t instanceof Error?t.name:`Error`}`,...sc(e)])}return await c(),tc(`saved`,n,e)}finally{t.close()}}async function $s(e){return{source:`doppler`,project:await ec(e,`Doppler project: `),config:await ec(e,`Doppler config (e.g. staging): `)}}async function ec(e,t){for(;;){let n=(await e.question(t)).trim();if(n.length>0)return n;j.write(` required
34
- `)}}function tc(e,t,n){let r=h(t),i=`${oc(e,t,r)} | ${ac()}`,a=nc(t,r);return rc(r)?S(i,a):ic(`no credentials resolved | ${i}`,a,n)}function nc(e,t){return{configPath:y(),configSource:e?.source??null,...e?.source===`doppler`?{configProject:e.project,configConfig:e.config}:{},resolved:t}}function rc(e){return p.some(t=>e[t].present)}function ic(e,t,n,r={oauth:!0,personal:!0}){return{...x(e,[...r.personal?[`For a personal key, run \`${n} auth personal-login\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\` in an interactive terminal.`]:[],m().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 ac(){return`read=${ee(`read`).ok?`available`:`unavailable`} write=${ee(`write`).ok?`available`:`unavailable`}`}function oc(e,t,n){return`${e}: ${za(n)} | ${t===null?`no config`:`doppler ${t.project}/${t.config}`}`}function sc(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 cc(e,t,n=m().bin[0]){let r=Ir(t),i=e.find(e=>e.cliPath.join(` `)===r||e.cliAliasPath?.join(` `)===r||e.operationId===r);return i===void 0?x(`No generated operation matches "${t}"`,[`Resolve the exact command with \`${n} command-catalog search "<query>"\`.`]):S(`Resolved ${i.operationId}`,i)}function lc(e){return e.parameters.some(e=>e.location===`path`)?x(`${e.operationId} has path parameters and cannot be batch-driven`,[e.path]):S(`no path parameters`,null)}function uc(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)return x(`--query expects key=value, got "${n}"`);t[n.slice(0,e)]=n.slice(e+1)}return S(`query parsed`,t)}function dc(e,t,n,r){let i=Number(t);return!Number.isInteger(i)||i<n||i>r?x(`${e} must be an integer between ${n} and ${r}, got "${t}"`):S(`${e} parsed`,i)}function fc(e){let t=v.safeParse(e);return t.success?t.data:void 0}function pc(e,t){let n=fc(e);for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function mc(e){let t=fc(e);return typeof t!=`object`||!t||Array.isArray(t)?null:t}function hc(e){return typeof e==`object`&&e&&`response`in e?fc(e.response):fc(e)}function gc(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function _c(e){if(!M(e))return x(`--input file not found: ${e}`);let t=N(e,`utf8`),n=[],r=t.split(`
35
- `);for(let[e,t]of r.entries()){if(t.trim()===``)continue;let r=v.safeParse(xc(t));if(!r.success)return x(`--input line ${e+1} is not valid JSON`,[t.slice(0,120)]);n.push(r.data)}return n.length===0?x(`--input has no NDJSON rows: ${e}`):S(`input parsed`,{row:n,digest:Sc(t)})}function vc(e,t,n){let r={inputDigest:t,chunkSize:n,completedChunk:[]};if(e===void 0||!M(e))return S(`no checkpoint`,r);let i=xc(N(e,`utf8`));if(i===void 0)return x(`--checkpoint file is not valid JSON: ${e}`);let a=pc(i,`inputDigest`),o=pc(i,`chunkSize`),s=pc(i,`completedChunk`);if(a!==t||o!==n)return x(`--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 x(`--checkpoint ${e} has an invalid completedChunk list`);let c=s.filter(e=>Number.isInteger(e));return c.length===s.length?S(`checkpoint loaded`,{inputDigest:t,chunkSize:n,completedChunk:c}):x(`--checkpoint ${e} has an invalid completedChunk list`)}function yc(e,t,n,r){if(e===void 0)return;let i={inputDigest:t,chunkSize:n,completedChunk:[...r].toSorted((e,t)=>e-t)};P(e,`${JSON.stringify(i)}\n`)}function bc(e,t){return[...t,e]}function xc(e){try{return JSON.parse(e)}catch{return}}function Sc(e){return yt(`sha256`).update(e).digest(`hex`)}function Cc(e,t,n=m().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.`);wc(r,t,n),Tc(r,t,`preview`,n),Tc(r,t,`run`,n)}function wc(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(`
36
- `)).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`,bc,[]).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`);T(r),r.action(async function(){let e=this.optsWithGlobals();L({mode:w(e)},await Ec(t,e,n))})}function Tc(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(`
37
- `):`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`,bc,[]).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),T(i),i.action(async function(){let e=this.optsWithGlobals();L({mode:w(e)},await Dc(t,e,n,r))})}async function Ec(e,t,n){let r=cc(e,t.command,n);if(!r.ok||r.data===null)return r;if(ne(r.data.intent))return x(`${t.command} is a write operation; use \`batch run\``,[r.data.path]);let i=lc(r.data);if(!i.ok)return i;let a=uc(t.query??[]);if(!a.ok||a.data===null)return a;let o=dc(`--max-pages`,t.maxPages,1,1e6);if(!o.ok||o.data===null)return o;let s=t.fromFile===void 0?void 0:await Nn(t.fromFile);if(s!==void 0&&!s.ok)return s;let c=s===void 0?void 0:mc(s.data);if(s!==void 0&&c===null)return x(`--from-file must contain a JSON object`,[t.fromFile??``]);P(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 b({method:r.data.method,path:r.data.path,searchParams:e,body:c??void 0,auth:r.data.auth,responseFormat:`json`});if(!n.ok)return x(`page ${u+1} failed: ${n.summary}`,[`rows already written to ${t.out}: ${d}`,...l===void 0?[]:[`resume with --cursor "${l}"`]]);let i=hc(n.data),o=pc(i,t.rowsPath);if(!Array.isArray(o))return x(`response has no array at --rows-path "${t.rowsPath}"`,[`page ${u+1}`]);At(t.out,o.map(e=>`${JSON.stringify(e)}\n`).join(``)),u+=1,d+=o.length;let s=pc(i,t.nextCursorPath);if(typeof s!=`string`||s===``||s===l){f=!0;break}l=s}return S(`${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 Dc(e,t,n,r){let i=cc(e,t.command,r);if(!i.ok||i.data===null)return i;if(!ne(i.data.intent))return x(`${t.command} is not a write operation; use \`batch export\``,[i.data.path]);let a=lc(i.data);if(!a.ok)return a;let o=uc(t.query??[]);if(!o.ok||o.data===null)return o;let s=dc(`--chunk-size`,t.chunkSize,1,1e4);if(!s.ok||s.data===null)return s;let c=dc(`--concurrency`,t.concurrency,1,8);if(!c.ok||c.data===null)return c;let l=t.base===void 0?void 0:await Nn(t.base);if(l!==void 0&&!l.ok)return l;let u=mc(l?.data??{});if(u===null)return x(`--base must contain a JSON object`,[t.base??``]);let d=_c(t.input);if(!d.ok||d.data===null)return d;let f=gc(d.data.row,s.data),p=vc(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 S(`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}});P(t.out,``,{flag:m.size>0?`a`:`w`});let g=i.data,_=o.data,ee=d.data.digest,te=s.data,v=[],re=!1,ie=0,ae=async e=>{let n=f[e]??[],r={...u,[t.arrayField]:n},i=await b({method:g.method,path:g.path,searchParams:_,body:r,auth:g.auth,responseFormat:`json`}),a=i.ok?hc(i.data):null;return At(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),yc(t.checkpoint,ee,te,m),!0):(v.push(e),!1)};await Promise.all(Array.from({length:c.data},async()=>{for(;!re;){let e=h[ie];if(ie+=1,e===void 0)return;!await ae(e)&&t.haltOnFailure&&(re=!0)}}));let oe={rowCount:d.data.row.length,chunkCount:f.length,completedChunkCount:m.size,failedChunkCount:v.length,remainingChunkCount:f.length-m.size-v.length},se={outPath:t.out,checkpointPath:t.checkpoint,failedChunk:v,halted:re};return v.length>0?x(`${v.length} chunk(s) failed; responses in ${t.out}${t.checkpoint===void 0?``:`, resume via --checkpoint ${t.checkpoint}`}`,[JSON.stringify({...se,...oe})]):S(`${m.size}/${f.length} chunks sent; responses in ${t.out}`,se,{counts:oe})}function Oc(e,t=E,n=m().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(()=>{A.stdout.write(Ac(e,i,t))});Ho(r,n),Uo(r,n)}function kc(){return m().bin}function Ac(e,t,n=E,r=kc()){let i=zc(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Mc(e),...r.map(e=>`complete -c ${J(e)} -e`),`${Zc(r)} -f`,...Nc(e,r),...Pc(e,i,r),``].join(`
38
- `):jc(e,t,i,r)}function jc(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=Hc(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}`),`)`,``,...Gc(t),...t===`bash`?[a,``]:[``]].join(`
39
- `)}function Mc(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Fc(e).filter(e=>e.required||e.optional).flatMap(e=>Jc(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
40
- set -l expected $argv
41
- set -l actual (__aventure_cli_command_path)
42
- if test (count $actual) -ne (count $expected)
43
- return 1
44
- end
45
- if test (count $expected) -eq 0
46
- return 0
47
- end
48
- for index in (seq (count $expected))
49
- if test $actual[$index] != $expected[$index]
50
- return 1
51
- end
52
- end
53
- return 0
54
- end
55
- `].flatMap(e=>e.split(`
56
- `))}function Nc(e,t){return Vc(e).map(e=>`${Zc(t)} -f -n ${J(Qc(e.parentPath))} -a ${J(e.name)} -d ${J(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Pc(e,t,n){return Yc(e).flatMap(e=>{let r=Xc(e),i=r.length===0?void 0:Qc(r);return Fc(e).flatMap(e=>{let a=t.get(Bc(r,e));return Wc(a)?Ic(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Fc(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function Ic(e,t,n,r){let i=Jc(e);if(i===void 0)return[];let a=e.argChoices??Uc(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?Lc(a,Rc(i,n)):`-f`,l=`${Zc(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${J($c(e.description))}`]:a.map(t=>`${l} -a ${J(t)} -d ${J($c(e.description))}`)}function Lc(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function Rc(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 zc(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...Tn(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[Bc(e.cliPath,n),t]})))}function Bc(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):Jc(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 Vc(e){return Yc(e).flatMap(e=>e.commands.map(t=>({parentPath:Xc(e),name:t.name(),description:$c(t.summary()||t.description()||t.name())})))}function Hc(e,t){let n=[],r=[];for(let i of Yc(e)){let e=Xc(i);for(let a of Fc(i)){let i=Jc(a);if(i===void 0)continue;let o=t.get(Bc(e,a));if(!Wc(o))continue;let s=a.argChoices??Uc(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&Rc(i,o)&&(c=`file`)),n.push(Kc([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(Kc([e.join(` `),`--${i}`,t,a.description]))}}return[Vc(e).map(e=>Kc([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 Uc(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 Wc(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function Gc(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 Kc(e){return`$'${e.map(qc).join(`|`)}'`}function qc(e){return $c(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function Jc(e){return e.long?.replace(/^--/,``)}function Yc(e){return[e,...e.commands.flatMap(e=>Yc(e))]}function Xc(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function Zc(e){return`complete ${e.map(e=>`-c ${J(e)}`).join(` `)}`}function Qc(e){return[`__aventure_cli_path_is`,...e.map(J)].join(` `)}function $c(e){return e.replace(/\s+/g,` `).trim()}function J(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function el(e,t){if(e!==t)return;let n=tl(t);n!==void 0&&t.error(`error: ${rl(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function tl(e){if(!process.argv.includes(`--`)&&e.args.some(nl))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function nl(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function rl(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function il(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function al(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function ol(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function sl(e){return e.flags.split(` `)[0]??e.flags}function cl(e,t){let n=il(t);if(n===void 0)return;let r=e.options.findIndex(e=>sl(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[sl(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 ll(e){return e.commands.length===0?[e]:e.commands.flatMap(ll)}function ul(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 dl(e,t){return t.toSorted((t,n)=>{let r=ul(e,t),i=ul(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 fl(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function pl(e,t){let n=Y(e),r=process.argv.slice(2+n.length);return[X(e).name(),...n,...ul(e,t),...r].map(fl).join(` `)}function ml(e,t){let n=al(t);if(n===void 0||e.commands.length===0)return;let r=dl(e,ll(e).filter(e=>e.options.some(e=>sl(e)===n)));if(r!==void 0)return`hint: run: ${pl(e,r)}`}function hl(e){return e!==void 0&&Object.hasOwn(Ge,e)}function gl(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 _l(e,t){let n=Y(e),r=[...n.slice(1),t];if(!hl(n.at(0))||!hl(r.at(0)))return;let i=gl(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 vl(e,t){let[n]=Y(e);if(!hl(n))return;let r=[n,t];return gl(X(e),r)?.commands.length===0?r:void 0}function yl(e){let[t,...n]=e.args;if(t===void 0)return[];let r=ll(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 bl(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=Ve(E).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(fl).join(` `)}`}function xl(e,t,n){if(!Cl(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(fl).join(` `)}`}function Sl(e){let t=Y(e);if(t.at(1)!==void 0&&hl(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(fl).join(` `)}`}function Cl(e,t){let n=e.join(` `);return E.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 wl(e){let t=Y(e);if(hl(t.at(0))&&Cl(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(fl).join(` `)}`}function Tl(e){let t=new Set,n=[];for(let r of E){let i=gl(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(sl);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 El(e,t){let n=Y(e);if(Cl(n,!1)&&Tl(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Dl(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=>sl(e)===`--root`);return n&&s!==void 0&&c!==void 0&&hl(s)&&o.push(sl(c),s),`hint: search generated commands: ${o.map(fl).join(` `)}`}function Ol(e,t){let n=ol(t);if(n===void 0||t.message.includes(`
57
- (Did you mean `))return;let r=yl(e),i=bl(e,r);if(i!==void 0)return i;let a=_l(e,n);if(a!==void 0)return Dl(e,a.join(` `),!1);let o=vl(e,n);if(o!==void 0)return xl(e,o,r)??Dl(e,o.join(` `),!1);let s=r.join(` `)||n;return Sl(e)??Dl(e,s)}function kl(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[tl(e),cl(e,t)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=tl(e)??wl(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=al(t),r=ml(e,t)??(n!==void 0&&!t.message.includes(`
58
- (Did you mean `)?El(e,n)??Dl(e,n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Ol(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Al=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 jl(e){e.showHelpAfterError(!1).exitOverride(kl(e)),e.commands.length===0?e.hook(`preAction`,el):e.addHelpOption(new Al(e));for(let t of e.commands)jl(t)}var Ml=`dist/aventure-cli/command-catalog.compact.txt`,Nl=` · `,Pl=`-`;function Fl(e=m().bin[0]){return k(Il(D(Vt(import.meta.url)),e),Ml)}function Il(e,t){let n=e;for(;;){if(M(k(n,`package.json`)))return n;let r=D(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Ll(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Rl(e,t,n,r=m().bin[0]){let i=fr(e,t,r);if(!i.ok){L({mode:n},i);return}Bl({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Hl(i.data,Vl(e.format,`lines`)),summary:`Generated operation matches`})}function zl(e,t,n,r=m().bin[0]){let i=pr(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}Bl({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Ul(i.data,Vl(e.format,`usage`)),summary:`Generated operation detail`})}function Bl(e){let t=e.mode,n=e.rendered.endsWith(`
59
- `)?e.rendered:`${e.rendered}\n`;if(e.opts.output!==void 0){P(e.opts.output,n),L({mode:t},S(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(n,`utf8`),format:Vl(e.opts.format,e.defaultFormat)},{counts:Jl(e.data)}));return}if(t===`text`){process.stdout.write(n);return}L({mode:t},S(e.summary,e.data,{counts:Jl(e.data)}))}function Vl(e,t){return e??t}function Hl(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
60
- `):t===`text`?Kl(e.operation):t===`compact`?e.operation.map(Wl).join(`
61
- `):e.operation.map(ql).join(`
62
- `)}function Ul(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?ql(e.operation):t===`compact`?Wl(e.operation):e.usage}function Wl(e){let t=Gl(e);return[e.cli.command,e.summary,t.length===0?Pl:t.join(` `)].join(Nl)}function Gl(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Kl(e){return e.map(e=>`${e.cli.command}\n ${ql(e)}`).join(`
63
- `)}function ql(e){let t=Gl(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 Jl(e){return`count`in e?e.count:{returned:1}}function Yl(e,t=new Date){let n=Ql(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 Xl(e){return`${JSON.stringify(e,null,2)}\n`}function Zl(e,t){let n=k(e),r=Xl(t);return Nt(D(n),{recursive:!0}),P(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function Ql(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:l(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 $l=`Match only the first canonical or CLI-alias command segment`;function eu(e,t,n=m().bin[0]){nu(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(`
64
- `));r.addHelpText(`after`,()=>`\nShipped compact catalog, greppable without running this CLI:\n ${Fl(n)}\n`),tu(r,t,n),au(r,t,n),ou(r,t,n),su(r)}function tu(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>`,$l).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`);T(r),r.action(function(e){let r=this.optsWithGlobals(),i=w(r,`text`),a=r.limit?.trim()??``,o=a===``?NaN:Number(a);if(!Number.isInteger(o)||o<0){L({mode:i},x(`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}Rl(Ll(r,e),t,i,n)})}function nu(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(`
65
- `)).argument(`<selector...>`,`METHOD and path, an operationId, or a CLI command path`);T(r),r.action(function(e){let r=this.optsWithGlobals(),i=w(r),a=iu(e,t);if(!a.ok||a.data===null){L({mode:i},a);return}zl({...r,...a.data},t,i,n)})}var ru='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function iu(e,t){let[n,...r]=e,i=ue.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return S(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=he(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return S(`Resolved by route template`,{operationId:s.operationId});let c=le({method:a,path:o});return!c.ok||c.data===null?x(c.summary,[...c.warnings,ru]):S(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function au(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`);T(r),r.action(function(){let e=this.optsWithGlobals();zl(e,t,w(e,`text`),n)})}function ou(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>`,$l).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`);T(r),r.action(function(){let e=this.optsWithGlobals();Rl(e,t,w(e,`text`),n)})}function su(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`);T(t),t.action(function(){let e=this.optsWithGlobals(),t=w(e,`text`),n=Yl(gt);if(e.output!==void 0){let r=Zl(e.output,n);L({mode:t},S(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(Xl(n));return}L({mode:t},S(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var cu=m(Vt(import.meta.url)),Q=cu.bin[0];function lu(e,t){f({component:`aventure-cli`,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`),ir({...x(`${Q} ${t}: ${e.message}`,[e.name||`Error`]),counts:{exitCode:1}}),process.exit(1)}function uu(e){return Je[$e(e)??`cli`]}function du(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:uu(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec);for(let t of n)fu(e,t,t.cliPath),t.cliAliasPath!==void 0&&t.cliAliasPath.join(` `)!==t.cliPath.join(` `)&&fu(e,t,t.cliAliasPath)}function fu(e,t,n){let r=e,i=``;for(let e of n.slice(0,-1))i=i===``?e:`${i} ${e}`,r=gu(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=>ce(e.schemaType,e.itemSchemaType))?Te:``].filter(Boolean).join(`
66
- `));for(let e of t.parameters)_u(o,e);In(o,t),ne(t.intent)&&o.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),T(o);let c=pu(t);if(c!==void 0){o.argument(`[text...]`,c.description||`Same as ${hu(c.flag)}.`),o.action(async function(e){let n=this.optsWithGlobals(),r=w(n),i=mu(c,e,n);return L({mode:r},i.ok&&i.data!==null?await vu(t,i.data,r):i)});return}o.action(async function(){let e=this.optsWithGlobals(),n=w(e),r=await vu(t,e,n);r.ok&&r.data instanceof Uint8Array?process.stdout.write(r.data):L({mode:n},r)})}function pu(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 mu(e,t,n){let r=t.join(` `).trim();return r.length===0?S(`No positional text`,n):n[e.optionKey]===void 0?S(`Positional text parsed`,{...n,[e.optionKey]:r}):x(`Use either the positional argument or ${hu(e.flag)}, not both.`)}function hu(e){return e.split(` `)[0]??e}function gu(e,t,n){let r=e.commands.find(e=>e.name()===t);if(r!==void 0)return r;let i=Ge[n],a=e.command(t);return i!==void 0&&a.summary(i.summary).description(i.summary),a}function _u(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 vu(e,t,n){if(t.environment!==void 0){let e=oe(t.environment);if(e===null)return x(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${ie().join(`, `)}`]);process.env.API_ENV=e}let r=await Vn(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 b({method:e.method,path:_e(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:typeof t.contentType==`string`?t.contentType:void 0,auth:e.auth,responseFormat:ze(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0})}process.on(`uncaughtException`,e=>lu(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>lu(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var yu=Qe(process.argv.slice(2),E),bu=yu===`required`?E:Ve(E),$=new re;$.name(Q).configureHelp({helpWidth:1/0}).version(cu.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 ${ae})`).choices([...ie()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),du($,bu),Hs($,Q),ls($,cu),Cc($,bu,Q),Oc($,bu,Q),eu($,bu,Q),Lr($,bu,Q),qr($,bu);for(let e of $.commands)e.helpGroup()||e.helpGroup(uu(e.name()).heading);if(jl($),yu===`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 c(),await Oe(),await We())}))}}$.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(`
67
- `));try{await $.parseAsync()}catch(e){lu(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};