@aventurevc/aventure-cli 0.7.301 → 0.7.328

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.
@@ -0,0 +1,74 @@
1
+ import{$ as e,A as t,B as n,E as r,Ft as i,G as a,It as o,J as s,M as c,O as l,Pt as u,Q as d,R as f,Rt as p,T as m,Y as h,Z as g,_,at as v,b as y,c as b,et as x,f as ee,it as S,j as C,l as te,nt as ne,o as re,p as ie,q as ae,rt as w,s as oe,u as T,v as se,y as ce}from"./auth-B_0cUOPk.js";import{C as E,D as le,R as ue,_ as de,a as fe,k as D,v as O,x as pe}from"./person-owner-BqBLyw4S.js";import{A as me,C as he,D as ge,M as k,N as _e,O as ve,S as ye,T as be,a as xe,b as Se,c as Ce,d as we,g as Te,j as Ee,k as De,l as Oe,m as ke,o as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as Re}from"./oauth-bearer-credential-C-EZmWvX.js";import{a as ze,c as Be,d as Ve,f as He,g as Ue,h as We,l as Ge,m as Ke,n as qe,o as A,p as Je,r as j,s as Ye,t as M,u as Xe}from"./openapi-commands-C70h-zCn.js";import{a as Ze}from"./text-field-_7ZvrzAF.js";import{a as Qe,n as $e,o as et,r as tt,t as nt}from"./text-response-DDwkjRpA.js";import{n as rt,r as it,t as at}from"./oauth-login-qlqzOJeW.js";import{spawnSync as ot}from"node:child_process";import{basename as st,dirname as N,join as ct,resolve as P,sep as lt}from"node:path";import{appendFileSync as ut,copyFileSync as dt,existsSync as F,lstatSync as ft,mkdirSync as pt,mkdtempSync as mt,readFileSync as ht,readlinkSync as gt,realpathSync as _t,renameSync as vt,rmSync as yt,rmdirSync as bt,statSync as xt,unlinkSync as St,writeFileSync as Ct}from"node:fs";import I,{stderr as L,stdin as wt}from"node:process";import{TextDecoder as Tt,inspect as Et}from"node:util";import{fileURLToPath as Dt}from"node:url";import{readFile as Ot}from"node:fs/promises";import{createHash as kt,webcrypto as At}from"node:crypto";import{homedir as jt,hostname as Mt,platform as Nt}from"node:os";import{setTimeout as Pt}from"node:timers/promises";import{createInterface as Ft}from"node:readline/promises";function It(e,t,n){let r={...n};for(let n of t.parameter){let t=n.envName;if(t===void 0)continue;let i=process.env[t]?.trim();if(i===void 0||i.length===0)continue;let a=r[n.optionKey];if(a!==void 0&&(typeof a!=`string`||a!==i))return{...w(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return S(`Environment-bound options applied`,r)}function Lt(e,t,n){if(!R(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!Zt(n,r.name))continue;let a=Xt(n,r.name);if(typeof a!=`string`||a!==i)return`${e} ${r.name} in --from-file conflicts with ${t}; omit the field or use ${i}.`}return null}function Rt(e){let t=new Set(e.parameter.map(({name:e})=>e));return e.kind===`multipart`?e.requiredPath:e.requiredPath.filter(e=>!t.has(e))}function zt(e,t,n,r=!1){if(r||!en(t)||!Array.isArray(n))return nn(e,t,n);for(let[r,i]of n.entries()){let n=nn(e,t,i,r);if(!n.ok)return n}return S(`Body value assigned`,null)}function Bt(e,t,n,r){return nn(e,t,r,n)}function Vt(e){let t=[];for(let n of e.split(`.`)){let e=an(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Ht(e,t){let n=Vt(t);if(n===null)return null;let r=Yt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Jt(r)}:null}function Ut(e,t){if(en(e.name)||e.schemaType===`array`)return S(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return S(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?S(`Scalar body option selected`,t[0]):w(`${n} was already given; pass it once.`)}var Wt=/^(?<row>\d+):(?<item>.*)$/su;function Gt(e,t){let n=Vt(e.name);if(e.schemaType!==`array`||n===null||t===void 0||typeof t==`boolean`)return null;let r=new Map,i=[];for(let e of typeof t==`string`?[t]:t){let t=Wt.exec(e)?.groups,n=t?.row,a=t?.item;if(n===void 0||a===void 0){i.push(e);continue}let o=r.get(Number(n));o===void 0?r.set(Number(n),[a]):o.push(a)}return r.size===0?null:{container:n,rows:r,plain:i}}function Kt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&Vt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function qt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Ht(r,i.name);if(a===null)continue;if(a.firstHole!==null)return w(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Gt(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return w(`${o} fills one ${a.path}[] row's list, so ${e} cannot also build ${a.rowCount} ${a.path}[] rows from direct options — prefix each value with its 0-based ${a.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function Jt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function Yt(e,t){let n=e;for(let e of t){if(!R(n))return;n=n[e]??null}return n}function Xt(e,t){if(!en(t))return Yt(e,t.split(`.`))}function Zt(e,t){return $t(e,t.split(`.`))}function Qt(e,t,n){if(!R(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&Zt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function $t(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=an(n);if(!R(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>$t(e,r)):$t(a,r)}function en(e){return e.split(`.`).some(e=>an(e).isArray)}function tn(e,t){return e.parameter.length===0||!R(t)?null:sn(t,[],on(e.parameter))}function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=an(o),c=e===i.length-1,l=rn(a,s,t,c,n,r);if(!l.ok||l.data===null)return w(l.summary,l.warnings);if(c)return S(`Body value assigned`,null);a=l.data}return w(`${t} is not a valid body option path.`)}function rn(e,t,n,r,i,a){let o=()=>w(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,S(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,S(`Body path created`,e)}return R(c)?S(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,S(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,S(`Body path created`,n)}return R(s)?S(`Body path stepped`,s):o()}function an(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function on(e){let t=new Set,n=new Set,r=new Map;for(let i of e){let e=`${i.name}${i.schemaType===`array`?`[]`:``}`;t.add(e),r.set(e,i.flag.split(` `)[0]??i.name);let a=e.split(`.`);for(let e=1;e<a.length;e+=1)n.add(a.slice(0,e).join(`.`))}return{leaf:t,prefix:n,flagByLeaf:r}}function sn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=sn(r,t,n);if(e!==null)return e}return null}if(!R(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!cn(a,n)){if(!ln(e))continue;return{path:a,suggestion:un(e,n)}}let o=sn(i,e,n);if(o!==null)return o}return null}function cn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function ln(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function un(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``,[i]=[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:dn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path));if(i!==void 0)return{path:i.path,flag:t.flagByLeaf.get(i.path)??i.path}}function dn(e,t){let n=t.replace(/\[\]$/u,``).toLowerCase();return n===e?0:n.endsWith(e)||e.endsWith(n)?1:n.includes(e)||e.includes(n)?2:1/0}function fn(e,t){let n=new Map;for(let e of t){let t=e.flag?.split(` `)[0];t!==void 0&&n.set(t,t===`--from-file`?{...e,inputType:`file`}:e)}for(let t of e){let e=t.long===void 0?void 0:n.get(t.long);e!==void 0&&t.helpGroup(Ke(e))}e.sort((e,t)=>{let r=e.long===void 0?void 0:n.get(e.long),i=t.long===void 0?void 0:n.get(t.long);return r!==void 0&&i!==void 0?bn(r,i):r===void 0?i===void 0?0:1:-1})}function pn(e){let t=new Map;for(let n of e)for(let e of n.parameter){let r=e.flag.split(` `)[0]??e.flag,i=t.get(r);i===void 0?t.set(r,{variant:[{descriptor:n,parameter:e}]}):t.set(r,{variant:[...i.variant,{descriptor:n,parameter:e}]})}return[...t.values()]}function mn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function hn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:vn(e,t)})),n=t[0];return n===void 0?``:t.every(({text:e})=>e===n.text)?`${n.text===``?``:`${n.text} `}Request content: ${t.map(({contentType:e})=>e).join(`, `)}.`:t.map(({contentType:e,text:t})=>`${e}: ${t}`).join(` `)}function gn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function _n(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?We(n):`${We(n)} Required JSON paths: ${r.join(`, `)}.`}function vn(e,t){return`${He(t.description,void 0)}${e.kind!==`multipart`&&en(t.name)?` Repeat to add another value.`:``}${yn(e,t)}`}function yn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=Vt(t.name);return n===null?``:` Prefix each value with its 0-based ${n}[] row index, as 0:value, to fill more than one ${n}[] row. A leading digits-and-colon is always read as that index, so name the row of a value that starts the same way, as 0:0:00 for the value 0:00.`}function bn(e,t){return Je(e)-Je(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function xn(e){let t;try{t=e===`-`?await Sn():await Ot(e,`utf8`)}catch(t){return w(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return S(`No input provided`,null);let e=JSON.parse(t);return S(`Input parsed`,e)}catch(e){return w(`Input is not valid JSON: ${e.message}`)}}async function Sn(){if(process.stdin.isTTY)throw Error(`--from-file - requires JSON on stdin, but stdin is a TTY`);process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}var Cn=`--content-type`;function wn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),a=t.requestBody??[];if(a.length>1&&r(Cn)){let t=a.map(({contentType:e})=>e);e.addOption(new i(`${Cn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(En(a)))}if(Kn(t)&&r(`--from-file`)){let n=a[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new i(`--from-file <path>`,_n(n,n.requiredPath)).argParser(On(`--from-file`)))}let o=pn(a).filter(e=>r(Rn(e.variant[0].parameter)));for(let t of o.toSorted((e,t)=>bn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],o=new i(mn(t),a.length>1?hn(t):vn(n,r));a.length===1&&r.envName!==void 0&&o.env(r.envName);let s=a.length===1?gn(n,r.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Tn):en(r.name)||r.schemaType===`array`?o.argParser(Dn):o.argParser(On(r.flag)),e.addOption(o),o.envVar!==void 0&&e.on(`optionEnv:${o.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}Gn(e,t,o)}function Tn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function En(e){return(t,n)=>{if(n!==void 0)throw new p(`${Cn} was already given; pass it once.`);let r=c(e,t);if(!r.ok)throw new p(r.summary);return t}}function Dn(e,t){return[...t??[],e]}function On(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new p(`${t} was already given; pass it once.`);return e}}async function kn(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,r=c(e.requestBody??[],n);if(!r.ok||r.data===null)return w(r.summary,r.warnings);let i=r.data;if(i===void 0)return S(`No body`,void 0);let a=An(e,i,t);if(a!==null)return w(a);let o=It(e.operationId,i,t);if(!o.ok)return w(o.summary,o.warnings);t=o.data;let s=jn(i,t);if(s!==null)return w(s);let l=await Fn(t);if(!l.ok)return w(l.summary,l.warnings);let u=Qt(e.requestBody??[],i,l.data);if(u!==null)return w(u);let d=Pn(e.operationId,i,l.data);if(!d.ok)return d;let f=Lt(e.operationId,i,l.data);if(f!==null)return w(f);let p=In(e.operationId,i,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return i.required?w(Wn(e.operationId,i)):S(`No body`,void 0);let m=zn(e.operationId,l.data,p.data);if(!m.ok||m.data===void 0)return m;if(i.schemaType===`array`&&!Array.isArray(m.data))return w(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!R(m.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return w(`${e.operationId} requires a JSON object${t}.`)}let h=Nn(i,m.data);if(h.length>0)return w(`${e.operationId} requires body option(s): ${h.join(`, `)}`);let g=m.data,_=R(g)?Rt(i).filter(e=>!Zt(g,e)):[];return _.length>0?w(Mn(e.operationId,i,_)):m}function An(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${Rn(t)} requires ${Cn} ${i.join(` or `)}.`}return null}function jn(e,t){for(let n of e.cliConflicts??[]){let e=n.filter(e=>t[e]!==void 0);if(e.length>1)return`Options ${e.join(`, `)} cannot be used together.`}return null}function Mn(e,t,n){let r=`${e} requires JSON body path(s): ${n.join(`, `)}`;return t.kind===`multipart`?`${r}. ${n.includes(`body`)?`For multipart --from-file, wrap the endpoint JSON under top-level "body".`:`For multipart --from-file, put the missing nested path(s) inside top-level "body".`}`:r}function Nn(e,t){return R(t)?e.parameter.filter(e=>e.required&&!Zt(t,e.name)).map(Rn):[]}function Pn(e,t,n){let r=tn(t,n);if(r===null)return S(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion.path} (${r.suggestion.flag}).`;return w(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Fn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return S(`No body file`,void 0);let n=await xn(t);if(!n.ok)return w(n.summary,n.warnings);let r=v.safeParse(n.data);return r.success?S(`Input parsed`,r.data):w(`Input is not valid JSON value: ${r.error.message}`)}function In(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Ut(e,n[e.optionKey]);if(!a.ok||a.data===null)return w(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Ln(t,n,r,e,o);if(!s.ok)return w(s.summary,s.warnings);i=!0}if(!i)return S(`No direct body options`,void 0);let a=qt(e,t,n,r);return a===null?S(`Direct body options parsed`,r):a}function Ln(e,t,n,r,i){let a=Gt(r,i);if(a===null){let e=Hn(r,i);return e.ok?zt(n,r.name,e.data,r.schemaType===`array`):w(e.summary,e.warnings)}if(a.plain.length>0)return w(`${Rn(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=Kt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return w(`${Rn(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=Un(r.name,r.itemSchemaType,e);if(!t.ok)return w(t.summary,t.warnings);i.push(t.data)}let a=Bt(n,r.name,e,i);if(!a.ok)return a}return S(`Body value assigned`,null)}var Rn=e=>e.flag.split(` `)[0]??e.name;function zn(e,t,n){if(t===void 0)return S(`Direct body parsed`,n);if(n===void 0)return S(`Input parsed`,t);if(R(t)&&R(n))try{return S(`Input parsed`,Bn(t,n))}catch(t){return w(`${e} ${t.message}`)}return w(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function Bn(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Array.isArray(t)&&Array.isArray(r))throw Error(`cannot combine --from-file array '${e}' with array body options at the same key — move the per-item fields inside the matching '${e}[]' object(s) in the file body.`);if(t!==void 0&&Vn(t)!==Vn(r))throw Error(`cannot combine --from-file ${Vn(t)} '${e}' with ${Vn(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=R(t)&&R(r)?Bn(t,r):r}return n}function Vn(e){return Array.isArray(e)?`array`:R(e)?`object`:`scalar`}function Hn(e,t){if(typeof t==`boolean`)return S(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return Un(e.name,e.schemaType,t??``);let n=[],r=en(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=Un(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return S(`Body value parsed`,n)}function Un(e,t,n){if(t===`boolean`)return n===`true`?S(`Body value parsed`,!0):n===`false`?S(`Body value parsed`,!1):w(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?w(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?w(`${e} must be an integer.`):S(`Body value parsed`,i)}return S(`Body value parsed`,n)}function Wn(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(Rn).join(`, `)}`;let r=Rt(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(Rn).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Gn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:Cn,location:`body`}),Kn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),fn(e.options,r)}function Kn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function qn(e){let t=ne(e);return nr(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Jn(e){nr(e);let t=nt(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
+ `)?t:`${t}\n`),Yn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&Qn(e.problem),Yn(e)}function Yn(e){e.ids.length>0&&process.stdout.write(` ids: ${e.ids.join(`, `)}\n`);for(let[t,n]of Object.entries(e.counts))process.stdout.write(` ${t}: ${n}\n`);for(let t of e.references)process.stdout.write(` ref: ${t}\n`);if(e.truncation!==void 0){let t=e.truncation.omitted.join(`, `);process.stdout.write(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${t}\n`),process.stdout.write(` recovery: ${e.truncation.recovery}\n`)}for(let t of e.warnings)process.stdout.write(` warn: ${t}\n`)}function z(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?ne(t):t;nr(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Xn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?qn(t):t;e.mode===`text`&&Jn(n),n.ok||(process.exitCode=1)}function Xn(e){return typeof e!=`object`||!e||Array.isArray(e)||!Reflect.has(e,`method`)||!Reflect.has(e,`endpoint`)||!(`response`in e)||e.response===void 0?e:e.response}function Zn(e,t){let n=$e(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
3
+ `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function Qn(e){typeof e.code==`string`&&process.stdout.write(` code: ${e.code}\n`),typeof e.detail==`string`&&process.stdout.write(` detail: ${e.detail}\n`),typeof e.hint==`string`&&process.stdout.write(` hint: ${e.hint}\n`),typeof e.suggestion==`string`&&process.stdout.write(` suggestion: ${e.suggestion}\n`);let t=Object.entries(e.suggestions??{});if(t.length>0){let e=t.map(([e,t])=>`${e}=${t}`).join(`; `);process.stdout.write(` suggestions: ${e}\n`)}typeof e.requiredRole==`string`&&process.stdout.write(` requiredRole: ${e.requiredRole}\n`),$n(e),er(`unknownParameters`,e.unknownParameters),er(`validParameters`,e.validParameters),tr(e.resolution)}function $n(e){let t=[];typeof e.limitType==`string`&&t.push(`limitType=${e.limitType}`),typeof e.used==`number`&&t.push(`used=${e.used}`),typeof e.limit==`number`&&t.push(`limit=${e.limit}`),typeof e.remaining==`number`&&t.push(`remaining=${e.remaining}`),typeof e.resetAt==`string`&&t.push(`resetAt=${e.resetAt}`),typeof e.windowSeconds==`number`&&t.push(`windowSeconds=${e.windowSeconds}`),typeof e.retryAfterSeconds==`number`&&t.push(`retryAfterSeconds=${e.retryAfterSeconds}`),t.length>0&&process.stdout.write(` meter: ${t.join(` `)}\n`)}function er(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function tr(e){if(e==null)return;let t=[`action=${e.action}`];typeof e.parameter==`string`&&t.push(`parameter=${e.parameter}`),typeof e.fieldPath==`string`&&t.push(`fieldPath=${e.fieldPath}`),typeof e.endpoint==`string`&&t.push(`endpoint=${e.endpoint}`),e.acceptedValue!==null&&e.acceptedValue!==void 0&&e.acceptedValue.length>0&&t.push(`acceptedValue=${e.acceptedValue.join(`, `)}`),typeof e.retryable==`boolean`&&t.push(`retryable=${e.retryable}`),process.stdout.write(` resolution: ${t.join(` `)}\n`)}function nr(e){e.ok&&e.warnings.length===0||n({component:`aventure-cli`,event:e.ok?`command_warning`:`command_failed`,message:e.warnings.length>0?e.warnings.join(` | `):e.summary,fields:{warningCount:e.warnings.length,summary:e.summary}})}function rr(e,t,n=s().bin[0]){let r=e.limit===void 0?void 0:Number(e.limit);if(r!==void 0&&(e.limit?.trim()===``||!Number.isInteger(r)||r<0))return w(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=tt(e.q??``,or(t,n).filter(t=>ur(t,e)),e=>({...e,cliPath:e.cli.path,enumParameter:e.flags.map(({choices:e,location:t})=>({values:e,direct:t!==`body`})),parameterName:e.flags.flatMap(({wireName:e,optionKey:t})=>[e,t]),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),a=i.slice(0,r);return S(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function ir(e,t,n=s().bin[0]){let r=or(t,n),i=e.operationId===void 0?ar(r,e.command):r.find(t=>t.operationId===e.operationId);return i===void 0?w(`Generated operation not found`,[`List candidates with \`${n} command-catalog search "<text>"\`.`]):S(`Generated operation detail`,{operation:i,usage:fr(i,r)})}function ar(e,t){if(t===void 0)return;let{bin:n}=s(),r=wr(t,n);return e.find(e=>wr(e.cli.command,n)===r)}function or(e,n){return e.map(e=>{let r=e.requestBody??[],i=[...e.parameters.map(e=>sr(e)),...r.flatMap(e=>e.parameter.map(t=>sr(t,r.length>1?e.contentType:void 0))),...cr(r)],a=[n,...e.cliPath].join(` `),o=t(e.intent),s=e.method===`DELETE`||e.intent===`delete`,c=r[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:s,auth:e.auth,cli:{command:a,path:e.cliPath},mcpTool:e.binaryResponse?null:C(e.intent),body:{hasBody:c!==void 0,kind:c?.kind??null,...c!==void 0&&r.length>1?{contentType:c.contentType}:{},required:c?.required??!1,description:c?.description??``,requiredPath:c?.requiredPath??[]},flags:i,errorResponse:e.errorResponse,summary:e.summary,description:e.description}})}function sr(e,t){let n=e.flag.split(/\s+/u);return{name:n[0]??e.flag,optionKey:e.optionKey,wireName:e.name,location:e.location,required:e.required,placeholder:n.length<=1?null:n.slice(1).join(` `),description:e.description,choices:e.choices??[],...t===void 0?{}:{contentType:t}}}function cr(e){if((e?.length??0)<=1)return[];let t=e?.map(({contentType:e})=>e)??[];return[{name:`--content-type`,optionKey:`contentType`,wireName:`Content-Type`,location:`body`,required:!1,placeholder:`<media-type>`,description:`Select the request content type; omit for ${t[0]}.`,choices:t}]}function lr(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function ur(e,t){return!(t.root!==void 0&&!dr(e,t.root)||t.scope!==void 0&&t.scope!==`all`&&t.scope!==e.scope||t.mutates!==void 0&&t.mutates!==`any`&&t.mutates===`true`!==e.mutates||t.destructive!==void 0&&t.destructive!==`any`&&t.destructive===`true`!==e.destructive||t.intent!==void 0&&t.intent!==`all`&&t.intent!==e.intent||t.method!==void 0&&t.method!==`all`&&t.method!==e.method)}function dr(e,t){let n=et(t);return n.length===0||et(e.cli.path.at(0)??``)===n}function fr(e,t){let n=lr(e),r=n.filter(e=>e.required),i=n.filter(e=>!e.required);return[`cli: ${e.cli.command}`,`${e.method} ${e.path}`,`operationId: ${e.operationId}`,`resource: ${e.resource}`,`intent: ${e.intent}`,`scope: ${e.scope}`,`mutates: ${e.mutates}`,`destructive: ${e.destructive}`,`mcpTool: ${e.mcpTool??`unavailable (binary CLI operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,Cr(`required path flags`,r,`path`),Cr(`required query flags`,r,`query`),Cr(`required header flags`,r,`header`),Cr(`required body flags`,r,`body`),Cr(`optional path flags`,i,`path`),Cr(`optional query flags`,i,`query`),Cr(`optional header flags`,i,`header`),Cr(`optional body flags`,i,`body`),...vr(e,t),...pr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
+ `)}function pr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var mr=[`-id`,`-slug`,`-url`],hr=[`--id`,`--slug`,`--url`],gr=`--from-file "<path>"`;function _r(e,t,n=s().bin[0]){let r=or(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:vr(i,r)}function vr(e,t){return[`example: ${[e.cli.command,...br(e),`--data`].join(` `)}`,...yr(e,t)]}function yr(e,t){return lr(e).flatMap(e=>{if(!e.required||!e.optionKey.endsWith(`Id`))return[];let n=`${e.optionKey.slice(0,-2)}Slug`,r=t.find(e=>e.method===`GET`&&e.path.endsWith(`/lookup`)&&e.flags.some(e=>e.optionKey===n)),i=r?.flags.find(e=>e.optionKey===n);if(r===void 0||i===void 0)return[];let a=`${r.cli.command} ${Sr(i)} --data`;return[`lookup: ${e.name} from a slug or name: ${a}`]})}function br(e){let t=lr(e).filter(e=>e.required),n=(t.length>0?t:xr(e)).map(Sr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,gr]:n}function xr(e){let t=new Set;Qe(t,e.resource);for(let n of mr)for(let r of t){let t=e.flags.find(e=>e.name===`--${r}${n}`);if(t!==void 0)return[t]}for(let t of hr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function Sr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function Cr(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function wr(e,t=s().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}function Tr(e,t,n=s().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show command help, or ask a grounded question`).description([`Show local --help output for a command path (deterministic, offline),`,`or answer a natural-language platform question with --ask via the grounded`,"help operation (the same generated operation as `help ask`)."].join(`
5
+ `)).argument(`[command...]`,"command path to show help for, e.g. `help search entities`"),r.addOption(new Er(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Mr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),j(r),r.action(async function(t){let r=this.optsWithGlobals();if(r.help&&t.length===0){this.outputHelp();return}if(!r.help&&i!==void 0&&r.ask!==void 0){let e=A(r);if(t.length>0){z({mode:e},w(`Use either a command path or --ask, not both.`));return}z({mode:e},await Pr(i,r.ask,r.environment,e));return}let a=Nr(e,t);a===void 0&&this.error(`unknown command '${t.join(` `)}' (run \`${n} --help\` for the command tree)`),a.outputHelp()}),jr(e,t,n)}var Er=class extends i{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},Dr=2,Or=6,kr={formatItem(e,t,n,r){let i=r.helpWidth??80,a=i-t-4;return n===``||a>=r.minWidthToWrap?o.prototype.formatItem.call(r,e,t,n,r):`${` `.repeat(Dr)}${e}\n${Ar(n,i,r)}`}};function Ar(e,t,n){return n.boxWrap(e,t-Or).replace(/^/gmu,` `.repeat(Or))}function jr(e,t,n){for(let r of t){let i=Nr(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=_r(r.operationId,t,n),[s,...c]=pr(r.errorResponse),l=c.map(t=>Ar(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Dr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
6
+ `)}\n`})}}function Mr(e){let[t,...n]=e.filter(e=>e.cliPath.at(-2)===`help`&&Fr(e)!==void 0);return n.length===0?t:void 0}function Nr(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 Pr(e,t,n,r){let i=Fr(e);if(i===void 0)return w(`The \`${e.cliPath.join(` `)}\` operation no longer takes a single required text body; run it directly instead of \`help --ask\`.`);n!==void 0&&(process.env.API_ENV=n);let a=await kn(e,{[i.optionKey]:t});return a.ok?await T({method:e.method,path:oe(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:ze(r)?`json`:`auto`}):a}function Fr(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 Ir(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}function Lr(e){return e.split(` `)[0]??e}function Rr(e){if(e.requestBody===void 0||e.requestBody.length===0){let[t,n]=e.parameters.filter(e=>e.required);return n===void 0&&t?.schemaType===`string`?t:void 0}if(e.requestBody.length!==1||e.parameters.some(e=>e.required))return;let t=e.requestBody[0]?.parameter??[],n=t.filter(e=>e.required);if(n.length===1&&n[0]?.schemaType===`string`)return n[0];if(n.length!==0||e.intent!==`search`)return;let r=t.filter(e=>{let t=e.name.split(`.`).at(-1);return e.schemaType===`string`&&(t===`query`||t===`search`)});return r.length===1?r[0]:void 0}function zr(e,t,n){let r=t.join(` `).trim();return r.length===0?S(`No positional text`,n):n[e.optionKey]===void 0?S(`Positional text parsed`,{...n,[e.optionKey]:r}):w(`Use either the positional argument or ${Lr(e.flag)}, not both.`)}function Br(e,t,n){if(e.cliPath[0]!==`lookup`||!Vr(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?w(i):w(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function Vr(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var Hr=O({artifact:E().nullish(),group:E().nullish(),name:E().nullish(),revision:E().nullish(),time:D({offset:!0}).nullish(),version:E().nullish()}),Ur=O({build:Hr});function B(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var Wr=fe([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),Gr=fe([`RSA_OAEP_256_A256_GCM_V1`]),Kr=O({clientLabel:E().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:Wr.nullish(),encryptionAlgorithm:Gr.nullish(),encryptionPublicKey:E().min(344).max(12e3).nullish()}),qr=32;async function Jr(){let e=await At.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await At.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function Yr(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=Xr(n,`wrapped key`,128,1024),s=Xr(r,`nonce`,12,12),c=Xr(i,`ciphertext`,1,65536),l=Xr(a,`authentication tag`,16,16),u;try{u=await At.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!==qr)throw Error(`broker credential used an invalid AES-256 key`);let e=await At.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 At.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Tt(`utf-8`,{fatal:!0}).decode(n);if(r.trim().length===0)throw Error(`broker returned a blank credential`);return r}finally{d.fill(0)}}function Xr(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 Zr=fe([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),Qr=fe([`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`]),$r=O({approvedAt:D({offset:!0}).nullish(),clientLabel:E(),clientPlatform:Wr,comparisonCode:E(),consumedAt:D({offset:!0}).nullish(),createdAt:D({offset:!0}),expiresAt:D({offset:!0}),id:le(),intervalSeconds:de().int().min(1),keyReadyAt:D({offset:!0}).nullish(),status:Zr,terminalAt:D({offset:!0}).nullish(),terminalReason:Qr.nullish(),updatedAt:D({offset:!0})}),ei=O({algorithm:Gr,authenticationTag:E(),ciphertext:E(),nonce:E(),wrappedKey:E()}),ti=O({delivery:ei.nullish(),expiresAt:D({offset:!0}),status:Zr,terminalReason:Qr.nullish()}),ni=O({comparisonCode:E(),expiresAt:D({offset:!0}),id:le(),intervalSeconds:de().int().min(1),pollSecret:E(),verificationUrl:E()}),V=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign in with a browser-approved Clerk API key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved Clerk API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI credential delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign out: revoke the API key and forget stored OAuth`,description:`Revokes the stored API key and returns provider metadata so the CLI can confirm remote revocation before removing local bytes.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Remove local bytes even when remote revocation cannot be confirmed.`}]}],ri=B(V,`start`),ii=B(V,`poll`),ai=B(V,`acknowledge`),oi=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${_e(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=fi(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},si=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${k(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function ci(e){let t=await ie(me(x()),{method:ri.method,path:y(ri.path,{},ri.operationId),headers:{},contentType:`application/json`,body:e},ni);if(!t.ok)throw new oi(`start`,t.problem);return pi(t.data)}async function li(e,t){let n=b(ii.operationId),r=await ie(me(x()),{method:ii.method,path:y(ii.path,{cliAuthorizationId:e},ii.operationId),headers:{[n]:t}},ti);if(!r.ok)throw new oi(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:di(r.headers[`retry-after`])}}async function ui(e,t){let n=b(ai.operationId),r;try{r=await ie(me(x()),{method:ai.method,path:y(ai.path,{cliAuthorizationId:e},ai.operationId),headers:{[n]:t}},$r)}catch(e){throw new si(`acknowledge`,e,[t])}if(!r.ok)throw new oi(`acknowledge`,r.problem,[t]);return r.data}function di(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function fi(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function pi(e){let{verificationUrl:t,pollSecret:n,...r}=e,i={...e},a=()=>({...r,verificationUrl:`<redacted>`,pollSecret:`<redacted>`});return Object.defineProperties(i,{verificationUrl:{enumerable:!1,get:()=>t},pollSecret:{enumerable:!1,get:()=>n},toJSON:{enumerable:!1,value:a},toString:{enumerable:!1,value:()=>`CliAuthorizationStart(${JSON.stringify(a())})`},[Et.custom]:{enumerable:!1,value:a}})}async function mi(e){let t=await hi(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await he(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 — ${k(n,[e.credential.secret])}`}}}}async function hi(e){let t=me(x()),n;try{n=await ie(t,{method:`GET`,path:oe(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Ie)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${k(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by Clerk`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${_e(n.problem,[e])}`}}var gi=B(V,`revoke`);async function _i(e){let t;try{t=Re(x().host)}catch(e){return w(`auth logout: invalid API host — ${k(e)}`)}let n=await vi(t),r=await xi(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],a={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?S(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...w(`auth logout: ${i[0]}`),data:a}:S(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function vi(e){let t=await Ae(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await bi(t.stored):{revoked:!1};try{await xe(e)}catch(e){return{state:`failed`,summary:k(e)}}return{state:`forgotten`,...n}}async function yi(e){let t=Reflect.get(await at(e),`revocation_endpoint`);return typeof t==`string`?Te(t,`revocation endpoint`,!0):void 0}async function bi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await yi(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:Pe(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:k(e,ke(n))}}}async function xi(e,t){let n;try{n=await ye(e)}catch(e){return w(`auth logout: stored credential could not be read — ${k(e)}`)}if(n.state===`unavailable`)return{...w(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Si(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...w(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.summary}`,[`Retry when the API is available. If an earlier response was lost after revocation, the retry can be unauthorized because revoked keys cannot authenticate.`,"Use `--forget-local` only to remove local bytes while accepting that the remote key may remain active."]),data:Ci(r,!1,!1)};try{await Se(r.host)}catch(e){return{...w(`auth logout: local credential removal failed — ${k(e,[r.credential.secret])}`,[a?"The remote key is revoked. Re-run with `--forget-local` to retry local cleanup.":`Remote revocation was not confirmed; inspect auth status before retrying.`]),data:Ci(r,a,!1)}}return S(a?`API key revoked remotely and removed locally.`:o?`Stale pending CLI credential removed; its remote key can no longer authenticate and unacknowledged keys expire at the authorization deadline.`:`API key removed locally without confirmed remote revocation.`,Ci(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Si(e){let t=me(x());try{let n=await ie(t,{method:gi.method,path:y(gi.path,{},gi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Ie);return n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored 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:_e(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:k(t,[e.credential.secret])}}}function Ci(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var wi=`RSA_OAEP_256_A256_GCM_V1`,Ti=1,Ei=30,Di=s().bin[0],Oi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${Di} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function ki(e){if(!wt.isTTY)return w(`${Di} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=x().host;t=Re(e),n=De(e)}catch(e){return w(`auth login --key: invalid environment configuration — ${k(e)}`)}for(;;){let e;try{e=await Le(t)}catch(e){return w(`auth login --key: credential storage could not be inspected — ${k(e)}`)}if(e.state===`unavailable`)return w(`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&&L.write(be(e.keyringFailure));break}let n=await Ai(e.stored);if(n!==null)return n}let r;try{r=await Jr()}catch(e){return w(`auth login --key: ephemeral encryption key could not be created — ${k(e)}`)}let i=Kr.safeParse({clientLabel:e.clientLabel?.trim()||(Mt().trim()||Di).slice(0,120),clientPlatform:Pi(),encryptionAlgorithm:wi,encryptionPublicKey:r.publicKey});if(!i.success)return w(`auth login --key: ${ue(i.error)}`);let a;try{a=await ci(i.data)}catch(e){return w(`auth login --key: could not start browser authorization — ${k(e)}`)}let o;try{o=ve(a,n)}catch(e){return w(`auth login --key: unsafe browser authorization URL rejected — ${k(e)}`)}if(!Ni(await ge(a,n,{noBrowser:e.noBrowser}),a,o))return w(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[o]});let s;try{s=await Mi(a)}catch(e){return w(`auth login --key: authorization did not complete — ${k(e)}`,[],{references:[o]})}if(s.algorithm!==wi)return w(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await Yr(r.privateKey,s)}catch(e){return w(`auth login --key: encrypted credential could not be opened — ${k(e)}`)}let l=await hi(c);if(l.state!==`verified`)return w(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await he(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return w(`auth login --key: credential could not be durably stored — ${k(e)}`)}let d;try{d=await ji(a)}catch(e){return H(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${k(e,[a.pollSecret])}`,Oi)}if(d.status!==`CONSUMED`)return H(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Oi);let f=await hi(c);if(f.state!==`verified`||!Ri(f.apiKey,u.credential.apiKey))return H(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Oi);try{let e=await he(t,{apiKey:f.apiKey,secret:c},`active`);return S(`API key stored; authenticated identity and broker acknowledgment verified.`,Li(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return H(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${k(e)}`,Oi)}}async function Ai(e){let t=await hi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?S(`API key is already stored and its authenticated identity was verified.`,Li(e,!0),{ids:[e.credential.apiKey.id]}):H(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${Di} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&Ri(t.apiKey,e.credential.apiKey))try{let n=await he(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return S(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,Li(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return H(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${k(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${Di} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return H(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${Di} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Si(e);if(n.outcome===`unconfirmed`)return H(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await Se(e.host)}catch(t){return H(e,!1,`auth login --key: stale pending credential could not be removed — ${k(t,[e.credential.secret])}`)}return L.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
7
+ `:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
8
+ `),null}async function ji(e){let t=new Date(e.expiresAt).getTime(),n=Fi(e.intervalSeconds);for(;;)try{return await ui(e.id,e.pollSecret)}catch(e){if(e instanceof oi){if(!e.retryable)throw e;n=Fi(e.retryAfterSeconds??n)}else if(!(e instanceof si))throw e;if(Date.now()>=t)throw e;L.write(`Broker acknowledgment was interrupted; retrying.
9
+ `),await Ii(n,t)}}async function Mi(e){let t=new Date(e.expiresAt).getTime(),n=Fi(e.intervalSeconds),r;for(L.write(`Waiting for browser approval...
10
+ `);Date.now()<t;){let i;try{i=await li(e.id,e.pollSecret)}catch(e){if(e instanceof oi){if(!e.retryable)throw e;n=Fi(e.retryAfterSeconds??n)}r=e,L.write(`Authorization poll was interrupted; retrying.
11
+ `),await Ii(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Fi(i.retryAfterSeconds??n),await Ii(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:throw Error(_(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${k(r,[e.pollSecret])}`)}function Ni(e,t,n){let r=e.state===`opened`;return!r&&!L.isTTY?!1:(L.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...L.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(`
12
+ `)),!0)}function Pi(){switch(Nt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Fi(e){return Math.min(Ei,Math.max(Ti,e))}async function Ii(e,t){let n=t-Date.now();n>0&&await Pt(Math.min(e*1e3,n))}function Li(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:_(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function H(e,t,n,r){return{...w(n,r===void 0?[]:[r]),data:Li(e,t)}}function Ri(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 zi(){return null}async function Bi(e){let t=null,n=e=>{t=e};try{await Ne(e,n),await Fe(n)}catch(e){return{materialized:t,failure:k(e)}}return{materialized:t,failure:null}}async function Vi(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=Hi(e.credential,r.materialized)};try{let t=await T({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(Ui(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=qi(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 zi(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:k(r,Wi(t,n,o))}}}function Hi(e,t){if(e===null)return null;let n=t??Ee().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function Ui(e){return[e.summary,...e.warnings].join(` — `)}function Wi(e,t,n){return[x().userBearerToken,...se(n?.headers??{}),...e.state===`found`?ke(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function Gi(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:_(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:Xi(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function Ki(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:Ce(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:we(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 qi(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=m.safeParse(e.response);if(!t.success)throw t.error;return t.data}function Ji(e,t){let{expiresAt:n,expiresInDay:r}=Gi(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with Clerk)`:``}var Yi=864e5;function Xi(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/Yi)}var Zi=7;function Qi(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,Zi)}\u2026${e.slice(-4)}`}var $i=13,ea=14;function ta(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api unreachable)`:` (api ${e.apiVersion})`),``,...ra(e.oauth,e.cliName,e.refresh),...aa(e.apiKey,e.oauth,e.cliName),``,U(`Providers`,ca(e.providers)),U(`Environment`,la(e.resolved)),U(`Selected`,ua(e.resolved,e.refresh,e.cliName)),...na(e.live),...e.systemOk?[]:[U(`System`,`uptime read failed`)]].join(`
13
+ `)}function na(e){if(e===null)return[];let t=W(`local credential provenance was captured before verification`);if(e.error!==null)return[``,U(`Live probe`,`${e.scope} permission probe failed`),t,W(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,U(`Live probe`,`${e.scope} permission probe succeeded`),t,W(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[W(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[U(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],W(`no API operation was executed or individually authorized`)]}function U(e,t){return` ${e.padEnd($i)}${t}`}function W(e){return` ${``.padEnd($i)}${e}`}function ra(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=we(r);return[U(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),W(ia(r,t,n))]}case`missing`:return[U(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[W(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[U(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[U(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function ia(e,t,n){return Ce(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 aa(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[U(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[W(`stored credential invalid: ${e.error}`)]]:[U(`Signed in`,`credential storage unavailable`),W(r)]}return[U(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),W(`via ${e.provider??`unknown store`}`),U(`Key`,`${e.name??`unnamed`} ${Qi(e.apiKeyId)}`),...oa(e,n),U(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function oa(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[U(`Key state`,`rejected by Clerk \u2014 ${n.summary}`),W(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[U(`Key state`,a?`${e.status??`unknown`}, verified by Clerk now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[W(`no expiry recorded`)]:[W(sa(i,r,a?`expires`:`cached expiry`))],...a?[]:[W(n===null?"Clerk owns the live verdict — `auth status` re-checks it":`Clerk could not be asked \u2014 ${n.summary}`)]]}function sa(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<=ea?`${n} ${r}, ${t}d away`:`${n} ${r}`}function ca(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`clerk browser sign-in`:`no browser sign-in`,t?`oauth ${Oe(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function la(e){return`${h.authToken}=${e.present?e.source??`resolved`:`unset`}`}function ua(e,t,n){return e.present||t.materialized===`env`?`${h.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:t.failure===null?`none — public reads only`:`none \u2014 sign in with \`${n} auth login\``}var da=fe([`PROMPT`,`SKILL`,`AGENT`]),fa=O({kind:da,name:E(),version:E()}),pa=O({content:E(),core:fa}),ma=O({key:E(),version:E()}),ha=O({agent:pe(E(),ma),prompt:pe(E(),ma),skill:pe(E(),ma)}),G=`aventure`,ga=`SKILL.md`,_a=`.aventure-skills.json`,va=`claude`,ya=2e4,ba=2,xa=[{name:`claude-code`,base:`home`,detect:[`.claude`],skill:[`.claude`,`skills`],mcp:{shape:`claude-cli`,file:[`.claude.json`],key:`mcpServers`}},{name:`codex`,base:`home`,detect:[`.codex`],skill:[`.agents`,`skills`],mcp:{shape:`toml`,file:[`.codex`,`config.toml`]}},{name:`cursor`,base:`home`,detect:[`.cursor`],skill:null,mcp:{shape:`json`,file:[`.cursor`,`mcp.json`],key:`mcpServers`,entry:e=>({type:`http`,url:e})}},{name:`opencode`,base:`config`,detect:[`opencode`],skill:[`opencode`,`skills`],mcp:{shape:`json`,file:[`opencode`,`opencode.json`],key:`mcp`,entry:e=>({type:`remote`,url:e,enabled:!0})}}];function Sa(e){return F(Ca(e))}function Ca(e){return ct(Ea(e),...e.detect)}function wa(e){return e.skill===null?null:ct(Ea(e),...e.skill)}function Ta(e){return ct(Ea(e),...e.mcp.file)}function Ea(e){return e.base===`home`?Oa(`HOME`)??jt():Da()}function Da(){return Oa(`XDG_CONFIG_HOME`)??ct(Oa(`HOME`)??jt(),`.config`)}function Oa(e){let t=process.env[e]?.trim();return t===void 0||t.length===0?void 0:t}function ka(e){return ct(N(e),_a)}function Aa(e){if(!F(e))return{};try{let t=ha.safeParse(JSON.parse(ht(e,`utf8`)));return t.success?t.data.skill:{}}catch{return{}}}function ja(e,t,n){let r=ka(e),i={...Aa(r)};for(let e of n){let n=t.skill[e];n!==void 0&&(i[e]=n)}return Na(r,`${JSON.stringify({prompt:{},skill:i,agent:{}},null,ba)}\n`)}function Ma(e,t,n){let r=ct(e,t,ga);return N(N(r))===e?Na(r,n):`refusing to install ${t}: it does not name one directory inside ${e}`}function Na(e,t){try{Pa(e,t)}catch(t){return`cannot write ${e}: ${k(t)}`}return null}function Pa(e,t){pt(N(e),{recursive:!0});let n=`${e}.aventure-tmp`;try{Ct(n,t,`utf8`),vt(n,e)}finally{yt(n,{force:!0})}}var Fa=RegExp(`^[ \\t]*\\[[ \\t]*mcp_servers[ \\t]*\\.[ \\t]*"?${G}"?[ \\t]*\\]`),Ia=/^[ \t]*mcp_servers[ \t]*=/m;function La(e){let t=Ta(e);if(!F(t))return null;try{let n=ht(t,`utf8`);if(e.mcp.shape===`toml`)return za(n);let r=Wa(n)?.[e.mcp.key],i=(r!==void 0&&Ga(r)?r:void 0)?.[G];return i===void 0||!Ga(i)?null:typeof i.url==`string`?i.url:Ra}catch{return null}}var Ra=`unknown`;function za(e){let t=e.split(`
14
+ `),n=t.findIndex(e=>Fa.test(e));if(n<0)return null;for(let e of t.slice(n+1)){if(e.trimStart().startsWith(`[`))break;let t=/^[ \t]*url[ \t]*=[ \t]*"([^"]*)"/.exec(e);if(t?.[1]!==void 0)return t[1]}return Ra}function Ba(e,t){let n=e.mcp,r=Ta(e);if(n.shape===`claude-cli`)return Ua(t);try{if(n.shape===`toml`)return Va(r,t);Ha(r,n.key,n.entry(t))}catch(e){return`cannot write ${r}: ${k(e)}`}return null}function Va(e,t){let n=F(e)?ht(e,`utf8`):``,r=`[mcp_servers.${G}]\nurl = "${t}"\n`;return Ia.test(n)?`${e} declares mcp_servers as an inline table, which this command cannot extend; add by hand:\n${r}`:Na(e,`${n}${n.length===0||n.endsWith(`
15
+ `)?``:`
16
+ `}\n${r}`)}function Ha(e,t,n){let r=Wa(F(e)?ht(e,`utf8`):`{}`);if(r===null)throw Error(`${e} is not a JSON object`);let i={...r},a=i[t];i[t]={...a!==void 0&&Ga(a)?a:{},[G]:n},Pa(e,`${JSON.stringify(i,null,ba)}\n`)}function Ua(e){let t=[`mcp`,`add`,`--transport`,`http`,`-s`,`user`,G,e],n=ot(va,t,{encoding:`utf8`,timeout:ya}),r=`${va} ${t.join(` `)}`;if(n.error!==void 0)return`run \`${r}\`: ${n.error.message}`;if(n.status!==0){let e=(n.stderr??``).trim().split(`
17
+ `).slice(-2).join(` | `);return`\`${r}\` exited ${n.status}: ${e||`no stderr`}`}return null}function Wa(e){let t=v.safeParse(JSON.parse(e));return t.success&&Ga(t.data)?t.data:null}function Ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ka=`aventure`;function qa(e,t=s().bin[0]){j(Ja(e).command(`setup`).summary(`Install the aventure skill bundle and MCP server into your agent runtimes`).description([`Detect the agent runtimes installed for this user (${xa.map(e=>e.name).join(`, `)}),`,`install or refresh the published ${Ka}* skill bundle into each runtime's own`,`skill directory, and register the ${G} MCP server in each runtime's own config.`,``,` ${t} agents setup # write the skills and the MCP registration`,` ${t} agents setup --status # compare what is installed; exit 1 on drift`,`--execute is deprecated, accepted, and ignored; setup executes by its verb.`].join(`
18
+ `)).addOption(new i(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`).default(!1)).addOption(new i(`--status`,`report installed skill versions against the manifest and exit 1 on drift; compares recorded versions, not file content, and writes nothing`).default(!1))).action(async function(e){let t=this.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment),z({mode:A(e)},await Ya(e))})}function Ja(e){let t=`agents`,n=e.commands.find(e=>e.name()===t);if(n!==void 0)return n;let r=Ue[t]?.summary??t;return e.command(t).summary(r).description(r)}async function Ya(e){let t=await so();if(!t.ok||t.data===null)return{...t,data:null};let n=await ao(`getAgentInstructionManifest`,ha);if(!n.ok||n.data===null)return{...n,data:null};let r=n.data,i=t.data,a=Object.keys(r.skill).filter(e=>e.startsWith(Ka)).toSorted();if(a.length===0)return w(`The agent instruction manifest carries no ${Ka}* skill; nothing to install.`);let o=xa.map(e=>$a(e,r,a,i));return Xa({runtime:e.status===!0?o:await to(o,r,i)},e,i)}function Xa(e,t,n){let r=e.runtime.filter(e=>e.detected),i=r.flatMap(e=>e.action.filter(e=>e.state!==`current`)),a=i.filter(e=>e.state===`failed`),o={runtimeDetected:r.length,actionPending:i.length,actionFailed:a.length},s=[`agents setup: ${r.length} runtime detected, ${i.length} action pending, mcp ${n}`,...e.runtime.map(Za)].join(`
19
+ `);if(r.length===0){let t=xa.map(e=>`${e.name}: no ${Ca(e)}`);return{...w(s,t,{counts:o}),data:e}}let c=a.length>0?a:t.status===!0?i:[];return c.length===0?S(s,e,{counts:o}):{...w(s,c.map(Qa),{counts:o}),data:e}}function Za(e){if(!e.detected)return` ${e.name} not installed`;let t=e.action.filter(e=>e.state!==`current`);return t.length===0?` ${e.name} current (${e.action.length} item)`:` ${e.name} ${t.length} pending — ${t.map(Qa).join(`; `)}`}function Qa(e){return`${e.kind} ${e.name} ${e.state}: ${e.detail}`}function K(e,t,n,r){return{kind:e,name:t,state:n,detail:r}}function $a(e,t,n,r){let i=wa(e),a=Ta(e),o={name:e.name,skillDir:i,mcpConfig:a};if(!Sa(e))return{...o,detected:!1,action:[]};let s=La(e),c=s===null?K(`mcp`,G,`install`,`register ${r} in ${a}`):K(`mcp`,G,`current`,`${s} in ${a}`);return{...o,detected:!0,action:[...i===null?[]:eo(i,t,n),c]}}function eo(e,t,n){let r=Aa(ka(e));return n.map(n=>{let i=t.skill[n]?.version??``,a=r[n]?.version,o=ct(e,n,ga);return a===void 0||!F(o)?K(`skill`,n,`install`,`write ${o} at version ${i}`):a===i?K(`skill`,n,`current`,`${o} at version ${i}`):K(`skill`,n,`update`,`${o} ${a} -> ${i}`)})}async function to(e,t,n){let r=e.flatMap(e=>e.action.filter(e=>e.kind===`skill`&&e.state!==`current`).map(e=>e.name)),i=new Map;for(let e of[...new Set(r)].toSorted())i.set(e,await io(e));return e.map(e=>{let r=xa.find(t=>t.name===e.name);if(!e.detected||r===void 0)return e;let a=[],o=e.action.map(t=>{if(t.state===`current`)return t;if(t.kind===`mcp`)return no(r,e.mcpConfig,n);let o=ro(e.skillDir,t.name,i.get(t.name));return o.state===`current`&&a.push(t.name),o}),s=e.skillDir===null||a.length===0?null:ja(e.skillDir,t,a),c=s===null?[]:[K(`skill`,_a,`failed`,s)];return{...e,action:[...o,...c]}})}function no(e,t,n){let r=Ba(e,n);return r===null?K(`mcp`,G,`current`,`registered ${n} in ${t}`):K(`mcp`,G,`failed`,r)}function ro(e,t,n){if(e===null||n===void 0||!n.ok||n.data===null)return K(`skill`,t,`failed`,n?.summary??`no document fetched for ${t}`);let r=Ma(e,t,n.data.content);return r===null?K(`skill`,t,`current`,`${ct(e,t,ga)} at version ${n.data.core.version}`):K(`skill`,t,`failed`,r)}async function io(e){return await ao(`getAgentInstruction`,pa,{kind:da.enum.SKILL,name:e})}async function ao(e,t,n={}){let r=oo(e);if(r===void 0)return w(`The generated command catalog carries no ${e} operation; regenerate it with \`make mcp-generate-contracts\` and reinstall.`);let i;try{i=oe(r.operationId,n)}catch(t){return w(`Cannot address ${e}: ${k(t)}`)}let a=await T({method:r.method,path:i,auth:r.auth,responseFormat:`json`}).catch(e=>w(k(e)));if(!a.ok)return{...a,summary:`${r.method} ${i} failed: ${a.summary}`,data:null};let o=a.data,s=t.safeParse(typeof o==`object`&&o&&`response`in o?o.response:void 0);return s.success?S(`${r.method} ${i} answered`,s.data):w(`${i} returned an unexpected body: ${s.error.message}`)}function oo(e){return M.find(t=>t.operationId===e)}async function so(){try{let e=(await rt()).oauthClient;if(e==null)return w(`The API published no OAuth client, so its MCP server URL is unknown.`);let t=e.mcpResource;return t==null?w(`The API published no MCP resource indicator, so its MCP server URL is unknown.`):S(`MCP host read from the API`,new URL(t).href)}catch(e){return w(`Correct API_ENV or pass \`--environment <name>\` — ${k(e)}.`)}}var co=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,lo=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,uo=`.aventure-cli-completion.bak`;function fo(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>yo([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>yo([`--uninstall`]))}function po(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=_o(),n=await go({rcFile:P(jt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Ao});I.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&yo(e.uninstall?[`--uninstall`]:[])})}function mo(e,t=`fpath-only`){return[co,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],lo].join(`
20
+ `)}function ho(){let e=yo([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!bo(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=yo([],`pipe`);return t.status===0?{refreshed:!0,message:(t.stdout??``).trim()||`shell completions refreshed`}:{refreshed:!1,message:`completion refresh exited ${t.status??1}`}}async function go({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=xo(e),o=a.length===0?[]:a.split(`
21
+ `),s=So(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Co(o,s,t,e):wo(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: cancelled`,content:a}:(Do(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function _o(e=I.argv[1]){let t=e===void 0?``:vo(e),n=P(N(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return F(n)?n:P(N(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function vo(e){try{return _t(e)}catch{return P(e)}}function yo(e,t=`inherit`){let n=ot(I.execPath,[_o(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(I.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function bo(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function xo(e){return F(e)?(Oo(e),ht(e,`utf8`)):``}function So(e,t){let n=To(e,co),r=To(e,lo);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 Co(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Eo(i),o=mo(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
22
+ `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return ko([...i.slice(0,c),...o,...i.slice(c)])}function wo(e,t){return ko(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function To(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Eo(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Do(e,t){pt(N(e),{recursive:!0}),F(e)&&(Oo(e),Oo(`${e}${uo}`),dt(e,`${e}${uo}`));let n=P(N(e),`.${st(e)}.${I.pid}.tmp`);Oo(n),Ct(n,t,{mode:420}),vt(n,e)}function Oo(e){if(F(e)&&ft(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function ko(e){let t=e.join(`
23
+ `);return t.length===0||t.endsWith(`
24
+ `)?t:`${t}\n`}async function Ao(e){let t=Ft({input:I.stdin,output:I.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var jo=new Intl.Collator(void 0,{numeric:!0}),Mo=2e4;function No(e,t=s()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from the public npm registry; no credential required.`;j(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(use \`make\` to rebuild that). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
25
+ `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1)).action(e=>z({mode:A(e)},Po()))}function Po(e,t=`apply`){let n=e;try{n??=s(process.argv[1])}catch(e){return w(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let r=n.name,i=n.version,o=n.registry===``?ae:a,c=n.registry===``&&r===`@aventurevc/aventure-cli`,l=Fo([`view`,o,`version`,`--silent`,`--global`],n,{timeout:Mo});if(!l.ok)return{...l,data:null};let u=(l.data??``).trim();if(u===``)return w(`npm view ${o} returned empty version`,[`empty_stdout`]);let d=c||jo.compare(i,u)<0,f={targetPackage:o,runningPackage:r,currentVersion:i,latestVersion:u,upgradeAvailable:d,upgradeInstalled:!1};if(t===`check`)return S(`${r}@${i} → ${o}@${u} (${d?`available`:`up to date`})`,f);if(!d)return S(`${r}@${i} already matches ${o}@${u}`,f);if(n.workingTreeRoot!==null)return w(`Refusing to install over the working-tree build at ${n.workingTreeRoot}; rebuild via make instead`,["running CLI is npm-linked from the back-end checkout — `update` is for published bins"]);let p=Ro(n),m=p===null?[]:[`--prefix`,p.installPrefix],h=p===null?null:P(p.installPrefix,`lib`,`node_modules`,...o.split(`/`)),g=c?Io(p,o,u):[];if(c){let e=Fo([`uninstall`,`-g`,...m,a],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return w(`Cannot remove the retired ${a}: ${e.summary}`,[...e.warnings,...g])}let _;try{_=zo(n,p)}catch(e){return w(`Cannot prepare MCP-owned CLI bins: ${Ho(e)}`,[`npm install was not run`])}let v=Fo([`install`,`-g`,...m,`${o}@${u}`],n,{stdio:[`ignore`,`inherit`,`inherit`]});if(!v.ok){let e=Bo(_,h);return e===null?{...v,warnings:[...v.warnings,...g],data:null}:w(`${v.summary}; MCP-owned CLI bin restoration failed`,[...v.warnings,e])}let y=p===null?void 0:Lo(p.installPrefix,o,u);if(y?.ok===!1){let e=Bo(_,h);return e===null?{...y,warnings:[...y.warnings,...g],data:null}:w(`${y.summary}; MCP-owned CLI bin restoration failed`,[...y.warnings,e])}let b=Vo(_);if(b!==null)return w(`${o} upgraded but MCP CLI bin backup cleanup failed`,[b]);let x=Uo();return S(`${o} upgraded to ${u}`,{...f,upgradeInstalled:!0,installPrefix:p?.installPrefix,verifiedVersion:y?.data??void 0,completionRefreshed:x.refreshed,completionRefreshMessage:x.message})}function Fo(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=ot(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?w(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):w(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
26
+ `).slice(-3).join(` | `);return w(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return S(`npm ok`,a.stdout??``)}function Io(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${a}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function Lo(e,t,n){let r;try{let n=s(P(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=P(e,`bin`,n.bin[0])}catch(e){return w(`updated ${t} verification failed: ${Ho(e)}`,[`invalid_package_metadata`])}let i=ot(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return w(`updated ${t} verification failed: ${i.error.message}`,[`spawn_error`]);let a=(i.stdout??``).trim();if(i.status!==0||a!==n){let e=(i.stderr??``).trim().split(`
27
+ `).slice(-3).join(` | `);return w(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return S(`active CLI version verified`,a)}function Ro(e){let t=`${lt}lib${lt}node_modules${lt}${e.name.replace(`/`,lt)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function zo(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}${lt}`))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=P(t.installPrefix,`bin`,n),i=ft(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=_t(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:gt(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=mt(P(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:P(r,st(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(vt(e.binPath,e.backupPath),a.push(e),gt(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=Bo({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 Bo(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=ft(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=P(N(r.binPath),gt(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${lt}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);St(r.binPath)}vt(r.backupPath,r.binPath)}catch(e){n.push(Ho(e))}if(e.backupDirectory!==null)try{bt(e.backupDirectory)}catch(e){n.push(Ho(e))}return n.length===0?null:n.join(`; `)}function Vo(e){let t=[];for(let n of e.backup)try{St(n.backupPath)}catch(e){t.push(Ho(e))}if(e.backupDirectory!==null)try{bt(e.backupDirectory)}catch(e){t.push(Ho(e))}return t.length===0?null:t.join(`; `)}function Ho(e){return e instanceof Error?e.message:String(e)}function Uo(){try{return ho()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var Wo=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers its generated status operation`},{name:`auth`,purpose:`which credential scope materialized locally, never the secret`},{name:`catalog`,purpose:`this catalog was generated from the operation set the API serves`}],Go=`operationFingerprint`;function Ko(e,t=s().bin[0]){j(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: [...] }`:",...Wo.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable)`,`does not fail the run. Each failing message names the command that fixes it.`,"--json always carries the report at `.data`; --data prints the report directly when",`every check passes and the result envelope when one fails, like every other command.`].join(`
28
+ `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),z({mode:A(e)},await qo(t))})}async function qo(e){let t=Yo(),n=Xo(e),[r,i]=await Promise.all([Zo(e),Qo(t,e)]),a=[n.check,r,i.check,await es(e),os(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:Jo(a,`pass`),fail:Jo(a,`fail`),skip:Jo(a,`skip`)},s=a.filter(e=>e.status===`fail`).map(e=>e.message),c={ok:s.length===0,check:a},l=[`doctor: ${o.pass} pass, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
29
+ `);return c.ok?S(l,c,{counts:o}):{...w(l,s,{counts:o}),data:c}}function Jo(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function Yo(){return M.find(e=>e.intent===`status`&&e.resource===`status`)}function Xo(e){let t=s(),n=Po(t,`check`);if(!n.ok||n.data===null)return{check:q(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?q(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):q(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function Zo(e){try{let{EntityDetailSchema:e}=await import(`./detail-D4XYLrLh.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return q(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return q(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${k(t)}.`)}}async function Qo(e,t){if(e===void 0)return{check:q(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=x().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${k(e)}.`),servedFingerprint:null}}let r=await T({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>w(k(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:$o(r.data)}:{check:q(`api-host`,`fail`,`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function $o(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)return null;let{response:t}=e;if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t[Go];return typeof n==`string`&&n.length>0?n:null}async function es(e){let t=Ee(),[n,r]=await Promise.all([ts(),ns()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?q(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Ce(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?q(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${h.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${rs(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${h.authToken} through the environment — ${r.summary}.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${h.authToken} in the environment.`)}async function ts(){let e;try{e=je(x().host)}catch(e){return{state:`unavailable`,summary:k(e)}}return await Me(e)}async function ns(){let e;try{e=Re(x().host)}catch(e){return{state:`unavailable`,summary:k(e),cause:`environment`}}try{return await Le(e)}catch(e){return{state:`unavailable`,summary:k(e),cause:`storage`}}}function rs(e,t,n){return[la(e),`oauth=${as(t)}`,`api-key=${is(n)}`].join(` `)}function is(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Re(x().host);return`${e.stored.activation}${Ji(t,e)}`}function as(e){switch(e.state){case`found`:return Ce(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 os(e,t,n,r){let i=M.length;if(e===void 0)return q(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return q(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${qe}.`);if(t===`9ffc3b4283f25389`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${qe}).`);let a=`This catalog describes a different operation set than the API serves (${qe} vs ${t})`;return n===!0?q(`catalog`,`fail`,`${a}: run \`${r} update\`.`):q(`catalog`,`skip`,n===!1?`${a}, and this CLI is already the latest published release: either the deployed API is older than this CLI, or a newer CLI has not been published yet.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var ss=B(V,`oauth`),cs=[B(V,`start`),B(V,`poll`),B(V,`acknowledge`)],ls=B(V,`revoke`);function us(e,t=s().bin[0]){let n=fs(e);Ko(n,t),qa(e,t);let r=[`${ss.description} Default method: OAuth in your browser.`,`With --key: ${cs.map(({description:e})=>e).join(` `)}`].join(`
30
+ `),a=async function(e){ps(this);let t=A(e);if(e.providers===!0){z({mode:t},await gs());return}z({mode:t},e.key===!0?await ki({noBrowser:!e.browser,clientLabel:e.clientLabel}):await it({noBrowser:!e.browser}))};j(ds(n,[ss,...cs],r)).action(a),j(ds(n,[ls],ls.description)).action(async function(e){ps(this),z({mode:A(e)},await _i({forgetLocal:e.forgetLocal===!0}))}),j(n.command(`status`).summary(`Keep saved credentials current and report them with API build and uptime`).description([`Runs the same credential materialization every command runs, then reports:`,` - auth: whether AUTH_TOKEN was already set in this shell's environment`,` - oauth: the saved OAuth identity and access-token expiry for the selected API host;`,` an expired token is renewed with its refresh token and a token Clerk rejects is retired`,` - api-key: the saved Clerk API key, re-verified with Clerk and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (Clerk instance and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`,` - system: GET /v1/status response (Better Stack uptime SLA)`,``,`Saved credentials are sent only to the selected API host and Clerk, never printed.`,`--verify read|write additionally runs a live permission probe for that scope; it does not`,`execute or authorize an arbitrary API operation.`].join(`
31
+ `)).addOption(new i(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){ps(this),z({mode:A(e)},await ms(t,e.verify))}),n.command(`token`).summary(`Print the bearer token the next command sends`).description([`Runs the same credential materialization every command runs, then prints the selected`,`bearer token alone on stdout: ${h.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved Clerk API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
32
+ `)).action(async function(){ps(this);let e=await Bi(t),n=process.env[h.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}z({mode:`text`},e.failure===null?Ss(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):w(`auth token: ${e.failure}`))})}function ds(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 fs(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${ss.command}\`: ${ss.summary}; \`--key\` ${cs[0].summary.toLowerCase()}.`,`\`${ls.command}\`: ${ls.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(`
33
+ `))}function ps(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function ms(e,t){let n;try{n=je(x().host)}catch(e){return w(`auth status: invalid API host — ${k(e)}`)}let r=Ee(),i=Bi(e),[a,o,c]=await Promise.all([xs(`/v1/status`,`GET /v1/status`),xs(`/info`,`GET /info`),_s()]),l=await i,[u,d]=await Promise.all([Me(n),hs(n)]),f=t===void 0?null:await Vi(t,u,d.inspection,l),p=s().version,m=Gi(n,d.inspection,d.verification),g=ta({cliName:e,cliVersion:p,apiVersion:o.ok?ys(o.data):null,oauth:u,apiKey:m,providers:c,resolved:r,refresh:l,systemOk:a.ok,live:f}),_={cli:{version:p},api:o.ok?o.data??null:null,auth:{[h.authToken]:r},selected:l.materialized,oauth:Ki(n,u),apiKey:m,providers:c,live:f,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return l.failure===null?f!==null&&f.error!==null?{...w(`auth status: ${f.scope} permission probe failed — ${f.error}`,[f.error]),data:_}:f!==null||r.present||u.state===`found`||d.inspection.state===`found`?S(g,_):Ss(`auth status: no credentials resolved | ${g}`,_,e,{oauth:u.state===`missing`,apiKey:d.inspection.state===`missing`}):{...w(`auth status: ${l.failure} | ${g}`,[l.failure]),data:_}}async function hs(e){let t=await vs(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await mi(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function gs(){let e=await _s();return e.state===`found`?S(`Sign-in providers for the selected API host`,e.catalog):w(`auth login --providers: ${e.summary}`)}async function _s(){try{return{state:`found`,catalog:await rt()}}catch(e){return{state:`unavailable`,summary:k(e)}}}async function vs(e){try{return await Le(e)}catch(e){return{state:`invalid`,summary:k(e)}}}function ys(e){if(!bs(e))return null;let t=Ur.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 bs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function xs(e,t){return await T({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>w(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Ss(e,t,n,r){return{...w(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${h.authToken} to a Clerk API key in the environment.`]),data:t}}var Cs=fe({VALIDATION_FAILED:`https://api.aventure.vc/errors/validation-failed`,MISSING_PARAMETER:`https://api.aventure.vc/errors/missing-parameter`,INVALID_PARAMETER_TYPE:`https://api.aventure.vc/errors/invalid-parameter-type`,UNKNOWN_PARAMETER:`https://api.aventure.vc/errors/unknown-parameter`,INVALID_ARGUMENT:`https://api.aventure.vc/errors/invalid-argument`,INVALID_REQUEST:`https://api.aventure.vc/errors/invalid-request`,INVALID_TOKEN:`https://api.aventure.vc/errors/invalid-token`,TOKEN_EXPIRED:`https://api.aventure.vc/errors/token-expired`,INVALID_AUTHENTICATION:`https://api.aventure.vc/errors/invalid-authentication`,CLIENT_CLOSED_REQUEST:`https://api.aventure.vc/errors/client-closed-request`,INVALID_JSON:`https://api.aventure.vc/errors/invalid-json`,METHOD_NOT_ALLOWED:`https://api.aventure.vc/errors/method-not-allowed`,NOT_ACCEPTABLE:`https://api.aventure.vc/errors/not-acceptable`,UNSUPPORTED_MEDIA_TYPE:`https://api.aventure.vc/errors/unsupported-media-type`,INTERNAL_ERROR:`https://api.aventure.vc/errors/internal-error`,UNEXPECTED_ERROR:`https://api.aventure.vc/errors/unexpected-error`,NOT_IMPLEMENTED:`https://api.aventure.vc/errors/not-implemented`,AUTHENTICATION_REQUIRED:`https://api.aventure.vc/errors/authentication-required`,AUTH_DOCS_REQUIRED:`https://api.aventure.vc/errors/auth.docs-required`,AUTH_ADMIN_KEY_NOT_CONFIGURED:`https://api.aventure.vc/errors/auth.admin-key-not-configured`,AUTH_EMPTY_ADMIN_KEY:`https://api.aventure.vc/errors/auth.empty-admin-key`,AUTH_EMPTY_ADMIN_BEARER:`https://api.aventure.vc/errors/auth.empty-admin-bearer`,AUTH_INVALID_ADMIN_KEY:`https://api.aventure.vc/errors/auth.invalid-admin-key`,AUTH_MISSING_ADMIN_KEY:`https://api.aventure.vc/errors/auth.missing-admin-key`,AUTH_METRICS_UNAUTHORIZED:`https://api.aventure.vc/errors/auth.metrics-unauthorized`,ACCESS_DENIED:`https://api.aventure.vc/errors/access-denied`,NOT_FOUND:`https://api.aventure.vc/errors/not-found`,GONE:`https://api.aventure.vc/errors/gone`,RATE_LIMITED:`https://api.aventure.vc/errors/rate-limited`,PRECONDITION_FAILED:`https://api.aventure.vc/errors/precondition-failed`,PRECONDITION_REQUIRED:`https://api.aventure.vc/errors/precondition-required`,BILLING_ALLOWANCE_EXHAUSTED:`https://api.aventure.vc/errors/billing-allowance-exhausted`,BILLING_ADDITIONAL_USAGE_CAP_REACHED:`https://api.aventure.vc/errors/billing-additional-usage-cap-reached`,SUBSCRIPTION_REQUIRED:`https://api.aventure.vc/errors/subscription-required`,SERVICE_UNAVAILABLE:`https://api.aventure.vc/errors/service-unavailable`,MALFORMED_FORM_BODY:`https://api.aventure.vc/errors/malformed-form-body`,STATE_CONFLICT:`https://api.aventure.vc/errors/state-conflict`,SLUG_HELD_BY_RECORD:`https://api.aventure.vc/errors/slug-held-by-record`,SLUG_HELD_BY_REDIRECT:`https://api.aventure.vc/errors/slug-held-by-redirect`,SLUG_AMBIGUOUS:`https://api.aventure.vc/errors/slug-ambiguous`,DUPLICATE:`https://api.aventure.vc/errors/duplicate`,DUPLICATE_KEY:`https://api.aventure.vc/errors/duplicate-key`,INTEGRITY_VIOLATION:`https://api.aventure.vc/errors/integrity-violation`,CIRCUIT_BREAKER_OPEN:`https://api.aventure.vc/errors/circuit-breaker-open`,BULKHEAD_FULL:`https://api.aventure.vc/errors/bulkhead-full`,WRITE_LANE_BUSY:`https://api.aventure.vc/errors/write-lane-busy`,DATABASE_UNAVAILABLE:`https://api.aventure.vc/errors/database-unavailable`,DATABASE_ERROR:`https://api.aventure.vc/errors/database-error`,FILE_TOO_LARGE:`https://api.aventure.vc/errors/file-too-large`,MISSING_FILE_PART:`https://api.aventure.vc/errors/missing-file-part`,INVALID_MULTIPART_BOUNDARY:`https://api.aventure.vc/errors/invalid-multipart-boundary`,MULTIPART_PARSE_ERROR:`https://api.aventure.vc/errors/multipart-parse-error`,NON_ENGLISH_ARTICLE:`https://api.aventure.vc/errors/non-english-article`,INVALID_IMAGE:`https://api.aventure.vc/errors/invalid-image`,UPSTREAM_EDGE_CHALLENGED:`https://api.aventure.vc/errors/upstream-edge-challenged`,ACCELERATOR_DETAIL_RESTATES_TARGET:`https://api.aventure.vc/errors/accelerator-detail-restates-target`});function ws(e,t,n=s().bin[0]){let r=wr(t),i=e.find(e=>e.cliPath.join(` `)===r||e.operationId===r);return i===void 0?w(`No generated operation matches "${t}"`,[`Resolve the exact command with \`${n} command-catalog search "<query>"\`.`]):S(`Resolved ${i.operationId}`,i)}function Ts(e){return e.parameters.some(e=>e.location===`path`)?w(`${e.operationId} has path parameters and cannot be batch-driven`,[e.path]):S(`no path parameters`,null)}function Es(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)return w(`--query expects key=value, got "${n}"`);t[n.slice(0,e)]=n.slice(e+1)}return S(`query parsed`,t)}function Ds(e,t,n,r){let i=Number(t);return!Number.isInteger(i)||i<n||i>r?w(`${e} must be an integer between ${n} and ${r}, got "${t}"`):S(`${e} parsed`,i)}function Os(e){let t=v.safeParse(e);return t.success?t.data:void 0}function ks(e,t){let n=Os(e);for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function As(e){let t=Os(e);return typeof t!=`object`||!t||Array.isArray(t)?null:t}function js(e){return typeof e==`object`&&e&&`response`in e?Os(e.response):Os(e)}function Ms(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ns(e){if(!F(e))return w(`--input file not found: ${e}`);let t=ht(e,`utf8`),n=[],r=t.split(`
34
+ `);for(let[e,t]of r.entries()){if(t.trim()===``)continue;let r=v.safeParse(Ls(t));if(!r.success)return w(`--input line ${e+1} is not valid JSON`,[t.slice(0,120)]);n.push(r.data)}return n.length===0?w(`--input has no NDJSON rows: ${e}`):S(`input parsed`,{row:n,digest:Rs(t)})}function Ps(e,t,n){let r={...t,outputBytes:0,completedChunk:[]};if(e===void 0||!F(e))return S(`no checkpoint`,r);let i=Ls(ht(e,`utf8`));if(i===void 0)return w(`--checkpoint file is not valid JSON: ${e}`);if(ks(i,`requestDigest`)===void 0)return w(`--checkpoint ${e} predates request identity checks; no chunks were sent`,[`Preserve the checkpoint and response file; reconcile completed chunks before restarting a write.`]);let a=ks(i,`completedChunk`),o=ks(i,`outputBytes`);if(Object.entries(t).some(([e,t])=>ks(i,e)!==t))return w(`--checkpoint ${e} was written for a different batch request or output`,[`Use the original request and output file, or a new checkpoint for a new batch.`]);if(!Array.isArray(a))return w(`--checkpoint ${e} has an invalid completedChunk list`);let s=a.filter(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<n);return s.length!==a.length||new Set(s).size!==s.length?w(`--checkpoint ${e} has an invalid completedChunk list`):s.length>0&&!F(t.outputPath)?w(`--checkpoint ${e} requires its previous output file: ${t.outputPath}`):typeof o!=`number`||!Number.isSafeInteger(o)||o<0||s.length>0&&xt(t.outputPath).size<o?w(`--checkpoint ${e} disagrees with its previous output file`):S(`checkpoint loaded`,{...t,outputBytes:o,completedChunk:s})}function Fs(e,t,n){if(e===void 0)return;let r={...t,outputBytes:xt(t.outputPath).size,completedChunk:[...n].toSorted((e,t)=>e-t)};Ct(e,`${JSON.stringify(r)}\n`)}function Is(e,t){return[...t,e]}function Ls(e){try{return JSON.parse(e)}catch{return}}function Rs(e){return kt(`sha256`).update(e).digest(`hex`)}var zs=new Set([Cs.enum.SUBSCRIPTION_REQUIRED,Cs.enum.BILLING_ALLOWANCE_EXHAUSTED]);function Bs(e,t,n=s().bin[0]){let r=e.command(`batch`).summary(`Export reads and run bulk writes as NDJSON`).description(`batch export pages a cursor read into an NDJSON file; batch preview reports a chunk plan; batch run sends chunked NDJSON writes with bounded concurrency and checkpoint/resume. Resolve targets with command-catalog search|show first.`);Vs(r,t,n),Hs(r,t,`preview`,n),Hs(r,t,`run`,n)}function Vs(e,t,n){let r=e.command(`export`).summary(`Page a cursor read operation into an NDJSON row file`).description([`Repeatedly call one generated cursor-paginated read operation and append`,`every returned row to --out as NDJSON while stdout stays a compact summary.`,` ${n} batch export --command "<resource> <area> <operation>" \\`,` --from-file filter.json --query size=200 --out rows.ndjson`].join(`
35
+ `)).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).option(`--from-file <path>`,`JSON request body sent on every page`).option(`--query <key=value>`,`Query parameter, repeatable`,Is,[]).requiredOption(`--out <path>`,`NDJSON output file; overwritten unless --append`).option(`--append`,`Append resumed pages to --out; requires --cursor`).option(`--cursor <cursor>`,`Starting cursor value`).option(`--cursor-param <name>`,`Cursor query parameter name`,`cursor`).option(`--rows-path <path>`,`Dot path to the row array in the response`,`row`).option(`--next-cursor-path <path>`,`Dot path to the next cursor in the response`,`nextCursor`).option(`--max-pages <count>`,`Safety cap on pages fetched`,`1000`);j(r),r.action(async function(){let e=this.optsWithGlobals();z({mode:A(e)},await Us(t,e,n))})}function Hs(e,t,n,r){let a=e.command(n).summary(n===`run`?`Send NDJSON rows through a batched write operation`:`Preview one batched write operation without sending rows`).description(n===`run`?[`Chunk NDJSON rows into batched request bodies for one generated write`,`operation and send them with bounded concurrency. Every chunk response is`,`appended to --out as NDJSON; --checkpoint records completed chunks so an`,`interrupted run resumes without resending them.`,`Use batch preview to inspect the chunk plan before sending rows.`,`--execute is deprecated, accepted, and ignored; run executes by its verb.`].join(`
36
+ `):`Build the same chunk plan as batch run without sending rows or writing --out.`).requiredOption(`--command <command>`,`Generated CLI command path or operationId`).requiredOption(`--input <path>`,`NDJSON file; each line is one batch row`).requiredOption(`--array-field <name>`,`Body field receiving each chunk of rows`).option(`--base <path>`,`JSON file with fixed body fields merged into every chunk`).option(`--query <key=value>`,`Query parameter, repeatable`,Is,[]).requiredOption(`--out <path>`,`NDJSON file receiving one response line per chunk`).option(`--chunk-size <count>`,`Rows per request body`,`25`).option(`--concurrency <count>`,`Concurrent requests, 1-8`,`2`).option(`--checkpoint <path>`,`JSON checkpoint file for resume`).addOption(new i(`--no-halt-on-failure`,`keep sending remaining chunks after a failed chunk; a subscription or allowance refusal still stops the run`));n===`run`&&a.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),j(a),a.action(async function(){let e=this.optsWithGlobals();z({mode:A(e)},await Ws(t,e,n,r))})}async function Us(e,n,r){let i=ws(e,n.command,r);if(!i.ok||i.data===null)return i;if(t(i.data.intent))return w(`${n.command} is a write operation; use \`batch run\``,[i.data.path]);let a=Ts(i.data);if(!a.ok)return a;let o=Es(n.query??[]);if(!o.ok||o.data===null)return o;let s=Ds(`--max-pages`,n.maxPages,1,1e6);if(!s.ok||s.data===null)return s;let c=n.fromFile===void 0?void 0:await xn(n.fromFile);if(c!==void 0&&!c.ok)return c;let l=c===void 0?void 0:As(c.data);if(c!==void 0&&l===null)return w(`--from-file must contain a JSON object`,[n.fromFile??``]);if(n.append&&n.cursor===void 0)return w(`--append requires --cursor from the previous export`);if(n.cursor!==void 0&&!n.append&&F(n.out))return w(`--cursor with an existing --out requires --append to preserve earlier rows`);if(n.append&&!F(n.out))return w(`--append requires the previous output file: ${n.out}`);Ct(n.out,``,{flag:n.append?`a`:`w`});let u=n.cursor,d=0,f=0,p=!1;for(;d<s.data;){let e={...o.data,...u===void 0?{}:{[n.cursorParam]:u}},t=await T({method:i.data.method,path:i.data.path,searchParams:e,body:l??void 0,auth:i.data.auth,responseFormat:`json`});if(!t.ok)return w(`page ${d+1} failed: ${t.summary}`,[`rows already written to ${n.out}: ${f}`,...u===void 0?[]:[`resume with --cursor "${u}" --append`]]);let r=js(t.data),a=ks(r,n.rowsPath);if(!Array.isArray(a))return w(`response has no array at --rows-path "${n.rowsPath}"`,[`page ${d+1}`]);ut(n.out,a.map(e=>`${JSON.stringify(e)}\n`).join(``)),d+=1,f+=a.length;let s=ks(r,n.nextCursorPath);if(typeof s!=`string`||s===``||s===u){p=!0;break}u=s}return S(`${f} rows across ${d} pages written to ${n.out}${p?``:`; PARTIAL export — hit --max-pages ${s.data}, resume with --cursor "${u}" --append`}`,{outPath:n.out,exhausted:p,lastCursor:u},{counts:{pageCount:d,rowCount:f}})}async function Ws(e,n,r,i){let a=ws(e,n.command,i);if(!a.ok||a.data===null)return a;if(!t(a.data.intent))return w(`${n.command} is not a write operation; use \`batch export\``,[a.data.path]);let o=Ts(a.data);if(!o.ok)return o;let s=Es(n.query??[]);if(!s.ok||s.data===null)return s;let c=Ds(`--chunk-size`,n.chunkSize,1,1e4);if(!c.ok||c.data===null)return c;let l=Ds(`--concurrency`,n.concurrency,1,8);if(!l.ok||l.data===null)return l;let u=n.base===void 0?void 0:await xn(n.base);if(u!==void 0&&!u.ok)return u;let d=As(u?.data??{});if(d===null)return w(`--base must contain a JSON object`,[n.base??``]);let f=Ns(n.input);if(!f.ok||f.data===null)return f;let p=Ms(f.data.row,c.data),m={inputDigest:f.data.digest,chunkSize:c.data,requestDigest:Rs(JSON.stringify({host:x().host,method:a.data.method,path:a.data.path,auth:a.data.auth,searchParams:s.data,baseBody:d,arrayField:n.arrayField})),outputPath:P(n.out)},h=Ps(n.checkpoint,m,p.length);if(!h.ok||h.data===null)return h;let g=new Set(h.data.completedChunk),_=[...p.keys()].filter(e=>!g.has(e));if(r===`preview`)return S(`PREVIEW — nothing sent. ${_.length} of ${p.length} chunks (${f.data.row.length} rows) would ${a.data.method} ${a.data.path}. Run ${i} batch run to send.`,{mode:`preview`,method:a.data.method,endpoint:a.data.path,arrayField:n.arrayField,outPath:n.out},{counts:{rowCount:f.data.row.length,chunkCount:p.length,pendingChunkCount:_.length,skippedChunkCount:g.size}});Ct(n.out,``,{flag:g.size>0?`a`:`w`});let v=a.data,y=s.data,b=[],ee=!1,C,te=0,ne=async e=>{let t=p[e]??[],r={...d,[n.arrayField]:t},i=await T({method:v.method,path:v.path,searchParams:y,body:r,auth:v.auth,responseFormat:`json`}),a=i.ok?js(i.data):null;return ut(n.out,`${JSON.stringify({chunk:e,rowCount:t.length,ok:i.ok,summary:i.summary,problem:i.ok?null:i.problem??null,response:a??i.data??null})}\n`),i.ok?(g.add(e),Fs(n.checkpoint,m,g),!0):(b.push(e),zs.has(i.problem?.type??``)&&(C=i.problem?.title),!1)};await Promise.all(Array.from({length:l.data},async()=>{for(;!ee;){let e=_[te];if(te+=1,e===void 0)return;!await ne(e)&&(n.haltOnFailure||C!==void 0)&&(ee=!0)}}));let re={rowCount:f.data.row.length,chunkCount:p.length,completedChunkCount:g.size,failedChunkCount:b.length,remainingChunkCount:p.length-g.size-b.length},ie={outPath:n.out,checkpointPath:n.checkpoint,failedChunk:b,halted:ee,...C===void 0?{}:{haltReason:C}};return b.length>0?w(`${b.length} chunk(s) failed${C===void 0?``:`; stopped: ${C}`}; responses in ${n.out}${n.checkpoint===void 0?``:`, resume via --checkpoint ${n.checkpoint}`}`,[JSON.stringify({...ie,...re})]):S(`${g.size}/${p.length} chunks sent; responses in ${n.out}`,ie,{counts:re})}function Gs(e,t=M,n=s().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{I.stdout.write(qs(e,i,t))});fo(r,n),po(r,n)}function Ks(){return s().bin}function qs(e,t,n=M,r=Ks()){let i=nc(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Ys(e),...r.map(e=>`complete -c ${J(e)} -e`),`${hc(r)} -f`,...Xs(e,r),...Zs(e,i,r),``].join(`
37
+ `):Js(e,t,i,r)}function Js(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=ac(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}`),`)`,``,...cc(t),...t===`bash`?[a,``]:[``]].join(`
38
+ `)}function Ys(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${Qs(e).filter(e=>e.required||e.optional).flatMap(e=>dc(e)??[]).map(J).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
39
+ set -l expected $argv
40
+ set -l actual (__aventure_cli_command_path)
41
+ if test (count $actual) -ne (count $expected)
42
+ return 1
43
+ end
44
+ if test (count $expected) -eq 0
45
+ return 0
46
+ end
47
+ for index in (seq (count $expected))
48
+ if test $actual[$index] != $expected[$index]
49
+ return 1
50
+ end
51
+ end
52
+ return 0
53
+ end
54
+ `].flatMap(e=>e.split(`
55
+ `))}function Xs(e,t){return ic(e).map(e=>`${hc(t)} -f -n ${J(gc(e.parentPath))} -a ${J(e.name)} -d ${J(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Zs(e,t,n){return fc(e).flatMap(e=>{let r=mc(e),i=r.length===0?void 0:gc(r);return Qs(e).flatMap(e=>{let a=t.get(rc(r,e));return sc(a)?$s(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function Qs(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function $s(e,t,n,r){let i=dc(e);if(i===void 0)return[];let a=e.argChoices??oc(n),o=[`-l ${J(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${J(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${J(t)}`,c=e.required||e.optional?ec(a,tc(i,n)):`-f`,l=`${hc(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${J(_c(e.description))}`]:a.map(t=>`${l} -a ${J(t)} -d ${J(_c(e.description))}`)}function ec(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function tc(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 nc(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...pn(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[[rc(e.cliPath,n),t]]})))}function rc(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):dc(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 ic(e){return fc(e).flatMap(e=>e.commands.map(t=>({parentPath:mc(e),name:t.name(),description:_c(t.summary()||t.description()||t.name())})))}function ac(e,t){let n=[],r=[];for(let i of fc(e)){let e=mc(i);for(let a of Qs(i)){let i=dc(a);if(i===void 0)continue;let o=t.get(rc(e,a));if(!sc(o))continue;let s=a.argChoices??oc(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&tc(i,o)&&(c=`file`)),n.push(lc([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(lc([e.join(` `),`--${i}`,t,a.description]))}}return[ic(e).map(e=>lc([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 oc(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 sc(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function cc(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 lc(e){return`$'${e.map(uc).join(`|`)}'`}function uc(e){return _c(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function dc(e){return e.long?.replace(/^--/,``)}function fc(e){return[e,...e.commands.filter(pc).flatMap(e=>fc(e))]}var pc=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function mc(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function hc(e){return`complete ${e.map(e=>`-c ${J(e)}`).join(` `)}`}function gc(e){return[`__aventure_cli_path_is`,...e.map(J)].join(` `)}function _c(e){return e.replace(/\s+/g,` `).trim()}function J(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function vc(e,t){if(e!==t)return;let n=yc(t);n!==void 0&&t.error(`error: ${xc(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function yc(e){if(!process.argv.includes(`--`)&&e.args.some(bc))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function bc(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function xc(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function Sc(e){return e.message.match(/required option '([^']+)' not specified/iu)?.[1]?.split(/\s+/u)[0]}function Cc(e){return e.message.match(/unknown option '([^']+)'/iu)?.[1]}function wc(e){return e.message.match(/unknown command '([^']+)'/iu)?.[1]}function Tc(e){return e.flags.split(` `)[0]??e.flags}function Ec(e,t){let n=Sc(t);if(n===void 0)return;let r=e.options.findIndex(e=>Tc(e)===n);if(r<0)return;let i=e.options.slice(r+1).filter(e=>e.mandatory).map(t=>[Tc(t),e.getOptionValue(t.attributeName())]).find(([,e])=>typeof e==`string`&&e.length>0)?.[0];if(i!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${i} does not replace the parent selector.`}function Y(e){let t=[];for(let n=e;n!==null&&n.parent!==null;n=n.parent)t.unshift(n.name());return t}function Dc(e){return e.commands.length===0?[e]:e.commands.flatMap(Dc)}function Oc(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 kc(e,t){return t.toSorted((t,n)=>{let r=Oc(e,t),i=Oc(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 Ac(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function jc(e,t){let n=Y(e),r=process.argv.slice(2+n.length);return[X(e).name(),...n,...Oc(e,t),...r].map(Ac).join(` `)}function Mc(e,t){let n=Cc(t);if(n===void 0||e.commands.length===0)return;let r=kc(e,Dc(e).filter(e=>e.options.some(e=>Tc(e)===n)));if(r!==void 0)return`hint: run: ${jc(e,r)}`}function Nc(e){return e!==void 0&&Object.hasOwn(Ue,e)}function Pc(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 Fc(e,t){let n=Y(e),r=[...n.slice(1),t];if(!Nc(n.at(0))||!Nc(r.at(0)))return;let i=Pc(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 Ic(e,t){let[n]=Y(e);if(!Nc(n))return;let r=[n,t];return Pc(X(e),r)?.commands.length===0?r:void 0}function Lc(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Dc(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 Rc(e,t){let n=process.argv.slice(2+Y(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return zc(e,t)}function zc(e,t,n=[]){let r=Y(e),i=Ge(M).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(Ac).join(` `)}`}function Bc(e,t,n){if(!Hc(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(Ac).join(` `)}`}function Vc(e){let t=Y(e);if(t.at(1)!==void 0&&Nc(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(Ac).join(` `)}`}function Hc(e,n){let r=e.join(` `);return M.some(e=>e.cliPath.join(` `)===r?n===void 0||t(e.intent)===n:!1)}function Uc(e){let t=Y(e).join(` `),n=Ge(M),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:_r(r.operationId,n,X(e).name()).map(e=>`hint: ${e}`)}function Wc(e){let t=Y(e);if(Nc(t.at(0))&&Hc(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(Ac).join(` `)}`}function Gc(e){let n=new Set,r=[];for(let i of M){let a=Pc(e,i.cliPath);if(a===void 0)continue;let o=a.options.map(Tc);if(t(i.intent))r.push(o);else for(let e of o)n.add(e)}let[i=[],...a]=r;return new Set(i.filter(e=>!n.has(e)&&a.every(t=>t.includes(e))))}function Kc(e,t){let n=Y(e);if(Hc(n,!1)&&Gc(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function qc(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=>Tc(e)===`--root`);return n&&s!==void 0&&c!==void 0&&Nc(s)&&o.push(Tc(c),s),`hint: search generated commands: ${o.map(Ac).join(` `)}`}function Jc(e,t){let n=wc(t);if(n===void 0||t.message.includes(`
56
+ (Did you mean `))return;let r=Lc(e),i=Rc(e,r);if(i!==void 0)return i;let a=Fc(e,n);if(a!==void 0)return qc(e,a.join(` `),!1);let o=Ic(e,n);if(o!==void 0)return Bc(e,o,r)??qc(e,o.join(` `),!1);let s=r.join(` `)||n,c=Vc(e)??qc(e,s),l=[...Y(e),...r.slice(1)];return[l.slice(1,-1).length>0?Bc(e,l,r):void 0,c].filter(e=>e!==void 0).join(`
57
+ `)||void 0}function Yc(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[yc(e),Ec(e,t),...Uc(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=yc(e)??Wc(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=Cc(t),r=Mc(e,t)??(n!==void 0&&!t.message.includes(`
58
+ (Did you mean `)?Kc(e,n)??zc(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??qc(e,n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Jc(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Xc=class extends i{group;constructor(e){super(`-h, --help`,`display help for command`),this.group=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.group.args.at(0);return t===void 0||t.startsWith(`-`)?!0:this.group.commands.some(e=>e.name()===t||e.aliases().includes(t))}};function Zc(e){e.showHelpAfterError(!1).exitOverride(Yc(e)),e.commands.length===0?e.hook(`preAction`,vc):e.addHelpOption(new Xc(e));for(let t of e.commands)Zc(t)}var Qc=`dist/aventure-cli/command-catalog.compact.txt`,$c=` · `,el=`-`;function tl(e=s().bin[0]){return P(nl(N(Dt(import.meta.url)),e),Qc)}function nl(e,t){let n=e;for(;;){if(F(P(n,`package.json`)))return n;let r=N(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function rl(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function il(e,t,n,r=s().bin[0]){let i=rr(e,t,r);if(!i.ok||i.data===null){z({mode:n},i);return}ol({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:cl(i.data,sl(e.format,`lines`)),summary:`Generated operation matches`})}function al(e,t,n,r=s().bin[0]){let i=ir(e,t,r);if(!i.ok||i.data===null){z({mode:n},i);return}ol({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:ll(i.data,sl(e.format,`usage`)),summary:`Generated operation detail`})}function ol(e){let t=e.mode,n=sl(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`)){z({mode:t},w(`--text or --all-fields cannot be combined with --format json or ndjson`,[`Omit the text flag for machine output, or use --format lines, compact, or text.`]));return}let i=e.opts.output===void 0&&t===`text`&&`count`in e.data&&e.data.count.returned===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
59
+ `)?i:`${i}\n`;if(e.opts.output!==void 0){Ct(e.opts.output,a),z({mode:t},S(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:ml(e.data)}));return}if(t===`text`){process.stdout.write(a);return}z({mode:t},S(e.summary,e.data,{counts:ml(e.data)}))}function sl(e,t){return e??t}function cl(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
60
+ `):t===`text`?fl(e.operation):t===`compact`?e.operation.map(ul).join(`
61
+ `):e.operation.map(pl).join(`
62
+ `)}function ll(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?pl(e.operation):t===`compact`?ul(e.operation):e.usage}function ul(e){let t=dl(e);return[e.cli.command,e.summary,t.length===0?el:t.join(` `)].join($c)}function dl(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function fl(e){return e.map(e=>`${e.cli.command}\n ${pl(e)}`).join(`
63
+ `)}function pl(e){let t=dl(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 ml(e){return`count`in e?e.count:{returned:1}}function hl(e,t=new Date){let n=vl(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 gl(e){return`${JSON.stringify(e,null,2)}\n`}function _l(e,t){let n=P(e),r=gl(t);return pt(N(n),{recursive:!0}),Ct(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function vl(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:C(e.intent),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var yl=`Match only the first canonical or CLI-alias command segment`,bl=[`text`,`lines`,`compact`,`json`,`ndjson`];function xl(e,t,n=s().bin[0]){Cl(e,t,n);let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
64
+ `));r.addHelpText(`after`,()=>`\nShipped compact catalog, greppable without running this CLI:\n ${tl(n)}\n`),Sl(r,t,n),El(r,t,n),Dl(r,t,n),Ol(r)}function Sl(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>`,yl).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`,`20`).addOption(new i(`--format <format>`,`Text/file render format`).choices(bl)).option(`--output <path>`,`Write rendered output to a file`);j(r),r.action(function(e){let r=this.optsWithGlobals(),i=A(r,`text`);il(rl(r,e),t,i,n)})}function Cl(e,t,n){let r=e.command(`docs`).summary(`Look up generated API documentation offline`).description(`Print generated operation documentation without calling the API.`).command(`api`).summary(`Show documentation for one operation`).description([`Print one operation's summary, description, flags, example, and error contract.`,"Select it by `<METHOD> <path>` (route template or concrete path), by operationId,",`or by CLI command path, e.g. "entities get".`].join(`
65
+ `)).argument(`<selector...>`,`METHOD and path, an operationId, or a CLI command path`);j(r),r.action(function(e){let r=this.optsWithGlobals(),i=A(r),a=Tl(e,t);if(!a.ok||a.data===null){z({mode:i},a);return}al({...r,...a.data},t,i,n)})}var wl='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Tl(e,t){let[n,...r]=e,i=ce.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return S(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=ee(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return S(`Resolved by route template`,{operationId:s.operationId});let c=te({method:a,path:o});return!c.ok||c.data===null?w(c.summary,[...c.warnings,wl]):S(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function El(e,t,n){let r=e.command(`show`).summary(`Show one generated operation`).description(`Show one generated operation by command path or operationId.`).option(`--command <command>`,`CLI command path, with or without ${n} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new i(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);j(r),r.action(function(){let e=this.optsWithGlobals();al(e,t,A(e,`text`),n)})}function Dl(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>`,yl).addOption(new i(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new i(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new i(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new i(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new i(`--format <format>`,`Text/file render format`).choices(bl)).option(`--output <path>`,`Write rendered output to a file`);j(r),r.action(function(){let e=this.optsWithGlobals();il(e,t,A(e,`text`),n)})}function Ol(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`);j(t),t.action(function(){let e=this.optsWithGlobals(),t=A(e,`text`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){z({mode:t},S(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:Ze.length}}));return}let n=hl(Ze);if(e.output!==void 0){let r=_l(e.output,n);z({mode:t},S(`Unified operations JSON written`,{outputPath:r.target,byteLength:r.byteLength,schemaVersion:n.schemaVersion},{counts:{totalOperations:r.totalOperations}}));return}if(t===`text`){process.stdout.write(gl(n));return}z({mode:t},S(`Unified operations JSON`,n,{counts:{totalOperations:n.totalOperations}}))})}var kl=s(Dt(import.meta.url)),Q=kl.bin[0];function Al(e,t){f({component:`aventure-cli`,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof re?{httpStatus:e.problem.status,problem:e.problem}:{};qn({...w(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function jl(e){return Xe[Ve(e)??`cli`]}function Ml(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:jl(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>Ye(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)Nl(e,t,r,a,i.has(t.cliPath.join(` `)))}function Nl(e,n,i,a,o){let s=n.cliPath,c=e,u=``,d=!i.has(s[0]??``);for(let e of s.slice(0,-1)){u=u===``?e:`${u} ${e}`;let t=d&&u===e||!a.has(u);c=Pl(c,e,u,t)}let f=s.at(-1)??n.operationId,p=c.commands.find(e=>e.name()===f)??c.command(f,n.deprecated===!0?{hidden:!0}:{}),m=n.requestBody?.flatMap(({parameter:e})=>e)??[];p.summary(n.summary||n.operationId).description([`${n.method} ${n.path}.`,n.summary||n.description,`Full API documentation: ${Q} docs api ${n.operationId}`,n.requestBody?.[0]?.kind===`json`||[...n.parameters,...m].some(e=>l(e.schemaType,e.itemSchemaType))?r:``].filter(Boolean).join(`
66
+ `));let h=Rr(n);for(let e of n.parameters)Fl(p,e,o||e===h);if(wn(p,n),t(n.intent)&&p.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),j(p),n.explain===!0&&p.option(`--explain`,`Print the search strategy and parsed constraints before the results`),h!==void 0){p.argument(`[text...]`,h.description||`Same as ${Lr(h.flag)}.`),p.action(async function(e){let t=this.optsWithGlobals(),r=A(t),i=zr(h,e,t);if(!i.ok||i.data===null)return z({mode:r},i);let a=Ir(n,i.data);if(a.length>0)return z({mode:r},w(`missing required options: ${a.join(`, `)}`));let o=await Il(n,i.data,r),s=Br(n,i.data,o);if(s!==null)return z({mode:r},s);t.explain===!0&&o.ok&&Zn(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):z({mode:r},o)});return}p.action(async function(){let e=this.optsWithGlobals(),t=A(e),r=Ir(n,e);if(r.length>0)return z({mode:t},w(`missing required options: ${r.join(`, `)}`));let i=await Il(n,e,t),a=Br(n,e,i);if(a!==null)return z({mode:t},a);e.explain===!0&&i.ok&&Zn(t,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):z({mode:t},i)})}function Pl(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=Ue[n],o=e.command(t,r?{hidden:!0}:{});return a!==void 0&&o.summary(a.summary).description(a.summary),o}function Fl(e,t,n=!1){let r=t.description||`${t.name} ${t.location} parameter`,a=t.defaultValue===void 0?void 0:typeof t.defaultValue==`string`||typeof t.defaultValue==`boolean`?t.defaultValue:[...t.defaultValue];if(t.legacyFlag!==void 0){let o=new i(t.flag,r);a!==void 0&&o.default(a);let s=new i(t.legacyFlag,r).conflicts(t.optionKey);e.addOption(o).addOption(s),e.hook(`preAction`,e=>{let r=e.opts(),i=r[t.optionKey],a=r[s.attributeName()];if(a!==void 0){(i===void 0||e.getOptionValueSource(t.optionKey)==="default")&&e.setOptionValueWithSource(t.optionKey,a,`cli`);return}!n&&t.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(a!==void 0){e.option(t.flag,r,a);return}if(t.required&&!n){e.requiredOption(t.flag,r);return}e.option(t.flag,r)}async function Il(t,n,r){if(n.environment!==void 0){let t=e(n.environment);if(t===null)return w(`Unknown aVenture environment '${n.environment}'`,[`Use one of: ${d().join(`, `)}`]);process.env.API_ENV=t}let i=await kn(t,n);if(!i.ok)return i;let a=Object.fromEntries(t.parameters.filter(e=>e.location===`path`).map(e=>{let t=n[e.optionKey];if(Array.isArray(t))return[e.name,t.at(0)??``];if(t===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(t)]})),o=Object.fromEntries(t.parameters.filter(e=>e.location===`query`).flatMap(e=>{let t=n[e.optionKey];if(t===void 0||Array.isArray(t)&&t.length===0)return[];let r=Array.isArray(t)||typeof t==`boolean`?t:String(t);return[[e.name,r]]})),s=Object.fromEntries(t.parameters.filter(e=>e.location===`header`).flatMap(e=>{let t=n[e.optionKey];return t===void 0||Array.isArray(t)&&t.length===0?[]:[[e.name,Array.isArray(t)?t.join(`,`):String(t)]]}));return await T({method:t.method,path:oe(t.operationId,a),searchParams:o,headers:s,body:i.data,contentType:typeof n.contentType==`string`?n.contentType:void 0,auth:t.auth,responseFormat:ze(r)?`json`:`auto`,responseBytes:t.binaryResponse===!0})}process.on(`uncaughtException`,e=>Al(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>Al(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var Ll=Be(process.argv.slice(2),M),Rl=Ll===`required`?M:Ge(M),$=new u;$.name(Q).configureHelp(kr).version(kl.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.
67
+ `,` Sign in: ${Q} auth login`,` Find: ${Q} entities lookup get --name Stripe\n`,`Mutations execute directly; --execute is a deprecated no-op.
68
+ The aVenture MCP server tools execute through this same CLI.`].join(`
69
+ `)).addOption(new i(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${g})`).choices([...d()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),Ml($,Rl),us($,Q),No($,kl),Bs($,Rl,Q),Gs($,Rl,Q),xl($,Rl,Q),Tr($,Rl,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(jl(e.name()).heading);if(Zc($),Ll===`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 Ne(),await Fe())}))}}$.addHelpText(`after`,[``,`Verbs, the same on every record:`,` search Find many from a plain-English query or a filter`,` lookup Resolve a name, URL, slug, ticker, or id to its record`,` get Read one record`,` list Read many records`,` suggest Read proposed values for a field`,` create, update, delete Write; each needs a credential that permits it
70
+ `,`Environment (the one API credential):`,` AUTH_TOKEN Clerk API key or session token for every authenticated call`,` Public reads work with no credential; a saved sign-in is used when present.`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
71
+ `,`Exit codes:`,` 0 envelope.ok === true
72
+ 1 envelope.ok === false
73
+ `,`Examples:`,` $ ${Q} auth login`,` $ ${Q} entities lookup get --entity-slug stripe-south-san-francisco-ca-us`,` $ ${Q} entities investors list \\\n --entity-id 4eabfc26-3ed9-4ad3-a935-9be07ae3329a`,` $ ${Q} search natural entities \\\n --query "fintech companies in Austin" # Pro plan`].join(`
74
+ `));try{await $.parseAsync()}catch(e){Al(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};
@@ -0,0 +1 @@
1
+ import{C as e,D as t,O as n,_ as r,a as i,c as a,f as o,k as s,l as c,n as l,p as u,t as d,v as f}from"./person-owner-BqBLyw4S.js";var ee=i([`domicile`,`dominant`,`origin`]),p=f({endDate:n().nullish(),id:o(),isCurrent:c(),role:ee.nullish(),startDate:n().nullish()}),m=f({id:o().nullish(),name:e()}),h=f({countryCodeChar2:e().nullish(),countryCodeChar3:e().nullish(),id:o().nullish(),name:e(),unRegion:e().nullish(),unSubregion:e().nullish()}),g=f({id:o().nullish(),name:e(),stateAbbrev:e().nullish()}),_=f({address:o().nullish(),addressLine1:e().nullish(),addressLine2:e().nullish(),association:a(p).optional(),city:m.nullish(),country:h.nullish(),countryAbbrev:e().nullish(),createdAt:s({offset:!0}).nullish(),fullAddress:e().nullish(),id:o().nullish(),isCurrent:c().nullish(),isHq:c().nullish(),isPrimary:c().nullish(),latitude:r().nullish(),longitude:r().nullish(),postalCode:e().nullish(),state:g.nullish(),stateAbbrev:e().nullish(),street:e().nullish(),updatedAt:s({offset:!0}).nullish()}),v=f({creatable:c(),isCurrent:c().nullish(),isPrimary:c().nullish(),name:e().max(255),writable:c()}),y=u(v,f({bucket:e().nullish(),classificationId:o().nullish(),creatable:c(),createdAt:s({offset:!0}).nullish(),id:o(),isCurrent:c().nullish(),isPrimary:c().nullish(),name:e().max(255),slug:e().regex(/^[a-z0-9_-]+$/).max(255).nullish(),type:e(),updatedAt:s({offset:!0}).nullish(),writable:c()})),b=u(v,f({category:e(),code:o().nullish(),creatable:c(),createdAt:s({offset:!0}).nullish(),entityClassificationId:o().nullish(),id:o(),isCurrent:c().nullish(),isPrimary:c().nullish(),level:o().nullish(),name:e().max(255),updatedAt:s({offset:!0}).nullish(),writable:c()})),x=f({geoLocationExposure:a(y).default([]).optional(),industry:a(y).default([]).optional(),mainProduct:a(y).default([]).optional(),standardizedClassification:a(b).default([]).optional(),tag:a(y).default([]).optional(),typeCustomer:a(y).default([]).optional(),typeModel:a(y).default([]).optional(),typeOwnership:a(y).default([]).optional(),typeRevenue:a(y).default([]).optional(),typeTechnologyUsed:a(y).default([]).optional()}),S=i(`Angel.Pre-Seed.Seed.Series A.Series B.Series C.Series D.Series E.Series F.Series G.Series H.Series I.Series J.Series K.Series L.Series M.Series N.Series O.Series P.Series Q.Series R.Series S.Series T.Series U.Series V.Series W.Series X.Series Y.Series Z.Investment Firm.Fund.Nonprofit.Government.Public.Acquired.Acquired Subsidiary`.split(`.`)),C=f({currency:e().nullish(),fundingRoundCount:o(),investorCount:o(),latestValuation:r().nullish(),mostRecentAmount:r().nullish(),mostRecentDate:n().nullish(),stage:S.nullish(),totalRaised:r()}),w=f({expanded:e().nullish(),generatedDescription:e().nullish(),short:e().nullish()}),te=i([`cloudflare`,`akamai`,`fastly`,`awsCloudfront`,`vercel`,`netlify`,`sucuri`,`incapsula`,`bunny`,`keycdn`,`cdn77`,`gcore`,`cdnetworks`,`azureCdn`,`leaseweb`,`digitalocean`,`stackpath`,`googlecloudCdn`,`none`,`unknown`]),ne=i([`static`,`jsRequired`,`jsEnhanced`]),T=i(`website.linkedin.twitter.github.facebook.instagram.tiktok.youtube.subreddit.forum.documentation.support.statuspage.changelog.roadmap.discord.crunchbase.wellfound.angellist.glassdoor.theorg.ycombinator.wikipedia.pitchbook.morningstar.bloomberg.nyse.nasdaq.g2.producthunt.trustpilot.alternativeto.gartnerpeerinsights.getapp.sourceforge.appstore.googleplay.capterra.trustradius.hubspotmarketplace.slackappdirectory.awsmarketplace.salesforceappexchange.chromewebstore.vscodemarketplace.npm.pypi.maven.dockerhub.homebrew.crates.huggingface`.split(`.`)),E=f({crawlCdnProvider:te.nullish(),crawlRenderMode:ne.nullish(),createdAt:s({offset:!0}).nullish(),id:o().nullish(),isCurrent:c().nullish(),isPrimary:c().nullish(),owner:d.nullish(),sourceId:e().nullish(),status:e().nullish(),statusChecked:s({offset:!0}).nullish(),updatedAt:s({offset:!0}).nullish(),url:e(),urlType:T}),D=f({address:a(_),classification:x,fundingDetail:C.nullish(),text:w,urlLink:a(E)}),O=f({isMonogram:c(),logo:e().nullish(),logoSquare:e().nullish()}),k=i([`alternativeDba`,`relatedLegal`]),A=f({displayable:c().nullish(),name:e(),type:k.nullish()}),j=f({hasAcquisitions:c().default(!1).optional(),hasAnalysis:c(),hasEmployees:c(),hasFundraising:c(),hasNews:c(),productServiceSlug:a(e())}),M=f({defaultCurrency:e().nullish(),foundedYear:o().nullish(),id:t(),image:O,lastModifiedAt:s({offset:!0}).nullish(),nameAlias:a(A),nameBrand:e(),nameLegal:e().nullish(),operatingStatus:e().nullish(),publicId:e().regex(/^e[0-9A-Za-z]{11}$/).nullish(),publicUrl:e().nullish(),sitemap:j.nullish(),slug:e().regex(/^[a-z0-9_-]+$/).max(255),typeRecord:l.nullish(),updatedAt:s({offset:!0}).nullish()}),N=f({core:M,fundingDetail:C.nullish()}),P=i([`High`,`Medium`,`Low`,`Verified`]),F=i([`direct`,`managedFund`]),I=f({round:e()}),L=f({amountInvested:r().nullish(),attributionType:F,beneficialEntityId:t().nullish(),fundManagerRelationshipId:o().nullish(),joinId:t(),leadInvestor:c(),recordedEntityId:t().nullish(),round:I.nullish(),transactionId:t()}),R=f({amountRaised:r().int().nullish(),createdAt:s({offset:!0}).nullish(),currency:e().nullish(),dataConfidence:P.nullish(),dateAnnounced:s({offset:!0}).nullish(),dateFundingComplete:s({offset:!0}).nullish(),dateInvestorExit:s({offset:!0}).nullish(),entity:N.nullish(),id:t(),investorAttribution:L.nullish(),investorCount:o().nullish(),round:e().nullish(),sourceAttribution:a(L),updatedAt:s({offset:!0}).nullish(),valuationPostMoney:r().int().nullish(),valuationPreMoney:r().int().nullish()}),z=f({fundingStage:S.nullish(),ownership:a(e()),pricingModel:a(e()),sellsTo:a(e()),totalRaised:r().nullish(),website:e().nullish()}),B=f({asOf:n().nullish(),comparisonSignals:z.nullish(),createdAt:s({offset:!0}).nullish(),detail:e().nullish(),entity:M,id:o().nullish(),isCurrent:c().nullish(),isPrimary:c().nullish(),get relationship(){return a(B)},relationshipType:e(),source:e().nullish(),sourceEntityId:t().nullish(),targetEntityId:t().nullish(),updatedAt:s({offset:!0}).nullish()}),V=B,H=f({accelerator:M,acceleratorName:e(),asOfDate:s({offset:!0}),batch:e().nullish(),id:e(),program:e().nullish(),status:e().nullish()}),U=i([`text`,`numeric`,`monetary`,`percentage`,`date`]),W=i([`pastDue`,`withinThreeMonths`,`threeToSixMonths`,`sixToTwelveMonths`,`twelveToTwentyFourMonths`,`beyondTwoYears`]),re=f({asOfDate:s({offset:!0}),bucket:W,monthsFromNow:o(),targetDate:s({offset:!0})}),G=f({asOfDate:s({offset:!0}).nullish(),derivedRange:re.nullish(),discreteValue:r().nullish(),entityId:t(),id:o(),textValue:e().nullish(),typeResearchDetail:e(),updatedAt:s({offset:!0}).nullish(),valueResearchDetail:e().nullish(),valueType:U}),K=f({characterCount:o(),meetsRequirements:c(),violation:a(e()),wordCount:o()}),q=f({compliance:K.nullish(),entityId:t(),id:o(),text:e(),textType:e(),updatedAt:s({offset:!0}).nullish()}),J=f({acceleratorParticipation:a(H),detail:a(G),snippet:a(q)}),Y=f({author:e().nullish(),category:e().nullish(),createdAt:s({offset:!0}).nullish(),excerpt:e().nullish(),externalNewsArticle:c().nullish(),id:o(),newsImageThumbnail:e().nullish(),newsUrlOriginal:e().nullish(),publication:e().nullish(),publishedAt:s({offset:!0}).nullish(),slug:e().regex(/^[a-z0-9_-]+$/).max(255).nullish(),title:e(),updatedAt:s({offset:!0}).nullish()}),X=i([`nickname`,`maidenName`,`formerName`,`stageName`]),Z=f({displayable:c().nullish(),name:e(),type:X.nullish()}),Q=f({isMonogram:c(),picture:e().nullish()}),ie=f({associationId:o(),endDate:s({offset:!0}).nullish(),entityAddress:a(_),entityId:t(),entityLogo:O,entityName:e().nullish(),entityOperatingStatus:e().nullish(),entitySlug:e().regex(/^[a-z0-9_-]+$/).max(255),entityType:l.nullish(),entityUrlLink:a(E),isCurrent:c().nullish(),personAddress:a(_),personId:t(),personImage:Q,personName:e(),personSlug:e().regex(/^[a-z0-9_-]+$/).max(255),personUrlLink:a(E),score:o().nullish(),startDate:s({offset:!0}).nullish(),titleFunction:e().nullish(),titleId:o().nullish(),titleLevel:e().nullish(),titleName:e().nullish()}),ae=f({address:a(_),urlLink:a(E)}),oe=f({amountRaised:r().nullish(),dateAnnounced:s({offset:!0}).nullish(),id:t(),image:O,investorCount:o().nullish(),nameBrand:e(),round:e().nullish(),status:e().nullish(),valuationPostMoney:r().nullish()}),se=f({entity:M}),ce=f({amount:r().nullish(),company:se,date:s({offset:!0}).nullish(),fundraiseTransaction:oe.nullish(),fundraiseTransactionId:t(),id:e(),investmentDate:s({offset:!0}),investorAttribution:L.nullish(),round:e().nullish()}),le=i([`entity`,`person`,`newsArticle`,`blogPost`,`text`,`classificationTag`,`classificationCode`,`product`,`service`,`agentHelpDoc`]),$=f({computedAt:s({offset:!0}),cosineDistance:r(),cosineScore:r(),modelVersion:e(),rank:o(),sourceHash:e(),sourceId:e(),sourceJson:e(),sourceText:e(),sourceType:le}),ue=f({createdAt:s({offset:!0}).nullish(),gender:e().nullish(),id:t(),image:Q,lastModifiedAt:s({offset:!0}).nullish(),nameAlias:a(Z),nameFirst:e().nullish(),nameFull:e(),nameLast:e().nullish(),nameMiddle:e().nullish(),nickname:e().nullish(),publicId:e().regex(/^p[0-9A-Za-z]{12}$/).nullish(),semanticMatch:$.nullish(),slug:e().regex(/^[a-z0-9_-]+$/).max(255),suffix:e().nullish(),text:w,updatedAt:s({offset:!0}).nullish()}),de=f({articleCount:o().nullish(),association:a(ie),core:ue,enrichment:ae,investment:a(ce),nameAlias:a(Z)}),fe=i([`ein`,`secCik`,`ticker`,`lei`,`duns`,`isin`,`cusip`,`crd`,`orcid`]),pe=f({createdAt:s({offset:!0}),id:o(),identifier:e(),idType:fe,owner:d,source:e().nullish(),updatedAt:s({offset:!0})}),me=f({core:M,enrichment:D,fundraiseRound:a(R),newsArticle:a(Y),person:a(de),publicUrl:e().nullish(),relationship:a(V),research:J,sitemap:j,uniqueId:a(pe)});export{me as EntityDetailSchema};
@@ -0,0 +1 @@
1
+ import{a as e}from"./auth-B_0cUOPk.js";import{C as t,T as n,_ as r,a as i,b as ee,c as a,d as te,g as o,h as s,k as ne,l as c,o as re,p as ie,u as ae,v as l,w as u,x as d,y as f}from"./person-owner-BqBLyw4S.js";var oe=l({clerkPublishableKey:t().nullish(),oauthClient:e.nullish()}),se=`2025-11-25`,ce=`2025-03-26`,le=[se,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],ue=`io.modelcontextprotocol/related-task`,p=ae(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),de=u([t(),r().int()]),fe=t();o({ttl:r().optional(),pollInterval:r().optional()});var pe=l({ttl:r().optional()}),me=l({taskId:t()}),m=o({progressToken:de.optional(),[ue]:me.optional()}),h=l({_meta:m.optional()}),g=h.extend({task:pe.optional()}),he=e=>g.safeParse(e).success,_=l({method:t(),params:h.loose().optional()}),v=l({_meta:m.optional()}),y=l({method:t(),params:v.loose().optional()}),b=o({_meta:m.optional()}),x=u([t(),r().int()]),ge=l({jsonrpc:s(`2.0`),id:x,..._.shape}).strict(),_e=e=>ge.safeParse(e).success,ve=l({jsonrpc:s(`2.0`),...y.shape}).strict(),ye=e=>ve.safeParse(e).success,S=l({jsonrpc:s(`2.0`),id:x,result:b}).strict(),be=e=>S.safeParse(e).success,C;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(C||={});var w=l({jsonrpc:s(`2.0`),id:x.optional(),error:l({code:r().int(),message:t(),data:n().optional()})}).strict(),xe=e=>w.safeParse(e).success,Se=u([ge,ve,S,w]);u([S,w]);var T=b.strict(),Ce=v.extend({requestId:x.optional(),reason:t().optional()}),E=y.extend({method:s(`notifications/cancelled`),params:Ce}),we=l({src:t(),mimeType:t().optional(),sizes:a(t()).optional(),theme:i([`light`,`dark`]).optional()}),D=l({icons:a(we).optional()}),O=l({name:t(),title:t().optional()}),Te=O.extend({...O.shape,...D.shape,version:t(),websiteUrl:t().optional(),description:t().optional()}),Ee=ie(l({applyDefaults:c().optional()}),d(t(),n())),De=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ie(l({form:Ee.optional(),url:p.optional()}),d(t(),n()).optional())),Oe=o({list:p.optional(),cancel:p.optional(),requests:o({sampling:o({createMessage:p.optional()}).optional(),elicitation:o({create:p.optional()}).optional()}).optional()}),ke=o({list:p.optional(),cancel:p.optional(),requests:o({tools:o({call:p.optional()}).optional()}).optional()}),Ae=l({experimental:d(t(),p).optional(),sampling:l({context:p.optional(),tools:p.optional()}).optional(),elicitation:De.optional(),roots:l({listChanged:c().optional()}).optional(),tasks:Oe.optional(),extensions:d(t(),p).optional()}),je=h.extend({protocolVersion:t(),capabilities:Ae,clientInfo:Te}),k=_.extend({method:s(`initialize`),params:je}),Me=e=>k.safeParse(e).success,Ne=l({experimental:d(t(),p).optional(),logging:p.optional(),completions:p.optional(),prompts:l({listChanged:c().optional()}).optional(),resources:l({subscribe:c().optional(),listChanged:c().optional()}).optional(),tools:l({listChanged:c().optional()}).optional(),tasks:ke.optional(),extensions:d(t(),p).optional()}),Pe=b.extend({protocolVersion:t(),capabilities:Ne,serverInfo:Te,instructions:t().optional()}),Fe=y.extend({method:s(`notifications/initialized`),params:v.optional()}),A=_.extend({method:s(`ping`),params:h.optional()}),Ie=l({progress:r(),total:f(r()),message:f(t())}),Le=l({...v.shape,...Ie.shape,progressToken:de}),j=y.extend({method:s(`notifications/progress`),params:Le}),Re=h.extend({cursor:fe.optional()}),M=_.extend({params:Re.optional()}),N=b.extend({nextCursor:fe.optional()}),ze=i([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P=l({taskId:t(),status:ze,ttl:u([r(),re()]),createdAt:t(),lastUpdatedAt:t(),pollInterval:f(r()),statusMessage:f(t())}),F=b.extend({task:P}),Be=v.merge(P),I=y.extend({method:s(`notifications/tasks/status`),params:Be}),L=_.extend({method:s(`tasks/get`),params:h.extend({taskId:t()})}),R=b.merge(P),z=_.extend({method:s(`tasks/result`),params:h.extend({taskId:t()})});b.loose();var B=M.extend({method:s(`tasks/list`)}),V=N.extend({tasks:a(P)}),H=_.extend({method:s(`tasks/cancel`),params:h.extend({taskId:t()})}),Ve=b.merge(P),He=l({uri:t(),mimeType:f(t()),_meta:d(t(),n()).optional()}),Ue=He.extend({text:t()}),U=t().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),We=He.extend({blob:U}),W=i([`user`,`assistant`]),G=l({audience:a(W).optional(),priority:r().min(0).max(1).optional(),lastModified:ne({offset:!0}).optional()}),Ge=l({...O.shape,...D.shape,uri:t(),description:f(t()),mimeType:f(t()),size:f(r()),annotations:G.optional(),_meta:f(o({}))}),Ke=l({...O.shape,...D.shape,uriTemplate:t(),description:f(t()),mimeType:f(t()),annotations:G.optional(),_meta:f(o({}))}),qe=M.extend({method:s(`resources/list`)}),Je=N.extend({resources:a(Ge)}),Ye=M.extend({method:s(`resources/templates/list`)}),Xe=N.extend({resourceTemplates:a(Ke)}),K=h.extend({uri:t()}),Ze=K,Qe=_.extend({method:s(`resources/read`),params:Ze}),$e=b.extend({contents:a(u([Ue,We]))}),et=y.extend({method:s(`notifications/resources/list_changed`),params:v.optional()}),tt=K,nt=_.extend({method:s(`resources/subscribe`),params:tt}),rt=K,it=_.extend({method:s(`resources/unsubscribe`),params:rt}),at=v.extend({uri:t()}),ot=y.extend({method:s(`notifications/resources/updated`),params:at}),st=l({name:t(),description:f(t()),required:f(c())}),ct=l({...O.shape,...D.shape,description:f(t()),arguments:f(a(st)),_meta:f(o({}))}),lt=M.extend({method:s(`prompts/list`)}),ut=N.extend({prompts:a(ct)}),dt=h.extend({name:t(),arguments:d(t(),t()).optional()}),ft=_.extend({method:s(`prompts/get`),params:dt}),q=l({type:s(`text`),text:t(),annotations:G.optional(),_meta:d(t(),n()).optional()}),J=l({type:s(`image`),data:U,mimeType:t(),annotations:G.optional(),_meta:d(t(),n()).optional()}),Y=l({type:s(`audio`),data:U,mimeType:t(),annotations:G.optional(),_meta:d(t(),n()).optional()}),pt=l({type:s(`tool_use`),name:t(),id:t(),input:d(t(),n()),_meta:d(t(),n()).optional()}),mt=l({type:s(`resource`),resource:u([Ue,We]),annotations:G.optional(),_meta:d(t(),n()).optional()}),ht=Ge.extend({type:s(`resource_link`)}),X=u([q,J,Y,ht,mt]),gt=l({role:W,content:X}),_t=b.extend({description:t().optional(),messages:a(gt)}),vt=y.extend({method:s(`notifications/prompts/list_changed`),params:v.optional()}),yt=l({title:t().optional(),readOnlyHint:c().optional(),destructiveHint:c().optional(),idempotentHint:c().optional(),openWorldHint:c().optional()}),bt=l({taskSupport:i([`required`,`optional`,`forbidden`]).optional()}),xt=l({...O.shape,...D.shape,description:t().optional(),inputSchema:l({type:s(`object`),properties:d(t(),p).optional(),required:a(t()).optional()}).catchall(n()),outputSchema:l({type:s(`object`),properties:d(t(),p).optional(),required:a(t()).optional()}).catchall(n()).optional(),annotations:yt.optional(),execution:bt.optional(),_meta:d(t(),n()).optional()}),St=M.extend({method:s(`tools/list`)}),Ct=N.extend({tools:a(xt)}),Z=b.extend({content:a(X).default([]),structuredContent:d(t(),n()).optional(),isError:c().optional()});Z.or(b.extend({toolResult:n()}));var wt=g.extend({name:t(),arguments:d(t(),n()).optional()}),Tt=_.extend({method:s(`tools/call`),params:wt}),Et=y.extend({method:s(`notifications/tools/list_changed`),params:v.optional()});l({autoRefresh:c().default(!0),debounceMs:r().int().nonnegative().default(300)});var Q=i([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Dt=h.extend({level:Q}),Ot=_.extend({method:s(`logging/setLevel`),params:Dt}),kt=v.extend({level:Q,logger:t().optional(),data:n()}),At=y.extend({method:s(`notifications/message`),params:kt}),jt=l({name:t().optional()}),Mt=l({hints:a(jt).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),Nt=l({mode:i([`auto`,`required`,`none`]).optional()}),Pt=l({type:s(`tool_result`),toolUseId:t().describe(`The unique identifier for the corresponding tool call.`),content:a(X).default([]),structuredContent:l({}).loose().optional(),isError:c().optional(),_meta:d(t(),n()).optional()}),Ft=te(`type`,[q,J,Y]),$=te(`type`,[q,J,Y,pt,Pt]),It=l({role:W,content:u([$,a($)]),_meta:d(t(),n()).optional()}),Lt=g.extend({messages:a(It),modelPreferences:Mt.optional(),systemPrompt:t().optional(),includeContext:i([`none`,`thisServer`,`allServers`]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:a(t()).optional(),metadata:p.optional(),tools:a(xt).optional(),toolChoice:Nt.optional()}),Rt=_.extend({method:s(`sampling/createMessage`),params:Lt}),zt=b.extend({model:t(),stopReason:f(i([`endTurn`,`stopSequence`,`maxTokens`]).or(t())),role:W,content:Ft}),Bt=b.extend({model:t(),stopReason:f(i([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(t())),role:W,content:u([$,a($)])}),Vt=l({type:s(`boolean`),title:t().optional(),description:t().optional(),default:c().optional()}),Ht=l({type:s(`string`),title:t().optional(),description:t().optional(),minLength:r().optional(),maxLength:r().optional(),format:i([`email`,`uri`,`date`,`date-time`]).optional(),default:t().optional()}),Ut=l({type:i([`number`,`integer`]),title:t().optional(),description:t().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),Wt=l({type:s(`string`),title:t().optional(),description:t().optional(),enum:a(t()),default:t().optional()}),Gt=l({type:s(`string`),title:t().optional(),description:t().optional(),oneOf:a(l({const:t(),title:t()})),default:t().optional()}),Kt=l({type:s(`string`),title:t().optional(),description:t().optional(),enum:a(t()),enumNames:a(t()).optional(),default:t().optional()}),qt=u([Wt,Gt]),Jt=l({type:s(`array`),title:t().optional(),description:t().optional(),minItems:r().optional(),maxItems:r().optional(),items:l({type:s(`string`),enum:a(t())}),default:a(t()).optional()}),Yt=l({type:s(`array`),title:t().optional(),description:t().optional(),minItems:r().optional(),maxItems:r().optional(),items:l({anyOf:a(l({const:t(),title:t()}))}),default:a(t()).optional()}),Xt=u([Jt,Yt]),Zt=u([Kt,qt,Xt]),Qt=u([Zt,Vt,Ht,Ut]),$t=g.extend({mode:s(`form`).optional(),message:t(),requestedSchema:l({type:s(`object`),properties:d(t(),Qt),required:a(t()).optional()})}),en=g.extend({mode:s(`url`),message:t(),elicitationId:t(),url:t().url()}),tn=u([$t,en]),nn=_.extend({method:s(`elicitation/create`),params:tn}),rn=v.extend({elicitationId:t()}),an=y.extend({method:s(`notifications/elicitation/complete`),params:rn}),on=b.extend({action:i([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,d(t(),u([t(),r(),c(),a(t())])).optional())}),sn=l({type:s(`ref/resource`),uri:t()}),cn=l({type:s(`ref/prompt`),name:t()}),ln=h.extend({ref:u([cn,sn]),argument:l({name:t(),value:t()}),context:l({arguments:d(t(),t()).optional()}).optional()}),un=_.extend({method:s(`completion/complete`),params:ln});function dn(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function fn(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var pn=b.extend({completion:o({values:a(t()).max(100),total:f(r().int()),hasMore:f(c())})}),mn=l({uri:t().startsWith(`file://`),name:t().optional(),_meta:d(t(),n()).optional()}),hn=_.extend({method:s(`roots/list`),params:h.optional()}),gn=b.extend({roots:a(mn)}),_n=y.extend({method:s(`notifications/roots/list_changed`),params:v.optional()});u([A,k,un,Ot,ft,lt,qe,Ye,Qe,nt,it,Tt,St,L,z,B,H]),u([E,j,Fe,_n,I]),u([T,zt,Bt,on,gn,R,V,F]),u([A,Rt,nn,hn,L,z,B,H]),u([E,j,At,ot,et,Et,vt,I,an]),u([T,Pe,pn,_t,ut,Je,Xe,$e,Z,Ct,R,V,F]);var vn=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===C.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new yn(e.elicitations,n)}return new e(t,n,r)}},yn=class extends vn{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(C.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},bn=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function xn(e){return(await bn).getRandomValues(new Uint8Array(e))}async function Sn(e){let t=``;for(;t.length<e;){let n=await xn(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Cn(e){return await Sn(e)}async function wn(e){let t=await(await bn).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function Tn(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Cn(e);return{code_verifier:t,code_challenge:await wn(t)}}export{Q as A,fn as B,lt as C,B as D,gn as E,Qe as F,be as G,xe as H,le as I,he as K,Ot as L,A as M,j as N,V as O,ue as P,I as R,se as S,qe as T,ye as U,Me as V,_e as W,L as _,Ve as a,Fe as b,zt as c,ce as d,on as f,z as g,ft as h,H as i,vn as j,St as k,Bt as l,C as m,Tt as n,E as o,T as p,oe as q,Z as r,un as s,Tn as t,F as u,R as v,Ye as w,Se as x,k as y,dn as z};
@@ -0,0 +1,4 @@
1
+ import{B as e,J as t,L as n,N as r,S as i,Y as a,_ as o,a as s,d as c,et as l,o as u,r as d}from"./auth-B_0cUOPk.js";import{C as f,a as p,c as m,k as h,v as ee}from"./person-owner-BqBLyw4S.js";import{execFile as te}from"node:child_process";import{dirname as g,join as _}from"node:path";import{chmod as ne,mkdir as re,readFile as ie,rename as ae,rm as v,stat as oe,writeFile as y}from"node:fs/promises";import{randomUUID as b}from"node:crypto";import{AsyncLocalStorage as se}from"node:async_hooks";import{homedir as x,platform as S}from"node:os";import{setTimeout as ce}from"node:timers/promises";function C(e,t=[]){let n=e instanceof Error?e.message:String(e);return o(n,t)}function le(e,t=[]){let n=o(e.title,t),r=o(e.detail?.trim()??``,t);return`${e.status} ${n}${r?` — ${r}`:``}`}function ue(){if(S()===`win32`){let e=process.env.APPDATA??_(x(),`AppData`,`Roaming`);return _(e,`aventure`,`config.json`)}let e=process.env.XDG_CONFIG_HOME??_(x(),`.config`);return _(e,`aventure`,`config.json`)}function de(){let e=process.env[a.authToken];return typeof e==`string`&&e.length>0?{present:!0,source:`env`}:{present:!1,source:null}}function w(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function T(e){let t=e.trim();if(t.length===0)throw Error(`API host must not be blank`);let n=new URL(me(t)?t:`${he(t)}://${t}`),r=E(n.hostname);if(n.protocol!==`https:`&&n.protocol!==`http:`||n.username.length>0||n.password.length>0||n.pathname!==`/`&&n.pathname!==``||n.search.length>0||n.hash.length>0)throw Error(`API host must contain only an HTTP(S) host and optional port`);if(n.protocol===`http:`&&!r)throw Error(`stored credentials require HTTPS except for loopback API hosts`);return{host:n.host.toLowerCase(),origin:n.origin,isLoopback:r}}function fe(e){return{...e,host:T(e.host).origin}}function pe(e){let t=T(e);if(t.isLoopback)return`http://localhost:3000`;if(t.host===`api.aventure.vc`)return`https://aventure.vc`;throw Error(`no first-party browser origin is configured for API host ${t.host}`)}function me(e){return/^[a-z][a-z\d+.-]*:\/\//iu.test(e)}function he(e){let t=e.split(`/`,1)[0]?.toLowerCase()??``;try{return E(new URL(`http://${t}`).hostname)?`http`:`https`}catch{return`https`}}function E(e){let t=e.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`0.0.0.0`||t===`[::1]`}var ge=2;function _e(e,t){return D(e,t).redactedUrl}async function ve(e,t,n){let r=D(e,t);return await ye(new URL(r.openerUrl),n)}async function ye(e,t){let n=t.environment??process.env,r=t.operatingSystem??S(),i=O(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=be(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await xe(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function D(e,t){let{id:n,verificationUrl:r,pollSecret:i}=e,a,o;try{a=new URL(r),o=new URL(t)}catch{throw Error(`broker returned an invalid browser verification URL`)}if(o.username.length>0||o.password.length>0||o.pathname!==`/`||o.search.length>0||o.hash.length>0)throw Error(`configured browser origin must contain only an origin`);let s=E(o.hostname);if(o.protocol!==`https:`&&!(o.protocol===`http:`&&s))throw Error(`configured browser origin must use HTTPS except for loopback development`);let c=new URLSearchParams(a.hash.slice(1)),l=[...c.keys()],u=c.getAll(`cliAuthorizationId`),d=c.getAll(`browserSecret`),f=d[0]??``;if(a.origin!==o.origin||a.protocol!==o.protocol||a.username.length>0||a.password.length>0||a.pathname!==`/settings/developer`||a.search.length>0||l.length!==ge||u.length!==1||u[0]!==n||d.length!==1||f.length===0||i.length===0||f===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let p;try{p=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||p.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m=new URL(a);return m.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:m.toString()}}function O(e,t,n){return e?`--no-browser was set`:n===`darwin`&&t.CODEX_SESSION_ID?`macOS Codex browser process boundary`:t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY?`SSH/headless session detected`:(n===`linux`||n===`freebsd`)&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?`no graphical display detected`:null}function be(e,t){return e===`darwin`?{command:`open`,arguments:[t]}:e===`win32`?{command:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,t]}:e===`linux`||e===`freebsd`?{command:`xdg-open`,arguments:[t]}:null}function xe(e,t){return new Promise((n,r)=>{te(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var Se=100,Ce=3e4,we=6e4,k=new se;function A(){return _(g(ue()),`credentials.json`)}function Te(e){return`OS keyring is unusable (${e}); the credential will be stored in ${A()} (mode 0600).\n`}async function j(e,t){let n;try{let n=await(await I(e,t)).getPassword()??void 0;if(n!==void 0)return{record:{provider:`keyring`,value:n}}}catch(e){n=F(e)}let r=(await L())[e]?.[t];return{...r===void 0?{}:{record:{provider:`file`,value:r}},...n===void 0?{}:{keyringFailure:n}}}async function M(e,t,n){let r;try{let i=await I(e,t);if(await i.setPassword(n),await i.getPassword()===n)return await z(e,t,void 0),`keyring`;r=`Error: keyring readback did not match`}catch(e){r=F(e,[n])}if(await z(e,t,n),(await L())[e]?.[t]!==n)throw Error(`credential storage did not confirm a durable write (keyring: ${r}; file: readback did not match)`);return`file`}async function N(e,t){try{let n=await I(e,t),r;try{await n.deleteCredential()}catch(e){r=e}let i;try{i=await n.getPassword()??void 0}catch(e){throw Error(`OS keyring removal outcome is unknown (${F(r??e)})`,{cause:e})}if(i!==void 0)throw Error(`OS keyring did not confirm removal (${F(r)})`,r===void 0?void 0:{cause:r})}finally{await z(e,t,void 0)}}async function P(e,t){let n=`${t}:probe:${b()}`,r=`aventure-cli-credential-probe:${b()}`,i;try{let t=await I(e,n);await t.setPassword(r);let a=await(await I(e,n)).getPassword(),o=await t.deleteCredential(),s=await(await I(e,n)).getPassword()??void 0;if(a!==r)i=`Error: probe readback did not match`;else if(!o||s!==void 0)i=`Error: probe cleanup was not confirmed`;else return{provider:`keyring`}}catch(e){i=F(e,[r])}try{await R(async()=>{await z(e,n,r);let t=(await L())[e]?.[n];if(await z(e,n,void 0),t!==r)throw Error(`probe readback did not match`)})}catch(e){throw Error(`credential storage is unavailable (keyring: ${i}; file ${A()}: ${F(e,[r])})`,{cause:e})}return{provider:`file`,keyringFailure:i}}function F(e,t=[]){if(!(e instanceof Error))return`Error`;let n=e.name||`Error`,[r=``]=C(e,t).trim().split(`
2
+ `,1);return r&&r!==n?`${n}: ${r}`:n}async function I(e,t){let n=S(),r=n===`linux`||n===`freebsd`?O(!1,process.env,n):null;if(r!==null)throw Error(`OS keyring unlock prompt is unreachable (${r})`);let{AsyncEntry:i}=await import(`@napi-rs/keyring`);return new i(e,t)}async function L(){let e=A(),t;try{t=await ie(e,`utf8`)}catch(e){if(w(e,`ENOENT`))return{};throw e}let n;try{n=JSON.parse(t)}catch(t){return await Ee(e,t)}return Oe(n)?n:await Ee(e,void 0)}async function Ee(t,n){let r=`${t}.corrupt-${new Date().toISOString().replace(/[:.]/gu,`-`)}`;try{await ae(t,r)}catch(e){if(w(e,`ENOENT`))return{};throw Error(`${t} is not a valid credential file and could not be moved aside`,{cause:e})}return e({component:`aventure-cli`,event:`credential_file_quarantined`,message:`${t} is not a valid credential file; moved it to ${r} and continuing with an empty file store`,...n===void 0?{}:{error:n}}),{}}async function R(e){if(k.getStore()===!0)return await e();let t=`${A()}.lock`;await re(g(t),{recursive:!0,mode:448});let n=Date.now()+Ce,r=b();for(;;){try{await y(t,r,{flag:`wx`,mode:384});break}catch(e){if(!w(e,`EEXIST`))throw e}if(await oe(t).then(e=>Date.now()-e.mtimeMs,()=>0)>we)await v(t,{force:!0});else if(Date.now()>n)throw Error(`credential store is locked by another CLI process (${t})`);else await ce(Se)}try{return await k.run(!0,e)}finally{await ie(t,`utf8`).catch(()=>``)===r&&await v(t,{force:!0})}}async function z(e,t,n){await R(async()=>await De(e,t,n))}async function De(e,t,n){let r=A(),i=await L(),a={...i[e]};if(n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,Object.keys(i).length===0){await v(r,{force:!0});return}await re(g(r),{recursive:!0,mode:448});let o=`${r}.${b()}.tmp`;await y(o,`${JSON.stringify(i,null,2)}\n`,{mode:384}),await ne(o,384),await ae(o,r)}function Oe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`))}var ke=ee({createdAt:h({offset:!0}),description:f().nullish(),expiresAt:h({offset:!0}).nullish(),id:f().regex(/^ak_[0-9A-Fa-f]{32}$/),lastUsedAt:h({offset:!0}).nullish(),name:f(),revocationReason:f().nullish(),scopes:m(f()),status:p([`ACTIVE`,`REVOKED`,`EXPIRED`]),subject:f(),updatedAt:h({offset:!0})}),B=`vc.aventure.aventure-cli`,V=`aventure-cli-personal-v1`;async function Ae(e,t,n){let r=U(e),i=Pe(t,n),a;try{a=await M(B,r,i)}catch(e){throw Error(`${C(e,[i,t.secret])}; broker acknowledgment was withheld. Re-run auth status before retrying.`,{cause:e})}return{host:r,provider:a,activation:n,credential:t}}async function H(e){let t=U(e),n;try{n=await j(B,t)}catch(e){return Ne(C(e))}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,...Fe(r.value)}}}async function je(e){let t=await H(e);if(t.state!==`missing`)return t;try{let{keyringFailure:t}=await P(B,U(e));return t===void 0?{state:`missing`}:{state:`missing`,keyringFailure:t}}catch(e){return Ne(C(e))}}async function Me(e){await N(B,U(e))}function U(e){return T(e).host}function Ne(e){return{state:`unavailable`,summary:e,cause:`storage`}}function Pe(e,t){return`${V}:${t}\n${JSON.stringify(e.apiKey)}\n${e.secret}`}function Fe(e){let t=e.indexOf(`
3
+ `),n=t<0?-1:e.indexOf(`
4
+ `,t+1),r=t<0?e:e.slice(0,t),i=r===`${V}:active`?`active`:`pending`;if(t<0||n<0||r!==`${V}:pending`&&r!==`${V}:active`)throw Error(`OS credential entry has an unsupported format`);let a=e.slice(n+1);if(a.length===0)throw Error(`OS credential entry has an empty secret`);let o;try{o=JSON.parse(e.slice(t+1,n))}catch(e){throw Error(`OS credential entry failed canonical schema validation`,{cause:e})}let s=ke.safeParse(o);if(!s.success)throw Error(`OS credential entry failed canonical schema validation`,{cause:s.error});return{activation:i,credential:{apiKey:s.data,secret:a}}}async function Ie(t){if(Le())return;let r=U(l().host);try{let e=await H(r);if(e.state===`unavailable`){n(Re(`keyring`,Error(e.summary)));return}e.state===`found`&&e.stored.activation===`active`&&!Le()&&(process.env[a.authToken]=e.stored.credential.secret,t?.(`api-key`))}catch(t){e(Re(`parse`,t))}}function Le(){return(process.env[a.authToken]?.trim().length??0)>0}function Re(e,t){return{component:`aventure-cli`,event:`api_key_materialization_unavailable`,message:`saved API key could not be loaded; continuing with environment auth`,fields:{source:e},error:t}}var ze=s.omit({mcpResource:!0}),W=`vc.aventure.aventure-cli.oauth`,Be=`oauth:`,Ve=6e4;function He(e,t){let n=Z(t);return{client:e,expiresAt:ot(at(n)),tokens:n}}async function Ue(e,t){let n=q(e),r=et(n,t),i;try{i=await M(W,X(n),r)}catch(e){throw Error(`OAuth credential could not be stored — ${C(e,[r,...Y(t.tokens)])}`,{cause:e})}return{host:n,provider:i,credential:tt(n,r)}}async function G(e){let t=q(e),n;try{n=await j(W,X(t))}catch(e){return{state:`unavailable`,summary:C(e)}}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,credential:tt(t,r.value)}}}async function We(e){await N(W,X(q(e)))}async function Ge(e){try{return await G(e)}catch(e){return{state:`invalid`,summary:C(e)}}}async function Ke(e){let t=await Ge(e);if(t.state!==`missing`)return t;let n=await qe(e);return n.state===`unavailable`?n:n.keyringFailure===void 0?{state:`missing`}:{state:`missing`,keyringFailure:n.keyringFailure}}async function qe(e){let t=q(e);try{return{state:`available`,...await P(W,X(t))}}catch(e){return{state:`unavailable`,summary:C(e)}}}function Je(e){return K(e.authorizationServer,`authorization server`)}function Ye(e){return K(e.resource,`resource`)}function Xe(e){if(e.clientId.trim()!==e.clientId||e.clientId.length===0)throw Error(`OAuth client ID must not be blank`);return e.clientId}function Ze(e){if(e.scope.length===0||e.scope.some(e=>e.trim()!==e||e.length===0)||new Set(e.scope).size!==e.scope.length)throw Error(`OAuth scope must contain unique non-blank values`);return e.scope}function K(e,t,n=!1){let r;try{r=new URL(e)}catch(e){throw Error(`OAuth ${t} is not a valid URL`,{cause:e})}if(r.protocol!==`https:`||r.username.length>0||r.password.length>0||!n&&r.search.length>0||r.hash.length>0)throw Error(`OAuth ${t} must be an HTTPS URL without credentials${n?``:`, query`} or fragment`);return r}function q(e){return T(e).host}function J(e){return new Date(e.expiresAt).getTime()-Ve<=Date.now()}function Qe(e){let t=$e(e.tokens.id_token)??$e(e.tokens.access_token),n=t?.email;return{subject:t?.sub??null,email:typeof n==`string`?n:null}}function $e(e){if(e!==void 0)try{return i(e)}catch{return}}function Y(e){return[e.access_token,e.refresh_token,e.id_token]}function X(e){return`${Be}${e}`}function et(e,t){return JSON.stringify({client:nt(e,t.client),expiresAt:st(t.expiresAt),tokens:Z(t.tokens)})}function tt(e,t){let n;try{n=JSON.parse(t)}catch(e){throw Error(`OS OAuth credential entry failed schema validation`,{cause:e})}if(!lt(n))throw Error(`OS OAuth credential entry failed schema validation`);return{client:nt(e,rt(n.client)),expiresAt:st(n.expiresAt),tokens:Z(it(n.tokens))}}function nt(e,t){if(q(t.resource)!==e)throw Error(`OAuth client resource must match the credential API host`);return t}function rt(e){let t=ze.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed canonical client validation`,{cause:t.error});return t.data}function it(e){let t=d.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed OAuth token validation`,{cause:t.error});return t.data}function Z(e){if(!ct(e.access_token)||e.token_type.trim().toLowerCase()!==`bearer`)throw Error(`OAuth token response must contain a bearer access token`);if(e.refresh_token!==void 0&&!ct(e.refresh_token))throw Error(`OAuth token response has an invalid refresh token`);return at(e),e}function at(e){let t=e.expires_in;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw Error(`OAuth token response must contain a positive expires_in`);return t}function ot(e){let t=new Date(Date.now()+e*1e3);if(!Number.isFinite(t.getTime()))throw Error(`OAuth token response has an expiry outside the supported date range`);return t.toISOString()}function st(e){if(typeof e!=`string`)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);return e}function ct(e){return e.trim()===e&&e.length>0}function lt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ut(t,n){if($())return;let i=async(r,i,a)=>{if(await Ie(n),!$())throw i instanceof u?i:ft(r,t,i,a);e({component:`aventure-cli`,event:`oauth_credential_bypassed`,message:`OAuth sign-in is unavailable (${r}); using the stored API key.`,...i===void 0?{}:{error:Error(C(i,Q(a)))}})},o=async(t,n,r)=>{let a=await G(t.host).catch(()=>void 0);if(a?.state===`found`&&a.stored.credential.tokens.access_token!==t.credential.tokens.access_token)return await s(a.stored,!1);try{await We(t.host)}catch(r){e({component:`aventure-cli`,event:`oauth_credential_retire_failed`,message:`the saved OAuth credential is dead (${n}) but could not be removed`,error:Error(C(r,Q(t)))})}await i(n,r,t)},s=async(e,t)=>{let s=(n,r)=>t?o(e,n,r):i(n,r,e),l=e.credential;if(J(l)){if(l.tokens.refresh_token===void 0)return await s(`the saved OAuth credential has expired`);try{l=await dt(e)}catch(t){return t instanceof r?await s(`Clerk rejected the saved refresh token`,t):await i(`the saved OAuth credential could not be renewed`,t,e)}}let u;try{u=await c(l.tokens.access_token,new URL(l.client.resource))!==null}catch(t){return await i(`the saved OAuth credential could not be verified`,t,e)}if(!u)return await s(`the saved OAuth credential was rejected`);$()||(process.env[a.authToken]=l.tokens.access_token,n?.(`oauth`))},d;try{d=q(l().host)}catch(e){throw ft(`the API host could not select its OAuth credential`,t,e)}let f;try{f=await G(d)}catch(e){return await i(`the saved OAuth credential is invalid or expired`,e)}if(f.state!==`missing`){if(f.state===`unavailable`)return await i(`the saved OAuth credential could not be read`,Error(f.summary));await s(f.stored,!0)}}async function dt(t){return await R(async()=>{let n=await G(t.host),r=n.state===`found`?n.stored:t;if(!J(r.credential))return r.credential;let{renewOAuthTokens:i}=await import(`./oauth-login-C3Cr4IJb.js`),a=He(r.credential.client,await i(r));try{await Ue(t.host,a)}catch(t){e({component:`aventure-cli`,event:`oauth_credential_store_failed`,message:`renewed OAuth credential could not be stored; this command uses it and the next one falls back to the API key or sign-in`,error:Error(C(t,Y(a.tokens)))})}return a})}function Q(e){return e===void 0?[]:Y(e.credential.tokens)}function $(){return(process.env[a.authToken]?.trim().length??0)>0}function ft(e,n,r,i){let a=r===void 0?``:` — ${C(r,Q(i))}`,o=n??t().bin[0];return Error(`OAuth sign-in is required: ${e}. Run \`${o} auth login\` before retrying.${a}`)}export{fe as A,Ae as C,ve as D,ye as E,C as M,le as N,_e as O,H as S,Te as T,Ue as _,We as a,Me as b,J as c,Qe as d,Ye as f,K as g,qe as h,He as i,de as j,pe as k,Je as l,Y as m,dt as n,Ge as o,Ze as p,q as r,Ke as s,ut as t,Xe as u,Ie as v,ke as w,je as x,U as y};
@@ -0,0 +1 @@
1
+ import{i as e}from"./oauth-login-qlqzOJeW.js";export{e as renewOAuthTokens};
@@ -0,0 +1,6 @@
1
+ import{C as e,F as t,P as n,d as r,et as i,i as a,it as o,n as s,p as c,r as l,rt as u,s as ee,t as d}from"./auth-B_0cUOPk.js";import{A as te,E as f,M as p,N as ne,T as re,_ as m,c as h,f as g,g as _,h as v,i as ie,l as y,m as b,n as x,o as S,p as C,r as ae,u as w}from"./oauth-bearer-credential-C-EZmWvX.js";import{S as oe,q as se,t as ce}from"./index.node-Dqukns1W.js";import{once as le}from"node:events";import{stderr as T}from"node:process";import{createServer as ue}from"node:http";import{randomBytes as de,timingSafeEqual as fe}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";function me(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var E=`code`,D=`S256`;function O(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&me(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function k(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:A(i,a,n);return;case`client_secret_post`:j(i,a,r);return;case`none`:M(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function A(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function j(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function M(e,t){t.set(`client_id`,e)}async function N(e){let r=e instanceof Response?e.status:void 0,i=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=d.parse(JSON.parse(i));return new(n[e]||t)(r||``,a)}catch(e){let n=`${r?`HTTP ${r}: `:``}Invalid OAuth error response: ${e}. Raw body: ${i}`;return new t(n)}}async function P(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?P(e,void 0,n):void 0;throw r}}function F(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function I(e,{fetchFn:t=fetch,protocolVersion:n=oe}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=F(e);for(let{url:e,type:n}of i){let i=await P(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?s.parse(await i.json()):a.parse(await i.json())}}}async function L(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(E))throw Error(`Incompatible auth server: does not support response type ${E}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(D))throw Error(`Incompatible auth server: does not support code challenge method ${D}`)}else s=new URL(`/authorize`,e);let c=await ce(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,E),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,D),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function R(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function z(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&k(O(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let u=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!u.ok)throw await N(u);return l.parse(await u.json())}async function he(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return z(e,{metadata:t,tokenRequestParams:R(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ge(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await z(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var _e=5e3,ve=500,B=`Approval poll was interrupted; retrying.
2
+ `,ye=`urn:ietf:params:oauth:grant-type:device_code`;function V(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return _(t,`device authorization endpoint`,!0)}async function be(e,t){let n=await fetch(V(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),scope:C(e).join(` `),resource:g(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return xe(await H(n,`device authorization`),Date.now())}async function H(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function xe(e,t){if(typeof e!=`object`||!e)throw Error(`device authorization response is not an object`);let n=Reflect.get(e,`device_code`),r=Reflect.get(e,`user_code`),i=Reflect.get(e,`verification_uri_complete`),a=Reflect.get(e,`verification_uri`),o=Reflect.get(e,`expires_in`),s=Reflect.get(e,`interval`);if(typeof n!=`string`||typeof r!=`string`||n.length===0||r.length===0)throw Error(`device authorization response lacks device_code or user_code`);let c=typeof i==`string`&&i.length>0?i:a;if(typeof c!=`string`)throw Error(`device authorization response lacks a verification URI`);if(typeof o!=`number`||o<=0)throw Error(`device authorization response lacks a positive expires_in`);return{deviceCode:n,userCode:r,verificationUri:_(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function Se(e,t,n){let r=_(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,a=null;for(;Date.now()<n.expiresAt;){await pe(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),grant_type:ye,device_code:n.deviceCode})})}catch(e){a=`the token endpoint was unreachable — ${p(e)}`,T.write(B);continue}if(t.status>=ve){await t.body?.cancel(),a=`the token endpoint answered ${t.status}`,T.write(B);continue}a=null;let o=await H(t,`token`);if(t.ok){let e=l.safeParse(o);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let s=d.safeParse(o),c=s.success?s.data.error:`HTTP ${t.status}`;if(c!==`authorization_pending`){if(c===`slow_down`){i+=_e;continue}throw Error(c===`access_denied`?`the sign-in was denied in the browser`:c===`expired_token`?`the device code expired before approval`:`token endpoint answered ${c}`)}}throw Error(a===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${a}`)}var Ce=3e5;function we(e){let t;try{t=new URL(e.redirectUri)}catch(e){throw Error(`OAuth callback configuration is not a valid URL`,{cause:e})}if(t.protocol!==`http:`||t.hostname!==`127.0.0.1`||t.port.length>0||t.pathname!==`/callback`||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0)throw Error(`OAuth callback configuration must be http://127.0.0.1/callback without a port, query, or fragment`);return t}async function Te(e,t){let n,r=new Promise(e=>{n=e}),i=ue((r,i)=>{i.setHeader(`Cache-Control`,`no-store`),i.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let a=new URL(r.url??`/`,e);if(r.method!==`GET`||a.pathname!==e.pathname){i.statusCode=404,i.end(`OAuth callback not found.`);return}let o=a.searchParams.getAll(`state`),s=Buffer.from(o[0]??``),c=Buffer.from(t);if(o.length!==1||s.length!==c.length||!fe(s,c)){i.statusCode=400,i.end(`OAuth callback state did not match. Return to the CLI and retry.`);return}if(a.searchParams.has(`error`)){i.statusCode=400,i.end(`OAuth authorization was not completed. Return to the CLI.`),n({state:`failed`,message:`OAuth authorization server returned an error`});return}let l=a.searchParams.getAll(`code`),u=l[0]?.trim();if(l.length!==1||u===void 0||u.length===0){i.statusCode=400,i.end(`OAuth callback did not include an authorization code.`);return}i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u})});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${p(e)}`}));try{let t=le(i,`listening`);i.listen({host:`127.0.0.1`,port:0}),await t;let n=i.address();if(n===null||typeof n==`string`||n.port<=0)throw Error(`OAuth callback listener did not receive an ephemeral loopback port`);let a=new URL(e);return a.port=String(n.port),{redirectUri:a,waitForAuthorizationCode:async()=>{let e;return await Promise.race([r,new Promise(t=>{e=setTimeout(()=>t({state:`timed-out`}),Ce)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await U(i)}}catch(e){throw i.listening&&await U(i),e}}function U(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}var W=`the OAuth credential is valid, but the API refused this account (HTTP 403); signing in again will not change that`;async function Ee(t){let n;try{n=ae(i().host)}catch(e){return u(`auth login: invalid API host — ${p(e)}`)}let a=await S(n);if(a.state===`missing`)return G(n,t);if(a.state===`unavailable`)return u(`auth login: ${a.summary}`);if(a.state===`invalid`)return G(n,t,`Saved OAuth credential cannot be read — ${a.summary}`);let{stored:s}=a;if(h(s.credential))return await De(s,t);let c;try{c=await r(s.credential.tokens.access_token,g(s.credential.client))}catch(r){return r instanceof e?G(n,t,`Saved OAuth credential was rejected`):u(`auth login: saved OAuth credential could not be verified — ${p(r,b(s.credential.tokens))}`)}return c===`forbidden`?u(`auth login: ${W}`):c===null?G(n,t,`Saved OAuth credential was rejected`):o(`OAuth CLI access token is already stored and verified.`,$(s))}async function De(e,t){let n=await v(e.host);if(n.state===`unavailable`)return u(`auth login: ${n.summary}`);let{tokens:r}=e.credential;if(r.refresh_token===void 0)return G(e.host,t,`Saved OAuth access token expired`,n);let i;try{i=await x(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${p(i,b(r))}`,n)}J(n);let a=await Q(e.host,i,`OAuth CLI access token renewed and verified.`);if(!a.ok)return a;let o=await Z(i);return o.state===`failed`?u(`auth login: ${o.summary}`):o.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):a}async function G(e,t,n,r){let i=r??await v(e);if(i.state===`unavailable`)return u(`auth login: ${i.summary}`);J(i),n!==void 0&&T.write(`${n}; continuing to browser sign-in.\n`);let a;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);a=e}catch(e){return u(`auth login: OAuth configuration is unavailable — ${p(e)}`)}let o;try{o=await X(a)}catch(e){return u(`auth login: OAuth authorization-server discovery failed — ${p(e)}`)}if(t.noBrowser)return await K(e,a,o);let s=de(32).toString(`base64url`),c;try{c=await Te(we(a),s);let t=await L(y(a),{metadata:o,clientInformation:{client_id:w(a)},redirectUrl:c.redirectUri,resource:g(a),scope:C(a).join(` `),state:s}),n=await f(t.authorizationUrl,{noBrowser:!1});if(n.state!==`opened`)return await c.close(),c=void 0,T.write(`Browser not opened automatically (${n.reason}).\n`),await K(e,a,o);T.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
3
+ `);let r=await c.waitForAuthorizationCode();if(r.state===`timed-out`)return await c.close(),c=void 0,T.write(`Browser sign-in was not completed; continuing with a device code.
4
+ `),await K(e,a,o);if(r.state===`failed`)return u(`auth login: ${r.message}`);let i;try{i=await he(y(a),{metadata:o,clientInformation:{client_id:w(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:c.redirectUri,resource:g(a)})}catch(e){return u(`auth login: OAuth token exchange failed — ${p(e,[r.authorizationCode,t.codeVerifier])}`)}return await q(e,a,i)}catch(e){return u(`auth login: OAuth browser authorization failed — ${p(e)}`)}finally{await c?.close()}}async function K(e,t,n){let r;try{r=await be(t,n)}catch(e){return u(`auth login: OAuth device authorization request failed — ${p(e)}`)}T.write([`Sign-in URL (works on any device): ${r.verificationUri.toString()}`,`Confirm that the page shows code ${r.userCode} before approving.`,"That page approves with the account already signed in there; to pick an account, run `auth login` on a machine with a browser.",`Waiting for approval...
5
+ `].join(`
6
+ `));let i;try{i=await Se(t,n,r)}catch(e){return u(`auth login: OAuth device authorization did not complete — ${p(e,[r.deviceCode])}`)}return await q(e,t,i)}async function q(e,t,n){let r=await ke(t,n);return r.state===`failed`?u(`auth login: ${r.summary}`):r.state===`rejected`?u(`auth login: OAuth access token was rejected and was not stored`):await Q(e,r.credential,`OAuth CLI access token stored and verified.`)}async function Oe(e){let{client:t,tokens:n}=e.credential;if(n.refresh_token===void 0)throw Error(`saved OAuth credential has no refresh token`);let r=await X(t);return await ge(y(t),{metadata:r,clientInformation:{client_id:w(t)},refreshToken:n.refresh_token,resource:g(t)})}function J(e){e.state===`available`&&e.provider===`file`&&T.write(re(e.keyringFailure??`unknown failure`))}async function Y(){let e=await c(te(i()),{method:`GET`,path:ee(`getAuthProviderCatalog`,{}),headers:{}},se);if(!e.ok)throw Error(`provider catalog request failed: ${ne(e.problem)}`);return e.data}async function X(e){let t=await I(y(e));if(t===void 0||t.issuer!==e.authorizationServer)throw Error(`OAuth authorization-server metadata issuer must match its configured server`);if(!t.response_types_supported.includes(`code`)||t.code_challenge_methods_supported?.includes(`S256`)!==!0)throw Error(`OAuth authorization-server metadata must advertise authorization-code and PKCE S256 support`);if(t.grant_types_supported?.includes(`urn:ietf:params:oauth:grant-type:device_code`)!==!0)throw Error(`OAuth authorization-server metadata must advertise the device authorization grant`);return _(t.authorization_endpoint,`authorization endpoint`,!0),V(t),_(t.token_endpoint,`token endpoint`,!0),t}async function ke(e,t){let n;try{n=ie(e,t)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${p(e,b(t))}`}}return await Z(n)}async function Z(t){let n;try{n=await r(t.tokens.access_token,g(t.client))}catch(n){return n instanceof e?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${p(n,b(t.tokens))}`}}return n===`forbidden`?{state:`failed`,summary:W}:n===null?{state:`rejected`}:{state:`accepted`,credential:t}}async function Q(e,t,n){try{let r=await m(e,t);return o(n,$(r))}catch(e){return u(`auth login: OAuth credential could not be durably stored — ${p(e,b(t.tokens))}`)}}function $(e){return{host:e.host,provider:e.provider,expiresAt:e.credential.expiresAt,client:e.credential.client}}export{Oe as i,Y as n,Ee as r,X as t};