useakit 0.2.0-dev.93 → 0.2.0-dev.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +25 -25
- 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}${Rt({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 Zt=[`stable`,`beta`],Qt=[`latest`,...Zt],$t=e=>Zt.includes(e),en=e=>Qt.includes(e);function tn(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 nn=`0.2.0-dev.
|
|
74
|
+
`}}}}).prompt()};`${r(`gray`,P)}`;const Zt=[`stable`,`beta`],Qt=[`latest`,...Zt],$t=e=>Zt.includes(e),en=e=>Qt.includes(e);function tn(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 nn=`0.2.0-dev.95`;const rn=[{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`}],an=e=>e===`global`?C():process.cwd();function on(e=C()){return rn.filter(t=>f(_(e,t.marker)))}function sn(e){return rn.find(t=>t.id===e)}function cn(e,t,n=an(t)){let r=e.map(e=>b(n,t===`global`?e.globalDir:e.projectDir));return[...new Set(r)]}const ln={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 un(e){return e===null||e===0?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(e<1?3:2)}`}ln.maxPromptBytes;function dn(e){return e<1e3?String(e):e<1e6?`${pn(e/1e3)}k`:`${pn(e/1e6)}M`}const fn=e=>`${dn(e.inputTokens+e.outputTokens)} tok · ${un(e.costUsd)}`,pn=e=>e>=100?Math.round(e):Number(e.toFixed(1));function mn(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 hn(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 gn(){return process.env.npm_command===`exec`||/[\\/]_npx[\\/]/.test(process.argv[1]??``)?nn.includes(`-dev`)?`npx useakit@next`:`npx useakit`:`a-kit`}const L=e=>`\`${gn()} ${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/${nn}`,...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=hn(a+o.decode(e,{stream:!0}));a=t.rest,t.events.forEach(n)}hn(`${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/${_n(e)}`),getPublicBlob:async(e,t)=>new Uint8Array(await(await r(`/public/skills/${_n(e)}/blobs/${t}`)).arrayBuffer()),countInstall:e=>r(`/public/skills/${_n(e)}/installs`,{method:`POST`})}}const _n=e=>e.split(`/`).map(encodeURIComponent).join(`/`),vn=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)&&!process.env.CI;function yn(e){return rt(e)&&(Ut(`Cancelled.`),process.exit(130)),e}async function bn(e,t){if(e.length>0)return e.map(e=>{let t=sn(e);if(!t)throw Error(`Unknown agent "${e}". Use one of: ${rn.map(e=>e.id).join(`, `)}.`);return t});let n=on(),r=n.length>0?n:[sn(`claude-code`)];return!t||!vn()?r:yn(await Ht({message:`Which agents should get the skills?`,options:rn.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=>sn(e))}async function xn(e,t){return e?`global`:!t||!vn()?`project`:yn(await Xt({message:`Where should they go?`,options:[{value:`project`,label:`This project`,hint:process.cwd()},{value:`global`,label:`Everywhere`,hint:`your home folder`}],initialValue:`project`}))}const Sn=`kit/`;function Cn(e){let t=[],n=[];for(let r of e)r.startsWith(`kit/`)?n.push(r.slice(4)):t.push(r);return{skills:t,kits:n}}async function wn(e,t,n){if(t.length>0)return En(e,t,n,`skill`);if(!n||!vn())throw Error(`Name the skills to add, like ${L(`add my-skill`)}.`);let r=yn(await Ht({message:`Which skills?`,options:e.map(e=>({value:e.id,label:Nn(e),hint:e.description.length>60?`${e.description.slice(0,57)}…`:e.description})),required:!0}));return e.filter(e=>r.includes(e.id))}const Tn=(e,t,n)=>En(e,t,n,`kit`);async function En(e,t,n,r){let i=[];for(let a of t){let t=An(e,a,r),o=t.length===1?t[0]:await jn(t,n,r);i.includes(o)||i.push(o)}return i}const Dn=(e,t)=>An(e,t,`skill`);function On(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 kn=(e,t)=>On(e,t);function An(e,t,n){let r=t.lastIndexOf(`/`),i=t.slice(r+1),a=On(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 jn(e,t,n){let r=e[0].name,i=n===`kit`?Sn:``;if(!t||!vn()){let t=e.map(e=>{let t=i+Mn(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=yn(await Xt({message:`More than one of your organizations has ${n===`kit`?`kit/${r}`:`"${r}"`}. Which one?`,options:e.map(e=>({value:e.id,label:Mn(e)}))}));return e.find(e=>e.id===a)}const Mn=e=>`${e.organizationName}/${e.name}`,Nn=e=>e.showOrganization?`${e.name} (${e.organizationName})`:e.name;function B(){return(process.env.AGENT_KIT_API_URL??`https://api-dev.useagentkit.dev`??`http://localhost:8787`).replace(/\/+$/,``)}function Pn(e){let t=new URL(e);return t.hostname===`localhost`&&t.port===`8787`?`http://localhost:5173`:(t.hostname=t.hostname.replace(/^api(?:-([^.]+))?\./,(e,t)=>t?`${t}.`:``),t.origin)}function V(){return process.env.AGENT_KIT_CONFIG_DIR?process.env.AGENT_KIT_CONFIG_DIR:process.platform===`win32`&&process.env.APPDATA?_(process.env.APPDATA,`agent-kit`):_(process.env.XDG_CONFIG_HOME??_(C(),`.config`),`agent-kit`)}const Fn=()=>_(V(),`credentials.json`);async function In(){try{return JSON.parse(await O(Fn(),`utf8`))}catch{return{}}}async function H(){return(await In())[B()]??null}async function Ln(e){let t=await In();e?t[B()]=e:delete t[B()];let n=Fn();await D(g(n),{recursive:!0,mode:448}),await k(n,JSON.stringify(t,null,2)+`
|
|
76
76
|
`,{mode:384}),await re(n,384)}const Rn=()=>_(V(),`settings.json`);async function U(){try{return JSON.parse(await O(Rn(),`utf8`))}catch{return{}}}async function zn(e){let t={...await U(),...e};await D(V(),{recursive:!0,mode:448}),await k(Rn(),JSON.stringify(t,null,2)+`
|
|
77
77
|
`)}function Bn(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=y(process.cwd(),e);return t&&!t.startsWith(`..`)?t:e}const Vn=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`,`desktop.ini`,`.git`,`.idea`,`.vscode`,`node_modules`,`__pycache__`,`4913`]);function Hn(e){return e.split(`/`).some(e=>Vn.has(e)||/^\..*\.sw[a-p]$/.test(e)||e.endsWith(`~`)||/^#.*#$/.test(e)||e.startsWith(`.#`)||e.endsWith(`.tmp`))}const Un=e=>he(`sha256`).update(e).digest(`hex`);async function Wn(e){let t=await ce(e,{recursive:!0,withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let t=y(e,_(r.parentPath,r.name)).split(x).join(`/`);if(Hn(t))continue;let i=new Uint8Array(await O(_(e,t)));n.push({path:t,size:i.byteLength,sha256:Un(i),bytes:i})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Gn(e,t){let n=new Map(t.filter(e=>!Hn(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 Kn(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 qn(e,t){for(let n of e){if(!f(n))continue;let{paths:e}=Gn(await Wn(n),t);if(e.length>0)return{folder:n,paths:e}}return null}async function Jn(e,t,n,r){let i=await e.getVersion(n.id,n.version).catch(()=>null);return i?qn(r.map(e=>_(e,t)),i.files):null}async function Yn(e){try{if(!(await oe(e)).isSymbolicLink())return null}catch{return null}return b(g(e),await le(e))}async function Xn(e,t){for(let n of e){let e=await Yn(_(n,t));if(e)return e}return null}async function Zn(e,t){await de(e,{recursive:!0,force:!0}),await D(g(e),{recursive:!0}),await pe(t,e,process.platform===`win32`?`junction`:`dir`)}const G=`SKILL.md`,Qn={maxFiles:200,maxFileBytes:1048576,maxSkillBytes:10485760,maxPathLength:255},$n=/[\u0000-\u001f\u007f\\:]/;function er(e){if(e.trim()===``)return`The path is empty.`;if(e.length>Qn.maxPathLength)return`Paths can be at most ${Qn.maxPathLength} characters.`;if(e.startsWith(`/`))return`Use a relative path, without a leading /.`;if($n.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 tr(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function nr(e){return e.slice(e.lastIndexOf(`/`)+1)}function rr(e,t){let n=tr(e)?tr(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})),ir=/* @__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})),ar=/* @__PURE__ */ A((e=>{var t=K(),n=ir();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(`
|
|
@@ -287,30 +287,30 @@ description:
|
|
|
287
287
|
`));for(let{path:a,from:o,to:s}of Oi(e,t)){if(a.startsWith(`/`)){i(`warning`,`Link to files with a path relative to SKILL.md, without a leading /.`,o,s);continue}let e=rr(G,a);if(e===null){let e=ki(a);if(e&&r?.has(e))continue;i(`warning`,e&&r?`There's no skill named \`${e}\` in this organization.`:`This link points outside the skill.`,o,s)}else!n.has(e)&&![...n].some(t=>t.startsWith(`${e}/`))&&i(`warning`,`There's no ${e} in this skill.`,o,s)}}function uc(e){return/nested mappings|implicit keys/i.test(e)&&!/map values/i.test(e)?`This value has a colon in it. Wrap the whole value in quotes.`:/implicit map keys need to be followed by map values/i.test(e)?"Each frontmatter line needs a key, a colon and a value, like `key: value`.":`YAML: ${e.replace(/\.$/,``)}.`}function dc(e){return{severity:`error`,path:null,message:e}}function fc(e){let t=e.trim().toLowerCase();return[`true`,`yes`,`on`,`1`].includes(t)?!0:![`false`,`no`,`off`,`0`].includes(t)&&null}function pc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mc(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${Math.round(e/1048576*10)/10} MB`}const hc=`channels.yaml`;function gc(e,t){let n=`${t}/`,r=/* @__PURE__ */ new Map,i=[];for(let t of e){if(!t.path.startsWith(n))continue;let e=t.path.slice(n.length),a=e.indexOf(`/`);if(a===-1){i.push(e);continue}let o=e.slice(0,a),s=r.get(o)??[];s.push({path:e.slice(a+1),size:t.size}),r.set(o,s)}return{folders:[...r].sort(([e],[t])=>e.localeCompare(t)),loose:i}}function _c(e){return gc(e,`skills`).folders.filter(([,e])=>e.some(e=>e.path===G)).map(([e])=>e)}function vc(e){let{files:t,skillMds:n}=e,r=[...e.problems??[]],i=new Set(_c(t));e.truncated&&r.push({severity:`warning`,path:null,message:`The repository has more files than GitHub lists at once, so some weren't checked.`}),i.size>300&&r.push({severity:`warning`,path:`skills`,message:`Only the first 300 skills were checked.`});let a=gc(t,`skills`).folders.map(([e,t])=>{let a=`skills/${e}`,o=[],s=n.get(e);if(!i.has(e))o.push({severity:`error`,path:a,message:`There's no ${G} in this folder, so it isn't a skill.`});else if(s===void 0)o.push({severity:`warning`,path:`${a}/${G}`,message:`It couldn't be read, so this skill wasn't checked.`});else{let n=new Set(i);n.delete(e);for(let e of nc({files:t,skillMd:s,skills:n}))o.push({severity:e.severity,path:e.path===null?a:`${a}/${e.path}`,...e.path===`SKILL.md`&&e.from!==void 0?{line:vs(s,e.from)}:{},message:e.message});let r=Si(s).name;r!==null&&r!==e&&o.push({severity:`error`,path:`${a}/${G}`,message:`Its name is “${r}”, but its folder is “${e}”. They have to match.`})}return r.push(...o),{name:e,description:s===void 0?null:Si(s).description,files:t.length,errors:o.filter(e=>e.severity===`error`).length,warnings:o.filter(e=>e.severity===`warning`).length}}),o=(e,t,n)=>{for(let i of n)t.some(e=>e.path===i)||r.push({severity:`error`,path:e,message:`It needs a ${i}.`})},s=gc(t,`evals`).folders.map(([e])=>{let n=`evals/${e}`;i.has(e)||r.push({severity:`warning`,path:n,message:`There's no skill named “${e}” in skills/, so these evals have nothing to test.`});let a=gc(t,n).folders;for(let[e,t]of a)o(`${n}/${e}`,t,[`case.yaml`,`prompt.md`]);return{skill:e,cases:a.length}}),c=gc(t,`benchmarks`).folders.map(([e,n])=>{let i=`benchmarks/${e}`;o(i,n,[`benchmark.yaml`]);let a=gc(t,`${i}/tasks`).folders;for(let[e,t]of a)o(`${i}/tasks/${e}`,t,[`task.yaml`,`prompt.md`]);return a.length===0&&r.push({severity:`warning`,path:i,message:`It has no tasks yet: add one in tasks/<task>/.`}),{name:e,tasks:a.length}});if(typeof e.channelsText==`string`){let t=Es(e.channelsText),n=(e,t)=>r.push({severity:e,path:hc,message:t});if(`error`in t)n(`error`,`${t.error} No channel was changed.`);else{for(let e of t.problems)n(`error`,e);for(let e of t.pins.keys())i.has(e)||n(`warning`,`There's no skill named “${e}” in skills/, so its channels set nothing.`)}}let l=[];for(let n of gc(t,`kits`).loose){let t=`kits/${n}`,a=Cs(t);if(a===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are kits: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}l.push(a);let o=(e,n)=>r.push({severity:e,path:t,message:n}),s=xs(a);if(!s.ok||s.name!==a){o(`error`,`“${a}” can't be a kit's name, so this file isn't read. ${s.ok?`Take out the spaces.`:s.message}`);continue}let c=e.kitTexts?.get(t);if(c===void 0)continue;let u=ws(c);if(`error`in u)o(`error`,`${u.error} The kit wasn't changed.`);else if(u.skills.length>100)o(`error`,`A kit holds at most 100 skills, and this one lists ${u.skills.length}. The kit wasn't changed.`);else for(let e of u.skills)i.has(e)||o(`warning`,`There's no skill named “${e}” in skills/, so the kit leaves it out.`)}let u=[],d=[];for(let n of gc(t,Ns).loose){let t=`${Ns}/${n}`,i=Is(t);if(i===null){/\.yml$/.test(n)&&r.push({severity:`warning`,path:t,message:`Only .yaml files are flows: rename it to ${n.replace(/\.yml$/,`.yaml`)}.`});continue}u.push(i);let a=Rs(i);if(a){r.push({severity:`error`,path:t,message:a});continue}let o=e.flowTexts?.get(t);if(o===void 0)continue;let s=Vs(o);for(let e of s.roles)d.push({path:t,...e.line===null?{}:{line:e.line},name:e.name});for(let e of s.problems)r.push({severity:`error`,path:t,...e.line===null?{}:{line:e.line},message:e.message})}return{skills:a,evals:s,benchmarks:c,fixtures:gc(t,`fixtures`).folders.map(([e])=>e),kits:l.sort((e,t)=>e.localeCompare(t)),flows:u.sort((e,t)=>e.localeCompare(t)),flowRoles:d,channels:t.some(e=>e.path===hc),problems:yc(r)}}const yc=e=>e.sort((e,t)=>Number(e.severity===`warning`)-Number(t.severity===`warning`)||(e.path??``).localeCompare(t.path??``)||(e.line??0)-(t.line??0));function bc(e,t){let n=(e.flowRoles??[]).filter(e=>!t.has(e.name));return n.length===0?e:{...e,problems:yc([...e.problems,...n.map(e=>({severity:`warning`,path:e.path,...e.line===void 0?{}:{line:e.line},message:`There's no role “${e.name}” in the organization. Name it in Settings → Roles, or fix the name.`}))])}}const xc=(e,t,n)=>`There's a ${e} called “${t}” in ${n} already, and a name is one in the organization. This one isn't read: rename it, or take it out of one of them.`;function Sc(e,t){let n=[],r=`${Ns}/`,i=e=>t.main!==null&&e!==null&&(e===`channels.yaml`||e.startsWith(r));n.push(...e.problems.filter(e=>!i(e.path))),t.main!==null&&e.channels&&n.push({severity:`warning`,path:hc,message:`It's ignored: release channels are only read from the main repository, ${t.main}.`}),t.main!==null&&(e.flows??[]).length>0&&n.push({severity:`warning`,path:Ns,message:`They're ignored: flows are only read from the main repository, ${t.main}.`});let a=e.skills.map(e=>{let r=t.skills.get(e.name);return r===void 0?e:(n.push({severity:`error`,path:`skills/${e.name}`,message:xc(`skill`,e.name,r)}),{...e,errors:e.errors+1})});for(let r of e.kits){let e=t.kits.get(r);e!==void 0&&n.push({severity:`error`,path:Ss(r),message:xc(`kit`,r,e)})}return{...e,skills:a,problems:yc(n)}}const Cc={maxPerRequest:100,maxAgeDays:90,maxFutureMs:3e5,maxMachineNameLength:120,maxRepositoryLength:200,maxBranchLength:255},wc=/^[A-Za-z0-9._:-]{1,128}$/,Tc=/^[a-z0-9.-]+(\/[a-z0-9._-]+){2,}$/,Ec=/^(?:https?|ssh|git):\/\/(?:[^@/\s]+@)?([^:/\s]+)(?::\d+)?\/([^\s?#]+)$/i,Dc=/^(?:[^@/\s]+@)?([^:/\s]{2,}):(?!\/\/)([^\s]+)$/,Oc=/[\u0000-\u001f\u007f]/;function kc(e){let t=e.trim(),n=Ec.exec(t)??Dc.exec(t);if(!n)return null;let[,r,i]=n,a=i.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);if(a.length<2)return null;let o=[r,...a].join(`/`).toLowerCase();return Ac(o)?o:null}const Ac=e=>Tc.test(e)&&e.length<=Cc.maxRepositoryLength,jc=e=>e.length>0&&e.length<=Cc.maxBranchLength&&e.trim()===e&&!Oc.test(e),Mc={sessionId:null,repository:null,branch:null,audience:null},Nc=e=>typeof e==`string`&&e?e:null;async function Pc(e,t,n=C(),r=null){let i=Nc(e),a=ba(t,n)!==null;if(!a&&!r)return{...Mc,sessionId:i};let{repository:o,branch:s}=await Ic(t),c=o?r?.repositories[o]:void 0,l=a?`any`:c?{organizationId:c}:null;return l?{sessionId:i,repository:o,branch:s,audience:l}:{...Mc,sessionId:i}}function Fc({audience:e,...t},n){return e===`any`||e!==null&&e.organizationId===n?t:{...t,repository:null,branch:null}}async function Ic(e){let[t,n]=await Promise.all([zc(e,[`remote`,`get-url`,`origin`]),zc(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`])]);return{repository:t?kc(t):null,branch:n}}async function Lc(e,t){if(Rc.includes(t))return!0;let n=await zc(e,[`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`]);return n!==null&&n.replace(/^origin\//,``)===t}const Rc=[`main`,`master`,`develop`];function zc(e,t){return new Promise(n=>{try{ye(`git`,[`-C`,e,...t],{timeout:2e3,windowsHide:!0},(e,t)=>n(e?null:t.trim()||null))}catch{n(null)}})}const Bc=[`skills`,`evals`,`benchmarks`,`fixtures`,`kits`,`flows`],Vc=e=>{try{return p(e).isDirectory()}catch{return!1}};function Hc(e){let t;for(let n=b(e);;n=g(n)){if(t??=Vc(_(n,`skills`))?n:void 0,f(_(n,`.git`))){if(Vc(_(n,`skills`)))return n;throw Error(`${W(n)} has no skills/ folder, so it isn't your organization's repository. Run this in a clone of it.`)}if(g(n)===n)break}if(t)return t;throw Error(`There's no skills/ folder here. Run this in a clone of your organization's repository.`)}async function Uc(e){let t=[];for(let n of Bc){let r=_(e,n);if(Vc(r))for(let n of await ce(r,{recursive:!0,withFileTypes:!0})){if(!n.isFile())continue;let r=_(n.parentPath,n.name),i=y(e,r).split(x).join(`/`);Hn(i)||t.push({path:i,size:(await fe(r)).size})}}return f(_(e,`channels.yaml`))&&t.push({path:hc,size:(await fe(_(e,hc))).size}),t}async function Wc(e){let t=await Uc(e),n=/* @__PURE__ */ new Map;for(let r of _c(t))n.set(r,await O(_(e,`skills`,r,G),`utf8`));let r=t.some(e=>e.path===`channels.yaml`)?await O(_(e,hc),`utf8`):null,i=/* @__PURE__ */ new Map;for(let{path:n}of t)Is(n)!==null&&i.set(n,await O(_(e,n),`utf8`));return vc({files:t,skillMds:n,channelsText:r,flowTexts:i})}const Gc=1e4,Kc=(e,t)=>t.aborted?`agent kit didn't answer in time`:e instanceof Error?e.message:String(e);async function qc(e,t,n=Gc){if(!e.flowRoles?.length)return{scan:e,unchecked:null};let r=t=>({scan:e,unchecked:`Roles in flows weren't checked: ${t}`});if(!t)return r(`log in with ${L(`login`)} to check them against your organization's.`);let i=AbortSignal.timeout(n);try{let n=t.organizationId;if(!n){let e=await t.api.listOrganizations(i);if(e.length===0)return r(`you're in no organization.`);if(e.length>1)return r(`you're in more than one organization. Pick yours with ${L(`org use`)}.`);n=e[0].id}let a=await t.api.listRoles(n,i);return{scan:bc(e,new Set(a.map(e=>e.name))),unchecked:null}}catch(e){return r(`couldn't get your organization's roles (${Kc(e,i)}).`)}}const Jc=`Skill names in your organization's other repositories`;async function Yc(e,t,n){let r=await e.listOrganizations(n),i=await Promise.all(r.map(t=>e.getRepository(t.id,n).then(e=>({organizationId:t.id,status:e})).catch(e=>{if(e instanceof R&&(e.status===403||e.status===404))return null;throw e})));for(let e of i){if(!e)continue;let n=e.status.repositories??(e.status.repository?[e.status.repository]:[]),r=n.find(e=>`github.com/${e.fullName.toLowerCase()}`===t);if(!r)continue;let i=n.find(e=>e.main);return{organizationId:e.organizationId,fullName:r.fullName,placement:{main:r.main?null:i?.fullName??null,skills:new Map(Object.entries(r.elsewhere?.skills??{})),kits:new Map(Object.entries(r.elsewhere?.kits??{}))}}}return null}async function Xc(e,t,n,{roles:r=!0,timeoutMs:i=Gc}={}){let a=r&&(e.flowRoles?.length??0)>0?`${Jc} and roles in flows`:Jc;if(!n)return{scan:e,unchecked:`${a} weren't checked: log in with ${L(`login`)} to check them.`,place:null};let o=null;if(t){let r=AbortSignal.timeout(i);try{o=await Yc(n.api,t,r)}catch(t){return{scan:e,unchecked:`${a} weren't checked: couldn't get your organization's repositories (${Kc(t,r)}).`,place:null}}}if(o){let t=Sc(e,o.placement);return!r||o.placement.main!==null?{scan:t,unchecked:null,place:o}:{...await qc(t,{api:n.api,organizationId:o.organizationId},i),place:o}}let s=r?await qc(e,n,i):{scan:e,unchecked:null},c=t?`${Jc} weren't checked: agent kit reads no repository at ${t}.`:null;return{scan:s.scan,unchecked:[c,s.unchecked].filter(Boolean).join(`
|
|
288
288
|
`)||null,place:null}}async function Zc(e,t,n){let r=await H();return Xc(t,(await Ic(e)).repository,r&&{api:z(B(),r.token),organizationId:r.organizationId},n)}function Qc(e,t,n=process.cwd()){let r=[];for(let i of t){let t=b(n,i);if(Vc(t)){if(t===e||t===_(e,`skills`))return[];if(g(t)===_(e,`skills`)){r.push(m(t));continue}let n=y(_(e,`skills`),t);if(!n.startsWith(`..`)&&n!==``){r.push(n.split(x)[0]);continue}throw Error(`${W(t)} isn't a skill's folder. Skills are in ${W(_(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 $c=(e,t)=>e.filter(e=>t.some(t=>e.path===`skills/${t}`||e.path?.startsWith(`skills/${t}/`)===!0));async function el(e){let t=Hc(e.find(e=>e.includes(`/`))??`.`),n=Qc(t,e),r=await Wc(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 Zc(t,r,{roles:n.length===0}),l=c?.placement.main?0:o.flows?.length??0,u=n.length>0?$c(o.problems,n):o.problems;for(let e of bs(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?ys(n.length,`skill`):`The repository (${[ys(o.skills.length,`skill`),...l?[ys(l,`flow`)]:[]].join(`, `)})`;d>0?(console.log(`\n${p}: ${ys(d,`error`)}`+(f?`, ${ys(f,`warning`)}`:``)+`. agent kit won't make a version of a skill or a flow with errors.`),process.exitCode=1):console.log((u.length||s?`
|
|
290
|
-
`:``)+`${p}: no errors`+(f?`, ${ys(f,`warning`)}`:``)+`.`)}const tl={maxPerRequest:20,maxEntries:1e3,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Z={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`},
|
|
291
|
-
`)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim(),i=r&&/^(?:[a-z][a-z-]*\s+)?(\S+)$/.exec(r)?.[1];if(!i)return[];let a=
|
|
292
|
-
`)}const
|
|
293
|
-
`)}async function
|
|
294
|
-
`)},async list(){let e=[];try{e=await ce(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(_(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await ce(t())){let r=_(t(),n);e-(await fe(r)).mtimeMs>6048e5&&await de(r,{force:!0})}}catch{}}}}const
|
|
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)
|
|
296
|
-
`).length,bodyTokens:
|
|
297
|
-
`)}async function
|
|
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
|
|
299
|
-
`))}function
|
|
300
|
-
`))}async function
|
|
290
|
+
`:``)+`${p}: no errors`+(f?`, ${ys(f,`warning`)}`:``)+`.`)}const tl=9e5,nl=e=>Math.floor(e/tl)*tl,rl={maxPerRequest:20,maxEntries:1e3,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxModelLength:100,maxIdLength:64,maxValue:0xe8d4a51000},Z={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`},il=/* @__PURE__ */ new Set([Z.personSeconds,Z.agentSeconds,Z.costUsd]),al=e=>typeof e==`string`&&e.length>0&&e.length<=rl.maxModelLength&&!/\s/.test(e)&&!Oc.test(e),ol={maxPerRequest:100,maxLinks:50,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},sl=/^[1-9][0-9]{0,8}$/,cl=/\s/,ll=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function ul(e,t){let n=t.trim();switch(e){case`repository`:{let t=n.toLowerCase();return Ac(t)?{kind:e,value:t}:null}case`branch`:case`issue`:case`pull_request`:case`touched`:{let t=n.indexOf(`#`);if(t<0)return null;let r=n.slice(0,t).toLowerCase(),i=n.slice(t+1);return Ac(r)&&(e===`branch`?jc(i):sl.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return fl(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=ol.maxThreadLength&&!cl.test(n)&&!Oc.test(n)?{kind:e,value:n}:null;case`session`:return wc.test(n)?{kind:e,value:n}:null;default:return null}}function dl(e){let t=e.trim();return ul(`slack_thread`,t)??ul(`thread`,t)}function fl(e){return e.length<=ol.maxUrlLength&&ll.test(e)}const pl=()=>_(V(),`sessions`),ml=()=>_(V(),`pending-session-events.jsonl`),hl=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function gl(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 _l(e,t){let n=e.trimStart().split(`
|
|
291
|
+
`)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim(),i=r&&/^(?:[a-z][a-z-]*\s+)?(\S+)$/.exec(r)?.[1];if(!i)return[];let a=yl(i,t,e=>e===`pull`?`pull_request`:`issue`);return a?[a]:[]}const vl=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/(issues|pull)\/(\d+)(?:[/?#]\S*)?$/;function yl(e,t,n){let r=vl.exec(e);return r?ul(n(r[2]),`${r[1]}#${r[3]}`):t&&/^#?\d+$/.test(e)?ul(n(null),`${t}#${e.replace(`#`,``)}`):null}function bl(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=wl(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(ul(o===`pr`?`pull_request`:`touched`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`&&o!==`pr`||!(o===`issue`?xl:Sl).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=Cl(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||vl.test(t))&&(u=t)}u&&i(yl(u,l,()=>`touched`))}return r}const xl=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),Sl=/* @__PURE__ */ new Set([`comment`,`edit`]),Cl=e=>e.split(`/`).length===2?`github.com/${e}`:e;function wl(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function Tl(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 El(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 Dl(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=gl(t,n),l=i.sessionId;if(!c||!l||!wc.test(l))return null;c===`end`&&t.reason===`clear`&&await Ll(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(ul(`repository`,i.repository)),i.branch&&!await Lc(r,i.branch)&&d(ul(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=El(t);if(p&&f)for(let e of _l(p,i.repository))d(e);let m=Tl(t);if(m&&f)for(let e of bl(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(dl(t));if(t.source===`clear`){let e=await Rl(r,l,o,s);e&&d(ul(`session`,e))}}let h=await Al(l),g=u.map(Pl),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await Fl(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await zl(o),{sessionId:l,agent:e,machineId:await xa(),machineName:ma(),type:c,occurredAt:o.toISOString(),links:u})}const Ol=(e,t=[])=>ha(ml(),e,t),kl=e=>_(pl(),`${hl(e)}.json`);async function Al(e){try{let t=JSON.parse(await O(kl(e),`utf8`));return{sentAt:typeof t.sentAt==`number`?t.sentAt:0,links:Array.isArray(t.links)?t.links:[],...t.imported===!0&&{imported:!0}}}catch{return{sentAt:0,links:[]}}}const jl=async e=>(await Al(e)).links;async function Ml(e,t){let n=await Al(e);await Fl(e,{sentAt:n.sentAt,links:[.../* @__PURE__ */ new Set([...n.links,...t.map(Pl)])],imported:!0})}async function Nl(e){try{return JSON.parse(await O(kl(e),`utf8`)).imported!==!0}catch{return!1}}const Pl=e=>`${e.kind} ${e.value}`;async function Fl(e,t){await D(pl(),{recursive:!0,mode:448}),await k(kl(e),JSON.stringify(t)+`
|
|
292
|
+
`)}const Il=e=>_(pl(),`cleared-${hl(e)}.json`);async function Ll(e,t,n){await D(pl(),{recursive:!0,mode:448}),await k(Il(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
|
|
293
|
+
`)}async function Rl(e,t,n,r){let i=Il(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 de(i,{force:!0}),e.sessionId}catch{}if(Date.now()>=a)return null;await Te(100)}}async function zl(e){try{for(let t of await ce(pl())){let n=_(pl(),t),{mtimeMs:r}=await fe(n);e.getTime()-r>6048e5&&await de(n,{force:!0})}}catch{}}function Bl(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 ls(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 fs(r.api,r.userId,u,new Date(s))??u),(u&&Vl(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function Vl(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 Hl={"claude_code.token.usage":{input:Z.inputTokens,output:Z.outputTokens,cacheRead:Z.cacheReadTokens,cacheCreation:Z.cacheCreationTokens},"claude_code.cost.usage":Z.costUsd,"claude_code.active_time.total":{user:Z.personSeconds,cli:Z.agentSeconds},"claude_code.commit.count":Z.commits,"claude_code.pull_request.count":Z.pullRequests};function Ul(e){let t=[];for(let n of ql(Q(e,`resourceMetrics`)))for(let e of ql(Q(n,`scopeMetrics`)))for(let n of ql(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?Hl[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of ql(Q(i,`dataPoints`))){let i=ql(Q(n,`attributes`)),o=e=>Jl(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Yl(Q(n,`asDouble`)??Q(n,`asInt`)),u=Xl(Q(n,`startTimeUnixNano`)),d=Xl(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Gl(e,i,a?u:null),metric:c,model:Kl(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Wl(e){let t=[];for(let n of ql(Q(e,`resourceLogs`)))for(let e of ql(Q(n,`scopeLogs`)))for(let n of ql(Q(e,`logRecords`))){let e=ql(Q(n,`attributes`)),r=Jl(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=Jl(e,`session.id`),a=Xl(Q(n,`timeUnixNano`))??Xl(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Gl(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 he(`sha256`).update(JSON.stringify([e,r,n])).digest(`hex`).slice(0,32)}const Kl=e=>al(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,ql=e=>Array.isArray(e)?e:[];function Jl(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Yl(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Xl(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 Zl=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function Ql(e){let t=()=>_(ao(),e),n=e=>_(t(),`${Zl(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 ce(t())}catch{return[]}let n=[];for(let i of e)try{n.push(await r(_(t(),i)))}catch{}return n},async forgetOld(e=Date.now()){try{for(let n of await ce(t())){let r=_(t(),n);e-(await fe(r)).mtimeMs>6048e5&&await de(r,{force:!0})}}catch{}}}}const $l=Ql(`sessions`),eu=e=>$l.write(e.sessionId,e);async function tu(e){let t=await $l.read(e);return t?.sessionId===e?t:null}const nu=(e=Date.now())=>$l.forgetOld(e),ru=Ql(`sent`),iu=(e,t,n=/* @__PURE__ */ new Date)=>ru.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),au=e=>ru.read(e),ou=async()=>(await ru.list()).sort((e,t)=>t.at.localeCompare(e.at)),su=(e=Date.now())=>ru.forgetOld(e),cu=(e,t)=>({sessionId:e,epoch:t,series:{},slices:{},prompts:0,lastAt:t});function lu(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],l=o;if(t.cumulative){if(c&&(c.at>=s||c.value===o))return c.at<s&&(c.at=s),!1;l=Math.max(0,o-(c?.value??0)),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)}}if(il.has(r)&&l>0){let t=nl(s),n=e.slices??={},o=JSON.stringify([r,i,a,t]),c=n[o]??={metric:r,model:i,skillName:a,start:t,value:0};c.value+=l}return e.lastAt=Math.max(e.lastAt,s),!0}function uu(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)},i=e=>e!==null&&Object.hasOwn(t.skillIds,e)?t.skillIds[e]:null;for(let t of Object.values(e.series))il.has(t.metric)||r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),value:t.value});for(let t of Object.values(e.slices??{}))r({metric:t.metric,model:t.model,skillId:i(t.skillName),start:new Date(t.start).toISOString(),end:new Date(t.start+tl).toISOString(),value:t.value});return e.prompts>0&&r({metric:Z.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)=>Number(!!e.entry.end)-Number(!!t.entry.end)||Date.parse(t.entry.start)-Date.parse(e.entry.start)||e.i-t.i).slice(0,rl.maxEntries).sort((e,t)=>e.i-t.i).map(({entry:e})=>e)}}const du=Ql(`state`);function fu(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=pu(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);lu(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await du.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 du.write(e.state.sessionId,e.state))}}}async function pu(e,t){let n=await du.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:cu(e,t),unsaved:!1}}const mu=(e=Date.now())=>du.forgetOld(e),hu=16777216,gu=()=>_(V(),`pending-session-usage.jsonl`);async function _u(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=fu(),s=Bl(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(!_a(e))for(let e of t)await iu(e,`refused`);throw e}for(let e of t)await iu(e,`sent`)}),p=(e=[])=>ha(gu(),f,e,{batch:rl.maxPerRequest,batchLength:409600,keyOf:e=>e.sessionId});async function m(){let e=[];for(let t of await o.dirty()){let r=await tu(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=uu(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await xa(),machineName:ma(),skillIds:i.skillIds});a.usage.length!==0&&(await iu(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(),wa(h),Ol(g)]);function v(e){let t=xu(e.activations),n=xu(e.sessionEvents);return u(()=>Promise.all([t.length>0&&wa(h,t),n.length>0&&Ol(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(),bu(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 bu(n,200,{api:e.apiUrl,pid:process.pid});if(t.method!==`POST`)return t.resume(),bu(n,404,{});if(i===`/stop`){t.resume(),bu(n,200,{}),se({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),bu(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),bu(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),bu(n,415,{message:`Send JSON.`});let a=await yu(t);if(!a.ok)return bu(n,a.status,{});i===`/report`?(bu(n,202,{}),v(a.json)):(await o.observe(i===`/v1/metrics`?Ul(a.json):Wl(a.json)),b(),bu(n,200,{}))}let S=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ve(t,c)},C=Ce((e,t)=>{x(e,t).catch(()=>{t.headersSent||bu(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=[gu(),Ca(),ml()];t=(await Promise.all(e.map(ga))).some(Boolean)||(await o.dirty()).length>0}),D||T!==e)return;let n=Date.now()-T;t&&n<a?E(Math.max(1,Math.min(i,a-n))):se()}ee();let ne=setInterval(()=>void u(m),t),re=setInterval(()=>void u(_),r);u(async()=>{let e=Date.now();await nu(e),await mu(e),await su(e),await o.resume()});let ie=()=>u(m).then(()=>u(_)),ae=()=>{},oe=new Promise(e=>ae=e),D=null;function se({send:e=!0}={}){return D??=(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,ae()})(),D}return{port:C.address().port,flush:ie,stop:se,stopped:oe}}const vu=n(we);async function yu(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>hu)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 vu(r,{maxOutputLength:hu})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function bu(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const xu=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function Su(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await co();await(await _u({port:t,secret:n,apiUrl:B(),login:async()=>{let e=await H();return e?{api:z(B(),e.token),userId:e.user.id}:null}}))?.stopped}const Cu=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,wu=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function Tu(e){let t=0;for(let[n]of e.matchAll(wu)){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)Cu.test(t)&&e++;let r=[...n].length-e;t+=e+Math.ceil(r/6)}else/\p{N}/u.test(e)?t+=Math.ceil(n.length/3):t+=1}return t}function Eu(e){return{always:e.description,max:e.description+e.body+e.files}}function Du(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=Eu(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function Ou(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${Au((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${Au((e/1e6).toFixed(1))}M`}const ku=(e,t)=>`${t===`estimate`?`~`:``}${Ou(e)}`,Au=e=>e.replace(/\.0$/,``),ju={high:15,medium:10,low:5},Mu=5e3,Nu=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function Pu(e){let t=nr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&Nu.has(n)}const Fu=/^(license|licence|notice|readme|changelog)(\..*)?$/i,Iu=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function Lu(e,t){let n=t(`SKILL.md`)??``,r=xi(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)Pu(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Yu(r)){let t=rr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Xu(r,n,t.path)&&(d.add(t.path),Pu(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!Fu.test(nr(e))).filter(e=>!nr(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:Tu(c),hasExamples:nd(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Ru(e,t,n=/* @__PURE__ */ new Date){let r=[...Ku(e),...t?qu(t,n):[]];return{score:zu(r),checks:Vu(r)}}function zu(e){let t=e.reduce((e,t)=>e+ju[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+ju[t.severity],0);return Math.round(n/t*100)}const Bu=[`high`,`medium`,`low`];function Vu(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:Bu.indexOf(e.severity)-Bu.indexOf(t.severity)))}const Hu=(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}),Uu=/\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,Wu=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,Gu=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Ku(e){let t=[],n=e.description??``;e.hasWhenToUse||Uu.test(n)?t.push(Hu(`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(Wu);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(Hu(`description-specific`,`medium`,`description is specific`)),Gu.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(Hu(`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(Hu(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Ju(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>Mu?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Ju(Mu)}; move reference material into files ${G} links to.`)):t.push(Hu(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Hu(`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(Hu(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${rd(e.missingFiles.length,`missing file`)}: ${id(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Hu(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${rd(e.unusedFiles.length,`file`)} nothing mentions: ${id(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function qu(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Hu(`eval-cases`,`high`,rd(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${rd(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Hu(`eval-negative`,`medium`,`${rd(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(Hu(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${rd(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 Ju(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Yu(e){let t=[];for(let n of e.matchAll(Iu)){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 Xu(e,t,n){if(n===t)return!1;let r=/* @__PURE__ */ new Set([n,nr(n)]),i=n.split(`/`);for(let e=1;e<i.length;e++)r.add(`${i.slice(0,e).join(`/`)}/`);let a=Zu(t,n);return a&&r.add(a),[...r].some(t=>Qu(e,t))}function Zu(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Qu(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 $u=/^(```|~~~)/m,ed=/^#{1,6}[^\n]*\bexamples?\b/im,td=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function nd(e){return $u.test(e)||ed.test(e)||td.test(e)}function rd(e,t){return`${e} ${t}${e===1?``:`s`}`}function id(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const ad=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function od(e){try{return(await fe(_(e,G))).isFile()}catch{return!1}}async function sd(e){let t=[],n=/* @__PURE__ */ new Map;async function r(i){for(let a of await ce(i,{withFileTypes:!0})){let o=_(i,a.name);if(a.isDirectory()){ad.has(a.name)||await r(o);continue}if(!a.isFile())continue;let s=y(e,o).split(x).join(`/`),{size:c}=await fe(o);t.push({path:s,size:c}),(s===`SKILL.md`||Pu({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Ru(Lu(t,e=>n.get(e)),null)}function cd(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 ld(e){let[t]=e;if(e.length>1)throw Error("Name one skill or folder, like `a-kit health pdf-forms`.");let n=b(t??`.`);if(await od(n)){let e=await sd(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(cd(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 to(),i=Dn(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(`${Nn(a)} v${a.version}`),console.log(cd(o))}async function ud(e){Wt(`agent kit`);let t=await eo();t?F.success(`Logged in as ${no(t.user)}`):t=await $a();let n=z(B(),t.token),r=await n.listSkills();if(r.length===0){I(ro(t.webUrl));return}let i=!e.yes;if(i&&!vn())throw Error("`a-kit init` asks questions. Pass --yes to install every skill, or use `a-kit add <skill>`.");let a=await xn(e.global,i),o=await bn(e.agent,i),s=i?yn(await Ht({message:`Which skills?`,options:r.map(e=>({value:e.id,label:Nn(e)})),initialValues:r.map(e=>e.id),required:!0})):r.map(e=>e.id),{dirs:c}=await Wo(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 dd(e,t){switch(e){case`send`:t&&(process.env.AGENT_KIT_API_URL=t),await Xa();return;case`on`:{if(await zn({heartbeat:!0}),!await H()){F.warn("Heartbeats are on; they start once you run `a-kit login`.");return}if(!la()){F.warn(`Run it from the published CLI to install the timer.`);return}await Za();let e=await Wa(B()),t=(await Ya())?.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 zn({heartbeat:!1}),await Ua(B()),F.success("Heartbeats are off: this machine stops reporting. It stays on the Machines page until someone forgets it there. Turn them back on with `a-kit heartbeat on`.");return;case void 0:case`status`:{let e=(await U()).heartbeat!==!1,t=await Wa(B()),n=await Ya();console.log(`Heartbeats are ${e?`on`:`off`}.`),console.log(`Timer: ${t?za(B()).join(`, `):`not installed`}.`),n&&console.log(`Last heartbeat: ${new Date(n.sentAt).toLocaleString()}${n.ok?``:` (it didn't go through)`}.`),n?.organization&&console.log(`Shows up on: ${n.organization.name}'s Machines page (change it with \`a-kit org use\`).`),console.log(`
|
|
298
|
+
Every 5 minutes, a system timer tells agent kit this machine's name, the CLI's version, the agents on it and their versions, and the skills installed everywhere (-g), so your organization's Machines page shows whether it's on and up to date. Logging in, installing and updating send it too.`);return}default:throw Error(`Unknown heartbeat action "${e}". Use on, off or status.`)}}const fd=2e3;async function pd(e,t={},n=300){let{port:r,secret:i}=await co();try{return await fetch(`http://127.0.0.1:${r}${e}`,{...t,headers:{[io]:i,...t.body?{"content-type":`application/json`}:{}},signal:AbortSignal.timeout(n)})}catch{return null}}async function md(){let e=await pd(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function hd(e,t,n=qo){let r=await md();return r===`taken`?`taken`:r?.api===t?`running`:(r&&await _d(),f(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function gd(e){return(await pd(`/report`,{method:`POST`,body:JSON.stringify(e)},fd))?.status===202}async function _d({send:e=!0}={}){return(await pd(e?`/stop`:`/stop?send=false`,{method:`POST`},fd))?.ok??!1}const vd=5e3;async function yd(e,t,n){try{if(t&&(process.env.AGENT_KIT_API_URL=t),e!==`claude-code`||process.stdin.isTTY)return;let r=JSON.parse(await Sd()),i=/* @__PURE__ */ new Date,a=n===`session`?n:void 0;if(r.hook_event_name===`SessionStart`&&!a){await es(la()??ca()),await Wa(B())||await Xa();return}if(Bn()||(await U()).telemetry===!1)return;let o=await H();if(!o)return;let s=typeof r.cwd==`string`?r.cwd:process.cwd(),c=r.hook_event_name===`SessionEnd`,l=await ls(o.user.id),u=c?{...Mc,sessionId:Nc(r.session_id)}:await Pc(r.session_id,s,void 0,l),d=z(B(),o.token),f=r.hook_event_name===`SessionStart`&&a===`session`;f&&u.sessionId&&await xd(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`)&&await hd(la()??ca(),B());let p=await Dl(e,r,a,s,u,{now:i}),m=Ao(r),h=m&&await ya(m.name,e,s),g=m&&h&&await Sa(h,e,m.trigger,Fc(u,l?.skills[h.id]??null),i);await Promise.all([!c&&ds(l,i,h?h.id:null)&&fs(d,o.user.id,l,i),(p||g)&&bd(d,p,g)])}catch{}}async function bd(e,t,n){await gd({activations:n?[n]:[],sessionEvents:t?[t]:[]})||await Promise.all([t&&Ol(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(vd))},t),n&&wa(async t=>{await e.reportActivations(t,AbortSignal.timeout(vd))},n)])}async function xd(e,t,n){let{repository:r,branch:i}=await Ic(n),a=ba(n,C());(r||a)&&await eu({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function Sd(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function Cd(e,t){if(e.length!==1)throw Error(`Name the skill's folder, like ${L(`link skills/release`)}.`);Wt(`agent kit`);let n=b(e[0]);if(!f(_(n,`SKILL.md`)))throw Error(`${W(n)} has no ${G}, so it isn't a skill.`);let r=m(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 bn(t.agent,!t.yes),o=cn(a,i),s=o.map(e=>_(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(f(e)&&!await Yn(e)&&!c)throw Error(`${W(e)} is a skill agent kit didn't install. Move it somewhere else first.`);if(c){let e=await Jn(z(B(),(await H())?.token),r,c,o);if(e&&!await Yn(e.folder))throw Error(`${W(e.folder)} has edits that aren't in agent kit (${Kn(e.paths)}). Copy them to ${W(n)} and delete them there first.`)}for(let e of s)await Zn(e,n);F.success(`${r}: ${s.map(W).join(`, `)} → ${W(n)}`);let l=i===`project`?await wd(cn(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 Td(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 wd(e,t,n){let r=[];for(let i of e){let e=_(i,t);f(e)&&await Yn(e)!==n&&r.push(e)}return r}async function Td(e,t,n){let r;try{r=Hc(e)}catch{return}if(b(r,`skills`,t)!==e)return;let{scan:i,place:a}=await Zc(r,await Wc(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=$c(i.problems,[t]);s.some(e=>e.severity===`error`)&&F.warn([`agent kit won't make a version of ${t} as it is:`,...bs(s)].join(`
|
|
299
|
+
`))}function Ed(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?ku(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[Nn(e),Dd(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[Od(`project`,r,e),Od(`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=Du(s.map(e=>e.skill.contextCost)),l=c.estimated?`~`:``,u=[o(i),...r.map(e=>o(e.cells))];return u.push(s.length===0?`${`TOTAL`.padEnd(a[0])} nothing installed here`:`${`TOTAL`.padEnd(a[0])} ${l}${Ou(c.always)} always · ${l}${Ou(c.max)} max (${s.length} installed${c.missing?`, ${c.missing} not counted yet`:``})`),r.some(e=>e.skill.contextCost?.source===`estimate`)&&u.push(`~ estimated locally: add a Claude API key to the organization to count exactly.`),u}function Dd(e){return[`v${e.version}`,...Zt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function Od(e,t,n){if(!t)return null;let r=Yi(t),{version:i}=tn(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 kd(){let{api:e,credentials:t}=await to(),[n,r]=await Promise.all([e.listSkills(),e.listKits()]);if(n.length===0){console.log(ro(t.webUrl));return}let i=await X(Y(`project`)),a=await X(Y(`global`));for(let e of Ed(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>Ad(e).length));for(let e of r){let t=[jd(i,e)&&`in project`,jd(a,e)&&`in global`].filter(Boolean);console.log(`${Ad(e).padEnd(o)} ${Md(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const Ad=e=>`${Sn}${Nn(e)}`,jd=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function Md(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 Nd=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${L(`heartbeat status`)}).`;async function Pd(e,t){switch(e){case`name`:{let{api:e}=await to(),n=await xa();if(t===void 0){let t=await Fd(e.machineName(n));if(!t)throw Error(Nd);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 Fd(e.nameMachine(n,t))??(await Xa()?await Fd(e.nameMachine(n,t)):null);if(!r)throw Error(Nd);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 Fd(e){try{return await e}catch(e){if(e instanceof R&&e.status===404)return null;throw e}}async function Id(e,t){switch(e){case void 0:case`status`:{let e=(await Ya())?.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 to(),r=await Ma(e,n,t);if(!r)throw Error(`Which organization? Name it, like ${L(`org use acme`)}.`);if((await U()).heartbeat===!1){F.warn(`This machine goes to ${r.name}, but its heartbeats are off. Turn them on with ${L(`heartbeat on`)}.`);return}await Xa()?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 Ld(){Wt(`agent kit`);let e=await eo().catch(()=>null);if(e){let t=no(e.user);if(!vn()){I(`Already logged in as ${t}.`);return}if(!yn(await zt({message:`You're logged in as ${t}. Log in with another account?`,initialValue:!1}))){I(`Still logged in as ${t}.`);return}}let t=await $a();e&&await z(B(),e.token).logout().catch(()=>{}),I(await Bd(t.token,t.webUrl))}async function Rd(e=process.stdin){Wt(`agent kit`);let t=await zd(e);if(!t)throw Error(`Give it the bot's token on stdin, like ${L(`login --token`)} < bot-token.`);let n;try{n=await z(B(),t).me()}catch(e){throw e instanceof R&&e.status===401?Error(`This token doesn't work: it's wrong, or the bot was revoked.`):e}let r=await H();await Ln({token:t,user:n,webUrl:Pn(B())}),r&&r.token!==t&&await z(B(),r.token).logout().catch(()=>{}),await Za(),I(`Logged in as ${no(n)}.`)}async function zd(e){if(e.isTTY)return yn(await Gt({message:`The bot's token`})).trim();let t=``;for await(let n of e)t+=String(n);return t.trim()}async function Bd(e,t){return(await z(B(),e).listSkills().catch(()=>null))?.length===0?`You're in. ${ro(t)}`:`You're in. Install your skills with ${L(`init`)}.`}async function Vd(){let e=await H();e?(await z(B(),e.token).logout().catch(()=>{}),await Ln(null),console.log(`Logged out ${no(e.user)}.`)):console.log(`You're not logged in.`)}async function Hd(){let e=await eo();e?console.log(no(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Ud=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Wd(e){let t=await Gd(),n=t.length>0?t.map(e=>`gh repo clone ${e}`).join(` or `):`Clone your organization's skills repository from GitHub.`,r=[`\`${gn()} ${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 Gd(){let e=(await H())?.token;if(!e)return[];let t=z(B(),e),n=async()=>{let e=await t.listOrganizations(),n=await Promise.all(e.map(e=>t.getRepository(e.id).then(e=>e.repositories?.map(e=>e.fullName)??(e.repository?[e.repository.fullName]:[])).catch(()=>[])));return[...new Set(n.flat())]},r=new Promise(e=>setTimeout(()=>e([]),3e3).unref());return Promise.race([n().catch(()=>[]),r])}const Kd={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},qd=[{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}],Jd=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,Yd=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,Xd=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),Zd=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,Qd=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function $d(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(Qd(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}_])${Qd(e.find)}(?![\\p{L}\\p{N}_])`:Qd(e.find),`giu`)}));function a(e){let t=e;for(let e of qd)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(Jd,e=>Zd.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(Yd,e=>Xd.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 ef=e=>e.map(e=>JSON.stringify(e)).join(`
|
|
301
301
|
`)+`
|
|
302
|
-
`;function
|
|
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
|
|
304
|
-
`):``}const
|
|
305
|
-
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=
|
|
306
|
-
`):``}function
|
|
307
|
-
`);return
|
|
308
|
-
`)),Buffer.byteLength(l)>
|
|
309
|
-
`)}const
|
|
310
|
-
`):``}function
|
|
311
|
-
`):null}function np(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=tp(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function rp(e){let t=tp(e);if(!t)return null;let n=/<command-name>\s*\/?([^\s<]+)\s*<\/command-name>/.exec(t)?.[1];if(n){let e=/<command-args>([\s\S]*?)<\/command-args>/.exec(t)?.[1];return`/${n}${e?.trim()?` ${e.trim()}`:``}`}return/^\s*\/[^\s]/.test(t)?t.trimStart():null}async function ip(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function ap(e,t){let n=Gf(t);await ip(e,e=>n.take(e));let r=n.result();if(r.runs.length>0)return r;let i=_(e.replace(/\.jsonl$/,``),`subagents`),a=[];try{a=(await ce(i)).filter(e=>e.endsWith(`.jsonl`))}catch{return r}for(let e of a)await ip(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const op=`claude-code`,sp={outside:`not in a repository of your organizations'`,gone:`its folder is gone, and nothing it printed says which repository it was`,several:`its folder is gone, and what it printed names more than one repository`,empty:`nothing in it says when it was`,old:`older than ${rl.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were`},cp=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function lp(e){let t;try{t=await ce(e)}catch{return[]}let n=[];for(let r of t){let t;try{t=await ce(_(e,r))}catch{continue}for(let i of t){let t=i.replace(/\.jsonl$/,``);if(t===i||!wc.test(t))continue;let a=_(e,r,i),{mtimeMs:o,isFile:s}=await fe(a).then(e=>({mtimeMs:e.mtimeMs,isFile:e.isFile()}),()=>({mtimeMs:0,isFile:!1}));s&&n.push({file:a,sessionId:t,at:o})}}return n.sort((e,t)=>e.at-t.at)}async function up(e){let t=e.now??/* @__PURE__ */ new Date,n={sessions:[],skipped:{}},r=e=>{n.skipped[e]=(n.skipped[e]??0)+1};for(let{file:i,sessionId:a}of await lp(e.projectsDir)){let o=await dp(await ap(i,a),e,t);typeof o==`string`?r(o):n.sessions.push(o)}return n.sessions.sort((e,t)=>e.startedAt.localeCompare(t.startedAt)),n}async function dp(e,t,n=t.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<n.getTime()-rl.maxAgeDays*864e5)return`old`;let r=t.home??C(),i=e.cwd,a=await fp(e,i,r,t.known);if(typeof a==`string`)return a;let{place:o}=a,s=o.repository;if(await Al(e.sessionId))return`live`;let c={sessionId:e.sessionId,agent:op,machineId:t.machineId,machineName:t.machineName,imported:!0},l=[],u=(e,t)=>{let n=t.filter(e=>e!==null);n.length>0&&l.push({at:e,links:n})};u(e.startedAt,[sl(`repository`,s)]);for(let{branch:t,at:n}of e.branches)await Lc(i,t)||u(n,[sl(`branch`,`${s}#${t}`)]);for(let t of e.skills)t.command&&u(t.at,ml(t.command,s));for(let{command:t,stdout:n,at:r}of e.commands)u(r,_l(t,n,s));l.sort((e,t)=>e.at-t.at);let d=/* @__PURE__ */ new Set,f=[],p=(e,t,n)=>{for(let r=0;r===0||r<n.length;){let i=n.slice(r,r+rl.maxLinks);f.push({...c,type:e,occurredAt:hp(t),links:i}),r+=Math.max(i.length,1)}},m=e=>e.filter(e=>{let t=jl(e);return!d.has(t)&&(d.add(t),!0)}),h=m(l.filter(t=>t.at<=e.startedAt).flatMap(e=>e.links));p(`start`,e.startedAt,h);for(let{at:t,links:n}of l){if(t<=e.startedAt)continue;let r=m(n);r.length>0&&p(`seen`,t,r)}p(`end`,e.endedAt,[]);let g=[];for(let[n,a]of e.skills.entries()){let s=await ya(a.name,op,i,r);s&&g.push({...c,...Fc({...o,branch:pp(e,a.at)},t.known.skills[s.id]??null),id:gp(`${e.sessionId}\n${n}\n${a.at}\n${a.name}`),skillId:s.id,version:s.version,trigger:a.trigger,occurredAt:hp(a.at),sessionId:e.sessionId})}let _=await t.organizationOf({sessionId:e.sessionId,agent:op,cwd:i,projectLock:ba(i,r),repository:s,branch:e.branches[0]?.branch??null,registeredAt:hp(e.startedAt)});if(_===`unknown`)throw Error(`Couldn't ask agent kit which organization a session's repository is. Try again in a moment.`);let v=_?{...c,organizationId:_.organizationId,occurredAt:hp(e.endedAt),usage:mp(e)}:null;return{sessionId:e.sessionId,repository:s,placedByOutput:a.byOutput,startedAt:hp(e.startedAt),events:f,activations:g,usage:v}}async function fp(e,t,n,r){let i=await Pc(e.sessionId,t,n,r);if(i.audience&&i.repository)return{place:{...i,repository:i.repository},byOutput:!1};if(f(t))return`outside`;let[a,...o]=e.namedRepositories;if(!a)return ba(t,n)?`outside`:`gone`;if(o.length>0)return`several`;let s=`github.com/${a}`,c=r.repositories[s];return c?{place:{sessionId:e.sessionId,repository:s,branch:null,audience:{organizationId:c}},byOutput:!0}:`outside`}function pp(e,t){let n=null;for(let r of e.branches)r.at<=t&&(n=r.branch);return n??e.branches[0]?.branch??null}function mp(e){let t=[],n=e.runs.length>0?e.runs:[{start:e.startedAt,models:e.replies}];e.prompts>0&&t.push({metric:Z.prompts,model:null,skillId:null,start:hp(n[0]?.start??e.startedAt),value:e.prompts});for(let e of n)for(let[n,r]of Object.entries(e.models))for(let[i,a]of Object.entries(r))a>0&&t.push({metric:i,model:n,skillId:null,start:hp(e.start),value:a});return t.slice(0,tl.maxEntries)}const hp=e=>new Date(e).toISOString();function gp(e){let t=he(`sha256`).update(e).digest(`hex`),n=(parseInt(t[16],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-${n}${t.slice(17,20)}-${t.slice(20,32)}`}const _p=rl.maxPerRequest;async function vp(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=_p){let i=await e.reportSessionEvents(r.slice(t,t+_p));for(let e of i.live??[])n.add(e)}let i=t.sessions.filter(e=>!n.has(e.sessionId)),a=i.flatMap(e=>e.activations);for(let t=0;t<a.length;t+=100)await e.reportActivations(a.slice(t,t+100));let o=[],s=0;for(let t of i.flatMap(e=>e.usage?[e.usage]:[])){let n=JSON.stringify(t).length;o.length>0&&(o.length>=tl.maxPerRequest||s+n>409600)&&(await e.reportSessionUsage(o),o=[],s=0),o.push(t),s+=n}return o.length>0&&await e.reportSessionUsage(o),{sent:i,live:[...n]}}async function yp({dryRun:e}){let t=await H();if(!t)throw Error("Log in first with `a-kit login`.");if(!e&&(Bn()||(await U()).telemetry===!1))throw Error("Telemetry is off, so nothing is sent. Turn it on with `a-kit telemetry on`, or see what would be sent with `--dry-run`.");let n=z(B(),t.token),r=t.user.id,i=await fs(n,r,await ls(r),/* @__PURE__ */ new Date);if(!i)throw Error(`Couldn't ask agent kit which repositories are your organizations'. Try again in a moment.`);let a=Ll(async()=>({api:n,userId:r})),o=cp(),s=await up({projectsDir:o,known:i,organizationOf:e=>a.of(e),machineId:await xa(),machineName:ma()});if(e){for(let e of s.sessions)console.log(Cp(e));console.log(`\nWould send ${bp(s.sessions.length)} from ${o}. Nothing was sent.`),xp(s.sessions),Sp(s.skipped,`Would skip`),s.sessions.length>0&&console.log(`agent kit leaves a session live telemetry already sent as it is.`);return}let c=await vp({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e)},s);for(let e of c.sent)await kl(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await tu(e.usage,`sent`);F.success(`Sent ${bp(c.sent.length)} from ${o} to agent kit.`),xp(c.sent),Sp({...s.skipped,...c.live.length>0&&{live:(s.skipped.live??0)+c.live.length}},`Skipped`),console.log("Claude Code keeps about 30 days of sessions. `a-kit telemetry show <session-id>` shows what was sent for one.")}const bp=e=>`${e} session${e===1?``:`s`}`;function xp(e){let t=e.filter(e=>e.placedByOutput).length;t!==0&&console.log(t===1?`1 was placed by the one repository it named itself (its pull requests, gh output or git push), its folder being gone.`:`${t} were placed by the one repository each named itself (its pull requests, gh output or git push), their folder being gone.`)}function Sp(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${bp(r)}:`);for(let[e,t]of n)console.log(` ${t} ${sp[e]}`)}}function Cp(e){let t=new Set(e.events.flatMap(e=>e.links.map(jl))),n=e=>[...t].filter(t=>t.startsWith(`${e} `)).length,r=e.usage?.usage.filter(e=>e.metric===Z.costUsd).reduce((e,t)=>e+t.value,0),i=[`${n(`branch`)} branches`,`${n(`pull_request`)} pull requests`,`${n(`issue`)} issues`,`${n(`touched`)} issues and pull requests touched`,`${e.activations.length} skills loaded`,e.usage?r?`$${r.toFixed(2)}`:`usage`:`no usage (no organization of yours is its)`];return`${e.sessionId} ${e.startedAt} ${e.repository} ${i.join(`, `)}`}const wp={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 Tp(e,t,{port:n,dryRun:r=!1}={}){switch(e){case`on`:{n!==void 0&&await lo(Number(n)),await zn({telemetry:!0});let e=await No();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 zn({telemetry:!1}),await No(),await md({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 Dp(t);case`import`:return yp({dryRun:r});case void 0:case`status`:{let e=await U(),t=(await Io()).includes(`telemetry`),n=e.telemetry===!1?`off`:Bn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await co(),i=await dd(),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`}; ${wp[await Fo()]}.`),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, show or import.`)}}const Ep={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Dp(e){if(e){let[t,n]=await Promise.all([nu(e),Ol(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(`
|
|
312
|
-
`)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${
|
|
313
|
-
Nothing of what it used was sent.`);return}let t=await
|
|
302
|
+
`;function tf(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=nf(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(zi))]}}function nf(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:rf(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function rf(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 af=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function of(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=cf(o.cli_version)??r,i=cf(o.cwd)??i;else if(e.type===`turn_context`)n=cf(o.model)??n,i=cf(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=lf(o.content);if(!t.trim()||e===`user`&&af.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`?uf(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:df(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(zi))]}}function sf(e){try{let t=JSON.parse(e);return t.type===`session_meta`?cf(t.payload?.cwd):null}catch{return null}}const cf=e=>typeof e==`string`&&e?e:null;function lf(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
306
|
+
`):``}function uf(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function df(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 lf(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return df(t)}return JSON.stringify(e??``)}const ff=()=>process.env.CLAUDE_CONFIG_DIR??_(C(),`.claude`),pf=()=>process.env.CODEX_HOME??_(C(),`.codex`),mf=(e,t=ff())=>_(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function hf(e,t,n=process.cwd()){if(t&&f(t))return b(t);let r=e===`claude-code`?await vf(t,n):await yf(t,n);if(r)return r.file;throw Error(t?`No ${_f(e)} session "${t}" on this machine.`:`No ${_f(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function gf(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([vf(void 0,e),yf(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 _f=e=>e===`claude-code`?`Claude Code`:`Codex`;async function vf(e,t){if(e){let t=_(ff(),`projects`),n=await wf(t);for(let r of n){let n=_(t,r,`${e}.jsonl`);if(f(n))return{file:n,mtime:0}}return null}for(let e of Tf(t)){let t=mf(e),n=(await wf(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Cf(n.map(e=>_(t,e)))}return null}async function yf(e,t){let n=_(pf(),`sessions`),r=[],i=0;outer:for(let e of bf(await wf(n)))for(let t of bf(await wf(_(n,e))))for(let a of bf(await wf(_(n,e,t)))){let o=_(n,e,t,a);for(let e of await wf(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(_(o,e));if(r.length>=300||++i>=14)break outer}return xf(r,e,t)}const bf=e=>e.sort().reverse();async function xf(e,t,n){if(t){let n=e.find(e=>m(e).includes(t));return n?{file:n,mtime:0}:null}let r=Tf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await Sf(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 Cf(t)}return null}async function Sf(e){let t=await se(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 sf(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function Cf(e){let t=null;for(let n of e){let{mtimeMs:e}=await fe(n);(!t||e>t.mtime)&&(t={file:n,mtime:e})}return t}async function wf(e){try{return await ce(e)}catch{return[]}}function Tf(e){let t=[b(e)];for(;g(t.at(-1))!==t.at(-1);)t.push(g(t.at(-1)));return t}const Ef=2e3;function Df(e){let t=[...e.map],n=Af(()=>ee().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=Af(()=>w());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=Of();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=Af(()=>be(`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:C(),as:`~`}],maxToolText:e.fullOutputs?null:Ef}}function Of(){return Af(()=>be(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function kf(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 Af(e){try{return e()}catch{return null}}function jf(e,t,n){let r=new Set(t),i=/* @__PURE__ */ new Map;for(let t of n)for(let[n,a]of Object.entries(t.skills))Nf(a.agents,e)&&(i.has(n)||i.set(n,{name:n,skillId:a.id,version:a.version,triggered:r.has(n)}));for(let e of t)e===`report-session-issue`||i.has(e)||i.set(e,{name:e,skillId:null,version:null,triggered:!0});return i.delete(Ni),[...i.values()]}const Mf=[`codex`,`cursor`,`gemini-cli`],Nf=(e,t)=>e.length===0||e.includes(t)||Mf.includes(t)&&e.some(e=>Mf.includes(e));async function Pf(e){Wt(`agent kit report`);let t=await Ff(e.agent[0]),n=await hf(t,e.session||void 0),r=await O(n,`utf8`),i=Li(t===`claude-code`?tf(r):of(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=$d(Df({map:e.map?kf(await If(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Rf(e.title,`--title`,`a short title`)),s=a.text(Rf(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=ef(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=jf(t,i.loaded,u),f={title:o,note:s,expected:c,agent:t,agentVersion:i.agentVersion,model:i.model,skills:d,transcript:l},p=_(E(),`a-kit-report-${Date.now()}.jsonl`);if(await k(p,l),F.info([`${_f(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${Bf(d)}`,`Taken out: ${Vf(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
|
|
308
|
+
`)),Buffer.byteLength(l)>Kd.maxTranscriptBytes)throw Error(`The transcript is over ${Kd.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(!vn())throw Error(`Check the scrubbed transcript, then pass --yes to send it.`);if(!yn(await zt({message:`Send this report to agent kit?`}))){I(`Not sent.`);return}}let{api:m,credentials:h}=await to(),[g,v]=await Promise.all([m.listOrganizations(),m.listSkills()]),y=zf(e.org,g,v,d),b=await m.createReport(y.id,f);I(`Reported: ${h.webUrl}/app/orgs/${y.id}/reports/${b.id}`)}async function Ff(e){if(e===void 0)return gf();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 If=e=>e===`-`?Lf():O(e,`utf8`);async function Lf(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Rf(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function zf(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 Bf(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Vf(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${Ef} characters`:`${e} ×${t}`).join(`, `)}function Hf(e){return e&&e.total>0?e.passed/e.total:null}async function Uf(e){let{api:t,credentials:n}=await to(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(Wf(r,n.webUrl,i.length>1))}function Wf({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=>Nn({...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=Hf(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 Gf={inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadInputTokens:Z.cacheReadTokens,cacheCreationInputTokens:Z.cacheCreationTokens,costUSD:Z.costUsd},Kf={input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,cache_read_input_tokens:Z.cacheReadTokens,cache_creation_input_tokens:Z.cacheCreationTokens},qf=/^\{"type":"(api-request|atis-latch|queue-operation)/;function Jf(e){let t={sessionId:e,cwd:null,startedAt:null,endedAt:null,branches:[],skills:[],commands:[],prompts:0,turns:[],runs:[],replies:{},namedRepositories:[]},n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{let n=e.toLowerCase();t.namedRepositories.includes(n)||t.namedRepositories.push(n)},o=e=>{let n=e.message,i=typeof n?.id==`string`?n.id:null,a=typeof n?.model==`string`?n.model:null,o=n?.usage;if(!i||!a||a.startsWith(`<`)||r.has(i)||typeof o!=`object`||!o)return;r.add(i);let s=t.replies[a]??={};for(let[e,t]of Object.entries(Kf)){let n=o[e];typeof n==`number`&&n>0&&(s[t]=(s[t]??0)+n)}};return{take(r,{subagent:s=!1}={}){if(!r||qf.test(r))return;let c;try{c=JSON.parse(r)}catch{return}if(typeof c!=`object`||!c)return;if(s){c.type===`assistant`&&o(c);return}if(typeof c.sessionId==`string`&&c.sessionId!==e)return;c.type===`assistant`&&o(c);let l=typeof c.timestamp==`string`?Date.parse(c.timestamp):NaN;if(Number.isNaN(l)||(t.startedAt=Math.min(t.startedAt??l,l),t.endedAt=Math.max(t.endedAt??l,l)),!Number.isNaN(l)&&(c.type===`assistant`||c.type===`user`)){let e=t.turns.at(-1);!e||c.type===`user`&&!tp(c).some(e=>e.type===`tool_result`)?t.turns.push({start:l,end:l}):e.end=Math.max(e.end,l)}t.cwd===null&&typeof c.cwd==`string`&&c.cwd&&(t.cwd=c.cwd);let u=c.gitBranch;switch(typeof u==`string`&&u&&u!==`HEAD`&&!Number.isNaN(l)&&!t.branches.some(e=>e.branch===u)&&t.branches.push({branch:u,at:l}),c.type){case`cost-state`:ep(c,n);return;case`pr-link`:typeof c.prRepository==`string`&&Zf.test(c.prRepository)&&a(c.prRepository);return;case`assistant`:if(Number.isNaN(l))return;for(let e of tp(c)){if(e.type!==`tool_use`||typeof e.input!=`object`)continue;let n=e.input??{};if(e.name===`Skill`&&typeof n.skill==`string`){let e=n.skill.replace(/^\//,``),r=typeof n.args==`string`?n.args:null;t.skills.push({name:e,command:r===null?null:`/${e} ${r}`,trigger:`model`,at:l})}if(e.name!==`Bash`||typeof n.command!=`string`||typeof e.id!=`string`)continue;let r=Yf.test(n.command),a=Xf.test(n.command);(r||a)&&i.set(e.id,{command:n.command,at:l,gh:r,push:a})}return;case`user`:{for(let e of tp(c)){if(e.type!==`tool_result`||typeof e.tool_use_id!=`string`)continue;let n=i.get(e.tool_use_id);if(!n)continue;i.delete(e.tool_use_id);let r=np(c,e);if(n.gh){for(let e of r.matchAll(Qf))a(e[1]);t.commands.push({command:n.command,stdout:r,at:Number.isNaN(l)?n.at:l})}if(n.push){let e=`${r}\n${rp(c)}`;for(let t of e.matchAll($f))a(t[1])}}if(Number.isNaN(l)||!ap(c))return;t.prompts++;let e=op(c),n=e?.match(/^\/([^\s]+)/)?.[1];e&&n&&t.skills.push({name:n,command:e,trigger:`user`,at:l});return}}},result(){for(let{command:e,at:n,gh:r}of i.values())r&&t.commands.push({command:e,at:n,stdout:``});return i.clear(),t.commands.sort((e,t)=>e.at-t.at),t.runs=[...n.values()].sort((e,t)=>e.start-t.start),t}}}const Yf=/(^|[\s;&|(])gh\s/,Xf=/(^|[\s;&|(])git\s(?:[^;&|\n]*\s)?push\b/,Zf=/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/,Qf=/https:\/\/github\.com\/([A-Za-z0-9-]+\/[A-Za-z0-9._-]+)\/(?:pull|issues)\/\d+/g,$f=/^To (?:https:\/\/(?:[^@\s/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/]|github\.com:)([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?\s*$/gm;function ep(e,t){let n=e.startTime,r=e.modelUsage;if(typeof n!=`number`||typeof r!=`object`||!r)return;let i=t.get(n);i||t.set(n,i={start:n,models:{}});for(let[e,t]of Object.entries(r)){if(typeof t!=`object`||!t)continue;let n=i.models[e]??={};for(let[e,r]of Object.entries(Gf)){let i=t[e];typeof i==`number`&&i>(n[r]??0)&&(n[r]=i)}}}function tp(e){let t=e.message?.content;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e):[]}function np(e,t){let n=e.toolUseResult;if(typeof n==`object`&&n){let e=n.stdout;if(typeof e==`string`)return e}return typeof t.content==`string`?t.content:Array.isArray(t.content)?t.content.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(`
|
|
310
|
+
`):``}function rp(e){let t=e.toolUseResult;if(typeof t!=`object`||!t)return``;let n=t.stderr;return typeof n==`string`?n:``}function ip(e){let t=e.message?.content;if(typeof t==`string`)return t;let n=tp(e);if(n.some(e=>e.type===`tool_result`))return null;let r=n.filter(e=>e.type===`text`);return r.length>0?r.map(e=>typeof e.text==`string`?e.text:``).join(`
|
|
311
|
+
`):null}function ap(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=ip(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function op(e){let t=ip(e);if(!t)return null;let n=/<command-name>\s*\/?([^\s<]+)\s*<\/command-name>/.exec(t)?.[1];if(n){let e=/<command-args>([\s\S]*?)<\/command-args>/.exec(t)?.[1];return`/${n}${e?.trim()?` ${e.trim()}`:``}`}return/^\s*\/[^\s]/.test(t)?t.trimStart():null}async function sp(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function cp(e,t){let n=Jf(t);await sp(e,e=>n.take(e));let r=n.result();if(r.runs.length>0)return r;let i=_(e.replace(/\.jsonl$/,``),`subagents`),a=[];try{a=(await ce(i)).filter(e=>e.endsWith(`.jsonl`))}catch{return r}for(let e of a)await sp(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const lp=`claude-code`,up={outside:`not in a repository of your organizations'`,gone:`its folder is gone, and nothing it printed says which repository it was`,several:`its folder is gone, and what it printed names more than one repository`,empty:`nothing in it says when it was`,old:`older than ${ol.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were`},dp=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function fp(e){let t;try{t=await ce(e)}catch{return[]}let n=[];for(let r of t){let t;try{t=await ce(_(e,r))}catch{continue}for(let i of t){let t=i.replace(/\.jsonl$/,``);if(t===i||!wc.test(t))continue;let a=_(e,r,i),{mtimeMs:o,isFile:s}=await fe(a).then(e=>({mtimeMs:e.mtimeMs,isFile:e.isFile()}),()=>({mtimeMs:0,isFile:!1}));s&&n.push({file:a,sessionId:t,at:o})}}return n.sort((e,t)=>e.at-t.at)}async function pp(e){let t=e.now??/* @__PURE__ */ new Date,n={sessions:[],skipped:{}},r=e=>{n.skipped[e]=(n.skipped[e]??0)+1};for(let{file:i,sessionId:a}of await fp(e.projectsDir)){let o=await mp(await cp(i,a),e,t);typeof o==`string`?r(o):n.sessions.push(o)}return n.sessions.sort((e,t)=>e.startedAt.localeCompare(t.startedAt)),n}async function mp(e,t,n=t.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<n.getTime()-ol.maxAgeDays*864e5)return`old`;let r=t.home??C(),i=e.cwd,a=await hp(e,i,r,t.known);if(typeof a==`string`)return a;let{place:o}=a,s=o.repository;if(await Nl(e.sessionId))return`live`;let c={sessionId:e.sessionId,agent:lp,machineId:t.machineId,machineName:t.machineName,imported:!0},l=[],u=(e,t)=>{let n=t.filter(e=>e!==null);n.length>0&&l.push({at:e,links:n})};u(e.startedAt,[ul(`repository`,s)]);for(let{branch:t,at:n}of e.branches)await Lc(i,t)||u(n,[ul(`branch`,`${s}#${t}`)]);for(let t of e.skills)t.command&&u(t.at,_l(t.command,s));for(let{command:t,stdout:n,at:r}of e.commands)u(r,bl(t,n,s));l.sort((e,t)=>e.at-t.at);let d=/* @__PURE__ */ new Set,f=[],p=(e,t,n)=>{for(let r=0;r===0||r<n.length;){let i=n.slice(r,r+ol.maxLinks);f.push({...c,type:e,occurredAt:vp(t),links:i}),r+=Math.max(i.length,1)}},m=e=>e.filter(e=>{let t=Pl(e);return!d.has(t)&&(d.add(t),!0)}),h=m(l.filter(t=>t.at<=e.startedAt).flatMap(e=>e.links));p(`start`,e.startedAt,h);for(let{at:t,links:n}of l){if(t<=e.startedAt)continue;let r=m(n);r.length>0&&p(`seen`,t,r)}p(`end`,e.endedAt,[]);let g=[];for(let[n,a]of e.skills.entries()){let s=await ya(a.name,lp,i,r);s&&g.push({...c,...Fc({...o,branch:gp(e,a.at)},t.known.skills[s.id]??null),id:yp(`${e.sessionId}\n${n}\n${a.at}\n${a.name}`),skillId:s.id,version:s.version,trigger:a.trigger,occurredAt:vp(a.at),sessionId:e.sessionId})}let _=await t.organizationOf({sessionId:e.sessionId,agent:lp,cwd:i,projectLock:ba(i,r),repository:s,branch:e.branches[0]?.branch??null,registeredAt:vp(e.startedAt)});if(_===`unknown`)throw Error(`Couldn't ask agent kit which organization a session's repository is. Try again in a moment.`);let v=_?{...c,organizationId:_.organizationId,occurredAt:vp(e.endedAt),usage:_p(e)}:null;return{sessionId:e.sessionId,repository:s,placedByOutput:a.byOutput,startedAt:vp(e.startedAt),events:f,activations:g,usage:v}}async function hp(e,t,n,r){let i=await Pc(e.sessionId,t,n,r);if(i.audience&&i.repository)return{place:{...i,repository:i.repository},byOutput:!1};if(f(t))return`outside`;let[a,...o]=e.namedRepositories;if(!a)return ba(t,n)?`outside`:`gone`;if(o.length>0)return`several`;let s=`github.com/${a}`,c=r.repositories[s];return c?{place:{sessionId:e.sessionId,repository:s,branch:null,audience:{organizationId:c}},byOutput:!0}:`outside`}function gp(e,t){let n=null;for(let r of e.branches)r.at<=t&&(n=r.branch);return n??e.branches[0]?.branch??null}function _p(e){let t=[],n=e.runs.length>0?e.runs:[{start:e.startedAt,models:e.replies}];e.prompts>0&&t.push({metric:Z.prompts,model:null,skillId:null,start:vp(n[0]?.start??e.startedAt),value:e.prompts});for(let e of n)for(let[n,r]of Object.entries(e.models))for(let[i,a]of Object.entries(r))a>0&&t.push({metric:i,model:n,skillId:null,start:vp(e.start),value:a});let r=/* @__PURE__ */ new Map;for(let{start:t,end:n}of e.turns)for(let e=t;e<n;){let t=nl(e),i=Math.min(n,t+tl);r.set(t,(r.get(t)??0)+(i-e)/1e3),e=i}for(let[e,n]of r)t.push({metric:Z.agentSeconds,model:null,skillId:null,start:vp(e),end:vp(e+tl),value:n});return t.slice(0,rl.maxEntries)}const vp=e=>new Date(e).toISOString();function yp(e){let t=he(`sha256`).update(e).digest(`hex`),n=(parseInt(t[16],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-${n}${t.slice(17,20)}-${t.slice(20,32)}`}const bp=ol.maxPerRequest;async function xp(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=bp){let i=await e.reportSessionEvents(r.slice(t,t+bp));for(let e of i.live??[])n.add(e)}let i=t.sessions.filter(e=>!n.has(e.sessionId)),a=i.flatMap(e=>e.activations);for(let t=0;t<a.length;t+=100)await e.reportActivations(a.slice(t,t+100));let o=[],s=0;for(let t of i.flatMap(e=>e.usage?[e.usage]:[])){let n=JSON.stringify(t).length;o.length>0&&(o.length>=rl.maxPerRequest||s+n>409600)&&(await e.reportSessionUsage(o),o=[],s=0),o.push(t),s+=n}return o.length>0&&await e.reportSessionUsage(o),{sent:i,live:[...n]}}async function Sp({dryRun:e}){let t=await H();if(!t)throw Error("Log in first with `a-kit login`.");if(!e&&(Bn()||(await U()).telemetry===!1))throw Error("Telemetry is off, so nothing is sent. Turn it on with `a-kit telemetry on`, or see what would be sent with `--dry-run`.");let n=z(B(),t.token),r=t.user.id,i=await fs(n,r,await ls(r),/* @__PURE__ */ new Date);if(!i)throw Error(`Couldn't ask agent kit which repositories are your organizations'. Try again in a moment.`);let a=Bl(async()=>({api:n,userId:r})),o=dp(),s=await pp({projectsDir:o,known:i,organizationOf:e=>a.of(e),machineId:await xa(),machineName:ma()});if(e){for(let e of s.sessions)console.log(Ep(e));console.log(`\nWould send ${Cp(s.sessions.length)} from ${o}. Nothing was sent.`),wp(s.sessions),Tp(s.skipped,`Would skip`),s.sessions.length>0&&console.log(`agent kit leaves a session live telemetry already sent as it is.`);return}let c=await xp({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e)},s);for(let e of c.sent)await Ml(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await iu(e.usage,`sent`);F.success(`Sent ${Cp(c.sent.length)} from ${o} to agent kit.`),wp(c.sent),Tp({...s.skipped,...c.live.length>0&&{live:(s.skipped.live??0)+c.live.length}},`Skipped`),console.log("Claude Code keeps about 30 days of sessions. `a-kit telemetry show <session-id>` shows what was sent for one.")}const Cp=e=>`${e} session${e===1?``:`s`}`;function wp(e){let t=e.filter(e=>e.placedByOutput).length;t!==0&&console.log(t===1?`1 was placed by the one repository it named itself (its pull requests, gh output or git push), its folder being gone.`:`${t} were placed by the one repository each named itself (its pull requests, gh output or git push), their folder being gone.`)}function Tp(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${Cp(r)}:`);for(let[e,t]of n)console.log(` ${t} ${up[e]}`)}}function Ep(e){let t=new Set(e.events.flatMap(e=>e.links.map(Pl))),n=e=>[...t].filter(t=>t.startsWith(`${e} `)).length,r=e.usage?.usage.filter(e=>e.metric===Z.costUsd).reduce((e,t)=>e+t.value,0),i=[`${n(`branch`)} branches`,`${n(`pull_request`)} pull requests`,`${n(`issue`)} issues`,`${n(`touched`)} issues and pull requests touched`,`${e.activations.length} skills loaded`,e.usage?r?`$${r.toFixed(2)}`:`usage`:`no usage (no organization of yours is its)`];return`${e.sessionId} ${e.startedAt} ${e.repository} ${i.join(`, `)}`}const Dp={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 Op(e,t,{port:n,dryRun:r=!1}={}){switch(e){case`on`:{n!==void 0&&await lo(Number(n)),await zn({telemetry:!0});let e=await No();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 zn({telemetry:!1}),await No(),await _d({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 Ap(t);case`import`:return Sp({dryRun:r});case void 0:case`status`:{let e=await U(),t=(await Io()).includes(`telemetry`),n=e.telemetry===!1?`off`:Bn()?`off in this environment (DO_NOT_TRACK or AGENT_KIT_TELEMETRY)`:`on`,{port:r}=await co(),i=await md(),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`}; ${Dp[await Fo()]}.`),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, show or import.`)}}const kp={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Ap(e){if(e){let[t,n]=await Promise.all([au(e),jl(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(`
|
|
312
|
+
`)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${kp[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
|
|
313
|
+
Nothing of what it used was sent.`);return}let t=await ou();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} ${kp[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function jp(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 Ip();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Fp(t.skillVersion),o=t.model??`claude-sonnet-5-5`,{api:s}=await to(),c=Dn(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)=>Mp(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;Pp(await d(!0,e=>{m||u(`With ${Nn(l)} v${a??l.version}`),m=!0,Np(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Np(e,l.name);Pp(h)}async function Mp(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 Np(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 Pp(e){if(typeof e==`string`){console.log(`\n\n${e}`);return}let t=mn(e.stopReason);t&&console.log(`\n\n${t}`),console.log(`\n\n${fn(e.usage)}`)}function Fp(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 Ip(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const Lp=`a-kit ${nn}: your agent kit skills, in your agents.
|
|
314
314
|
|
|
315
315
|
Usage
|
|
316
316
|
a-kit init Log in and pick skills to install
|
|
@@ -373,4 +373,4 @@ Report options (the report-session-issue skill passes them for you)
|
|
|
373
373
|
--org <id|name> The organization, when it can't tell
|
|
374
374
|
--full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
|
|
375
375
|
--dry-run Scrub and show what would be sent, without sending
|
|
376
|
-
`;async function
|
|
376
|
+
`;async function Rp(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Ud.has(e))return Wd(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(nn);let[i,...a]=r;if(n.help||!i)return console.log(Lp);if(!en(n.channel))throw Error(`Unknown channel "${n.channel}". Use one of: ${Qt.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 ud(o);case`add`:case`install`:return Ko(a,o);case`update`:return ms(o);case`list`:case`ls`:return kd();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Uf(a);case`health`:return ld(a);case`check`:return el(a);case`link`:return Cd(a,o);case`login`:return n.token?Rd():Ld();case`logout`:return Vd();case`whoami`:return Hd();case`try`:return jp(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return Pf({...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 Op(a[0],a[1],{port:n.port,dryRun:n[`dry-run`]});case`auto-update`:return _s(a[0]);case`heartbeat`:return dd(a[0],n.api);case`org`:return Id(a[0],a.slice(1).join(` `)||n.org);case`machine`:return Pd(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return yd(a[0],n.api,a[1]);case`collector`:return Su(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}Rp().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
|