useakit 0.2.0-dev.68 → 0.2.0-dev.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/index.mjs +37 -36
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -92,6 +92,13 @@ a-kit auto-update on # turn it back on
|
|
|
92
92
|
|
|
93
93
|
Installing skills for Claude Code also adds a hook to `~/.claude/settings.json`, so each time Claude Code loads a skill installed from agent kit (on its own or because you typed `/<skill>`), it reports the skill, its version, the agent, this machine (a random id and its hostname) and when. Your organization sees it on the skills table and each skill's page. Nothing else is sent: not your prompts, not your code. Reports that can't be sent wait in `~/.config/agent-kit/` for the next one.
|
|
94
94
|
|
|
95
|
+
The repository (its `origin` remote) and the branch you're on go too, and with your sessions the issue a skill was started for, only from a repo of your organization:
|
|
96
|
+
|
|
97
|
+
- a repo with an `agent-kit.lock.json`, which installs skills from agent kit;
|
|
98
|
+
- or one of your organizations' projects' repositories, told only to that organization: another organization's skill loaded there doesn't say which repository it was.
|
|
99
|
+
|
|
100
|
+
From any other repo, neither is sent. The hook decides from a list of the projects' repositories kept in `~/.config/agent-kit/`, never waiting for the API: it's asked for again once a day, so a repository added to a project starts sending within a day, or right away after `a-kit update`.
|
|
101
|
+
|
|
95
102
|
```sh
|
|
96
103
|
a-kit telemetry # whether it's on
|
|
97
104
|
a-kit telemetry off # stop reporting and remove its hooks
|
package/dist/index.mjs
CHANGED
|
@@ -72,8 +72,8 @@ ${n(`gray`,P)}`:``}`}default:{let a=i?`${n(`cyan`,P)} `:``,o=c.split(`
|
|
|
72
72
|
${a}`)}
|
|
73
73
|
${l}
|
|
74
74
|
`}}}}).prompt()};`${n(`gray`,P)}`;const Wt=[`stable`,`beta`],Gt=[`latest`,...Wt],Kt=e=>Wt.includes(e),qt=e=>Gt.includes(e);function Jt(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 Yt=`0.2.0`;const Xt=[{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`}],Zt=e=>e===`global`?b():process.cwd();function Qt(e=b()){return Xt.filter(t=>l(m(e,t.marker)))}function $t(e){return Xt.find(t=>t.id===e)}function en(e,t,n=Zt(t)){let r=e.map(e=>_(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const tn={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 nn(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}tn.maxPromptBytes;function rn(e){return e<1e3?String(e):e<1e6?`${on(e/1e3)}k`:`${on(e/1e6)}M`}const an=e=>`${rn(e.inputTokens+e.outputTokens)} tok · ${nn(e.costUsd)}`,on=e=>e>=100?Math.round(e):Number(e.toFixed(1));function sn(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 cn(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 ln(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?Yt.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${ln()} ${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/${Yt}`,...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:()=>i(`/orgs
|
|
76
|
-
`,{mode:384}),await ee(n,384)}const
|
|
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 ln(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?Yt.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${ln()} ${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/${Yt}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new R(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new R(401,`UNAUTHORIZED`,`You're not logged in. Run ${L(`login`)}.`):new R(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),listProjects:(e,t)=>i(`/orgs/${e}/projects`,{signal:t}),getRepository:e=>i(`/orgs/${e}/repository`),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),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=cn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}cn(`${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/${un(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${un(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${un(e)}/installs`,{method:`POST`})}}const un=e=>e.split(`/`).map(encodeURIComponent).join(`/`),dn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function fn(e){return Xe(e)&&(It(`Cancelled.`),process.exit(130)),e}async function pn(e,t){if(e.length>0)return e.map(e=>{let t=$t(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${Xt.map(e=>e.id).join(`, `)}.`);return t});let n=Qt(),r=n.length>0?n:[$t(`claude-code`)];return!t||!dn()?r:fn(await Ft({message:`Which agents should get the skills?`,options:Xt.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=>$t(e))}async function mn(e,t){return e?`global`:!t||!dn()?`project`:fn(await Ut({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 hn=`kit/`;function gn(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 _n(e,t,n){if(t.length>0)return yn(e,t,n,`skill`);if(!n||!dn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=fn(await Ft({message:`Which skills?`,options:e.map(e=>({value:e.id,label:En(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const vn=(e,t,n)=>yn(e,t,n,`kit`);async function yn(e,t,n,r){let i=[];for(let a of t){let t=Cn(e,a,r),o=t.length===1?t[0]:await wn(t,n,r);i.includes(o)||i.push(o)}return i}const bn=(e,t)=>Cn(e,t,`skill`);function xn(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 Sn=(e,t)=>xn(e,t);function Cn(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=xn(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 wn(e,t,n){let r=e[0].name,i=n===`kit`?hn:``;if(!t||!dn()){let t=e.map(e=>{let t=i+Tn(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=fn(await Ut({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:Tn(e)}))}));return e.find(e=>e.id===a)}const Tn=e=>`${e.organizationName}/${e.name}`,En=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 Dn(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?m(process.env.APPDATA,`agent-kit`):m(process.env.XDG_CONFIG_HOME??m(b(),`.config`),`agent-kit`)}const On=()=>m(V(),`credentials.json`);async function kn(){try{return JSON.parse(await O(On(),`utf8`))}catch{return{}}}async function H(){return(await kn())[B()]??null}async function An(e){let t=await kn();e?t[B()]=e:delete t[B()];let n=On();await D(p(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
|
|
76
|
+
`,{mode:384}),await ee(n,384)}const jn=()=>m(V(),`settings.json`);async function U(){try{return JSON.parse(await O(jn(),`utf8`))}catch{return{}}}async function Mn(e){let t={...await U(),...e};await D(V(),{recursive:!0,mode:448}),await k(jn(),JSON.stringify(t,null,2)+`
|
|
77
77
|
`)}function Nn(e=process.env){let t=e=>e!==void 0&&[`0`,`false`,`off`,`no`].includes(e.toLowerCase());return(e=>e!==void 0&&e!==``&&!t(e))(e.DO_NOT_TRACK)||t(e.AGENT_KIT_TELEMETRY)}function W(e){let t=g(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const Pn=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Fn(e){return e.split(`/`).some(e=>Pn.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const In=e=>fe(`sha256`).update(e).digest(`hex`);async function Ln(e){let t=await ae(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=g(e,m(r.parentPath,r.name)).split(v).join(`/`);if(Fn(t))continue;let i=new Uint8Array(await O(m(e,t)));n.push({path:t,size:i.byteLength,sha256:In(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Rn(e,t){let n=new Map(t.filter(e=>!Fn(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 zn(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 Bn(e,t){for(let n of e){if(!l(n))continue;let{paths:e}=Rn(await Ln(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Vn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?Bn(r.map(e=>m(e,t)),i.files):null}async function Hn(e){try{if(!(await re(e)).isSymbolicLink())return null}catch{return null}return _(p(e),await oe(e))}async function Un(e,t){for(let n of e){let e=await Hn(m(n,t));if(e)return e}return null}async function Wn(e,t){await ce(e,{recursive:!0,force:!0}),await D(p(e),{recursive:!0}),await ue(t,e,process.platform===`win32`?`junction`:`dir`)}const G=`SKILL.md`,Gn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},Kn=/[\u0000-\u001f\u007f\\:]/;function qn(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Gn.maxPathLength)return`Paths can be at most ${Gn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if(Kn.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 Jn(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function Yn(e){return e.slice(e.lastIndexOf(`/`)+1)}function Xn(e,t){let n=Jn(e)?Jn(e).split(`/`):[];for(let e of t.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){if(n.length===0)return null;n.pop()}else n.push(e)}return n.join(`/`)}var K=/* @__PURE__ */ A((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Zn=/* @__PURE__ */ A((e=>{var t=K();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Qn=/* @__PURE__ */ A((e=>{var t=K(),n=Zn();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})),$n=/* @__PURE__ */ A((e=>{var t=K(),n=Zn();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})),er=/* @__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})),tr=/* @__PURE__ */ A((e=>{var t=K();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),nr=/* @__PURE__ */ A((e=>{var t=er(),n=K(),r=tr();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}}})),rr=/* @__PURE__ */ A((e=>{var t=$n(),n=Zn(),r=K(),i=nr(),a=tr(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
|
|
79
79
|
/* istanbul ignore if */
|
|
@@ -215,17 +215,17 @@ n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2
|
|
|
215
215
|
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),di=/* @__PURE__ */ A((e=>{var t=ri(),n=Br(),r=Vr(),i=dr(),a=K(),o=li(),s=ui();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),J=(/* @__PURE__ */ A((e=>{var t=ri(),n=Br(),r=Rr(),i=Vr(),a=rr(),o=K(),s=mr(),c=q(),l=gr(),u=vr();si();var d=ci(),f=li(),p=ui(),m=di(),h=Zn();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();const fi=/^---[ \t]*$/;function pi(e){let t=_i(e,0);if(!fi.test(e.slice(0,t).replace(/\r$/,``)))return`no-frontmatter`;let n=vi(e,t),r=n;for(;n<e.length;){let t=_i(e,n);if(fi.test(e.slice(n,t).replace(/\r$/,``)))return{yamlFrom:r,yamlTo:n,bodyFrom:vi(e,t)};n=vi(e,t)}return`unclosed`}function mi(e){let t=pi(e);if(typeof t==`string`)return{ok:!1,reason:t};let n=e.slice(t.yamlFrom,t.yamlTo),r=(0,J.parseDocument)(n,{prettyErrors:!1}),i=e=>t.yamlFrom+e,a=r.errors.map(e=>({message:e.message.split(`
|
|
216
216
|
`)[0],from:i(e.pos[0]),to:i(Math.max(e.pos[1],e.pos[0]+1))})),o=r.contents,s=o===null||(0,J.isMap)(o),c=[];if((0,J.isMap)(o)){let e=gi(()=>r.toJS());for(let t of o.items){if(!(0,J.isScalar)(t.key)||!t.key.range)continue;let[n,r]=t.key.range,a=t.value?.range;c.push({key:String(t.key.value),keyFrom:i(n),keyTo:i(r),value:e?.[String(t.key.value)]??null,valueFrom:i(a?.[0]??r),valueTo:i(a?.[1]??r)})}}return{ok:!0,block:t,yamlErrors:a,isMapping:s,entries:c,body:e.slice(t.bodyFrom)}}function hi(e){let t=mi(e),n=e=>{if(!t.ok)return null;let n=t.entries.find(t=>t.key===e)?.value;return typeof n==`string`?n.trim():null};return{name:n(`name`),description:n(`description`)}}function gi(e){try{let t=e();return t&&typeof t==`object`?t:null}catch{return null}}function _i(e,t){let n=e.indexOf(`
|
|
217
217
|
`,t);return n===-1?e.length:n}function vi(e,t){return Math.min(t+1,e.length)}const yi=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,bi=/^[a-z0-9]+(-[a-z0-9]+)*$/;function xi(e,t){let n=[],r=e.slice(t);for(let e of r.matchAll(yi)){let r=e[1];if(/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(r))continue;let i=Ti(r.split(`#`)[0].split(`?`)[0]);if(i===``)continue;let a=t+e.index+e[0].indexOf(r);n.push({target:r,path:i,from:a,to:a+r.length})}return n}function Si(e){if(e.startsWith(`/`))return null;let t=[`\0self`];for(let n of e.split(`/`))if(n!==``&&n!==`.`){if(n===`..`){if(t.length===0)return null;t.pop()}else t.push(n)}let n=t[0];return n&&n!==`\0self`&&bi.test(n)?n:null}function Ci(e){let t=mi(e),n=t.ok?t.block.bodyFrom:0,r=[];for(let t of xi(e,n)){let e=Si(t.path);e&&r.push({...t,name:e})}return r}function wi(e){let t=mi(e),n=t.ok?t.entries.find(e=>e.key===`name`)?.value:null,r=Ci(e).map(e=>e.name);return[...new Set(r)].filter(e=>e!==n)}function Ti(e){try{return decodeURIComponent(e)}catch{return e}}const Ei=`report-session-issue`,Di=/skills\/([a-z0-9][a-z0-9-]*)\/SKILL\.md/g;function Oi(e,t){if(e===`Skill`){let e=t?.skill;return typeof e==`string`?[ki(e)]:[]}return[...(typeof t==`string`?t:JSON.stringify(t??``)).matchAll(Di)].map(e=>e[1])}const ki=e=>e.slice(e.lastIndexOf(`:`)+1).replace(/^\//,``);function Ai(e){let t=e.events.findIndex(e=>ji(e));if(t===-1)return e;let n=t;for(let r=t;r>=0;r--){let t=e.events[r];if(t.type===`user`&&t.message.content.some(e=>e.type===`text`)){n=r;break}}let r=e.events.slice(0,n);return{...e,events:r,loaded:[...new Set(r.flatMap(Mi))]}}function ji(e){return Mi(e).includes(Ei)}function Mi(e){return e.type===`system`?[]:e.message.content.flatMap(t=>t.type===`tool_use`?Oi(t.name,t.input):t.type===`text`&&e.type===`user`?[...t.text.matchAll(/<command-name>\/?([\w:-]+)<\/command-name>/g)].map(e=>ki(e[1])):[])}const Ni=e=>e?wi(new TextDecoder().decode(e)):[];async function Pi(e,t,n,r,i){let a=[],o=[],s=new Set(n.map(e=>e.name)),c=[...n];for(;c.length>0;){let n=c.shift();for(let l of n.references){if(s.has(l))continue;s.add(l);let u=t.find(e=>e.name===l&&e.organizationId===n.organizationId);if(!u){o.push({name:l,by:n.name});continue}let d=Fi(u,r,i);a.push({skill:u,by:n.name,status:d}),d===`new`&&c.push({name:u.name,organizationId:u.organizationId,references:await Ii(e,u.id)})}}return{dependencies:a,missing:o}}function Fi(e,t,n){let r=t.skills[e.name];return r?r.id===e.id?`installed`:`conflict`:e.name===`report-session-issue`?`new`:n.some(t=>l(m(t,e.name)))?`conflict`:`new`}async function Ii(e,t){let n=(await e.getSkill(t)).files.find(e=>e.path===G);return n?Ni(await e.getBlob(t,n.sha256)):[]}async function Li(e,t,n){let{dependencies:r,missing:i}=e;for(let{name:e,by:t}of i)F.warn(`${t} links to ${e}, which isn't in its organization.`);let a=r.filter(e=>e.status===`new`),o=r.filter(e=>e.status===`conflict`);if(a.length===0&&o.length===0)return[];let s=/* @__PURE__ */ new Map;for(let e of[...a,...o])s.set(e.by,[...s.get(e.by)??[],e.skill.name]);F.info([...s].map(([e,t])=>`${e} uses ${t.length===1?`another skill`:`${t.length} other skills`}: ${t.join(`, `)}`).join(`
|
|
218
|
-
`));let c=n&&dn(),l=[];a.length>0&&(!c||
|
|
219
|
-
`)}const Wi=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];function Gi(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Wi(e,i.id);if(n===void 0){e.skills[i.name]?r.clashes.push(i):r.install.push(i);continue}let a=e.skills[n].kits;a&&!a.includes(t)&&r.tag.push(n)}let i=new Set(n.map(e=>e.id));for(let[n,a]of Object.entries(e.skills))a.kits?.includes(t)&&!i.has(a.id)&&(a.kits.length>1?r.untag.push(n):r.remove.push(n));return r}function Ki(e,t,n){if(t===n)return;let r=e.kits[t];if(r){delete e.kits[t],e.kits[n]=r;for(let r of Object.values(e.skills))r.kits?.includes(t)&&(r.kits=[...new Set(r.kits.map(e=>e===t?n:e))])}}async function qi(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Gi(t,n.name,n.skills),a={installed:[],removed:[],skipped:[],kept:[]};for(let e of i.clashes)F.warn(`${e.name} from kit/${n.name} wasn't installed: another skill named ${e.name} already is.`),a.skipped.push(e.name);for(let e of i.tag){let r=t.skills[e];r.kits=[...r.kits??[],n.name]}for(let e of i.untag){let r=t.skills[e];r.kits=r.kits.filter(e=>e!==n.name)}let o=new Set(i.install.map(e=>e.id)),s=r.reinstall?n.skills.filter(e=>!i.clashes.some(t=>t.id===e.id)):i.install,c=Bt();for(let i of s){let s=Wi(t,i.id),l=s?t.skills[s]:void 0,u=l&&!l.kits?l.agents:r.agents;c.start(`Installing ${i.name}`);let d;try{d=await Bi(e,i.id,r.dirsOf(u))}catch(e){throw c.error(`${i.name} failed`),e}c.stop(`${d.name} v${d.version}`),s&&s!==d.name&&delete t.skills[s],delete t.public?.[d.name],t.skills[d.name]={id:d.id,version:d.version,agents:u,kits:o.has(i.id)?[n.name]:l?.kits&&[.../* @__PURE__ */ new Set([...l.kits,n.name])]},o.has(i.id)&&a.installed.push(d.name)}for(let o of i.remove){let i=t.skills[o],s=await Un(r.dirsOf(i.agents),o);if(s){F.warn(`${o} was taken out of kit/${n.name}, but it uses ${W(s)} (\`a-kit link\`); left it.`),a.kept.push(o);continue}let c=await Vn(e,o,i,r.dirsOf(i.agents));c?(F.warn(`${o} was taken out of kit/${n.name}, but it has edits here that aren't in agent kit (${zn(c.paths)}); left it. To keep them, make them in your organization's repository; otherwise delete its folder.`),a.kept.push(o)):(await Ji(t,o,r.dirsOf),a.removed.push(o))}return a}async function Ji(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await ce(m(e,t),{recursive:!0,force:!0});delete e.skills[t]}function Yi(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const Xi=e=>Yi(e)!==null;function Zi(e,t){let n=[],r=[];for(let i of t)Xi(i)&&
|
|
218
|
+
`));let c=n&&dn(),l=[];a.length>0&&(!c||fn(await Mt({message:`Install ${a.length===1?a[0].skill.name:`these ${a.length} skills`} too?`,initialValue:!0})))&&l.push(...a.map(e=>e.skill));let u=t.map(W).join(`, `);for(let{skill:e}of o){let t=`There's already a different skill named ${e.name} in ${u}.`;c?fn(await Mt({message:`${t} Replace it with the one from agent kit?`,initialValue:!1}))&&l.push(e):F.warn(`${t} Left it alone; \`a-kit add ${e.name}\` replaces it.`)}return l}const Ri=e=>fe(`sha256`).update(e).digest(`hex`),zi=(e,t)=>({getSkill:async n=>{let r=t&&t.ref===n?t:await e.getPublicSkill(n);return{...r,id:r.ref}},getBlob:(t,n)=>e.getPublicBlob(t,n)});async function Bi(e,t,n,r=`latest`){let i=await e.getSkill(t,r);if(!/^[a-z0-9-]+$/.test(i.name))throw Error(`"${i.name}" isn't a valid skill name.`);let a=[];for(let t of i.files){let n=qn(t.path);if(n)throw Error(`${i.name}: ${t.path}: ${n}`);let r=await e.getBlob(i.id,t.sha256);if(Ri(r)!==t.sha256)throw Error(`${i.name}: ${t.path} didn't download intact.`);a.push({path:t.path,bytes:r})}for(let e of n){let t=m(e,i.name);await ce(t,{recursive:!0,force:!0});for(let e of a){let n=m(t,e.path);await D(p(n),{recursive:!0}),await k(n,e.bytes)}}let o=a.find(e=>e.path===G)?.bytes;return{...i,references:Ni(o)}}const Vi=(e,t,n)=>({id:e.id,version:e.version,agents:t,...n!==`latest`&&{channel:n}}),Hi=e=>Kt(e.channel)?e.channel:`latest`,Y=(e,t=process.cwd())=>e===`global`?m(V(),`global.lock.json`):m(t,`agent-kit.lock.json`);async function X(e){try{let t=JSON.parse(await O(e,`utf8`));return{version:1,kits:t.kits??{},skills:t.skills??{},public:t.public??{}}}catch{return{version:1,kits:{},skills:{},public:{}}}}async function Ui(e,t){let n=e=>Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t))),r=Object.fromEntries(Object.entries(n(t.skills)).map(([e,t])=>{let{kits:n,...r}=t;return[e,n?.length?{...r,kits:[...n].sort()}:r]})),i=Object.keys(t.kits).length>0?n(t.kits):void 0,a=t.public&&Object.keys(t.public).length>0?n(t.public):void 0;await D(p(e),{recursive:!0}),await k(e,JSON.stringify({version:t.version,kits:i,skills:r,public:a},null,2)+`
|
|
219
|
+
`)}const Wi=(e,t)=>Object.entries(e.skills).find(([,e])=>e.id===t)?.[0];function Gi(e,t,n){let r={install:[],tag:[],untag:[],remove:[],clashes:[]};for(let i of n){let n=Wi(e,i.id);if(n===void 0){e.skills[i.name]?r.clashes.push(i):r.install.push(i);continue}let a=e.skills[n].kits;a&&!a.includes(t)&&r.tag.push(n)}let i=new Set(n.map(e=>e.id));for(let[n,a]of Object.entries(e.skills))a.kits?.includes(t)&&!i.has(a.id)&&(a.kits.length>1?r.untag.push(n):r.remove.push(n));return r}function Ki(e,t,n){if(t===n)return;let r=e.kits[t];if(r){delete e.kits[t],e.kits[n]=r;for(let r of Object.values(e.skills))r.kits?.includes(t)&&(r.kits=[...new Set(r.kits.map(e=>e===t?n:e))])}}async function qi(e,t,n,r){t.kits[n.name]={id:n.id,agents:r.agents};let i=Gi(t,n.name,n.skills),a={installed:[],removed:[],skipped:[],kept:[]};for(let e of i.clashes)F.warn(`${e.name} from kit/${n.name} wasn't installed: another skill named ${e.name} already is.`),a.skipped.push(e.name);for(let e of i.tag){let r=t.skills[e];r.kits=[...r.kits??[],n.name]}for(let e of i.untag){let r=t.skills[e];r.kits=r.kits.filter(e=>e!==n.name)}let o=new Set(i.install.map(e=>e.id)),s=r.reinstall?n.skills.filter(e=>!i.clashes.some(t=>t.id===e.id)):i.install,c=Bt();for(let i of s){let s=Wi(t,i.id),l=s?t.skills[s]:void 0,u=l&&!l.kits?l.agents:r.agents;c.start(`Installing ${i.name}`);let d;try{d=await Bi(e,i.id,r.dirsOf(u))}catch(e){throw c.error(`${i.name} failed`),e}c.stop(`${d.name} v${d.version}`),s&&s!==d.name&&delete t.skills[s],delete t.public?.[d.name],t.skills[d.name]={id:d.id,version:d.version,agents:u,kits:o.has(i.id)?[n.name]:l?.kits&&[.../* @__PURE__ */ new Set([...l.kits,n.name])]},o.has(i.id)&&a.installed.push(d.name)}for(let o of i.remove){let i=t.skills[o],s=await Un(r.dirsOf(i.agents),o);if(s){F.warn(`${o} was taken out of kit/${n.name}, but it uses ${W(s)} (\`a-kit link\`); left it.`),a.kept.push(o);continue}let c=await Vn(e,o,i,r.dirsOf(i.agents));c?(F.warn(`${o} was taken out of kit/${n.name}, but it has edits here that aren't in agent kit (${zn(c.paths)}); left it. To keep them, make them in your organization's repository; otherwise delete its folder.`),a.kept.push(o)):(await Ji(t,o,r.dirsOf),a.removed.push(o))}return a}async function Ji(e,t,n){let r=e.skills[t];if(/^[a-z0-9-]+$/.test(t))for(let e of n(r.agents))await ce(m(e,t),{recursive:!0,force:!0});delete e.skills[t]}function Yi(e){let t=e.trim().match(/^([^/\s]+)\/([^/\s]+)$/);return t?{org:t[1].toLowerCase(),name:t[2]}:null}const Xi=e=>Yi(e)!==null;function Zi(e,t){let n=[],r=[];for(let i of t)Xi(i)&&Sn(e,i).length===0?r.push(i):n.push(i);return{own:n,others:r}}async function Qi(e,t,n){let r=[];for(let i of t){let t=Yi(i);try{let n=await e.getPublicSkill(`${t.org}/${t.name}`);r.some(e=>e.ref===n.ref)||r.push(n)}catch(e){throw e instanceof R&&e.status===404?Error(n?`There's no skill "${i}" in your organizations, and no public one. See yours with ${L(`list`)}.`:`There's no public skill "${i}". If it's one of your organization's, log in first: ${L(`login`)}.`):e}}return r}async function $i(e,t,n,r,i){let a=Bt();for(let o of n){if(t.skills[o.name])throw Error(`You already have a skill named "${o.name}" installed from your organization; ${o.ref} would replace it. Remove it first.`);a.start(`Installing ${o.ref}`);try{let n=await Bi(zi(e,o),o.ref,i);t.public??={},t.public[n.name]={ref:n.ref,version:n.version,agents:r},a.stop(`${n.name} v${n.version} (${n.ref})`)}catch(e){throw a.error(`${o.ref} failed`),e}await e.countInstall(o.ref).catch(()=>{})}}function ea(e){let[t,n]=process.platform===`darwin`?[`open`,[e]]:process.platform===`win32`?[`cmd`,[`/c`,`start`,``,e.replace(/&/g,`^&`)]]:[`xdg-open`,[e]];try{let e=ge(t,n,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}const ta=()=>m(V(),`bin`,`a-kit.mjs`);function na(){let e=_e(import.meta.url);return e.endsWith(`.mjs`)?e:null}async function ra(e){let t=ta();return await D(p(t),{recursive:!0}),e!==t&&await ne(e,t),t}async function ia(e,t,n){let r=`${e}.${process.pid}`,i=[];try{await se(e,r),i=oa(await O(r,`utf8`)),await ce(r,{force:!0})}catch{}let a=[...i,n].slice(-500),o=0;for(let n=0;n<a.length;n+=100){let r=a.slice(n,n+100);try{await t(r),o+=r.length}catch(t){if(!aa(t))continue;let r=a.slice(n);return await D(p(e),{recursive:!0,mode:448}),await E(e,r.map(e=>JSON.stringify(e)).join(`
|
|
220
220
|
`)+`
|
|
221
221
|
`),{sent:o,queued:r.length}}}return{sent:o,queued:0}}const aa=e=>!(e instanceof R)||e.status===0||e.status===429||e.status>=500;function oa(e){return e.split(`
|
|
222
|
-
`).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}async function sa(e,t,n,r=b()){let i=[Y(`global`)],a=ca(n,r);a&&i.push(a);for(let n of i){let r=(await X(n)).skills[e];if(r?.agents.includes(t))return r}return null}function ca(e,t){let n=e,{root:r}=h(e);for(;n&&n!==t;){let e=Y(`project`,n);if(l(e))return e;if(n===r)break;n=p(n)}return null}async function la(){let e=m(
|
|
223
|
-
`),t}async function ua(e,t,n,r={sessionId:null,repository:null,branch:null},i=/* @__PURE__ */ new Date){return{...r,id:pe(),skillId:e.id,version:e.version,agent:t,machineId:await la(),machineName:x()||null,trigger:n,occurredAt:i.toISOString()}}const da=()=>m(
|
|
222
|
+
`).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}})}async function sa(e,t,n,r=b()){let i=[Y(`global`)],a=ca(n,r);a&&i.push(a);for(let n of i){let r=(await X(n)).skills[e];if(r?.agents.includes(t))return r}return null}function ca(e,t){let n=e,{root:r}=h(e);for(;n&&n!==t;){let e=Y(`project`,n);if(l(e))return e;if(n===r)break;n=p(n)}return null}async function la(){let e=m(V(),`machine.json`);try{let t=JSON.parse(await O(e,`utf8`));if(typeof t.id==`string`&&t.id)return t.id}catch{}let t=pe();return await D(p(e),{recursive:!0,mode:448}),await k(e,JSON.stringify({id:t},null,2)+`
|
|
223
|
+
`),t}async function ua(e,t,n,r={sessionId:null,repository:null,branch:null},i=/* @__PURE__ */ new Date){return{...r,id:pe(),skillId:e.id,version:e.version,agent:t,machineId:await la(),machineName:x()||null,trigger:n,occurredAt:i.toISOString()}}const da=()=>m(V(),`pending-activations.jsonl`),fa=(e,t)=>ia(da(),e,t),pa=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function ma(e){return e.match(pa)?.[0]??null}const ha={"claude-code":`claude`,codex:`codex`,"gemini-cli":`gemini`};function ga(e=b()){let t=[...(process.env.PATH??``).split(f),p(process.execPath),m(e,`.local`,`bin`),m(e,`.claude`,`local`),m(e,`.npm-global`,`bin`),m(e,`.bun`,`bin`),m(e,`.volta`,`bin`),`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`];return[...new Set(t.filter(Boolean))]}const _a=async e=>{let t=ga(),n=await va(e,t);return n?new Promise(e=>{me(n,[`--version`],{timeout:5e3,env:{...process.env,PATH:t.join(f)}},(t,n)=>e(t?null:n))}):null};async function va(e,t){for(let n of t){let t=m(n,e);try{return await T(t,te.X_OK),t}catch{}}return null}async function ya(e,t=_a){let n=await Promise.all(e.map(async e=>{let n=ha[e],r=n?await t(n):null;return[e,r?ma(r):null]}));return Object.fromEntries(n.filter(e=>e[1]!==null))}async function ba(e,t,n){let r=await e.listOrganizations(),i;if(n)i=xa(r,n);else if(r.length<=1)i=r[0]??null;else if(dn())i=await Sa(r,t.organizationId);else return null;return i&&await An({...t,organizationId:i.id}),i}function xa(e,t){let n=t.trim().toLowerCase(),r=e.find(e=>e.id===t||e.name.toLowerCase()===n);if(!r)throw Error(`None of your organizations is "${t}". Yours: ${e.map(e=>e.name).join(`, `)}.`);return r}async function Sa(e,t){let n=fn(await Ut({message:`Which organization's Machines page should this machine show up on?`,options:e.map(e=>({value:e.id,label:e.name})),initialValue:e.some(e=>e.id===t)?t:void 0}));return e.find(e=>e.id===n)}const Ca=(e,t)=>new Promise(n=>{me(e,t,{timeout:15e3},(e,t,r)=>{n({ok:!e,output:`${t}${r}`.trim()})})}),wa=e=>new URL(e).host.toLowerCase().replace(/[^a-z0-9]+/g,`-`),Ta=e=>`agent-kit-heartbeat-${wa(e)}`,Ea=e=>`com.agent-kit.heartbeat.${wa(e)}`;function Da(e,t=process.platform,n=b()){if(t===`linux`){let t=m(process.env.XDG_CONFIG_HOME??m(n,`.config`),`systemd`,`user`);return[m(t,`${Ta(e)}.service`),m(t,`${Ta(e)}.timer`)]}return t===`darwin`?[m(n,`Library`,`LaunchAgents`,`${Ea(e)}.plist`)]:[]}function Oa(e){let t=e=>`"${e.replace(/(["\\])/g,`\\$1`)}"`,n=e.configDir?`Environment=${t(`AGENT_KIT_CONFIG_DIR=${e.configDir}`)}\n`:``;return[`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Service]\nType=oneshot\n${n}ExecStart=${t(e.node)} ${t(e.script)} heartbeat send --api ${t(e.api)}\n`,`[Unit]\nDescription=agent kit heartbeat (${e.api})\n\n[Timer]\nOnBootSec=1min\nOnUnitActiveSec=300s\n\n[Install]\nWantedBy=timers.target\n`]}function ka(e){let t=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`),n=[e.node,e.script,`heartbeat`,`send`,`--api`,e.api],r=e.configDir?` <key>EnvironmentVariables</key>\n <dict>\n <key>AGENT_KIT_CONFIG_DIR</key>\n <string>${t(e.configDir)}</string>\n </dict>\n`:``;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
224
224
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
225
225
|
<plist version="1.0">
|
|
226
226
|
<dict>
|
|
227
|
-
<key>Label</key>\n <string>${t(Ea(e.api))}</string>\n <key>ProgramArguments</key>\n <array>\n`+n.map(e=>` <string>${t(e)}</string>\n`).join(``)+` </array>\n${r} <key>StartInterval</key>\n <integer>300</integer>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>/dev/null</string>\n <key>StandardErrorPath</key>\n <string>/dev/null</string>\n</dict>\n</plist>\n`}async function Aa(e){let t=e.platform??process.platform,n=e.run??Ca,r=Da(e.api,t,e.home);if(r.length===0)return{status:`skipped`,reason:`the heartbeat timer only runs on Linux (systemd) and macOS`};let i=t===`linux`?Oa(e):[ka(e)];if((await Promise.all(r.map(e=>O(e,`utf8`).catch(()=>null)))).every((e,t)=>e===i[t]))return{status:`already`};for(let[e,t]of r.entries())await D(p(t),{recursive:!0}),await k(t,i[e]);if(t===`linux`){await n(`systemctl`,[`--user`,`daemon-reload`]);let t=await n(`systemctl`,[`--user`,`enable`,`--now`,`${Ta(e.api)}.timer`]);if(!t.ok)return await Pa(r),{status:`skipped`,reason:`systemd couldn't start it${t.output?`: ${t.output}`:``}`}}else{let t=`gui/${process.getuid?.()??501}`;await n(`launchctl`,[`bootout`,`${t}/${Ea(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await Pa(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function ja(e,{platform:t=process.platform,home:n,run:r=Ca}={}){if(!await Ma(e,t,n))return!1;let i=Da(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${Ta(e)}.timer`]),await Pa(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Ea(e)}`]),await Pa(i)),!0}async function Ma(e,t=process.platform,n){let r=Da(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Na(e=Ca,t=process.platform){if(t!==`linux`)return null;let n=process.env.USER;if(!n)return null;let{ok:r,output:i}=await e(`loginctl`,[`show-user`,n,`--property=Linger`]);return r&&i.trim()===`Linger=no`?"The timer stops while you're logged out of this machine. To keep it reporting, run `loginctl enable-linger`.":null}async function Pa(e){for(let t of e)await ce(t,{force:!0})}async function Fa(e,t){let n=await X(Y(`global`)),r=Qt().map(e=>e.id);return{machineId:await la(),hostname:x()||`unknown`,platform:S(),arch:y(),cliVersion:Yt,agents:r,agentVersions:await ya(r,t),skills:Object.entries(n.skills).map(([e,t])=>({id:t.id,name:e,version:t.version,...t.channel&&{channel:t.channel},agents:t.agents})),every:e?300:null}}const Ia=()=>m(
|
|
228
|
-
`),n.ok}catch{return!1}}async function za(e=na()){try{if(Nn()||(await
|
|
227
|
+
<key>Label</key>\n <string>${t(Ea(e.api))}</string>\n <key>ProgramArguments</key>\n <array>\n`+n.map(e=>` <string>${t(e)}</string>\n`).join(``)+` </array>\n${r} <key>StartInterval</key>\n <integer>300</integer>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>/dev/null</string>\n <key>StandardErrorPath</key>\n <string>/dev/null</string>\n</dict>\n</plist>\n`}async function Aa(e){let t=e.platform??process.platform,n=e.run??Ca,r=Da(e.api,t,e.home);if(r.length===0)return{status:`skipped`,reason:`the heartbeat timer only runs on Linux (systemd) and macOS`};let i=t===`linux`?Oa(e):[ka(e)];if((await Promise.all(r.map(e=>O(e,`utf8`).catch(()=>null)))).every((e,t)=>e===i[t]))return{status:`already`};for(let[e,t]of r.entries())await D(p(t),{recursive:!0}),await k(t,i[e]);if(t===`linux`){await n(`systemctl`,[`--user`,`daemon-reload`]);let t=await n(`systemctl`,[`--user`,`enable`,`--now`,`${Ta(e.api)}.timer`]);if(!t.ok)return await Pa(r),{status:`skipped`,reason:`systemd couldn't start it${t.output?`: ${t.output}`:``}`}}else{let t=`gui/${process.getuid?.()??501}`;await n(`launchctl`,[`bootout`,`${t}/${Ea(e.api)}`]);let i=await n(`launchctl`,[`bootstrap`,t,r[0]]);if(!i.ok)return await Pa(r),{status:`skipped`,reason:`launchd couldn't load it${i.output?`: ${i.output}`:``}`}}return{status:`installed`}}async function ja(e,{platform:t=process.platform,home:n,run:r=Ca}={}){if(!await Ma(e,t,n))return!1;let i=Da(e,t,n);return t===`linux`?(await r(`systemctl`,[`--user`,`disable`,`--now`,`${Ta(e)}.timer`]),await Pa(i),await r(`systemctl`,[`--user`,`daemon-reload`])):(await r(`launchctl`,[`bootout`,`${`gui/${process.getuid?.()??501}`}/${Ea(e)}`]),await Pa(i)),!0}async function Ma(e,t=process.platform,n){let r=Da(e,t,n);return r.length!==0&&(await Promise.all(r.map(e=>O(e).then(()=>!0,()=>!1)))).every(Boolean)}async function Na(e=Ca,t=process.platform){if(t!==`linux`)return null;let n=process.env.USER;if(!n)return null;let{ok:r,output:i}=await e(`loginctl`,[`show-user`,n,`--property=Linger`]);return r&&i.trim()===`Linger=no`?"The timer stops while you're logged out of this machine. To keep it reporting, run `loginctl enable-linger`.":null}async function Pa(e){for(let t of e)await ce(t,{force:!0})}async function Fa(e,t){let n=await X(Y(`global`)),r=Qt().map(e=>e.id);return{machineId:await la(),hostname:x()||`unknown`,platform:S(),arch:y(),cliVersion:Yt,agents:r,agentVersions:await ya(r,t),skills:Object.entries(n.skills).map(([e,t])=>({id:t.id,name:e,version:t.version,...t.channel&&{channel:t.channel},agents:t.agents})),every:e?300:null}}const Ia=()=>m(V(),`heartbeat.json`);async function La(){try{return JSON.parse(await O(Ia(),`utf8`))}catch{return null}}async function Ra(){try{if(Nn()||(await U()).heartbeat===!1)return!1;let e=await H();if(!e)return!1;let t={...await Fa(await Ma(B())),...e.organizationId&&{organizationId:e.organizationId}},n={sentAt:(/* @__PURE__ */ new Date()).toISOString(),ok:!0};try{n.organization=(await z(B(),e.token).sendHeartbeat(t,AbortSignal.timeout(5e3))).organization}catch{n.ok=!1}return await D(V(),{recursive:!0,mode:448}),await k(Ia(),JSON.stringify(n)+`
|
|
228
|
+
`),n.ok}catch{return!1}}async function za(e=na()){try{if(Nn()||(await U()).heartbeat===!1)return;let t=await H();if(!t||(t.organizationId||await ba(z(B(),t.token),t).catch(()=>null),!e))return;let n=await Ma(B()),r=await ra(e);if((await Aa({node:process.execPath,script:r,api:B(),configDir:process.env.AGENT_KIT_CONFIG_DIR})).status===`installed`&&!n){F.info("This machine now reports to agent kit every 5 minutes (its name, agents and their versions, and global skills), so your organization's Machines page shows it. Turn it off with `a-kit heartbeat off`.");let e=await Na();e&&F.warn(e)}await Ra()}catch{}}const Ba=e=>new Promise(t=>setTimeout(t,e));async function Va(){let e=await z(B()).startLogin();F.step(`Opening agent kit in your browser. Log in, or sign up if you're new, and approve this code:\n\n ${e.userCode}\n\nIf it doesn't open, go to ${e.verificationUrl}`),ea(e.verificationUrl);let t=Bt();t.start(`Waiting for you to approve it`);let n=z(B()),r=Date.now()+e.expiresIn*1e3;for(;Date.now()<r;){await Ba(e.interval*1e3);let r;try{r=await n.pollLogin(e.deviceCode)}catch(e){if(e instanceof R&&e.status===410)break;if(e instanceof R&&e.code===`NETWORK`)continue;throw t.error(`Login failed`),e}if(r.status===`approved`){let n={token:r.token,user:r.user,webUrl:new URL(e.verificationUrl).origin};return await An(n),t.stop(`Logged in as ${Wa(r.user)}`),await za(),n}}throw t.error(`The code expired`),Error(`The login expired before it was approved. Run ${L(`login`)} again.`)}async function Ha(){let e=await H();if(!e)return null;try{let t=await z(B(),e.token).me();return{...e,user:t}}catch(t){if(t instanceof R&&t.status===401){if(await An(null),e.user.kind===`bot`)throw Error(`${Wa(e.user)} isn't logged in anymore: its token was revoked. Log in with a new one: ${L(`login --token`)} < bot-token`);return null}throw t}}async function Ua(){let e=await H();if(!e){if(!dn())throw Error(`You're not logged in. Run ${L(`login`)} first.`);F.info(`First, log in to agent kit. New here? You'll sign up on the way.`),e=await Va()}return{api:z(B(),e.token),credentials:e}}const Wa=e=>e.kind===`bot`?`${e.name} (bot)`:e.email,Ga=e=>`You don't have skills yet. Create or import one at ${e}/app/skills, then install it with ${L(`add`)}.`,Ka=(e=b())=>m(process.env.CLAUDE_CONFIG_DIR??m(e,`.claude`),`settings.json`),qa=(e,t)=>`node "${e}" hook claude-code --api "${t}"`,Ja=e=>typeof e.command==`string`&&e.command.includes(`a-kit.mjs`)&&e.command.includes(` hook claude-code`),Ya=[`telemetry`,`autoUpdate`],Xa={telemetry:[{event:`PostToolUse`,matcher:`Skill`},{event:`UserPromptSubmit`},{event:`SessionStart`,matcher:`startup|resume|clear`,role:`session`},{event:`Stop`},{event:`SessionEnd`}],autoUpdate:[{event:`SessionStart`,matcher:`startup|resume`}]},Za=(e,{role:t})=>t?`${e} ${t}`:e;function Qa(e){if(!e.hooks)return e;let t={};for(let[n,r]of Object.entries(e.hooks)){if(!Array.isArray(r)){t[n]=r;continue}let e=r.map(e=>({...e,hooks:e.hooks?.filter(e=>!Ja(e))})).filter((e,t)=>(e.hooks?.length??0)>0||!r[t].hooks);e.length>0&&(t[n]=e)}let{hooks:n,...r}=e;return Object.keys(t).length>0?{...r,hooks:t}:r}function $a(e,t,n=Ya){let r=Qa(e),i={...r.hooks};for(let e of n.flatMap(e=>Xa[e])){let n={type:`command`,command:Za(t,e),async:!0,timeout:10},{event:r,matcher:a}=e;i[r]=[...i[r]??[],a?{matcher:a,hooks:[n]}:{hooks:[n]}]}return Object.keys(i).length>0?{...r,hooks:i}:r}const eo=(e,t,n)=>e.hooks?.[t.event]?.some(e=>e.matcher===t.matcher&&e.hooks?.some(e=>Ja(e)&&(!n||e.command===Za(n,t))))??!1;function to(e,t,n){return Xa[t].every(t=>eo(e,t,n))}function no(e,t,n){return Ya.every(r=>n.includes(r)?to(e,r,t):Xa[r].every(t=>!eo(e,t)))}function ro(e){if(e.hook_event_name===`PostToolUse`&&e.tool_name===`Skill`){let t=e.tool_input?.skill??e.tool_input?.command,n=typeof t==`string`?t.replace(/^\//,``):``;return io(n)?{name:n,trigger:`model`}:null}if(e.hook_event_name===`UserPromptSubmit`&&typeof e.prompt==`string`){let t=e.prompt.match(/^\s*\/([^\s]+)/)?.[1]??``;return io(t)?{name:t,trigger:`user`}:null}return null}const io=e=>/^[a-z0-9][a-z0-9-]*$/.test(e);async function ao(){let e=await U();return Ya.filter(t=>e[t]!==!1)}async function oo(e=na(),t=Ka(),n){let r=n??await ao(),i=await uo(t);if(i===`invalid`)return{status:`skipped`,reason:`${t} isn't valid JSON`};if(r.length===0)return Ya.some(e=>to(i,e))?(await fo(t,Qa(i)),{status:`installed`,added:[]}):{status:`already`};if(!e)return{status:`skipped`,reason:`not running from a build`};let a=await ra(e),o=qa(a,B());if(no(i,o,r))return{status:`already`};let s=r.filter(e=>!to(i,e));return await fo(t,$a(i,o,r)),{status:`installed`,added:s}}async function so(e=Ka()){let t=await uo(e);return t===`invalid`?[]:Ya.filter(e=>to(t,e))}const co={telemetry:"Claude Code now reports to agent kit each time it loads one of these skills, and when its sessions start and end, so your organization sees which ones get used. Turn it off with `a-kit telemetry off`.",autoUpdate:"Claude Code now checks the skills you installed everywhere (-g) for changes when a session starts, and updates them in the background when they changed. Turn it off with `a-kit auto-update off`."};async function lo(e){if(e.includes(`claude-code`))try{let e=await oo();if(e.status===`installed`)for(let t of e.added)F.info(co[t])}catch{}await za()}async function uo(e){let t;try{t=await O(e,`utf8`)}catch{return{}}if(!t.trim())return{};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?e:`invalid`}catch{return`invalid`}}async function fo(e,t){await D(p(e),{recursive:!0}),await k(e,JSON.stringify(t,null,2)+`
|
|
229
229
|
`)}const po=(e=`npx -y useakit@next`)=>`---
|
|
230
230
|
name: ${Ei}
|
|
231
231
|
description: Reports this conversation to agent kit because it went wrong, so it can become an eval. Use when the developer says the session went badly and asks to report it ("report this", "reportá esta conversación", "mandalo a agent kit"), or wants it turned into an eval.
|
|
@@ -266,42 +266,43 @@ Only the conversation up to the developer's request to report it is sent; this p
|
|
|
266
266
|
4. **Confirm.** Tell the developer in a few lines: the title, the skills it links, what was taken out, and that long tool outputs and written files are cut to 2,000 characters (\`--full-outputs\` keeps them whole). Ask before sending.
|
|
267
267
|
|
|
268
268
|
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.
|
|
269
|
-
`;async function mo(e){for(let t of e){let e=m(t,Ei);await D(e,{recursive:!0}),await k(m(e,`SKILL.md`),po())}}const ho=e=>t=>en(t.map(e=>$t(e)).filter(e=>e!==void 0),e);async function go(e,t,n,r,i=`latest`,a){let o=en(n,r),s=Y(r),c=await X(s);await mo(o);try{await _o(e,c,t,n,o,i,a)}finally{await Ui(s,c)}return await lo(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function _o(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=Bt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Bi(e,o.id,i,a);l.push(n),t.skills[n.name]=Vi(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 Li(await Pi(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await _o(e,t,u,r,i)}async function vo(e,t){Lt(`agent kit`);let n=!t.yes,r=
|
|
270
|
-
`)}const wo=(e,t)=>{ge(process.execPath,[e,...t],{cwd:b(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},To=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function Eo(e,t=wo,n=Date.now()){return(await
|
|
271
|
-
`)[
|
|
272
|
-
`)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{
|
|
273
|
-
`)[0]}`})
|
|
274
|
-
|
|
269
|
+
`;async function mo(e){for(let t of e){let e=m(t,Ei);await D(e,{recursive:!0}),await k(m(e,`SKILL.md`),po())}}const ho=e=>t=>en(t.map(e=>$t(e)).filter(e=>e!==void 0),e);async function go(e,t,n,r,i=`latest`,a){let o=en(n,r),s=Y(r),c=await X(s);await mo(o);try{await _o(e,c,t,n,o,i,a)}finally{await Ui(s,c)}return await lo(n.map(e=>e.id)),{dirs:o,lockFile:s}}async function _o(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=Bt(),l=[];for(let o of n){c.start(`Installing ${o.name}`);try{let n=await Bi(e,o.id,i,a);l.push(n),t.skills[n.name]=Vi(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 Li(await Pi(e,o.catalog,l,t,i),i,o.ask);u.length>0&&await _o(e,t,u,r,i)}async function vo(e,t){Lt(`agent kit`);let n=!t.yes,r=gn(e),i=r.kits.length===0&&r.skills.length>0&&r.skills.every(Xi)&&await H()===null?null:await Ua(),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?Zi(s,r.skills):{own:[],others:r.skills},u=await Qi(a,l,i!==null),d=c.length>0||e.length===0;if(i&&d&&s.length===0){I(Ga(i.credentials.webUrl));return}let f=d?await _n(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 vn(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 pn(t.agent,n),g=t.global?`global`:`project`,_=en(h,g),v=Y(g),y=await X(v);await mo(_);try{await _o(a,y,f,h,_,t.channel,{catalog:s,ask:n}),await $i(a,y,u,h.map(e=>e.id),_);for(let e of m){let t=await qi(a,y,e,{agents:h.map(e=>e.id),dirsOf:ho(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 Ui(v,y)}await lo(h.map(e=>e.id)),I(`Installed in ${_.map(W).join(`, `)}`)}const yo=()=>m(V(),`auto-update.json`);async function bo(e=Date.now(),t=6e4,n=yo()){if(xo((await So(n)).startedAt,e,t))return!1;await D(p(n),{recursive:!0});let r=`${n}.claim`;try{await k(r,``,{flag:`wx`})}catch{let e=await le(r).then(e=>e.mtimeMs,()=>null);return e!==null&&Date.now()-e>6e4&&await de(r).catch(()=>{}),!1}try{let r=await So(n);return!xo(r.startedAt,e,t)&&(await Co(n,{...r,startedAt:e}),!0)}finally{await de(r).catch(()=>{})}}const xo=(e,t,n)=>typeof e==`number`&&t-e<n&&e<=t;async function So(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 Co(e,t){await D(p(e),{recursive:!0}),await k(e,JSON.stringify(t)+`
|
|
270
|
+
`)}const wo=(e,t)=>{ge(process.execPath,[e,...t],{cwd:b(),detached:!0,stdio:`ignore`,windowsHide:!0}).unref()},To=e=>Object.keys(e.skills).length===0&&Object.keys(e.kits).length===0&&Object.keys(e.public??{}).length===0;async function Eo(e,t=wo,n=Date.now()){return(await U()).autoUpdate===!1||To(await X(Y(`global`)))||!await H()||!await bo(n)?!1:(t(e,[`auto-update`,`run`]),!0)}const Do=e=>({skills:Object.values(e.skills).map(e=>{let t=Hi(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 Oo(e,t,n=yo()){try{let r=await X(Y(`global`));if(To(r))return`unchanged`;let{fingerprint:i}=await e.fingerprint(Do(r),AbortSignal.timeout(5e3));return(await So(n)).fingerprint===i?`unchanged`:(await t(),await Co(n,{...await So(n),fingerprint:i}),`updated`)}catch{return`failed`}}const ko=6e3,Ao=e=>`github.com/${e.toLowerCase()}`,jo=()=>m(V(),`project-repositories.json`);async function Mo(){try{let e=JSON.parse(await O(jo(),`utf8`));return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}catch{return{}}}async function No(e){let t=await Mo();t[B()]=e,await D(V(),{recursive:!0,mode:448});let n=`${jo()}.${process.pid}`;await k(n,JSON.stringify(t)+`
|
|
271
|
+
`),await se(n,jo())}const Po=e=>typeof e==`object`&&!!e&&!Array.isArray(e);async function Fo(e){let t=(await Mo())[B()];return!t||t.userId!==e||typeof t.checkedAt!=`string`||typeof t.triedAt!=`string`||!Po(t.repositories)||!Po(t.skills)?null:t}async function Io(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[Ao(t.fullName)]=e;for(let e of a)s.skills[e.id]=e.organizationId;return await No(s),s}function Lo(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 Ro(e,t,n,r){try{await No({userId:t,checkedAt:n?.checkedAt??(/* @__PURE__ */ new Date(0)).toISOString(),repositories:n?.repositories??{},skills:n?.skills??{},triedAt:r.toISOString()}),await Io(e,t,r,AbortSignal.timeout(ko))}catch{}}async function zo(){try{if(Nn()||(await U()).telemetry===!1)return;let e=await H();if(!e)return;await Io(z(B(),e.token),e.user.id,/* @__PURE__ */ new Date,AbortSignal.timeout(ko))}catch{}}async function Bo(e){Lt(`agent kit`),await zo();let t=e.global?`global`:`project`,n=Y(t),r=await X(n),i=Object.entries(r.public??{});if(Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0&&i.length===0){I(e.global?"No skills installed everywhere yet. Add some with `a-kit add -g`.":"No skills installed in this project yet. Add some with `a-kit add`.");return}let a=Object.keys(r.skills).length===0&&Object.keys(r.kits).length===0?z(B(),(await H())?.token):(await Ua()).api,o=ho(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 mo([...new Set(s)]);let c=0,l=0,u=0;for(let[e,t]of Object.entries(r.kits)){let i;try{i=await a.getKit(t.id)}catch(t){if(t instanceof R&&t.status===404){F.warn(`kit/${e} isn't in your agent kit anymore; left its skills as they are.`);continue}throw t}Ki(r,e,i.name);try{let e=await qi(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 Ui(n,r)}}let d=0;for(let[e,t]of Object.entries(r.skills)){let i=Hi(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 Un(c,e);if(l){F.warn(`${e} uses ${W(l)} (\`a-kit link\`); left it. \`a-kit add ${e}\` goes back to v${s.version}.`),u++;continue}let f=await Vn(a,e,t,c);if(f)F.warn(`${e} has edits here that aren't in agent kit (${zn(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 Bi(a,t.id,c,i),s.name!==e){for(let t of c)await ce(m(t,e),{recursive:!0,force:!0});delete r.skills[e]}r.skills[s.name]={...t,version:s.version},await Ui(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 Bi(zi(a,i),t.ref,s),i.name!==e){for(let t of s)await ce(m(t,e),{recursive:!0,force:!0});delete r.public[e]}r.public[i.name]={...t,version:i.version},await Ui(n,r),F.success(`${i.name}: v${t.version} → v${i.version} (${t.ref})`+(i.name===e?``:` (was ${e})`)),d++}await lo([...new Set([...Object.values(r.skills),...Object.values(r.kits),...i.map(([,e])=>e)].flatMap(e=>e.agents))]),I(Ho(d,c,l,u))}const Vo=e=>`${e} skill${e===1?``:`s`}`;function Ho(e,t,n,r){let i=[e&&`updated ${Vo(e)}`,t&&`installed ${Vo(t)}`,n&&`removed ${Vo(n)}`].filter(Boolean),a=r?`Left ${Vo(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 Uo(e){switch(e){case`run`:{let e=await H();if(!e)return;await Oo(z(B(),e.token),()=>Bo({global:!0,agent:[],yes:!0,channel:`latest`}));return}case`on`:{await Mn({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 Mn({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 U()).autoUpdate!==!1,t=(await so()).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 Wo(e,t){let n=1;for(let r=0;r<Math.min(t,e.length);r++)e.charCodeAt(r)===10&&n++;return n}const Go=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function Ko(e,t=!!process.stdout.isTTY&&!process.env.NO_COLOR){let r=(e,r)=>t?n(e,r):r;return e.map(e=>{let t=e.severity===`error`?r(`red`,`✗`):r(`yellow`,`▲`),n=e.path===null?`repository`:e.path+(e.line?`:${e.line}`:``);return`${t} ${e.message} ${r(`dim`,n)}`})}function qo(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 Jo(e){let t=/^kits\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function Yo(e){let t;try{t=(0,J.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
|
|
272
|
+
`)[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(!Xo(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 Xo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Zo(e){let t;try{t=(0,J.parse)(e)}catch(e){let t=e instanceof Error?e.message.split(`
|
|
273
|
+
`)[0]:``;return{error:`It isn't valid YAML${t?`: ${t}`:`.`}`}}if(t==null)return{pins:/* @__PURE__ */ new Map,problems:[]};if(!Xo(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(Xo(r))for(let[i,a]of Object.entries(r))Wt.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 Wt)t[e]=null;n.problems.push(`“${e}” has to have its channels, like \`{ stable: 7 }\`.`)}}}return n}const Qo=(...e)=>({words:e}),$o={text:`one`},es={issue:{about:`an issue's state changed`,value:Qo(`opened`,`closed`,`reopened`),fields:{}},label:{about:`a label was put on an issue or a pull request, or taken off`,value:$o,fields:{on:Qo(`added`,`removed`)}},path:{about:`a pull request that changes a path was merged`,value:$o,fields:{on:Qo(`merged`)}},"pull-request":{about:`a pull request was opened, marked ready, merged or closed`,value:Qo(`opened`,`ready`,`merged`,`closed`),fields:{base:$o,head:$o}},review:{about:`a pull request got a review`,value:Qo(`approved`,`changes-requested`,`commented`),fields:{by:{text:`many`}}},checks:{about:`a pull request's checks finished`,value:Qo(`passed`,`failed`),fields:{}},release:{about:`a release was published`,value:Qo(`published`),fields:{}},skill:{about:`an agent loaded a skill`,value:$o,fields:{}},branch:{about:`a branch got its first commit`,value:Qo(`first-commit`),fields:{}}},ts=Object.keys(es),ns=e=>Object.hasOwn(es,e),rs=(e,t=`and`)=>e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)} ${t} ${e.at(-1)}`,is=`flows`,as=[`epic`,`ticket`,`pull-request`],os=[`paths`,`labels`];function ss(e){let t=/^flows\/([^/]+)\.yaml$/.exec(e);return t?t[1]:null}function cs(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 ls(e){let t=cs(e);return t===null?null:`“${e}” can't be a flow's name, so this file isn't read. ${t}`}const us=[`name`,`description`,`stations`],ds=[`id`,`unit`,`signal`,`owner`,`before`,`when`];function fs(e){let t=[],n=(0,J.parseDocument)(e,{prettyErrors:!1}),r=t=>t&&typeof t==`object`&&`range`in t&&t.range?Wo(e,t.range[0]):null,i=(e,n)=>{t.push({line:r(e),message:n})};if(n.errors.length>0){for(let r of n.errors)t.push({line:Wo(e,r.pos[0]),message:`It isn't valid YAML: ${r.message.split(`
|
|
274
|
+
`)[0]}`});return{flow:null,problems:t}}let a=Z(n,n.contents);if(a===null||(0,J.isScalar)(a)&&a.value===null)return t.push({line:null,message:"It's empty. A flow lists its stations: `stations: [{ id: review, unit: pull-request, signal: { review: approved } }]`."}),{flow:null,problems:t};if(!(0,J.isMap)(a))return i(a,"A flow has to be a mapping, with its `stations`."),{flow:null,problems:t};let o=ps(n,a,us,`A flow`,i),s=o.has(`name`)?ms(o.get(`name`),"Its `name`",i):null,c=o.has(`description`)?ms(o.get(`description`),"Its `description`",i):null,l=o.get(`stations`),u=[],d=[];if(!l)i(a,"It has no `stations`: a flow lists them in order.");else if(!(0,J.isSeq)(l.value)||l.value.items.length===0)i(l.value??l.key,"Its `stations` have to be a list, with one station at least.");else if(l.value.items.length>100)i(l.key,`A flow has at most 100 stations, and this one has ${l.value.items.length}.`);else{let e=/* @__PURE__ */ new Map;l.value.items.forEach((t,a)=>{let o=Z(n,t),s=`Station ${a+1}`;if(!(0,J.isMap)(o)){i(o??l.value,`${s} has to be a mapping, with its \`id\`, \`unit\` and \`signal\`.`);return}let c=ps(n,o,ds,s,i),f=c.get(`id`),p=null;if(!f)i(o,`${s} has no \`id\`. Give it one that stays the same, like \`review\`.`);else{p=ms(f,`The \`id\` of ${s.toLowerCase()}`,i);let t=p===null?null:cs(p);if(p!==null&&t)i(f.value,`“${p}” can't be a station's id. ${t}`),p=null;else if(p!==null&&e.has(p)){let t=e.get(p);i(f.value,`There's another station with the id “${p}”${t?` (line ${t})`:``}. Each station's id has to be its own.`),p=null}else p!==null&&e.set(p,r(f.value))}let m=p?`Station “${p}”`:s,h=c.get(`unit`),g=null;if(!h)i(o,`${m} has no \`unit\`: say whether it's counted for an \`epic\`, a \`ticket\` or a \`pull-request\`.`);else{let e=ms(h,`The \`unit\` of ${m.toLowerCase()}`,i);e!==null&&(as.includes(e)?g=e:i(h.value,`“${e}” isn't a unit. A station is counted for an epic, a ticket or a pull-request.`))}let _=c.get(`signal`),v=null;_?v=gs(n,_.value,m,i):i(o,`${m} has no \`signal\`: say how agent kit knows it happened, like \`{ review: approved }\`.`);let y=c.has(`owner`)?hs(n,c.get(`owner`),`The \`owner\` of ${m.toLowerCase()}`,`a role`,i):[],b=[],x=c.get(`before`);if(x){let e=Z(n,x.value),t=(0,J.isSeq)(e)?e.items.map(e=>Z(n,e)):[e];for(let e of t){let t=(0,J.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)?String(e.value).trim():``;t?(b.push(t),d.push({station:p??``,node:e,id:t})):i(e??x.key,`The \`before\` of ${m.toLowerCase()} has to be a station's id, or a list of them.`)}}let S=c.has(`when`)?bs(n,c.get(`when`),m,i):null;p!==null&&g!==null&&v!==null&&y!==null&&S!==void 0&&u.push({id:p,unit:g,signals:v,owner:y,before:b,when:S})});for(let{station:t,node:n,id:r}of d)r===t?i(n,`Station “${t}” can't come before itself.`):e.has(r)||i(n,`There's no station “${r}” in this flow, so nothing can come before it.`)}return t.sort((e,t)=>(e.line??0)-(t.line??0)),{flow:t.length===0?{name:s,description:c,stations:u}:null,problems:t}}const Z=(e,t)=>t==null?null:(0,J.isAlias)(t)?t.resolve(e)??null:t;function ps(e,t,n,r,i){let a=/* @__PURE__ */ new Map;if(!(0,J.isMap)(t))return a;for(let o of t.items){let s=Z(e,o.key),c=(0,J.isScalar)(s)?String(s.value):null;c===null||!n.includes(c)?i(s??t,`${r} doesn't take \`${c??`?`}\`. It takes ${rs(n.map(e=>`\`${e}\``))}.`):a.set(c,{key:s,value:Z(e,o.value)})}return a}function ms(e,t,n){let{value:r}=e;return(0,J.isScalar)(r)&&(typeof r.value==`string`||typeof r.value==`number`)&&String(r.value).trim()!==``?String(r.value).trim():(n(r??e.key,`${t} has to be some text.`),null)}function hs(e,t,n,r,i){let a=Z(e,t.value),o=(0,J.isSeq)(a)?a.items.map(t=>Z(e,t)):[a],s=[];for(let e of o){if(!(0,J.isScalar)(e)||typeof e.value!=`string`&&typeof e.value!=`number`||String(e.value).trim()===``)return i(e??t.key,`${n} has to be ${r}, or a list of them.`),null;s.push(String(e.value).trim())}return s.length===0?(i(a??t.key,`${n} has to be ${r}, or a list of them.`),null):s}function gs(e,t,n,r){let i=(0,J.isSeq)(t)?t.items.map(t=>Z(e,t)):[t];if(i.length===0)return r(t,`The \`signal\` of ${n.toLowerCase()} is an empty list: give it one at least.`),null;let a=[],o=!0;for(let t of i){let i=vs(e,t,n,r);i?a.push(i):o=!1}return o?a:null}const _s=rs(ts.map(e=>`\`${e}\``));function vs(e,t,n,r){if(!(0,J.isMap)(t))return r(t,`A signal of ${n.toLowerCase()} has to be a mapping that starts with its kind, like \`{ review: approved }\`. The kinds are ${_s}.`),null;let i=t.items.map(t=>{let n=Z(e,t.key);return{key:n,name:(0,J.isScalar)(n)?String(n.value):`?`,value:Z(e,t.value)}}),a=i.filter(e=>ns(e.name));if(a.length===0){let[e]=i;return r(e?.key??t,e?`“${e.name}” isn't a kind of signal. The kinds are ${_s}.`:`A signal of ${n.toLowerCase()} is empty. Start it with its kind: ${_s}.`),null}if(a.length>1)return r(a[1].key,`A signal is of one kind, and this one has ${rs(a.map(e=>`\`${e.name}\``))}. To take any of them, make \`signal\` a list.`),null;let o=a[0].name,s=es[o],c=!0,l=ys(a[0].value,s.value,`\`${o}\``,a[0].key,r);(l===null||Array.isArray(l))&&(c=!1);let u={},d=Object.keys(s.fields);for(let e of i){if(e.name===o)continue;let t=s.fields[e.name];if(!t){r(e.key,d.length===0?`A \`${o}\` signal takes no other field, and this one has \`${e.name}\`.`:`A \`${o}\` signal doesn't take \`${e.name}\`. It takes ${rs(d.map(e=>`\`${e}\``))}.`),c=!1;continue}let n=ys(e.value,t,`\`${e.name}\``,e.key,r);n===null?c=!1:u[e.name]=n}return c?{kind:o,value:l,fields:u}:null}function ys(e,t,n,r,i){let a=e=>(0,J.isScalar)(e)&&(typeof e.value==`string`||typeof e.value==`number`)&&String(e.value).trim()!==``?String(e.value).trim():null;if(`words`in t){let o=a(e);return o!==null&&t.words.includes(o)?o:(i(e??r,`${n} has to be ${rs(t.words.map(e=>`\`${e}\``),`or`)}${o===null?``:`, not “${o}”`}.`),null)}if(t.text===`many`&&(0,J.isSeq)(e)){let t=e.items.map(e=>a(e));return t.length>0&&t.every(e=>e!==null)?t:(i(e,`${n} has to be a name, or a list of them.`),null)}let o=a(e);return o===null?(i(e??r,`${n} has to be ${t.text===`many`?`a name, or a list of them`:`some text`}.`),null):o}function bs(e,t,n,r){let i=t.value;if(!(0,J.isMap)(i)){r(i??t.key,`The \`when\` of ${n.toLowerCase()} has to be a mapping, like \`{ paths: [docs] }\`.`);return}let a=ps(e,i,os,`The \`when\` of ${n.toLowerCase()}`,r);if(a.size!==i.items.length)return;let o={};for(let[t,n]of a){let i=hs(e,n,`\`${t}\``,`a name`,r);if(i===null)return;o[t]=i}return o}const xs=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:`
|
|
275
|
+
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])),Ss=1024,Cs=1536,ws=[`anthropic`,`claude`],Ts=/<\/?[A-Za-z][^>]*>/;function Es(e){let t=[];e.files.length>Gn.maxFiles&&t.push(Fs(`A skill can have at most ${Gn.maxFiles} files.`));let n=0,r=/* @__PURE__ */ new Set;for(let i of e.files){n+=i.size;let e=qn(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>Gn.maxFileBytes&&t.push({severity:`error`,path:i.path,message:`Files can be at most ${Rs(Gn.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>Gn.maxSkillBytes&&t.push(Fs(`The whole skill can be at most ${Rs(Gn.maxSkillBytes)}.`)),e.skillMd===null?(t.push(Fs(`Every skill needs a ${G} at its root.`)),t):(t.push(...Ds(e.skillMd,r,e.skills)),t)}function Ds(e,t,n){let r=[],i=(e,t,n,i,a)=>r.push({severity:e,path:G,message:t,from:n,to:i,fix:a}),a=mi(e);if(!a.ok)return a.reason===`unclosed`?i(`error`,`The frontmatter has no closing --- line.`,0,3):i(`error`,`${G} must start with frontmatter: a --- line, name and description, and another --- line.`,0,Math.min(e.indexOf(`
|
|
275
276
|
`)===-1?e.length:e.indexOf(`
|
|
276
277
|
`),80),{label:`Add frontmatter`,from:0,to:0,insert:`---
|
|
277
278
|
name: my-skill
|
|
278
279
|
description:
|
|
279
280
|
---
|
|
280
281
|
|
|
281
|
-
`}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,
|
|
282
|
+
`}),r;let{block:o,entries:s}=a;for(let e of a.yamlErrors)i(`error`,Ps(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
|
|
282
283
|
`:`description:
|
|
283
|
-
`});for(let e of s){let t=
|
|
284
|
+
`});for(let e of s){let t=xs.get(e.key);if(t)Ms(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=xs.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 As(u.value)){let t=js(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`,Os,d.keyFrom,d.keyTo);else{let n=ks(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>Cs&&i(`warning`,`description and when_to_use add up to ${a} characters; Claude Code cuts the listing at ${Cs}.`,...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&&Ls(p.value))for(let[e,t]of Object.entries(p.value))typeof t!=`string`&&i(`warning`,`metadata.${e} should be a string; quote it.`,p.valueFrom,p.valueTo);let m=c.get(`allowed-tools`);return m&&Array.isArray(m.value)&&i(`warning`,`The spec expects allowed-tools as one space-separated string; only Claude Code accepts a list.`,m.valueFrom,m.valueTo),Ns(e,o.bodyFrom,t,n,i),r}const Os=`The description is empty. Say what the skill does and when to use it.`;function ks(e){let t=e.trim();if(t===``)return{errors:[Os],warnings:[]};let n=[],r=[];return t.length>Ss&&n.push(`The description is ${t.length} characters; the most is ${Ss}.`),Ts.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 As(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=ws.find(t=>e.toLowerCase().includes(t));return n&&t.push(`The name can't contain the reserved word "${n}".`),t}function js(e){let t=e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase();for(let e of ws)t=t.replaceAll(e,``);return t=t.replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64).replace(/-+$/,``),t===``?null:t}function Ms(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`?Is(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`&&!Ls(r)?n(`error`,`\`${e.key}\` must be indented key: value lines.`,...i):a===`tools`&&typeof r!=`string`&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`))?n(`error`,`\`${e.key}\` must be a space-separated list of names.`,...i):typeof a==`object`&&!a.oneOf.includes(String(r))&&n(`error`,`\`${e.key}\` must be one of: ${a.oneOf.join(`, `)}.`,...i)}function Ns(e,t,n,r,i){let a=e.slice(t);if(a.trim()===``){i(`warning`,`The skill has no instructions yet. Write them below the frontmatter.`,Math.max(0,t-4),t);return}let o=a.split(`
|
|
284
285
|
`).length;o>500&&i(`warning`,`${G} has ${o} lines below the frontmatter. Keep it under 500 and move details to other files it links to.`,t,t+a.indexOf(`
|
|
285
|
-
`));for(let{path:a,from:o,to:s}of xi(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=Xn(G,a);if(e===null){let e=Si(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
|
|
286
|
-
`:``)+`${l}: no errors`+(c?`, ${
|
|
287
|
-
`)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)
|
|
288
|
-
`).length,bodyTokens
|
|
289
|
-
`)}async function
|
|
290
|
-
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
|
|
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(
|
|
292
|
-
`)}const
|
|
293
|
-
`)}async function
|
|
294
|
-
`))}function
|
|
295
|
-
`))}async function
|
|
286
|
+
`));for(let{path:a,from:o,to:s}of xi(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=Xn(G,a);if(e===null){let e=Si(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 Ps(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 Fs(e){return{severity:`error`,path:null,message:e}}function Is(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function Ls(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rs(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const zs=`channels.yaml`;function Bs(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 Vs(e){return Bs(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===G)).map(([e])=>e)}function Hs(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(Vs(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=Bs(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${G} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${G}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of Es({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:Wo(s,e.from)}:{},message:e.message});let r=hi(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${G}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:hi(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=Bs(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=Bs(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=Bs(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=Bs(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=Zo(e.channelsText),n=(e,t)=>r.push({severity:e,path:zs,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 Bs(t,`kits`).loose){let t=`kits/${n}`,a=Jo(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=qo(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=Yo(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}let u=[];for(let n of Bs(t,is).loose){let t=`${is}/${n}`,i=ss(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=ls(i);if(a){r.push({severity:`error`,path:t,message:a});continue}let o=e.flowTexts?.get(t);if(o!==void 0)for(let e of fs(o).problems)r.push({severity:`error`,path:t,...e.line===null?{}:{line:e.line},message:e.message})}return{skills:a,evals:s,benchmarks:c,fixtures:Bs(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),flows:u.sort((e,t)=>e.localeCompare(t)),channels:t.some(e=>e.path===zs),problems:r.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0))}}const Us=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],Ws=e=>{try{return u(e).isDirectory()}catch{return!1}};function Gs(e){let t;for(let n=_(e);;n=p(n)){if(t??=Ws(m(n,`skills`))?n:void 0,l(m(n,`.git`))){if(Ws(m(n,`skills`)))return n;throw Error(`${W(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(p(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 Ks(e){let t=[];for(let n of Us){let r=m(e,n);if(Ws(r))for(let n of await ae(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=m(n.parentPath,n.name),i=g(e,r).split(v).join(`/`);Fn(i)||t.push({path:i,size:(await le(r)).size})}}return l(m(e,`channels.yaml`))&&t.push({path:zs,size:(await le(m(e,zs))).size}),t}async function qs(e){let t=await Ks(e),n=/* @__PURE__ */ new Map;for(let r of Vs(t))n.set(r,await O(m(e,`skills`,r,G),`utf8`));let r=t.some(e=>e.path===`channels.yaml`)?await O(m(e,zs),`utf8`):null,i=/* @__PURE__ */ new Map;for(let{path:n}of t)ss(n)!==null&&i.set(n,await O(m(e,n),`utf8`));return Hs({files:t,skillMds:n,channelsText:r,flowTexts:i})}function Js(e,t,n=process.cwd()){let r=[];for(let i of t){let t=_(n,i);if(Ws(t)){if(t===e||t===m(e,`skills`))return[];if(p(t)===m(e,`skills`)){r.push(d(t));continue}let n=g(m(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(v)[0]);continue}throw Error(`${W(t)} isn't a skill's folder. Skills are in ${W(m(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 Ys=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function Xs(e){let t=Gs(e.find(e=>e.includes(`/`))??`.`),n=Js(t,e),r=await qs(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${W(t)}.`);let o=n.length>0?Ys(r.problems,n):r.problems;for(let e of Ko(o))console.log(e);let s=o.filter(e=>e.severity===`error`).length,c=o.length-s,l=n.length===1?n[0]:n.length>0?Go(n.length,`skill`):`The repository (${[Go(r.skills.length,`skill`),...r.flows?.length?[Go(r.flows.length,`flow`)]:[]].join(`, `)})`;s>0?(console.log(`\n${l}: ${Go(s,`error`)}`+(c?`, ${Go(c,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((o.length?`
|
|
287
|
+
`:``)+`${l}: no errors`+(c?`, ${Go(c,`warning`)}`:``)+`.`)}const Zs=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Qs=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function $s(e){let t=0;for(let[n]of e.matchAll(Qs)){let e=n[0];if(e===`
|
|
288
|
+
`)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)Zs.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 ec(e){return{always:e.description,max:e.description+e.body+e.files}}function tc(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=ec(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function nc(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${ic((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${ic((e/1e6).toFixed(1))}M`}const rc=(e,t)=>`${t===`estimate`?`~`:``}${nc(e)}`,ic=e=>e.replace(/\.0$/,``),ac={high:15,medium:10,low:5},oc=5e3,sc=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function cc(e){let t=Yn(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&sc.has(n)}const lc=/^(license|licence|notice|readme|changelog)(\..*)?$/i,uc=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function dc(e,t){let n=t(`SKILL.md`)??``,r=mi(n),i=e=>r.ok?r.entries.find(t=>t.key===e):void 0,a=i(`description`)?.value,o=i(`when_to_use`)?.value,s=r.ok?r.body:n,c=s.trim(),l=new Set(e.map(e=>e.path)),u=e=>l.has(e)||[...l].some(t=>t.startsWith(`${e}/`)),d=/* @__PURE__ */ new Set([G]),f=/* @__PURE__ */ new Set,p=!1,m=[G];for(;m.length>0;){let n=m.shift(),r=n===`SKILL.md`?s:t(n);if(r===void 0)cc(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Sc(r)){let t=Xn(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Cc(r,n,t.path)&&(d.add(t.path),cc(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!lc.test(Yn(e))).filter(e=>!Yn(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(`
|
|
289
|
+
`).length,bodyTokens:$s(c),hasExamples:kc(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function fc(e,t,n=/* @__PURE__ */ new Date){let r=[...yc(e),...t?bc(t,n):[]];return{score:pc(r),checks:hc(r)}}function pc(e){let t=e.reduce((e,t)=>e+ac[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+ac[t.severity],0);return Math.round(n/t*100)}const mc=[`high`,`medium`,`low`];function hc(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:mc.indexOf(e.severity)-mc.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}),gc=/\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,_c=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,vc=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function yc(e){let t=[],n=e.description??``;e.hasWhenToUse||gc.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(_c);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`)),vc.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=xc(e.bodyTokens);return e.bodyLines===0?t.push($(`body-length`,`medium`,`${G} has no instructions`,`Write the instructions below the frontmatter.`)):e.bodyLines>500||e.bodyTokens>oc?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${xc(oc)}; move reference material into files ${G} 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 ${Ac(e.missingFiles.length,`missing file`)}: ${jc(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`,`${Ac(e.unusedFiles.length,`file`)} nothing mentions: ${jc(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function bc(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Q(`eval-cases`,`high`,Ac(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Ac(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Q(`eval-negative`,`medium`,`${Ac(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 ${Ac(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 xc(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Sc(e){let t=[];for(let n of e.matchAll(uc)){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 Cc(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,Yn(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=wc(t,n);return a&&r.add(a),[...r].some(t=>Tc(e,t))}function wc(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Tc(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 Ec=/^(```|~~~)/m,Dc=/^#{1,6}[^\n]*\bexamples?\b/im,Oc=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function kc(e){return Ec.test(e)||Dc.test(e)||Oc.test(e)}function Ac(e,t){return`${e} ${t}${e===1?``:`s`}`}function jc(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Mc=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Nc(e){try{return(await le(m(e,G))).isFile()}catch{return!1}}async function Pc(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await ae(i,{withFileTypes:!0})){let o=m(i,a.name);if(a.isDirectory()){Mc.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=g(e,o).split(v).join(`/`),{size:c}=await le(o);t.push({path:s,size:c}),(s===`SKILL.md`||cc({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),fc(dc(t,e=>n.get(e)),null)}function Fc(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(`
|
|
290
|
+
`)}async function Ic(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=_(t??`.`);if(await Nc(n)){let e=await Pc(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(Fc(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 Ua(),i=bn(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(`${En(a)} v${a.version}`),console.log(Fc(o))}async function Lc(e){Lt(`agent kit`);let t=await Ha();t?F.success(`Logged in as ${Wa(t.user)}`):t=await Va();let n=z(B(),t.token),r=await n.listSkills();if(r.length===0){I(Ga(t.webUrl));return}let i=!e.yes;if(i&&!dn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await mn(e.global,i),o=await pn(e.agent,i),s=i?fn(await Ft({message:`Which skills?`,options:r.map(e=>({value:e.id,label:En(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await go(n,r.filter(e=>s.includes(e.id)),o,a,e.channel,{catalog:r,ask:i});I(`Installed in ${c.map(W).join(`, `)}`)}async function Rc(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ra();return;case`on`:{if(await Mn({heartbeat:!0}),!await H()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!na()){F.warn(`Run it from the published CLI to install the timer.`);return}await za();let e=await Ma(B()),t=(await La())?.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 Mn({heartbeat:!1}),await ja(B()),F.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await U()).heartbeat!==!1,t=await Ma(B()),n=await La();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?Da(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(`
|
|
291
|
+
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 zc={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},Bc=/^[A-Za-z0-9._:-]{1,128}$/,Vc=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,Hc=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Uc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Wc=/[\u0000-\u001f\u007f]/;function Gc(e){let t=e.trim(),n=Hc.exec(t)??Uc.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 Kc(o)?o:null}const Kc=e=>Vc.test(e)&&e.length<=zc.maxRepositoryLength,qc=e=>e.length>0&&e.length<=zc.maxBranchLength&&e.trim()===e&&!Wc.test(e),Jc={maxPerRequest:100,maxLinks:50,maxAgeDays:zc.maxAgeDays,maxFutureMs:zc.maxFutureMs,maxMachineNameLength:zc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},Yc=/^[1-9][0-9]{0,8}$/,Xc=/\s/,Zc=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function Qc(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Kc(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 Kc(r)&&(e===`branch`?qc(i):Yc.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return el(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Jc.maxThreadLength&&!Xc.test(n)&&!Wc.test(n)?{kind:e,value:n}:null;case`session`:return Bc.test(n)?{kind:e,value:n}:null;default:return null}}function $c(e){let t=e.trim();return Qc(`slack_thread`,t)??Qc(`thread`,t)}function el(e){return e.length<=Jc.maxUrlLength&&Zc.test(e)}const tl={sessionId:null,repository:null,branch:null,audience:null},nl=e=>typeof e==`string`&&e?e:null;async function rl(e,t,n=b(),r=null){let i=nl(e),a=ca(t,n)!==null;if(!a&&!r)return{...tl,sessionId:i};let[o,s]=await Promise.all([sl(t,[`remote`,`get-url`,`origin`]),sl(t,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]),c=o?Gc(o):null,l=c?r?.repositories[c]:void 0,u=a?`any`:l?{organizationId:l}:null;return u?{sessionId:i,repository:c,branch:s,audience:u}:{...tl,sessionId:i}}function il({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function al(e,t){if(ol.includes(t))return!0;let n=await sl(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const ol=[`main`,`master`,`develop`];function sl(e,t){return new Promise(n=>{try{me(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const cl=()=>m(V(),`sessions`),ll=()=>m(V(),`pending-session-events.jsonl`),ul=e=>fe(`sha256`).update(e).digest(`hex`).slice(0,32);function dl(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 fl(e,t){let n=e.trimStart().split(`
|
|
292
|
+
`)[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(Qc(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(Qc(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(Qc(`issue`,`${t}#${o}`)),i}function pl(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 ml(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=dl(t,n),l=i.sessionId;if(!c||!l||!Bc.test(l))return null;c===`end`&&t.reason===`clear`&&await bl(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(Qc(`repository`,i.repository)),i.branch&&!await al(r,i.branch)&&d(Qc(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=pl(t);if(p&&f)for(let e of fl(p,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($c(t));if(t.source===`clear`){let e=await xl(r,l,o,s);e&&d(Qc(`session`,e))}}let m=await _l(l),h=u.map(e=>`${e.kind} ${e.value}`),g=h.some(e=>!m.links.includes(e));return c===`seen`&&!g&&o.getTime()-m.sentAt<3e5?null:(await vl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...m.links,...h])]}),c===`start`&&await Sl(o),{sessionId:l,agent:e,machineId:await la(),machineName:x()||null,type:c,occurredAt:o.toISOString(),links:u})}const hl=(e,t)=>ia(ll(),e,t),gl=e=>m(cl(),`${ul(e)}.json`);async function _l(e){try{let t=JSON.parse(await O(gl(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 vl(e,t){await D(cl(),{recursive:!0,mode:448}),await k(gl(e),JSON.stringify(t)+`
|
|
293
|
+
`)}const yl=e=>m(cl(),`cleared-${ul(e)}.json`);async function bl(e,t,n){await D(cl(),{recursive:!0,mode:448}),await k(yl(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
|
|
294
|
+
`)}async function xl(e,t,n,r){let i=yl(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 ce(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await ve(100)}}async function Sl(e){try{for(let t of await ae(cl())){let n=m(cl(),t),{mtimeMs:r}=await le(n);e.getTime()-r>6048e5&&await ce(n,{force:!0})}}catch{}}const Cl=5e3;async function wl(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 Tl()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Eo(na()??ta()),await Ma(B())||await Ra();return}if(Nn()||(await U()).telemetry===!1)return;let o=await H();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await Fo(o.user.id),u=c?{...tl,sessionId:nl(r.session_id)}:await rl(r.session_id,s,void 0,l),d=z(B(),o.token),f=await ml(e,r,a,s,u,{now:i}),p=ro(r),m=p&&await sa(p.name,e,s);await Promise.all([!c&&Lo(l,i,m?m.id:null)&&Ro(d,o.user.id,l,i),f&&hl(async e=>{await d.reportSessionEvents(e,AbortSignal.timeout(Cl))},f),p&&m&&fa(async e=>{await d.reportActivations(e,AbortSignal.timeout(Cl))},await ua(m,e,p.trigger,il(u,l?.skills[m.id]??null),i))])}catch{}}async function Tl(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function El(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Lt(`agent kit`);let n=_(e[0]);if(!l(m(n,`SKILL.md`)))throw Error(`${W(n)} has no ${G}, so it isn't a skill.`);let r=d(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 pn(t.agent,!t.yes),o=en(a,i),s=o.map(e=>m(e,r));if(s.includes(n))throw Error(`${W(n)} is already where your agents read it.`);let c=(await X(Y(i))).skills[r];for(let e of s)if(l(e)&&!await Hn(e)&&!c)throw Error(`${W(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Vn(z(B(),(await H())?.token),r,c,o);if(e&&!await Hn(e.folder))throw Error(`${W(e.folder)} has edits that aren't in agent kit (${zn(e.paths)}). Copy them to ${W(n)} and delete them there first.`)}for(let e of s)await Wn(e,n);F.success(`${r}: ${s.map(W).join(`, `)} → ${W(n)}`);let u=i===`project`?await Dl(en(a,`global`),r,n):[];u.length>0&&F.warn(`You also have ${r} in ${u.map(W).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await Ol(n,r),I(`${u.length>0?`This project's agents would use`:`Your agents use`} ${W(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function Dl(e,t,n){let r=[];for(let i of e){let e=m(i,t);l(e)&&await Hn(e)!==n&&r.push(e)}return r}async function Ol(e,t){let n;try{n=Gs(e)}catch{return}if(_(n,`skills`,t)!==e)return;let r=Ys((await qs(n)).problems,[t]);r.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...Ko(r)].join(`
|
|
295
|
+
`))}function kl(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?rc(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[En(e),Al(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[jl(`project`,r,e),jl(`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=tc(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}${nc(c.always)} always · ${l}${nc(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 Al(e){return[`v${e.version}`,...Wt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function jl(e,t,n){if(!t)return null;let r=Hi(t),{version:i}=Jt(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 Ml(){let{api:e,credentials:t}=await Ua(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(Ga(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of kl(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>Nl(e).length));for(let e of r){let t=[Pl(i,e)&&`in project`,Pl(a,e)&&`in global`].filter(Boolean);console.log(`${Nl(e).padEnd(o)} ${Fl(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const Nl=e=>`${hn}${En(e)}`,Pl=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function Fl(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 Il(e,t){switch(e){case void 0:case`status`:{let e=(await La())?.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 Ua(),r=await ba(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await U()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Ra()?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 Ll(){Lt(`agent kit`);let e=await Ha().catch(()=>null);if(e){let t=Wa(e.user);if(!dn()){I(`Already logged in as ${t}.`);return}if(!fn(await Mt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Va();e&&await z(B(),e.token).logout().catch(()=>{}),I(await Bl(t.token,t.webUrl))}async function Rl(e=process.stdin){Lt(`agent kit`);let t=await zl(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 An({token:t,user:n,webUrl:Dn(B())}),r&&r.token!==t&&await z(B(),r.token).logout().catch(()=>{}),await za(),I(`Logged in as ${Wa(n)}.`)}async function zl(e){if(e.isTTY)return fn(await Rt({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function Bl(e,t){return(await z(B(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${Ga(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function Vl(){let e=await H();e?(await z(B(),e.token).logout().catch(()=>{}),await An(null),console.log(`Logged out ${Wa(e.user)}.`)):console.log(`You're not logged in.`)}async function Hl(){let e=await Ha();e?console.log(Wa(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Ul=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Wl(e){let t=await Gl(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${ln()} ${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(`
|
|
296
|
+
`))}async function Gl(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repository?.fullName??null).catch(()=>null)));return[...new Set(n.filter(e=>e!==null))]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Kl={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},ql=[{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}],Jl=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Yl=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Xl=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Zl=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Ql=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function $l(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(Ql(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}_])${Ql(e.find)}(?![\\p{L}\\p{N}_])`:Ql(e.find),`giu`)}));function a(e){let t=e;for(let e of ql)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(Jl,e=>Zl.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Yl,e=>Xl.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 eu=e=>e.map(e=>JSON.stringify(e)).join(`
|
|
296
297
|
`)+`
|
|
297
|
-
`;function
|
|
298
|
-
`)){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=
|
|
299
|
-
`):``}const
|
|
300
|
-
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=
|
|
301
|
-
`):``}function
|
|
302
|
-
`);return
|
|
303
|
-
`)),Buffer.byteLength(l)>
|
|
304
|
-
`)}async function
|
|
298
|
+
`;function tu(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
|
|
299
|
+
`)){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=nu(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(Mi))]}}function nu(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:ru(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function ru(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(`
|
|
300
|
+
`):``}const iu=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function au(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(`
|
|
301
|
+
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=su(o.cli_version)??r,i=su(o.cwd)??i;else if(e.type===`turn_context`)n=su(o.model)??n,i=su(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=cu(o.content);if(!t.trim()||e===`user`&&iu.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`?lu(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:uu(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(Mi))]}}function ou(e){try{let t=JSON.parse(e);return t.type===`session_meta`?su(t.payload?.cwd):null}catch{return null}}const su=e=>typeof e==`string`&&e?e:null;function cu(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
302
|
+
`):``}function lu(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function uu(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 cu(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return uu(t)}return JSON.stringify(e??``)}const du=()=>process.env.CLAUDE_CONFIG_DIR??m(b(),`.claude`),fu=()=>process.env.CODEX_HOME??m(b(),`.codex`),pu=(e,t=du())=>m(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function mu(e,t,n=process.cwd()){if(t&&l(t))return _(t);let r=e===`claude-code`?await _u(t,n):await vu(t,n);if(r)return r.file;throw Error(t?`No ${gu(e)} session "${t}" on this machine.`:`No ${gu(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function hu(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([_u(void 0,e),vu(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 gu=e=>e===`claude-code`?`Claude Code`:`Codex`;async function _u(e,t){if(e){let t=m(du(),`projects`),n=await Cu(t);for(let r of n){let n=m(t,r,`${e}.jsonl`);if(l(n))return{file:n,mtime:0}}return null}for(let e of wu(t)){let t=pu(e),n=(await Cu(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Su(n.map(e=>m(t,e)))}return null}async function vu(e,t){let n=m(fu(),`sessions`),r=[],i=0;outer:for(let e of yu(await Cu(n)))for(let t of yu(await Cu(m(n,e))))for(let a of yu(await Cu(m(n,e,t)))){let o=m(n,e,t,a);for(let e of await Cu(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(m(o,e));if(r.length>=300||++i>=14)break outer}return bu(r,e,t)}const yu=e=>e.sort().reverse();async function bu(e,t,n){if(t){let n=e.find(e=>d(e).includes(t));return n?{file:n,mtime:0}:null}let r=wu(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await xu(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 Su(t)}return null}async function xu(e){let t=await ie(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(`
|
|
303
|
+
`);return ou(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Su(e){let t=null;for(let n of e){let{mtimeMs:e}=await le(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function Cu(e){try{return await ae(e)}catch{return[]}}function wu(e){let t=[_(e)];for(;p(t.at(-1))!==t.at(-1);)t.push(p(t.at(-1)));return t}const Tu=2e3;function Eu(e){let t=[...e.map],n=ku(()=>w().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=ku(()=>x());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=Du();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=ku(()=>he(`git`,[`rev-parse`,`--show-toplevel`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim());return{replacements:t,paths:[...[...new Set([...e.cwds,a].filter(Boolean))].map(e=>({path:e,as:`<repo>`})),{path:b(),as:`~`}],maxToolText:e.fullOutputs?null:Tu}}function Du(){return ku(()=>he(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function Ou(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 ku(e){try{return e()}catch{return null}}function Au(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))Mu(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(Ei),[...i.values()]}const ju=[`codex`,`cursor`,`gemini-cli`],Mu=(e,t)=>e.length===0||e.includes(t)||ju.includes(t)&&e.some(e=>ju.includes(e));async function Nu(e){Lt(`agent kit report`);let t=await Pu(e.agent[0]),n=await mu(t,e.session||void 0),r=await O(n,`utf8`),i=Ai(t===`claude-code`?tu(r):au(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=$l(Eu({map:e.map?Ou(await Fu(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Lu(e.title,`--title`,`a short title`)),s=a.text(Lu(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=eu(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=Au(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=m(C(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${gu(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${zu(d)}`,`Taken out: ${Bu(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
|
|
304
|
+
`)),Buffer.byteLength(l)>Kl.maxTranscriptBytes)throw Error(`The transcript is over ${Kl.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(!dn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!fn(await Mt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:h,credentials:g}=await Ua(),[_,v]=await Promise.all([h.listOrganizations(),h.listSkills()]),y=Ru(e.org,_,v,d),b=await h.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function Pu(e){if(e===void 0)return hu();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 Fu=e=>e===`-`?Iu():O(e,`utf8`);async function Iu(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Lu(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function Ru(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 zu(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Bu(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${Tu} characters`:`${e} ×${t}`).join(`, `)}function Vu(e){return e&&e.total>0?e.passed/e.total:null}async function Hu(e){let{api:t,credentials:n}=await Ua(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Uu(r,n.webUrl,i.length>1))}function Uu({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=>En({...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=Vu(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(`
|
|
305
|
+
`)}async function Wu(e){switch(e){case`on`:{await Mn({telemetry:!0});let e=await oo();e.status===`skipped`?F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`):F.success(`Telemetry is on: Claude Code reports its sessions and the skills it loads.`);return}case`off`:await Mn({telemetry:!1}),await oo(),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads. Turn it back on with `a-kit telemetry on`.");return;case void 0:case`status`:{let e=await U(),t=(await so()).includes(`telemetry`),n=e.telemetry===!1?`off`:Nn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}.`),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`) and where the session came from (`AGENT_KIT_FROM`). Never what you or the agent wrote.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off or status.`)}}async function Gu(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 Xu();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Yu(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await Ua(),c=bn(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)=>Ku(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;Ju(await d(!0,e=>{m||u(`With ${En(l)} v${a??l.version}`),m=!0,qu(e,l.name)})),u(`Without`);let h=await p;for(let e of f)qu(e,l.name);Ju(h)}async function Ku(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 qu(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 Ju(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=sn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${an(e.usage)}`)}function Yu(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 Xu(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Zu=`a-kit ${Yt}: your agent kit skills, in your agents.
|
|
305
306
|
|
|
306
307
|
Usage
|
|
307
308
|
a-kit init Log in and pick skills to install
|
|
@@ -353,4 +354,4 @@ Report options (the report-session-issue skill passes them for you)
|
|
|
353
354
|
--org <id|name> The organization, when it can't tell
|
|
354
355
|
--full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
|
|
355
356
|
--dry-run Scrub and show what would be sent, without sending
|
|
356
|
-
`;async function
|
|
357
|
+
`;async function Qu(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Ul.has(e))return Wl(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`}}});if(n.version)return console.log(Yt);let[i,...a]=r;if(n.help||!i)return console.log(Zu);if(!qt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Gt.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 Lc(o);case`add`:case`install`:return vo(a,o);case`update`:return Bo(o);case`list`:case`ls`:return Ml();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Hu(a);case`health`:return Ic(a);case`check`:return Xs(a);case`link`:return El(a,o);case`login`:return n.token?Rl():Ll();case`logout`:return Vl();case`whoami`:return Hl();case`try`:return Gu(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return Nu({...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 Wu(a[0]);case`auto-update`:return Uo(a[0]);case`heartbeat`:return Rc(a[0],n.api);case`org`:return Il(a[0],a.slice(1).join(` `)||n.org);case`hook`:return wl(a[0],n.api,a[1]);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Qu().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
|