useakit 0.2.0-dev.98 → 0.3.0-dev.115

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.
Files changed (3) hide show
  1. package/README.md +3 -17
  2. package/dist/index.mjs +109 -172
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,90 +1,90 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import{parseArgs as t,promisify as n,styleText as r}from"node:util";import i,{stdin as a,stdout as o}from"node:process";import*as s from"node:readline";import c,{createInterface as l}from"node:readline";import{ReadStream as u}from"node:tty";import{createReadStream as d,existsSync as f,statSync as p}from"node:fs";import{basename as m,delimiter as h,dirname as g,join as _,parse as v,relative as y,resolve as b,sep as x}from"node:path";import{arch as S,homedir as C,hostname as w,platform as T,tmpdir as E,userInfo as ee}from"node:os";import{access as te,appendFile as ne,chmod as re,constants as ie,copyFile as ae,lstat as oe,mkdir as D,open as se,readFile as O,readdir as ce,readlink as le,rename as ue,rm as de,stat as fe,symlink as pe,unlink as me,writeFile as k}from"node:fs/promises";import{createHash as he,randomBytes as ge,randomUUID as _e,timingSafeEqual as ve}from"node:crypto";import{execFile as ye,execFileSync as be,spawn as xe}from"node:child_process";import{fileURLToPath as Se}from"node:url";import{createServer as Ce}from"node:http";import{gunzip as we}from"node:zlib";import{setTimeout as Te}from"node:timers/promises";var A=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),Ee=/* @__PURE__ */ e(import.meta.url);const De=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Oe=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ke=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ae=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,je=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Me=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Ne=/\t{1,1000}/y,Pe=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Fe=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ie=/\p{M}+/gu,Le={limit:1/0,ellipsis:``},Re=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Re(i,Le,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Fe,l],[Ae,0],[je,o],[Ne,s],[Pe,c],[Me,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Ie,``)){let t=e.codePointAt(0)||0;if(S=Oe(t)?2:ke(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Me?De(e.slice(p,n.lastIndex)):n===Pe?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},ze={limit:1/0,ellipsis:``,ellipsisWidth:0},Be=(e,t={})=>Re(e,ze,t).width,Ve=`]8;;`,He=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ve}(?<uri>.*))`,`y`),Ue=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},We=e=>`[${e}m`,Ge=e=>`${Ve}${e}`,Ke=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Be(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Be(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ve,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!Be(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Je=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Be(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Be(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ke(s,r,t),c=Be(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ke(s,r,t),c=Be(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Ke(s,r,t),c=Be(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>qe(e)));let l=s.join(`
3
- `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){He.lastIndex=e+1;let t=He.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
4
- `){a&&(r+=Ge(``));let e=i?Ue(i):void 0;i&&e&&(r+=We(e))}else t===`
5
- `&&(i&&Ue(i)&&(r+=We(i)),a&&(r+=Ge(a)))}return r},Ye=/\r?\n/;function Xe(e,t,n){return String(e).normalize().split(Ye).map(e=>Je(e,t,n)).join(`
6
- `)}var j=(/* @__PURE__ */ A(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})))();function Ze(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a]?.disabled?Ze(a,t<0?-1:1,n):a}const M={actions:/* @__PURE__ */ new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:/* @__PURE__ */ new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,accessible:void 0,date:{monthNames:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Qe(e){if(e!==void 0)return e;if(M.accessible!==void 0)return M.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==``&&t!==`0`&&t!==`false`}function $e(e,t){if(typeof e==`string`)return M.aliases.get(e)===t;for(let n of e)if(n!==void 0&&$e(n,t))return!0;return!1}function et(e,t){if(e===t)return;let n=e.split(`
2
+ import{createRequire as e}from"node:module";import{parseArgs as t,promisify as n,styleText as r}from"node:util";import i,{stdin as a,stdout as o}from"node:process";import*as s from"node:readline";import c,{createInterface as l}from"node:readline";import{ReadStream as u}from"node:tty";import{createReadStream as d,existsSync as f,statSync as p}from"node:fs";import{basename as m,delimiter as h,dirname as g,join as _,parse as v,relative as y,resolve as b,sep as x}from"node:path";import{arch as S,homedir as C,hostname as w,platform as T}from"node:os";import{access as E,appendFile as ee,chmod as te,constants as ne,copyFile as re,lstat as ie,mkdir as D,readFile as O,readdir as k,readlink as ae,rename as oe,rm as se,stat as ce,symlink as le,unlink as ue,writeFile as A}from"node:fs/promises";import{createHash as de,randomBytes as fe,randomUUID as pe,timingSafeEqual as me}from"node:crypto";import{execFile as he,execFileSync as ge,spawn as _e}from"node:child_process";import{fileURLToPath as ve}from"node:url";import{createServer as ye}from"node:http";import{gunzip as be}from"node:zlib";import{setTimeout as xe}from"node:timers/promises";var j=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),Se=/* @__PURE__ */ e(import.meta.url);const Ce=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),we=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Te=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ee=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,De=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Oe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ke=/\t{1,1000}/y,Ae=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,je=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Me=/\p{M}+/gu,Ne={limit:1/0,ellipsis:``},Pe=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Pe(i,Ne,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[je,l],[Ee,0],[De,o],[ke,s],[Ae,c],[Oe,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Me,``)){let t=e.codePointAt(0)||0;if(S=we(t)?2:Te(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Oe?Ce(e.slice(p,n.lastIndex)):n===Ae?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Fe={limit:1/0,ellipsis:``,ellipsisWidth:0},Ie=(e,t={})=>Pe(e,Fe,t).width,Le=`]8;;`,Re=RegExp(`(?:\\[(?<code>\\d+)m|\\${Le}(?<uri>.*))`,`y`),ze=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Be=e=>`[${e}m`,Ve=e=>`${Le}${e}`,He=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ie(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ie(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Le,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ue=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ie(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},We=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=Ie(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=Ie(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),He(s,r,t),c=Ie(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){He(s,r,t),c=Ie(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(He(s,r,t),c=Ie(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Ue(e)));let l=s.join(`
3
+ `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){Re.lastIndex=e+1;let t=Re.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
4
+ `){a&&(r+=Ve(``));let e=i?ze(i):void 0;i&&e&&(r+=Be(e))}else t===`
5
+ `&&(i&&ze(i)&&(r+=Be(i)),a&&(r+=Ve(a)))}return r},Ge=/\r?\n/;function Ke(e,t,n){return String(e).normalize().split(Ge).map(e=>We(e,t,n)).join(`
6
+ `)}var M=(/* @__PURE__ */ j(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})))();function qe(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a]?.disabled?qe(a,t<0?-1:1,n):a}const N={actions:/* @__PURE__ */ new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:/* @__PURE__ */ new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,accessible:void 0,date:{monthNames:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Je(e){if(e!==void 0)return e;if(N.accessible!==void 0)return N.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==``&&t!==`0`&&t!==`false`}function Ye(e,t){if(typeof e==`string`)return N.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Ye(n,t))return!0;return!1}function Xe(e,t){if(e===t)return;let n=e.split(`
7
7
  `),r=t.split(`
8
- `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const tt=globalThis.process.platform.startsWith(`win`),nt=Symbol(`clack:cancel`);function rt(e){return e===nt}function it(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function at({input:e=a,output:t=o,overwrite:n=!0,hideCursor:r=!0}={}){let i=s.createInterface({input:e,output:t,prompt:``,tabSize:1});s.emitKeypressEvents(e,i),e instanceof u&&e.isTTY&&e.setRawMode(!0);let c=(i,{name:a,sequence:o})=>{if($e([String(i),a,o],`cancel`)){r&&t.write(j.cursor.show),process.exit(0);return}if(!n)return;let l=a===`return`?0:-1,u=a===`return`?-1:0;s.moveCursor(t,l,u,()=>{s.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return r&&t.write(j.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),r&&t.write(j.cursor.show),e instanceof u&&e.isTTY&&!tt&&e.setRawMode(!1),i.terminal=!1,i.close()}}const ot=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,st=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function ct(e,t,n,r=n,i=n,a){return Xe(t,ot(e??o)-n.length,{hard:!0,trim:!1}).split(`
8
+ `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const Ze=globalThis.process.platform.startsWith(`win`),Qe=Symbol(`clack:cancel`);function $e(e){return e===Qe}function et(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function tt({input:e=a,output:t=o,overwrite:n=!0,hideCursor:r=!0}={}){let i=s.createInterface({input:e,output:t,prompt:``,tabSize:1});s.emitKeypressEvents(e,i),e instanceof u&&e.isTTY&&e.setRawMode(!0);let c=(i,{name:a,sequence:o})=>{if(Ye([String(i),a,o],`cancel`)){r&&t.write(M.cursor.show),process.exit(0);return}if(!n)return;let l=a===`return`?0:-1,u=a===`return`?-1:0;s.moveCursor(t,l,u,()=>{s.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return r&&t.write(M.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),r&&t.write(M.cursor.show),e instanceof u&&e.isTTY&&!Ze&&e.setRawMode(!1),i.terminal=!1,i.close()}}const nt=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,rt=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function it(e,t,n,r=n,i=n,a){return Ke(t,nt(e??o)-n.length,{hard:!0,trim:!1}).split(`
9
9
  `).map((e,t,o)=>{let s=a?a(e,t):e;return t===0?`${r}${s}`:t===o.length-1?`${i}${s}`:`${n}${s}`}).join(`
10
- `)}function lt(e,t){if(`~standard`in e){let n=e[`~standard`].validate(t);return n instanceof Promise?n.then(e=>e.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var ut=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=/* @__PURE__ */ new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;get accessible(){return Qe(this.opts.accessible)}constructor(e,t=!0){let{input:n=a,output:r=o,render:i,signal:s,...c}=e;this.opts=c,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(nt);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=c.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),it(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(j.cursor.show),this.output.off(`resize`,this.render),it(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(j.cursor.show),this.output.off(`resize`,this.render),it(this.input,!1),e(nt)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}async onKeypress(e,t){if(this.state!==`validating`){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&M.aliases.has(t.name)&&this.emit(`cursor`,M.aliases.get(t.name)),M.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e,t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=lt(this.opts.validate,this.value),t;e instanceof Promise?(this.state=`validating`,this.render(),t=await e):t=e,t&&(this.error=t instanceof Error?t.message:t,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}$e([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
11
- `),it(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Xe(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
- `).length-1;this.output.write(j.cursor.move(-999,e*-1))}render(){let e=Xe(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(j.cursor.hide);else{let t=et(this._prevFrame,e),n=st(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(j.cursor.move(0,a-i)),this.output.write(j.erase.lines(1));let t=e.split(`
13
- `);this.output.write(t[a]),this._prevFrame=e,this.output.write(j.cursor.move(0,t.length-a-1));return}if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(j.cursor.move(0,e))}this.output.write(j.erase.down());let t=e.split(`
10
+ `)}function at(e,t){if(`~standard`in e){let n=e[`~standard`].validate(t);return n instanceof Promise?n.then(e=>e.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var ot=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=/* @__PURE__ */ new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;get accessible(){return Je(this.opts.accessible)}constructor(e,t=!0){let{input:n=a,output:r=o,render:i,signal:s,...c}=e;this.opts=c,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(Qe);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=c.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),et(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),et(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),et(this.input,!1),e(Qe)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}async onKeypress(e,t){if(this.state!==`validating`){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&N.aliases.has(t.name)&&this.emit(`cursor`,N.aliases.get(t.name)),N.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e,t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=at(this.opts.validate,this.value),t;e instanceof Promise?(this.state=`validating`,this.render(),t=await e):t=e,t&&(this.error=t instanceof Error?t.message:t,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}Ye([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
11
+ `),et(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Ke(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
+ `).length-1;this.output.write(M.cursor.move(-999,e*-1))}render(){let e=Ke(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(M.cursor.hide);else{let t=Xe(this._prevFrame,e),n=rt(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(M.cursor.move(0,a-i)),this.output.write(M.erase.lines(1));let t=e.split(`
13
+ `);this.output.write(t[a]),this._prevFrame=e,this.output.write(M.cursor.move(0,t.length-a-1));return}if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(M.cursor.move(0,e))}this.output.write(M.erase.down());let t=e.split(`
14
14
  `).slice(a);this.output.write(t.join(`
15
- `)),this._prevFrame=e;return}}this.output.write(j.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},dt=class extends ut{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(j.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},ft=class extends ut{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(e=>e.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(t=>!e.includes(t.value));this.value=t.map(e=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ze(t,1,this.options):t,this.on(`key`,(e,t)=>{t.name===`a`&&this.toggleAll(),t.name===`i`&&this.toggleInvert()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=Ze(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Ze(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let pt=class extends ut{_mask=`•`;get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state===`submit`||this.state===`cancel`)return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${r([`inverse`,`hidden`],`_`)}`;let t=this.masked,n=t.slice(0,this.cursor),i=t.slice(this.cursor,this.cursor+1),a=t.slice(this.cursor+1);return`${n}${r(`inverse`,i)}${a}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??`•`,this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value===void 0&&(this.value=``)})}},mt=class extends ut{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n]?.disabled?Ze(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=Ze(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Ze(this.cursor,1,this.options)}this.changeValue()})}};function ht(){return i.platform===`win32`?!!i.env.CI||!!i.env.WT_SESSION||!!i.env.TERMINUS_SUBLIME||i.env.ConEmuTask===`{cmd::Cmder}`||i.env.TERM_PROGRAM===`Terminus-Sublime`||i.env.TERM_PROGRAM===`vscode`||i.env.TERM===`xterm-256color`||i.env.TERM===`alacritty`||i.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:i.env.TERM!==`linux`}const gt=ht(),_t=()=>process.env.CI===`true`,N=(e,t)=>gt?e:t,vt=N(`◆`,`*`),yt=N(`■`,`x`),bt=N(`▲`,`x`),xt=N(`◇`,`o`),St=N(`┌`,`T`),P=N(`│`,`|`),Ct=N(`└`,`—`),wt=N(`●`,`>`),Tt=N(`○`,` `),Et=N(`◻`,`[•]`),Dt=N(`◼`,`[+]`),Ot=N(`◻`,`[ ]`),kt=N(`▪`,`•`),At=N(`●`,`•`),jt=N(`◆`,`*`),Mt=N(`▲`,`!`),Nt=N(`■`,`x`),Pt=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,vt);case`cancel`:return r(`red`,yt);case`error`:return r(`yellow`,bt);case`submit`:return r(`green`,xt);case`validating`:return r(`dim`,vt)}},Ft=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,P);case`cancel`:return r(`red`,P);case`error`:return r(`yellow`,P);case`submit`:return r(`green`,P)}};function It(e,t){let n=[`${t?`${r(`cyan`,P)} `:``}${e.join(` • `)}`];return t&&n.push(r(`cyan`,Ct)),n}const Lt=(e,t,n,r,i,a=!1)=>{let o=t,s=0;if(a)for(let t=r-1;t>=n;t--){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}else for(let t=n;t<r;t++){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}return{lineCount:o,removals:s}},Rt=({cursor:e,options:t,style:n,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=ot(i)-o,l=st(i),u=r(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let r=y;r<b;r++){let i=t[r],a=Xe(i?n(i,r===e):``,c,{hard:!0,trim:!1}).split(`
16
- `);_.push(a),v+=a.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=d,o=()=>Lt(_,r,0,i,a),s=()=>Lt(_,r,i+1,_.length,a,!0);m?({lineCount:r,removals:t}=o(),r>a&&(h||--a,{lineCount:r,removals:n}=s())):(h||--a,{lineCount:r,removals:n}=s(),r>a&&(--a,{lineCount:r,removals:t}=o())),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},zt=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new dt({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??M.withGuide,a=`${Pt(this.state)} `,o=i?`${r(`gray`,P)} `:``,s=ct(e.output,e.message,o,a),c=`${i?`${r(`gray`,P)}
15
+ `)),this._prevFrame=e;return}}this.output.write(M.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},st=class extends ot{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(M.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},ct=class extends ot{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(e=>e.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(t=>!e.includes(t.value));this.value=t.map(e=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[t]?.disabled?qe(t,1,this.options):t,this.on(`key`,(e,t)=>{t.name===`a`&&this.toggleAll(),t.name===`i`&&this.toggleInvert()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=qe(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=qe(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let lt=class extends ot{_mask=`•`;get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state===`submit`||this.state===`cancel`)return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${r([`inverse`,`hidden`],`_`)}`;let t=this.masked,n=t.slice(0,this.cursor),i=t.slice(this.cursor,this.cursor+1),a=t.slice(this.cursor+1);return`${n}${r(`inverse`,i)}${a}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??`•`,this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value===void 0&&(this.value=``)})}},ut=class extends ot{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n]?.disabled?qe(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=qe(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=qe(this.cursor,1,this.options)}this.changeValue()})}};function dt(){return i.platform===`win32`?!!i.env.CI||!!i.env.WT_SESSION||!!i.env.TERMINUS_SUBLIME||i.env.ConEmuTask===`{cmd::Cmder}`||i.env.TERM_PROGRAM===`Terminus-Sublime`||i.env.TERM_PROGRAM===`vscode`||i.env.TERM===`xterm-256color`||i.env.TERM===`alacritty`||i.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:i.env.TERM!==`linux`}const ft=dt(),pt=()=>process.env.CI===`true`,P=(e,t)=>ft?e:t,mt=P(`◆`,`*`),ht=P(`■`,`x`),gt=P(`▲`,`x`),_t=P(`◇`,`o`),vt=P(`┌`,`T`),F=P(`│`,`|`),yt=P(`└`,`—`),bt=P(`●`,`>`),xt=P(`○`,` `),St=P(`◻`,`[•]`),Ct=P(`◼`,`[+]`),wt=P(`◻`,`[ ]`),Tt=P(`▪`,`•`),Et=P(`●`,`•`),Dt=P(`◆`,`*`),Ot=P(`▲`,`!`),kt=P(`■`,`x`),At=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,mt);case`cancel`:return r(`red`,ht);case`error`:return r(`yellow`,gt);case`submit`:return r(`green`,_t);case`validating`:return r(`dim`,mt)}},jt=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,F);case`cancel`:return r(`red`,F);case`error`:return r(`yellow`,F);case`submit`:return r(`green`,F)}};function Mt(e,t){let n=[`${t?`${r(`cyan`,F)} `:``}${e.join(` • `)}`];return t&&n.push(r(`cyan`,yt)),n}const Nt=(e,t,n,r,i,a=!1)=>{let o=t,s=0;if(a)for(let t=r-1;t>=n;t--){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}else for(let t=n;t<r;t++){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}return{lineCount:o,removals:s}},Pt=({cursor:e,options:t,style:n,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=nt(i)-o,l=rt(i),u=r(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let r=y;r<b;r++){let i=t[r],a=Ke(i?n(i,r===e):``,c,{hard:!0,trim:!1}).split(`
16
+ `);_.push(a),v+=a.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=d,o=()=>Nt(_,r,0,i,a),s=()=>Nt(_,r,i+1,_.length,a,!0);m?({lineCount:r,removals:t}=o(),r>a&&(h||--a,{lineCount:r,removals:n}=s())):(h||--a,{lineCount:r,removals:n}=s(),r>a&&(--a,{lineCount:r,removals:t}=o())),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},Ft=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new st({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??N.withGuide,a=`${At(this.state)} `,o=i?`${r(`gray`,F)} `:``,s=it(e.output,e.message,o,a),c=`${i?`${r(`gray`,F)}
17
17
  `:``}${s}
18
- `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${i?`${r(`gray`,P)} `:``}${r(`dim`,l)}`;case`cancel`:return`${c}${i?`${r(`gray`,P)} `:``}${r([`strikethrough`,`dim`],l)}${i?`
19
- ${r(`gray`,P)}`:``}`;default:{let a=i?`${r(`cyan`,P)} `:``,o=i?r(`cyan`,Ct):``;return`${c}${a}${this.value?`${r(`green`,wt)} ${t}`:`${r(`dim`,Tt)} ${r(`dim`,t)}`}${e.vertical?i?`
20
- ${r(`cyan`,P)} `:`
21
- `:` ${r(`dim`,`/`)} `}${this.value?`${r(`dim`,Tt)} ${r(`dim`,n)}`:`${r(`green`,wt)} ${n}`}
18
+ `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${i?`${r(`gray`,F)} `:``}${r(`dim`,l)}`;case`cancel`:return`${c}${i?`${r(`gray`,F)} `:``}${r([`strikethrough`,`dim`],l)}${i?`
19
+ ${r(`gray`,F)}`:``}`;default:{let a=i?`${r(`cyan`,F)} `:``,o=i?r(`cyan`,yt):``;return`${c}${a}${this.value?`${r(`green`,bt)} ${t}`:`${r(`dim`,xt)} ${r(`dim`,t)}`}${e.vertical?i?`
20
+ ${r(`cyan`,F)} `:`
21
+ `:` ${r(`dim`,`/`)} `}${this.value?`${r(`dim`,xt)} ${r(`dim`,n)}`:`${r(`green`,bt)} ${n}`}
22
22
  ${o}
23
- `}}}}).prompt()},Bt=[`${r(`dim`,`↑/↓`)} to navigate`,`${r(`dim`,`Space:`)} select`,`${r(`dim`,`Enter:`)} confirm`],Vt=(e,t)=>e.split(`
23
+ `}}}}).prompt()},It=[`${r(`dim`,`↑/↓`)} to navigate`,`${r(`dim`,`Space:`)} select`,`${r(`dim`,`Enter:`)} confirm`],Lt=(e,t)=>e.split(`
24
24
  `).map(e=>t(e)).join(`
25
- `),Ht=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`disabled`?`${r(`gray`,Ot)} ${Vt(n,e=>r([`strikethrough`,`gray`],e))}${e.hint?` ${r(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${r(`cyan`,Et)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${r(`green`,Dt)} ${Vt(n,e=>r(`dim`,e))}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${Vt(n,e=>r([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${r(`green`,Dt)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${Vt(n,e=>r(`dim`,e))}`:`${r(`dim`,Ot)} ${Vt(n,e=>r(`dim`,e))}`},n=e.required??!0,i=e.showInstructions??!0;return new ft({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(e){if(n&&(e===void 0||e.length===0))return`Please select at least one option.
26
- ${r(`reset`,r(`dim`,`Press ${r([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${r(`gray`,r(`bgWhite`,r(`inverse`,` enter `)))} to submit`))}`},render(){let n=e.withGuide??M.withGuide,a=ct(e.output,e.message,n?`${Ft(this.state)} `:``,`${Pt(this.state)} `),o=`${n?`${r(`gray`,P)}
25
+ `),Rt=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`disabled`?`${r(`gray`,wt)} ${Lt(n,e=>r([`strikethrough`,`gray`],e))}${e.hint?` ${r(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${r(`cyan`,St)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${r(`green`,Ct)} ${Lt(n,e=>r(`dim`,e))}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${Lt(n,e=>r([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${r(`green`,Ct)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${Lt(n,e=>r(`dim`,e))}`:`${r(`dim`,wt)} ${Lt(n,e=>r(`dim`,e))}`},n=e.required??!0,i=e.showInstructions??!0;return new ct({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(e){if(n&&(e===void 0||e.length===0))return`Please select at least one option.
26
+ ${r(`reset`,r(`dim`,`Press ${r([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${r(`gray`,r(`bgWhite`,r(`inverse`,` enter `)))} to submit`))}`},render(){let n=e.withGuide??N.withGuide,a=it(e.output,e.message,n?`${jt(this.state)} `:``,`${At(this.state)} `),o=`${n?`${r(`gray`,F)}
27
27
  `:``}${a}
28
- `,s=this.value??[],c=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=s.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let i=this.options.filter(({value:e})=>s.includes(e)).map(e=>t(e,`submitted`)).join(r(`dim`,`, `))||r(`dim`,`none`);return`${o}${ct(e.output,i,n?`${r(`gray`,P)} `:``)}`}case`cancel`:{let i=this.options.filter(({value:e})=>s.includes(e)).map(e=>t(e,`cancelled`)).join(r(`dim`,`, `));return i.trim()===``?`${o}${r(`gray`,P)}`:`${o}${ct(e.output,i,n?`${r(`gray`,P)} `:``)}${n?`
29
- ${r(`gray`,P)}`:``}`}case`error`:{let t=n?`${r(`yellow`,P)} `:``,i=this.error.split(`
30
- `).map((e,t)=>t===0?`${n?`${r(`yellow`,Ct)} `:``}${r(`yellow`,e)}`:` ${e}`).join(`
28
+ `,s=this.value??[],c=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=s.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let i=this.options.filter(({value:e})=>s.includes(e)).map(e=>t(e,`submitted`)).join(r(`dim`,`, `))||r(`dim`,`none`);return`${o}${it(e.output,i,n?`${r(`gray`,F)} `:``)}`}case`cancel`:{let i=this.options.filter(({value:e})=>s.includes(e)).map(e=>t(e,`cancelled`)).join(r(`dim`,`, `));return i.trim()===``?`${o}${r(`gray`,F)}`:`${o}${it(e.output,i,n?`${r(`gray`,F)} `:``)}${n?`
29
+ ${r(`gray`,F)}`:``}`}case`error`:{let t=n?`${r(`yellow`,F)} `:``,i=this.error.split(`
30
+ `).map((e,t)=>t===0?`${n?`${r(`yellow`,yt)} `:``}${r(`yellow`,e)}`:` ${e}`).join(`
31
31
  `),a=o.split(`
32
32
  `).length,s=i.split(`
33
- `).length+1;return`${o}${t}${Rt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:a+s,style:c}).join(`
33
+ `).length+1;return`${o}${t}${Pt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:a+s,style:c}).join(`
34
34
  ${t}`)}
35
35
  ${i}
36
- `}default:{let t=n?`${r(`cyan`,P)} `:``,a=o.split(`
37
- `).length,s=i?It(Bt,n):n?[r(`cyan`,Ct)]:[],l=s.join(`
38
- `),u=s.length+1;return`${o}${t}${Rt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:a+u,style:c}).join(`
36
+ `}default:{let t=n?`${r(`cyan`,F)} `:``,a=o.split(`
37
+ `).length,s=i?Mt(It,n):n?[r(`cyan`,yt)]:[],l=s.join(`
38
+ `),u=s.length+1;return`${o}${t}${Pt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:a+u,style:c}).join(`
39
39
  ${t}`)}
40
40
  ${l}
41
- `}}}}).prompt()},F={message:(e=[],{symbol:t=r(`gray`,P),secondarySymbol:n=r(`gray`,P),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??M.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
41
+ `}}}}).prompt()},I={message:(e=[],{symbol:t=r(`gray`,F),secondarySymbol:n=r(`gray`,F),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??N.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
42
42
  `);if(f.length>0){let[e,...r]=f;e.length>0?s.push(`${u}${e}`):s.push(c?t:``);for(let e of r)e.length>0?s.push(`${d}${e}`):s.push(c?n:``)}i.write(`${s.join(`
43
43
  `)}
44
- `)},info:(e,t)=>{F.message(e,{...t,symbol:r(`blue`,At)})},success:(e,t)=>{F.message(e,{...t,symbol:r(`green`,jt)})},step:(e,t)=>{F.message(e,{...t,symbol:r(`green`,xt)})},warn:(e,t)=>{F.message(e,{...t,symbol:r(`yellow`,Mt)})},warning:(e,t)=>{F.warn(e,t)},error:(e,t)=>{F.message(e,{...t,symbol:r(`red`,Nt)})}},Ut=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${r(`gray`,Ct)} `:``;n.write(`${i}${r(`red`,e)}
44
+ `)},info:(e,t)=>{I.message(e,{...t,symbol:r(`blue`,Et)})},success:(e,t)=>{I.message(e,{...t,symbol:r(`green`,Dt)})},step:(e,t)=>{I.message(e,{...t,symbol:r(`green`,_t)})},warn:(e,t)=>{I.message(e,{...t,symbol:r(`yellow`,Ot)})},warning:(e,t)=>{I.warn(e,t)},error:(e,t)=>{I.message(e,{...t,symbol:r(`red`,kt)})}},zt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${r(`gray`,yt)} `:``;n.write(`${i}${r(`red`,e)}
45
45
 
46
- `)},Wt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${r(`gray`,St)} `:``;n.write(`${i}${e}
47
- `)},I=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${r(`gray`,P)}
48
- ${r(`gray`,Ct)} `:``;n.write(`${i}${e}
46
+ `)},Bt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${r(`gray`,vt)} `:``;n.write(`${i}${e}
47
+ `)},L=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${r(`gray`,F)}
48
+ ${r(`gray`,yt)} `:``;n.write(`${i}${e}
49
49
 
50
- `)},Gt=e=>new pt({validate:e.validate,mask:e.mask??kt,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??M.withGuide,n=`${t?`${r(`gray`,P)}
51
- `:``}${Pt(this.state)} ${e.message}
52
- `,i=this.userInputWithCursor,a=this.masked;switch(this.state){case`error`:{let i=t?`${r(`yellow`,P)} `:``,o=t?`${r(`yellow`,Ct)} `:``,s=a??``;return e.clearOnError&&this.clear(),`${n.trim()}
50
+ `)},Vt=e=>new lt({validate:e.validate,mask:e.mask??Tt,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??N.withGuide,n=`${t?`${r(`gray`,F)}
51
+ `:``}${At(this.state)} ${e.message}
52
+ `,i=this.userInputWithCursor,a=this.masked;switch(this.state){case`error`:{let i=t?`${r(`yellow`,F)} `:``,o=t?`${r(`yellow`,yt)} `:``,s=a??``;return e.clearOnError&&this.clear(),`${n.trim()}
53
53
  ${i}${s}
54
54
  ${o}${r(`yellow`,this.error)}
55
- `}case`submit`:return`${n}${t?`${r(`gray`,P)} `:``}${a?r(`dim`,a):``}`;case`cancel`:return`${n}${t?`${r(`gray`,P)} `:``}${a?r([`strikethrough`,`dim`],a):``}${a&&t?`
56
- ${r(`gray`,P)}`:``}`;default:return`${n}${t?`${r(`cyan`,P)} `:``}${i}
57
- ${t?r(`cyan`,Ct):``}
58
- `}}}).prompt(),Kt=e=>r(`magenta`,e),qt=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:a,frames:o=gt?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=gt?80:120,signal:c,...l}={})=>{let u=_t(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=ot(n),y=l?.styleFrame??Kt,b=e=>{let n=e>1?a??M.messages.error:i??M.messages.cancel;m=e===1,p&&(re(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),C=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},w=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},T=()=>{if(g===void 0)return;u&&n.write(`
59
- `);let e=Xe(g,v,{hard:!0,trim:!1}).split(`
60
- `);e.length>1&&n.write(j.cursor.up(e.length-1)),n.write(j.cursor.to(0)),n.write(j.erase.down())},E=e=>e.replace(/\.+$/,``),ee=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},te=l.withGuide??M.withGuide,ne=(t=``)=>{p=!0,d=at({output:n}),h=E(t),_=performance.now(),te&&n.write(`${r(`gray`,P)}
61
- `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;T(),g=h;let t=y(o[i]),r;if(u)r=`${t} ${h}...`;else if(e===`timer`)r=`${t} ${h} ${ee(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);r=`${t} ${h}${e}`}let s=Xe(r,v,{hard:!0,trim:!1});n.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},re=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),T();let o=i===0?r(`green`,xt):i===1?r(`red`,yt):r(`red`,bt);h=t??h,a||(e===`timer`?n.write(`${o} ${h} ${ee(_)}
55
+ `}case`submit`:return`${n}${t?`${r(`gray`,F)} `:``}${a?r(`dim`,a):``}`;case`cancel`:return`${n}${t?`${r(`gray`,F)} `:``}${a?r([`strikethrough`,`dim`],a):``}${a&&t?`
56
+ ${r(`gray`,F)}`:``}`;default:return`${n}${t?`${r(`cyan`,F)} `:``}${i}
57
+ ${t?r(`cyan`,yt):``}
58
+ `}}}).prompt(),Ht=e=>r(`magenta`,e),Ut=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:a,frames:o=ft?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=ft?80:120,signal:c,...l}={})=>{let u=pt(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=nt(n),y=l?.styleFrame??Ht,b=e=>{let n=e>1?a??N.messages.error:i??N.messages.cancel;m=e===1,p&&(re(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),C=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},w=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},T=()=>{if(g===void 0)return;u&&n.write(`
59
+ `);let e=Ke(g,v,{hard:!0,trim:!1}).split(`
60
+ `);e.length>1&&n.write(M.cursor.up(e.length-1)),n.write(M.cursor.to(0)),n.write(M.erase.down())},E=e=>e.replace(/\.+$/,``),ee=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},te=l.withGuide??N.withGuide,ne=(t=``)=>{p=!0,d=tt({output:n}),h=E(t),_=performance.now(),te&&n.write(`${r(`gray`,F)}
61
+ `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;T(),g=h;let t=y(o[i]),r;if(u)r=`${t} ${h}...`;else if(e===`timer`)r=`${t} ${h} ${ee(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);r=`${t} ${h}${e}`}let s=Ke(r,v,{hard:!0,trim:!1});n.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},re=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),T();let o=i===0?r(`green`,_t):i===1?r(`red`,ht):r(`red`,gt);h=t??h,a||(e===`timer`?n.write(`${o} ${h} ${ee(_)}
62
62
  `):n.write(`${o} ${h}
63
- `)),w(),d()};return{start:ne,stop:(e=``)=>re(e,0),message:(e=``)=>{h=E(e??h)},cancel:(e=``)=>re(e,1),error:(e=``)=>re(e,2),clear:()=>re(``,0,!0),get isCancelled(){return m}}},Jt=[`${r(`dim`,`↑/↓`)} to navigate`,`${r(`dim`,`Enter:`)} confirm`],Yt=(e,t)=>e.includes(`
63
+ `)),w(),d()};return{start:ne,stop:(e=``)=>re(e,0),message:(e=``)=>{h=E(e??h)},cancel:(e=``)=>re(e,1),error:(e=``)=>re(e,2),clear:()=>re(``,0,!0),get isCancelled(){return m}}},Wt=[`${r(`dim`,`↑/↓`)} to navigate`,`${r(`dim`,`Enter:`)} confirm`],Gt=(e,t)=>e.includes(`
64
64
  `)?e.split(`
65
65
  `).map(e=>t(e)).join(`
66
- `):t(e),Xt=e=>{let t=(e,t)=>{if(e===void 0)return``;let n=e.label??String(e.value);switch(t){case`disabled`:return`${r(`gray`,Tt)} ${Yt(n,e=>r(`gray`,e))}${e.hint?` ${r(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${Yt(n,e=>r(`dim`,e))}`;case`active`:return`${r(`green`,wt)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${Yt(n,e=>r([`strikethrough`,`dim`],e))}`;default:return`${r(`dim`,Tt)} ${Yt(n,e=>r(`dim`,e))}`}},n=e.showInstructions??!0;return new mt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??M.withGuide,a=`${Pt(this.state)} `,o=`${Ft(this.state)} `,s=ct(e.output,e.message,o,a),c=`${i?`${r(`gray`,P)}
66
+ `):t(e),Kt=e=>{let t=(e,t)=>{if(e===void 0)return``;let n=e.label??String(e.value);switch(t){case`disabled`:return`${r(`gray`,xt)} ${Gt(n,e=>r(`gray`,e))}${e.hint?` ${r(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${Gt(n,e=>r(`dim`,e))}`;case`active`:return`${r(`green`,bt)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${Gt(n,e=>r([`strikethrough`,`dim`],e))}`;default:return`${r(`dim`,xt)} ${Gt(n,e=>r(`dim`,e))}`}},n=e.showInstructions??!0;return new ut({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??N.withGuide,a=`${At(this.state)} `,o=`${jt(this.state)} `,s=it(e.output,e.message,o,a),c=`${i?`${r(`gray`,F)}
67
67
  `:``}${s}
68
- `;switch(this.state){case`submit`:{let n=i?`${r(`gray`,P)} `:``;return`${c}${ct(e.output,t(this.options[this.cursor],`selected`),n)}`}case`cancel`:{let n=i?`${r(`gray`,P)} `:``;return`${c}${ct(e.output,t(this.options[this.cursor],`cancelled`),n)}${i?`
69
- ${r(`gray`,P)}`:``}`}default:{let a=i?`${r(`cyan`,P)} `:``,o=c.split(`
70
- `).length,s=n?It(Jt,i):i?[r(`cyan`,Ct)]:[],l=s.join(`
71
- `),u=s.length+1;return`${c}${a}${Rt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:o+u,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
68
+ `;switch(this.state){case`submit`:{let n=i?`${r(`gray`,F)} `:``;return`${c}${it(e.output,t(this.options[this.cursor],`selected`),n)}`}case`cancel`:{let n=i?`${r(`gray`,F)} `:``;return`${c}${it(e.output,t(this.options[this.cursor],`cancelled`),n)}${i?`
69
+ ${r(`gray`,F)}`:``}`}default:{let a=i?`${r(`cyan`,F)} `:``,o=c.split(`
70
+ `).length,s=n?Mt(Wt,i):i?[r(`cyan`,yt)]:[],l=s.join(`
71
+ `),u=s.length+1;return`${c}${a}${Pt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:o+u,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
72
72
  ${a}`)}
73
73
  ${l}
74
- `}}}}).prompt()};`${r(`gray`,P)}`;const Zt=[`stable`,`beta`],Qt=[`latest`,...Zt],$t=e=>Zt.includes(e),en=e=>Qt.includes(e);function tn(e,t,n){if(n===`latest`)return{version:t,fellBack:!1};let r=e[n];return r===null?{version:t,fellBack:!0}:{version:r,fellBack:!1}}var nn=`0.2.0-dev.98`;const rn=[{id:`claude-code`,name:`Claude Code`,projectDir:`.claude/skills`,globalDir:`.claude/skills`,marker:`.claude`},{id:`codex`,name:`Codex`,projectDir:`.agents/skills`,globalDir:`.agents/skills`,marker:`.codex`},{id:`cursor`,name:`Cursor`,projectDir:`.agents/skills`,globalDir:`.cursor/skills`,marker:`.cursor`},{id:`gemini-cli`,name:`Gemini CLI`,projectDir:`.agents/skills`,globalDir:`.gemini/skills`,marker:`.gemini`}],an=e=>e===`global`?C():process.cwd();function on(e=C()){return rn.filter(t=>f(_(e,t.marker)))}function sn(e){return rn.find(t=>t.id===e)}function cn(e,t,n=an(t)){let r=e.map(e=>b(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const ln={maxNameLength:100,maxPromptBytes:20480,maxChecks:20,maxHiddenFiles:20,maxHiddenBytes:1048576,maxSetupLength:4096,maxCheckTextLength:10240,minTrials:1,maxTrials:5,maxAttemptsPerRun:50,maxModelsPerRun:4,maxFinalTextBytes:20480,maxJudgedDiffBytes:102400,maxCheckOutputBytes:8192,maxSandboxesPerOrganization:5};function un(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}ln.maxPromptBytes;function dn(e){return e<1e3?String(e):e<1e6?`${pn(e/1e3)}k`:`${pn(e/1e6)}M`}const fn=e=>`${dn(e.inputTokens+e.outputTokens)} tok · ${un(e.costUsd)}`,pn=e=>e>=100?Math.round(e):Number(e.toFixed(1));function mn(e){switch(e){case`refusal`:return`Claude declined to answer this.`;case`max_tokens`:return`The answer was cut off at the token limit.`;case`tool_use`:return`Stopped after too many skill loads in one turn.`;default:return null}}function hn(e){let t=e.split(`
75
- `),n=t.pop()??``,r=[];for(let e of t)if(e.trim()!==``)try{r.push(JSON.parse(e))}catch{r.push({type:`error`,message:`The answer came back garbled.`})}return{events:r,rest:n}}function gn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?nn.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${gn()} ${e}\``;var R=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function z(e,t,n=fetch){async function r(r,i={}){let a;try{a=await n(`${e}${r}`,{...i,headers:{"User-Agent":`a-kit/${nn}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new R(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new R(401,`UNAUTHORIZED`,`You're not logged in. Run ${L(`login`)}.`):new R(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),listProjects:(e,t)=>i(`/orgs/${e}/projects`,{signal:t}),listRoles:(e,t)=>i(`/orgs/${e}/roles`,{signal:t}),getRepository:(e,t)=>i(`/orgs/${e}/repository`,{signal:t}),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),machineName:e=>i(`/machines/${encodeURIComponent(e)}/name`),nameMachine:(e,t)=>i(`/machines/${encodeURIComponent(e)}/name`,{method:`PUT`,body:JSON.stringify({name:t})}),search:e=>i(`/search?q=${encodeURIComponent(e)}`),getSkill:(e,t=`latest`)=>i(`/skills/${e}${t===`latest`?``:`?channel=${t}`}`),getVersion:(e,t)=>i(`/skills/${e}/versions/${t}`),getSkillHealth:e=>i(`/skills/${e}/health`),createReport:(e,t)=>i(`/orgs/${e}/reports`,{method:`POST`,body:JSON.stringify(t)}),playground:async(e,t,n)=>{let i=await r(`/skills/${e}/playground`,{method:`POST`,body:JSON.stringify(t)}),a=``,o=new TextDecoder;for await(let e of i.body??[]){let t=hn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}hn(`${a}${o.decode()}\n`).events.forEach(n)},getBlob:async(e,t)=>new Uint8Array(await(await r(`/skills/${e}/blobs/${t}`)).arrayBuffer()),getPublicSkill:e=>i(`/public/skills/${_n(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${_n(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${_n(e)}/installs`,{method:`POST`})}}const _n=e=>e.split(`/`).map(encodeURIComponent).join(`/`),vn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function yn(e){return rt(e)&&(Ut(`Cancelled.`),process.exit(130)),e}async function bn(e,t){if(e.length>0)return e.map(e=>{let t=sn(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${rn.map(e=>e.id).join(`, `)}.`);return t});let n=on(),r=n.length>0?n:[sn(`claude-code`)];return!t||!vn()?r:yn(await Ht({message:`Which agents should get the skills?`,options:rn.map(e=>({value:e.id,label:e.name,hint:n.includes(e)?`detected`:void 0})),initialValues:r.map(e=>e.id),required:!0})).map(e=>sn(e))}async function xn(e,t){return e?`global`:!t||!vn()?`project`:yn(await Xt({message:`Where should they go?`,options:[{value:`project`,label:`This project`,hint:process.cwd()},{value:`global`,label:`Everywhere`,hint:`your home folder`}],initialValue:`project`}))}const Sn=`kit/`;function Cn(e){let t=[],n=[];for(let r of e)r.startsWith(`kit/`)?n.push(r.slice(4)):t.push(r);return{skills:t,kits:n}}async function wn(e,t,n){if(t.length>0)return En(e,t,n,`skill`);if(!n||!vn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=yn(await Ht({message:`Which skills?`,options:e.map(e=>({value:e.id,label:Nn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const Tn=(e,t,n)=>En(e,t,n,`kit`);async function En(e,t,n,r){let i=[];for(let a of t){let t=An(e,a,r),o=t.length===1?t[0]:await jn(t,n,r);i.includes(o)||i.push(o)}return i}const Dn=(e,t)=>An(e,t,`skill`);function On(e,t){let n=t.lastIndexOf(`/`),r=t.slice(n+1),i=n===-1?null:t.slice(0,n).trim().toLowerCase();return e.filter(e=>e.name===r&&(i===null||e.organizationName.toLowerCase()===i||e.organizationSlug!=null&&e.organizationSlug===i))}const kn=(e,t)=>On(e,t);function An(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=On(e,t);if(a.length===0)throw Error(r===-1?`There's no ${n} named "${i}" in your agent kit. See them with ${L(`list`)}.`:`There's no ${n} named "${i}" in an organization called "${t.slice(0,r)}". See them with ${L(`list`)}.`);return a}async function jn(e,t,n){let r=e[0].name,i=n===`kit`?Sn:``;if(!t||!vn()){let t=e.map(e=>{let t=i+Mn(e);return L(`add ${/\s/.test(t)?`"${t}"`:t}`)});throw Error(`More than one of your organizations has a ${n} named "${r}". Say which one: ${t.join(` or `)}.`)}let a=yn(await Xt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:Mn(e)}))}));return e.find(e=>e.id===a)}const Mn=e=>`${e.organizationName}/${e.name}`,Nn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function B(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function Pn(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function V(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?_(process.env.APPDATA,`agent-kit`):_(process.env.XDG_CONFIG_HOME??_(C(),`.config`),`agent-kit`)}const Fn=()=>_(V(),`credentials.json`);async function In(){try{return JSON.parse(await O(Fn(),`utf8`))}catch{return{}}}async function H(){return(await In())[B()]??null}async function Ln(e){let t=await In();e?t[B()]=e:delete t[B()];let n=Fn();await D(g(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
76
- `,{mode:384}),await re(n,384)}const Rn=()=>_(V(),`settings.json`);async function U(){try{return JSON.parse(await O(Rn(),`utf8`))}catch{return{}}}async function zn(e){let t={...await U(),...e};await D(V(),{recursive:!0,mode:448}),await k(Rn(),JSON.stringify(t,null,2)+`
77
- `)}function Bn(e=process.env){let t=e=>e!==void 0&&[`0`,`false`,`off`,`no`].includes(e.toLowerCase());return(e=>e!==void 0&&e!==``&&!t(e))(e.DO_NOT_TRACK)||t(e.AGENT_KIT_TELEMETRY)}function W(e){let t=y(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const Vn=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Hn(e){return e.split(`/`).some(e=>Vn.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const Un=e=>he(`sha256`).update(e).digest(`hex`);async function Wn(e){let t=await ce(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=y(e,_(r.parentPath,r.name)).split(x).join(`/`);if(Hn(t))continue;let i=new Uint8Array(await O(_(e,t)));n.push({path:t,size:i.byteLength,sha256:Un(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Gn(e,t){let n=new Map(t.filter(e=>!Hn(e.path)).map(e=>[e.path,e.sha256])),r=new Set(e.map(e=>e.path)),i=e.filter(e=>n.get(e.path)!==e.sha256),a=[...n.keys()].filter(e=>!r.has(e));return{upserts:i,deletes:a,paths:[...i.map(e=>e.path),...a].sort()}}function Kn(e){return e.length===0?`nothing`:e.length>3?`${e.length} files`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e.at(-1)}`}async function qn(e,t){for(let n of e){if(!f(n))continue;let{paths:e}=Gn(await Wn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Jn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?qn(r.map(e=>_(e,t)),i.files):null}async function Yn(e){try{if(!(await oe(e)).isSymbolicLink())return null}catch{return null}return b(g(e),await le(e))}async function Xn(e,t){for(let n of e){let e=await Yn(_(n,t));if(e)return e}return null}async function Zn(e,t){await de(e,{recursive:!0,force:!0}),await D(g(e),{recursive:!0}),await pe(t,e,process.platform===`win32`?`junction`:`dir`)}const G=`SKILL.md`,Qn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},$n=/[\u0000-\u001f\u007f\\:]/;function er(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Qn.maxPathLength)return`Paths can be at most ${Qn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if($n.test(e))return`Paths can't contain \\, : or control characters.`;for(let t of e.split(`/`)){if(t===``)return`The path has an empty folder name (//).`;if(t===`.`||t===`..`)return`The path can't contain . or .. folders.`;if(t!==t.trim())return`Names can't start or end with a space.`}return null}function tr(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function nr(e){return e.slice(e.lastIndexOf(`/`)+1)}function rr(e,t){let n=tr(e)?tr(e).split(`/`):[];for(let e of t.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){if(n.length===0)return null;n.pop()}else n.push(e)}return n.join(`/`)}var K=/* @__PURE__ */ A((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),ir=/* @__PURE__ */ A((e=>{var t=K();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),ar=/* @__PURE__ */ A((e=>{var t=K(),n=ir();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||e&&!a.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join(`
78
- `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),or=/* @__PURE__ */ A((e=>{var t=K(),n=ir();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=/* @__PURE__ */ new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=/* @__PURE__ */ new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=/* @__PURE__ */ Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),sr=/* @__PURE__ */ A((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),cr=/* @__PURE__ */ A((e=>{var t=K();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),lr=/* @__PURE__ */ A((e=>{var t=sr(),n=K(),r=cr();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:/* @__PURE__ */ new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),ur=/* @__PURE__ */ A((e=>{var t=or(),n=ir(),r=K(),i=lr(),a=cr(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
74
+ `}}}}).prompt()};`${r(`gray`,F)}`;const qt=[`stable`,`beta`],Jt=[`latest`,...qt],Yt=e=>qt.includes(e),Xt=e=>Jt.includes(e);function Zt(e,t,n){if(n===`latest`)return{version:t,fellBack:!1};let r=e[n];return r===null?{version:t,fellBack:!0}:{version:r,fellBack:!1}}var Qt=`0.3.0-dev.115`;const $t=[{id:`claude-code`,name:`Claude Code`,projectDir:`.claude/skills`,globalDir:`.claude/skills`,marker:`.claude`},{id:`codex`,name:`Codex`,projectDir:`.agents/skills`,globalDir:`.agents/skills`,marker:`.codex`},{id:`cursor`,name:`Cursor`,projectDir:`.agents/skills`,globalDir:`.cursor/skills`,marker:`.cursor`},{id:`gemini-cli`,name:`Gemini CLI`,projectDir:`.agents/skills`,globalDir:`.gemini/skills`,marker:`.gemini`}],en=e=>e===`global`?C():process.cwd();function tn(e=C()){return $t.filter(t=>f(_(e,t.marker)))}function nn(e){return $t.find(t=>t.id===e)}function rn(e,t,n=en(t)){let r=e.map(e=>b(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const an={maxNameLength:100,maxPromptBytes:20480,maxChecks:20,maxHiddenFiles:20,maxHiddenBytes:1048576,maxSetupLength:4096,maxCheckTextLength:10240,minTrials:1,maxTrials:5,maxAttemptsPerRun:50,maxModelsPerRun:4,maxFinalTextBytes:20480,maxJudgedDiffBytes:102400,maxCheckOutputBytes:8192,maxSandboxesPerOrganization:5};function on(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}an.maxPromptBytes;function sn(e){return e<1e3?String(e):e<1e6?`${ln(e/1e3)}k`:`${ln(e/1e6)}M`}const cn=e=>`${sn(e.inputTokens+e.outputTokens)} tok · ${on(e.costUsd)}`,ln=e=>e>=100?Math.round(e):Number(e.toFixed(1));function un(e){switch(e){case`refusal`:return`Claude declined to answer this.`;case`max_tokens`:return`The answer was cut off at the token limit.`;case`tool_use`:return`Stopped after too many skill loads in one turn.`;default:return null}}function dn(e){let t=e.split(`
75
+ `),n=t.pop()??``,r=[];for(let e of t)if(e.trim()!==``)try{r.push(JSON.parse(e))}catch{r.push({type:`error`,message:`The answer came back garbled.`})}return{events:r,rest:n}}function fn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?Qt.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const R=e=>`\`${fn()} ${e}\``;var z=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function B(e,t,n=fetch){async function r(r,i={}){let a;try{a=await n(`${e}${r}`,{...i,headers:{"User-Agent":`a-kit/${Qt}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new z(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new z(401,`UNAUTHORIZED`,`You're not logged in. Run ${R(`login`)}.`):new z(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),getRepository:(e,t)=>i(`/orgs/${e}/repository`,{signal:t}),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),machineName:e=>i(`/machines/${encodeURIComponent(e)}/name`),nameMachine:(e,t)=>i(`/machines/${encodeURIComponent(e)}/name`,{method:`PUT`,body:JSON.stringify({name:t})}),search:e=>i(`/search?q=${encodeURIComponent(e)}`),getSkill:(e,t=`latest`)=>i(`/skills/${e}${t===`latest`?``:`?channel=${t}`}`),getVersion:(e,t)=>i(`/skills/${e}/versions/${t}`),getSkillHealth:e=>i(`/skills/${e}/health`),playground:async(e,t,n)=>{let i=await r(`/skills/${e}/playground`,{method:`POST`,body:JSON.stringify(t)}),a=``,o=new TextDecoder;for await(let e of i.body??[]){let t=dn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}dn(`${a}${o.decode()}\n`).events.forEach(n)},getBlob:async(e,t)=>new Uint8Array(await(await r(`/skills/${e}/blobs/${t}`)).arrayBuffer()),getPublicSkill:e=>i(`/public/skills/${pn(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${pn(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${pn(e)}/installs`,{method:`POST`})}}const pn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),mn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function hn(e){return $e(e)&&(zt(`Cancelled.`),process.exit(130)),e}async function gn(e,t){if(e.length>0)return e.map(e=>{let t=nn(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${$t.map(e=>e.id).join(`, `)}.`);return t});let n=tn(),r=n.length>0?n:[nn(`claude-code`)];return!t||!mn()?r:hn(await Rt({message:`Which agents should get the skills?`,options:$t.map(e=>({value:e.id,label:e.name,hint:n.includes(e)?`detected`:void 0})),initialValues:r.map(e=>e.id),required:!0})).map(e=>nn(e))}async function _n(e,t){return e?`global`:!t||!mn()?`project`:hn(await Kt({message:`Where should they go?`,options:[{value:`project`,label:`This project`,hint:process.cwd()},{value:`global`,label:`Everywhere`,hint:`your home folder`}],initialValue:`project`}))}const vn=`kit/`;function yn(e){let t=[],n=[];for(let r of e)r.startsWith(`kit/`)?n.push(r.slice(4)):t.push(r);return{skills:t,kits:n}}async function bn(e,t,n){if(t.length>0)return Sn(e,t,n,`skill`);if(!n||!mn())throw Error(`Name the skills to add, like ${R(`add my-skill`)}.`);let r=hn(await Rt({message:`Which skills?`,options:e.map(e=>({value:e.id,label:kn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const xn=(e,t,n)=>Sn(e,t,n,`kit`);async function Sn(e,t,n,r){let i=[];for(let a of t){let t=En(e,a,r),o=t.length===1?t[0]:await Dn(t,n,r);i.includes(o)||i.push(o)}return i}const Cn=(e,t)=>En(e,t,`skill`);function wn(e,t){let n=t.lastIndexOf(`/`),r=t.slice(n+1),i=n===-1?null:t.slice(0,n).trim().toLowerCase();return e.filter(e=>e.name===r&&(i===null||e.organizationName.toLowerCase()===i||e.organizationSlug!=null&&e.organizationSlug===i))}const Tn=(e,t)=>wn(e,t);function En(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=wn(e,t);if(a.length===0)throw Error(r===-1?`There's no ${n} named "${i}" in your agent kit. See them with ${R(`list`)}.`:`There's no ${n} named "${i}" in an organization called "${t.slice(0,r)}". See them with ${R(`list`)}.`);return a}async function Dn(e,t,n){let r=e[0].name,i=n===`kit`?vn:``;if(!t||!mn()){let t=e.map(e=>{let t=i+On(e);return R(`add ${/\s/.test(t)?`"${t}"`:t}`)});throw Error(`More than one of your organizations has a ${n} named "${r}". Say which one: ${t.join(` or `)}.`)}let a=hn(await Kt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:On(e)}))}));return e.find(e=>e.id===a)}const On=e=>`${e.organizationName}/${e.name}`,kn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function V(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function An(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function H(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?_(process.env.APPDATA,`agent-kit`):_(process.env.XDG_CONFIG_HOME??_(C(),`.config`),`agent-kit`)}const jn=()=>_(H(),`credentials.json`);async function Mn(){try{return JSON.parse(await O(jn(),`utf8`))}catch{return{}}}async function U(){return(await Mn())[V()]??null}async function Nn(e){let t=await Mn();e?t[V()]=e:delete t[V()];let n=jn();await D(g(n),{recursive:!0,mode:448}),await A(n,JSON.stringify(t,null,2)+`
76
+ `,{mode:384}),await te(n,384)}const Pn=()=>_(H(),`settings.json`);async function W(){try{return JSON.parse(await O(Pn(),`utf8`))}catch{return{}}}async function Fn(e){let t={...await W(),...e};await D(H(),{recursive:!0,mode:448}),await A(Pn(),JSON.stringify(t,null,2)+`
77
+ `)}function In(e=process.env){let t=e=>e!==void 0&&[`0`,`false`,`off`,`no`].includes(e.toLowerCase());return(e=>e!==void 0&&e!==``&&!t(e))(e.DO_NOT_TRACK)||t(e.AGENT_KIT_TELEMETRY)}function G(e){let t=y(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const Ln=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Rn(e){return e.split(`/`).some(e=>Ln.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const zn=e=>de(`sha256`).update(e).digest(`hex`);async function Bn(e){let t=await k(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=y(e,_(r.parentPath,r.name)).split(x).join(`/`);if(Rn(t))continue;let i=new Uint8Array(await O(_(e,t)));n.push({path:t,size:i.byteLength,sha256:zn(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Vn(e,t){let n=new Map(t.filter(e=>!Rn(e.path)).map(e=>[e.path,e.sha256])),r=new Set(e.map(e=>e.path)),i=e.filter(e=>n.get(e.path)!==e.sha256),a=[...n.keys()].filter(e=>!r.has(e));return{upserts:i,deletes:a,paths:[...i.map(e=>e.path),...a].sort()}}function Hn(e){return e.length===0?`nothing`:e.length>3?`${e.length} files`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e.at(-1)}`}async function Un(e,t){for(let n of e){if(!f(n))continue;let{paths:e}=Vn(await Bn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Wn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?Un(r.map(e=>_(e,t)),i.files):null}async function Gn(e){try{if(!(await ie(e)).isSymbolicLink())return null}catch{return null}return b(g(e),await ae(e))}async function Kn(e,t){for(let n of e){let e=await Gn(_(n,t));if(e)return e}return null}async function qn(e,t){await se(e,{recursive:!0,force:!0}),await D(g(e),{recursive:!0}),await le(t,e,process.platform===`win32`?`junction`:`dir`)}const K=`SKILL.md`,Jn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},Yn=/[\u0000-\u001f\u007f\\:]/;function Xn(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Jn.maxPathLength)return`Paths can be at most ${Jn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if(Yn.test(e))return`Paths can't contain \\, : or control characters.`;for(let t of e.split(`/`)){if(t===``)return`The path has an empty folder name (//).`;if(t===`.`||t===`..`)return`The path can't contain . or .. folders.`;if(t!==t.trim())return`Names can't start or end with a space.`}return null}function Zn(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function Qn(e){return e.slice(e.lastIndexOf(`/`)+1)}function $n(e,t){let n=Zn(e)?Zn(e).split(`/`):[];for(let e of t.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){if(n.length===0)return null;n.pop()}else n.push(e)}return n.join(`/`)}var q=/* @__PURE__ */ j((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),er=/* @__PURE__ */ j((e=>{var t=q();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),tr=/* @__PURE__ */ j((e=>{var t=q(),n=er();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||e&&!a.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join(`
78
+ `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),nr=/* @__PURE__ */ j((e=>{var t=q(),n=er();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=/* @__PURE__ */ new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=/* @__PURE__ */ new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=/* @__PURE__ */ Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),rr=/* @__PURE__ */ j((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),ir=/* @__PURE__ */ j((e=>{var t=q();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),ar=/* @__PURE__ */ j((e=>{var t=rr(),n=q(),r=ir();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:/* @__PURE__ */ new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),or=/* @__PURE__ */ j((e=>{var t=nr(),n=er(),r=q(),i=ar(),a=ir(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
79
79
  /* istanbul ignore if */
80
- if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=s(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),q=/* @__PURE__ */ A((e=>{var t=K(),n=lr(),r=cr();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),dr=/* @__PURE__ */ A((e=>{var t=ur(),n=K(),r=q();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),fr=/* @__PURE__ */ A((e=>{var t=dr(),n=K(),r=lr();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=/* @__PURE__ */ new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:/* @__PURE__ */ new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),pr=/* @__PURE__ */ A((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
80
+ if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=s(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),J=/* @__PURE__ */ j((e=>{var t=q(),n=ar(),r=ir();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),sr=/* @__PURE__ */ j((e=>{var t=or(),n=q(),r=J();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),cr=/* @__PURE__ */ j((e=>{var t=sr(),n=q(),r=ar();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=/* @__PURE__ */ new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:/* @__PURE__ */ new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),lr=/* @__PURE__ */ j((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
81
81
  `)?n(r,t):r.includes(`
82
82
  `)?`
83
- `+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),mr=/* @__PURE__ */ A((e=>{let t=`block`,n=`quoted`;function r(e,r,a=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-r.length);if(e.length<=d)return e;let f=[],p={},m=s-r.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;a===t&&(v=i(e,v,r.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(a===n&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
83
+ `+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),ur=/* @__PURE__ */ j((e=>{let t=`block`,n=`quoted`;function r(e,r,a=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-r.length);if(e.length<=d)return e;let f=[],p={},m=s-r.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;a===t&&(v=i(e,v,r.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(a===n&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
84
84
  `)a===t&&(v=i(e,v,r.length)),m=v+r.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
85
85
  `&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
86
86
  `&&t!==` `&&(h=v)}if(v>=m){if(h)f.push(h),m=h+d,h=void 0;else if(a===n){for(;g===` `||g===` `;)g=o,o=e[v+=1],_=!0;let t=v>b+1?v-2:y-1;if(p[t])return e;f.push(t),p[t]=!0,m=t+d,h=void 0}else _=!0}}g=o}if(_&&u&&u(),f.length===0)return e;l&&l();let x=e.slice(0,f[0]);for(let t=0;t<f.length;++t){let i=f[t],o=f[t+1]||e.length;i===0?x=`\n${r}${e.slice(0,o)}`:(a===n&&p[i]&&(x+=`${e[i]}\\`),x+=`\n${r}${e.slice(i+1,o)}`)}return x}function i(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
87
- `);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=t,e.FOLD_FLOW=`flow`,e.FOLD_QUOTED=n,e.foldFlowLines=r})),hr=/* @__PURE__ */ A((e=>{var t=q(),n=mr();let r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
87
+ `);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=t,e.FOLD_FLOW=`flow`,e.FOLD_QUOTED=n,e.foldFlowLines=r})),dr=/* @__PURE__ */ j((e=>{var t=J(),n=ur();let r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
88
88
  `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function o(e,t){let a=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return a;let{implicitKey:o}=t,s=t.options.doubleQuotedMinMultiLineLength,c=t.indent||(i(e)?` `:``),l=``,u=0;for(let e=0,t=a[e];t;t=a[++e])if(t===` `&&a[e+1]===`\\`&&a[e+2]===`n`&&(l+=a.slice(u,e)+`\\ `,e+=1,u=e,t=`\\`),t===`\\`)switch(a[e+1]){case`u`:{l+=a.slice(u,e);let t=a.substr(e+2,4);switch(t){case`0000`:l+=`\\0`;break;case`0007`:l+=`\\a`;break;case`000b`:l+=`\\v`;break;case`001b`:l+=`\\e`;break;case`0085`:l+=`\\N`;break;case`00a0`:l+=`\\_`;break;case`2028`:l+=`\\L`;break;case`2029`:l+=`\\P`;break;default:t.substr(0,2)===`00`?l+=`\\x`+t.substr(2):l+=a.substr(e,6)}e+=5,u=e+1}break;case`n`:if(o||a[e+2]===`"`||a.length<s)e+=1;else{for(l+=a.slice(u,e)+`
89
89
 
90
90
  `;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
@@ -102,29 +102,29 @@ if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This sh
102
102
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${E}\n${g}${c}`}return s=s.replace(/\n+/g,`$&${g}`),`|${E}\n${g}${T}${s}${b}`}function d(e,a,o,s){let{type:l,value:d}=e,{actualString:f,implicitKey:p,indent:m,indentStep:h,inFlow:g}=a;if(p&&d.includes(`
103
103
  `)||g&&/[[\]{},]/.test(d))return c(d,a);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return p||g||!d.includes(`
104
104
  `)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
105
- `))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),gr=/* @__PURE__ */ A((e=>{var t=or(),n=K(),r=pr(),i=hr();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:/* @__PURE__ */ new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=/* @__PURE__ */ new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),_r=/* @__PURE__ */ A((e=>{var t=K(),n=q(),r=gr(),i=pr();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
105
+ `))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),fr=/* @__PURE__ */ j((e=>{var t=nr(),n=q(),r=lr(),i=dr();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:/* @__PURE__ */ new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=/* @__PURE__ */ new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),pr=/* @__PURE__ */ j((e=>{var t=q(),n=J(),r=fr(),i=lr();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
106
106
  `:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
107
107
  `&&C&&(E=`
108
108
 
109
109
  `):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
110
110
  `),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(E=`\n${o.indent}`)}}else(T===``||T[0]===`
111
- `)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),vr=/* @__PURE__ */ A((e=>{var t=Ee(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),yr=/* @__PURE__ */ A((e=>{var t=K(),n=q();let r={identify:e=>e===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(`<<`)),{addToJSMap:a}),stringify:()=>`<<`},i=(e,i)=>(r.identify(i)||t.isScalar(i)&&(!i.type||i.type===n.Scalar.PLAIN)&&r.identify(i.value))&&e?.doc.schema.tags.some(e=>e.tag===r.tag&&e.default);function a(e,n,r){let i=s(e,r);if(t.isSeq(i))for(let t of i.items)o(e,n,t);else if(Array.isArray(i))for(let t of i)o(e,n,t);else o(e,n,i)}function o(e,n,r){let i=s(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function s(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=a,e.isMergeKey=i,e.merge=r})),br=/* @__PURE__ */ A((e=>{var t=vr(),n=yr(),r=gr(),i=K(),a=cr();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=/* @__PURE__ */ new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),xr=/* @__PURE__ */ A((e=>{var t=dr(),n=_r(),r=br(),i=K();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?/* @__PURE__ */ new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),Sr=/* @__PURE__ */ A((e=>{var t=K(),n=gr(),r=pr();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
111
+ `)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),mr=/* @__PURE__ */ j((e=>{var t=Se(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),hr=/* @__PURE__ */ j((e=>{var t=q(),n=J();let r={identify:e=>e===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(`<<`)),{addToJSMap:a}),stringify:()=>`<<`},i=(e,i)=>(r.identify(i)||t.isScalar(i)&&(!i.type||i.type===n.Scalar.PLAIN)&&r.identify(i.value))&&e?.doc.schema.tags.some(e=>e.tag===r.tag&&e.default);function a(e,n,r){let i=s(e,r);if(t.isSeq(i))for(let t of i.items)o(e,n,t);else if(Array.isArray(i))for(let t of i)o(e,n,t);else o(e,n,i)}function o(e,n,r){let i=s(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function s(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=a,e.isMergeKey=i,e.merge=r})),gr=/* @__PURE__ */ j((e=>{var t=mr(),n=hr(),r=fr(),i=q(),a=ir();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=/* @__PURE__ */ new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),_r=/* @__PURE__ */ j((e=>{var t=sr(),n=pr(),r=gr(),i=q();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?/* @__PURE__ */ new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),vr=/* @__PURE__ */ j((e=>{var t=q(),n=fr(),r=lr();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
112
112
  `}}return e?(_+=`
113
113
  `+r.indentComment(p(e),f),d&&d()):h&&u&&u(),_}function o({items:e},i,{flowChars:a,itemIndent:o}){let{indent:c,indentStep:l,flowCollectionPadding:u,options:{commentString:d}}=i;o+=l;let f=Object.assign({},i,{indent:o,inFlow:!0,type:null}),p=!1,m=0,h=[];for(let a=0;a<e.length;++a){let c=e[a],l=null;if(t.isNode(c))c.spaceBefore&&h.push(``),s(i,h,c.commentBefore,!1),c.comment&&(l=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(e.spaceBefore&&h.push(``),s(i,h,e.commentBefore,!1),e.comment&&(p=!0));let n=t.isNode(c.value)?c.value:null;n?(n.comment&&(l=n.comment),n.commentBefore&&(p=!0)):c.value==null&&e?.comment&&(l=e.comment)}l&&(p=!0);let u=n.stringify(c,f,()=>l=null);p||=h.length>m||u.includes(`
114
114
  `),a<e.length-1?u+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(p||=h.reduce((e,t)=>e+t.length+2,2)+(u.length+2)>i.options.lineWidth),p&&(u+=`,`)),l&&(u+=r.lineComment(u,o,d(l))),h.push(u),m=h.length}let{start:g,end:_}=a;if(h.length===0)return g+_;if(!p){let e=h.reduce((e,t)=>e+t.length+2,2);p=i.options.lineWidth>0&&e>i.options.lineWidth}if(p){let e=g;for(let t of h)e+=t?`\n${l}${c}${t}`:`
115
- `;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),Cr=/* @__PURE__ */ A((e=>{var t=Sr(),n=br(),r=fr(),i=K(),a=xr(),o=q();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?/* @__PURE__ */ new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),wr=/* @__PURE__ */ A((e=>{var t=K(),n=Cr();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),Tr=/* @__PURE__ */ A((e=>{var t=dr(),n=Sr(),r=fr(),i=K(),a=q(),o=cr(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),Er=/* @__PURE__ */ A((e=>{var t=K(),n=Tr();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),Dr=/* @__PURE__ */ A((e=>{var t=hr();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),Or=/* @__PURE__ */ A((e=>{var t=q();let n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),kr=/* @__PURE__ */ A((e=>{var t=q();let n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),Ar=/* @__PURE__ */ A((e=>{function t({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=t})),jr=/* @__PURE__ */ A((e=>{var t=q(),n=Ar();let r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Mr=/* @__PURE__ */ A((e=>{var t=Ar();let n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),Nr=/* @__PURE__ */ A((e=>{var t=wr(),n=Or(),r=Er(),i=Dr(),a=kr(),o=jr(),s=Mr();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),Pr=/* @__PURE__ */ A((e=>{var t=q(),n=wr(),r=Er();function i(e){return typeof e==`bigint`||Number.isInteger(e)}let a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>i(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),Fr=/* @__PURE__ */ A((e=>{var t=Ee(`buffer`),n=q(),r=hr();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
116
- `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Ir=/* @__PURE__ */ A((e=>{var t=K(),n=xr(),r=q(),i=Tr();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}let s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),Lr=/* @__PURE__ */ A((e=>{var t=K(),n=cr(),r=Cr(),i=Tr(),a=Ir(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=/* @__PURE__ */ new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;let s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),Rr=/* @__PURE__ */ A((e=>{var t=q();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}let r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),zr=/* @__PURE__ */ A((e=>{var t=q(),n=Ar();let r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Br=/* @__PURE__ */ A((e=>{var t=Ar();let n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}let a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),Vr=/* @__PURE__ */ A((e=>{var t=K(),n=xr(),r=Cr(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;let a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Hr=/* @__PURE__ */ A((e=>{var t=Ar();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),Ur=/* @__PURE__ */ A((e=>{var t=wr(),n=Or(),r=Er(),i=Dr(),a=Fr(),o=Rr(),s=zr(),c=Br(),l=yr(),u=Lr(),d=Ir(),f=Vr(),p=Hr();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Wr=/* @__PURE__ */ A((e=>{var t=wr(),n=Or(),r=Er(),i=Dr(),a=kr(),o=jr(),s=Mr(),c=Nr(),l=Pr(),u=Fr(),d=yr(),f=Lr(),p=Ir(),m=Ur(),h=Vr(),g=Hr();let _=/* @__PURE__ */ new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Gr=/* @__PURE__ */ A((e=>{var t=K(),n=wr(),r=Er(),i=Dr(),a=Wr();let o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),Kr=/* @__PURE__ */ A((e=>{var t=K(),n=gr(),r=pr();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
115
+ `;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),yr=/* @__PURE__ */ j((e=>{var t=vr(),n=gr(),r=cr(),i=q(),a=_r(),o=J();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?/* @__PURE__ */ new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),br=/* @__PURE__ */ j((e=>{var t=q(),n=yr();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),xr=/* @__PURE__ */ j((e=>{var t=sr(),n=vr(),r=cr(),i=q(),a=J(),o=ir(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),Sr=/* @__PURE__ */ j((e=>{var t=q(),n=xr();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),Cr=/* @__PURE__ */ j((e=>{var t=dr();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),wr=/* @__PURE__ */ j((e=>{var t=J();let n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),Tr=/* @__PURE__ */ j((e=>{var t=J();let n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),Er=/* @__PURE__ */ j((e=>{function t({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=t})),Dr=/* @__PURE__ */ j((e=>{var t=J(),n=Er();let r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Or=/* @__PURE__ */ j((e=>{var t=Er();let n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),kr=/* @__PURE__ */ j((e=>{var t=br(),n=wr(),r=Sr(),i=Cr(),a=Tr(),o=Dr(),s=Or();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),Ar=/* @__PURE__ */ j((e=>{var t=J(),n=br(),r=Sr();function i(e){return typeof e==`bigint`||Number.isInteger(e)}let a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>i(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),jr=/* @__PURE__ */ j((e=>{var t=Se(`buffer`),n=J(),r=dr();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
116
+ `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Mr=/* @__PURE__ */ j((e=>{var t=q(),n=_r(),r=J(),i=xr();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}let s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),Nr=/* @__PURE__ */ j((e=>{var t=q(),n=ir(),r=yr(),i=xr(),a=Mr(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=/* @__PURE__ */ new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;let s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),Pr=/* @__PURE__ */ j((e=>{var t=J();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}let r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),Fr=/* @__PURE__ */ j((e=>{var t=J(),n=Er();let r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Ir=/* @__PURE__ */ j((e=>{var t=Er();let n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}let a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),Lr=/* @__PURE__ */ j((e=>{var t=q(),n=_r(),r=yr(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;let a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Rr=/* @__PURE__ */ j((e=>{var t=Er();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),zr=/* @__PURE__ */ j((e=>{var t=br(),n=wr(),r=Sr(),i=Cr(),a=jr(),o=Pr(),s=Fr(),c=Ir(),l=hr(),u=Nr(),d=Mr(),f=Lr(),p=Rr();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Br=/* @__PURE__ */ j((e=>{var t=br(),n=wr(),r=Sr(),i=Cr(),a=Tr(),o=Dr(),s=Or(),c=kr(),l=Ar(),u=jr(),d=hr(),f=Nr(),p=Mr(),m=zr(),h=Lr(),g=Rr();let _=/* @__PURE__ */ new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Vr=/* @__PURE__ */ j((e=>{var t=q(),n=br(),r=Sr(),i=Cr(),a=Br();let o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),Hr=/* @__PURE__ */ j((e=>{var t=q(),n=fr(),r=lr();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
117
117
  `)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
118
118
  `)+`
119
- `}e.stringifyDocument=i})),qr=/* @__PURE__ */ A((e=>{var t=ur(),n=fr(),r=K(),i=xr(),a=cr(),o=Gr(),s=Kr(),c=or(),l=sr(),u=dr(),d=ar(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:/* @__PURE__ */ new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),Jr=/* @__PURE__ */ A((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
120
- `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),Yr=/* @__PURE__ */ A((e=>{function t(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:b&&n===`seq-item-ind`||(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=t})),Xr=/* @__PURE__ */ A((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
121
- `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),Zr=/* @__PURE__ */ A((e=>{var t=Xr();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),Qr=/* @__PURE__ */ A((e=>{var t=K();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),$r=/* @__PURE__ */ A((e=>{var t=xr(),n=Cr(),r=Yr(),i=Xr(),a=Zr(),o=Qr();let s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
119
+ `}e.stringifyDocument=i})),Ur=/* @__PURE__ */ j((e=>{var t=or(),n=cr(),r=q(),i=_r(),a=ir(),o=Vr(),s=Hr(),c=nr(),l=rr(),u=sr(),d=tr(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:/* @__PURE__ */ new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),Wr=/* @__PURE__ */ j((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
120
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),Gr=/* @__PURE__ */ j((e=>{function t(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:b&&n===`seq-item-ind`||(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=t})),Kr=/* @__PURE__ */ j((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
121
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),qr=/* @__PURE__ */ j((e=>{var t=Kr();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),Jr=/* @__PURE__ */ j((e=>{var t=q();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),Yr=/* @__PURE__ */ j((e=>{var t=_r(),n=yr(),r=Gr(),i=Kr(),a=qr(),o=Jr();let s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
122
122
  `+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
123
- `+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),ei=/* @__PURE__ */ A((e=>{var t=Tr(),n=Yr(),r=Zr();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),ti=/* @__PURE__ */ A((e=>{function t(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=t})),ni=/* @__PURE__ */ A((e=>{var t=K(),n=xr(),r=Cr(),i=Tr(),a=ti(),o=Yr(),s=Xr(),c=Qr();let l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
123
+ `+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),Xr=/* @__PURE__ */ j((e=>{var t=xr(),n=Gr(),r=qr();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),Zr=/* @__PURE__ */ j((e=>{function t(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=t})),Qr=/* @__PURE__ */ j((e=>{var t=q(),n=_r(),r=yr(),i=xr(),a=Zr(),o=Gr(),s=Kr(),c=Jr();let l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
124
124
  `+C.comment:v.comment=C.comment),b=C.end;continue}!g&&f.options.strict&&s.containsNewline(y)&&m(y,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)C.comma&&m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`);else if(C.comma||m(C.start,`MISSING_CHAR`,`Missing , between ${_} items`),C.comment){let e=``;loop:for(let t of h)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
125
125
  `+e:n.comment=e,C.comment=C.comment.substring(e.length+1)}}if(!g&&!x&&!C.found){let t=S?e(f,S,C,m):d(f,C.end,x,null,C,m);v.items.push(t),b=t.range[2],u(S)&&m(t.range,`BLOCK_IN_FLOW`,l)}else{f.atKey=!0;let t=C.end,i=y?e(f,y,C,m):d(f,t,h,null,C,m);u(y)&&m(i.range,`BLOCK_IN_FLOW`,l),f.atKey=!1;let s=o.resolveProps(x??[],{flow:_,indicator:`map-value-ind`,next:S,offset:i.range[2],onError:m,parentIndent:p.indent,startOnNewline:!1});if(s.found){if(!g&&!C.found&&f.options.strict){if(x)for(let e of x){if(e===s.found)break;if(e.type===`newline`){m(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}C.start<s.found.offset-1024&&m(s.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else S&&(`source`in S&&S.source?.[0]===`:`?m(S,`MISSING_CHAR`,`Missing space after : in ${_}`):m(s.start,`MISSING_CHAR`,`Missing , or : between ${_} items`));let w=S?e(f,S,s,m):s.found?d(f,s.end,x,null,s,m):null;w?u(S)&&m(w.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
126
126
  `+s.comment:i.comment=s.comment);let T=new n.Pair(i,w);if(f.options.keepSourceTokens&&(T.srcToken=a),g){let e=v;c.mapIncludes(f,e.items,i)&&m(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(T)}else{let e=new r.YAMLMap(f.schema);e.flow=!0,e.items.push(T);let t=(w??i).range;e.range=[i.range[0],t[1],t[2]],v.items.push(e)}b=w?w.range[2]:s.end}}let x=g?`}`:`]`,[S,...C]=p.end,w=b;if(S?.source===x)w=S.offset+S.source.length;else{let e=_[0].toUpperCase()+_.substring(1),t=y?`${e} must end with a ${x}`:`${e} in block collection must be sufficiently indented and end with a ${x}`;m(b,y?`MISSING_CHAR`:`BAD_INDENT`,t),S&&S.source.length!==1&&C.unshift(S)}if(C.length>0){let e=a.resolveEnd(C,w,f.options.strict,m);e.comment&&(v.comment?v.comment+=`
127
- `+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),ri=/* @__PURE__ */ A((e=>{var t=K(),n=q(),r=Cr(),i=Tr(),a=$r(),o=ei(),s=ni();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),ii=/* @__PURE__ */ A((e=>{var t=q();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
127
+ `+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),$r=/* @__PURE__ */ j((e=>{var t=q(),n=J(),r=yr(),i=xr(),a=Yr(),o=Xr(),s=Qr();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),ei=/* @__PURE__ */ j((e=>{var t=J();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
128
128
  `.repeat(Math.max(1,l.length-1)):``,t=o+s.length;return n.source&&(t+=n.source.length),{value:e,type:c,comment:s.comment,range:[o,t,t]}}let d=n.indent+s.indent,f=n.offset+s.length,p=0;for(let t=0;t<u;++t){let[n,r]=l[t];if(r===``||r===`\r`)s.indent===0&&n.length>d&&(d=n.length);else{n.length<d&&a(f+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),s.indent===0&&(d=n.length),p=t,d===0&&!e.atRoot&&a(f,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}f+=n.length+r.length+1}for(let e=l.length-1;e>=u;--e)l[e][0].length>d&&(u=e+1);let m=``,h=``,g=!1;for(let e=0;e<p;++e)m+=l[e][0].slice(d)+`
129
129
  `;for(let e=p;e<u;++e){let[n,r]=l[e];f+=n.length+r.length+1;let i=r[r.length-1]===`\r`;
130
130
  /* istanbul ignore if already caught in lexer */
@@ -145,7 +145,7 @@ if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be les
145
145
  /* istanbul ignore if should not happen */
146
146
  if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;
147
147
  /* istanbul ignore next should not happen */
148
- default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),ai=/* @__PURE__ */ A((e=>{var t=q(),n=ti();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;
148
+ default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),ti=/* @__PURE__ */ j((e=>{var t=J(),n=Zr();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;
149
149
  /* istanbul ignore next should not happen */
150
150
  default:return o(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${l}`),{value:``,type:null,comment:``,range:[c,c+u.length,c+u.length]}}let h=c+u.length,g=n.resolveEnd(d,h,r,o);return{value:p,type:f,comment:g.comment,range:[c,h,g.offset]}}function i(e,t){let n=``;switch(e[0]){
151
151
  /* istanbul ignore next should not happen */
@@ -162,10 +162,10 @@ case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;c
162
162
  `);)r===`
163
163
  `&&(n+=`
164
164
  `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}let l={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
165
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),oi=/* @__PURE__ */ A((e=>{var t=K(),n=q(),r=ii(),i=ai();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),si=/* @__PURE__ */ A((e=>{function t(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=t})),ci=/* @__PURE__ */ A((e=>{var t=ur(),n=K(),r=ri(),i=oi(),a=ti(),o=si();let s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),li=/* @__PURE__ */ A((e=>{var t=qr(),n=ci(),r=ti(),i=Yr();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),ui=/* @__PURE__ */ A((e=>{var t=Ee(`process`),n=ar(),r=qr(),i=Jr(),a=K(),o=li(),s=ti();function c(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
165
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),ni=/* @__PURE__ */ j((e=>{var t=q(),n=J(),r=ei(),i=ti();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),ri=/* @__PURE__ */ j((e=>{function t(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=t})),ii=/* @__PURE__ */ j((e=>{var t=or(),n=q(),r=$r(),i=ni(),a=Zr(),o=ri();let s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),ai=/* @__PURE__ */ j((e=>{var t=Ur(),n=ii(),r=Zr(),i=Gr();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),oi=/* @__PURE__ */ j((e=>{var t=Se(`process`),n=tr(),r=Ur(),i=Wr(),a=q(),o=ai(),s=Zr();function c(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
166
166
 
167
167
  `:`
168
- `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),di=/* @__PURE__ */ A((e=>{var t=ii(),n=ai(),r=Jr(),i=hr();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
168
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),si=/* @__PURE__ */ j((e=>{var t=ei(),n=ti(),r=Wr(),i=dr();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
169
169
  `}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
170
170
  `),t=c.substring(0,e),n=c.substring(e+1)+`
171
171
  `,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
@@ -173,11 +173,11 @@ case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;c
173
173
  `),r=t.substring(0,n),i=t.substring(n+1)+`
174
174
  `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];l(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
175
175
  `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function l(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function u(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
176
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),fi=/* @__PURE__ */ A((e=>{let t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),pi=/* @__PURE__ */ A((e=>{let t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),mi=/* @__PURE__ */ A((e=>{var t=di(),n=fi(),r=pi();let i=e=>!!e&&`items`in e,a=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);
176
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),ci=/* @__PURE__ */ j((e=>{let t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),li=/* @__PURE__ */ j((e=>{let t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),ui=/* @__PURE__ */ j((e=>{var t=si(),n=ci(),r=li();let i=e=>!!e&&`items`in e,a=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);
177
177
  /* istanbul ignore next */
178
178
  function o(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function s(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
179
179
  `:case`\r
180
- `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=``,e.DOCUMENT=``,e.FLOW_END=``,e.SCALAR=``,e.isCollection=i,e.isScalar=a,e.prettyToken=o,e.tokenType=s})),hi=/* @__PURE__ */ A((e=>{var t=mi();function n(e){switch(e){case void 0:case` `:case`
180
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=``,e.DOCUMENT=``,e.FLOW_END=``,e.SCALAR=``,e.isCollection=i,e.isScalar=a,e.prettyToken=o,e.tokenType=s})),di=/* @__PURE__ */ j((e=>{var t=ui();function n(e){switch(e){case void 0:case` `:case`
181
181
  `:case`\r`:case` `:return!0;default:return!1}}let r=/* @__PURE__ */ new Set(`0123456789ABCDEFabcdef`),i=/* @__PURE__ */ new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=/* @__PURE__ */ new Set(`,[]{}`),o=/* @__PURE__ */ new Set(` ,[]{}
182
182
  \r `),s=e=>!e||o.has(e);e.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
183
183
  `||t===`\r`&&this.buffer[e+1]===`
@@ -196,7 +196,7 @@ function o(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:re
196
196
  `,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
197
197
  `){let e=this.continueScalar(i+1);if(e===-1)break;i=Math.max(i,e-2)}}else{if(e&&a.has(o))break;r=i}return!o&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(r+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(s),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,r=this.charAt(1);if(n(r)||t&&a.has(r)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!n(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(i.has(t))t=this.buffer[++e];else if(t===`%`&&r.has(this.buffer[e+1])&&r.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
198
198
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
199
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),gi=/* @__PURE__ */ A((e=>{e.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}})),_i=/* @__PURE__ */ A((e=>{var t=Ee(`process`),n=mi(),r=hi();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function o(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function s(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;
199
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),fi=/* @__PURE__ */ j((e=>{e.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}})),pi=/* @__PURE__ */ j((e=>{var t=Se(`process`),n=ui(),r=di();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function o(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function s(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;
200
200
  /* istanbul ignore next should not happen */
201
201
  default:return[]}}function c(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function l(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function u(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i(t.start,`explicit-key-ind`)&&!i(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o(t.value)?t.value.end?l(t.value.end,t.sep):t.value.end=t.sep:l(t.start,t.sep),delete t.sep)}e.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}
202
202
  /* istanbul ignore next should not happen */
@@ -212,105 +212,53 @@ default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.l
212
212
  /* istanbul ignore else should not happen */
213
213
  n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
214
214
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
215
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),vi=/* @__PURE__ */ A((e=>{var t=ui(),n=qr(),r=Jr(),i=vr(),a=K(),o=gi(),s=_i();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),J=(/* @__PURE__ */ A((e=>{var t=ui(),n=qr(),r=Gr(),i=Jr(),a=ur(),o=K(),s=xr(),c=q(),l=Cr(),u=Tr();mi();var d=hi(),f=gi(),p=_i(),m=vi(),h=ir();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();const yi=/^---[ \t]*$/;function bi(e){let t=wi(e,0);if(!yi.test(e.slice(0,t).replace(/\r$/,``)))return`no-frontmatter`;let n=Ti(e,t),r=n;for(;n<e.length;){let t=wi(e,n);if(yi.test(e.slice(n,t).replace(/\r$/,``)))return{yamlFrom:r,yamlTo:n,bodyFrom:Ti(e,t)};n=Ti(e,t)}return`unclosed`}function xi(e){let t=bi(e);if(typeof t==`string`)return{ok:!1,reason:t};let n=e.slice(t.yamlFrom,t.yamlTo),r=(0,J.parseDocument)(n,{prettyErrors:!1}),i=e=>t.yamlFrom+e,a=r.errors.map(e=>({message:e.message.split(`
216
- `)[0],from:i(e.pos[0]),to:i(Math.max(e.pos[1],e.pos[0]+1))})),o=r.contents,s=o===null||(0,J.isMap)(o),c=[];if((0,J.isMap)(o)){let e=Ci(()=>r.toJS());for(let t of o.items){if(!(0,J.isScalar)(t.key)||!t.key.range)continue;let[n,r]=t.key.range,a=t.value?.range;c.push({key:String(t.key.value),keyFrom:i(n),keyTo:i(r),value:e?.[String(t.key.value)]??null,valueFrom:i(a?.[0]??r),valueTo:i(a?.[1]??r)})}}return{ok:!0,block:t,yamlErrors:a,isMapping:s,entries:c,body:e.slice(t.bodyFrom)}}function Si(e){let t=xi(e),n=e=>{if(!t.ok)return null;let n=t.entries.find(t=>t.key===e)?.value;return typeof n==`string`?n.trim():null};return{name:n(`name`),description:n(`description`)}}function Ci(e){try{let t=e();return t&&typeof t==`object`?t:null}catch{return null}}function wi(e,t){let n=e.indexOf(`
217
- `,t);return n===-1?e.length:n}function Ti(e,t){return Math.min(t+1,e.length)}const Ei=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,Di=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Oi(e,t){let n=[],r=e.slice(t);for(let e of r.matchAll(Ei)){let r=e[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(r))continue;let i=Mi(r.split(`#`)[0].split(`?`)[0]);if(i===``)continue;let a=t+e.index+e[0].indexOf(r);n.push({target:r,path:i,from:a,to:a+r.length})}return n}function ki(e){if(e.startsWith(`/`))return null;let t=[`\0self`];for(let n of e.split(`/`))if(n!==``&&n!==`.`){if(n===`..`){if(t.length===0)return null;t.pop()}else t.push(n)}let n=t[0];return n&&n!==`\0self`&&Di.test(n)?n:null}function Ai(e){let t=xi(e),n=t.ok?t.block.bodyFrom:0,r=[];for(let t of Oi(e,n)){let e=ki(t.path);e&&r.push({...t,name:e})}return r}function ji(e){let t=xi(e),n=t.ok?t.entries.find(e=>e.key===`name`)?.value:null,r=Ai(e).map(e=>e.name);return[...new Set(r)].filter(e=>e!==n)}function Mi(e){try{return decodeURIComponent(e)}catch{return e}}const Ni=`report-session-issue`,Pi=/skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;function Fi(e,t){if(e===`Skill`){let e=t?.skill;return typeof e==`string`?[Ii(e)]:[]}return[...(typeof t==`string`?t:JSON.stringify(t??``)).matchAll(Pi)].map(e=>e[1])}const Ii=e=>e.slice(e.lastIndexOf(`:`)+1).replace(/^\//,``);function Li(e){let t=e.events.findIndex(e=>Ri(e));if(t===-1)return e;let n=t;for(let r=t;r>=0;r--){let t=e.events[r];if(t.type===`user`&&t.message.content.some(e=>e.type===`text`)){n=r;break}}let r=e.events.slice(0,n);return{...e,events:r,loaded:[...new Set(r.flatMap(zi))]}}function Ri(e){return zi(e).includes(Ni)}function zi(e){return e.type===`system`?[]:e.message.content.flatMap(t=>t.type===`tool_use`?Fi(t.name,t.input):t.type===`text`&&e.type===`user`?[...t.text.matchAll(/<command-name>\/?([\w:-]+)<\/command-name>/g)].map(e=>Ii(e[1])):[])}const Bi=e=>e?ji(new TextDecoder().decode(e)):[];async function Vi(e,t,n,r,i){let a=[],o=[],s=new Set(n.map(e=>e.name)),c=[...n];for(;c.length>0;){let n=c.shift();for(let l of n.references){if(s.has(l))continue;s.add(l);let u=t.find(e=>e.name===l&&e.organizationId===n.organizationId);if(!u){o.push({name:l,by:n.name});continue}let d=Hi(u,r,i);a.push({skill:u,by:n.name,status:d}),d===`new`&&c.push({name:u.name,organizationId:u.organizationId,references:await Ui(e,u.id)})}}return{dependencies:a,missing:o}}function Hi(e,t,n){let r=t.skills[e.name];return r?r.id===e.id?`installed`:`conflict`:e.name===`report-session-issue`?`new`:n.some(t=>f(_(t,e.name)))?`conflict`:`new`}async function Ui(e,t){let n=(await e.getSkill(t)).files.find(e=>e.path===G);return n?Bi(await e.getBlob(t,n.sha256)):[]}async function Wi(e,t,n){let{dependencies:r,missing:i}=e;for(let{name:e,by:t}of i)F.warn(`${t} links to ${e}, which isn't in its organization.`);let a=r.filter(e=>e.status===`new`),o=r.filter(e=>e.status===`conflict`);if(a.length===0&&o.length===0)return[];let s=/* @__PURE__ */ new Map;for(let e of[...a,...o])s.set(e.by,[...s.get(e.by)??[],e.skill.name]);F.info([...s].map(([e,t])=>`${e} uses ${t.length===1?`another skill`:`${t.length} other skills`}: ${t.join(`, `)}`).join(`
218
- `));let c=n&&vn(),l=[];a.length>0&&(!c||yn(await zt({message:`Install ${a.length===1?a[0].skill.name:`these ${a.length} skills`} too?`,initialValue:!0})))&&l.push(...a.map(e=>e.skill));let u=t.map(W).join(`, `);for(let{skill:e}of o){let t=`There's already a different skill named ${e.name} in ${u}.`;c?yn(await zt({message:`${t} Replace it with the one from agent kit?`,initialValue:!1}))&&l.push(e):F.warn(`${t} Left it alone; \`a-kit add ${e.name}\` replaces it.`)}return l}const Gi=e=>he(`sha256`).update(e).digest(`hex`),Ki=(e,t)=>({getSkill:async n=>{let r=t&&t.ref===n?t:await e.getPublicSkill(n);return{...r,id:r.ref}},getBlob:(t,n)=>e.getPublicBlob(t,n)});async function qi(e,t,n,r=`latest`){let i=await e.getSkill(t,r);if(!/^[a-z0-9-]+$/.test(i.name))throw Error(`"${i.name}" isn't a valid skill name.`);let a=[];for(let t of i.files){let n=er(t.path);if(n)throw Error(`${i.name}: ${t.path}: ${n}`);let r=await e.getBlob(i.id,t.sha256);if(Gi(r)!==t.sha256)throw Error(`${i.name}: ${t.path} didn't download intact.`);a.push({path:t.path,bytes:r})}for(let e of n){let t=_(e,i.name);await de(t,{recursive:!0,force:!0});for(let e of a){let n=_(t,e.path);await D(g(n),{recursive:!0}),await k(n,e.bytes)}}let o=a.find(e=>e.path===G)?.bytes;return{...i,references:Bi(o)}}const Ji=(e,t,n)=>({id:e.id,version:e.version,agents:t,...n!==`latest`&&{channel:n}}),Yi=e=>$t(e.channel)?e.channel:`latest`,Y=(e,t=process.cwd())=>e===`global`?_(V(),`global.lock.json`):_(t,`agent-kit.lock.json`);async function X(e){try{let t=JSON.parse(await O(e,`utf8`));return{version:1,kits:t.kits??{},skills:t.skills??{},public:t.public??{}}}catch{return{version:1,kits:{},skills:{},public:{}}}}async function Xi(e,t){let n=e=>Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t))),r=Object.fromEntries(Object.entries(n(t.skills)).map(([e,t])=>{let{kits:n,...r}=t;return[e,n?.length?{...r,kits:[...n].sort()}:r]})),i=Object.keys(t.kits).length>0?n(t.kits):void 0,a=t.public&&Object.keys(t.public).length>0?n(t.public):void 0;await D(g(e),{recursive:!0}),await k(e,JSON.stringify({version:t.version,kits:i,skills:r,public:a},null,2)+`
219
- `)}const Zi=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];function Qi(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Zi(e,i.id);if(n===void 0){e.skills[i.name]?r.clashes.push(i):r.install.push(i);continue}let a=e.skills[n].kits;a&&!a.includes(t)&&r.tag.push(n)}let i=new Set(n.map(e=>e.id));for(let[n,a]of Object.entries(e.skills))a.kits?.includes(t)&&!i.has(a.id)&&(a.kits.length>1?r.untag.push(n):r.remove.push(n));return r}function $i(e,t,n){if(t===n)return;let r=e.kits[t];if(r){delete e.kits[t],e.kits[n]=r;for(let r of Object.values(e.skills))r.kits?.includes(t)&&(r.kits=[...new Set(r.kits.map(e=>e===t?n:e))])}}async function ea(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Qi(t,n.name,n.skills),a={installed:[],removed:[],skipped:[],kept:[]};for(let e of i.clashes)F.warn(`${e.name} from kit/${n.name} wasn't installed: another skill named ${e.name} already is.`),a.skipped.push(e.name);for(let e of i.tag){let r=t.skills[e];r.kits=[...r.kits??[],n.name]}for(let e of i.untag){let r=t.skills[e];r.kits=r.kits.filter(e=>e!==n.name)}let o=new Set(i.install.map(e=>e.id)),s=r.reinstall?n.skills.filter(e=>!i.clashes.some(t=>t.id===e.id)):i.install,c=qt();for(let i of s){let s=Zi(t,i.id),l=s?t.skills[s]:void 0,u=l&&!l.kits?l.agents:r.agents;c.start(`Installing ${i.name}`);let d;try{d=await qi(e,i.id,r.dirsOf(u))}catch(e){throw c.error(`${i.name} failed`),e}c.stop(`${d.name} v${d.version}`),s&&s!==d.name&&delete t.skills[s],delete t.public?.[d.name],t.skills[d.name]={id:d.id,version:d.version,agents:u,kits:o.has(i.id)?[n.name]:l?.kits&&[.../* @__PURE__ */ new Set([...l.kits,n.name])]},o.has(i.id)&&a.installed.push(d.name)}for(let o of i.remove){let i=t.skills[o],s=await Xn(r.dirsOf(i.agents),o);if(s){F.warn(`${o} was taken out of kit/${n.name}, but it uses ${W(s)} (\`a-kit link\`); left it.`),a.kept.push(o);continue}let c=await Jn(e,o,i,r.dirsOf(i.agents));c?(F.warn(`${o} was taken out of kit/${n.name}, but it has edits here that aren't in agent kit (${Kn(c.paths)}); left it. To keep them, make them in your organization's repository; otherwise delete its folder.`),a.kept.push(o)):(await ta(t,o,r.dirsOf),a.removed.push(o))}return a}async function ta(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await de(_(e,t),{recursive:!0,force:!0});delete e.skills[t]}function na(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const ra=e=>na(e)!==null;function ia(e,t){let n=[],r=[];for(let i of t)ra(i)&&kn(e,i).length===0?r.push(i):n.push(i);return{own:n,others:r}}async function aa(e,t,n){let r=[];for(let i of t){let t=na(i);try{let n=await e.getPublicSkill(`${t.org}/${t.name}`);r.some(e=>e.ref===n.ref)||r.push(n)}catch(e){throw e instanceof R&&e.status===404?Error(n?`There's no skill "${i}" in your organizations, and no public one. See yours with ${L(`list`)}.`:`There's no public skill "${i}". If it's one of your organization's, log in first: ${L(`login`)}.`):e}}return r}async function oa(e,t,n,r,i){let a=qt();for(let o of n){if(t.skills[o.name])throw Error(`You already have a skill named "${o.name}" installed from your organization; ${o.ref} would replace it. Remove it first.`);a.start(`Installing ${o.ref}`);try{let n=await qi(Ki(e,o),o.ref,i);t.public??={},t.public[n.name]={ref:n.ref,version:n.version,agents:r},a.stop(`${n.name} v${n.version} (${n.ref})`)}catch(e){throw a.error(`${o.ref} failed`),e}await e.countInstall(o.ref).catch(()=>{})}}function sa(e){let[t,n]=process.platform===`darwin`?[`open`,[e]]:process.platform===`win32`?[`cmd`,[`/c`,`start`,``,e.replace(/&/g,`^&`)]]:[`xdg-open`,[e]];try{let e=xe(t,n,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}const ca=()=>_(V(),`bin`,`a-kit.mjs`);function la(){let e=Se(import.meta.url);return e.endsWith(`.mjs`)?e:null}async function ua(e){let t=ca();return await D(g(t),{recursive:!0}),e!==t&&await ae(e,t),t}const da=(e,t)=>{try{return be(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:500}).trim()}catch{return null}};let fa;function pa(e={platform:T(),read:da,hostname:w}){if(e.platform===`darwin`)for(let t of[`ComputerName`,`LocalHostName`]){let n=e.read(`scutil`,[`--get`,t]);if(n)return n}try{return e.hostname().trim()||null}catch{return null}}function ma(){return fa===void 0&&(fa=pa()),fa}async function ha(e,t,n=[],{batch:r=100,batchLength:i=1/0,keyOf:a}={}){let o=`${e}.${process.pid}`,s=[];try{await ue(e,o),s=va(await O(o,`utf8`)),await de(o,{force:!0})}catch{}let c=[...s,...Array.isArray(n)?n:[n]];if(a){let e=new Map(c.map((e,t)=>[a(e),t]));c=c.filter((t,n)=>e.get(a(t))===n)}c=c.slice(-500);let l=0;for(let n=0,a=0;n<c.length;n=a){let o=0;for(a=n;a<n+r&&a<c.length&&(o+=JSON.stringify(c[a]).length,!(a>n&&o>i));)a++;let s=c.slice(n,a);try{await t(s),l+=s.length}catch(t){if(!_a(t))continue;let r=c.slice(n);return await D(g(e),{recursive:!0,mode:448}),await ne(e,r.map(e=>JSON.stringify(e)).join(`
215
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),mi=/* @__PURE__ */ j((e=>{var t=oi(),n=Ur(),r=Wr(),i=mr(),a=q(),o=fi(),s=pi();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),hi=(/* @__PURE__ */ j((e=>{var t=oi(),n=Ur(),r=Vr(),i=Wr(),a=or(),o=q(),s=_r(),c=J(),l=yr(),u=xr();ui();var d=di(),f=fi(),p=pi(),m=mi(),h=er();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();const gi=/^---[ \t]*$/;function _i(e){let t=xi(e,0);if(!gi.test(e.slice(0,t).replace(/\r$/,``)))return`no-frontmatter`;let n=Si(e,t),r=n;for(;n<e.length;){let t=xi(e,n);if(gi.test(e.slice(n,t).replace(/\r$/,``)))return{yamlFrom:r,yamlTo:n,bodyFrom:Si(e,t)};n=Si(e,t)}return`unclosed`}function vi(e){let t=_i(e);if(typeof t==`string`)return{ok:!1,reason:t};let n=e.slice(t.yamlFrom,t.yamlTo),r=(0,hi.parseDocument)(n,{prettyErrors:!1}),i=e=>t.yamlFrom+e,a=r.errors.map(e=>({message:e.message.split(`
216
+ `)[0],from:i(e.pos[0]),to:i(Math.max(e.pos[1],e.pos[0]+1))})),o=r.contents,s=o===null||(0,hi.isMap)(o),c=[];if((0,hi.isMap)(o)){let e=bi(()=>r.toJS());for(let t of o.items){if(!(0,hi.isScalar)(t.key)||!t.key.range)continue;let[n,r]=t.key.range,a=t.value?.range;c.push({key:String(t.key.value),keyFrom:i(n),keyTo:i(r),value:e?.[String(t.key.value)]??null,valueFrom:i(a?.[0]??r),valueTo:i(a?.[1]??r)})}}return{ok:!0,block:t,yamlErrors:a,isMapping:s,entries:c,body:e.slice(t.bodyFrom)}}function yi(e){let t=vi(e),n=e=>{if(!t.ok)return null;let n=t.entries.find(t=>t.key===e)?.value;return typeof n==`string`?n.trim():null};return{name:n(`name`),description:n(`description`)}}function bi(e){try{let t=e();return t&&typeof t==`object`?t:null}catch{return null}}function xi(e,t){let n=e.indexOf(`
217
+ `,t);return n===-1?e.length:n}function Si(e,t){return Math.min(t+1,e.length)}const Ci=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,wi=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ti(e,t){let n=[],r=e.slice(t);for(let e of r.matchAll(Ci)){let r=e[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(r))continue;let i=ki(r.split(`#`)[0].split(`?`)[0]);if(i===``)continue;let a=t+e.index+e[0].indexOf(r);n.push({target:r,path:i,from:a,to:a+r.length})}return n}function Ei(e){if(e.startsWith(`/`))return null;let t=[`\0self`];for(let n of e.split(`/`))if(n!==``&&n!==`.`){if(n===`..`){if(t.length===0)return null;t.pop()}else t.push(n)}let n=t[0];return n&&n!==`\0self`&&wi.test(n)?n:null}function Di(e){let t=vi(e),n=t.ok?t.block.bodyFrom:0,r=[];for(let t of Ti(e,n)){let e=Ei(t.path);e&&r.push({...t,name:e})}return r}function Oi(e){let t=vi(e),n=t.ok?t.entries.find(e=>e.key===`name`)?.value:null,r=Di(e).map(e=>e.name);return[...new Set(r)].filter(e=>e!==n)}function ki(e){try{return decodeURIComponent(e)}catch{return e}}const Ai=e=>e?Oi(new TextDecoder().decode(e)):[];async function ji(e,t,n,r,i){let a=[],o=[],s=new Set(n.map(e=>e.name)),c=[...n];for(;c.length>0;){let n=c.shift();for(let l of n.references){if(s.has(l))continue;s.add(l);let u=t.find(e=>e.name===l&&e.organizationId===n.organizationId);if(!u){o.push({name:l,by:n.name});continue}let d=Mi(u,r,i);a.push({skill:u,by:n.name,status:d}),d===`new`&&c.push({name:u.name,organizationId:u.organizationId,references:await Ni(e,u.id)})}}return{dependencies:a,missing:o}}function Mi(e,t,n){let r=t.skills[e.name];return r?r.id===e.id?`installed`:`conflict`:n.some(t=>f(_(t,e.name)))?`conflict`:`new`}async function Ni(e,t){let n=(await e.getSkill(t)).files.find(e=>e.path===K);return n?Ai(await e.getBlob(t,n.sha256)):[]}async function Pi(e,t,n){let{dependencies:r,missing:i}=e;for(let{name:e,by:t}of i)I.warn(`${t} links to ${e}, which isn't in its organization.`);let a=r.filter(e=>e.status===`new`),o=r.filter(e=>e.status===`conflict`);if(a.length===0&&o.length===0)return[];let s=/* @__PURE__ */ new Map;for(let e of[...a,...o])s.set(e.by,[...s.get(e.by)??[],e.skill.name]);I.info([...s].map(([e,t])=>`${e} uses ${t.length===1?`another skill`:`${t.length} other skills`}: ${t.join(`, `)}`).join(`
218
+ `));let c=n&&mn(),l=[];a.length>0&&(!c||hn(await Ft({message:`Install ${a.length===1?a[0].skill.name:`these ${a.length} skills`} too?`,initialValue:!0})))&&l.push(...a.map(e=>e.skill));let u=t.map(G).join(`, `);for(let{skill:e}of o){let t=`There's already a different skill named ${e.name} in ${u}.`;c?hn(await Ft({message:`${t} Replace it with the one from agent kit?`,initialValue:!1}))&&l.push(e):I.warn(`${t} Left it alone; \`a-kit add ${e.name}\` replaces it.`)}return l}const Fi=e=>de(`sha256`).update(e).digest(`hex`),Ii=(e,t)=>({getSkill:async n=>{let r=t&&t.ref===n?t:await e.getPublicSkill(n);return{...r,id:r.ref}},getBlob:(t,n)=>e.getPublicBlob(t,n)});async function Li(e,t,n,r=`latest`){let i=await e.getSkill(t,r);if(!/^[a-z0-9-]+$/.test(i.name))throw Error(`"${i.name}" isn't a valid skill name.`);let a=[];for(let t of i.files){let n=Xn(t.path);if(n)throw Error(`${i.name}: ${t.path}: ${n}`);let r=await e.getBlob(i.id,t.sha256);if(Fi(r)!==t.sha256)throw Error(`${i.name}: ${t.path} didn't download intact.`);a.push({path:t.path,bytes:r})}for(let e of n){let t=_(e,i.name);await se(t,{recursive:!0,force:!0});for(let e of a){let n=_(t,e.path);await D(g(n),{recursive:!0}),await A(n,e.bytes)}}let o=a.find(e=>e.path===K)?.bytes;return{...i,references:Ai(o)}}const Ri=(e,t,n)=>({id:e.id,version:e.version,agents:t,...n!==`latest`&&{channel:n}}),zi=e=>Yt(e.channel)?e.channel:`latest`,Y=(e,t=process.cwd())=>e===`global`?_(H(),`global.lock.json`):_(t,`agent-kit.lock.json`);async function X(e){try{let t=JSON.parse(await O(e,`utf8`));return{version:1,kits:t.kits??{},skills:t.skills??{},public:t.public??{}}}catch{return{version:1,kits:{},skills:{},public:{}}}}async function Bi(e,t){let n=e=>Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t))),r=Object.fromEntries(Object.entries(n(t.skills)).map(([e,t])=>{let{kits:n,...r}=t;return[e,n?.length?{...r,kits:[...n].sort()}:r]})),i=Object.keys(t.kits).length>0?n(t.kits):void 0,a=t.public&&Object.keys(t.public).length>0?n(t.public):void 0;await D(g(e),{recursive:!0}),await A(e,JSON.stringify({version:t.version,kits:i,skills:r,public:a},null,2)+`
219
+ `)}const Vi=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];function Hi(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Vi(e,i.id);if(n===void 0){e.skills[i.name]?r.clashes.push(i):r.install.push(i);continue}let a=e.skills[n].kits;a&&!a.includes(t)&&r.tag.push(n)}let i=new Set(n.map(e=>e.id));for(let[n,a]of Object.entries(e.skills))a.kits?.includes(t)&&!i.has(a.id)&&(a.kits.length>1?r.untag.push(n):r.remove.push(n));return r}function Ui(e,t,n){if(t===n)return;let r=e.kits[t];if(r){delete e.kits[t],e.kits[n]=r;for(let r of Object.values(e.skills))r.kits?.includes(t)&&(r.kits=[...new Set(r.kits.map(e=>e===t?n:e))])}}async function Wi(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Hi(t,n.name,n.skills),a={installed:[],removed:[],skipped:[],kept:[]};for(let e of i.clashes)I.warn(`${e.name} from kit/${n.name} wasn't installed: another skill named ${e.name} already is.`),a.skipped.push(e.name);for(let e of i.tag){let r=t.skills[e];r.kits=[...r.kits??[],n.name]}for(let e of i.untag){let r=t.skills[e];r.kits=r.kits.filter(e=>e!==n.name)}let o=new Set(i.install.map(e=>e.id)),s=r.reinstall?n.skills.filter(e=>!i.clashes.some(t=>t.id===e.id)):i.install,c=Ut();for(let i of s){let s=Vi(t,i.id),l=s?t.skills[s]:void 0,u=l&&!l.kits?l.agents:r.agents;c.start(`Installing ${i.name}`);let d;try{d=await Li(e,i.id,r.dirsOf(u))}catch(e){throw c.error(`${i.name} failed`),e}c.stop(`${d.name} v${d.version}`),s&&s!==d.name&&delete t.skills[s],delete t.public?.[d.name],t.skills[d.name]={id:d.id,version:d.version,agents:u,kits:o.has(i.id)?[n.name]:l?.kits&&[.../* @__PURE__ */ new Set([...l.kits,n.name])]},o.has(i.id)&&a.installed.push(d.name)}for(let o of i.remove){let i=t.skills[o],s=await Kn(r.dirsOf(i.agents),o);if(s){I.warn(`${o} was taken out of kit/${n.name}, but it uses ${G(s)} (\`a-kit link\`); left it.`),a.kept.push(o);continue}let c=await Wn(e,o,i,r.dirsOf(i.agents));c?(I.warn(`${o} was taken out of kit/${n.name}, but it has edits here that aren't in agent kit (${Hn(c.paths)}); left it. To keep them, make them in your organization's repository; otherwise delete its folder.`),a.kept.push(o)):(await Gi(t,o,r.dirsOf),a.removed.push(o))}return a}async function Gi(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await se(_(e,t),{recursive:!0,force:!0});delete e.skills[t]}function Ki(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const qi=e=>Ki(e)!==null;function Ji(e,t){let n=[],r=[];for(let i of t)qi(i)&&Tn(e,i).length===0?r.push(i):n.push(i);return{own:n,others:r}}async function Yi(e,t,n){let r=[];for(let i of t){let t=Ki(i);try{let n=await e.getPublicSkill(`${t.org}/${t.name}`);r.some(e=>e.ref===n.ref)||r.push(n)}catch(e){throw e instanceof z&&e.status===404?Error(n?`There's no skill "${i}" in your organizations, and no public one. See yours with ${R(`list`)}.`:`There's no public skill "${i}". If it's one of your organization's, log in first: ${R(`login`)}.`):e}}return r}async function Xi(e,t,n,r,i){let a=Ut();for(let o of n){if(t.skills[o.name])throw Error(`You already have a skill named "${o.name}" installed from your organization; ${o.ref} would replace it. Remove it first.`);a.start(`Installing ${o.ref}`);try{let n=await Li(Ii(e,o),o.ref,i);t.public??={},t.public[n.name]={ref:n.ref,version:n.version,agents:r},a.stop(`${n.name} v${n.version} (${n.ref})`)}catch(e){throw a.error(`${o.ref} failed`),e}await e.countInstall(o.ref).catch(()=>{})}}function Zi(e){let[t,n]=process.platform===`darwin`?[`open`,[e]]:process.platform===`win32`?[`cmd`,[`/c`,`start`,``,e.replace(/&/g,`^&`)]]:[`xdg-open`,[e]];try{let e=_e(t,n,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}const Qi=()=>_(H(),`bin`,`a-kit.mjs`);function $i(){let e=ve(import.meta.url);return e.endsWith(`.mjs`)?e:null}async function ea(e){let t=Qi();return await D(g(t),{recursive:!0}),e!==t&&await re(e,t),t}const ta=(e,t)=>{try{return ge(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:500}).trim()}catch{return null}};let na;function ra(e={platform:T(),read:ta,hostname:w}){if(e.platform===`darwin`)for(let t of[`ComputerName`,`LocalHostName`]){let n=e.read(`scutil`,[`--get`,t]);if(n)return n}try{return e.hostname().trim()||null}catch{return null}}function ia(){return na===void 0&&(na=ra()),na}async function aa(e,t,n=[],{batch:r=100,batchLength:i=1/0,keyOf:a}={}){let o=`${e}.${process.pid}`,s=[];try{await oe(e,o),s=ca(await O(o,`utf8`)),await se(o,{force:!0})}catch{}let c=[...s,...Array.isArray(n)?n:[n]];if(a){let e=new Map(c.map((e,t)=>[a(e),t]));c=c.filter((t,n)=>e.get(a(t))===n)}c=c.slice(-500);let l=0;for(let n=0,a=0;n<c.length;n=a){let o=0;for(a=n;a<n+r&&a<c.length&&(o+=JSON.stringify(c[a]).length,!(a>n&&o>i));)a++;let s=c.slice(n,a);try{await t(s),l+=s.length}catch(t){if(!sa(t))continue;let r=c.slice(n);return await D(g(e),{recursive:!0,mode:448}),await ee(e,r.map(e=>JSON.stringify(e)).join(`
220
220
  `)+`
221
- `),{sent:l,queued:r.length}}}return{sent:l,queued:0}}async function ga(e){try{return(await fe(e)).size>0}catch{return!1}}const _a=e=>!(e instanceof R)||e.status===0||e.status===429||e.status>=500;function va(e){return e.split(`
222
- `).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}async function ya(e,t,n,r=C()){let i=[Y(`global`)],a=ba(n,r);a&&i.push(a);for(let n of i){let r=(await X(n)).skills[e];if(r?.agents.includes(t))return r}return null}function ba(e,t){let n=e,{root:r}=v(e);for(;n&&n!==t;){let e=Y(`project`,n);if(f(e))return e;if(n===r)break;n=g(n)}return null}async function xa(){let e=_(V(),`machine.json`);try{let t=JSON.parse(await O(e,`utf8`));if(typeof t.id==`string`&&t.id)return t.id}catch{}let t=_e();return await D(g(e),{recursive:!0,mode:448}),await k(e,JSON.stringify({id:t},null,2)+`
223
- `),t}async function Sa(e,t,n,r={sessionId:null,repository:null,branch:null},i=/* @__PURE__ */ new Date){return{...r,id:_e(),skillId:e.id,version:e.version,agent:t,machineId:await xa(),machineName:ma(),trigger:n,occurredAt:i.toISOString()}}const Ca=()=>_(V(),`pending-activations.jsonl`),wa=(e,t=[])=>ha(Ca(),e,t),Ta=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function Ea(e){return e.match(Ta)?.[0]??null}const Da={"claude-code":`claude`,codex:`codex`,"gemini-cli":`gemini`};function Oa(e=C()){let t=[...(process.env.PATH??``).split(h),g(process.execPath),_(e,`.local`,`bin`),_(e,`.claude`,`local`),_(e,`.npm-global`,`bin`),_(e,`.bun`,`bin`),_(e,`.volta`,`bin`),`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`];return[...new Set(t.filter(Boolean))]}const ka=async e=>{let t=Oa(),n=await Aa(e,t);return n?new Promise(e=>{ye(n,[`--version`],{timeout:5e3,env:{...process.env,PATH:t.join(h)}},(t,n)=>e(t?null:n))}):null};async function Aa(e,t){for(let n of t){let t=_(n,e);try{return await te(t,ie.X_OK),t}catch{}}return null}async function ja(e,t=ka){let n=await Promise.all(e.map(async e=>{let n=Da[e],r=n?await t(n):null;return[e,r?Ea(r):null]}));return Object.fromEntries(n.filter(e=>e[1]!==null))}async function Ma(e,t,n){let r=await e.listOrganizations(),i;if(n)i=Na(r,n);else if(r.length<=1)i=r[0]??null;else if(vn())i=await Pa(r,t.organizationId);else return null;return i&&await Ln({...t,organizationId:i.id}),i}function Na(e,t){let n=t.trim().toLowerCase(),r=e.find(e=>e.id===t||e.name.toLowerCase()===n);if(!r)throw Error(`None of your organizations is "${t}". Yours: ${e.map(e=>e.name).join(`, `)}.`);return r}async function Pa(e,t){let n=yn(await Xt({message:`Which organization's Machines page should this machine show up on?`,options:e.map(e=>({value:e.id,label:e.name})),initialValue:e.some(e=>e.id===t)?t:void 0}));return e.find(e=>e.id===n)}const Fa=(e,t)=>new Promise(n=>{ye(e,t,{timeout:15e3},(e,t,r)=>{n({ok:!e,output:`${t}${r}`.trim()})})}),Ia=e=>new URL(e).host.toLowerCase().replace(/[^a-z0-9]+/g,`-`),La=e=>`agent-kit-heartbeat-${Ia(e)}`,Ra=e=>`com.agent-kit.heartbeat.${Ia(e)}`;function za(e,t=process.platform,n=C()){if(t===`linux`){let t=_(process.env.XDG_CONFIG_HOME??_(n,`.config`),`systemd`,`user`);return[_(t,`${La(e)}.service`),_(t,`${La(e)}.timer`)]}return t===`darwin`?[_(n,`Library`,`LaunchAgents`,`${Ra(e)}.plist`)]:[]}function Ba(e){let t=e=>`"${e.replace(/(["\\])/g,`\\$1`)}"`,n=e.configDir?`Environment=${t(`AGENT_KIT_CONFIG_DIR=${e.configDir}`)}\n`:``;return[`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Service]\nType=oneshot\n${n}ExecStart=${t(e.node)} ${t(e.script)} heartbeat send --api ${t(e.api)}\n`,`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Timer]\nOnBootSec=1min\nOnUnitActiveSec=300s\n\n[Install]\nWantedBy=timers.target\n`]}function Va(e){let t=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),n=[e.node,e.script,`heartbeat`,`send`,`--api`,e.api],r=e.configDir?` <key>EnvironmentVariables</key>\n <dict>\n <key>AGENT_KIT_CONFIG_DIR</key>\n <string>${t(e.configDir)}</string>\n </dict>\n`:``;return`<?xml version="1.0" encoding="UTF-8"?>
221
+ `),{sent:l,queued:r.length}}}return{sent:l,queued:0}}async function oa(e){try{return(await ce(e)).size>0}catch{return!1}}const sa=e=>!(e instanceof z)||e.status===0||e.status===429||e.status>=500;function ca(e){return e.split(`
222
+ `).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}async function la(e,t,n,r=C()){let i=[Y(`global`)],a=ua(n,r);a&&i.push(a);for(let n of i){let r=(await X(n)).skills[e];if(r?.agents.includes(t))return r}return null}function ua(e,t){let n=e,{root:r}=v(e);for(;n&&n!==t;){let e=Y(`project`,n);if(f(e))return e;if(n===r)break;n=g(n)}return null}async function da(){let e=_(H(),`machine.json`);try{let t=JSON.parse(await O(e,`utf8`));if(typeof t.id==`string`&&t.id)return t.id}catch{}let t=pe();return await D(g(e),{recursive:!0,mode:448}),await A(e,JSON.stringify({id:t},null,2)+`
223
+ `),t}async function fa(e,t,n,r={sessionId:null,repository:null,branch:null},i=/* @__PURE__ */ new Date){return{...r,id:pe(),skillId:e.id,version:e.version,agent:t,machineId:await da(),machineName:ia(),trigger:n,occurredAt:i.toISOString()}}const pa=()=>_(H(),`pending-activations.jsonl`),ma=(e,t=[])=>aa(pa(),e,t),ha=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function ga(e){return e.match(ha)?.[0]??null}const _a={"claude-code":`claude`,codex:`codex`,"gemini-cli":`gemini`};function va(e=C()){let t=[...(process.env.PATH??``).split(h),g(process.execPath),_(e,`.local`,`bin`),_(e,`.claude`,`local`),_(e,`.npm-global`,`bin`),_(e,`.bun`,`bin`),_(e,`.volta`,`bin`),`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`];return[...new Set(t.filter(Boolean))]}const ya=async e=>{let t=va(),n=await ba(e,t);return n?new Promise(e=>{he(n,[`--version`],{timeout:5e3,env:{...process.env,PATH:t.join(h)}},(t,n)=>e(t?null:n))}):null};async function ba(e,t){for(let n of t){let t=_(n,e);try{return await E(t,ne.X_OK),t}catch{}}return null}async function xa(e,t=ya){let n=await Promise.all(e.map(async e=>{let n=_a[e],r=n?await t(n):null;return[e,r?ga(r):null]}));return Object.fromEntries(n.filter(e=>e[1]!==null))}async function Sa(e,t,n){let r=await e.listOrganizations(),i;if(n)i=Ca(r,n);else if(r.length<=1)i=r[0]??null;else if(mn())i=await wa(r,t.organizationId);else return null;return i&&await Nn({...t,organizationId:i.id}),i}function Ca(e,t){let n=t.trim().toLowerCase(),r=e.find(e=>e.id===t||e.name.toLowerCase()===n);if(!r)throw Error(`None of your organizations is "${t}". Yours: ${e.map(e=>e.name).join(`, `)}.`);return r}async function wa(e,t){let n=hn(await Kt({message:`Which organization's Machines page should this machine show up on?`,options:e.map(e=>({value:e.id,label:e.name})),initialValue:e.some(e=>e.id===t)?t:void 0}));return e.find(e=>e.id===n)}const Ta=(e,t)=>new Promise(n=>{he(e,t,{timeout:15e3},(e,t,r)=>{n({ok:!e,output:`${t}${r}`.trim()})})}),Ea=e=>new URL(e).host.toLowerCase().replace(/[^a-z0-9]+/g,`-`),Da=e=>`agent-kit-heartbeat-${Ea(e)}`,Oa=e=>`com.agent-kit.heartbeat.${Ea(e)}`;function ka(e,t=process.platform,n=C()){if(t===`linux`){let t=_(process.env.XDG_CONFIG_HOME??_(n,`.config`),`systemd`,`user`);return[_(t,`${Da(e)}.service`),_(t,`${Da(e)}.timer`)]}return t===`darwin`?[_(n,`Library`,`LaunchAgents`,`${Oa(e)}.plist`)]:[]}function Aa(e){let t=e=>`"${e.replace(/(["\\])/g,`\\$1`)}"`,n=e.configDir?`Environment=${t(`AGENT_KIT_CONFIG_DIR=${e.configDir}`)}\n`:``;return[`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Service]\nType=oneshot\n${n}ExecStart=${t(e.node)} ${t(e.script)} heartbeat send --api ${t(e.api)}\n`,`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Timer]\nOnBootSec=1min\nOnUnitActiveSec=300s\n\n[Install]\nWantedBy=timers.target\n`]}function ja(e){let t=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),n=[e.node,e.script,`heartbeat`,`send`,`--api`,e.api],r=e.configDir?` <key>EnvironmentVariables</key>\n <dict>\n <key>AGENT_KIT_CONFIG_DIR</key>\n <string>${t(e.configDir)}</string>\n </dict>\n`:``;return`<?xml version="1.0" encoding="UTF-8"?>
224
224
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
225
225
  <plist version="1.0">
226
226
  <dict>
227
- <key>Label</key>\n <string>${t(Ra(e.api))}</string>\n <key>ProgramArguments</key>\n <array>\n`+n.map(e=>` <string>${t(e)}</string>\n`).join(``)+` </array>\n${r} <key>StartInterval</key>\n <integer>300</integer>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>/dev/null</string>\n <key>StandardErrorPath</key>\n <string>/dev/null</string>\n</dict>\n</plist>\n`}async function Ha(e){let t=e.platform??process.platform,n=e.run??Fa,r=za(e.api,t,e.home);if(r.length===0)return{status:`skipped`,reason:`the heartbeat timer only runs on Linux (systemd) and macOS`};let i=t===`linux`?Ba(e):[Va(e)];if((await Promise.all(r.map(e=>O(e,`utf8`).catch(()=>null)))).every((e,t)=>e===i[t]))return{status:`already`};for(let[e,t]of r.entries())await D(g(t),{recursive:!0}),await k(t,i[e]);if(t===`linux`){await n(`systemctl`,[`--user`,`daemon-reload`]);let t=await n(`systemctl`,[`--user`,`enable`,`--now`,`${La(e.api)}.timer`]);if(!t.ok)return await Ka(r),{status:`skipped`,reason:`systemd couldn't start it${t.output?`: ${t.output}`:``}`}}else{let t=`gui/${process.getuid?.()??501}`;await n(`launchctl`,[`bootout`,`${t}/${Ra(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await Ka(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function Ua(e,{platform:t=process.platform,home:n,run:r=Fa}={}){if(!await Wa(e,t,n))return!1;let i=za(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${La(e)}.timer`]),await Ka(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Ra(e)}`]),await Ka(i)),!0}async function Wa(e,t=process.platform,n){let r=za(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Ga(e=Fa,t=process.platform){if(t!==`linux`)return null;let n=process.env.USER;if(!n)return null;let{ok:r,output:i}=await e(`loginctl`,[`show-user`,n,`--property=Linger`]);return r&&i.trim()===`Linger=no`?"The timer stops while you're logged out of this machine. To keep it reporting, run `loginctl enable-linger`.":null}async function Ka(e){for(let t of e)await de(t,{force:!0})}async function qa(e,t){let n=await X(Y(`global`)),r=on().map(e=>e.id);return{machineId:await xa(),hostname:ma()??`unknown`,platform:T(),arch:S(),cliVersion:nn,agents:r,agentVersions:await ja(r,t),skills:Object.entries(n.skills).map(([e,t])=>({id:t.id,name:e,version:t.version,...t.channel&&{channel:t.channel},agents:t.agents})),every:e?300:null}}const Ja=()=>_(V(),`heartbeat.json`);async function Ya(){try{return JSON.parse(await O(Ja(),`utf8`))}catch{return null}}async function Xa(){try{if(Bn()||(await U()).heartbeat===!1)return!1;let e=await H();if(!e)return!1;let t={...await qa(await Wa(B())),...e.organizationId&&{organizationId:e.organizationId}},n={sentAt:(/* @__PURE__ */ new Date()).toISOString(),ok:!0};try{n.organization=(await z(B(),e.token).sendHeartbeat(t,AbortSignal.timeout(5e3))).organization}catch{n.ok=!1}return await D(V(),{recursive:!0,mode:448}),await k(Ja(),JSON.stringify(n)+`
228
- `),n.ok}catch{return!1}}async function Za(e=la()){try{if(Bn()||(await U()).heartbeat===!1)return;let t=await H();if(!t||(t.organizationId||await Ma(z(B(),t.token),t).catch(()=>null),!e))return;let n=await Wa(B()),r=await ua(e);if((await Ha({node:process.execPath,script:r,api:B(),configDir:process.env.AGENT_KIT_CONFIG_DIR})).status===`installed`&&!n){F.info("This machine now reports to agent kit every 5 minutes (its name, agents and their versions, and global skills), so your organization's Machines page shows it. Turn it off with `a-kit heartbeat off`.");let e=await Ga();e&&F.warn(e)}await Xa()}catch{}}const Qa=e=>new Promise(t=>setTimeout(t,e));async function $a(){let e=await z(B()).startLogin();F.step(`Opening agent kit in your browser. Log in, or sign up if you're new, and approve this code:\n\n ${e.userCode}\n\nIf it doesn't open, go to ${e.verificationUrl}`),sa(e.verificationUrl);let t=qt();t.start(`Waiting for you to approve it`);let n=z(B()),r=Date.now()+e.expiresIn*1e3;for(;Date.now()<r;){await Qa(e.interval*1e3);let r;try{r=await n.pollLogin(e.deviceCode)}catch(e){if(e instanceof R&&e.status===410)break;if(e instanceof R&&e.code===`NETWORK`)continue;throw t.error(`Login failed`),e}if(r.status===`approved`){let n={token:r.token,user:r.user,webUrl:new URL(e.verificationUrl).origin};return await Ln(n),t.stop(`Logged in as ${no(r.user)}`),await Za(),n}}throw t.error(`The code expired`),Error(`The login expired before it was approved. Run ${L(`login`)} again.`)}async function eo(){let e=await H();if(!e)return null;try{let t=await z(B(),e.token).me();return{...e,user:t}}catch(t){if(t instanceof R&&t.status===401){if(await Ln(null),e.user.kind===`bot`)throw Error(`${no(e.user)} isn't logged in anymore: its token was revoked. Log in with a new one: ${L(`login --token`)} < bot-token`);return null}throw t}}async function to(){let e=await H();if(!e){if(!vn())throw Error(`You're not logged in. Run ${L(`login`)} first.`);F.info(`First, log in to agent kit. New here? You'll sign up on the way.`),e=await $a()}return{api:z(B(),e.token),credentials:e}}const no=e=>e.kind===`bot`?`${e.name} (bot)`:e.email,ro=e=>`You don't have skills yet. Create or import one at ${e}/app/skills, then install it with ${L(`add`)}.`,io=`x-agent-kit-collector`,ao=()=>_(V(),`collector`),oo=()=>_(V(),`collector.json`),so=e=>typeof e==`number`&&Number.isInteger(e)&&e>0&&e<65536;async function co(){let e={};try{e=JSON.parse(await O(oo(),`utf8`))}catch{}let t={port:so(e.port)?e.port:24318,secret:typeof e.secret==`string`&&/^[0-9a-f]{32}$/.test(e.secret)?e.secret:ge(16).toString(`hex`)};return(t.port!==e.port||t.secret!==e.secret)&&await uo(t),t}async function lo(e){if(!so(e))throw Error(`${e} isn't a port.`);let t={...await co(),port:e};return await uo(t),t}async function uo(e){await D(V(),{recursive:!0,mode:448}),await k(oo(),JSON.stringify(e,null,2)+`
229
- `,{mode:384}),await re(oo(),384)}const fo=({port:e,secret:t})=>({CLAUDE_CODE_ENABLE_TELEMETRY:`1`,OTEL_METRICS_EXPORTER:`otlp`,OTEL_LOGS_EXPORTER:`otlp`,OTEL_EXPORTER_OTLP_PROTOCOL:`http/json`,OTEL_EXPORTER_OTLP_ENDPOINT:`http://127.0.0.1:${e}`,OTEL_EXPORTER_OTLP_HEADERS:`${io}=${t}`,OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:`cumulative`,OTEL_LOG_TOOL_DETAILS:`1`}),po=Object.keys(fo({port:0,secret:``})),mo=e=>e.OTEL_EXPORTER_OTLP_HEADERS?.startsWith(`x-agent-kit-collector=`)??!1;function ho(e){let t=e.env??{};return!mo(t)&&Object.keys(t).some(e=>/^OTEL_(EXPORTER_OTLP_(\w+_)?ENDPOINT|\w+_EXPORTER)$/.test(e))}const go=(e,t)=>({...e,env:{..._o(e).env,...t}});function _o(e){if(!e.env||!mo(e.env))return e;let t=Object.fromEntries(Object.entries(e.env).filter(([e])=>!po.includes(e))),{env:n,...r}=e;return Object.keys(t).length>0?{...r,env:t}:r}const vo=(e,t)=>t?Object.entries(t).every(([t,n])=>e.env?.[t]===n):!mo(e.env??{}),yo=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`settings.json`),bo=(e,t)=>`node "${e}" hook claude-code --api "${t}"`,xo=e=>typeof e.command==`string`&&e.command.includes(`a-kit.mjs`)&&e.command.includes(` hook claude-code`),So=[`telemetry`,`autoUpdate`],Co={telemetry:[{event:`PostToolUse`,matcher:`Skill`},{event:`PostToolUse`,matcher:`Bash`,if:`Bash(gh *)`},{event:`UserPromptSubmit`},{event:`SessionStart`,matcher:`startup|resume|clear`,role:`session`},{event:`Stop`},{event:`SessionEnd`}],autoUpdate:[{event:`SessionStart`,matcher:`startup|resume`}]},wo=(e,{role:t})=>t?`${e} ${t}`:e;function To(e){if(!e.hooks)return e;let t={};for(let[n,r]of Object.entries(e.hooks)){if(!Array.isArray(r)){t[n]=r;continue}let e=r.map(e=>({...e,hooks:e.hooks?.filter(e=>!xo(e))})).filter((e,t)=>(e.hooks?.length??0)>0||!r[t].hooks);e.length>0&&(t[n]=e)}let{hooks:n,...r}=e;return Object.keys(t).length>0?{...r,hooks:t}:r}function Eo(e,t,n=So){let r=To(e),i={...r.hooks};for(let e of n.flatMap(e=>Co[e])){let n={type:`command`,command:wo(t,e),...e.if&&{if:e.if},async:!0,timeout:10},{event:r,matcher:a}=e;i[r]=[...i[r]??[],a?{matcher:a,hooks:[n]}:{hooks:[n]}]}return Object.keys(i).length>0?{...r,hooks:i}:r}const Do=(e,t,n)=>e.hooks?.[t.event]?.some(e=>e.matcher===t.matcher&&e.hooks?.some(e=>xo(e)&&e.if===t.if&&(!n||e.command===wo(n,t))))??!1;function Oo(e,t,n){return Co[t].every(t=>Do(e,t,n))}function ko(e,t,n){return So.every(r=>n.includes(r)?Oo(e,r,t):Co[r].every(t=>!Do(e,t)))}function Ao(e){if(e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`){let t=e.tool_input?.skill??e.tool_input?.command,n=typeof t==`string`?t.replace(/^\//,``):``;return jo(n)?{name:n,trigger:`model`}:null}if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`){let t=e.prompt.match(/^\s*\/([^\s]+)/)?.[1]??``;return jo(t)?{name:t,trigger:`user`}:null}return null}const jo=e=>/^[a-z0-9][a-z0-9-]*$/.test(e);async function Mo(){let e=await U();return So.filter(t=>e[t]!==!1)}async function No(e=la(),t=yo(),n){let r=n??await Mo(),i=await zo(t);if(i===`invalid`)return{status:`skipped`,reason:`${t} isn't valid JSON`};let a=await Po(i,r.includes(`telemetry`)),o=a.elsewhere?{exportsElsewhere:!0}:{};if(r.length===0)return!So.some(e=>Oo(i,e))&&a.matches?{status:`already`}:(await Bo(t,a.apply(To(i))),{status:`installed`,added:[]});if(!e)return{status:`skipped`,reason:`not running from a build`};let s=await ua(e),c=bo(s,B());if(ko(i,c,r)&&a.matches)return{status:`already`,...o};let l=r.filter(e=>!Oo(i,e));return await Bo(t,a.apply(Eo(i,c,r))),{status:`installed`,added:l,...o}}async function Po(e,t){if(!t)return{apply:_o,matches:vo(e,null),elsewhere:!1};if(ho(e))return{apply:e=>e,matches:!0,elsewhere:!0};let n=fo(await co());return{apply:e=>go(e,n),matches:vo(e,n),elsewhere:!1}}async function Fo(e=yo()){let t=await zo(e);return t===`invalid`?`off`:ho(t)?`elsewhere`:vo(t,fo(await co()))?`collector`:`off`}async function Io(e=yo()){let t=await zo(e);return t===`invalid`?[]:So.filter(e=>Oo(t,e))}const Lo={telemetry:"Claude Code now reports to agent kit each time it loads one of these skills, when its sessions start and end, and what they used (tokens, cost and time, never what you or the agent wrote), so your organization sees which ones get used. `a-kit telemetry show` shows what was sent; turn it off with `a-kit telemetry off`.",autoUpdate:"Claude Code now checks the skills you installed everywhere (-g) for changes when a session starts, and updates them in the background when they changed. Turn it off with `a-kit auto-update off`."};async function Ro(e){if(e.includes(`claude-code`))try{let e=await No();if(e.status===`installed`)for(let t of e.added)F.info(Lo[t])}catch{}await Za()}async function zo(e){let t;try{t=await O(e,`utf8`)}catch{return{}}if(!t.trim())return{};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?e:`invalid`}catch{return`invalid`}}async function Bo(e,t){await D(g(e),{recursive:!0}),await k(e,JSON.stringify(t,null,2)+`
230
- `)}const Vo=(e=`npx -y useakit@next`)=>`---
231
- name: ${Ni}
232
- description: Reports this conversation to agent kit because it went wrong, so it can become an eval. Use when the developer says the session went badly and asks to report it ("report this", "reportá esta conversación", "mandalo a agent kit"), or wants it turned into an eval.
233
- ---
234
-
235
- # Report this session
236
-
237
- Sends this conversation (every message and tool call) to the developer's agent kit organization, scrubbed of what's private, so it can become an eval. The \`a-kit report\` command reads the session from the agent's own log, scrubs it on this machine and sends it. What only you can add is what went wrong and which words are private.
238
-
239
- Only the conversation up to the developer's request to report it is sent; this part isn't.
240
-
241
- 1. **What went wrong.** If the developer hasn't said, ask: what went wrong, and what they expected instead. Use their words; don't guess. Write a title of under 120 characters.
242
-
243
- 2. **What's private.** \`a-kit report\` takes out secrets, emails, IPs, the user and machine names, and paths to the repo and the home folder on its own. You add the words that identify the project or its people, from what you saw in this conversation:
244
- - company, client and product names, and the repo's name;
245
- - domains and URLs of their services, and internal hostnames;
246
- - people's names;
247
- - business data, like amounts or ids of real records.
248
-
249
- Map each one to a neutral stand-in that keeps the meaning, and save the map as JSON outside the repo:
250
-
251
- \`\`\`json
252
- {"Nigon SRL": "Acme Corp", "nigon.com.uy": "example.com", "Juan Pérez": "Alex Doe"}
253
- \`\`\`
254
-
255
- Words are found in any case. Words under four characters are only replaced as whole words.
256
-
257
- 3. **Preview.** Run, with \`--agent codex\` instead in Codex:
258
-
259
- \`\`\`sh
260
- ${e} report --agent claude-code --session "\${CLAUDE_SESSION_ID}" \\
261
- --title "…" --note "what went wrong" --expected "what they expected" \\
262
- --map /tmp/a-kit-report-map.json --dry-run
263
- \`\`\`
264
-
265
- Without \`--session\`, it reads this folder's latest session. It prints the skills it links, what it took out, and the path of the scrubbed transcript. Search that file for the private words you know of (\`grep -i\`), and anything else that names the project. Add what's left to the map and preview again until nothing is.
266
-
267
- 4. **Confirm.** Tell the developer in a few lines: the title, the skills it links, what was taken out, and that long tool outputs and written files are cut to 2,000 characters (\`--full-outputs\` keeps them whole). Ask before sending.
268
-
269
- 5. **Send.** Run the same command with \`--yes\` instead of \`--dry-run\`, and give the developer the link it prints. If it says they're not logged in, they run \`${e} login\` first.
270
- `;async function Ho(e){for(let t of e){let e=_(t,Ni);await D(e,{recursive:!0}),await k(_(e,`SKILL.md`),Vo())}}const Uo=e=>t=>cn(t.map(e=>sn(e)).filter(e=>e!==void 0),e);async function Wo(e,t,n,r,i=`latest`,a){let o=cn(n,r),s=Y(r),c=await X(s);await Ho(o);try{await Go(e,c,t,n,o,i,a)}finally{await Xi(s,c)}return await Ro(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function Go(e,t,n,r,i,a=`latest`,o){let s=n.find((e,t)=>n.some((n,r)=>r<t&&n.name===e.name));if(s)throw Error(`You picked more than one skill named "${s.name}"; they'd install to the same folder. Pick one.`);let c=qt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await qi(e,o.id,i,a);l.push(n),t.skills[n.name]=Ji(n,r.map(e=>e.id),a),delete t.public?.[n.name],c.stop(`${n.name} v${n.version}`+(a===`latest`?``:` (${a})`)),a!==`latest`&&n.channels[a]===null&&F.warn(`${n.name} has no ${a} release yet, so you got the latest. \`a-kit update\` follows ${a} once someone sets it.`)}catch(e){throw c.error(`${o.name} failed`),e}}if(!o)return;let u=await Wi(await Vi(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await Go(e,t,u,r,i)}async function Ko(e,t){Wt(`agent kit`);let n=!t.yes,r=Cn(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(ra)&&await H()===null?null:await to(),a=i?.api??z(B()),o=r.skills.length>0||r.kits.length===0,s=i&&o?await a.listSkills():[],{own:c,others:l}=i?ia(s,r.skills):{own:[],others:r.skills},u=await aa(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){I(ro(i.credentials.webUrl));return}let f=d?await wn(s,c,n):[],p=u.find(e=>f.some(t=>t.name===e.name));if(p)throw Error(`${p.ref} and one of your skills are both named "${p.name}"; they'd install to the same folder. Pick one.`);let m=r.kits.length>0?await Tn(await a.listKits(),r.kits,n):[];m.length>0&&t.channel!==`latest`&&F.warn(`--channel ${t.channel} applies to skills you name; kits install and follow each skill's latest version.`);let h=await bn(t.agent,n),g=t.global?`global`:`project`,_=cn(h,g),v=Y(g),y=await X(v);await Ho(_);try{await Go(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await oa(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await ea(a,y,e,{agents:h.map(e=>e.id),dirsOf:Uo(g),reinstall:!0}),n=e.skills.length-t.skipped.length;F.success(`kit/${e.name}: ${n} skill${n===1?``:`s`} installed`+(t.removed.length?`, ${t.removed.join(`, `)} removed (no longer in it)`:``))}}finally{await Xi(v,y)}await Ro(h.map(e=>e.id)),I(`Installed in ${_.map(W).join(`, `)}`)}const qo=(e,t)=>{xe(process.execPath,[e,...t],{cwd:C(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},Jo=()=>_(V(),`auto-update.json`);async function Yo(e=Date.now(),t=6e4,n=Jo()){if(Xo((await Zo(n)).startedAt,e,t))return!1;await D(g(n),{recursive:!0});let r=`${n}.claim`;try{await k(r,``,{flag:`wx`})}catch{let e=await fe(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await me(r).catch(()=>{}),!1}try{let r=await Zo(n);return!Xo(r.startedAt,e,t)&&(await Qo(n,{...r,startedAt:e}),!0)}finally{await me(r).catch(()=>{})}}const Xo=(e,t,n)=>typeof e==`number`&&t-e<n&&e<=t;async function Zo(e){try{let{startedAt:t,fingerprint:n}=JSON.parse(await O(e,`utf8`));return{...typeof t==`number`&&{startedAt:t},...typeof n==`string`&&{fingerprint:n}}}catch{return{}}}async function Qo(e,t){await D(g(e),{recursive:!0}),await k(e,JSON.stringify(t)+`
271
- `)}const $o=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function es(e,t=qo,n=Date.now()){return(await U()).autoUpdate===!1||$o(await X(Y(`global`)))||!await H()||!await Yo(n)?!1:(t(e,[`auto-update`,`run`]),!0)}const ts=e=>({skills:Object.values(e.skills).map(e=>{let t=Yi(e);return t===`latest`?{id:e.id}:{id:e.id,channel:t}}),kits:Object.values(e.kits).map(e=>e.id),public:Object.values(e.public??{}).map(e=>e.ref)});async function ns(e,t,n=Jo()){try{let r=await X(Y(`global`));if($o(r))return`unchanged`;let{fingerprint:i}=await e.fingerprint(ts(r),AbortSignal.timeout(5e3));return(await Zo(n)).fingerprint===i?`unchanged`:(await t(),await Qo(n,{...await Zo(n),fingerprint:i}),`updated`)}catch{return`failed`}}const rs=6e3,is=e=>`github.com/${e.toLowerCase()}`,as=()=>_(V(),`project-repositories.json`);async function os(){try{let e=JSON.parse(await O(as(),`utf8`));return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}catch{return{}}}async function ss(e){let t=await os();t[B()]=e,await D(V(),{recursive:!0,mode:448});let n=`${as()}.${process.pid}`;await k(n,JSON.stringify(t)+`
272
- `),await ue(n,as())}const cs=e=>typeof e==`object`&&!!e&&!Array.isArray(e);async function ls(e){let t=(await os())[B()];return!t||t.userId!==e||typeof t.checkedAt!=`string`||typeof t.triedAt!=`string`||!cs(t.repositories)||!cs(t.skills)?null:t}async function us(e,t,n,r){let[i,a]=await Promise.all([e.listOrganizations(r),e.listSkillSummaries(r)]),o=await Promise.all(i.map(async t=>({organizationId:t.id,projects:await e.listProjects(t.id,r)}))),s={userId:t,checkedAt:n.toISOString(),triedAt:n.toISOString(),repositories:{},skills:{}};for(let{organizationId:e,projects:t}of o)for(let n of t)for(let t of n.repositories)s.repositories[is(t.fullName)]=e;for(let e of a)s.skills[e.id]=e.organizationId;return await ss(s),s}function ds(e,t,n){if(!e)return!0;let r=e=>t.getTime()-(Date.parse(e)||0);return r(e.triedAt)<36e5?!1:r(e.checkedAt)>=864e5||!!n&&!(n in e.skills)}async function fs(e,t,n,r){try{return await ss({userId:t,checkedAt:n?.checkedAt??(/* @__PURE__ */ new Date(0)).toISOString(),repositories:n?.repositories??{},skills:n?.skills??{},triedAt:r.toISOString()}),await us(e,t,r,AbortSignal.timeout(rs))}catch{return null}}async function ps(){try{if(Bn()||(await U()).telemetry===!1)return;let e=await H();if(!e)return;await us(z(B(),e.token),e.user.id,/* @__PURE__ */ new Date,AbortSignal.timeout(rs))}catch{}}async function ms(e){Wt(`agent kit`),await ps();let t=e.global?`global`:`project`,n=Y(t),r=await X(n),i=Object.entries(r.public??{});if(Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0&&i.length===0){I(e.global?"No skills installed everywhere yet. Add some with `a-kit add -g`.":"No skills installed in this project yet. Add some with `a-kit add`.");return}let a=Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0?z(B(),(await H())?.token):(await to()).api,o=Uo(t),s=[...Object.values(r.skills).flatMap(e=>o(e.agents)),...Object.values(r.kits).flatMap(e=>o(e.agents)),...i.flatMap(([,e])=>o(e.agents))];await Ho([...new Set(s)]);let c=0,l=0,u=0;for(let[e,t]of Object.entries(r.kits)){let i;try{i=await a.getKit(t.id)}catch(t){if(t instanceof R&&t.status===404){F.warn(`kit/${e} isn't in your agent kit anymore; left its skills as they are.`);continue}throw t}$i(r,e,i.name);try{let e=await ea(a,r,i,{agents:t.agents,dirsOf:o,reinstall:!1});for(let t of e.installed)F.success(`${t}: added to kit/${i.name}, installed`);for(let t of e.removed)F.success(`${t}: taken out of kit/${i.name}, removed`);c+=e.installed.length,l+=e.removed.length,u+=e.kept.length}finally{await Xi(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=Yi(t),s;try{s=await a.getSkill(t.id,i)}catch(t){if(t instanceof R&&t.status===404){F.warn(`${e} isn't in your agent kit anymore; left it as it is.`);continue}throw t}if(s.version===t.version)continue;let c=o(t.agents),l=await Xn(c,e);if(l){F.warn(`${e} uses ${W(l)} (\`a-kit link\`); left it. \`a-kit add ${e}\` goes back to v${s.version}.`),u++;continue}let f=await Jn(a,e,t,c);if(f)F.warn(`${e} has edits here that aren't in agent kit (${Kn(f.paths)}); left it at v${t.version}. To keep them, make them in your organization's repository (\`a-kit link\` tries a skill from it); \`a-kit add ${e}\` throws them away.`),u++;else{if(await qi(a,t.id,c,i),s.name!==e){for(let t of c)await de(_(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Xi(n,r),F.success(`${s.name}: v${t.version} → v${s.version}`+(i===`latest`?``:` (${i})`)+(s.name===e?``:` (was ${e})`)),d++}}for(let[e,t]of i){let i;try{i=await a.getPublicSkill(t.ref)}catch(e){if(e instanceof R&&e.status===404){F.warn(`${t.ref} isn't public anymore; left it as it is.`);continue}throw e}if(i.version===t.version&&i.name===e)continue;if(i.name!==e&&r.skills[i.name]){F.warn(`${t.ref} is now named ${i.name}, like one of your skills; left it at v${t.version}.`);continue}let s=o(t.agents);if(await qi(Ki(a,i),t.ref,s),i.name!==e){for(let t of s)await de(_(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Xi(n,r),F.success(`${i.name}: v${t.version} → v${i.version} (${t.ref})`+(i.name===e?``:` (was ${e})`)),d++}await Ro([...new Set([...Object.values(r.skills),...Object.values(r.kits),...i.map(([,e])=>e)].flatMap(e=>e.agents))]),I(gs(d,c,l,u))}const hs=e=>`${e} skill${e===1?``:`s`}`;function gs(e,t,n,r){let i=[e&&`updated ${hs(e)}`,t&&`installed ${hs(t)}`,n&&`removed ${hs(n)}`].filter(Boolean),a=r?`Left ${hs(r)} with local edits or links as they are.`:``;if(i.length===0)return a||`Everything is up to date.`;let o=i.join(`, `);return`${o[0].toUpperCase()}${o.slice(1)}.${a&&` ${a}`}`}async function _s(e){switch(e){case`run`:{let e=await H();if(!e)return;await ns(z(B(),e.token),()=>ms({global:!0,agent:[],yes:!0,channel:`latest`}));return}case`on`:{await zn({autoUpdate:!0});let e=await No();e.status===`skipped`?F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):F.success(`Auto-update is on: when a Claude Code session starts, your global skills update if they changed.`);return}case`off`:await zn({autoUpdate:!1}),await No(),F.success("Auto-update is off. Update with `a-kit update -g`, or turn it back on with `a-kit auto-update on`.");return;case void 0:case`status`:{let e=(await U()).autoUpdate!==!1,t=(await Io()).includes(`autoUpdate`);console.log(`Auto-update is ${e?`on`:`off`}.`),console.log(`Claude Code: ${t?`checks the global skills for changes when a session starts`:`no hook installed`}.`),console.log("\nWhen a Claude Code session starts, agent kit checks in the background whether the skills and kits you installed everywhere (-g) changed, and updates them when they did. A project's skills stay as they are until you run `a-kit update` there.");return}default:throw Error(`Unknown auto-update action "${e}". Use on, off or status.`)}}function vs(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}const ys=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function bs(e,t=!!process.stdout.isTTY&&!process.env.NO_COLOR){let n=(e,n)=>t?r(e,n):n;return e.map(e=>{let t=e.severity===`error`?n(`red`,`✗`):n(`yellow`,`▲`),r=e.path===null?`repository`:e.path+(e.line?`:${e.line}`:``);return`${t} ${e.message} ${n(`dim`,r)}`})}function xs(e){let t=typeof e==`string`?e.trim():``;return t?t.length>64?{ok:!1,message:`Keep the name under 64 characters.`}:/^[a-z0-9-]+$/.test(t)?t.startsWith(`-`)||t.endsWith(`-`)||t.includes(`--`)?{ok:!1,message:`The name can't start or end with a hyphen, or have two in a row.`}:{ok:!0,name:t}:{ok:!1,message:`Use only lowercase letters, numbers and hyphens in the name.`}:{ok:!1,message:`Give the kit a name.`}}const Ss=e=>`kits/${e}.yaml`;function Cs(e){let t=/^kits\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function ws(e){let t;try{t=(0,J.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
273
- `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{skills:[]};let n="It has to list the kit's skills by name: `skills: [tdd, notes]`.";if(!Ts(t))return{error:n};let{skills:r}=t;return r==null?{skills:[]}:!Array.isArray(r)||!r.every(e=>typeof e==`string`)?{error:n}:{skills:[...new Set(r.map(e=>e.trim()))]}}const Ts=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Es(e){let t;try{t=(0,J.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
274
- `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!Ts(t))return{error:"It has to be a list of skills, each with its channels: `tdd: { stable: 7, beta: 9 }`."};let n={pins:/* @__PURE__ */ new Map,problems:[]};for(let[e,r]of Object.entries(t)){let t={};if(n.pins.set(e,t),r!==null){if(Ts(r))for(let[i,a]of Object.entries(r))Zt.includes(i)?Number.isInteger(a)&&Number(a)>0?t[i]=a:(t[i]=null,n.problems.push(`The ${i} channel of “${e}” has to be a version number, like 7.`)):n.problems.push(`“${e}” has a channel called “${i}”. Only stable and beta can be set.`);else{for(let e of Zt)t[e]=null;n.problems.push(`“${e}” has to have its channels, like \`{ stable: 7 }\`.`)}}}return n}const Ds=(...e)=>({words:e}),Os={text:`one`},ks={issue:{about:`an issue's state changed`,value:Ds(`opened`,`closed`,`reopened`),fields:{}},label:{about:`a label was put on an issue or a pull request, or taken off`,value:Os,fields:{on:Ds(`added`,`removed`)}},path:{about:`a pull request that changes a path was merged`,value:Os,fields:{on:Ds(`merged`)}},"pull-request":{about:`a pull request was opened, marked ready, merged or closed`,value:Ds(`opened`,`ready`,`merged`,`closed`),fields:{base:Os,head:Os}},review:{about:`a pull request got a review`,value:Ds(`approved`,`changes-requested`,`commented`),fields:{by:{text:`many`}},roles:[`by`]},checks:{about:`a pull request's checks finished`,value:Ds(`passed`,`failed`),fields:{}},release:{about:`a release was published`,value:Ds(`published`),fields:{}},skill:{about:`an agent loaded a skill`,value:Os,fields:{}},branch:{about:`a branch got its first commit`,value:Ds(`first-commit`),fields:{}}},As=Object.keys(ks),js=e=>Object.hasOwn(ks,e),Ms=(e,t=`and`)=>e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)} ${t} ${e.at(-1)}`,Ns=`flows`,Ps=[`epic`,`ticket`,`pull-request`],Fs=[`paths`,`labels`];function Is(e){let t=/^flows\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function Ls(e){return e.length===0?`It's empty.`:e.length>64?`It's longer than 64 characters.`:/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e)?null:`Use only lowercase letters, numbers and single hyphens, not at the start or the end.`}function Rs(e){let t=Ls(e);return t===null?null:`“${e}” can't be a flow's name, so this file isn't read. ${t}`}const zs=[`name`,`description`,`stations`],Bs=[`id`,`unit`,`signal`,`owner`,`before`,`when`];function Vs(e){let t=[],n=[],r=(0,J.parseDocument)(e,{prettyErrors:!1}),i=t=>t&&typeof t==`object`&&`range`in t&&t.range?vs(e,t.range[0]):null,a=(e,n)=>{t.push({line:i(e),message:n})},o=(e,t)=>{n.push({name:e,line:i(t)})};if(r.errors.length>0){for(let n of r.errors)t.push({line:vs(e,n.pos[0]),message:`It isn't valid YAML: ${n.message.split(`
275
- `)[0]}`});return{flow:null,problems:t,roles:n}}let s=Hs(r,r.contents);if(s===null||(0,J.isScalar)(s)&&s.value===null)return t.push({line:null,message:"It's empty. A flow lists its stations: `stations: [{ id: review, unit: pull-request, signal: { review: approved } }]`."}),{flow:null,problems:t,roles:n};if(!(0,J.isMap)(s))return a(s,"A flow has to be a mapping, with its `stations`."),{flow:null,problems:t,roles:n};let c=Us(r,s,zs,`A flow`,a),l=c.has(`name`)?Ws(c.get(`name`),"Its `name`",a):null,u=c.has(`description`)?Ws(c.get(`description`),"Its `description`",a):null,d=c.get(`stations`),f=[],p=[];if(!d)a(s,"It has no `stations`: a flow lists them in order.");else if(!(0,J.isSeq)(d.value)||d.value.items.length===0)a(d.value??d.key,"Its `stations` have to be a list, with one station at least.");else if(d.value.items.length>100)a(d.key,`A flow has at most 100 stations, and this one has ${d.value.items.length}.`);else{let e=/* @__PURE__ */ new Map;d.value.items.forEach((t,n)=>{let s=Hs(r,t),c=`Station ${n+1}`;if(!(0,J.isMap)(s)){a(s??d.value,`${c} has to be a mapping, with its \`id\`, \`unit\` and \`signal\`.`);return}let l=Us(r,s,Bs,c,a),u=l.get(`id`),m=null;if(!u)a(s,`${c} has no \`id\`. Give it one that stays the same, like \`review\`.`);else{m=Ws(u,`The \`id\` of ${c.toLowerCase()}`,a);let t=m===null?null:Ls(m);if(m!==null&&t)a(u.value,`“${m}” can't be a station's id. ${t}`),m=null;else if(m!==null&&e.has(m)){let t=e.get(m);a(u.value,`There's another station with the id “${m}”${t?` (line ${t})`:``}. Each station's id has to be its own.`),m=null}else m!==null&&e.set(m,i(u.value))}let h=m?`Station “${m}”`:c,g=l.get(`unit`),_=null;if(!g)a(s,`${h} has no \`unit\`: say whether it's counted for an \`epic\`, a \`ticket\` or a \`pull-request\`.`);else{let e=Ws(g,`The \`unit\` of ${h.toLowerCase()}`,a);e!==null&&(Ps.includes(e)?_=e:a(g.value,`“${e}” isn't a unit. A station is counted for an epic, a ticket or a pull-request.`))}let v=l.get(`signal`),y=null;v?y=Ks(r,v.value,h,a,o):a(s,`${h} has no \`signal\`: say how agent kit knows it happened, like \`{ review: approved }\`.`);let b=l.has(`owner`)?Gs(r,l.get(`owner`),`The \`owner\` of ${h.toLowerCase()}`,`a role`,a,o):[],x=[],S=l.get(`before`);if(S){let e=Hs(r,S.value),t=(0,J.isSeq)(e)?e.items.map(e=>Hs(r,e)):[e];for(let e of t){let t=(0,J.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)?String(e.value).trim():``;t?(x.push(t),p.push({station:m??``,node:e,id:t})):a(e??S.key,`The \`before\` of ${h.toLowerCase()} has to be a station's id, or a list of them.`)}}let C=l.has(`when`)?Xs(r,l.get(`when`),h,a):null;m!==null&&_!==null&&y!==null&&b!==null&&C!==void 0&&f.push({id:m,unit:_,signals:y,owner:b,before:x,when:C})});for(let{station:t,node:n,id:r}of p)r===t?a(n,`Station “${t}” can't come before itself.`):e.has(r)||a(n,`There's no station “${r}” in this flow, so nothing can come before it.`)}return t.sort((e,t)=>(e.line??0)-(t.line??0)),n.sort((e,t)=>(e.line??0)-(t.line??0)),{flow:t.length===0?{name:l,description:u,stations:f}:null,problems:t,roles:n}}const Hs=(e,t)=>t==null?null:(0,J.isAlias)(t)?t.resolve(e)??null:t;function Us(e,t,n,r,i){let a=/* @__PURE__ */ new Map;if(!(0,J.isMap)(t))return a;for(let o of t.items){let s=Hs(e,o.key),c=(0,J.isScalar)(s)?String(s.value):null;c===null||!n.includes(c)?i(s??t,`${r} doesn't take \`${c??`?`}\`. It takes ${Ms(n.map(e=>`\`${e}\``))}.`):a.set(c,{key:s,value:Hs(e,o.value)})}return a}function Ws(e,t,n){let{value:r}=e;return(0,J.isScalar)(r)&&(typeof r.value==`string`||typeof r.value==`number`)&&String(r.value).trim()!==``?String(r.value).trim():(n(r??e.key,`${t} has to be some text.`),null)}function Gs(e,t,n,r,i,a){let o=Hs(e,t.value),s=(0,J.isSeq)(o)?o.items.map(t=>Hs(e,t)):[o],c=[];for(let e of s){if(!(0,J.isScalar)(e)||typeof e.value!=`string`&&typeof e.value!=`number`||String(e.value).trim()===``)return i(e??t.key,`${n} has to be ${r}, or a list of them.`),null;c.push(String(e.value).trim())}return c.forEach((e,t)=>a?.(e,s[t])),c.length===0?(i(o??t.key,`${n} has to be ${r}, or a list of them.`),null):c}function Ks(e,t,n,r,i){let a=(0,J.isSeq)(t)?t.items.map(t=>Hs(e,t)):[t];if(a.length===0)return r(t,`The \`signal\` of ${n.toLowerCase()} is an empty list: give it one at least.`),null;let o=[],s=!0;for(let t of a){let a=Js(e,t,n,r,i);a?o.push(a):s=!1}return s?o:null}const qs=Ms(As.map(e=>`\`${e}\``));function Js(e,t,n,r,i){if(!(0,J.isMap)(t))return r(t,`A signal of ${n.toLowerCase()} has to be a mapping that starts with its kind, like \`{ review: approved }\`. The kinds are ${qs}.`),null;let a=t.items.map(t=>{let n=Hs(e,t.key);return{key:n,name:(0,J.isScalar)(n)?String(n.value):`?`,value:Hs(e,t.value)}}),o=a.filter(e=>js(e.name));if(o.length===0){let[e]=a;return r(e?.key??t,e?`“${e.name}” isn't a kind of signal. The kinds are ${qs}.`:`A signal of ${n.toLowerCase()} is empty. Start it with its kind: ${qs}.`),null}if(o.length>1)return r(o[1].key,`A signal is of one kind, and this one has ${Ms(o.map(e=>`\`${e.name}\``))}. To take any of them, make \`signal\` a list.`),null;let s=o[0].name,c=ks[s],l=!0,u=Ys(o[0].value,c.value,`\`${s}\``,o[0].key,r);(u===null||Array.isArray(u))&&(l=!1);let d={},f=Object.keys(c.fields);for(let e of a){if(e.name===s)continue;let t=c.fields[e.name];if(!t){r(e.key,f.length===0?`A \`${s}\` signal takes no other field, and this one has \`${e.name}\`.`:`A \`${s}\` signal doesn't take \`${e.name}\`. It takes ${Ms(f.map(e=>`\`${e}\``))}.`),l=!1;continue}let n=Ys(e.value,t,`\`${e.name}\``,e.key,r);if(n===null)l=!1;else if(d[e.name]=n,c.roles?.includes(e.name)){let t=(0,J.isSeq)(e.value)?e.value.items:[e.value];(Array.isArray(n)?n:[n]).forEach((n,r)=>i(n,t[r]??e.key))}}return l?{kind:s,value:u,fields:d}:null}function Ys(e,t,n,r,i){let a=e=>(0,J.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)&&String(e.value).trim()!==``?String(e.value).trim():null;if(`words`in t){let o=a(e);return o!==null&&t.words.includes(o)?o:(i(e??r,`${n} has to be ${Ms(t.words.map(e=>`\`${e}\``),`or`)}${o===null?``:`, not “${o}”`}.`),null)}if(t.text===`many`&&(0,J.isSeq)(e)){let t=e.items.map(e=>a(e));return t.length>0&&t.every(e=>e!==null)?t:(i(e,`${n} has to be a name, or a list of them.`),null)}let o=a(e);return o===null?(i(e??r,`${n} has to be ${t.text===`many`?`a name, or a list of them`:`some text`}.`),null):o}function Xs(e,t,n,r){let i=t.value;if(!(0,J.isMap)(i)){r(i??t.key,`The \`when\` of ${n.toLowerCase()} has to be a mapping, like \`{ paths: [docs] }\`.`);return}let a=Us(e,i,Fs,`The \`when\` of ${n.toLowerCase()}`,r);if(a.size!==i.items.length)return;let o={};for(let[t,n]of a){let i=Gs(e,n,`\`${t}\``,`a name`,r);if(i===null)return;o[t]=i}return o}const Zs=new Map([{key:`name`,scope:`standard`,kind:`string`,required:!0,summary:`The skill's id and its /command. 1–64 lowercase letters, numbers and single hyphens.`},{key:`description`,scope:`standard`,kind:`string`,required:!0,summary:`What the skill does and when to use it. The agent reads it to decide when to load the skill. Up to 1024 characters.`},{key:`license`,scope:`standard`,kind:`string`,summary:`A license name, or the path of a license file in the skill.`},{key:`compatibility`,scope:`standard`,kind:`string`,summary:`Environment the skill needs (tools, network, OS). Up to 500 characters; only add it when it matters.`},{key:`metadata`,scope:`standard`,kind:`map`,summary:`Extra key: value pairs, both strings (author, version…).`,snippet:`
276
- author: `},{key:`allowed-tools`,scope:`standard`,kind:`tools`,summary:"Space-separated tools the skill may use without asking, like `Bash(git:*) Read`. Experimental."},{key:`when_to_use`,scope:`claude-code`,kind:`string`,summary:`More on when to use the skill, appended to the description in Claude Code's listing.`},{key:`argument-hint`,scope:`claude-code`,kind:`string`,summary:"Hint shown when typing the /command, like `[issue-number]`."},{key:`arguments`,scope:`claude-code`,kind:`tools`,summary:`Names for the /command's arguments, in order; use them as $name in the body.`},{key:`disable-model-invocation`,scope:`claude-code`,kind:`boolean`,summary:`true: only you can run it with its /command; Claude won't load it.`,snippet:`true`},{key:`user-invocable`,scope:`claude-code`,kind:`boolean`,summary:`false: hide it from the / menu, so only Claude loads it.`,snippet:`false`},{key:`disallowed-tools`,scope:`claude-code`,kind:`tools`,summary:`Tools taken away while the skill runs.`},{key:`model`,scope:`claude-code`,kind:`string`,summary:"Model to use while the skill runs, or `inherit`."},{key:`effort`,scope:`claude-code`,kind:{oneOf:[`low`,`medium`,`high`,`xhigh`,`max`]},summary:`Reasoning effort while the skill runs.`},{key:`context`,scope:`claude-code`,kind:{oneOf:[`fork`]},summary:"`fork` runs the skill in a subagent with its own context.",snippet:`fork`},{key:`agent`,scope:`claude-code`,kind:`string`,summary:"Subagent type to run in, with `context: fork`."},{key:`background`,scope:`claude-code`,kind:`boolean`,summary:"With `context: fork`, whether the subagent runs in the background."},{key:`hooks`,scope:`claude-code`,kind:`any`,summary:`Hooks registered while the skill is in use.`},{key:`paths`,scope:`claude-code`,kind:`tools`,summary:`Globs; Claude offers the skill when working on matching files.`},{key:`shell`,scope:`claude-code`,kind:{oneOf:[`bash`,`powershell`]},summary:"Shell for !`command` blocks in the body."}].map(e=>[e.key,e])),Qs=1024,$s=1536,ec=[`anthropic`,`claude`],tc=/<\/?[A-Za-z][^>]*>/;function nc(e){let t=[];e.files.length>Qn.maxFiles&&t.push(dc(`A skill can have at most ${Qn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=er(i.path);e&&t.push({severity:`error`,path:i.path,message:e}),r.has(i.path)&&t.push({severity:`error`,path:i.path,message:`Duplicate path.`}),r.add(i.path),i.size>Qn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${mc(Qn.maxFileBytes)}.`})}for(let e of r){let n=e.split(`/`);for(let i=1;i<n.length;i++){let a=n.slice(0,i).join(`/`);r.has(a)&&t.push({severity:`error`,path:a,message:`${a} is a file, so it can't also be the folder of ${e}.`})}}return n>Qn.maxSkillBytes&&t.push(dc(`The whole skill can be at most ${mc(Qn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(dc(`Every skill needs a ${G} at its root.`)),t):(t.push(...rc(e.skillMd,r,e.skills)),t)}function rc(e,t,n){let r=[],i=(e,t,n,i,a)=>r.push({severity:e,path:G,message:t,from:n,to:i,fix:a}),a=xi(e);if(!a.ok)return a.reason===`unclosed`?i(`error`,`The frontmatter has no closing --- line.`,0,3):i(`error`,`${G} must start with frontmatter: a --- line, name and description, and another --- line.`,0,Math.min(e.indexOf(`
227
+ <key>Label</key>\n <string>${t(Oa(e.api))}</string>\n <key>ProgramArguments</key>\n <array>\n`+n.map(e=>` <string>${t(e)}</string>\n`).join(``)+` </array>\n${r} <key>StartInterval</key>\n <integer>300</integer>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>/dev/null</string>\n <key>StandardErrorPath</key>\n <string>/dev/null</string>\n</dict>\n</plist>\n`}async function Ma(e){let t=e.platform??process.platform,n=e.run??Ta,r=ka(e.api,t,e.home);if(r.length===0)return{status:`skipped`,reason:`the heartbeat timer only runs on Linux (systemd) and macOS`};let i=t===`linux`?Aa(e):[ja(e)];if((await Promise.all(r.map(e=>O(e,`utf8`).catch(()=>null)))).every((e,t)=>e===i[t]))return{status:`already`};for(let[e,t]of r.entries())await D(g(t),{recursive:!0}),await A(t,i[e]);if(t===`linux`){await n(`systemctl`,[`--user`,`daemon-reload`]);let t=await n(`systemctl`,[`--user`,`enable`,`--now`,`${Da(e.api)}.timer`]);if(!t.ok)return await Ia(r),{status:`skipped`,reason:`systemd couldn't start it${t.output?`: ${t.output}`:``}`}}else{let t=`gui/${process.getuid?.()??501}`;await n(`launchctl`,[`bootout`,`${t}/${Oa(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await Ia(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function Na(e,{platform:t=process.platform,home:n,run:r=Ta}={}){if(!await Pa(e,t,n))return!1;let i=ka(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${Da(e)}.timer`]),await Ia(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Oa(e)}`]),await Ia(i)),!0}async function Pa(e,t=process.platform,n){let r=ka(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Fa(e=Ta,t=process.platform){if(t!==`linux`)return null;let n=process.env.USER;if(!n)return null;let{ok:r,output:i}=await e(`loginctl`,[`show-user`,n,`--property=Linger`]);return r&&i.trim()===`Linger=no`?"The timer stops while you're logged out of this machine. To keep it reporting, run `loginctl enable-linger`.":null}async function Ia(e){for(let t of e)await se(t,{force:!0})}async function La(e,t){let n=await X(Y(`global`)),r=tn().map(e=>e.id);return{machineId:await da(),hostname:ia()??`unknown`,platform:T(),arch:S(),cliVersion:Qt,agents:r,agentVersions:await xa(r,t),skills:Object.entries(n.skills).map(([e,t])=>({id:t.id,name:e,version:t.version,...t.channel&&{channel:t.channel},agents:t.agents})),every:e?300:null}}const Ra=()=>_(H(),`heartbeat.json`);async function za(){try{return JSON.parse(await O(Ra(),`utf8`))}catch{return null}}async function Ba(){try{if(In()||(await W()).heartbeat===!1)return!1;let e=await U();if(!e)return!1;let t={...await La(await Pa(V())),...e.organizationId&&{organizationId:e.organizationId}},n={sentAt:(/* @__PURE__ */ new Date()).toISOString(),ok:!0};try{n.organization=(await B(V(),e.token).sendHeartbeat(t,AbortSignal.timeout(5e3))).organization}catch{n.ok=!1}return await D(H(),{recursive:!0,mode:448}),await A(Ra(),JSON.stringify(n)+`
228
+ `),n.ok}catch{return!1}}async function Va(e=$i()){try{if(In()||(await W()).heartbeat===!1)return;let t=await U();if(!t||(t.organizationId||await Sa(B(V(),t.token),t).catch(()=>null),!e))return;let n=await Pa(V()),r=await ea(e);if((await Ma({node:process.execPath,script:r,api:V(),configDir:process.env.AGENT_KIT_CONFIG_DIR})).status===`installed`&&!n){I.info("This machine now reports to agent kit every 5 minutes (its name, agents and their versions, and global skills), so your organization's Machines page shows it. Turn it off with `a-kit heartbeat off`.");let e=await Fa();e&&I.warn(e)}await Ba()}catch{}}const Ha=e=>new Promise(t=>setTimeout(t,e));async function Ua(){let e=await B(V()).startLogin();I.step(`Opening agent kit in your browser. Log in, or sign up if you're new, and approve this code:\n\n ${e.userCode}\n\nIf it doesn't open, go to ${e.verificationUrl}`),Zi(e.verificationUrl);let t=Ut();t.start(`Waiting for you to approve it`);let n=B(V()),r=Date.now()+e.expiresIn*1e3;for(;Date.now()<r;){await Ha(e.interval*1e3);let r;try{r=await n.pollLogin(e.deviceCode)}catch(e){if(e instanceof z&&e.status===410)break;if(e instanceof z&&e.code===`NETWORK`)continue;throw t.error(`Login failed`),e}if(r.status===`approved`){let n={token:r.token,user:r.user,webUrl:new URL(e.verificationUrl).origin};return await Nn(n),t.stop(`Logged in as ${Ka(r.user)}`),await Va(),n}}throw t.error(`The code expired`),Error(`The login expired before it was approved. Run ${R(`login`)} again.`)}async function Wa(){let e=await U();if(!e)return null;try{let t=await B(V(),e.token).me();return{...e,user:t}}catch(t){if(t instanceof z&&t.status===401){if(await Nn(null),e.user.kind===`bot`)throw Error(`${Ka(e.user)} isn't logged in anymore: its token was revoked. Log in with a new one: ${R(`login --token`)} < bot-token`);return null}throw t}}async function Ga(){let e=await U();if(!e){if(!mn())throw Error(`You're not logged in. Run ${R(`login`)} first.`);I.info(`First, log in to agent kit. New here? You'll sign up on the way.`),e=await Ua()}return{api:B(V(),e.token),credentials:e}}const Ka=e=>e.kind===`bot`?`${e.name} (bot)`:e.email,qa=e=>`You don't have skills yet. Create or import one at ${e}/app/skills, then install it with ${R(`add`)}.`,Ja=`x-agent-kit-collector`,Ya=()=>_(H(),`collector`),Xa=()=>_(H(),`collector.json`),Za=e=>typeof e==`number`&&Number.isInteger(e)&&e>0&&e<65536;async function Qa(){let e={};try{e=JSON.parse(await O(Xa(),`utf8`))}catch{}let t={port:Za(e.port)?e.port:24318,secret:typeof e.secret==`string`&&/^[0-9a-f]{32}$/.test(e.secret)?e.secret:fe(16).toString(`hex`)};return(t.port!==e.port||t.secret!==e.secret)&&await eo(t),t}async function $a(e){if(!Za(e))throw Error(`${e} isn't a port.`);let t={...await Qa(),port:e};return await eo(t),t}async function eo(e){await D(H(),{recursive:!0,mode:448}),await A(Xa(),JSON.stringify(e,null,2)+`
229
+ `,{mode:384}),await te(Xa(),384)}const to=({port:e,secret:t})=>({CLAUDE_CODE_ENABLE_TELEMETRY:`1`,OTEL_METRICS_EXPORTER:`otlp`,OTEL_LOGS_EXPORTER:`otlp`,OTEL_EXPORTER_OTLP_PROTOCOL:`http/json`,OTEL_EXPORTER_OTLP_ENDPOINT:`http://127.0.0.1:${e}`,OTEL_EXPORTER_OTLP_HEADERS:`${Ja}=${t}`,OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:`cumulative`,OTEL_LOG_TOOL_DETAILS:`1`}),no=Object.keys(to({port:0,secret:``})),ro=e=>e.OTEL_EXPORTER_OTLP_HEADERS?.startsWith(`x-agent-kit-collector=`)??!1;function io(e){let t=e.env??{};return!ro(t)&&Object.keys(t).some(e=>/^OTEL_(EXPORTER_OTLP_(\w+_)?ENDPOINT|\w+_EXPORTER)$/.test(e))}const ao=(e,t)=>({...e,env:{...oo(e).env,...t}});function oo(e){if(!e.env||!ro(e.env))return e;let t=Object.fromEntries(Object.entries(e.env).filter(([e])=>!no.includes(e))),{env:n,...r}=e;return Object.keys(t).length>0?{...r,env:t}:r}const so=(e,t)=>t?Object.entries(t).every(([t,n])=>e.env?.[t]===n):!ro(e.env??{}),co=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`settings.json`),lo=(e,t)=>`node "${e}" hook claude-code --api "${t}"`,uo=e=>typeof e.command==`string`&&e.command.includes(`a-kit.mjs`)&&e.command.includes(` hook claude-code`),fo=[`telemetry`,`autoUpdate`],po={telemetry:[{event:`PostToolUse`,matcher:`Skill`},{event:`UserPromptSubmit`},{event:`SessionStart`,matcher:`startup|resume|clear`,role:`session`},{event:`Stop`},{event:`SessionEnd`}],autoUpdate:[{event:`SessionStart`,matcher:`startup|resume`}]},mo=(e,{role:t})=>t?`${e} ${t}`:e;function ho(e){if(!e.hooks)return e;let t={};for(let[n,r]of Object.entries(e.hooks)){if(!Array.isArray(r)){t[n]=r;continue}let e=r.map(e=>({...e,hooks:e.hooks?.filter(e=>!uo(e))})).filter((e,t)=>(e.hooks?.length??0)>0||!r[t].hooks);e.length>0&&(t[n]=e)}let{hooks:n,...r}=e;return Object.keys(t).length>0?{...r,hooks:t}:r}function go(e,t,n=fo){let r=ho(e),i={...r.hooks};for(let e of n.flatMap(e=>po[e])){let n={type:`command`,command:mo(t,e),...e.if&&{if:e.if},async:!0,timeout:10},{event:r,matcher:a}=e;i[r]=[...i[r]??[],a?{matcher:a,hooks:[n]}:{hooks:[n]}]}return Object.keys(i).length>0?{...r,hooks:i}:r}const _o=(e,t,n)=>e.hooks?.[t.event]?.some(e=>e.matcher===t.matcher&&e.hooks?.some(e=>uo(e)&&e.if===t.if&&(!n||e.command===mo(n,t))))??!1;function vo(e,t,n){return po[t].every(t=>_o(e,t,n))}function yo(e,t,n){return fo.every(r=>n.includes(r)?vo(e,r,t):po[r].every(t=>!_o(e,t)))}function bo(e){if(e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`){let t=e.tool_input?.skill??e.tool_input?.command,n=typeof t==`string`?t.replace(/^\//,``):``;return xo(n)?{name:n,trigger:`model`}:null}if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`){let t=e.prompt.match(/^\s*\/([^\s]+)/)?.[1]??``;return xo(t)?{name:t,trigger:`user`}:null}return null}const xo=e=>/^[a-z0-9][a-z0-9-]*$/.test(e);async function So(){let e=await W();return fo.filter(t=>e[t]!==!1)}async function Co(e=$i(),t=co(),n){let r=n??await So(),i=await ko(t);if(i===`invalid`)return{status:`skipped`,reason:`${t} isn't valid JSON`};let a=await wo(i,r.includes(`telemetry`)),o=a.elsewhere?{exportsElsewhere:!0}:{};if(r.length===0)return!fo.some(e=>vo(i,e))&&a.matches?{status:`already`}:(await Ao(t,a.apply(ho(i))),{status:`installed`,added:[]});if(!e)return{status:`skipped`,reason:`not running from a build`};let s=await ea(e),c=lo(s,V());if(yo(i,c,r)&&a.matches)return{status:`already`,...o};let l=r.filter(e=>!vo(i,e));return await Ao(t,a.apply(go(i,c,r))),{status:`installed`,added:l,...o}}async function wo(e,t){if(!t)return{apply:oo,matches:so(e,null),elsewhere:!1};if(io(e))return{apply:e=>e,matches:!0,elsewhere:!0};let n=to(await Qa());return{apply:e=>ao(e,n),matches:so(e,n),elsewhere:!1}}async function To(e=co()){let t=await ko(e);return t===`invalid`?`off`:io(t)?`elsewhere`:so(t,to(await Qa()))?`collector`:`off`}async function Eo(e=co()){let t=await ko(e);return t===`invalid`?[]:fo.filter(e=>vo(t,e))}const Do={telemetry:"Claude Code now reports to agent kit each time it loads one of these skills, when its sessions start and end, and what they used (tokens, cost and time, never what you or the agent wrote), so your organization sees which ones get used. `a-kit telemetry show` shows what was sent; turn it off with `a-kit telemetry off`.",autoUpdate:"Claude Code now checks the skills you installed everywhere (-g) for changes when a session starts, and updates them in the background when they changed. Turn it off with `a-kit auto-update off`."};async function Oo(e){if(e.includes(`claude-code`))try{let e=await Co();if(e.status===`installed`)for(let t of e.added)I.info(Do[t])}catch{}await Va()}async function ko(e){let t;try{t=await O(e,`utf8`)}catch{return{}}if(!t.trim())return{};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?e:`invalid`}catch{return`invalid`}}async function Ao(e,t){await D(g(e),{recursive:!0}),await A(e,JSON.stringify(t,null,2)+`
230
+ `)}const jo=/\breport --agent claude-code\b/;async function Mo(e){for(let t of e){let e=_(t,`report-session-issue`),n=await O(_(e,`SKILL.md`),`utf8`).catch(()=>null);n!==null&&jo.test(n)&&await se(e,{recursive:!0,force:!0})}}const No=e=>t=>rn(t.map(e=>nn(e)).filter(e=>e!==void 0),e);async function Po(e,t,n,r,i=`latest`,a){let o=rn(n,r),s=Y(r),c=await X(s);c.skills[`report-session-issue`]||await Mo(o);try{await Fo(e,c,t,n,o,i,a)}finally{await Bi(s,c)}return await Oo(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function Fo(e,t,n,r,i,a=`latest`,o){let s=n.find((e,t)=>n.some((n,r)=>r<t&&n.name===e.name));if(s)throw Error(`You picked more than one skill named "${s.name}"; they'd install to the same folder. Pick one.`);let c=Ut(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Li(e,o.id,i,a);l.push(n),t.skills[n.name]=Ri(n,r.map(e=>e.id),a),delete t.public?.[n.name],c.stop(`${n.name} v${n.version}`+(a===`latest`?``:` (${a})`)),a!==`latest`&&n.channels[a]===null&&I.warn(`${n.name} has no ${a} release yet, so you got the latest. \`a-kit update\` follows ${a} once someone sets it.`)}catch(e){throw c.error(`${o.name} failed`),e}}if(!o)return;let u=await Pi(await ji(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await Fo(e,t,u,r,i)}async function Io(e,t){Bt(`agent kit`);let n=!t.yes,r=yn(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(qi)&&await U()===null?null:await Ga(),a=i?.api??B(V()),o=r.skills.length>0||r.kits.length===0,s=i&&o?await a.listSkills():[],{own:c,others:l}=i?Ji(s,r.skills):{own:[],others:r.skills},u=await Yi(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){L(qa(i.credentials.webUrl));return}let f=d?await bn(s,c,n):[],p=u.find(e=>f.some(t=>t.name===e.name));if(p)throw Error(`${p.ref} and one of your skills are both named "${p.name}"; they'd install to the same folder. Pick one.`);let m=r.kits.length>0?await xn(await a.listKits(),r.kits,n):[];m.length>0&&t.channel!==`latest`&&I.warn(`--channel ${t.channel} applies to skills you name; kits install and follow each skill's latest version.`);let h=await gn(t.agent,n),g=t.global?`global`:`project`,_=rn(h,g),v=Y(g),y=await X(v);y.skills[`report-session-issue`]||await Mo(_);try{await Fo(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await Xi(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await Wi(a,y,e,{agents:h.map(e=>e.id),dirsOf:No(g),reinstall:!0}),n=e.skills.length-t.skipped.length;I.success(`kit/${e.name}: ${n} skill${n===1?``:`s`} installed`+(t.removed.length?`, ${t.removed.join(`, `)} removed (no longer in it)`:``))}}finally{await Bi(v,y)}await Oo(h.map(e=>e.id)),L(`Installed in ${_.map(G).join(`, `)}`)}const Lo=(e,t)=>{_e(process.execPath,[e,...t],{cwd:C(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},Ro=()=>_(H(),`auto-update.json`);async function zo(e=Date.now(),t=6e4,n=Ro()){if(Bo((await Vo(n)).startedAt,e,t))return!1;await D(g(n),{recursive:!0});let r=`${n}.claim`;try{await A(r,``,{flag:`wx`})}catch{let e=await ce(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await ue(r).catch(()=>{}),!1}try{let r=await Vo(n);return!Bo(r.startedAt,e,t)&&(await Ho(n,{...r,startedAt:e}),!0)}finally{await ue(r).catch(()=>{})}}const Bo=(e,t,n)=>typeof e==`number`&&t-e<n&&e<=t;async function Vo(e){try{let{startedAt:t,fingerprint:n}=JSON.parse(await O(e,`utf8`));return{...typeof t==`number`&&{startedAt:t},...typeof n==`string`&&{fingerprint:n}}}catch{return{}}}async function Ho(e,t){await D(g(e),{recursive:!0}),await A(e,JSON.stringify(t)+`
231
+ `)}const Uo=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function Wo(e,t=Lo,n=Date.now()){return(await W()).autoUpdate===!1||Uo(await X(Y(`global`)))||!await U()||!await zo(n)?!1:(t(e,[`auto-update`,`run`]),!0)}const Go=e=>({skills:Object.values(e.skills).map(e=>{let t=zi(e);return t===`latest`?{id:e.id}:{id:e.id,channel:t}}),kits:Object.values(e.kits).map(e=>e.id),public:Object.values(e.public??{}).map(e=>e.ref)});async function Ko(e,t,n=Ro()){try{let r=await X(Y(`global`));if(Uo(r))return`unchanged`;let{fingerprint:i}=await e.fingerprint(Go(r),AbortSignal.timeout(5e3));return(await Vo(n)).fingerprint===i?`unchanged`:(await t(),await Ho(n,{...await Vo(n),fingerprint:i}),`updated`)}catch{return`failed`}}const qo=6e3,Jo=()=>_(H(),`known-skills.json`);async function Yo(){try{let e=JSON.parse(await O(Jo(),`utf8`));return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}catch{return{}}}async function Xo(e){let t=await Yo();t[V()]=e,await D(H(),{recursive:!0,mode:448});let n=`${Jo()}.${process.pid}`;await A(n,JSON.stringify(t)+`
232
+ `),await oe(n,Jo())}const Zo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);async function Qo(e){let t=(await Yo())[V()];return!t||t.userId!==e||typeof t.checkedAt!=`string`||typeof t.triedAt!=`string`||!Zo(t.skills)?null:t}async function $o(e,t,n,r){let i=await e.listSkillSummaries(r),a={userId:t,checkedAt:n.toISOString(),triedAt:n.toISOString(),skills:{}};for(let e of i)a.skills[e.id]=e.organizationId;return await Xo(a),a}function es(e,t,n){if(!e)return!0;let r=e=>t.getTime()-(Date.parse(e)||0);return r(e.triedAt)<36e5?!1:r(e.checkedAt)>=864e5||!!n&&!(n in e.skills)}async function ts(e,t,n,r){try{return await Xo({userId:t,checkedAt:n?.checkedAt??(/* @__PURE__ */ new Date(0)).toISOString(),skills:n?.skills??{},triedAt:r.toISOString()}),await $o(e,t,r,AbortSignal.timeout(qo))}catch{return null}}async function ns(){try{if(In()||(await W()).telemetry===!1)return;let e=await U();if(!e)return;await $o(B(V(),e.token),e.user.id,/* @__PURE__ */ new Date,AbortSignal.timeout(qo))}catch{}}async function rs(e){Bt(`agent kit`),await ns();let t=e.global?`global`:`project`,n=Y(t),r=await X(n),i=Object.entries(r.public??{});if(Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0&&i.length===0){L(e.global?"No skills installed everywhere yet. Add some with `a-kit add -g`.":"No skills installed in this project yet. Add some with `a-kit add`.");return}let a=Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0?B(V(),(await U())?.token):(await Ga()).api,o=No(t),s=[...Object.values(r.skills).flatMap(e=>o(e.agents)),...Object.values(r.kits).flatMap(e=>o(e.agents)),...i.flatMap(([,e])=>o(e.agents))];r.skills[`report-session-issue`]||await Mo([...new Set(s)]);let c=0,l=0,u=0;for(let[e,t]of Object.entries(r.kits)){let i;try{i=await a.getKit(t.id)}catch(t){if(t instanceof z&&t.status===404){I.warn(`kit/${e} isn't in your agent kit anymore; left its skills as they are.`);continue}throw t}Ui(r,e,i.name);try{let e=await Wi(a,r,i,{agents:t.agents,dirsOf:o,reinstall:!1});for(let t of e.installed)I.success(`${t}: added to kit/${i.name}, installed`);for(let t of e.removed)I.success(`${t}: taken out of kit/${i.name}, removed`);c+=e.installed.length,l+=e.removed.length,u+=e.kept.length}finally{await Bi(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=zi(t),s;try{s=await a.getSkill(t.id,i)}catch(t){if(t instanceof z&&t.status===404){I.warn(`${e} isn't in your agent kit anymore; left it as it is.`);continue}throw t}if(s.version===t.version)continue;let c=o(t.agents),l=await Kn(c,e);if(l){I.warn(`${e} uses ${G(l)} (\`a-kit link\`); left it. \`a-kit add ${e}\` goes back to v${s.version}.`),u++;continue}let f=await Wn(a,e,t,c);if(f)I.warn(`${e} has edits here that aren't in agent kit (${Hn(f.paths)}); left it at v${t.version}. To keep them, make them in your organization's repository (\`a-kit link\` tries a skill from it); \`a-kit add ${e}\` throws them away.`),u++;else{if(await Li(a,t.id,c,i),s.name!==e){for(let t of c)await se(_(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Bi(n,r),I.success(`${s.name}: v${t.version} → v${s.version}`+(i===`latest`?``:` (${i})`)+(s.name===e?``:` (was ${e})`)),d++}}for(let[e,t]of i){let i;try{i=await a.getPublicSkill(t.ref)}catch(e){if(e instanceof z&&e.status===404){I.warn(`${t.ref} isn't public anymore; left it as it is.`);continue}throw e}if(i.version===t.version&&i.name===e)continue;if(i.name!==e&&r.skills[i.name]){I.warn(`${t.ref} is now named ${i.name}, like one of your skills; left it at v${t.version}.`);continue}let s=o(t.agents);if(await Li(Ii(a,i),t.ref,s),i.name!==e){for(let t of s)await se(_(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Bi(n,r),I.success(`${i.name}: v${t.version} → v${i.version} (${t.ref})`+(i.name===e?``:` (was ${e})`)),d++}await Oo([...new Set([...Object.values(r.skills),...Object.values(r.kits),...i.map(([,e])=>e)].flatMap(e=>e.agents))]),L(as(d,c,l,u))}const is=e=>`${e} skill${e===1?``:`s`}`;function as(e,t,n,r){let i=[e&&`updated ${is(e)}`,t&&`installed ${is(t)}`,n&&`removed ${is(n)}`].filter(Boolean),a=r?`Left ${is(r)} with local edits or links as they are.`:``;if(i.length===0)return a||`Everything is up to date.`;let o=i.join(`, `);return`${o[0].toUpperCase()}${o.slice(1)}.${a&&` ${a}`}`}async function os(e){switch(e){case`run`:{let e=await U();if(!e)return;await Ko(B(V(),e.token),()=>rs({global:!0,agent:[],yes:!0,channel:`latest`}));return}case`on`:{await Fn({autoUpdate:!0});let e=await Co();e.status===`skipped`?I.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):I.success(`Auto-update is on: when a Claude Code session starts, your global skills update if they changed.`);return}case`off`:await Fn({autoUpdate:!1}),await Co(),I.success("Auto-update is off. Update with `a-kit update -g`, or turn it back on with `a-kit auto-update on`.");return;case void 0:case`status`:{let e=(await W()).autoUpdate!==!1,t=(await Eo()).includes(`autoUpdate`);console.log(`Auto-update is ${e?`on`:`off`}.`),console.log(`Claude Code: ${t?`checks the global skills for changes when a session starts`:`no hook installed`}.`),console.log("\nWhen a Claude Code session starts, agent kit checks in the background whether the skills and kits you installed everywhere (-g) changed, and updates them when they did. A project's skills stay as they are until you run `a-kit update` there.");return}default:throw Error(`Unknown auto-update action "${e}". Use on, off or status.`)}}function ss(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}const cs=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function ls(e,t=!!process.stdout.isTTY&&!process.env.NO_COLOR){let n=(e,n)=>t?r(e,n):n;return e.map(e=>{let t=e.severity===`error`?n(`red`,`✗`):n(`yellow`,`▲`),r=e.path===null?`repository`:e.path+(e.line?`:${e.line}`:``);return`${t} ${e.message} ${n(`dim`,r)}`})}function us(e){let t=typeof e==`string`?e.trim():``;return t?t.length>64?{ok:!1,message:`Keep the name under 64 characters.`}:/^[a-z0-9-]+$/.test(t)?t.startsWith(`-`)||t.endsWith(`-`)||t.includes(`--`)?{ok:!1,message:`The name can't start or end with a hyphen, or have two in a row.`}:{ok:!0,name:t}:{ok:!1,message:`Use only lowercase letters, numbers and hyphens in the name.`}:{ok:!1,message:`Give the kit a name.`}}const ds=e=>`kits/${e}.yaml`;function fs(e){let t=/^kits\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function ps(e){let t;try{t=(0,hi.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
233
+ `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{skills:[]};let n="It has to list the kit's skills by name: `skills: [tdd, notes]`.";if(!ms(t))return{error:n};let{skills:r}=t;return r==null?{skills:[]}:!Array.isArray(r)||!r.every(e=>typeof e==`string`)?{error:n}:{skills:[...new Set(r.map(e=>e.trim()))]}}const ms=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function hs(e){let t;try{t=(0,hi.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
234
+ `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!ms(t))return{error:"It has to be a list of skills, each with its channels: `tdd: { stable: 7, beta: 9 }`."};let n={pins:/* @__PURE__ */ new Map,problems:[]};for(let[e,r]of Object.entries(t)){let t={};if(n.pins.set(e,t),r!==null){if(ms(r))for(let[i,a]of Object.entries(r))qt.includes(i)?Number.isInteger(a)&&Number(a)>0?t[i]=a:(t[i]=null,n.problems.push(`The ${i} channel of “${e}” has to be a version number, like 7.`)):n.problems.push(`“${e}” has a channel called “${i}”. Only stable and beta can be set.`);else{for(let e of qt)t[e]=null;n.problems.push(`“${e}” has to have its channels, like \`{ stable: 7 }\`.`)}}}return n}const gs=new Map([{key:`name`,scope:`standard`,kind:`string`,required:!0,summary:`The skill's id and its /command. 1–64 lowercase letters, numbers and single hyphens.`},{key:`description`,scope:`standard`,kind:`string`,required:!0,summary:`What the skill does and when to use it. The agent reads it to decide when to load the skill. Up to 1024 characters.`},{key:`license`,scope:`standard`,kind:`string`,summary:`A license name, or the path of a license file in the skill.`},{key:`compatibility`,scope:`standard`,kind:`string`,summary:`Environment the skill needs (tools, network, OS). Up to 500 characters; only add it when it matters.`},{key:`metadata`,scope:`standard`,kind:`map`,summary:`Extra key: value pairs, both strings (author, version…).`,snippet:`
235
+ author: `},{key:`allowed-tools`,scope:`standard`,kind:`tools`,summary:"Space-separated tools the skill may use without asking, like `Bash(git:*) Read`. Experimental."},{key:`when_to_use`,scope:`claude-code`,kind:`string`,summary:`More on when to use the skill, appended to the description in Claude Code's listing.`},{key:`argument-hint`,scope:`claude-code`,kind:`string`,summary:"Hint shown when typing the /command, like `[issue-number]`."},{key:`arguments`,scope:`claude-code`,kind:`tools`,summary:`Names for the /command's arguments, in order; use them as $name in the body.`},{key:`disable-model-invocation`,scope:`claude-code`,kind:`boolean`,summary:`true: only you can run it with its /command; Claude won't load it.`,snippet:`true`},{key:`user-invocable`,scope:`claude-code`,kind:`boolean`,summary:`false: hide it from the / menu, so only Claude loads it.`,snippet:`false`},{key:`disallowed-tools`,scope:`claude-code`,kind:`tools`,summary:`Tools taken away while the skill runs.`},{key:`model`,scope:`claude-code`,kind:`string`,summary:"Model to use while the skill runs, or `inherit`."},{key:`effort`,scope:`claude-code`,kind:{oneOf:[`low`,`medium`,`high`,`xhigh`,`max`]},summary:`Reasoning effort while the skill runs.`},{key:`context`,scope:`claude-code`,kind:{oneOf:[`fork`]},summary:"`fork` runs the skill in a subagent with its own context.",snippet:`fork`},{key:`agent`,scope:`claude-code`,kind:`string`,summary:"Subagent type to run in, with `context: fork`."},{key:`background`,scope:`claude-code`,kind:`boolean`,summary:"With `context: fork`, whether the subagent runs in the background."},{key:`hooks`,scope:`claude-code`,kind:`any`,summary:`Hooks registered while the skill is in use.`},{key:`paths`,scope:`claude-code`,kind:`tools`,summary:`Globs; Claude offers the skill when working on matching files.`},{key:`shell`,scope:`claude-code`,kind:{oneOf:[`bash`,`powershell`]},summary:"Shell for !`command` blocks in the body."}].map(e=>[e.key,e])),_s=1024,vs=1536,ys=[`anthropic`,`claude`],bs=/<\/?[A-Za-z][^>]*>/;function xs(e){let t=[];e.files.length>Jn.maxFiles&&t.push(As(`A skill can have at most ${Jn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=Xn(i.path);e&&t.push({severity:`error`,path:i.path,message:e}),r.has(i.path)&&t.push({severity:`error`,path:i.path,message:`Duplicate path.`}),r.add(i.path),i.size>Jn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${Ns(Jn.maxFileBytes)}.`})}for(let e of r){let n=e.split(`/`);for(let i=1;i<n.length;i++){let a=n.slice(0,i).join(`/`);r.has(a)&&t.push({severity:`error`,path:a,message:`${a} is a file, so it can't also be the folder of ${e}.`})}}return n>Jn.maxSkillBytes&&t.push(As(`The whole skill can be at most ${Ns(Jn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(As(`Every skill needs a ${K} at its root.`)),t):(t.push(...Ss(e.skillMd,r,e.skills)),t)}function Ss(e,t,n){let r=[],i=(e,t,n,i,a)=>r.push({severity:e,path:K,message:t,from:n,to:i,fix:a}),a=vi(e);if(!a.ok)return a.reason===`unclosed`?i(`error`,`The frontmatter has no closing --- line.`,0,3):i(`error`,`${K} must start with frontmatter: a --- line, name and description, and another --- line.`,0,Math.min(e.indexOf(`
277
236
  `)===-1?e.length:e.indexOf(`
278
237
  `),80),{label:`Add frontmatter`,from:0,to:0,insert:`---
279
238
  name: my-skill
280
239
  description:
281
240
  ---
282
241
 
283
- `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,uc(e.message),e.from,e.to);if(a.yamlErrors.length>0)return r;if(!a.isMapping)return i(`error`,`The frontmatter must be key: value lines.`,o.yamlFrom,o.yamlTo),r;let c=/* @__PURE__ */ new Map;for(let e of s)c.has(e.key)&&i(`error`,`\`${e.key}\` appears twice.`,e.keyFrom,e.keyTo),c.set(e.key,e);let l=o.yamlTo;for(let e of[`name`,`description`])c.has(e)||i(`error`,`The frontmatter needs a \`${e}\`.`,Math.max(0,o.yamlFrom-4),o.yamlFrom-1,{label:`Add ${e}`,from:l,to:l,insert:e===`name`?`name: my-skill
242
+ `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,ks(e.message),e.from,e.to);if(a.yamlErrors.length>0)return r;if(!a.isMapping)return i(`error`,`The frontmatter must be key: value lines.`,o.yamlFrom,o.yamlTo),r;let c=/* @__PURE__ */ new Map;for(let e of s)c.has(e.key)&&i(`error`,`\`${e.key}\` appears twice.`,e.keyFrom,e.keyTo),c.set(e.key,e);let l=o.yamlTo;for(let e of[`name`,`description`])c.has(e)||i(`error`,`The frontmatter needs a \`${e}\`.`,Math.max(0,o.yamlFrom-4),o.yamlFrom-1,{label:`Add ${e}`,from:l,to:l,insert:e===`name`?`name: my-skill
284
243
  `:`description:
285
- `});for(let e of s){let t=Zs.get(e.key);if(t)cc(t,e,i),t.scope===`claude-code`&&i(`warning`,`Only Claude Code reads \`${t.key}\`; claude.ai and the Skills API reject skills that have it.`,e.keyFrom,e.keyTo);else{let t=Zs.get(e.key.toLowerCase().replace(/_/g,`-`));i(`warning`,t?`Unknown field \`${e.key}\`. Did you mean \`${t.key}\`?`:`Unknown field \`${e.key}\`. Claude Code ignores it, and claude.ai and the Skills API reject the skill.`,e.keyFrom,e.keyTo,t?{label:`Rename to ${t.key}`,from:e.keyFrom,to:e.keyTo,insert:t.key}:void 0)}}let u=c.get(`name`);if(u&&typeof u.value==`string`)for(let e of oc(u.value)){let t=sc(u.value);i(`error`,e,u.valueFrom,u.valueTo,t&&t!==u.value?{label:`Change to ${t}`,from:u.valueFrom,to:u.valueTo,insert:t}:void 0)}let d=c.get(`description`);if(d&&typeof d.value==`string`){let e=d.value.trim(),t=[d.valueFrom,d.valueTo];if(e===``)i(`error`,ic,d.keyFrom,d.keyTo);else{let n=ac(e);for(let e of n.errors)i(`error`,e,...t);for(let e of n.warnings)i(`warning`,e,...t);let r=c.get(`when_to_use`)?.value,a=e.length+(typeof r==`string`?r.length:0);a>$s&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${$s}.`,...t)}}let f=c.get(`compatibility`);f&&typeof f.value==`string`&&f.value.length>500&&i(`error`,`compatibility can be at most 500 characters.`,f.valueFrom,f.valueTo);let p=c.get(`metadata`);if(p&&pc(p.value))for(let[e,t]of Object.entries(p.value))typeof t!=`string`&&i(`warning`,`metadata.${e} should be a string; quote it.`,p.valueFrom,p.valueTo);let m=c.get(`allowed-tools`);return m&&Array.isArray(m.value)&&i(`warning`,`The spec expects allowed-tools as one space-separated string; only Claude Code accepts a list.`,m.valueFrom,m.valueTo),lc(e,o.bodyFrom,t,n,i),r}const ic=`The description is empty. Say what the skill does and when to use it.`;function ac(e){let t=e.trim();if(t===``)return{errors:[ic],warnings:[]};let n=[],r=[];return t.length>Qs&&n.push(`The description is ${t.length} characters; the most is ${Qs}.`),tc.test(t)&&n.push(`The description can't contain XML tags.`),t.length<40&&r.push(`The description is short. Say what the skill does and when to use it, with the words a user would say.`),{errors:n,warnings:r}}function oc(e){if(e===``)return[`The name is empty.`];let t=[];e.length>64&&t.push(`The name is ${e.length} characters; the most is 64.`),/^[a-z0-9-]+$/.test(e)?((e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`The name can't start or end with a hyphen.`),e.includes(`--`)&&t.push(`The name can't have two hyphens in a row.`)):t.push(`Use only lowercase letters, numbers and hyphens in the name.`);let n=ec.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function sc(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of ec)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function cc(e,t,n){let{value:r}=t,i=[t.valueFrom,t.valueTo],a=e.kind;if(r===null)e.required&&n(`error`,`\`${e.key}\` is empty.`,t.keyFrom,t.keyTo);else if(a===`string`&&typeof r!=`string`)n(`error`,`\`${e.key}\` must be text.`,...i);else if(a===`boolean`&&typeof r!=`boolean`){let t=typeof r==`string`?fc(r):null;n(`error`,`\`${e.key}\` must be true or false.`,...i,t===null?void 0:{label:`Change to ${t}`,from:i[0],to:i[1],insert:String(t)})}else a===`map`&&!pc(r)?n(`error`,`\`${e.key}\` must be indented key: value lines.`,...i):a===`tools`&&typeof r!=`string`&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`))?n(`error`,`\`${e.key}\` must be a space-separated list of names.`,...i):typeof a==`object`&&!a.oneOf.includes(String(r))&&n(`error`,`\`${e.key}\` must be one of: ${a.oneOf.join(`, `)}.`,...i)}function lc(e,t,n,r,i){let a=e.slice(t);if(a.trim()===``){i(`warning`,`The skill has no instructions yet. Write them below the frontmatter.`,Math.max(0,t-4),t);return}let o=a.split(`
286
- `).length;o>500&&i(`warning`,`${G} has ${o} lines below the frontmatter. Keep it under 500 and move details to other files it links to.`,t,t+a.indexOf(`
287
- `));for(let{path:a,from:o,to:s}of Oi(e,t)){if(a.startsWith(`/`)){i(`warning`,`Link to files with a path relative to SKILL.md, without a leading /.`,o,s);continue}let e=rr(G,a);if(e===null){let e=ki(a);if(e&&r?.has(e))continue;i(`warning`,e&&r?`There's no skill named \`${e}\` in this organization.`:`This link points outside the skill.`,o,s)}else!n.has(e)&&![...n].some(t=>t.startsWith(`${e}/`))&&i(`warning`,`There's no ${e} in this skill.`,o,s)}}function uc(e){return/nested mappings|implicit keys/i.test(e)&&!/map values/i.test(e)?`This value has a colon in it. Wrap the whole value in quotes.`:/implicit map keys need to be followed by map values/i.test(e)?"Each frontmatter line needs a key, a colon and a value, like `key: value`.":`YAML: ${e.replace(/\.$/,``)}.`}function dc(e){return{severity:`error`,path:null,message:e}}function fc(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function pc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mc(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const hc=`channels.yaml`;function gc(e,t){let n=`${t}/`,r=/* @__PURE__ */ new Map,i=[];for(let t of e){if(!t.path.startsWith(n))continue;let e=t.path.slice(n.length),a=e.indexOf(`/`);if(a===-1){i.push(e);continue}let o=e.slice(0,a),s=r.get(o)??[];s.push({path:e.slice(a+1),size:t.size}),r.set(o,s)}return{folders:[...r].sort(([e],[t])=>e.localeCompare(t)),loose:i}}function _c(e){return gc(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===G)).map(([e])=>e)}function vc(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(_c(t));e.truncated&&r.push({severity:`warning`,path:null,message:`The repository has more files than GitHub lists at once, so some weren't checked.`}),i.size>300&&r.push({severity:`warning`,path:`skills`,message:`Only the first 300 skills were checked.`});let a=gc(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${G} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${G}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of nc({files:t,skillMd:s,skills:n}))o.push({severity:e.severity,path:e.path===null?a:`${a}/${e.path}`,...e.path===`SKILL.md`&&e.from!==void 0?{line:vs(s,e.from)}:{},message:e.message});let r=Si(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${G}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:Si(s).description,files:t.length,errors:o.filter(e=>e.severity===`error`).length,warnings:o.filter(e=>e.severity===`warning`).length}}),o=(e,t,n)=>{for(let i of n)t.some(e=>e.path===i)||r.push({severity:`error`,path:e,message:`It needs a ${i}.`})},s=gc(t,`evals`).folders.map(([e])=>{let n=`evals/${e}`;i.has(e)||r.push({severity:`warning`,path:n,message:`There's no skill named “${e}” in skills/, so these evals have nothing to test.`});let a=gc(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=gc(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=gc(t,`${i}/tasks`).folders;for(let[e,t]of a)o(`${i}/tasks/${e}`,t,[`task.yaml`,`prompt.md`]);return a.length===0&&r.push({severity:`warning`,path:i,message:`It has no tasks yet: add one in tasks/<task>/.`}),{name:e,tasks:a.length}});if(typeof e.channelsText==`string`){let t=Es(e.channelsText),n=(e,t)=>r.push({severity:e,path:hc,message:t});if(`error`in t)n(`error`,`${t.error} No channel was changed.`);else{for(let e of t.problems)n(`error`,e);for(let e of t.pins.keys())i.has(e)||n(`warning`,`There's no skill named “${e}” in skills/, so its channels set nothing.`)}}let l=[];for(let n of gc(t,`kits`).loose){let t=`kits/${n}`,a=Cs(t);if(a===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are kits: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}l.push(a);let o=(e,n)=>r.push({severity:e,path:t,message:n}),s=xs(a);if(!s.ok||s.name!==a){o(`error`,`“${a}” can't be a kit's name, so this file isn't read. ${s.ok?`Take out the spaces.`:s.message}`);continue}let c=e.kitTexts?.get(t);if(c===void 0)continue;let u=ws(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}let u=[],d=[];for(let n of gc(t,Ns).loose){let t=`${Ns}/${n}`,i=Is(t);if(i===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are flows: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}u.push(i);let a=Rs(i);if(a){r.push({severity:`error`,path:t,message:a});continue}let o=e.flowTexts?.get(t);if(o===void 0)continue;let s=Vs(o);for(let e of s.roles)d.push({path:t,...e.line===null?{}:{line:e.line},name:e.name});for(let e of s.problems)r.push({severity:`error`,path:t,...e.line===null?{}:{line:e.line},message:e.message})}return{skills:a,evals:s,benchmarks:c,fixtures:gc(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),flows:u.sort((e,t)=>e.localeCompare(t)),flowRoles:d,channels:t.some(e=>e.path===hc),problems:yc(r)}}const yc=e=>e.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0));function bc(e,t){let n=(e.flowRoles??[]).filter(e=>!t.has(e.name));return n.length===0?e:{...e,problems:yc([...e.problems,...n.map(e=>({severity:`warning`,path:e.path,...e.line===void 0?{}:{line:e.line},message:`There's no role “${e.name}” in the organization. Name it in Settings → Roles, or fix the name.`}))])}}const xc=(e,t,n)=>`There's a ${e} called “${t}” in ${n} already, and a name is one in the organization. This one isn't read: rename it, or take it out of one of them.`;function Sc(e,t){let n=[],r=`${Ns}/`,i=e=>t.main!==null&&e!==null&&(e===`channels.yaml`||e.startsWith(r));n.push(...e.problems.filter(e=>!i(e.path))),t.main!==null&&e.channels&&n.push({severity:`warning`,path:hc,message:`It's ignored: release channels are only read from the main repository, ${t.main}.`}),t.main!==null&&(e.flows??[]).length>0&&n.push({severity:`warning`,path:Ns,message:`They're ignored: flows are only read from the main repository, ${t.main}.`});let a=e.skills.map(e=>{let r=t.skills.get(e.name);return r===void 0?e:(n.push({severity:`error`,path:`skills/${e.name}`,message:xc(`skill`,e.name,r)}),{...e,errors:e.errors+1})});for(let r of e.kits){let e=t.kits.get(r);e!==void 0&&n.push({severity:`error`,path:Ss(r),message:xc(`kit`,r,e)})}return{...e,skills:a,problems:yc(n)}}const Cc={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},wc=/^[A-Za-z0-9._:-]{1,128}$/,Tc=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,Ec=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Dc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Oc=/[\u0000-\u001f\u007f]/;function kc(e){let t=e.trim(),n=Ec.exec(t)??Dc.exec(t);if(!n)return null;let[,r,i]=n,a=i.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);if(a.length<2)return null;let o=[r,...a].join(`/`).toLowerCase();return Ac(o)?o:null}const Ac=e=>Tc.test(e)&&e.length<=Cc.maxRepositoryLength,jc=e=>e.length>0&&e.length<=Cc.maxBranchLength&&e.trim()===e&&!Oc.test(e),Mc={sessionId:null,repository:null,branch:null,audience:null},Nc=e=>typeof e==`string`&&e?e:null;async function Pc(e,t,n=C(),r=null){let i=Nc(e),a=ba(t,n)!==null;if(!a&&!r)return{...Mc,sessionId:i};let{repository:o,branch:s}=await Ic(t),c=o?r?.repositories[o]:void 0,l=a?`any`:c?{organizationId:c}:null;return l?{sessionId:i,repository:o,branch:s,audience:l}:{...Mc,sessionId:i}}function Fc({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function Ic(e){let[t,n]=await Promise.all([zc(e,[`remote`,`get-url`,`origin`]),zc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?kc(t):null,branch:n}}async function Lc(e,t){if(Rc.includes(t))return!0;let n=await zc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const Rc=[`main`,`master`,`develop`];function zc(e,t){return new Promise(n=>{try{ye(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const Bc=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],Vc=e=>{try{return p(e).isDirectory()}catch{return!1}};function Hc(e){let t;for(let n=b(e);;n=g(n)){if(t??=Vc(_(n,`skills`))?n:void 0,f(_(n,`.git`))){if(Vc(_(n,`skills`)))return n;throw Error(`${W(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(g(n)===n)break}if(t)return t;throw Error(`There's no skills/ folder here. Run this in a clone of your organization's repository.`)}async function Uc(e){let t=[];for(let n of Bc){let r=_(e,n);if(Vc(r))for(let n of await ce(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=_(n.parentPath,n.name),i=y(e,r).split(x).join(`/`);Hn(i)||t.push({path:i,size:(await fe(r)).size})}}return f(_(e,`channels.yaml`))&&t.push({path:hc,size:(await fe(_(e,hc))).size}),t}async function Wc(e){let t=await Uc(e),n=/* @__PURE__ */ new Map;for(let r of _c(t))n.set(r,await O(_(e,`skills`,r,G),`utf8`));let r=t.some(e=>e.path===`channels.yaml`)?await O(_(e,hc),`utf8`):null,i=/* @__PURE__ */ new Map;for(let{path:n}of t)Is(n)!==null&&i.set(n,await O(_(e,n),`utf8`));return vc({files:t,skillMds:n,channelsText:r,flowTexts:i})}const Gc=1e4,Kc=(e,t)=>t.aborted?`agent kit didn't answer in time`:e instanceof Error?e.message:String(e);async function qc(e,t,n=Gc){if(!e.flowRoles?.length)return{scan:e,unchecked:null};let r=t=>({scan:e,unchecked:`Roles in flows weren't checked: ${t}`});if(!t)return r(`log in with ${L(`login`)} to check them against your organization's.`);let i=AbortSignal.timeout(n);try{let n=t.organizationId;if(!n){let e=await t.api.listOrganizations(i);if(e.length===0)return r(`you're in no organization.`);if(e.length>1)return r(`you're in more than one organization. Pick yours with ${L(`org use`)}.`);n=e[0].id}let a=await t.api.listRoles(n,i);return{scan:bc(e,new Set(a.map(e=>e.name))),unchecked:null}}catch(e){return r(`couldn't get your organization's roles (${Kc(e,i)}).`)}}const Jc=`Skill names in your organization's other repositories`;async function Yc(e,t,n){let r=await e.listOrganizations(n),i=await Promise.all(r.map(t=>e.getRepository(t.id,n).then(e=>({organizationId:t.id,status:e})).catch(e=>{if(e instanceof R&&(e.status===403||e.status===404))return null;throw e})));for(let e of i){if(!e)continue;let n=e.status.repositories??(e.status.repository?[e.status.repository]:[]),r=n.find(e=>`github.com/${e.fullName.toLowerCase()}`===t);if(!r)continue;let i=n.find(e=>e.main);return{organizationId:e.organizationId,fullName:r.fullName,placement:{main:r.main?null:i?.fullName??null,skills:new Map(Object.entries(r.elsewhere?.skills??{})),kits:new Map(Object.entries(r.elsewhere?.kits??{}))}}}return null}async function Xc(e,t,n,{roles:r=!0,timeoutMs:i=Gc}={}){let a=r&&(e.flowRoles?.length??0)>0?`${Jc} and roles in flows`:Jc;if(!n)return{scan:e,unchecked:`${a} weren't checked: log in with ${L(`login`)} to check them.`,place:null};let o=null;if(t){let r=AbortSignal.timeout(i);try{o=await Yc(n.api,t,r)}catch(t){return{scan:e,unchecked:`${a} weren't checked: couldn't get your organization's repositories (${Kc(t,r)}).`,place:null}}}if(o){let t=Sc(e,o.placement);return!r||o.placement.main!==null?{scan:t,unchecked:null,place:o}:{...await qc(t,{api:n.api,organizationId:o.organizationId},i),place:o}}let s=r?await qc(e,n,i):{scan:e,unchecked:null},c=t?`${Jc} weren't checked: agent kit reads no repository at ${t}.`:null;return{scan:s.scan,unchecked:[c,s.unchecked].filter(Boolean).join(`
288
- `)||null,place:null}}async function Zc(e,t,n){let r=await H();return Xc(t,(await Ic(e)).repository,r&&{api:z(B(),r.token),organizationId:r.organizationId},n)}function Qc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=b(n,i);if(Vc(t)){if(t===e||t===_(e,`skills`))return[];if(g(t)===_(e,`skills`)){r.push(m(t));continue}let n=y(_(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(x)[0]);continue}throw Error(`${W(t)} isn't a skill's folder. Skills are in ${W(_(e,`skills`))}/<skill>/.`)}if(!/^[a-z0-9-]+$/.test(i))throw Error(`There's no folder ${i}, and it isn't a skill's name.`);r.push(i)}return[...new Set(r)]}const $c=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function el(e){let t=Hc(e.find(e=>e.includes(`/`))??`.`),n=Qc(t,e),r=await Wc(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${W(t)}.`);let{scan:o,unchecked:s,place:c}=await Zc(t,r,{roles:n.length===0}),l=c?.placement.main?0:o.flows?.length??0,u=n.length>0?$c(o.problems,n):o.problems;for(let e of bs(u))console.log(e);s&&console.log(`${u.length?`
289
- `:``}${s}`);let d=u.filter(e=>e.severity===`error`).length,f=u.length-d,p=n.length===1?n[0]:n.length>0?ys(n.length,`skill`):`The repository (${[ys(o.skills.length,`skill`),...l?[ys(l,`flow`)]:[]].join(`, `)})`;d>0?(console.log(`\n${p}: ${ys(d,`error`)}`+(f?`, ${ys(f,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((u.length||s?`
290
- `:``)+`${p}: no errors`+(f?`, ${ys(f,`warning`)}`:``)+`.`)}const tl=9e5,nl=e=>Math.floor(e/tl)*tl,rl={maxPerRequest:20,maxEntries:1e3,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Z={inputTokens:`tokens.input`,outputTokens:`tokens.output`,cacheReadTokens:`tokens.cache_read`,cacheCreationTokens:`tokens.cache_creation`,costUsd:`cost.usd`,personSeconds:`active.person`,agentSeconds:`active.agent`,prompts:`prompts`,commits:`commits`,pullRequests:`pull_requests`},il=/* @__PURE__ */ new Set([Z.personSeconds,Z.agentSeconds,Z.costUsd]),al=e=>typeof e==`string`&&e.length>0&&e.length<=rl.maxModelLength&&!/\s/.test(e)&&!Oc.test(e),ol={maxPerRequest:100,maxLinks:50,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},sl=/^[1-9][0-9]{0,8}$/,cl=/\s/,ll=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function ul(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Ac(t)?{kind:e,value:t}:null}case`branch`:case`issue`:case`pull_request`:case`touched`:{let t=n.indexOf(`#`);if(t<0)return null;let r=n.slice(0,t).toLowerCase(),i=n.slice(t+1);return Ac(r)&&(e===`branch`?jc(i):sl.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return fl(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=ol.maxThreadLength&&!cl.test(n)&&!Oc.test(n)?{kind:e,value:n}:null;case`session`:return wc.test(n)?{kind:e,value:n}:null;default:return null}}function dl(e){let t=e.trim();return ul(`slack_thread`,t)??ul(`thread`,t)}function fl(e){return e.length<=ol.maxUrlLength&&ll.test(e)}const pl=()=>_(V(),`sessions`),ml=()=>_(V(),`pending-session-events.jsonl`),hl=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function gl(e,t){switch(e.hook_event_name){case`SessionStart`:return t===`session`?`start`:null;case`SessionEnd`:return`end`;case`UserPromptSubmit`:case`PostToolUse`:case`Stop`:return`seen`;default:return null}}function _l(e,t){let n=e.trimStart().split(`
291
- `)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim(),i=r&&/^(?:[a-z][a-z-]*\s+)?(\S+)$/.exec(r)?.[1];if(!i)return[];let a=yl(i,t,e=>e===`pull`?`pull_request`:`issue`);return a?[a]:[]}const vl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/(issues|pull)\/(\d+)(?:[/?#]\S*)?$/;function yl(e,t,n){let r=vl.exec(e);return r?ul(n(r[2]),`${r[1]}#${r[3]}`):t&&/^#?\d+$/.test(e)?ul(n(null),`${t}#${e.replace(`#`,``)}`):null}function bl(e,t,n){let r=[],i=e=>{e&&!r.some(t=>t.kind===e.kind&&t.value===e.value)&&r.push(e)};for(let r of e.split(/&&|\|\||[;|\n]/)){let e=wl(r);for(;e[0]&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[0]);)e.shift();let[a,o,s,...c]=e;if(a!==`gh`)continue;if(s===`create`&&(o===`pr`||o===`issue`)){let e=RegExp(`https://(github\\.com/[^\\s/]+/[^\\s/]+)/${o===`pr`?`pull`:`issues`}/(\\d+)`).exec(t);e&&i(ul(o===`pr`?`pull_request`:`touched`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`&&o!==`pr`||!(o===`issue`?xl:Sl).has(s??``))continue;let l=n,u=null;for(let[e,t]of c.entries()){let n=/^(?:-R|--repo)(?:=(.*))?$/.exec(t);if(n){let t=n[1]??c[e+1];t&&(l=Cl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||vl.test(t))&&(u=t)}u&&i(yl(u,l,()=>`touched`))}return r}const xl=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),Sl=/* @__PURE__ */ new Set([`comment`,`edit`]),Cl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function wl(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function Tl(e){if(e.hook_event_name!==`PostToolUse`||e.tool_name!==`Bash`||typeof e.tool_input?.command!=`string`)return null;let t=e.tool_response?.stdout;return{command:e.tool_input.command,stdout:typeof t==`string`?t:``}}function El(e){if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`)return e.prompt;let t=e.tool_input;return e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`&&typeof t?.skill==`string`&&typeof t.args==`string`?`/${t.skill.replace(/^\//,``)} ${t.args}`:null}async function Dl(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=gl(t,n),l=i.sessionId;if(!c||!l||!wc.test(l))return null;c===`end`&&t.reason===`clear`&&await Ll(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(ul(`repository`,i.repository)),i.branch&&!await Lc(r,i.branch)&&d(ul(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=El(t);if(p&&f)for(let e of _l(p,i.repository))d(e);let m=Tl(t);if(m&&f)for(let e of bl(m.command,m.stdout,i.repository))d(e);if(c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&f)for(let t of e.split(/\s+/))d(dl(t));if(t.source===`clear`){let e=await Rl(r,l,o,s);e&&d(ul(`session`,e))}}let h=await Al(l),g=u.map(Pl),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await Fl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await zl(o),{sessionId:l,agent:e,machineId:await xa(),machineName:ma(),type:c,occurredAt:o.toISOString(),links:u})}const Ol=(e,t=[])=>ha(ml(),e,t),kl=e=>_(pl(),`${hl(e)}.json`);async function Al(e){try{let t=JSON.parse(await O(kl(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[],...t.imported===!0&&{imported:!0}}}catch{return{sentAt:0,links:[]}}}const jl=async e=>(await Al(e)).links;async function Ml(e,t){let n=await Al(e);await Fl(e,{sentAt:n.sentAt,links:[.../* @__PURE__ */ new Set([...n.links,...t.map(Pl)])],imported:!0})}async function Nl(e){try{return JSON.parse(await O(kl(e),`utf8`)).imported!==!0}catch{return!1}}const Pl=e=>`${e.kind} ${e.value}`;async function Fl(e,t){await D(pl(),{recursive:!0,mode:448}),await k(kl(e),JSON.stringify(t)+`
292
- `)}const Il=e=>_(pl(),`cleared-${hl(e)}.json`);async function Ll(e,t,n){await D(pl(),{recursive:!0,mode:448}),await k(Il(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
293
- `)}async function Rl(e,t,n,r){let i=Il(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await de(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Te(100)}}async function zl(e){try{for(let t of await ce(pl())){let n=_(pl(),t),{mtimeMs:r}=await fe(n);e.getTime()-r>6048e5&&await de(n,{force:!0})}}catch{}}function Bl(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await X(n.projectLock):null,a=await X(Y(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await ls(r.userId),d=!u||n.repository!==null&&!Object.hasOwn(u.repositories,n.repository)||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await fs(r.api,r.userId,u,new Date(s))??u),(u&&Vl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function Vl(e,t,n,r){let{repository:i}=e,a=i&&Object.hasOwn(r.repositories,i)?r.repositories[i]:null;if(!a){let e=/* @__PURE__ */ new Map;for(let{id:n}of Object.values(t?.skills??{})){let t=r.skills[n];t&&e.set(t,(e.get(t)??0)+1)}a=[...e.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null}if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const Hl={"claude_code.token.usage":{input:Z.inputTokens,output:Z.outputTokens,cacheRead:Z.cacheReadTokens,cacheCreation:Z.cacheCreationTokens},"claude_code.cost.usage":Z.costUsd,"claude_code.active_time.total":{user:Z.personSeconds,cli:Z.agentSeconds},"claude_code.commit.count":Z.commits,"claude_code.pull_request.count":Z.pullRequests};function Ul(e){let t=[];for(let n of ql(Q(e,`resourceMetrics`)))for(let e of ql(Q(n,`scopeMetrics`)))for(let n of ql(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?Hl[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of ql(Q(i,`dataPoints`))){let i=ql(Q(n,`attributes`)),o=e=>Jl(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Yl(Q(n,`asDouble`)??Q(n,`asInt`)),u=Xl(Q(n,`startTimeUnixNano`)),d=Xl(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Gl(e,i,a?u:null),metric:c,model:Kl(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Wl(e){let t=[];for(let n of ql(Q(e,`resourceLogs`)))for(let e of ql(Q(n,`scopeLogs`)))for(let n of ql(Q(e,`logRecords`))){let e=ql(Q(n,`attributes`)),r=Jl(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Jl(e,`session.id`),a=Xl(Q(n,`timeUnixNano`))??Xl(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Gl(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return he(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const Kl=e=>al(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,ql=e=>Array.isArray(e)?e:[];function Jl(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Yl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Xl(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const Zl=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function Ql(e){let t=()=>_(ao(),e),n=e=>_(t(),`${Zl(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
294
- `)},async list(){let e=[];try{e=await ce(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(_(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await ce(t())){let r=_(t(),n);e-(await fe(r)).mtimeMs>6048e5&&await de(r,{force:!0})}}catch{}}}}const $l=Ql(`sessions`),eu=e=>$l.write(e.sessionId,e);async function tu(e){let t=await $l.read(e);return t?.sessionId===e?t:null}const nu=(e=Date.now())=>$l.forgetOld(e),ru=Ql(`sent`),iu=(e,t,n=/* @__PURE__ */ new Date)=>ru.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),au=e=>ru.read(e),ou=async()=>(await ru.list()).sort((e,t)=>t.at.localeCompare(e.at)),su=(e=Date.now())=>ru.forgetOld(e),cu=(e,t)=>({sessionId:e,epoch:t,series:{},slices:{},prompts:0,lastAt:t});function lu(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n],l=o;if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;l=Math.max(0,o-(c?.value??0)),e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}if(il.has(r)&&l>0){let t=nl(s),n=e.slices??={},o=JSON.stringify([r,i,a,t]),c=n[o]??={metric:r,model:i,skillName:a,start:t,value:0};c.value+=l}return e.lastAt=Math.max(e.lastAt,s),!0}function uu(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)},i=e=>e!==null&&Object.hasOwn(t.skillIds,e)?t.skillIds[e]:null;for(let t of Object.values(e.series))il.has(t.metric)||r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),value:t.value});for(let t of Object.values(e.slices??{}))r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),end:new Date(t.start+tl).toISOString(),value:t.value});return e.prompts>0&&r({metric:Z.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Number(!!e.entry.end)-Number(!!t.entry.end)||Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,rl.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const du=Ql(`state`);function fu(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=pu(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);lu(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await du.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await du.write(e.state.sessionId,e.state))}}}async function pu(e,t){let n=await du.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:cu(e,t),unsaved:!1}}const mu=(e=Date.now())=>du.forgetOld(e),hu=16777216,gu=()=>_(V(),`pending-session-usage.jsonl`);async function _u(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=fu(),s=Bl(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new R(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!_a(e))for(let e of t)await iu(e,`refused`);throw e}for(let e of t)await iu(e,`sent`)}),p=(e=[])=>ha(gu(),f,e,{batch:rl.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await tu(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=uu(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await xa(),machineName:ma(),skillIds:i.skillIds});a.usage.length!==0&&(await iu(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),wa(h),Ol(g)]);function v(e){let t=xu(e.activations),n=xu(e.sessionEvents);return u(()=>Promise.all([t.length>0&&wa(h,t),n.length>0&&Ol(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(ee(),!S(t.headers[`x-agent-kit-collector`]))return t.resume(),bu(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return bu(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),bu(n,404,{});if(i===`/stop`){t.resume(),bu(n,200,{}),se({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),bu(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),bu(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),bu(n,415,{message:`Send JSON.`});let a=await yu(t);if(!a.ok)return bu(n,a.status,{});i===`/report`?(bu(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?Ul(a.json):Wl(a.json)),b(),bu(n,200,{}))}let S=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ve(t,c)},C=Ce((e,t)=>{x(e,t).catch(()=>{t.headersSent||bu(t,500,{})})});if(!await new Promise(t=>{C.once(`error`,()=>t(!1)),C.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let w=null,T=Date.now(),E=e=>{w&&clearTimeout(w),w=setTimeout(()=>void te(),e)};function ee(){T=Date.now(),E(i)}async function te(){let e=T,t=!1;if(await u(async()=>{let e=[gu(),Ca(),ml()];t=(await Promise.all(e.map(ga))).some(Boolean)||(await o.dirty()).length>0}),D||T!==e)return;let n=Date.now()-T;t&&n<a?E(Math.max(1,Math.min(i,a-n))):se()}ee();let ne=setInterval(()=>void u(m),t),re=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await nu(e),await mu(e),await su(e),await o.resume()});let ie=()=>u(m).then(()=>u(_)),ae=()=>{},oe=new Promise(e=>ae=e),D=null;function se({send:e=!0}={}){return D??=(async()=>{w&&clearTimeout(w),y&&clearTimeout(y),clearInterval(ne),clearInterval(re);let t=new Promise(e=>C.close(()=>e()));C.closeIdleConnections(),await(e?ie():u(()=>o.save())),C.closeAllConnections(),await t,ae()})(),D}return{port:C.address().port,flush:ie,stop:se,stopped:oe}}const vu=n(we);async function yu(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>hu)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await vu(r,{maxOutputLength:hu})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function bu(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const xu=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function Su(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await co();await(await _u({port:t,secret:n,apiUrl:B(),login:async()=>{let e=await H();return e?{api:z(B(),e.token),userId:e.user.id}:null}}))?.stopped}const Cu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,wu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function Tu(e){let t=0;for(let[n]of e.matchAll(wu)){let e=n[0];if(e===`
295
- `)t+=1;else if(/\s/.test(e))t+=n.length===1?0:Math.ceil(n.length/4);else if(/\p{L}/u.test(e)){let e=0;for(let t of n)Cu.test(t)&&e++;let r=[...n].length-e;t+=e+Math.ceil(r/6)}else/\p{N}/u.test(e)?t+=Math.ceil(n.length/3):t+=1}return t}function Eu(e){return{always:e.description,max:e.description+e.body+e.files}}function Du(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=Eu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function Ou(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${Au((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${Au((e/1e6).toFixed(1))}M`}const ku=(e,t)=>`${t===`estimate`?`~`:``}${Ou(e)}`,Au=e=>e.replace(/\.0$/,``),ju={high:15,medium:10,low:5},Mu=5e3,Nu=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function Pu(e){let t=nr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&Nu.has(n)}const Fu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Iu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Lu(e,t){let n=t(`SKILL.md`)??``,r=xi(n),i=e=>r.ok?r.entries.find(t=>t.key===e):void 0,a=i(`description`)?.value,o=i(`when_to_use`)?.value,s=r.ok?r.body:n,c=s.trim(),l=new Set(e.map(e=>e.path)),u=e=>l.has(e)||[...l].some(t=>t.startsWith(`${e}/`)),d=/* @__PURE__ */ new Set([G]),f=/* @__PURE__ */ new Set,p=!1,m=[G];for(;m.length>0;){let n=m.shift(),r=n===`SKILL.md`?s:t(n);if(r===void 0)Pu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Yu(r)){let t=rr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Xu(r,n,t.path)&&(d.add(t.path),Pu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!Fu.test(nr(e))).filter(e=>!nr(e).startsWith(`.`)).sort();return{v:1,description:typeof a==`string`&&a.trim()!==``?a.trim():null,hasWhenToUse:typeof o==`string`&&o.trim()!==``,bodyLines:c===``?0:c.split(`
296
- `).length,bodyTokens:Tu(c),hasExamples:nd(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Ru(e,t,n=/* @__PURE__ */ new Date){let r=[...Ku(e),...t?qu(t,n):[]];return{score:zu(r),checks:Vu(r)}}function zu(e){let t=e.reduce((e,t)=>e+ju[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+ju[t.severity],0);return Math.round(n/t*100)}const Bu=[`high`,`medium`,`low`];function Vu(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Bu.indexOf(e.severity)-Bu.indexOf(t.severity)))}const Hu=(e,t,n)=>({id:e,severity:t,passed:!0,message:n,fix:null}),$=(e,t,n,r)=>({id:e,severity:t,passed:!1,message:n,fix:r}),Uu=/\b(use (this( skill)?|it) (when|for|whenever|if|to)|use (when|for|whenever|if)|trigger(s|ed)? (on|when|for)|when(ever)? (the )?(user|you|someone|asked|working|writing|reviewing|handling|dealing|creating|editing)|invoke when)\b/i,Wu=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Gu=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Ku(e){let t=[],n=e.description??``;e.hasWhenToUse||Uu.test(n)?t.push(Hu(`description-when`,`high`,`description says when to use it`)):t.push($(`description-when`,`high`,`description has no "Use when…"`,`End the description with "Use when…" and the situations and words that should load the skill.`));let r=n.split(/\s+/).filter(Boolean).length,i=n.match(Wu);n.length<40||r<6?t.push($(`description-specific`,`medium`,n===``?`no description`:`description is too short`,`Say what the skill does in concrete terms: the task, what it takes and what it makes.`)):i?t.push($(`description-specific`,`medium`,`description is vague ("${i[0]}")`,`Name the task, the file types or tools, and the result instead of general words.`)):t.push(Hu(`description-specific`,`medium`,`description is specific`)),Gu.test(n)?t.push($(`description-person`,`low`,`description isn't in the third person`,`Write "Fills PDF forms…", not "I can…" or "You can…": the description goes into the system prompt.`)):t.push(Hu(`description-person`,`low`,`description is in the third person`)),n.length>600?t.push($(`description-length`,`low`,`description is long (${n.length} chars)`,`Keep it under 600 characters; move the details into SKILL.md's body.`)):t.push(Hu(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Ju(e.bodyTokens);return e.bodyLines===0?t.push($(`body-length`,`medium`,`${G} has no instructions`,`Write the instructions below the frontmatter.`)):e.bodyLines>500||e.bodyTokens>Mu?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Ju(Mu)}; move reference material into files ${G} links to.`)):t.push(Hu(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Hu(`examples`,`medium`,`has examples`)):t.push($(`examples`,`medium`,`no examples`,`Show an input and the output you want, in a code block or under an Examples heading.`)),e.missingFiles.length===0?t.push(Hu(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${rd(e.missingFiles.length,`missing file`)}: ${id(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Hu(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${rd(e.unusedFiles.length,`file`)} nothing mentions: ${id(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function qu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Hu(`eval-cases`,`high`,rd(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${rd(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Hu(`eval-negative`,`medium`,`${rd(e.negativeCaseCount,`case`)} where the skill shouldn't help`)):n.push($(`eval-negative`,`medium`,`no eval cases where the skill shouldn't help`,`Add a case whose prompt shouldn't load the skill (Should trigger off), so you notice when it fires too often.`));let r=e.lastRunAt===null?null:Math.max(0,Math.floor((t.getTime()-Date.parse(e.lastRunAt))/864e5));return r!==null&&r<=30?n.push(Hu(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${rd(r,`day`)} ago`)):n.push($(`eval-recent-run`,`low`,r===null?`evals never ran`:`no eval run in the last 30 days`,`Run the evals, so you know the current version still works.`)),n}function Ju(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Yu(e){let t=[];for(let n of e.matchAll(Iu)){let e=n[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/|\/)/i.test(e))continue;let r=e.split(`#`)[0].split(`?`)[0];try{r=decodeURIComponent(r)}catch{}r!==``&&t.push(r)}return t}function Xu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,nr(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Zu(t,n);return a&&r.add(a),[...r].some(t=>Qu(e,t))}function Zu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Qu(e,t){let n=e.indexOf(t);for(;n!==-1;){let r=n===0?``:e[n-1],i=e[n+t.length]??``,a=/[A-Za-z0-9_-]/;if(!a.test(r)&&(t.endsWith(`/`)||!a.test(i)))return!0;n=e.indexOf(t,n+1)}return!1}const $u=/^(```|~~~)/m,ed=/^#{1,6}[^\n]*\bexamples?\b/im,td=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function nd(e){return $u.test(e)||ed.test(e)||td.test(e)}function rd(e,t){return`${e} ${t}${e===1?``:`s`}`}function id(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const ad=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function od(e){try{return(await fe(_(e,G))).isFile()}catch{return!1}}async function sd(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await ce(i,{withFileTypes:!0})){let o=_(i,a.name);if(a.isDirectory()){ad.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=y(e,o).split(x).join(`/`),{size:c}=await fe(o);t.push({path:s,size:c}),(s===`SKILL.md`||Pu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Ru(Lu(t,e=>n.get(e)),null)}function cd(e){let t=[`HEALTH ${e.score}/100`];for(let n of e.checks)n.passed?t.push(`✓ ${n.message}`):(t.push(`■ ${n.message} [${n.severity}]`),n.fix&&t.push(` ${n.fix}`));return t.join(`
297
- `)}async function ld(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=b(t??`.`);if(await od(n)){let e=await sd(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(cd(e));return}if(t===void 0)throw Error("There's no SKILL.md here. Name one of your skills, like `a-kit health pdf-forms`, or a skill's folder.");let{api:r}=await to(),i=Dn(await r.listSkills(),t);if(i.length>1)throw Error(`More than one organization has a skill named "${t}". Name it with its organization: ${i.map(e=>`"${e.organizationName}/${e.name}"`).join(`, `)}.`);let a=i[0],o=await r.getSkillHealth(a.id);F.info(`${Nn(a)} v${a.version}`),console.log(cd(o))}async function ud(e){Wt(`agent kit`);let t=await eo();t?F.success(`Logged in as ${no(t.user)}`):t=await $a();let n=z(B(),t.token),r=await n.listSkills();if(r.length===0){I(ro(t.webUrl));return}let i=!e.yes;if(i&&!vn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await xn(e.global,i),o=await bn(e.agent,i),s=i?yn(await Ht({message:`Which skills?`,options:r.map(e=>({value:e.id,label:Nn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await Wo(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});I(`Installed in ${c.map(W).join(`, `)}`)}async function dd(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Xa();return;case`on`:{if(await zn({heartbeat:!0}),!await H()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!la()){F.warn(`Run it from the published CLI to install the timer.`);return}await Za();let e=await Wa(B()),t=(await Ya())?.ok??!1;e?F.success(`Heartbeats are on${t?`; this machine is on your Machines page`:``}.`):F.warn(`Heartbeats are on, but this system has no timer agent kit can use (only Linux with systemd and macOS). It still reports when you install, update, or start Claude Code.`);return}case`off`:await zn({heartbeat:!1}),await Ua(B()),F.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await U()).heartbeat!==!1,t=await Wa(B()),n=await Ya();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?za(B()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
298
- Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const fd=2e3;async function pd(e,t={},n=300){let{port:r,secret:i}=await co();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[io]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function md(){let e=await pd(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function hd(e,t,n=qo){let r=await md();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await _d(),f(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function gd(e){return(await pd(`/report`,{method:`POST`,body:JSON.stringify(e)},fd))?.status===202}async function _d({send:e=!0}={}){return(await pd(e?`/stop`:`/stop?send=false`,{method:`POST`},fd))?.ok??!1}const vd=5e3;async function yd(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await Sd()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await es(la()??ca()),await Wa(B())||await Xa();return}if(Bn()||(await U()).telemetry===!1)return;let o=await H();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await ls(o.user.id),u=c?{...Mc,sessionId:Nc(r.session_id)}:await Pc(r.session_id,s,void 0,l),d=z(B(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await xd(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await hd(la()??ca(),B());let p=await Dl(e,r,a,s,u,{now:i}),m=Ao(r),h=m&&await ya(m.name,e,s),g=m&&h&&await Sa(h,e,m.trigger,Fc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&ds(l,i,h?h.id:null)&&fs(d,o.user.id,l,i),(p||g)&&bd(d,p,g)])}catch{}}async function bd(e,t,n){await gd({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&Ol(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(vd))},t),n&&wa(async t=>{await e.reportActivations(t,AbortSignal.timeout(vd))},n)])}async function xd(e,t,n){let{repository:r,branch:i}=await Ic(n),a=ba(n,C());(r||a)&&await eu({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function Sd(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function Cd(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Wt(`agent kit`);let n=b(e[0]);if(!f(_(n,`SKILL.md`)))throw Error(`${W(n)} has no ${G}, so it isn't a skill.`);let r=m(n);if(!/^[a-z0-9-]+$/.test(r)||r===`report-session-issue`)throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await bn(t.agent,!t.yes),o=cn(a,i),s=o.map(e=>_(e,r));if(s.includes(n))throw Error(`${W(n)} is already where your agents read it.`);let c=(await X(Y(i))).skills[r];for(let e of s)if(f(e)&&!await Yn(e)&&!c)throw Error(`${W(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Jn(z(B(),(await H())?.token),r,c,o);if(e&&!await Yn(e.folder))throw Error(`${W(e.folder)} has edits that aren't in agent kit (${Kn(e.paths)}). Copy them to ${W(n)} and delete them there first.`)}for(let e of s)await Zn(e,n);F.success(`${r}: ${s.map(W).join(`, `)} → ${W(n)}`);let l=i===`project`?await wd(cn(a,`global`),r,n):[];l.length>0&&F.warn(`You also have ${r} in ${l.map(W).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await Td(n,r,c!==void 0),I(`${l.length>0?`This project's agents would use`:`Your agents use`} ${W(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function wd(e,t,n){let r=[];for(let i of e){let e=_(i,t);f(e)&&await Yn(e)!==n&&r.push(e)}return r}async function Td(e,t,n){let r;try{r=Hc(e)}catch{return}if(b(r,`skills`,t)!==e)return;let{scan:i,place:a}=await Zc(r,await Wc(r),{roles:!1}),o=a?.placement.skills.get(t);n&&o!==void 0&&F.warn(`The ${t} you installed from agent kit is ${o}'s, a different skill: this link takes its place, so your agents use ${W(e)} instead. ${L(`add ${t}`)} puts ${o}'s back.`);let s=$c(i.problems,[t]);s.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...bs(s)].join(`
299
- `))}function Ed(e,t,n){let r=e.map(e=>{let r=t.skills[e.name],i=n.skills[e.name],a=e.contextCost,o=e=>a?ku(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[Nn(e),Dd(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[Od(`project`,r,e),Od(`global`,i,e)].filter(Boolean).join(`, `)]}}),i=[`SKILL`,`VERSION`,`DESC`,`BODY`,`FILES`,`INSTALLED`],a=i.map((e,t)=>Math.max(e.length,...r.map(e=>e.cells[t].length))),o=e=>e.map((t,n)=>n===e.length-1?t:t.padEnd(a[n])).join(` `).trimEnd(),s=r.filter(e=>e.installed),c=Du(s.map(e=>e.skill.contextCost)),l=c.estimated?`~`:``,u=[o(i),...r.map(e=>o(e.cells))];return u.push(s.length===0?`${`TOTAL`.padEnd(a[0])} nothing installed here`:`${`TOTAL`.padEnd(a[0])} ${l}${Ou(c.always)} always · ${l}${Ou(c.max)} max (${s.length} installed${c.missing?`, ${c.missing} not counted yet`:``})`),r.some(e=>e.skill.contextCost?.source===`estimate`)&&u.push(`~ estimated locally: add a Claude API key to the organization to count exactly.`),u}function Dd(e){return[`v${e.version}`,...Zt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function Od(e,t,n){if(!t)return null;let r=Yi(t),{version:i}=tn(n.channels,n.version,r),a=`in ${e}${r===`latest`?``:` on ${r}`}`;return t.version===i?a:`${a} at v${t.version}, run a-kit update${e===`global`?` -g`:``}`}async function kd(){let{api:e,credentials:t}=await to(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(ro(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of Ed(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>Ad(e).length));for(let e of r){let t=[jd(i,e)&&`in project`,jd(a,e)&&`in global`].filter(Boolean);console.log(`${Ad(e).padEnd(o)} ${Md(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const Ad=e=>`${Sn}${Nn(e)}`,jd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function Md(e){let t=e.skills.length;if(t===0)return`no skills`;let n=e.skills.slice(0,3).map(e=>e.name);return`${t} skill${t===1?``:`s`}: ${n.join(`, `)}${t>3?`, …`:``}`}const Nd=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${L(`heartbeat status`)}).`;async function Pd(e,t){switch(e){case`name`:{let{api:e}=await to(),n=await xa();if(t===void 0){let t=await Fd(e.machineName(n));if(!t)throw Error(Nd);console.log(t.name?`This machine is "${t.name}" on the Machines page (its hostname is ${t.hostname}).`:`This machine goes by its hostname, "${t.hostname}", on the Machines page. Name it with ${L(`machine name <name>`)}.`);return}let r=await Fd(e.nameMachine(n,t))??(await Xa()?await Fd(e.nameMachine(n,t)):null);if(!r)throw Error(Nd);F.success(r.name?`This machine is "${r.name}" on the Machines page.`:`This machine goes by its hostname, "${r.hostname}", on the Machines page.`);return}default:throw Error(`Unknown machine action "${e??``}". Use ${L(`machine name [<name>]`)}.`)}}async function Fd(e){try{return await e}catch(e){if(e instanceof R&&e.status===404)return null;throw e}}async function Id(e,t){switch(e){case void 0:case`status`:{let e=(await Ya())?.organization;console.log(e?`This machine shows up on ${e.name}'s Machines page.`:`This machine hasn't shown up on a Machines page yet.`),console.log(`Move it to another organization with ${L(`org use`)}.`);return}case`use`:{let{api:e,credentials:n}=await to(),r=await Ma(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await U()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Xa()?F.success(`This machine now shows up on ${r.name}'s Machines page.`):F.warn(`This machine goes to ${r.name}; it shows up there with its next heartbeat.`);return}default:throw Error(`Unknown org action "${e}". Use status or use.`)}}async function Ld(){Wt(`agent kit`);let e=await eo().catch(()=>null);if(e){let t=no(e.user);if(!vn()){I(`Already logged in as ${t}.`);return}if(!yn(await zt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await $a();e&&await z(B(),e.token).logout().catch(()=>{}),I(await Bd(t.token,t.webUrl))}async function Rd(e=process.stdin){Wt(`agent kit`);let t=await zd(e);if(!t)throw Error(`Give it the bot's token on stdin, like ${L(`login --token`)} < bot-token.`);let n;try{n=await z(B(),t).me()}catch(e){throw e instanceof R&&e.status===401?Error(`This token doesn't work: it's wrong, or the bot was revoked.`):e}let r=await H();await Ln({token:t,user:n,webUrl:Pn(B())}),r&&r.token!==t&&await z(B(),r.token).logout().catch(()=>{}),await Za(),I(`Logged in as ${no(n)}.`)}async function zd(e){if(e.isTTY)return yn(await Gt({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function Bd(e,t){return(await z(B(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${ro(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function Vd(){let e=await H();e?(await z(B(),e.token).logout().catch(()=>{}),await Ln(null),console.log(`Logged out ${no(e.user)}.`)):console.log(`You're not logged in.`)}async function Hd(){let e=await eo();e?console.log(no(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Ud=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Wd(e){let t=await Gd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${gn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${L(`check <skill>`)}`,` 3. Try it in your agent: ${L(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${L(`add <skill>`)} or ${L(`update`)}.`),Error(r.join(`
300
- `))}async function Gd(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Kd={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},qd=[{kind:`private-key`,pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,strict:!0},{kind:`anthropic-key`,pattern:/\bsk-ant-[A-Za-z0-9_-]{20,}/g,strict:!0},{kind:`openai-key`,pattern:/\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}/g,strict:!0},{kind:`github-token`,pattern:/\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})/g,strict:!0},{kind:`aws-key`,pattern:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,strict:!0},{kind:`slack-token`,pattern:/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,strict:!0},{kind:`stripe-key`,pattern:/\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g,strict:!0},{kind:`google-key`,pattern:/\bAIza[0-9A-Za-z_-]{35}\b/g,strict:!0},{kind:`jwt`,pattern:/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,strict:!0},{kind:`url-credentials`,pattern:/\b([a-z][a-z0-9+.-]*:\/\/)[^\s:/@]+:[^\s@/]+@/gi,keep:(e,t)=>`${t}<secret>@`,strict:!1},{kind:`bearer`,pattern:/\b(Bearer\s+)[A-Za-z0-9._~+/-]{20,}=*/g,keep:(e,t)=>`${t}<secret>`,strict:!1},{kind:`assignment`,pattern:/\b([A-Za-z0-9_]*(?:secret|token|password|passwd|api_?key|private_?key|access_?key)[A-Za-z0-9_]*["']?\s*[=:]\s*)(["']?)(?!<secret)[^\s"'`,;]{8,}\2/gi,keep:(e,t,n)=>`${t}${n}<secret>${n}`,strict:!1}],Jd=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Yd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Xd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Zd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Qd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function $d(e){let t={},n=(e,n=1)=>{t[e]=(t[e]??0)+n},r=e.paths.filter(e=>e.path.length>1).sort((e,t)=>t.path.length-e.path.length).map(e=>({...e,pattern:new RegExp(Qd(e.path),`g`)})),i=e.replacements.filter(e=>e.find.trim().length>1).sort((e,t)=>t.find.length-e.find.length).map(e=>({...e,pattern:new RegExp(e.find.length<4?`(?<![\\p{L}\\p{N}_])${Qd(e.find)}(?![\\p{L}\\p{N}_])`:Qd(e.find),`giu`)}));function a(e){let t=e;for(let e of qd)t=t.replace(e.pattern,(t,...r)=>(n(`secret:${e.kind}`),e.keep?e.keep(t,...r):`<secret>`));for(let e of r)t=t.replace(e.pattern,()=>(n(`path:${e.as}`),e.as));for(let e of i)t=t.replace(e.pattern,()=>(n(`term:${e.find}`),e.replace));return t=t.replace(Jd,e=>Zd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Yd,e=>Xd.has(e)?e:(n(`ip`),`192.0.2.1`)),t}function o(t){let r=e.maxToolText;return r===null||t.length<=r?t:(n(`cut`),`${t.slice(0,r)}\n… [${t.length-r} more characters left out by a-kit report]`)}function s(e){return typeof e==`string`?o(a(e)):Array.isArray(e)?e.map(s):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,s(t)])):e}function c(e){return e.type===`text`?{...e,text:a(e.text)}:e.type===`tool_use`?{...e,input:s(e.input)}:{...e,content:o(a(e.content))}}function l(e){return e.map(e=>e.type===`system`?e:{...e,message:{content:e.message.content.map(c)}})}return{text:a,events:l,counts:t}}const ef=e=>e.map(e=>JSON.stringify(e)).join(`
301
- `)+`
302
- `;function tf(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
303
- `)){if(!a.trim())continue;let e;try{e=JSON.parse(a)}catch{continue}if(e.type!==`user`&&e.type!==`assistant`||e.isSidechain||e.isMeta)continue;r=e.version??r,i=e.cwd??i,e.type===`assistant`&&e.message?.model&&(e.message.model.startsWith(`<`)||(n=e.message.model));let o=nf(e.message?.content);o.length>0&&t.push({type:e.type,message:{content:o}})}return{agent:`claude-code`,agentVersion:r,model:n,cwd:i,events:[{type:`system`,subtype:`init`,agent:`Claude Code`,agent_version:r,model:n},...t],loaded:[...new Set(t.flatMap(zi))]}}function nf(e){if(typeof e==`string`)return e.trim()?[{type:`text`,text:e}]:[];if(!Array.isArray(e))return[];let t=[];for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text.trim()?t.push({type:`text`,text:n.text}):n.type===`tool_use`?t.push({type:`tool_use`,id:String(n.id??``),name:String(n.name??``),input:n.input??{}}):n.type===`tool_result`&&t.push({type:`tool_result`,tool_use_id:String(n.tool_use_id??``),content:rf(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function rf(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>e.type===`text`&&typeof e.text==`string`?e.text:e.type===`image`?`[image]`:``).filter(Boolean).join(`
304
- `):``}const af=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function of(e){let t=[],n=null,r=null,i=null,a=(e,n)=>t.push({type:e,message:{content:[n]}});for(let t of e.split(`
305
- `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=cf(o.cli_version)??r,i=cf(o.cwd)??i;else if(e.type===`turn_context`)n=cf(o.model)??n,i=cf(o.cwd)??i;else if(e.type===`response_item`){if(o.type===`message`){let e=o.role;if(e!==`user`&&e!==`assistant`)continue;let t=lf(o.content);if(!t.trim()||e===`user`&&af.some(e=>e.test(t.trim())))continue;a(e,{type:`text`,text:t})}else o.type===`function_call`||o.type===`custom_tool_call`?a(`assistant`,{type:`tool_use`,id:String(o.call_id??o.id??``),name:String(o.name??``),input:o.type===`function_call`?uf(o.arguments):{input:o.input??``}}):o.type===`function_call_output`||o.type===`custom_tool_call_output`?a(`user`,{type:`tool_result`,tool_use_id:String(o.call_id??``),content:df(o.output)}):o.type===`local_shell_call`&&a(`assistant`,{type:`tool_use`,id:String(o.call_id??o.id??``),name:`shell`,input:o.action??{}})}}return{agent:`codex`,agentVersion:r,model:n,cwd:i,events:[{type:`system`,subtype:`init`,agent:`Codex`,agent_version:r,model:n},...t],loaded:[...new Set(t.flatMap(zi))]}}function sf(e){try{let t=JSON.parse(e);return t.type===`session_meta`?cf(t.payload?.cwd):null}catch{return null}}const cf=e=>typeof e==`string`&&e?e:null;function lf(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
306
- `):``}function uf(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function df(e){if(typeof e==`string`){try{let t=JSON.parse(e);if(typeof t?.output==`string`)return t.output}catch{}return e}if(Array.isArray(e))return lf(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return df(t)}return JSON.stringify(e??``)}const ff=()=>process.env.CLAUDE_CONFIG_DIR??_(C(),`.claude`),pf=()=>process.env.CODEX_HOME??_(C(),`.codex`),mf=(e,t=ff())=>_(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function hf(e,t,n=process.cwd()){if(t&&f(t))return b(t);let r=e===`claude-code`?await vf(t,n):await yf(t,n);if(r)return r.file;throw Error(t?`No ${_f(e)} session "${t}" on this machine.`:`No ${_f(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function gf(e=process.cwd()){if(process.env.CLAUDECODE===`1`)return`claude-code`;if(Object.keys(process.env).some(e=>e.startsWith(`CODEX_`)))return`codex`;let[t,n]=await Promise.all([vf(void 0,e),yf(void 0,e)]);if(t&&(!n||t.mtime>=n.mtime))return`claude-code`;if(n)return`codex`;throw Error(`No Claude Code or Codex session for ${e}. Pass --agent and --session.`)}const _f=e=>e===`claude-code`?`Claude Code`:`Codex`;async function vf(e,t){if(e){let t=_(ff(),`projects`),n=await wf(t);for(let r of n){let n=_(t,r,`${e}.jsonl`);if(f(n))return{file:n,mtime:0}}return null}for(let e of Tf(t)){let t=mf(e),n=(await wf(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Cf(n.map(e=>_(t,e)))}return null}async function yf(e,t){let n=_(pf(),`sessions`),r=[],i=0;outer:for(let e of bf(await wf(n)))for(let t of bf(await wf(_(n,e))))for(let a of bf(await wf(_(n,e,t)))){let o=_(n,e,t,a);for(let e of await wf(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(_(o,e));if(r.length>=300||++i>=14)break outer}return xf(r,e,t)}const bf=e=>e.sort().reverse();async function xf(e,t,n){if(t){let n=e.find(e=>m(e).includes(t));return n?{file:n,mtime:0}:null}let r=Tf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Sf(t);e&&r.includes(e)&&i.set(e,[...i.get(e)??[],t])}for(let e of r){let t=i.get(e);if(t)return Cf(t)}return null}async function Sf(e){let t=await se(e,`r`);try{let e=Buffer.alloc(262144),{bytesRead:n}=await t.read(e,0,e.length,0),r=e.subarray(0,n).toString(`utf8`),i=r.indexOf(`
307
- `);return sf(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Cf(e){let t=null;for(let n of e){let{mtimeMs:e}=await fe(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function wf(e){try{return await ce(e)}catch{return[]}}function Tf(e){let t=[b(e)];for(;g(t.at(-1))!==t.at(-1);)t.push(g(t.at(-1)));return t}const Ef=2e3;function Df(e){let t=[...e.map],n=Af(()=>ee().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=Af(()=>w());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=Of();if(i){t.push({find:i,replace:`acme/app`});let e=i.split(`/`)[0];e.length>=3&&t.push({find:e,replace:`acme`})}let a=Af(()=>be(`git`,[`rev-parse`,`--show-toplevel`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim());return{replacements:t,paths:[...[...new Set([...e.cwds,a].filter(Boolean))].map(e=>({path:e,as:`<repo>`})),{path:C(),as:`~`}],maxToolText:e.fullOutputs?null:Ef}}function Of(){return Af(()=>be(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function kf(e){let t;try{t=JSON.parse(e)}catch{throw Error(`--map isn't valid JSON.`)}let n=Array.isArray(t)?t.map(e=>[e?.find,e?.replace]):typeof t==`object`&&t?Object.entries(t):null;if(!n||!n.every(([e,t])=>typeof e==`string`&&typeof t==`string`))throw Error(`--map must be an object of words to replace, like {"Acme Corp": "Example Inc"}.`);return n.map(([e,t])=>({find:e,replace:t}))}function Af(e){try{return e()}catch{return null}}function jf(e,t,n){let r=new Set(t),i=/* @__PURE__ */ new Map;for(let t of n)for(let[n,a]of Object.entries(t.skills))Nf(a.agents,e)&&(i.has(n)||i.set(n,{name:n,skillId:a.id,version:a.version,triggered:r.has(n)}));for(let e of t)e===`report-session-issue`||i.has(e)||i.set(e,{name:e,skillId:null,version:null,triggered:!0});return i.delete(Ni),[...i.values()]}const Mf=[`codex`,`cursor`,`gemini-cli`],Nf=(e,t)=>e.length===0||e.includes(t)||Mf.includes(t)&&e.some(e=>Mf.includes(e));async function Pf(e){Wt(`agent kit report`);let t=await Ff(e.agent[0]),n=await hf(t,e.session||void 0),r=await O(n,`utf8`),i=Li(t===`claude-code`?tf(r):of(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=$d(Df({map:e.map?kf(await If(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Rf(e.title,`--title`,`a short title`)),s=a.text(Rf(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=ef(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=jf(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=_(E(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${_f(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${Bf(d)}`,`Taken out: ${Vf(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
308
- `)),Buffer.byteLength(l)>Kd.maxTranscriptBytes)throw Error(`The transcript is over ${Kd.maxTranscriptBytes/1024/1024} MB.${e.fullOutputs?` Leave out --full-outputs.`:``}`);if(e.dryRun){I(`Nothing was sent. Check the file above, then run it again without --dry-run.`);return}if(!e.yes){if(!vn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!yn(await zt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:h}=await to(),[g,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=zf(e.org,g,v,d),b=await m.createReport(y.id,f);I(`Reported: ${h.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function Ff(e){if(e===void 0)return gf();if(e===`claude-code`||e===`codex`)return e;throw Error(`a-kit report reads Claude Code and Codex sessions; --agent must be claude-code or codex.`)}const If=e=>e===`-`?Lf():O(e,`utf8`);async function Lf(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Rf(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function zf(e,t,n,r){let i=()=>t.map(e=>`${e.name} (${e.id})`).join(`, `);if(e){let n=t.filter(t=>t.id===e||t.name===e);if(n.length===1)return n[0];throw Error(`--org: none of your organizations is "${e}". Yours: ${i()}`)}let a=new Set(r.map(e=>e.skillId).filter(Boolean)),o=new Set(n.filter(e=>a.has(e.id)).map(e=>e.organizationId));if(o.size===1){let e=t.find(e=>o.has(e.id));if(e)return e}if(t.length===1)return t[0];throw Error(`Which organization is it for? Pass --org with one of: ${i()}`)}function Bf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Vf(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${Ef} characters`:`${e} ×${t}`).join(`, `)}function Hf(e){return e&&e.total>0?e.passed/e.total:null}async function Uf(e){let{api:t,credentials:n}=await to(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Wf(r,n.webUrl,i.length>1))}function Wf({skills:e,runs:t},n,r){if(e.length===0&&t.length===0)return`Nothing matches.`;let i=[];if(e.length>0){let t=e.map(e=>Nn({...e,showOrganization:r})),n=Math.max(...t.map(e=>e.length));i.push(`Skills`),e.forEach((e,r)=>{i.push(` ${t[r].padEnd(n)} v${e.version} a-kit add ${e.name}`)})}if(t.length>0){i.length>0&&i.push(``);let e=t.map(e=>`${e.skillName} v${e.version}`),r=Math.max(...e.map(e=>e.length));i.push(`Runs`),t.forEach((t,a)=>{let o=Hf(t.withSkill),s=o===null?`—`:`${Math.round(o*100)}%`;i.push(` ${e[a].padEnd(r)} ${s.padStart(4)} ${t.status.padEnd(9)} ${n}/app/skills/${t.skillId}?tab=runs&run=${t.id}`)})}return i.join(`
309
- `)}const Gf={inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadInputTokens:Z.cacheReadTokens,cacheCreationInputTokens:Z.cacheCreationTokens,costUSD:Z.costUsd},Kf={input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,cache_read_input_tokens:Z.cacheReadTokens,cache_creation_input_tokens:Z.cacheCreationTokens},qf=/^\{"type":"(api-request|atis-latch|queue-operation)/;function Jf(e){let t={sessionId:e,cwd:null,startedAt:null,endedAt:null,branches:[],skills:[],commands:[],prompts:0,turns:[],runs:[],replies:{},namedRepositories:[]},n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{let n=e.toLowerCase();t.namedRepositories.includes(n)||t.namedRepositories.push(n)},o=e=>{let n=e.message,i=typeof n?.id==`string`?n.id:null,a=typeof n?.model==`string`?n.model:null,o=n?.usage;if(!i||!a||a.startsWith(`<`)||r.has(i)||typeof o!=`object`||!o)return;r.add(i);let s=t.replies[a]??={};for(let[e,t]of Object.entries(Kf)){let n=o[e];typeof n==`number`&&n>0&&(s[t]=(s[t]??0)+n)}};return{take(r,{subagent:s=!1}={}){if(!r||qf.test(r))return;let c;try{c=JSON.parse(r)}catch{return}if(typeof c!=`object`||!c)return;if(s){c.type===`assistant`&&o(c);return}if(typeof c.sessionId==`string`&&c.sessionId!==e)return;c.type===`assistant`&&o(c);let l=typeof c.timestamp==`string`?Date.parse(c.timestamp):NaN;if(Number.isNaN(l)||(t.startedAt=Math.min(t.startedAt??l,l),t.endedAt=Math.max(t.endedAt??l,l)),!Number.isNaN(l)&&(c.type===`assistant`||c.type===`user`)){let e=t.turns.at(-1);!e||c.type===`user`&&!tp(c).some(e=>e.type===`tool_result`)?t.turns.push({start:l,end:l}):e.end=Math.max(e.end,l)}t.cwd===null&&typeof c.cwd==`string`&&c.cwd&&(t.cwd=c.cwd);let u=c.gitBranch;switch(typeof u==`string`&&u&&u!==`HEAD`&&!Number.isNaN(l)&&!t.branches.some(e=>e.branch===u)&&t.branches.push({branch:u,at:l}),c.type){case`cost-state`:ep(c,n);return;case`pr-link`:typeof c.prRepository==`string`&&Zf.test(c.prRepository)&&a(c.prRepository);return;case`assistant`:if(Number.isNaN(l))return;for(let e of tp(c)){if(e.type!==`tool_use`||typeof e.input!=`object`)continue;let n=e.input??{};if(e.name===`Skill`&&typeof n.skill==`string`){let e=n.skill.replace(/^\//,``),r=typeof n.args==`string`?n.args:null;t.skills.push({name:e,command:r===null?null:`/${e} ${r}`,trigger:`model`,at:l})}if(e.name!==`Bash`||typeof n.command!=`string`||typeof e.id!=`string`)continue;let r=Yf.test(n.command),a=Xf.test(n.command);(r||a)&&i.set(e.id,{command:n.command,at:l,gh:r,push:a})}return;case`user`:{for(let e of tp(c)){if(e.type!==`tool_result`||typeof e.tool_use_id!=`string`)continue;let n=i.get(e.tool_use_id);if(!n)continue;i.delete(e.tool_use_id);let r=np(c,e);if(n.gh){for(let e of r.matchAll(Qf))a(e[1]);t.commands.push({command:n.command,stdout:r,at:Number.isNaN(l)?n.at:l})}if(n.push){let e=`${r}\n${rp(c)}`;for(let t of e.matchAll($f))a(t[1])}}if(Number.isNaN(l)||!ap(c))return;t.prompts++;let e=op(c),n=e?.match(/^\/([^\s]+)/)?.[1];e&&n&&t.skills.push({name:n,command:e,trigger:`user`,at:l});return}}},result(){for(let{command:e,at:n,gh:r}of i.values())r&&t.commands.push({command:e,at:n,stdout:``});return i.clear(),t.commands.sort((e,t)=>e.at-t.at),t.runs=[...n.values()].sort((e,t)=>e.start-t.start),t}}}const Yf=/(^|[\s;&|(])gh\s/,Xf=/(^|[\s;&|(])git\s(?:[^;&|\n]*\s)?push\b/,Zf=/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/,Qf=/https:\/\/github\.com\/([A-Za-z0-9-]+\/[A-Za-z0-9._-]+)\/(?:pull|issues)\/\d+/g,$f=/^To (?:https:\/\/(?:[^@\s/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/]|github\.com:)([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?\s*$/gm;function ep(e,t){let n=e.startTime,r=e.modelUsage;if(typeof n!=`number`||typeof r!=`object`||!r)return;let i=t.get(n);i||t.set(n,i={start:n,models:{}});for(let[e,t]of Object.entries(r)){if(typeof t!=`object`||!t)continue;let n=i.models[e]??={};for(let[e,r]of Object.entries(Gf)){let i=t[e];typeof i==`number`&&i>(n[r]??0)&&(n[r]=i)}}}function tp(e){let t=e.message?.content;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e):[]}function np(e,t){let n=e.toolUseResult;if(typeof n==`object`&&n){let e=n.stdout;if(typeof e==`string`)return e}return typeof t.content==`string`?t.content:Array.isArray(t.content)?t.content.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(`
310
- `):``}function rp(e){let t=e.toolUseResult;if(typeof t!=`object`||!t)return``;let n=t.stderr;return typeof n==`string`?n:``}function ip(e){let t=e.message?.content;if(typeof t==`string`)return t;let n=tp(e);if(n.some(e=>e.type===`tool_result`))return null;let r=n.filter(e=>e.type===`text`);return r.length>0?r.map(e=>typeof e.text==`string`?e.text:``).join(`
311
- `):null}function ap(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=ip(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function op(e){let t=ip(e);if(!t)return null;let n=/<command-name>\s*\/?([^\s<]+)\s*<\/command-name>/.exec(t)?.[1];if(n){let e=/<command-args>([\s\S]*?)<\/command-args>/.exec(t)?.[1];return`/${n}${e?.trim()?` ${e.trim()}`:``}`}return/^\s*\/[^\s]/.test(t)?t.trimStart():null}async function sp(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function cp(e,t){let n=Jf(t);await sp(e,e=>n.take(e));let r=n.result();if(r.runs.length>0)return r;let i=_(e.replace(/\.jsonl$/,``),`subagents`),a=[];try{a=(await ce(i)).filter(e=>e.endsWith(`.jsonl`))}catch{return r}for(let e of a)await sp(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const lp=`claude-code`,up={outside:`not in a repository of your organizations'`,gone:`its folder is gone, and nothing it printed says which repository it was`,several:`its folder is gone, and what it printed names more than one repository`,empty:`nothing in it says when it was`,old:`older than ${ol.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were`},dp=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function fp(e){let t;try{t=await ce(e)}catch{return[]}let n=[];for(let r of t){let t;try{t=await ce(_(e,r))}catch{continue}for(let i of t){let t=i.replace(/\.jsonl$/,``);if(t===i||!wc.test(t))continue;let a=_(e,r,i),{mtimeMs:o,isFile:s}=await fe(a).then(e=>({mtimeMs:e.mtimeMs,isFile:e.isFile()}),()=>({mtimeMs:0,isFile:!1}));s&&n.push({file:a,sessionId:t,at:o})}}return n.sort((e,t)=>e.at-t.at)}async function pp(e){let t=e.now??/* @__PURE__ */ new Date,n={sessions:[],skipped:{}},r=e=>{n.skipped[e]=(n.skipped[e]??0)+1};for(let{file:i,sessionId:a}of await fp(e.projectsDir)){let o=await mp(await cp(i,a),e,t);typeof o==`string`?r(o):n.sessions.push(o)}return n.sessions.sort((e,t)=>e.startedAt.localeCompare(t.startedAt)),n}async function mp(e,t,n=t.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<n.getTime()-ol.maxAgeDays*864e5)return`old`;let r=t.home??C(),i=e.cwd,a=await hp(e,i,r,t.known);if(typeof a==`string`)return a;let{place:o}=a,s=o.repository;if(await Nl(e.sessionId))return`live`;let c={sessionId:e.sessionId,agent:lp,machineId:t.machineId,machineName:t.machineName,imported:!0},l=[],u=(e,t)=>{let n=t.filter(e=>e!==null);n.length>0&&l.push({at:e,links:n})};u(e.startedAt,[ul(`repository`,s)]);for(let{branch:t,at:n}of e.branches)await Lc(i,t)||u(n,[ul(`branch`,`${s}#${t}`)]);for(let t of e.skills)t.command&&u(t.at,_l(t.command,s));for(let{command:t,stdout:n,at:r}of e.commands)u(r,bl(t,n,s));l.sort((e,t)=>e.at-t.at);let d=/* @__PURE__ */ new Set,f=[],p=(e,t,n)=>{for(let r=0;r===0||r<n.length;){let i=n.slice(r,r+ol.maxLinks);f.push({...c,type:e,occurredAt:vp(t),links:i}),r+=Math.max(i.length,1)}},m=e=>e.filter(e=>{let t=Pl(e);return!d.has(t)&&(d.add(t),!0)}),h=m(l.filter(t=>t.at<=e.startedAt).flatMap(e=>e.links));p(`start`,e.startedAt,h);for(let{at:t,links:n}of l){if(t<=e.startedAt)continue;let r=m(n);r.length>0&&p(`seen`,t,r)}p(`end`,e.endedAt,[]);let g=[];for(let[n,a]of e.skills.entries()){let s=await ya(a.name,lp,i,r);s&&g.push({...c,...Fc({...o,branch:gp(e,a.at)},t.known.skills[s.id]??null),id:yp(`${e.sessionId}\n${n}\n${a.at}\n${a.name}`),skillId:s.id,version:s.version,trigger:a.trigger,occurredAt:vp(a.at),sessionId:e.sessionId})}let _=await t.organizationOf({sessionId:e.sessionId,agent:lp,cwd:i,projectLock:ba(i,r),repository:s,branch:e.branches[0]?.branch??null,registeredAt:vp(e.startedAt)});if(_===`unknown`)throw Error(`Couldn't ask agent kit which organization a session's repository is. Try again in a moment.`);let v=_?{...c,organizationId:_.organizationId,occurredAt:vp(e.endedAt),usage:_p(e)}:null;return{sessionId:e.sessionId,repository:s,placedByOutput:a.byOutput,startedAt:vp(e.startedAt),events:f,activations:g,usage:v}}async function hp(e,t,n,r){let i=await Pc(e.sessionId,t,n,r);if(i.audience&&i.repository)return{place:{...i,repository:i.repository},byOutput:!1};if(f(t))return`outside`;let[a,...o]=e.namedRepositories;if(!a)return ba(t,n)?`outside`:`gone`;if(o.length>0)return`several`;let s=`github.com/${a}`,c=r.repositories[s];return c?{place:{sessionId:e.sessionId,repository:s,branch:null,audience:{organizationId:c}},byOutput:!0}:`outside`}function gp(e,t){let n=null;for(let r of e.branches)r.at<=t&&(n=r.branch);return n??e.branches[0]?.branch??null}function _p(e){let t=[],n=e.runs.length>0?e.runs:[{start:e.startedAt,models:e.replies}];e.prompts>0&&t.push({metric:Z.prompts,model:null,skillId:null,start:vp(n[0]?.start??e.startedAt),value:e.prompts});for(let e of n)for(let[n,r]of Object.entries(e.models))for(let[i,a]of Object.entries(r))a>0&&t.push({metric:i,model:n,skillId:null,start:vp(e.start),value:a});let r=/* @__PURE__ */ new Map;for(let{start:t,end:n}of e.turns)for(let e=t;e<n;){let t=nl(e),i=Math.min(n,t+tl);r.set(t,(r.get(t)??0)+(i-e)/1e3),e=i}for(let[e,n]of r)t.push({metric:Z.agentSeconds,model:null,skillId:null,start:vp(e),end:vp(e+tl),value:n});return t.slice(0,rl.maxEntries)}const vp=e=>new Date(e).toISOString();function yp(e){let t=he(`sha256`).update(e).digest(`hex`),n=(parseInt(t[16],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-${n}${t.slice(17,20)}-${t.slice(20,32)}`}const bp=ol.maxPerRequest;async function xp(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=bp){let i=await e.reportSessionEvents(r.slice(t,t+bp));for(let e of i.live??[])n.add(e)}let i=t.sessions.filter(e=>!n.has(e.sessionId)),a=i.flatMap(e=>e.activations);for(let t=0;t<a.length;t+=100)await e.reportActivations(a.slice(t,t+100));let o=[],s=0;for(let t of i.flatMap(e=>e.usage?[e.usage]:[])){let n=JSON.stringify(t).length;o.length>0&&(o.length>=rl.maxPerRequest||s+n>409600)&&(await e.reportSessionUsage(o),o=[],s=0),o.push(t),s+=n}return o.length>0&&await e.reportSessionUsage(o),{sent:i,live:[...n]}}async function Sp({dryRun:e}){let t=await H();if(!t)throw Error("Log in first with `a-kit login`.");if(!e&&(Bn()||(await U()).telemetry===!1))throw Error("Telemetry is off, so nothing is sent. Turn it on with `a-kit telemetry on`, or see what would be sent with `--dry-run`.");let n=z(B(),t.token),r=t.user.id,i=await fs(n,r,await ls(r),/* @__PURE__ */ new Date);if(!i)throw Error(`Couldn't ask agent kit which repositories are your organizations'. Try again in a moment.`);let a=Bl(async()=>({api:n,userId:r})),o=dp(),s=await pp({projectsDir:o,known:i,organizationOf:e=>a.of(e),machineId:await xa(),machineName:ma()});if(e){for(let e of s.sessions)console.log(Ep(e));console.log(`\nWould send ${Cp(s.sessions.length)} from ${o}. Nothing was sent.`),wp(s.sessions),Tp(s.skipped,`Would skip`),s.sessions.length>0&&console.log(`agent kit leaves a session live telemetry already sent as it is.`);return}let c=await xp({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e)},s);for(let e of c.sent)await Ml(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await iu(e.usage,`sent`);F.success(`Sent ${Cp(c.sent.length)} from ${o} to agent kit.`),wp(c.sent),Tp({...s.skipped,...c.live.length>0&&{live:(s.skipped.live??0)+c.live.length}},`Skipped`),console.log("Claude Code keeps about 30 days of sessions. `a-kit telemetry show <session-id>` shows what was sent for one.")}const Cp=e=>`${e} session${e===1?``:`s`}`;function wp(e){let t=e.filter(e=>e.placedByOutput).length;t!==0&&console.log(t===1?`1 was placed by the one repository it named itself (its pull requests, gh output or git push), its folder being gone.`:`${t} were placed by the one repository each named itself (its pull requests, gh output or git push), their folder being gone.`)}function Tp(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${Cp(r)}:`);for(let[e,t]of n)console.log(` ${t} ${up[e]}`)}}function Ep(e){let t=new Set(e.events.flatMap(e=>e.links.map(Pl))),n=e=>[...t].filter(t=>t.startsWith(`${e} `)).length,r=e.usage?.usage.filter(e=>e.metric===Z.costUsd).reduce((e,t)=>e+t.value,0),i=[`${n(`branch`)} branches`,`${n(`pull_request`)} pull requests`,`${n(`issue`)} issues`,`${n(`touched`)} issues and pull requests touched`,`${e.activations.length} skills loaded`,e.usage?r?`$${r.toFixed(2)}`:`usage`:`no usage (no organization of yours is its)`];return`${e.sessionId} ${e.startedAt} ${e.repository} ${i.join(`, `)}`}const Dp={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function Op(e,t,{port:n,dryRun:r=!1}={}){switch(e){case`on`:{n!==void 0&&await lo(Number(n)),await zn({telemetry:!0});let e=await No();if(e.status===`skipped`){F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}F.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&F.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await zn({telemetry:!1}),await No(),await _d({send:!1}),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return Ap(t);case`import`:return Sp({dryRun:r});case void 0:case`status`:{let e=await U(),t=(await Io()).includes(`telemetry`),n=e.telemetry===!1?`off`:Bn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await co(),i=await md(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${Dp[await Fo()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status, show or import.`)}}const kp={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Ap(e){if(e){let[t,n]=await Promise.all([au(e),jl(e)]);if(!t&&n.length===0)throw Error(`Nothing was sent for session ${e}.`);console.log(n.length>0?`Its session told agent kit of:\n${n.map(e=>` ${e}`).join(`
312
- `)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${kp[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
313
- Nothing of what it used was sent.`);return}let t=await ou();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${kp[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function jp(e,t){let[n,...r]=e;if(!n)throw Error(`Name a skill and a prompt: a-kit try <skill> "<prompt>"`);let i=r.length>0?r.join(` `):await Ip();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Fp(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await to(),c=Dn(await s.listSkills(),n);if(c.length>1)throw Error(`More than one of your organizations has a skill named "${n}". Say which one: ${c.map(e=>`${e.organizationName}/${e.name}`).join(` or `)}.`);let l=c[0],u=e=>console.log(`\n${e.toUpperCase()} · ${o}\n`),d=(e,t)=>Mp(s,l.id,{model:o,version:a,withSkill:e,prompt:i},t),f=[],p=d(!1,e=>f.push(e));p.catch(()=>{});let m=!1;Pp(await d(!0,e=>{m||u(`With ${Nn(l)} v${a??l.version}`),m=!0,Np(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Np(e,l.name);Pp(h)}async function Mp(e,t,n,r){let i=`The answer ended before it finished.`;try{await e.playground(t,{model:n.model,version:n.version,withSkill:n.withSkill,messages:[{role:`user`,content:n.prompt}]},e=>{e.type===`done`&&(i=e),e.type===`error`&&(i=e.message),r(e)})}catch(e){if(e instanceof R)throw e;i=e instanceof Error?e.message:String(e)}return i}function Np(e,t){if(e.type===`text`&&process.stdout.write(e.text),e.type===`tool`){let n=e.tool===`load_skill`?`Loaded ${e.skill}`:`Read ${e.skill}/${e.path??``}`;process.stdout.write(`${e.skill===t?`■`:`□`} ${n}\n\n`)}}function Pp(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=mn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${fn(e.usage)}`)}function Fp(e){if(e===void 0)return;let t=Number(e.replace(/^v/,``));if(!Number.isInteger(t)||t<1)throw Error(`"${e}" isn't a version number, like 3.`);return t}async function Ip(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Lp=`a-kit ${nn}: your agent kit skills, in your agents.
244
+ `});for(let e of s){let t=gs.get(e.key);if(t)Ds(t,e,i),t.scope===`claude-code`&&i(`warning`,`Only Claude Code reads \`${t.key}\`; claude.ai and the Skills API reject skills that have it.`,e.keyFrom,e.keyTo);else{let t=gs.get(e.key.toLowerCase().replace(/_/g,`-`));i(`warning`,t?`Unknown field \`${e.key}\`. Did you mean \`${t.key}\`?`:`Unknown field \`${e.key}\`. Claude Code ignores it, and claude.ai and the Skills API reject the skill.`,e.keyFrom,e.keyTo,t?{label:`Rename to ${t.key}`,from:e.keyFrom,to:e.keyTo,insert:t.key}:void 0)}}let u=c.get(`name`);if(u&&typeof u.value==`string`)for(let e of Ts(u.value)){let t=Es(u.value);i(`error`,e,u.valueFrom,u.valueTo,t&&t!==u.value?{label:`Change to ${t}`,from:u.valueFrom,to:u.valueTo,insert:t}:void 0)}let d=c.get(`description`);if(d&&typeof d.value==`string`){let e=d.value.trim(),t=[d.valueFrom,d.valueTo];if(e===``)i(`error`,Cs,d.keyFrom,d.keyTo);else{let n=ws(e);for(let e of n.errors)i(`error`,e,...t);for(let e of n.warnings)i(`warning`,e,...t);let r=c.get(`when_to_use`)?.value,a=e.length+(typeof r==`string`?r.length:0);a>vs&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${vs}.`,...t)}}let f=c.get(`compatibility`);f&&typeof f.value==`string`&&f.value.length>500&&i(`error`,`compatibility can be at most 500 characters.`,f.valueFrom,f.valueTo);let p=c.get(`metadata`);if(p&&Ms(p.value))for(let[e,t]of Object.entries(p.value))typeof t!=`string`&&i(`warning`,`metadata.${e} should be a string; quote it.`,p.valueFrom,p.valueTo);let m=c.get(`allowed-tools`);return m&&Array.isArray(m.value)&&i(`warning`,`The spec expects allowed-tools as one space-separated string; only Claude Code accepts a list.`,m.valueFrom,m.valueTo),Os(e,o.bodyFrom,t,n,i),r}const Cs=`The description is empty. Say what the skill does and when to use it.`;function ws(e){let t=e.trim();if(t===``)return{errors:[Cs],warnings:[]};let n=[],r=[];return t.length>_s&&n.push(`The description is ${t.length} characters; the most is ${_s}.`),bs.test(t)&&n.push(`The description can't contain XML tags.`),t.length<40&&r.push(`The description is short. Say what the skill does and when to use it, with the words a user would say.`),{errors:n,warnings:r}}function Ts(e){if(e===``)return[`The name is empty.`];let t=[];e.length>64&&t.push(`The name is ${e.length} characters; the most is 64.`),/^[a-z0-9-]+$/.test(e)?((e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`The name can't start or end with a hyphen.`),e.includes(`--`)&&t.push(`The name can't have two hyphens in a row.`)):t.push(`Use only lowercase letters, numbers and hyphens in the name.`);let n=ys.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function Es(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of ys)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function Ds(e,t,n){let{value:r}=t,i=[t.valueFrom,t.valueTo],a=e.kind;if(r===null)e.required&&n(`error`,`\`${e.key}\` is empty.`,t.keyFrom,t.keyTo);else if(a===`string`&&typeof r!=`string`)n(`error`,`\`${e.key}\` must be text.`,...i);else if(a===`boolean`&&typeof r!=`boolean`){let t=typeof r==`string`?js(r):null;n(`error`,`\`${e.key}\` must be true or false.`,...i,t===null?void 0:{label:`Change to ${t}`,from:i[0],to:i[1],insert:String(t)})}else a===`map`&&!Ms(r)?n(`error`,`\`${e.key}\` must be indented key: value lines.`,...i):a===`tools`&&typeof r!=`string`&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`))?n(`error`,`\`${e.key}\` must be a space-separated list of names.`,...i):typeof a==`object`&&!a.oneOf.includes(String(r))&&n(`error`,`\`${e.key}\` must be one of: ${a.oneOf.join(`, `)}.`,...i)}function Os(e,t,n,r,i){let a=e.slice(t);if(a.trim()===``){i(`warning`,`The skill has no instructions yet. Write them below the frontmatter.`,Math.max(0,t-4),t);return}let o=a.split(`
245
+ `).length;o>500&&i(`warning`,`${K} has ${o} lines below the frontmatter. Keep it under 500 and move details to other files it links to.`,t,t+a.indexOf(`
246
+ `));for(let{path:a,from:o,to:s}of Ti(e,t)){if(a.startsWith(`/`)){i(`warning`,`Link to files with a path relative to SKILL.md, without a leading /.`,o,s);continue}let e=$n(K,a);if(e===null){let e=Ei(a);if(e&&r?.has(e))continue;i(`warning`,e&&r?`There's no skill named \`${e}\` in this organization.`:`This link points outside the skill.`,o,s)}else!n.has(e)&&![...n].some(t=>t.startsWith(`${e}/`))&&i(`warning`,`There's no ${e} in this skill.`,o,s)}}function ks(e){return/nested mappings|implicit keys/i.test(e)&&!/map values/i.test(e)?`This value has a colon in it. Wrap the whole value in quotes.`:/implicit map keys need to be followed by map values/i.test(e)?"Each frontmatter line needs a key, a colon and a value, like `key: value`.":`YAML: ${e.replace(/\.$/,``)}.`}function As(e){return{severity:`error`,path:null,message:e}}function js(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function Ms(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ns(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const Ps=`channels.yaml`;function Fs(e,t){let n=`${t}/`,r=/* @__PURE__ */ new Map,i=[];for(let t of e){if(!t.path.startsWith(n))continue;let e=t.path.slice(n.length),a=e.indexOf(`/`);if(a===-1){i.push(e);continue}let o=e.slice(0,a),s=r.get(o)??[];s.push({path:e.slice(a+1),size:t.size}),r.set(o,s)}return{folders:[...r].sort(([e],[t])=>e.localeCompare(t)),loose:i}}function Is(e){return Fs(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===K)).map(([e])=>e)}function Ls(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(Is(t));e.truncated&&r.push({severity:`warning`,path:null,message:`The repository has more files than GitHub lists at once, so some weren't checked.`}),i.size>300&&r.push({severity:`warning`,path:`skills`,message:`Only the first 300 skills were checked.`});let a=Fs(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${K} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${K}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of xs({files:t,skillMd:s,skills:n}))o.push({severity:e.severity,path:e.path===null?a:`${a}/${e.path}`,...e.path===`SKILL.md`&&e.from!==void 0?{line:ss(s,e.from)}:{},message:e.message});let r=yi(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${K}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:yi(s).description,files:t.length,errors:o.filter(e=>e.severity===`error`).length,warnings:o.filter(e=>e.severity===`warning`).length}}),o=(e,t,n)=>{for(let i of n)t.some(e=>e.path===i)||r.push({severity:`error`,path:e,message:`It needs a ${i}.`})},s=Fs(t,`evals`).folders.map(([e])=>{let n=`evals/${e}`;i.has(e)||r.push({severity:`warning`,path:n,message:`There's no skill named “${e}” in skills/, so these evals have nothing to test.`});let a=Fs(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=Fs(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=Fs(t,`${i}/tasks`).folders;for(let[e,t]of a)o(`${i}/tasks/${e}`,t,[`task.yaml`,`prompt.md`]);return a.length===0&&r.push({severity:`warning`,path:i,message:`It has no tasks yet: add one in tasks/<task>/.`}),{name:e,tasks:a.length}});if(typeof e.channelsText==`string`){let t=hs(e.channelsText),n=(e,t)=>r.push({severity:e,path:Ps,message:t});if(`error`in t)n(`error`,`${t.error} No channel was changed.`);else{for(let e of t.problems)n(`error`,e);for(let e of t.pins.keys())i.has(e)||n(`warning`,`There's no skill named “${e}” in skills/, so its channels set nothing.`)}}let l=[];for(let n of Fs(t,`kits`).loose){let t=`kits/${n}`,a=fs(t);if(a===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are kits: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}l.push(a);let o=(e,n)=>r.push({severity:e,path:t,message:n}),s=us(a);if(!s.ok||s.name!==a){o(`error`,`“${a}” can't be a kit's name, so this file isn't read. ${s.ok?`Take out the spaces.`:s.message}`);continue}let c=e.kitTexts?.get(t);if(c===void 0)continue;let u=ps(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}return{skills:a,evals:s,benchmarks:c,fixtures:Fs(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),channels:t.some(e=>e.path===Ps),problems:Rs(r)}}const Rs=e=>e.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0)),zs=(e,t,n)=>`There's a ${e} called “${t}” in ${n} already, and a name is one in the organization. This one isn't read: rename it, or take it out of one of them.`;function Bs(e,t){let n=[],r=e=>t.main!==null&&e===`channels.yaml`;n.push(...e.problems.filter(e=>!r(e.path))),t.main!==null&&e.channels&&n.push({severity:`warning`,path:Ps,message:`It's ignored: release channels are only read from the main repository, ${t.main}.`});let i=e.skills.map(e=>{let r=t.skills.get(e.name);return r===void 0?e:(n.push({severity:`error`,path:`skills/${e.name}`,message:zs(`skill`,e.name,r)}),{...e,errors:e.errors+1})});for(let r of e.kits){let e=t.kits.get(r);e!==void 0&&n.push({severity:`error`,path:ds(r),message:zs(`kit`,r,e)})}return{...e,skills:i,problems:Rs(n)}}const Vs={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},Hs=/^[A-Za-z0-9._:-]{1,128}$/,Us=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,Ws=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Gs=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Ks=/[\u0000-\u001f\u007f]/;function qs(e){let t=e.trim(),n=Ws.exec(t)??Gs.exec(t);if(!n)return null;let[,r,i]=n,a=i.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);if(a.length<2)return null;let o=[r,...a].join(`/`).toLowerCase();return Js(o)?o:null}const Js=e=>Us.test(e)&&e.length<=Vs.maxRepositoryLength,Ys=e=>e.length>0&&e.length<=Vs.maxBranchLength&&e.trim()===e&&!Ks.test(e),Xs={sessionId:null,repository:null,branch:null,locked:!1},Zs=e=>typeof e==`string`&&e?e:null;async function Qs(e,t,n=C()){let r=Zs(e);if(ua(t,n)===null)return{...Xs,sessionId:r};let{repository:i,branch:a}=await ec(t);return{sessionId:r,repository:i,branch:a,locked:!0}}const $s=({locked:e,...t})=>t;async function ec(e){let[t,n]=await Promise.all([rc(e,[`remote`,`get-url`,`origin`]),rc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?qs(t):null,branch:n}}async function tc(e,t){if(nc.includes(t))return!0;let n=await rc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const nc=[`main`,`master`,`develop`];function rc(e,t){return new Promise(n=>{try{he(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const ic=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`],ac=e=>{try{return p(e).isDirectory()}catch{return!1}};function oc(e){let t;for(let n=b(e);;n=g(n)){if(t??=ac(_(n,`skills`))?n:void 0,f(_(n,`.git`))){if(ac(_(n,`skills`)))return n;throw Error(`${G(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(g(n)===n)break}if(t)return t;throw Error(`There's no skills/ folder here. Run this in a clone of your organization's repository.`)}async function sc(e){let t=[];for(let n of ic){let r=_(e,n);if(ac(r))for(let n of await k(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=_(n.parentPath,n.name),i=y(e,r).split(x).join(`/`);Rn(i)||t.push({path:i,size:(await ce(r)).size})}}return f(_(e,`channels.yaml`))&&t.push({path:Ps,size:(await ce(_(e,Ps))).size}),t}async function cc(e){let t=await sc(e),n=/* @__PURE__ */ new Map;for(let r of Is(t))n.set(r,await O(_(e,`skills`,r,K),`utf8`));return Ls({files:t,skillMds:n,channelsText:t.some(e=>e.path===`channels.yaml`)?await O(_(e,Ps),`utf8`):null})}const lc=(e,t)=>t.aborted?`agent kit didn't answer in time`:e instanceof Error?e.message:String(e),uc=`Skill names in your organization's other repositories`;async function dc(e,t,n){let r=await e.listOrganizations(n),i=await Promise.all(r.map(t=>e.getRepository(t.id,n).then(e=>({organizationId:t.id,status:e})).catch(e=>{if(e instanceof z&&(e.status===403||e.status===404))return null;throw e})));for(let e of i){if(!e)continue;let n=e.status.repositories??(e.status.repository?[e.status.repository]:[]),r=n.find(e=>`github.com/${e.fullName.toLowerCase()}`===t);if(!r)continue;let i=n.find(e=>e.main);return{organizationId:e.organizationId,fullName:r.fullName,placement:{main:r.main?null:i?.fullName??null,skills:new Map(Object.entries(r.elsewhere?.skills??{})),kits:new Map(Object.entries(r.elsewhere?.kits??{}))}}}return null}async function fc(e,t,n,{timeoutMs:r=1e4}={}){if(!n)return{scan:e,unchecked:`${uc} weren't checked: log in with ${R(`login`)} to check them.`,place:null};if(!t)return{scan:e,unchecked:null,place:null};let i=AbortSignal.timeout(r),a;try{a=await dc(n.api,t,i)}catch(t){return{scan:e,unchecked:`${uc} weren't checked: couldn't get your organization's repositories (${lc(t,i)}).`,place:null}}return a?{scan:Bs(e,a.placement),unchecked:null,place:a}:{scan:e,unchecked:`${uc} weren't checked: agent kit reads no repository at ${t}.`,place:null}}async function pc(e,t){let n=await U();return fc(t,(await ec(e)).repository,n&&{api:B(V(),n.token)})}function mc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=b(n,i);if(ac(t)){if(t===e||t===_(e,`skills`))return[];if(g(t)===_(e,`skills`)){r.push(m(t));continue}let n=y(_(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(x)[0]);continue}throw Error(`${G(t)} isn't a skill's folder. Skills are in ${G(_(e,`skills`))}/<skill>/.`)}if(!/^[a-z0-9-]+$/.test(i))throw Error(`There's no folder ${i}, and it isn't a skill's name.`);r.push(i)}return[...new Set(r)]}const hc=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function gc(e){let t=oc(e.find(e=>e.includes(`/`))??`.`),n=mc(t,e),r=await cc(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${G(t)}.`);let{scan:o,unchecked:s}=await pc(t,r),c=n.length>0?hc(o.problems,n):o.problems;for(let e of ls(c))console.log(e);s&&console.log(`${c.length?`
247
+ `:``}${s}`);let l=c.filter(e=>e.severity===`error`).length,u=c.length-l,d=n.length===1?n[0]:n.length>0?cs(n.length,`skill`):`The repository (${cs(o.skills.length,`skill`)})`;l>0?(console.log(`\n${d}: ${cs(l,`error`)}`+(u?`, ${cs(u,`warning`)}`:``)+`. agent kit won't make a version of a skill with errors.`),process.exitCode=1):console.log((c.length||s?`
248
+ `:``)+`${d}: no errors`+(u?`, ${cs(u,`warning`)}`:``)+`.`)}const _c=9e5,vc=e=>Math.floor(e/_c)*_c,yc={maxPerRequest:20,maxEntries:1e3,maxAgeDays:Vs.maxAgeDays,maxFutureMs:Vs.maxFutureMs,maxMachineNameLength:Vs.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Z={inputTokens:`tokens.input`,outputTokens:`tokens.output`,cacheReadTokens:`tokens.cache_read`,cacheCreationTokens:`tokens.cache_creation`,costUsd:`cost.usd`,personSeconds:`active.person`,agentSeconds:`active.agent`,prompts:`prompts`,commits:`commits`,pullRequests:`pull_requests`},bc=/* @__PURE__ */ new Set([Z.personSeconds,Z.agentSeconds,Z.costUsd]),xc=e=>typeof e==`string`&&e.length>0&&e.length<=yc.maxModelLength&&!/\s/.test(e)&&!Ks.test(e),Sc={maxPerRequest:100,maxLinks:50,maxAgeDays:Vs.maxAgeDays,maxFutureMs:Vs.maxFutureMs,maxMachineNameLength:Vs.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},Cc=/\s/,wc=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function Tc(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Js(t)?{kind:e,value:t}:null}case`branch`:{let t=n.indexOf(`#`);if(t<0)return null;let r=n.slice(0,t).toLowerCase(),i=n.slice(t+1);return Js(r)&&Ys(i)?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return Dc(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Sc.maxThreadLength&&!Cc.test(n)&&!Ks.test(n)?{kind:e,value:n}:null;case`session`:return Hs.test(n)?{kind:e,value:n}:null;default:return null}}function Ec(e){let t=e.trim();return Tc(`slack_thread`,t)??Tc(`thread`,t)}function Dc(e){return e.length<=Sc.maxUrlLength&&wc.test(e)}const Oc=()=>_(H(),`sessions`),kc=()=>_(H(),`pending-session-events.jsonl`),Ac=e=>de(`sha256`).update(e).digest(`hex`).slice(0,32);function jc(e,t){switch(e.hook_event_name){case`SessionStart`:return t===`session`?`start`:null;case`SessionEnd`:return`end`;case`UserPromptSubmit`:case`PostToolUse`:case`Stop`:return`seen`;default:return null}}async function Mc(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=jc(t,n),l=i.sessionId;if(!c||!l||!Hs.test(l))return null;c===`end`&&t.reason===`clear`&&await Hc(r,l,o);let u=[],d=e=>{e&&u.push(e)};if(c!==`end`&&i.repository&&(d(Tc(`repository`,i.repository)),i.branch&&!await tc(r,i.branch)&&d(Tc(`branch`,`${i.repository}#${i.branch}`))),c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&i.locked)for(let t of e.split(/\s+/))d(Ec(t));if(t.source===`clear`){let e=await Uc(r,l,o,s);e&&d(Tc(`session`,e))}}let f=await Fc(l),p=u.map(zc),m=p.some(e=>!f.links.includes(e));return c===`seen`&&!m&&o.getTime()-f.sentAt<3e5?null:(await Bc(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...f.links,...p])]}),c===`start`&&await Wc(o),{sessionId:l,agent:e,machineId:await da(),machineName:ia(),type:c,occurredAt:o.toISOString(),links:u})}const Nc=(e,t=[])=>aa(kc(),e,t),Pc=e=>_(Oc(),`${Ac(e)}.json`);async function Fc(e){try{let t=JSON.parse(await O(Pc(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[],...t.imported===!0&&{imported:!0}}}catch{return{sentAt:0,links:[]}}}const Ic=async e=>(await Fc(e)).links;async function Lc(e,t){let n=await Fc(e);await Bc(e,{sentAt:n.sentAt,links:[.../* @__PURE__ */ new Set([...n.links,...t.map(zc)])],imported:!0})}async function Rc(e){try{return JSON.parse(await O(Pc(e),`utf8`)).imported!==!0}catch{return!1}}const zc=e=>`${e.kind} ${e.value}`;async function Bc(e,t){await D(Oc(),{recursive:!0,mode:448}),await A(Pc(e),JSON.stringify(t)+`
249
+ `)}const Vc=e=>_(Oc(),`cleared-${Ac(e)}.json`);async function Hc(e,t,n){await D(Oc(),{recursive:!0,mode:448}),await A(Vc(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
250
+ `)}async function Uc(e,t,n,r){let i=Vc(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await se(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await xe(100)}}async function Wc(e){try{for(let t of await k(Oc())){let n=_(Oc(),t),{mtimeMs:r}=await ce(n);e.getTime()-r>6048e5&&await se(n,{force:!0})}}catch{}}function Gc(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await X(n.projectLock):null,a=await X(Y(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await Qo(r.userId),d=!u||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await ts(r.api,r.userId,u,new Date(s))??u),(u&&Kc(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function Kc(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let{id:e}of Object.values(t?.skills??{})){let t=r.skills[e];t&&i.set(t,(i.get(t)??0)+1)}let a=[...i.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null;if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const qc={"claude_code.token.usage":{input:Z.inputTokens,output:Z.outputTokens,cacheRead:Z.cacheReadTokens,cacheCreation:Z.cacheCreationTokens},"claude_code.cost.usage":Z.costUsd,"claude_code.active_time.total":{user:Z.personSeconds,cli:Z.agentSeconds},"claude_code.commit.count":Z.commits,"claude_code.pull_request.count":Z.pullRequests};function Jc(e){let t=[];for(let n of Qc(Q(e,`resourceMetrics`)))for(let e of Qc(Q(n,`scopeMetrics`)))for(let n of Qc(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?qc[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of Qc(Q(i,`dataPoints`))){let i=Qc(Q(n,`attributes`)),o=e=>$c(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=el(Q(n,`asDouble`)??Q(n,`asInt`)),u=tl(Q(n,`startTimeUnixNano`)),d=tl(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Xc(e,i,a?u:null),metric:c,model:Zc(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Yc(e){let t=[];for(let n of Qc(Q(e,`resourceLogs`)))for(let e of Qc(Q(n,`scopeLogs`)))for(let n of Qc(Q(e,`logRecords`))){let e=Qc(Q(n,`attributes`)),r=$c(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=$c(e,`session.id`),a=tl(Q(n,`timeUnixNano`))??tl(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Xc(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return de(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const Zc=e=>xc(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Qc=e=>Array.isArray(e)?e:[];function $c(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function el(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function tl(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const nl=e=>de(`sha256`).update(e).digest(`hex`).slice(0,32);function rl(e){let t=()=>_(Ya(),e),n=e=>_(t(),`${nl(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await A(n(e),JSON.stringify(r)+`
251
+ `)},async list(){let e=[];try{e=await k(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(_(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await k(t())){let r=_(t(),n);e-(await ce(r)).mtimeMs>6048e5&&await se(r,{force:!0})}}catch{}}}}const il=rl(`sessions`),al=e=>il.write(e.sessionId,e);async function ol(e){let t=await il.read(e);return t?.sessionId===e?t:null}const sl=(e=Date.now())=>il.forgetOld(e),cl=rl(`sent`),ll=(e,t,n=/* @__PURE__ */ new Date)=>cl.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),ul=e=>cl.read(e),dl=async()=>(await cl.list()).sort((e,t)=>t.at.localeCompare(e.at)),fl=(e=Date.now())=>cl.forgetOld(e),pl=(e,t)=>({sessionId:e,epoch:t,series:{},slices:{},prompts:0,lastAt:t});function ml(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n],l=o;if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;l=Math.max(0,o-(c?.value??0)),e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}if(bc.has(r)&&l>0){let t=vc(s),n=e.slices??={},o=JSON.stringify([r,i,a,t]),c=n[o]??={metric:r,model:i,skillName:a,start:t,value:0};c.value+=l}return e.lastAt=Math.max(e.lastAt,s),!0}function hl(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)},i=e=>e!==null&&Object.hasOwn(t.skillIds,e)?t.skillIds[e]:null;for(let t of Object.values(e.series))bc.has(t.metric)||r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),value:t.value});for(let t of Object.values(e.slices??{}))r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),end:new Date(t.start+_c).toISOString(),value:t.value});return e.prompts>0&&r({metric:Z.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Number(!!e.entry.end)-Number(!!t.entry.end)||Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,yc.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const gl=rl(`state`);function _l(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=vl(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);ml(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await gl.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await gl.write(e.state.sessionId,e.state))}}}async function vl(e,t){let n=await gl.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:pl(e,t),unsaved:!1}}const yl=(e=Date.now())=>gl.forgetOld(e),bl=16777216,xl=()=>_(H(),`pending-session-usage.jsonl`);async function Sl(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=_l(),s=Gc(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new z(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!sa(e))for(let e of t)await ll(e,`refused`);throw e}for(let e of t)await ll(e,`sent`)}),p=(e=[])=>aa(xl(),f,e,{batch:yc.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await ol(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=hl(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await da(),machineName:ia(),skillIds:i.skillIds});a.usage.length!==0&&(await ll(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),ma(h),Nc(g)]);function v(e){let t=El(e.activations),n=El(e.sessionEvents);return u(()=>Promise.all([t.length>0&&ma(h,t),n.length>0&&Nc(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(ee(),!S(t.headers[`x-agent-kit-collector`]))return t.resume(),Tl(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return Tl(n,200,{api:e.apiUrl,pid:process.pid,version:Qt});if(t.method!==`POST`)return t.resume(),Tl(n,404,{});if(i===`/stop`){t.resume(),Tl(n,200,{}),ae({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),Tl(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),Tl(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),Tl(n,415,{message:`Send JSON.`});let a=await wl(t);if(!a.ok)return Tl(n,a.status,{});i===`/report`?(Tl(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?Jc(a.json):Yc(a.json)),b(),Tl(n,200,{}))}let S=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&me(t,c)},C=ye((e,t)=>{x(e,t).catch(()=>{t.headersSent||Tl(t,500,{})})});if(!await new Promise(t=>{C.once(`error`,()=>t(!1)),C.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let w=null,T=Date.now(),E=e=>{w&&clearTimeout(w),w=setTimeout(()=>void te(),e)};function ee(){T=Date.now(),E(i)}async function te(){let e=T,t=!1;if(await u(async()=>{let e=[xl(),pa(),kc()];t=(await Promise.all(e.map(oa))).some(Boolean)||(await o.dirty()).length>0}),k||T!==e)return;let n=Date.now()-T;t&&n<a?E(Math.max(1,Math.min(i,a-n))):ae()}ee();let ne=setInterval(()=>void u(m),t),re=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await sl(e),await yl(e),await fl(e),await o.resume()});let ie=()=>u(m).then(()=>u(_)),D=()=>{},O=new Promise(e=>D=e),k=null;function ae({send:e=!0}={}){return k??=(async()=>{w&&clearTimeout(w),y&&clearTimeout(y),clearInterval(ne),clearInterval(re);let t=new Promise(e=>C.close(()=>e()));C.closeIdleConnections(),await(e?ie():u(()=>o.save())),C.closeAllConnections(),await t,D()})(),k}return{port:C.address().port,flush:ie,stop:ae,stopped:O}}const Cl=n(be);async function wl(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>bl)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await Cl(r,{maxOutputLength:bl})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function Tl(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const El=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function Dl(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await Qa();await(await Sl({port:t,secret:n,apiUrl:V(),login:async()=>{let e=await U();return e?{api:B(V(),e.token),userId:e.user.id}:null}}))?.stopped}const Ol=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,kl=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function Al(e){let t=0;for(let[n]of e.matchAll(kl)){let e=n[0];if(e===`
252
+ `)t+=1;else if(/\s/.test(e))t+=n.length===1?0:Math.ceil(n.length/4);else if(/\p{L}/u.test(e)){let e=0;for(let t of n)Ol.test(t)&&e++;let r=[...n].length-e;t+=e+Math.ceil(r/6)}else/\p{N}/u.test(e)?t+=Math.ceil(n.length/3):t+=1}return t}function jl(e){return{always:e.description,max:e.description+e.body+e.files}}function Ml(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=jl(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function Nl(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${Fl((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${Fl((e/1e6).toFixed(1))}M`}const Pl=(e,t)=>`${t===`estimate`?`~`:``}${Nl(e)}`,Fl=e=>e.replace(/\.0$/,``),Il={high:15,medium:10,low:5},Ll=5e3,Rl=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function zl(e){let t=Qn(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&Rl.has(n)}const Bl=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Vl=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Hl(e,t){let n=t(`SKILL.md`)??``,r=vi(n),i=e=>r.ok?r.entries.find(t=>t.key===e):void 0,a=i(`description`)?.value,o=i(`when_to_use`)?.value,s=r.ok?r.body:n,c=s.trim(),l=new Set(e.map(e=>e.path)),u=e=>l.has(e)||[...l].some(t=>t.startsWith(`${e}/`)),d=/* @__PURE__ */ new Set([K]),f=/* @__PURE__ */ new Set,p=!1,m=[K];for(;m.length>0;){let n=m.shift(),r=n===`SKILL.md`?s:t(n);if(r===void 0)zl(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of eu(r)){let t=$n(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&tu(r,n,t.path)&&(d.add(t.path),zl(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!Bl.test(Qn(e))).filter(e=>!Qn(e).startsWith(`.`)).sort();return{v:1,description:typeof a==`string`&&a.trim()!==``?a.trim():null,hasWhenToUse:typeof o==`string`&&o.trim()!==``,bodyLines:c===``?0:c.split(`
253
+ `).length,bodyTokens:Al(c),hasExamples:su(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Ul(e,t,n=/* @__PURE__ */ new Date){let r=[...Zl(e),...t?Ql(t,n):[]];return{score:Wl(r),checks:Kl(r)}}function Wl(e){let t=e.reduce((e,t)=>e+Il[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+Il[t.severity],0);return Math.round(n/t*100)}const Gl=[`high`,`medium`,`low`];function Kl(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Gl.indexOf(e.severity)-Gl.indexOf(t.severity)))}const ql=(e,t,n)=>({id:e,severity:t,passed:!0,message:n,fix:null}),$=(e,t,n,r)=>({id:e,severity:t,passed:!1,message:n,fix:r}),Jl=/\b(use (this( skill)?|it) (when|for|whenever|if|to)|use (when|for|whenever|if)|trigger(s|ed)? (on|when|for)|when(ever)? (the )?(user|you|someone|asked|working|writing|reviewing|handling|dealing|creating|editing)|invoke when)\b/i,Yl=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Xl=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Zl(e){let t=[],n=e.description??``;e.hasWhenToUse||Jl.test(n)?t.push(ql(`description-when`,`high`,`description says when to use it`)):t.push($(`description-when`,`high`,`description has no "Use when…"`,`End the description with "Use when…" and the situations and words that should load the skill.`));let r=n.split(/\s+/).filter(Boolean).length,i=n.match(Yl);n.length<40||r<6?t.push($(`description-specific`,`medium`,n===``?`no description`:`description is too short`,`Say what the skill does in concrete terms: the task, what it takes and what it makes.`)):i?t.push($(`description-specific`,`medium`,`description is vague ("${i[0]}")`,`Name the task, the file types or tools, and the result instead of general words.`)):t.push(ql(`description-specific`,`medium`,`description is specific`)),Xl.test(n)?t.push($(`description-person`,`low`,`description isn't in the third person`,`Write "Fills PDF forms…", not "I can…" or "You can…": the description goes into the system prompt.`)):t.push(ql(`description-person`,`low`,`description is in the third person`)),n.length>600?t.push($(`description-length`,`low`,`description is long (${n.length} chars)`,`Keep it under 600 characters; move the details into SKILL.md's body.`)):t.push(ql(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=$l(e.bodyTokens);return e.bodyLines===0?t.push($(`body-length`,`medium`,`${K} has no instructions`,`Write the instructions below the frontmatter.`)):e.bodyLines>500||e.bodyTokens>Ll?t.push($(`body-length`,`medium`,`${K} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${$l(Ll)}; move reference material into files ${K} links to.`)):t.push(ql(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(ql(`examples`,`medium`,`has examples`)):t.push($(`examples`,`medium`,`no examples`,`Show an input and the output you want, in a code block or under an Examples heading.`)),e.missingFiles.length===0?t.push(ql(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${cu(e.missingFiles.length,`missing file`)}: ${lu(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(ql(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${cu(e.unusedFiles.length,`file`)} nothing mentions: ${lu(e.unusedFiles)}`,`Mention them in ${K}, saying when to read or run them, or delete them.`))),t}function Ql(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(ql(`eval-cases`,`high`,cu(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${cu(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(ql(`eval-negative`,`medium`,`${cu(e.negativeCaseCount,`case`)} where the skill shouldn't help`)):n.push($(`eval-negative`,`medium`,`no eval cases where the skill shouldn't help`,`Add a case whose prompt shouldn't load the skill (Should trigger off), so you notice when it fires too often.`));let r=e.lastRunAt===null?null:Math.max(0,Math.floor((t.getTime()-Date.parse(e.lastRunAt))/864e5));return r!==null&&r<=30?n.push(ql(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${cu(r,`day`)} ago`)):n.push($(`eval-recent-run`,`low`,r===null?`evals never ran`:`no eval run in the last 30 days`,`Run the evals, so you know the current version still works.`)),n}function $l(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function eu(e){let t=[];for(let n of e.matchAll(Vl)){let e=n[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/|\/)/i.test(e))continue;let r=e.split(`#`)[0].split(`?`)[0];try{r=decodeURIComponent(r)}catch{}r!==``&&t.push(r)}return t}function tu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,Qn(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=nu(t,n);return a&&r.add(a),[...r].some(t=>ru(e,t))}function nu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function ru(e,t){let n=e.indexOf(t);for(;n!==-1;){let r=n===0?``:e[n-1],i=e[n+t.length]??``,a=/[A-Za-z0-9_-]/;if(!a.test(r)&&(t.endsWith(`/`)||!a.test(i)))return!0;n=e.indexOf(t,n+1)}return!1}const iu=/^(```|~~~)/m,au=/^#{1,6}[^\n]*\bexamples?\b/im,ou=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function su(e){return iu.test(e)||au.test(e)||ou.test(e)}function cu(e,t){return`${e} ${t}${e===1?``:`s`}`}function lu(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const uu=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function du(e){try{return(await ce(_(e,K))).isFile()}catch{return!1}}async function fu(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await k(i,{withFileTypes:!0})){let o=_(i,a.name);if(a.isDirectory()){uu.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=y(e,o).split(x).join(`/`),{size:c}=await ce(o);t.push({path:s,size:c}),(s===`SKILL.md`||zl({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Ul(Hl(t,e=>n.get(e)),null)}function pu(e){let t=[`HEALTH ${e.score}/100`];for(let n of e.checks)n.passed?t.push(`✓ ${n.message}`):(t.push(`■ ${n.message} [${n.severity}]`),n.fix&&t.push(` ${n.fix}`));return t.join(`
254
+ `)}async function mu(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=b(t??`.`);if(await du(n)){let e=await fu(n),r=t===void 0?`This folder`:G(n);I.info(`${r}: checked from its files; evals aren't.`),console.log(pu(e));return}if(t===void 0)throw Error("There's no SKILL.md here. Name one of your skills, like `a-kit health pdf-forms`, or a skill's folder.");let{api:r}=await Ga(),i=Cn(await r.listSkills(),t);if(i.length>1)throw Error(`More than one organization has a skill named "${t}". Name it with its organization: ${i.map(e=>`"${e.organizationName}/${e.name}"`).join(`, `)}.`);let a=i[0],o=await r.getSkillHealth(a.id);I.info(`${kn(a)} v${a.version}`),console.log(pu(o))}async function hu(e){Bt(`agent kit`);let t=await Wa();t?I.success(`Logged in as ${Ka(t.user)}`):t=await Ua();let n=B(V(),t.token),r=await n.listSkills();if(r.length===0){L(qa(t.webUrl));return}let i=!e.yes;if(i&&!mn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await _n(e.global,i),o=await gn(e.agent,i),s=i?hn(await Rt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:kn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await Po(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});L(`Installed in ${c.map(G).join(`, `)}`)}async function gu(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ba();return;case`on`:{if(await Fn({heartbeat:!0}),!await U()){I.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!$i()){I.warn(`Run it from the published CLI to install the timer.`);return}await Va();let e=await Pa(V()),t=(await za())?.ok??!1;e?I.success(`Heartbeats are on${t?`; this machine is on your Machines page`:``}.`):I.warn(`Heartbeats are on, but this system has no timer agent kit can use (only Linux with systemd and macOS). It still reports when you install, update, or start Claude Code.`);return}case`off`:await Fn({heartbeat:!1}),await Na(V()),I.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await W()).heartbeat!==!1,t=await Pa(V()),n=await za();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?ka(V()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
255
+ Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const _u=2e3;async function vu(e,t={},n=300){let{port:r,secret:i}=await Qa();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[Ja]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function yu(){let e=await vu(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function bu(e,t,n=Lo){let r=await yu();return r===`taken`?`taken`:r?.api===t&&r.version===Qt?`running`:(r&&await Su(),f(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function xu(e){return(await vu(`/report`,{method:`POST`,body:JSON.stringify(e)},_u))?.status===202}async function Su({send:e=!0}={}){return(await vu(e?`/stop`:`/stop?send=false`,{method:`POST`},_u))?.ok??!1}const Cu=5e3;async function wu(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await Du()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Wo($i()??Qi()),await Pa(V())||await Ba();return}if(In()||(await W()).telemetry===!1)return;let o=await U();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=c?{...Xs,sessionId:Zs(r.session_id)}:await Qs(r.session_id,s),u=B(V(),o.token),d=r.hook_event_name===`SessionStart`&&a===`session`;d&&l.sessionId&&await Eu(e,l.sessionId,s),(d||r.hook_event_name===`UserPromptSubmit`||r.hook_event_name===`Stop`||c)&&await bu($i()??Qi(),V());let f=await Mc(e,r,a,s,l,{now:i}),p=bo(r),m=p&&await la(p.name,e,s),h=p&&m&&await fa(m,e,p.trigger,$s(l),i),g=await Qo(o.user.id);await Promise.all([!c&&es(g,i,m?m.id:null)&&ts(u,o.user.id,g,i),(f||h)&&Tu(u,f,h)])}catch{}}async function Tu(e,t,n){await xu({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&Nc(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(Cu))},t),n&&ma(async t=>{await e.reportActivations(t,AbortSignal.timeout(Cu))},n)])}async function Eu(e,t,n){let{repository:r,branch:i}=await ec(n),a=ua(n,C());(r||a)&&await al({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function Du(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function Ou(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${R(`link skills/release`)}.`);Bt(`agent kit`);let n=b(e[0]);if(!f(_(n,`SKILL.md`)))throw Error(`${G(n)} has no ${K}, so it isn't a skill.`);let r=m(n);if(!/^[a-z0-9-]+$/.test(r))throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await gn(t.agent,!t.yes),o=rn(a,i),s=o.map(e=>_(e,r));if(s.includes(n))throw Error(`${G(n)} is already where your agents read it.`);let c=(await X(Y(i))).skills[r];for(let e of s)if(f(e)&&!await Gn(e)&&!c)throw Error(`${G(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Wn(B(V(),(await U())?.token),r,c,o);if(e&&!await Gn(e.folder))throw Error(`${G(e.folder)} has edits that aren't in agent kit (${Hn(e.paths)}). Copy them to ${G(n)} and delete them there first.`)}for(let e of s)await qn(e,n);I.success(`${r}: ${s.map(G).join(`, `)} → ${G(n)}`);let l=i===`project`?await ku(rn(a,`global`),r,n):[];l.length>0&&I.warn(`You also have ${r} in ${l.map(G).join(`, `)}, and your agents use that copy over this project's. Run ${R(`link ${e[0]} -g`)} to try yours everywhere instead.`),await Au(n,r,c!==void 0),L(`${l.length>0?`This project's agents would use`:`Your agents use`} ${G(n)} as it is, edits included (a new session sees an edit an open one missed). ${R(`add ${r}`)} goes back to agent kit's version.`)}async function ku(e,t,n){let r=[];for(let i of e){let e=_(i,t);f(e)&&await Gn(e)!==n&&r.push(e)}return r}async function Au(e,t,n){let r;try{r=oc(e)}catch{return}if(b(r,`skills`,t)!==e)return;let{scan:i,place:a}=await pc(r,await cc(r)),o=a?.placement.skills.get(t);n&&o!==void 0&&I.warn(`The ${t} you installed from agent kit is ${o}'s, a different skill: this link takes its place, so your agents use ${G(e)} instead. ${R(`add ${t}`)} puts ${o}'s back.`);let s=hc(i.problems,[t]);s.some(e=>e.severity===`error`)&&I.warn([`agent kit won't make a version of ${t} as it is:`,...ls(s)].join(`
256
+ `))}function ju(e,t,n){let r=e.map(e=>{let r=t.skills[e.name],i=n.skills[e.name],a=e.contextCost,o=e=>a?Pl(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[kn(e),Mu(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[Nu(`project`,r,e),Nu(`global`,i,e)].filter(Boolean).join(`, `)]}}),i=[`SKILL`,`VERSION`,`DESC`,`BODY`,`FILES`,`INSTALLED`],a=i.map((e,t)=>Math.max(e.length,...r.map(e=>e.cells[t].length))),o=e=>e.map((t,n)=>n===e.length-1?t:t.padEnd(a[n])).join(` `).trimEnd(),s=r.filter(e=>e.installed),c=Ml(s.map(e=>e.skill.contextCost)),l=c.estimated?`~`:``,u=[o(i),...r.map(e=>o(e.cells))];return u.push(s.length===0?`${`TOTAL`.padEnd(a[0])} nothing installed here`:`${`TOTAL`.padEnd(a[0])} ${l}${Nl(c.always)} always · ${l}${Nl(c.max)} max (${s.length} installed${c.missing?`, ${c.missing} not counted yet`:``})`),r.some(e=>e.skill.contextCost?.source===`estimate`)&&u.push(`~ estimated locally: add a Claude API key to the organization to count exactly.`),u}function Mu(e){return[`v${e.version}`,...qt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function Nu(e,t,n){if(!t)return null;let r=zi(t),{version:i}=Zt(n.channels,n.version,r),a=`in ${e}${r===`latest`?``:` on ${r}`}`;return t.version===i?a:`${a} at v${t.version}, run a-kit update${e===`global`?` -g`:``}`}async function Pu(){let{api:e,credentials:t}=await Ga(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(qa(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of ju(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>Fu(e).length));for(let e of r){let t=[Iu(i,e)&&`in project`,Iu(a,e)&&`in global`].filter(Boolean);console.log(`${Fu(e).padEnd(o)} ${Lu(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const Fu=e=>`${vn}${kn(e)}`,Iu=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function Lu(e){let t=e.skills.length;if(t===0)return`no skills`;let n=e.skills.slice(0,3).map(e=>e.name);return`${t} skill${t===1?``:`s`}: ${n.join(`, `)}${t>3?`, …`:``}`}const Ru=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${R(`heartbeat status`)}).`;async function zu(e,t){switch(e){case`name`:{let{api:e}=await Ga(),n=await da();if(t===void 0){let t=await Bu(e.machineName(n));if(!t)throw Error(Ru);console.log(t.name?`This machine is "${t.name}" on the Machines page (its hostname is ${t.hostname}).`:`This machine goes by its hostname, "${t.hostname}", on the Machines page. Name it with ${R(`machine name <name>`)}.`);return}let r=await Bu(e.nameMachine(n,t))??(await Ba()?await Bu(e.nameMachine(n,t)):null);if(!r)throw Error(Ru);I.success(r.name?`This machine is "${r.name}" on the Machines page.`:`This machine goes by its hostname, "${r.hostname}", on the Machines page.`);return}default:throw Error(`Unknown machine action "${e??``}". Use ${R(`machine name [<name>]`)}.`)}}async function Bu(e){try{return await e}catch(e){if(e instanceof z&&e.status===404)return null;throw e}}async function Vu(e,t){switch(e){case void 0:case`status`:{let e=(await za())?.organization;console.log(e?`This machine shows up on ${e.name}'s Machines page.`:`This machine hasn't shown up on a Machines page yet.`),console.log(`Move it to another organization with ${R(`org use`)}.`);return}case`use`:{let{api:e,credentials:n}=await Ga(),r=await Sa(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${R(`org use acme`)}.`);if((await W()).heartbeat===!1){I.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${R(`heartbeat on`)}.`);return}await Ba()?I.success(`This machine now shows up on ${r.name}'s Machines page.`):I.warn(`This machine goes to ${r.name}; it shows up there with its next heartbeat.`);return}default:throw Error(`Unknown org action "${e}". Use status or use.`)}}async function Hu(){Bt(`agent kit`);let e=await Wa().catch(()=>null);if(e){let t=Ka(e.user);if(!mn()){L(`Already logged in as ${t}.`);return}if(!hn(await Ft({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){L(`Still logged in as ${t}.`);return}}let t=await Ua();e&&await B(V(),e.token).logout().catch(()=>{}),L(await Gu(t.token,t.webUrl))}async function Uu(e=process.stdin){Bt(`agent kit`);let t=await Wu(e);if(!t)throw Error(`Give it the bot's token on stdin, like ${R(`login --token`)} < bot-token.`);let n;try{n=await B(V(),t).me()}catch(e){throw e instanceof z&&e.status===401?Error(`This token doesn't work: it's wrong, or the bot was revoked.`):e}let r=await U();await Nn({token:t,user:n,webUrl:An(V())}),r&&r.token!==t&&await B(V(),r.token).logout().catch(()=>{}),await Va(),L(`Logged in as ${Ka(n)}.`)}async function Wu(e){if(e.isTTY)return hn(await Vt({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function Gu(e,t){return(await B(V(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${qa(t)}`:`You're in. Install your skills with ${R(`init`)}.`}async function Ku(){let e=await U();e?(await B(V(),e.token).logout().catch(()=>{}),await Nn(null),console.log(`Logged out ${Ka(e.user)}.`)):console.log(`You're not logged in.`)}async function qu(){let e=await Wa();e?console.log(Ka(e.user)):(console.log(`You're not logged in. Run ${R(`login`)}.`),process.exitCode=1)}const Ju=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Yu(e){let t=await Xu(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${fn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${R(`check <skill>`)}`,` 3. Try it in your agent: ${R(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${R(`add <skill>`)} or ${R(`update`)}.`),Error(r.join(`
257
+ `))}async function Xu(){let e=(await U())?.token;if(!e)return[];let t=B(V(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}function Zu(e){return e&&e.total>0?e.passed/e.total:null}async function Qu(e){let{api:t,credentials:n}=await Ga(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log($u(r,n.webUrl,i.length>1))}function $u({skills:e,runs:t},n,r){if(e.length===0&&t.length===0)return`Nothing matches.`;let i=[];if(e.length>0){let t=e.map(e=>kn({...e,showOrganization:r})),n=Math.max(...t.map(e=>e.length));i.push(`Skills`),e.forEach((e,r)=>{i.push(` ${t[r].padEnd(n)} v${e.version} a-kit add ${e.name}`)})}if(t.length>0){i.length>0&&i.push(``);let e=t.map(e=>`${e.skillName} v${e.version}`),r=Math.max(...e.map(e=>e.length));i.push(`Runs`),t.forEach((t,a)=>{let o=Zu(t.withSkill),s=o===null?`—`:`${Math.round(o*100)}%`;i.push(` ${e[a].padEnd(r)} ${s.padStart(4)} ${t.status.padEnd(9)} ${n}/app/skills/${t.skillId}?tab=runs&run=${t.id}`)})}return i.join(`
258
+ `)}const ed={inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadInputTokens:Z.cacheReadTokens,cacheCreationInputTokens:Z.cacheCreationTokens,costUSD:Z.costUsd},td={input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,cache_read_input_tokens:Z.cacheReadTokens,cache_creation_input_tokens:Z.cacheCreationTokens},nd=/^\{"type":"(api-request|atis-latch|queue-operation)/;function rd(e){let t={sessionId:e,cwd:null,startedAt:null,endedAt:null,branches:[],skills:[],prompts:0,turns:[],runs:[],replies:{}},n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=e=>{let n=e.message,i=typeof n?.id==`string`?n.id:null,a=typeof n?.model==`string`?n.model:null,o=n?.usage;if(!i||!a||a.startsWith(`<`)||r.has(i)||typeof o!=`object`||!o)return;r.add(i);let s=t.replies[a]??={};for(let[e,t]of Object.entries(td)){let n=o[e];typeof n==`number`&&n>0&&(s[t]=(s[t]??0)+n)}};return{take(r,{subagent:a=!1}={}){if(!r||nd.test(r))return;let o;try{o=JSON.parse(r)}catch{return}if(typeof o!=`object`||!o)return;if(a){o.type===`assistant`&&i(o);return}if(typeof o.sessionId==`string`&&o.sessionId!==e)return;o.type===`assistant`&&i(o);let s=typeof o.timestamp==`string`?Date.parse(o.timestamp):NaN;if(Number.isNaN(s)||(t.startedAt=Math.min(t.startedAt??s,s),t.endedAt=Math.max(t.endedAt??s,s)),!Number.isNaN(s)&&(o.type===`assistant`||o.type===`user`)){let e=t.turns.at(-1);!e||o.type===`user`&&!ad(o).some(e=>e.type===`tool_result`)?t.turns.push({start:s,end:s}):e.end=Math.max(e.end,s)}t.cwd===null&&typeof o.cwd==`string`&&o.cwd&&(t.cwd=o.cwd);let c=o.gitBranch;switch(typeof c==`string`&&c&&c!==`HEAD`&&!Number.isNaN(s)&&!t.branches.some(e=>e.branch===c)&&t.branches.push({branch:c,at:s}),o.type){case`cost-state`:id(o,n);return;case`assistant`:if(Number.isNaN(s))return;for(let e of ad(o)){if(e.type!==`tool_use`||typeof e.input!=`object`)continue;let n=e.input??{};if(e.name===`Skill`&&typeof n.skill==`string`){let e=n.skill.replace(/^\//,``);t.skills.push({name:e,trigger:`model`,at:s})}}return;case`user`:{if(Number.isNaN(s)||!sd(o))return;t.prompts++;let e=cd(o)?.match(/^\/([^\s]+)/)?.[1];e&&t.skills.push({name:e,trigger:`user`,at:s});return}}},result(){return t.runs=[...n.values()].sort((e,t)=>e.start-t.start),t}}}function id(e,t){let n=e.startTime,r=e.modelUsage;if(typeof n!=`number`||typeof r!=`object`||!r)return;let i=t.get(n);i||t.set(n,i={start:n,models:{}});for(let[e,t]of Object.entries(r)){if(typeof t!=`object`||!t)continue;let n=i.models[e]??={};for(let[e,r]of Object.entries(ed)){let i=t[e];typeof i==`number`&&i>(n[r]??0)&&(n[r]=i)}}}function ad(e){let t=e.message?.content;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e):[]}function od(e){let t=e.message?.content;if(typeof t==`string`)return t;let n=ad(e);if(n.some(e=>e.type===`tool_result`))return null;let r=n.filter(e=>e.type===`text`);return r.length>0?r.map(e=>typeof e.text==`string`?e.text:``).join(`
259
+ `):null}function sd(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=od(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function cd(e){let t=od(e);if(!t)return null;let n=/<command-name>\s*\/?([^\s<]+)\s*<\/command-name>/.exec(t)?.[1];if(n){let e=/<command-args>([\s\S]*?)<\/command-args>/.exec(t)?.[1];return`/${n}${e?.trim()?` ${e.trim()}`:``}`}return/^\s*\/[^\s]/.test(t)?t.trimStart():null}async function ld(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function ud(e,t){let n=rd(t);await ld(e,e=>n.take(e));let r=n.result();if(r.runs.length>0)return r;let i=_(e.replace(/\.jsonl$/,``),`subagents`),a=[];try{a=(await k(i)).filter(e=>e.endsWith(`.jsonl`))}catch{return r}for(let e of a)await ld(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const dd=`claude-code`,fd={outside:`not in a repository that installs skills from agent kit, or its folder is gone`,empty:`nothing in it says when it was`,old:`older than ${Sc.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were`},pd=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function md(e){let t;try{t=await k(e)}catch{return[]}let n=[];for(let r of t){let t;try{t=await k(_(e,r))}catch{continue}for(let i of t){let t=i.replace(/\.jsonl$/,``);if(t===i||!Hs.test(t))continue;let a=_(e,r,i),{mtimeMs:o,isFile:s}=await ce(a).then(e=>({mtimeMs:e.mtimeMs,isFile:e.isFile()}),()=>({mtimeMs:0,isFile:!1}));s&&n.push({file:a,sessionId:t,at:o})}}return n.sort((e,t)=>e.at-t.at)}async function hd(e){let t=e.now??/* @__PURE__ */ new Date,n={sessions:[],skipped:{}},r=e=>{n.skipped[e]=(n.skipped[e]??0)+1};for(let{file:i,sessionId:a}of await md(e.projectsDir)){let o=await gd(await ud(i,a),e,t);typeof o==`string`?r(o):n.sessions.push(o)}return n.sessions.sort((e,t)=>e.startedAt.localeCompare(t.startedAt)),n}async function gd(e,t,n=t.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<n.getTime()-Sc.maxAgeDays*864e5)return`old`;let r=t.home??C(),i=e.cwd,a=await Qs(e.sessionId,i,r),o=a.repository;if(!a.locked||!o)return`outside`;let s={sessionId:e.sessionId,agent:dd,machineId:t.machineId,machineName:t.machineName,imported:!0},c=await t.organizationOf({sessionId:e.sessionId,agent:dd,cwd:i,projectLock:ua(i,r),repository:o,branch:e.branches[0]?.branch??null,registeredAt:yd(e.startedAt)});if(await Rc(e.sessionId))return`live`;if(c===`unknown`)throw Error(`Couldn't ask agent kit which organization a session's skills are of. Try again in a moment.`);let l=[],u=(e,t)=>{let n=t.filter(e=>e!==null);n.length>0&&l.push({at:e,links:n})};u(e.startedAt,[Tc(`repository`,o)]);for(let{branch:t,at:n}of e.branches)await tc(i,t)||u(n,[Tc(`branch`,`${o}#${t}`)]);l.sort((e,t)=>e.at-t.at);let d=/* @__PURE__ */ new Set,f=[],p=(e,t,n)=>{for(let r=0;r===0||r<n.length;){let i=n.slice(r,r+Sc.maxLinks);f.push({...s,type:e,occurredAt:yd(t),links:i}),r+=Math.max(i.length,1)}},m=e=>e.filter(e=>{let t=zc(e);return!d.has(t)&&(d.add(t),!0)}),h=m(l.filter(t=>t.at<=e.startedAt).flatMap(e=>e.links));p(`start`,e.startedAt,h);for(let{at:t,links:n}of l){if(t<=e.startedAt)continue;let r=m(n);r.length>0&&p(`seen`,t,r)}p(`end`,e.endedAt,[]);let g=[];for(let[t,n]of e.skills.entries()){let o=await la(n.name,dd,i,r);o&&g.push({...s,...$s({...a,branch:_d(e,n.at)}),id:bd(`${e.sessionId}\n${t}\n${n.at}\n${n.name}`),skillId:o.id,version:o.version,trigger:n.trigger,occurredAt:yd(n.at),sessionId:e.sessionId})}let _=c?{...s,organizationId:c.organizationId,occurredAt:yd(e.endedAt),usage:vd(e)}:null;return{sessionId:e.sessionId,repository:o,startedAt:yd(e.startedAt),events:f,activations:g,usage:_}}function _d(e,t){let n=null;for(let r of e.branches)r.at<=t&&(n=r.branch);return n??e.branches[0]?.branch??null}function vd(e){let t=[],n=e.runs.length>0?e.runs:[{start:e.startedAt,models:e.replies}];e.prompts>0&&t.push({metric:Z.prompts,model:null,skillId:null,start:yd(n[0]?.start??e.startedAt),value:e.prompts});for(let e of n)for(let[n,r]of Object.entries(e.models))for(let[i,a]of Object.entries(r))a>0&&t.push({metric:i,model:n,skillId:null,start:yd(e.start),value:a});let r=/* @__PURE__ */ new Map;for(let{start:t,end:n}of e.turns)for(let e=t;e<n;){let t=vc(e),i=Math.min(n,t+_c);r.set(t,(r.get(t)??0)+(i-e)/1e3),e=i}for(let[e,n]of r)t.push({metric:Z.agentSeconds,model:null,skillId:null,start:yd(e),end:yd(e+_c),value:n});return t.slice(0,yc.maxEntries)}const yd=e=>new Date(e).toISOString();function bd(e){let t=de(`sha256`).update(e).digest(`hex`),n=(parseInt(t[16],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-${n}${t.slice(17,20)}-${t.slice(20,32)}`}const xd=Sc.maxPerRequest;async function Sd(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=xd){let i=await e.reportSessionEvents(r.slice(t,t+xd));for(let e of i.live??[])n.add(e)}let i=t.sessions.filter(e=>!n.has(e.sessionId)),a=i.flatMap(e=>e.activations);for(let t=0;t<a.length;t+=100)await e.reportActivations(a.slice(t,t+100));let o=Cd(t=>e.reportSessionUsage(t),yc.maxPerRequest,409600);for(let e of i)e.usage&&await o.add(e.usage);return await o.flush(),{sent:i,live:[...n]}}function Cd(e,t,n){let r=[],i=0,a=async()=>{if(r.length===0)return;let t=r;r=[],i=0,await e(t)};return{async add(e){let o=JSON.stringify(e).length;(r.length>=t||r.length>0&&i+o>n)&&await a(),r.push(e),i+=o},flush:a}}async function wd({dryRun:e}){let t=await U();if(!t)throw Error("Log in first with `a-kit login`.");if(!e&&(In()||(await W()).telemetry===!1))throw Error("Telemetry is off, so nothing is sent. Turn it on with `a-kit telemetry on`, or see what would be sent with `--dry-run`.");let n=B(V(),t.token),r=t.user.id;if(!await ts(n,r,await Qo(r),/* @__PURE__ */ new Date))throw Error(`Couldn't ask agent kit which skills are your organizations'. Try again in a moment.`);let i=Gc(async()=>({api:n,userId:r})),a=pd(),o=await hd({projectsDir:a,organizationOf:e=>i.of(e),machineId:await da(),machineName:ia()});if(e){for(let e of o.sessions)console.log(Dd(e));console.log(`\nWould send ${Td(o.sessions.length)} from ${a}. Nothing was sent.`),Ed(o.skipped,`Would skip`),o.sessions.length>0&&console.log(`agent kit leaves a session live telemetry already sent as it is.`);return}let s=await Sd({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e)},o);for(let e of s.sent)await Lc(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await ll(e.usage,`sent`);I.success(`Sent ${Td(s.sent.length)} from ${a} to agent kit.`),Ed({...o.skipped,...s.live.length>0&&{live:(o.skipped.live??0)+s.live.length}},`Skipped`),console.log("Claude Code keeps about 30 days of sessions. `a-kit telemetry show <session-id>` shows what was sent for one.")}const Td=e=>`${e} session${e===1?``:`s`}`;function Ed(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${Td(r)}:`);for(let[e,t]of n)console.log(` ${t} ${fd[e]}`)}}function Dd(e){let t=new Set(e.events.flatMap(e=>e.links.map(zc))),n=e=>[...t].filter(t=>t.startsWith(`${e} `)).length,r=e.usage?.usage.filter(e=>e.metric===Z.costUsd).reduce((e,t)=>e+t.value,0),i=[`${n(`branch`)} branches`,`${e.activations.length} skills loaded`,e.usage?r?`$${r.toFixed(2)}`:`usage`:`no usage (no organization of yours is its)`];return`${e.sessionId} ${e.startedAt} ${e.repository} ${i.join(`, `)}`}const Od={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function kd(e,t,{port:n,dryRun:r=!1}={}){switch(e){case`on`:{n!==void 0&&await $a(Number(n)),await Fn({telemetry:!0});let e=await Co();if(e.status===`skipped`){I.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}I.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&I.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await Fn({telemetry:!1}),await Co(),await Su({send:!1}),I.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return jd(t);case`import`:return wd({dryRun:r});case void 0:case`status`:{let e=await W(),t=(await Eo()).includes(`telemetry`),n=e.telemetry===!1?`off`:In()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await Qa(),i=await yu(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${Od[await To()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status, show or import.`)}}const Ad={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function jd(e){if(e){let[t,n]=await Promise.all([ul(e),Ic(e)]);if(!t&&n.length===0)throw Error(`Nothing was sent for session ${e}.`);console.log(n.length>0?`Its session told agent kit of:\n${n.map(e=>` ${e}`).join(`
260
+ `)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${Ad[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
261
+ Nothing of what it used was sent.`);return}let t=await dl();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${Ad[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function Md(e,t){let[n,...r]=e;if(!n)throw Error(`Name a skill and a prompt: a-kit try <skill> "<prompt>"`);let i=r.length>0?r.join(` `):await Ld();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Id(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Ga(),c=Cn(await s.listSkills(),n);if(c.length>1)throw Error(`More than one of your organizations has a skill named "${n}". Say which one: ${c.map(e=>`${e.organizationName}/${e.name}`).join(` or `)}.`);let l=c[0],u=e=>console.log(`\n${e.toUpperCase()} · ${o}\n`),d=(e,t)=>Nd(s,l.id,{model:o,version:a,withSkill:e,prompt:i},t),f=[],p=d(!1,e=>f.push(e));p.catch(()=>{});let m=!1;Fd(await d(!0,e=>{m||u(`With ${kn(l)} v${a??l.version}`),m=!0,Pd(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Pd(e,l.name);Fd(h)}async function Nd(e,t,n,r){let i=`The answer ended before it finished.`;try{await e.playground(t,{model:n.model,version:n.version,withSkill:n.withSkill,messages:[{role:`user`,content:n.prompt}]},e=>{e.type===`done`&&(i=e),e.type===`error`&&(i=e.message),r(e)})}catch(e){if(e instanceof z)throw e;i=e instanceof Error?e.message:String(e)}return i}function Pd(e,t){if(e.type===`text`&&process.stdout.write(e.text),e.type===`tool`){let n=e.tool===`load_skill`?`Loaded ${e.skill}`:`Read ${e.skill}/${e.path??``}`;process.stdout.write(`${e.skill===t?`■`:`□`} ${n}\n\n`)}}function Fd(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=un(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${cn(e.usage)}`)}function Id(e){if(e===void 0)return;let t=Number(e.replace(/^v/,``));if(!Number.isInteger(t)||t<1)throw Error(`"${e}" isn't a version number, like 3.`);return t}async function Ld(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Rd=`a-kit ${Qt}: your agent kit skills, in your agents.
314
262
 
315
263
  Usage
316
264
  a-kit init Log in and pick skills to install
@@ -325,7 +273,6 @@ Usage
325
273
  its skills with the rules agent kit reads them with
326
274
  a-kit link <folder> Have your agents use a skill's folder in that clone,
327
275
  edits included (\`a-kit add <skill>\` undoes it)
328
- a-kit report Send an agent session that went wrong, scrubbed
329
276
  a-kit try <skill> <prompt> Ask Claude with the skill and without it, side by side
330
277
  a-kit login Log in through the browser
331
278
  a-kit login --token Log a bot in with the token an admin made for it,
@@ -353,8 +300,8 @@ Usage
353
300
 
354
301
  Options
355
302
  -g, --global Install in your home folder instead of this project
356
- -a, --agent <id> Install for this agent (repeatable): ${rn.map(e=>e.id).join(`, `)}
357
- --channel <channel> Install a release channel: ${Qt.join(`, `)} (default latest);
303
+ -a, --agent <id> Install for this agent (repeatable): ${$t.map(e=>e.id).join(`, `)}
304
+ --channel <channel> Install a release channel: ${Jt.join(`, `)} (default latest);
358
305
  \`a-kit update\` keeps following it
359
306
  -y, --yes Don't ask; use the defaults
360
307
  -h, --help Show this help
@@ -363,14 +310,4 @@ Options
363
310
  Try options (billed to the organization's Claude API key)
364
311
  --model <id> The Claude model; defaults to claude-sonnet-5-5
365
312
  --skill-version <n> The skill's version; defaults to the current
366
-
367
- Report options (the report-session-issue skill passes them for you)
368
- --title <text> A short title
369
- --note <text> What went wrong
370
- --expected <text> What should have happened
371
- --session <id|path> The session; defaults to this folder's latest
372
- --map <file|-> JSON of private words to replace: {"Acme": "Example"}
373
- --org <id|name> The organization, when it can't tell
374
- --full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
375
- --dry-run Scrub and show what would be sent, without sending
376
- `;async function Rp(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Ud.has(e))return Wd(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},session:{type:`string`},title:{type:`string`},note:{type:`string`},expected:{type:`string`},map:{type:`string`},org:{type:`string`},"full-outputs":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(nn);let[i,...a]=r;if(n.help||!i)return console.log(Lp);if(!en(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Qt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return ud(o);case`add`:case`install`:return Ko(a,o);case`update`:return ms(o);case`list`:case`ls`:return kd();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Uf(a);case`health`:return ld(a);case`check`:return el(a);case`link`:return Cd(a,o);case`login`:return n.token?Rd():Ld();case`logout`:return Vd();case`whoami`:return Hd();case`try`:return jp(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return Pf({...o,session:n.session,title:n.title,note:n.note,expected:n.expected,map:n.map,org:n.org,fullOutputs:n[`full-outputs`],dryRun:n[`dry-run`]});case`telemetry`:return Op(a[0],a[1],{port:n.port,dryRun:n[`dry-run`]});case`auto-update`:return _s(a[0]);case`heartbeat`:return dd(a[0],n.api);case`org`:return Id(a[0],a.slice(1).join(` `)||n.org);case`machine`:return Pd(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return yd(a[0],n.api,a[1]);case`collector`:return Su(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Rp().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
313
+ `;async function zd(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Ju.has(e))return Yu(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},org:{type:`string`},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(Qt);let[i,...a]=r;if(n.help||!i)return console.log(Rd);if(!Xt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Jt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return hu(o);case`add`:case`install`:return Io(a,o);case`update`:return rs(o);case`list`:case`ls`:return Pu();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Qu(a);case`health`:return mu(a);case`check`:return gc(a);case`link`:return Ou(a,o);case`login`:return n.token?Uu():Hu();case`logout`:return Ku();case`whoami`:return qu();case`try`:return Md(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:throw Error("`a-kit report` is gone: agent kit takes no reports.");case`telemetry`:return kd(a[0],a[1],{port:n.port,dryRun:n[`dry-run`]});case`auto-update`:return os(a[0]);case`heartbeat`:return gu(a[0],n.api);case`org`:return Vu(a[0],a.slice(1).join(` `)||n.org);case`machine`:return zu(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return wu(a[0],n.api,a[1]);case`collector`:return Dl(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}zd().catch(e=>{let t=e instanceof Error?e.message:String(e);I.error(t),process.exitCode=1});export{};