useakit 0.2.0-dev.86 → 0.2.0-dev.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +22 -20
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -71,7 +71,7 @@ ${r(`gray`,P)}`:``}`}default:{let a=i?`${r(`cyan`,P)} `:``,o=c.split(`
71
71
  `),u=s.length+1;return`${c}${a}${It({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:o+u,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
72
72
  ${a}`)}
73
73
  ${l}
74
- `}}}}).prompt()};`${r(`gray`,P)}`;const Yt=[`stable`,`beta`],Xt=[`latest`,...Yt],Zt=e=>Yt.includes(e),Qt=e=>Xt.includes(e);function $t(e,t,n){if(n===`latest`)return{version:t,fellBack:!1};let r=e[n];return r===null?{version:t,fellBack:!0}:{version:r,fellBack:!1}}var en=`0.2.0`;const tn=[{id:`claude-code`,name:`Claude Code`,projectDir:`.claude/skills`,globalDir:`.claude/skills`,marker:`.claude`},{id:`codex`,name:`Codex`,projectDir:`.agents/skills`,globalDir:`.agents/skills`,marker:`.codex`},{id:`cursor`,name:`Cursor`,projectDir:`.agents/skills`,globalDir:`.cursor/skills`,marker:`.cursor`},{id:`gemini-cli`,name:`Gemini CLI`,projectDir:`.agents/skills`,globalDir:`.gemini/skills`,marker:`.gemini`}],nn=e=>e===`global`?x():process.cwd();function rn(e=x()){return tn.filter(t=>u(h(e,t.marker)))}function an(e){return tn.find(t=>t.id===e)}function on(e,t,n=nn(t)){let r=e.map(e=>v(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const sn={maxNameLength:100,maxPromptBytes:20480,maxChecks:20,maxHiddenFiles:20,maxHiddenBytes:1048576,maxSetupLength:4096,maxCheckTextLength:10240,minTrials:1,maxTrials:5,maxAttemptsPerRun:50,maxModelsPerRun:4,maxFinalTextBytes:20480,maxJudgedDiffBytes:102400,maxCheckOutputBytes:8192,maxSandboxesPerOrganization:5};function cn(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}sn.maxPromptBytes;function ln(e){return e<1e3?String(e):e<1e6?`${dn(e/1e3)}k`:`${dn(e/1e6)}M`}const un=e=>`${ln(e.inputTokens+e.outputTokens)} tok · ${cn(e.costUsd)}`,dn=e=>e>=100?Math.round(e):Number(e.toFixed(1));function fn(e){switch(e){case`refusal`:return`Claude declined to answer this.`;case`max_tokens`:return`The answer was cut off at the token limit.`;case`tool_use`:return`Stopped after too many skill loads in one turn.`;default:return null}}function pn(e){let t=e.split(`
74
+ `}}}}).prompt()};`${r(`gray`,P)}`;const Yt=[`stable`,`beta`],Xt=[`latest`,...Yt],Zt=e=>Yt.includes(e),Qt=e=>Xt.includes(e);function $t(e,t,n){if(n===`latest`)return{version:t,fellBack:!1};let r=e[n];return r===null?{version:t,fellBack:!0}:{version:r,fellBack:!1}}var en=`0.2.0-dev.88`;const tn=[{id:`claude-code`,name:`Claude Code`,projectDir:`.claude/skills`,globalDir:`.claude/skills`,marker:`.claude`},{id:`codex`,name:`Codex`,projectDir:`.agents/skills`,globalDir:`.agents/skills`,marker:`.codex`},{id:`cursor`,name:`Cursor`,projectDir:`.agents/skills`,globalDir:`.cursor/skills`,marker:`.cursor`},{id:`gemini-cli`,name:`Gemini CLI`,projectDir:`.agents/skills`,globalDir:`.gemini/skills`,marker:`.gemini`}],nn=e=>e===`global`?x():process.cwd();function rn(e=x()){return tn.filter(t=>u(h(e,t.marker)))}function an(e){return tn.find(t=>t.id===e)}function on(e,t,n=nn(t)){let r=e.map(e=>v(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const sn={maxNameLength:100,maxPromptBytes:20480,maxChecks:20,maxHiddenFiles:20,maxHiddenBytes:1048576,maxSetupLength:4096,maxCheckTextLength:10240,minTrials:1,maxTrials:5,maxAttemptsPerRun:50,maxModelsPerRun:4,maxFinalTextBytes:20480,maxJudgedDiffBytes:102400,maxCheckOutputBytes:8192,maxSandboxesPerOrganization:5};function cn(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}sn.maxPromptBytes;function ln(e){return e<1e3?String(e):e<1e6?`${dn(e/1e3)}k`:`${dn(e/1e6)}M`}const un=e=>`${ln(e.inputTokens+e.outputTokens)} tok · ${cn(e.costUsd)}`,dn=e=>e>=100?Math.round(e):Number(e.toFixed(1));function fn(e){switch(e){case`refusal`:return`Claude declined to answer this.`;case`max_tokens`:return`The answer was cut off at the token limit.`;case`tool_use`:return`Stopped after too many skill loads in one turn.`;default:return null}}function pn(e){let t=e.split(`
75
75
  `),n=t.pop()??``,r=[];for(let e of t)if(e.trim()!==``)try{r.push(JSON.parse(e))}catch{r.push({type:`error`,message:`The answer came back garbled.`})}return{events:r,rest:n}}function mn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?en.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${mn()} ${e}\``;var R=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function z(e,t,n=fetch){async function r(r,i={}){let a;try{a=await n(`${e}${r}`,{...i,headers:{"User-Agent":`a-kit/${en}`,...i.body?{"Content-Type":`application/json`}:{},...t?{Authorization:`Bearer ${t}`}:{},...i.headers}})}catch{throw new R(0,`NETWORK`,`Couldn't reach ${e}.`)}if(!a.ok){let e=await a.json().catch(()=>null);throw a.status===401?new R(401,`UNAUTHORIZED`,`You're not logged in. Run ${L(`login`)}.`):new R(a.status,e?.code??`HTTP_ERROR`,e?.message??`${i.method??`GET`} ${r} failed (${a.status})`)}return a}let i=async(e,t)=>await(await r(e,t)).json();return{me:()=>i(`/me`),logout:()=>r(`/auth/logout`,{method:`POST`}),startLogin:()=>i(`/auth/cli`,{method:`POST`}),pollLogin:e=>i(`/auth/cli/token`,{method:`POST`,body:JSON.stringify({deviceCode:e})}),listSkills:async()=>{let[e,t]=await Promise.all([i(`/skills`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)?.name??``,organizationSlug:n.get(e.organizationId)?.slug??null,showOrganization:t.length>1}))},listKits:async()=>{let[e,t]=await Promise.all([i(`/kits`),i(`/orgs`)]),n=new Map(t.map(e=>[e.id,e.name]));return e.map(e=>({...e,organizationName:n.get(e.organizationId)??``,showOrganization:t.length>1}))},getKit:e=>i(`/kits/${e}`),listOrganizations:e=>i(`/orgs`,{signal:e}),listSkillSummaries:e=>i(`/skills`,{signal:e}),listProjects:(e,t)=>i(`/orgs/${e}/projects`,{signal:t}),listRoles:(e,t)=>i(`/orgs/${e}/roles`,{signal:t}),getRepository:(e,t)=>i(`/orgs/${e}/repository`,{signal:t}),reportActivations:(e,t)=>i(`/activations`,{method:`POST`,body:JSON.stringify({activations:e}),signal:t}),reportSessionEvents:(e,t)=>i(`/agent-sessions/events`,{method:`POST`,body:JSON.stringify({events:e}),signal:t}),reportSessionUsage:(e,t)=>i(`/agent-sessions/usage`,{method:`POST`,body:JSON.stringify({sessions:e}),signal:t}),fingerprint:(e,t)=>i(`/fingerprint`,{method:`POST`,body:JSON.stringify(e),signal:t}),sendHeartbeat:(e,t)=>i(`/machines/heartbeat`,{method:`POST`,body:JSON.stringify(e),signal:t}),machineName:e=>i(`/machines/${encodeURIComponent(e)}/name`),nameMachine:(e,t)=>i(`/machines/${encodeURIComponent(e)}/name`,{method:`PUT`,body:JSON.stringify({name:t})}),search:e=>i(`/search?q=${encodeURIComponent(e)}`),getSkill:(e,t=`latest`)=>i(`/skills/${e}${t===`latest`?``:`?channel=${t}`}`),getVersion:(e,t)=>i(`/skills/${e}/versions/${t}`),getSkillHealth:e=>i(`/skills/${e}/health`),createReport:(e,t)=>i(`/orgs/${e}/reports`,{method:`POST`,body:JSON.stringify(t)}),playground:async(e,t,n)=>{let i=await r(`/skills/${e}/playground`,{method:`POST`,body:JSON.stringify(t)}),a=``,o=new TextDecoder;for await(let e of i.body??[]){let t=pn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}pn(`${a}${o.decode()}\n`).events.forEach(n)},getBlob:async(e,t)=>new Uint8Array(await(await r(`/skills/${e}/blobs/${t}`)).arrayBuffer()),getPublicSkill:e=>i(`/public/skills/${hn(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${hn(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${hn(e)}/installs`,{method:`POST`})}}const hn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),gn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function B(e){return tt(e)&&(Vt(`Cancelled.`),process.exit(130)),e}async function _n(e,t){if(e.length>0)return e.map(e=>{let t=an(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${tn.map(e=>e.id).join(`, `)}.`);return t});let n=rn(),r=n.length>0?n:[an(`claude-code`)];return!t||!gn()?r:B(await Bt({message:`Which agents should get the skills?`,options:tn.map(e=>({value:e.id,label:e.name,hint:n.includes(e)?`detected`:void 0})),initialValues:r.map(e=>e.id),required:!0})).map(e=>an(e))}async function vn(e,t){return e?`global`:!t||!gn()?`project`:B(await Jt({message:`Where should they go?`,options:[{value:`project`,label:`This project`,hint:process.cwd()},{value:`global`,label:`Everywhere`,hint:`your home folder`}],initialValue:`project`}))}const yn=`kit/`;function bn(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 xn(e,t,n){if(t.length>0)return Cn(e,t,n,`skill`);if(!n||!gn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=B(await Bt({message:`Which skills?`,options:e.map(e=>({value:e.id,label:An(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const Sn=(e,t,n)=>Cn(e,t,n,`kit`);async function Cn(e,t,n,r){let i=[];for(let a of t){let t=Dn(e,a,r),o=t.length===1?t[0]:await On(t,n,r);i.includes(o)||i.push(o)}return i}const wn=(e,t)=>Dn(e,t,`skill`);function Tn(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 En=(e,t)=>Tn(e,t);function Dn(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=Tn(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 On(e,t,n){let r=e[0].name,i=n===`kit`?yn:``;if(!t||!gn()){let t=e.map(e=>{let t=i+kn(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=B(await Jt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:kn(e)}))}));return e.find(e=>e.id===a)}const kn=e=>`${e.organizationName}/${e.name}`,An=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function V(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function jn(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function H(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?h(process.env.APPDATA,`agent-kit`):h(process.env.XDG_CONFIG_HOME??h(x(),`.config`),`agent-kit`)}const Mn=()=>h(H(),`credentials.json`);async function Nn(){try{return JSON.parse(await O(Mn(),`utf8`))}catch{return{}}}async function U(){return(await Nn())[V()]??null}async function Pn(e){let t=await Nn();e?t[V()]=e:delete t[V()];let n=Mn();await D(m(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
76
76
  `,{mode:384}),await te(n,384)}const Fn=()=>h(H(),`settings.json`);async function In(){try{return JSON.parse(await O(Fn(),`utf8`))}catch{return{}}}async function Ln(e){let t={...await In(),...e};await D(H(),{recursive:!0,mode:448}),await k(Fn(),JSON.stringify(t,null,2)+`
77
77
  `)}function Rn(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=_(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const zn=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Bn(e){return e.split(`/`).some(e=>zn.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const Vn=e=>pe(`sha256`).update(e).digest(`hex`);async function Hn(e){let t=await oe(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=_(e,h(r.parentPath,r.name)).split(y).join(`/`);if(Bn(t))continue;let i=new Uint8Array(await O(h(e,t)));n.push({path:t,size:i.byteLength,sha256:Vn(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Un(e,t){let n=new Map(t.filter(e=>!Bn(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 Wn(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 Gn(e,t){for(let n of e){if(!u(n))continue;let{paths:e}=Un(await Hn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Kn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?Gn(r.map(e=>h(e,t)),i.files):null}async function qn(e){try{if(!(await ie(e)).isSymbolicLink())return null}catch{return null}return v(m(e),await se(e))}async function Jn(e,t){for(let n of e){let e=await qn(h(n,t));if(e)return e}return null}async function Yn(e,t){await le(e,{recursive:!0,force:!0}),await D(m(e),{recursive:!0}),await de(t,e,process.platform===`win32`?`junction`:`dir`)}const G=`SKILL.md`,Xn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},Zn=/[\u0000-\u001f\u007f\\:]/;function Qn(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Xn.maxPathLength)return`Paths can be at most ${Xn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if(Zn.test(e))return`Paths can't contain \\, : or control characters.`;for(let t of e.split(`/`)){if(t===``)return`The path has an empty folder name (//).`;if(t===`.`||t===`..`)return`The path can't contain . or .. folders.`;if(t!==t.trim())return`Names can't start or end with a space.`}return null}function $n(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function er(e){return e.slice(e.lastIndexOf(`/`)+1)}function tr(e,t){let n=$n(e)?$n(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})),nr=/* @__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})),rr=/* @__PURE__ */ A((e=>{var t=K(),n=nr();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(`
@@ -288,25 +288,27 @@ description:
288
288
  `)||null,place:null}}async function Jc(e,t,n){let r=await U();return qc(t,(await Nc(e)).repository,r&&{api:z(V(),r.token),organizationId:r.organizationId},n)}function Yc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=v(n,i);if(Rc(t)){if(t===e||t===h(e,`skills`))return[];if(m(t)===h(e,`skills`)){r.push(f(t));continue}let n=_(h(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(y)[0]);continue}throw Error(`${W(t)} isn't a skill's folder. Skills are in ${W(h(e,`skills`))}/<skill>/.`)}if(!/^[a-z0-9-]+$/.test(i))throw Error(`There's no folder ${i}, and it isn't a skill's name.`);r.push(i)}return[...new Set(r)]}const Xc=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function Zc(e){let t=zc(e.find(e=>e.includes(`/`))??`.`),n=Yc(t,e),r=await Vc(t),i=new Set(r.skills.map(e=>e.name)),a=n.filter(e=>!i.has(e));if(a.length>0)throw Error(`There's no ${a.map(e=>`skills/${e}/`).join(`, `)} in ${W(t)}.`);let{scan:o,unchecked:s,place:c}=await Jc(t,r,{roles:n.length===0}),l=c?.placement.main?0:o.flows?.length??0,u=n.length>0?Xc(o.problems,n):o.problems;for(let e of vs(u))console.log(e);s&&console.log(`${u.length?`
289
289
  `:``}${s}`);let d=u.filter(e=>e.severity===`error`).length,f=u.length-d,p=n.length===1?n[0]:n.length>0?_s(n.length,`skill`):`The repository (${[_s(o.skills.length,`skill`),...l?[_s(l,`flow`)]:[]].join(`, `)})`;d>0?(console.log(`\n${p}: ${_s(d,`error`)}`+(f?`, ${_s(f,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((u.length||s?`
290
290
  `:``)+`${p}: no errors`+(f?`, ${_s(f,`warning`)}`:``)+`.`)}const Qc={maxPerRequest:20,maxEntries:1e3,maxAgeDays:bc.maxAgeDays,maxFutureMs:bc.maxFutureMs,maxMachineNameLength:bc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},$c={inputTokens:`tokens.input`,outputTokens:`tokens.output`,cacheReadTokens:`tokens.cache_read`,cacheCreationTokens:`tokens.cache_creation`,costUsd:`cost.usd`,personSeconds:`active.person`,agentSeconds:`active.agent`,prompts:`prompts`,commits:`commits`,pullRequests:`pull_requests`},el=e=>typeof e==`string`&&e.length>0&&e.length<=Qc.maxModelLength&&!/\s/.test(e)&&!Tc.test(e),tl={maxPerRequest:100,maxLinks:50,maxAgeDays:bc.maxAgeDays,maxFutureMs:bc.maxFutureMs,maxMachineNameLength:bc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},nl=/^[1-9][0-9]{0,8}$/,rl=/\s/,il=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function al(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Dc(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 Dc(r)&&(e===`branch`?Oc(i):nl.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return sl(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=tl.maxThreadLength&&!rl.test(n)&&!Tc.test(n)?{kind:e,value:n}:null;case`session`:return xc.test(n)?{kind:e,value:n}:null;default:return null}}function ol(e){let t=e.trim();return al(`slack_thread`,t)??al(`thread`,t)}function sl(e){return e.length<=tl.maxUrlLength&&il.test(e)}const cl=()=>h(H(),`sessions`),ll=()=>h(H(),`pending-session-events.jsonl`),ul=e=>pe(`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(`
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(al(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(al(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(al(`issue`,`${t}#${o}`)),i}function pl(e,t,n){let r=[],i=e=>{e&&!r.some(t=>t.kind===e.kind&&t.value===e.value)&&r.push(e)};for(let r of e.split(/&&|\|\||[;|\n]/)){let e=_l(r);for(;e[0]&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[0]);)e.shift();let[a,o,s,...c]=e;if(a!==`gh`)continue;if(s===`create`&&(o===`pr`||o===`issue`)){let e=RegExp(`https://(github\\.com/[^\\s/]+/[^\\s/]+)/${o===`pr`?`pull`:`issues`}/(\\d+)`).exec(t);e&&i(al(o===`pr`?`pull_request`:`issue`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`||!ml.has(s??``))continue;let l=n,u=null;for(let[e,t]of c.entries()){let n=/^(?:-R|--repo)(?:=(.*))?$/.exec(t);if(n){let t=n[1]??c[e+1];t&&(l=gl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||hl.test(t))&&(u=t)}if(!u)continue;let d=hl.exec(u);d?i(al(`issue`,`${d[1]}#${d[2]}`)):l&&i(al(`issue`,`${l}#${u.replace(`#`,``)}`))}return r}const ml=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),hl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/issues\/(\d+)/,gl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function _l(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function vl(e){if(e.hook_event_name!==`PostToolUse`||e.tool_name!==`Bash`||typeof e.tool_input?.command!=`string`)return null;let t=e.tool_response?.stdout;return{command:e.tool_input.command,stdout:typeof t==`string`?t:``}}function yl(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 bl(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||!xc.test(l))return null;c===`end`&&t.reason===`clear`&&await El(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(al(`repository`,i.repository)),i.branch&&!await Pc(r,i.branch)&&d(al(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=yl(t);if(p&&f)for(let e of fl(p,i.repository))d(e);let m=vl(t);if(m&&f)for(let e of pl(m.command,m.stdout,i.repository))d(e);if(c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&f)for(let t of e.split(/\s+/))d(ol(t));if(t.source===`clear`){let e=await Dl(r,l,o,s);e&&d(al(`session`,e))}}let h=await Cl(l),g=u.map(e=>`${e.kind} ${e.value}`),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await wl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await Ol(o),{sessionId:l,agent:e,machineId:await ya(),machineName:fa(),type:c,occurredAt:o.toISOString(),links:u})}const xl=(e,t=[])=>pa(ll(),e,t),Sl=e=>h(cl(),`${ul(e)}.json`);async function Cl(e){try{let t=JSON.parse(await O(Sl(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 wl(e,t){await D(cl(),{recursive:!0,mode:448}),await k(Sl(e),JSON.stringify(t)+`
292
- `)}const Tl=e=>h(cl(),`cleared-${ul(e)}.json`);async function El(e,t,n){await D(cl(),{recursive:!0,mode:448}),await k(Tl(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
293
- `)}async function Dl(e,t,n,r){let i=Tl(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await le(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Ce(100)}}async function Ol(e){try{for(let t of await oe(cl())){let n=h(cl(),t),{mtimeMs:r}=await ue(n);e.getTime()-r>6048e5&&await le(n,{force:!0})}}catch{}}function kl(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await X(n.projectLock):null,a=await X(Y(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await ss(r.userId),d=!u||n.repository!==null&&!Object.hasOwn(u.repositories,n.repository)||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await us(r.api,r.userId,u,new Date(s))??u),(u&&Al(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function Al(e,t,n,r){let{repository:i}=e,a=i&&Object.hasOwn(r.repositories,i)?r.repositories[i]:null;if(!a){let e=/* @__PURE__ */ new Map;for(let{id:n}of Object.values(t?.skills??{})){let t=r.skills[n];t&&e.set(t,(e.get(t)??0)+1)}a=[...e.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null}if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const jl={"claude_code.token.usage":{input:$c.inputTokens,output:$c.outputTokens,cacheRead:$c.cacheReadTokens,cacheCreation:$c.cacheCreationTokens},"claude_code.cost.usage":$c.costUsd,"claude_code.active_time.total":{user:$c.personSeconds,cli:$c.agentSeconds},"claude_code.commit.count":$c.commits,"claude_code.pull_request.count":$c.pullRequests};function Ml(e){let t=[];for(let n of Il(Q(e,`resourceMetrics`)))for(let e of Il(Q(n,`scopeMetrics`)))for(let n of Il(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?jl[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of Il(Q(i,`dataPoints`))){let i=Il(Q(n,`attributes`)),o=e=>Ll(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Rl(Q(n,`asDouble`)??Q(n,`asInt`)),u=zl(Q(n,`startTimeUnixNano`)),d=zl(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Pl(e,i,a?u:null),metric:c,model:Fl(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Nl(e){let t=[];for(let n of Il(Q(e,`resourceLogs`)))for(let e of Il(Q(n,`scopeLogs`)))for(let n of Il(Q(e,`logRecords`))){let e=Il(Q(n,`attributes`)),r=Ll(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Ll(e,`session.id`),a=zl(Q(n,`timeUnixNano`))??zl(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Pl(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return pe(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const Fl=e=>el(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Il=e=>Array.isArray(e)?e:[];function Ll(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Rl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function zl(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const Bl=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Vl(e){let t=()=>h(ro(),e),n=e=>h(t(),`${Bl(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
294
- `)},async list(){let e=[];try{e=await oe(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(h(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await oe(t())){let r=h(t(),n);e-(await ue(r)).mtimeMs>6048e5&&await le(r,{force:!0})}}catch{}}}}const Hl=Vl(`sessions`),Ul=e=>Hl.write(e.sessionId,e);async function Wl(e){let t=await Hl.read(e);return t?.sessionId===e?t:null}const Gl=(e=Date.now())=>Hl.forgetOld(e),Kl=Vl(`sent`),ql=(e,t,n=/* @__PURE__ */ new Date)=>Kl.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Jl=e=>Kl.read(e),Yl=async()=>(await Kl.list()).sort((e,t)=>t.at.localeCompare(e.at)),Xl=(e=Date.now())=>Kl.forgetOld(e),Zl=(e,t)=>({sessionId:e,epoch:t,series:{},prompts:0,lastAt:t});function Ql(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n];if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}return e.lastAt=Math.max(e.lastAt,s),!0}function $l(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)};for(let n of Object.values(e.series))r({metric:n.metric,model:n.model,skillId:n.skillName!==null&&Object.hasOwn(t.skillIds,n.skillName)?t.skillIds[n.skillName]:null,start:new Date(n.start).toISOString(),value:n.value});return e.prompts>0&&r({metric:$c.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,Qc.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const eu=Vl(`state`);function tu(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=nu(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);Ql(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await eu.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await eu.write(e.state.sessionId,e.state))}}}async function nu(e,t){let n=await eu.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Zl(e,t),unsaved:!1}}const ru=(e=Date.now())=>eu.forgetOld(e),iu=16777216,au=()=>h(H(),`pending-session-usage.jsonl`);async function ou(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=tu(),s=kl(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new R(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!ha(e))for(let e of t)await ql(e,`refused`);throw e}for(let e of t)await ql(e,`sent`)}),p=(e=[])=>pa(au(),f,e,{batch:Qc.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await Wl(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=$l(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await ya(),machineName:fa(),skillIds:i.skillIds});a.usage.length!==0&&(await ql(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),Sa(h),xl(g)]);function v(e){let t=uu(e.activations),n=uu(e.sessionEvents);return u(()=>Promise.all([t.length>0&&Sa(h,t),n.length>0&&xl(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(ee(),!S(t.headers[`x-agent-kit-collector`]))return t.resume(),lu(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return lu(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),lu(n,404,{});if(i===`/stop`){t.resume(),lu(n,200,{}),oe({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),lu(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),lu(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),lu(n,415,{message:`Send JSON.`});let a=await cu(t);if(!a.ok)return lu(n,a.status,{});i===`/report`?(lu(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?Ml(a.json):Nl(a.json)),b(),lu(n,200,{}))}let S=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ge(t,c)},C=xe((e,t)=>{x(e,t).catch(()=>{t.headersSent||lu(t,500,{})})});if(!await new Promise(t=>{C.once(`error`,()=>t(!1)),C.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let w=null,T=Date.now(),E=e=>{w&&clearTimeout(w),w=setTimeout(()=>void te(),e)};function ee(){T=Date.now(),E(i)}async function te(){let e=T,t=!1;if(await u(async()=>{let e=[au(),xa(),ll()];t=(await Promise.all(e.map(ma))).some(Boolean)||(await o.dirty()).length>0}),O||T!==e)return;let n=Date.now()-T;t&&n<a?E(Math.max(1,Math.min(i,a-n))):oe()}ee();let ne=setInterval(()=>void u(m),t),re=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await Gl(e),await ru(e),await Xl(e),await o.resume()});let ie=()=>u(m).then(()=>u(_)),D=()=>{},ae=new Promise(e=>D=e),O=null;function oe({send:e=!0}={}){return O??=(async()=>{w&&clearTimeout(w),y&&clearTimeout(y),clearInterval(ne),clearInterval(re);let t=new Promise(e=>C.close(()=>e()));C.closeIdleConnections(),await(e?ie():u(()=>o.save())),C.closeAllConnections(),await t,D()})(),O}return{port:C.address().port,flush:ie,stop:oe,stopped:ae}}const su=n(Se);async function cu(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>iu)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await su(r,{maxOutputLength:iu})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function lu(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const uu=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function du(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await oo();await(await ou({port:t,secret:n,apiUrl:V(),login:async()=>{let e=await U();return e?{api:z(V(),e.token),userId:e.user.id}:null}}))?.stopped}const fu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,pu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function mu(e){let t=0;for(let[n]of e.matchAll(pu)){let e=n[0];if(e===`
295
- `)t+=1;else if(/\s/.test(e))t+=n.length===1?0:Math.ceil(n.length/4);else if(/\p{L}/u.test(e)){let e=0;for(let t of n)fu.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 hu(e){return{always:e.description,max:e.description+e.body+e.files}}function gu(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=hu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function _u(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${yu((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${yu((e/1e6).toFixed(1))}M`}const vu=(e,t)=>`${t===`estimate`?`~`:``}${_u(e)}`,yu=e=>e.replace(/\.0$/,``),bu={high:15,medium:10,low:5},xu=5e3,Su=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function Cu(e){let t=er(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&Su.has(n)}const wu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Tu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Eu(e,t){let n=t(`SKILL.md`)??``,r=yi(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)Cu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Ru(r)){let t=tr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&zu(r,n,t.path)&&(d.add(t.path),Cu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!wu.test(er(e))).filter(e=>!er(e).startsWith(`.`)).sort();return{v:1,description:typeof a==`string`&&a.trim()!==``?a.trim():null,hasWhenToUse:typeof o==`string`&&o.trim()!==``,bodyLines:c===``?0:c.split(`
296
- `).length,bodyTokens:mu(c),hasExamples:Gu(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Du(e,t,n=/* @__PURE__ */ new Date){let r=[...Fu(e),...t?Iu(t,n):[]];return{score:Ou(r),checks:Au(r)}}function Ou(e){let t=e.reduce((e,t)=>e+bu[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+bu[t.severity],0);return Math.round(n/t*100)}const ku=[`high`,`medium`,`low`];function Au(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:ku.indexOf(e.severity)-ku.indexOf(t.severity)))}const ju=(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}),Mu=/\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,Nu=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Pu=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Fu(e){let t=[],n=e.description??``;e.hasWhenToUse||Mu.test(n)?t.push(ju(`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(Nu);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(ju(`description-specific`,`medium`,`description is specific`)),Pu.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(ju(`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(ju(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Lu(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>xu?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Lu(xu)}; move reference material into files ${G} links to.`)):t.push(ju(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(ju(`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(ju(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${Ku(e.missingFiles.length,`missing file`)}: ${qu(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(ju(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${Ku(e.unusedFiles.length,`file`)} nothing mentions: ${qu(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function Iu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(ju(`eval-cases`,`high`,Ku(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Ku(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(ju(`eval-negative`,`medium`,`${Ku(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(ju(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${Ku(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 Lu(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Ru(e){let t=[];for(let n of e.matchAll(Tu)){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 zu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,er(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Bu(t,n);return a&&r.add(a),[...r].some(t=>Vu(e,t))}function Bu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Vu(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 Hu=/^(```|~~~)/m,Uu=/^#{1,6}[^\n]*\bexamples?\b/im,Wu=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Gu(e){return Hu.test(e)||Uu.test(e)||Wu.test(e)}function Ku(e,t){return`${e} ${t}${e===1?``:`s`}`}function qu(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Ju=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Yu(e){try{return(await ue(h(e,G))).isFile()}catch{return!1}}async function Xu(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await oe(i,{withFileTypes:!0})){let o=h(i,a.name);if(a.isDirectory()){Ju.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=_(e,o).split(y).join(`/`),{size:c}=await ue(o);t.push({path:s,size:c}),(s===`SKILL.md`||Cu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Du(Eu(t,e=>n.get(e)),null)}function Zu(e){let t=[`HEALTH ${e.score}/100`];for(let n of e.checks)n.passed?t.push(`✓ ${n.message}`):(t.push(`■ ${n.message} [${n.severity}]`),n.fix&&t.push(` ${n.fix}`));return t.join(`
297
- `)}async function Qu(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=v(t??`.`);if(await Yu(n)){let e=await Xu(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(Zu(e));return}if(t===void 0)throw Error("There's no SKILL.md here. Name one of your skills, like `a-kit health pdf-forms`, or a skill's folder.");let{api:r}=await $a(),i=wn(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(`${An(a)} v${a.version}`),console.log(Zu(o))}async function $u(e){Ht(`agent kit`);let t=await Qa();t?F.success(`Logged in as ${eo(t.user)}`):t=await Za();let n=z(V(),t.token),r=await n.listSkills();if(r.length===0){I(to(t.webUrl));return}let i=!e.yes;if(i&&!gn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await vn(e.global,i),o=await _n(e.agent,i),s=i?B(await Bt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:An(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await Ho(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 ed(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ja();return;case`on`:{if(await Ln({heartbeat:!0}),!await U()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!sa()){F.warn(`Run it from the published CLI to install the timer.`);return}await Ya();let e=await Ha(V()),t=(await qa())?.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 Ln({heartbeat:!1}),await Va(V()),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 In()).heartbeat!==!1,t=await Ha(V()),n=await qa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?La(V()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
298
- Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const td=2e3;async function nd(e,t={},n=300){let{port:r,secret:i}=await oo();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[no]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function rd(){let e=await nd(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function id(e,t,n=Go){let r=await rd();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await od(),u(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function ad(e){return(await nd(`/report`,{method:`POST`,body:JSON.stringify(e)},td))?.status===202}async function od({send:e=!0}={}){return(await nd(e?`/stop`:`/stop?send=false`,{method:`POST`},td))?.ok??!1}const sd=5e3;async function cd(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 dd()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Qo(sa()??oa()),await Ha(V())||await Ja();return}if(Rn()||(await In()).telemetry===!1)return;let o=await U();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await ss(o.user.id),u=c?{...kc,sessionId:Ac(r.session_id)}:await jc(r.session_id,s,void 0,l),d=z(V(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await ud(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await id(sa()??oa(),V());let p=await bl(e,r,a,s,u,{now:i}),m=Oo(r),h=m&&await _a(m.name,e,s),g=m&&h&&await ba(h,e,m.trigger,Mc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&ls(l,i,h?h.id:null)&&us(d,o.user.id,l,i),(p||g)&&ld(d,p,g)])}catch{}}async function ld(e,t,n){await ad({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&xl(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(sd))},t),n&&Sa(async t=>{await e.reportActivations(t,AbortSignal.timeout(sd))},n)])}async function ud(e,t,n){let{repository:r,branch:i}=await Nc(n),a=va(n,x());(r||a)&&await Ul({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function dd(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function fd(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Ht(`agent kit`);let n=v(e[0]);if(!u(h(n,`SKILL.md`)))throw Error(`${W(n)} has no ${G}, so it isn't a skill.`);let r=f(n);if(!/^[a-z0-9-]+$/.test(r)||r===`report-session-issue`)throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await _n(t.agent,!t.yes),o=on(a,i),s=o.map(e=>h(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(u(e)&&!await qn(e)&&!c)throw Error(`${W(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Kn(z(V(),(await U())?.token),r,c,o);if(e&&!await qn(e.folder))throw Error(`${W(e.folder)} has edits that aren't in agent kit (${Wn(e.paths)}). Copy them to ${W(n)} and delete them there first.`)}for(let e of s)await Yn(e,n);F.success(`${r}: ${s.map(W).join(`, `)} → ${W(n)}`);let l=i===`project`?await pd(on(a,`global`),r,n):[];l.length>0&&F.warn(`You also have ${r} in ${l.map(W).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await md(n,r,c!==void 0),I(`${l.length>0?`This project's agents would use`:`Your agents use`} ${W(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function pd(e,t,n){let r=[];for(let i of e){let e=h(i,t);u(e)&&await qn(e)!==n&&r.push(e)}return r}async function md(e,t,n){let r;try{r=zc(e)}catch{return}if(v(r,`skills`,t)!==e)return;let{scan:i,place:a}=await Jc(r,await Vc(r),{roles:!1}),o=a?.placement.skills.get(t);n&&o!==void 0&&F.warn(`The ${t} you installed from agent kit is ${o}'s, a different skill: this link takes its place, so your agents use ${W(e)} instead. ${L(`add ${t}`)} puts ${o}'s back.`);let s=Xc(i.problems,[t]);s.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...vs(s)].join(`
299
- `))}function hd(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?vu(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[An(e),gd(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[_d(`project`,r,e),_d(`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=gu(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}${_u(c.always)} always · ${l}${_u(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 gd(e){return[`v${e.version}`,...Yt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function _d(e,t,n){if(!t)return null;let r=qi(t),{version:i}=$t(n.channels,n.version,r),a=`in ${e}${r===`latest`?``:` on ${r}`}`;return t.version===i?a:`${a} at v${t.version}, run a-kit update${e===`global`?` -g`:``}`}async function vd(){let{api:e,credentials:t}=await $a(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(to(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of hd(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>yd(e).length));for(let e of r){let t=[bd(i,e)&&`in project`,bd(a,e)&&`in global`].filter(Boolean);console.log(`${yd(e).padEnd(o)} ${xd(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const yd=e=>`${yn}${An(e)}`,bd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function xd(e){let t=e.skills.length;if(t===0)return`no skills`;let n=e.skills.slice(0,3).map(e=>e.name);return`${t} skill${t===1?``:`s`}: ${n.join(`, `)}${t>3?`, …`:``}`}const Sd=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${L(`heartbeat status`)}).`;async function Cd(e,t){switch(e){case`name`:{let{api:e}=await $a(),n=await ya();if(t===void 0){let t=await wd(e.machineName(n));if(!t)throw Error(Sd);console.log(t.name?`This machine is "${t.name}" on the Machines page (its hostname is ${t.hostname}).`:`This machine goes by its hostname, "${t.hostname}", on the Machines page. Name it with ${L(`machine name <name>`)}.`);return}let r=await wd(e.nameMachine(n,t))??(await Ja()?await wd(e.nameMachine(n,t)):null);if(!r)throw Error(Sd);F.success(r.name?`This machine is "${r.name}" on the Machines page.`:`This machine goes by its hostname, "${r.hostname}", on the Machines page.`);return}default:throw Error(`Unknown machine action "${e??``}". Use ${L(`machine name [<name>]`)}.`)}}async function wd(e){try{return await e}catch(e){if(e instanceof R&&e.status===404)return null;throw e}}async function Td(e,t){switch(e){case void 0:case`status`:{let e=(await qa())?.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 $a(),r=await Aa(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await In()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Ja()?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 Ed(){Ht(`agent kit`);let e=await Qa().catch(()=>null);if(e){let t=eo(e.user);if(!gn()){I(`Already logged in as ${t}.`);return}if(!B(await Lt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Za();e&&await z(V(),e.token).logout().catch(()=>{}),I(await kd(t.token,t.webUrl))}async function Dd(e=process.stdin){Ht(`agent kit`);let t=await Od(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(V(),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 U();await Pn({token:t,user:n,webUrl:jn(V())}),r&&r.token!==t&&await z(V(),r.token).logout().catch(()=>{}),await Ya(),I(`Logged in as ${eo(n)}.`)}async function Od(e){if(e.isTTY)return B(await Ut({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function kd(e,t){return(await z(V(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${to(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function Ad(){let e=await U();e?(await z(V(),e.token).logout().catch(()=>{}),await Pn(null),console.log(`Logged out ${eo(e.user)}.`)):console.log(`You're not logged in.`)}async function jd(){let e=await Qa();e?console.log(eo(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Md=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Nd(e){let t=await Pd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${mn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${L(`check <skill>`)}`,` 3. Try it in your agent: ${L(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${L(`add <skill>`)} or ${L(`update`)}.`),Error(r.join(`
300
- `))}async function Pd(){let e=(await U())?.token;if(!e)return[];let t=z(V(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Fd={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},Id=[{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}],Ld=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Rd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,zd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Bd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Vd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Hd(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(Vd(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}_])${Vd(e.find)}(?![\\p{L}\\p{N}_])`:Vd(e.find),`giu`)}));function a(e){let t=e;for(let e of Id)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(Ld,e=>Bd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Rd,e=>zd.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 Ud=e=>e.map(e=>JSON.stringify(e)).join(`
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(al(t===`pull`?`pull_request`:`issue`,`${e}#${n}`));if(!t)return i;for(let[,e]of r.matchAll(/(?:^|\s)#(\d+)\b/g))a(al(`issue`,`${t}#${e}`));let o=/^(?:[a-z][a-z-]*\s+)?(\d+)$/.exec(r)?.[1];return o&&a(al(`issue`,`${t}#${o}`)),i}function pl(e,t,n){let r=[],i=e=>{e&&!r.some(t=>t.kind===e.kind&&t.value===e.value)&&r.push(e)};for(let r of e.split(/&&|\|\||[;|\n]/)){let e=_l(r);for(;e[0]&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[0]);)e.shift();let[a,o,s,...c]=e;if(a!==`gh`)continue;if(s===`create`&&(o===`pr`||o===`issue`)){let e=RegExp(`https://(github\\.com/[^\\s/]+/[^\\s/]+)/${o===`pr`?`pull`:`issues`}/(\\d+)`).exec(t);e&&i(al(o===`pr`?`pull_request`:`issue`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`||!ml.has(s??``))continue;let l=n,u=null;for(let[e,t]of c.entries()){let n=/^(?:-R|--repo)(?:=(.*))?$/.exec(t);if(n){let t=n[1]??c[e+1];t&&(l=gl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||hl.test(t))&&(u=t)}if(!u)continue;let d=hl.exec(u);d?i(al(`issue`,`${d[1]}#${d[2]}`)):l&&i(al(`issue`,`${l}#${u.replace(`#`,``)}`))}return r}const ml=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),hl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/issues\/(\d+)/,gl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function _l(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function vl(e){if(e.hook_event_name!==`PostToolUse`||e.tool_name!==`Bash`||typeof e.tool_input?.command!=`string`)return null;let t=e.tool_response?.stdout;return{command:e.tool_input.command,stdout:typeof t==`string`?t:``}}function yl(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 bl(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||!xc.test(l))return null;c===`end`&&t.reason===`clear`&&await Dl(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(al(`repository`,i.repository)),i.branch&&!await Pc(r,i.branch)&&d(al(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=yl(t);if(p&&f)for(let e of fl(p,i.repository))d(e);let m=vl(t);if(m&&f)for(let e of pl(m.command,m.stdout,i.repository))d(e);if(c===`start`){let e=a.AGENT_KIT_FROM?.trim();if(e&&f)for(let t of e.split(/\s+/))d(ol(t));if(t.source===`clear`){let e=await Ol(r,l,o,s);e&&d(al(`session`,e))}}let h=await Cl(l),g=u.map(e=>`${e.kind} ${e.value}`),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await Tl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await kl(o),{sessionId:l,agent:e,machineId:await ya(),machineName:fa(),type:c,occurredAt:o.toISOString(),links:u})}const xl=(e,t=[])=>pa(ll(),e,t),Sl=e=>h(cl(),`${ul(e)}.json`);async function Cl(e){try{let t=JSON.parse(await O(Sl(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[]}}catch{return{sentAt:0,links:[]}}}const wl=async e=>(await Cl(e)).links;async function Tl(e,t){await D(cl(),{recursive:!0,mode:448}),await k(Sl(e),JSON.stringify(t)+`
292
+ `)}const El=e=>h(cl(),`cleared-${ul(e)}.json`);async function Dl(e,t,n){await D(cl(),{recursive:!0,mode:448}),await k(El(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
293
+ `)}async function Ol(e,t,n,r){let i=El(e),a=Date.now()+r;for(;;){try{let e=JSON.parse(await O(i,`utf8`));if(typeof e.sessionId==`string`&&e.sessionId!==t&&typeof e.at==`number`&&Math.abs(n.getTime()-e.at)<=3e4)return await le(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Ce(100)}}async function kl(e){try{for(let t of await oe(cl())){let n=h(cl(),t),{mtimeMs:r}=await ue(n);e.getTime()-r>6048e5&&await le(n,{force:!0})}}catch{}}function Al(e,t=()=>Date.now()){return{async of(n){let r=await e();if(!r)return`unknown`;let i=n.projectLock?await X(n.projectLock):null,a=await X(Y(`global`)),o=[i,a].flatMap(e=>Object.values(e?.skills??{}).map(e=>e.id)),s=t(),c=e=>s-(Date.parse(e)||0)<3e5,l=e=>!!e&&c(e.checkedAt),u=await ss(r.userId),d=!u||n.repository!==null&&!Object.hasOwn(u.repositories,n.repository)||o.some(e=>!Object.hasOwn(u.skills,e));return d&&!l(u)&&!(u&&c(u.triedAt))&&(u=await us(r.api,r.userId,u,new Date(s))??u),(u&&jl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function jl(e,t,n,r){let{repository:i}=e,a=i&&Object.hasOwn(r.repositories,i)?r.repositories[i]:null;if(!a){let e=/* @__PURE__ */ new Map;for(let{id:n}of Object.values(t?.skills??{})){let t=r.skills[n];t&&e.set(t,(e.get(t)??0)+1)}a=[...e.entries()].sort(([e,t],[n,r])=>r-t||e.localeCompare(n))[0]?.[0]??null}if(!a)return null;let o={};for(let i of[t,n])for(let[t,n]of Object.entries(i?.skills??{}))!Object.hasOwn(o,t)&&n.agents.includes(e.agent)&&r.skills[n.id]===a&&(o[t]=n.id);return{organizationId:a,skillIds:o}}const Ml={"claude_code.token.usage":{input:$c.inputTokens,output:$c.outputTokens,cacheRead:$c.cacheReadTokens,cacheCreation:$c.cacheCreationTokens},"claude_code.cost.usage":$c.costUsd,"claude_code.active_time.total":{user:$c.personSeconds,cli:$c.agentSeconds},"claude_code.commit.count":$c.commits,"claude_code.pull_request.count":$c.pullRequests};function Nl(e){let t=[];for(let n of Ll(Q(e,`resourceMetrics`)))for(let e of Ll(Q(n,`scopeMetrics`)))for(let n of Ll(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?Ml[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of Ll(Q(i,`dataPoints`))){let i=Ll(Q(n,`attributes`)),o=e=>Rl(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=zl(Q(n,`asDouble`)??Q(n,`asInt`)),u=Bl(Q(n,`startTimeUnixNano`)),d=Bl(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Fl(e,i,a?u:null),metric:c,model:Il(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Pl(e){let t=[];for(let n of Ll(Q(e,`resourceLogs`)))for(let e of Ll(Q(n,`scopeLogs`)))for(let n of Ll(Q(e,`logRecords`))){let e=Ll(Q(n,`attributes`)),r=Rl(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Rl(e,`session.id`),a=Bl(Q(n,`timeUnixNano`))??Bl(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Fl(e,t,n){let r=t.filter(e=>typeof e.key==`string`).map(e=>[e.key,JSON.stringify(e.value??null)]).sort(([e],[t])=>e<t?-1:+(e>t));return pe(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const Il=e=>el(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Ll=e=>Array.isArray(e)?e:[];function Rl(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function zl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Bl(e){try{if(typeof e==`string`&&/^\d+$/.test(e))return Number(BigInt(e)/1000000n);if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e/1e6)}catch{}return null}const Vl=e=>pe(`sha256`).update(e).digest(`hex`).slice(0,32);function Hl(e){let t=()=>h(ro(),e),n=e=>h(t(),`${Vl(e)}.json`),r=async e=>JSON.parse(await O(e,`utf8`));return{async read(e){try{return await r(n(e))}catch{return null}},async write(e,r){await D(t(),{recursive:!0,mode:448}),await k(n(e),JSON.stringify(r)+`
294
+ `)},async list(){let e=[];try{e=await oe(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(h(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await oe(t())){let r=h(t(),n);e-(await ue(r)).mtimeMs>6048e5&&await le(r,{force:!0})}}catch{}}}}const Ul=Hl(`sessions`),Wl=e=>Ul.write(e.sessionId,e);async function Gl(e){let t=await Ul.read(e);return t?.sessionId===e?t:null}const Kl=(e=Date.now())=>Ul.forgetOld(e),ql=Hl(`sent`),Jl=(e,t,n=/* @__PURE__ */ new Date)=>ql.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Yl=e=>ql.read(e),Xl=async()=>(await ql.list()).sort((e,t)=>t.at.localeCompare(e.at)),Zl=(e=Date.now())=>ql.forgetOld(e),Ql=(e,t)=>({sessionId:e,epoch:t,series:{},prompts:0,lastAt:t});function $l(e,t){if(t.kind===`prompt`)return e.prompts++,e.lastAt=Math.max(e.lastAt,t.at),!0;let{series:n,metric:r,model:i,skillName:a,value:o,at:s}=t,c=e.series[n];if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;e.series[n]={metric:r,model:i,skillName:a,start:t.start,value:o,at:s}}else{if(o===0)return!1;e.series[n]={metric:r,model:i,skillName:a,start:e.epoch,value:(c?.value??0)+o,at:Math.max(c?.at??0,s)}}return e.lastAt=Math.max(e.lastAt,s),!0}function eu(e,t){let n=/* @__PURE__ */ new Map,r=e=>{let t=JSON.stringify([e.metric,e.model,e.skillId,e.start]),r=n.get(t);r?r.value+=e.value:n.set(t,e)};for(let n of Object.values(e.series))r({metric:n.metric,model:n.model,skillId:n.skillName!==null&&Object.hasOwn(t.skillIds,n.skillName)?t.skillIds[n.skillName]:null,start:new Date(n.start).toISOString(),value:n.value});return e.prompts>0&&r({metric:$c.prompts,model:null,skillId:null,start:new Date(e.epoch).toISOString(),value:e.prompts}),{sessionId:e.sessionId,agent:t.agent,machineId:t.machineId,machineName:t.machineName,organizationId:t.organizationId,occurredAt:new Date(e.lastAt).toISOString(),usage:[...n.values()].map((e,t)=>({entry:e,i:t})).sort((e,t)=>Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,Qc.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const tu=Hl(`state`);function nu(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=ru(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);$l(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await tu.list())e.unsent&&await n(e.sessionId)},async dirty(){return(await Promise.all(t.values())).filter(e=>e.state.unsent)},handed(e){e.state.unsent=!1,e.unsaved=!0},async save(){for(let e of await Promise.all(t.values()))e.unsaved&&(e.unsaved=!1,await tu.write(e.state.sessionId,e.state))}}}async function ru(e,t){let n=await tu.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Ql(e,t),unsaved:!1}}const iu=(e=Date.now())=>tu.forgetOld(e),au=16777216,ou=()=>h(H(),`pending-session-usage.jsonl`);async function su(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=nu(),s=Al(e.login),c=Buffer.from(e.secret),l=Promise.resolve(),u=e=>l=l.then(e).then(()=>{},()=>{}),d=t=>async n=>{let r=(await e.login())?.api;if(!r)throw new R(0,`LOGGED_OUT`,`Not logged in.`);await t(r,n,AbortSignal.timeout(1e4))},f=d(async(e,t,n)=>{try{await e.reportSessionUsage(t,n)}catch(e){if(!ha(e))for(let e of t)await Jl(e,`refused`);throw e}for(let e of t)await Jl(e,`sent`)}),p=(e=[])=>pa(ou(),f,e,{batch:Qc.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await Gl(t.state.sessionId);if(!r){Date.now()-t.state.epoch>n&&o.handed(t);continue}let i=await s.of(r);if(i===`unknown`||(o.handed(t),!i))continue;let a=eu(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await ya(),machineName:fa(),skillIds:i.skillIds});a.usage.length!==0&&(await Jl(a,`waiting`),e.push(a))}await o.save(),e.length>0&&await p(e)}let h=d((e,t,n)=>e.reportActivations(t,n)),g=d((e,t,n)=>e.reportSessionEvents(t,n)),_=()=>Promise.all([p(),Sa(h),xl(g)]);function v(e){let t=du(e.activations),n=du(e.sessionEvents);return u(()=>Promise.all([t.length>0&&Sa(h,t),n.length>0&&xl(g,n)]))}let y=null,b=()=>{y??=setTimeout(()=>{y=null,u(()=>o.save())},1e3)};async function x(t,n){if(ee(),!S(t.headers[`x-agent-kit-collector`]))return t.resume(),uu(n,401,{message:`Not this collector's secret.`});let r=new URL(t.url??`/`,`http://collector`),i=r.pathname;if(t.method===`GET`&&i===`/health`)return uu(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),uu(n,404,{});if(i===`/stop`){t.resume(),uu(n,200,{}),oe({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),uu(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),uu(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),uu(n,415,{message:`Send JSON.`});let a=await lu(t);if(!a.ok)return uu(n,a.status,{});i===`/report`?(uu(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?Nl(a.json):Pl(a.json)),b(),uu(n,200,{}))}let S=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ge(t,c)},C=xe((e,t)=>{x(e,t).catch(()=>{t.headersSent||uu(t,500,{})})});if(!await new Promise(t=>{C.once(`error`,()=>t(!1)),C.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let w=null,T=Date.now(),E=e=>{w&&clearTimeout(w),w=setTimeout(()=>void te(),e)};function ee(){T=Date.now(),E(i)}async function te(){let e=T,t=!1;if(await u(async()=>{let e=[ou(),xa(),ll()];t=(await Promise.all(e.map(ma))).some(Boolean)||(await o.dirty()).length>0}),O||T!==e)return;let n=Date.now()-T;t&&n<a?E(Math.max(1,Math.min(i,a-n))):oe()}ee();let ne=setInterval(()=>void u(m),t),re=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await Kl(e),await iu(e),await Zl(e),await o.resume()});let ie=()=>u(m).then(()=>u(_)),D=()=>{},ae=new Promise(e=>D=e),O=null;function oe({send:e=!0}={}){return O??=(async()=>{w&&clearTimeout(w),y&&clearTimeout(y),clearInterval(ne),clearInterval(re);let t=new Promise(e=>C.close(()=>e()));C.closeIdleConnections(),await(e?ie():u(()=>o.save())),C.closeAllConnections(),await t,D()})(),O}return{port:C.address().port,flush:ie,stop:oe,stopped:ae}}const cu=n(Se);async function lu(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>au)return e.resume(),{ok:!1,status:413};t.push(r)}let r=Buffer.concat(t);try{return/gzip/i.test(e.headers[`content-encoding`]??``)&&(r=await cu(r,{maxOutputLength:au})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function uu(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const du=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function fu(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await oo();await(await su({port:t,secret:n,apiUrl:V(),login:async()=>{let e=await U();return e?{api:z(V(),e.token),userId:e.user.id}:null}}))?.stopped}const pu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,mu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function hu(e){let t=0;for(let[n]of e.matchAll(mu)){let e=n[0];if(e===`
295
+ `)t+=1;else if(/\s/.test(e))t+=n.length===1?0:Math.ceil(n.length/4);else if(/\p{L}/u.test(e)){let e=0;for(let t of n)pu.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 gu(e){return{always:e.description,max:e.description+e.body+e.files}}function _u(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=gu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function vu(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${bu((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${bu((e/1e6).toFixed(1))}M`}const yu=(e,t)=>`${t===`estimate`?`~`:``}${vu(e)}`,bu=e=>e.replace(/\.0$/,``),xu={high:15,medium:10,low:5},Su=5e3,Cu=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function wu(e){let t=er(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&Cu.has(n)}const Tu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Eu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Du(e,t){let n=t(`SKILL.md`)??``,r=yi(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)wu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of zu(r)){let t=tr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Bu(r,n,t.path)&&(d.add(t.path),wu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!Tu.test(er(e))).filter(e=>!er(e).startsWith(`.`)).sort();return{v:1,description:typeof a==`string`&&a.trim()!==``?a.trim():null,hasWhenToUse:typeof o==`string`&&o.trim()!==``,bodyLines:c===``?0:c.split(`
296
+ `).length,bodyTokens:hu(c),hasExamples:Ku(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Ou(e,t,n=/* @__PURE__ */ new Date){let r=[...Iu(e),...t?Lu(t,n):[]];return{score:ku(r),checks:ju(r)}}function ku(e){let t=e.reduce((e,t)=>e+xu[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+xu[t.severity],0);return Math.round(n/t*100)}const Au=[`high`,`medium`,`low`];function ju(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Au.indexOf(e.severity)-Au.indexOf(t.severity)))}const Mu=(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}),Nu=/\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,Pu=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Fu=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Iu(e){let t=[],n=e.description??``;e.hasWhenToUse||Nu.test(n)?t.push(Mu(`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(Pu);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(Mu(`description-specific`,`medium`,`description is specific`)),Fu.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(Mu(`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(Mu(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Ru(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>Su?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Ru(Su)}; move reference material into files ${G} links to.`)):t.push(Mu(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Mu(`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(Mu(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${qu(e.missingFiles.length,`missing file`)}: ${Ju(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Mu(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${qu(e.unusedFiles.length,`file`)} nothing mentions: ${Ju(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function Lu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Mu(`eval-cases`,`high`,qu(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${qu(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Mu(`eval-negative`,`medium`,`${qu(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(Mu(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${qu(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 Ru(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function zu(e){let t=[];for(let n of e.matchAll(Eu)){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 Bu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,er(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Vu(t,n);return a&&r.add(a),[...r].some(t=>Hu(e,t))}function Vu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Hu(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 Uu=/^(```|~~~)/m,Wu=/^#{1,6}[^\n]*\bexamples?\b/im,Gu=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Ku(e){return Uu.test(e)||Wu.test(e)||Gu.test(e)}function qu(e,t){return`${e} ${t}${e===1?``:`s`}`}function Ju(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Yu=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Xu(e){try{return(await ue(h(e,G))).isFile()}catch{return!1}}async function Zu(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await oe(i,{withFileTypes:!0})){let o=h(i,a.name);if(a.isDirectory()){Yu.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=_(e,o).split(y).join(`/`),{size:c}=await ue(o);t.push({path:s,size:c}),(s===`SKILL.md`||wu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Ou(Du(t,e=>n.get(e)),null)}function Qu(e){let t=[`HEALTH ${e.score}/100`];for(let n of e.checks)n.passed?t.push(`✓ ${n.message}`):(t.push(`■ ${n.message} [${n.severity}]`),n.fix&&t.push(` ${n.fix}`));return t.join(`
297
+ `)}async function $u(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=v(t??`.`);if(await Xu(n)){let e=await Zu(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(Qu(e));return}if(t===void 0)throw Error("There's no SKILL.md here. Name one of your skills, like `a-kit health pdf-forms`, or a skill's folder.");let{api:r}=await $a(),i=wn(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(`${An(a)} v${a.version}`),console.log(Qu(o))}async function ed(e){Ht(`agent kit`);let t=await Qa();t?F.success(`Logged in as ${eo(t.user)}`):t=await Za();let n=z(V(),t.token),r=await n.listSkills();if(r.length===0){I(to(t.webUrl));return}let i=!e.yes;if(i&&!gn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await vn(e.global,i),o=await _n(e.agent,i),s=i?B(await Bt({message:`Which skills?`,options:r.map(e=>({value:e.id,label:An(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await Ho(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 td(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Ja();return;case`on`:{if(await Ln({heartbeat:!0}),!await U()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!sa()){F.warn(`Run it from the published CLI to install the timer.`);return}await Ya();let e=await Ha(V()),t=(await qa())?.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 Ln({heartbeat:!1}),await Va(V()),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 In()).heartbeat!==!1,t=await Ha(V()),n=await qa();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?La(V()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
298
+ Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const nd=2e3;async function rd(e,t={},n=300){let{port:r,secret:i}=await oo();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[no]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function id(){let e=await rd(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function ad(e,t,n=Go){let r=await id();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await sd(),u(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function od(e){return(await rd(`/report`,{method:`POST`,body:JSON.stringify(e)},nd))?.status===202}async function sd({send:e=!0}={}){return(await rd(e?`/stop`:`/stop?send=false`,{method:`POST`},nd))?.ok??!1}const cd=5e3;async function ld(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 fd()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await Qo(sa()??oa()),await Ha(V())||await Ja();return}if(Rn()||(await In()).telemetry===!1)return;let o=await U();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await ss(o.user.id),u=c?{...kc,sessionId:Ac(r.session_id)}:await jc(r.session_id,s,void 0,l),d=z(V(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await dd(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await ad(sa()??oa(),V());let p=await bl(e,r,a,s,u,{now:i}),m=Oo(r),h=m&&await _a(m.name,e,s),g=m&&h&&await ba(h,e,m.trigger,Mc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&ls(l,i,h?h.id:null)&&us(d,o.user.id,l,i),(p||g)&&ud(d,p,g)])}catch{}}async function ud(e,t,n){await od({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&xl(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(cd))},t),n&&Sa(async t=>{await e.reportActivations(t,AbortSignal.timeout(cd))},n)])}async function dd(e,t,n){let{repository:r,branch:i}=await Nc(n),a=va(n,x());(r||a)&&await Wl({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function fd(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function pd(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Ht(`agent kit`);let n=v(e[0]);if(!u(h(n,`SKILL.md`)))throw Error(`${W(n)} has no ${G}, so it isn't a skill.`);let r=f(n);if(!/^[a-z0-9-]+$/.test(r)||r===`report-session-issue`)throw Error(`"${r}" can't be a skill's folder name.`);let i=t.global?`global`:`project`,a=await _n(t.agent,!t.yes),o=on(a,i),s=o.map(e=>h(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(u(e)&&!await qn(e)&&!c)throw Error(`${W(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Kn(z(V(),(await U())?.token),r,c,o);if(e&&!await qn(e.folder))throw Error(`${W(e.folder)} has edits that aren't in agent kit (${Wn(e.paths)}). Copy them to ${W(n)} and delete them there first.`)}for(let e of s)await Yn(e,n);F.success(`${r}: ${s.map(W).join(`, `)} → ${W(n)}`);let l=i===`project`?await md(on(a,`global`),r,n):[];l.length>0&&F.warn(`You also have ${r} in ${l.map(W).join(`, `)}, and your agents use that copy over this project's. Run ${L(`link ${e[0]} -g`)} to try yours everywhere instead.`),await hd(n,r,c!==void 0),I(`${l.length>0?`This project's agents would use`:`Your agents use`} ${W(n)} as it is, edits included (a new session sees an edit an open one missed). ${L(`add ${r}`)} goes back to agent kit's version.`)}async function md(e,t,n){let r=[];for(let i of e){let e=h(i,t);u(e)&&await qn(e)!==n&&r.push(e)}return r}async function hd(e,t,n){let r;try{r=zc(e)}catch{return}if(v(r,`skills`,t)!==e)return;let{scan:i,place:a}=await Jc(r,await Vc(r),{roles:!1}),o=a?.placement.skills.get(t);n&&o!==void 0&&F.warn(`The ${t} you installed from agent kit is ${o}'s, a different skill: this link takes its place, so your agents use ${W(e)} instead. ${L(`add ${t}`)} puts ${o}'s back.`);let s=Xc(i.problems,[t]);s.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...vs(s)].join(`
299
+ `))}function gd(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?yu(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[An(e),_d(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[vd(`project`,r,e),vd(`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=_u(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}${vu(c.always)} always · ${l}${vu(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 _d(e){return[`v${e.version}`,...Yt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function vd(e,t,n){if(!t)return null;let r=qi(t),{version:i}=$t(n.channels,n.version,r),a=`in ${e}${r===`latest`?``:` on ${r}`}`;return t.version===i?a:`${a} at v${t.version}, run a-kit update${e===`global`?` -g`:``}`}async function yd(){let{api:e,credentials:t}=await $a(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(to(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of gd(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>bd(e).length));for(let e of r){let t=[xd(i,e)&&`in project`,xd(a,e)&&`in global`].filter(Boolean);console.log(`${bd(e).padEnd(o)} ${Sd(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const bd=e=>`${yn}${An(e)}`,xd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function Sd(e){let t=e.skills.length;if(t===0)return`no skills`;let n=e.skills.slice(0,3).map(e=>e.name);return`${t} skill${t===1?``:`s`}: ${n.join(`, `)}${t>3?`, …`:``}`}const Cd=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${L(`heartbeat status`)}).`;async function wd(e,t){switch(e){case`name`:{let{api:e}=await $a(),n=await ya();if(t===void 0){let t=await Td(e.machineName(n));if(!t)throw Error(Cd);console.log(t.name?`This machine is "${t.name}" on the Machines page (its hostname is ${t.hostname}).`:`This machine goes by its hostname, "${t.hostname}", on the Machines page. Name it with ${L(`machine name <name>`)}.`);return}let r=await Td(e.nameMachine(n,t))??(await Ja()?await Td(e.nameMachine(n,t)):null);if(!r)throw Error(Cd);F.success(r.name?`This machine is "${r.name}" on the Machines page.`:`This machine goes by its hostname, "${r.hostname}", on the Machines page.`);return}default:throw Error(`Unknown machine action "${e??``}". Use ${L(`machine name [<name>]`)}.`)}}async function Td(e){try{return await e}catch(e){if(e instanceof R&&e.status===404)return null;throw e}}async function Ed(e,t){switch(e){case void 0:case`status`:{let e=(await qa())?.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 $a(),r=await Aa(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await In()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Ja()?F.success(`This machine now shows up on ${r.name}'s Machines page.`):F.warn(`This machine goes to ${r.name}; it shows up there with its next heartbeat.`);return}default:throw Error(`Unknown org action "${e}". Use status or use.`)}}async function Dd(){Ht(`agent kit`);let e=await Qa().catch(()=>null);if(e){let t=eo(e.user);if(!gn()){I(`Already logged in as ${t}.`);return}if(!B(await Lt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await Za();e&&await z(V(),e.token).logout().catch(()=>{}),I(await Ad(t.token,t.webUrl))}async function Od(e=process.stdin){Ht(`agent kit`);let t=await kd(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(V(),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 U();await Pn({token:t,user:n,webUrl:jn(V())}),r&&r.token!==t&&await z(V(),r.token).logout().catch(()=>{}),await Ya(),I(`Logged in as ${eo(n)}.`)}async function kd(e){if(e.isTTY)return B(await Ut({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function Ad(e,t){return(await z(V(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${to(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function jd(){let e=await U();e?(await z(V(),e.token).logout().catch(()=>{}),await Pn(null),console.log(`Logged out ${eo(e.user)}.`)):console.log(`You're not logged in.`)}async function Md(){let e=await Qa();e?console.log(eo(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Nd=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Pd(e){let t=await Fd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${mn()} ${e}\` is gone: skills are changed in your organization's GitHub repository now, and merging a pull request there makes the new version.`,` 1. ${n}`,` 2. Change skills/<skill>/ and check it: ${L(`check <skill>`)}`,` 3. Try it in your agent: ${L(`link <clone>/skills/<skill>`)}`,e===`propose`?` 4. Commit it on a branch and open a pull request; that's the proposal, reviewed on GitHub.`:` 4. Commit it on a branch and open a pull request.`];throw e===`pull`&&r.push(`To get a skill's latest version instead, ${L(`add <skill>`)} or ${L(`update`)}.`),Error(r.join(`
300
+ `))}async function Fd(){let e=(await U())?.token;if(!e)return[];let t=z(V(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Id={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},Ld=[{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}],Rd=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,zd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Bd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Vd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Hd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Ud(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(Hd(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}_])${Hd(e.find)}(?![\\p{L}\\p{N}_])`:Hd(e.find),`giu`)}));function a(e){let t=e;for(let e of Ld)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(Rd,e=>Vd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(zd,e=>Bd.has(e)?e:(n(`ip`),`192.0.2.1`)),t}function o(t){let r=e.maxToolText;return r===null||t.length<=r?t:(n(`cut`),`${t.slice(0,r)}\n… [${t.length-r} more characters left out by a-kit report]`)}function s(e){return typeof e==`string`?o(a(e)):Array.isArray(e)?e.map(s):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,s(t)])):e}function c(e){return e.type===`text`?{...e,text:a(e.text)}:e.type===`tool_use`?{...e,input:s(e.input)}:{...e,content:o(a(e.content))}}function l(e){return e.map(e=>e.type===`system`?e:{...e,message:{content:e.message.content.map(c)}})}return{text:a,events:l,counts:t}}const Wd=e=>e.map(e=>JSON.stringify(e)).join(`
301
301
  `)+`
302
- `;function Wd(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
303
- `)){if(!a.trim())continue;let e;try{e=JSON.parse(a)}catch{continue}if(e.type!==`user`&&e.type!==`assistant`||e.isSidechain||e.isMeta)continue;r=e.version??r,i=e.cwd??i,e.type===`assistant`&&e.message?.model&&(e.message.model.startsWith(`<`)||(n=e.message.model));let o=Gd(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(Li))]}}function Gd(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:Kd(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function Kd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>e.type===`text`&&typeof e.text==`string`?e.text:e.type===`image`?`[image]`:``).filter(Boolean).join(`
304
- `):``}const qd=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function Jd(e){let t=[],n=null,r=null,i=null,a=(e,n)=>t.push({type:e,message:{content:[n]}});for(let t of e.split(`
305
- `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=Xd(o.cli_version)??r,i=Xd(o.cwd)??i;else if(e.type===`turn_context`)n=Xd(o.model)??n,i=Xd(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=Zd(o.content);if(!t.trim()||e===`user`&&qd.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`?Qd(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:$d(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(Li))]}}function Yd(e){try{let t=JSON.parse(e);return t.type===`session_meta`?Xd(t.payload?.cwd):null}catch{return null}}const Xd=e=>typeof e==`string`&&e?e:null;function Zd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
306
- `):``}function Qd(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function $d(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 Zd(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return $d(t)}return JSON.stringify(e??``)}const ef=()=>process.env.CLAUDE_CONFIG_DIR??h(x(),`.claude`),tf=()=>process.env.CODEX_HOME??h(x(),`.codex`),nf=(e,t=ef())=>h(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function rf(e,t,n=process.cwd()){if(t&&u(t))return v(t);let r=e===`claude-code`?await sf(t,n):await cf(t,n);if(r)return r.file;throw Error(t?`No ${of(e)} session "${t}" on this machine.`:`No ${of(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function af(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([sf(void 0,e),cf(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 of=e=>e===`claude-code`?`Claude Code`:`Codex`;async function sf(e,t){if(e){let t=h(ef(),`projects`),n=await pf(t);for(let r of n){let n=h(t,r,`${e}.jsonl`);if(u(n))return{file:n,mtime:0}}return null}for(let e of mf(t)){let t=nf(e),n=(await pf(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return ff(n.map(e=>h(t,e)))}return null}async function cf(e,t){let n=h(tf(),`sessions`),r=[],i=0;outer:for(let e of lf(await pf(n)))for(let t of lf(await pf(h(n,e))))for(let a of lf(await pf(h(n,e,t)))){let o=h(n,e,t,a);for(let e of await pf(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(h(o,e));if(r.length>=300||++i>=14)break outer}return uf(r,e,t)}const lf=e=>e.sort().reverse();async function uf(e,t,n){if(t){let n=e.find(e=>f(e).includes(t));return n?{file:n,mtime:0}:null}let r=mf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await df(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 ff(t)}return null}async function df(e){let t=await ae(e,`r`);try{let e=Buffer.alloc(262144),{bytesRead:n}=await t.read(e,0,e.length,0),r=e.subarray(0,n).toString(`utf8`),i=r.indexOf(`
307
- `);return Yd(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function ff(e){let t=null;for(let n of e){let{mtimeMs:e}=await ue(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function pf(e){try{return await oe(e)}catch{return[]}}function mf(e){let t=[v(e)];for(;m(t.at(-1))!==t.at(-1);)t.push(m(t.at(-1)));return t}const hf=2e3;function gf(e){let t=[...e.map],n=yf(()=>T().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=yf(()=>S());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=_f();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=yf(()=>ve(`git`,[`rev-parse`,`--show-toplevel`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim());return{replacements:t,paths:[...[...new Set([...e.cwds,a].filter(Boolean))].map(e=>({path:e,as:`<repo>`})),{path:x(),as:`~`}],maxToolText:e.fullOutputs?null:hf}}function _f(){return yf(()=>ve(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function vf(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 yf(e){try{return e()}catch{return null}}function bf(e,t,n){let r=new Set(t),i=/* @__PURE__ */ new Map;for(let t of n)for(let[n,a]of Object.entries(t.skills))Sf(a.agents,e)&&(i.has(n)||i.set(n,{name:n,skillId:a.id,version:a.version,triggered:r.has(n)}));for(let e of t)e===`report-session-issue`||i.has(e)||i.set(e,{name:e,skillId:null,version:null,triggered:!0});return i.delete(ji),[...i.values()]}const xf=[`codex`,`cursor`,`gemini-cli`],Sf=(e,t)=>e.length===0||e.includes(t)||xf.includes(t)&&e.some(e=>xf.includes(e));async function Cf(e){Ht(`agent kit report`);let t=await wf(e.agent[0]),n=await rf(t,e.session||void 0),r=await O(n,`utf8`),i=Fi(t===`claude-code`?Wd(r):Jd(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Hd(gf({map:e.map?vf(await Tf(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Df(e.title,`--title`,`a short title`)),s=a.text(Df(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=Ud(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=bf(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=h(w(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${of(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${kf(d)}`,`Taken out: ${Af(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
308
- `)),Buffer.byteLength(l)>Fd.maxTranscriptBytes)throw Error(`The transcript is over ${Fd.maxTranscriptBytes/1024/1024} MB.${e.fullOutputs?` Leave out --full-outputs.`:``}`);if(e.dryRun){I(`Nothing was sent. Check the file above, then run it again without --dry-run.`);return}if(!e.yes){if(!gn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!B(await Lt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:g}=await $a(),[_,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=Of(e.org,_,v,d),b=await m.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function wf(e){if(e===void 0)return af();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 Tf=e=>e===`-`?Ef():O(e,`utf8`);async function Ef(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Df(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function Of(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 kf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Af(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${hf} characters`:`${e} ×${t}`).join(`, `)}function jf(e){return e&&e.total>0?e.passed/e.total:null}async function Mf(e){let{api:t,credentials:n}=await $a(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Nf(r,n.webUrl,i.length>1))}function Nf({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=>An({...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=jf(t.withSkill),s=o===null?`—`:`${Math.round(o*100)}%`;i.push(` ${e[a].padEnd(r)} ${s.padStart(4)} ${t.status.padEnd(9)} ${n}/app/skills/${t.skillId}?tab=runs&run=${t.id}`)})}return i.join(`
309
- `)}const Pf={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function Ff(e,t,{port:n}={}){switch(e){case`on`:{n!==void 0&&await so(Number(n)),await Ln({telemetry:!0});let e=await jo();if(e.status===`skipped`){F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}F.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&F.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await Ln({telemetry:!1}),await jo(),await od({send:!1}),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return Lf(t);case void 0:case`status`:{let e=await In(),t=(await Po()).includes(`telemetry`),n=e.telemetry===!1?`off`:Rn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await oo(),i=await rd(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${Pf[await No()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status or show.`)}}const If={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Lf(e){if(e){let t=await Jl(e);if(!t)throw Error(`Nothing was sent for session ${e}.`);console.log(JSON.stringify(t.record,null,2));return}let t=await Yl();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${If[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function Rf(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 Uf();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Hf(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await $a(),c=wn(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)=>zf(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;Vf(await d(!0,e=>{m||u(`With ${An(l)} v${a??l.version}`),m=!0,Bf(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Bf(e,l.name);Vf(h)}async function zf(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 Bf(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 Vf(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=fn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${un(e.usage)}`)}function Hf(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 Uf(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Wf=`a-kit ${en}: your agent kit skills, in your agents.
302
+ `;function Gd(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
303
+ `)){if(!a.trim())continue;let e;try{e=JSON.parse(a)}catch{continue}if(e.type!==`user`&&e.type!==`assistant`||e.isSidechain||e.isMeta)continue;r=e.version??r,i=e.cwd??i,e.type===`assistant`&&e.message?.model&&(e.message.model.startsWith(`<`)||(n=e.message.model));let o=Kd(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(Li))]}}function Kd(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:qd(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function qd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>e.type===`text`&&typeof e.text==`string`?e.text:e.type===`image`?`[image]`:``).filter(Boolean).join(`
304
+ `):``}const Jd=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function Yd(e){let t=[],n=null,r=null,i=null,a=(e,n)=>t.push({type:e,message:{content:[n]}});for(let t of e.split(`
305
+ `)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=Zd(o.cli_version)??r,i=Zd(o.cwd)??i;else if(e.type===`turn_context`)n=Zd(o.model)??n,i=Zd(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=Qd(o.content);if(!t.trim()||e===`user`&&Jd.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`?$d(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:ef(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(Li))]}}function Xd(e){try{let t=JSON.parse(e);return t.type===`session_meta`?Zd(t.payload?.cwd):null}catch{return null}}const Zd=e=>typeof e==`string`&&e?e:null;function Qd(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
306
+ `):``}function $d(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function ef(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 Qd(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return ef(t)}return JSON.stringify(e??``)}const tf=()=>process.env.CLAUDE_CONFIG_DIR??h(x(),`.claude`),nf=()=>process.env.CODEX_HOME??h(x(),`.codex`),rf=(e,t=tf())=>h(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function af(e,t,n=process.cwd()){if(t&&u(t))return v(t);let r=e===`claude-code`?await cf(t,n):await lf(t,n);if(r)return r.file;throw Error(t?`No ${sf(e)} session "${t}" on this machine.`:`No ${sf(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function of(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([cf(void 0,e),lf(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 sf=e=>e===`claude-code`?`Claude Code`:`Codex`;async function cf(e,t){if(e){let t=h(tf(),`projects`),n=await mf(t);for(let r of n){let n=h(t,r,`${e}.jsonl`);if(u(n))return{file:n,mtime:0}}return null}for(let e of hf(t)){let t=rf(e),n=(await mf(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return pf(n.map(e=>h(t,e)))}return null}async function lf(e,t){let n=h(nf(),`sessions`),r=[],i=0;outer:for(let e of uf(await mf(n)))for(let t of uf(await mf(h(n,e))))for(let a of uf(await mf(h(n,e,t)))){let o=h(n,e,t,a);for(let e of await mf(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(h(o,e));if(r.length>=300||++i>=14)break outer}return df(r,e,t)}const uf=e=>e.sort().reverse();async function df(e,t,n){if(t){let n=e.find(e=>f(e).includes(t));return n?{file:n,mtime:0}:null}let r=hf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await ff(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 pf(t)}return null}async function ff(e){let t=await ae(e,`r`);try{let e=Buffer.alloc(262144),{bytesRead:n}=await t.read(e,0,e.length,0),r=e.subarray(0,n).toString(`utf8`),i=r.indexOf(`
307
+ `);return Xd(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function pf(e){let t=null;for(let n of e){let{mtimeMs:e}=await ue(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function mf(e){try{return await oe(e)}catch{return[]}}function hf(e){let t=[v(e)];for(;m(t.at(-1))!==t.at(-1);)t.push(m(t.at(-1)));return t}const gf=2e3;function _f(e){let t=[...e.map],n=bf(()=>T().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=bf(()=>S());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=vf();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=bf(()=>ve(`git`,[`rev-parse`,`--show-toplevel`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim());return{replacements:t,paths:[...[...new Set([...e.cwds,a].filter(Boolean))].map(e=>({path:e,as:`<repo>`})),{path:x(),as:`~`}],maxToolText:e.fullOutputs?null:gf}}function vf(){return bf(()=>ve(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function yf(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 bf(e){try{return e()}catch{return null}}function xf(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))Cf(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(ji),[...i.values()]}const Sf=[`codex`,`cursor`,`gemini-cli`],Cf=(e,t)=>e.length===0||e.includes(t)||Sf.includes(t)&&e.some(e=>Sf.includes(e));async function wf(e){Ht(`agent kit report`);let t=await Tf(e.agent[0]),n=await af(t,e.session||void 0),r=await O(n,`utf8`),i=Fi(t===`claude-code`?Gd(r):Yd(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=Ud(_f({map:e.map?yf(await Ef(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Of(e.title,`--title`,`a short title`)),s=a.text(Of(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=Wd(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=xf(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=h(w(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${sf(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${Af(d)}`,`Taken out: ${jf(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
308
+ `)),Buffer.byteLength(l)>Id.maxTranscriptBytes)throw Error(`The transcript is over ${Id.maxTranscriptBytes/1024/1024} MB.${e.fullOutputs?` Leave out --full-outputs.`:``}`);if(e.dryRun){I(`Nothing was sent. Check the file above, then run it again without --dry-run.`);return}if(!e.yes){if(!gn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!B(await Lt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:g}=await $a(),[_,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=kf(e.org,_,v,d),b=await m.createReport(y.id,f);I(`Reported: ${g.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function Tf(e){if(e===void 0)return of();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 Ef=e=>e===`-`?Df():O(e,`utf8`);async function Df(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Of(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function kf(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 Af(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function jf(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${gf} characters`:`${e} ×${t}`).join(`, `)}function Mf(e){return e&&e.total>0?e.passed/e.total:null}async function Nf(e){let{api:t,credentials:n}=await $a(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Pf(r,n.webUrl,i.length>1))}function Pf({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=>An({...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=Mf(t.withSkill),s=o===null?`—`:`${Math.round(o*100)}%`;i.push(` ${e[a].padEnd(r)} ${s.padStart(4)} ${t.status.padEnd(9)} ${n}/app/skills/${t.skillId}?tab=runs&run=${t.id}`)})}return i.join(`
309
+ `)}const Ff={collector:`sends its OpenTelemetry to the collector`,elsewhere:"exports its telemetry elsewhere; the collector gets nothing (see `env` in ~/.claude/settings.json)",off:`doesn't send its OpenTelemetry to the collector`};async function If(e,t,{port:n}={}){switch(e){case`on`:{n!==void 0&&await so(Number(n)),await Ln({telemetry:!0});let e=await jo();if(e.status===`skipped`){F.warn(`Couldn't add the Claude Code hook: ${e.reason}.`);return}F.success(`Telemetry is on: Claude Code reports its sessions, what they used and the skills it loads.`),e.exportsElsewhere&&F.warn("Claude Code exports its telemetry elsewhere (`env` in ~/.claude/settings.json), so the collector gets nothing.");return}case`off`:await Ln({telemetry:!1}),await jo(),await sd({send:!1}),F.success("Telemetry is off: Claude Code doesn't report its sessions or the skills it loads, and the collector stopped. Turn it back on with `a-kit telemetry on`.");return;case`show`:return Rf(t);case void 0:case`status`:{let e=await In(),t=(await Po()).includes(`telemetry`),n=e.telemetry===!1?`off`:Rn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await oo(),i=await id(),a=i===`taken`?`another user's collector has the port`:i?`running (process ${i.pid})`:`not running`;console.log(`Telemetry is ${n}.`),console.log(`Claude Code: ${t?`reports its sessions and the skills it loads`:`no hook installed`}; ${Ff[await No()]}.`),console.log(`Collector: port ${r}, ${a}.`),console.log("\nWhen an agent loads a skill installed from agent kit, it reports the skill, its version, the agent, its session, this machine and when, so your organization sees which skills get used. It also reports when each session starts and ends. In a repo that installs skills from agent kit, it reports the repository and the branch too, the issue a skill was started for (`/implement 12`), the pull requests and issues a `gh` command opened or changed, and where the session came from (`AGENT_KIT_FROM`).\n\nClaude Code also sends its OpenTelemetry to a collector on this machine, which sends your organization what each session used: tokens and cost by model and by skill, how long you and the agent were each at work, and how many prompts, commits and pull requests it made. Only for a session in a repository of your organization's (one of its projects, or one that installs its skills); nothing of the others. Never what you or the agent wrote: no prompt, response, command or file path leaves the machine. `a-kit telemetry show` shows what was sent.\nTurn it off with `a-kit telemetry off`.");return}default:throw Error(`Unknown telemetry action "${e}". Use on, off, status or show.`)}}const Lf={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Rf(e){if(e){let[t,n]=await Promise.all([Yl(e),wl(e)]);if(!t&&n.length===0)throw Error(`Nothing was sent for session ${e}.`);console.log(n.length>0?`Its session told agent kit of:\n${n.map(e=>` ${e}`).join(`
310
+ `)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${Lf[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
311
+ Nothing of what it used was sent.`);return}let t=await Xl();if(t.length===0)console.log(`Nothing was sent for a session yet.`);else{for(let{at:e,status:n,record:r}of t)console.log(`${r.sessionId} ${r.organizationId} ${e} ${Lf[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function zf(e,t){let[n,...r]=e;if(!n)throw Error(`Name a skill and a prompt: a-kit try <skill> "<prompt>"`);let i=r.length>0?r.join(` `):await Wf();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Uf(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await $a(),c=wn(await s.listSkills(),n);if(c.length>1)throw Error(`More than one of your organizations has a skill named "${n}". Say which one: ${c.map(e=>`${e.organizationName}/${e.name}`).join(` or `)}.`);let l=c[0],u=e=>console.log(`\n${e.toUpperCase()} · ${o}\n`),d=(e,t)=>Bf(s,l.id,{model:o,version:a,withSkill:e,prompt:i},t),f=[],p=d(!1,e=>f.push(e));p.catch(()=>{});let m=!1;Hf(await d(!0,e=>{m||u(`With ${An(l)} v${a??l.version}`),m=!0,Vf(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Vf(e,l.name);Hf(h)}async function Bf(e,t,n,r){let i=`The answer ended before it finished.`;try{await e.playground(t,{model:n.model,version:n.version,withSkill:n.withSkill,messages:[{role:`user`,content:n.prompt}]},e=>{e.type===`done`&&(i=e),e.type===`error`&&(i=e.message),r(e)})}catch(e){if(e instanceof R)throw e;i=e instanceof Error?e.message:String(e)}return i}function Vf(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 Hf(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=fn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${un(e.usage)}`)}function Uf(e){if(e===void 0)return;let t=Number(e.replace(/^v/,``));if(!Number.isInteger(t)||t<1)throw Error(`"${e}" isn't a version number, like 3.`);return t}async function Wf(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Gf=`a-kit ${en}: your agent kit skills, in your agents.
310
312
 
311
313
  Usage
312
314
  a-kit init Log in and pick skills to install
@@ -366,4 +368,4 @@ Report options (the report-session-issue skill passes them for you)
366
368
  --org <id|name> The organization, when it can't tell
367
369
  --full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
368
370
  --dry-run Scrub and show what would be sent, without sending
369
- `;async function Gf(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Md.has(e))return Nd(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},session:{type:`string`},title:{type:`string`},note:{type:`string`},expected:{type:`string`},map:{type:`string`},org:{type:`string`},"full-outputs":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(en);let[i,...a]=r;if(n.help||!i)return console.log(Wf);if(!Qt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Xt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return $u(o);case`add`:case`install`:return Wo(a,o);case`update`:return fs(o);case`list`:case`ls`:return vd();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Mf(a);case`health`:return Qu(a);case`check`:return Zc(a);case`link`:return fd(a,o);case`login`:return n.token?Dd():Ed();case`logout`:return Ad();case`whoami`:return jd();case`try`:return Rf(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return Cf({...o,session:n.session,title:n.title,note:n.note,expected:n.expected,map:n.map,org:n.org,fullOutputs:n[`full-outputs`],dryRun:n[`dry-run`]});case`telemetry`:return Ff(a[0],a[1],{port:n.port});case`auto-update`:return hs(a[0]);case`heartbeat`:return ed(a[0],n.api);case`org`:return Td(a[0],a.slice(1).join(` `)||n.org);case`machine`:return Cd(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return cd(a[0],n.api,a[1]);case`collector`:return du(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Gf().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
371
+ `;async function Kf(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Nd.has(e))return Pd(e);let{values:n,positionals:r}=t({allowPositionals:!0,options:{global:{type:`boolean`,short:`g`,default:!1},agent:{type:`string`,short:`a`,multiple:!0,default:[]},yes:{type:`boolean`,short:`y`,default:!1},channel:{type:`string`,default:`latest`},help:{type:`boolean`,short:`h`,default:!1},version:{type:`boolean`,short:`v`,default:!1},session:{type:`string`},title:{type:`string`},note:{type:`string`},expected:{type:`string`},map:{type:`string`},org:{type:`string`},"full-outputs":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},model:{type:`string`},"skill-version":{type:`string`},token:{type:`boolean`,default:!1},api:{type:`string`},port:{type:`string`}}});if(n.version)return console.log(en);let[i,...a]=r;if(n.help||!i)return console.log(Gf);if(!Qt(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Xt.join(`, `)}.`);let o={global:n.global,agent:n.agent.flatMap(e=>e.split(`,`)).filter(Boolean),yes:n.yes,channel:n.channel};switch(i){case`init`:return ed(o);case`add`:case`install`:return Wo(a,o);case`update`:return fs(o);case`list`:case`ls`:return yd();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Nf(a);case`health`:return $u(a);case`check`:return Zc(a);case`link`:return pd(a,o);case`login`:return n.token?Od():Dd();case`logout`:return jd();case`whoami`:return Md();case`try`:return zf(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return wf({...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 If(a[0],a[1],{port:n.port});case`auto-update`:return hs(a[0]);case`heartbeat`:return td(a[0],n.api);case`org`:return Ed(a[0],a.slice(1).join(` `)||n.org);case`machine`:return wd(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return ld(a[0],n.api,a[1]);case`collector`:return fu(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Kf().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "useakit",
3
- "version": "0.2.0-dev.86",
3
+ "version": "0.2.0-dev.88",
4
4
  "description": "Install your agent kit skills into Claude Code, Codex, Cursor and Gemini CLI.",
5
5
  "keywords": [
6
6
  "agent-kit",