useakit 0.2.0-dev.113 → 0.2.0-dev.114
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/index.mjs +28 -26
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -99,6 +99,8 @@ The repository (its `origin` remote) and the branch you're on go too, and with y
|
|
|
99
99
|
|
|
100
100
|
From any other repo, neither is sent. The hook decides from a list of the projects' repositories kept in `~/.config/agent-kit/`, never waiting for the API: it's asked for again once a day, so a repository added to a project starts sending within a day, or right away after `a-kit update`.
|
|
101
101
|
|
|
102
|
+
At the end of each turn, a session in a repo of your organization also sends its profile, for your organization to see on the session's page, the Profiler and the machine's page: the skills and agents it called and how each ran (inline, in a fresh context, as a copy of its caller's, or in the background), when each started, how long it took and whether it failed, each context's tokens, and how many times every other tool ran, for how long and how often it failed. It sends names: of every skill called, your personal and plugins' ones included, of every agent type, and of every tool, an MCP server's as `mcp__<server>__<tool>`. Never a prompt, a response, a call's arguments or result, a command or a file path.
|
|
103
|
+
|
|
102
104
|
```sh
|
|
103
105
|
a-kit telemetry # whether it's on
|
|
104
106
|
a-kit telemetry off # stop reporting and remove its hooks
|
|
@@ -109,14 +111,14 @@ a-kit telemetry on # turn it back on
|
|
|
109
111
|
|
|
110
112
|
### Importing past sessions
|
|
111
113
|
|
|
112
|
-
Claude Code keeps a transcript of each session on your machine for about 30 days (`~/.claude/projects`, or under `CLAUDE_CONFIG_DIR`). `a-kit telemetry import` sends agent kit what live telemetry would have sent for each of them, so your organization sees the last month's work without waiting for new sessions: when each session started and ended, its repository and branches, the pull requests and issues its `gh` commands opened or changed, the issue a skill was started for, the skills from agent kit it loaded,
|
|
114
|
+
Claude Code keeps a transcript of each session on your machine for about 30 days (`~/.claude/projects`, or under `CLAUDE_CONFIG_DIR`). `a-kit telemetry import` sends agent kit what live telemetry would have sent for each of them, so your organization sees the last month's work without waiting for new sessions: when each session started and ended, its repository and branches, the pull requests and issues its `gh` commands opened or changed, the issue a skill was started for, the skills from agent kit it loaded, its tokens, cost and prompts by model, each at the time it happened, and its profile.
|
|
113
115
|
|
|
114
116
|
```sh
|
|
115
117
|
a-kit telemetry import --dry-run # what it would send, sending nothing
|
|
116
118
|
a-kit telemetry import # send it
|
|
117
119
|
```
|
|
118
120
|
|
|
119
|
-
The same rules as live telemetry apply: only a session in a repository of your organizations' is sent, and nothing of the others leaves the machine; a session whose folder is gone (a worktree removed since) is in the repository its own output names, when it names one only: the pull request and issue URLs its `gh` commands printed, the remote its `git push` printed, or the pull requests Claude Code tied it to; no prompt, response, command, file path or tool output is ever sent. A session keeps its id, so importing twice changes nothing, and a session live telemetry already sent is left as it is. A bot logged in with `a-kit login --token` imports its own sessions as itself. `a-kit telemetry show <session-id>` shows what was sent for an imported session, like a live one.
|
|
121
|
+
The same rules as live telemetry apply: only a session in a repository of your organizations' is sent, and nothing of the others leaves the machine; a session whose folder is gone (a worktree removed since) is in the repository its own output names, when it names one only: the pull request and issue URLs its `gh` commands printed, the remote its `git push` printed, or the pull requests Claude Code tied it to; no prompt, response, command, file path or tool output is ever sent. A session keeps its id, so importing twice changes nothing, and a session live telemetry already sent is left as it is, but for its profile, which is the whole of it and replaces the one live telemetry sent. A bot logged in with `a-kit login --token` imports its own sessions as itself. `a-kit telemetry show <session-id>` shows what was sent for an imported session, like a live one.
|
|
120
122
|
|
|
121
123
|
## Heartbeat
|
|
122
124
|
|
package/dist/index.mjs
CHANGED
|
@@ -71,8 +71,8 @@ ${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.
|
|
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)+`
|
|
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.114`;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
|
+
`),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}),reportSessionProfiles:(e,t)=>i(`/agent-sessions/profiles`,{method:`POST`,body:JSON.stringify({profiles: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(`
|
|
78
78
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),or=/* @__PURE__ */ A((e=>{var t=K(),n=ir();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=/* @__PURE__ */ new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=/* @__PURE__ */ new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=/* @__PURE__ */ Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),sr=/* @__PURE__ */ A((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),cr=/* @__PURE__ */ A((e=>{var t=K();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),lr=/* @__PURE__ */ A((e=>{var t=sr(),n=K(),r=cr();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:/* @__PURE__ */ new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),ur=/* @__PURE__ */ A((e=>{var t=or(),n=ir(),r=K(),i=lr(),a=cr(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
|
|
@@ -287,30 +287,32 @@ 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=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
|
|
291
|
-
`)
|
|
292
|
-
`)}
|
|
293
|
-
`)
|
|
294
|
-
`)
|
|
295
|
-
`)
|
|
296
|
-
`)
|
|
297
|
-
`)}async function
|
|
298
|
-
|
|
299
|
-
`)
|
|
300
|
-
`))
|
|
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:10,maxContexts:500,maxCalls:2e3,maxTools:5e3,maxAgeDays:rl.maxAgeDays,maxFutureMs:rl.maxFutureMs,maxMachineNameLength:rl.maxMachineNameLength,maxIdLength:128,maxNameLength:200,maxValue:0xe8d4a51000},sl={inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadInputTokens:Z.cacheReadTokens,cacheCreationInputTokens:Z.cacheCreationTokens,costUSD:Z.costUsd},cl={input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,cache_read_input_tokens:Z.cacheReadTokens,cache_creation_input_tokens:Z.cacheCreationTokens},ll=/^\{"type":"(api-request|atis-latch|queue-operation)/;function ul(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(cl)){let n=o[e];typeof n==`number`&&n>0&&(s[t]=(s[t]??0)+n)}};return{take(r,{subagent:s=!1}={}){if(!r||ll.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`&&!_l(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`:gl(c,n);return;case`pr-link`:typeof c.prRepository==`string`&&pl.test(c.prRepository)&&a(c.prRepository);return;case`assistant`:if(Number.isNaN(l))return;for(let e of _l(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=dl.test(n.command),a=fl.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 _l(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=vl(c,e);if(n.gh){for(let e of r.matchAll(ml))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${yl(c)}`;for(let t of e.matchAll(hl))a(t[1])}}if(Number.isNaN(l)||!xl(c))return;t.prompts++;let e=Sl(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 dl=/(^|[\s;&|(])gh\s/,fl=/(^|[\s;&|(])git\s(?:[^;&|\n]*\s)?push\b/,pl=/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/,ml=/https:\/\/github\.com\/([A-Za-z0-9-]+\/[A-Za-z0-9._-]+)\/(?:pull|issues)\/\d+/g,hl=/^To (?:https:\/\/(?:[^@\s/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/]|github\.com:)([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?\s*$/gm;function gl(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(sl)){let i=t[e];typeof i==`number`&&i>(n[r]??0)&&(n[r]=i)}}}function _l(e){let t=e.message?.content;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e):[]}function vl(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(`
|
|
291
|
+
`):``}function yl(e){let t=e.toolUseResult;if(typeof t!=`object`||!t)return``;let n=t.stderr;return typeof n==`string`?n:``}function bl(e){let t=e.message?.content;if(typeof t==`string`)return t;let n=_l(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(`
|
|
292
|
+
`):null}function xl(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=bl(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function Sl(e){let t=bl(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 Cl(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function wl(e,t){let n=ul(t);await Cl(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 Cl(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const Tl=(e,t=null)=>({context:e,meta:t,startedAt:null,endedAt:null,calls:/* @__PURE__ */ new Map,running:/* @__PURE__ */ new Map,tools:/* @__PURE__ */ new Map,typed:null}),El=/* @__PURE__ */ new Set([`Skill`,`Agent`]);function Dl(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=Tl({id:`root`,parentCallId:null,kind:`root`,background:!1,newTokens:0,cachedTokens:0,outputTokens:0}),i=[r],a=/* @__PURE__ */ new Map;function o(t,r){if(r.type!==`assistant`&&r.type!==`user`)return;if(typeof r.uuid==`string`){let e=n.get(r.uuid);if(e&&e!==t)return;n.set(r.uuid,t)}if(typeof r.sessionId==`string`&&r.sessionId!==e)return;let i=typeof r.timestamp==`string`?Date.parse(r.timestamp):NaN;Number.isNaN(i)||(r.type!==`assistant`||u(t,r))&&(t.startedAt=Math.min(t.startedAt??i,i),t.endedAt=Math.max(t.endedAt??i,i),r.type===`assistant`?s(t,r,i):c(t,r,i))}function s(e,t,n){let r=e.typed;r&&(e.typed=null,t.attributionSkill===r.name&&e.calls.set(r.id,{id:r.id,contextId:e.context.id,kind:`skill`,name:r.name,mode:`inline`,openedContextId:null,at:r.at,endedAt:r.loadedAt??r.at,failed:!1,agentId:null,background:null}));for(let r of _l(t)){if(r.type!==`tool_use`||!Il(r.id))continue;if(!El.has(String(r.name))){Fl(r.name)&&e.running.set(r.id,{name:r.name,at:n});continue}let t=r.input??{},i={id:r.id,contextId:e.context.id,openedContextId:null,at:n,endedAt:null,failed:!1,agentId:null,background:null};if(r.name===`Skill`&&typeof t.skill==`string`){let n=t.skill.replace(/^\//,``);if(!Fl(n))continue;e.calls.set(r.id,{...i,kind:`skill`,name:n,mode:`inline`})}else if(r.name===`Agent`){let n=Fl(t.subagent_type)?t.subagent_type:`general-purpose`;e.calls.set(r.id,{...i,kind:`agent`,name:n,mode:`fresh`})}}}function c(e,t,n){if(e===r)for(let e of Ml(t,n))a.has(e.agentId)||a.set(e.agentId,e);for(let r of _l(t)){if(r.type!==`tool_result`||typeof r.tool_use_id!=`string`)continue;let i=r.is_error===!0||Nl(t),a=e.running.get(r.tool_use_id);if(a){e.running.delete(r.tool_use_id),l(e,a.name,Math.max(n-a.at,0),i);continue}let o=e.calls.get(r.tool_use_id);if(!o||o.endedAt!==null)continue;o.endedAt=Math.max(n,o.at),o.failed=i;let s=Rl(t);o.kind===`agent`?(o.agentId=zl(s.agentId)?s.agentId:Bl(r),s.status===`async_launched`?o.background=!0:s.status===`completed`&&(o.background=!1)):s.status===`forked`&&zl(s.agentId)&&(o.agentId=s.agentId)}if(t.isMeta){e.typed&&e.typed.loadedAt===null&&(e.typed.loadedAt=n);return}if(!xl(t))return;e.typed=null;let i=Sl(t)?.match(/^\/([^\s]+)/)?.[1],o=t.uuid;i&&Fl(i)&&Il(o)&&(e.typed={id:o,name:i,at:n,loadedAt:null})}function l(e,t,n,r){let i=e.tools.get(t)??{contextId:e.context.id,name:t,count:0,totalMs:0,maxMs:0,failures:0};i.count+=1,i.totalMs+=n,i.maxMs=Math.max(i.maxMs,n),r&&(i.failures+=1),e.tools.set(t,i)}function u(e,n){let r=n.message?.id;if(typeof r!=`string`)return!0;let i=t.get(r);return i?i===e:(t.set(r,e),d(e,n),!0)}function d(e,t){let n=t.message,r=typeof n?.model==`string`?n.model:null;if(!r||r.startsWith(`<`))return;let i=n?.usage;if(typeof i!=`object`||!i)return;let a=e=>{let t=i[e];return typeof t==`number`&&t>0?t:0};e.context.newTokens+=a(`input_tokens`)+a(`cache_creation_input_tokens`),e.context.cachedTokens+=a(`cache_read_input_tokens`),e.context.outputTokens+=a(`output_tokens`)}function f(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map;for(let n of i.flatMap(e=>[...e.calls.values()]))e.set(n.id,n),n.agentId&&t.set(n.agentId,n);let n=/* @__PURE__ */ new Map,r=i.slice(1).map(r=>{let i=r.meta??{},a=Il(i.toolUseId)?i.toolUseId:null,o=a&&e.get(a)||t.get(r.context.id),s=Fl(i.agentType)?i.agentType:null,c={state:r,agentType:s,context:{...r.context,parentCallId:o?.id??a,kind:o?.kind!==`skill`&&s===`fork`?`copy`:`fresh`,background:o?.background??i.requestShape===`background`}};return o&&n.set(o.id,c),c}),o=e=>{let t=n.get(e.id);if(e.kind===`skill`&&!t)return e;let r=e.kind===`agent`&&t?.agentType||e.name,i=t?.context.background??e.background?`background`:t?.context.kind??(r===`fork`?`copy`:`fresh`);return{...e,...i===`background`&&s(e,t?.state??null),name:r,mode:i,openedContextId:t?.context.id??null}},s=(e,t)=>{let n=t?.context.id??e.agentId,r=n?a.get(n):void 0;return r?{endedAt:Math.max(r.durationMs===null?r.at:e.at+r.durationMs,e.at),failed:r.status===`failed`}:t?.endedAt==null||e.contextId===`root`&&t.meta?.finished!==!0?{endedAt:null,failed:!1}:{endedAt:Math.max(t.endedAt,e.at),failed:e.failed}};return{subagents:r,callOf:o}}return{take(e){let t=jl(e);t&&o(r,t)},subagent(e,t){let n=Tl({id:e,parentCallId:null,kind:`fresh`,background:!1,newTokens:0,cachedTokens:0,outputTokens:0},t);return i.push(n),e=>{let t=jl(e);t&&o(n,t)}},result(){if(r.startedAt===null)return null;let{subagents:e,callOf:t}=f(),n=[{state:r,context:r.context},...e.sort((e,t)=>(e.state.startedAt??1/0)-(t.state.startedAt??1/0)||e.context.id.localeCompare(t.context.id))].slice(0,ol.maxContexts),a=new Set(n.map(({context:e})=>e.id)),o=i.flatMap(e=>[...e.calls.values()]).filter(e=>a.has(e.contextId)).sort((e,t)=>e.at-t.at).slice(0,ol.maxCalls).map(t).map(({at:e,endedAt:t,failed:n,agentId:r,background:i,...o})=>({...o,openedContextId:o.openedContextId&&a.has(o.openedContextId)?o.openedContextId:null,startedAt:Ll(e),durationMs:t===null?null:t-e,status:t===null?`running`:n?`failed`:`ok`}));return{startedAt:Ll(r.startedAt),contexts:n.map(({state:e,context:t})=>({...t,startedAt:e.startedAt===null?null:Ll(e.startedAt),endedAt:e.endedAt===null?null:Ll(e.endedAt)})),calls:o,tools:n.flatMap(({state:e})=>[...e.tools.values()].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))).slice(0,ol.maxTools).map(e=>({...e}))}}}}async function Ol(e,t){let n=Dl(t);await Cl(e,e=>n.take(e));let r=_(e.replace(/\.jsonl$/,``),`subagents`),i=[];try{i=await ce(r)}catch{}let a=[];for(let e of i){let t=/^agent-(a[0-9a-f]+)\.jsonl$/.exec(e)?.[1];t&&a.push({id:t,meta:await kl(r,t)})}let o=({meta:e})=>typeof e.spawnDepth==`number`?e.spawnDepth:1;a.sort((e,t)=>o(e)-o(t));for(let{id:e,meta:t}of a)await Cl(_(r,`agent-${e}.jsonl`),n.subagent(e,t));return n.result()}async function kl(e,t){try{let n=JSON.parse(await O(_(e,`agent-${t}.meta.json`),`utf8`));return typeof n==`object`&&n?n:{}}catch{return{}}}const Al=(e,t)=>({...t,occurredAt:e.startedAt,contexts:e.contexts,calls:e.calls,tools:e.tools});function jl(e){if(!e||ll.test(e))return null;try{let t=JSON.parse(e);return typeof t==`object`&&t?t:null}catch{return null}}function Ml(e,t){let n=e.message?.content;if(!(e.origin?.kind===`task-notification`||typeof n==`string`&&n.trimStart().startsWith(`<task-notification`)))return[];let r=typeof n==`string`?n:Array.isArray(n)?n.map(e=>e?.type===`text`&&typeof e.text==`string`?e.text:``).join(`
|
|
293
|
+
`):``;if(!r.includes(`<task-notification>`))return[];let i=[];for(let[,e]of r.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)){let n=/^\s*<task-id>(a[0-9a-f]+)<\/task-id>/.exec(e)?.[1],r=/<status>(\w+)<\/status>/.exec(e)?.[1];if(!n||!Il(n)||!r)continue;let a=[...e.matchAll(/<usage>([\s\S]*?)<\/usage>/g)].at(-1)?.[1],o=a&&/<duration_ms>(\d+)<\/duration_ms>/.exec(a)?.[1];i.push({agentId:n,at:t,status:r,durationMs:o?Number(o):null})}return i}function Nl(e){let t=e.toolUseResult;return typeof t==`object`&&!!t&&t.success===!1}const Pl=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t&&!/[\s\u0000-\u001f\u007f]/.test(e),Fl=e=>Pl(e,ol.maxNameLength),Il=e=>Pl(e,ol.maxIdLength),Ll=e=>new Date(e).toISOString();function Rl(e){let t=e.toolUseResult;return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}const zl=e=>Il(e)&&/^a[0-9a-f]+$/.test(e);function Bl(e){let t=e.content;return[...(typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e?.text==`string`?e.text:``).join(`
|
|
294
|
+
`):``).matchAll(/\bagentId: (a[0-9a-f]+)\b/g)].at(-1)?.[1]??null}const Vl=/^[A-Z][A-Z0-9_]{1,9}-[1-9]\d*$/,Hl={maxPerRequest:100,maxLinks:50,maxAgeDays:Cc.maxAgeDays,maxFutureMs:Cc.maxFutureMs,maxMachineNameLength:Cc.maxMachineNameLength,maxUrlLength:500,maxThreadLength:200},Ul=/^[1-9][0-9]{0,8}$/,Wl=/\s/,Gl=/^https:\/\/(?:[a-z0-9-]+\.)*slack\.com(?:\/[^\s\u0000-\u001f\u007f]*)?$/i;function Kl(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`:{if(e===`issue`&&Vl.test(n))return{kind:e,value:n};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):Ul.test(i))?{kind:e,value:`${r}#${i}`}:null}case`slack_thread`:return Jl(n)?{kind:e,value:n}:null;case`thread`:return n&&n.length<=Hl.maxThreadLength&&!Wl.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 ql(e){let t=e.trim();return Kl(`slack_thread`,t)??Kl(`thread`,t)}function Jl(e){return e.length<=Hl.maxUrlLength&&Gl.test(e)}const Yl=()=>_(V(),`sessions`),Xl=()=>_(V(),`pending-session-events.jsonl`),Zl=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function Ql(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(`
|
|
295
|
+
`)[0]??``,r=/^\/[^\s]+(.*)$/.exec(n)?.[1]?.trim(),i=r&&/^(?:[a-z][a-z-]*\s+)?(\S+)$/.exec(r)?.[1];if(!i)return[];let a=eu.exec(i)?.[1]??i;if(Vl.test(a))return[{kind:`issue`,value:a}];let o=nu(i,t,e=>e===`pull`?`pull_request`:`issue`);return o?[o]:[]}const eu=/^https:\/\/[a-z0-9-]+\.atlassian\.net\/browse\/([^\s/?#]+)(?:[/?#]\S*)?$/i,tu=/^https:\/\/([^\s/]+\/[^\s/]+\/[^\s/?#]+)\/(issues|pull)\/(\d+)(?:[/?#]\S*)?$/;function nu(e,t,n){let r=tu.exec(e);return r?Kl(n(r[2]),`${r[1]}#${r[3]}`):t&&/^#?\d+$/.test(e)?Kl(n(null),`${t}#${e.replace(`#`,``)}`):null}function ru(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=su(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(Kl(o===`pr`?`pull_request`:`touched`,`${e[1]}#${e[2]}`));continue}if(o!==`issue`&&o!==`pr`||!(o===`issue`?iu:au).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=ou(t));continue}let r=c[e-1]??``;u||t.startsWith(`-`)||r.startsWith(`-`)&&!r.includes(`=`)||(/^#?\d+$/.test(t)||tu.test(t))&&(u=t)}u&&i(nu(u,l,()=>`touched`))}return r}const iu=/* @__PURE__ */ new Set([`comment`,`edit`,`close`,`reopen`]),au=/* @__PURE__ */ new Set([`comment`,`edit`]),ou=e=>e.split(`/`).length===2?`github.com/${e}`:e;function su(e){let t=[];for(let[,n,r,i]of e.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'|((?:[^\s"'\\]|\\.)+)/g))t.push(n??r??i??``);return t}function cu(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 lu(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 uu(e,t,n,r,i,{env:a=process.env,now:o=/* @__PURE__ */ new Date,clearedWaitMs:s=2e3}={}){let c=Ql(t,n),l=i.sessionId;if(!c||!l||!wc.test(l))return null;c===`end`&&t.reason===`clear`&&await bu(r,l,o);let u=[],d=e=>{e&&u.push(e)};c!==`end`&&i.repository&&(d(Kl(`repository`,i.repository)),i.branch&&!await Lc(r,i.branch)&&d(Kl(`branch`,`${i.repository}#${i.branch}`)));let f=c!==`end`&&i.audience!==null,p=lu(t);if(p&&f)for(let e of $l(p,i.repository))d(e);let m=cu(t);if(m&&f)for(let e of ru(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(ql(t));if(t.source===`clear`){let e=await xu(r,l,o,s);e&&d(Kl(`session`,e))}}let h=await pu(l),g=u.map(_u),_=g.some(e=>!h.links.includes(e));return c===`seen`&&!_&&o.getTime()-h.sentAt<3e5?null:(await vu(l,{sentAt:o.getTime(),links:[.../* @__PURE__ */ new Set([...h.links,...g])]}),c===`start`&&await Su(o),{sessionId:l,agent:e,machineId:await xa(),machineName:ma(),type:c,occurredAt:o.toISOString(),links:u})}const du=(e,t=[])=>ha(Xl(),e,t),fu=e=>_(Yl(),`${Zl(e)}.json`);async function pu(e){try{let t=JSON.parse(await O(fu(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 mu=async e=>(await pu(e)).links;async function hu(e,t){let n=await pu(e);await vu(e,{sentAt:n.sentAt,links:[.../* @__PURE__ */ new Set([...n.links,...t.map(_u)])],imported:!0})}async function gu(e){try{return JSON.parse(await O(fu(e),`utf8`)).imported!==!0}catch{return!1}}const _u=e=>`${e.kind} ${e.value}`;async function vu(e,t){await D(Yl(),{recursive:!0,mode:448}),await k(fu(e),JSON.stringify(t)+`
|
|
296
|
+
`)}const yu=e=>_(Yl(),`cleared-${Zl(e)}.json`);async function bu(e,t,n){await D(Yl(),{recursive:!0,mode:448}),await k(yu(e),JSON.stringify({sessionId:t,at:n.getTime()})+`
|
|
297
|
+
`)}async function xu(e,t,n,r){let i=yu(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 Su(e){try{for(let t of await ce(Yl())){let n=_(Yl(),t),{mtimeMs:r}=await fe(n);e.getTime()-r>6048e5&&await de(n,{force:!0})}}catch{}}function Cu(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&&wu(n,i,a,u))??(!d||l(u)?null:`unknown`)}}}function wu(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 Tu={"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 Eu(e){let t=[];for(let n of Au(Q(e,`resourceMetrics`)))for(let e of Au(Q(n,`scopeMetrics`)))for(let n of Au(Q(e,`metrics`))){let e=Q(n,`name`),r=typeof e==`string`?Tu[e]:void 0,i=Q(n,`sum`);if(!r||!i)continue;let a=Q(i,`aggregationTemporality`)===2;for(let n of Au(Q(i,`dataPoints`))){let i=Au(Q(n,`attributes`)),o=e=>ju(i,e),s=o(`session.id`),c=typeof r==`string`?r:r[o(`type`)??``],l=Mu(Q(n,`asDouble`)??Q(n,`asInt`)),u=Nu(Q(n,`startTimeUnixNano`)),d=Nu(Q(n,`timeUnixNano`));s&&c&&l!==null&&u!==null&&d!==null&&t.push({kind:`point`,sessionId:s,series:Ou(e,i,a?u:null),metric:c,model:ku(o(`model`)),skillName:o(`skill.name`),cumulative:a,start:u,at:d,value:l})}}return t}function Du(e){let t=[];for(let n of Au(Q(e,`resourceLogs`)))for(let e of Au(Q(n,`scopeLogs`)))for(let n of Au(Q(e,`logRecords`))){let e=Au(Q(n,`attributes`)),r=ju(e,`event.name`)??Q(Q(n,`body`),`stringValue`);if(r!==`user_prompt`&&r!==`claude_code.user_prompt`)continue;let i=ju(e,`session.id`),a=Nu(Q(n,`timeUnixNano`))??Nu(Q(n,`observedTimeUnixNano`));i&&a!==null&&t.push({kind:`prompt`,sessionId:i,at:a})}return t}function Ou(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 ku=e=>al(e)?e:null,Q=(e,t)=>typeof e==`object`&&e&&!Array.isArray(e)?e[t]:void 0,Au=e=>Array.isArray(e)?e:[];function ju(e,t){let n=e.find(e=>e.key===t)?.value?.stringValue;return typeof n==`string`&&n?n:null}function Mu(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function Nu(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 Pu=e=>he(`sha256`).update(e).digest(`hex`).slice(0,32);function Fu(e){let t=()=>_(ao(),e),n=e=>_(t(),`${Pu(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)+`
|
|
298
|
+
`)},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 Iu=Fu(`sessions`),Lu=e=>Iu.write(e.sessionId,e);async function Ru(e){let t=await Iu.read(e);return t?.sessionId===e?t:null}const zu=(e=Date.now())=>Iu.forgetOld(e),Bu=Fu(`sent`),Vu=(e,t,n=/* @__PURE__ */ new Date)=>Bu.write(e.sessionId,{at:n.toISOString(),status:t,record:e}),Hu=e=>Bu.read(e),Uu=async()=>(await Bu.list()).sort((e,t)=>t.at.localeCompare(e.at)),Wu=(e=Date.now())=>Bu.forgetOld(e),Gu=(e,t)=>({sessionId:e,epoch:t,series:{},slices:{},prompts:0,lastAt:t});function Ku(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 qu(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 Ju=Fu(`state`);function Yu(e=()=>Date.now()){let t=/* @__PURE__ */ new Map,n=n=>{let r=t.get(n);return r||(r=Xu(n,e()),t.set(n,r)),r};return{async observe(e){for(let t of e){let e=await n(t.sessionId);Ku(e.state,t)&&(e.state.unsent=!0,e.unsaved=!0)}},async resume(){for(let e of await Ju.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 Ju.write(e.state.sessionId,e.state))}}}async function Xu(e,t){let n=await Ju.read(e);return n?.sessionId===e&&typeof n.series==`object`?{state:n,unsaved:!1}:{state:Gu(e,t),unsaved:!1}}const Zu=(e=Date.now())=>Ju.forgetOld(e),Qu=16777216,$u=()=>_(V(),`pending-session-usage.jsonl`),ed=()=>_(V(),`pending-session-profiles.jsonl`);async function td(e){let{sendEveryMs:t=3e4,registerWithinMs:n=6e5,retryEveryMs:r=6e4,idleMs:i=12e5,maxIdleMs:a=864e5}=e,o=Yu(),s=Cu(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 Vu(e,`refused`);throw e}for(let e of t)await Vu(e,`sent`)}),p=(e=[])=>ha($u(),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 Ru(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=qu(t.state,{agent:r.agent,organizationId:i.organizationId,machineId:await xa(),machineName:ma(),skillIds:i.skillIds});a.usage.length!==0&&(await Vu(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)),_=d((e,t,n)=>e.reportSessionProfiles(t,n)),v=(e=[])=>ha(ed(),_,e,{batch:ol.maxPerRequest,batchLength:1048576,keyOf:e=>e.sessionId}),y=/* @__PURE__ */ new Map;async function b(e){let t=[];for(let n of e){let e=await Ru(n.sessionId);if(!e){y.delete(n.sessionId);continue}let r=await s.of(e);if(r===`unknown`){y.set(n.sessionId,n);continue}if(y.delete(n.sessionId),!r)continue;let i=await Ol(n.transcriptPath,n.sessionId).catch(()=>null);i&&t.push(Al(i,{sessionId:n.sessionId,agent:n.agent,machineId:await xa(),machineName:ma(),organizationId:r.organizationId}))}t.length>0&&await v(t)}let x=()=>Promise.all([p(),b([...y.values()]).then(()=>v()),wa(h),du(g)]);function S(e){let t=ad(e.activations),n=ad(e.sessionEvents),r=ad(e.profiles).filter(e=>typeof e.agent==`string`&&typeof e.sessionId==`string`&&wc.test(e.sessionId)&&typeof e.transcriptPath==`string`&&e.transcriptPath.endsWith(`.jsonl`));return u(()=>Promise.all([r.length>0&&b(r),t.length>0&&wa(h,t),n.length>0&&du(g,n)]))}let C=null,w=()=>{C??=setTimeout(()=>{C=null,u(()=>o.save())},1e3)};async function T(t,n){if(ie(),!E(t.headers[`x-agent-kit-collector`]))return t.resume(),id(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 id(n,200,{api:e.apiUrl,pid:process.pid,version:nn});if(t.method!==`POST`)return t.resume(),id(n,404,{});if(i===`/stop`){t.resume(),id(n,200,{}),ue({send:r.searchParams.get(`send`)!==`false`});return}if(i===`/v1/traces`)return t.resume(),id(n,200,{});if(![`/v1/metrics`,`/v1/logs`,`/report`].includes(i))return t.resume(),id(n,404,{});if(!/\bjson\b/i.test(t.headers[`content-type`]??``))return t.resume(),id(n,415,{message:`Send JSON.`});let a=await rd(t);if(!a.ok)return id(n,a.status,{});i===`/report`?(id(n,202,{}),S(a.json)):(await o.observe(i===`/v1/metrics`?Eu(a.json):Du(a.json)),w(),id(n,200,{}))}let E=e=>{let t=Buffer.from(typeof e==`string`?e:``);return t.length===c.length&&ve(t,c)},ee=Ce((e,t)=>{T(e,t).catch(()=>{t.headersSent||id(t,500,{})})});if(!await new Promise(t=>{ee.once(`error`,()=>t(!1)),ee.listen(e.port,`127.0.0.1`,()=>t(!0))}))return null;let te=null,ne=Date.now(),re=e=>{te&&clearTimeout(te),te=setTimeout(()=>void ae(),e)};function ie(){ne=Date.now(),re(i)}async function ae(){let e=ne,t=!1;if(await u(async()=>{let e=[$u(),ed(),Ca(),Xl()];t=(await Promise.all(e.map(ga))).some(Boolean)||y.size>0||(await o.dirty()).length>0}),le||ne!==e)return;let n=Date.now()-ne;t&&n<a?re(Math.max(1,Math.min(i,a-n))):ue()}ie();let oe=setInterval(()=>void u(m),t),D=setInterval(()=>void u(x),r);u(async()=>{let e=Date.now();await zu(e),await Zu(e),await Wu(e),await o.resume()});let se=()=>u(m).then(()=>u(x)),O=()=>{},ce=new Promise(e=>O=e),le=null;function ue({send:e=!0}={}){return le??=(async()=>{te&&clearTimeout(te),C&&clearTimeout(C),clearInterval(oe),clearInterval(D);let t=new Promise(e=>ee.close(()=>e()));ee.closeIdleConnections(),await(e?se():u(()=>o.save())),ee.closeAllConnections(),await t,O()})(),le}return{port:ee.address().port,flush:se,stop:ue,stopped:ce}}const nd=n(we);async function rd(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>Qu)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 nd(r,{maxOutputLength:Qu})),{ok:!0,json:JSON.parse(r.toString(`utf8`))}}catch(e){return{ok:!1,status:e instanceof RangeError?413:400}}}function id(e,t,n){e.writeHead(t,{"content-type":`application/json`}),e.end(JSON.stringify(n))}const ad=e=>Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[];async function od(e){e&&(process.env.AGENT_KIT_API_URL=e);let{port:t,secret:n}=await co();await(await td({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 sd=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,cd=/\p{L}[\p{L}\p{M}]*|\p{N}+|\n|[^\S\n]+|[^\p{L}\p{N}\s]/gu;function ld(e){let t=0;for(let[n]of e.matchAll(cd)){let e=n[0];if(e===`
|
|
299
|
+
`)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)sd.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 ud(e){return{always:e.description,max:e.description+e.body+e.files}}function dd(e){let t=0,n=0,r=0,i=!1;for(let a of e){if(!a){r++;continue}let e=ud(a);t+=e.always,n+=e.max,a.source===`estimate`&&(i=!0)}return{always:t,max:n,missing:r,estimated:i}}function fd(e){let t=Math.abs(e);return t<1e3?`${Math.round(e)}t`:t<9950?`${md((e/1e3).toFixed(1))}k`:t<999500?`${Math.round(e/1e3)}k`:`${md((e/1e6).toFixed(1))}M`}const pd=(e,t)=>`${t===`estimate`?`~`:``}${fd(e)}`,md=e=>e.replace(/\.0$/,``),hd={high:15,medium:10,low:5},gd=5e3,_d=/* @__PURE__ */ new Set([`md`,`markdown`,`mdx`,`txt`,`py`,`sh`,`bash`,`js`,`mjs`,`cjs`,`ts`,`json`,`yaml`,`yml`,`toml`,`html`,`xml`]);function vd(e){let t=nr(e.path),n=t.includes(`.`)?t.split(`.`).pop().toLowerCase():``;return e.size<=262144&&_d.has(n)}const yd=/^(license|licence|notice|readme|changelog)(\..*)?$/i,bd=/!?\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;function xd(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)vd(e.find(e=>e.path===n))&&(p=!0);else{if(/\.(md|markdown|mdx)$/i.test(n))for(let e of Nd(r)){let t=rr(n,e);t!==null&&!u(t)&&f.add(t)}for(let t of e)!d.has(t.path)&&Pd(r,n,t.path)&&(d.add(t.path),vd(t)&&m.push(t.path))}}let h=e.map(e=>e.path).filter(e=>!d.has(e)&&!yd.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(`
|
|
300
|
+
`).length,bodyTokens:ld(c),hasExamples:Bd(s)||e.some(e=>/example/i.test(e.path)&&d.has(e.path)),missingFiles:[...f].sort(),unusedFiles:p&&h.length>0?null:h}}function Sd(e,t,n=/* @__PURE__ */ new Date){let r=[...Ad(e),...t?jd(t,n):[]];return{score:Cd(r),checks:Td(r)}}function Cd(e){let t=e.reduce((e,t)=>e+hd[t.severity],0);if(t===0)return 100;let n=e.filter(e=>e.passed).reduce((e,t)=>e+hd[t.severity],0);return Math.round(n/t*100)}const wd=[`high`,`medium`,`low`];function Td(e){return[...e].sort((e,t)=>Number(e.passed)-Number(t.passed)||(e.passed?0:wd.indexOf(e.severity)-wd.indexOf(t.severity)))}const Ed=(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}),Dd=/\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,Od=/\b(helps? (with|you)|assists? (with|you)|various|stuff|things|and more|etc\.?|miscellaneous|general[- ]purpose|useful (for|tool))\b/i,kd=/(^|[\s(])I('m|'ll|'ve)?(?=[\s,.!?)]|$)|\b(me|my|My)\b|^(you|your|You|Your)\b|\b[Yy]ou can\b/;function Ad(e){let t=[],n=e.description??``;e.hasWhenToUse||Dd.test(n)?t.push(Ed(`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(Od);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(Ed(`description-specific`,`medium`,`description is specific`)),kd.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(Ed(`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(Ed(`description-length`,`low`,`description length OK (${n.length} chars)`));let a=Md(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>gd?t.push($(`body-length`,`medium`,`${G} is long (${a}, ${e.bodyLines} lines)`,`Keep the body under 500 lines and about ${Md(gd)}; move reference material into files ${G} links to.`)):t.push(Ed(`body-length`,`medium`,`length OK (${a})`)),e.hasExamples?t.push(Ed(`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(Ed(`missing-files`,`high`,`every linked file exists`)):t.push($(`missing-files`,`high`,`links to ${Vd(e.missingFiles.length,`missing file`)}: ${Hd(e.missingFiles)}`,`Add the files, or fix the links.`)),e.unusedFiles!==null&&(e.unusedFiles.length===0?t.push(Ed(`unused-files`,`low`,`every file is used`)):t.push($(`unused-files`,`low`,`${Vd(e.unusedFiles.length,`file`)} nothing mentions: ${Hd(e.unusedFiles)}`,`Mention them in ${G}, saying when to read or run them, or delete them.`))),t}function jd(e,t=/* @__PURE__ */ new Date){let n=[];e.caseCount>=3?n.push(Ed(`eval-cases`,`high`,Vd(e.caseCount,`eval case`))):n.push($(`eval-cases`,`high`,e.caseCount===0?`no eval cases`:`only ${Vd(e.caseCount,`eval case`)}`,`Write at least 3 cases, with prompts people really send.`)),e.negativeCaseCount>0?n.push(Ed(`eval-negative`,`medium`,`${Vd(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(Ed(`eval-recent-run`,`low`,r===0?`evals ran today`:`evals ran ${Vd(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 Md(e){return e<1e3?`${e} tokens`:`${(Math.round(e/100)/10).toString()}k tokens`}function Nd(e){let t=[];for(let n of e.matchAll(bd)){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 Pd(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=Fd(t,n);return a&&r.add(a),[...r].some(t=>Id(e,t))}function Fd(e,t){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;return n&&t.startsWith(n)?t.slice(n.length):null}function Id(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 Ld=/^(```|~~~)/m,Rd=/^#{1,6}[^\n]*\bexamples?\b/im,zd=/^\s*(\*\*|__)?(example|input|output)s?\b[^\n]*:/im;function Bd(e){return Ld.test(e)||Rd.test(e)||zd.test(e)}function Vd(e,t){return`${e} ${t}${e===1?``:`s`}`}function Hd(e,t=3){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} and ${e.length-t} more`:n}const Ud=/* @__PURE__ */ new Set([`.git`,`node_modules`,`__pycache__`]);async function Wd(e){try{return(await fe(_(e,G))).isFile()}catch{return!1}}async function Gd(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()){Ud.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`||vd({path:s,size:c}))&&n.set(s,await O(o,`utf8`))}}return await r(e),Sd(xd(t,e=>n.get(e)),null)}function Kd(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(`
|
|
301
|
+
`)}async function qd(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 Wd(n)){let e=await Gd(n),r=t===void 0?`This folder`:W(n);F.info(`${r}: checked from its files; evals aren't.`),console.log(Kd(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(Kd(o))}async function Jd(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 Yd(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(`
|
|
302
|
+
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 Xd=2e3;async function Zd(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 Qd(){let e=await Zd(`/health`);return e?e.status===401?`taken`:e.ok?await e.json().catch(()=>null)??null:null:null}async function $d(e,t,n=qo){let r=await Qd();return r===`taken`?`taken`:r?.api===t&&r.version===nn?`running`:(r&&await tf(),f(e)?(n(e,[`collector`,`--api`,t]),`started`):`missing`)}async function ef(e){return(await Zd(`/report`,{method:`POST`,body:JSON.stringify(e)},Xd))?.status===202}async function tf({send:e=!0}={}){return(await Zd(e?`/stop`:`/stop?send=false`,{method:`POST`},Xd))?.ok??!1}const nf=[/^# AGENTS\.md instructions/,/^<(environment_context|user_instructions|permissions instructions|turn_aborted)>/];function rf(e){let t=[],n=null,r=null,i=null,a=(e,n)=>t.push({type:e,message:{content:[n]}});for(let t of e.split(`
|
|
303
|
+
`)){if(!t.trim())continue;let e;try{e=JSON.parse(t)}catch{continue}let o=e.payload??{};if(e.type===`session_meta`)r=of(o.cli_version)??r,i=of(o.cwd)??i;else if(e.type===`turn_context`)n=of(o.model)??n,i=of(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=sf(o.content);if(!t.trim()||e===`user`&&nf.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`?cf(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:lf(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 af(e){try{let t=JSON.parse(e);return t.type===`session_meta`?of(t.payload?.cwd):null}catch{return null}}const of=e=>typeof e==`string`&&e?e:null;function sf(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
304
|
+
`):``}function cf(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function lf(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 sf(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return lf(t)}return JSON.stringify(e??``)}const uf=()=>process.env.CLAUDE_CONFIG_DIR??_(C(),`.claude`),df=()=>process.env.CODEX_HOME??_(C(),`.codex`),ff=(e,t=uf())=>_(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function pf(e,t,n=process.cwd()){if(t&&f(t))return b(t);let r=e===`claude-code`?await gf(t,n):await _f(t,n);if(r)return r.file;throw Error(t?`No ${hf(e)} session "${t}" on this machine.`:`No ${hf(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function mf(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([gf(void 0,e),_f(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 hf=e=>e===`claude-code`?`Claude Code`:`Codex`;async function gf(e,t){if(e){let t=_(uf(),`projects`),n=await Sf(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 Cf(t)){let t=ff(e),n=(await Sf(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return xf(n.map(e=>_(t,e)))}return null}async function _f(e,t){let n=_(df(),`sessions`),r=[],i=0;outer:for(let e of vf(await Sf(n)))for(let t of vf(await Sf(_(n,e))))for(let a of vf(await Sf(_(n,e,t)))){let o=_(n,e,t,a);for(let e of await Sf(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(_(o,e));if(r.length>=300||++i>=14)break outer}return yf(r,e,t)}const vf=e=>e.sort().reverse();async function yf(e,t,n){if(t){let n=e.find(e=>m(e).includes(t));return n?{file:n,mtime:0}:null}let r=Cf(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await bf(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 xf(t)}return null}async function bf(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(`
|
|
305
|
+
`);return af(i===-1?r:r.slice(0,i))??(JSON.parse(`"${r.match(/"cwd":"((?:[^"\\]|\\.)*)"/)?.[1]??``}"`)||null)}finally{await t.close()}}async function xf(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 Sf(e){try{return await ce(e)}catch{return[]}}function Cf(e){let t=[b(e)];for(;g(t.at(-1))!==t.at(-1);)t.push(g(t.at(-1)));return t}const wf=5e3;async function Tf(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 kf()),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 Of(e,u.sessionId,s),(f||r.hook_event_name===`UserPromptSubmit`||r.hook_event_name===`Stop`||c)&&await $d(la()??ca(),B());let p=await uu(e,r,a,s,u,{now:i}),m=Ef(e,r,s),h=Ao(r),g=h&&await ya(h.name,e,s),_=h&&g&&await Sa(g,e,h.trigger,Fc(u,l?.skills[g.id]??null),i);await Promise.all([!c&&ds(l,i,g?g.id:null)&&fs(d,o.user.id,l,i),(p||_||m)&&Df(d,p,_,m)])}catch{}}function Ef(e,t,n){if(t.hook_event_name!==`Stop`&&t.hook_event_name!==`SessionEnd`)return null;let r=Nc(t.session_id);return r?{agent:e,sessionId:r,transcriptPath:typeof t.transcript_path==`string`&&t.transcript_path?t.transcript_path:_(ff(n),`${r}.jsonl`)}:null}async function Df(e,t,n,r){await ef({activations:n?[n]:[],sessionEvents:t?[t]:[],profiles:r?[r]:[]})||await Promise.all([t&&du(async t=>{await e.reportSessionEvents(t,AbortSignal.timeout(wf))},t),n&&wa(async t=>{await e.reportActivations(t,AbortSignal.timeout(wf))},n)])}async function Of(e,t,n){let{repository:r,branch:i}=await Ic(n),a=ba(n,C());(r||a)&&await Lu({sessionId:t,agent:e,cwd:n,projectLock:a,repository:r,branch:i,registeredAt:(/* @__PURE__ */ new Date()).toISOString()})}async function kf(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}async function Af(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 jf(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 Mf(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 jf(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 Mf(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(`
|
|
306
|
+
`))}function Nf(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?pd(e,a.source):`—`;return{skill:e,installed:r!==void 0||i!==void 0,cells:[Nn(e),Pf(e),o(a?.description??0),o(a?.body??0),o(a?.files??0),[Ff(`project`,r,e),Ff(`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=dd(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}${fd(c.always)} always · ${l}${fd(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 Pf(e){return[`v${e.version}`,...Zt.filter(t=>e.channels[t]!==null).map(t=>`${t} v${e.channels[t]}`)].join(` · `)}function Ff(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 If(){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 Nf(n,i,a))console.log(e);if(r.length===0)return;console.log(``);let o=Math.max(...r.map(e=>Lf(e).length));for(let e of r){let t=[Rf(i,e)&&`in project`,Rf(a,e)&&`in global`].filter(Boolean);console.log(`${Lf(e).padEnd(o)} ${zf(e)}`+(t.length?` (${t.join(`, `)})`:``))}}const Lf=e=>`${Sn}${Nn(e)}`,Rf=(e,t)=>Object.values(e.kits).some(e=>e.id===t.id);function zf(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 Bf=`This machine isn't on a Machines page yet: its heartbeat is off or hasn't gone through (${L(`heartbeat status`)}).`;async function Vf(e,t){switch(e){case`name`:{let{api:e}=await to(),n=await xa();if(t===void 0){let t=await Hf(e.machineName(n));if(!t)throw Error(Bf);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 Hf(e.nameMachine(n,t))??(await Xa()?await Hf(e.nameMachine(n,t)):null);if(!r)throw Error(Bf);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 Hf(e){try{return await e}catch(e){if(e instanceof R&&e.status===404)return null;throw e}}async function Uf(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 Wf(){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 qf(t.token,t.webUrl))}async function Gf(e=process.stdin){Wt(`agent kit`);let t=await Kf(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 Kf(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 qf(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 Jf(){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 Yf(){let e=await eo();e?console.log(no(e.user)):(console.log(`You're not logged in. Run ${L(`login`)}.`),process.exitCode=1)}const Xf=/* @__PURE__ */ new Set([`push`,`pull`,`dev`,`propose`]);async function Zf(e){let t=await Qf(),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(`
|
|
307
|
+
`))}async function Qf(){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 $f={maxTitleLength:120,maxNoteLength:4e3,maxSkills:50,maxTranscriptBytes:8388608},ep=[{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}],tp=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g,np=/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,rp=/* @__PURE__ */ new Set([`127.0.0.1`,`0.0.0.0`]),ip=/@(?:example\.(?:com|org|net)|anthropic\.com)$/i,ap=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function op(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(ap(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}_])${ap(e.find)}(?![\\p{L}\\p{N}_])`:ap(e.find),`giu`)}));function a(e){let t=e;for(let e of ep)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(tp,e=>ip.test(e)?e:(n(`email`),`user@example.com`)),t=t.replace(np,e=>rp.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 sp=e=>e.map(e=>JSON.stringify(e)).join(`
|
|
301
308
|
`)+`
|
|
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
|
-
`))
|
|
306
|
-
`):``}function ff(e){if(typeof e!=`string`)return e??{};try{return JSON.parse(e)}catch{return{arguments:e}}}function pf(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 df(e);if(typeof e==`object`&&e){let{content:t,output:n}=e;if(typeof n==`string`)return n;if(t!==void 0)return pf(t)}return JSON.stringify(e??``)}const mf=()=>process.env.CLAUDE_CONFIG_DIR??_(C(),`.claude`),hf=()=>process.env.CODEX_HOME??_(C(),`.codex`),gf=(e,t=mf())=>_(t,`projects`,e.replace(/[^A-Za-z0-9]/g,`-`));async function _f(e,t,n=process.cwd()){if(t&&f(t))return b(t);let r=e===`claude-code`?await bf(t,n):await xf(t,n);if(r)return r.file;throw Error(t?`No ${yf(e)} session "${t}" on this machine.`:`No ${yf(e)} session for ${n}. Run this from the folder the session runs in, or pass --session <id or path>.`)}async function vf(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([bf(void 0,e),xf(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 yf=e=>e===`claude-code`?`Claude Code`:`Codex`;async function bf(e,t){if(e){let t=_(mf(),`projects`),n=await Ef(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 Df(t)){let t=gf(e),n=(await Ef(t)).filter(e=>e.endsWith(`.jsonl`));if(n.length>0)return Tf(n.map(e=>_(t,e)))}return null}async function xf(e,t){let n=_(hf(),`sessions`),r=[],i=0;outer:for(let e of Sf(await Ef(n)))for(let t of Sf(await Ef(_(n,e))))for(let a of Sf(await Ef(_(n,e,t)))){let o=_(n,e,t,a);for(let e of await Ef(o))e.startsWith(`rollout-`)&&e.endsWith(`.jsonl`)&&r.push(_(o,e));if(r.length>=300||++i>=14)break outer}return Cf(r,e,t)}const Sf=e=>e.sort().reverse();async function Cf(e,t,n){if(t){let n=e.find(e=>m(e).includes(t));return n?{file:n,mtime:0}:null}let r=Df(n),i=/* @__PURE__ */ new Map;for(let t of e){let e=await wf(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 Tf(t)}return null}async function wf(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
|
-
`)
|
|
308
|
-
|
|
309
|
-
`)}const qf={inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadInputTokens:Z.cacheReadTokens,cacheCreationInputTokens:Z.cacheCreationTokens,costUSD:Z.costUsd},Jf={input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,cache_read_input_tokens:Z.cacheReadTokens,cache_creation_input_tokens:Z.cacheCreationTokens},Yf=/^\{"type":"(api-request|atis-latch|queue-operation)/;function Xf(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(Jf)){let n=o[e];typeof n==`number`&&n>0&&(s[t]=(s[t]??0)+n)}};return{take(r,{subagent:s=!1}={}){if(!r||Yf.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`&&!rp(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`:np(c,n);return;case`pr-link`:typeof c.prRepository==`string`&&$f.test(c.prRepository)&&a(c.prRepository);return;case`assistant`:if(Number.isNaN(l))return;for(let e of rp(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=Zf.test(n.command),a=Qf.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 rp(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=ip(c,e);if(n.gh){for(let e of r.matchAll(ep))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${ap(c)}`;for(let t of e.matchAll(tp))a(t[1])}}if(Number.isNaN(l)||!sp(c))return;t.prompts++;let e=cp(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 Zf=/(^|[\s;&|(])gh\s/,Qf=/(^|[\s;&|(])git\s(?:[^;&|\n]*\s)?push\b/,$f=/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/,ep=/https:\/\/github\.com\/([A-Za-z0-9-]+\/[A-Za-z0-9._-]+)\/(?:pull|issues)\/\d+/g,tp=/^To (?:https:\/\/(?:[^@\s/]+@)?github\.com\/|(?:ssh:\/\/)?git@github\.com[:/]|github\.com:)([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?\s*$/gm;function np(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(qf)){let i=t[e];typeof i==`number`&&i>(n[r]??0)&&(n[r]=i)}}}function rp(e){let t=e.message?.content;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e):[]}function ip(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 ap(e){let t=e.toolUseResult;if(typeof t!=`object`||!t)return``;let n=t.stderr;return typeof n==`string`?n:``}function op(e){let t=e.message?.content;if(typeof t==`string`)return t;let n=rp(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 sp(e){if(e.isMeta||e.isSidechain||e.isCompactSummary||e.promptSource===`system`||e.origin)return!1;let t=op(e);return t!==null&&!/^\s*(<(local-command-|task-notification|bash-|system-reminder)|\[Request interrupted)/.test(t)}function cp(e){let t=op(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 lp(e,t){let n=l({input:d(e,{encoding:`utf8`}),crlfDelay:1/0});for await(let e of n)t(e)}async function up(e,t){let n=Xf(t);await lp(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 lp(_(i,e),e=>n.take(e,{subagent:!0}));return n.result()}const dp=`claude-code`,fp={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 ${sl.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were`},pp=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function mp(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 hp(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 mp(e.projectsDir)){let o=await gp(await up(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 gp(e,t,n=t.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<n.getTime()-sl.maxAgeDays*864e5)return`old`;let r=t.home??C(),i=e.cwd,a=await _p(e,i,r,t.known);if(typeof a==`string`)return a;let{place:o}=a,s=o.repository;if(await Fl(e.sessionId))return`live`;let c={sessionId:e.sessionId,agent:dp,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,[dl(`repository`,s)]);for(let{branch:t,at:n}of e.branches)await Lc(i,t)||u(n,[dl(`branch`,`${s}#${t}`)]);for(let t of e.skills)t.command&&u(t.at,vl(t.command,s));for(let{command:t,stdout:n,at:r}of e.commands)u(r,Sl(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+sl.maxLinks);f.push({...c,type:e,occurredAt:bp(t),links:i}),r+=Math.max(i.length,1)}},m=e=>e.filter(e=>{let t=Il(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,dp,i,r);s&&g.push({...c,...Fc({...o,branch:vp(e,a.at)},t.known.skills[s.id]??null),id:xp(`${e.sessionId}\n${n}\n${a.at}\n${a.name}`),skillId:s.id,version:s.version,trigger:a.trigger,occurredAt:bp(a.at),sessionId:e.sessionId})}let _=await t.organizationOf({sessionId:e.sessionId,agent:dp,cwd:i,projectLock:ba(i,r),repository:s,branch:e.branches[0]?.branch??null,registeredAt:bp(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:bp(e.endedAt),usage:yp(e)}:null;return{sessionId:e.sessionId,repository:s,placedByOutput:a.byOutput,startedAt:bp(e.startedAt),events:f,activations:g,usage:v}}async function _p(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 vp(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 yp(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:bp(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:bp(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:bp(e),end:bp(e+tl),value:n});return t.slice(0,rl.maxEntries)}const bp=e=>new Date(e).toISOString();function xp(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 Sp=sl.maxPerRequest;async function Cp(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=Sp){let i=await e.reportSessionEvents(r.slice(t,t+Sp));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 wp({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=Hl(async()=>({api:n,userId:r})),o=pp(),s=await hp({projectsDir:o,known:i,organizationOf:e=>a.of(e),machineId:await xa(),machineName:ma()});if(e){for(let e of s.sessions)console.log(Op(e));console.log(`\nWould send ${Tp(s.sessions.length)} from ${o}. Nothing was sent.`),Ep(s.sessions),Dp(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 Cp({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e)},s);for(let e of c.sent)await Pl(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await ou(e.usage,`sent`);F.success(`Sent ${Tp(c.sent.length)} from ${o} to agent kit.`),Ep(c.sent),Dp({...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 Tp=e=>`${e} session${e===1?``:`s`}`;function Ep(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 Dp(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${Tp(r)}:`);for(let[e,t]of n)console.log(` ${t} ${fp[e]}`)}}function Op(e){let t=new Set(e.events.flatMap(e=>e.links.map(Il))),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 kp={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 Ap(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 yd({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 Mp(t);case`import`:return wp({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 gd(),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`}; ${kp[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 jp={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Mp(e){if(e){let[t,n]=await Promise.all([su(e),Nl(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, ${jp[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
|
|
313
|
-
Nothing of what it used was sent.`);return}let t=await cu();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} ${jp[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function Np(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 Rp();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=Lp(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)=>Pp(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;Ip(await d(!0,e=>{m||u(`With ${Nn(l)} v${a??l.version}`),m=!0,Fp(e,l.name)})),u(`Without`);let h=await p;for(let e of f)Fp(e,l.name);Ip(h)}async function Pp(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 Fp(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 Ip(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 Lp(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 Rp(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const zp=`a-kit ${nn}: your agent kit skills, in your agents.
|
|
309
|
+
`;function cp(e){let t=[],n=null,r=null,i=null;for(let a of e.split(`
|
|
310
|
+
`)){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=lp(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 lp(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:up(n.content),...n.is_error===!0?{is_error:!0}:{}});return t}function up(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(`
|
|
311
|
+
`):``}const dp=2e3;function fp(e){let t=[...e.map],n=hp(()=>ee().username);n&&n.length>=3&&t.push({find:n,replace:`user`});let r=hp(()=>w());r&&r.length>=3&&r!==`localhost`&&t.push({find:r,replace:`host`});let i=pp();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=hp(()=>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:dp}}function pp(){return hp(()=>be(`git`,[`remote`,`get-url`,`origin`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim())?.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/)?.[1]??null}function mp(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 hp(e){try{return e()}catch{return null}}function gp(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))vp(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 _p=[`codex`,`cursor`,`gemini-cli`],vp=(e,t)=>e.length===0||e.includes(t)||_p.includes(t)&&e.some(e=>_p.includes(e));async function yp(e){Wt(`agent kit report`);let t=await bp(e.agent[0]),n=await pf(t,e.session||void 0),r=await O(n,`utf8`),i=Li(t===`claude-code`?cp(r):rf(r));if(i.events.length<2)throw Error(`${n} has no conversation to report.`);let a=op(fp({map:e.map?mp(await xp(e.map)):[],cwds:i.cwd?[i.cwd]:[],fullOutputs:e.fullOutputs})),o=a.text(Cp(e.title,`--title`,`a short title`)),s=a.text(Cp(e.note,`--note`,`what went wrong`)),c=e.expected?a.text(e.expected):null,l=sp(a.events(i.events)),u=await Promise.all([X(Y(`project`)),X(Y(`global`))]),d=gp(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([`${hf(t)} session: ${n}`,`Model: ${i.model??`unknown`}, ${i.events.length-1} messages`,`Skills: ${Tp(d)}`,`Taken out: ${Ep(a.counts)}`,`Scrubbed transcript: ${p}`].join(`
|
|
312
|
+
`)),Buffer.byteLength(l)>$f.maxTranscriptBytes)throw Error(`The transcript is over ${$f.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=wp(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 bp(e){if(e===void 0)return mf();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 xp=e=>e===`-`?Sp():O(e,`utf8`);async function Sp(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}function Cp(e,t,n){if(!e?.trim())throw Error(`Pass ${t} with ${n}.`);return e}function wp(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 Tp(e){return e.length===0?`none`:e.map(e=>`${e.name}${e.version?` v${e.version}`:``}${e.triggered?` (loaded)`:``}`).join(`, `)}function Ep(e){let t=Object.entries(e);return t.length===0?`nothing`:t.map(([e,t])=>e===`cut`?`${t} tool outputs cut to ${dp} characters`:`${e} ×${t}`).join(`, `)}function Dp(e){return e&&e.total>0?e.passed/e.total:null}async function Op(e){let{api:t,credentials:n}=await to(),[r,i]=await Promise.all([t.search(e.join(` `)),t.listOrganizations()]);console.log(kp(r,n.webUrl,i.length>1))}function kp({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=Dp(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(`
|
|
313
|
+
`)}const Ap=`claude-code`,jp={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 ${Hl.maxAgeDays} days, which agent kit doesn't take`,live:`already sent by live telemetry, left as they were but for their profile`},Mp=(e=C())=>_(process.env.CLAUDE_CONFIG_DIR??_(e,`.claude`),`projects`);async function Np(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:[],liveProfiles:[],skipped:{}},r=e=>{n.skipped[e]=(n.skipped[e]??0)+1};for(let{file:i,sessionId:a}of await Np(e.projectsDir)){let o=await Fp(await wl(i,a),i,e,t);typeof o==`string`?r(o):`live`in o?(r(`live`),o.profile&&n.liveProfiles.push({sessionId:a,profile:o.profile})):n.sessions.push(o)}return n.sessions.sort((e,t)=>e.startedAt.localeCompare(t.startedAt)),n}async function Fp(e,t,n,r=n.now??/* @__PURE__ */ new Date){if(e.startedAt===null||e.endedAt===null||!e.cwd)return`empty`;if(e.endedAt<r.getTime()-Hl.maxAgeDays*864e5)return`old`;let i=n.home??C(),a=e.cwd,o=await Ip(e,a,i,n.known);if(typeof o==`string`)return o;let{place:s}=o,c=s.repository,l={sessionId:e.sessionId,agent:Ap,machineId:n.machineId,machineName:n.machineName,imported:!0},u=await n.organizationOf({sessionId:e.sessionId,agent:Ap,cwd:a,projectLock:ba(a,i),repository:c,branch:e.branches[0]?.branch??null,registeredAt:zp(e.startedAt)}),d=u&&u!==`unknown`?{transcriptPath:t,from:{...l,organizationId:u.organizationId}}:null;if(await gu(e.sessionId))return{live:!0,profile:d};if(u===`unknown`)throw Error(`Couldn't ask agent kit which organization a session's repository is. Try again in a moment.`);let f=[],p=(e,t)=>{let n=t.filter(e=>e!==null);n.length>0&&f.push({at:e,links:n})};p(e.startedAt,[Kl(`repository`,c)]);for(let{branch:t,at:n}of e.branches)await Lc(a,t)||p(n,[Kl(`branch`,`${c}#${t}`)]);for(let t of e.skills)t.command&&p(t.at,$l(t.command,c));for(let{command:t,stdout:n,at:r}of e.commands)p(r,ru(t,n,c));f.sort((e,t)=>e.at-t.at);let m=/* @__PURE__ */ new Set,h=[],g=(e,t,n)=>{for(let r=0;r===0||r<n.length;){let i=n.slice(r,r+Hl.maxLinks);h.push({...l,type:e,occurredAt:zp(t),links:i}),r+=Math.max(i.length,1)}},_=e=>e.filter(e=>{let t=_u(e);return!m.has(t)&&(m.add(t),!0)}),v=_(f.filter(t=>t.at<=e.startedAt).flatMap(e=>e.links));g(`start`,e.startedAt,v);for(let{at:t,links:n}of f){if(t<=e.startedAt)continue;let r=_(n);r.length>0&&g(`seen`,t,r)}g(`end`,e.endedAt,[]);let y=[];for(let[t,r]of e.skills.entries()){let o=await ya(r.name,Ap,a,i);o&&y.push({...l,...Fc({...s,branch:Lp(e,r.at)},n.known.skills[o.id]??null),id:Bp(`${e.sessionId}\n${t}\n${r.at}\n${r.name}`),skillId:o.id,version:o.version,trigger:r.trigger,occurredAt:zp(r.at),sessionId:e.sessionId})}let b=u?{...l,organizationId:u.organizationId,occurredAt:zp(e.endedAt),usage:Rp(e)}:null;return{sessionId:e.sessionId,repository:c,placedByOutput:o.byOutput,startedAt:zp(e.startedAt),events:h,activations:y,usage:b,profile:d}}async function Ip(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 Lp(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 Rp(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:zp(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:zp(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:zp(e),end:zp(e+tl),value:n});return t.slice(0,rl.maxEntries)}const zp=e=>new Date(e).toISOString();function Bp(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 Vp=Hl.maxPerRequest;async function Hp(e,t){let n=/* @__PURE__ */ new Set,r=t.sessions.flatMap(e=>e.events);for(let t=0;t<r.length;t+=Vp){let i=await e.reportSessionEvents(r.slice(t,t+Vp));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=Up(t=>e.reportSessionUsage(t),rl.maxPerRequest,409600);for(let e of i)e.usage&&await o.add(e.usage);await o.flush();let s=Up(t=>e.reportSessionProfiles(t),ol.maxPerRequest,1048576);for(let{sessionId:e,profile:n}of[...t.sessions,...t.liveProfiles]){if(!n)continue;let t=await Ol(n.transcriptPath,e).catch(()=>null);t&&await s.add(Al(t,n.from))}return await s.flush(),{sent:i,live:[...n]}}function Up(e,t,n){let r=[],i=0,a=async()=>{if(r.length===0)return;let t=r;r=[],i=0,await e(t)};return{async add(e){let o=JSON.stringify(e).length;(r.length>=t||r.length>0&&i+o>n)&&await a(),r.push(e),i+=o},flush:a}}async function Wp({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=Cu(async()=>({api:n,userId:r})),o=Mp(),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(Jp(e));console.log(`\nWould send ${Gp(s.sessions.length)} from ${o}. Nothing was sent.`),Kp(s.sessions),qp(s.skipped,`Would skip`),s.sessions.length>0&&console.log(`agent kit leaves a session live telemetry already sent as it is, but for its profile, which replaces.`);return}let c=await Hp({reportSessionEvents:e=>n.reportSessionEvents(e),reportActivations:e=>n.reportActivations(e),reportSessionUsage:e=>n.reportSessionUsage(e),reportSessionProfiles:e=>n.reportSessionProfiles(e)},s);for(let e of c.sent)await hu(e.sessionId,e.events.flatMap(e=>e.links)),e.usage&&await Vu(e.usage,`sent`);F.success(`Sent ${Gp(c.sent.length)} from ${o} to agent kit.`),Kp(c.sent),qp({...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 Gp=e=>`${e} session${e===1?``:`s`}`;function Kp(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 qp(e,t){let n=Object.entries(e),r=n.reduce((e,[,t])=>e+t,0);if(r!==0){console.log(`${t} ${Gp(r)}:`);for(let[e,t]of n)console.log(` ${t} ${jp[e]}`)}}function Jp(e){let t=new Set(e.events.flatMap(e=>e.links.map(_u))),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 Yp={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 Xp(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 tf({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 Qp(t);case`import`:return Wp({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 Qd(),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`}; ${Yp[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 Zp={sent:`sent`,waiting:`waiting to be sent`,refused:`refused by agent kit, not sent again`};async function Qp(e){if(e){let[t,n]=await Promise.all([Hu(e),mu(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(`
|
|
314
|
+
`)}`:`Its session told agent kit of no repository or branch.`),console.log(t?`\nWhat it used, ${Zp[t.status]} (${t.at}):\n${JSON.stringify(t.record,null,2)}`:`
|
|
315
|
+
Nothing of what it used was sent.`);return}let t=await Uu();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} ${Zp[n]}`);console.log("\n`a-kit telemetry show <session-id>` shows what was sent for one.")}}async function $p(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 im();if(!i.trim())throw Error(`Write the prompt after the skill, or pipe it in: a-kit try <skill> "<prompt>"`);let a=rm(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)=>em(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;nm(await d(!0,e=>{m||u(`With ${Nn(l)} v${a??l.version}`),m=!0,tm(e,l.name)})),u(`Without`);let h=await p;for(let e of f)tm(e,l.name);nm(h)}async function em(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 tm(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 nm(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 rm(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 im(){if(process.stdin.isTTY)return``;let e=``;for await(let t of process.stdin)e+=t;return e}const am=`a-kit ${nn}: your agent kit skills, in your agents.
|
|
314
316
|
|
|
315
317
|
Usage
|
|
316
318
|
a-kit init Log in and pick skills to install
|
|
@@ -373,4 +375,4 @@ Report options (the report-session-issue skill passes them for you)
|
|
|
373
375
|
--org <id|name> The organization, when it can't tell
|
|
374
376
|
--full-outputs Keep tool outputs whole (they're cut to 2,000 characters)
|
|
375
377
|
--dry-run Scrub and show what would be sent, without sending
|
|
376
|
-
`;async function
|
|
378
|
+
`;async function om(){let e=t({allowPositionals:!0,strict:!1}).positionals[0];if(e&&Xf.has(e))return Zf(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(am);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 Jd(o);case`add`:case`install`:return Ko(a,o);case`update`:return ms(o);case`list`:case`ls`:return If();case`search`:if(a.length===0)throw Error("What should it look for? Like `a-kit search pdf`.");return Op(a);case`health`:return qd(a);case`check`:return el(a);case`link`:return Af(a,o);case`login`:return n.token?Gf():Wf();case`logout`:return Jf();case`whoami`:return Yf();case`try`:return $p(a,{model:n.model,skillVersion:n[`skill-version`]});case`report`:return yp({...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 Xp(a[0],a[1],{port:n.port,dryRun:n[`dry-run`]});case`auto-update`:return _s(a[0]);case`heartbeat`:return Yd(a[0],n.api);case`org`:return Uf(a[0],a.slice(1).join(` `)||n.org);case`machine`:return Vf(a[0],a.length>1?a.slice(1).join(` `):void 0);case`hook`:return Tf(a[0],n.api,a[1]);case`collector`:return od(n.api);default:throw Error(`Unknown command "${i}". Run \`a-kit --help\`.`)}}om().catch(e=>{let t=e instanceof Error?e.message:String(e);F.error(t),process.exitCode=1});export{};
|