useakit 0.2.0-dev.75 → 0.2.0-dev.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +28 -27
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -72,7 +72,7 @@ ${r(`gray`,P)}`:``}`}default:{let a=i?`${r(`cyan`,P)} `:``,o=c.split(`
72
72
  ${a}`)}
73
73
  ${l}
74
74
  `}}}}).prompt()};`${r(`gray`,P)}`;const Yt=[`stable`,`beta`],Xt=[`latest`,...Yt],Zt=e=>Yt.includes(e),Qt=e=>Xt.includes(e);function $t(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 en=`0.2.0`;const tn=[{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`}],nn=e=>e===`global`?x():process.cwd();function rn(e=x()){return tn.filter(t=>u(h(e,t.marker)))}function an(e){return tn.find(t=>t.id===e)}function on(e,t,n=nn(t)){let r=e.map(e=>v(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const sn={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 cn(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}sn.maxPromptBytes;function ln(e){return e<1e3?String(e):e<1e6?`${dn(e/1e3)}k`:`${dn(e/1e6)}M`}const un=e=>`${ln(e.inputTokens+e.outputTokens)} tok · ${cn(e.costUsd)}`,dn=e=>e>=100?Math.round(e):Number(e.toFixed(1));function fn(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 pn(e){let t=e.split(`
75
- `),n=t.pop()??``,r=[];for(let e of t)if(e.trim()!==``)try{r.push(JSON.parse(e))}catch{r.push({type:`error`,message:`The answer came back garbled.`})}return{events:r,rest:n}}function mn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?en.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${mn()} ${e}\``;var R=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function z(e,t,n=fetch){async function r(r,i={}){let a;try{a=await n(`${e}${r}`,{...i,headers:{"User-Agent":`a-kit/${en}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new R(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new R(401,`UNAUTHORIZED`,`You're not logged in. Run ${L(`login`)}.`):new R(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),listProjects:(e,t)=>i(`/orgs/${e}/projects`,{signal:t}),getRepository:e=>i(`/orgs/${e}/repository`),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),search:e=>i(`/search?q=${encodeURIComponent(e)}`),getSkill:(e,t=`latest`)=>i(`/skills/${e}${t===`latest`?``:`?channel=${t}`}`),getVersion:(e,t)=>i(`/skills/${e}/versions/${t}`),getSkillHealth:e=>i(`/skills/${e}/health`),createReport:(e,t)=>i(`/orgs/${e}/reports`,{method:`POST`,body:JSON.stringify(t)}),playground:async(e,t,n)=>{let i=await r(`/skills/${e}/playground`,{method:`POST`,body:JSON.stringify(t)}),a=``,o=new TextDecoder;for await(let e of i.body??[]){let t=pn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}pn(`${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/${hn(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${hn(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${hn(e)}/installs`,{method:`POST`})}}const hn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),gn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function _n(e){return tt(e)&&(Vt(`Cancelled.`),process.exit(130)),e}async function vn(e,t){if(e.length>0)return e.map(e=>{let t=an(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${tn.map(e=>e.id).join(`, `)}.`);return t});let n=rn(),r=n.length>0?n:[an(`claude-code`)];return!t||!gn()?r:_n(await Bt({message:`Which agents should get the skills?`,options:tn.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=>an(e))}async function yn(e,t){return e?`global`:!t||!gn()?`project`:_n(await Jt({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 bn=`kit/`;function xn(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 Sn(e,t,n){if(t.length>0)return wn(e,t,n,`skill`);if(!n||!gn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=_n(await Bt({message:`Which skills?`,options:e.map(e=>({value:e.id,label:jn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const Cn=(e,t,n)=>wn(e,t,n,`kit`);async function wn(e,t,n,r){let i=[];for(let a of t){let t=On(e,a,r),o=t.length===1?t[0]:await kn(t,n,r);i.includes(o)||i.push(o)}return i}const Tn=(e,t)=>On(e,t,`skill`);function En(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 Dn=(e,t)=>En(e,t);function On(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=En(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 kn(e,t,n){let r=e[0].name,i=n===`kit`?bn:``;if(!t||!gn()){let t=e.map(e=>{let t=i+An(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=_n(await Jt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:An(e)}))}));return e.find(e=>e.id===a)}const An=e=>`${e.organizationName}/${e.name}`,jn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function B(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function Mn(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function V(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?h(process.env.APPDATA,`agent-kit`):h(process.env.XDG_CONFIG_HOME??h(x(),`.config`),`agent-kit`)}const Nn=()=>h(V(),`credentials.json`);async function Pn(){try{return JSON.parse(await O(Nn(),`utf8`))}catch{return{}}}async function H(){return(await Pn())[B()]??null}async function Fn(e){let t=await Pn();e?t[B()]=e:delete t[B()];let n=Nn();await D(m(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
75
+ `),n=t.pop()??``,r=[];for(let e of t)if(e.trim()!==``)try{r.push(JSON.parse(e))}catch{r.push({type:`error`,message:`The answer came back garbled.`})}return{events:r,rest:n}}function mn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?en.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${mn()} ${e}\``;var R=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function z(e,t,n=fetch){async function r(r,i={}){let a;try{a=await n(`${e}${r}`,{...i,headers:{"User-Agent":`a-kit/${en}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new R(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new R(401,`UNAUTHORIZED`,`You're not logged in. Run ${L(`login`)}.`):new R(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),listProjects:(e,t)=>i(`/orgs/${e}/projects`,{signal:t}),listRoles:(e,t)=>i(`/orgs/${e}/roles`,{signal:t}),getRepository:e=>i(`/orgs/${e}/repository`),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),search:e=>i(`/search?q=${encodeURIComponent(e)}`),getSkill:(e,t=`latest`)=>i(`/skills/${e}${t===`latest`?``:`?channel=${t}`}`),getVersion:(e,t)=>i(`/skills/${e}/versions/${t}`),getSkillHealth:e=>i(`/skills/${e}/health`),createReport:(e,t)=>i(`/orgs/${e}/reports`,{method:`POST`,body:JSON.stringify(t)}),playground:async(e,t,n)=>{let i=await r(`/skills/${e}/playground`,{method:`POST`,body:JSON.stringify(t)}),a=``,o=new TextDecoder;for await(let e of i.body??[]){let t=pn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}pn(`${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/${hn(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${hn(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${hn(e)}/installs`,{method:`POST`})}}const hn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),gn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function _n(e){return tt(e)&&(Vt(`Cancelled.`),process.exit(130)),e}async function vn(e,t){if(e.length>0)return e.map(e=>{let t=an(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${tn.map(e=>e.id).join(`, `)}.`);return t});let n=rn(),r=n.length>0?n:[an(`claude-code`)];return!t||!gn()?r:_n(await Bt({message:`Which agents should get the skills?`,options:tn.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=>an(e))}async function yn(e,t){return e?`global`:!t||!gn()?`project`:_n(await Jt({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 bn=`kit/`;function xn(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 Sn(e,t,n){if(t.length>0)return wn(e,t,n,`skill`);if(!n||!gn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=_n(await Bt({message:`Which skills?`,options:e.map(e=>({value:e.id,label:jn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const Cn=(e,t,n)=>wn(e,t,n,`kit`);async function wn(e,t,n,r){let i=[];for(let a of t){let t=On(e,a,r),o=t.length===1?t[0]:await kn(t,n,r);i.includes(o)||i.push(o)}return i}const Tn=(e,t)=>On(e,t,`skill`);function En(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 Dn=(e,t)=>En(e,t);function On(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=En(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 kn(e,t,n){let r=e[0].name,i=n===`kit`?bn:``;if(!t||!gn()){let t=e.map(e=>{let t=i+An(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=_n(await Jt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:An(e)}))}));return e.find(e=>e.id===a)}const An=e=>`${e.organizationName}/${e.name}`,jn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function B(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function Mn(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function V(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?h(process.env.APPDATA,`agent-kit`):h(process.env.XDG_CONFIG_HOME??h(x(),`.config`),`agent-kit`)}const Nn=()=>h(V(),`credentials.json`);async function Pn(){try{return JSON.parse(await O(Nn(),`utf8`))}catch{return{}}}async function H(){return(await Pn())[B()]??null}async function Fn(e){let t=await Pn();e?t[B()]=e:delete t[B()];let n=Nn();await D(m(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
76
76
  `,{mode:384}),await te(n,384)}const In=()=>h(V(),`settings.json`);async function Ln(){try{return JSON.parse(await O(In(),`utf8`))}catch{return{}}}async function Rn(e){let t={...await Ln(),...e};await D(V(),{recursive:!0,mode:448}),await k(In(),JSON.stringify(t,null,2)+`
77
77
  `)}function zn(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 U(e){let t=_(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const Bn=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Vn(e){return e.split(`/`).some(e=>Bn.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const Hn=e=>pe(`sha256`).update(e).digest(`hex`);async function Un(e){let t=await oe(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=_(e,h(r.parentPath,r.name)).split(y).join(`/`);if(Vn(t))continue;let i=new Uint8Array(await O(h(e,t)));n.push({path:t,size:i.byteLength,sha256:Hn(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Wn(e,t){let n=new Map(t.filter(e=>!Vn(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 Gn(e){return e.length===0?`nothing`:e.length>3?`${e.length} files`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e.at(-1)}`}async function Kn(e,t){for(let n of e){if(!u(n))continue;let{paths:e}=Wn(await Un(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function qn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?Kn(r.map(e=>h(e,t)),i.files):null}async function Jn(e){try{if(!(await ie(e)).isSymbolicLink())return null}catch{return null}return v(m(e),await se(e))}async function Yn(e,t){for(let n of e){let e=await Jn(h(n,t));if(e)return e}return null}async function Xn(e,t){await le(e,{recursive:!0,force:!0}),await D(m(e),{recursive:!0}),await de(t,e,process.platform===`win32`?`junction`:`dir`)}const W=`SKILL.md`,Zn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},Qn=/[\u0000-\u001f\u007f\\:]/;function $n(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Zn.maxPathLength)return`Paths can be at most ${Zn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if(Qn.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 er(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function tr(e){return e.slice(e.lastIndexOf(`/`)+1)}function nr(e,t){let n=er(e)?er(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 G=/* @__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})),rr=/* @__PURE__ */ A((e=>{var t=G();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})),ir=/* @__PURE__ */ A((e=>{var t=G(),n=rr();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||e&&!a.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join(`
78
78
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ar=/* @__PURE__ */ A((e=>{var t=G(),n=rr();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})),or=/* @__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})),sr=/* @__PURE__ */ A((e=>{var t=G();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})),cr=/* @__PURE__ */ A((e=>{var t=or(),n=G(),r=sr();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}}})),lr=/* @__PURE__ */ A((e=>{var t=ar(),n=rr(),r=G(),i=cr(),a=sr(),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);
@@ -271,40 +271,41 @@ Only the conversation up to the developer's request to report it is sent; this p
271
271
  `)}const Jo=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function Yo(e,t=Ho,n=Date.now()){return(await Ln()).autoUpdate===!1||Jo(await Y(J(`global`)))||!await H()||!await Wo(n)?!1:(t(e,[`auto-update`,`run`]),!0)}const Xo=e=>({skills:Object.values(e.skills).map(e=>{let t=Ji(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 Zo(e,t,n=Uo()){try{let r=await Y(J(`global`));if(Jo(r))return`unchanged`;let{fingerprint:i}=await e.fingerprint(Xo(r),AbortSignal.timeout(5e3));return(await Ko(n)).fingerprint===i?`unchanged`:(await t(),await qo(n,{...await Ko(n),fingerprint:i}),`updated`)}catch{return`failed`}}const Qo=6e3,$o=e=>`github.com/${e.toLowerCase()}`,es=()=>h(V(),`project-repositories.json`);async function ts(){try{let e=JSON.parse(await O(es(),`utf8`));return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}catch{return{}}}async function ns(e){let t=await ts();t[B()]=e,await D(V(),{recursive:!0,mode:448});let n=`${es()}.${process.pid}`;await k(n,JSON.stringify(t)+`
272
272
  `),await ce(n,es())}const rs=e=>typeof e==`object`&&!!e&&!Array.isArray(e);async function is(e){let t=(await ts())[B()];return!t||t.userId!==e||typeof t.checkedAt!=`string`||typeof t.triedAt!=`string`||!rs(t.repositories)||!rs(t.skills)?null:t}async function as(e,t,n,r){let[i,a]=await Promise.all([e.listOrganizations(r),e.listSkillSummaries(r)]),o=await Promise.all(i.map(async t=>({organizationId:t.id,projects:await e.listProjects(t.id,r)}))),s={userId:t,checkedAt:n.toISOString(),triedAt:n.toISOString(),repositories:{},skills:{}};for(let{organizationId:e,projects:t}of o)for(let n of t)for(let t of n.repositories)s.repositories[$o(t.fullName)]=e;for(let e of a)s.skills[e.id]=e.organizationId;return await ns(s),s}function os(e,t,n){if(!e)return!0;let r=e=>t.getTime()-(Date.parse(e)||0);return r(e.triedAt)<36e5?!1:r(e.checkedAt)>=864e5||!!n&&!(n in e.skills)}async function ss(e,t,n,r){try{return await ns({userId:t,checkedAt:n?.checkedAt??(/* @__PURE__ */ new Date(0)).toISOString(),repositories:n?.repositories??{},skills:n?.skills??{},triedAt:r.toISOString()}),await as(e,t,r,AbortSignal.timeout(Qo))}catch{return null}}async function cs(){try{if(zn()||(await Ln()).telemetry===!1)return;let e=await H();if(!e)return;await as(z(B(),e.token),e.user.id,/* @__PURE__ */ new Date,AbortSignal.timeout(Qo))}catch{}}async function ls(e){Ht(`agent kit`),await cs();let t=e.global?`global`:`project`,n=J(t),r=await Y(n),i=Object.entries(r.public??{});if(Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0&&i.length===0){I(e.global?"No skills installed everywhere yet. Add some with `a-kit add -g`.":"No skills installed in this project yet. Add some with `a-kit add`.");return}let a=Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0?z(B(),(await H())?.token):(await Xa()).api,o=Ro(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 Lo([...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}Qi(r,e,i.name);try{let e=await $i(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 Yi(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=Ji(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 Yn(c,e);if(l){F.warn(`${e} uses ${U(l)} (\`a-kit link\`); left it. \`a-kit add ${e}\` goes back to v${s.version}.`),u++;continue}let f=await qn(a,e,t,c);if(f)F.warn(`${e} has edits here that aren't in agent kit (${Gn(f.paths)}); left it at v${t.version}. To keep them, make them in your organization's repository (\`a-kit link\` tries a skill from it); \`a-kit add ${e}\` throws them away.`),u++;else{if(await Ki(a,t.id,c,i),s.name!==e){for(let t of c)await le(h(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Yi(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 Ki(Gi(a,i),t.ref,s),i.name!==e){for(let t of s)await le(h(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Yi(n,r),F.success(`${i.name}: v${t.version} → v${i.version} (${t.ref})`+(i.name===e?``:` (was ${e})`)),d++}await No([...new Set([...Object.values(r.skills),...Object.values(r.kits),...i.map(([,e])=>e)].flatMap(e=>e.agents))]),I(ds(d,c,l,u))}const us=e=>`${e} skill${e===1?``:`s`}`;function ds(e,t,n,r){let i=[e&&`updated ${us(e)}`,t&&`installed ${us(t)}`,n&&`removed ${us(n)}`].filter(Boolean),a=r?`Left ${us(r)} with local edits or links as they are.`:``;if(i.length===0)return a||`Everything is up to date.`;let o=i.join(`, `);return`${o[0].toUpperCase()}${o.slice(1)}.${a&&` ${a}`}`}async function fs(e){switch(e){case`run`:{let e=await H();if(!e)return;await Zo(z(B(),e.token),()=>ls({global:!0,agent:[],yes:!0,channel:`latest`}));return}case`on`:{await Rn({autoUpdate:!0});let e=await Oo();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 Rn({autoUpdate:!1}),await Oo(),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 Ln()).autoUpdate!==!1,t=(await jo()).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 ps(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}const ms=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function hs(e,t=!!process.stdout.isTTY&&!process.env.NO_COLOR){let n=(e,n)=>t?r(e,n):n;return e.map(e=>{let t=e.severity===`error`?n(`red`,`✗`):n(`yellow`,`▲`),r=e.path===null?`repository`:e.path+(e.line?`:${e.line}`:``);return`${t} ${e.message} ${n(`dim`,r)}`})}function gs(e){let t=typeof e==`string`?e.trim():``;return t?t.length>64?{ok:!1,message:`Keep the name under 64 characters.`}:/^[a-z0-9-]+$/.test(t)?t.startsWith(`-`)||t.endsWith(`-`)||t.includes(`--`)?{ok:!1,message:`The name can't start or end with a hyphen, or have two in a row.`}:{ok:!0,name:t}:{ok:!1,message:`Use only lowercase letters, numbers and hyphens in the name.`}:{ok:!1,message:`Give the kit a name.`}}function _s(e){let t=/^kits\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function vs(e){let t;try{t=(0,q.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
273
273
  `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{skills:[]};let n="It has to list the kit's skills by name: `skills: [tdd, notes]`.";if(!ys(t))return{error:n};let{skills:r}=t;return r==null?{skills:[]}:!Array.isArray(r)||!r.every(e=>typeof e==`string`)?{error:n}:{skills:[...new Set(r.map(e=>e.trim()))]}}const ys=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function bs(e){let t;try{t=(0,q.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
274
- `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!ys(t))return{error:"It has to be a list of skills, each with its channels: `tdd: { stable: 7, beta: 9 }`."};let n={pins:/* @__PURE__ */ new Map,problems:[]};for(let[e,r]of Object.entries(t)){let t={};if(n.pins.set(e,t),r!==null){if(ys(r))for(let[i,a]of Object.entries(r))Yt.includes(i)?Number.isInteger(a)&&Number(a)>0?t[i]=a:(t[i]=null,n.problems.push(`The ${i} channel of “${e}” has to be a version number, like 7.`)):n.problems.push(`“${e}” has a channel called “${i}”. Only stable and beta can be set.`);else{for(let e of Yt)t[e]=null;n.problems.push(`“${e}” has to have its channels, like \`{ stable: 7 }\`.`)}}}return n}const xs=(...e)=>({words:e}),Ss={text:`one`},Cs={issue:{about:`an issue's state changed`,value:xs(`opened`,`closed`,`reopened`),fields:{}},label:{about:`a label was put on an issue or a pull request, or taken off`,value:Ss,fields:{on:xs(`added`,`removed`)}},path:{about:`a pull request that changes a path was merged`,value:Ss,fields:{on:xs(`merged`)}},"pull-request":{about:`a pull request was opened, marked ready, merged or closed`,value:xs(`opened`,`ready`,`merged`,`closed`),fields:{base:Ss,head:Ss}},review:{about:`a pull request got a review`,value:xs(`approved`,`changes-requested`,`commented`),fields:{by:{text:`many`}}},checks:{about:`a pull request's checks finished`,value:xs(`passed`,`failed`),fields:{}},release:{about:`a release was published`,value:xs(`published`),fields:{}},skill:{about:`an agent loaded a skill`,value:Ss,fields:{}},branch:{about:`a branch got its first commit`,value:xs(`first-commit`),fields:{}}},ws=Object.keys(Cs),Ts=e=>Object.hasOwn(Cs,e),Es=(e,t=`and`)=>e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)} ${t} ${e.at(-1)}`,Ds=`flows`,Os=[`epic`,`ticket`,`pull-request`],ks=[`paths`,`labels`];function As(e){let t=/^flows\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function js(e){return e.length===0?`It's empty.`:e.length>64?`It's longer than 64 characters.`:/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e)?null:`Use only lowercase letters, numbers and single hyphens, not at the start or the end.`}function Ms(e){let t=js(e);return t===null?null:`“${e}” can't be a flow's name, so this file isn't read. ${t}`}const Ns=[`name`,`description`,`stations`],Ps=[`id`,`unit`,`signal`,`owner`,`before`,`when`];function Fs(e){let t=[],n=(0,q.parseDocument)(e,{prettyErrors:!1}),r=t=>t&&typeof t==`object`&&`range`in t&&t.range?ps(e,t.range[0]):null,i=(e,n)=>{t.push({line:r(e),message:n})};if(n.errors.length>0){for(let r of n.errors)t.push({line:ps(e,r.pos[0]),message:`It isn't valid YAML: ${r.message.split(`
275
- `)[0]}`});return{flow:null,problems:t}}let a=Is(n,n.contents);if(a===null||(0,q.isScalar)(a)&&a.value===null)return t.push({line:null,message:"It's empty. A flow lists its stations: `stations: [{ id: review, unit: pull-request, signal: { review: approved } }]`."}),{flow:null,problems:t};if(!(0,q.isMap)(a))return i(a,"A flow has to be a mapping, with its `stations`."),{flow:null,problems:t};let o=Ls(n,a,Ns,`A flow`,i),s=o.has(`name`)?Rs(o.get(`name`),"Its `name`",i):null,c=o.has(`description`)?Rs(o.get(`description`),"Its `description`",i):null,l=o.get(`stations`),u=[],d=[];if(!l)i(a,"It has no `stations`: a flow lists them in order.");else if(!(0,q.isSeq)(l.value)||l.value.items.length===0)i(l.value??l.key,"Its `stations` have to be a list, with one station at least.");else if(l.value.items.length>100)i(l.key,`A flow has at most 100 stations, and this one has ${l.value.items.length}.`);else{let e=/* @__PURE__ */ new Map;l.value.items.forEach((t,a)=>{let o=Is(n,t),s=`Station ${a+1}`;if(!(0,q.isMap)(o)){i(o??l.value,`${s} has to be a mapping, with its \`id\`, \`unit\` and \`signal\`.`);return}let c=Ls(n,o,Ps,s,i),f=c.get(`id`),p=null;if(!f)i(o,`${s} has no \`id\`. Give it one that stays the same, like \`review\`.`);else{p=Rs(f,`The \`id\` of ${s.toLowerCase()}`,i);let t=p===null?null:js(p);if(p!==null&&t)i(f.value,`“${p}” can't be a station's id. ${t}`),p=null;else if(p!==null&&e.has(p)){let t=e.get(p);i(f.value,`There's another station with the id “${p}”${t?` (line ${t})`:``}. Each station's id has to be its own.`),p=null}else p!==null&&e.set(p,r(f.value))}let m=p?`Station “${p}”`:s,h=c.get(`unit`),g=null;if(!h)i(o,`${m} has no \`unit\`: say whether it's counted for an \`epic\`, a \`ticket\` or a \`pull-request\`.`);else{let e=Rs(h,`The \`unit\` of ${m.toLowerCase()}`,i);e!==null&&(Os.includes(e)?g=e:i(h.value,`“${e}” isn't a unit. A station is counted for an epic, a ticket or a pull-request.`))}let _=c.get(`signal`),v=null;_?v=Bs(n,_.value,m,i):i(o,`${m} has no \`signal\`: say how agent kit knows it happened, like \`{ review: approved }\`.`);let y=c.has(`owner`)?zs(n,c.get(`owner`),`The \`owner\` of ${m.toLowerCase()}`,`a role`,i):[],b=[],x=c.get(`before`);if(x){let e=Is(n,x.value),t=(0,q.isSeq)(e)?e.items.map(e=>Is(n,e)):[e];for(let e of t){let t=(0,q.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)?String(e.value).trim():``;t?(b.push(t),d.push({station:p??``,node:e,id:t})):i(e??x.key,`The \`before\` of ${m.toLowerCase()} has to be a station's id, or a list of them.`)}}let S=c.has(`when`)?Ws(n,c.get(`when`),m,i):null;p!==null&&g!==null&&v!==null&&y!==null&&S!==void 0&&u.push({id:p,unit:g,signals:v,owner:y,before:b,when:S})});for(let{station:t,node:n,id:r}of d)r===t?i(n,`Station “${t}” can't come before itself.`):e.has(r)||i(n,`There's no station “${r}” in this flow, so nothing can come before it.`)}return t.sort((e,t)=>(e.line??0)-(t.line??0)),{flow:t.length===0?{name:s,description:c,stations:u}:null,problems:t}}const Is=(e,t)=>t==null?null:(0,q.isAlias)(t)?t.resolve(e)??null:t;function Ls(e,t,n,r,i){let a=/* @__PURE__ */ new Map;if(!(0,q.isMap)(t))return a;for(let o of t.items){let s=Is(e,o.key),c=(0,q.isScalar)(s)?String(s.value):null;c===null||!n.includes(c)?i(s??t,`${r} doesn't take \`${c??`?`}\`. It takes ${Es(n.map(e=>`\`${e}\``))}.`):a.set(c,{key:s,value:Is(e,o.value)})}return a}function Rs(e,t,n){let{value:r}=e;return(0,q.isScalar)(r)&&(typeof r.value==`string`||typeof r.value==`number`)&&String(r.value).trim()!==``?String(r.value).trim():(n(r??e.key,`${t} has to be some text.`),null)}function zs(e,t,n,r,i){let a=Is(e,t.value),o=(0,q.isSeq)(a)?a.items.map(t=>Is(e,t)):[a],s=[];for(let e of o){if(!(0,q.isScalar)(e)||typeof e.value!=`string`&&typeof e.value!=`number`||String(e.value).trim()===``)return i(e??t.key,`${n} has to be ${r}, or a list of them.`),null;s.push(String(e.value).trim())}return s.length===0?(i(a??t.key,`${n} has to be ${r}, or a list of them.`),null):s}function Bs(e,t,n,r){let i=(0,q.isSeq)(t)?t.items.map(t=>Is(e,t)):[t];if(i.length===0)return r(t,`The \`signal\` of ${n.toLowerCase()} is an empty list: give it one at least.`),null;let a=[],o=!0;for(let t of i){let i=Hs(e,t,n,r);i?a.push(i):o=!1}return o?a:null}const Vs=Es(ws.map(e=>`\`${e}\``));function Hs(e,t,n,r){if(!(0,q.isMap)(t))return r(t,`A signal of ${n.toLowerCase()} has to be a mapping that starts with its kind, like \`{ review: approved }\`. The kinds are ${Vs}.`),null;let i=t.items.map(t=>{let n=Is(e,t.key);return{key:n,name:(0,q.isScalar)(n)?String(n.value):`?`,value:Is(e,t.value)}}),a=i.filter(e=>Ts(e.name));if(a.length===0){let[e]=i;return r(e?.key??t,e?`“${e.name}” isn't a kind of signal. The kinds are ${Vs}.`:`A signal of ${n.toLowerCase()} is empty. Start it with its kind: ${Vs}.`),null}if(a.length>1)return r(a[1].key,`A signal is of one kind, and this one has ${Es(a.map(e=>`\`${e.name}\``))}. To take any of them, make \`signal\` a list.`),null;let o=a[0].name,s=Cs[o],c=!0,l=Us(a[0].value,s.value,`\`${o}\``,a[0].key,r);(l===null||Array.isArray(l))&&(c=!1);let u={},d=Object.keys(s.fields);for(let e of i){if(e.name===o)continue;let t=s.fields[e.name];if(!t){r(e.key,d.length===0?`A \`${o}\` signal takes no other field, and this one has \`${e.name}\`.`:`A \`${o}\` signal doesn't take \`${e.name}\`. It takes ${Es(d.map(e=>`\`${e}\``))}.`),c=!1;continue}let n=Us(e.value,t,`\`${e.name}\``,e.key,r);n===null?c=!1:u[e.name]=n}return c?{kind:o,value:l,fields:u}:null}function Us(e,t,n,r,i){let a=e=>(0,q.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)&&String(e.value).trim()!==``?String(e.value).trim():null;if(`words`in t){let o=a(e);return o!==null&&t.words.includes(o)?o:(i(e??r,`${n} has to be ${Es(t.words.map(e=>`\`${e}\``),`or`)}${o===null?``:`, not “${o}”`}.`),null)}if(t.text===`many`&&(0,q.isSeq)(e)){let t=e.items.map(e=>a(e));return t.length>0&&t.every(e=>e!==null)?t:(i(e,`${n} has to be a name, or a list of them.`),null)}let o=a(e);return o===null?(i(e??r,`${n} has to be ${t.text===`many`?`a name, or a list of them`:`some text`}.`),null):o}function Ws(e,t,n,r){let i=t.value;if(!(0,q.isMap)(i)){r(i??t.key,`The \`when\` of ${n.toLowerCase()} has to be a mapping, like \`{ paths: [docs] }\`.`);return}let a=Ls(e,i,ks,`The \`when\` of ${n.toLowerCase()}`,r);if(a.size!==i.items.length)return;let o={};for(let[t,n]of a){let i=zs(e,n,`\`${t}\``,`a name`,r);if(i===null)return;o[t]=i}return o}const Gs=new Map([{key:`name`,scope:`standard`,kind:`string`,required:!0,summary:`The skill's id and its /command. 1–64 lowercase letters, numbers and single hyphens.`},{key:`description`,scope:`standard`,kind:`string`,required:!0,summary:`What the skill does and when to use it. The agent reads it to decide when to load the skill. Up to 1024 characters.`},{key:`license`,scope:`standard`,kind:`string`,summary:`A license name, or the path of a license file in the skill.`},{key:`compatibility`,scope:`standard`,kind:`string`,summary:`Environment the skill needs (tools, network, OS). Up to 500 characters; only add it when it matters.`},{key:`metadata`,scope:`standard`,kind:`map`,summary:`Extra key: value pairs, both strings (author, version…).`,snippet:`
276
- author: `},{key:`allowed-tools`,scope:`standard`,kind:`tools`,summary:"Space-separated tools the skill may use without asking, like `Bash(git:*) Read`. Experimental."},{key:`when_to_use`,scope:`claude-code`,kind:`string`,summary:`More on when to use the skill, appended to the description in Claude Code's listing.`},{key:`argument-hint`,scope:`claude-code`,kind:`string`,summary:"Hint shown when typing the /command, like `[issue-number]`."},{key:`arguments`,scope:`claude-code`,kind:`tools`,summary:`Names for the /command's arguments, in order; use them as $name in the body.`},{key:`disable-model-invocation`,scope:`claude-code`,kind:`boolean`,summary:`true: only you can run it with its /command; Claude won't load it.`,snippet:`true`},{key:`user-invocable`,scope:`claude-code`,kind:`boolean`,summary:`false: hide it from the / menu, so only Claude loads it.`,snippet:`false`},{key:`disallowed-tools`,scope:`claude-code`,kind:`tools`,summary:`Tools taken away while the skill runs.`},{key:`model`,scope:`claude-code`,kind:`string`,summary:"Model to use while the skill runs, or `inherit`."},{key:`effort`,scope:`claude-code`,kind:{oneOf:[`low`,`medium`,`high`,`xhigh`,`max`]},summary:`Reasoning effort while the skill runs.`},{key:`context`,scope:`claude-code`,kind:{oneOf:[`fork`]},summary:"`fork` runs the skill in a subagent with its own context.",snippet:`fork`},{key:`agent`,scope:`claude-code`,kind:`string`,summary:"Subagent type to run in, with `context: fork`."},{key:`background`,scope:`claude-code`,kind:`boolean`,summary:"With `context: fork`, whether the subagent runs in the background."},{key:`hooks`,scope:`claude-code`,kind:`any`,summary:`Hooks registered while the skill is in use.`},{key:`paths`,scope:`claude-code`,kind:`tools`,summary:`Globs; Claude offers the skill when working on matching files.`},{key:`shell`,scope:`claude-code`,kind:{oneOf:[`bash`,`powershell`]},summary:"Shell for !`command` blocks in the body."}].map(e=>[e.key,e])),Ks=1024,qs=1536,Js=[`anthropic`,`claude`],Ys=/<\/?[A-Za-z][^>]*>/;function Xs(e){let t=[];e.files.length>Zn.maxFiles&&t.push(ac(`A skill can have at most ${Zn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=$n(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>Zn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${cc(Zn.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>Zn.maxSkillBytes&&t.push(ac(`The whole skill can be at most ${cc(Zn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(ac(`Every skill needs a ${W} at its root.`)),t):(t.push(...Zs(e.skillMd,r,e.skills)),t)}function Zs(e,t,n){let r=[],i=(e,t,n,i,a)=>r.push({severity:e,path:W,message:t,from:n,to:i,fix:a}),a=bi(e);if(!a.ok)return a.reason===`unclosed`?i(`error`,`The frontmatter has no closing --- line.`,0,3):i(`error`,`${W} must start with frontmatter: a --- line, name and description, and another --- line.`,0,Math.min(e.indexOf(`
274
+ `)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!ys(t))return{error:"It has to be a list of skills, each with its channels: `tdd: { stable: 7, beta: 9 }`."};let n={pins:/* @__PURE__ */ new Map,problems:[]};for(let[e,r]of Object.entries(t)){let t={};if(n.pins.set(e,t),r!==null){if(ys(r))for(let[i,a]of Object.entries(r))Yt.includes(i)?Number.isInteger(a)&&Number(a)>0?t[i]=a:(t[i]=null,n.problems.push(`The ${i} channel of “${e}” has to be a version number, like 7.`)):n.problems.push(`“${e}” has a channel called “${i}”. Only stable and beta can be set.`);else{for(let e of Yt)t[e]=null;n.problems.push(`“${e}” has to have its channels, like \`{ stable: 7 }\`.`)}}}return n}const xs=(...e)=>({words:e}),Ss={text:`one`},Cs={issue:{about:`an issue's state changed`,value:xs(`opened`,`closed`,`reopened`),fields:{}},label:{about:`a label was put on an issue or a pull request, or taken off`,value:Ss,fields:{on:xs(`added`,`removed`)}},path:{about:`a pull request that changes a path was merged`,value:Ss,fields:{on:xs(`merged`)}},"pull-request":{about:`a pull request was opened, marked ready, merged or closed`,value:xs(`opened`,`ready`,`merged`,`closed`),fields:{base:Ss,head:Ss}},review:{about:`a pull request got a review`,value:xs(`approved`,`changes-requested`,`commented`),fields:{by:{text:`many`}},roles:[`by`]},checks:{about:`a pull request's checks finished`,value:xs(`passed`,`failed`),fields:{}},release:{about:`a release was published`,value:xs(`published`),fields:{}},skill:{about:`an agent loaded a skill`,value:Ss,fields:{}},branch:{about:`a branch got its first commit`,value:xs(`first-commit`),fields:{}}},ws=Object.keys(Cs),Ts=e=>Object.hasOwn(Cs,e),Es=(e,t=`and`)=>e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)} ${t} ${e.at(-1)}`,Ds=`flows`,Os=[`epic`,`ticket`,`pull-request`],ks=[`paths`,`labels`];function As(e){let t=/^flows\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function js(e){return e.length===0?`It's empty.`:e.length>64?`It's longer than 64 characters.`:/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e)?null:`Use only lowercase letters, numbers and single hyphens, not at the start or the end.`}function Ms(e){let t=js(e);return t===null?null:`“${e}” can't be a flow's name, so this file isn't read. ${t}`}const Ns=[`name`,`description`,`stations`],Ps=[`id`,`unit`,`signal`,`owner`,`before`,`when`];function Fs(e){let t=[],n=[],r=(0,q.parseDocument)(e,{prettyErrors:!1}),i=t=>t&&typeof t==`object`&&`range`in t&&t.range?ps(e,t.range[0]):null,a=(e,n)=>{t.push({line:i(e),message:n})},o=(e,t)=>{n.push({name:e,line:i(t)})};if(r.errors.length>0){for(let n of r.errors)t.push({line:ps(e,n.pos[0]),message:`It isn't valid YAML: ${n.message.split(`
275
+ `)[0]}`});return{flow:null,problems:t,roles:n}}let s=X(r,r.contents);if(s===null||(0,q.isScalar)(s)&&s.value===null)return t.push({line:null,message:"It's empty. A flow lists its stations: `stations: [{ id: review, unit: pull-request, signal: { review: approved } }]`."}),{flow:null,problems:t,roles:n};if(!(0,q.isMap)(s))return a(s,"A flow has to be a mapping, with its `stations`."),{flow:null,problems:t,roles:n};let c=Is(r,s,Ns,`A flow`,a),l=c.has(`name`)?Ls(c.get(`name`),"Its `name`",a):null,u=c.has(`description`)?Ls(c.get(`description`),"Its `description`",a):null,d=c.get(`stations`),f=[],p=[];if(!d)a(s,"It has no `stations`: a flow lists them in order.");else if(!(0,q.isSeq)(d.value)||d.value.items.length===0)a(d.value??d.key,"Its `stations` have to be a list, with one station at least.");else if(d.value.items.length>100)a(d.key,`A flow has at most 100 stations, and this one has ${d.value.items.length}.`);else{let e=/* @__PURE__ */ new Map;d.value.items.forEach((t,n)=>{let s=X(r,t),c=`Station ${n+1}`;if(!(0,q.isMap)(s)){a(s??d.value,`${c} has to be a mapping, with its \`id\`, \`unit\` and \`signal\`.`);return}let l=Is(r,s,Ps,c,a),u=l.get(`id`),m=null;if(!u)a(s,`${c} has no \`id\`. Give it one that stays the same, like \`review\`.`);else{m=Ls(u,`The \`id\` of ${c.toLowerCase()}`,a);let t=m===null?null:js(m);if(m!==null&&t)a(u.value,`“${m}” can't be a station's id. ${t}`),m=null;else if(m!==null&&e.has(m)){let t=e.get(m);a(u.value,`There's another station with the id “${m}”${t?` (line ${t})`:``}. Each station's id has to be its own.`),m=null}else m!==null&&e.set(m,i(u.value))}let h=m?`Station “${m}”`:c,g=l.get(`unit`),_=null;if(!g)a(s,`${h} has no \`unit\`: say whether it's counted for an \`epic\`, a \`ticket\` or a \`pull-request\`.`);else{let e=Ls(g,`The \`unit\` of ${h.toLowerCase()}`,a);e!==null&&(Os.includes(e)?_=e:a(g.value,`“${e}” isn't a unit. A station is counted for an epic, a ticket or a pull-request.`))}let v=l.get(`signal`),y=null;v?y=zs(r,v.value,h,a,o):a(s,`${h} has no \`signal\`: say how agent kit knows it happened, like \`{ review: approved }\`.`);let b=l.has(`owner`)?Rs(r,l.get(`owner`),`The \`owner\` of ${h.toLowerCase()}`,`a role`,a,o):[],x=[],S=l.get(`before`);if(S){let e=X(r,S.value),t=(0,q.isSeq)(e)?e.items.map(e=>X(r,e)):[e];for(let e of t){let t=(0,q.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)?String(e.value).trim():``;t?(x.push(t),p.push({station:m??``,node:e,id:t})):a(e??S.key,`The \`before\` of ${h.toLowerCase()} has to be a station's id, or a list of them.`)}}let C=l.has(`when`)?Us(r,l.get(`when`),h,a):null;m!==null&&_!==null&&y!==null&&b!==null&&C!==void 0&&f.push({id:m,unit:_,signals:y,owner:b,before:x,when:C})});for(let{station:t,node:n,id:r}of p)r===t?a(n,`Station “${t}” can't come before itself.`):e.has(r)||a(n,`There's no station “${r}” in this flow, so nothing can come before it.`)}return t.sort((e,t)=>(e.line??0)-(t.line??0)),n.sort((e,t)=>(e.line??0)-(t.line??0)),{flow:t.length===0?{name:l,description:u,stations:f}:null,problems:t,roles:n}}const X=(e,t)=>t==null?null:(0,q.isAlias)(t)?t.resolve(e)??null:t;function Is(e,t,n,r,i){let a=/* @__PURE__ */ new Map;if(!(0,q.isMap)(t))return a;for(let o of t.items){let s=X(e,o.key),c=(0,q.isScalar)(s)?String(s.value):null;c===null||!n.includes(c)?i(s??t,`${r} doesn't take \`${c??`?`}\`. It takes ${Es(n.map(e=>`\`${e}\``))}.`):a.set(c,{key:s,value:X(e,o.value)})}return a}function Ls(e,t,n){let{value:r}=e;return(0,q.isScalar)(r)&&(typeof r.value==`string`||typeof r.value==`number`)&&String(r.value).trim()!==``?String(r.value).trim():(n(r??e.key,`${t} has to be some text.`),null)}function Rs(e,t,n,r,i,a){let o=X(e,t.value),s=(0,q.isSeq)(o)?o.items.map(t=>X(e,t)):[o],c=[];for(let e of s){if(!(0,q.isScalar)(e)||typeof e.value!=`string`&&typeof e.value!=`number`||String(e.value).trim()===``)return i(e??t.key,`${n} has to be ${r}, or a list of them.`),null;c.push(String(e.value).trim())}return c.forEach((e,t)=>a?.(e,s[t])),c.length===0?(i(o??t.key,`${n} has to be ${r}, or a list of them.`),null):c}function zs(e,t,n,r,i){let a=(0,q.isSeq)(t)?t.items.map(t=>X(e,t)):[t];if(a.length===0)return r(t,`The \`signal\` of ${n.toLowerCase()} is an empty list: give it one at least.`),null;let o=[],s=!0;for(let t of a){let a=Vs(e,t,n,r,i);a?o.push(a):s=!1}return s?o:null}const Bs=Es(ws.map(e=>`\`${e}\``));function Vs(e,t,n,r,i){if(!(0,q.isMap)(t))return r(t,`A signal of ${n.toLowerCase()} has to be a mapping that starts with its kind, like \`{ review: approved }\`. The kinds are ${Bs}.`),null;let a=t.items.map(t=>{let n=X(e,t.key);return{key:n,name:(0,q.isScalar)(n)?String(n.value):`?`,value:X(e,t.value)}}),o=a.filter(e=>Ts(e.name));if(o.length===0){let[e]=a;return r(e?.key??t,e?`“${e.name}” isn't a kind of signal. The kinds are ${Bs}.`:`A signal of ${n.toLowerCase()} is empty. Start it with its kind: ${Bs}.`),null}if(o.length>1)return r(o[1].key,`A signal is of one kind, and this one has ${Es(o.map(e=>`\`${e.name}\``))}. To take any of them, make \`signal\` a list.`),null;let s=o[0].name,c=Cs[s],l=!0,u=Hs(o[0].value,c.value,`\`${s}\``,o[0].key,r);(u===null||Array.isArray(u))&&(l=!1);let d={},f=Object.keys(c.fields);for(let e of a){if(e.name===s)continue;let t=c.fields[e.name];if(!t){r(e.key,f.length===0?`A \`${s}\` signal takes no other field, and this one has \`${e.name}\`.`:`A \`${s}\` signal doesn't take \`${e.name}\`. It takes ${Es(f.map(e=>`\`${e}\``))}.`),l=!1;continue}let n=Hs(e.value,t,`\`${e.name}\``,e.key,r);if(n===null)l=!1;else if(d[e.name]=n,c.roles?.includes(e.name)){let t=(0,q.isSeq)(e.value)?e.value.items:[e.value];(Array.isArray(n)?n:[n]).forEach((n,r)=>i(n,t[r]??e.key))}}return l?{kind:s,value:u,fields:d}:null}function Hs(e,t,n,r,i){let a=e=>(0,q.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)&&String(e.value).trim()!==``?String(e.value).trim():null;if(`words`in t){let o=a(e);return o!==null&&t.words.includes(o)?o:(i(e??r,`${n} has to be ${Es(t.words.map(e=>`\`${e}\``),`or`)}${o===null?``:`, not “${o}”`}.`),null)}if(t.text===`many`&&(0,q.isSeq)(e)){let t=e.items.map(e=>a(e));return t.length>0&&t.every(e=>e!==null)?t:(i(e,`${n} has to be a name, or a list of them.`),null)}let o=a(e);return o===null?(i(e??r,`${n} has to be ${t.text===`many`?`a name, or a list of them`:`some text`}.`),null):o}function Us(e,t,n,r){let i=t.value;if(!(0,q.isMap)(i)){r(i??t.key,`The \`when\` of ${n.toLowerCase()} has to be a mapping, like \`{ paths: [docs] }\`.`);return}let a=Is(e,i,ks,`The \`when\` of ${n.toLowerCase()}`,r);if(a.size!==i.items.length)return;let o={};for(let[t,n]of a){let i=Rs(e,n,`\`${t}\``,`a name`,r);if(i===null)return;o[t]=i}return o}const Ws=new Map([{key:`name`,scope:`standard`,kind:`string`,required:!0,summary:`The skill's id and its /command. 1–64 lowercase letters, numbers and single hyphens.`},{key:`description`,scope:`standard`,kind:`string`,required:!0,summary:`What the skill does and when to use it. The agent reads it to decide when to load the skill. Up to 1024 characters.`},{key:`license`,scope:`standard`,kind:`string`,summary:`A license name, or the path of a license file in the skill.`},{key:`compatibility`,scope:`standard`,kind:`string`,summary:`Environment the skill needs (tools, network, OS). Up to 500 characters; only add it when it matters.`},{key:`metadata`,scope:`standard`,kind:`map`,summary:`Extra key: value pairs, both strings (author, version…).`,snippet:`
276
+ author: `},{key:`allowed-tools`,scope:`standard`,kind:`tools`,summary:"Space-separated tools the skill may use without asking, like `Bash(git:*) Read`. Experimental."},{key:`when_to_use`,scope:`claude-code`,kind:`string`,summary:`More on when to use the skill, appended to the description in Claude Code's listing.`},{key:`argument-hint`,scope:`claude-code`,kind:`string`,summary:"Hint shown when typing the /command, like `[issue-number]`."},{key:`arguments`,scope:`claude-code`,kind:`tools`,summary:`Names for the /command's arguments, in order; use them as $name in the body.`},{key:`disable-model-invocation`,scope:`claude-code`,kind:`boolean`,summary:`true: only you can run it with its /command; Claude won't load it.`,snippet:`true`},{key:`user-invocable`,scope:`claude-code`,kind:`boolean`,summary:`false: hide it from the / menu, so only Claude loads it.`,snippet:`false`},{key:`disallowed-tools`,scope:`claude-code`,kind:`tools`,summary:`Tools taken away while the skill runs.`},{key:`model`,scope:`claude-code`,kind:`string`,summary:"Model to use while the skill runs, or `inherit`."},{key:`effort`,scope:`claude-code`,kind:{oneOf:[`low`,`medium`,`high`,`xhigh`,`max`]},summary:`Reasoning effort while the skill runs.`},{key:`context`,scope:`claude-code`,kind:{oneOf:[`fork`]},summary:"`fork` runs the skill in a subagent with its own context.",snippet:`fork`},{key:`agent`,scope:`claude-code`,kind:`string`,summary:"Subagent type to run in, with `context: fork`."},{key:`background`,scope:`claude-code`,kind:`boolean`,summary:"With `context: fork`, whether the subagent runs in the background."},{key:`hooks`,scope:`claude-code`,kind:`any`,summary:`Hooks registered while the skill is in use.`},{key:`paths`,scope:`claude-code`,kind:`tools`,summary:`Globs; Claude offers the skill when working on matching files.`},{key:`shell`,scope:`claude-code`,kind:{oneOf:[`bash`,`powershell`]},summary:"Shell for !`command` blocks in the body."}].map(e=>[e.key,e])),Gs=1024,Ks=1536,qs=[`anthropic`,`claude`],Js=/<\/?[A-Za-z][^>]*>/;function Ys(e){let t=[];e.files.length>Zn.maxFiles&&t.push(ic(`A skill can have at most ${Zn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=$n(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>Zn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${sc(Zn.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>Zn.maxSkillBytes&&t.push(ic(`The whole skill can be at most ${sc(Zn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(ic(`Every skill needs a ${W} at its root.`)),t):(t.push(...Xs(e.skillMd,r,e.skills)),t)}function Xs(e,t,n){let r=[],i=(e,t,n,i,a)=>r.push({severity:e,path:W,message:t,from:n,to:i,fix:a}),a=bi(e);if(!a.ok)return a.reason===`unclosed`?i(`error`,`The frontmatter has no closing --- line.`,0,3):i(`error`,`${W} must start with frontmatter: a --- line, name and description, and another --- line.`,0,Math.min(e.indexOf(`
277
277
  `)===-1?e.length:e.indexOf(`
278
278
  `),80),{label:`Add frontmatter`,from:0,to:0,insert:`---
279
279
  name: my-skill
280
280
  description:
281
281
  ---
282
282
 
283
- `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,ic(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
283
+ `}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,rc(e.message),e.from,e.to);if(a.yamlErrors.length>0)return r;if(!a.isMapping)return i(`error`,`The frontmatter must be key: value lines.`,o.yamlFrom,o.yamlTo),r;let c=/* @__PURE__ */ new Map;for(let e of s)c.has(e.key)&&i(`error`,`\`${e.key}\` appears twice.`,e.keyFrom,e.keyTo),c.set(e.key,e);let l=o.yamlTo;for(let e of[`name`,`description`])c.has(e)||i(`error`,`The frontmatter needs a \`${e}\`.`,Math.max(0,o.yamlFrom-4),o.yamlFrom-1,{label:`Add ${e}`,from:l,to:l,insert:e===`name`?`name: my-skill
284
284
  `:`description:
285
- `});for(let e of s){let t=Gs.get(e.key);if(t)nc(t,e,i),t.scope===`claude-code`&&i(`warning`,`Only Claude Code reads \`${t.key}\`; claude.ai and the Skills API reject skills that have it.`,e.keyFrom,e.keyTo);else{let t=Gs.get(e.key.toLowerCase().replace(/_/g,`-`));i(`warning`,t?`Unknown field \`${e.key}\`. Did you mean \`${t.key}\`?`:`Unknown field \`${e.key}\`. Claude Code ignores it, and claude.ai and the Skills API reject the skill.`,e.keyFrom,e.keyTo,t?{label:`Rename to ${t.key}`,from:e.keyFrom,to:e.keyTo,insert:t.key}:void 0)}}let u=c.get(`name`);if(u&&typeof u.value==`string`)for(let e of ec(u.value)){let t=tc(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`,Qs,d.keyFrom,d.keyTo);else{let n=$s(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>qs&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${qs}.`,...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&&sc(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),rc(e,o.bodyFrom,t,n,i),r}const Qs=`The description is empty. Say what the skill does and when to use it.`;function $s(e){let t=e.trim();if(t===``)return{errors:[Qs],warnings:[]};let n=[],r=[];return t.length>Ks&&n.push(`The description is ${t.length} characters; the most is ${Ks}.`),Ys.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 ec(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=Js.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function tc(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of Js)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function nc(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`?oc(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`&&!sc(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 rc(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(`
285
+ `});for(let e of s){let t=Ws.get(e.key);if(t)tc(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=Ws.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 $s(u.value)){let t=ec(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`,Zs,d.keyFrom,d.keyTo);else{let n=Qs(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>Ks&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${Ks}.`,...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&&oc(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),nc(e,o.bodyFrom,t,n,i),r}const Zs=`The description is empty. Say what the skill does and when to use it.`;function Qs(e){let t=e.trim();if(t===``)return{errors:[Zs],warnings:[]};let n=[],r=[];return t.length>Gs&&n.push(`The description is ${t.length} characters; the most is ${Gs}.`),Js.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 $s(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=qs.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function ec(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of qs)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function tc(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`?ac(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`&&!oc(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 nc(e,t,n,r,i){let a=e.slice(t);if(a.trim()===``){i(`warning`,`The skill has no instructions yet. Write them below the frontmatter.`,Math.max(0,t-4),t);return}let o=a.split(`
286
286
  `).length;o>500&&i(`warning`,`${W} has ${o} lines below the frontmatter. Keep it under 500 and move details to other files it links to.`,t,t+a.indexOf(`
287
- `));for(let{path:a,from:o,to:s}of Di(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=nr(W,a);if(e===null){let e=Oi(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 ic(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 ac(e){return{severity:`error`,path:null,message:e}}function oc(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function sc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cc(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const lc=`channels.yaml`;function uc(e,t){let n=`${t}/`,r=/* @__PURE__ */ new Map,i=[];for(let t of e){if(!t.path.startsWith(n))continue;let e=t.path.slice(n.length),a=e.indexOf(`/`);if(a===-1){i.push(e);continue}let o=e.slice(0,a),s=r.get(o)??[];s.push({path:e.slice(a+1),size:t.size}),r.set(o,s)}return{folders:[...r].sort(([e],[t])=>e.localeCompare(t)),loose:i}}function dc(e){return uc(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===W)).map(([e])=>e)}function fc(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(dc(t));e.truncated&&r.push({severity:`warning`,path:null,message:`The repository has more files than GitHub lists at once, so some weren't checked.`}),i.size>300&&r.push({severity:`warning`,path:`skills`,message:`Only the first 300 skills were checked.`});let a=uc(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${W} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${W}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of Xs({files:t,skillMd:s,skills:n}))o.push({severity:e.severity,path:e.path===null?a:`${a}/${e.path}`,...e.path===`SKILL.md`&&e.from!==void 0?{line:ps(s,e.from)}:{},message:e.message});let r=xi(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${W}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:xi(s).description,files:t.length,errors:o.filter(e=>e.severity===`error`).length,warnings:o.filter(e=>e.severity===`warning`).length}}),o=(e,t,n)=>{for(let i of n)t.some(e=>e.path===i)||r.push({severity:`error`,path:e,message:`It needs a ${i}.`})},s=uc(t,`evals`).folders.map(([e])=>{let n=`evals/${e}`;i.has(e)||r.push({severity:`warning`,path:n,message:`There's no skill named “${e}” in skills/, so these evals have nothing to test.`});let a=uc(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=uc(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=uc(t,`${i}/tasks`).folders;for(let[e,t]of a)o(`${i}/tasks/${e}`,t,[`task.yaml`,`prompt.md`]);return a.length===0&&r.push({severity:`warning`,path:i,message:`It has no tasks yet: add one in tasks/<task>/.`}),{name:e,tasks:a.length}});if(typeof e.channelsText==`string`){let t=bs(e.channelsText),n=(e,t)=>r.push({severity:e,path:lc,message:t});if(`error`in t)n(`error`,`${t.error} No channel was changed.`);else{for(let e of t.problems)n(`error`,e);for(let e of t.pins.keys())i.has(e)||n(`warning`,`There's no skill named “${e}” in skills/, so its channels set nothing.`)}}let l=[];for(let n of uc(t,`kits`).loose){let t=`kits/${n}`,a=_s(t);if(a===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are kits: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}l.push(a);let o=(e,n)=>r.push({severity:e,path:t,message:n}),s=gs(a);if(!s.ok||s.name!==a){o(`error`,`“${a}” can't be a kit's name, so this file isn't read. ${s.ok?`Take out the spaces.`:s.message}`);continue}let c=e.kitTexts?.get(t);if(c===void 0)continue;let u=vs(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}let u=[];for(let n of uc(t,Ds).loose){let t=`${Ds}/${n}`,i=As(t);if(i===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are flows: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}u.push(i);let a=Ms(i);if(a){r.push({severity:`error`,path:t,message:a});continue}let o=e.flowTexts?.get(t);if(o!==void 0)for(let e of Fs(o).problems)r.push({severity:`error`,path:t,...e.line===null?{}:{line:e.line},message:e.message})}return{skills:a,evals:s,benchmarks:c,fixtures:uc(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),flows:u.sort((e,t)=>e.localeCompare(t)),channels:t.some(e=>e.path===lc),problems:r.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0))}}const pc=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],mc=e=>{try{return d(e).isDirectory()}catch{return!1}};function hc(e){let t;for(let n=v(e);;n=m(n)){if(t??=mc(h(n,`skills`))?n:void 0,u(h(n,`.git`))){if(mc(h(n,`skills`)))return n;throw Error(`${U(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(m(n)===n)break}if(t)return t;throw Error(`There's no skills/ folder here. Run this in a clone of your organization's repository.`)}async function gc(e){let t=[];for(let n of pc){let r=h(e,n);if(mc(r))for(let n of await oe(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=h(n.parentPath,n.name),i=_(e,r).split(y).join(`/`);Vn(i)||t.push({path:i,size:(await ue(r)).size})}}return u(h(e,`channels.yaml`))&&t.push({path:lc,size:(await ue(h(e,lc))).size}),t}async function _c(e){let t=await gc(e),n=/* @__PURE__ */ new Map;for(let r of dc(t))n.set(r,await O(h(e,`skills`,r,W),`utf8`));let r=t.some(e=>e.path===`channels.yaml`)?await O(h(e,lc),`utf8`):null,i=/* @__PURE__ */ new Map;for(let{path:n}of t)As(n)!==null&&i.set(n,await O(h(e,n),`utf8`));return fc({files:t,skillMds:n,channelsText:r,flowTexts:i})}function vc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=v(n,i);if(mc(t)){if(t===e||t===h(e,`skills`))return[];if(m(t)===h(e,`skills`)){r.push(f(t));continue}let n=_(h(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(y)[0]);continue}throw Error(`${U(t)} isn't a skill's folder. Skills are in ${U(h(e,`skills`))}/<skill>/.`)}if(!/^[a-z0-9-]+$/.test(i))throw Error(`There's no folder ${i}, and it isn't a skill's name.`);r.push(i)}return[...new Set(r)]}const yc=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function bc(e){let t=hc(e.find(e=>e.includes(`/`))??`.`),n=vc(t,e),r=await _c(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${U(t)}.`);let o=n.length>0?yc(r.problems,n):r.problems;for(let e of hs(o))console.log(e);let s=o.filter(e=>e.severity===`error`).length,c=o.length-s,l=n.length===1?n[0]:n.length>0?ms(n.length,`skill`):`The repository (${[ms(r.skills.length,`skill`),...r.flows?.length?[ms(r.flows.length,`flow`)]:[]].join(`, `)})`;s>0?(console.log(`\n${l}: ${ms(s,`error`)}`+(c?`, ${ms(c,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((o.length?`
288
- `:``)+`${l}: no errors`+(c?`, ${ms(c,`warning`)}`:``)+`.`)}const xc={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},Sc=/^[A-Za-z0-9._:-]{1,128}$/,Cc=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,wc=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Tc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Ec=/[\u0000-\u001f\u007f]/;function Dc(e){let t=e.trim(),n=wc.exec(t)??Tc.exec(t);if(!n)return null;let[,r,i]=n,a=i.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);if(a.length<2)return null;let o=[r,...a].join(`/`).toLowerCase();return Oc(o)?o:null}const Oc=e=>Cc.test(e)&&e.length<=xc.maxRepositoryLength,kc=e=>e.length>0&&e.length<=xc.maxBranchLength&&e.trim()===e&&!Ec.test(e),Ac={maxPerRequest:20,maxEntries:1e3,maxAgeDays:xc.maxAgeDays,maxFutureMs:xc.maxFutureMs,maxMachineNameLength:xc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},jc={inputTokens:`tokens.input`,outputTokens:`tokens.output`,cacheReadTokens:`tokens.cache_read`,cacheCreationTokens:`tokens.cache_creation`,costUsd:`cost.usd`,personSeconds:`active.person`,agentSeconds:`active.agent`,prompts:`prompts`,commits:`commits`,pullRequests:`pull_requests`},Mc=e=>typeof e==`string`&&e.length>0&&e.length<=Ac.maxModelLength&&!/\s/.test(e)&&!Ec.test(e),Nc={maxPerRequest:100,maxLinks:50,maxAgeDays:xc.maxAgeDays,maxFutureMs:xc.maxFutureMs,maxMachineNameLength:xc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},Pc=/^[1-9][0-9]{0,8}$/,Fc=/\s/,Ic=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function Lc(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Oc(t)?{kind:e,value:t}:null}case`branch`:case`issue`:case`pull_request`:{let t=n.indexOf(`#`);if(t<0)return null;let r=n.slice(0,t).toLowerCase(),i=n.slice(t+1);return Oc(r)&&(e===`branch`?kc(i):Pc.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return zc(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Nc.maxThreadLength&&!Fc.test(n)&&!Ec.test(n)?{kind:e,value:n}:null;case`session`:return Sc.test(n)?{kind:e,value:n}:null;default:return null}}function Rc(e){let t=e.trim();return Lc(`slack_thread`,t)??Lc(`thread`,t)}function zc(e){return e.length<=Nc.maxUrlLength&&Ic.test(e)}const Bc={sessionId:null,repository:null,branch:null,audience:null},Vc=e=>typeof e==`string`&&e?e:null;async function Hc(e,t,n=x(),r=null){let i=Vc(e),a=ha(t,n)!==null;if(!a&&!r)return{...Bc,sessionId:i};let{repository:o,branch:s}=await Wc(t),c=o?r?.repositories[o]:void 0,l=a?`any`:c?{organizationId:c}:null;return l?{sessionId:i,repository:o,branch:s,audience:l}:{...Bc,sessionId:i}}function Uc({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function Wc(e){let[t,n]=await Promise.all([qc(e,[`remote`,`get-url`,`origin`]),qc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?Dc(t):null,branch:n}}async function Gc(e,t){if(Kc.includes(t))return!0;let n=await qc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const Kc=[`main`,`master`,`develop`];function qc(e,t){return new Promise(n=>{try{_e(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const Jc=()=>h(V(),`sessions`),Yc=()=>h(V(),`pending-session-events.jsonl`),Xc=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Zc(e,t){switch(e.hook_event_name){case`SessionStart`:return t===`session`?`start`:null;case`SessionEnd`:return`end`;case`UserPromptSubmit`:case`PostToolUse`:case`Stop`:return`seen`;default:return null}}function Qc(e,t){let n=e.trimStart().split(`
289
- `)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim();if(!r)return[];let i=[],a=e=>{e&&!i.some(t=>t.kind===e.kind&&t.value===e.value)&&i.push(e)};for(let[,e,t,n]of r.matchAll(/https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/(issues|pull)\/(\d+)/g))a(Lc(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(Lc(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(Lc(`issue`,`${t}#${o}`)),i}function $c(e,t,n){let r=[],i=e=>{e&&!r.some(t=>t.kind===e.kind&&t.value===e.value)&&r.push(e)};for(let r of e.split(/&&|\|\||[;|\n]/)){let e=rl(r);for(;e[0]&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[0]);)e.shift();let[a,o,s,...c]=e;if(a!==`gh`)continue;if(s===`create`&&(o===`pr`||o===`issue`)){let e=RegExp(`https://(github\\.com/[^\\s/]+/[^\\s/]+)/${o===`pr`?`pull`:`issues`}/(\\d+)`).exec(t);e&&i(Lc(o===`pr`?`pull_request`:`issue`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`||!el.has(s??``))continue;let l=n,u=null;for(let[e,t]of c.entries()){let n=/^(?:-R|--repo)(?:=(.*))?$/.exec(t);if(n){let t=n[1]??c[e+1];t&&(l=nl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||tl.test(t))&&(u=t)}if(!u)continue;let d=tl.exec(u);d?i(Lc(`issue`,`${d[1]}#${d[2]}`)):l&&i(Lc(`issue`,`${l}#${u.replace(`#`,``)}`))}return r}const el=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),tl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/issues\/(\d+)/,nl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function rl(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function il(e){if(e.hook_event_name!==`PostToolUse`||e.tool_name!==`Bash`||typeof e.tool_input?.command!=`string`)return null;let t=e.tool_response?.stdout;return{command:e.tool_input.command,stdout:typeof t==`string`?t:``}}function al(e){if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`)return e.prompt;let t=e.tool_input;return e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`&&typeof t?.skill==`string`&&typeof t.args==`string`?`/${t.skill.replace(/^\//,``)} ${t.args}`:null}async function ol(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=Zc(t,n),l=i.sessionId;if(!c||!l||!Sc.test(l))return null;c===`end`&&t.reason===`clear`&&await fl(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(Lc(`repository`,i.repository)),i.branch&&!await Gc(r,i.branch)&&d(Lc(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=al(t);if(p&&f)for(let e of Qc(p,i.repository))d(e);let m=il(t);if(m&&f)for(let e of $c(m.command,m.stdout,i.repository))d(e);if(c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&f)for(let t of e.split(/\s+/))d(Rc(t));if(t.source===`clear`){let e=await pl(r,l,o,s);e&&d(Lc(`session`,e))}}let h=await ll(l),g=u.map(e=>`${e.kind} ${e.value}`),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await ul(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await ml(o),{sessionId:l,agent:e,machineId:await ga(),machineName:S()||null,type:c,occurredAt:o.toISOString(),links:u})}const sl=(e,t=[])=>ua(Yc(),e,t),cl=e=>h(Jc(),`${Xc(e)}.json`);async function ll(e){try{let t=JSON.parse(await O(cl(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[]}}catch{return{sentAt:0,links:[]}}}async function ul(e,t){await D(Jc(),{recursive:!0,mode:448}),await k(cl(e),JSON.stringify(t)+`
290
- `)}const dl=e=>h(Jc(),`cleared-${Xc(e)}.json`);async function fl(e,t,n){await D(Jc(),{recursive:!0,mode:448}),await k(dl(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
291
- `)}async function pl(e,t,n,r){let i=dl(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await le(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Ce(100)}}async function ml(e){try{for(let t of await oe(Jc())){let n=h(Jc(),t),{mtimeMs:r}=await ue(n);e.getTime()-r>6048e5&&await le(n,{force:!0})}}catch{}}function hl(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await Y(n.projectLock):null,a=await Y(J(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await is(r.userId),d=!u||n.repository!==null&&!Object.hasOwn(u.repositories,n.repository)||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await ss(r.api,r.userId,u,new Date(s))??u),(u&&gl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function gl(e,t,n,r){let{repository:i}=e,a=i&&Object.hasOwn(r.repositories,i)?r.repositories[i]:null;if(!a){let e=/* @__PURE__ */ new Map;for(let{id:n}of Object.values(t?.skills??{})){let t=r.skills[n];t&&e.set(t,(e.get(t)??0)+1)}a=[...e.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null}if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const _l={"claude_code.token.usage":{input:jc.inputTokens,output:jc.outputTokens,cacheRead:jc.cacheReadTokens,cacheCreation:jc.cacheCreationTokens},"claude_code.cost.usage":jc.costUsd,"claude_code.active_time.total":{user:jc.personSeconds,cli:jc.agentSeconds},"claude_code.commit.count":jc.commits,"claude_code.pull_request.count":jc.pullRequests};function vl(e){let t=[];for(let n of Sl(X(e,`resourceMetrics`)))for(let e of Sl(X(n,`scopeMetrics`)))for(let n of Sl(X(e,`metrics`))){let e=X(n,`name`),r=typeof e==`string`?_l[e]:void 0,i=X(n,`sum`);if(!r||!i)continue;let a=X(i,`aggregationTemporality`)===2;for(let n of Sl(X(i,`dataPoints`))){let i=Sl(X(n,`attributes`)),o=e=>Cl(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=wl(X(n,`asDouble`)??X(n,`asInt`)),u=Tl(X(n,`startTimeUnixNano`)),d=Tl(X(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:bl(e,i,a?u:null),metric:c,model:xl(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function yl(e){let t=[];for(let n of Sl(X(e,`resourceLogs`)))for(let e of Sl(X(n,`scopeLogs`)))for(let n of Sl(X(e,`logRecords`))){let e=Sl(X(n,`attributes`)),r=Cl(e,`event.name`)??X(X(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Cl(e,`session.id`),a=Tl(X(n,`timeUnixNano`))??Tl(X(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function bl(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return pe(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const xl=e=>Mc(e)?e:null,X=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Sl=e=>Array.isArray(e)?e:[];function Cl(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function wl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Tl(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const El=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Dl(e){let t=()=>h(eo(),e),n=e=>h(t(),`${El(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
292
- `)},async list(){let e=[];try{e=await oe(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(h(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await oe(t())){let r=h(t(),n);e-(await ue(r)).mtimeMs>6048e5&&await le(r,{force:!0})}}catch{}}}}const Ol=Dl(`sessions`),kl=e=>Ol.write(e.sessionId,e);async function Al(e){let t=await Ol.read(e);return t?.sessionId===e?t:null}const jl=(e=Date.now())=>Ol.forgetOld(e),Ml=Dl(`sent`),Nl=(e,t,n=/* @__PURE__ */ new Date)=>Ml.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Pl=e=>Ml.read(e),Fl=async()=>(await Ml.list()).sort((e,t)=>t.at.localeCompare(e.at)),Il=(e=Date.now())=>Ml.forgetOld(e),Ll=(e,t)=>({sessionId:e,epoch:t,series:{},prompts:0,lastAt:t});function Rl(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n];if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}return e.lastAt=Math.max(e.lastAt,s),!0}function zl(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)};for(let n of Object.values(e.series))r({metric:n.metric,model:n.model,skillId:n.skillName!==null&&Object.hasOwn(t.skillIds,n.skillName)?t.skillIds[n.skillName]:null,start:new Date(n.start).toISOString(),value:n.value});return e.prompts>0&&r({metric:jc.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,Ac.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const Bl=Dl(`state`);function Vl(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=Hl(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);Rl(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await Bl.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await Bl.write(e.state.sessionId,e.state))}}}async function Hl(e,t){let n=await Bl.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Ll(e,t),unsaved:!1}}const Ul=(e=Date.now())=>Bl.forgetOld(e),Wl=16777216,Gl=()=>h(V(),`pending-session-usage.jsonl`);async function Kl(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=Vl(),s=hl(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new R(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!fa(e))for(let e of t)await Nl(e,`refused`);throw e}for(let e of t)await Nl(e,`sent`)}),p=(e=[])=>ua(Gl(),f,e,{batch:Ac.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await Al(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=zl(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await ga(),machineName:S()||null,skillIds:i.skillIds});a.usage.length!==0&&(await Nl(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),ya(h),sl(g)]);function v(e){let t=Yl(e.activations),n=Yl(e.sessionEvents);return u(()=>Promise.all([t.length>0&&ya(h,t),n.length>0&&sl(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(te(),!C(t.headers[`x-agent-kit-collector`]))return t.resume(),Z(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return Z(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),Z(n,404,{});if(i===`/stop`){t.resume(),Z(n,200,{}),se({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),Z(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),Z(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),Z(n,415,{message:`Send JSON.`});let a=await Jl(t);if(!a.ok)return Z(n,a.status,{});i===`/report`?(Z(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?vl(a.json):yl(a.json)),b(),Z(n,200,{}))}let C=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ge(t,c)},w=xe((e,t)=>{x(e,t).catch(()=>{t.headersSent||Z(t,500,{})})});if(!await new Promise(t=>{w.once(`error`,()=>t(!1)),w.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let T=null,E=Date.now(),ee=e=>{T&&clearTimeout(T),T=setTimeout(()=>void ne(),e)};function te(){E=Date.now(),ee(i)}async function ne(){let e=E,t=!1;if(await u(async()=>{let e=[Gl(),va(),Yc()];t=(await Promise.all(e.map(da))).some(Boolean)||(await o.dirty()).length>0}),oe||E!==e)return;let n=Date.now()-E;t&&n<a?ee(Math.max(1,Math.min(i,a-n))):se()}te();let re=setInterval(()=>void u(m),t),ie=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await jl(e),await Ul(e),await Il(e),await o.resume()});let D=()=>u(m).then(()=>u(_)),ae=()=>{},O=new Promise(e=>ae=e),oe=null;function se({send:e=!0}={}){return oe??=(async()=>{T&&clearTimeout(T),y&&clearTimeout(y),clearInterval(re),clearInterval(ie);let t=new Promise(e=>w.close(()=>e()));w.closeIdleConnections(),await(e?D():u(()=>o.save())),w.closeAllConnections(),await t,ae()})(),oe}return{port:w.address().port,flush:D,stop:se,stopped:O}}const ql=n(Se);async function Jl(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>Wl)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await ql(r,{maxOutputLength:Wl})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function Z(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const Yl=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function Xl(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await ro();await(await Kl({port:t,secret:n,apiUrl:B(),login:async()=>{let e=await H();return e?{api:z(B(),e.token),userId:e.user.id}:null}}))?.stopped}const Zl=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Ql=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function $l(e){let t=0;for(let[n]of e.matchAll(Ql)){let e=n[0];if(e===`
293
- `)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)Zl.test(t)&&e++;let r=[...n].length-e;t+=e+Math.ceil(r/6)}else/\p{N}/u.test(e)?t+=Math.ceil(n.length/3):t+=1}return t}function eu(e){return{always:e.description,max:e.description+e.body+e.files}}function tu(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=eu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function nu(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${iu((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${iu((e/1e6).toFixed(1))}M`}const ru=(e,t)=>`${t===`estimate`?`~`:``}${nu(e)}`,iu=e=>e.replace(/\.0$/,``),au={high:15,medium:10,low:5},ou=5e3,su=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function cu(e){let t=tr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&su.has(n)}const lu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,uu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function du(e,t){let n=t(`SKILL.md`)??``,r=bi(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([W]),f=/* @__PURE__ */ new Set,p=!1,m=[W];for(;m.length>0;){let n=m.shift(),r=n===`SKILL.md`?s:t(n);if(r===void 0)cu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Su(r)){let t=nr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Cu(r,n,t.path)&&(d.add(t.path),cu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!lu.test(tr(e))).filter(e=>!tr(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(`
294
- `).length,bodyTokens:$l(c),hasExamples:ku(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function fu(e,t,n=/* @__PURE__ */ new Date){let r=[...yu(e),...t?bu(t,n):[]];return{score:pu(r),checks:hu(r)}}function pu(e){let t=e.reduce((e,t)=>e+au[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+au[t.severity],0);return Math.round(n/t*100)}const mu=[`high`,`medium`,`low`];function hu(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:mu.indexOf(e.severity)-mu.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}),gu=/\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,_u=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,vu=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function yu(e){let t=[],n=e.description??``;e.hasWhenToUse||gu.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(_u);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`)),vu.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=xu(e.bodyTokens);return e.bodyLines===0?t.push($(`body-length`,`medium`,`${W} has no instructions`,`Write the instructions below the frontmatter.`)):e.bodyLines>500||e.bodyTokens>ou?t.push($(`body-length`,`medium`,`${W} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${xu(ou)}; move reference material into files ${W} 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 ${Au(e.missingFiles.length,`missing file`)}: ${ju(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`,`${Au(e.unusedFiles.length,`file`)} nothing mentions: ${ju(e.unusedFiles)}`,`Mention them in ${W}, saying when to read or run them, or delete them.`))),t}function bu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,Au(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Au(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${Au(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 ${Au(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 xu(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Su(e){let t=[];for(let n of e.matchAll(uu)){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 Cu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,tr(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=wu(t,n);return a&&r.add(a),[...r].some(t=>Tu(e,t))}function wu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Tu(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 Eu=/^(```|~~~)/m,Du=/^#{1,6}[^\n]*\bexamples?\b/im,Ou=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function ku(e){return Eu.test(e)||Du.test(e)||Ou.test(e)}function Au(e,t){return`${e} ${t}${e===1?``:`s`}`}function ju(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Mu=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Nu(e){try{return(await ue(h(e,W))).isFile()}catch{return!1}}async function Pu(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await oe(i,{withFileTypes:!0})){let o=h(i,a.name);if(a.isDirectory()){Mu.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=_(e,o).split(y).join(`/`),{size:c}=await ue(o);t.push({path:s,size:c}),(s===`SKILL.md`||cu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),fu(du(t,e=>n.get(e)),null)}function Fu(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(`
295
- `)}async function Iu(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=v(t??`.`);if(await Nu(n)){let e=await Pu(n),r=t===void 0?`This folder`:U(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(Fu(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 Xa(),i=Tn(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(`${jn(a)} v${a.version}`),console.log(Fu(o))}async function Lu(e){Ht(`agent kit`);let t=await Ya();t?F.success(`Logged in as ${Za(t.user)}`):t=await Ja();let n=z(B(),t.token),r=await n.listSkills();if(r.length===0){I(Qa(t.webUrl));return}let i=!e.yes;if(i&&!gn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await yn(e.global,i),o=await vn(e.agent,i),s=i?_n(await Bt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:jn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await zo(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});I(`Installed in ${c.map(U).join(`, `)}`)}async function Ru(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ga();return;case`on`:{if(await Rn({heartbeat:!0}),!await H()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!ca()){F.warn(`Run it from the published CLI to install the timer.`);return}await Ka();let e=await za(B()),t=(await Wa())?.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 Rn({heartbeat:!1}),await Ra(B()),F.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await Ln()).heartbeat!==!1,t=await za(B()),n=await Wa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?Pa(B()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
296
- 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 zu=2e3;async function Bu(e,t={},n=300){let{port:r,secret:i}=await ro();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[$a]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function Vu(){let e=await Bu(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function Hu(e,t,n=Ho){let r=await Vu();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await Wu(),u(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function Uu(e){return(await Bu(`/report`,{method:`POST`,body:JSON.stringify(e)},zu))?.status===202}async function Wu({send:e=!0}={}){return(await Bu(e?`/stop`:`/stop?send=false`,{method:`POST`},zu))?.ok??!1}const Gu=5e3;async function Ku(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await Yu()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Yo(ca()??sa()),await za(B())||await Ga();return}if(zn()||(await Ln()).telemetry===!1)return;let o=await H();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await is(o.user.id),u=c?{...Bc,sessionId:Vc(r.session_id)}:await Hc(r.session_id,s,void 0,l),d=z(B(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await Ju(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await Hu(ca()??sa(),B());let p=await ol(e,r,a,s,u,{now:i}),m=To(r),h=m&&await ma(m.name,e,s),g=m&&h&&await _a(h,e,m.trigger,Uc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&os(l,i,h?h.id:null)&&ss(d,o.user.id,l,i),(p||g)&&qu(d,p,g)])}catch{}}async function qu(e,t,n){await Uu({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&sl(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(Gu))},t),n&&ya(async t=>{await e.reportActivations(t,AbortSignal.timeout(Gu))},n)])}async function Ju(e,t,n){let{repository:r,branch:i}=await Wc(n),a=ha(n,x());(r||a)&&await kl({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function Yu(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function Xu(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Ht(`agent kit`);let n=v(e[0]);if(!u(h(n,`SKILL.md`)))throw Error(`${U(n)} has no ${W}, so it isn't a skill.`);let r=f(n);if(!/^[a-z0-9-]+$/.test(r)||r===`report-session-issue`)throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await vn(t.agent,!t.yes),o=on(a,i),s=o.map(e=>h(e,r));if(s.includes(n))throw Error(`${U(n)} is already where your agents read it.`);let c=(await Y(J(i))).skills[r];for(let e of s)if(u(e)&&!await Jn(e)&&!c)throw Error(`${U(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await qn(z(B(),(await H())?.token),r,c,o);if(e&&!await Jn(e.folder))throw Error(`${U(e.folder)} has edits that aren't in agent kit (${Gn(e.paths)}). Copy them to ${U(n)} and delete them there first.`)}for(let e of s)await Xn(e,n);F.success(`${r}: ${s.map(U).join(`, `)} → ${U(n)}`);let l=i===`project`?await Zu(on(a,`global`),r,n):[];l.length>0&&F.warn(`You also have ${r} in ${l.map(U).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await Qu(n,r),I(`${l.length>0?`This project's agents would use`:`Your agents use`} ${U(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function Zu(e,t,n){let r=[];for(let i of e){let e=h(i,t);u(e)&&await Jn(e)!==n&&r.push(e)}return r}async function Qu(e,t){let n;try{n=hc(e)}catch{return}if(v(n,`skills`,t)!==e)return;let r=yc((await _c(n)).problems,[t]);r.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...hs(r)].join(`
297
- `))}function $u(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?ru(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[jn(e),ed(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[td(`project`,r,e),td(`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=tu(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}${nu(c.always)} always · ${l}${nu(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 ed(e){return[`v${e.version}`,...Yt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function td(e,t,n){if(!t)return null;let r=Ji(t),{version:i}=$t(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 nd(){let{api:e,credentials:t}=await Xa(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(Qa(t.webUrl));return}let i=await Y(J(`project`)),a=await Y(J(`global`));for(let e of $u(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>rd(e).length));for(let e of r){let t=[id(i,e)&&`in project`,id(a,e)&&`in global`].filter(Boolean);console.log(`${rd(e).padEnd(o)} ${ad(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const rd=e=>`${bn}${jn(e)}`,id=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function ad(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 od(e,t){switch(e){case void 0:case`status`:{let e=(await Wa())?.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 Xa(),r=await Da(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await Ln()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Ga()?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 sd(){Ht(`agent kit`);let e=await Ya().catch(()=>null);if(e){let t=Za(e.user);if(!gn()){I(`Already logged in as ${t}.`);return}if(!_n(await Lt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Ja();e&&await z(B(),e.token).logout().catch(()=>{}),I(await ud(t.token,t.webUrl))}async function cd(e=process.stdin){Ht(`agent kit`);let t=await ld(e);if(!t)throw Error(`Give it the bot's token on stdin, like ${L(`login --token`)} < bot-token.`);let n;try{n=await z(B(),t).me()}catch(e){throw e instanceof R&&e.status===401?Error(`This token doesn't work: it's wrong, or the bot was revoked.`):e}let r=await H();await Fn({token:t,user:n,webUrl:Mn(B())}),r&&r.token!==t&&await z(B(),r.token).logout().catch(()=>{}),await Ka(),I(`Logged in as ${Za(n)}.`)}async function ld(e){if(e.isTTY)return _n(await Ut({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function ud(e,t){return(await z(B(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${Qa(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function dd(){let e=await H();e?(await z(B(),e.token).logout().catch(()=>{}),await Fn(null),console.log(`Logged out ${Za(e.user)}.`)):console.log(`You're not logged in.`)}async function fd(){let e=await Ya();e?console.log(Za(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const pd=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function md(e){let t=await hd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${mn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${L(`check <skill>`)}`,` 3. Try it in your agent: ${L(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${L(`add <skill>`)} or ${L(`update`)}.`),Error(r.join(`
298
- `))}async function hd(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repository?.fullName??null).catch(()=>null)));return[...new Set(n.filter(e=>e!==null))]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const gd={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},_d=[{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}],vd=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,yd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,bd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),xd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Sd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Cd(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(Sd(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}_])${Sd(e.find)}(?![\\p{L}\\p{N}_])`:Sd(e.find),`giu`)}));function a(e){let t=e;for(let e of _d)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(vd,e=>xd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(yd,e=>bd.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 wd=e=>e.map(e=>JSON.stringify(e)).join(`
287
+ `));for(let{path:a,from:o,to:s}of Di(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=nr(W,a);if(e===null){let e=Oi(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 rc(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 ic(e){return{severity:`error`,path:null,message:e}}function ac(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function oc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sc(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const cc=`channels.yaml`;function lc(e,t){let n=`${t}/`,r=/* @__PURE__ */ new Map,i=[];for(let t of e){if(!t.path.startsWith(n))continue;let e=t.path.slice(n.length),a=e.indexOf(`/`);if(a===-1){i.push(e);continue}let o=e.slice(0,a),s=r.get(o)??[];s.push({path:e.slice(a+1),size:t.size}),r.set(o,s)}return{folders:[...r].sort(([e],[t])=>e.localeCompare(t)),loose:i}}function uc(e){return lc(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===W)).map(([e])=>e)}function dc(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(uc(t));e.truncated&&r.push({severity:`warning`,path:null,message:`The repository has more files than GitHub lists at once, so some weren't checked.`}),i.size>300&&r.push({severity:`warning`,path:`skills`,message:`Only the first 300 skills were checked.`});let a=lc(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${W} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${W}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of Ys({files:t,skillMd:s,skills:n}))o.push({severity:e.severity,path:e.path===null?a:`${a}/${e.path}`,...e.path===`SKILL.md`&&e.from!==void 0?{line:ps(s,e.from)}:{},message:e.message});let r=xi(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${W}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:xi(s).description,files:t.length,errors:o.filter(e=>e.severity===`error`).length,warnings:o.filter(e=>e.severity===`warning`).length}}),o=(e,t,n)=>{for(let i of n)t.some(e=>e.path===i)||r.push({severity:`error`,path:e,message:`It needs a ${i}.`})},s=lc(t,`evals`).folders.map(([e])=>{let n=`evals/${e}`;i.has(e)||r.push({severity:`warning`,path:n,message:`There's no skill named “${e}” in skills/, so these evals have nothing to test.`});let a=lc(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=lc(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=lc(t,`${i}/tasks`).folders;for(let[e,t]of a)o(`${i}/tasks/${e}`,t,[`task.yaml`,`prompt.md`]);return a.length===0&&r.push({severity:`warning`,path:i,message:`It has no tasks yet: add one in tasks/<task>/.`}),{name:e,tasks:a.length}});if(typeof e.channelsText==`string`){let t=bs(e.channelsText),n=(e,t)=>r.push({severity:e,path:cc,message:t});if(`error`in t)n(`error`,`${t.error} No channel was changed.`);else{for(let e of t.problems)n(`error`,e);for(let e of t.pins.keys())i.has(e)||n(`warning`,`There's no skill named “${e}” in skills/, so its channels set nothing.`)}}let l=[];for(let n of lc(t,`kits`).loose){let t=`kits/${n}`,a=_s(t);if(a===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are kits: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}l.push(a);let o=(e,n)=>r.push({severity:e,path:t,message:n}),s=gs(a);if(!s.ok||s.name!==a){o(`error`,`“${a}” can't be a kit's name, so this file isn't read. ${s.ok?`Take out the spaces.`:s.message}`);continue}let c=e.kitTexts?.get(t);if(c===void 0)continue;let u=vs(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}let u=[],d=[];for(let n of lc(t,Ds).loose){let t=`${Ds}/${n}`,i=As(t);if(i===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are flows: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}u.push(i);let a=Ms(i);if(a){r.push({severity:`error`,path:t,message:a});continue}let o=e.flowTexts?.get(t);if(o===void 0)continue;let s=Fs(o);for(let e of s.roles)d.push({path:t,...e.line===null?{}:{line:e.line},name:e.name});for(let e of s.problems)r.push({severity:`error`,path:t,...e.line===null?{}:{line:e.line},message:e.message})}return{skills:a,evals:s,benchmarks:c,fixtures:lc(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),flows:u.sort((e,t)=>e.localeCompare(t)),flowRoles:d,channels:t.some(e=>e.path===cc),problems:fc(r)}}const fc=e=>e.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0));function pc(e,t){let n=(e.flowRoles??[]).filter(e=>!t.has(e.name));return n.length===0?e:{...e,problems:fc([...e.problems,...n.map(e=>({severity:`warning`,path:e.path,...e.line===void 0?{}:{line:e.line},message:`There's no role “${e.name}” in the organization. Name it in Settings → Roles, or fix the name.`}))])}}const mc=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],hc=e=>{try{return d(e).isDirectory()}catch{return!1}};function gc(e){let t;for(let n=v(e);;n=m(n)){if(t??=hc(h(n,`skills`))?n:void 0,u(h(n,`.git`))){if(hc(h(n,`skills`)))return n;throw Error(`${U(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(m(n)===n)break}if(t)return t;throw Error(`There's no skills/ folder here. Run this in a clone of your organization's repository.`)}async function _c(e){let t=[];for(let n of mc){let r=h(e,n);if(hc(r))for(let n of await oe(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=h(n.parentPath,n.name),i=_(e,r).split(y).join(`/`);Vn(i)||t.push({path:i,size:(await ue(r)).size})}}return u(h(e,`channels.yaml`))&&t.push({path:cc,size:(await ue(h(e,cc))).size}),t}async function vc(e){let t=await _c(e),n=/* @__PURE__ */ new Map;for(let r of uc(t))n.set(r,await O(h(e,`skills`,r,W),`utf8`));let r=t.some(e=>e.path===`channels.yaml`)?await O(h(e,cc),`utf8`):null,i=/* @__PURE__ */ new Map;for(let{path:n}of t)As(n)!==null&&i.set(n,await O(h(e,n),`utf8`));return dc({files:t,skillMds:n,channelsText:r,flowTexts:i})}async function yc(e,t,n=1e4){if(!e.flowRoles?.length)return{scan:e,unchecked:null};let r=t=>({scan:e,unchecked:`Roles in flows weren't checked: ${t}`});if(!t)return r(`log in with ${L(`login`)} to check them against your organization's.`);let i=AbortSignal.timeout(n);try{let n=t.organizationId;if(!n){let e=await t.api.listOrganizations(i);if(e.length===0)return r(`you're in no organization.`);if(e.length>1)return r(`you're in more than one organization. Pick yours with ${L(`org use`)}.`);n=e[0].id}let a=await t.api.listRoles(n,i);return{scan:pc(e,new Set(a.map(e=>e.name))),unchecked:null}}catch(e){return r(`couldn't get your organization's roles (${i.aborted?`agent kit didn't answer in time`:e instanceof Error?e.message:String(e)}).`)}}function bc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=v(n,i);if(hc(t)){if(t===e||t===h(e,`skills`))return[];if(m(t)===h(e,`skills`)){r.push(f(t));continue}let n=_(h(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(y)[0]);continue}throw Error(`${U(t)} isn't a skill's folder. Skills are in ${U(h(e,`skills`))}/<skill>/.`)}if(!/^[a-z0-9-]+$/.test(i))throw Error(`There's no folder ${i}, and it isn't a skill's name.`);r.push(i)}return[...new Set(r)]}const xc=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function Sc(){let e=await H();return e&&{api:z(B(),e.token),organizationId:e.organizationId}}async function Cc(e){let t=gc(e.find(e=>e.includes(`/`))??`.`),n=bc(t,e),r=await vc(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${U(t)}.`);let{scan:o,unchecked:s}=n.length===0?await yc(r,await Sc()):{scan:r,unchecked:null},c=n.length>0?xc(o.problems,n):o.problems;for(let e of hs(c))console.log(e);s&&console.log(`${c.length?`
288
+ `:``}${s}`);let l=c.filter(e=>e.severity===`error`).length,u=c.length-l,d=n.length===1?n[0]:n.length>0?ms(n.length,`skill`):`The repository (${[ms(o.skills.length,`skill`),...o.flows?.length?[ms(o.flows.length,`flow`)]:[]].join(`, `)})`;l>0?(console.log(`\n${d}: ${ms(l,`error`)}`+(u?`, ${ms(u,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((c.length||s?`
289
+ `:``)+`${d}: no errors`+(u?`, ${ms(u,`warning`)}`:``)+`.`)}const wc={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},Tc=/^[A-Za-z0-9._:-]{1,128}$/,Ec=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,Dc=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Oc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,kc=/[\u0000-\u001f\u007f]/;function Ac(e){let t=e.trim(),n=Dc.exec(t)??Oc.exec(t);if(!n)return null;let[,r,i]=n,a=i.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);if(a.length<2)return null;let o=[r,...a].join(`/`).toLowerCase();return jc(o)?o:null}const jc=e=>Ec.test(e)&&e.length<=wc.maxRepositoryLength,Mc=e=>e.length>0&&e.length<=wc.maxBranchLength&&e.trim()===e&&!kc.test(e),Nc={maxPerRequest:20,maxEntries:1e3,maxAgeDays:wc.maxAgeDays,maxFutureMs:wc.maxFutureMs,maxMachineNameLength:wc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Pc={inputTokens:`tokens.input`,outputTokens:`tokens.output`,cacheReadTokens:`tokens.cache_read`,cacheCreationTokens:`tokens.cache_creation`,costUsd:`cost.usd`,personSeconds:`active.person`,agentSeconds:`active.agent`,prompts:`prompts`,commits:`commits`,pullRequests:`pull_requests`},Fc=e=>typeof e==`string`&&e.length>0&&e.length<=Nc.maxModelLength&&!/\s/.test(e)&&!kc.test(e),Ic={maxPerRequest:100,maxLinks:50,maxAgeDays:wc.maxAgeDays,maxFutureMs:wc.maxFutureMs,maxMachineNameLength:wc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},Lc=/^[1-9][0-9]{0,8}$/,Rc=/\s/,zc=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function Bc(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return jc(t)?{kind:e,value:t}:null}case`branch`:case`issue`:case`pull_request`:{let t=n.indexOf(`#`);if(t<0)return null;let r=n.slice(0,t).toLowerCase(),i=n.slice(t+1);return jc(r)&&(e===`branch`?Mc(i):Lc.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return Hc(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Ic.maxThreadLength&&!Rc.test(n)&&!kc.test(n)?{kind:e,value:n}:null;case`session`:return Tc.test(n)?{kind:e,value:n}:null;default:return null}}function Vc(e){let t=e.trim();return Bc(`slack_thread`,t)??Bc(`thread`,t)}function Hc(e){return e.length<=Ic.maxUrlLength&&zc.test(e)}const Uc={sessionId:null,repository:null,branch:null,audience:null},Wc=e=>typeof e==`string`&&e?e:null;async function Gc(e,t,n=x(),r=null){let i=Wc(e),a=ha(t,n)!==null;if(!a&&!r)return{...Uc,sessionId:i};let{repository:o,branch:s}=await qc(t),c=o?r?.repositories[o]:void 0,l=a?`any`:c?{organizationId:c}:null;return l?{sessionId:i,repository:o,branch:s,audience:l}:{...Uc,sessionId:i}}function Kc({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function qc(e){let[t,n]=await Promise.all([Xc(e,[`remote`,`get-url`,`origin`]),Xc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?Ac(t):null,branch:n}}async function Jc(e,t){if(Yc.includes(t))return!0;let n=await Xc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const Yc=[`main`,`master`,`develop`];function Xc(e,t){return new Promise(n=>{try{_e(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const Zc=()=>h(V(),`sessions`),Qc=()=>h(V(),`pending-session-events.jsonl`),$c=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function el(e,t){switch(e.hook_event_name){case`SessionStart`:return t===`session`?`start`:null;case`SessionEnd`:return`end`;case`UserPromptSubmit`:case`PostToolUse`:case`Stop`:return`seen`;default:return null}}function tl(e,t){let n=e.trimStart().split(`
290
+ `)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim();if(!r)return[];let i=[],a=e=>{e&&!i.some(t=>t.kind===e.kind&&t.value===e.value)&&i.push(e)};for(let[,e,t,n]of r.matchAll(/https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/(issues|pull)\/(\d+)/g))a(Bc(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(Bc(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(Bc(`issue`,`${t}#${o}`)),i}function nl(e,t,n){let r=[],i=e=>{e&&!r.some(t=>t.kind===e.kind&&t.value===e.value)&&r.push(e)};for(let r of e.split(/&&|\|\||[;|\n]/)){let e=ol(r);for(;e[0]&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[0]);)e.shift();let[a,o,s,...c]=e;if(a!==`gh`)continue;if(s===`create`&&(o===`pr`||o===`issue`)){let e=RegExp(`https://(github\\.com/[^\\s/]+/[^\\s/]+)/${o===`pr`?`pull`:`issues`}/(\\d+)`).exec(t);e&&i(Bc(o===`pr`?`pull_request`:`issue`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`||!rl.has(s??``))continue;let l=n,u=null;for(let[e,t]of c.entries()){let n=/^(?:-R|--repo)(?:=(.*))?$/.exec(t);if(n){let t=n[1]??c[e+1];t&&(l=al(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||il.test(t))&&(u=t)}if(!u)continue;let d=il.exec(u);d?i(Bc(`issue`,`${d[1]}#${d[2]}`)):l&&i(Bc(`issue`,`${l}#${u.replace(`#`,``)}`))}return r}const rl=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),il=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/issues\/(\d+)/,al=e=>e.split(`/`).length===2?`github.com/${e}`:e;function ol(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function sl(e){if(e.hook_event_name!==`PostToolUse`||e.tool_name!==`Bash`||typeof e.tool_input?.command!=`string`)return null;let t=e.tool_response?.stdout;return{command:e.tool_input.command,stdout:typeof t==`string`?t:``}}function cl(e){if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`)return e.prompt;let t=e.tool_input;return e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`&&typeof t?.skill==`string`&&typeof t.args==`string`?`/${t.skill.replace(/^\//,``)} ${t.args}`:null}async function ll(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=el(t,n),l=i.sessionId;if(!c||!l||!Tc.test(l))return null;c===`end`&&t.reason===`clear`&&await hl(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(Bc(`repository`,i.repository)),i.branch&&!await Jc(r,i.branch)&&d(Bc(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=cl(t);if(p&&f)for(let e of tl(p,i.repository))d(e);let m=sl(t);if(m&&f)for(let e of nl(m.command,m.stdout,i.repository))d(e);if(c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&f)for(let t of e.split(/\s+/))d(Vc(t));if(t.source===`clear`){let e=await gl(r,l,o,s);e&&d(Bc(`session`,e))}}let h=await fl(l),g=u.map(e=>`${e.kind} ${e.value}`),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await pl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await _l(o),{sessionId:l,agent:e,machineId:await ga(),machineName:S()||null,type:c,occurredAt:o.toISOString(),links:u})}const ul=(e,t=[])=>ua(Qc(),e,t),dl=e=>h(Zc(),`${$c(e)}.json`);async function fl(e){try{let t=JSON.parse(await O(dl(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[]}}catch{return{sentAt:0,links:[]}}}async function pl(e,t){await D(Zc(),{recursive:!0,mode:448}),await k(dl(e),JSON.stringify(t)+`
291
+ `)}const ml=e=>h(Zc(),`cleared-${$c(e)}.json`);async function hl(e,t,n){await D(Zc(),{recursive:!0,mode:448}),await k(ml(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
292
+ `)}async function gl(e,t,n,r){let i=ml(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await le(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Ce(100)}}async function _l(e){try{for(let t of await oe(Zc())){let n=h(Zc(),t),{mtimeMs:r}=await ue(n);e.getTime()-r>6048e5&&await le(n,{force:!0})}}catch{}}function vl(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await Y(n.projectLock):null,a=await Y(J(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await is(r.userId),d=!u||n.repository!==null&&!Object.hasOwn(u.repositories,n.repository)||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await ss(r.api,r.userId,u,new Date(s))??u),(u&&yl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function yl(e,t,n,r){let{repository:i}=e,a=i&&Object.hasOwn(r.repositories,i)?r.repositories[i]:null;if(!a){let e=/* @__PURE__ */ new Map;for(let{id:n}of Object.values(t?.skills??{})){let t=r.skills[n];t&&e.set(t,(e.get(t)??0)+1)}a=[...e.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null}if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const bl={"claude_code.token.usage":{input:Pc.inputTokens,output:Pc.outputTokens,cacheRead:Pc.cacheReadTokens,cacheCreation:Pc.cacheCreationTokens},"claude_code.cost.usage":Pc.costUsd,"claude_code.active_time.total":{user:Pc.personSeconds,cli:Pc.agentSeconds},"claude_code.commit.count":Pc.commits,"claude_code.pull_request.count":Pc.pullRequests};function xl(e){let t=[];for(let n of Tl(Z(e,`resourceMetrics`)))for(let e of Tl(Z(n,`scopeMetrics`)))for(let n of Tl(Z(e,`metrics`))){let e=Z(n,`name`),r=typeof e==`string`?bl[e]:void 0,i=Z(n,`sum`);if(!r||!i)continue;let a=Z(i,`aggregationTemporality`)===2;for(let n of Tl(Z(i,`dataPoints`))){let i=Tl(Z(n,`attributes`)),o=e=>El(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Dl(Z(n,`asDouble`)??Z(n,`asInt`)),u=Ol(Z(n,`startTimeUnixNano`)),d=Ol(Z(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Cl(e,i,a?u:null),metric:c,model:wl(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Sl(e){let t=[];for(let n of Tl(Z(e,`resourceLogs`)))for(let e of Tl(Z(n,`scopeLogs`)))for(let n of Tl(Z(e,`logRecords`))){let e=Tl(Z(n,`attributes`)),r=El(e,`event.name`)??Z(Z(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=El(e,`session.id`),a=Ol(Z(n,`timeUnixNano`))??Ol(Z(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Cl(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return pe(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const wl=e=>Fc(e)?e:null,Z=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Tl=e=>Array.isArray(e)?e:[];function El(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Dl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Ol(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const kl=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Al(e){let t=()=>h(eo(),e),n=e=>h(t(),`${kl(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
293
+ `)},async list(){let e=[];try{e=await oe(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(h(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await oe(t())){let r=h(t(),n);e-(await ue(r)).mtimeMs>6048e5&&await le(r,{force:!0})}}catch{}}}}const jl=Al(`sessions`),Ml=e=>jl.write(e.sessionId,e);async function Nl(e){let t=await jl.read(e);return t?.sessionId===e?t:null}const Pl=(e=Date.now())=>jl.forgetOld(e),Fl=Al(`sent`),Il=(e,t,n=/* @__PURE__ */ new Date)=>Fl.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Ll=e=>Fl.read(e),Rl=async()=>(await Fl.list()).sort((e,t)=>t.at.localeCompare(e.at)),zl=(e=Date.now())=>Fl.forgetOld(e),Bl=(e,t)=>({sessionId:e,epoch:t,series:{},prompts:0,lastAt:t});function Vl(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n];if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}return e.lastAt=Math.max(e.lastAt,s),!0}function Hl(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)};for(let n of Object.values(e.series))r({metric:n.metric,model:n.model,skillId:n.skillName!==null&&Object.hasOwn(t.skillIds,n.skillName)?t.skillIds[n.skillName]:null,start:new Date(n.start).toISOString(),value:n.value});return e.prompts>0&&r({metric:Pc.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,Nc.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const Ul=Al(`state`);function Wl(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=Gl(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);Vl(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await Ul.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await Ul.write(e.state.sessionId,e.state))}}}async function Gl(e,t){let n=await Ul.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Bl(e,t),unsaved:!1}}const Kl=(e=Date.now())=>Ul.forgetOld(e),ql=16777216,Jl=()=>h(V(),`pending-session-usage.jsonl`);async function Yl(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=Wl(),s=vl(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new R(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!fa(e))for(let e of t)await Il(e,`refused`);throw e}for(let e of t)await Il(e,`sent`)}),p=(e=[])=>ua(Jl(),f,e,{batch:Nc.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await Nl(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=Hl(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await ga(),machineName:S()||null,skillIds:i.skillIds});a.usage.length!==0&&(await Il(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),ya(h),ul(g)]);function v(e){let t=$l(e.activations),n=$l(e.sessionEvents);return u(()=>Promise.all([t.length>0&&ya(h,t),n.length>0&&ul(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(te(),!C(t.headers[`x-agent-kit-collector`]))return t.resume(),Ql(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return Ql(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),Ql(n,404,{});if(i===`/stop`){t.resume(),Ql(n,200,{}),se({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),Ql(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),Ql(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),Ql(n,415,{message:`Send JSON.`});let a=await Zl(t);if(!a.ok)return Ql(n,a.status,{});i===`/report`?(Ql(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?xl(a.json):Sl(a.json)),b(),Ql(n,200,{}))}let C=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ge(t,c)},w=xe((e,t)=>{x(e,t).catch(()=>{t.headersSent||Ql(t,500,{})})});if(!await new Promise(t=>{w.once(`error`,()=>t(!1)),w.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let T=null,E=Date.now(),ee=e=>{T&&clearTimeout(T),T=setTimeout(()=>void ne(),e)};function te(){E=Date.now(),ee(i)}async function ne(){let e=E,t=!1;if(await u(async()=>{let e=[Jl(),va(),Qc()];t=(await Promise.all(e.map(da))).some(Boolean)||(await o.dirty()).length>0}),oe||E!==e)return;let n=Date.now()-E;t&&n<a?ee(Math.max(1,Math.min(i,a-n))):se()}te();let re=setInterval(()=>void u(m),t),ie=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await Pl(e),await Kl(e),await zl(e),await o.resume()});let D=()=>u(m).then(()=>u(_)),ae=()=>{},O=new Promise(e=>ae=e),oe=null;function se({send:e=!0}={}){return oe??=(async()=>{T&&clearTimeout(T),y&&clearTimeout(y),clearInterval(re),clearInterval(ie);let t=new Promise(e=>w.close(()=>e()));w.closeIdleConnections(),await(e?D():u(()=>o.save())),w.closeAllConnections(),await t,ae()})(),oe}return{port:w.address().port,flush:D,stop:se,stopped:O}}const Xl=n(Se);async function Zl(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>ql)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await Xl(r,{maxOutputLength:ql})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function Ql(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const $l=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function eu(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await ro();await(await Yl({port:t,secret:n,apiUrl:B(),login:async()=>{let e=await H();return e?{api:z(B(),e.token),userId:e.user.id}:null}}))?.stopped}const tu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,nu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function ru(e){let t=0;for(let[n]of e.matchAll(nu)){let e=n[0];if(e===`
294
+ `)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)tu.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 iu(e){return{always:e.description,max:e.description+e.body+e.files}}function au(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=iu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function ou(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${cu((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${cu((e/1e6).toFixed(1))}M`}const su=(e,t)=>`${t===`estimate`?`~`:``}${ou(e)}`,cu=e=>e.replace(/\.0$/,``),lu={high:15,medium:10,low:5},uu=5e3,du=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function fu(e){let t=tr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&du.has(n)}const pu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,mu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function hu(e,t){let n=t(`SKILL.md`)??``,r=bi(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([W]),f=/* @__PURE__ */ new Set,p=!1,m=[W];for(;m.length>0;){let n=m.shift(),r=n===`SKILL.md`?s:t(n);if(r===void 0)fu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Eu(r)){let t=nr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Du(r,n,t.path)&&(d.add(t.path),fu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!pu.test(tr(e))).filter(e=>!tr(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(`
295
+ `).length,bodyTokens:ru(c),hasExamples:Nu(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function gu(e,t,n=/* @__PURE__ */ new Date){let r=[...Cu(e),...t?wu(t,n):[]];return{score:_u(r),checks:yu(r)}}function _u(e){let t=e.reduce((e,t)=>e+lu[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+lu[t.severity],0);return Math.round(n/t*100)}const vu=[`high`,`medium`,`low`];function yu(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:vu.indexOf(e.severity)-vu.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}),bu=/\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,xu=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Su=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Cu(e){let t=[],n=e.description??``;e.hasWhenToUse||bu.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(xu);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`)),Su.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=Tu(e.bodyTokens);return e.bodyLines===0?t.push($(`body-length`,`medium`,`${W} has no instructions`,`Write the instructions below the frontmatter.`)):e.bodyLines>500||e.bodyTokens>uu?t.push($(`body-length`,`medium`,`${W} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Tu(uu)}; move reference material into files ${W} 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 ${Pu(e.missingFiles.length,`missing file`)}: ${Fu(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`,`${Pu(e.unusedFiles.length,`file`)} nothing mentions: ${Fu(e.unusedFiles)}`,`Mention them in ${W}, saying when to read or run them, or delete them.`))),t}function wu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,Pu(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Pu(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${Pu(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 ${Pu(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 Tu(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Eu(e){let t=[];for(let n of e.matchAll(mu)){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 Du(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,tr(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Ou(t,n);return a&&r.add(a),[...r].some(t=>ku(e,t))}function Ou(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function ku(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 Au=/^(```|~~~)/m,ju=/^#{1,6}[^\n]*\bexamples?\b/im,Mu=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Nu(e){return Au.test(e)||ju.test(e)||Mu.test(e)}function Pu(e,t){return`${e} ${t}${e===1?``:`s`}`}function Fu(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Iu=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Lu(e){try{return(await ue(h(e,W))).isFile()}catch{return!1}}async function Ru(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await oe(i,{withFileTypes:!0})){let o=h(i,a.name);if(a.isDirectory()){Iu.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=_(e,o).split(y).join(`/`),{size:c}=await ue(o);t.push({path:s,size:c}),(s===`SKILL.md`||fu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),gu(hu(t,e=>n.get(e)),null)}function zu(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(`
296
+ `)}async function Bu(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=v(t??`.`);if(await Lu(n)){let e=await Ru(n),r=t===void 0?`This folder`:U(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(zu(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 Xa(),i=Tn(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(`${jn(a)} v${a.version}`),console.log(zu(o))}async function Vu(e){Ht(`agent kit`);let t=await Ya();t?F.success(`Logged in as ${Za(t.user)}`):t=await Ja();let n=z(B(),t.token),r=await n.listSkills();if(r.length===0){I(Qa(t.webUrl));return}let i=!e.yes;if(i&&!gn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await yn(e.global,i),o=await vn(e.agent,i),s=i?_n(await Bt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:jn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await zo(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});I(`Installed in ${c.map(U).join(`, `)}`)}async function Hu(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ga();return;case`on`:{if(await Rn({heartbeat:!0}),!await H()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!ca()){F.warn(`Run it from the published CLI to install the timer.`);return}await Ka();let e=await za(B()),t=(await Wa())?.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 Rn({heartbeat:!1}),await Ra(B()),F.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await Ln()).heartbeat!==!1,t=await za(B()),n=await Wa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?Pa(B()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
297
+ 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 Uu=2e3;async function Wu(e,t={},n=300){let{port:r,secret:i}=await ro();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[$a]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function Gu(){let e=await Wu(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function Ku(e,t,n=Ho){let r=await Gu();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await Ju(),u(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function qu(e){return(await Wu(`/report`,{method:`POST`,body:JSON.stringify(e)},Uu))?.status===202}async function Ju({send:e=!0}={}){return(await Wu(e?`/stop`:`/stop?send=false`,{method:`POST`},Uu))?.ok??!1}const Yu=5e3;async function Xu(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await $u()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Yo(ca()??sa()),await za(B())||await Ga();return}if(zn()||(await Ln()).telemetry===!1)return;let o=await H();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await is(o.user.id),u=c?{...Uc,sessionId:Wc(r.session_id)}:await Gc(r.session_id,s,void 0,l),d=z(B(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await Qu(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await Ku(ca()??sa(),B());let p=await ll(e,r,a,s,u,{now:i}),m=To(r),h=m&&await ma(m.name,e,s),g=m&&h&&await _a(h,e,m.trigger,Kc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&os(l,i,h?h.id:null)&&ss(d,o.user.id,l,i),(p||g)&&Zu(d,p,g)])}catch{}}async function Zu(e,t,n){await qu({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&ul(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(Yu))},t),n&&ya(async t=>{await e.reportActivations(t,AbortSignal.timeout(Yu))},n)])}async function Qu(e,t,n){let{repository:r,branch:i}=await qc(n),a=ha(n,x());(r||a)&&await Ml({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function $u(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function ed(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Ht(`agent kit`);let n=v(e[0]);if(!u(h(n,`SKILL.md`)))throw Error(`${U(n)} has no ${W}, so it isn't a skill.`);let r=f(n);if(!/^[a-z0-9-]+$/.test(r)||r===`report-session-issue`)throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await vn(t.agent,!t.yes),o=on(a,i),s=o.map(e=>h(e,r));if(s.includes(n))throw Error(`${U(n)} is already where your agents read it.`);let c=(await Y(J(i))).skills[r];for(let e of s)if(u(e)&&!await Jn(e)&&!c)throw Error(`${U(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await qn(z(B(),(await H())?.token),r,c,o);if(e&&!await Jn(e.folder))throw Error(`${U(e.folder)} has edits that aren't in agent kit (${Gn(e.paths)}). Copy them to ${U(n)} and delete them there first.`)}for(let e of s)await Xn(e,n);F.success(`${r}: ${s.map(U).join(`, `)} → ${U(n)}`);let l=i===`project`?await td(on(a,`global`),r,n):[];l.length>0&&F.warn(`You also have ${r} in ${l.map(U).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await nd(n,r),I(`${l.length>0?`This project's agents would use`:`Your agents use`} ${U(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function td(e,t,n){let r=[];for(let i of e){let e=h(i,t);u(e)&&await Jn(e)!==n&&r.push(e)}return r}async function nd(e,t){let n;try{n=gc(e)}catch{return}if(v(n,`skills`,t)!==e)return;let r=xc((await vc(n)).problems,[t]);r.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...hs(r)].join(`
298
+ `))}function rd(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?su(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[jn(e),id(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[ad(`project`,r,e),ad(`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=au(s.map(e=>e.skill.contextCost)),l=c.estimated?`~`:``,u=[o(i),...r.map(e=>o(e.cells))];return u.push(s.length===0?`${`TOTAL`.padEnd(a[0])} nothing installed here`:`${`TOTAL`.padEnd(a[0])} ${l}${ou(c.always)} always · ${l}${ou(c.max)} max (${s.length} installed${c.missing?`, ${c.missing} not counted yet`:``})`),r.some(e=>e.skill.contextCost?.source===`estimate`)&&u.push(`~ estimated locally: add a Claude API key to the organization to count exactly.`),u}function id(e){return[`v${e.version}`,...Yt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function ad(e,t,n){if(!t)return null;let r=Ji(t),{version:i}=$t(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 od(){let{api:e,credentials:t}=await Xa(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(Qa(t.webUrl));return}let i=await Y(J(`project`)),a=await Y(J(`global`));for(let e of rd(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>sd(e).length));for(let e of r){let t=[cd(i,e)&&`in project`,cd(a,e)&&`in global`].filter(Boolean);console.log(`${sd(e).padEnd(o)} ${ld(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const sd=e=>`${bn}${jn(e)}`,cd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function ld(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 ud(e,t){switch(e){case void 0:case`status`:{let e=(await Wa())?.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 Xa(),r=await Da(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await Ln()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Ga()?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 dd(){Ht(`agent kit`);let e=await Ya().catch(()=>null);if(e){let t=Za(e.user);if(!gn()){I(`Already logged in as ${t}.`);return}if(!_n(await Lt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Ja();e&&await z(B(),e.token).logout().catch(()=>{}),I(await md(t.token,t.webUrl))}async function fd(e=process.stdin){Ht(`agent kit`);let t=await pd(e);if(!t)throw Error(`Give it the bot's token on stdin, like ${L(`login --token`)} < bot-token.`);let n;try{n=await z(B(),t).me()}catch(e){throw e instanceof R&&e.status===401?Error(`This token doesn't work: it's wrong, or the bot was revoked.`):e}let r=await H();await Fn({token:t,user:n,webUrl:Mn(B())}),r&&r.token!==t&&await z(B(),r.token).logout().catch(()=>{}),await Ka(),I(`Logged in as ${Za(n)}.`)}async function pd(e){if(e.isTTY)return _n(await Ut({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function md(e,t){return(await z(B(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${Qa(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function hd(){let e=await H();e?(await z(B(),e.token).logout().catch(()=>{}),await Fn(null),console.log(`Logged out ${Za(e.user)}.`)):console.log(`You're not logged in.`)}async function gd(){let e=await Ya();e?console.log(Za(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const _d=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function vd(e){let t=await yd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${mn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${L(`check <skill>`)}`,` 3. Try it in your agent: ${L(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${L(`add <skill>`)} or ${L(`update`)}.`),Error(r.join(`
299
+ `))}async function yd(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repository?.fullName??null).catch(()=>null)));return[...new Set(n.filter(e=>e!==null))]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const bd={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},xd=[{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}],Sd=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Cd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,wd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Td=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Ed=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Dd(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(Ed(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}_])${Ed(e.find)}(?![\\p{L}\\p{N}_])`:Ed(e.find),`giu`)}));function a(e){let t=e;for(let e of xd)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(Sd,e=>Td.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Cd,e=>wd.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 Od=e=>e.map(e=>JSON.stringify(e)).join(`
299
300
  `)+`
300
- `;function Td(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
301
- `)){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=Ed(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(Ri))]}}function Ed(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:Dd(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function Dd(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(`
302
- `):``}const Od=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function kd(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(`
303
- `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=jd(o.cli_version)??r,i=jd(o.cwd)??i;else if(e.type===`turn_context`)n=jd(o.model)??n,i=jd(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=Md(o.content);if(!t.trim()||e===`user`&&Od.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`?Nd(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:Pd(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(Ri))]}}function Ad(e){try{let t=JSON.parse(e);return t.type===`session_meta`?jd(t.payload?.cwd):null}catch{return null}}const jd=e=>typeof e==`string`&&e?e:null;function Md(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
304
- `):``}function Nd(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function Pd(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 Md(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return Pd(t)}return JSON.stringify(e??``)}const Fd=()=>process.env.CLAUDE_CONFIG_DIR??h(x(),`.claude`),Id=()=>process.env.CODEX_HOME??h(x(),`.codex`),Ld=(e,t=Fd())=>h(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function Rd(e,t,n=process.cwd()){if(t&&u(t))return v(t);let r=e===`claude-code`?await Vd(t,n):await Hd(t,n);if(r)return r.file;throw Error(t?`No ${Bd(e)} session "${t}" on this machine.`:`No ${Bd(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function zd(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([Vd(void 0,e),Hd(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 Bd=e=>e===`claude-code`?`Claude Code`:`Codex`;async function Vd(e,t){if(e){let t=h(Fd(),`projects`),n=await qd(t);for(let r of n){let n=h(t,r,`${e}.jsonl`);if(u(n))return{file:n,mtime:0}}return null}for(let e of Jd(t)){let t=Ld(e),n=(await qd(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Kd(n.map(e=>h(t,e)))}return null}async function Hd(e,t){let n=h(Id(),`sessions`),r=[],i=0;outer:for(let e of Ud(await qd(n)))for(let t of Ud(await qd(h(n,e))))for(let a of Ud(await qd(h(n,e,t)))){let o=h(n,e,t,a);for(let e of await qd(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(h(o,e));if(r.length>=300||++i>=14)break outer}return Wd(r,e,t)}const Ud=e=>e.sort().reverse();async function Wd(e,t,n){if(t){let n=e.find(e=>f(e).includes(t));return n?{file:n,mtime:0}:null}let r=Jd(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Gd(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 Kd(t)}return null}async function Gd(e){let t=await ae(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(`
305
- `);return Ad(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Kd(e){let t=null;for(let n of e){let{mtimeMs:e}=await ue(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function qd(e){try{return await oe(e)}catch{return[]}}function Jd(e){let t=[v(e)];for(;m(t.at(-1))!==t.at(-1);)t.push(m(t.at(-1)));return t}const Yd=2e3;function Xd(e){let t=[...e.map],n=$d(()=>T().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=$d(()=>S());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=Zd();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=$d(()=>ve(`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:x(),as:`~`}],maxToolText:e.fullOutputs?null:Yd}}function Zd(){return $d(()=>ve(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function Qd(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 $d(e){try{return e()}catch{return null}}function ef(e,t,n){let r=new Set(t),i=/* @__PURE__ */ new Map;for(let t of n)for(let[n,a]of Object.entries(t.skills))nf(a.agents,e)&&(i.has(n)||i.set(n,{name:n,skillId:a.id,version:a.version,triggered:r.has(n)}));for(let e of t)e===`report-session-issue`||i.has(e)||i.set(e,{name:e,skillId:null,version:null,triggered:!0});return i.delete(Mi),[...i.values()]}const tf=[`codex`,`cursor`,`gemini-cli`],nf=(e,t)=>e.length===0||e.includes(t)||tf.includes(t)&&e.some(e=>tf.includes(e));async function rf(e){Ht(`agent kit report`);let t=await af(e.agent[0]),n=await Rd(t,e.session||void 0),r=await O(n,`utf8`),i=Ii(t===`claude-code`?Td(r):kd(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Cd(Xd({map:e.map?Qd(await of(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(cf(e.title,`--title`,`a short title`)),s=a.text(cf(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=wd(a.events(i.events)),u=await Promise.all([Y(J(`project`)),Y(J(`global`))]),d=ef(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=h(w(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${Bd(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${uf(d)}`,`Taken out: ${df(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
306
- `)),Buffer.byteLength(l)>gd.maxTranscriptBytes)throw Error(`The transcript is over ${gd.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(!gn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!_n(await Lt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:g}=await Xa(),[_,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=lf(e.org,_,v,d),b=await m.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function af(e){if(e===void 0)return zd();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 of=e=>e===`-`?sf():O(e,`utf8`);async function sf(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function cf(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function lf(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 uf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function df(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${Yd} characters`:`${e} ×${t}`).join(`, `)}function ff(e){return e&&e.total>0?e.passed/e.total:null}async function pf(e){let{api:t,credentials:n}=await Xa(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(mf(r,n.webUrl,i.length>1))}function mf({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=>jn({...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=ff(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(`
307
- `)}const hf={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function gf(e,t,{port:n}={}){switch(e){case`on`:{n!==void 0&&await io(Number(n)),await Rn({telemetry:!0});let e=await Oo();if(e.status===`skipped`){F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}F.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&F.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await Rn({telemetry:!1}),await Oo(),await Wu({send:!1}),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return vf(t);case void 0:case`status`:{let e=await Ln(),t=(await jo()).includes(`telemetry`),n=e.telemetry===!1?`off`:zn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await ro(),i=await Vu(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${hf[await Ao()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status or show.`)}}const _f={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function vf(e){if(e){let t=await Pl(e);if(!t)throw Error(`Nothing was sent for session ${e}.`);console.log(JSON.stringify(t.record,null,2));return}let t=await Fl();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${_f[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function yf(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 wf();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Cf(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Xa(),c=Tn(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)=>bf(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;Sf(await d(!0,e=>{m||u(`With ${jn(l)} v${a??l.version}`),m=!0,xf(e,l.name)})),u(`Without`);let h=await p;for(let e of f)xf(e,l.name);Sf(h)}async function bf(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 xf(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 Sf(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=fn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${un(e.usage)}`)}function Cf(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 wf(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Tf=`a-kit ${en}: your agent kit skills, in your agents.
301
+ `;function kd(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
302
+ `)){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=Ad(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(Ri))]}}function Ad(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:jd(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function jd(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(`
303
+ `):``}const Md=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function Nd(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(`
304
+ `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=Fd(o.cli_version)??r,i=Fd(o.cwd)??i;else if(e.type===`turn_context`)n=Fd(o.model)??n,i=Fd(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=Id(o.content);if(!t.trim()||e===`user`&&Md.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`?Ld(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:Rd(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(Ri))]}}function Pd(e){try{let t=JSON.parse(e);return t.type===`session_meta`?Fd(t.payload?.cwd):null}catch{return null}}const Fd=e=>typeof e==`string`&&e?e:null;function Id(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
305
+ `):``}function Ld(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function Rd(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 Id(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return Rd(t)}return JSON.stringify(e??``)}const zd=()=>process.env.CLAUDE_CONFIG_DIR??h(x(),`.claude`),Bd=()=>process.env.CODEX_HOME??h(x(),`.codex`),Vd=(e,t=zd())=>h(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function Hd(e,t,n=process.cwd()){if(t&&u(t))return v(t);let r=e===`claude-code`?await Gd(t,n):await Kd(t,n);if(r)return r.file;throw Error(t?`No ${Wd(e)} session "${t}" on this machine.`:`No ${Wd(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function Ud(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([Gd(void 0,e),Kd(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 Wd=e=>e===`claude-code`?`Claude Code`:`Codex`;async function Gd(e,t){if(e){let t=h(zd(),`projects`),n=await Zd(t);for(let r of n){let n=h(t,r,`${e}.jsonl`);if(u(n))return{file:n,mtime:0}}return null}for(let e of Qd(t)){let t=Vd(e),n=(await Zd(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Xd(n.map(e=>h(t,e)))}return null}async function Kd(e,t){let n=h(Bd(),`sessions`),r=[],i=0;outer:for(let e of qd(await Zd(n)))for(let t of qd(await Zd(h(n,e))))for(let a of qd(await Zd(h(n,e,t)))){let o=h(n,e,t,a);for(let e of await Zd(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(h(o,e));if(r.length>=300||++i>=14)break outer}return Jd(r,e,t)}const qd=e=>e.sort().reverse();async function Jd(e,t,n){if(t){let n=e.find(e=>f(e).includes(t));return n?{file:n,mtime:0}:null}let r=Qd(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Yd(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 Xd(t)}return null}async function Yd(e){let t=await ae(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(`
306
+ `);return Pd(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Xd(e){let t=null;for(let n of e){let{mtimeMs:e}=await ue(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function Zd(e){try{return await oe(e)}catch{return[]}}function Qd(e){let t=[v(e)];for(;m(t.at(-1))!==t.at(-1);)t.push(m(t.at(-1)));return t}const $d=2e3;function ef(e){let t=[...e.map],n=rf(()=>T().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=rf(()=>S());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=tf();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=rf(()=>ve(`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:x(),as:`~`}],maxToolText:e.fullOutputs?null:$d}}function tf(){return rf(()=>ve(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function nf(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 rf(e){try{return e()}catch{return null}}function af(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))sf(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(Mi),[...i.values()]}const of=[`codex`,`cursor`,`gemini-cli`],sf=(e,t)=>e.length===0||e.includes(t)||of.includes(t)&&e.some(e=>of.includes(e));async function cf(e){Ht(`agent kit report`);let t=await lf(e.agent[0]),n=await Hd(t,e.session||void 0),r=await O(n,`utf8`),i=Ii(t===`claude-code`?kd(r):Nd(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Dd(ef({map:e.map?nf(await uf(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(ff(e.title,`--title`,`a short title`)),s=a.text(ff(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=Od(a.events(i.events)),u=await Promise.all([Y(J(`project`)),Y(J(`global`))]),d=af(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=h(w(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${Wd(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${mf(d)}`,`Taken out: ${hf(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
307
+ `)),Buffer.byteLength(l)>bd.maxTranscriptBytes)throw Error(`The transcript is over ${bd.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(!gn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!_n(await Lt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:g}=await Xa(),[_,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=pf(e.org,_,v,d),b=await m.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function lf(e){if(e===void 0)return Ud();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 uf=e=>e===`-`?df():O(e,`utf8`);async function df(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function ff(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function pf(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 mf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function hf(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${$d} characters`:`${e} ×${t}`).join(`, `)}function gf(e){return e&&e.total>0?e.passed/e.total:null}async function _f(e){let{api:t,credentials:n}=await Xa(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(vf(r,n.webUrl,i.length>1))}function vf({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=>jn({...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=gf(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(`
308
+ `)}const yf={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function bf(e,t,{port:n}={}){switch(e){case`on`:{n!==void 0&&await io(Number(n)),await Rn({telemetry:!0});let e=await Oo();if(e.status===`skipped`){F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}F.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&F.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await Rn({telemetry:!1}),await Oo(),await Ju({send:!1}),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return Sf(t);case void 0:case`status`:{let e=await Ln(),t=(await jo()).includes(`telemetry`),n=e.telemetry===!1?`off`:zn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await ro(),i=await Gu(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${yf[await Ao()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status or show.`)}}const xf={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Sf(e){if(e){let t=await Ll(e);if(!t)throw Error(`Nothing was sent for session ${e}.`);console.log(JSON.stringify(t.record,null,2));return}let t=await Rl();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${xf[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function Cf(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 Of();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Df(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Xa(),c=Tn(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)=>wf(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;Ef(await d(!0,e=>{m||u(`With ${jn(l)} v${a??l.version}`),m=!0,Tf(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Tf(e,l.name);Ef(h)}async function wf(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 Tf(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 Ef(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=fn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${un(e.usage)}`)}function Df(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 Of(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const kf=`a-kit ${en}: your agent kit skills, in your agents.
308
309
 
309
310
  Usage
310
311
  a-kit init Log in and pick skills to install
@@ -361,4 +362,4 @@ Report options (the report-session-issue skill passes them for you)
361
362
  --org <id|name> The organization, when it can't tell
362
363
  --full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
363
364
  --dry-run Scrub and show what would be sent, without sending
364
- `;async function Ef(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&pd.has(e))return md(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},session:{type:`string`},title:{type:`string`},note:{type:`string`},expected:{type:`string`},map:{type:`string`},org:{type:`string`},"full-outputs":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(en);let[i,...a]=r;if(n.help||!i)return console.log(Tf);if(!Qt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Xt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return Lu(o);case`add`:case`install`:return Vo(a,o);case`update`:return ls(o);case`list`:case`ls`:return nd();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return pf(a);case`health`:return Iu(a);case`check`:return bc(a);case`link`:return Xu(a,o);case`login`:return n.token?cd():sd();case`logout`:return dd();case`whoami`:return fd();case`try`:return yf(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return rf({...o,session:n.session,title:n.title,note:n.note,expected:n.expected,map:n.map,org:n.org,fullOutputs:n[`full-outputs`],dryRun:n[`dry-run`]});case`telemetry`:return gf(a[0],a[1],{port:n.port});case`auto-update`:return fs(a[0]);case`heartbeat`:return Ru(a[0],n.api);case`org`:return od(a[0],a.slice(1).join(` `)||n.org);case`hook`:return Ku(a[0],n.api,a[1]);case`collector`:return Xl(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Ef().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
365
+ `;async function Af(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&_d.has(e))return vd(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},session:{type:`string`},title:{type:`string`},note:{type:`string`},expected:{type:`string`},map:{type:`string`},org:{type:`string`},"full-outputs":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(en);let[i,...a]=r;if(n.help||!i)return console.log(kf);if(!Qt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Xt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return Vu(o);case`add`:case`install`:return Vo(a,o);case`update`:return ls(o);case`list`:case`ls`:return od();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return _f(a);case`health`:return Bu(a);case`check`:return Cc(a);case`link`:return ed(a,o);case`login`:return n.token?fd():dd();case`logout`:return hd();case`whoami`:return gd();case`try`:return Cf(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return cf({...o,session:n.session,title:n.title,note:n.note,expected:n.expected,map:n.map,org:n.org,fullOutputs:n[`full-outputs`],dryRun:n[`dry-run`]});case`telemetry`:return bf(a[0],a[1],{port:n.port});case`auto-update`:return fs(a[0]);case`heartbeat`:return Hu(a[0],n.api);case`org`:return ud(a[0],a.slice(1).join(` `)||n.org);case`hook`:return Xu(a[0],n.api,a[1]);case`collector`:return eu(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Af().catch(e=>{let t=e instanceof Error?e.message:String(e);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.75",
3
+ "version": "0.2.0-dev.77",
4
4
  "description": "Install your agent kit skills into Claude Code, Codex, Cursor and Gemini CLI.",
5
5
  "keywords": [
6
6
  "agent-kit",