@aventurevc/aventure-cli 0.8.80 → 0.8.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aventure-cli/index.js +1 -1
- package/dist/aventure-cli/unified-operations.json +1 -1
- package/dist/chunks/aventure-cli-DAem7-7s.js +67 -0
- package/dist/chunks/{client-Crj4ZlqG.js → client-DIIL1OMZ.js} +1 -1
- package/dist/chunks/{oauth-bearer-credential-BCAM49rO.js → oauth-bearer-credential-NM9Y1Exb.js} +2 -2
- package/dist/chunks/oauth-login-CS4C5BkV.js +1 -0
- package/dist/chunks/{oauth-login-Dx0-i5Kr.js → oauth-login-DkhO9MAb.js} +1 -1
- package/dist/chunks/{openapi-commands-CcltxKpW.js → openapi-commands-BCrHJmS5.js} +1 -1
- package/dist/chunks/provider-catalog-BTXlVpD7.js +1 -0
- package/dist/chunks/{text-field-Dg2MUYnB.js → text-field-Bwrj-Da1.js} +1 -1
- package/dist/chunks/text-response-PQC2nyx8.js +22 -0
- package/package.json +3 -3
- package/dist/chunks/aventure-cli-b77ujbYh.js +0 -65
- package/dist/chunks/oauth-login-C24wzgmD.js +0 -1
- package/dist/chunks/provider-catalog-C7Q6SSmn.js +0 -1
- package/dist/chunks/text-response--7xESGBO.js +0 -14
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{_i as e,ci as t,gi as n,la as r,ui as i}from"../chunks/client-
|
|
2
|
+
import{_i as e,ci as t,gi as n,la as r,ui as i}from"../chunks/client-DIIL1OMZ.js";import{t as a,v as o}from"../chunks/oauth-bearer-credential-NM9Y1Exb.js";import{i as s}from"../chunks/text-field-Bwrj-Da1.js";import{c,i as l,t as u}from"../chunks/openapi-commands-BCrHJmS5.js";var d=process.argv.slice(2);l(d)&&i(!1),d.includes(`--all-fields`)&&s(!0);try{if(e(),c(d,u)===`optional`)try{await a(),await o()}catch(e){t({component:n().bin[0],event:`optional_auth_materialization_failed`,message:`saved credential unavailable; continuing with credential-optional command`,error:e})}await import(`../chunks/aventure-cli-DAem7-7s.js`)}catch(e){if(!(e instanceof r))throw e;process.stderr.write(`${e.message}\n`),process.exitCode=e.exitCode}export{};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"generatedFrom": "MCP_GENERATION_CONTRACT",
|
|
4
|
-
"generatedAt": "2026-10-
|
|
4
|
+
"generatedAt": "2026-10-07T00:07:45.865Z",
|
|
5
5
|
"totalOperations": 136,
|
|
6
6
|
"note": "Projection of MCP_GENERATION_CONTRACT - see mcp/scripts/build-unified-operations.ts header for SSOT rules.",
|
|
7
7
|
"operations": [
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import{Ai as e,C as t,Ci as n,D as r,Di as i,Oi as a,S as o,Ti as s,a as c,b as l,bi as u,c as d,ca as f,ci as p,d as m,f as h,gi as g,i as _,ki as v,l as y,m as b,mi as ee,n as te,o as x,oa as ne,oi as re,p as ie,r as ae,sa as S,u as oe,ua as se,v as ce,vi as C,wi as le,xi as ue,y as de}from"./client-DIIL1OMZ.js";import{M as fe,O as pe,i as w,o as me,v as he,w as T,y as E}from"./person-owner-BJgNYLKX.js";import{A as ge,C as _e,D as ve,M as D,N as ye,O as be,S as xe,T as Se,a as Ce,b as we,c as Te,d as Ee,g as De,j as Oe,k as ke,l as Ae,m as je,o as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./oauth-bearer-credential-NM9Y1Exb.js";import{c as Ve,d as He,h as Ue,m as We,o as Ge,p as Ke,s as qe,u as Je}from"./text-field-Bwrj-Da1.js";import{a as Ye,c as Xe,d as Ze,f as Qe,g as $e,h as et,l as tt,m as nt,n as rt,o as O,p as it,r as k,s as at,t as A,u as ot}from"./openapi-commands-BCrHJmS5.js";import{a as st,c as ct,i as j,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./text-response-PQC2nyx8.js";import{n as gt,r as _t,t as vt}from"./oauth-login-DkhO9MAb.js";import{spawnSync as yt}from"node:child_process";import{basename as bt,dirname as M,resolve as N,sep as xt}from"node:path";import{copyFileSync as St,existsSync as Ct,lstatSync as wt,mkdirSync as Tt,mkdtempSync as Et,readFileSync as Dt,readlinkSync as Ot,realpathSync as kt,renameSync as At,rmdirSync as jt,unlinkSync as Mt,writeFileSync as Nt}from"node:fs";import P,{stderr as F,stdin as Pt}from"node:process";import{TextDecoder as Ft,inspect as It}from"node:util";import{fileURLToPath as Lt}from"node:url";import{readFile as Rt}from"node:fs/promises";import{setTimeout as zt}from"node:timers/promises";import{webcrypto as Bt}from"node:crypto";import{homedir as Vt,hostname as Ht,platform as Ut}from"node:os";import{createInterface as Wt}from"node:readline/promises";function Gt(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 o=r[n.optionKey];if(o!==void 0&&(typeof o!=`string`||o!==i))return{...a(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};o===void 0&&(r[n.optionKey]=i)}return v(`Environment-bound options applied`,r)}function Kt(e,t,n){if(!I(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||!sn(n,r.name))continue;let a=on(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 qt(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 Jt(e,t,n,r=!1){if(r||!un(t)||!Array.isArray(n))return fn(e,t,n);for(let[r,i]of n.entries()){let n=fn(e,t,i,r);if(!n.ok)return n}return v(`Body value assigned`,null)}function Yt(e,t,n,r){return fn(e,t,r,n)}function Xt(e){let t=[];for(let n of e.split(`.`)){let e=mn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Zt(e,t){let n=Xt(t);if(n===null)return null;let r=an(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:rn(r)}:null}function Qt(e,t){if(un(e.name)||e.schemaType===`array`)return v(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return v(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?v(`Scalar body option selected`,t[0]):a(`${n} was already given; pass it once.`)}var $t=/^(?<row>\d+):(?<item>.*)$/su;function en(e,t){let n=Xt(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=$t.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 tn(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Xt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function nn(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let o=Zt(r,i.name);if(o===null)continue;if(o.firstHole!==null)return a(`${e} has no ${o.path}[] row ${o.firstHole} — number ${o.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||o.rowCount<=1||en(i,t)!==null)continue;let s=i.flag.split(` `)[0]??i.name;return a(`${s} fills one ${o.path}[] row's list, so ${e} cannot also build ${o.rowCount} ${o.path}[] rows from direct options — prefix each value with its 0-based ${o.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function rn(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function an(e,t){let n=e;for(let e of t){if(!I(n))return;n=n[e]??null}return n}function on(e,t){if(!un(t))return an(e,t.split(`.`))}function sn(e,t){return ln(e,t.split(`.`))}function cn(e,t,n){if(!I(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)&&sn(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function ln(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=mn(n);if(!I(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>ln(e,r)):ln(a,r)}function un(e){return e.split(`.`).some(e=>mn(e).isArray)}function dn(e,t){return e.parameter.length===0||!I(t)?null:gn(t,[],hn(e.parameter))}function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fn(e,t,n,r=0){let i=t.split(`.`),o=e;for(let[e,s]of i.entries()){let c=mn(s),l=e===i.length-1,u=pn(o,c,t,l,n,r);if(!u.ok||u.data===null)return a(u.summary,u.warnings);if(l)return v(`Body value assigned`,null);o=u.data}return a(`${t} is not a valid body option path.`)}function pn(e,t,n,r,i,o){let s=()=>a(`${n} cannot be combined with another body option at ${t.key}.`),c=e[t.key];if(t.isArray){if(c!==void 0&&!Array.isArray(c))return s();let n=c??[];if(c===void 0&&(e[t.key]=n),r)return n[o]===void 0?(n[o]=i,v(`Body value assigned`,e)):s();let a=n[o];if(a===void 0){let e={};return n[o]=e,v(`Body path created`,e)}return I(a)?v(`Body path stepped`,a):s()}if(r)return c===void 0?(e[t.key]=i,v(`Body value assigned`,e)):s();if(c===void 0){let n={};return e[t.key]=n,v(`Body path created`,n)}return I(c)?v(`Body path stepped`,c):s()}function mn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function hn(e){let t=new Set,n=new Set;for(let r of e){let e=`${r.name}${r.schemaType===`array`?`[]`:``}`;t.add(e);let i=e.split(`.`);for(let e=1;e<i.length;e+=1)n.add(i.slice(0,e).join(`.`))}return{leaf:t,prefix:n}}function gn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=gn(r,t,n);if(e!==null)return e}return null}if(!I(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!_n(a,n)){if(!vn(e))continue;return{path:a,suggestion:yn(e,n)}}let o=gn(i,e,n);if(o!==null)return o}return null}function _n(e,t){return t.prefix.has(e)||t.leaf.has(e)}function vn(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function yn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``;return[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:bn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path))[0]?.path}function bn(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 xn(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(We(e)),t.description=d(t.description,{...e,hasParseDefault:t.defaultValue!==void 0}))}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?kn(r,i):r===void 0?i===void 0?0:1:-1})}function Sn(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 Cn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function wn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:Dn(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 Tn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function En(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?Ue(n):`${Ue(n)} Required JSON paths: ${r.join(`, `)}.`}function Dn(e,t){let n=He(t.description,void 0),r=e.kind!==`multipart`&&un(t.name),i=e.kind!==`multipart`&&t.optionKey!==t.name&&/^\w+$/u.test(t.name);return`${n}${r?` Repeat to add another value.`:``}${i?` --from-file JSON key: ${t.name}.`:``}${On(e,t)}`}function On(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Xt(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 kn(e,t){return Ke(e)-Ke(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function An(e){let t;try{t=e===`-`?await jn():await Rt(e,`utf8`)}catch(t){return a(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return v(`No input provided`,null);let e=JSON.parse(t);return v(`Input parsed`,e)}catch(e){return a(`Input is not valid JSON: ${e.message}`)}}async function jn(){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 Mn=`--content-type`;function Nn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),i=t.requestBody??[];if(i.length>1&&r(Mn)){let t=i.map(({contentType:e})=>e);e.addOption(new S(`${Mn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Fn(i)))}if(er(t)&&r(`--from-file`)){let n=i[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new S(`--from-file <path>`,En(n,n.requiredPath)).argParser(Ln(`--from-file`)))}let a=Sn(i).filter(e=>r(L(e.variant[0].parameter)));for(let t of a.toSorted((e,t)=>kn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],a=new S(Cn(t),i.length>1?wn(t):Dn(n,r));i.length===1&&r.envName!==void 0&&a.env(r.envName);let o=i.length===1?Tn(n,r.optionKey):[];o.length>0&&a.conflicts(o),i.length>1?a.argParser(Pn):un(r.name)||r.schemaType===`array`?a.argParser(In):a.argParser(Ln(r.flag)),e.addOption(a),a.envVar!==void 0&&e.on(`optionEnv:${a.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}$n(e,t,a)}function Pn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Fn(e){return(t,n)=>{if(n!==void 0)throw new se(`${Mn} was already given; pass it once.`);let i=r(e,t);if(!i.ok)throw new se(i.summary);return t}}function In(e,t){return[...t??[],e]}function Ln(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new se(`${t} was already given; pass it once.`);return e}}async function Rn(e,t){let n=Ze(e,t),i=r(e.requestBody??[],n);if(!i.ok||i.data===null)return a(i.summary,i.warnings);let o=i.data;if(o===void 0)return v(`No body`,void 0);let s=zn(e,o,t);if(s!==null)return a(s);let c=Gt(e.operationId,o,t);if(!c.ok)return a(c.summary,c.warnings);t=c.data;let l=Bn(o,t);if(l!==null)return a(l);let u=await Wn(t);if(!u.ok)return a(u.summary,u.warnings);let d=cn(e.requestBody??[],o,u.data);if(d!==null)return a(d);let f=Un(e.operationId,o,u.data);if(!f.ok)return f;let p=Kt(e.operationId,o,u.data);if(p!==null)return a(p);let m=Gn(e.operationId,o,t);if(!m.ok)return m;if(u.data===void 0&&m.data===void 0)return o.required?a(Qn(e.operationId,o)):v(`No body`,void 0);let h=qn(e.operationId,u.data,m.data);if(!h.ok||h.data===void 0)return h;if(o.schemaType===`array`&&!Array.isArray(h.data))return a(`${e.operationId} requires a JSON array body.`);if(o.parameter.length>0&&!I(h.data)){let t=o.kind===`multipart`?` keyed by multipart part name`:` body`;return a(`${e.operationId} requires a JSON object${t}.`)}let g=Hn(o,h.data);if(g.length>0)return a(`${e.operationId} requires body option(s): ${g.join(`, `)}`);let _=h.data,y=I(_)?qt(o).filter(e=>!sn(_,e)):[];return y.length>0?a(Vn(e.operationId,o,y)):h}function zn(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`${L(t)} requires ${Mn} ${i.join(` or `)}.`}return null}function Bn(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 Vn(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 Hn(e,t){return I(t)?e.parameter.filter(e=>e.required&&!sn(t,e.name)).map(L):[]}function Un(e,t,n){let r=dn(t,n);if(r===null)return v(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return a(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Wn(t){let n=typeof t.fromFile==`string`?t.fromFile:void 0;if(n===void 0)return v(`No body file`,void 0);let r=await An(n);if(!r.ok)return a(r.summary,r.warnings);let i=e.safeParse(r.data);return i.success?v(`Input parsed`,i.data):a(`Input is not valid JSON value: ${i.error.message}`)}function Gn(e,t,n){let r={},i=!1;for(let e of t.parameter){let o=Qt(e,n[e.optionKey]);if(!o.ok||o.data===null)return a(o.summary,o.warnings);let s=o.data;if(s===void 0)continue;let c=Kn(t,n,r,e,s);if(!c.ok)return a(c.summary,c.warnings);i=!0}if(!i)return v(`No direct body options`,void 0);let o=nn(e,t,n,r);return o===null?v(`Direct body options parsed`,r):o}function Kn(e,t,n,r,i){let o=en(r,i);if(o===null){let e=Xn(r,i);return e.ok?Jt(n,r.name,e.data,r.schemaType===`array`):a(e.summary,e.warnings)}if(o.plain.length>0)return a(`${L(r)} mixes row-form values with plain value(s): ${o.plain.join(`, `)} — prefix every value with its 0-based ${o.container}[] row index, as 0:value.`);let s=tn(e,t,o.container);for(let e of o.rows.keys())if(!(e<s))return a(`${L(r)} names ${o.container}[] row ${e}, but these options build at most ${s} ${o.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 o.rows){let i=[];for(let e of t){let t=Zn(r.name,r.itemSchemaType,e);if(!t.ok)return a(t.summary,t.warnings);i.push(t.data)}let o=Yt(n,r.name,e,i);if(!o.ok)return o}return v(`Body value assigned`,null)}var L=e=>e.flag.split(` `)[0]??e.name;function qn(e,t,n){if(t===void 0)return v(`Direct body parsed`,n);if(n===void 0)return v(`Input parsed`,t);if(I(t)&&I(n))try{return v(`Input parsed`,Jn(t,n))}catch(t){return a(`${e} ${t.message}`)}return a(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Jn(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&&Yn(t)!==Yn(r))throw Error(`cannot combine --from-file ${Yn(t)} '${e}' with ${Yn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=I(t)&&I(r)?Jn(t,r):r}return n}function Yn(e){return Array.isArray(e)?`array`:I(e)?`object`:`scalar`}function Xn(e,t){if(typeof t==`boolean`)return v(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Zn(e.name,e.schemaType,t??``);let n=[],r=un(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Zn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return v(`Body value parsed`,n)}function Zn(e,t,n){if(t===`boolean`)return n===`true`?v(`Body value parsed`,!0):n===`false`?v(`Body value parsed`,!1):a(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?a(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?a(`${e} must be an integer.`):v(`Body value parsed`,i)}return v(`Body value parsed`,n)}function Qn(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(L).join(`, `)}`;let r=qt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(L).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function $n(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:Mn,location:`body`}),er(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),xn(e.options,r)}function er(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function tr(e){let t=i(e);return ur(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function nr(e){let t=i(e);ur(t);let n=mt(t.data,t.summary),r=[];if(t.ok&&n!==null){let e=rr(t);r.push(n.endsWith(`
|
|
2
|
+
`)?n.slice(0,-1):n),r.push(...e),process.stdout.write(lt(r.join(`
|
|
3
|
+
`),!0,!0,e.length));return}let a=t.ok?`OK`:`FAIL`;r.push(`[${a}] ${t.summary}`),!t.ok&&t.problem!==void 0&&r.push(...or(t.problem)),r.push(...rr(t)),process.stdout.write(lt(r.join(`
|
|
4
|
+
`),!0))}function rr(e){let t=[];e.ids.length>0&&t.push(` ids: ${e.ids.join(`, `)}`);for(let[n,r]of Object.entries(e.counts))t.push(` ${n}: ${r}`);for(let n of e.references)t.push(` ref: ${n}`);if(e.truncation!==void 0){let n=e.truncation.omitted.join(`, `);t.push(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${n}`,` recovery: ${e.truncation.recovery}`)}for(let n of e.warnings)t.push(` warn: ${n}`);return t}function R(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?i(t):t;ur(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?ir(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?tr(t):t;e.mode===`text`&&nr(n),n.ok||(process.exitCode=1)}function ir(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 ar(e,t){let n=ft(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
|
|
5
|
+
`),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function or(e){let t=[];typeof e.code==`string`&&t.push(` code: ${e.code}`),typeof e.detail==`string`&&t.push(` detail: ${e.detail}`),typeof e.hint==`string`&&t.push(` hint: ${e.hint}`),typeof e.suggestion==`string`&&t.push(` suggestion: ${e.suggestion}`);let n=Object.entries(e.suggestions??{});if(n.length>0){let e=n.map(([e,t])=>`${e}=${t}`).join(`; `);t.push(` suggestions: ${e}`)}return typeof e.requiredRole==`string`&&t.push(` requiredRole: ${e.requiredRole}`),t.push(...sr(e),...cr(`unknownParameters`,e.unknownParameters),...cr(`validParameters`,e.validParameters),...lr(e.resolution)),t}function sr(e){let t=[];return typeof e.limitType==`string`&&t.push(`limitType=${e.limitType}`),typeof e.used==`number`&&t.push(`used=${e.used}`),typeof e.limit==`number`&&t.push(`limit=${e.limit}`),typeof e.remaining==`number`&&t.push(`remaining=${e.remaining}`),typeof e.resetAt==`string`&&t.push(`resetAt=${e.resetAt}`),typeof e.windowSeconds==`number`&&t.push(`windowSeconds=${e.windowSeconds}`),typeof e.retryAfterSeconds==`number`&&t.push(`retryAfterSeconds=${e.retryAfterSeconds}`),t.length>0?[` meter: ${t.join(` `)}`]:[]}function cr(e,t){return t!=null&&t.length>0?[` ${e}: ${t.join(`, `)}`]:[]}function lr(e){if(e==null)return[];let t=[`action=${e.action}`];return 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}`),[` resolution: ${t.join(` `)}`]}function ur(e){e.ok&&e.warnings.length===0||p({component:g().bin[0],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 dr(e,t,n=g().bin[0]){let r=e.limit===void 0?void 0:Number(e.limit);if(r!==void 0&&(e.limit?.trim()===``||!Number.isInteger(r)||r<0))return a(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=ht(e.q??``,ct(t,n).filter(t=>hr(t,e)),e=>({...e,cliPath:e.cli.path,enumParameter:e.flags.map(({choices:e,location:t})=>({values:e,direct:t!==`body`})),parameterName:e.flags.flatMap(({wireName:e,optionKey:t})=>[e,t]),directParameterName:e.flags.filter(({location:e})=>e!==`body`).map(({wireName:e})=>e),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),o=i.slice(0,r);return v(`Operation catalog matches`,{operation:o,count:{totalOperations:t.length,matched:i.length,returned:o.length}})}function fr(e,t,n=g().bin[0]){let r=ct(t,n),i=e.operationId===void 0?pr(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let i=br(e.command??``),o=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${i} `));if(o.length>0)return a(`${i} is a command group; show one of its subcommands.`,[`Run \`${n} command-catalog show --command "<subcommand>"\` with one of:`,...o]);let s=i.split(` `),c=new Set([...[...s.keys()].map(e=>s.slice(e+1).join(` `)),...s.slice(1).map((e,t)=>s.toSpliced(t,2,`${s[t]}-${e}`).join(` `))]),l=dr({q:e.command??e.operationId},t,n),u=[...r.filter(({cli:e})=>e.path.length>1&&c.has(e.path.join(` `))).toSorted((e,t)=>t.cli.path.length-e.cli.path.length),...l.data?.operation??[]];return a(`Generated operation not found`,[...[...new Set(u.map(({cli:e,operationId:t})=>`${e.command} (operationId ${t})`))].slice(0,3).map(e=>`closest: ${e}`),`List candidates with \`${n} command-catalog search "<text>"\`.`])}return v(`Generated operation detail`,{operation:i,usage:_r(i,r)})}function pr(e,t){if(t===void 0)return;let{bin:n}=g(),r=br(t,n);return e.find(e=>br(e.cli.command,n)===r)}var mr=(e,t)=>e===void 0||e===`all`||e===`any`||e===String(t);function hr(e,t){return(t.root===void 0||gr(e,t.root))&&mr(t.scope,e.scope)&&mr(t.mutates,e.mutates)&&mr(t.destructive,e.destructive)&&mr(t.intent,e.intent)&&mr(t.method,e.method)}function gr(e,t){let n=dt(t);return n.length===0||dt(e.cli.path.at(0)??``)===n}function _r(e,t){let n=st(e);return[`cli: ${e.cli.command}`,`${e.method} ${e.path}`,`operationId: ${e.operationId}`,`resource: ${e.resource}`,`intent: ${e.intent}`,`scope: ${e.scope}`,`mutates: ${e.mutates}`,`destructive: ${e.destructive}`,`mcpTool: ${e.mcpTool??`unavailable (CLI-only operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,...[!0,!1].flatMap(e=>[`path`,`query`,`header`,`body`].map(t=>yr(`${e?`required`:`optional`} ${t} flags`,n.filter(n=>n.required===e&&n.location===t)))),...pt(e,t),...vr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
|
|
6
|
+
`)}function vr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}function yr(e,t){return`${e}: ${t.length===0?`none`:t.map(e=>e.name).join(` `)}`}function br(e,t=g().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var xr=`dist/aventure-cli/command-catalog.compact.txt`,Sr=` · `,Cr=`-`;function wr(e=g().bin[0]){return N(Tr(M(Lt(import.meta.url)),e),xr)}function Tr(e,t){let n=e;for(;;){if(Ct(N(n,`package.json`)))return n;let r=M(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Er(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Dr(e,t,n,r=g().bin[0]){let i=dr(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}kr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:jr(i.data,Ar(e.format,`lines`)),summary:`Generated operation matches`})}function Or(e,t,n,r=g().bin[0]){let i=fr(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}kr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Mr(i.data,Ar(e.format,`usage`)),summary:`Generated operation detail`})}function kr(e){let t=e.mode,n=Ar(e.opts.format,e.defaultFormat),r=e.opts.text===!0||e.opts.allFields===!0;if(e.opts.output===void 0&&r&&(n===`json`||n===`ndjson`)){R({mode:t},a(`--text or --all-fields cannot be combined with --format json or ndjson`,[`Omit the text flag for machine output, or use --format lines, compact, or text.`]));return}let i=e.opts.output===void 0&&t===`text`&&`count`in e.data&&e.data.count.matched===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,o=i.endsWith(`
|
|
7
|
+
`)?i:`${i}\n`;if(e.opts.output!==void 0){Nt(e.opts.output,o),R({mode:t},v(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(o,`utf8`),format:n},{counts:Lr(e.data)}));return}if(t===`text`){process.stdout.write(o);return}R({mode:t},v(e.summary,e.data,{counts:Lr(e.data)}))}function Ar(e,t){return e??t}function jr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
|
|
8
|
+
`):t===`text`?Fr(e.operation):t===`compact`?e.operation.map(Nr).join(`
|
|
9
|
+
`):e.operation.map(Ir).join(`
|
|
10
|
+
`)}function Mr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Ir(e.operation):t===`compact`?Nr(e.operation):e.usage}function Nr(e){let t=Pr(e);return[e.cli.command,e.summary,t.length===0?Cr:t.join(` `)].join(Sr)}function Pr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Fr(e){return e.map(e=>`${e.cli.command}\n ${Ir(e)}`).join(`
|
|
11
|
+
`)}function Ir(e){let t=Pr(e);return[z(`operationId`,e.operationId),z(`scope`,e.scope),z(`mutates`,String(e.mutates)),z(`destructive`,String(e.destructive)),z(`intent`,e.intent),z(`resource`,e.resource),z(`cli`,e.cli.command),e.mcpTool===null?``:z(`mcpTool`,e.mcpTool),z(`method`,e.method),z(`path`,e.path),z(`auth`,e.auth),z(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),z(`requiredFlags`,t.join(` `)),z(`bodyKind`,e.body.kind??``),z(`bodyRequired`,String(e.body.required)),z(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function z(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Lr(e){return`count`in e?e.count:{returned:1}}function Rr(e,t,n=g().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show full documentation for a command, or ask a question`).description([`Show a command's full documentation offline. Select it by command path,`,"operationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.","`help ask <question>` or `help --ask <question>` answers a platform question."].join(`
|
|
12
|
+
`)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new zr(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Gr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),k(r),r.action(async function(r){let o=this.optsWithGlobals();if(o.help&&r.length===0){this.outputHelp();return}if(!o.help&&i!==void 0&&o.ask!==void 0){let e=O(o);if(r.length>0){R({mode:e},a(`Use either a command path or --ask, not both.`));return}R({mode:e},await Yr(i,o.ask,o.environment,e));return}let s=Jr(e,r),c=t.find(t=>s!==void 0&&Jr(e,t.cliPath)===s);if(o.help||s!==void 0&&c===void 0){s===void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),s.outputHelp();return}let l=c===void 0?qr(r,t):v(`Resolved by command path`,{operationId:c.operationId});if(l.ok&&l.data?.command!==void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),!l.ok||l.data===null){R({mode:O(o)},l);return}Or({...o,...l.data},t,O(o,`text`),n)}),Wr(e,t,n)}var zr=class extends S{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},Br=2,Vr=6,Hr={formatHelp(e,t){let n=n=>f.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),n));if(t.visibleCommands(e).length===0)return n({});let r=t.padWidth(e,t),i={padWidth:()=>r,visibleOptions:()=>[],showGlobalOptions:!1},a=n({...i,visibleCommands:()=>[]}),o=n({padWidth:()=>r,visibleCommands:()=>[]}).slice(a.length);return n(i)+o},visibleCommands(e){let t=f.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>!Ve.has(e.name())):t},subcommandTerm(e){let t=f.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,n,r){let i=r.helpWidth??80,a=i-t-4;return n===``||a>=r.minWidthToWrap?f.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Br)}${e}\n${Ur(n,i,r)}`}};function Ur(e,t,n){return n.boxWrap(e,t-Vr).replace(/^/gmu,` `.repeat(Vr))}function Wr(e,t,n){for(let r of t){let i=Jr(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp();e.prepareContext({helpWidth:i.configureOutput().getOutHelpWidth?.()});let a=e.helpWidth??80,o=ut(r.operationId,t,n),[s,...c]=vr(r.errorResponse),l=c.map(t=>Ur(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Br))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
|
|
13
|
+
`)}\n`})}}function Gr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&Xr(e)!==void 0});return n.length===0?t:void 0}var Kr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function qr(e,t){let[n,...r]=e,i=ie.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return v(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let o=y(i),s=r.join(``),l=t.find(e=>e.method===o&&e.path===s);if(l!==void 0)return v(`Resolved by route template`,{operationId:l.operationId});let u=c({method:o,path:s});return!u.ok||u.data===null?a(u.summary,[...u.warnings,Kr]):v(`Resolved by method and path`,{operationId:u.data.operation.operationId})}function Jr(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(t===void 0)return;n=t}return n}async function Yr(e,t,n,r){let i=Xr(e);if(i===void 0)return a(`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 o=await Rn(e,{[i.optionKey]:t});return o.ok?await x({method:e.method,path:ae(e.operationId,{}),searchParams:{},body:o.data,auth:e.auth,responseFormat:Ye(r)?`json`:`auto`}):o}function Xr(e){if(e.requestBody?.length!==1||e.parameters.some(e=>e.required))return;let t=(e.requestBody[0]?.parameter??[]).filter(e=>e.required);return t.length===1&&t[0]?.schemaType===`string`?t[0]:void 0}function Zr(e,t,n){if(e.cliPath[0]!==`lookup`||!Qr(n))return null;let r=e.parameters.filter(e=>t[e.optionKey]!==void 0).map(e=>`${e.name}=${String(t[e.optionKey])}`),i=`no record for ${r.length===0?`the given input`:r.join(`, `)}`;return n.ok?a(i):a(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function Qr(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}function $r(e,t){if(e.deprecated!==!0)return t;let n=e.description.match(/^Deprecated:[^.]*\./u)?.[0]??`Deprecated; run \`help ${e.cliPath.join(` `)}\` for its replacement.`;return{...t,warnings:[n,...t.warnings]}}var ei=E({artifact:T().nullish(),group:T().nullish(),name:T().nullish(),revision:T().nullish(),time:w({offset:!0}).nullish(),version:T().nullish()}),ti=E({build:ei}),ni=me([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),ri=me([`RSA_OAEP_256_A256_GCM_V1`]),ii=E({clientLabel:T().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:ni.nullish(),encryptionAlgorithm:ri.nullish(),encryptionPublicKey:T().min(344).max(12e3).nullish()}),ai=32;async function oi(){let e=await Bt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await Bt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function si(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=ci(n,`wrapped key`,128,1024),s=ci(r,`nonce`,12,12),c=ci(i,`ciphertext`,1,65536),l=ci(a,`authentication tag`,16,16),u;try{u=await Bt.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!==ai)throw Error(`broker credential used an invalid AES-256 key`);let e=await Bt.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 Bt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Ft(`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 ci(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 li=me([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),ui=me([`Denied by user`,`Authorization request expired`,`CLI authorization expired before acknowledgement`,`Credential issuance recovery revoked an unrecoverable key`,`Revoked by user`,`Clerk create response validation failed`,`Credential issuance failed`,`Credential issuance could not be recovered`,`API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),di=E({approvedAt:w({offset:!0}).nullish(),clientLabel:T(),clientPlatform:ni,comparisonCode:T(),consumedAt:w({offset:!0}).nullish(),createdAt:w({offset:!0}),expiresAt:w({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),keyReadyAt:w({offset:!0}).nullish(),status:li,terminalAt:w({offset:!0}).nullish(),terminalReason:ui.nullish(),updatedAt:w({offset:!0})}),fi=E({algorithm:ri,authenticationTag:T(),ciphertext:T(),nonce:T(),wrappedKey:T()}),pi=E({delivery:fi.nullish(),expiresAt:w({offset:!0}),status:li,terminalReason:ui.nullish()}),mi=E({comparisonCode:T(),expiresAt:w({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),pollSecret:T(),verificationUrl:T()}),B=[{command:`auth login`,role:`oauth`,summary:`Sign In Through Your Browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign In With a Browser-Approved aVenture API Key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved aVenture API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI Authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI Credential Delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign Out: Revoke the API Key and Forget Stored OAuth`,description:`Revokes the aVenture API key authenticating this request and returns its metadata so the CLI can confirm revocation before deleting its saved copy.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Delete the saved key even when revocation cannot be confirmed.`}]}],hi=j(B,`start`),gi=j(B,`poll`),_i=j(B,`acknowledge`),V=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${ye(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Ci(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},vi=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${D(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function yi(e){let t=await oe(ge(s()),{method:hi.method,path:b(hi.path,{},hi.operationId),headers:{},contentType:`application/json`,body:e},mi);if(t.ok&&t.redirect)throw new V(`start`,wi(t.status));if(!t.ok)throw new V(`start`,t.problem);return Ti(t.data)}async function bi(e,t){let n=_(gi.operationId),r=await oe(ge(s()),{method:gi.method,path:b(gi.path,{cliAuthorizationId:e},gi.operationId),headers:{[n]:t}},pi);if(r.ok&&r.redirect)throw new V(`poll`,wi(r.status),[t]);if(!r.ok)throw new V(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Si(r.headers[`retry-after`])}}async function xi(e,t){let n=_(_i.operationId),r;try{r=await oe(ge(s()),{method:_i.method,path:b(_i.path,{cliAuthorizationId:e},_i.operationId),headers:{[n]:t}},di)}catch(e){throw new vi(`acknowledge`,e,[t])}if(r.ok&&r.redirect)throw new V(`acknowledge`,wi(r.status),[t]);if(!r.ok)throw new V(`acknowledge`,r.problem,[t]);return r.data}function Si(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Ci(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function wi(e){return{status:e,title:`Unexpected redirect`,type:`about:blank`,code:void 0,detail:`CLI authorization endpoint returned an unexpected redirect`}}function Ti(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())})`},[It.custom]:{enumerable:!1,value:a}})}async function Ei(e){let t=await Di(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`),verification:t}}catch(n){return{stored:e,verification:{state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${D(n,[e.credential.secret])}`}}}}async function Di(e){let t=ge(s()),n;try{n=await oe(t,{method:`GET`,path:ae(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Re)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${D(t,[e])}`}}return n.ok&&n.redirect?{state:`unavailable`,summary:`identity verification returned unexpected redirect ${n.status}`}:n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${ye(n.problem,[e])}`}}var Oi=j(B,`revoke`);async function ki(e){let t;try{t=Be(s().host)}catch(e){return a(`auth logout: invalid API host — ${D(e)}`)}let n=await Ai(t),r=await Ni(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],o={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?v(`No CLI credential is stored for this API host.`,o):n.state===`failed`?{...a(`auth logout: ${i[0]}`),data:o}:v(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,o,{warnings:i}):{...r,data:{...r.data??o,oauth:n},warnings:[...r.warnings,...i]}}async function Ai(e){let t=await Me(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Mi(t.stored):{revoked:!1};try{await Ce(e)}catch(e){return{state:`failed`,summary:D(e)}}return{state:`forgotten`,...n}}async function ji(e){let t=Reflect.get(await vt(e),`revocation_endpoint`);return typeof t==`string`?De(t,`revocation endpoint`,!0):void 0}async function Mi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await ji(t);if(e===void 0)return{revoked:!1};let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:r,client_id:Ie(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:D(e,je(n))}}}async function Ni(e,t){let n;try{n=await xe(e)}catch(e){return a(`auth logout: stored credential could not be read — ${D(e)}`)}if(n.state===`unavailable`)return{...a(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Pi(r),o=i.outcome===`revoked`,s=r.activation===`pending`&&i.outcome===`rejected`;if(!o&&!s&&!t.forgetLocal)return{...a(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.summary}`,[`Retry when the API is available. If an earlier response was lost after revocation, the retry can be unauthorized because revoked keys cannot authenticate.`,"Use `--forget-local` only to remove local bytes while accepting that the remote key may remain active."]),data:Fi(r,!1,!1)};try{await we(r.host)}catch(e){return{...a(`auth logout: local credential removal failed — ${D(e,[r.credential.secret])}`,[o?"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:Fi(r,o,!1)}}return v(o?`API key revoked remotely and removed locally.`:s?`Stale pending CLI credential removed; its remote key can no longer authenticate and unacknowledged keys expire at the authorization deadline.`:`API key removed locally without confirmed remote revocation.`,Fi(r,o,!0),{ids:[r.credential.apiKey.id],warnings:o||s?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Pi(e){let t=ge(s());try{let n=await oe(t,{method:Oi.method,path:b(Oi.path,{},Oi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Re);return n.ok&&n.redirect?{outcome:`unconfirmed`,summary:`remote key revocation returned unexpected redirect ${n.status}`}:n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:n.data.status===`REVOKED`?{outcome:`revoked`,summary:`remote key revocation confirmed`}:{outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}:{outcome:n.problem.status===401&&n.problem.type!==`about:blank`?`rejected`:`unconfirmed`,summary:ye(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:D(t,[e.credential.secret])}}}function Fi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Ii=`RSA_OAEP_256_A256_GCM_V1`,Li=1,Ri=30,H=g().bin[0],zi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${H} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Bi(e){if(!Pt.isTTY)return a(`${H} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=s().host;t=Be(e),n=ke(e)}catch(e){return a(`auth login --key: invalid environment configuration — ${D(e)}`)}for(;;){let e;try{e=await ze(t)}catch(e){return a(`auth login --key: credential storage could not be inspected — ${D(e)}`)}if(e.state===`unavailable`)return a(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use AUTH_TOKEN from the environment.`]);if(e.state===`missing`){e.keyringFailure!==void 0&&F.write(Se(e.keyringFailure));break}let n=await Vi(e.stored);if(n!==null)return n}let r;try{r=await oi()}catch(e){return a(`auth login --key: ephemeral encryption key could not be created — ${D(e)}`)}let i=ii.safeParse({clientLabel:e.clientLabel?.trim()||(Ht().trim()||H).slice(0,120),clientPlatform:Gi(),encryptionAlgorithm:Ii,encryptionPublicKey:r.publicKey});if(!i.success)return a(`auth login --key: ${fe(i.error)}`);let o;try{o=await yi(i.data)}catch(e){return a(`auth login --key: could not start browser authorization — ${D(e)}`)}let c;try{c=be(o,n)}catch(e){return a(`auth login --key: unsafe browser authorization URL rejected — ${D(e)}`)}if(!Wi(await ve(o,n,{noBrowser:e.noBrowser}),o,c))return a(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[c]});let l;try{l=await Ui(o)}catch(e){return a(`auth login --key: authorization did not complete — ${D(e)}`,[],{references:[c]})}if(l.algorithm!==Ii)return a(`auth login --key: broker selected an unsupported encryption algorithm`);let u;try{u=await si(r.privateKey,l)}catch(e){return a(`auth login --key: encrypted credential could not be opened — ${D(e)}`)}let d=await Di(u);if(d.state!==`verified`)return a(`auth login --key: decrypted credential was neither stored nor acknowledged — ${d.summary}`);let f;try{f=await _e(t,{apiKey:d.apiKey,secret:u},`pending`)}catch(e){return a(`auth login --key: credential could not be durably stored — ${D(e)}`)}let p;try{p=await Hi(o)}catch(e){return U(f,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${D(e,[o.pollSecret])}`,zi)}if(p.status!==`CONSUMED`)return U(f,!0,`auth login --key: broker returned ${p.status} after acknowledgment`,zi);let m=await Di(u);if(m.state!==`verified`||!Yi(m.apiKey,f.credential.apiKey))return U(f,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${m.summary}`,zi);try{let e=await _e(t,{apiKey:m.apiKey,secret:u},`active`);return v(`API key stored; authenticated identity and broker acknowledgment verified.`,Ji(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return U(f,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${D(e)}`,zi)}}async function Vi(e){let t=await Di(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?v(`API key is already stored and its authenticated identity was verified.`,Ji(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${H} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&Yi(t.apiKey,e.credential.apiKey))try{let n=await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return v(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,Ji(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return U(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${D(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${H} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return U(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${H} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Pi(e);if(n.outcome===`unconfirmed`)return U(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await we(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${D(t,[e.credential.secret])}`)}return F.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
|
|
14
|
+
`:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
|
|
15
|
+
`),null}async function Hi(e){let t=new Date(e.expiresAt).getTime(),n=Ki(e.intervalSeconds);for(;;)try{return await xi(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=Ki(e.retryAfterSeconds??n)}else if(!(e instanceof vi))throw e;if(Date.now()>=t)throw e;F.write(`Broker acknowledgment was interrupted; retrying.
|
|
16
|
+
`),await qi(n,t)}}async function Ui(e){let t=new Date(e.expiresAt).getTime(),n=Ki(e.intervalSeconds),r;for(F.write(`Waiting for browser approval...
|
|
17
|
+
`);Date.now()<t;){let i;try{i=await bi(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=Ki(e.retryAfterSeconds??n)}r=e,F.write(`Authorization poll was interrupted; retrying.
|
|
18
|
+
`),await qi(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Ki(i.retryAfterSeconds??n),await qi(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:throw Error(m(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${D(r,[e.pollSecret])}`)}function Wi(e,t,n){let r=e.state===`opened`;return!r&&!F.isTTY?!1:(F.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...F.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
|
|
19
|
+
`)),!0)}function Gi(){switch(Ut()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Ki(e){return Math.min(Ri,Math.max(Li,e))}async function qi(e,t){let n=t-Date.now();n>0&&await zt(Math.min(e*1e3,n))}function Ji(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:m(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...a(n,r===void 0?[]:[r]),data:Ji(e,t)}}function Yi(e,t){return e.expiresAt===null||e.expiresAt===void 0||t.expiresAt===null||t.expiresAt===void 0?!1:new Date(e.expiresAt)>new Date(t.expiresAt)}async function Xi(){return null}async function Zi(e){let t=null,n=e=>{t=e};try{await Fe(e,n),await Le(n)}catch(e){return{materialized:t,failure:D(e)}}return{materialized:t,failure:null}}async function Qi(e,t,n,r){if(r.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:r.failure};let i=null,a=null,o,s=e=>{o=e,a=$i(e.credential,r.materialized)};try{let t=await x({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(ea(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=ia(t.data),e===`read`)return{scope:e,selected:a,identity:null,authorization:i,error:null};if(o===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await Xi(e,o);return{scope:e,selected:a,identity:n,authorization:i,error:null}}catch(r){return{scope:e,selected:a,identity:null,authorization:i,error:D(r,ta(t,n,o))}}}function $i(e,t){if(e===null)return null;let n=t??Oe().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function ea(e){return[e.summary,...e.warnings].join(` — `)}function ta(e,t,n){return[s().userBearerToken,...h(n?.headers??{}),...e.state===`found`?je(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function na(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:m(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:sa(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ra(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:Te(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:Ee(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ia(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=ce.safeParse(e.response);if(!t.success)throw t.error;return t.data}function aa(e,t){let{expiresAt:n,expiresInDay:r}=na(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with aVenture sign-in)`:``}var oa=864e5;function sa(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/oa)}var ca=7;function la(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ca)}\u2026${e.slice(-4)}`}var ua=13,da=14;function fa(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...ma(e.oauth,e.cliName,e.refresh),...ga(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,ya(e.providers)),W(`Environment`,ba(e.resolved)),W(`Selected`,xa(e.resolved,e.refresh,e.cliName)),...pa(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
|
|
20
|
+
`)}function pa(e){if(e===null)return[];let t=G(`local credential provenance was captured before verification`);if(e.error!==null)return[``,W(`Live probe`,`${e.scope} permission probe failed`),t,G(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,W(`Live probe`,`${e.scope} permission probe succeeded`),t,G(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[G(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[W(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],G(`no API operation was executed or individually authorized`)]}function W(e,t){return` ${e.padEnd(ua)}${t}`}function G(e){return` ${``.padEnd(ua)}${e}`}function ma(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=Ee(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(ha(r,t,n))]}case`missing`:return[W(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[G(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[W(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[W(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function ha(e,t,n){return Te(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function ga(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[W(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[G(`stored credential invalid: ${e.error}`)]]:[W(`Signed in`,`credential storage unavailable`),G(r)]}return[W(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),G(`via ${e.provider??`unknown store`}`),W(`Key`,`${e.name??`unnamed`} ${la(e.apiKeyId)}`),..._a(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function _a(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by aVenture sign-in \u2014 ${n.summary}`),G(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[W(`Key state`,a?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(va(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${n.summary}`)]]}function va(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=da?`${n} ${r}, ${t}d away`:`${n} ${r}`}function ya(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${Ae(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function ba(e){return`${C.authToken}=${e.present?e.source??`resolved`:`unset`}`}function xa(e,t,n){return e.present||t.materialized===`env`?`${C.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${n} auth login\``}var Sa=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,Ca=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,wa=`.aventure-cli-completion.bak`;function Ta(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Ma([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Ma([`--uninstall`]))}function Ea(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=Aa(),n=await ka({rcFile:N(Vt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Ua});P.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Ma(e.uninstall?[`--uninstall`]:[])})}function Da(e,t=`fpath-only`){return[Sa,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],Ca].join(`
|
|
21
|
+
`)}function Oa(){let e=Ma([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!Na(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=Ma([],`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 ka({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Pa(e),o=a.length===0?[]:a.split(`
|
|
22
|
+
`),s=Fa(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ia(o,s,t,e):La(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: unchanged; pass --yes to apply without a prompt`,content:a}:(Ba(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Aa(e=P.argv[1]){let t=e===void 0?``:ja(e),n=N(M(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return Ct(n)?n:N(M(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function ja(e){try{return kt(e)}catch{return N(e)}}function Ma(e,t=`inherit`){let n=yt(P.execPath,[Aa(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(P.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function Na(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Pa(e){return Ct(e)?(Va(e),Dt(e,`utf8`)):``}function Fa(e,t){let n=Ra(e,Sa),r=Ra(e,Ca);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 Ia(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=za(i),o=Da(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
|
|
23
|
+
`),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 Ha([...i.slice(0,c),...o,...i.slice(c)])}function La(e,t){return Ha(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Ra(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function za(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ba(e,t){Tt(M(e),{recursive:!0}),Ct(e)&&(Va(e),Va(`${e}${wa}`),St(e,`${e}${wa}`));let n=N(M(e),`.${bt(e)}.${P.pid}.tmp`);Va(n),Nt(n,t,{mode:420}),At(n,e)}function Va(e){if(Ct(e)&&wt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Ha(e){let t=e.join(`
|
|
24
|
+
`);return t.length===0||t.endsWith(`
|
|
25
|
+
`)?t:`${t}\n`}async function Ua(e){if(!P.stdin.isTTY)return!1;let t=Wt({input:P.stdin,output:P.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Wa=new Intl.Collator(void 0,{numeric:!0}),Ga=2e4;function Ka(e,t=g()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from npm.`;k(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(rebuild that checkout instead). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
|
|
26
|
+
`)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>R({mode:O(e)},qa()))}function qa(e,t=`apply`){let n=e;try{n??=g(process.argv[1])}catch(e){return a(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,o=n.registry===``?``:ee,s=n.registry===``&&r===`@aventurevc/aventure-cli`,c=Ja([`view`,o,`version`,`--silent`,`--global`],n,{timeout:Ga});if(!c.ok)return{...c,data:null};let l=(c.data??``).trim();if(l===``)return a(`npm view ${o} returned empty version`,[`empty_stdout`]);let u=s||Wa.compare(i,l)<0,d={targetPackage:o,runningPackage:r,currentVersion:i,latestVersion:l,upgradeAvailable:u,upgradeInstalled:!1};if(t===`check`)return v(`${r}@${i} → ${o}@${l} (${u?`available`:`up to date`})`,d);if(!u)return v(`${r}@${i} already matches ${o}@${l}`,d);if(n.workingTreeRoot!==null)return a(`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 f=Za(n),p=f===null?[]:[`--prefix`,f.installPrefix],m=f===null?null:N(f.installPrefix,`lib`,`node_modules`,...o.split(`/`)),h=s?Ya(f,o,l):[];if(s){let e=Ja([`uninstall`,`-g`,...p,ee],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return a(`Cannot remove the retired ${ee}: ${e.summary}`,[...e.warnings,...h])}let _;try{_=Qa(n,f)}catch(e){return a(`Cannot prepare MCP-owned CLI bins: ${to(e)}`,[`npm install was not run`])}let y=Ja([`install`,`-g`,...p,`${o}@${l}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!y.ok){let e=$a(_,m);return e===null?{...y,warnings:[...y.warnings,...h],data:null}:a(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let b=f===null?void 0:Xa(f.installPrefix,o,l);if(b?.ok===!1){let e=$a(_,m);return e===null?{...b,warnings:[...b.warnings,...h],data:null}:a(`${b.summary}; MCP-owned CLI bin restoration failed`,[...b.warnings,e])}let te=eo(_);if(te!==null)return a(`${o} upgraded but MCP CLI bin backup cleanup failed`,[te]);let x=no();return v(`${o} upgraded to ${l}`,{...d,upgradeInstalled:!0,installPrefix:f?.installPrefix,verifiedVersion:b?.data??void 0,completionRefreshed:x.refreshed,completionRefreshMessage:x.message})}function Ja(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],o=yt(`npm`,i,{env:r,encoding:`utf8`,...n});if(o.error)return o.signal===`SIGTERM`&&n.timeout!==void 0?a(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):a(`npm ${e[0]??``} failed to start: ${o.error.message}`,[`spawn_error`]);if(o.status!==0){let t=(o.stderr??``).trim().split(`
|
|
27
|
+
`).slice(-3).join(` | `);return a(`npm ${e.join(` `)} exited ${o.status}`,[t||`no stderr`])}return v(`npm ok`,o.stdout??``)}function Ya(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${ee}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function Xa(e,t,n){let r;try{let n=g(N(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=N(e,`bin`,n.bin[0])}catch(e){return a(`updated ${t} verification failed: ${to(e)}`,[`invalid_package_metadata`])}let i=yt(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return a(`updated ${t} verification failed: ${i.error.message}`,[`spawn_error`]);let o=(i.stdout??``).trim();if(i.status!==0||o!==n){let e=(i.stderr??``).trim().split(`
|
|
28
|
+
`).slice(-3).join(` | `);return a(`updated ${t} verification expected ${n} but active bin reported ${o||`empty output`}`,[e||`active bin: ${r}`])}return v(`active CLI version verified`,o)}function Za(e){let t=`${xt}lib${xt}node_modules${xt}${e.name.replace(`/`,xt)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function Qa(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}${xt}`))throw Error(`the running CLI entry is outside the MCP package root`);let n=e.bin.filter(e=>e===`aventure`||e===`aventure-cli`).flatMap(n=>{let r=N(t.installPrefix,`bin`,n),i=wt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=kt(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:Ot(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=Et(N(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:N(r,bt(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(At(e.binPath,e.backupPath),a.push(e),Ot(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=$a({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 $a(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=wt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=N(M(r.binPath),Ot(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${xt}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);Mt(r.binPath)}At(r.backupPath,r.binPath)}catch(e){n.push(to(e))}if(e.backupDirectory!==null)try{jt(e.backupDirectory)}catch(e){n.push(to(e))}return n.length===0?null:n.join(`; `)}function eo(e){let t=[];for(let n of e.backup)try{Mt(n.backupPath)}catch(e){t.push(to(e))}if(e.backupDirectory!==null)try{jt(e.backupDirectory)}catch(e){t.push(to(e))}return t.length===0?null:t.join(`; `)}function to(e){return e instanceof Error?e.message:String(e)}function no(){try{return Oa()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var ro=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers its generated status operation`},{name:`auth`,purpose:`which credential scope materialized locally, never the secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],io=`operationFingerprint`;function ao(e,t=g().bin[0]){k(e.command(`doctor`).summary(`One-call selftest: CLI version, schemas, API host, auth scope, command catalog`).description(["Run every environment check in one call and report `{ ok, check: [...] }`:",...ro.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(`
|
|
29
|
+
`))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),R({mode:O(e)},await oo(t))})}async function oo(e){let t=co(),n=lo(e),[r,i]=await Promise.all([uo(e),fo(t,e)]),o=[n.check,r,i.check,await mo(e),bo(t,i.servedFingerprint,n.upgradeAvailable,e)],s={pass:so(o,`pass`),fail:so(o,`fail`),skip:so(o,`skip`)},c=o.filter(e=>e.status===`fail`).map(e=>e.message),l={ok:c.length===0,check:o},u=[`doctor: ${s.pass} pass, ${s.fail} fail, ${s.skip} skip`,...o.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
|
|
30
|
+
`);return l.ok?v(u,l,{counts:s}):{...a(u,c,{counts:s}),data:l}}function so(e,t){return e.filter(e=>e.status===t).length}function K(e,t,n){return{name:e,status:t,message:n}}function co(){return A.find(e=>e.intent===`status`&&e.resource===`status`)}function lo(e){let t=g(),n=qa(t,`check`);if(!n.ok||n.data===null)return{check:K(`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?K(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):K(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function uo(e){try{let{EntityDetailSchema:e}=await import(`./detail-CYpIsWgP.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return K(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return K(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${D(t)}.`)}}async function fo(e,t){if(e===void 0)return{check:K(`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:K(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${D(e)}.`),servedFingerprint:null}}let r=await x({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>a(D(e)));return r.ok?{check:K(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:po(r.data)}:{check:K(`api-host`,`fail`,r.httpStatus===401?`Replace or unset the credential ${n} rejected, or run \`${t} auth login\`, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} returned ${r.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function po(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[io];return typeof n==`string`&&n.length>0?n:null}async function mo(e){let t=Oe(),[n,r]=await Promise.all([ho(),go()]);if(r.state===`unavailable`&&r.cause===`environment`)return K(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present,a=r.state===`found`&&r.stored.activation===`active`;return!i&&n.state===`invalid`?K(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Te(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?K(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&!a&&n.state===`unavailable`?K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${C.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||a?K(`auth`,`pass`,`Credential source available: ${_o(t,n,r)}.`):r.state===`unavailable`?K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${C.authToken} through the environment — ${r.summary}.`):K(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${C.authToken} in the environment.`)}async function ho(){let e;try{e=Ne(s().host)}catch(e){return{state:`unavailable`,summary:D(e)}}return await Pe(e)}async function go(){let e;try{e=Be(s().host)}catch(e){return{state:`unavailable`,summary:D(e),cause:`environment`}}try{return await ze(e)}catch(e){return{state:`unavailable`,summary:D(e),cause:`storage`}}}function _o(e,t,n){return[ba(e),`oauth=${yo(t)}`,`api-key=${vo(n)}`].join(` `)}function vo(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Be(s().host);return`${e.stored.activation}${aa(t,e)}`}function yo(e){switch(e.state){case`found`:return Te(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function bo(e,t,n,r){let i=A.length;if(e===void 0)return K(`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 K(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${rt}.`);if(t===`155fa333c1d6919d`)return K(`catalog`,`pass`,`${i} generated operations match the set the API serves (${rt}).`);let a=`This catalog describes a different operation set than the API serves (${rt} vs ${t})`;return n===!0?K(`catalog`,`fail`,`${a}: run \`${r} update\`.`):K(`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 xo=j(B,`oauth`),So=[j(B,`start`),j(B,`poll`),j(B,`acknowledge`)],Co=j(B,`revoke`);function wo(e,t=g().bin[0]){let n=Oo(e);ao(n,t);let r=[`${xo.description} Default method: OAuth in your browser.`,`With --key: ${So.map(({description:e})=>e).join(` `)}`].join(`
|
|
31
|
+
`);k(Do(n,[xo,...So],r)).action(To),k(Do(n,[Co],Co.description)).action(Eo),k(n.command(`status`).summary(`Keep saved credentials current and report them with API build and uptime`).description([`Runs the same credential materialization every command runs, then reports:`,` - auth: whether AUTH_TOKEN was already set in this shell's environment`,` - oauth: the saved OAuth identity and access-token expiry for the selected API host;`,` an expired token is renewed with its refresh token and a token the sign-in service rejects is retired`,` - api-key: the saved aVenture API key, re-verified with aVenture sign-in and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (browser sign-in and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (uptime SLA)`,``,`Saved credentials are sent only to the selected API host and aVenture sign-in, never printed.`,`--verify read|write additionally runs a live permission probe for that scope; it does not`,`execute or authorize an arbitrary API operation.`].join(`
|
|
32
|
+
`)).addOption(new S(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){ko(this),R({mode:O(e)},await Ao(t,e.verify))}),n.command(`token`).summary(`Print the bearer token the next command sends`).description([`Runs the same credential materialization every command runs, then prints the selected`,`bearer token alone on stdout: ${C.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved aVenture API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
|
|
33
|
+
`)).action(async function(){ko(this);let e=await Zi(t),n=process.env[C.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}R({mode:`text`},e.failure===null?Ro(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):a(`auth token: ${e.failure}`))})}async function To(e){ko(this);let t=O(e);if(e.providers===!0){R({mode:t},await Mo());return}R({mode:t},e.key===!0?await Bi({noBrowser:!e.browser,clientLabel:e.clientLabel}):await _t({noBrowser:!e.browser}))}async function Eo(e){ko(this),R({mode:O(e)},await ki({forgetLocal:e.forgetLocal===!0}))}function Do(e,t,n){let[r]=t,i=e.command(r.command.slice(r.command.indexOf(` `)+1)).summary(r.summary).description(n),a=new Set;for(let e of t)for(let t of[...e.bodyOption,...e.localOption])a.has(t.flag)||(a.add(t.flag),`required`in t&&t.required?i.requiredOption(t.flag,t.description):i.option(t.flag,t.description));return i}function Oo(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${xo.command}\`: ${xo.summary}; \`--key\` ${So[0].summary.toLowerCase()}.`,`\`${Co.command}\`: ${Co.summary}.`,"`auth status` reports local credential provenance, sign-in providers, and CLI/API build and uptime.","`auth doctor` runs the one-call selftest and prints `{ ok, check: [...] }`.","`auth token` prints the bearer token the next command sends."].join(`
|
|
34
|
+
`))}function ko(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Ao(e,t){let n;try{n=Ne(s().host)}catch(e){return a(`auth status: invalid API host — ${D(e)}`)}let r=Oe(),i=Zi(e),[o,c,l]=await Promise.all([Lo(`/v1/status`,`GET /v1/status`),Lo(`/info`,`GET /info`),No()]),u=await i,[d,f]=await Promise.all([Pe(n),jo(n)]),p=t===void 0?null:await Qi(t,d,f.inspection,u),m=g().version,h=na(n,f.inspection,f.verification),_=fa({cliName:e,cliVersion:m,apiVersion:c.ok?Fo(c.data):null,oauth:d,apiKey:h,providers:l,resolved:r,refresh:u,systemOk:o.ok,live:p}),y={cli:{version:m},api:c.ok?c.data??null:null,auth:{[C.authToken]:r},selected:u.materialized,oauth:ra(n,d),apiKey:h,providers:l,live:p,system:o.ok?o.data??null:null,...c.ok?{}:{apiError:c.summary},...o.ok?{}:{systemError:o.summary}};return u.failure===null?!c.ok&&c.httpStatus===401?{...a(`auth status: the API rejected the selected credential (401) | ${_}`,[`Replace or unset ${C.authToken}, or run \`${e} auth login\`.`]),data:y}:p!==null&&p.error!==null?{...a(`auth status: ${p.scope} permission probe failed — ${p.error}`,[p.error]),data:y}:p!==null||r.present||d.state===`found`||f.inspection.state===`found`?v(_,y):Ro(`auth status: no credentials resolved | ${_}`,y,e,{oauth:d.state===`missing`,apiKey:f.inspection.state===`missing`}):{...a(`auth status: ${u.failure} | ${_}`,[u.failure]),data:y}}async function jo(e){let t=await Po(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Ei(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Mo(){let e=await No();return e.state===`found`?v(`Sign-in providers for the selected API host`,e.catalog):a(`auth login --providers: ${e.summary}`)}async function No(){try{return{state:`found`,catalog:await gt()}}catch(e){return{state:`unavailable`,summary:D(e)}}}async function Po(e){try{return await ze(e)}catch(e){return{state:`invalid`,summary:D(e)}}}function Fo(e){if(!Io(e))return null;let t=ti.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 Io(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Lo(e,t){return await x({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>a(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Ro(e,t,n,r){return{...a(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${C.authToken} to an aVenture API key (create one at ${ue}/settings/api-keys).`]),data:t}}function zo(e,t=A,n=g().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(()=>{P.stdout.write(Vo(e,i,t))});Ta(r,n),Ea(r,n)}function Bo(){return g().bin}function Vo(e,t,n=A,r=Bo()){let i=Xo(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Uo(e),...r.map(e=>`complete -c ${q(e)} -e`),`${ls(r)} -f`,...Wo(e,r),...Go(e,i,r),``].join(`
|
|
35
|
+
`):Ho(e,t,i,r)}function Ho(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=$o(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}`),`)`,``,...ns(t),...t===`bash`?[a,``]:[``]].join(`
|
|
36
|
+
`)}function Uo(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Ko(e).filter(e=>e.required||e.optional).flatMap(e=>as(e)??[]).map(q).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
|
|
37
|
+
set -l expected $argv
|
|
38
|
+
set -l actual (__aventure_cli_command_path)
|
|
39
|
+
if test (count $actual) -ne (count $expected)
|
|
40
|
+
return 1
|
|
41
|
+
end
|
|
42
|
+
if test (count $expected) -eq 0
|
|
43
|
+
return 0
|
|
44
|
+
end
|
|
45
|
+
for index in (seq (count $expected))
|
|
46
|
+
if test $actual[$index] != $expected[$index]
|
|
47
|
+
return 1
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
return 0
|
|
51
|
+
end
|
|
52
|
+
`].flatMap(e=>e.split(`
|
|
53
|
+
`))}function Wo(e,t){return Qo(e).map(e=>`${ls(t)} -f -n ${q(us(e.parentPath))} -a ${q(e.name)} -d ${q(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Go(e,t,n){return os(e).flatMap(e=>{let r=cs(e),i=r.length===0?void 0:us(r);return Ko(e).flatMap(e=>{let a=t.get(Zo(r,e));return ts(a)?qo(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Ko(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function qo(e,t,n,r){let i=as(e);if(i===void 0)return[];let a=e.argChoices??es(n),o=[`-l ${q(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${q(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${q(t)}`,c=e.required||e.optional?Jo(a,Yo(i,n)):`-f`,l=`${ls(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${q(ds(e.description))}`]:a.map(t=>`${l} -a ${q(t)} -d ${q(ds(e.description))}`)}function Jo(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function Yo(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 Xo(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...Sn(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].flatMap(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[[Zo(e.cliPath,n),t]]})))}function Zo(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):as(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 Qo(e){return os(e).flatMap(e=>e.commands.map(t=>({parentPath:cs(e),name:t.name(),description:ds(t.summary()||t.description()||t.name())})))}function $o(e,t){let n=[],r=[];for(let i of os(e)){let e=cs(i);for(let a of Ko(i)){let i=as(a);if(i===void 0)continue;let o=t.get(Zo(e,a));if(!ts(o))continue;let s=a.argChoices??es(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&Yo(i,o)&&(c=`file`)),n.push(rs([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(rs([e.join(` `),`--${i}`,t,a.description]))}}return[Qo(e).map(e=>rs([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 es(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 ts(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function ns(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 rs(e){return`$'${e.map(is).join(`|`)}'`}function is(e){return ds(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function as(e){return e.long?.replace(/^--/,``)}function os(e){return[e,...e.commands.filter(ss).flatMap(e=>os(e))]}var ss=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function cs(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function ls(e){return`complete ${e.map(e=>`-c ${q(e)}`).join(` `)}`}function us(e){return[`__aventure_cli_path_is`,...e.map(q)].join(` `)}function ds(e){return e.replace(/\s+/g,` `).trim()}function q(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function fs(e,t){if(e!==t)return;let n=ps(t);n!==void 0&&t.error(`error: ${hs(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function ps(e){if(!process.argv.includes(`--`)&&e.args.some(ms))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function ms(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function hs(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function gs(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function _s(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function vs(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function J(e){return e.flags.split(` `)[0]??e.flags}function ys(e,t){let n=gs(t);if(n===void 0)return;let r=e.options.findIndex(e=>J(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[J(t),e.getOptionValue(t.attributeName())]).find(([,e])=>typeof e==`string`&&e.length>0)?.[0];if(i!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${i} does not replace the parent selector.`}var bs=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`]];function xs(e){let t=new Set(e.options.map(J)),n=process.argv.slice(2).filter(e=>e.startsWith(`--`)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e)).flatMap(e=>{let n=bs.find(t=>t.includes(e))?.find(e=>t.has(e));return n===void 0?[]:[`use ${n}, not ${e}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function Y(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function Ss(e){return e.commands.length===0?[e]:e.commands.flatMap(Ss)}function Cs(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 ws(e,t){return t.toSorted((t,n)=>{let r=Cs(e,t),i=Cs(e,n),a=+![`get`,`list`].includes(r.at(-1)??``),o=+![`get`,`list`].includes(i.at(-1)??``);return r.length-i.length||a-o})[0]}function Z(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Ts(e,t){let n=Y(e),r=process.argv.slice(2+n.length);return[X(e).name(),...n,...Cs(e,t),...r].map(Z).join(` `)}function Es(e,t){let n=_s(t);if(n===void 0||e.commands.length===0)return;let r=ws(e,Ss(e).filter(e=>e.options.some(e=>J(e)===n)));if(r!==void 0)return`hint: run: ${Ts(e,r)}`}function Ds(e){return e!==void 0&&Object.hasOwn(ot,e)}function Os(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 ks(e,t){let n=Y(e),r=[...n.slice(1),t];if(!Ds(n.at(0))||!Ds(r.at(0)))return;let i=Os(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 As(e,t){let[n]=Y(e);if(!Ds(n))return;let r=[n,t];return Os(X(e),r)?.commands.length===0?r:void 0}function js(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Ss(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 Ms(e,t){let n=process.argv.slice(2+Y(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return Ns(e,t)}function Ns(e,t,n=[]){let r=Y(e),i=tt(A).map(e=>e.cliPath).filter(e=>e[0]!==r[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),a=i.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(i.length===1?i[0]:void 0);if(a!==void 0)return`hint: run: ${[X(e).name(),...a,...n].map(Z).join(` `)}`}function Ps(e,t,n){if(!Is(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(Z).join(` `)}`}function Fs(e){let t=Y(e);if(t.at(1)!==void 0&&Ds(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(Z).join(` `)}`}function Is(e,t){let n=e.join(` `);return A.some(e=>e.cliPath.join(` `)===n?t===void 0||o(e.intent)===t:!1)}function Ls(e){let t=Y(e).join(` `),n=tt(A),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:ut(r.operationId,n,X(e).name()).map(e=>`hint: ${e}`)}function Rs(e){let t=Y(e);if(Ds(t.at(0))&&Is(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(Z).join(` `)}`}function zs(e){let t=new Set,n=[];for(let r of A){let i=Os(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(J);if(o(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 Bs(e,t){let n=Y(e);if(Is(n,!1)&&zs(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Vs(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=>J(e)===`--root`),l=n&&c!==void 0&&Ds(s)?s:void 0;c!==void 0&&l!==void 0&&o.push(J(c),l);let u=tt(A),d=dr({q:t,root:l,limit:`3`},u,r.name()),f=d.ok&&d.data!==null?jr(d.data,`compact`):``;return[`hint: search generated commands: ${o.map(Z).join(` `)}`,...f===``?[]:[`hint: closest commands (command · summary · required flags):`],...f.split(`
|
|
54
|
+
`).filter(Boolean).map(e=>` ${e}`)].join(`
|
|
55
|
+
`)}function Hs(e){if(e.commands.length>0&&!Is(Y(e)))return;let t=e.options.flatMap(e=>e.hidden?[]:[J(e)]);return`hint: ${Y(e).join(` `)} accepts: ${t.join(` `)}`}function Us(e,t){let n=vs(t);if(n===void 0||t.message.includes(`
|
|
56
|
+
(Did you mean `))return;let r=js(e),i=Ms(e,r);if(i!==void 0)return i;let a=Y(e),o=[...a.slice(0,-1),`${a.at(-1)}-${n}`,...r.slice(1)],s=(Is(o)?o:void 0)??ks(e,n)??As(e,n);if(s!==void 0)return Ps(e,s,r)??Vs(e,s.join(` `),!1);let c=r.join(` `)||n,l=Fs(e)??Vs(e,c),u=[...Y(e),...r.slice(1)];return[l,r.length===Y(e).length+Y(e).length&&Y(e).at(-1)===Y(e).at(0)?Ps(e,u,r)?.replace(/^hint: Did you mean: /u,` `)+` · `:u.slice(1,-1).length>0?Ps(e,u,r):void 0].filter(e=>e!==void 0).join(`
|
|
57
|
+
`)||void 0}function Ws(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[xs(e),ps(e),ys(e,t),...Ls(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=ps(e)??Rs(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=_s(t),r=xs(e)??Es(e,t)??(n!==void 0&&!t.message.includes(`
|
|
58
|
+
(Did you mean `)?Bs(e,n)??Ns(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??Hs(e)??Vs(e,Y(e).slice(1).join(` `)||n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Us(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Gs=class extends S{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 Ks(e){e.showHelpAfterError(!1).exitOverride(Ws(e)),e.commands.length===0?e.hook(`preAction`,fs):e.registeredArguments.length===0&&e.addHelpOption(new Gs(e));for(let t of e.commands)Ks(t)}function qs(e,t=new Date){let n=Xs(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 Js(e){return`${JSON.stringify(e,null,2)}\n`}function Ys(e,t){let n=N(e),r=Js(t);return Tt(M(n),{recursive:!0}),Nt(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function Xs(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:t(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 Zs=`Match only the first canonical or CLI-alias command segment`,Qs=[`text`,`lines`,`compact`,`json`,`ndjson`];function $s(e,t,n=g().bin[0]){let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
|
|
59
|
+
`));r.addHelpText(`after`,()=>`\nShipped compact catalog of operations callable without an admin grant, greppable without\nrunning this CLI (dump --format compact lists every operation your credential reaches):\n ${wr(n)}\n`),ec(r,t,n),tc(r,t,n),nc(r,t,n),rc(r)}function ec(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>`,Zs).addOption(new S(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new S(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new S(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new S(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new S(`--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 S(`--format <format>`,`Text/file render format`).choices(Qs)).option(`--output <path>`,`Write rendered output to a file`);k(r),r.action(function(e){let r=this.optsWithGlobals(),i=O(r,`text`);Dr(Er(r,e),t,i,n)})}function tc(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 S(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);k(r),r.action(function(){let e=this.optsWithGlobals();Or(e,t,O(e,`text`),n)})}function nc(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>`,Zs).addOption(new S(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new S(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new S(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new S(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new S(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new S(`--format <format>`,`Text/file render format`).choices(Qs)).option(`--output <path>`,`Write rendered output to a file`);k(r),r.action(function(){let e=this.optsWithGlobals();Dr(e,t,O(e,`text`),n)})}function rc(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);k(t),t.action(function(){let e=this.optsWithGlobals(),t=O(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){R({mode:t},v(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:Ge.length}}));return}let n=qs(Ge);if(e.output!==void 0){let r=Ys(e.output,n);R({mode:t},v(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(Js(n));return}R({mode:t},v(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var ic=g(Lt(import.meta.url)),Q=ic.bin[0];function ac(e,t){re({component:Q,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof te?{httpStatus:e.problem.status,problem:e.problem}:{};tr({...a(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function oc(e){return qe[Je(e,ot)??`cli`]}function sc(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:oc(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>at(e.cliPath[0])).map(e=>e.cliPath[0]??``)),i=new Set,a=new Set;for(let{cliPath:e,deprecated:t}of n)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);i.add(r),t!==!0&&a.add(r)}for(let t of n)cc(e,t,r,a,i.has(t.cliPath.join(` `)))}function cc(e,t,n,r,i){let s=t.cliPath,c=e,u=``,d=!n.has(s[0]??``);for(let e of s.slice(0,-1)){u=u===``?e:`${u} ${e}`;let t=d&&u===e||!r.has(u);c=lc(c,e,u,t)}let f=s.at(-1)??t.operationId,p=c.commands.find(e=>e.name()===f)??c.command(f,t.deprecated===!0?{hidden:!0}:{}),m=t.requestBody?.flatMap(({parameter:e})=>e)??[];p.summary(t.summary||t.operationId).description([`${t.method} ${t.path}.`,t.summary||t.description,`Full documentation: ${Q} help ${t.cliPath.join(` `)}`,t.requestBody?.[0]?.kind===`json`||[...t.parameters,...m].some(e=>l(e.schemaType,e.itemSchemaType))?de:``].filter(Boolean).join(`
|
|
60
|
+
`));let h=et(t);for(let e of t.parameters)uc(p,e,i||e===h);if(Nn(p,t),o(t.intent)&&p.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),k(p),p.hook(`preAction`,e=>nt(e,t)),t.explain===!0&&p.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){p.argument(`[text...]`,h.description||`Same as ${Qe(h.flag)}.`),p.action(async function(e){let n=this.optsWithGlobals(),r=O(n),i=$e(h,e,n);if(!i.ok||i.data===null)return R({mode:r},i);let o=it(t,i.data);if(o.length>0)return R({mode:r},a(`missing required options: ${o.join(`, `)}`));let s=await dc(t,i.data,r),c=Zr(t,i.data,s);if(c!==null)return R({mode:r},c);n.explain===!0&&s.ok&&ar(r,s.data),s.ok&&s.data instanceof Uint8Array?process.stdout.write(s.data):R({mode:r},s)});return}p.action(async function(){let e=this.optsWithGlobals(),n=O(e),r=it(t,e);if(r.length>0)return R({mode:n},a(`missing required options: ${r.join(`, `)}`));let i=await dc(t,e,n),o=Zr(t,e,i);if(o!==null)return R({mode:n},o);e.explain===!0&&i.ok&&ar(n,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):R({mode:n},i)})}function lc(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=ot[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function uc(e,t,n=!1){let r=t.description||`${t.name} ${t.location} parameter`,i=t.defaultValue===void 0?void 0:typeof t.defaultValue==`string`||typeof t.defaultValue==`boolean`?t.defaultValue:[...t.defaultValue];if(t.legacyFlag!==void 0){let a=new S(t.flag,r);i!==void 0&&a.default(i);let o=new S(t.legacyFlag,r).conflicts(t.optionKey);e.addOption(a).addOption(o),e.hook(`preAction`,e=>{let r=e.opts(),i=r[t.optionKey],s=r[o.attributeName()];if(s!==void 0){(i===void 0||e.getOptionValueSource(t.optionKey)==="default")&&e.setOptionValueWithSource(t.optionKey,s,`cli`);return}!n&&t.required&&i===void 0&&e.error(`error: required option '${a.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(i!==void 0){e.option(t.flag,r,i);return}if(t.required&&!n){e.requiredOption(t.flag,r);return}e.option(t.flag,r)}async function dc(e,t,r){if(t.environment!==void 0){let e=le(t.environment);if(e===null)return a(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${n().join(`, `)}`]);process.env.API_ENV=e}let i=await Rn(e,t);if(!i.ok)return i;let o=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)]})),s=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]]})),c=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 $r(e,await x({method:e.method,path:ae(e.operationId,o),searchParams:s,headers:c,body:i.data,contentType:Ze(e,t),auth:e.auth,responseFormat:Ye(r)?`json`:`auto`,responseBytes:e.binaryResponse===!0}))}process.on(`uncaughtException`,e=>ac(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>ac(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var fc=Xe(process.argv.slice(2),A),pc=fc===`required`?A:tt(A),$=new ne;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Hr).version(ic.version).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description([`The aVenture research API from your terminal. Three records — companies,`,`people, and news — carry everything else: funding, publications, and tags.
|
|
61
|
+
`,`Mutations execute directly; --execute is a deprecated no-op.
|
|
62
|
+
The aVenture MCP server tools execute through this same CLI.`].join(`
|
|
63
|
+
`)).addOption(new S(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${u})`).choices([...n()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),sc($,pc),wo($,Q),Ka($,ic),zo($,pc,Q),$s($,pc,Q),Rr($,pc,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(oc(e.name()).heading);if(Ks($),fc===`required`){let e=[$];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&(await Fe(),await Le())}))}}var mc=new Set($.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));$.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find one news article; companies and people use the root lookup`],[`get`,` get Read one record`],[`list`,` list Read many records`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>mc.has(e)?[t]:[]),``,`Account (free or paid; every command that calls aVenture needs one):`,` Create one at ${ue}/sign-up, then run: ${Q} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Profile views, searches, and web searches count toward your monthly allowance.`,` Usage and upgrades: ${ue}/settings/subscription`,` Plans and prices: ${Q} billing plans list`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
|
|
64
|
+
`,`Exit codes:`,` 0 envelope.ok === true
|
|
65
|
+
1 envelope.ok === false
|
|
66
|
+
`,`Examples:`,` $ ${Q} auth login`,` $ ${Q} lookup --name Stripe --url https://stripe.com`,` $ ${Q} search "fintech companies in Austin"\n`,`Run \`${Q} <command> --help\` for its subcommands and options,`,`or \`${Q} help <command>\` for its full documentation.`].join(`
|
|
67
|
+
`));try{await $.parseAsync()}catch(e){ac(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};
|