useakit 0.2.0-dev.42 → 0.2.0-dev.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -70,7 +70,7 @@ Installing skills also installs `report-session-issue`. Tell your agent "report
70
70
 
71
71
  ## Auto-update
72
72
 
73
- Installing skills for Claude Code also adds a `SessionStart` hook to `~/.claude/settings.json` that runs `a-kit update -g` when a session starts or resumes. It runs in a background process, so the session doesn't wait for it, and at most once an hour, however many sessions start. It skips the run when nothing is installed everywhere or you're not logged in. A project's skills aren't touched: they live in its repo, so they change only when you run `a-kit update` there.
73
+ Installing skills for Claude Code also adds a `SessionStart` hook to `~/.claude/settings.json` that checks your global skills when a session starts or resumes. A background process, so the session doesn't wait for it, sends agent kit what your global lock has and gets back one fingerprint of it: the version each skill's channel installs, each kit's skills, each public skill's version. When the fingerprint isn't the one your last update left, it runs `a-kit update -g`; when it is, that one request is all. Sessions that start within the same minute check once. It skips the check when nothing is installed everywhere or you're not logged in. A project's skills aren't touched: they live in its repo, so they change only when you run `a-kit update` there.
74
74
 
75
75
  ```sh
76
76
  a-kit auto-update # whether it's on
package/dist/index.mjs CHANGED
@@ -12,70 +12,70 @@ import{createRequire as e}from"node:module";import{parseArgs as t,styleText as n
12
12
  `).length-1;this.output.write(j.cursor.move(-999,e*-1))}render(){let e=ze(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=Ue(this._prevFrame,e),n=Xe(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
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(`
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}}},et=class extends $e{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})}},tt=class extends $e{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?Be(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=Be(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Be(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let nt=class extends $e{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?Be(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=Be(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Be(this.cursor,1,this.options)}this.changeValue()})}};var rt=class extends $e{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),r=e.slice(this.cursor,this.cursor+1),i=e.slice(this.cursor+1);return`${t}${n(`inverse`,r)}${i}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function it(){return r.platform===`win32`?!!r.env.CI||!!r.env.WT_SESSION||!!r.env.TERMINUS_SUBLIME||r.env.ConEmuTask===`{cmd::Cmder}`||r.env.TERM_PROGRAM===`Terminus-Sublime`||r.env.TERM_PROGRAM===`vscode`||r.env.TERM===`xterm-256color`||r.env.TERM===`alacritty`||r.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:r.env.TERM!==`linux`}const at=it(),ot=()=>process.env.CI===`true`,N=(e,t)=>at?e:t,st=N(`◆`,`*`),ct=N(`■`,`x`),lt=N(`▲`,`x`),ut=N(`◇`,`o`),dt=N(`┌`,`T`),P=N(`│`,`|`),F=N(`└`,`—`),ft=N(`●`,`>`),pt=N(`○`,` `),mt=N(`◻`,`[•]`),ht=N(`◼`,`[+]`),gt=N(`◻`,`[ ]`),_t=N(`●`,`•`),vt=N(`◆`,`*`),yt=N(`▲`,`!`),bt=N(`■`,`x`),xt=e=>{switch(e){case`initial`:case`active`:return n(`cyan`,st);case`cancel`:return n(`red`,ct);case`error`:return n(`yellow`,lt);case`submit`:return n(`green`,ut);case`validating`:return n(`dim`,st)}},St=e=>{switch(e){case`initial`:case`active`:return n(`cyan`,P);case`cancel`:return n(`red`,P);case`error`:return n(`yellow`,P);case`submit`:return n(`green`,P)}};function Ct(e,t){let r=[`${t?`${n(`cyan`,P)} `:``}${e.join(` • `)}`];return t&&r.push(n(`cyan`,F)),r}const wt=(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}},Tt=({cursor:e,options:t,style:r,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=Ye(i)-o,l=Xe(i),u=n(`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 n=y;n<b;n++){let i=t[n],a=ze(i?r(i,n===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=()=>wt(_,r,0,i,a),s=()=>wt(_,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},Et=e=>{let t=e.active??`Yes`,r=e.inactive??`No`;return new et({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??M.withGuide,a=`${xt(this.state)} `,o=i?`${n(`gray`,P)} `:``,s=Ze(e.output,e.message,o,a),c=`${i?`${n(`gray`,P)}
15
+ `)),this._prevFrame=e;return}}this.output.write(j.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},et=class extends $e{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})}},tt=class extends $e{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?Be(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=Be(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Be(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let nt=class extends $e{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?Be(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=Be(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Be(this.cursor,1,this.options)}this.changeValue()})}};var rt=class extends $e{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),r=e.slice(this.cursor,this.cursor+1),i=e.slice(this.cursor+1);return`${t}${n(`inverse`,r)}${i}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function it(){return r.platform===`win32`?!!r.env.CI||!!r.env.WT_SESSION||!!r.env.TERMINUS_SUBLIME||r.env.ConEmuTask===`{cmd::Cmder}`||r.env.TERM_PROGRAM===`Terminus-Sublime`||r.env.TERM_PROGRAM===`vscode`||r.env.TERM===`xterm-256color`||r.env.TERM===`alacritty`||r.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:r.env.TERM!==`linux`}const at=it(),ot=()=>process.env.CI===`true`,N=(e,t)=>at?e:t,st=N(`◆`,`*`),ct=N(`■`,`x`),lt=N(`▲`,`x`),ut=N(`◇`,`o`),dt=N(`┌`,`T`),P=N(`│`,`|`),ft=N(`└`,`—`),pt=N(`●`,`>`),mt=N(`○`,` `),ht=N(`◻`,`[•]`),gt=N(`◼`,`[+]`),_t=N(`◻`,`[ ]`),vt=N(`●`,`•`),yt=N(`◆`,`*`),bt=N(`▲`,`!`),xt=N(`■`,`x`),St=e=>{switch(e){case`initial`:case`active`:return n(`cyan`,st);case`cancel`:return n(`red`,ct);case`error`:return n(`yellow`,lt);case`submit`:return n(`green`,ut);case`validating`:return n(`dim`,st)}},Ct=e=>{switch(e){case`initial`:case`active`:return n(`cyan`,P);case`cancel`:return n(`red`,P);case`error`:return n(`yellow`,P);case`submit`:return n(`green`,P)}};function wt(e,t){let r=[`${t?`${n(`cyan`,P)} `:``}${e.join(` • `)}`];return t&&r.push(n(`cyan`,ft)),r}const Tt=(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}},Et=({cursor:e,options:t,style:r,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=Ye(i)-o,l=Xe(i),u=n(`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 n=y;n<b;n++){let i=t[n],a=ze(i?r(i,n===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=()=>Tt(_,r,0,i,a),s=()=>Tt(_,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},Dt=e=>{let t=e.active??`Yes`,r=e.inactive??`No`;return new et({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??M.withGuide,a=`${St(this.state)} `,o=i?`${n(`gray`,P)} `:``,s=Ze(e.output,e.message,o,a),c=`${i?`${n(`gray`,P)}
17
17
  `:``}${s}
18
18
  `,l=this.value?t:r;switch(this.state){case`submit`:return`${c}${i?`${n(`gray`,P)} `:``}${n(`dim`,l)}`;case`cancel`:return`${c}${i?`${n(`gray`,P)} `:``}${n([`strikethrough`,`dim`],l)}${i?`
19
- ${n(`gray`,P)}`:``}`;default:{let a=i?`${n(`cyan`,P)} `:``,o=i?n(`cyan`,F):``;return`${c}${a}${this.value?`${n(`green`,ft)} ${t}`:`${n(`dim`,pt)} ${n(`dim`,t)}`}${e.vertical?i?`
19
+ ${n(`gray`,P)}`:``}`;default:{let a=i?`${n(`cyan`,P)} `:``,o=i?n(`cyan`,ft):``;return`${c}${a}${this.value?`${n(`green`,pt)} ${t}`:`${n(`dim`,mt)} ${n(`dim`,t)}`}${e.vertical?i?`
20
20
  ${n(`cyan`,P)} `:`
21
- `:` ${n(`dim`,`/`)} `}${this.value?`${n(`dim`,pt)} ${n(`dim`,r)}`:`${n(`green`,ft)} ${r}`}
21
+ `:` ${n(`dim`,`/`)} `}${this.value?`${n(`dim`,mt)} ${n(`dim`,r)}`:`${n(`green`,pt)} ${r}`}
22
22
  ${o}
23
- `}}}}).prompt()},Dt=[`${n(`dim`,`↑/↓`)} to navigate`,`${n(`dim`,`Space:`)} select`,`${n(`dim`,`Enter:`)} confirm`],Ot=(e,t)=>e.split(`
23
+ `}}}}).prompt()},Ot=[`${n(`dim`,`↑/↓`)} to navigate`,`${n(`dim`,`Space:`)} select`,`${n(`dim`,`Enter:`)} confirm`],kt=(e,t)=>e.split(`
24
24
  `).map(e=>t(e)).join(`
25
- `),kt=e=>{let t=(e,t)=>{let r=e.label??String(e.value);return t===`disabled`?`${n(`gray`,gt)} ${Ot(r,e=>n([`strikethrough`,`gray`],e))}${e.hint?` ${n(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${n(`cyan`,mt)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${n(`green`,ht)} ${Ot(r,e=>n(`dim`,e))}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${Ot(r,e=>n([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${n(`green`,ht)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${Ot(r,e=>n(`dim`,e))}`:`${n(`dim`,gt)} ${Ot(r,e=>n(`dim`,e))}`},r=e.required??!0,i=e.showInstructions??!0;return new tt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(e){if(r&&(e===void 0||e.length===0))return`Please select at least one option.
26
- ${n(`reset`,n(`dim`,`Press ${n([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${n(`gray`,n(`bgWhite`,n(`inverse`,` enter `)))} to submit`))}`},render(){let r=e.withGuide??M.withGuide,a=Ze(e.output,e.message,r?`${St(this.state)} `:``,`${xt(this.state)} `),o=`${r?`${n(`gray`,P)}
25
+ `),At=e=>{let t=(e,t)=>{let r=e.label??String(e.value);return t===`disabled`?`${n(`gray`,_t)} ${kt(r,e=>n([`strikethrough`,`gray`],e))}${e.hint?` ${n(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${n(`cyan`,ht)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${n(`green`,gt)} ${kt(r,e=>n(`dim`,e))}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${kt(r,e=>n([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${n(`green`,gt)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${kt(r,e=>n(`dim`,e))}`:`${n(`dim`,_t)} ${kt(r,e=>n(`dim`,e))}`},r=e.required??!0,i=e.showInstructions??!0;return new tt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(e){if(r&&(e===void 0||e.length===0))return`Please select at least one option.
26
+ ${n(`reset`,n(`dim`,`Press ${n([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${n(`gray`,n(`bgWhite`,n(`inverse`,` enter `)))} to submit`))}`},render(){let r=e.withGuide??M.withGuide,a=Ze(e.output,e.message,r?`${Ct(this.state)} `:``,`${St(this.state)} `),o=`${r?`${n(`gray`,P)}
27
27
  `:``}${a}
28
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(n(`dim`,`, `))||n(`dim`,`none`);return`${o}${Ze(e.output,i,r?`${n(`gray`,P)} `:``)}`}case`cancel`:{let i=this.options.filter(({value:e})=>s.includes(e)).map(e=>t(e,`cancelled`)).join(n(`dim`,`, `));return i.trim()===``?`${o}${n(`gray`,P)}`:`${o}${Ze(e.output,i,r?`${n(`gray`,P)} `:``)}${r?`
29
29
  ${n(`gray`,P)}`:``}`}case`error`:{let t=r?`${n(`yellow`,P)} `:``,i=this.error.split(`
30
- `).map((e,t)=>t===0?`${r?`${n(`yellow`,F)} `:``}${n(`yellow`,e)}`:` ${e}`).join(`
30
+ `).map((e,t)=>t===0?`${r?`${n(`yellow`,ft)} `:``}${n(`yellow`,e)}`:` ${e}`).join(`
31
31
  `),a=o.split(`
32
32
  `).length,s=i.split(`
33
- `).length+1;return`${o}${t}${Tt({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}${Et({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
36
  `}default:{let t=r?`${n(`cyan`,P)} `:``,a=o.split(`
37
- `).length,s=i?Ct(Dt,r):r?[n(`cyan`,F)]:[],l=s.join(`
38
- `),u=s.length+1;return`${o}${t}${Tt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:a+u,style:c}).join(`
37
+ `).length,s=i?wt(Ot,r):r?[n(`cyan`,ft)]:[],l=s.join(`
38
+ `),u=s.length+1;return`${o}${t}${Et({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()},I={message:(e=[],{symbol:t=n(`gray`,P),secondarySymbol:r=n(`gray`,P),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??M.withGuide,l=c?r:``,u=c?`${t} `:``,d=c?`${r} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
41
+ `}}}}).prompt()},F={message:(e=[],{symbol:t=n(`gray`,P),secondarySymbol:r=n(`gray`,P),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??M.withGuide,l=c?r:``,u=c?`${t} `:``,d=c?`${r} `:``;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,...n]=f;e.length>0?s.push(`${u}${e}`):s.push(c?t:``);for(let e of n)e.length>0?s.push(`${d}${e}`):s.push(c?r:``)}i.write(`${s.join(`
43
43
  `)}
44
- `)},info:(e,t)=>{I.message(e,{...t,symbol:n(`blue`,_t)})},success:(e,t)=>{I.message(e,{...t,symbol:n(`green`,vt)})},step:(e,t)=>{I.message(e,{...t,symbol:n(`green`,ut)})},warn:(e,t)=>{I.message(e,{...t,symbol:n(`yellow`,yt)})},warning:(e,t)=>{I.warn(e,t)},error:(e,t)=>{I.message(e,{...t,symbol:n(`red`,bt)})}},At=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,F)} `:``;r.write(`${i}${n(`red`,e)}
44
+ `)},info:(e,t)=>{F.message(e,{...t,symbol:n(`blue`,vt)})},success:(e,t)=>{F.message(e,{...t,symbol:n(`green`,yt)})},step:(e,t)=>{F.message(e,{...t,symbol:n(`green`,ut)})},warn:(e,t)=>{F.message(e,{...t,symbol:n(`yellow`,bt)})},warning:(e,t)=>{F.warn(e,t)},error:(e,t)=>{F.message(e,{...t,symbol:n(`red`,xt)})}},jt=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,ft)} `:``;r.write(`${i}${n(`red`,e)}
45
45
 
46
- `)},jt=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,dt)} `:``;r.write(`${i}${e}
47
- `)},L=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,P)}
48
- ${n(`gray`,F)} `:``;r.write(`${i}${e}
46
+ `)},Mt=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,dt)} `:``;r.write(`${i}${e}
47
+ `)},I=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${n(`gray`,P)}
48
+ ${n(`gray`,ft)} `:``;r.write(`${i}${e}
49
49
 
50
- `)},Mt=e=>n(`magenta`,e),Nt=({indicator:e=`dots`,onCancel:t,output:r=process.stdout,cancelMessage:i,errorMessage:a,frames:o=at?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=at?80:120,signal:c,...l}={})=>{let u=ot(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ye(r),y=l?.styleFrame??Mt,b=e=>{let n=e>1?a??M.messages.error:i??M.messages.cancel;m=e===1,p&&(D(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&&r.write(`
50
+ `)},Nt=e=>n(`magenta`,e),Pt=({indicator:e=`dots`,onCancel:t,output:r=process.stdout,cancelMessage:i,errorMessage:a,frames:o=at?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=at?80:120,signal:c,...l}={})=>{let u=ot(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ye(r),y=l?.styleFrame??Nt,b=e=>{let n=e>1?a??M.messages.error:i??M.messages.cancel;m=e===1,p&&(D(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&&r.write(`
51
51
  `);let e=ze(g,v,{hard:!0,trim:!1}).split(`
52
52
  `);e.length>1&&r.write(j.cursor.up(e.length-1)),r.write(j.cursor.to(0)),r.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=Je({output:r}),h=E(t),_=performance.now(),te&&r.write(`${n(`gray`,P)}
53
53
  `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;T(),g=h;let t=y(o[i]),n;if(u)n=`${t} ${h}...`;else if(e===`timer`)n=`${t} ${h} ${ee(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);n=`${t} ${h}${e}`}let s=ze(n,v,{hard:!0,trim:!1});r.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},D=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),T();let o=i===0?n(`green`,ut):i===1?n(`red`,ct):n(`red`,lt);h=t??h,a||(e===`timer`?r.write(`${o} ${h} ${ee(_)}
54
54
  `):r.write(`${o} ${h}
55
- `)),w(),d()};return{start:ne,stop:(e=``)=>D(e,0),message:(e=``)=>{h=E(e??h)},cancel:(e=``)=>D(e,1),error:(e=``)=>D(e,2),clear:()=>D(``,0,!0),get isCancelled(){return m}}},Pt=[`${n(`dim`,`↑/↓`)} to navigate`,`${n(`dim`,`Enter:`)} confirm`],Ft=(e,t)=>e.includes(`
55
+ `)),w(),d()};return{start:ne,stop:(e=``)=>D(e,0),message:(e=``)=>{h=E(e??h)},cancel:(e=``)=>D(e,1),error:(e=``)=>D(e,2),clear:()=>D(``,0,!0),get isCancelled(){return m}}},Ft=[`${n(`dim`,`↑/↓`)} to navigate`,`${n(`dim`,`Enter:`)} confirm`],It=(e,t)=>e.includes(`
56
56
  `)?e.split(`
57
57
  `).map(e=>t(e)).join(`
58
- `):t(e),It=e=>{let t=(e,t)=>{if(e===void 0)return``;let r=e.label??String(e.value);switch(t){case`disabled`:return`${n(`gray`,pt)} ${Ft(r,e=>n(`gray`,e))}${e.hint?` ${n(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${Ft(r,e=>n(`dim`,e))}`;case`active`:return`${n(`green`,ft)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${Ft(r,e=>n([`strikethrough`,`dim`],e))}`;default:return`${n(`dim`,pt)} ${Ft(r,e=>n(`dim`,e))}`}},r=e.showInstructions??!0;return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??M.withGuide,a=`${xt(this.state)} `,o=`${St(this.state)} `,s=Ze(e.output,e.message,o,a),c=`${i?`${n(`gray`,P)}
58
+ `):t(e),Lt=e=>{let t=(e,t)=>{if(e===void 0)return``;let r=e.label??String(e.value);switch(t){case`disabled`:return`${n(`gray`,mt)} ${It(r,e=>n(`gray`,e))}${e.hint?` ${n(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${It(r,e=>n(`dim`,e))}`;case`active`:return`${n(`green`,pt)} ${r}${e.hint?` ${n(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${It(r,e=>n([`strikethrough`,`dim`],e))}`;default:return`${n(`dim`,mt)} ${It(r,e=>n(`dim`,e))}`}},r=e.showInstructions??!0;return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??M.withGuide,a=`${St(this.state)} `,o=`${Ct(this.state)} `,s=Ze(e.output,e.message,o,a),c=`${i?`${n(`gray`,P)}
59
59
  `:``}${s}
60
60
  `;switch(this.state){case`submit`:{let r=i?`${n(`gray`,P)} `:``;return`${c}${Ze(e.output,t(this.options[this.cursor],`selected`),r)}`}case`cancel`:{let r=i?`${n(`gray`,P)} `:``;return`${c}${Ze(e.output,t(this.options[this.cursor],`cancelled`),r)}${i?`
61
61
  ${n(`gray`,P)}`:``}`}default:{let a=i?`${n(`cyan`,P)} `:``,o=c.split(`
62
- `).length,s=r?Ct(Pt,i):i?[n(`cyan`,F)]:[],l=s.join(`
63
- `),u=s.length+1;return`${c}${a}${Tt({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(`
62
+ `).length,s=r?wt(Ft,i):i?[n(`cyan`,ft)]:[],l=s.join(`
63
+ `),u=s.length+1;return`${c}${a}${Et({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(`
64
64
  ${a}`)}
65
65
  ${l}
66
- `}}}}).prompt()};`${n(`gray`,P)}`;const Lt=e=>new rt({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??M.withGuide,r=`${`${t?`${n(`gray`,P)}
67
- `:``}${xt(this.state)} `}${e.message}
68
- `,i=e.placeholder&&e.placeholder.length>0?n(`inverse`,e.placeholder[0])+n(`dim`,e.placeholder.slice(1)):n([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`validating`:{let e=t?`${n(`cyan`,P)} `:``,i=t?n(`cyan`,F):``;return`${r}${e}${n(`dim`,a)}
66
+ `}}}}).prompt()};`${n(`gray`,P)}`;const Rt=e=>new rt({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??M.withGuide,r=`${`${t?`${n(`gray`,P)}
67
+ `:``}${St(this.state)} `}${e.message}
68
+ `,i=e.placeholder&&e.placeholder.length>0?n(`inverse`,e.placeholder[0])+n(`dim`,e.placeholder.slice(1)):n([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`validating`:{let e=t?`${n(`cyan`,P)} `:``,i=t?n(`cyan`,ft):``;return`${r}${e}${n(`dim`,a)}
69
69
  ${i} ${n(`dim`,`Validating...`)}
70
- `}case`error`:{let e=this.error?` ${n(`yellow`,this.error)}`:``,i=t?`${n(`yellow`,P)} `:``,o=t?n(`yellow`,F):``;return`${r.trim()}
70
+ `}case`error`:{let e=this.error?` ${n(`yellow`,this.error)}`:``,i=t?`${n(`yellow`,P)} `:``,o=t?n(`yellow`,ft):``;return`${r.trim()}
71
71
  ${i}${a}
72
72
  ${o}${e}
73
73
  `}case`submit`:{let e=o?`${t?` `:``}${n(`dim`,o)}`:``;return`${r}${t?n(`gray`,P):``}${e}`}case`cancel`:{let e=o?` ${n([`strikethrough`,`dim`],o)}`:``,i=t?n(`gray`,P):``;return`${r}${i}${e}${o.trim()?`
74
74
  ${i}`:``}`}default:return`${r}${t?`${n(`cyan`,P)} `:``}${a}
75
- ${t?n(`cyan`,F):``}
76
- `}}}).prompt(),Rt=[`stable`,`beta`],zt=[`latest`,...Rt],Bt=e=>Rt.includes(e),Vt=e=>zt.includes(e);function Ht(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 Ut=`0.2.0`;const Wt=[{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`}],Gt=e=>e===`global`?b():process.cwd();function Kt(e=b()){return Wt.filter(t=>l(m(e,t.marker)))}function qt(e){return Wt.find(t=>t.id===e)}function Jt(e,t,n=Gt(t)){let r=e.map(e=>_(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const Yt={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 Xt(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}Yt.maxPromptBytes;function Zt(e){return e<1e3?String(e):e<1e6?`${$t(e/1e3)}k`:`${$t(e/1e6)}M`}const Qt=e=>`${Zt(e.inputTokens+e.outputTokens)} tok · ${Xt(e.costUsd)}`,$t=e=>e>=100?Math.round(e):Number(e.toFixed(1));function en(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 tn(e){let t=e.split(`
77
- `),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 nn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?Ut.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const R=e=>`\`${nn()} ${e}\``;var z=class extends Error{status;code;diagnostics;constructor(e,t,n,r=[]){super(n),this.status=e,this.code=t,this.diagnostics=r}};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/${Ut}`,...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})`,e?.diagnostics??[])}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:()=>i(`/orgs`),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal: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`),saveSkill:(e,t)=>i(`/skills/${e}`,{method:`PUT`,body:JSON.stringify(t)}),createProposal:(e,t)=>i(`/skills/${e}/proposals`,{method:`POST`,body:JSON.stringify(t)}),createSkill:(e,t)=>i(`/orgs/${e}/skills`,{method:`POST`,body:JSON.stringify(t)}),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=tn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}tn(`${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/${rn(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${rn(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${rn(e)}/installs`,{method:`POST`})}}const rn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),V=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function H(e){return Ke(e)&&(At(`Cancelled.`),process.exit(130)),e}async function an(e,t){if(e.length>0)return e.map(e=>{let t=qt(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${Wt.map(e=>e.id).join(`, `)}.`);return t});let n=Kt(),r=n.length>0?n:[qt(`claude-code`)];return!t||!V()?r:H(await kt({message:`Which agents should get the skills?`,options:Wt.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=>qt(e))}async function on(e,t){return e?`global`:!t||!V()?`project`:H(await It({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 ln(e,t,n){if(t.length>0)return dn(e,t,n,`skill`);if(!n||!V())throw Error(`Name the skills to add, like ${R(`add my-skill`)}.`);let r=H(await kt({message:`Which skills?`,options:e.map(e=>({value:e.id,label:vn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const un=(e,t,n)=>dn(e,t,n,`kit`);async function dn(e,t,n,r){let i=[];for(let a of t){let t=hn(e,a,r),o=t.length===1?t[0]:await gn(t,n,r);i.includes(o)||i.push(o)}return i}const fn=(e,t)=>hn(e,t,`skill`);function pn(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 mn=(e,t)=>pn(e,t);function hn(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=pn(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 gn(e,t,n){let r=e[0].name,i=n===`kit`?sn:``;if(!t||!V()){let t=e.map(e=>{let t=i+_n(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=H(await It({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:_n(e)}))}));return e.find(e=>e.id===a)}const _n=e=>`${e.organizationName}/${e.name}`,vn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;async function yn(e,t,n){let r=()=>e.map(e=>e.name).join(`, `);if(t){let n=t.trim().toLowerCase(),i=e.find(e=>e.id===t||e.name.toLowerCase()===n);if(!i)throw Error(`--org: none of your organizations is "${t}". Yours: ${r()}.`);return i}if(e.length===0)throw Error(`You're not in an organization yet. Create one on the web.`);if(e.length===1)return e[0];if(!n||!V())throw Error(`Which organization should the new skill go to? Pass --org with one of: ${r()}.`);let i=H(await It({message:`Which organization should the new skill go to?`,options:e.map(e=>({value:e.id,label:e.name}))}));return e.find(e=>e.id===i)}function U(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.agent-kit.fausanchez.com`??`http://localhost:8787`).replace(/\/+$/,``)}function W(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?m(process.env.APPDATA,`agent-kit`):m(process.env.XDG_CONFIG_HOME??m(b(),`.config`),`agent-kit`)}const bn=()=>m(W(),`credentials.json`);async function xn(){try{return JSON.parse(await O(bn(),`utf8`))}catch{return{}}}async function Sn(){return(await xn())[U()]??null}async function Cn(e){let t=await xn();e?t[U()]=e:delete t[U()];let n=bn();await D(p(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
78
- `,{mode:384}),await ee(n,384)}const wn=()=>m(W(),`settings.json`);async function Tn(){try{return JSON.parse(await O(wn(),`utf8`))}catch{return{}}}async function En(e){let t={...await Tn(),...e};await D(W(),{recursive:!0,mode:448}),await k(wn(),JSON.stringify(t,null,2)+`
75
+ ${t?n(`cyan`,ft):``}
76
+ `}}}).prompt(),zt=[`stable`,`beta`],Bt=[`latest`,...zt],Vt=e=>zt.includes(e),Ht=e=>Bt.includes(e);function Ut(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 Wt=`0.2.0`;const Gt=[{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`}],Kt=e=>e===`global`?b():process.cwd();function qt(e=b()){return Gt.filter(t=>l(m(e,t.marker)))}function Jt(e){return Gt.find(t=>t.id===e)}function Yt(e,t,n=Kt(t)){let r=e.map(e=>_(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const Xt={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 Zt(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}Xt.maxPromptBytes;function Qt(e){return e<1e3?String(e):e<1e6?`${en(e/1e3)}k`:`${en(e/1e6)}M`}const $t=e=>`${Qt(e.inputTokens+e.outputTokens)} tok · ${Zt(e.costUsd)}`,en=e=>e>=100?Math.round(e):Number(e.toFixed(1));function tn(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 nn(e){let t=e.split(`
77
+ `),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 rn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?Wt.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${rn()} ${e}\``;var R=class extends Error{status;code;diagnostics;constructor(e,t,n,r=[]){super(n),this.status=e,this.code=t,this.diagnostics=r}};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/${Wt}`,...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})`,e?.diagnostics??[])}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:()=>i(`/orgs`),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations: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}),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`),saveSkill:(e,t)=>i(`/skills/${e}`,{method:`PUT`,body:JSON.stringify(t)}),createProposal:(e,t)=>i(`/skills/${e}/proposals`,{method:`POST`,body:JSON.stringify(t)}),createSkill:(e,t)=>i(`/orgs/${e}/skills`,{method:`POST`,body:JSON.stringify(t)}),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=nn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}nn(`${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/${an(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${an(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${an(e)}/installs`,{method:`POST`})}}const an=e=>e.split(`/`).map(encodeURIComponent).join(`/`),B=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function V(e){return Ke(e)&&(jt(`Cancelled.`),process.exit(130)),e}async function on(e,t){if(e.length>0)return e.map(e=>{let t=Jt(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${Gt.map(e=>e.id).join(`, `)}.`);return t});let n=qt(),r=n.length>0?n:[Jt(`claude-code`)];return!t||!B()?r:V(await At({message:`Which agents should get the skills?`,options:Gt.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=>Jt(e))}async function sn(e,t){return e?`global`:!t||!B()?`project`:V(await Lt({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 cn=`kit/`;function ln(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 un(e,t,n){if(t.length>0)return fn(e,t,n,`skill`);if(!n||!B())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=V(await At({message:`Which skills?`,options:e.map(e=>({value:e.id,label:yn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const dn=(e,t,n)=>fn(e,t,n,`kit`);async function fn(e,t,n,r){let i=[];for(let a of t){let t=gn(e,a,r),o=t.length===1?t[0]:await _n(t,n,r);i.includes(o)||i.push(o)}return i}const pn=(e,t)=>gn(e,t,`skill`);function mn(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 hn=(e,t)=>mn(e,t);function gn(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=mn(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 _n(e,t,n){let r=e[0].name,i=n===`kit`?cn:``;if(!t||!B()){let t=e.map(e=>{let t=i+vn(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=V(await Lt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:vn(e)}))}));return e.find(e=>e.id===a)}const vn=e=>`${e.organizationName}/${e.name}`,yn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;async function bn(e,t,n){let r=()=>e.map(e=>e.name).join(`, `);if(t){let n=t.trim().toLowerCase(),i=e.find(e=>e.id===t||e.name.toLowerCase()===n);if(!i)throw Error(`--org: none of your organizations is "${t}". Yours: ${r()}.`);return i}if(e.length===0)throw Error(`You're not in an organization yet. Create one on the web.`);if(e.length===1)return e[0];if(!n||!B())throw Error(`Which organization should the new skill go to? Pass --org with one of: ${r()}.`);let i=V(await Lt({message:`Which organization should the new skill go to?`,options:e.map(e=>({value:e.id,label:e.name}))}));return e.find(e=>e.id===i)}function H(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.agent-kit.fausanchez.com`??`http://localhost:8787`).replace(/\/+$/,``)}function U(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?m(process.env.APPDATA,`agent-kit`):m(process.env.XDG_CONFIG_HOME??m(b(),`.config`),`agent-kit`)}const xn=()=>m(U(),`credentials.json`);async function Sn(){try{return JSON.parse(await O(xn(),`utf8`))}catch{return{}}}async function W(){return(await Sn())[H()]??null}async function Cn(e){let t=await Sn();e?t[H()]=e:delete t[H()];let n=xn();await D(p(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
78
+ `,{mode:384}),await ee(n,384)}const wn=()=>m(U(),`settings.json`);async function Tn(){try{return JSON.parse(await O(wn(),`utf8`))}catch{return{}}}async function En(e){let t={...await Tn(),...e};await D(U(),{recursive:!0,mode:448}),await k(wn(),JSON.stringify(t,null,2)+`
79
79
  `)}function Dn(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=g(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const On=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function kn(e){return e.split(`/`).some(e=>On.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const An=e=>le(`sha256`).update(e).digest(`hex`);async function jn(e){let t=await ie(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=g(e,m(r.parentPath,r.name)).split(v).join(`/`);if(kn(t))continue;let i=new Uint8Array(await O(m(e,t)));n.push({path:t,size:i.byteLength,sha256:An(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Mn(e,t){let n=new Map(t.filter(e=>!kn(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 Nn(e,t){let n=e=>e.filter(e=>!kn(e.path)).map(e=>`${e.path}\0${e.sha256}`).sort().join(`
80
80
  `);return n(e)===n(t)}function Pn(e){try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e.bytes);if(!t.includes(`\0`))return{path:e.path,content:t,encoding:`utf8`}}catch{}return{path:e.path,content:Buffer.from(e.bytes).toString(`base64`),encoding:`base64`}}async function Fn(e,t){await oe(e,{recursive:!0,force:!0});for(let n of t){let t=m(e,n.path);await D(p(t),{recursive:!0}),await k(t,n.bytes)}}function In(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)}`}function Ln(e,t){let n=e.find(e=>e.path===t);return n?new TextDecoder().decode(n.bytes):void 0}const K=`SKILL.md`,Rn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},zn=/[\u0000-\u001f\u007f\\:]/;function Bn(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Rn.maxPathLength)return`Paths can be at most ${Rn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if(zn.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 Vn(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function Hn(e){return e.slice(e.lastIndexOf(`/`)+1)}function Un(e,t){let n=Vn(e)?Vn(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__ */ 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})),Wn=/* @__PURE__ */ A((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})),Gn=/* @__PURE__ */ A((e=>{var t=q(),n=Wn();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(`
81
81
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),Kn=/* @__PURE__ */ A((e=>{var t=q(),n=Wn();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})),qn=/* @__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})),Jn=/* @__PURE__ */ A((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})),Yn=/* @__PURE__ */ A((e=>{var t=qn(),n=q(),r=Jn();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}}})),Xn=/* @__PURE__ */ A((e=>{var t=Kn(),n=Wn(),r=q(),i=Yn(),a=Jn(),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);
@@ -217,18 +217,18 @@ n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2
217
217
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
218
218
  `,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())}}}})),ii=/* @__PURE__ */ A((e=>{var t=Xr(),n=Nr(),r=Pr(),i=ir(),a=q(),o=ni(),s=ri();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})),ai=(/* @__PURE__ */ A((e=>{var t=Xr(),n=Nr(),r=jr(),i=Pr(),a=Xn(),o=q(),s=sr(),c=J(),l=lr(),u=dr();ei();var d=ti(),f=ni(),p=ri(),m=ii(),h=Wn();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 oi=/^---[ \t]*$/;function si(e){let t=ui(e,0);if(!oi.test(e.slice(0,t).replace(/\r$/,``)))return`no-frontmatter`;let n=di(e,t),r=n;for(;n<e.length;){let t=ui(e,n);if(oi.test(e.slice(n,t).replace(/\r$/,``)))return{yamlFrom:r,yamlTo:n,bodyFrom:di(e,t)};n=di(e,t)}return`unclosed`}function ci(e){let t=si(e);if(typeof t==`string`)return{ok:!1,reason:t};let n=e.slice(t.yamlFrom,t.yamlTo),r=(0,ai.parseDocument)(n,{prettyErrors:!1}),i=e=>t.yamlFrom+e,a=r.errors.map(e=>({message:e.message.split(`
219
219
  `)[0],from:i(e.pos[0]),to:i(Math.max(e.pos[1],e.pos[0]+1))})),o=r.contents,s=o===null||(0,ai.isMap)(o),c=[];if((0,ai.isMap)(o)){let e=li(()=>r.toJS());for(let t of o.items){if(!(0,ai.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 li(e){try{let t=e();return t&&typeof t==`object`?t:null}catch{return null}}function ui(e,t){let n=e.indexOf(`
220
- `,t);return n===-1?e.length:n}function di(e,t){return Math.min(t+1,e.length)}const fi=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,pi=/^[a-z0-9]+(-[a-z0-9]+)*$/;function mi(e,t){let n=[],r=e.slice(t);for(let e of r.matchAll(fi)){let r=e[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(r))continue;let i=vi(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 hi(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`&&pi.test(n)?n:null}function gi(e){let t=ci(e),n=t.ok?t.block.bodyFrom:0,r=[];for(let t of mi(e,n)){let e=hi(t.path);e&&r.push({...t,name:e})}return r}function _i(e){let t=ci(e),n=t.ok?t.entries.find(e=>e.key===`name`)?.value:null,r=gi(e).map(e=>e.name);return[...new Set(r)].filter(e=>e!==n)}function vi(e){try{return decodeURIComponent(e)}catch{return e}}const yi=`report-session-issue`,bi=/skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;function xi(e,t){if(e===`Skill`){let e=t?.skill;return typeof e==`string`?[Si(e)]:[]}return[...(typeof t==`string`?t:JSON.stringify(t??``)).matchAll(bi)].map(e=>e[1])}const Si=e=>e.slice(e.lastIndexOf(`:`)+1).replace(/^\//,``);function Ci(e){let t=e.events.findIndex(e=>wi(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(Ti))]}}function wi(e){return Ti(e).includes(yi)}function Ti(e){return e.type===`system`?[]:e.message.content.flatMap(t=>t.type===`tool_use`?xi(t.name,t.input):t.type===`text`&&e.type===`user`?[...t.text.matchAll(/<command-name>\/?([\w:-]+)<\/command-name>/g)].map(e=>Si(e[1])):[])}const Ei=e=>e?_i(new TextDecoder().decode(e)):[];async function Di(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=Oi(u,r,i);a.push({skill:u,by:n.name,status:d}),d===`new`&&c.push({name:u.name,organizationId:u.organizationId,references:await ki(e,u.id)})}}return{dependencies:a,missing:o}}function Oi(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=>l(m(t,e.name)))?`conflict`:`new`}async function ki(e,t){let n=(await e.getSkill(t)).files.find(e=>e.path===K);return n?Ei(await e.getBlob(t,n.sha256)):[]}async function Ai(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(`
221
- `));let c=n&&V(),l=[];a.length>0&&(!c||H(await Et({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?H(await Et({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 ji=e=>le(`sha256`).update(e).digest(`hex`),Mi=(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 Ni(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=Bn(t.path);if(n)throw Error(`${i.name}: ${t.path}: ${n}`);let r=await e.getBlob(i.id,t.sha256);if(ji(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=m(e,i.name);await oe(t,{recursive:!0,force:!0});for(let e of a){let n=m(t,e.path);await D(p(n),{recursive:!0}),await k(n,e.bytes)}}let o=a.find(e=>e.path===K)?.bytes;return{...i,references:Ei(o)}}const Pi=(e,t,n)=>({id:e.id,version:e.version,agents:t,...n!==`latest`&&{channel:n}}),Fi=e=>Bt(e.channel)?e.channel:`latest`,Y=(e,t=process.cwd())=>e===`global`?m(W(),`global.lock.json`):m(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 Ii(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(p(e),{recursive:!0}),await k(e,JSON.stringify({version:t.version,kits:i,skills:r,public:a},null,2)+`
222
- `)}const Li=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];var Ri=class extends Error{name;folder;paths;constructor(e,t,n){super(`${G(t)} has edits that aren't in agent kit (${In(n)}). Push them with \`a-kit push ${e}\`, or pass --force to throw them away.`),this.name=e,this.folder=t,this.paths=n}};async function zi(e,t){for(let n of e){if(!l(n))continue;let{paths:e}=Mn(await jn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Bi(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?zi(r.map(e=>m(e,t)),i.files):null}async function Vi(e,t,n){return!t||t.id!==n.id||t.version===n.version?n.files:(await e.getVersion(t.id,t.version)).files}async function Hi(e,t,n,{force:r}){let i=await e.getSkill(n),{entry:a}=t,o=await zi(t.existing,await Vi(e,a,i));if(o&&!r)throw new Ri(t.name,o.folder,o.paths);let s=a?.id===n?a.version:null,c=t.folders.every(e=>l(e));if(!o&&c&&s===i.version)return{kind:`unchanged`,skill:i,from:s};let u=t.folders.map(e=>p(e)),d=await Ni(e,n,u),f=await X(t.lockFile);if(d.name!==t.name){for(let e of u)await oe(m(e,t.name),{recursive:!0,force:!0});delete f.skills[t.name]}return f.skills[d.name]={id:d.id,version:d.version,agents:t.agents.map(e=>e.id)},await Ii(t.lockFile,f),{kind:`pulled`,skill:d,from:s}}function Ui(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Li(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 Wi(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 Gi(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Ui(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=Nt();for(let i of s){let s=Li(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 Ni(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 Bi(e,o,i,r.dirsOf(i.agents));s?(I.warn(`${o} was taken out of kit/${n.name}, but it has edits that aren't in agent kit (${In(s.paths)}); left it. Push them with \`a-kit push ${o}\`, or delete its folder.`),a.kept.push(o)):(await Ki(t,o,r.dirsOf),a.removed.push(o))}return a}async function Ki(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await oe(m(e,t),{recursive:!0,force:!0});delete e.skills[t]}function qi(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const Ji=e=>qi(e)!==null;function Yi(e,t){let n=[],r=[];for(let i of t)Ji(i)&&mn(e,i).length===0?r.push(i):n.push(i);return{own:n,others:r}}async function Xi(e,t,n){let r=[];for(let i of t){let t=qi(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 Zi(e,t,n,r,i){let a=Nt();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 Ni(Mi(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 Qi(e){let[t,n]=process.platform===`darwin`?[`open`,[e]]:process.platform===`win32`?[`cmd`,[`/c`,`start`,``,e.replace(/&/g,`^&`)]]:[`xdg-open`,[e]];try{let e=pe(t,n,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}const $i=()=>m(W(),`bin`,`a-kit.mjs`);function ea(){let e=me(import.meta.url);return e.endsWith(`.mjs`)?e:null}async function ta(e){let t=$i();return await D(p(t),{recursive:!0}),e!==t&&await ne(e,t),t}async function na(e,t,n,r=b()){let i=[Y(`global`)],a=ra(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 ra(e,t){let n=e,{root:r}=h(e);for(;n&&n!==t;){let e=Y(`project`,n);if(l(e))return e;if(n===r)break;n=p(n)}return null}async function ia(){let e=m(W(),`machine.json`);try{let t=JSON.parse(await O(e,`utf8`));if(typeof t.id==`string`&&t.id)return t.id}catch{}let t=ue();return await D(p(e),{recursive:!0,mode:448}),await k(e,JSON.stringify({id:t},null,2)+`
223
- `),t}async function aa(e,t,n,r=/* @__PURE__ */ new Date){return{id:ue(),skillId:e.id,version:e.version,agent:t,machineId:await ia(),machineName:x()||null,trigger:n,occurredAt:r.toISOString()}}const oa=()=>m(W(),`pending-activations.jsonl`);async function sa(e,t){let n=`${oa()}.${process.pid}`,r=[];try{await ae(oa(),n),r=la(await O(n,`utf8`)),await oe(n,{force:!0})}catch{}let i=[...r,t].slice(-500),a=0;for(let t=0;t<i.length;t+=100){let n=i.slice(t,t+100);try{await e(n),a+=n.length}catch(e){if(!ca(e))continue;let n=i.slice(t);return await D(W(),{recursive:!0,mode:448}),await E(oa(),n.map(e=>JSON.stringify(e)).join(`
220
+ `,t);return n===-1?e.length:n}function di(e,t){return Math.min(t+1,e.length)}const fi=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,pi=/^[a-z0-9]+(-[a-z0-9]+)*$/;function mi(e,t){let n=[],r=e.slice(t);for(let e of r.matchAll(fi)){let r=e[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(r))continue;let i=vi(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 hi(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`&&pi.test(n)?n:null}function gi(e){let t=ci(e),n=t.ok?t.block.bodyFrom:0,r=[];for(let t of mi(e,n)){let e=hi(t.path);e&&r.push({...t,name:e})}return r}function _i(e){let t=ci(e),n=t.ok?t.entries.find(e=>e.key===`name`)?.value:null,r=gi(e).map(e=>e.name);return[...new Set(r)].filter(e=>e!==n)}function vi(e){try{return decodeURIComponent(e)}catch{return e}}const yi=`report-session-issue`,bi=/skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;function xi(e,t){if(e===`Skill`){let e=t?.skill;return typeof e==`string`?[Si(e)]:[]}return[...(typeof t==`string`?t:JSON.stringify(t??``)).matchAll(bi)].map(e=>e[1])}const Si=e=>e.slice(e.lastIndexOf(`:`)+1).replace(/^\//,``);function Ci(e){let t=e.events.findIndex(e=>wi(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(Ti))]}}function wi(e){return Ti(e).includes(yi)}function Ti(e){return e.type===`system`?[]:e.message.content.flatMap(t=>t.type===`tool_use`?xi(t.name,t.input):t.type===`text`&&e.type===`user`?[...t.text.matchAll(/<command-name>\/?([\w:-]+)<\/command-name>/g)].map(e=>Si(e[1])):[])}const Ei=e=>e?_i(new TextDecoder().decode(e)):[];async function Di(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=Oi(u,r,i);a.push({skill:u,by:n.name,status:d}),d===`new`&&c.push({name:u.name,organizationId:u.organizationId,references:await ki(e,u.id)})}}return{dependencies:a,missing:o}}function Oi(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=>l(m(t,e.name)))?`conflict`:`new`}async function ki(e,t){let n=(await e.getSkill(t)).files.find(e=>e.path===K);return n?Ei(await e.getBlob(t,n.sha256)):[]}async function Ai(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(`
221
+ `));let c=n&&B(),l=[];a.length>0&&(!c||V(await Dt({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?V(await Dt({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 ji=e=>le(`sha256`).update(e).digest(`hex`),Mi=(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 Ni(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=Bn(t.path);if(n)throw Error(`${i.name}: ${t.path}: ${n}`);let r=await e.getBlob(i.id,t.sha256);if(ji(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=m(e,i.name);await oe(t,{recursive:!0,force:!0});for(let e of a){let n=m(t,e.path);await D(p(n),{recursive:!0}),await k(n,e.bytes)}}let o=a.find(e=>e.path===K)?.bytes;return{...i,references:Ei(o)}}const Pi=(e,t,n)=>({id:e.id,version:e.version,agents:t,...n!==`latest`&&{channel:n}}),Fi=e=>Vt(e.channel)?e.channel:`latest`,Y=(e,t=process.cwd())=>e===`global`?m(U(),`global.lock.json`):m(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 Ii(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(p(e),{recursive:!0}),await k(e,JSON.stringify({version:t.version,kits:i,skills:r,public:a},null,2)+`
222
+ `)}const Li=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];var Ri=class extends Error{name;folder;paths;constructor(e,t,n){super(`${G(t)} has edits that aren't in agent kit (${In(n)}). Push them with \`a-kit push ${e}\`, or pass --force to throw them away.`),this.name=e,this.folder=t,this.paths=n}};async function zi(e,t){for(let n of e){if(!l(n))continue;let{paths:e}=Mn(await jn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Bi(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?zi(r.map(e=>m(e,t)),i.files):null}async function Vi(e,t,n){return!t||t.id!==n.id||t.version===n.version?n.files:(await e.getVersion(t.id,t.version)).files}async function Hi(e,t,n,{force:r}){let i=await e.getSkill(n),{entry:a}=t,o=await zi(t.existing,await Vi(e,a,i));if(o&&!r)throw new Ri(t.name,o.folder,o.paths);let s=a?.id===n?a.version:null,c=t.folders.every(e=>l(e));if(!o&&c&&s===i.version)return{kind:`unchanged`,skill:i,from:s};let u=t.folders.map(e=>p(e)),d=await Ni(e,n,u),f=await X(t.lockFile);if(d.name!==t.name){for(let e of u)await oe(m(e,t.name),{recursive:!0,force:!0});delete f.skills[t.name]}return f.skills[d.name]={id:d.id,version:d.version,agents:t.agents.map(e=>e.id)},await Ii(t.lockFile,f),{kind:`pulled`,skill:d,from:s}}function Ui(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Li(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 Wi(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 Gi(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Ui(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=Pt();for(let i of s){let s=Li(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 Ni(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 Bi(e,o,i,r.dirsOf(i.agents));s?(F.warn(`${o} was taken out of kit/${n.name}, but it has edits that aren't in agent kit (${In(s.paths)}); left it. Push them with \`a-kit push ${o}\`, or delete its folder.`),a.kept.push(o)):(await Ki(t,o,r.dirsOf),a.removed.push(o))}return a}async function Ki(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await oe(m(e,t),{recursive:!0,force:!0});delete e.skills[t]}function qi(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const Ji=e=>qi(e)!==null;function Yi(e,t){let n=[],r=[];for(let i of t)Ji(i)&&hn(e,i).length===0?r.push(i):n.push(i);return{own:n,others:r}}async function Xi(e,t,n){let r=[];for(let i of t){let t=qi(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 Zi(e,t,n,r,i){let a=Pt();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 Ni(Mi(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 Qi(e){let[t,n]=process.platform===`darwin`?[`open`,[e]]:process.platform===`win32`?[`cmd`,[`/c`,`start`,``,e.replace(/&/g,`^&`)]]:[`xdg-open`,[e]];try{let e=pe(t,n,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}const $i=()=>m(U(),`bin`,`a-kit.mjs`);function ea(){let e=me(import.meta.url);return e.endsWith(`.mjs`)?e:null}async function ta(e){let t=$i();return await D(p(t),{recursive:!0}),e!==t&&await ne(e,t),t}async function na(e,t,n,r=b()){let i=[Y(`global`)],a=ra(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 ra(e,t){let n=e,{root:r}=h(e);for(;n&&n!==t;){let e=Y(`project`,n);if(l(e))return e;if(n===r)break;n=p(n)}return null}async function ia(){let e=m(U(),`machine.json`);try{let t=JSON.parse(await O(e,`utf8`));if(typeof t.id==`string`&&t.id)return t.id}catch{}let t=ue();return await D(p(e),{recursive:!0,mode:448}),await k(e,JSON.stringify({id:t},null,2)+`
223
+ `),t}async function aa(e,t,n,r=/* @__PURE__ */ new Date){return{id:ue(),skillId:e.id,version:e.version,agent:t,machineId:await ia(),machineName:x()||null,trigger:n,occurredAt:r.toISOString()}}const oa=()=>m(U(),`pending-activations.jsonl`);async function sa(e,t){let n=`${oa()}.${process.pid}`,r=[];try{await ae(oa(),n),r=la(await O(n,`utf8`)),await oe(n,{force:!0})}catch{}let i=[...r,t].slice(-500),a=0;for(let t=0;t<i.length;t+=100){let n=i.slice(t,t+100);try{await e(n),a+=n.length}catch(e){if(!ca(e))continue;let n=i.slice(t);return await D(U(),{recursive:!0,mode:448}),await E(oa(),n.map(e=>JSON.stringify(e)).join(`
224
224
  `)+`
225
- `),{sent:a,queued:n.length}}}return{sent:a,queued:0}}const ca=e=>!(e instanceof z)||e.status===0||e.status===429||e.status>=500;function la(e){return e.split(`
226
- `).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}const ua=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function da(e){return e.match(ua)?.[0]??null}const fa={"claude-code":`claude`,codex:`codex`,"gemini-cli":`gemini`};function pa(e=b()){let t=[...(process.env.PATH??``).split(f),p(process.execPath),m(e,`.local`,`bin`),m(e,`.claude`,`local`),m(e,`.npm-global`,`bin`),m(e,`.bun`,`bin`),m(e,`.volta`,`bin`),`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`];return[...new Set(t.filter(Boolean))]}const ma=async e=>{let t=pa(),n=await ha(e,t);return n?new Promise(e=>{de(n,[`--version`],{timeout:5e3,env:{...process.env,PATH:t.join(f)}},(t,n)=>e(t?null:n))}):null};async function ha(e,t){for(let n of t){let t=m(n,e);try{return await T(t,te.X_OK),t}catch{}}return null}async function ga(e,t=ma){let n=await Promise.all(e.map(async e=>{let n=fa[e],r=n?await t(n):null;return[e,r?da(r):null]}));return Object.fromEntries(n.filter(e=>e[1]!==null))}async function _a(e,t,n){let r=await e.listOrganizations(),i;if(n)i=va(r,n);else if(r.length<=1)i=r[0]??null;else if(V())i=await ya(r,t.organizationId);else return null;return i&&await Cn({...t,organizationId:i.id}),i}function va(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 ya(e,t){let n=H(await It({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 ba=(e,t)=>new Promise(n=>{de(e,t,{timeout:15e3},(e,t,r)=>{n({ok:!e,output:`${t}${r}`.trim()})})}),xa=e=>new URL(e).host.toLowerCase().replace(/[^a-z0-9]+/g,`-`),Sa=e=>`agent-kit-heartbeat-${xa(e)}`,Ca=e=>`com.agent-kit.heartbeat.${xa(e)}`;function wa(e,t=process.platform,n=b()){if(t===`linux`){let t=m(process.env.XDG_CONFIG_HOME??m(n,`.config`),`systemd`,`user`);return[m(t,`${Sa(e)}.service`),m(t,`${Sa(e)}.timer`)]}return t===`darwin`?[m(n,`Library`,`LaunchAgents`,`${Ca(e)}.plist`)]:[]}function Ta(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 Ea(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"?>
225
+ `),{sent:a,queued:n.length}}}return{sent:a,queued:0}}const ca=e=>!(e instanceof R)||e.status===0||e.status===429||e.status>=500;function la(e){return e.split(`
226
+ `).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}const ua=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function da(e){return e.match(ua)?.[0]??null}const fa={"claude-code":`claude`,codex:`codex`,"gemini-cli":`gemini`};function pa(e=b()){let t=[...(process.env.PATH??``).split(f),p(process.execPath),m(e,`.local`,`bin`),m(e,`.claude`,`local`),m(e,`.npm-global`,`bin`),m(e,`.bun`,`bin`),m(e,`.volta`,`bin`),`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`];return[...new Set(t.filter(Boolean))]}const ma=async e=>{let t=pa(),n=await ha(e,t);return n?new Promise(e=>{de(n,[`--version`],{timeout:5e3,env:{...process.env,PATH:t.join(f)}},(t,n)=>e(t?null:n))}):null};async function ha(e,t){for(let n of t){let t=m(n,e);try{return await T(t,te.X_OK),t}catch{}}return null}async function ga(e,t=ma){let n=await Promise.all(e.map(async e=>{let n=fa[e],r=n?await t(n):null;return[e,r?da(r):null]}));return Object.fromEntries(n.filter(e=>e[1]!==null))}async function _a(e,t,n){let r=await e.listOrganizations(),i;if(n)i=va(r,n);else if(r.length<=1)i=r[0]??null;else if(B())i=await ya(r,t.organizationId);else return null;return i&&await Cn({...t,organizationId:i.id}),i}function va(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 ya(e,t){let n=V(await Lt({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 ba=(e,t)=>new Promise(n=>{de(e,t,{timeout:15e3},(e,t,r)=>{n({ok:!e,output:`${t}${r}`.trim()})})}),xa=e=>new URL(e).host.toLowerCase().replace(/[^a-z0-9]+/g,`-`),Sa=e=>`agent-kit-heartbeat-${xa(e)}`,Ca=e=>`com.agent-kit.heartbeat.${xa(e)}`;function wa(e,t=process.platform,n=b()){if(t===`linux`){let t=m(process.env.XDG_CONFIG_HOME??m(n,`.config`),`systemd`,`user`);return[m(t,`${Sa(e)}.service`),m(t,`${Sa(e)}.timer`)]}return t===`darwin`?[m(n,`Library`,`LaunchAgents`,`${Ca(e)}.plist`)]:[]}function Ta(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 Ea(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"?>
227
227
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
228
228
  <plist version="1.0">
229
229
  <dict>
230
- <key>Label</key>\n <string>${t(Ca(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 Da(e){let t=e.platform??process.platform,n=e.run??ba,r=wa(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`?Ta(e):[Ea(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(p(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`,`${Sa(e.api)}.timer`]);if(!t.ok)return await ja(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}/${Ca(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await ja(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function Oa(e,{platform:t=process.platform,home:n,run:r=ba}={}){if(!await ka(e,t,n))return!1;let i=wa(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${Sa(e)}.timer`]),await ja(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Ca(e)}`]),await ja(i)),!0}async function ka(e,t=process.platform,n){let r=wa(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Aa(e=ba,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 ja(e){for(let t of e)await oe(t,{force:!0})}async function Ma(e,t){let n=await X(Y(`global`)),r=Kt().map(e=>e.id);return{machineId:await ia(),hostname:x()||`unknown`,platform:S(),arch:y(),cliVersion:Ut,agents:r,agentVersions:await ga(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 Na=()=>m(W(),`heartbeat.json`);async function Pa(){try{return JSON.parse(await O(Na(),`utf8`))}catch{return null}}async function Fa(){try{if(Dn()||(await Tn()).heartbeat===!1)return!1;let e=await Sn();if(!e)return!1;let t={...await Ma(await ka(U())),...e.organizationId&&{organizationId:e.organizationId}},n={sentAt:(/* @__PURE__ */ new Date()).toISOString(),ok:!0};try{n.organization=(await B(U(),e.token).sendHeartbeat(t,AbortSignal.timeout(5e3))).organization}catch{n.ok=!1}return await D(W(),{recursive:!0,mode:448}),await k(Na(),JSON.stringify(n)+`
231
- `),n.ok}catch{return!1}}async function Ia(e=ea()){try{if(Dn()||(await Tn()).heartbeat===!1)return;let t=await Sn();if(!t||(t.organizationId||await _a(B(U(),t.token),t).catch(()=>null),!e))return;let n=await ka(U()),r=await ta(e);if((await Da({node:process.execPath,script:r,api:U(),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 Aa();e&&I.warn(e)}await Fa()}catch{}}const La=e=>new Promise(t=>setTimeout(t,e));async function Ra(){let e=await B(U()).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}`),Qi(e.verificationUrl);let t=Nt();t.start(`Waiting for you to approve it`);let n=B(U()),r=Date.now()+e.expiresIn*1e3;for(;Date.now()<r;){await La(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 Cn(n),t.stop(`Logged in as ${r.user.email}`),await Ia(),n}}throw t.error(`The code expired`),Error(`The login expired before it was approved. Run ${R(`login`)} again.`)}async function za(){let e=await Sn();if(!e)return null;try{let t=await B(U(),e.token).me();return{...e,user:t}}catch(e){if(e instanceof z&&e.status===401)return await Cn(null),null;throw e}}async function Z(){let e=await Sn();if(!e){if(!V())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 Ra()}return{api:B(U(),e.token),credentials:e}}const Ba=e=>`You don't have skills yet. Create or import one at ${e}/app/skills, then install it with ${R(`add`)}.`,Va=(e=b())=>m(process.env.CLAUDE_CONFIG_DIR??m(e,`.claude`),`settings.json`),Ha=(e,t)=>`node "${e}" hook claude-code --api "${t}"`,Ua=e=>typeof e.command==`string`&&e.command.includes(`a-kit.mjs`)&&e.command.includes(` hook claude-code`),Wa=[`telemetry`,`autoUpdate`],Ga={telemetry:[{event:`PostToolUse`,matcher:`Skill`},{event:`UserPromptSubmit`}],autoUpdate:[{event:`SessionStart`,matcher:`startup|resume`}]};function Ka(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=>!Ua(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 qa(e,t,n=Wa){let r=Ka(e),i={...r.hooks};for(let{event:e,matcher:r}of n.flatMap(e=>Ga[e])){let n={type:`command`,command:t,async:!0,timeout:10};i[e]=[...i[e]??[],r?{matcher:r,hooks:[n]}:{hooks:[n]}]}return Object.keys(i).length>0?{...r,hooks:i}:r}const Ja=(e,t,n)=>e.hooks?.[t]?.some(e=>e.hooks?.some(e=>Ua(e)&&(!n||e.command===n)))??!1;function Ya(e,t,n){return Ga[t].every(({event:t})=>Ja(e,t,n))}function Xa(e,t,n){return Wa.every(r=>n.includes(r)?Ya(e,r,t):Ga[r].every(({event:t})=>!Ja(e,t)))}function Za(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 Qa(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 Qa(t)?{name:t,trigger:`user`}:null}return null}const Qa=e=>/^[a-z0-9][a-z0-9-]*$/.test(e);async function $a(){let e=await Tn();return Wa.filter(t=>e[t]!==!1)}async function eo(e=ea(),t=Va(),n){let r=n??await $a(),i=await io(t);if(i===`invalid`)return{status:`skipped`,reason:`${t} isn't valid JSON`};if(r.length===0)return Wa.some(e=>Ya(i,e))?(await ao(t,Ka(i)),{status:`installed`,added:[]}):{status:`already`};if(!e)return{status:`skipped`,reason:`not running from a build`};let a=await ta(e),o=Ha(a,U());if(Xa(i,o,r))return{status:`already`};let s=r.filter(e=>!Ya(i,e));return await ao(t,qa(i,o,r)),{status:`installed`,added:s}}async function to(e=Va()){let t=await io(e);return t===`invalid`?[]:Wa.filter(e=>Ya(t,e))}const no={telemetry:"Claude Code now reports to agent kit each time it loads one of these skills, so your organization sees which ones get used. Turn it off with `a-kit telemetry off`.",autoUpdate:"Claude Code now updates the skills you installed everywhere (-g) in the background when a session starts, at most once an hour. Turn it off with `a-kit auto-update off`."};async function ro(e){if(e.includes(`claude-code`))try{let e=await eo();if(e.status===`installed`)for(let t of e.added)I.info(no[t])}catch{}await Ia()}async function io(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(p(e),{recursive:!0}),await k(e,JSON.stringify(t,null,2)+`
230
+ <key>Label</key>\n <string>${t(Ca(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 Da(e){let t=e.platform??process.platform,n=e.run??ba,r=wa(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`?Ta(e):[Ea(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(p(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`,`${Sa(e.api)}.timer`]);if(!t.ok)return await ja(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}/${Ca(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await ja(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function Oa(e,{platform:t=process.platform,home:n,run:r=ba}={}){if(!await ka(e,t,n))return!1;let i=wa(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${Sa(e)}.timer`]),await ja(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Ca(e)}`]),await ja(i)),!0}async function ka(e,t=process.platform,n){let r=wa(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Aa(e=ba,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 ja(e){for(let t of e)await oe(t,{force:!0})}async function Ma(e,t){let n=await X(Y(`global`)),r=qt().map(e=>e.id);return{machineId:await ia(),hostname:x()||`unknown`,platform:S(),arch:y(),cliVersion:Wt,agents:r,agentVersions:await ga(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 Na=()=>m(U(),`heartbeat.json`);async function Pa(){try{return JSON.parse(await O(Na(),`utf8`))}catch{return null}}async function Fa(){try{if(Dn()||(await Tn()).heartbeat===!1)return!1;let e=await W();if(!e)return!1;let t={...await Ma(await ka(H())),...e.organizationId&&{organizationId:e.organizationId}},n={sentAt:(/* @__PURE__ */ new Date()).toISOString(),ok:!0};try{n.organization=(await z(H(),e.token).sendHeartbeat(t,AbortSignal.timeout(5e3))).organization}catch{n.ok=!1}return await D(U(),{recursive:!0,mode:448}),await k(Na(),JSON.stringify(n)+`
231
+ `),n.ok}catch{return!1}}async function Ia(e=ea()){try{if(Dn()||(await Tn()).heartbeat===!1)return;let t=await W();if(!t||(t.organizationId||await _a(z(H(),t.token),t).catch(()=>null),!e))return;let n=await ka(H()),r=await ta(e);if((await Da({node:process.execPath,script:r,api:H(),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 Aa();e&&F.warn(e)}await Fa()}catch{}}const La=e=>new Promise(t=>setTimeout(t,e));async function Ra(){let e=await z(H()).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}`),Qi(e.verificationUrl);let t=Pt();t.start(`Waiting for you to approve it`);let n=z(H()),r=Date.now()+e.expiresIn*1e3;for(;Date.now()<r;){await La(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 Cn(n),t.stop(`Logged in as ${r.user.email}`),await Ia(),n}}throw t.error(`The code expired`),Error(`The login expired before it was approved. Run ${L(`login`)} again.`)}async function za(){let e=await W();if(!e)return null;try{let t=await z(H(),e.token).me();return{...e,user:t}}catch(e){if(e instanceof R&&e.status===401)return await Cn(null),null;throw e}}async function Z(){let e=await W();if(!e){if(!B())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 Ra()}return{api:z(H(),e.token),credentials:e}}const Ba=e=>`You don't have skills yet. Create or import one at ${e}/app/skills, then install it with ${L(`add`)}.`,Va=(e=b())=>m(process.env.CLAUDE_CONFIG_DIR??m(e,`.claude`),`settings.json`),Ha=(e,t)=>`node "${e}" hook claude-code --api "${t}"`,Ua=e=>typeof e.command==`string`&&e.command.includes(`a-kit.mjs`)&&e.command.includes(` hook claude-code`),Wa=[`telemetry`,`autoUpdate`],Ga={telemetry:[{event:`PostToolUse`,matcher:`Skill`},{event:`UserPromptSubmit`}],autoUpdate:[{event:`SessionStart`,matcher:`startup|resume`}]};function Ka(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=>!Ua(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 qa(e,t,n=Wa){let r=Ka(e),i={...r.hooks};for(let{event:e,matcher:r}of n.flatMap(e=>Ga[e])){let n={type:`command`,command:t,async:!0,timeout:10};i[e]=[...i[e]??[],r?{matcher:r,hooks:[n]}:{hooks:[n]}]}return Object.keys(i).length>0?{...r,hooks:i}:r}const Ja=(e,t,n)=>e.hooks?.[t]?.some(e=>e.hooks?.some(e=>Ua(e)&&(!n||e.command===n)))??!1;function Ya(e,t,n){return Ga[t].every(({event:t})=>Ja(e,t,n))}function Xa(e,t,n){return Wa.every(r=>n.includes(r)?Ya(e,r,t):Ga[r].every(({event:t})=>!Ja(e,t)))}function Za(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 Qa(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 Qa(t)?{name:t,trigger:`user`}:null}return null}const Qa=e=>/^[a-z0-9][a-z0-9-]*$/.test(e);async function $a(){let e=await Tn();return Wa.filter(t=>e[t]!==!1)}async function eo(e=ea(),t=Va(),n){let r=n??await $a(),i=await io(t);if(i===`invalid`)return{status:`skipped`,reason:`${t} isn't valid JSON`};if(r.length===0)return Wa.some(e=>Ya(i,e))?(await ao(t,Ka(i)),{status:`installed`,added:[]}):{status:`already`};if(!e)return{status:`skipped`,reason:`not running from a build`};let a=await ta(e),o=Ha(a,H());if(Xa(i,o,r))return{status:`already`};let s=r.filter(e=>!Ya(i,e));return await ao(t,qa(i,o,r)),{status:`installed`,added:s}}async function to(e=Va()){let t=await io(e);return t===`invalid`?[]:Wa.filter(e=>Ya(t,e))}const no={telemetry:"Claude Code now reports to agent kit each time it loads one of these skills, so your organization sees which ones get used. 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 eo();if(e.status===`installed`)for(let t of e.added)F.info(no[t])}catch{}await Ia()}async function io(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(p(e),{recursive:!0}),await k(e,JSON.stringify(t,null,2)+`
232
232
  `)}const oo=(e=`npx -y useakit@next`)=>`---
233
233
  name: ${yi}
234
234
  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.
@@ -269,36 +269,36 @@ Only the conversation up to the developer's request to report it is sent; this p
269
269
  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.
270
270
 
271
271
  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.
272
- `;async function so(e){for(let t of e){let e=m(t,yi);await D(e,{recursive:!0}),await k(m(e,`SKILL.md`),oo())}}const co=e=>t=>Jt(t.map(e=>qt(e)).filter(e=>e!==void 0),e);async function lo(e,t,n,r,i=`latest`,a){let o=Jt(n,r),s=Y(r),c=await X(s);await so(o);try{await uo(e,c,t,n,o,i,a)}finally{await Ii(s,c)}return await ro(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function uo(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=Nt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Ni(e,o.id,i,a);l.push(n),t.skills[n.name]=Pi(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 Ai(await Di(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await uo(e,t,u,r,i)}async function fo(e,t){jt(`agent kit`);let n=!t.yes,r=cn(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(Ji)&&await Sn()===null?null:await Z(),a=i?.api??B(U()),o=r.skills.length>0||r.kits.length===0,s=i&&o?await a.listSkills():[],{own:c,others:l}=i?Yi(s,r.skills):{own:[],others:r.skills},u=await Xi(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){L(Ba(i.credentials.webUrl));return}let f=d?await ln(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 un(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 an(t.agent,n),g=t.global?`global`:`project`,_=Jt(h,g),v=Y(g),y=await X(v);await so(_);try{await uo(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await Zi(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await Gi(a,y,e,{agents:h.map(e=>e.id),dirsOf:co(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 Ii(v,y)}await ro(h.map(e=>e.id)),L(`Installed in ${_.map(G).join(`, `)}`)}async function po(e){switch(e){case`on`:{await En({autoUpdate:!0});let e=await eo();e.status===`skipped`?I.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):I.success(`Auto-update is on: Claude Code updates your global skills when a session starts, at most once an hour.`);return}case`off`:await En({autoUpdate:!1}),await eo(),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 Tn()).autoUpdate!==!1,t=(await to()).includes(`autoUpdate`);console.log(`Auto-update is ${e?`on`:`off`}.`),console.log(`Claude Code: ${t?`updates the global skills when a session starts`:`no hook installed`}.`),console.log("\nWhen a Claude Code session starts, the skills and kits you installed everywhere (-g) update in the background, at most once an hour. 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 mo(e,t){let n,r=null,i=!1,a=!1,o=()=>{n=void 0,a||(r?i=!0:r=e().catch(()=>{}).finally(()=>{r=null,i&&!a&&(i=!1,s())}))};function s(){a||(clearTimeout(n),n=setTimeout(o,t))}return{trigger:s,async stop(){a=!0,clearTimeout(n),await r},async idle(){for(;n!==void 0||r;)await(r??new Promise(e=>setTimeout(e,t)))}}}function ho(e){return e.map(e=>{let t=qt(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${Wt.map(e=>e.id).join(`, `)}.`);return t})}async function go(e,t,n,r=Gt(t)){if(!/^[a-z0-9-]+$/.test(e))throw Error(`"${e}" isn't a skill name: use lowercase letters, numbers and hyphens.`);let i=Y(t,t===`global`?void 0:r),a=(await X(i)).skills[e],o=n.length>0?ho(n):a?a.agents.map(e=>qt(e)).filter(e=>e!==void 0):Wt.filter(n=>l(m(Jt([n],t,r)[0],e)));o.length===0&&a&&(o=ho([`claude-code`]));let s=Jt(o,t,r).map(t=>m(t,e));return{name:e,scope:t,lockFile:i,entry:a,agents:o,folders:s,existing:s.filter(e=>l(e))}}async function _o(e,t){if(e.existing.length===0)throw Error(`There's no ${e.name} folder in ${e.folders.map(e=>G(e)).join(` or `)||`your skills folders`}. Get it with \`a-kit pull ${e.name}\`.`);let n=await Promise.all(e.existing.map(async e=>({folder:e,files:await jn(e)}))),r=n[0];if(n.every(e=>Nn(e.files,r.files)))return r;let i=await t(),a=i?n.filter(e=>Mn(e.files,i).paths.length>0):n;if(a.length===1)return a[0];throw Error(`${e.name} differs between ${n.map(e=>G(e.folder)).join(` and `)}. Say which to use with --agent, like \`--agent ${e.agents[0]?.id??`claude-code`}\`.`)}function vo(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}function yo(e){return[...e].sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.from??0)-(t.from??0))}function bo(e,t){if(e.path===null)return`skill`;let n=t(e.path);return e.from!==void 0&&n!==void 0?`${e.path}:${vo(n,e.from)}`:e.path}function xo(e,t,r=!!process.stdout.isTTY&&!process.env.NO_COLOR){let i=(e,t)=>r?n(e,t):t;return yo(e).map(e=>{let n=e.severity===`error`?i(`red`,`✗`):i(`yellow`,`▲`),r=e.fix?i(`dim`,` (fix: ${e.fix.label.toLowerCase()})`):``;return`${n} ${e.message} ${i(`dim`,bo(e,t))}${r}`})}const So=(e,t)=>`${e} ${t}${e===1?``:`s`}`,Co=()=>!!process.stdout.isTTY&&!process.env.NO_COLOR,wo=(e,t)=>Co()?n(e,t):t,To=e=>console.log(`${wo(`green`,`✓`)} ${e}`),Eo=e=>console.error(`${wo(`red`,`✗`)} ${e}`),Do=e=>console.log(wo(`dim`,e)),Oo=(e,t,n)=>`${e} v${t}${n?` (renamed from ${n})`:``}`;function ko(e,t){let n=t.diagnostics.filter(e=>e.severity===`error`).length;Eo(`${e} wasn't pushed: ${So(n,`error`)}`);for(let e of xo(t.diagnostics,t.textOf,Co()))console.error(` ${e}`)}function Ao(e,t){for(let n of xo(e,t,Co()))console.log(` ${n}`)}const jo=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:`
273
- 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])),Mo=1024,No=1536,Po=[`anthropic`,`claude`],Fo=/<\/?[A-Za-z][^>]*>/;function Io(e){let t=[];e.files.length>Rn.maxFiles&&t.push(Go(`A skill can have at most ${Rn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=Bn(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>Rn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${Jo(Rn.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>Rn.maxSkillBytes&&t.push(Go(`The whole skill can be at most ${Jo(Rn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(Go(`Every skill needs a ${K} at its root.`)),t):(t.push(...Lo(e.skillMd,r,e.skills)),t)}function Lo(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=ci(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(`
272
+ `;async function so(e){for(let t of e){let e=m(t,yi);await D(e,{recursive:!0}),await k(m(e,`SKILL.md`),oo())}}const co=e=>t=>Yt(t.map(e=>Jt(e)).filter(e=>e!==void 0),e);async function lo(e,t,n,r,i=`latest`,a){let o=Yt(n,r),s=Y(r),c=await X(s);await so(o);try{await uo(e,c,t,n,o,i,a)}finally{await Ii(s,c)}return await ro(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function uo(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=Pt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Ni(e,o.id,i,a);l.push(n),t.skills[n.name]=Pi(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 Ai(await Di(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await uo(e,t,u,r,i)}async function fo(e,t){Mt(`agent kit`);let n=!t.yes,r=ln(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(Ji)&&await W()===null?null:await Z(),a=i?.api??z(H()),o=r.skills.length>0||r.kits.length===0,s=i&&o?await a.listSkills():[],{own:c,others:l}=i?Yi(s,r.skills):{own:[],others:r.skills},u=await Xi(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){I(Ba(i.credentials.webUrl));return}let f=d?await un(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 dn(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 on(t.agent,n),g=t.global?`global`:`project`,_=Yt(h,g),v=Y(g),y=await X(v);await so(_);try{await uo(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await Zi(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await Gi(a,y,e,{agents:h.map(e=>e.id),dirsOf:co(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 Ii(v,y)}await ro(h.map(e=>e.id)),I(`Installed in ${_.map(G).join(`, `)}`)}const po=()=>m(U(),`auto-update.json`);async function mo(e=Date.now(),t=6e4,n=po()){if(ho((await go(n)).startedAt,e,t))return!1;await D(p(n),{recursive:!0});let r=`${n}.claim`;try{await k(r,``,{flag:`wx`})}catch{let e=await se(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await ce(r).catch(()=>{}),!1}try{let r=await go(n);return!ho(r.startedAt,e,t)&&(await _o(n,{...r,startedAt:e}),!0)}finally{await ce(r).catch(()=>{})}}const ho=(e,t,n)=>typeof e==`number`&&t-e<n&&e<=t;async function go(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 _o(e,t){await D(p(e),{recursive:!0}),await k(e,JSON.stringify(t)+`
273
+ `)}const vo=(e,t)=>{pe(process.execPath,[e,...t],{cwd:b(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},yo=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function bo(e,t=vo,n=Date.now()){return(await Tn()).autoUpdate===!1||yo(await X(Y(`global`)))||!await W()||!await mo(n)?!1:(t(e,[`auto-update`,`run`]),!0)}const xo=e=>({skills:Object.values(e.skills).map(e=>{let t=Fi(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 So(e,t,n=po()){try{let r=await X(Y(`global`));if(yo(r))return`unchanged`;let{fingerprint:i}=await e.fingerprint(xo(r),AbortSignal.timeout(5e3));return(await go(n)).fingerprint===i?`unchanged`:(await t(),await _o(n,{...await go(n),fingerprint:i}),`updated`)}catch{return`failed`}}async function Co(e){Mt(`agent kit`);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(H(),(await W())?.token):(await Z()).api,o=co(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 so([...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}Wi(r,e,i.name);try{let e=await Gi(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 Ii(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=Fi(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 Bi(a,e,t,c);if(l)F.warn(`${e} has edits that aren't in agent kit (${In(l.paths)}); left it at v${t.version}. Push them with \`a-kit push ${e}\`, or drop them with \`a-kit pull ${e} --force\`.`),u++;else{if(await Ni(a,t.id,c,i),s.name!==e){for(let t of c)await oe(m(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Ii(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 Ni(Mi(a,i),t.ref,s),i.name!==e){for(let t of s)await oe(m(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Ii(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(To(d,c,l,u))}const wo=e=>`${e} skill${e===1?``:`s`}`;function To(e,t,n,r){let i=[e&&`updated ${wo(e)}`,t&&`installed ${wo(t)}`,n&&`removed ${wo(n)}`].filter(Boolean),a=r?`Left ${wo(r)} with local edits 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 Eo(e){switch(e){case`run`:{let e=await W();if(!e)return;await So(z(H(),e.token),()=>Co({global:!0,agent:[],yes:!0,channel:`latest`}));return}case`on`:{await En({autoUpdate:!0});let e=await eo();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 En({autoUpdate:!1}),await eo(),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 Tn()).autoUpdate!==!1,t=(await to()).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 Do(e,t){let n,r=null,i=!1,a=!1,o=()=>{n=void 0,a||(r?i=!0:r=e().catch(()=>{}).finally(()=>{r=null,i&&!a&&(i=!1,s())}))};function s(){a||(clearTimeout(n),n=setTimeout(o,t))}return{trigger:s,async stop(){a=!0,clearTimeout(n),await r},async idle(){for(;n!==void 0||r;)await(r??new Promise(e=>setTimeout(e,t)))}}}function Oo(e){return e.map(e=>{let t=Jt(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${Gt.map(e=>e.id).join(`, `)}.`);return t})}async function ko(e,t,n,r=Kt(t)){if(!/^[a-z0-9-]+$/.test(e))throw Error(`"${e}" isn't a skill name: use lowercase letters, numbers and hyphens.`);let i=Y(t,t===`global`?void 0:r),a=(await X(i)).skills[e],o=n.length>0?Oo(n):a?a.agents.map(e=>Jt(e)).filter(e=>e!==void 0):Gt.filter(n=>l(m(Yt([n],t,r)[0],e)));o.length===0&&a&&(o=Oo([`claude-code`]));let s=Yt(o,t,r).map(t=>m(t,e));return{name:e,scope:t,lockFile:i,entry:a,agents:o,folders:s,existing:s.filter(e=>l(e))}}async function Ao(e,t){if(e.existing.length===0)throw Error(`There's no ${e.name} folder in ${e.folders.map(e=>G(e)).join(` or `)||`your skills folders`}. Get it with \`a-kit pull ${e.name}\`.`);let n=await Promise.all(e.existing.map(async e=>({folder:e,files:await jn(e)}))),r=n[0];if(n.every(e=>Nn(e.files,r.files)))return r;let i=await t(),a=i?n.filter(e=>Mn(e.files,i).paths.length>0):n;if(a.length===1)return a[0];throw Error(`${e.name} differs between ${n.map(e=>G(e.folder)).join(` and `)}. Say which to use with --agent, like \`--agent ${e.agents[0]?.id??`claude-code`}\`.`)}function jo(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}function Mo(e){return[...e].sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.from??0)-(t.from??0))}function No(e,t){if(e.path===null)return`skill`;let n=t(e.path);return e.from!==void 0&&n!==void 0?`${e.path}:${jo(n,e.from)}`:e.path}function Po(e,t,r=!!process.stdout.isTTY&&!process.env.NO_COLOR){let i=(e,t)=>r?n(e,t):t;return Mo(e).map(e=>{let n=e.severity===`error`?i(`red`,`✗`):i(`yellow`,`▲`),r=e.fix?i(`dim`,` (fix: ${e.fix.label.toLowerCase()})`):``;return`${n} ${e.message} ${i(`dim`,No(e,t))}${r}`})}const Fo=(e,t)=>`${e} ${t}${e===1?``:`s`}`,Io=()=>!!process.stdout.isTTY&&!process.env.NO_COLOR,Lo=(e,t)=>Io()?n(e,t):t,Ro=e=>console.log(`${Lo(`green`,`✓`)} ${e}`),zo=e=>console.error(`${Lo(`red`,`✗`)} ${e}`),Bo=e=>console.log(Lo(`dim`,e)),Vo=(e,t,n)=>`${e} v${t}${n?` (renamed from ${n})`:``}`;function Ho(e,t){let n=t.diagnostics.filter(e=>e.severity===`error`).length;zo(`${e} wasn't pushed: ${Fo(n,`error`)}`);for(let e of Po(t.diagnostics,t.textOf,Io()))console.error(` ${e}`)}function Uo(e,t){for(let n of Po(e,t,Io()))console.log(` ${n}`)}const Wo=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:`
274
+ 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])),Go=1024,Ko=1536,qo=[`anthropic`,`claude`],Jo=/<\/?[A-Za-z][^>]*>/;function Yo(e){let t=[];e.files.length>Rn.maxFiles&&t.push(is(`A skill can have at most ${Rn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=Bn(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>Rn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${ss(Rn.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>Rn.maxSkillBytes&&t.push(is(`The whole skill can be at most ${ss(Rn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(is(`Every skill needs a ${K} at its root.`)),t):(t.push(...Xo(e.skillMd,r,e.skills)),t)}function Xo(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=ci(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(`
274
275
  `)===-1?e.length:e.indexOf(`
275
276
  `),80),{label:`Add frontmatter`,from:0,to:0,insert:`---
276
277
  name: my-skill
277
278
  description:
278
279
  ---
279
280
 
280
- `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,Wo(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
281
+ `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,rs(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
281
282
  `:`description:
282
- `});for(let e of s){let t=jo.get(e.key);if(t)Ho(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=jo.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 Bo(u.value)){let t=Vo(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`,Ro,d.keyFrom,d.keyTo);else{let n=zo(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>No&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${No}.`,...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&&qo(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),Uo(e,o.bodyFrom,t,n,i),r}const Ro=`The description is empty. Say what the skill does and when to use it.`;function zo(e){let t=e.trim();if(t===``)return{errors:[Ro],warnings:[]};let n=[],r=[];return t.length>Mo&&n.push(`The description is ${t.length} characters; the most is ${Mo}.`),Fo.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 Bo(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=Po.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function Vo(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of Po)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function Ho(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`?Ko(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`&&!qo(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 Uo(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(`
283
+ `});for(let e of s){let t=Wo.get(e.key);if(t)ts(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=Wo.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 $o(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`,Zo,d.keyFrom,d.keyTo);else{let n=Qo(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>Ko&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${Ko}.`,...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&&os(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),ns(e,o.bodyFrom,t,n,i),r}const Zo=`The description is empty. Say what the skill does and when to use it.`;function Qo(e){let t=e.trim();if(t===``)return{errors:[Zo],warnings:[]};let n=[],r=[];return t.length>Go&&n.push(`The description is ${t.length} characters; the most is ${Go}.`),Jo.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 $o(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=qo.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 qo)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function ts(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`?as(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`&&!os(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 ns(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(`
283
284
  `).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(`
284
- `));for(let{path:a,from:o,to:s}of mi(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=Un(K,a);if(e===null){let e=hi(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 Wo(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 Go(e){return{severity:`error`,path:null,message:e}}function Ko(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jo(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}var Yo=class extends Error{diagnostics;files;constructor(e,t){super(e[0]?.message??`The skill doesn't follow the format rules.`),this.diagnostics=e,this.files=t}textOf=e=>Ln(this.files,e)},Xo=class extends Error{name;local;remote;constructor(e,t,n){super(`${e} is at v${n} in agent kit, and your copy is from v${t}. Push with --force to save yours over it, or set your edits aside and get v${n} with \`a-kit pull ${e} --force\`.`),this.name=e,this.local=t,this.remote=n}};async function Zo(e,t,n){if(t.name===`report-session-issue`&&!t.entry)throw Error(`${yi} is the CLI's own skill; it comes with every install.`);let{entry:r}=t,i=n.source?{folder:n.source,files:await jn(n.source)}:await _o(t,async()=>r?(await e.getVersion(r.id,r.version)).files:null),{files:a}=i,o=Ln(a,`SKILL.md`)??null,s=o&&_i(o).length>0?new Set((await e.listSkills()).map(e=>e.name)):void 0,c=Io({files:a.map(({path:e,size:t})=>({path:e,size:t})),skillMd:o,skills:s});if(c.filter(e=>e.severity===`error`).length>0)throw new Yo(c,a);let l=c.filter(e=>e.severity===`warning`),u=await Qo(e,t,n);if(u&&r&&u.version!==r.version&&!n.force)throw new Xo(t.name,r.version,u.version);let d,f,p;try{if(!u)d=await e.createSkill(await n.organization(),{files:a.map(Pn)}),f=`created`,p=a.map(e=>e.path);else{let t=Mn(a,u.files);p=t.paths,t.paths.length===0?(d=u,f=`unchanged`):(d=await e.saveSkill(u.id,{baseVersionId:u.versionId,upserts:t.upserts.map(Pn),deletes:t.deletes}),f=`pushed`)}}catch(n){if(n instanceof z&&n.status===422)throw new Yo(n.diagnostics,a);if(n instanceof z&&n.status===409&&u){let n=await e.getSkill(u.id);throw new Xo(t.name,u.version,n.version)}throw n}let m=f===`unchanged`&&r?.id===d.id&&r.version===d.version?{folder:i.folder,renamed:!1}:await $o(t,i.folder,a,d);return{kind:f,skill:d,changed:p,folder:m.folder,renamedFrom:m.renamed?t.name:void 0,warnings:l,files:a}}async function Qo(e,t,n){if(t.entry)try{return await e.getSkill(t.entry.id)}catch(e){throw e instanceof z&&e.status===404?Error(`${t.name} isn't in your agent kit anymore. Remove it from ${d(t.lockFile)} to push it as a new skill.`):e}let r=n.org?.trim().toLowerCase(),i=(await e.listSkills()).filter(e=>e.name===t.name&&(!r||e.organizationId.toLowerCase()===r||e.organizationName.toLowerCase()===r));if(i.length===0)return null;if(i.length>1)throw Error(`More than one of your organizations has a skill named "${t.name}". Say which with --org: ${i.map(e=>e.organizationName).join(`, `)}.`);let a=i[0];if(!n.force)throw Error(`${a.organizationName} already has a skill named "${t.name}", and this folder didn't come from it. Push with --force to save your folder as its next version, or get it with \`a-kit pull ${t.name} --force\`.`);return e.getSkill(a.id)}async function $o(e,t,n,r){let i=await X(e.lockFile),a=r.name!==e.name&&/^[a-z0-9-]+$/.test(r.name)&&!e.folders.some(e=>l(m(p(e),r.name)))&&!i.skills[r.name],o=a?r.name:e.name,s=/* @__PURE__ */ new Set([...e.folders,t]),c=t;for(let e of s){let r=m(p(e),o);e===t&&(c=r),(e!==t||a)&&(await Fn(r,n),a&&await oe(e,{recursive:!0,force:!0}))}return a&&delete i.skills[e.name],i.skills[o]={id:r.id,version:r.version,agents:e.agents.map(e=>e.id)},await Ii(e.lockFile,i),{folder:c,renamed:a}}function es(e,t){let n=e.lastIndexOf(`/`);return n===-1?{name:e,org:t}:{name:e.slice(n+1),org:t??e.slice(0,n)}}async function ts(e,t){let n=t.global?`global`:`project`,{api:r}=await Z(),i=e.length===0,a=i?Object.keys((await X(Y(n))).skills):e,o=rs(r,t),s=0,c=0;for(let e of a){let{name:a,org:l}=es(e,t.org);try{let e=await go(a,n,t.agent);if(i&&e.existing.length===0)continue;let c=await Zo(r,e,{force:t.force,org:l,organization:()=>o(l)});if(c.kind===`unchanged`){i||Do(`${a} is up to date (v${c.skill.version}).`);continue}ns(c),s++}catch(e){if(c++,e instanceof Yo)ko(a,e);else if(i)Eo(`${a}: ${e instanceof Error?e.message:e}`);else throw e}}i&&s===0&&c===0&&Do(`Nothing to push.`),c>0&&(process.exitCode=1)}function ns(e){let{skill:t}=e;To(Oo(t.name,t.version,e.renamedFrom)+(e.kind===`created`?`, new in agent kit`:``)),Ao(e.warnings,t=>Ln(e.files,t))}function rs(e,t){let n;return async r=>(n??=e.listOrganizations(),(await yn(await n,r,!t.yes)).id)}async function is(e,t){if(!e)throw Error("Name the skill to watch, like `a-kit dev release`.");let n=t.global?`global`:`project`,r=es(e,t.org),{api:i}=await Z(),a=rs(i,t),o=r.name,s=await go(o,n,t.agent),{folder:c}=await _o(s,async()=>s.entry?(await i.getVersion(s.entry.id,s.entry.version)).files:null),l=``,d=!1,f,p,m=new Promise(e=>p=e),h=e=>{f?.close(),g.stop(),process.exitCode=e,p()},g=mo(async()=>{try{let e=await go(o,n,t.agent),s=await Zo(i,e,{force:t.force,source:c,org:r.org,organization:()=>a(r.org)}),u=JSON.stringify(s.warnings.map(e=>e.message)),{version:f}=s.skill;if(s.kind===`unchanged`){d&&To(`fixed, and the same as v${f}; nothing to push`),d=!1;return}d=!1,To(s.kind===`created`?`${s.skill.name} is new in agent kit → v${f}`:`${In(s.changed)} changed → v${f}`+(s.renamedFrom?` (renamed to ${s.skill.name})`:``)),u!==l&&(Ao(s.warnings,e=>Ln(s.files,e)),l=u),s.folder!==c&&(o=s.skill.name,c=s.folder,_())}catch(e){e instanceof Yo?(ko(o,e),l=``,d=!0):e instanceof Xo?(Eo(e.message),h(1)):as(e)?(Eo(`${G(c)} is gone; stopped watching.`),h(1)):e instanceof z&&e.status===401?(Eo(e.message),h(1)):(Eo(e instanceof Error?e.message:String(e)),d=!0)}},300);function _(){f?.close(),f=u(c,{recursive:!0},(e,t)=>{let n=t?.toString().split(v).join(`/`);n&&kn(n)||g.trigger()}),f.on(`error`,()=>{Eo(`Can't watch ${G(c)} anymore; stopped.`),h(1)}),console.log(`watching ${G(c)} …`)}_(),g.trigger();let y=()=>h(0);process.once(`SIGINT`,y),process.once(`SIGTERM`,y),await m,process.off(`SIGINT`,y),process.off(`SIGTERM`,y)}const as=e=>typeof e==`object`&&!!e&&e.code===`ENOENT`,os=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,ss=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function cs(e){let t=0;for(let[n]of e.matchAll(ss)){let e=n[0];if(e===`
285
- `)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)os.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 ls(e){return{always:e.description,max:e.description+e.body+e.files}}function us(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=ls(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function ds(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${ps((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${ps((e/1e6).toFixed(1))}M`}const fs=(e,t)=>`${t===`estimate`?`~`:``}${ds(e)}`,ps=e=>e.replace(/\.0$/,``),ms={high:15,medium:10,low:5},hs=5e3,gs=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function _s(e){let t=Hn(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&gs.has(n)}const vs=/^(license|licence|notice|readme|changelog)(\..*)?$/i,ys=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function bs(e,t){let n=t(`SKILL.md`)??``,r=ci(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)_s(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of js(r)){let t=Un(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Ms(r,n,t.path)&&(d.add(t.path),_s(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!vs.test(Hn(e))).filter(e=>!Hn(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(`
286
- `).length,bodyTokens:cs(c),hasExamples:Rs(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function xs(e,t,n=/* @__PURE__ */ new Date){let r=[...Os(e),...t?ks(t,n):[]];return{score:Ss(r),checks:ws(r)}}function Ss(e){let t=e.reduce((e,t)=>e+ms[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+ms[t.severity],0);return Math.round(n/t*100)}const Cs=[`high`,`medium`,`low`];function ws(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Cs.indexOf(e.severity)-Cs.indexOf(t.severity)))}const Q=(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}),Ts=/\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,Es=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Ds=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Os(e){let t=[],n=e.description??``;e.hasWhenToUse||Ts.test(n)?t.push(Q(`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(Es);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(Q(`description-specific`,`medium`,`description is specific`)),Ds.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(Q(`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(Q(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=As(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>hs?t.push($(`body-length`,`medium`,`${K} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${As(hs)}; move reference material into files ${K} links to.`)):t.push(Q(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Q(`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(Q(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${zs(e.missingFiles.length,`missing file`)}: ${Bs(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Q(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${zs(e.unusedFiles.length,`file`)} nothing mentions: ${Bs(e.unusedFiles)}`,`Mention them in ${K}, saying when to read or run them, or delete them.`))),t}function ks(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,zs(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${zs(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${zs(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(Q(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${zs(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 As(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function js(e){let t=[];for(let n of e.matchAll(ys)){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 Ms(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,Hn(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Ns(t,n);return a&&r.add(a),[...r].some(t=>Ps(e,t))}function Ns(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Ps(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 Fs=/^(```|~~~)/m,Is=/^#{1,6}[^\n]*\bexamples?\b/im,Ls=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Rs(e){return Fs.test(e)||Is.test(e)||Ls.test(e)}function zs(e,t){return`${e} ${t}${e===1?``:`s`}`}function Bs(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Vs=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Hs(e){try{return(await se(m(e,K))).isFile()}catch{return!1}}async function Us(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await ie(i,{withFileTypes:!0})){let o=m(i,a.name);if(a.isDirectory()){Vs.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=g(e,o).split(v).join(`/`),{size:c}=await se(o);t.push({path:s,size:c}),(s===`SKILL.md`||_s({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),xs(bs(t,e=>n.get(e)),null)}function Ws(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(`
287
- `)}async function Gs(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=_(t??`.`);if(await Hs(n)){let e=await Us(n),r=t===void 0?`This folder`:G(n);I.info(`${r}: checked from its files; evals aren't.`),console.log(Ws(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 Z(),i=fn(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(`${vn(a)} v${a.version}`),console.log(Ws(o))}async function Ks(e){jt(`agent kit`);let t=await za();t?I.success(`Logged in as ${t.user.email}`):t=await Ra();let n=B(U(),t.token),r=await n.listSkills();if(r.length===0){L(Ba(t.webUrl));return}let i=!e.yes;if(i&&!V())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await on(e.global,i),o=await an(e.agent,i),s=i?H(await kt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:vn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await lo(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 qs(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Fa();return;case`on`:{if(await En({heartbeat:!0}),!await Sn()){I.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!ea()){I.warn(`Run it from the published CLI to install the timer.`);return}await Ia();let e=await ka(U()),t=(await Pa())?.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 En({heartbeat:!1}),await Oa(U()),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 Tn()).heartbeat!==!1,t=await ka(U()),n=await Pa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?wa(U()).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(`
288
- 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 Js=()=>m(W(),`auto-update.json`);async function Ys(e=Date.now(),t=36e5,n=Js()){if(Xs(await Zs(n),e,t))return!1;await D(p(n),{recursive:!0});let r=`${n}.claim`;try{await k(r,``,{flag:`wx`})}catch{let e=await se(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await ce(r).catch(()=>{}),!1}try{return!Xs(await Zs(n),e,t)&&(await k(n,JSON.stringify({startedAt:e})+`
289
- `),!0)}finally{await ce(r).catch(()=>{})}}const Xs=(e,t,n)=>e!==null&&t-e<n&&e<=t;async function Zs(e){try{let{startedAt:t}=JSON.parse(await O(e,`utf8`));return typeof t==`number`?t:null}catch{return null}}const Qs=(e,t)=>{pe(process.execPath,[e,...t],{cwd:b(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()};async function $s(e,t=Qs,n=Date.now()){if((await Tn()).autoUpdate===!1)return!1;let r=await X(Y(`global`));return Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0||!await Sn()||!await Ys(n)?!1:(t(e,[`update`,`--global`]),!0)}async function ec(e,t){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let n=JSON.parse(await tc());if(n.hook_event_name===`SessionStart`){await $s(ea()??$i()),await ka(U())||await Fa();return}if(Dn()||(await Tn()).telemetry===!1)return;let r=Za(n);if(!r)return;let i=await na(r.name,e,typeof n.cwd==`string`?n.cwd:process.cwd());if(!i)return;let a=await Sn();if(!a)return;let o=B(U(),a.token);await sa(async e=>{await o.reportActivations(e,AbortSignal.timeout(5e3))},await aa(i,e,r.trigger))}catch{}}async function tc(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function nc(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?fs(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[vn(e),rc(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[ic(`project`,r,e),ic(`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=us(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}${ds(c.always)} always · ${l}${ds(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 rc(e){return[`v${e.version}`,...Rt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function ic(e,t,n){if(!t)return null;let r=Fi(t),{version:i}=Ht(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 ac(){let{api:e,credentials:t}=await Z(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(Ba(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of nc(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>oc(e).length));for(let e of r){let t=[sc(i,e)&&`in project`,sc(a,e)&&`in global`].filter(Boolean);console.log(`${oc(e).padEnd(o)} ${cc(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const oc=e=>`${sn}${vn(e)}`,sc=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function cc(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?`, …`:``}`}async function lc(e,t){switch(e){case void 0:case`status`:{let e=(await Pa())?.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 Z(),r=await _a(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${R(`org use acme`)}.`);if((await Tn()).heartbeat===!1){I.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${R(`heartbeat on`)}.`);return}await Fa()?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 uc(){jt(`agent kit`);let e=await za().catch(()=>null);if(e){let t=e.user.email;if(!V()){L(`Already logged in as ${t}.`);return}if(!H(await Et({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){L(`Still logged in as ${t}.`);return}}let t=await Ra();e&&await B(U(),e.token).logout().catch(()=>{}),L(await dc(t.token,t.webUrl))}async function dc(e,t){return(await B(U(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${Ba(t)}`:`You're in. Install your skills with ${R(`init`)}.`}async function fc(){let e=await Sn();e?(await B(U(),e.token).logout().catch(()=>{}),await Cn(null),console.log(`Logged out ${e.user.email}.`)):console.log(`You're not logged in.`)}async function pc(){let e=await za();e?console.log(e.user.email):(console.log(`You're not logged in. Run ${R(`login`)}.`),process.exitCode=1)}async function mc(e,t){jt(`agent kit propose`);let n=t.global?`global`:`project`,r=await X(Y(n)),i=Object.keys(r.skills),a=e[0]??(i.length===1?i[0]:void 0);if(!a)throw Error(i.length===0?`No skills installed ${t.global?`everywhere`:`in this project`}; there's nothing to propose a change to.`:`Which skill? Run \`a-kit propose <skill>\`. Installed here: ${i.join(`, `)}.`);let o=await go(a,n,t.agent),s=o.entry;if(!s)throw Error(`${a} isn't installed ${t.global?`everywhere (-g)`:`in this project`}.`);let{api:c,credentials:l}=await Z(),u=await c.getVersion(s.id,s.version),{folder:d,files:f}=await _o(o,async()=>u.files),p=Mn(f,u.files);if(p.paths.length===0){L(`Nothing changed in ${G(d)} since v${s.version}.`);return}let m=new Set(u.files.map(e=>e.path));I.info([`${a} in ${G(d)}, from v${s.version}:`,...p.upserts.map(e=>` ${m.has(e.path)?`~`:`+`} ${e.path}`),...p.deletes.map(e=>` - ${e}`)].join(`
290
- `));let h=t.title?.trim();if(!h){if(!V())throw Error(`Pass --title with a short title.`);h=H(await Lt({message:`What does the change do? (a short title)`,validate:e=>e?.trim()?void 0:`Give it a title.`})).trim()}let g=await c.createProposal(s.id,{title:h,description:t.note??``,baseVersionId:u.id,upserts:p.upserts.map(Pn),deletes:p.deletes});I.success(`#${g.number} "${g.title}": +${g.changes.added} −${g.changes.removed} in ${g.changes.files} file${g.changes.files===1?``:`s`}`),g.outdated&&I.warn(`agent kit has a newer version of ${a} than v${s.version}. Update the proposal on the web before it's approved.`),L(`Proposed: ${l.webUrl}/app/skills/${s.id}?tab=proposals&proposal=${g.number}`)}async function hc(e,t){if(e.length===0)throw Error("Name the skill to pull, like `a-kit pull release`. To refresh every installed skill, run `a-kit update`.");let n=t.global?`global`:`project`,r=!t.yes,{api:i}=await Z(),a,o=/* @__PURE__ */ new Set;for(let s of e){let{name:e,org:c}=es(s,t.org),l=await go(e,n,t.agent),u=l.entry?.id;if(!u){a??=await i.listSkills();let[o]=await ln(a,[c?`${c}/${e}`:e],r);u=o.id,l.existing.length===0&&t.agent.length===0&&(l=await go(e,n,(await an([],r)).map(e=>e.id)))}let d=await Hi(i,l,u,{force:t.force});for(let e of l.agents)o.add(e.id);await so([...new Set(l.folders.map(e=>p(e)))]),d.kind===`unchanged`?Do(`${d.skill.name} is up to date (v${d.skill.version}).`):To(`${d.skill.name} v${d.skill.version}`+(d.from!==null&&d.from!==d.skill.version?` (was v${d.from})`:``))}await ro([...o])}const gc={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},_c=[{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}],vc=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,yc=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,bc=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),xc=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Sc=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Cc(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(Sc(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}_])${Sc(e.find)}(?![\\p{L}\\p{N}_])`:Sc(e.find),`giu`)}));function a(e){let t=e;for(let e of _c)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(vc,e=>xc.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(yc,e=>bc.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 wc=e=>e.map(e=>JSON.stringify(e)).join(`
285
+ `));for(let{path:a,from:o,to:s}of mi(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=Un(K,a);if(e===null){let e=hi(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 rs(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 is(e){return{severity:`error`,path:null,message:e}}function as(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function os(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ss(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}var cs=class extends Error{diagnostics;files;constructor(e,t){super(e[0]?.message??`The skill doesn't follow the format rules.`),this.diagnostics=e,this.files=t}textOf=e=>Ln(this.files,e)},ls=class extends Error{name;local;remote;constructor(e,t,n){super(`${e} is at v${n} in agent kit, and your copy is from v${t}. Push with --force to save yours over it, or set your edits aside and get v${n} with \`a-kit pull ${e} --force\`.`),this.name=e,this.local=t,this.remote=n}};async function us(e,t,n){if(t.name===`report-session-issue`&&!t.entry)throw Error(`${yi} is the CLI's own skill; it comes with every install.`);let{entry:r}=t,i=n.source?{folder:n.source,files:await jn(n.source)}:await Ao(t,async()=>r?(await e.getVersion(r.id,r.version)).files:null),{files:a}=i,o=Ln(a,`SKILL.md`)??null,s=o&&_i(o).length>0?new Set((await e.listSkills()).map(e=>e.name)):void 0,c=Yo({files:a.map(({path:e,size:t})=>({path:e,size:t})),skillMd:o,skills:s});if(c.filter(e=>e.severity===`error`).length>0)throw new cs(c,a);let l=c.filter(e=>e.severity===`warning`),u=await ds(e,t,n);if(u&&r&&u.version!==r.version&&!n.force)throw new ls(t.name,r.version,u.version);let d,f,p;try{if(!u)d=await e.createSkill(await n.organization(),{files:a.map(Pn)}),f=`created`,p=a.map(e=>e.path);else{let t=Mn(a,u.files);p=t.paths,t.paths.length===0?(d=u,f=`unchanged`):(d=await e.saveSkill(u.id,{baseVersionId:u.versionId,upserts:t.upserts.map(Pn),deletes:t.deletes}),f=`pushed`)}}catch(n){if(n instanceof R&&n.status===422)throw new cs(n.diagnostics,a);if(n instanceof R&&n.status===409&&u){let n=await e.getSkill(u.id);throw new ls(t.name,u.version,n.version)}throw n}let m=f===`unchanged`&&r?.id===d.id&&r.version===d.version?{folder:i.folder,renamed:!1}:await fs(t,i.folder,a,d);return{kind:f,skill:d,changed:p,folder:m.folder,renamedFrom:m.renamed?t.name:void 0,warnings:l,files:a}}async function ds(e,t,n){if(t.entry)try{return await e.getSkill(t.entry.id)}catch(e){throw e instanceof R&&e.status===404?Error(`${t.name} isn't in your agent kit anymore. Remove it from ${d(t.lockFile)} to push it as a new skill.`):e}let r=n.org?.trim().toLowerCase(),i=(await e.listSkills()).filter(e=>e.name===t.name&&(!r||e.organizationId.toLowerCase()===r||e.organizationName.toLowerCase()===r));if(i.length===0)return null;if(i.length>1)throw Error(`More than one of your organizations has a skill named "${t.name}". Say which with --org: ${i.map(e=>e.organizationName).join(`, `)}.`);let a=i[0];if(!n.force)throw Error(`${a.organizationName} already has a skill named "${t.name}", and this folder didn't come from it. Push with --force to save your folder as its next version, or get it with \`a-kit pull ${t.name} --force\`.`);return e.getSkill(a.id)}async function fs(e,t,n,r){let i=await X(e.lockFile),a=r.name!==e.name&&/^[a-z0-9-]+$/.test(r.name)&&!e.folders.some(e=>l(m(p(e),r.name)))&&!i.skills[r.name],o=a?r.name:e.name,s=/* @__PURE__ */ new Set([...e.folders,t]),c=t;for(let e of s){let r=m(p(e),o);e===t&&(c=r),(e!==t||a)&&(await Fn(r,n),a&&await oe(e,{recursive:!0,force:!0}))}return a&&delete i.skills[e.name],i.skills[o]={id:r.id,version:r.version,agents:e.agents.map(e=>e.id)},await Ii(e.lockFile,i),{folder:c,renamed:a}}function ps(e,t){let n=e.lastIndexOf(`/`);return n===-1?{name:e,org:t}:{name:e.slice(n+1),org:t??e.slice(0,n)}}async function ms(e,t){let n=t.global?`global`:`project`,{api:r}=await Z(),i=e.length===0,a=i?Object.keys((await X(Y(n))).skills):e,o=gs(r,t),s=0,c=0;for(let e of a){let{name:a,org:l}=ps(e,t.org);try{let e=await ko(a,n,t.agent);if(i&&e.existing.length===0)continue;let c=await us(r,e,{force:t.force,org:l,organization:()=>o(l)});if(c.kind===`unchanged`){i||Bo(`${a} is up to date (v${c.skill.version}).`);continue}hs(c),s++}catch(e){if(c++,e instanceof cs)Ho(a,e);else if(i)zo(`${a}: ${e instanceof Error?e.message:e}`);else throw e}}i&&s===0&&c===0&&Bo(`Nothing to push.`),c>0&&(process.exitCode=1)}function hs(e){let{skill:t}=e;Ro(Vo(t.name,t.version,e.renamedFrom)+(e.kind===`created`?`, new in agent kit`:``)),Uo(e.warnings,t=>Ln(e.files,t))}function gs(e,t){let n;return async r=>(n??=e.listOrganizations(),(await bn(await n,r,!t.yes)).id)}async function _s(e,t){if(!e)throw Error("Name the skill to watch, like `a-kit dev release`.");let n=t.global?`global`:`project`,r=ps(e,t.org),{api:i}=await Z(),a=gs(i,t),o=r.name,s=await ko(o,n,t.agent),{folder:c}=await Ao(s,async()=>s.entry?(await i.getVersion(s.entry.id,s.entry.version)).files:null),l=``,d=!1,f,p,m=new Promise(e=>p=e),h=e=>{f?.close(),g.stop(),process.exitCode=e,p()},g=Do(async()=>{try{let e=await ko(o,n,t.agent),s=await us(i,e,{force:t.force,source:c,org:r.org,organization:()=>a(r.org)}),u=JSON.stringify(s.warnings.map(e=>e.message)),{version:f}=s.skill;if(s.kind===`unchanged`){d&&Ro(`fixed, and the same as v${f}; nothing to push`),d=!1;return}d=!1,Ro(s.kind===`created`?`${s.skill.name} is new in agent kit → v${f}`:`${In(s.changed)} changed → v${f}`+(s.renamedFrom?` (renamed to ${s.skill.name})`:``)),u!==l&&(Uo(s.warnings,e=>Ln(s.files,e)),l=u),s.folder!==c&&(o=s.skill.name,c=s.folder,_())}catch(e){e instanceof cs?(Ho(o,e),l=``,d=!0):e instanceof ls?(zo(e.message),h(1)):vs(e)?(zo(`${G(c)} is gone; stopped watching.`),h(1)):e instanceof R&&e.status===401?(zo(e.message),h(1)):(zo(e instanceof Error?e.message:String(e)),d=!0)}},300);function _(){f?.close(),f=u(c,{recursive:!0},(e,t)=>{let n=t?.toString().split(v).join(`/`);n&&kn(n)||g.trigger()}),f.on(`error`,()=>{zo(`Can't watch ${G(c)} anymore; stopped.`),h(1)}),console.log(`watching ${G(c)} …`)}_(),g.trigger();let y=()=>h(0);process.once(`SIGINT`,y),process.once(`SIGTERM`,y),await m,process.off(`SIGINT`,y),process.off(`SIGTERM`,y)}const vs=e=>typeof e==`object`&&!!e&&e.code===`ENOENT`,ys=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,bs=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function xs(e){let t=0;for(let[n]of e.matchAll(bs)){let e=n[0];if(e===`
286
+ `)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)ys.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 Ss(e){return{always:e.description,max:e.description+e.body+e.files}}function Cs(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=Ss(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function ws(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${Es((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${Es((e/1e6).toFixed(1))}M`}const Ts=(e,t)=>`${t===`estimate`?`~`:``}${ws(e)}`,Es=e=>e.replace(/\.0$/,``),Ds={high:15,medium:10,low:5},Os=5e3,ks=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function As(e){let t=Hn(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&ks.has(n)}const js=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Ms=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Ns(e,t){let n=t(`SKILL.md`)??``,r=ci(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)As(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Ws(r)){let t=Un(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Gs(r,n,t.path)&&(d.add(t.path),As(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!js.test(Hn(e))).filter(e=>!Hn(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(`
287
+ `).length,bodyTokens:xs(c),hasExamples:Zs(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Ps(e,t,n=/* @__PURE__ */ new Date){let r=[...Vs(e),...t?Hs(t,n):[]];return{score:Fs(r),checks:Ls(r)}}function Fs(e){let t=e.reduce((e,t)=>e+Ds[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+Ds[t.severity],0);return Math.round(n/t*100)}const Is=[`high`,`medium`,`low`];function Ls(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Is.indexOf(e.severity)-Is.indexOf(t.severity)))}const Q=(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}),Rs=/\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,zs=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Bs=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Vs(e){let t=[],n=e.description??``;e.hasWhenToUse||Rs.test(n)?t.push(Q(`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(zs);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(Q(`description-specific`,`medium`,`description is specific`)),Bs.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(Q(`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(Q(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Us(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>Os?t.push($(`body-length`,`medium`,`${K} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Us(Os)}; move reference material into files ${K} links to.`)):t.push(Q(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Q(`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(Q(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${Qs(e.missingFiles.length,`missing file`)}: ${$s(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Q(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${Qs(e.unusedFiles.length,`file`)} nothing mentions: ${$s(e.unusedFiles)}`,`Mention them in ${K}, saying when to read or run them, or delete them.`))),t}function Hs(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,Qs(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Qs(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${Qs(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(Q(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${Qs(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 Us(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Ws(e){let t=[];for(let n of e.matchAll(Ms)){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 Gs(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,Hn(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Ks(t,n);return a&&r.add(a),[...r].some(t=>qs(e,t))}function Ks(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function qs(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 Js=/^(```|~~~)/m,Ys=/^#{1,6}[^\n]*\bexamples?\b/im,Xs=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Zs(e){return Js.test(e)||Ys.test(e)||Xs.test(e)}function Qs(e,t){return`${e} ${t}${e===1?``:`s`}`}function $s(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const ec=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function tc(e){try{return(await se(m(e,K))).isFile()}catch{return!1}}async function nc(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await ie(i,{withFileTypes:!0})){let o=m(i,a.name);if(a.isDirectory()){ec.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=g(e,o).split(v).join(`/`),{size:c}=await se(o);t.push({path:s,size:c}),(s===`SKILL.md`||As({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Ps(Ns(t,e=>n.get(e)),null)}function rc(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(`
288
+ `)}async function ic(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=_(t??`.`);if(await tc(n)){let e=await nc(n),r=t===void 0?`This folder`:G(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(rc(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 Z(),i=pn(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(`${yn(a)} v${a.version}`),console.log(rc(o))}async function ac(e){Mt(`agent kit`);let t=await za();t?F.success(`Logged in as ${t.user.email}`):t=await Ra();let n=z(H(),t.token),r=await n.listSkills();if(r.length===0){I(Ba(t.webUrl));return}let i=!e.yes;if(i&&!B())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await sn(e.global,i),o=await on(e.agent,i),s=i?V(await At({message:`Which skills?`,options:r.map(e=>({value:e.id,label:yn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await lo(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});I(`Installed in ${c.map(G).join(`, `)}`)}async function oc(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Fa();return;case`on`:{if(await En({heartbeat:!0}),!await W()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!ea()){F.warn(`Run it from the published CLI to install the timer.`);return}await Ia();let e=await ka(H()),t=(await Pa())?.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 En({heartbeat:!1}),await Oa(H()),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 Tn()).heartbeat!==!1,t=await ka(H()),n=await Pa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?wa(H()).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(`
289
+ 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.`)}}async function sc(e,t){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let n=JSON.parse(await cc());if(n.hook_event_name===`SessionStart`){await bo(ea()??$i()),await ka(H())||await Fa();return}if(Dn()||(await Tn()).telemetry===!1)return;let r=Za(n);if(!r)return;let i=await na(r.name,e,typeof n.cwd==`string`?n.cwd:process.cwd());if(!i)return;let a=await W();if(!a)return;let o=z(H(),a.token);await sa(async e=>{await o.reportActivations(e,AbortSignal.timeout(5e3))},await aa(i,e,r.trigger))}catch{}}async function cc(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function lc(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?Ts(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[yn(e),uc(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[dc(`project`,r,e),dc(`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=Cs(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}${ws(c.always)} always · ${l}${ws(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 uc(e){return[`v${e.version}`,...zt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function dc(e,t,n){if(!t)return null;let r=Fi(t),{version:i}=Ut(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 fc(){let{api:e,credentials:t}=await Z(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(Ba(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of lc(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>pc(e).length));for(let e of r){let t=[mc(i,e)&&`in project`,mc(a,e)&&`in global`].filter(Boolean);console.log(`${pc(e).padEnd(o)} ${hc(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const pc=e=>`${cn}${yn(e)}`,mc=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function hc(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?`, …`:``}`}async function gc(e,t){switch(e){case void 0:case`status`:{let e=(await Pa())?.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 Z(),r=await _a(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await Tn()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Fa()?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 _c(){Mt(`agent kit`);let e=await za().catch(()=>null);if(e){let t=e.user.email;if(!B()){I(`Already logged in as ${t}.`);return}if(!V(await Dt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Ra();e&&await z(H(),e.token).logout().catch(()=>{}),I(await vc(t.token,t.webUrl))}async function vc(e,t){return(await z(H(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${Ba(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function yc(){let e=await W();e?(await z(H(),e.token).logout().catch(()=>{}),await Cn(null),console.log(`Logged out ${e.user.email}.`)):console.log(`You're not logged in.`)}async function bc(){let e=await za();e?console.log(e.user.email):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}async function xc(e,t){Mt(`agent kit propose`);let n=t.global?`global`:`project`,r=await X(Y(n)),i=Object.keys(r.skills),a=e[0]??(i.length===1?i[0]:void 0);if(!a)throw Error(i.length===0?`No skills installed ${t.global?`everywhere`:`in this project`}; there's nothing to propose a change to.`:`Which skill? Run \`a-kit propose <skill>\`. Installed here: ${i.join(`, `)}.`);let o=await ko(a,n,t.agent),s=o.entry;if(!s)throw Error(`${a} isn't installed ${t.global?`everywhere (-g)`:`in this project`}.`);let{api:c,credentials:l}=await Z(),u=await c.getVersion(s.id,s.version),{folder:d,files:f}=await Ao(o,async()=>u.files),p=Mn(f,u.files);if(p.paths.length===0){I(`Nothing changed in ${G(d)} since v${s.version}.`);return}let m=new Set(u.files.map(e=>e.path));F.info([`${a} in ${G(d)}, from v${s.version}:`,...p.upserts.map(e=>` ${m.has(e.path)?`~`:`+`} ${e.path}`),...p.deletes.map(e=>` - ${e}`)].join(`
290
+ `));let h=t.title?.trim();if(!h){if(!B())throw Error(`Pass --title with a short title.`);h=V(await Rt({message:`What does the change do? (a short title)`,validate:e=>e?.trim()?void 0:`Give it a title.`})).trim()}let g=await c.createProposal(s.id,{title:h,description:t.note??``,baseVersionId:u.id,upserts:p.upserts.map(Pn),deletes:p.deletes});F.success(`#${g.number} "${g.title}": +${g.changes.added} −${g.changes.removed} in ${g.changes.files} file${g.changes.files===1?``:`s`}`),g.outdated&&F.warn(`agent kit has a newer version of ${a} than v${s.version}. Update the proposal on the web before it's approved.`),I(`Proposed: ${l.webUrl}/app/skills/${s.id}?tab=proposals&proposal=${g.number}`)}async function Sc(e,t){if(e.length===0)throw Error("Name the skill to pull, like `a-kit pull release`. To refresh every installed skill, run `a-kit update`.");let n=t.global?`global`:`project`,r=!t.yes,{api:i}=await Z(),a,o=/* @__PURE__ */ new Set;for(let s of e){let{name:e,org:c}=ps(s,t.org),l=await ko(e,n,t.agent),u=l.entry?.id;if(!u){a??=await i.listSkills();let[o]=await un(a,[c?`${c}/${e}`:e],r);u=o.id,l.existing.length===0&&t.agent.length===0&&(l=await ko(e,n,(await on([],r)).map(e=>e.id)))}let d=await Hi(i,l,u,{force:t.force});for(let e of l.agents)o.add(e.id);await so([...new Set(l.folders.map(e=>p(e)))]),d.kind===`unchanged`?Bo(`${d.skill.name} is up to date (v${d.skill.version}).`):Ro(`${d.skill.name} v${d.skill.version}`+(d.from!==null&&d.from!==d.skill.version?` (was v${d.from})`:``))}await ro([...o])}const Cc={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},wc=[{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}],Tc=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Ec=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Dc=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Oc=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,kc=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Ac(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(kc(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}_])${kc(e.find)}(?![\\p{L}\\p{N}_])`:kc(e.find),`giu`)}));function a(e){let t=e;for(let e of wc)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(Tc,e=>Oc.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Ec,e=>Dc.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 jc=e=>e.map(e=>JSON.stringify(e)).join(`
291
291
  `)+`
292
- `;function Tc(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
293
- `)){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=Ec(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(Ti))]}}function Ec(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:Dc(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function Dc(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(`
294
- `):``}const Oc=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function kc(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(`
295
- `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=jc(o.cli_version)??r,i=jc(o.cwd)??i;else if(e.type===`turn_context`)n=jc(o.model)??n,i=jc(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=Mc(o.content);if(!t.trim()||e===`user`&&Oc.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`?Nc(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:Pc(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(Ti))]}}function Ac(e){try{let t=JSON.parse(e);return t.type===`session_meta`?jc(t.payload?.cwd):null}catch{return null}}const jc=e=>typeof e==`string`&&e?e:null;function Mc(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
296
- `):``}function Nc(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function Pc(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 Mc(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return Pc(t)}return JSON.stringify(e??``)}const Fc=()=>process.env.CLAUDE_CONFIG_DIR??m(b(),`.claude`),Ic=()=>process.env.CODEX_HOME??m(b(),`.codex`),Lc=(e,t=Fc())=>m(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function Rc(e,t,n=process.cwd()){if(t&&l(t))return _(t);let r=e===`claude-code`?await Vc(t,n):await Hc(t,n);if(r)return r.file;throw Error(t?`No ${Bc(e)} session "${t}" on this machine.`:`No ${Bc(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function zc(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([Vc(void 0,e),Hc(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 Bc=e=>e===`claude-code`?`Claude Code`:`Codex`;async function Vc(e,t){if(e){let t=m(Fc(),`projects`),n=await qc(t);for(let r of n){let n=m(t,r,`${e}.jsonl`);if(l(n))return{file:n,mtime:0}}return null}for(let e of Jc(t)){let t=Lc(e),n=(await qc(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Kc(n.map(e=>m(t,e)))}return null}async function Hc(e,t){let n=m(Ic(),`sessions`),r=[],i=0;outer:for(let e of Uc(await qc(n)))for(let t of Uc(await qc(m(n,e))))for(let a of Uc(await qc(m(n,e,t)))){let o=m(n,e,t,a);for(let e of await qc(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(m(o,e));if(r.length>=300||++i>=14)break outer}return Wc(r,e,t)}const Uc=e=>e.sort().reverse();async function Wc(e,t,n){if(t){let n=e.find(e=>d(e).includes(t));return n?{file:n,mtime:0}:null}let r=Jc(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Gc(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 Kc(t)}return null}async function Gc(e){let t=await re(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(`
297
- `);return Ac(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Kc(e){let t=null;for(let n of e){let{mtimeMs:e}=await se(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function qc(e){try{return await ie(e)}catch{return[]}}function Jc(e){let t=[_(e)];for(;p(t.at(-1))!==t.at(-1);)t.push(p(t.at(-1)));return t}const Yc=2e3;function Xc(e){let t=[...e.map],n=$c(()=>w().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=$c(()=>x());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=Zc();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=$c(()=>fe(`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:b(),as:`~`}],maxToolText:e.fullOutputs?null:Yc}}function Zc(){return $c(()=>fe(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function Qc(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 $c(e){try{return e()}catch{return null}}function el(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))nl(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(yi),[...i.values()]}const tl=[`codex`,`cursor`,`gemini-cli`],nl=(e,t)=>e.length===0||e.includes(t)||tl.includes(t)&&e.some(e=>tl.includes(e));async function rl(e){jt(`agent kit report`);let t=await il(e.agent[0]),n=await Rc(t,e.session||void 0),r=await O(n,`utf8`),i=Ci(t===`claude-code`?Tc(r):kc(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Cc(Xc({map:e.map?Qc(await al(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(sl(e.title,`--title`,`a short title`)),s=a.text(sl(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=wc(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=el(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=m(C(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),I.info([`${Bc(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${ll(d)}`,`Taken out: ${ul(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
298
- `)),Buffer.byteLength(l)>gc.maxTranscriptBytes)throw Error(`The transcript is over ${gc.maxTranscriptBytes/1024/1024} MB.${e.fullOutputs?` Leave out --full-outputs.`:``}`);if(e.dryRun){L(`Nothing was sent. Check the file above, then run it again without --dry-run.`);return}if(!e.yes){if(!V())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!H(await Et({message:`Send this report to agent kit?`}))){L(`Not sent.`);return}}let{api:h,credentials:g}=await Z(),[_,v]=await Promise.all([h.listOrganizations(),h.listSkills()]),y=cl(e.org,_,v,d),b=await h.createReport(y.id,f);L(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function il(e){if(e===void 0)return zc();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 al=e=>e===`-`?ol():O(e,`utf8`);async function ol(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function sl(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function cl(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 ll(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function ul(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${Yc} characters`:`${e} ×${t}`).join(`, `)}function dl(e){return e&&e.total>0?e.passed/e.total:null}async function fl(e){let{api:t,credentials:n}=await Z(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(pl(r,n.webUrl,i.length>1))}function pl({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=>vn({...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=dl(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(`
299
- `)}async function ml(e){switch(e){case`on`:{await En({telemetry:!0});let e=await eo();e.status===`skipped`?I.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):I.success(`Telemetry is on: Claude Code reports the skills it loads.`);return}case`off`:await En({telemetry:!1}),await eo(),I.success("Telemetry is off: Claude Code doesn't report the skills it loads. Turn it back on with `a-kit telemetry on`.");return;case void 0:case`status`:{let e=await Tn(),t=(await to()).includes(`telemetry`),n=e.telemetry===!1?`off`:Dn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports the skills it loads`:`no hook installed`}.`),console.log(`
292
+ `;function Mc(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
293
+ `)){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=Nc(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(Ti))]}}function Nc(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:Pc(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function Pc(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(`
294
+ `):``}const Fc=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function Ic(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(`
295
+ `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=Rc(o.cli_version)??r,i=Rc(o.cwd)??i;else if(e.type===`turn_context`)n=Rc(o.model)??n,i=Rc(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=zc(o.content);if(!t.trim()||e===`user`&&Fc.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`?Bc(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:Vc(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(Ti))]}}function Lc(e){try{let t=JSON.parse(e);return t.type===`session_meta`?Rc(t.payload?.cwd):null}catch{return null}}const Rc=e=>typeof e==`string`&&e?e:null;function zc(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
296
+ `):``}function Bc(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function Vc(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 zc(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return Vc(t)}return JSON.stringify(e??``)}const Hc=()=>process.env.CLAUDE_CONFIG_DIR??m(b(),`.claude`),Uc=()=>process.env.CODEX_HOME??m(b(),`.codex`),Wc=(e,t=Hc())=>m(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function Gc(e,t,n=process.cwd()){if(t&&l(t))return _(t);let r=e===`claude-code`?await Jc(t,n):await Yc(t,n);if(r)return r.file;throw Error(t?`No ${qc(e)} session "${t}" on this machine.`:`No ${qc(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function Kc(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([Jc(void 0,e),Yc(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 qc=e=>e===`claude-code`?`Claude Code`:`Codex`;async function Jc(e,t){if(e){let t=m(Hc(),`projects`),n=await el(t);for(let r of n){let n=m(t,r,`${e}.jsonl`);if(l(n))return{file:n,mtime:0}}return null}for(let e of tl(t)){let t=Wc(e),n=(await el(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return $c(n.map(e=>m(t,e)))}return null}async function Yc(e,t){let n=m(Uc(),`sessions`),r=[],i=0;outer:for(let e of Xc(await el(n)))for(let t of Xc(await el(m(n,e))))for(let a of Xc(await el(m(n,e,t)))){let o=m(n,e,t,a);for(let e of await el(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(m(o,e));if(r.length>=300||++i>=14)break outer}return Zc(r,e,t)}const Xc=e=>e.sort().reverse();async function Zc(e,t,n){if(t){let n=e.find(e=>d(e).includes(t));return n?{file:n,mtime:0}:null}let r=tl(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Qc(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 $c(t)}return null}async function Qc(e){let t=await re(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(`
297
+ `);return Lc(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function $c(e){let t=null;for(let n of e){let{mtimeMs:e}=await se(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function el(e){try{return await ie(e)}catch{return[]}}function tl(e){let t=[_(e)];for(;p(t.at(-1))!==t.at(-1);)t.push(p(t.at(-1)));return t}const nl=2e3;function rl(e){let t=[...e.map],n=ol(()=>w().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=ol(()=>x());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=il();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=ol(()=>fe(`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:b(),as:`~`}],maxToolText:e.fullOutputs?null:nl}}function il(){return ol(()=>fe(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function al(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 ol(e){try{return e()}catch{return null}}function sl(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))ll(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(yi),[...i.values()]}const cl=[`codex`,`cursor`,`gemini-cli`],ll=(e,t)=>e.length===0||e.includes(t)||cl.includes(t)&&e.some(e=>cl.includes(e));async function ul(e){Mt(`agent kit report`);let t=await dl(e.agent[0]),n=await Gc(t,e.session||void 0),r=await O(n,`utf8`),i=Ci(t===`claude-code`?Mc(r):Ic(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Ac(rl({map:e.map?al(await fl(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(ml(e.title,`--title`,`a short title`)),s=a.text(ml(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=jc(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=sl(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=m(C(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${qc(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${gl(d)}`,`Taken out: ${_l(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
298
+ `)),Buffer.byteLength(l)>Cc.maxTranscriptBytes)throw Error(`The transcript is over ${Cc.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(!B())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!V(await Dt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:h,credentials:g}=await Z(),[_,v]=await Promise.all([h.listOrganizations(),h.listSkills()]),y=hl(e.org,_,v,d),b=await h.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function dl(e){if(e===void 0)return Kc();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 fl=e=>e===`-`?pl():O(e,`utf8`);async function pl(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function ml(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function hl(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 gl(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function _l(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${nl} characters`:`${e} ×${t}`).join(`, `)}function vl(e){return e&&e.total>0?e.passed/e.total:null}async function yl(e){let{api:t,credentials:n}=await Z(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(bl(r,n.webUrl,i.length>1))}function bl({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=>yn({...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=vl(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(`
299
+ `)}async function xl(e){switch(e){case`on`:{await En({telemetry:!0});let e=await eo();e.status===`skipped`?F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):F.success(`Telemetry is on: Claude Code reports the skills it loads.`);return}case`off`:await En({telemetry:!1}),await eo(),F.success("Telemetry is off: Claude Code doesn't report the skills it loads. Turn it back on with `a-kit telemetry on`.");return;case void 0:case`status`:{let e=await Tn(),t=(await to()).includes(`telemetry`),n=e.telemetry===!1?`off`:Dn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports the skills it loads`:`no hook installed`}.`),console.log(`
300
300
  When an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, this machine and when, so your organization sees which skills get used.
301
- Turn it off with \`a-kit telemetry off\`.`);return}default:throw Error(`Unknown telemetry action "${e}". Use on, off or status.`)}}async function hl(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 bl();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=yl(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Z(),c=fn(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)=>gl(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;vl(await d(!0,e=>{m||u(`With ${vn(l)} v${a??l.version}`),m=!0,_l(e,l.name)})),u(`Without`);let h=await p;for(let e of f)_l(e,l.name);vl(h)}async function gl(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 _l(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 vl(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=en(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${Qt(e.usage)}`)}function yl(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 bl(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}async function xl(e){jt(`agent kit`);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(U(),(await Sn())?.token):(await Z()).api,o=co(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 so([...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}Wi(r,e,i.name);try{let e=await Gi(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 Ii(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=Fi(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 Bi(a,e,t,c);if(l)I.warn(`${e} has edits that aren't in agent kit (${In(l.paths)}); left it at v${t.version}. Push them with \`a-kit push ${e}\`, or drop them with \`a-kit pull ${e} --force\`.`),u++;else{if(await Ni(a,t.id,c,i),s.name!==e){for(let t of c)await oe(m(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Ii(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 Ni(Mi(a,i),t.ref,s),i.name!==e){for(let t of s)await oe(m(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Ii(n,r),I.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))]),L(Cl(d,c,l,u))}const Sl=e=>`${e} skill${e===1?``:`s`}`;function Cl(e,t,n,r){let i=[e&&`updated ${Sl(e)}`,t&&`installed ${Sl(t)}`,n&&`removed ${Sl(n)}`].filter(Boolean),a=r?`Left ${Sl(r)} with local edits 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}`}`}const wl=`a-kit ${Ut}: your agent kit skills, in your agents.
301
+ Turn it off with \`a-kit telemetry off\`.`);return}default:throw Error(`Unknown telemetry action "${e}". Use on, off or status.`)}}async function Sl(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 Dl();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=El(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Z(),c=pn(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)=>Cl(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;Tl(await d(!0,e=>{m||u(`With ${yn(l)} v${a??l.version}`),m=!0,wl(e,l.name)})),u(`Without`);let h=await p;for(let e of f)wl(e,l.name);Tl(h)}async function Cl(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 wl(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 Tl(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=tn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${$t(e.usage)}`)}function El(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 Dl(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Ol=`a-kit ${Wt}: your agent kit skills, in your agents.
302
302
 
303
303
  Usage
304
304
  a-kit init Log in and pick skills to install
@@ -321,7 +321,7 @@ Usage
321
321
  a-kit whoami Who you're logged in as
322
322
  a-kit telemetry [on|off] Whether your agents report the skills they load
323
323
  a-kit auto-update [on|off] Whether Claude Code updates your global skills
324
- when a session starts (at most once an hour)
324
+ when a session starts and they changed
325
325
  a-kit heartbeat [on|off] Whether this machine reports to your Machines page
326
326
  every 5 minutes (a systemd or launchd timer)
327
327
  a-kit org [use [name]] The organization whose Machines page shows this
@@ -329,8 +329,8 @@ Usage
329
329
 
330
330
  Options
331
331
  -g, --global Install in your home folder instead of this project
332
- -a, --agent <id> Install for this agent (repeatable): ${Wt.map(e=>e.id).join(`, `)}
333
- --channel <channel> Install a release channel: ${zt.join(`, `)} (default latest);
332
+ -a, --agent <id> Install for this agent (repeatable): ${Gt.map(e=>e.id).join(`, `)}
333
+ --channel <channel> Install a release channel: ${Bt.join(`, `)} (default latest);
334
334
  \`a-kit update\` keeps following it
335
335
  -y, --yes Don't ask; use the defaults
336
336
  -h, --help Show this help
@@ -359,4 +359,4 @@ Report options (the report-session-issue skill passes them for you)
359
359
  --org <id|name> The organization, when it can't tell
360
360
  --full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
361
361
  --dry-run Scrub and show what would be sent, without sending
362
- `;let Tl;async function El(){let{values:e,positionals:n}=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`},force:{type:`boolean`,short:`f`,default:!1},api:{type:`string`}}});if(e.version)return console.log(Ut);let[r,...i]=n;if(Tl=r,e.help||!r)return console.log(wl);if(!Vt(e.channel))throw Error(`Unknown channel "${e.channel}". Use one of: ${zt.join(`, `)}.`);let a={global:e.global,agent:e.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:e.yes,channel:e.channel},o={...a,force:e.force,org:e.org};switch(r){case`init`:return Ks(a);case`add`:case`install`:return fo(i,a);case`update`:return xl(a);case`list`:case`ls`:return ac();case`pull`:return hc(i,o);case`push`:return ts(i,o);case`dev`:if(i.length>1)throw Error("`a-kit dev` watches one skill.");return is(i[0],o);case`search`:if(i.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return fl(i);case`health`:return Gs(i);case`login`:return uc();case`logout`:return fc();case`whoami`:return pc();case`try`:return hl(i,{model:e.model,skillVersion:e[`skill-version`]});case`propose`:return mc(i,{...a,title:e.title,note:e.note});case`report`:return rl({...a,session:e.session,title:e.title,note:e.note,expected:e.expected,map:e.map,org:e.org,fullOutputs:e[`full-outputs`],dryRun:e[`dry-run`]});case`telemetry`:return ml(i[0]);case`auto-update`:return po(i[0]);case`heartbeat`:return qs(i[0],e.api);case`org`:return lc(i[0],i.slice(1).join(` `)||e.org);case`hook`:return ec(i[0],e.api);default:throw Error(`Unknown command "${r}". Run \`a-kit --help\`.`)}}const Dl=/* @__PURE__ */ new Set([`pull`,`push`,`dev`]);El().catch(e=>{let t=e instanceof Error?e.message:String(e);Tl&&Dl.has(Tl)?Eo(t):I.error(t),process.exitCode=1});export{};
362
+ `;let kl;async function Al(){let{values:e,positionals:n}=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`},force:{type:`boolean`,short:`f`,default:!1},api:{type:`string`}}});if(e.version)return console.log(Wt);let[r,...i]=n;if(kl=r,e.help||!r)return console.log(Ol);if(!Ht(e.channel))throw Error(`Unknown channel "${e.channel}". Use one of: ${Bt.join(`, `)}.`);let a={global:e.global,agent:e.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:e.yes,channel:e.channel},o={...a,force:e.force,org:e.org};switch(r){case`init`:return ac(a);case`add`:case`install`:return fo(i,a);case`update`:return Co(a);case`list`:case`ls`:return fc();case`pull`:return Sc(i,o);case`push`:return ms(i,o);case`dev`:if(i.length>1)throw Error("`a-kit dev` watches one skill.");return _s(i[0],o);case`search`:if(i.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return yl(i);case`health`:return ic(i);case`login`:return _c();case`logout`:return yc();case`whoami`:return bc();case`try`:return Sl(i,{model:e.model,skillVersion:e[`skill-version`]});case`propose`:return xc(i,{...a,title:e.title,note:e.note});case`report`:return ul({...a,session:e.session,title:e.title,note:e.note,expected:e.expected,map:e.map,org:e.org,fullOutputs:e[`full-outputs`],dryRun:e[`dry-run`]});case`telemetry`:return xl(i[0]);case`auto-update`:return Eo(i[0]);case`heartbeat`:return oc(i[0],e.api);case`org`:return gc(i[0],i.slice(1).join(` `)||e.org);case`hook`:return sc(i[0],e.api);default:throw Error(`Unknown command "${r}". Run \`a-kit --help\`.`)}}const jl=/* @__PURE__ */ new Set([`pull`,`push`,`dev`]);Al().catch(e=>{let t=e instanceof Error?e.message:String(e);kl&&jl.has(kl)?zo(t):F.error(t),process.exitCode=1});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "useakit",
3
- "version": "0.2.0-dev.42",
3
+ "version": "0.2.0-dev.44",
4
4
  "description": "Install your agent kit skills into Claude Code, Codex, Cursor and Gemini CLI.",
5
5
  "keywords": [
6
6
  "agent-kit",