useakit 0.2.0-dev.83 → 0.2.0-dev.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +32 -31
- 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}),listRoles:(e,t)=>i(`/orgs/${e}/roles`,{signal:t}),getRepository:e=>i(`/orgs/${e}/repository
|
|
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,t)=>i(`/orgs/${e}/repository`,{signal:t}),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),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);
|
|
@@ -269,43 +269,44 @@ Only the conversation up to the developer's request to report it is sent; this p
|
|
|
269
269
|
5. **Send.** Run the same command with \`--yes\` instead of \`--dry-run\`, and give the developer the link it prints. If it says they're not logged in, they run \`${e} login\` first.
|
|
270
270
|
`;async function Lo(e){for(let t of e){let e=h(t,Mi);await D(e,{recursive:!0}),await k(h(e,`SKILL.md`),Io())}}const Ro=e=>t=>on(t.map(e=>an(e)).filter(e=>e!==void 0),e);async function zo(e,t,n,r,i=`latest`,a){let o=on(n,r),s=J(r),c=await Y(s);await Lo(o);try{await Bo(e,c,t,n,o,i,a)}finally{await Yi(s,c)}return await No(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function Bo(e,t,n,r,i,a=`latest`,o){let s=n.find((e,t)=>n.some((n,r)=>r<t&&n.name===e.name));if(s)throw Error(`You picked more than one skill named "${s.name}"; they'd install to the same folder. Pick one.`);let c=Gt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Ki(e,o.id,i,a);l.push(n),t.skills[n.name]=qi(n,r.map(e=>e.id),a),delete t.public?.[n.name],c.stop(`${n.name} v${n.version}`+(a===`latest`?``:` (${a})`)),a!==`latest`&&n.channels[a]===null&&F.warn(`${n.name} has no ${a} release yet, so you got the latest. \`a-kit update\` follows ${a} once someone sets it.`)}catch(e){throw c.error(`${o.name} failed`),e}}if(!o)return;let u=await Ui(await Bi(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await Bo(e,t,u,r,i)}async function Vo(e,t){Ht(`agent kit`);let n=!t.yes,r=xn(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(na)&&await H()===null?null:await Xa(),a=i?.api??z(B()),o=r.skills.length>0||r.kits.length===0,s=i&&o?await a.listSkills():[],{own:c,others:l}=i?ra(s,r.skills):{own:[],others:r.skills},u=await ia(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){I(Qa(i.credentials.webUrl));return}let f=d?await Sn(s,c,n):[],p=u.find(e=>f.some(t=>t.name===e.name));if(p)throw Error(`${p.ref} and one of your skills are both named "${p.name}"; they'd install to the same folder. Pick one.`);let m=r.kits.length>0?await Cn(await a.listKits(),r.kits,n):[];m.length>0&&t.channel!==`latest`&&F.warn(`--channel ${t.channel} applies to skills you name; kits install and follow each skill's latest version.`);let h=await vn(t.agent,n),g=t.global?`global`:`project`,_=on(h,g),v=J(g),y=await Y(v);await Lo(_);try{await Bo(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await aa(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await $i(a,y,e,{agents:h.map(e=>e.id),dirsOf:Ro(g),reinstall:!0}),n=e.skills.length-t.skipped.length;F.success(`kit/${e.name}: ${n} skill${n===1?``:`s`} installed`+(t.removed.length?`, ${t.removed.join(`, `)} removed (no longer in it)`:``))}}finally{await Yi(v,y)}await No(h.map(e=>e.id)),I(`Installed in ${_.map(U).join(`, `)}`)}const Ho=(e,t)=>{ye(process.execPath,[e,...t],{cwd:x(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},Uo=()=>h(V(),`auto-update.json`);async function Wo(e=Date.now(),t=6e4,n=Uo()){if(Go((await Ko(n)).startedAt,e,t))return!1;await D(m(n),{recursive:!0});let r=`${n}.claim`;try{await k(r,``,{flag:`wx`})}catch{let e=await ue(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await fe(r).catch(()=>{}),!1}try{let r=await Ko(n);return!Go(r.startedAt,e,t)&&(await qo(n,{...r,startedAt:e}),!0)}finally{await fe(r).catch(()=>{})}}const Go=(e,t,n)=>typeof e==`number`&&t-e<n&&e<=t;async function Ko(e){try{let{startedAt:t,fingerprint:n}=JSON.parse(await O(e,`utf8`));return{...typeof t==`number`&&{startedAt:t},...typeof n==`string`&&{fingerprint:n}}}catch{return{}}}async function qo(e,t){await D(m(e),{recursive:!0}),await k(e,JSON.stringify(t)+`
|
|
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
|
-
`),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
|
|
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(!
|
|
274
|
-
`)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!
|
|
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=
|
|
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])),
|
|
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.`}}const _s=e=>`kits/${e}.yaml`;function vs(e){let t=/^kits\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function ys(e){let t;try{t=(0,q.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
|
|
273
|
+
`)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{skills:[]};let n="It has to list the kit's skills by name: `skills: [tdd, notes]`.";if(!bs(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 bs=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function xs(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(!bs(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(bs(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 Ss=(...e)=>({words:e}),Cs={text:`one`},ws={issue:{about:`an issue's state changed`,value:Ss(`opened`,`closed`,`reopened`),fields:{}},label:{about:`a label was put on an issue or a pull request, or taken off`,value:Cs,fields:{on:Ss(`added`,`removed`)}},path:{about:`a pull request that changes a path was merged`,value:Cs,fields:{on:Ss(`merged`)}},"pull-request":{about:`a pull request was opened, marked ready, merged or closed`,value:Ss(`opened`,`ready`,`merged`,`closed`),fields:{base:Cs,head:Cs}},review:{about:`a pull request got a review`,value:Ss(`approved`,`changes-requested`,`commented`),fields:{by:{text:`many`}},roles:[`by`]},checks:{about:`a pull request's checks finished`,value:Ss(`passed`,`failed`),fields:{}},release:{about:`a release was published`,value:Ss(`published`),fields:{}},skill:{about:`an agent loaded a skill`,value:Cs,fields:{}},branch:{about:`a branch got its first commit`,value:Ss(`first-commit`),fields:{}}},Ts=Object.keys(ws),Es=e=>Object.hasOwn(ws,e),Ds=(e,t=`and`)=>e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)} ${t} ${e.at(-1)}`,Os=`flows`,ks=[`epic`,`ticket`,`pull-request`],As=[`paths`,`labels`];function js(e){let t=/^flows\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function Ms(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 Ns(e){let t=Ms(e);return t===null?null:`“${e}” can't be a flow's name, so this file isn't read. ${t}`}const Ps=[`name`,`description`,`stations`],Fs=[`id`,`unit`,`signal`,`owner`,`before`,`when`];function Is(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=Ls(r,s,Ps,`A flow`,a),l=c.has(`name`)?Rs(c.get(`name`),"Its `name`",a):null,u=c.has(`description`)?Rs(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=Ls(r,s,Fs,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=Rs(u,`The \`id\` of ${c.toLowerCase()}`,a);let t=m===null?null:Ms(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=Rs(g,`The \`unit\` of ${h.toLowerCase()}`,a);e!==null&&(ks.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=Bs(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`)?zs(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`)?Ws(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 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=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 ${Ds(n.map(e=>`\`${e}\``))}.`):a.set(c,{key:s,value:X(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,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 Bs(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=Hs(e,t,n,r,i);a?o.push(a):s=!1}return s?o:null}const Vs=Ds(Ts.map(e=>`\`${e}\``));function Hs(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 ${Vs}.`),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=>Es(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 ${Vs}.`:`A signal of ${n.toLowerCase()} is empty. Start it with its kind: ${Vs}.`),null}if(o.length>1)return r(o[1].key,`A signal is of one kind, and this one has ${Ds(o.map(e=>`\`${e.name}\``))}. To take any of them, make \`signal\` a list.`),null;let s=o[0].name,c=ws[s],l=!0,u=Us(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 ${Ds(f.map(e=>`\`${e}\``))}.`),l=!1;continue}let n=Us(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 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 ${Ds(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,As,`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(`
|
|
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`,
|
|
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
|
|
284
284
|
`:`description:
|
|
285
|
-
`});for(let e of s){let t=
|
|
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(`
|
|
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 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
|
-
|
|
289
|
-
`:``
|
|
290
|
-
|
|
291
|
-
`)}const ml=e=>
|
|
292
|
-
`)}
|
|
293
|
-
`)}
|
|
294
|
-
`)
|
|
295
|
-
`)
|
|
296
|
-
`)
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
`))}
|
|
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=xs(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=vs(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=ys(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 uc(t,Os).loose){let t=`${Os}/${n}`,i=js(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=Ns(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=Is(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:uc(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===lc),problems:pc(r)}}const pc=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 mc(e,t){let n=(e.flowRoles??[]).filter(e=>!t.has(e.name));return n.length===0?e:{...e,problems:pc([...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 hc=(e,t,n)=>`There's a ${e} called “${t}” in ${n} already, and a name is one in the organization. This one isn't read: rename it, or take it out of one of them.`;function gc(e,t){let n=[],r=`${Os}/`,i=e=>t.main!==null&&e!==null&&(e===`channels.yaml`||e.startsWith(r));n.push(...e.problems.filter(e=>!i(e.path))),t.main!==null&&e.channels&&n.push({severity:`warning`,path:lc,message:`It's ignored: release channels are only read from the main repository, ${t.main}.`}),t.main!==null&&(e.flows??[]).length>0&&n.push({severity:`warning`,path:Os,message:`They're ignored: flows are only read from the main repository, ${t.main}.`});let a=e.skills.map(e=>{let r=t.skills.get(e.name);return r===void 0?e:(n.push({severity:`error`,path:`skills/${e.name}`,message:hc(`skill`,e.name,r)}),{...e,errors:e.errors+1})});for(let r of e.kits){let e=t.kits.get(r);e!==void 0&&n.push({severity:`error`,path:_s(r),message:hc(`kit`,r,e)})}return{...e,skills:a,problems:pc(n)}}const _c={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},vc=/^[A-Za-z0-9._:-]{1,128}$/,yc=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,bc=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,xc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Sc=/[\u0000-\u001f\u007f]/;function Cc(e){let t=e.trim(),n=bc.exec(t)??xc.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 wc(o)?o:null}const wc=e=>yc.test(e)&&e.length<=_c.maxRepositoryLength,Tc=e=>e.length>0&&e.length<=_c.maxBranchLength&&e.trim()===e&&!Sc.test(e),Ec={sessionId:null,repository:null,branch:null,audience:null},Dc=e=>typeof e==`string`&&e?e:null;async function Oc(e,t,n=x(),r=null){let i=Dc(e),a=ha(t,n)!==null;if(!a&&!r)return{...Ec,sessionId:i};let{repository:o,branch:s}=await Ac(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}:{...Ec,sessionId:i}}function kc({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function Ac(e){let[t,n]=await Promise.all([Nc(e,[`remote`,`get-url`,`origin`]),Nc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?Cc(t):null,branch:n}}async function jc(e,t){if(Mc.includes(t))return!0;let n=await Nc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const Mc=[`main`,`master`,`develop`];function Nc(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 Pc=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],Fc=e=>{try{return d(e).isDirectory()}catch{return!1}};function Ic(e){let t;for(let n=v(e);;n=m(n)){if(t??=Fc(h(n,`skills`))?n:void 0,u(h(n,`.git`))){if(Fc(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 Lc(e){let t=[];for(let n of Pc){let r=h(e,n);if(Fc(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 Rc(e){let t=await Lc(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)js(n)!==null&&i.set(n,await O(h(e,n),`utf8`));return fc({files:t,skillMds:n,channelsText:r,flowTexts:i})}const zc=1e4,Bc=(e,t)=>t.aborted?`agent kit didn't answer in time`:e instanceof Error?e.message:String(e);async function Vc(e,t,n=zc){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:mc(e,new Set(a.map(e=>e.name))),unchecked:null}}catch(e){return r(`couldn't get your organization's roles (${Bc(e,i)}).`)}}const Hc=`Skill names in your organization's other repositories`;async function Uc(e,t,n){let r=await e.listOrganizations(n),i=await Promise.all(r.map(t=>e.getRepository(t.id,n).then(e=>({organizationId:t.id,status:e})).catch(e=>{if(e instanceof R&&(e.status===403||e.status===404))return null;throw e})));for(let e of i){if(!e)continue;let n=e.status.repositories??(e.status.repository?[e.status.repository]:[]),r=n.find(e=>`github.com/${e.fullName.toLowerCase()}`===t);if(!r)continue;let i=n.find(e=>e.main);return{organizationId:e.organizationId,fullName:r.fullName,placement:{main:r.main?null:i?.fullName??null,skills:new Map(Object.entries(r.elsewhere?.skills??{})),kits:new Map(Object.entries(r.elsewhere?.kits??{}))}}}return null}async function Wc(e,t,n,{roles:r=!0,timeoutMs:i=zc}={}){let a=r&&(e.flowRoles?.length??0)>0?`${Hc} and roles in flows`:Hc;if(!n)return{scan:e,unchecked:`${a} weren't checked: log in with ${L(`login`)} to check them.`,place:null};let o=null;if(t){let r=AbortSignal.timeout(i);try{o=await Uc(n.api,t,r)}catch(t){return{scan:e,unchecked:`${a} weren't checked: couldn't get your organization's repositories (${Bc(t,r)}).`,place:null}}}if(o){let t=gc(e,o.placement);return!r||o.placement.main!==null?{scan:t,unchecked:null,place:o}:{...await Vc(t,{api:n.api,organizationId:o.organizationId},i),place:o}}let s=r?await Vc(e,n,i):{scan:e,unchecked:null},c=t?`${Hc} weren't checked: agent kit reads no repository at ${t}.`:null;return{scan:s.scan,unchecked:[c,s.unchecked].filter(Boolean).join(`
|
|
288
|
+
`)||null,place:null}}async function Gc(e,t,n){let r=await H();return Wc(t,(await Ac(e)).repository,r&&{api:z(B(),r.token),organizationId:r.organizationId},n)}function Kc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=v(n,i);if(Fc(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 qc=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function Jc(e){let t=Ic(e.find(e=>e.includes(`/`))??`.`),n=Kc(t,e),r=await Rc(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,place:c}=await Gc(t,r,{roles:n.length===0}),l=c?.placement.main?0:o.flows?.length??0,u=n.length>0?qc(o.problems,n):o.problems;for(let e of hs(u))console.log(e);s&&console.log(`${u.length?`
|
|
289
|
+
`:``}${s}`);let d=u.filter(e=>e.severity===`error`).length,f=u.length-d,p=n.length===1?n[0]:n.length>0?ms(n.length,`skill`):`The repository (${[ms(o.skills.length,`skill`),...l?[ms(l,`flow`)]:[]].join(`, `)})`;d>0?(console.log(`\n${p}: ${ms(d,`error`)}`+(f?`, ${ms(f,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((u.length||s?`
|
|
290
|
+
`:``)+`${p}: no errors`+(f?`, ${ms(f,`warning`)}`:``)+`.`)}const Yc={maxPerRequest:20,maxEntries:1e3,maxAgeDays:_c.maxAgeDays,maxFutureMs:_c.maxFutureMs,maxMachineNameLength:_c.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Xc={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`},Zc=e=>typeof e==`string`&&e.length>0&&e.length<=Yc.maxModelLength&&!/\s/.test(e)&&!Sc.test(e),Qc={maxPerRequest:100,maxLinks:50,maxAgeDays:_c.maxAgeDays,maxFutureMs:_c.maxFutureMs,maxMachineNameLength:_c.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},$c=/^[1-9][0-9]{0,8}$/,el=/\s/,tl=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function nl(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return wc(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 wc(r)&&(e===`branch`?Tc(i):$c.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return il(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Qc.maxThreadLength&&!el.test(n)&&!Sc.test(n)?{kind:e,value:n}:null;case`session`:return vc.test(n)?{kind:e,value:n}:null;default:return null}}function rl(e){let t=e.trim();return nl(`slack_thread`,t)??nl(`thread`,t)}function il(e){return e.length<=Qc.maxUrlLength&&tl.test(e)}const al=()=>h(V(),`sessions`),ol=()=>h(V(),`pending-session-events.jsonl`),sl=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function cl(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 ll(e,t){let n=e.trimStart().split(`
|
|
291
|
+
`)[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(nl(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(nl(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(nl(`issue`,`${t}#${o}`)),i}function ul(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=ml(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(nl(o===`pr`?`pull_request`:`issue`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`||!dl.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=pl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||fl.test(t))&&(u=t)}if(!u)continue;let d=fl.exec(u);d?i(nl(`issue`,`${d[1]}#${d[2]}`)):l&&i(nl(`issue`,`${l}#${u.replace(`#`,``)}`))}return r}const dl=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),fl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/issues\/(\d+)/,pl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function ml(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function hl(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 gl(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 _l(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=cl(t,n),l=i.sessionId;if(!c||!l||!vc.test(l))return null;c===`end`&&t.reason===`clear`&&await Cl(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(nl(`repository`,i.repository)),i.branch&&!await jc(r,i.branch)&&d(nl(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=gl(t);if(p&&f)for(let e of ll(p,i.repository))d(e);let m=hl(t);if(m&&f)for(let e of ul(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(rl(t));if(t.source===`clear`){let e=await wl(r,l,o,s);e&&d(nl(`session`,e))}}let h=await bl(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 xl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await Tl(o),{sessionId:l,agent:e,machineId:await ga(),machineName:S()||null,type:c,occurredAt:o.toISOString(),links:u})}const vl=(e,t=[])=>ua(ol(),e,t),yl=e=>h(al(),`${sl(e)}.json`);async function bl(e){try{let t=JSON.parse(await O(yl(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 xl(e,t){await D(al(),{recursive:!0,mode:448}),await k(yl(e),JSON.stringify(t)+`
|
|
292
|
+
`)}const Sl=e=>h(al(),`cleared-${sl(e)}.json`);async function Cl(e,t,n){await D(al(),{recursive:!0,mode:448}),await k(Sl(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
|
|
293
|
+
`)}async function wl(e,t,n,r){let i=Sl(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 Tl(e){try{for(let t of await oe(al())){let n=h(al(),t),{mtimeMs:r}=await ue(n);e.getTime()-r>6048e5&&await le(n,{force:!0})}}catch{}}function El(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&&Dl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function Dl(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 Ol={"claude_code.token.usage":{input:Xc.inputTokens,output:Xc.outputTokens,cacheRead:Xc.cacheReadTokens,cacheCreation:Xc.cacheCreationTokens},"claude_code.cost.usage":Xc.costUsd,"claude_code.active_time.total":{user:Xc.personSeconds,cli:Xc.agentSeconds},"claude_code.commit.count":Xc.commits,"claude_code.pull_request.count":Xc.pullRequests};function kl(e){let t=[];for(let n of Nl(Z(e,`resourceMetrics`)))for(let e of Nl(Z(n,`scopeMetrics`)))for(let n of Nl(Z(e,`metrics`))){let e=Z(n,`name`),r=typeof e==`string`?Ol[e]:void 0,i=Z(n,`sum`);if(!r||!i)continue;let a=Z(i,`aggregationTemporality`)===2;for(let n of Nl(Z(i,`dataPoints`))){let i=Nl(Z(n,`attributes`)),o=e=>Pl(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Fl(Z(n,`asDouble`)??Z(n,`asInt`)),u=Il(Z(n,`startTimeUnixNano`)),d=Il(Z(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:jl(e,i,a?u:null),metric:c,model:Ml(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Al(e){let t=[];for(let n of Nl(Z(e,`resourceLogs`)))for(let e of Nl(Z(n,`scopeLogs`)))for(let n of Nl(Z(e,`logRecords`))){let e=Nl(Z(n,`attributes`)),r=Pl(e,`event.name`)??Z(Z(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Pl(e,`session.id`),a=Il(Z(n,`timeUnixNano`))??Il(Z(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function jl(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 Ml=e=>Zc(e)?e:null,Z=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Nl=e=>Array.isArray(e)?e:[];function Pl(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Fl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Il(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 Ll=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Rl(e){let t=()=>h(eo(),e),n=e=>h(t(),`${Ll(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
|
|
294
|
+
`)},async list(){let e=[];try{e=await 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 zl=Rl(`sessions`),Bl=e=>zl.write(e.sessionId,e);async function Vl(e){let t=await zl.read(e);return t?.sessionId===e?t:null}const Hl=(e=Date.now())=>zl.forgetOld(e),Ul=Rl(`sent`),Wl=(e,t,n=/* @__PURE__ */ new Date)=>Ul.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Gl=e=>Ul.read(e),Kl=async()=>(await Ul.list()).sort((e,t)=>t.at.localeCompare(e.at)),ql=(e=Date.now())=>Ul.forgetOld(e),Jl=(e,t)=>({sessionId:e,epoch:t,series:{},prompts:0,lastAt:t});function Yl(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 Xl(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:Xc.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,Yc.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const Zl=Rl(`state`);function Ql(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=$l(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);Yl(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await Zl.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 Zl.write(e.state.sessionId,e.state))}}}async function $l(e,t){let n=await Zl.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Jl(e,t),unsaved:!1}}const eu=(e=Date.now())=>Zl.forgetOld(e),tu=16777216,nu=()=>h(V(),`pending-session-usage.jsonl`);async function ru(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=Ql(),s=El(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 Wl(e,`refused`);throw e}for(let e of t)await Wl(e,`sent`)}),p=(e=[])=>ua(nu(),f,e,{batch:Yc.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await Vl(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=Xl(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await ga(),machineName:S()||null,skillIds:i.skillIds});a.usage.length!==0&&(await Wl(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),vl(g)]);function v(e){let t=su(e.activations),n=su(e.sessionEvents);return u(()=>Promise.all([t.length>0&&ya(h,t),n.length>0&&vl(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(),ou(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 ou(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),ou(n,404,{});if(i===`/stop`){t.resume(),ou(n,200,{}),se({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),ou(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),ou(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),ou(n,415,{message:`Send JSON.`});let a=await au(t);if(!a.ok)return ou(n,a.status,{});i===`/report`?(ou(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?kl(a.json):Al(a.json)),b(),ou(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||ou(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=[nu(),va(),ol()];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 Hl(e),await eu(e),await ql(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 iu=n(Se);async function au(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>tu)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 iu(r,{maxOutputLength:tu})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function ou(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const su=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function cu(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await ro();await(await ru({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 lu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,uu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function du(e){let t=0;for(let[n]of e.matchAll(uu)){let e=n[0];if(e===`
|
|
295
|
+
`)t+=1;else if(/\s/.test(e))t+=n.length===1?0:Math.ceil(n.length/4);else if(/\p{L}/u.test(e)){let e=0;for(let t of n)lu.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 fu(e){return{always:e.description,max:e.description+e.body+e.files}}function pu(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=fu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function mu(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${gu((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${gu((e/1e6).toFixed(1))}M`}const hu=(e,t)=>`${t===`estimate`?`~`:``}${mu(e)}`,gu=e=>e.replace(/\.0$/,``),_u={high:15,medium:10,low:5},vu=5e3,yu=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function bu(e){let t=tr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&yu.has(n)}const xu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Su=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Cu(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)bu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Pu(r)){let t=nr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Fu(r,n,t.path)&&(d.add(t.path),bu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!xu.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(`
|
|
296
|
+
`).length,bodyTokens:du(c),hasExamples:Vu(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function wu(e,t,n=/* @__PURE__ */ new Date){let r=[...ju(e),...t?Mu(t,n):[]];return{score:Tu(r),checks:Du(r)}}function Tu(e){let t=e.reduce((e,t)=>e+_u[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+_u[t.severity],0);return Math.round(n/t*100)}const Eu=[`high`,`medium`,`low`];function Du(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Eu.indexOf(e.severity)-Eu.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}),Ou=/\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,ku=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Au=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function ju(e){let t=[],n=e.description??``;e.hasWhenToUse||Ou.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(ku);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`)),Au.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=Nu(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>vu?t.push($(`body-length`,`medium`,`${W} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Nu(vu)}; 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 ${Hu(e.missingFiles.length,`missing file`)}: ${Uu(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`,`${Hu(e.unusedFiles.length,`file`)} nothing mentions: ${Uu(e.unusedFiles)}`,`Mention them in ${W}, saying when to read or run them, or delete them.`))),t}function Mu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,Hu(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Hu(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${Hu(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 ${Hu(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 Nu(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Pu(e){let t=[];for(let n of e.matchAll(Su)){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 Fu(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=Iu(t,n);return a&&r.add(a),[...r].some(t=>Lu(e,t))}function Iu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Lu(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 Ru=/^(```|~~~)/m,zu=/^#{1,6}[^\n]*\bexamples?\b/im,Bu=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Vu(e){return Ru.test(e)||zu.test(e)||Bu.test(e)}function Hu(e,t){return`${e} ${t}${e===1?``:`s`}`}function Uu(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Wu=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Gu(e){try{return(await ue(h(e,W))).isFile()}catch{return!1}}async function Ku(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()){Wu.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`||bu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),wu(Cu(t,e=>n.get(e)),null)}function qu(e){let t=[`HEALTH ${e.score}/100`];for(let n of e.checks)n.passed?t.push(`✓ ${n.message}`):(t.push(`■ ${n.message} [${n.severity}]`),n.fix&&t.push(` ${n.fix}`));return t.join(`
|
|
297
|
+
`)}async function Ju(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 Gu(n)){let e=await Ku(n),r=t===void 0?`This folder`:U(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(qu(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(qu(o))}async function Yu(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 Xu(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(`
|
|
298
|
+
Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const Zu=2e3;async function Qu(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 $u(){let e=await Qu(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function ed(e,t,n=Ho){let r=await $u();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await nd(),u(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function td(e){return(await Qu(`/report`,{method:`POST`,body:JSON.stringify(e)},Zu))?.status===202}async function nd({send:e=!0}={}){return(await Qu(e?`/stop`:`/stop?send=false`,{method:`POST`},Zu))?.ok??!1}const rd=5e3;async function id(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await sd()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await 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?{...Ec,sessionId:Dc(r.session_id)}:await Oc(r.session_id,s,void 0,l),d=z(B(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await od(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await ed(ca()??sa(),B());let p=await _l(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)&&ad(d,p,g)])}catch{}}async function ad(e,t,n){await td({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&vl(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(rd))},t),n&&ya(async t=>{await e.reportActivations(t,AbortSignal.timeout(rd))},n)])}async function od(e,t,n){let{repository:r,branch:i}=await Ac(n),a=ha(n,x());(r||a)&&await Bl({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function sd(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function cd(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);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 ld(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 ud(n,r,c!==void 0),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 ld(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 ud(e,t,n){let r;try{r=Ic(e)}catch{return}if(v(r,`skills`,t)!==e)return;let{scan:i,place:a}=await Gc(r,await Rc(r),{roles:!1}),o=a?.placement.skills.get(t);n&&o!==void 0&&F.warn(`The ${t} you installed from agent kit is ${o}'s, a different skill: this link takes its place, so your agents use ${U(e)} instead. ${L(`add ${t}`)} puts ${o}'s back.`);let s=qc(i.problems,[t]);s.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...hs(s)].join(`
|
|
299
|
+
`))}function dd(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?hu(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[jn(e),fd(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[pd(`project`,r,e),pd(`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=pu(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}${mu(c.always)} always · ${l}${mu(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 fd(e){return[`v${e.version}`,...Yt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function pd(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 md(){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 dd(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>hd(e).length));for(let e of r){let t=[gd(i,e)&&`in project`,gd(a,e)&&`in global`].filter(Boolean);console.log(`${hd(e).padEnd(o)} ${_d(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const hd=e=>`${bn}${jn(e)}`,gd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function _d(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 vd(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 yd(){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 Sd(t.token,t.webUrl))}async function bd(e=process.stdin){Ht(`agent kit`);let t=await xd(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 xd(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 Sd(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 Cd(){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 wd(){let e=await Ya();e?console.log(Za(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Td=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Ed(e){let t=await Dd(),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(`
|
|
300
|
+
`))}async function Dd(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Od={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},kd=[{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}],Ad=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,jd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Md=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Nd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Pd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Fd(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(Pd(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}_])${Pd(e.find)}(?![\\p{L}\\p{N}_])`:Pd(e.find),`giu`)}));function a(e){let t=e;for(let e of kd)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(Ad,e=>Nd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(jd,e=>Md.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 Id=e=>e.map(e=>JSON.stringify(e)).join(`
|
|
300
301
|
`)+`
|
|
301
|
-
`;function
|
|
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=
|
|
303
|
-
`):``}const
|
|
304
|
-
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=
|
|
305
|
-
`):``}function
|
|
306
|
-
`);return
|
|
307
|
-
`)),Buffer.byteLength(l)>
|
|
308
|
-
`)}const
|
|
302
|
+
`;function Ld(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
|
|
303
|
+
`)){if(!a.trim())continue;let e;try{e=JSON.parse(a)}catch{continue}if(e.type!==`user`&&e.type!==`assistant`||e.isSidechain||e.isMeta)continue;r=e.version??r,i=e.cwd??i,e.type===`assistant`&&e.message?.model&&(e.message.model.startsWith(`<`)||(n=e.message.model));let o=Rd(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 Rd(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:zd(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function zd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>e.type===`text`&&typeof e.text==`string`?e.text:e.type===`image`?`[image]`:``).filter(Boolean).join(`
|
|
304
|
+
`):``}const Bd=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function Vd(e){let t=[],n=null,r=null,i=null,a=(e,n)=>t.push({type:e,message:{content:[n]}});for(let t of e.split(`
|
|
305
|
+
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=Ud(o.cli_version)??r,i=Ud(o.cwd)??i;else if(e.type===`turn_context`)n=Ud(o.model)??n,i=Ud(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=Wd(o.content);if(!t.trim()||e===`user`&&Bd.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`?Gd(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:Kd(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 Hd(e){try{let t=JSON.parse(e);return t.type===`session_meta`?Ud(t.payload?.cwd):null}catch{return null}}const Ud=e=>typeof e==`string`&&e?e:null;function Wd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
306
|
+
`):``}function Gd(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function Kd(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 Wd(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return Kd(t)}return JSON.stringify(e??``)}const qd=()=>process.env.CLAUDE_CONFIG_DIR??h(x(),`.claude`),Jd=()=>process.env.CODEX_HOME??h(x(),`.codex`),Yd=(e,t=qd())=>h(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function Xd(e,t,n=process.cwd()){if(t&&u(t))return v(t);let r=e===`claude-code`?await $d(t,n):await ef(t,n);if(r)return r.file;throw Error(t?`No ${Qd(e)} session "${t}" on this machine.`:`No ${Qd(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([$d(void 0,e),ef(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 Qd=e=>e===`claude-code`?`Claude Code`:`Codex`;async function $d(e,t){if(e){let t=h(qd(),`projects`),n=await of(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 sf(t)){let t=Yd(e),n=(await of(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return af(n.map(e=>h(t,e)))}return null}async function ef(e,t){let n=h(Jd(),`sessions`),r=[],i=0;outer:for(let e of tf(await of(n)))for(let t of tf(await of(h(n,e))))for(let a of tf(await of(h(n,e,t)))){let o=h(n,e,t,a);for(let e of await of(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(h(o,e));if(r.length>=300||++i>=14)break outer}return nf(r,e,t)}const tf=e=>e.sort().reverse();async function nf(e,t,n){if(t){let n=e.find(e=>f(e).includes(t));return n?{file:n,mtime:0}:null}let r=sf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await rf(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 af(t)}return null}async function rf(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(`
|
|
307
|
+
`);return Hd(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function af(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 of(e){try{return await oe(e)}catch{return[]}}function sf(e){let t=[v(e)];for(;m(t.at(-1))!==t.at(-1);)t.push(m(t.at(-1)));return t}const cf=2e3;function lf(e){let t=[...e.map],n=ff(()=>T().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=ff(()=>S());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=uf();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=ff(()=>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:cf}}function uf(){return ff(()=>ve(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function df(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 ff(e){try{return e()}catch{return null}}function pf(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))hf(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 mf=[`codex`,`cursor`,`gemini-cli`],hf=(e,t)=>e.length===0||e.includes(t)||mf.includes(t)&&e.some(e=>mf.includes(e));async function gf(e){Ht(`agent kit report`);let t=await _f(e.agent[0]),n=await Xd(t,e.session||void 0),r=await O(n,`utf8`),i=Ii(t===`claude-code`?Ld(r):Vd(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Fd(lf({map:e.map?df(await vf(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(bf(e.title,`--title`,`a short title`)),s=a.text(bf(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=Id(a.events(i.events)),u=await Promise.all([Y(J(`project`)),Y(J(`global`))]),d=pf(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([`${Qd(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${Sf(d)}`,`Taken out: ${Cf(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
|
|
308
|
+
`)),Buffer.byteLength(l)>Od.maxTranscriptBytes)throw Error(`The transcript is over ${Od.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=xf(e.org,_,v,d),b=await m.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function _f(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 vf=e=>e===`-`?yf():O(e,`utf8`);async function yf(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function bf(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function xf(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 Sf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Cf(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${cf} characters`:`${e} ×${t}`).join(`, `)}function wf(e){return e&&e.total>0?e.passed/e.total:null}async function Tf(e){let{api:t,credentials:n}=await Xa(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Ef(r,n.webUrl,i.length>1))}function Ef({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=wf(t.withSkill),s=o===null?`—`:`${Math.round(o*100)}%`;i.push(` ${e[a].padEnd(r)} ${s.padStart(4)} ${t.status.padEnd(9)} ${n}/app/skills/${t.skillId}?tab=runs&run=${t.id}`)})}return i.join(`
|
|
309
|
+
`)}const Df={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 Of(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 nd({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 Af(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 $u(),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`}; ${Df[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 kf={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Af(e){if(e){let t=await Gl(e);if(!t)throw Error(`Nothing was sent for session ${e}.`);console.log(JSON.stringify(t.record,null,2));return}let t=await Kl();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} ${kf[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function jf(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 If();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Ff(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)=>Mf(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;Pf(await d(!0,e=>{m||u(`With ${jn(l)} v${a??l.version}`),m=!0,Nf(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Nf(e,l.name);Pf(h)}async function Mf(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 Nf(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 Pf(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 Ff(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 If(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Lf=`a-kit ${en}: your agent kit skills, in your agents.
|
|
309
310
|
|
|
310
311
|
Usage
|
|
311
312
|
a-kit init Log in and pick skills to install
|
|
@@ -316,7 +317,7 @@ Usage
|
|
|
316
317
|
a-kit list Your skills and kits, their context cost, and where they're installed
|
|
317
318
|
a-kit search <query> Find skills and eval runs (\`v9\` for a version)
|
|
318
319
|
a-kit health [skill|dir] A skill's health score and what to fix (this folder by default)
|
|
319
|
-
a-kit check [skill...] In a clone of your organization's
|
|
320
|
+
a-kit check [skill...] In a clone of one of your organization's repositories: check
|
|
320
321
|
its skills with the rules agent kit reads them with
|
|
321
322
|
a-kit link <folder> Have your agents use a skill's folder in that clone,
|
|
322
323
|
edits included (\`a-kit add <skill>\` undoes it)
|
|
@@ -362,4 +363,4 @@ Report options (the report-session-issue skill passes them for you)
|
|
|
362
363
|
--org <id|name> The organization, when it can't tell
|
|
363
364
|
--full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
|
|
364
365
|
--dry-run Scrub and show what would be sent, without sending
|
|
365
|
-
`;async function
|
|
366
|
+
`;async function Rf(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Td.has(e))return Ed(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(Lf);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 Yu(o);case`add`:case`install`:return Vo(a,o);case`update`:return ls(o);case`list`:case`ls`:return md();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Tf(a);case`health`:return Ju(a);case`check`:return Jc(a);case`link`:return cd(a,o);case`login`:return n.token?bd():yd();case`logout`:return Cd();case`whoami`:return wd();case`try`:return jf(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return gf({...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 Of(a[0],a[1],{port:n.port});case`auto-update`:return fs(a[0]);case`heartbeat`:return Xu(a[0],n.api);case`org`:return vd(a[0],a.slice(1).join(` `)||n.org);case`hook`:return id(a[0],n.api,a[1]);case`collector`:return cu(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Rf().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
|