@agenttrail/cli 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-LS6ULVMB.js → chunk-77RT6DZY.js} +11 -11
- package/dist/cli/index.cjs +5 -5
- package/dist/cli/index.js +1 -1
- package/dist/cursor/capture-hook.mjs +5 -5
- package/dist/cursor/flush.mjs +10 -10
- package/dist/index.cjs +39 -39
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/marketplace.json +2 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
package/dist/cli/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var ys=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Eg=Object.getOwnPropertyNames;var Ig=Object.prototype.hasOwnProperty;var bg=(e,n)=>{for(var t in n)ys(e,t,{get:n[t],enumerable:!0})},kg=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Eg(n))!Ig.call(e,o)&&o!==t&&ys(e,o,{get:()=>n[o],enumerable:!(r=Rg(n,o))||r.enumerable});return e};var Cg=e=>kg(ys({},"__esModule",{value:!0}),e);var
|
|
2
|
+
"use strict";var ys=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Eg=Object.getOwnPropertyNames;var Ig=Object.prototype.hasOwnProperty;var bg=(e,n)=>{for(var t in n)ys(e,t,{get:n[t],enumerable:!0})},kg=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Eg(n))!Ig.call(e,o)&&o!==t&&ys(e,o,{get:()=>n[o],enumerable:!(r=Rg(n,o))||r.enumerable});return e};var Cg=e=>kg(ys({},"__esModule",{value:!0}),e);var mI={};bg(mI,{isCliEntry:()=>yg,run:()=>mg});module.exports=Cg(mI);var eg=require("child_process"),Yn=require("fs"),U=require("os"),Se=require("path"),ng=require("readline/promises"),tg=require("util");var _g=["MacBook Pro","MacBook Air","Mac mini","iMac","Mac Studio","Mac Pro","Mac","Windows","Linux"];function wr(e){return typeof e=="string"&&_g.includes(e)}var Xa="pubsub:sse:org:",Tg=`${Xa}*`;var xe={mode:"standard"};var hs=["Free","Pro","Team","Business","Enterprise"];var Og=new Set(["Pro","Team","Business","Enterprise"]);function Ss(e){let n=hs.indexOf(e);return hs.slice(n+1).find(t=>Og.has(t))??null}var zn={Free:7,Pro:14,Team:30,Business:90,Enterprise:365};function Re(e,n){return e.io.error(`error: \`${n} --agent codex\` is not yet available.`),1}function Za(e){return Re(e,"login")}var nt=require("fs"),et=require("path");var nd=require("crypto"),v=require("fs"),P=require("path");var Ut="agenttrail.agent.vendor",Rs="agenttrail.tool.vendor_name",Es=255,$t="agenttrail.usage.reported",Is="agenttrail.time.approximate",bs="agenttrail.span.synthetic",ks="agenttrail.subagent.conversation_id";var Cs="agenttrail.turn.closed_by";var _s="agenttrail.mcp.server_unknown",Ts="agenttrail.pep.blocked";var Os="18a5d968-0fa2-5c8a-88da-0b29d80105d4",Bt="7f050af4-796e-5b05-94c2-dba78bcdc7c2",X="https://ingest.agenttrail.sh";function Gt(e){let n;try{n=new URL(e)}catch{throw new Error(`invalid endpoint '${e}': must be an absolute http(s) URL (e.g. http://localhost:4318).`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid endpoint '${e}': protocol must be http: or https: (got '${n.protocol}').`);return n.href.replace(/\/$/,"")}var xs="ef5f62d8-0a65-5a09-be97-07afd9bdab87",As="7d12feb9-faf4-5d1a-b711-9362724c66b3";var pe="claude-code";var Ht="CLAUDE_CODE_ENABLE_TELEMETRY",ws="CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",Xn="OTEL_TRACES_EXPORTER",vs="OTEL_EXPORTER_OTLP_PROTOCOL",en="OTEL_EXPORTER_OTLP_ENDPOINT",z="OTEL_EXPORTER_OTLP_HEADERS",ve="OTEL_RESOURCE_ATTRIBUTES",Pe=["OTEL_LOG_USER_PROMPTS","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_TOOL_CONTENT"],De="agenttrail.org.id",Kt="agenttrail.project.id",Ps="agenttrail.agent.id",Ds=Ut,Ns="agenttrail.developer.id",js="agenttrail.project",En=255;function we(e){return encodeURIComponent(e)}function Fs(e){let n=[`${De}=${we(e.orgId)}`,`${Kt}=${we(e.projectId)}`];if(e.agentId&&n.push(`${Ps}=${we(e.agentId)}`),n.push(`${Ds}=${we(pe)}`),e.developerId&&n.push(`${Ns}=${we(e.developerId)}`),e.project){let t=we(e.project);t.length<=En&&n.push(`${js}=${t}`)}return n.join(",")}function Dr(e){let n={[Ht]:"1",[ws]:"1",[Xn]:"otlp",[vs]:"http/protobuf",[en]:e.endpoint??X,[ve]:Fs(e)};if(e.captureContent!==void 0){let t=e.captureContent?"1":"0";for(let r of Pe)n[r]=t}return n}function td(e){return e.team||!e.apiKey?{}:{[z]:`Authorization=Bearer ${e.apiKey}`}}function Ms(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];Ae(s)&&Ae(o)?t[r]=Ms(s,o):t[r]=o}return t}function Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var vr=class extends Error{path;constructor(n,t){super(`${n} is ${t}. AgentTrail refused to overwrite it \u2014 your existing Claude Code settings are unchanged. Fix or move the file, then re-run.`),this.name="MalformedSettingsError",this.path=n}};function wg(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function K(e,n){let t;try{t=n(e)}catch(o){if(wg(o))return null;throw o}let r;try{r=JSON.parse(t)}catch{throw new vr(e,"not valid JSON")}if(!Ae(r))throw new vr(e,"not a JSON object");return r}function D(e,n,t={}){let r=e,o=!0;try{r=(0,v.realpathSync)(e)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=(0,v.lstatSync)(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=(0,P.resolve)((0,P.dirname)(r),(0,v.readlinkSync)(r))}if(a){let d=new Error(`atomicWriteFileSync: too many symbolic links: ${e}`);throw d.code="ELOOP",d}}let s=t.mode;if(s===void 0&&o)try{s=(0,v.statSync)(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${(0,nd.randomBytes)(6).toString("hex")}`;try{(0,v.writeFileSync)(i,n,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&(0,v.chmodSync)(i,s),(0,v.renameSync)(i,r)}catch(a){try{(0,v.unlinkSync)(i)}catch{}throw a}}function w(e){return(0,P.join)(e,".claude","settings.json")}function G(e){return(0,P.join)(e,".claude","settings.local.json")}var nn=".claude/settings.local.json";function tn(e,n,t={}){let r=G(e),o=t.readFile??(p=>(0,v.readFileSync)(p,"utf8")),s=t.writeFile??((p,l,f)=>D(p,l,f!==void 0?{mode:f}:{})),i=t.mkdir??(p=>(0,v.mkdirSync)(p,{recursive:!0})),a=K(r,o),d=a??{},c=a!==null,u=Ms(d,{env:n});return i((0,P.dirname)(r)),s(r,`${JSON.stringify(u,null,2)}
|
|
3
3
|
`,384),{path:r,env:n,merged:c}}function Ne(e,n,t={},r={}){let o=Nr(e,{env:n},t,r);return{path:o.path,env:n,merged:o.merged}}function Nr(e,n,t={},r={}){let o=w(e),s=t.readFile??(l=>(0,v.readFileSync)(l,"utf8")),i=t.writeFile??((l,f,m)=>D(l,f,m!==void 0?{mode:m}:{})),a=t.mkdir??(l=>(0,v.mkdirSync)(l,{recursive:!0})),d=K(o,s),c=d??{},u=d!==null,p=Ms(c,n);return a((0,P.dirname)(o)),r.mode!==void 0?i(o,`${JSON.stringify(p,null,2)}
|
|
4
4
|
`,r.mode):i(o,`${JSON.stringify(p,null,2)}
|
|
5
5
|
`),{path:o,merged:u}}var qn=class extends Error{path;repo;constructor(n,t,r=!1){super(r?`${n} may be managed by the dotfiles repo ${t}, and git could not confirm it is untracked, so AgentTrail did not write its token there: a commit would publish it. Check with git, or make the file one no repo manages, then re-run \`npx -y @agenttrail/cli@latest setup --agent claude --global\`.`:`${n} is inside the git repo ${t}, so AgentTrail did not write its token there: a commit would publish it. Capture from Claude Code sessions needs the token in that file. Make it a regular file outside the repo, then re-run \`npx -y @agenttrail/cli@latest setup --agent claude --global\`.`),this.name="UserSettingsInGitRepoError",this.path=n,this.repo=t}};function Pr(e){return e.slice((0,P.dirname)(e).length).replace(/^[/\\]+/,"")}function rd(e){try{return(0,v.realpathSync)(e)}catch{let n=e;for(let t=0;t<8;t++)try{if(!(0,v.lstatSync)(n).isSymbolicLink())break;n=(0,P.resolve)((0,P.dirname)(n),(0,v.readlinkSync)(n))}catch{break}try{return(0,P.join)((0,v.realpathSync)((0,P.dirname)(n)),Pr(n))}catch{return(0,P.resolve)(n)}}}function vg(e){return(0,P.dirname)(rd(e))}function Pg(e){try{return(0,P.join)((0,v.realpathSync)((0,P.dirname)(e)),Pr(e))}catch{return(0,P.resolve)(e)}}function ed(e){try{return(0,v.realpathSync)(e)}catch{return(0,P.resolve)(e)}}function Dg(e){let n=vg(e);for(;;){try{return(0,v.lstatSync)((0,P.join)(n,".git")),n}catch{}let t=(0,P.dirname)(n);if(t===n)return;n=t}}var Ng=[".cfg",".dotfiles",".dotfiles.git",".dots",".local/share/yadm/repo.git",".config/yadm/repo.git",".yadm/repo.git"];function jg(e,n){let t;try{t=(0,v.statSync)(n)}catch{return}let r=[Pr(e)],o=(0,P.dirname)(e);for(;;){try{let i=(0,v.statSync)(o);if(i.dev===t.dev&&i.ino===t.ino)return r.reverse().join("/")}catch{return}let s=(0,P.dirname)(o);if(s===o)return;r.push(Pr(o)),o=s}}function Fg(e,n,t){let r=[],o=t.env?.GIT_DIR?.trim();o&&r.push({gitDir:(0,P.resolve)(e,o),workTree:ed((0,P.resolve)(e,t.env?.GIT_WORK_TREE?.trim()||e))});for(let a of Ng){let d=(0,P.join)(e,a);try{(0,v.lstatSync)(d)}catch{continue}r.push({gitDir:d,workTree:ed(e)})}let s=[...new Set([Pg(n),rd(n)])],i;for(let{gitDir:a,workTree:d}of r)for(let c of s){let u=jg(c,d);if(u===void 0)continue;let p=t.git(["--git-dir",a,"--work-tree",d,"ls-files","--error-unmatch","--",u],d);if(p.code===0)return{repo:a,state:"tracked"};if(p.code!==1)return{repo:a,state:"unsure"};i??={repo:a,state:"untracked"}}return i}function Zn(e,n,t={},r={}){let o=w(e),s=Dg(o);if(s!==void 0)throw new qn(o,s);if(r.dotfiles){let i=Fg(e,o,r.dotfiles);if(i&&i.state!=="untracked")throw new qn(o,i.repo,i.state==="unsure");i&&r.dotfiles.log?.(`WARNING: ${i.repo} manages your home folder. It does not track ${o}, which now holds your AgentTrail token: never add that file to it.`)}return Ne(e,n,t,{mode:384})}var jr="npx -y @agenttrail/cli@latest login --refresh --agent claude",Mg=["agenttrail login --refresh","npx -y @agenttrail/claude-code-exporter@latest login --refresh"];function Lg(){return{hooks:[{type:"command",command:jr}]}}function Fr(e,n={}){let t=w(e),r=n.readFile??(p=>(0,v.readFileSync)(p,"utf8")),o=[],s=K(t,r),i=Ae(s)?s.hooks:void 0,a=Ae(i)?i.SessionStart:void 0;Array.isArray(a)&&(o=a);let d=o.map(p=>{if(!Ae(p)||!Array.isArray(p.hooks))return p;let l=p.hooks.filter(f=>!(Ae(f)&&typeof f.command=="string"&&Mg.includes(f.command)));return{...p,hooks:l}}).filter(p=>!(Ae(p)&&Array.isArray(p.hooks)&&p.hooks.length===0)),u=d.some(p=>Ae(p)&&Array.isArray(p.hooks)&&p.hooks.some(l=>Ae(l)&&l.command===jr))?d:[...d,Lg()];return Nr(e,{hooks:{SessionStart:u}},n)}var Ug=448;function Ee(e,n="claude"){switch(n){case"claude":return(0,et.join)(e,".agenttrail","credentials.json");case"cursor":return(0,et.join)(e,".agenttrail","cursor","credentials.json");case"codex":return(0,et.join)(e,".agenttrail","codex","credentials.json")}return $g(n)}function $g(e){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(e)}.`)}function L(e,n={},t="claude"){let r=n.readFile??(o=>(0,nt.readFileSync)(o,"utf8"));try{let o=JSON.parse(r(Ee(e,t)));return Bg(o)?o:null}catch{return null}}function tt(e,n,t={},r="claude"){let o=Ee(e,r),s=t.writeFile??((a,d,c)=>D(a,d,c!==void 0?{mode:c}:{}));return(t.mkdir??((a,d)=>(0,nt.mkdirSync)(a,{recursive:!0,mode:d})))((0,et.dirname)(o),Ug),s(o,`${JSON.stringify(n,null,2)}
|
|
@@ -44,17 +44,17 @@ Logged in. Traces will be attributed to org ${t.org_id}.`),e.log(rt),e.log("A Se
|
|
|
44
44
|
`,F),r}function kl(e){let n=(0,El.createHash)("sha256");for(let t of[...e].sort((r,o)=>r.path.localeCompare(o.path)))n.update(`${t.path}\0${t.size}\0${Math.round(t.mtimeMs)}
|
|
45
45
|
`);return n.digest("hex")}var Ko=require("fs"),fn=require("path");var Tl=require("fs"),Ol=require("readline"),Bn=class extends Error{constructor(t,r){super(t);this.sessionId=r;this.name="QuarantineError"}sessionId},ur={async*readLines(e){let n=(0,Ol.createInterface)({input:(0,Tl.createReadStream)(e,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY});try{for await(let t of n)yield t}finally{n.close()}}};function Be(e){return typeof e=="string"&&e.length>0?e:null}function Cl(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[]}function _l(e){return e.filter(n=>n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
|
|
46
46
|
`)}function Yh(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&"text"in n?String(n.text):"").join(`
|
|
47
|
-
`):e==null?"":JSON.stringify(e)}async function Go(e,n,t=ur){let r=null,o=null,s=null,i=null,a=null,d=null,c=0,u=[],p=[],l=new Map,f="";for await(let S of t.readLines(e)){let b=S.trim();if(b.length===0)continue;let E;try{E=JSON.parse(b)}catch{c++;continue}if(E===null||typeof E!="object"){c++;continue}r??=Be(E.sessionId),o??=Be(E.version),s??=Be(E.gitBranch),i??=Be(E.cwd);let k=Be(E.timestamp),I=Be(E.uuid)??"",y=E.isSidechain===!0,R=E.type;if(k&&(R==="user"||R==="assistant")&&(a??=k,d=k),R==="assistant"&&E.message){let _=Cl(E.message.content),C=[];for(let T of _)T.type==="tool_use"&&Be(T.id)&&Be(T.name)&&C.push({toolUseId:T.id,name:T.name,input:T.input??{}});u.push({messageUuid:I,timestamp:k??d??"",model:Be(E.message.model)??"",usage:E.message.usage??{},text:_l(_),toolUses:C,isSidechain:y,promptUuid:f})}else if(R==="user"&&E.message){let _=Cl(E.message.content),C=!1;for(let T of _)T.type==="tool_result"&&Be(T.tool_use_id)&&(C=!0,l.set(T.tool_use_id,{toolUseId:T.tool_use_id,isError:T.is_error===!0,content:Yh(T.content),timestamp:k??d??""}));if(!C){let T=_l(_);T.length>0&&(p.push({messageUuid:I,timestamp:k??"",text:T,isSidechain:y}),y||(f=I))}}}let m=r??n;if(u.length===0&&p.length===0)throw new Bn(`no coherent message spine (${c} unparseable line(s))`,m);let g=a??u[0]?.timestamp??p[0]?.timestamp??"";return{sessionId:m,version:o,gitBranch:s,cwd:i,turns:u,userPrompts:p,toolResults:l,firstTimestamp:g,lastTimestamp:d??g,skippedLines:c}}var zh="agent-transcripts",xl="subagents";function qh(e){return[e.root,...(e.subfolders??[]).map(t=>t.path)].map(t=>({name:Fn(t),path:t,found:!1}))}function Xh(e){let n=new Map;for(let t of Object.values(e.projects)){let r=Fn(t.root),o=n.get(r)??new Set;o.add(t.root),n.set(r,o)}for(let[t,r]of[...n.entries()].sort(([o],[s])=>o.localeCompare(s)))if(r.size>1)return{name:t,roots:[...r].sort()}}var wl={readdir(e){return(0,Ko.readdirSync)(e).sort()},stat(e){let n=(0,Ko.statSync)(e);return{size:n.size,mtimeMs:n.mtimeMs,birthtimeMs:Number.isFinite(n.birthtimeMs)?n.birthtimeMs:0,isDirectory:()=>n.isDirectory()}},readLines(e){return ur.readLines(e)}};function Ho(e,n){try{return[...e.readdir(n)].sort()}catch{return}}function Al(e,n){try{return e.stat(n).isDirectory()}catch{return!1}}function Zh(e,n,t,r,o){let s=(0,fn.join)(n,r),i=Ho(e,s)??[],a=[],d=(c,u)=>{try{let p=e.stat(c);if(p.isDirectory())return;a.push({path:c,size:p.size,mtimeMs:p.mtimeMs,birthtimeMs:p.birthtimeMs,isSidechain:u})}catch{o.unreadableFiles+=1}};if(i.includes(`${r}.jsonl`)&&d((0,fn.join)(s,`${r}.jsonl`),!1),i.includes(xl)){let c=(0,fn.join)(s,xl);for(let u of Ho(e,c)??[])u.endsWith(".jsonl")&&d((0,fn.join)(c,u),!0)}return o.notRead+=i.filter(c=>c.endsWith(".jsonl")&&c!==`${r}.jsonl`).length,a.length>0?{conversationId:r,folder:t,files:a}:void 0}function vl(e,n,t,r,o=Wc(t)){let s=Xh(n);if(s!==void 0)return{kind:"collision",...s};let i=qh(e),a=new Map(i.map(f=>[f.name,f])),d={notRead:0,unreadableFiles:0},c=[],u=[],p=0,l=new Set(Ho(r,o)??[]);for(let f of l)a.has(f)||(p+=1);for(let f of i){let m=(0,fn.join)(o,f.name),g=(0,fn.join)(m,zh);if(!l.has(f.name)||!Al(r,g)){u.push({...f,found:!1});continue}u.push({...f,found:!0});for(let h of Ho(r,g)??[]){let S=(0,fn.join)(g,h);if(!Al(r,S)){h.endsWith(".jsonl")&&(d.notRead+=1);continue}let b=Zh(r,g,f.name,h,d);b!==void 0&&c.push(b)}}return{kind:"ok",projectsRoot:o,folders:u,sessions:c,otherFolders:p,notRead:d.notRead,unreadableFiles:d.unreadableFiles}}var jl=require("path");var Vo=require("fs"),Pl=require("os"),Ge=require("path");function eS(e=(0,Pl.homedir)()){return(0,Ge.join)(e,".claude","projects")}var nS=40;async function tS(e,n){let t={cwd:null,gitBranch:null,version:null,sessionId:null},r=0,o=0;for await(let s of n.readLines(e)){let i=s.trim();if(i.length===0)continue;r++;let a=t.cwd&&t.gitBranch&&t.version&&t.sessionId;if(o<nS&&!a){o++;try{let d=JSON.parse(i);t.sessionId??=typeof d.sessionId=="string"?d.sessionId:null,t.cwd??=typeof d.cwd=="string"?d.cwd:null,t.gitBranch??=typeof d.gitBranch=="string"?d.gitBranch:null,t.version??=typeof d.version=="string"?d.version:null}catch{}}}return{...t,messageCount:r}}function sa(e,n){if(e===null)return!1;let t=(0,Ge.relative)(n,e);return t===""||!t.startsWith("..")&&!(0,Ge.isAbsolute)(t)}async function ia(e=eS(),n,t={}){let r=t.readdir??(f=>(0,Vo.readdirSync)(f)),o=t.stat??(f=>(0,Vo.statSync)(f)),s=t.lineSource??ur,i=n!==void 0,a=0,d=0,c=(f,m)=>i?{projectsRoot:e,projects:f,totalSessions:m,excludedOtherProject:a,excludedUnknownCwd:d}:{projectsRoot:e,projects:f,totalSessions:m},u;try{u=r(e)}catch{return c([],0)}let p=[],l=0;for(let f of u.sort()){let m=(0,Ge.join)(e,f),g;try{if(!o(m).isDirectory())continue;g=r(m)}catch{continue}let h=[];for(let S of g.sort()){if(!S.endsWith(".jsonl"))continue;let b=(0,Ge.join)(m,S),E=0,k=0;try{let y=o(b);E=y.size,k=y.mtimeMs}catch{continue}let I;try{I=await tS(b,s)}catch{I={cwd:null,gitBranch:null,version:null,sessionId:null,messageCount:0}}if(i&&!sa(I.cwd,n)){I.cwd===null?d++:a++;continue}h.push({sessionId:I.sessionId??(0,Ge.basename)(S,".jsonl"),file:b,project:f,cwd:I.cwd,gitBranch:I.gitBranch,version:I.version,sizeBytes:E,modifiedAt:new Date(k).toISOString(),messageCount:I.messageCount})}h.length>0&&(p.push({project:f,sessions:h}),l+=h.length)}return c(p,l)}var aa={unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0};function Dl(e,n){return{unparseableLines:e.unparseableLines+n.unparseableLines,truncatedLastLines:e.truncatedLastLines+n.truncatedLastLines,unknownRecords:e.unknownRecords+n.unknownRecords,turnsEndedWithError:e.turnsEndedWithError+n.turnsEndedWithError}}function Wo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rS(e){return Array.isArray(e)?e:typeof e=="string"?[{type:"text",text:e}]:[]}async function Nl(e,n,t){let r=[],o=[],s=0,i=0,a=0,d=!1,c=0;for await(let u of n.readLines(e)){c++;let p=u.trim();if(p.length===0)continue;d&&(s++,d=!1);let l;try{l=JSON.parse(p)}catch{d=!0;continue}if(!Wo(l)){i++;continue}if(l.type==="turn_ended"){(l.status==="error"||l.error!==void 0)&&a++;continue}let f=l.message;if(l.role!=="user"&&l.role!=="assistant"||!Wo(f)){i++;continue}if(l.role==="user"){o.push({messageUuid:"",timestamp:t.timestamp,text:"",isSidechain:t.isSidechain});continue}let m=[];rS(f.content).forEach((g,h)=>{!Wo(g)||g.type!=="tool_use"||m.push({toolUseId:`${t.idPrefix}:${c}:${h}`,name:typeof g.name=="string"?g.name:"",input:Wo(g.input)?g.input:{}})}),r.push({messageUuid:"",timestamp:t.timestamp,model:"",usage:{},text:"",toolUses:m,isSidechain:t.isSidechain,promptUuid:""})}return{turns:r,userPrompts:o,counts:{unparseableLines:s,truncatedLastLines:d?1:0,unknownRecords:i,turnsEndedWithError:a}}}var oS=1e3,q_={...aa,notActions:0,unmapped:0};function sS(e){let n=[],t=na(e);if(t.kind==="action")for(let o of t.candidates){let s=o.args.file_path;typeof s=="string"&&s!==""&&n.push(s)}let r=e.input?.cwd;return typeof r=="string"&&r!==""&&n.push(r),n.filter(o=>(0,jl.isAbsolute)(o))}function iS(e,n){for(let t of e)for(let r of sS(t))if(!sa(r,n))return!0;return!1}function aS(e,n){let t=e.args.full_command,r=wi(n,t);return r===void 0||r===t?e:{...e,args:{...e.args,full_command:bu(r)}}}function dS(e,n,t,r){let o=e.length>0?(t-n)/e.length:0,s=[];return e.forEach((i,a)=>{let d=na(i);if(d.kind==="not-action"){r.notActions+=1;return}if(d.kind==="unmapped"){r.unmapped+=1;return}s.push({vendorTool:d.vendorTool,call:aS(d.candidates[0],sl(i)),correlationId:null,ordinal:a,startMs:Math.round(n+a*o),endMs:Math.round(n+(a+1)*o),failed:!1})}),s}function cS(e,n){let t=d=>Number.isFinite(d)&&d>0,r=e.files.map(d=>d.mtimeMs).filter(t),o=e.files.map(d=>d.birthtimeMs).filter(t),s=r.length>0?Math.max(...r):0,i=o.length>0?Math.min(...o):0;return{startMs:i>0&&i<s?i:Math.max(0,s-Math.max(1,n)*oS),endMs:s}}async function Fl(e,n,t){let{conversationId:r}=e,o=[],s=aa,i=0,a="";for(let[f,m]of e.files.entries())try{let g=await Nl(m.path,t,{timestamp:"",isSidechain:m.isSidechain,idPrefix:`${r}:${f}`});for(let h of g.turns)o.push({uses:h.toolUses});s=Dl(s,g.counts),i+=1}catch(g){a=g.message}if(i===0)return{kind:"unreadable",conversationId:r,error:a};let d=o.flatMap(f=>f.uses);if(iS(d,n))return{kind:"outside-root",conversationId:r};let c=cS(e,o.length),u=o.length>0?(c.endMs-c.startMs)/o.length:0,p={notActions:0,unmapped:0},l=[];return o.forEach((f,m)=>{let g=Math.round(c.startMs+m*u),h=Math.round(c.startMs+(m+1)*u),S=dS(f.uses,g,h,p);S.length!==0&&l.push({conversationId:r,generationId:null,importOrdinal:m,startMs:g,endMs:h,model:null,usage:null,tools:S})}),l.length===0?{kind:"empty",conversationId:r}:{kind:"imported",conversationId:r,turns:l,counts:{...s,...p}}}var uS=6;function lS(e){return`bf_${e.toString(36)}_${Math.random().toString(36).slice(2,10)}`}function pS(e,n,t){let r=new Set,{files:o}=gl(St(e,n),t);for(let s of o){let i=s.entry;i===void 0||i.kind!=="capture"||i.conversationId!==null&&r.add(i.conversationId)}return r}function da(e,n){e.io.log(`Cursor projects root: ${n.projectsRoot}`);for(let t of n.folders)e.io.log(t.found?` ${t.path} -> ${t.name} (found)`:` ${t.path} -> ${t.name} (no folder with this name; if Cursor named it something else, that is what to report)`)}function Ml(e,n){return e.io.error(`error: Cursor names these projects the same folder (${n.name}), so their sessions cannot be told apart: ${n.roots.join(", ")}. Importing either would file the other's sessions under it. Run \`${V("cursor","setup")} --unregister\` in one of them, or move it, then import again.`),1}function fS(e,n,t,r){let o=se(n,t);if(o.kind==="unreadable")return e.io.error(`error: ${M(n).projects} cannot be read. Fix or delete it, then run \`${V("cursor","setup")}\`.`),1;let s;try{s=r(e.io.cwd)}catch{s=e.io.cwd}let i=o.kind==="ok"?o.registry:tu,a=bi(i,[s],e.io.env.CURSOR_PROJECT_DIR);return a===void 0?(e.io.error(`error: ${s} is unregistered. Run \`${V("cursor","setup")}\` in the folder you open in Cursor, then import.`),1):{record:a,registry:i}}async function gS(e,n,t,r){let o={},s={notActions:0,unmapped:0,unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0},i={},a=0,d=0,c=0,u=0,p=0,l=pS(t.home,e.projectKey,t.io),f=0,m=n.filter(R=>l.has(R.conversationId)?(f+=1,ge(o,"queued"),r.emit?.({event:"queued-skip",conversationId:R.conversationId}),!1):!0),g=0,h=!0,S=m;if(!t.reimport){let R=await $o(m.map(_=>_.conversationId),{endpoint:t.endpoint,token:t.token},{fetch:r.upload?.fetch});h=R.ok,R.ok&&R.known.size>0&&(S=m.filter(_=>R.known.has(_.conversationId)?(g+=1,r.emit?.({event:"dedup-skip",conversationId:_.conversationId}),!1):!0))}let b=oa(t.home,t.io);r.emit?.({event:"import-start",batchId:t.batchId,total:n.length,queuedSkipped:f,dedupSkipped:g,dedupOk:h,dryRun:t.dryRun});let E=Ui(t.orgId),k=Je(xe),I=await dr(S,t.concurrency,async R=>{let _=kl(R.files);if(t.resume&&!cr(b,R.conversationId,_))return{session:R,sourceHash:_,kind:"skipped"};let C=await Fl(R,e.root,t.scanIO);if(C.kind!=="imported")return{session:R,sourceHash:_,kind:C.kind,error:"error"in C?C.error:""};let T=mS(C.turns,{record:e,orgId:t.orgId,agentId:E,captureContent:t.captureContent,batchId:t.batchId,resolvedScrubbers:k}),$=await pn($e(T),{endpoint:t.endpoint,token:t.token,dryRun:t.dryRun},r.upload);return{session:R,sourceHash:_,kind:$.status==="failed"?"failed":"done",counts:C.counts,body:T,httpStatus:$.httpStatus,error:$.error}});for(let R of I){let _=R.session.conversationId;if(R.kind==="skipped")u+=1;else if(R.kind==="outside-root")ge(o,"outside-root");else if(R.kind==="empty")ge(o,"empty");else if(R.kind==="unreadable")ge(o,"unreadable"),b=$n(b,_,{status:"quarantined",sourceHash:R.sourceHash,batchId:t.batchId,error:R.error});else{let C=R.body;p+=C.spans.length,a+=C.redactions.total;for(let[T,$]of Object.entries(C.redactions.byType))i[T]=(i[T]??0)+$;for(let T of Object.keys(s))s[T]+=R.counts?.[T]??0;R.kind==="failed"?(c+=1,R.httpStatus!==void 0&&ge(o,`rejected-${R.httpStatus}`)):d+=1,b=$n(b,_,{status:R.kind,sourceHash:R.sourceHash,batchId:t.batchId,error:R.error})}r.emit?.({event:"session",conversationId:_,status:R.kind,spans:R.kind==="done"||R.kind==="failed"?R.body?.spans.length:0,httpStatus:R.httpStatus})}t.dryRun||bl(t.home,b,t.io);let y={total:n.length,imported:d,failed:c,skipped:u,dedupSkipped:g,dedupOk:h,queuedSkipped:f,spans:p,dropped:o,notImported:s,otherFolders:t.otherFolders,notRead:t.notRead,redactions:{total:a,byType:i}};return r.emit?.({event:"import-done",batchId:t.batchId,...yS(y)}),y}function mS(e,n){let t=e.map(o=>No(o,{orgId:n.orgId,project:{projectId:n.record.projectId,projectLabel:n.record.projectLabel,...n.record.developerId!==void 0?{developerId:n.record.developerId}:{}},captureContent:n.captureContent,mode:"import",scopeVersion:"0.0.0",batchId:n.batchId,resolvedScrubbers:n.resolvedScrubbers})),r=t[0];if(r===void 0)throw new Error("a conversation with no turn never reaches the span builder");return{resource:r.resource,scope:r.scope,spans:t.flatMap(o=>o.spans),redactions:{total:t.reduce((o,s)=>o+s.redactions.total,0),byType:t.reduce((o,s)=>{for(let[i,a]of Object.entries(s.redactions.byType))o[i]=(o[i]??0)+a;return o},{})}}}function yS(e){return{total:e.total,imported:e.imported,failed:e.failed,skipped:e.skipped,dedupSkipped:e.dedupSkipped,dedupOk:e.dedupOk,queuedSkipped:e.queuedSkipped,spans:e.spans,dropped:e.dropped,notImported:e.notImported,otherFolders:e.otherFolders,notRead:e.notRead}}async function Ll(e,n={}){let t=e.flags,r=[t.scan,t.import,t.status,t.resume].filter(Boolean).length;if(r===0)return e.io.error("error: backfill needs one of --scan | --import | --status | --resume."),1;if(r>1)return e.io.error("error: pass exactly one of --scan | --import | --status | --resume."),1;let o;try{o=e.sessionEnv()}catch(I){return e.io.error(`error: ${I.message}`),1}let s=o.homeDir,i=n.io??O,a=n.scanIO??wl,d=n.realpath??(I=>I),c=fS(e,s,i,d);if(typeof c=="number")return c;let{record:u,registry:p}=c,l=vl(u,p,s,a);if(t.status){let I=oa(s,i),y=Object.entries(I.sessions);e.io.log(`Cursor import record: ${M(s).backfillState}`),e.io.log(` conversations recorded: ${y.length}`);for(let[R,_]of y)e.io.log(` ${R}: ${_.status} (batch ${_.batchId}, ${_.updatedAt})`);return l.kind==="ok"?da(e,l):Ml(e,l),n.emit?.({event:"status",sessions:I.sessions}),0}if(l.kind==="collision")return Ml(e,l);if(t.scan)return da(e,l),e.io.log(`Conversations found for ${u.projectSlug}: ${l.sessions.length}`),e.io.log(`Other projects' folders on this machine: ${l.otherFolders} (counted, never opened)`),n.emit?.({event:"scan",projectsRoot:l.projectsRoot,folders:l.folders,conversations:l.sessions.length,otherFolders:l.otherFolders,notRead:l.notRead,unreadableFiles:l.unreadableFiles}),0;let f=Fe(o),m=t.endpoint?.trim()||e.io.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||f?.endpoint,g=t.key?.trim()||f?.ingest_token,h=t.org?.trim()||f?.org_id||u.orgId;if(!m||!g)return e.io.error(`error: not signed in for Cursor. Run \`${V("cursor","login")}\`, or pass --endpoint and --key.`),1;let S=uS;if(t.concurrency){let I=Number(t.concurrency);if(!Number.isInteger(I)||I<1)return e.io.error(`error: invalid --concurrency '${t.concurrency}' (positive integer).`),1;S=I}let b=!!t.content||u.captureContent;if(b&&e.io.error("note: a Cursor session file holds no prompt or response text, so --content adds tool inputs (commands and paths) and nothing a person typed. They are edge-scrubbed on this machine, and your org's config is applied again on arrival."),t.since)return e.io.error("error: --since is not supported for Cursor yet. A Cursor session file carries no time of its own, so the import is bounded by the project you run it in, not by a window."),1;let E=!!t["dry-run"],k=await gS(u,l.sessions,{home:s,io:i,scanIO:a,endpoint:m,token:g,orgId:h,captureContent:b,dryRun:E,reimport:!!t.reimport,resume:!!t.resume,concurrency:S,batchId:lS((n.now??Date.now)()),otherFolders:l.otherFolders,notRead:l.notRead},n);da(e,l),e.io.log(`Cursor import ${E?"(dry-run) ":""}complete for ${u.projectSlug}: ${k.imported} imported, ${k.failed} failed, ${k.skipped} unchanged (of ${k.total} conversations), ${k.spans} spans.`),k.queuedSkipped>0&&e.io.log(`${k.queuedSkipped} conversation(s) are still queued for live upload and were left to the sender.`),k.dedupSkipped>0&&e.io.log(`${k.dedupSkipped} conversation(s) AgentTrail already holds (live capture or an earlier import) were skipped.`),k.dedupOk||e.io.log("The `already recorded?` check could not run, so every conversation was treated as new. Imported spans replace rather than duplicate, because their ids and times are fixed \u2014 re-run when AgentTrail is reachable to get the skip counts back.");for(let[I,y]of Object.entries(k.dropped))e.io.log(`Not imported (${I}): ${y}`);return k.otherFolders>0&&e.io.log(`${k.otherFolders} folder(s) under ${l.projectsRoot} belong to other projects and were not opened.`),e.io.log(""),k.redactions.total>0&&e.io.log(`Edge-scrubbed ${k.redactions.total} secret-shaped value(s) on this machine before upload (${Object.keys(k.redactions.byType).sort().join(", ")}).`),e.io.log("Imported spans are marked approximate and carry no model, tokens or cost: a Cursor session file records none. They are never metered."),k.failed>0?1:0}var Kl=require("path");var Ul=require("crypto"),$l=require("uuid");function Bl(e,n){return(0,$l.v5)(`${e}:${n}`,xs).replace(/-/g,"")}function Qo(e,n,t){return(0,Ul.createHash)("sha256").update(`${e}:${n}:${t}`).digest("hex").slice(0,16)}function hS(e,n){return e===""?n:n===""||Date.parse(e)>=Date.parse(n)?e:n}function SS(e,n,t,r){let{sessionId:o,toolResults:s}=e,i=[],a=null;for(let d of r){let c=Qo(o,d.messageUuid,"llm"),u=d.isSidechain?a??t:t;i.push({role:"llm",spanId:c,parentSpanId:u,promptId:n,startTs:d.timestamp,endTs:d.timestamp,failed:!1,turn:d});for(let p of d.toolUses){let l=s.get(p.toolUseId),f=Qo(o,d.messageUuid,p.toolUseId);i.push({role:"tool",spanId:f,parentSpanId:c,promptId:n,startTs:d.timestamp,endTs:l?.timestamp||d.timestamp,failed:l?.isError??!1,tool:p,toolResult:l}),!d.isSidechain&&p.name==="Task"&&(a=f)}}return i}function Gl(e){let{sessionId:n,turns:t,userPrompts:r}=e,o=r.filter(p=>!p.isSidechain),s=o.length>0,i=s?o[0].messageUuid:"",a=p=>p.promptUuid!==""?p.promptUuid:i,d=new Map;for(let p of t){let l=a(p),f=d.get(l);f?f.push(p):d.set(l,[p])}let c=s?o.map(p=>({promptId:p.messageUuid,text:p.text,ts:p.timestamp})):[{promptId:"",text:"",ts:""}],u=[];for(let p of c){let l=Qo(n,p.promptId,"root"),f=SS(e,p.promptId,l,d.get(p.promptId)??[]),m=f.map(S=>S.startTs).find(S=>S!==""),g=p.ts!==""?p.ts:m??e.firstTimestamp??"",h=g;for(let S of f)h=hS(h,S.endTs);u.push({role:"agent",spanId:l,parentSpanId:"",promptId:p.promptId,startTs:g,endTs:h,failed:!1,promptText:p.text}),u.push(...f)}return u}var RS=1,ES=3,IS="claude-code-backfill",bS="claude-code-session-upload";function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function kS(e){let n=_t(e.input_tokens),t=_t(e.output_tokens),r=_t(e.cache_read_input_tokens),o=_t(e.cache_creation_input_tokens),s={"gen_ai.usage.input_tokens":String(n),input_tokens:String(n),"gen_ai.usage.output_tokens":String(t),output_tokens:String(t),"gen_ai.usage.cache_read.input_tokens":String(r),cache_read_input_tokens:String(r),"gen_ai.usage.cache_creation.input_tokens":String(o),cache_creation_input_tokens:String(o)};if(e.cache_creation!==void 0){let i=_t(e.cache_creation.ephemeral_5m_input_tokens),a=_t(e.cache_creation.ephemeral_1h_input_tokens);s["gen_ai.usage.cache_creation.ephemeral_5m.input_tokens"]=String(i),s.cache_creation_ephemeral_5m_input_tokens=String(i),s["gen_ai.usage.cache_creation.ephemeral_1h.input_tokens"]=String(a),s.cache_creation_ephemeral_1h_input_tokens=String(a)}return typeof e.speed=="string"&&e.speed!==""&&(s.speed=e.speed),typeof e.inference_geo=="string"&&e.inference_geo.length>0&&(s["gen_ai.usage.inference_geo"]=e.inference_geo),s}function Hl(e){let n=Date.parse(e);return Number.isNaN(n)?"0":(BigInt(n)*1000000n).toString()}function Vl(e){return e.provenance==="live"?{}:{[wn]:st,[vn]:e.batchId}}function CS(e,n,t,r){let o={...Vl(t),"session.id":n.sessionId,...r?{[js]:r}:{}};if(e.role==="agent")return{...o,...hu(e.promptText??"",t.captureContent)};if(e.role==="llm"&&e.turn){let{turn:s}=e;return{...o,"gen_ai.system":"anthropic","gen_ai.request.model":s.model,"gen_ai.conversation.id":n.sessionId,...kS(s.usage),...Su(s.text,t.captureContent)}}if(e.role==="tool"&&e.tool){let s={...o,"gen_ai.tool.name":e.tool.name,"gen_ai.tool.call.id":e.tool.toolUseId,...Ru(e.tool.input,e.toolResult?.content,t.captureContent)};return e.failed&&(s["otel.status_code"]="ERROR"),s}return o}function Jo(e,n){let t=Gl(e),r=e.cwd?(0,Kl.basename)(Dn(e.cwd)):null,o=n.resolved??null,s=0,i={},a=t.map(c=>{let u=Ao(CS(c,e,n,r),o);s+=u.redactedCount;for(let p in u.byType)i[p]=(i[p]??0)+u.byType[p];return{traceId:Bl(e.sessionId,c.promptId),spanId:c.spanId,parentSpanId:c.parentSpanId,name:c.role==="agent"?"session":c.role==="llm"?"chat":c.tool?.name??"tool",kind:c.role==="llm"?ES:RS,startTimeUnixNano:Hl(c.startTs),endTimeUnixNano:Hl(c.endTs),attributes:u.attributes,error:c.failed}}),d={[De]:n.orgId,[Kt]:n.projectId,[Ps]:Le(n.orgId,pe),[Ds]:pe,...Vl(n)};return n.developerId&&(d[Ns]=n.developerId),{resource:{attributes:d},scope:{name:n.provenance==="live"?bS:IS,version:n.scopeVersion??"0.0.0"},spans:a,redactions:{total:s,byType:i}}}var _S=6;function TS(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function OS(e){if(e.cwd){let n=ct(e.cwd);if(n)return n}return oo(e.project)||"default"}function xS(e,n){let t=[];for(let r of e.projects)for(let o of r.sessions)n.sinceMs!==void 0&&Date.parse(o.modifiedAt)<n.sinceMs||t.push(o);return t}async function Wl(e,n={}){let t=await ia(e.projectsRoot,e.projectRoot,{...n.scanIO,lineSource:n.lineSource??n.scanIO?.lineSource});return n.emit?.({event:"scan",...t}),t}function Ql(e,n={}){let t=ta(e.homeDir,n.checkpointIO);return n.emit?.({event:"status",sessions:t.sessions}),t}async function Jl(e,n,t={}){let r=vS(),o=t.hashFile??Rl,s=Je(e.scrubConfig??xe),i=await ia(e.projectsRoot,e.projectRoot,{...t.scanIO,lineSource:t.lineSource??t.scanIO?.lineSource}),a=xS(i,e),d=a.length,c=Math.max(1,e.concurrency??_S),u=ta(e.homeDir,t.checkpointIO),p=await dr(a,c,async T=>{try{return await o(T.file)}catch($){return`unhashable:${$.message}`}}),l=new Map;a.forEach((T,$)=>{l.set(T.sessionId,p[$])});let f=0,m=!0,g=a;if(!e.reimport){let T=await $o(a.map($=>$.sessionId),{endpoint:e.endpoint,token:e.token},{fetch:t.upload?.fetch});if(m=T.ok,T.ok&&T.known.size>0){let $=[];for(let x of a)wS(T.known,u,x.sessionId,l.get(x.sessionId)??"")?(f++,t.emit?.({event:"dedup-skip",sessionId:x.sessionId})):$.push(x);g=$}}t.emit?.({event:"import-start",batchId:r,total:d,dedupSkipped:f,dedupOk:m,dryRun:e.dryRun??!1});let h=[],S=0,b=0,E=0,k=0,I=0,y=0,R=0,_={};for(let T of TS(g,c)){let $=await dr(T,c,async x=>{let ce=l.get(x.sessionId)??"";if(n&&!cr(u,x.sessionId,ce))return{item:x,kind:"skipped",sourceHash:ce};let Ze;try{Ze=await Go(x.file,x.sessionId,t.lineSource)}catch(Mt){let Rn=(Mt instanceof Bn,Mt.message);return{item:x,kind:"quarantined",sourceHash:ce,error:Rn}}if(e.retentionCutoffMs!==void 0&&Date.parse(Ze.firstTimestamp)<e.retentionCutoffMs)return{item:x,kind:"skipped-retention",sourceHash:ce};let Sn=ne(e.orgId,OS(x)),Oe=Jo(Ze,{orgId:e.orgId,projectId:Sn,developerId:e.developerId,batchId:r,captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:s}),Ft=await pn($e(Oe),{endpoint:e.endpoint,token:e.token,dryRun:e.dryRun},t.upload);return{item:x,kind:Ft.status==="failed"?"failed":"done",sourceHash:ce,spans:Oe.spans.length,error:Ft.error,upload:Ft,redactions:Oe.redactions}});for(let x of $){if(x.redactions){R+=x.redactions.total;for(let ce in x.redactions.byType)_[ce]=(_[ce]??0)+x.redactions.byType[ce]}x.kind==="skipped"?b++:x.kind==="skipped-retention"?I++:x.kind==="quarantined"?(k++,u=$n(u,x.item.sessionId,{status:"quarantined",sourceHash:x.sourceHash,batchId:r,error:x.error})):(x.kind==="failed"?E++:S++,y+=x.spans??0,u=$n(u,x.item.sessionId,{status:x.kind,sourceHash:x.sourceHash,batchId:r,error:x.error})),h.push({sessionId:x.item.sessionId,project:x.item.project,status:x.kind,spans:x.spans,error:x.error,upload:x.upload}),t.emit?.({event:"session",sessionId:x.item.sessionId,status:x.kind,spans:x.spans,httpStatus:x.upload?.httpStatus})}Sl(e.homeDir,u,t.checkpointIO)}let C={total:d,imported:S,skipped:b,failed:E,quarantined:k,retentionSkipped:I,dedupSkipped:f,dedupOk:m,estimatedActions:y,outcomes:h,redactions:{total:R,byType:_},excludedOtherProject:i.excludedOtherProject??0,excludedUnknownCwd:i.excludedUnknownCwd??0};return t.emit?.({event:"import-done",batchId:r,...AS(C),dedupOk:C.dedupOk,redactions:C.redactions}),C}function AS(e){return{total:e.total,imported:e.imported,skipped:e.skipped,failed:e.failed,quarantined:e.quarantined,retentionSkipped:e.retentionSkipped,dedupSkipped:e.dedupSkipped,estimatedActions:e.estimatedActions,excludedOtherProject:e.excludedOtherProject,excludedUnknownCwd:e.excludedUnknownCwd}}function wS(e,n,t,r){if(!e.has(t))return!1;let o=n.sessions[t];return!(o!==void 0&&(o.status!=="done"||o.sourceHash!==r))}function vS(){return`bf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Yl(e){return Re(e,"setup")}function zl(e){return Re(e,"logout")}function ql(e,n="status"){return Re(e,n)}var Xe=require("fs"),q=require("path");var Xl=require("fs"),lr=require("path");var PS=15e3,DS=200;async function Zl(e,n,t,r={}){let o=r.io??O,s=N(e,n).root;return o.mkdirp(s,rn),je({lockPath:(0,lr.join)(s,"install.lock"),io:r.lockIO,timeoutMs:PS},t)}function ep(e,n,t,r){let o=N(e,n).queue,s=0,i=(()=>{if(r!==void 0)return[r];try{return t.exists(o)?t.readdir(o):[]}catch{return[]}})();for(let a of i)try{let d=on(e,n,a);t.exists(d)&&(s+=t.readdir(d).filter(c=>c.endsWith(".json")).length)}catch{}return s}async function np(e,n,t,r){let o=r.io??O,s=r.now??(()=>Date.now()),i=r.sleep??(l=>new Promise(f=>setTimeout(f,l))),a=r.run,d=N(e,n).senderLock,c=s()+t,u=()=>Math.max(0,c-s());if(await a({home:e,maxRunMs:u()}),!o.exists(d))return{waited:!1,stillLocked:!1};let p=!1;for(;o.exists(d)&&u()>0;)p=!0,await i(Math.min(DS,u()));return o.exists(d)?{waited:p,stillLocked:!0}:(await a({home:e,maxRunMs:u()}),{waited:p,stillLocked:!1})}function tp(e,n,t){let r=dt(e);return r!==null?t(r):n.filter(s=>e===s||e.startsWith(s.endsWith(lr.sep)?s:`${s}${lr.sep}`)).sort((s,i)=>i.length-s.length)[0]??e}function rp(e,n,t){let r=ut(e),o=t.project?.trim();if(o)return{slug:o,id:ne(n,o),source:"flag",label:r};let s=Qs(e);if(s!==null)try{let a=to(JSON.parse((0,Xl.readFileSync)(s,"utf8"))),d=a.orgId===n&&a.projectId!==void 0?a.projectId:ne(n,a.projectSlug);return{slug:a.projectSlug,id:d,source:"agenttrail-json",label:r}}catch(a){return{error:`${s} cannot be read as a ${Y} (${a.message}). Fix it, or pass --project <slug>.`}}let i=Nn(e);return i===null?{error:"could not work out a project slug for this folder. Pass --project <slug>."}:{slug:i.slug,id:ne(n,i.slug),source:"derived",label:r,note:i.source==="directory"?"NOTE: no git remote found \u2014 this project's identity comes from its directory name and may differ on another machine. Add an `origin` remote for a stable one.":void 0}}var NS=require("fs");function ca(e,n,t=O){let r=Tt(e,t),o=r===void 0?n:{...n,writtenAt:r.writtenAt};return r!==void 0&&JSON.stringify(r)===JSON.stringify(o)?!1:(t.writeFileAtomic(M(e).enforcement,`${JSON.stringify(o,null,2)}
|
|
47
|
+
`):e==null?"":JSON.stringify(e)}async function Go(e,n,t=ur){let r=null,o=null,s=null,i=null,a=null,d=null,c=0,u=[],p=[],l=new Map,f="";for await(let S of t.readLines(e)){let b=S.trim();if(b.length===0)continue;let E;try{E=JSON.parse(b)}catch{c++;continue}if(E===null||typeof E!="object"){c++;continue}r??=Be(E.sessionId),o??=Be(E.version),s??=Be(E.gitBranch),i??=Be(E.cwd);let k=Be(E.timestamp),I=Be(E.uuid)??"",y=E.isSidechain===!0,R=E.type;if(k&&(R==="user"||R==="assistant")&&(a??=k,d=k),R==="assistant"&&E.message){let _=Cl(E.message.content),C=[];for(let T of _)T.type==="tool_use"&&Be(T.id)&&Be(T.name)&&C.push({toolUseId:T.id,name:T.name,input:T.input??{}});u.push({messageUuid:I,timestamp:k??d??"",model:Be(E.message.model)??"",usage:E.message.usage??{},text:_l(_),toolUses:C,isSidechain:y,promptUuid:f})}else if(R==="user"&&E.message){let _=Cl(E.message.content),C=!1;for(let T of _)T.type==="tool_result"&&Be(T.tool_use_id)&&(C=!0,l.set(T.tool_use_id,{toolUseId:T.tool_use_id,isError:T.is_error===!0,content:Yh(T.content),timestamp:k??d??""}));if(!C){let T=_l(_);T.length>0&&(p.push({messageUuid:I,timestamp:k??"",text:T,isSidechain:y}),y||(f=I))}}}let m=r??n;if(u.length===0&&p.length===0)throw new Bn(`no coherent message spine (${c} unparseable line(s))`,m);let g=a??u[0]?.timestamp??p[0]?.timestamp??"";return{sessionId:m,version:o,gitBranch:s,cwd:i,turns:u,userPrompts:p,toolResults:l,firstTimestamp:g,lastTimestamp:d??g,skippedLines:c}}var zh="agent-transcripts",xl="subagents";function qh(e){return[e.root,...(e.subfolders??[]).map(t=>t.path)].map(t=>({name:Fn(t),path:t,found:!1}))}function Xh(e){let n=new Map;for(let t of Object.values(e.projects)){let r=Fn(t.root),o=n.get(r)??new Set;o.add(t.root),n.set(r,o)}for(let[t,r]of[...n.entries()].sort(([o],[s])=>o.localeCompare(s)))if(r.size>1)return{name:t,roots:[...r].sort()}}var wl={readdir(e){return(0,Ko.readdirSync)(e).sort()},stat(e){let n=(0,Ko.statSync)(e);return{size:n.size,mtimeMs:n.mtimeMs,birthtimeMs:Number.isFinite(n.birthtimeMs)?n.birthtimeMs:0,isDirectory:()=>n.isDirectory()}},readLines(e){return ur.readLines(e)}};function Ho(e,n){try{return[...e.readdir(n)].sort()}catch{return}}function Al(e,n){try{return e.stat(n).isDirectory()}catch{return!1}}function Zh(e,n,t,r,o){let s=(0,fn.join)(n,r),i=Ho(e,s)??[],a=[],d=(c,u)=>{try{let p=e.stat(c);if(p.isDirectory())return;a.push({path:c,size:p.size,mtimeMs:p.mtimeMs,birthtimeMs:p.birthtimeMs,isSidechain:u})}catch{o.unreadableFiles+=1}};if(i.includes(`${r}.jsonl`)&&d((0,fn.join)(s,`${r}.jsonl`),!1),i.includes(xl)){let c=(0,fn.join)(s,xl);for(let u of Ho(e,c)??[])u.endsWith(".jsonl")&&d((0,fn.join)(c,u),!0)}return o.notRead+=i.filter(c=>c.endsWith(".jsonl")&&c!==`${r}.jsonl`).length,a.length>0?{conversationId:r,folder:t,files:a}:void 0}function vl(e,n,t,r,o=Wc(t)){let s=Xh(n);if(s!==void 0)return{kind:"collision",...s};let i=qh(e),a=new Map(i.map(f=>[f.name,f])),d={notRead:0,unreadableFiles:0},c=[],u=[],p=0,l=new Set(Ho(r,o)??[]);for(let f of l)a.has(f)||(p+=1);for(let f of i){let m=(0,fn.join)(o,f.name),g=(0,fn.join)(m,zh);if(!l.has(f.name)||!Al(r,g)){u.push({...f,found:!1});continue}u.push({...f,found:!0});for(let h of Ho(r,g)??[]){let S=(0,fn.join)(g,h);if(!Al(r,S)){h.endsWith(".jsonl")&&(d.notRead+=1);continue}let b=Zh(r,g,f.name,h,d);b!==void 0&&c.push(b)}}return{kind:"ok",projectsRoot:o,folders:u,sessions:c,otherFolders:p,notRead:d.notRead,unreadableFiles:d.unreadableFiles}}var jl=require("path");var Vo=require("fs"),Pl=require("os"),Ge=require("path");function eS(e=(0,Pl.homedir)()){return(0,Ge.join)(e,".claude","projects")}var nS=40;async function tS(e,n){let t={cwd:null,gitBranch:null,version:null,sessionId:null},r=0,o=0;for await(let s of n.readLines(e)){let i=s.trim();if(i.length===0)continue;r++;let a=t.cwd&&t.gitBranch&&t.version&&t.sessionId;if(o<nS&&!a){o++;try{let d=JSON.parse(i);t.sessionId??=typeof d.sessionId=="string"?d.sessionId:null,t.cwd??=typeof d.cwd=="string"?d.cwd:null,t.gitBranch??=typeof d.gitBranch=="string"?d.gitBranch:null,t.version??=typeof d.version=="string"?d.version:null}catch{}}}return{...t,messageCount:r}}function sa(e,n){if(e===null)return!1;let t=(0,Ge.relative)(n,e);return t===""||!t.startsWith("..")&&!(0,Ge.isAbsolute)(t)}async function ia(e=eS(),n,t={}){let r=t.readdir??(f=>(0,Vo.readdirSync)(f)),o=t.stat??(f=>(0,Vo.statSync)(f)),s=t.lineSource??ur,i=n!==void 0,a=0,d=0,c=(f,m)=>i?{projectsRoot:e,projects:f,totalSessions:m,excludedOtherProject:a,excludedUnknownCwd:d}:{projectsRoot:e,projects:f,totalSessions:m},u;try{u=r(e)}catch{return c([],0)}let p=[],l=0;for(let f of u.sort()){let m=(0,Ge.join)(e,f),g;try{if(!o(m).isDirectory())continue;g=r(m)}catch{continue}let h=[];for(let S of g.sort()){if(!S.endsWith(".jsonl"))continue;let b=(0,Ge.join)(m,S),E=0,k=0;try{let y=o(b);E=y.size,k=y.mtimeMs}catch{continue}let I;try{I=await tS(b,s)}catch{I={cwd:null,gitBranch:null,version:null,sessionId:null,messageCount:0}}if(i&&!sa(I.cwd,n)){I.cwd===null?d++:a++;continue}h.push({sessionId:I.sessionId??(0,Ge.basename)(S,".jsonl"),file:b,project:f,cwd:I.cwd,gitBranch:I.gitBranch,version:I.version,sizeBytes:E,modifiedAt:new Date(k).toISOString(),messageCount:I.messageCount})}h.length>0&&(p.push({project:f,sessions:h}),l+=h.length)}return c(p,l)}var aa={unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0};function Dl(e,n){return{unparseableLines:e.unparseableLines+n.unparseableLines,truncatedLastLines:e.truncatedLastLines+n.truncatedLastLines,unknownRecords:e.unknownRecords+n.unknownRecords,turnsEndedWithError:e.turnsEndedWithError+n.turnsEndedWithError}}function Wo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rS(e){return Array.isArray(e)?e:typeof e=="string"?[{type:"text",text:e}]:[]}async function Nl(e,n,t){let r=[],o=[],s=0,i=0,a=0,d=!1,c=0;for await(let u of n.readLines(e)){c++;let p=u.trim();if(p.length===0)continue;d&&(s++,d=!1);let l;try{l=JSON.parse(p)}catch{d=!0;continue}if(!Wo(l)){i++;continue}if(l.type==="turn_ended"){(l.status==="error"||l.error!==void 0)&&a++;continue}let f=l.message;if(l.role!=="user"&&l.role!=="assistant"||!Wo(f)){i++;continue}if(l.role==="user"){o.push({messageUuid:"",timestamp:t.timestamp,text:"",isSidechain:t.isSidechain});continue}let m=[];rS(f.content).forEach((g,h)=>{!Wo(g)||g.type!=="tool_use"||m.push({toolUseId:`${t.idPrefix}:${c}:${h}`,name:typeof g.name=="string"?g.name:"",input:Wo(g.input)?g.input:{}})}),r.push({messageUuid:"",timestamp:t.timestamp,model:"",usage:{},text:"",toolUses:m,isSidechain:t.isSidechain,promptUuid:""})}return{turns:r,userPrompts:o,counts:{unparseableLines:s,truncatedLastLines:d?1:0,unknownRecords:i,turnsEndedWithError:a}}}var oS=1e3,oT={...aa,notActions:0,unmapped:0};function sS(e){let n=[],t=na(e);if(t.kind==="action")for(let o of t.candidates){let s=o.args.file_path;typeof s=="string"&&s!==""&&n.push(s)}let r=e.input?.cwd;return typeof r=="string"&&r!==""&&n.push(r),n.filter(o=>(0,jl.isAbsolute)(o))}function iS(e,n){for(let t of e)for(let r of sS(t))if(!sa(r,n))return!0;return!1}function aS(e,n){let t=e.args.full_command,r=wi(n,t);return r===void 0||r===t?e:{...e,args:{...e.args,full_command:bu(r)}}}function dS(e,n,t,r){let o=e.length>0?(t-n)/e.length:0,s=[];return e.forEach((i,a)=>{let d=na(i);if(d.kind==="not-action"){r.notActions+=1;return}if(d.kind==="unmapped"){r.unmapped+=1;return}s.push({vendorTool:d.vendorTool,call:aS(d.candidates[0],sl(i)),correlationId:null,ordinal:a,startMs:Math.round(n+a*o),endMs:Math.round(n+(a+1)*o),failed:!1})}),s}function cS(e,n){let t=d=>Number.isFinite(d)&&d>0,r=e.files.map(d=>d.mtimeMs).filter(t),o=e.files.map(d=>d.birthtimeMs).filter(t),s=r.length>0?Math.max(...r):0,i=o.length>0?Math.min(...o):0;return{startMs:i>0&&i<s?i:Math.max(0,s-Math.max(1,n)*oS),endMs:s}}async function Fl(e,n,t){let{conversationId:r}=e,o=[],s=aa,i=0,a="";for(let[f,m]of e.files.entries())try{let g=await Nl(m.path,t,{timestamp:"",isSidechain:m.isSidechain,idPrefix:`${r}:${f}`});for(let h of g.turns)o.push({uses:h.toolUses});s=Dl(s,g.counts),i+=1}catch(g){a=g.message}if(i===0)return{kind:"unreadable",conversationId:r,error:a};let d=o.flatMap(f=>f.uses);if(iS(d,n))return{kind:"outside-root",conversationId:r};let c=cS(e,o.length),u=o.length>0?(c.endMs-c.startMs)/o.length:0,p={notActions:0,unmapped:0},l=[];return o.forEach((f,m)=>{let g=Math.round(c.startMs+m*u),h=Math.round(c.startMs+(m+1)*u),S=dS(f.uses,g,h,p);S.length!==0&&l.push({conversationId:r,generationId:null,importOrdinal:m,startMs:g,endMs:h,model:null,usage:null,tools:S})}),l.length===0?{kind:"empty",conversationId:r}:{kind:"imported",conversationId:r,turns:l,counts:{...s,...p}}}var uS=6;function lS(e){return`bf_${e.toString(36)}_${Math.random().toString(36).slice(2,10)}`}function pS(e,n,t){let r=new Set,{files:o}=gl(St(e,n),t);for(let s of o){let i=s.entry;i===void 0||i.kind!=="capture"||i.conversationId!==null&&r.add(i.conversationId)}return r}function da(e,n){e.io.log(`Cursor projects root: ${n.projectsRoot}`);for(let t of n.folders)e.io.log(t.found?` ${t.path} -> ${t.name} (found)`:` ${t.path} -> ${t.name} (no folder with this name; if Cursor named it something else, that is what to report)`)}function Ml(e,n){return e.io.error(`error: Cursor names these projects the same folder (${n.name}), so their sessions cannot be told apart: ${n.roots.join(", ")}. Importing either would file the other's sessions under it. Run \`${V("cursor","setup")} --unregister\` in one of them, or move it, then import again.`),1}function fS(e,n,t,r){let o=se(n,t);if(o.kind==="unreadable")return e.io.error(`error: ${M(n).projects} cannot be read. Fix or delete it, then run \`${V("cursor","setup")}\`.`),1;let s;try{s=r(e.io.cwd)}catch{s=e.io.cwd}let i=o.kind==="ok"?o.registry:tu,a=bi(i,[s],e.io.env.CURSOR_PROJECT_DIR);return a===void 0?(e.io.error(`error: ${s} is unregistered. Run \`${V("cursor","setup")}\` in the folder you open in Cursor, then import.`),1):{record:a,registry:i}}async function gS(e,n,t,r){let o={},s={notActions:0,unmapped:0,unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0},i={},a=0,d=0,c=0,u=0,p=0,l=pS(t.home,e.projectKey,t.io),f=0,m=n.filter(R=>l.has(R.conversationId)?(f+=1,ge(o,"queued"),r.emit?.({event:"queued-skip",conversationId:R.conversationId}),!1):!0),g=0,h=!0,S=m;if(!t.reimport){let R=await $o(m.map(_=>_.conversationId),{endpoint:t.endpoint,token:t.token},{fetch:r.upload?.fetch});h=R.ok,R.ok&&R.known.size>0&&(S=m.filter(_=>R.known.has(_.conversationId)?(g+=1,r.emit?.({event:"dedup-skip",conversationId:_.conversationId}),!1):!0))}let b=oa(t.home,t.io);r.emit?.({event:"import-start",batchId:t.batchId,total:n.length,queuedSkipped:f,dedupSkipped:g,dedupOk:h,dryRun:t.dryRun});let E=Ui(t.orgId),k=Je(xe),I=await dr(S,t.concurrency,async R=>{let _=kl(R.files);if(t.resume&&!cr(b,R.conversationId,_))return{session:R,sourceHash:_,kind:"skipped"};let C=await Fl(R,e.root,t.scanIO);if(C.kind!=="imported")return{session:R,sourceHash:_,kind:C.kind,error:"error"in C?C.error:""};let T=mS(C.turns,{record:e,orgId:t.orgId,agentId:E,captureContent:t.captureContent,batchId:t.batchId,resolvedScrubbers:k}),$=await pn($e(T),{endpoint:t.endpoint,token:t.token,dryRun:t.dryRun},r.upload);return{session:R,sourceHash:_,kind:$.status==="failed"?"failed":"done",counts:C.counts,body:T,httpStatus:$.httpStatus,error:$.error}});for(let R of I){let _=R.session.conversationId;if(R.kind==="skipped")u+=1;else if(R.kind==="outside-root")ge(o,"outside-root");else if(R.kind==="empty")ge(o,"empty");else if(R.kind==="unreadable")ge(o,"unreadable"),b=$n(b,_,{status:"quarantined",sourceHash:R.sourceHash,batchId:t.batchId,error:R.error});else{let C=R.body;p+=C.spans.length,a+=C.redactions.total;for(let[T,$]of Object.entries(C.redactions.byType))i[T]=(i[T]??0)+$;for(let T of Object.keys(s))s[T]+=R.counts?.[T]??0;R.kind==="failed"?(c+=1,R.httpStatus!==void 0&&ge(o,`rejected-${R.httpStatus}`)):d+=1,b=$n(b,_,{status:R.kind,sourceHash:R.sourceHash,batchId:t.batchId,error:R.error})}r.emit?.({event:"session",conversationId:_,status:R.kind,spans:R.kind==="done"||R.kind==="failed"?R.body?.spans.length:0,httpStatus:R.httpStatus})}t.dryRun||bl(t.home,b,t.io);let y={total:n.length,imported:d,failed:c,skipped:u,dedupSkipped:g,dedupOk:h,queuedSkipped:f,spans:p,dropped:o,notImported:s,otherFolders:t.otherFolders,notRead:t.notRead,redactions:{total:a,byType:i}};return r.emit?.({event:"import-done",batchId:t.batchId,...yS(y)}),y}function mS(e,n){let t=e.map(o=>No(o,{orgId:n.orgId,project:{projectId:n.record.projectId,projectLabel:n.record.projectLabel,...n.record.developerId!==void 0?{developerId:n.record.developerId}:{}},captureContent:n.captureContent,mode:"import",scopeVersion:"0.0.0",batchId:n.batchId,resolvedScrubbers:n.resolvedScrubbers})),r=t[0];if(r===void 0)throw new Error("a conversation with no turn never reaches the span builder");return{resource:r.resource,scope:r.scope,spans:t.flatMap(o=>o.spans),redactions:{total:t.reduce((o,s)=>o+s.redactions.total,0),byType:t.reduce((o,s)=>{for(let[i,a]of Object.entries(s.redactions.byType))o[i]=(o[i]??0)+a;return o},{})}}}function yS(e){return{total:e.total,imported:e.imported,failed:e.failed,skipped:e.skipped,dedupSkipped:e.dedupSkipped,dedupOk:e.dedupOk,queuedSkipped:e.queuedSkipped,spans:e.spans,dropped:e.dropped,notImported:e.notImported,otherFolders:e.otherFolders,notRead:e.notRead}}async function Ll(e,n={}){let t=e.flags,r=[t.scan,t.import,t.status,t.resume].filter(Boolean).length;if(r===0)return e.io.error("error: backfill needs one of --scan | --import | --status | --resume."),1;if(r>1)return e.io.error("error: pass exactly one of --scan | --import | --status | --resume."),1;let o;try{o=e.sessionEnv()}catch(I){return e.io.error(`error: ${I.message}`),1}let s=o.homeDir,i=n.io??O,a=n.scanIO??wl,d=n.realpath??(I=>I),c=fS(e,s,i,d);if(typeof c=="number")return c;let{record:u,registry:p}=c,l=vl(u,p,s,a);if(t.status){let I=oa(s,i),y=Object.entries(I.sessions);e.io.log(`Cursor import record: ${M(s).backfillState}`),e.io.log(` conversations recorded: ${y.length}`);for(let[R,_]of y)e.io.log(` ${R}: ${_.status} (batch ${_.batchId}, ${_.updatedAt})`);return l.kind==="ok"?da(e,l):Ml(e,l),n.emit?.({event:"status",sessions:I.sessions}),0}if(l.kind==="collision")return Ml(e,l);if(t.scan)return da(e,l),e.io.log(`Conversations found for ${u.projectSlug}: ${l.sessions.length}`),e.io.log(`Other projects' folders on this machine: ${l.otherFolders} (counted, never opened)`),n.emit?.({event:"scan",projectsRoot:l.projectsRoot,folders:l.folders,conversations:l.sessions.length,otherFolders:l.otherFolders,notRead:l.notRead,unreadableFiles:l.unreadableFiles}),0;let f=Fe(o),m=t.endpoint?.trim()||e.io.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||f?.endpoint,g=t.key?.trim()||f?.ingest_token,h=t.org?.trim()||f?.org_id||u.orgId;if(!m||!g)return e.io.error(`error: not signed in for Cursor. Run \`${V("cursor","login")}\`, or pass --endpoint and --key.`),1;let S=uS;if(t.concurrency){let I=Number(t.concurrency);if(!Number.isInteger(I)||I<1)return e.io.error(`error: invalid --concurrency '${t.concurrency}' (positive integer).`),1;S=I}let b=!!t.content||u.captureContent;if(b&&e.io.error("note: a Cursor session file holds no prompt or response text, so --content adds tool inputs (commands and paths) and nothing a person typed. They are edge-scrubbed on this machine, and your org's config is applied again on arrival."),t.since)return e.io.error("error: --since is not supported for Cursor yet. A Cursor session file carries no time of its own, so the import is bounded by the project you run it in, not by a window."),1;let E=!!t["dry-run"],k=await gS(u,l.sessions,{home:s,io:i,scanIO:a,endpoint:m,token:g,orgId:h,captureContent:b,dryRun:E,reimport:!!t.reimport,resume:!!t.resume,concurrency:S,batchId:lS((n.now??Date.now)()),otherFolders:l.otherFolders,notRead:l.notRead},n);da(e,l),e.io.log(`Cursor import ${E?"(dry-run) ":""}complete for ${u.projectSlug}: ${k.imported} imported, ${k.failed} failed, ${k.skipped} unchanged (of ${k.total} conversations), ${k.spans} spans.`),k.queuedSkipped>0&&e.io.log(`${k.queuedSkipped} conversation(s) are still queued for live upload and were left to the sender.`),k.dedupSkipped>0&&e.io.log(`${k.dedupSkipped} conversation(s) AgentTrail already holds (live capture or an earlier import) were skipped.`),k.dedupOk||e.io.log("The `already recorded?` check could not run, so every conversation was treated as new. Imported spans replace rather than duplicate, because their ids and times are fixed \u2014 re-run when AgentTrail is reachable to get the skip counts back.");for(let[I,y]of Object.entries(k.dropped))e.io.log(`Not imported (${I}): ${y}`);return k.otherFolders>0&&e.io.log(`${k.otherFolders} folder(s) under ${l.projectsRoot} belong to other projects and were not opened.`),e.io.log(""),k.redactions.total>0&&e.io.log(`Edge-scrubbed ${k.redactions.total} secret-shaped value(s) on this machine before upload (${Object.keys(k.redactions.byType).sort().join(", ")}).`),e.io.log("Imported spans are marked approximate and carry no model, tokens or cost: a Cursor session file records none. They are never metered."),k.failed>0?1:0}var Kl=require("path");var Ul=require("crypto"),$l=require("uuid");function Bl(e,n){return(0,$l.v5)(`${e}:${n}`,xs).replace(/-/g,"")}function Qo(e,n,t){return(0,Ul.createHash)("sha256").update(`${e}:${n}:${t}`).digest("hex").slice(0,16)}function hS(e,n){return e===""?n:n===""||Date.parse(e)>=Date.parse(n)?e:n}function SS(e,n,t,r){let{sessionId:o,toolResults:s}=e,i=[],a=null;for(let d of r){let c=Qo(o,d.messageUuid,"llm"),u=d.isSidechain?a??t:t;i.push({role:"llm",spanId:c,parentSpanId:u,promptId:n,startTs:d.timestamp,endTs:d.timestamp,failed:!1,turn:d});for(let p of d.toolUses){let l=s.get(p.toolUseId),f=Qo(o,d.messageUuid,p.toolUseId);i.push({role:"tool",spanId:f,parentSpanId:c,promptId:n,startTs:d.timestamp,endTs:l?.timestamp||d.timestamp,failed:l?.isError??!1,tool:p,toolResult:l}),!d.isSidechain&&p.name==="Task"&&(a=f)}}return i}function Gl(e){let{sessionId:n,turns:t,userPrompts:r}=e,o=r.filter(p=>!p.isSidechain),s=o.length>0,i=s?o[0].messageUuid:"",a=p=>p.promptUuid!==""?p.promptUuid:i,d=new Map;for(let p of t){let l=a(p),f=d.get(l);f?f.push(p):d.set(l,[p])}let c=s?o.map(p=>({promptId:p.messageUuid,text:p.text,ts:p.timestamp})):[{promptId:"",text:"",ts:""}],u=[];for(let p of c){let l=Qo(n,p.promptId,"root"),f=SS(e,p.promptId,l,d.get(p.promptId)??[]),m=f.map(S=>S.startTs).find(S=>S!==""),g=p.ts!==""?p.ts:m??e.firstTimestamp??"",h=g;for(let S of f)h=hS(h,S.endTs);u.push({role:"agent",spanId:l,parentSpanId:"",promptId:p.promptId,startTs:g,endTs:h,failed:!1,promptText:p.text}),u.push(...f)}return u}var RS=1,ES=3,IS="claude-code-backfill",bS="claude-code-session-upload";function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function kS(e){let n=_t(e.input_tokens),t=_t(e.output_tokens),r=_t(e.cache_read_input_tokens),o=_t(e.cache_creation_input_tokens),s={"gen_ai.usage.input_tokens":String(n),input_tokens:String(n),"gen_ai.usage.output_tokens":String(t),output_tokens:String(t),"gen_ai.usage.cache_read.input_tokens":String(r),cache_read_input_tokens:String(r),"gen_ai.usage.cache_creation.input_tokens":String(o),cache_creation_input_tokens:String(o)};if(e.cache_creation!==void 0){let i=_t(e.cache_creation.ephemeral_5m_input_tokens),a=_t(e.cache_creation.ephemeral_1h_input_tokens);s["gen_ai.usage.cache_creation.ephemeral_5m.input_tokens"]=String(i),s.cache_creation_ephemeral_5m_input_tokens=String(i),s["gen_ai.usage.cache_creation.ephemeral_1h.input_tokens"]=String(a),s.cache_creation_ephemeral_1h_input_tokens=String(a)}return typeof e.speed=="string"&&e.speed!==""&&(s.speed=e.speed),typeof e.inference_geo=="string"&&e.inference_geo.length>0&&(s["gen_ai.usage.inference_geo"]=e.inference_geo),s}function Hl(e){let n=Date.parse(e);return Number.isNaN(n)?"0":(BigInt(n)*1000000n).toString()}function Vl(e){return e.provenance==="live"?{}:{[wn]:st,[vn]:e.batchId}}function CS(e,n,t,r){let o={...Vl(t),"session.id":n.sessionId,...r?{[js]:r}:{}};if(e.role==="agent")return{...o,...hu(e.promptText??"",t.captureContent)};if(e.role==="llm"&&e.turn){let{turn:s}=e;return{...o,"gen_ai.system":"anthropic","gen_ai.request.model":s.model,"gen_ai.conversation.id":n.sessionId,...kS(s.usage),...Su(s.text,t.captureContent)}}if(e.role==="tool"&&e.tool){let s={...o,"gen_ai.tool.name":e.tool.name,"gen_ai.tool.call.id":e.tool.toolUseId,...Ru(e.tool.input,e.toolResult?.content,t.captureContent)};return e.failed&&(s["otel.status_code"]="ERROR"),s}return o}function Jo(e,n){let t=Gl(e),r=e.cwd?(0,Kl.basename)(Dn(e.cwd)):null,o=n.resolved??null,s=0,i={},a=t.map(c=>{let u=Ao(CS(c,e,n,r),o);s+=u.redactedCount;for(let p in u.byType)i[p]=(i[p]??0)+u.byType[p];return{traceId:Bl(e.sessionId,c.promptId),spanId:c.spanId,parentSpanId:c.parentSpanId,name:c.role==="agent"?"session":c.role==="llm"?"chat":c.tool?.name??"tool",kind:c.role==="llm"?ES:RS,startTimeUnixNano:Hl(c.startTs),endTimeUnixNano:Hl(c.endTs),attributes:u.attributes,error:c.failed}}),d={[De]:n.orgId,[Kt]:n.projectId,[Ps]:Le(n.orgId,pe),[Ds]:pe,...Vl(n)};return n.developerId&&(d[Ns]=n.developerId),{resource:{attributes:d},scope:{name:n.provenance==="live"?bS:IS,version:n.scopeVersion??"0.0.0"},spans:a,redactions:{total:s,byType:i}}}var _S=6;function TS(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function OS(e){if(e.cwd){let n=ct(e.cwd);if(n)return n}return oo(e.project)||"default"}function xS(e,n){let t=[];for(let r of e.projects)for(let o of r.sessions)n.sinceMs!==void 0&&Date.parse(o.modifiedAt)<n.sinceMs||t.push(o);return t}async function Wl(e,n={}){let t=await ia(e.projectsRoot,e.projectRoot,{...n.scanIO,lineSource:n.lineSource??n.scanIO?.lineSource});return n.emit?.({event:"scan",...t}),t}function Ql(e,n={}){let t=ta(e.homeDir,n.checkpointIO);return n.emit?.({event:"status",sessions:t.sessions}),t}async function Jl(e,n,t={}){let r=vS(),o=t.hashFile??Rl,s=Je(e.scrubConfig??xe),i=await ia(e.projectsRoot,e.projectRoot,{...t.scanIO,lineSource:t.lineSource??t.scanIO?.lineSource}),a=xS(i,e),d=a.length,c=Math.max(1,e.concurrency??_S),u=ta(e.homeDir,t.checkpointIO),p=await dr(a,c,async T=>{try{return await o(T.file)}catch($){return`unhashable:${$.message}`}}),l=new Map;a.forEach((T,$)=>{l.set(T.sessionId,p[$])});let f=0,m=!0,g=a;if(!e.reimport){let T=await $o(a.map($=>$.sessionId),{endpoint:e.endpoint,token:e.token},{fetch:t.upload?.fetch});if(m=T.ok,T.ok&&T.known.size>0){let $=[];for(let x of a)wS(T.known,u,x.sessionId,l.get(x.sessionId)??"")?(f++,t.emit?.({event:"dedup-skip",sessionId:x.sessionId})):$.push(x);g=$}}t.emit?.({event:"import-start",batchId:r,total:d,dedupSkipped:f,dedupOk:m,dryRun:e.dryRun??!1});let h=[],S=0,b=0,E=0,k=0,I=0,y=0,R=0,_={};for(let T of TS(g,c)){let $=await dr(T,c,async x=>{let ce=l.get(x.sessionId)??"";if(n&&!cr(u,x.sessionId,ce))return{item:x,kind:"skipped",sourceHash:ce};let Ze;try{Ze=await Go(x.file,x.sessionId,t.lineSource)}catch(Mt){let Rn=(Mt instanceof Bn,Mt.message);return{item:x,kind:"quarantined",sourceHash:ce,error:Rn}}if(e.retentionCutoffMs!==void 0&&Date.parse(Ze.firstTimestamp)<e.retentionCutoffMs)return{item:x,kind:"skipped-retention",sourceHash:ce};let Sn=ne(e.orgId,OS(x)),Oe=Jo(Ze,{orgId:e.orgId,projectId:Sn,developerId:e.developerId,batchId:r,captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:s}),Ft=await pn($e(Oe),{endpoint:e.endpoint,token:e.token,dryRun:e.dryRun},t.upload);return{item:x,kind:Ft.status==="failed"?"failed":"done",sourceHash:ce,spans:Oe.spans.length,error:Ft.error,upload:Ft,redactions:Oe.redactions}});for(let x of $){if(x.redactions){R+=x.redactions.total;for(let ce in x.redactions.byType)_[ce]=(_[ce]??0)+x.redactions.byType[ce]}x.kind==="skipped"?b++:x.kind==="skipped-retention"?I++:x.kind==="quarantined"?(k++,u=$n(u,x.item.sessionId,{status:"quarantined",sourceHash:x.sourceHash,batchId:r,error:x.error})):(x.kind==="failed"?E++:S++,y+=x.spans??0,u=$n(u,x.item.sessionId,{status:x.kind,sourceHash:x.sourceHash,batchId:r,error:x.error})),h.push({sessionId:x.item.sessionId,project:x.item.project,status:x.kind,spans:x.spans,error:x.error,upload:x.upload}),t.emit?.({event:"session",sessionId:x.item.sessionId,status:x.kind,spans:x.spans,httpStatus:x.upload?.httpStatus})}Sl(e.homeDir,u,t.checkpointIO)}let C={total:d,imported:S,skipped:b,failed:E,quarantined:k,retentionSkipped:I,dedupSkipped:f,dedupOk:m,estimatedActions:y,outcomes:h,redactions:{total:R,byType:_},excludedOtherProject:i.excludedOtherProject??0,excludedUnknownCwd:i.excludedUnknownCwd??0};return t.emit?.({event:"import-done",batchId:r,...AS(C),dedupOk:C.dedupOk,redactions:C.redactions}),C}function AS(e){return{total:e.total,imported:e.imported,skipped:e.skipped,failed:e.failed,quarantined:e.quarantined,retentionSkipped:e.retentionSkipped,dedupSkipped:e.dedupSkipped,estimatedActions:e.estimatedActions,excludedOtherProject:e.excludedOtherProject,excludedUnknownCwd:e.excludedUnknownCwd}}function wS(e,n,t,r){if(!e.has(t))return!1;let o=n.sessions[t];return!(o!==void 0&&(o.status!=="done"||o.sourceHash!==r))}function vS(){return`bf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Yl(e){return Re(e,"setup")}function zl(e){return Re(e,"logout")}function ql(e,n="status"){return Re(e,n)}var Xe=require("fs"),q=require("path");var Xl=require("fs"),lr=require("path");var PS=15e3,DS=200;async function Zl(e,n,t,r={}){let o=r.io??O,s=N(e,n).root;return o.mkdirp(s,rn),je({lockPath:(0,lr.join)(s,"install.lock"),io:r.lockIO,timeoutMs:PS},t)}function ep(e,n,t,r){let o=N(e,n).queue,s=0,i=(()=>{if(r!==void 0)return[r];try{return t.exists(o)?t.readdir(o):[]}catch{return[]}})();for(let a of i)try{let d=on(e,n,a);t.exists(d)&&(s+=t.readdir(d).filter(c=>c.endsWith(".json")).length)}catch{}return s}async function np(e,n,t,r){let o=r.io??O,s=r.now??(()=>Date.now()),i=r.sleep??(l=>new Promise(f=>setTimeout(f,l))),a=r.run,d=N(e,n).senderLock,c=s()+t,u=()=>Math.max(0,c-s());if(await a({home:e,maxRunMs:u()}),!o.exists(d))return{waited:!1,stillLocked:!1};let p=!1;for(;o.exists(d)&&u()>0;)p=!0,await i(Math.min(DS,u()));return o.exists(d)?{waited:p,stillLocked:!0}:(await a({home:e,maxRunMs:u()}),{waited:p,stillLocked:!1})}function tp(e,n,t){let r=dt(e);return r!==null?t(r):n.filter(s=>e===s||e.startsWith(s.endsWith(lr.sep)?s:`${s}${lr.sep}`)).sort((s,i)=>i.length-s.length)[0]??e}function rp(e,n,t){let r=ut(e),o=t.project?.trim();if(o)return{slug:o,id:ne(n,o),source:"flag",label:r};let s=Qs(e);if(s!==null)try{let a=to(JSON.parse((0,Xl.readFileSync)(s,"utf8"))),d=a.orgId===n&&a.projectId!==void 0?a.projectId:ne(n,a.projectSlug);return{slug:a.projectSlug,id:d,source:"agenttrail-json",label:r}}catch(a){return{error:`${s} cannot be read as a ${Y} (${a.message}). Fix it, or pass --project <slug>.`}}let i=Nn(e);return i===null?{error:"could not work out a project slug for this folder. Pass --project <slug>."}:{slug:i.slug,id:ne(n,i.slug),source:"derived",label:r,note:i.source==="directory"?"NOTE: no git remote found \u2014 this project's identity comes from its directory name and may differ on another machine. Add an `origin` remote for a stable one.":void 0}}var NS=require("fs");function ca(e,n,t=O){let r=Tt(e,t),o=r===void 0?n:{...n,writtenAt:r.writtenAt};return r!==void 0&&JSON.stringify(r)===JSON.stringify(o)?!1:(t.writeFileAtomic(M(e).enforcement,`${JSON.stringify(o,null,2)}
|
|
48
48
|
`,F),!0)}function Tt(e,n=O){let t;try{let o=M(e).enforcement;if(!n.exists(o))return;t=JSON.parse(n.readFile(o).toString("utf8"))}catch{return}if(t===null||typeof t!="object"||Array.isArray(t))return;let r=t;if(r.v===1&&!(typeof r.enabled!="boolean"||typeof r.apiBase!="string"||typeof r.orgId!="string"||typeof r.agentId!="string"||typeof r.timeoutMs!="number"||typeof r.userScopeHandoff!="boolean"))return r}var op="cursor";var Ra=require("path");var ip=require("child_process"),zo=require("fs");var pr=class extends Error{constructor(n){super(n),this.name="HookCommandError"}},jS=/["$`\\\r\n\0]/,FS=/^[A-Za-z0-9_.:=/-]+$/;function Yo(e){if(jS.test(e))return`${JSON.stringify(e)} holds a double quote, "$", a backtick, a backslash or a line break, which a hook command cannot carry`}function Gn(e){if(e==="")return"''";let n="",t="",r=()=>{t!==""&&(n+=`'${t}'`,t="")};for(let o of e)o==="'"?(r(),n+=`"'"`):o==="\\"?(r(),n+="\\\\"):t+=o;return r(),n}function sp(e,n,t,r=o=>new pr(o)){for(let o of[e,n]){let s=Yo(o);if(s!==void 0)throw r(s)}for(let o of t)if(!FS.test(o))throw r(`${JSON.stringify(o)} is not a fixed hook argument`);return[Gn(e),Gn(n),...t].join(" ")}var ua="{}",fr="CURSOR_PROJECT_DIR",gn=class extends pr{constructor(n){super(n),this.name="CursorGateError"}},MS=/[\r\n\0]/;function ya(e){if(MS.test(e))return`${JSON.stringify(e)} holds a line break, which the gate cannot match`}function LS(e,n,t){return sp(e,n,t,r=>new gn(r))}function Hn(e,n,t){return LS(e,n,["--agent",Ri,"--scope",t])}var la='m() { case "$1" in ',pa=`) return 0 ;; esac; return 1; }; if m "$${fr}"; then exec `,fa=`; fi; p=$(cd -P -- "$${fr}" 2>/dev/null && pwd -P); if [ -n "$p" ] && m "$p"; then exec `,ga=`; fi; printf "${ua}"`,ma="/bin/sh -c ";function US(e){let n=e.endsWith("/")?e:`${e}/`;return`${Gn(e)}|${Gn(n)}*`}function qo(e,n){if(e.length===0)throw new gn("a gated command needs at least one connected folder");let t=[];for(let o of e){let s=ya(o);if(s!==void 0)throw new gn(s);t.push(US(o))}let r=la+t.join("|")+pa+n+fa+n+ga;return ma+Gn(r)}function ap(e,n){let t=n,r="",o=!1;for(;;){let s=e[t];if(s===void 0||s==="|"||s===")")break;if(o)throw new gn("a gate pattern ends at its star");if(s==="'"){let i=e.indexOf("'",t+1);if(i===-1)throw new gn("an unterminated quoted run");r+=e.slice(t+1,i),t=i+1}else if(e.startsWith(`"'"`,t))r+="'",t+=3;else if(e.startsWith("\\\\",t))r+="\\",t+=2;else if(s==="*")o=!0,t+=1;else throw new gn("a character this generator never writes")}return{value:r,end:t,star:o}}function $S(e){try{let n=ap(e,0);return n.end===e.length&&!n.star?n.value:void 0}catch{return}}function Kn(e){if(!e.startsWith(ma))return;let n=$S(e.slice(ma.length));if(n===void 0||!n.startsWith(la))return;let t=[],r=la.length;try{for(;;){let d=ap(n,r);if(d.star||t.push(d.value),r=d.end,n[r]==="|"){r+=1;continue}break}}catch{return}if(t.length===0||!n.startsWith(pa,r))return;let o=n.slice(r+pa.length),s=o.indexOf(fa);if(s===-1||!o.endsWith(ga))return;let i=o.slice(0,s),a=o.slice(s+fa.length,o.length-ga.length);return i===a?{folders:t,helper:i}:void 0}function ha(e){return typeof e=="string"&&Kn(e)!==void 0}function dp(e,n){let t=Kn(e);if(t!==void 0)return qo(n,t.helper)}var BS="/nonexistent/agenttrail-gate-dry-run";function GS(e){let n=[e.SHELL,process.platform==="darwin"?"/bin/zsh":void 0,"/bin/sh"],t=[];for(let r of n)if(!(r===void 0||r===""||t.includes(r)))try{(0,zo.accessSync)(r,zo.constants.X_OK),t.push(r)}catch{}return t}function cp(e,n={}){let t=n.env??process.env,r=n.shells===void 0?GS(t):[...n.shells];if(r.length===0)return{ok:!1,shells:r,reason:"no shell to run the gate with"};for(let o of r){let s;try{s=(0,ip.execFileSync)(o,["-c",e],{input:"",encoding:"utf8",timeout:n.timeoutMs??5e3,env:{...t,[fr]:BS},stdio:["pipe","pipe","pipe"]})}catch(i){let a=i.status??null;return{ok:!1,shells:r,reason:`${o} exited ${a===null?"abnormally":a} on the gate`}}if(s!==ua)return{ok:!1,shells:r,reason:`${o} answered ${JSON.stringify(s)} for an unconnected workspace, not ${ua}`}}return{ok:!0,shells:r}}function up(e=process.platform){return e!=="win32"}var gr="3.21.16",HS=/^(\d+)\.(\d+)\.(\d+)$/;function lp(e){if(typeof e!="string")return;let n=HS.exec(e);if(n===null)return;let[t,r,o]=[n[1],n[2],n[3]].map(Number);if(!(t===void 0||r===void 0||o===void 0)&&!(!Number.isSafeInteger(t)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)))return{major:t,minor:r,patch:o}}function KS(e,n){return e.major!==n.major?e.major-n.major:e.minor!==n.minor?e.minor-n.minor:e.patch-n.patch}function pp(e){let n=lp(e);if(n===void 0)return"unknown";let t=lp(gr);return t===void 0?"unknown":KS(n,t)>=0?"supported":"too-old"}var VS=require("fs"),He=class extends Error{constructor(n){super(`PDP unreachable: ${n}`),this.name="PdpUnreachableError"}},WS=/^This feature requires the (Pro|Team|Business|Enterprise) plan or higher\.$/;async function QS(e){let n;try{n=JSON.parse(await e.text())}catch{return!1}if(typeof n!="object"||n===null)return!1;let t=n.error;if(typeof t!="object"||t===null)return!1;let{code:r,message:o}=t;return r==="forbidden"&&typeof o=="string"&&WS.test(o)}function JS(e){return new He(`${e} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`)}async function YS(e,n,t,r){let o=new AbortController,s=setTimeout(()=>o.abort(),r);try{return await e(n,{...t,signal:o.signal})}catch(i){let a=i instanceof Error?i.message:String(i);throw new He(a)}finally{clearTimeout(s)}}async function mr(e,n){let t=await YS(n,e.url,{method:"GET",headers:{authorization:`Bearer ${e.token}`}},e.timeoutMs);if(t.status===200){let r;try{r=await t.json()}catch{throw new He("200 snapshot with unparseable JSON body")}if(!zS(r))throw new He("200 with malformed PolicyCompiledSnapshot");return{kind:"ok",snapshot:r}}if(t.status===403){if(await QS(t))return{kind:"tier-disabled"};throw JS("snapshot")}if(t.status===401)return{kind:"unauthorized"};throw new He(`unexpected snapshot status ${t.status}`)}function zS(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.version=="string"&&(n.fail_mode==="closed"||n.fail_mode==="open")&&Array.isArray(n.policies)}async function Sa(e,n){try{let t=await mr(e,n);return t.kind==="ok"?{outcome:"ok",snapshot:t.snapshot}:{outcome:t.kind==="unauthorized"?"unauthorized":"forbidden"}}catch{return{outcome:"unreachable"}}}var Vn="pep-hook.mjs",fp={preToolUse:600,beforeMCPExecution:600,beforeShellExecution:30},Ea=Object.keys(fp);function Xo(e){return typeof e=="string"&&e.includes(Vn)&&/(?:^|\s)--agent cursor(?=\s|$)/.test(e)}function Ia(e){return Object.fromEntries(Ea.map(n=>[n,[{command:e,timeout:fp[n]??600,failClosed:!0}]]))}function gp(e,n){return Hn(e,(0,Ra.join)(n,Vn),"project")}function ba(e,n){return Hn(e,(0,Ra.join)(n,Vn),"user")}var XS=!0;function ZS(e){return!(e.row0Verified??XS)||!e.hasUserScopeFolders?!1:e.version==="supported"}function mp(e){let n=pp(e.rawCursorVersion);return{v:1,enabled:n==="supported",apiBase:e.apiBase,orgId:e.orgId,agentId:e.agentId,timeoutMs:e.timeoutMs,userScopeHandoff:ZS({hasUserScopeFolders:e.hasUserScopeFolders,version:n,...e.row0Verified===void 0?{}:{row0Verified:e.row0Verified}}),cursorVersion:e.rawCursorVersion,versionSupport:n,writtenAt:e.now.toISOString()}}var eR="/Applications/Cursor.app/Contents/Info.plist",nR=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]*)<\/string>/;function yp(e=t=>O.readFile(t).toString("utf8"),n=eR){try{let r=nR.exec(e(n))?.[1]?.trim();return r===void 0||r===""?null:r}catch{return null}}function hp(e){switch(e){case"unauthorized":return"AgentTrail could not verify this device (401), so enforcement is off and capture is on. Run `login --agent cursor` again, then setup.";case"forbidden":return"AgentTrail refused the enforcement check (403), so enforcement is off and capture is on.";case"unreachable":return"AgentTrail could not be reached, so enforcement is off and capture is on. Run setup again when you are online."}}function Zo(e){let{record:n,problems:t}=e;return e.entriesInstalled===!0&&(n===void 0||!n.enabled)?{headline:"Enforcement: BROKEN",details:[n===void 0?"an enforcement entry runs in this folder, but this machine has no enforcement record":"an enforcement entry runs in this folder, but this machine's enforcement record says it is off","Every call in this project is refused until the two agree \u2014 run `setup --agent cursor` in this folder."]}:n===void 0||e.projectEnforced===void 0?{headline:"Enforcement: NOT INSTALLED",details:["Run `setup --agent cursor` in the folder you open in Cursor."]}:n.enabled?t.length>0?{headline:"Enforcement: BROKEN",details:[...t,"Every call in this project is blocked until setup runs again, because the entries are fail-closed."]}:{headline:"Enforcement: ON",details:[`Approval window: this hook allows up to ${590}s, but each rule's own hold window decides \u2014 a rule with none set holds for the server default. The hook is fail-closed: a call is blocked if it cannot answer.`,`Cursor ${n.cursorVersion??"(version not recorded)"}.`,"An unanswered hold on a shell command is handed back to Cursor, which asks you; every other tool is refused."]}:n.versionSupport!=="supported"?{headline:"Enforcement: OFF",details:[`update Cursor to enable enforcement \u2014 ${gr} or later is needed${n.cursorVersion===null?"":`, and this is ${n.cursorVersion}`}`,"Capture keeps working meanwhile."]}:{headline:"Enforcement: OFF",details:[n.probeNote??"a check at setup refused; run setup again"]}}var Dp=require("fs"),Np=require("os");var _p=require("crypto");function Sp(e,n,t){if(n.length===0)return{records:e,filledToolUseId:0};let r=d=>{if(!t.fillableEvent(d.event))return!1;let c=d.tool;return c!==void 0&&c.correlationId===null},o=(d,c)=>{let u=c.tool;if(u===void 0)return!1;let p=t.decisionTurnOf(d),l=t.turnOf(c);return d.toolUseId!==null&&d.toolUseId!==""&&p.conversationId===l.conversationId&&p.generationId===l.generationId&&d.vendorTool===u.vendorTool&&d.argsHash===u.argsHash&&d.decidedAtMs<=c.capturedAtMs},s=new Set,i=0,a=e.map(d=>{if(!r(d))return d;let c;if(n.forEach((p,l)=>{s.has(l)||!o(p,d)||(c===void 0||p.decidedAtMs>c.decision.decidedAtMs)&&(c={index:l,decision:p})}),c===void 0)return d;s.add(c.index),i+=1;let u=d.tool;return{...d,tool:{...u,correlationId:c.decision.toolUseId}}});return{records:tR(a,n,t),filledToolUseId:i}}function tR(e,n,t){let r=n.filter(o=>o.blocked&&o.toolUseId!==null&&o.toolUseId!=="");return r.length===0?e:e.map(o=>{let s=o.tool;if(s===void 0||s.failed!==!0||!t.fillableEvent(o.event)||s.correlationId===null)return o;let i=t.turnOf(o);return r.some(d=>{let c=t.decisionTurnOf(d);return d.toolUseId===s.correlationId&&c.conversationId===i.conversationId&&c.generationId===i.generationId&&d.decidedAtMs<=o.capturedAtMs})?{...o,tool:{...s,pepBlocked:!0}}:o})}var rR=require("fs");var ka=".dropped",oR="c";function Rp(e){return e===oR?"queue-full":`mark-${e}`}var Ep=require("crypto"),ie=require("fs"),Ip=5e3,Ca=2e4,yr={acquire(e,n){let t=(0,ie.openSync)(e,"wx",384);try{(0,ie.writeSync)(t,n)}finally{(0,ie.closeSync)(t)}},release(e){try{(0,ie.rmSync)(e,{force:!0})}catch{}},age(e){try{return Date.now()-(0,ie.statSync)(e).mtimeMs}catch{return null}},read(e){try{return(0,ie.readFileSync)(e,"utf8")}catch{return null}},touch(e){try{let n=new Date;(0,ie.utimesSync)(e,n,n)}catch{}},now:()=>Date.now()};function bp(e,n=yr){let t=n.age(e);return t!==null&&t<=Ca&&t>=-Ca}function sR(e,n){return`${e} ${new Date(n).toISOString()} ${(0,Ep.randomBytes)(8).toString("hex")}
|
|
49
49
|
`}function es(e,n=yr,t=process.pid){let r=sR(t,n.now()),o=()=>{try{return n.acquire(e,r),!0}catch{return!1}};if(!o()&&(bp(e,n)||(n.release(e),!o())))return;let s=n.now();return{token:r,owned:()=>n.read(e)===r,heartbeat(){let i=n.now();return i-s<Ip?!0:(s=i,n.read(e)!==r?!1:(n.touch(e),!0))},release(){n.read(e)===r&&n.release(e)}}}var Tp=35e5,iR=new Set([400,413,422]),_a={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function Ta(e){return(0,_p.createHash)("sha256").update(JSON.stringify([e.spanId,e.parentSpanId,e.name,e.kind,e.startTimeUnixNano,e.endTimeUnixNano,e.error,Object.entries(e.attributes).sort()]),"utf8").digest("hex").slice(0,16)}function Op(e,n){let t=n.closed;return t===void 0?{...e,endMs:null}:t.by==="stop"?{...e,endMs:e.endMs??t.atMs,closedBy:"stop"}:{...e,endMs:e.endMs??t.atMs,closedBy:t.by,status:e.status??"unknown"}}function xp(e,n,t){let r={},o=[];for(let s of e){if(t.has(s.spanId))continue;let i=n.starts[s.spanId],a=i===void 0||i===s.startTimeUnixNano?s:{...s,startTimeUnixNano:i,endTimeUnixNano:BigInt(s.endTimeUnixNano)<BigInt(i)?i:s.endTimeUnixNano},d=n.sent[a.spanId];d!==Ta(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function Ap(e,n,t=Tp){let r=[],o=[];for(let s of n){let i=[...o,s];if(Buffer.byteLength(JSON.stringify($e({...e,spans:i})),"utf8")>t&&o.length>0){r.push(o),o=[s];continue}o=i}return o.length>0&&r.push(o),r}function ns(e,n,t){ge(e.totals.dropped,t),ge(e.report,t),n!==void 0&&ge(or(e.totals,n).dropped,t)}async function aR(e,n,t){let r=async()=>(n.posts+=1,pn(t,{endpoint:n.credentials.endpoint,token:n.credentials.ingest_token,maxRetries:2},{fetch:e.fetch,sleep:e.sleep})),o=await r();if(o.status==="failed"&&o.httpStatus===401){let s=await e.refresh(n.credentials.ingest_token);if(s===null)return{ok:!1,status:401,error:"not signed in"};n.credentials=s,o=await r()}return o.status==="ok"?{ok:!0,status:o.httpStatus}:{ok:!1,...o.httpStatus!==void 0?{status:o.httpStatus}:{},...o.error!==void 0?{error:o.error}:{}}}function dR(e,n,t,r){if(t.length===n.length)return!1;let o=new Set(t),s=ze(r.conversationId,r.generationId);return n.some(i=>{if(o.has(i)||!e.closesTurn(i))return!1;let a=e.turnOf(i);return a.conversationId!==null&&ze(a.conversationId,a.generationId)===s})}function cR(e){let{closed:n,...t}=e;return t}async function uR(e,n,t){let{adapter:r,deps:o,mem:s}=e,i=o.now(),a=Sp(t.records,t.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=t.state,p=dR(r,a.records,d,u)?cR(u):u,l=p.closed===void 0;if(d.length===0)return u.closed===void 0||c?{state:u,sent:0,drained:!1,open:l}:kp(e,u,t,a.filledToolUseId);let f=Op(o.builder.assemble(d,void 0,t.decisions),p);if(p.closed!==void 0&&r.usageOf!==void 0){let k=r.usageOf({conversationId:u.conversationId,generationId:u.generationId},{home:o.home,env:o.env??process.env,io:o.io});k!==null&&(f={...f,usage:k})}let m=o.builder.build(f,{orgId:n.credentials.org_id,project:{projectId:n.project.projectId,projectLabel:n.project.projectLabel,...n.project.developerId!==void 0?{developerId:n.project.developerId}:{}},captureContent:n.project.captureContent,mode:"live",scopeVersion:o.scopeVersion,resolvedScrubbers:s.scrubbers}),g=new Set;l&&(g.add(o.builder.spanId(u.traceId,"root")),g.add(o.builder.spanId(u.traceId,"model")));let{spans:h,starts:S}=xp(m.spans,u,g),b=0;for(let k of Ap(m,h)){let I=await aR(o,n,$e({...m,spans:k}));if(I.ok){let y={...u.sent},R={...u.starts};for(let C of k)y[C.spanId]=Ta(C),R[C.spanId]=S[C.spanId]??C.startTimeUnixNano;u={...u,sent:y,starts:R},b+=k.length;let _=o.now();s.totals.lastUploadAtMs=_,or(s.totals,n.project.projectKey).lastUploadAtMs=_,kt(o.home,r.stateDir,u,o.io);continue}if(I.status!==void 0&&iR.has(I.status)){let y={...u.sent};for(let R of k)y[R.spanId]=`dropped:${I.status}`,ns(s,n.project.projectKey,`rejected-${I.status}`);u={...u,sent:y},kt(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:b,drained:!1,open:l,fatal:I.status===401?"auth":"network",...I.error!==void 0?{error:I.error}:{}}}return u.closed!==void 0&&!c&&m.spans.every(k=>u.sent[k.spanId]!==void 0)?{...kp(e,u,t,a.filledToolUseId),sent:b}:{state:u,sent:b,drained:!1,open:l}}function kp(e,n,t,r){let{adapter:o,deps:s,mem:i}=e,a={...n,files:[]};kt(s.home,o.stateDir,a,s.io);let d=on(s.home,o.stateDir,n.projectKey);for(let c of t.files)s.io.remove(`${d}/${c}`);return i.totals.pepDecisions.seen+=t.decisions.length,i.totals.pepDecisions.filledToolUseId+=r,{state:a,sent:0,drained:!0,open:!1}}function lR(e,n,t){let{adapter:r,mem:o}=e,s;for(let d of t){let c=d.entry;if(c?.kind!=="capture")continue;let u=r.versionOf(c);u!==void 0&&(s===void 0||u.seenAtMs>s.seenAtMs)&&(s=u)}if(s===void 0)return;let i=or(o.totals,n),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function pR(e,n,t){let{deps:r,mem:o}=e,s=`${t}/${ka}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))ns(o,n,Rp(a))}catch{}r.io.remove(i)}}function fR(e,n){let t=/^\.(\d+)-\d+-\d+\.json\./.exec(e);if(!(t===null||!e.endsWith(".tmp")))return n-Number(t[1])}function Cp(e){let{adapter:n,deps:t,mem:r}=e;if(!Ti(r.totals))try{if(!t.io.exists(N(t.home,n.stateDir).projects)){r.totals=rr();return}Oi(t.home,n.stateDir,xi(sr(t.home,n.stateDir,n.versionKey,t.io),r.totals,n.versionKey),t.io),r.totals=rr()}catch{}}function wp(e,n,t){try{return t.readdir(N(e,n).queue)}catch{return[]}}async function gR(e,n){let{adapter:t,deps:r,mem:o}=e,s=r.now(),i=r.credentials();if(i===null)return mR(s,{fatal:"credentials"});let a=t.readRegistry(r.home,r.io),d=0,c=0,u=0,p=0,l=!1,f,m;for(let g of wp(r.home,t.stateDir,r.io)){let h=on(r.home,t.stateDir,g),{files:S,other:b}=Fo(h,y=>t.parseQueueEntry(y),r.io,o.cache,h);b.includes(ka)&&pR(e,g,h);for(let y of b){let R=fR(y,s);R!==void 0&&R>=ar&&r.io.remove(`${h}/${y}`)}if(S.length===0)continue;for(let y of S)u=Math.max(u,y.atMs);lR(e,g,S);let E=Vi({projectKey:g,files:S,states:[...o.states.values()],nowMs:s,traceIdFor:y=>r.builder.traceId(y),...n.closeOpenTurns===!0?{limits:{idleSweepMs:0}}:{},rules:t});for(let{file:y,reason:R}of E.dropped){ns(o,g,R);let _=y.entry;_?.kind==="unknown"&&ge(o.totals.unknownKinds,_.rawKind),R==="decision-orphan"&&(o.totals.pepDecisions.orphaned+=1,o.totals.pepDecisions.seen+=1),r.io.remove(`${h}/${y.name}`),o.cache.delete(`${h}/${y.name}`)}d+=E.pending.length;let k=a.kind==="ok"?a.registry.projects[g]:void 0;if(k===void 0){if(d+=E.turns.reduce((y,R)=>y+R.files.length,0),a.kind==="ok"){for(let y of E.turns)if(!(s-y.state.lastRecordAtMs<ar)){for(let R of y.files)ns(o,g,"unregistered"),r.io.remove(`${h}/${R}`),o.cache.delete(`${h}/${R}`);o.states.delete(y.state.traceId),jo(r.home,t.stateDir,y.state.traceId,r.io)}}continue}let I={project:k,credentials:i,posts:o.posts};for(let y of E.turns){let R;try{R=await uR(e,I,y)}catch(_){R={state:y.state,sent:0,drained:!1,open:y.state.closed===void 0,fatal:"network",error:_ instanceof Error?_.message:String(_)},yR(e,y.state)}if(o.states.set(R.state.traceId,R.state),p+=R.sent,R.drained)for(let _ of y.files)o.cache.delete(`${h}/${_}`);else d+=y.files.length,R.open&&(c+=1);if(R.fatal!==void 0){l=!0,m=R.error??m,o.totals.lastError={atMs:r.now(),message:R.error??(R.fatal==="auth"?"not signed in":"upload failed")},R.fatal==="auth"&&(f="auth");break}}if(o.posts=I.posts,i=I.credentials,f!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:p,failed:l,...f!==void 0?{fatal:f}:{},...m!==void 0?{error:m}:{}}}function mR(e,n={}){return{entries:0,openTurns:0,newestRecordMs:e,sent:0,failed:!1,...n}}function yR(e,n){try{kt(e.deps.home,e.adapter.stateDir,n,e.deps.io)}catch{}}function hR(e,n,t){for(let r of wp(e,n,t))try{if(t.readdir(on(e,n,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function SR(e,n,t,r){return e.failed?r:e.openTurns===0?n.pollIdleMs:t-e.newestRecordMs<=n.flowWindowMs?n.pollFlowingMs:n.pollOpenMs}async function vp(e,n,t={}){let r=N(n.home,e.stateDir),o=es(r.senderLock,n.lockIO,n.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=Ki(n.home,e.stateDir,n.io);for(let g of s.unreadable)n.io.remove(g);let i={states:new Map(s.states.map(g=>[g.traceId,g])),cache:new Map,totals:rr(),report:{},scrubbers:Je(xe),posts:0},a={adapter:e,deps:n,mem:i},d=n.now(),c="done",u=0,p=0,l,f,m=n.limits.backoffMs;try{for(;;){if(!o.heartbeat()){c="lost-lock";break}let g=await gR(a,t);u+=1,p+=g.sent,l=g.error??l,Cp(a);for(let h of Wi([...i.states.values()],n.now()))jo(n.home,e.stateDir,h.traceId,n.io),i.states.delete(h.traceId);if(g.fatal==="credentials"){c="no-credentials";break}if(g.failed){if(f??=n.now(),g.fatal==="auth"||n.now()-f>=n.limits.giveUpMs){c="send-failed";break}}else f=void 0,m=n.limits.backoffMs;if(t.maxRunMs!==void 0&&n.now()-d>=t.maxRunMs){c="time-limit";break}if(g.entries===0&&!g.failed){if(o.release(),o=void 0,!hR(n.home,e.stateDir,n.io)||(o=es(r.senderLock,n.lockIO,n.pid),o===void 0))break;continue}await n.sleep(SR(g,n.limits,n.now(),m)),g.failed&&(m=Math.min(m*2,n.limits.pollIdleMs*12))}}finally{Cp(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:p,dropped:i.report,...l!==void 0?{lastError:l}:{}}}function Pp(e,n,t){try{let r=JSON.parse(t.readFile(N(e,n).install).toString("utf8"));return typeof r.cliVersion=="string"?r.cliVersion:void 0}catch{return}}var RR=2e3,ER={traceId:e=>$i(e,"live"),spanId:(e,n)=>Bi(e,n),assemble:e=>Gu(e),build:(e,n)=>No(e,n)};function IR(e,n,t=RR){let r=new Set(e.filter(o=>o.event==="afterMCPExecution").map(o=>`${o.generationId??""}\0${o.tool?.vendorTool??""}`));return e.filter(o=>{if(o.event!=="postToolUse")return!0;let s=o.tool;return s?.mcpServerUnknown!==!0||!s.vendorTool.startsWith(ea)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:n-o.capturedAtMs>=t})}function bR(e){if(e.cursorVersion!==null)return{version:e.cursorVersion,seenAtMs:e.capturedAtMs}}var kR={...ko,versionKey:To,versionOf:bR,readRegistry:(e,n)=>se(e,n),parseQueueEntry:e=>Uo(e),turnOf:dl,decisionTurnOf:cl,opensTurn:ul,closesTurn:ll,subagentOf:pl,fillableEvent:fl,holdBack:(e,n)=>IR(e,n)};function CR(e,n={}){return vp(kR,e,n)}async function _R(e,n,t){let r=Fe({homeDir:e});return r===null?null:r.ingest_token!==n?r:je({lockPath:`${Ee(e,"cursor")}.lock`},async()=>{let o=Fe({homeDir:e});if(o===null)return null;if(o.ingest_token!==n)return o;let s=o.api_endpoint;if(s===void 0)return null;try{let i={agent:"cursor",apiEndpoint:s,ingestEndpoint:o.endpoint,homeDir:e,host:o.host,device:ot(e),log:()=>{}},a=kn(i),d=await bn(s,o.refresh_token,t,a),c=_n(i,d,{apiEndpoint:s,ingestEndpoint:o.endpoint});return tt(e,c,{},"cursor"),Cn(i,d,a),c}catch{return null}})}function TR(e={}){let n=e.home??(0,Np.homedir)(),t=e.io??O;return{home:n,io:t,lockIO:yr,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:ER,pid:process.pid,limits:_a,credentials:()=>Fe({homeDir:n}),refresh:r=>_R(n,r),claimFile:(r,o)=>{try{return(0,Dp.renameSync)(r,o),!0}catch{return!1}},scopeVersion:Pp(n,j,t)??"0.0.0",...e}}async function Oa(e={}){try{await CR(TR(e.deps??{}),e)}catch{}return 0}function OR(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}OR()&&Oa().then(e=>{process.exitCode=e});var ts="# agenttrail: Cursor capture hooks (agenttrail setup --agent cursor)";function jp(e,n,t={}){return eo(e,n,ts,t)}function xa(e,n,t={}){return Bd(e,n,ts,t)}var Fp="capture-hook.mjs",xR="pep-hook.mjs",Mp=/(?:^|\s)--agent cursor(?=\s|$)/;function hr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ot(e){return typeof e=="string"&&e.includes(Fp)&&Mp.test(e)}function Lp(e){return typeof e!="string"?!1:ha(e)?!0:Mp.test(e)?e.includes(Fp)||e.includes(xR):!1}function mn(e){if(e===void 0){let o={};return{ok:!0,doc:{version:1,hooks:o},hooks:o}}let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:"is not valid JSON"}}if(!hr(n))return{ok:!1,reason:"is not a JSON object"};if(n.version!==void 0&&n.version!==1)return{ok:!1,reason:`has version ${JSON.stringify(n.version)}, not 1`};if(n.hooks!==void 0&&!hr(n.hooks))return{ok:!1,reason:'has a "hooks" value that is not an object'};let t=n.hooks??{};for(let[o,s]of Object.entries(t))if(!Array.isArray(s))return{ok:!1,reason:`has a "${o}" hook list that is not an array`};let r="version"in n?{...n}:{version:1,...n};return r.hooks=t,{ok:!0,doc:r,hooks:t}}function AR(e){return`${JSON.stringify(e,null,2)}
|
|
50
50
|
`}function Sr(e){return Array.isArray(e)?`[${e.map(Sr).join(",")}]`:hr(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Sr(e[t])}`).join(",")}}`:JSON.stringify(e)}function Aa(e,n,t,r){let o=AR(e),s=Object.values(r).every(i=>i.length===0)&&Object.keys(e).every(i=>i==="version"||i==="hooks");return{ok:!0,text:o,changed:o!==n,removed:t,empty:s}}function rs(e){return hr(e)&&typeof e.command=="string"?e.command:void 0}function Rr(e,n,t){let r=mn(e);if(!r.ok)return r;let o={...r.hooks},s=0;for(let[i,a]of Object.entries(o)){let d=a.filter(p=>{let l=rs(p);return l!==void 0&&t(l)}),c=n[i]??[];if(Sr(d)===Sr(c))continue;let u=a.filter(p=>!d.includes(p));s+=d.length,o[i]=[...u,...c]}for(let[i,a]of Object.entries(n))o[i]===void 0&&(o[i]=[...a]);return r.doc.hooks=o,Aa(r.doc,e,s,o)}function wa(e,n){if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=mn(e);if(!t.ok)return t;let r={},o=0;for(let[s,i]of Object.entries(t.hooks)){let a=i.filter(d=>{let c=rs(d);return!(c!==void 0&&n(c))});o+=i.length-a.length,(a.length>0||i.length===0)&&(r[s]=a)}return t.doc.hooks=r,Aa(t.doc,e,o,r)}function va(e,n){if(n.length===0)return wa(e,ha);if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=mn(e);if(!t.ok)return t;let r={};for(let[o,s]of Object.entries(t.hooks))r[o]=s.map(i=>{let a=rs(i);if(a===void 0||!hr(i))return i;let d=dp(a,n);return d===void 0||d===a?i:{...i,command:d}});return t.doc.hooks=r,Aa(t.doc,e,0,r)}function xt(e,n){let t=mn(e);if(!t.ok)return[];let r=[];for(let[o,s]of Object.entries(t.hooks))for(let i of s){let a=rs(i);a!==void 0&&n(a)&&r.push({event:o,entry:i})}return r}function wR(e,n){let t=o=>{let s=wa(o,Lp);if(!s.ok)return;let i=mn(s.text);if(!i.ok)return;let a=Object.fromEntries(Object.entries(i.hooks).filter(([,d])=>d.length>0));return Sr({...i.doc,hooks:a})},r=t(e);return r!==void 0&&r===t(n)}var Pa={refusal:e=>{let n=mn(e);return n.ok?void 0:n.reason},remove:(e,n)=>wa(e,n),hasAnyOurs:e=>xt(e,Lp).length>0,sameApartFromOurs:(e,n)=>wR(e,n)};function Up(e){return Vs(e,j)}function At(e,n,t,r={}){return Md(e,j,n,t,r)}function Da(e,n,t,r={}){return Ld(e,j,n,Pa,t,r)}var $p=require("crypto"),ye=require("path"),Bp=require("url");var vR={};function Gp(){let e=vR.url;return e?(0,ye.dirname)((0,Bp.fileURLToPath)(e)):typeof __dirname<"u"?__dirname:process.cwd()}function Hp(e,n,t=Gp(),r=o=>O.exists(o)){let o=t;for(;;){for(let i of[(0,ye.join)(o,e),(0,ye.join)(o,"dist",e)])if(r((0,ye.join)(i,n)))return i;let s=(0,ye.dirname)(o);if(s===o)return;o=s}}function ja(e=Gp(),n=O){let t=e;for(;;){let r=(0,ye.join)(t,"package.json");if(n.exists(r))try{let s=JSON.parse(n.readFile(r).toString("utf8"));if(s!==null&&typeof s=="object"){let{name:i,version:a}=s;if(typeof a=="string"&&(i===void 0||typeof i=="string"))return a}}catch{}let o=(0,ye.dirname)(t);if(o===t)return"unknown";t=o}}function Na(e){return(0,$p.createHash)("sha256").update(e).digest("hex")}function os(e,n,t=O){let r=N(e,n).install;try{if(!t.exists(r))return;let o=JSON.parse(t.readFile(r).toString("utf8"));if(o===null||typeof o!="object")return;let s=o;return s.v===1&&typeof s.nodePath=="string"?s:void 0}catch{return}}function Kp(e,n,t,r){let o=r.io??O,s=N(e,n);o.mkdirp(s.runtime,rn);let i={},a=[];for(let p of t){let l=o.readFile((0,ye.join)(r.sourceDir,p)),f=Na(l);i[p]=f;let m=(0,ye.join)(s.runtime,p),g;try{g=o.exists(m)?Na(o.readFile(m)):void 0}catch{g=void 0}g!==f&&(o.writeFileAtomic(m,l,F),a.push(p))}let d=os(e,n,o),c={v:1,cliVersion:r.cliVersion,nodePath:r.nodePath,files:i,installedAt:d?.installedAt??r.now.toISOString()},u=d!==void 0&&d.cliVersion===c.cliVersion&&d.nodePath===c.nodePath&&JSON.stringify(d.files)===JSON.stringify(c.files);return u||o.writeFileAtomic(s.install,`${JSON.stringify(c,null,2)}
|
|
51
|
-
`,F),{runtimeDir:s.runtime,copied:a,record:c,recordWritten:!u}}function Vp(e,n,t,r=O){let o=N(e,n),s=os(e,n,r);if(s===void 0)return["no install record (run setup again)"];let i=[];r.exists(s.nodePath)||i.push(`the Node the hooks run, ${s.nodePath}, is no longer there`);for(let a of t){let d=(0,ye.join)(o.runtime,a),c;try{c=r.exists(d)?Na(r.readFile(d)):void 0}catch{c=void 0}c===void 0?i.push(`${d} is missing`):s.files[a]!==void 0&&c!==s.files[a]&&i.push(`${d} is not the file setup copied`)}return i}var wt=["capture-hook.mjs","flush.mjs","pep-hook.mjs"],ss=["capture-hook.mjs","flush.mjs"];function Wp(e,n=t=>O.exists(t)){return Hp(j,wt[0],e,n)}function Qp(e,n=O){return os(e,j,n)}function Jp(e,n){return Kp(e,j,wt,n)}function Er(e,n=O,t=wt){return Vp(e,j,t,n)}var PR={stop:5},DR=2,Xp=".cursor",Zp="hooks.json",Yp=1e4;async function Ma(e,n,t={}){return Zl(e,j,n,t)}function NR(e,n){return{command:n,timeout:PR[e]??DR}}function vt(e){return Ot(e)||Xo(e)}function Fa(e,n){return{...ef(e),...n===void 0?{}:Ia(n)}}function ef(e){return Object.fromEntries(me.map(n=>[n,[NR(n,e)]]))}function jR(e,n){return Hn(e,(0,q.join)(n,"capture-hook.mjs"),"project")}function is(e,n){return Hn(e,(0,q.join)(n,"capture-hook.mjs"),"user")}function qe(e){return(0,q.join)(e,Xp,Zp)}function ae(e){return(0,q.join)(e,Xp,Zp)}function as(e,n){return(0,q.relative)(e,qe(n)).split(q.sep).join("/")}var
|
|
51
|
+
`,F),{runtimeDir:s.runtime,copied:a,record:c,recordWritten:!u}}function Vp(e,n,t,r=O){let o=N(e,n),s=os(e,n,r);if(s===void 0)return["no install record (run setup again)"];let i=[];r.exists(s.nodePath)||i.push(`the Node the hooks run, ${s.nodePath}, is no longer there`);for(let a of t){let d=(0,ye.join)(o.runtime,a),c;try{c=r.exists(d)?Na(r.readFile(d)):void 0}catch{c=void 0}c===void 0?i.push(`${d} is missing`):s.files[a]!==void 0&&c!==s.files[a]&&i.push(`${d} is not the file setup copied`)}return i}var wt=["capture-hook.mjs","flush.mjs","pep-hook.mjs"],ss=["capture-hook.mjs","flush.mjs"];function Wp(e,n=t=>O.exists(t)){return Hp(j,wt[0],e,n)}function Qp(e,n=O){return os(e,j,n)}function Jp(e,n){return Kp(e,j,wt,n)}function Er(e,n=O,t=wt){return Vp(e,j,t,n)}var PR={stop:5},DR=2,Xp=".cursor",Zp="hooks.json",Yp=1e4;async function Ma(e,n,t={}){return Zl(e,j,n,t)}function NR(e,n){return{command:n,timeout:PR[e]??DR}}function vt(e){return Ot(e)||Xo(e)}function Fa(e,n){return{...ef(e),...n===void 0?{}:Ia(n)}}function ef(e){return Object.fromEntries(me.map(n=>[n,[NR(n,e)]]))}function jR(e,n){return Hn(e,(0,q.join)(n,"capture-hook.mjs"),"project")}function is(e,n){return Hn(e,(0,q.join)(n,"capture-hook.mjs"),"user")}function qe(e){return(0,q.join)(e,Xp,Zp)}function ae(e){return(0,q.join)(e,Xp,Zp)}function as(e,n){return(0,q.relative)(e,qe(n)).split(q.sep).join("/")}var Jx={...ko,runtimeFiles:wt,captureRuntimeFiles:ss,captureEvents:me,projectHooksPath:qe,userHooksPath:ae,hooksFormat:Pa,mergeEntries:(e,n,t)=>Rr(e,n,t),isOurs:vt,captureEntries:ef,enforcementEntries:Ia,command:Hn,gateEnvVar:fr,excludeMarker:ts,transcriptFolderOf:Fn};function FR(e,n){let t;try{t=n.readText(e)}catch(s){return`${e} cannot be read \u2014 ${s.message}`}let r=mn(t);if(!r.ok)return`${e} ${r.reason}`;let o=n.fileMode(e);if(o!==void 0&&(o&128)===0)return`${e} is read-only`}function nf(e,n,t){return tp(e,n,t)}function MR(e,n,t){return rp(e,n,t)}function zp(e,n){let t=r=>(r??"").replace(/\/+$/,"");return t(e)===t(n)}async function LR(e,n,t){let r=t.login??Wr,o=Fe(n),s=e.flags.endpoint?.trim()||e.io.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||e.flags["api-endpoint"]?.trim()||e.io.env.AGENTTRAIL_API_ENDPOINT?.trim(),i=o!==null&&!!s&&(!zp(o.endpoint,n.ingestEndpoint)||!zp(o.api_endpoint??n.apiEndpoint,n.apiEndpoint));return o&&!dn(o,n.now)&&!i?{creds:o,reused:!0,endpointChanged:!1}:{creds:await r(n),reused:!1,endpointChanged:i}}function qp(e,n,t,r){let o=t.git??B,s=t.hooksIO??J;if(!(0,Xe.existsSync)(n))return{path:n,install:r??"project"};if(!be(e,o))return{path:n,install:"project",excluded:"not-a-repo"};let i=as(e,n),a=Me(e,i,o);if(a==="tracked")return{path:n,install:"user",note:`this repo tracks ${i}`};if(a==="unknown")return{path:n,install:"user",note:`git could not say whether ${i} is tracked, so nothing was written into the repo`};let d=jp(e,i,{git:o,io:s});return d.ok?{path:n,install:"project",excluded:d.state}:{path:n,install:"user",note:d.reason}}function La(e,n,t,r,o){let s=o.hooksIO??J,i=ae(e);if(n.length===0){let l=Da(e,i,vt,{io:s});if(!l.ok)return{ok:!1,reason:l.reason};let f=At(e,i,m=>va(m,[]),{io:s});return f.ok?{ok:!0,changed:l.change.changed||f.change.changed}:{ok:!1,reason:f.reason}}if(!up(o.platform??process.platform))return{ok:!0,changed:!1,note:"capture for a repo that tracks .cursor/hooks.json needs a POSIX shell, which Windows has not; nothing was written to ~/.cursor/hooks.json"};let a=qo(n,t),d=r===void 0?void 0:qo(n,r),c=(o.dryRun??cp)(a);if(!c.ok)return{ok:!0,changed:!1,note:`capture for a repo that tracks .cursor/hooks.json was not installed: ${c.reason}. Fix your shell's startup file, or stop tracking .cursor/hooks.json`};let u=At(e,i,l=>Rr(l,Fa(a,d),vt),{io:s});if(!u.ok)return{ok:!1,reason:u.reason};let p=At(e,i,l=>va(l,n),{io:s});return p.ok?{ok:!0,changed:u.change.changed||p.change.changed}:{ok:!1,reason:p.reason}}var UR=["key","team","global"];async function tf(e,n={}){let t=e.flags;if(t.unregister===!0)return $R(e,n);let r=UR.filter(C=>!!t[C]);if(r.length>0)return e.io.error(`error: ${r.map(C=>`--${C}`).join(", ")} ${r.length===1?"is":"are"} for Claude Code. Cursor setup signs this device in with your browser and connects this project: ${V("cursor","setup")}`),1;let o;try{o=e.sessionEnv()}catch(C){return e.io.error(`error: ${C.message}`),1}let s=o.homeDir,i=n.io??O,a=n.hooksIO??J,d=n.realpath??(C=>Xe.realpathSync.native(C)),c=n.nodePath??process.execPath,u,p;try{let C=se(s,i);if(C.kind==="unreadable")throw new un(s);p=C.kind==="ok"?Object.values(C.registry.projects).map(x=>x.root):[];let T=d(e.io.cwd),$=nf(T,p,d);u={root:$,folder:T,isSubfolder:T!==$}}catch(C){return e.io.error(`error: ${C.message}`),1}let l=[],f=(()=>{try{return d(s)}catch{return s}})();(u.root===f||f.startsWith(`${u.root}${q.sep}`))&&l.push(`${u.root} holds your home folder, whose .cursor/hooks.json is Cursor's user-level file \u2014 every workspace would run these hooks. Run setup inside a project.`);for(let C of[u.root,u.folder]){let T=ya(C);T!==void 0&&l.push(T)}let m=n.runtimeSourceDir??Wp();if(m===void 0)l.push("could not find the built Cursor runtime (dist/cursor/capture-hook.mjs) in this installation");else for(let C of wt)i.exists((0,q.join)(m,C))||l.push(`the built Cursor runtime is incomplete: ${(0,q.join)(m,C)} is missing`);let g=M(s).runtime;for(let C of[c,(0,q.join)(g,"capture-hook.mjs")]){let T=Yo(C);T!==void 0&&l.push(T)}let h=[qe(u.root),...u.isSubfolder?[qe(u.folder)]:[],ae(s)];for(let C of h){let T=FR(C,a);T!==void 0&&l.push(T)}if(l.length>0||m===void 0){for(let C of l)e.io.error(`error: ${C}`);return e.io.error("Nothing was changed."),1}let S=m,b,E,k;try{({creds:b,reused:E,endpointChanged:k}=await LR(e,o,n))}catch(C){return e.io.error(`error: ${C.message}`),1}let I=MR(u.root,b.org_id,t);if("error"in I)return e.io.error(`error: ${I.error}`),1;let y=t.developer?.trim()||void 0,R=!!t["capture-content"],_=(n.now??(()=>new Date))();try{return await Ma(s,async()=>{let C=[];Jp(s,{sourceDir:S,nodePath:c,cliVersion:n.cliVersion??ja(),now:_,io:i}),al(s,i);let T=se(s,i);if(T.kind==="unreadable")throw new un(s);let $=T.kind==="ok"?T.registry:{v:1,projects:{}},x=qr(u.root),ce=$.projects[x],Ze=new Map((ce?.subfolders??[]).map(A=>[A.path,A]));u.isSubfolder&&!Ze.has(u.folder)&&Ze.set(u.folder,{path:u.folder,transcriptFolder:Fn(u.folder),install:"project",registeredAt:_.toISOString()});let Sn=qp(u.root,u.root,n),Oe=[...Ze.values()].map(A=>qp(u.root,A.path,n,A.install));for(let A of[Sn,...Oe])A.note!==void 0&&C.push(`${A.path}: ${A.note}`);let Ft={projectKey:x,root:u.root,transcriptFolder:Fn(u.root),orgId:b.org_id,projectSlug:I.slug,projectId:I.id,projectSource:I.source,projectLabel:I.label,...y!==void 0?{developerId:y}:{},captureContent:R,install:Sn.install,registeredAt:ce?.registeredAt??_.toISOString(),...Oe.length>0?{subfolders:Oe.map(A=>({...Ze.get(A.path),install:A.install}))}:{}},Mt=(n.cursorVersion??yp)(),Rn=mp({apiBase:b.api_endpoint??b.endpoint,orgId:b.org_id,agentId:Le(b.org_id,op),timeoutMs:lt,rawCursorVersion:Mt,hasUserScopeFolders:[Sn,...Oe].some(A=>A.install==="user"),now:_}),ue=Rn;if(Rn.enabled){let A=await Sa({url:pt(Rn.apiBase),token:b.ingest_token,timeoutMs:Rn.timeoutMs},n.fetchFn??fetch);if(A.outcome==="ok")A.snapshot!==void 0&&i.writeFileAtomic(M(s).pepSnapshot,`${JSON.stringify(A.snapshot)}
|
|
52
52
|
`,F);else{let We=hp(A.outcome);ue={...Rn,enabled:!1,userScopeHandoff:!1,probeNote:We},C.push(We)}}ou(s,{...Ft,enforce:ue.enabled},i),ue.enabled&&ca(s,ue,i);let Ya=jR(c,g),za=ue.enabled?gp(c,g):void 0,Lt=[];for(let A of[Sn,...Oe]){if(!(0,Xe.existsSync)(A.path))continue;let We=qe(A.path);if(A.install==="project"){let le=At(s,We,Ar=>Rr(Ar,Fa(Ya,za),vt),{io:a});le.ok||Lt.push(le.reason)}else{let le=rf(s,u.root,A.path,n);le.ok||Lt.push(le.reason),xa(u.root,as(u.root,A.path),{git:n.git??B,io:a})}}for(let A of Object.values($.projects)){if(A.projectKey===x)continue;let We=[{path:A.root,install:A.install},...(A.subfolders??[]).map(le=>({path:le.path,install:le.install}))];for(let le of We){if(le.install!=="project"||!(0,Xe.existsSync)(le.path))continue;let Ar=At(s,qe(le.path),Sg=>Rr(Sg,Fa(Ya,A.enforce===!0?za:void 0),vt),{io:a});Ar.ok||C.push(Ar.reason)}}let qa=se(s,i),hg=qa.kind==="ok"?ki(qa.registry):[],xr=La(s,hg,is(c,g),ue.enabled?ba(c,g):void 0,n);if(xr.ok?xr.note!==void 0&&C.push(xr.note):Lt.push(xr.reason),Lt.length>0){for(let A of Lt)e.io.error(`error: ${A}`);return 1}ue.enabled||ca(s,ue,i),E?(e.io.log(`Sign-in: REUSED \u2014 this project is connected to org ${b.org_id}.`),e.io.log(" This device was already signed in, and that sign-in is shared by every Cursor project on this machine."),e.io.log(` For a different org: \`${V("cursor","logout")}\`, then run setup again. That signs the WHOLE MACHINE out and disconnects every other project set up here \u2014 there is no per-project sign-in.`)):e.io.log(`Signed in for Cursor (org ${b.org_id}, device ${b.host}).`),k&&e.io.log(`Every connected project now sends to ${b.endpoint}.`),e.io.log(`Project: ${I.slug} -> project.id ${I.id}`),I.note!==void 0&&e.io.error(I.note);for(let A of[Sn,...Oe]){if(!(0,Xe.existsSync)(A.path)){e.io.error(`note: ${A.path} is no longer there; it keeps its record until you run setup --unregister`);continue}e.io.log(A.install==="project"?`Capture: ${me.length} capture entries in ${qe(A.path)}${A.excluded==="not-a-repo"?"":" (kept out of git)"}`:`Capture: ${me.length} capture entries for ${A.path} in ${ae(s)}, gated to your connected folders`)}for(let A of C)e.io.error(`note: ${A}`);R?(e.io.log("Content capture: ON (prompts, commands, paths and tool output; scrubbed on this machine before anything is queued)."),e.io.error(Mr("cursor"))):e.io.log("Content capture: OFF (metadata and tokens only; turn it on with --capture-content).");{let A=Zo({record:ue,projectEnforced:ue.enabled,problems:Er(s,i,[Vn]),entriesInstalled:ue.enabled});e.io.log(A.headline),ue.enabled&&e.io.log(` ${Ea.length} enforcement entries written alongside the capture ones, fail-closed.`);for(let We of A.details)e.io.log(` ${We}`)}return e.io.log(`Open ${u.folder} in Cursor: it loads hooks from the folder it opens, and runs a project's hooks only in a trusted workspace \u2014 trust the folder if Cursor asks.`),e.io.log(`Then check it with \`${V("cursor","status")}\`.`),0},n)}catch(C){return e.io.error(`error: ${C.message}`),1}}async function $R(e,n={}){let t;try{t=e.sessionEnv()}catch(a){return e.io.error(`error: ${a.message}`),1}let r=t.homeDir,o=n.io??O,s=n.realpath??(a=>Xe.realpathSync.native(a)),i=n.nodePath??process.execPath;try{return await Ma(r,async()=>{let a=se(r,o);if(a.kind==="unreadable")throw new un(r);if(a.kind==="missing")return e.io.log("No Cursor project is connected on this machine; nothing to remove."),0;let d=s(e.io.cwd),c=Object.values(a.registry.projects).map(S=>S.root),u=nf(d,c,s),p=a.registry.projects[qr(u)]??Object.values(a.registry.projects).filter(S=>d===S.root||d.startsWith(`${S.root}${q.sep}`)).sort((S,b)=>b.root.length-S.root.length)[0];if(p===void 0)return e.io.log(`${d} is not a connected Cursor project; nothing to remove.`),0;let l=of(r,p,n);if(l.failures.length>0){for(let S of l.failures)e.io.error(`error: ${S}`);return e.io.error("The project is still connected; fix the file above and run this again."),1}let f={v:1,projects:Object.fromEntries(Object.entries(a.registry.projects).filter(([S])=>S!==p.projectKey))},m=Tt(r,o)?.enabled===!0,g=La(r,ki(f),is(i,M(r).runtime),m?ba(i,M(r).runtime):void 0,n);if(!g.ok)return e.io.error(`error: ${g.reason}`),1;su(r,p.projectKey,o);let h=sf(r,o,p.projectKey);o.remove(St(r,p.projectKey)),e.io.log(`Disconnected ${p.root} (project ${p.projectSlug}).`);for(let S of l.folders)e.io.log(`Removed our entries from ${S}`);return h>0&&e.io.log(`Dropped ${h} queued event(s) that had not been sent.`),e.io.log(`This device stays signed in for Cursor; \`${V("cursor","logout")}\` signs it out and removes the rest.`),0},n)}catch(a){return e.io.error(`error: ${a.message}`),1}}function rf(e,n,t,r){let o=r.git??B,s=r.hooksIO??J,i=qe(t),a=be(n,o)&&Me(n,as(n,t),o)==="tracked";return Da(e,i,vt,{io:s,keepFile:a})}function of(e,n,t){let r=t.hooksIO??J,o=t.git??B,s=[],i=[],a=[n.root,...(n.subfolders??[]).map(d=>d.path)];for(let d of a){let c=qe(d),u=rf(e,n.root,d,t);u.ok?u.change.changed&&s.push(c):i.push(u.reason),(0,Xe.existsSync)((0,q.dirname)((0,q.dirname)(c)))&&xa(n.root,as(n.root,d),{git:o,io:r})}return{folders:s,failures:i}}function sf(e,n,t){return ep(e,j,n,t)}async function BR(e){try{await Oa({maxRunMs:e.maxRunMs,closeOpenTurns:!0,deps:{home:e.home}})}catch{}}async function GR(e,n,t={}){return np(e,j,n,{...t,run:t.run??BR})}var HR={root:"the folder itself, which holds only what the entries below account for",credentials:"revoked and cleared by runCursorLogout, which reports it separately",captureHook:"inside runtime, removed with it",flush:"inside runtime, removed with it"};function KR(e){let n=M(e);return[...Object.entries(n).filter(([r])=>!(r in HR)).map(([,r])=>r),Up(e)]}async function af(e,n={}){let t;try{t=e.sessionEnv()}catch(i){return e.io.error(`error: ${i.message}`),1}let r=t.homeDir,o=n.io??O,s=!1;try{await Ma(r,async()=>{let i=await(n.flush??GR)(r,Yp),a=se(r,o);if(a.kind==="unreadable"){e.io.error(`error: ${new un(r).message}`),s=!0;return}let d=a.kind==="ok"?a.registry:{v:1,projects:{}},c=[];for(let l of Object.values(d.projects)){let f=of(r,l,n);c.push(...f.folders);for(let m of f.failures)e.io.error(`error: ${m}`),s=!0}let u=La(r,[],"",void 0,n);u.ok?u.changed&&c.push(ae(r)):(e.io.error(`error: ${u.reason}`),s=!0);for(let l of c)e.io.log(`Removed our entries from ${l}`);let p=sf(r,o);if(s)e.io.error("Some entries are still in place, so the runtime and the registry were kept. Fix the file above and run logout again.");else{let l=KR(r),f=l.some(m=>o.exists(m));for(let m of l)o.remove(m);i.stillLocked&&e.io.log(`A Cursor sender was still running after ${Yp/1e3}s, so logout went ahead.`),p>0&&e.io.log(`Dropped ${p} queued event(s) that had not been sent.`),f&&e.io.log("Removed this machine's Cursor capture state.")}},n)}catch(i){e.io.error(`error: ${i.message}`),s=!0}try{await Rd(t)}catch(i){e.io.error(`error: ${i.message}`),s=!0}return s?1:0}var cf=require("fs"),Wn=require("path");var VR="3.21.16";function df(e){return[{path:e.root,install:e.install,record:e},...(e.subfolders??[]).map(n=>({path:n.path,install:n.install,record:e}))]}function WR(e,n){return n===e||n.startsWith(e.endsWith(Wn.sep)?e:`${e}${Wn.sep}`)}function QR(e,n,t){let r=St(e,t);try{return n.exists(r)?n.readdir(r).filter(o=>o.endsWith(".json")).length:0}catch{return 0}}function JR(e,n,t){let r=t.hooksIO??J,o=n.install==="project"?(0,Wn.join)(n.path,".cursor","hooks.json"):ae(e),s;try{s=r.readText(o)}catch{return}let i=xt(s,Xo);return n.install==="project"?i.length>0:i.some(a=>(Kn(a.entry.command)?.folders??[]).includes(n.path))}function YR(e,n,t){let r=t.hooksIO??J,o=t.git??B,s=[],i=(0,Wn.join)(n.path,".cursor","hooks.json");if(n.install==="project"){let u;try{u=r.readText(i)}catch(f){return s.push(`${i} cannot be read \u2014 ${f.message}`),s}let p=xt(u,Ot);p.length!==me.length&&s.push(`${i} holds ${p.length} of our ${me.length} entries; run setup again`);let l=i.slice(n.record.root.length+1).split(Wn.sep).join("/");return Me(n.record.root,l,o)==="tracked"&&s.push(`${l} is tracked by git now, so a checkout can replace our entries; run setup again to move this folder to the gated entries in ${ae(e)}`),s}let a;try{a=r.readText(ae(e))}catch(u){return s.push(`${ae(e)} cannot be read \u2014 ${u.message}`),s}let d=xt(a,Ot);return d.length!==me.length?(s.push(`${ae(e)} holds ${d.length} of our ${me.length} gated entries; run setup again`),s):(new Set(d.flatMap(u=>Kn(u.entry.command)?.folders??[])).has(n.path)||s.push(`the gate in ${ae(e)} does not list ${n.path}; run setup again there`),s)}function uf(e,n={}){let t;try{t=e.sessionEnv()}catch(E){return e.io.error(`error: ${E.message}`),1}let r=t.homeDir,o=n.io??O,s=n.hooksIO??J,i=n.realpath??(E=>cf.realpathSync.native(E)),a=Fe(t);a?(e.io.log(`AgentTrail for Cursor: SIGNED IN (org ${a.org_id}, device ${a.host})`),e.io.log(`Ingest endpoint: ${a.endpoint}`),a.api_endpoint&&e.io.log(`API endpoint (device-auth): ${a.api_endpoint}`),e.io.log(dn(a,t.now)?`Ingest token: EXPIRED (${a.ingest_token_expires_at})`:`Ingest token: valid until ${a.ingest_token_expires_at}`)):e.io.log(`AgentTrail for Cursor: NOT SIGNED IN. Run \`${V("cursor","login")}\`.`);let d=se(r,o);if(d.kind==="unreadable")return e.io.log(`Capture: BROKEN \u2014 ${M(r).projects} cannot be read. Fix or delete it, then run \`${V("cursor","setup")}\`.`),0;let c=d.kind==="ok"?d.registry:{v:1,projects:{}};for(let E of d.kind==="ok"?d.skipped:[])e.io.log(`Capture: one record in ${M(r).projects} cannot be read${E.root!==void 0?` (${E.root})`:""}; run setup again there.`);let u;try{u=i(e.io.cwd)}catch{u=e.io.cwd}let p=Object.values(c.projects).flatMap(df),l=p.filter(E=>WR(E.path,u)).sort((E,k)=>k.path.length-E.path.length)[0];if(l===void 0){if(e.io.log(`Capture: NOT INSTALLED for ${u}. Run \`${V("cursor","setup")}\` in the folder you open in Cursor.`),Object.keys(c.projects).length===0)return 0}else{let E=[];a||E.push("this device is not signed in for Cursor, so nothing is uploaded"),il(r,o)===void 0&&E.push(`${M(r).queueKey} is missing or damaged; the capture hook records nothing without it`),E.push(...Er(r,o,ss)),E.push(...YR(r,l,n)),e.io.log(E.length===0?`Capture: ON for ${l.path} (project ${l.record.projectSlug})`:`Capture: BROKEN for ${l.path} (project ${l.record.projectSlug})`);for(let k of E)e.io.log(` ${k}`);l.path!==u&&e.io.log(` Cursor loads hooks from the folder it opens: open ${l.path}, or run setup in ${u} to capture it on its own.`),e.io.log(` Content capture: ${l.record.captureContent?"ON (scrubbed on this machine before anything is queued)":"OFF (metadata and tokens only)"}`),e.io.log(` Queued and not yet sent: ${QR(r,o,l.record.projectKey)}`)}{let E=Tt(r,o),k=Zo({record:E,projectEnforced:l?.record.enforce,problems:Er(r,o,[Vn]),entriesInstalled:l===void 0?void 0:JR(r,l,n)});e.io.log(k.headline);for(let I of k.details)e.io.log(` ${I}`)}let f=(()=>{try{return(n.versionSeen??fu)(r,l?.record.projectKey,o)}catch{return}})();e.io.log(f===void 0?"Cursor version seen: none recorded yet \u2014 open the project in Cursor and take one turn.":`Cursor version seen: ${f.version} (recorded ${new Date(f.seenAtMs).toISOString()})`),e.io.log("Workspace trust: cannot be checked from here. Cursor runs a project's hooks only in a trusted workspace."),e.io.log(`Agent Window: on Cursor older than ${VR}, hooks may not launch there; use an editor window or update Cursor.`);let m=Object.values(c.projects);if(m.length>0){e.io.log(`Connected projects (${m.length}):`);for(let E of m){e.io.log(` ${E.root} \u2014 ${E.projectSlug} (project.id ${E.projectId})`);for(let k of df(E))e.io.log(` ${k.path}: ${k.install==="project"?"entries in its own .cursor/hooks.json":`gated entries in ${ae(r)}`}`)}}let g=ae(r),h;try{h=s.readText(g)}catch{h=void 0}let S=xt(h,Ot);if(S.length>0){let E=[...new Set(S.flatMap(y=>Kn(y.entry.command)?.folders??[]))].sort(),k=p.filter(y=>y.install==="user").map(y=>y.path).sort();e.io.log(`Gate in ${g}: ${E.join(", ")}`),JSON.stringify(E)!==JSON.stringify([...new Set(k)])&&e.io.log(` does not match the registry (${k.join(", ")||"no folder"}); run \`${V("cursor","setup")}\` again`);let I=is(Qp(r,o)?.nodePath??n.nodePath??process.execPath,M(r).runtime);S.every(y=>Kn(y.entry.command)?.helper===I)||e.io.log(" one gated entry runs another Node or another copy; run setup again")}let b=(n.senderSummary??((E,k)=>gu(E,k,o)))(r,l?.record.projectKey);b?.lastUploadAt!==void 0&&e.io.log(`Last upload: ${b.lastUploadAt}`),b?.lastError!==void 0&&e.io.log(`Last error: ${b.lastError}`);for(let[E,k]of Object.entries(b?.dropped??{}))e.io.log(`Dropped (${E}): ${k}`);return 0}var Cr=require("fs"),bf=require("path");var lf=require("child_process"),br=require("fs"),Qn=require("path"),pf=require("url"),oE={},us="agenttrail",zR="agenttrail",Te=`${zR}@${us}`,ff="2.1.211",ls=e=>{let n=(0,lf.spawnSync)("claude",[...e],{encoding:"utf8"});return n.error?{code:null,stdout:"",stderr:"",spawnError:n.error.code??n.error.message}:{code:n.status,stdout:n.stdout??"",stderr:n.stderr??""}},cs=class extends Error{constructor(){super("Claude Code (`claude`) was not found on your PATH. Install Claude Code first, then re-run \u2014 see https://docs.claude.com/en/docs/claude-code."),this.name="ClaudeCliNotFoundError"}},$a=class extends Error{constructor(t,r=ff){super(`This Claude Code version (${t??"unknown"}) does not support the AgentTrail enforcement plugin. Upgrade Claude Code to ${r} or newer, then re-run.`);this.foundVersion=t;this.minVersion=r;this.name="PluginUnsupportedError"}foundVersion;minVersion},Ir=class extends Error{constructor(t,r,o){super(`\`claude plugin ${t}\` failed (exit ${r??"null"}): ${o.trim()||"no stderr"}`);this.step=t;this.exitCode=r;this.stderr=o;this.name="PluginCommandError"}step;exitCode;stderr};function gf(e){let n=e.match(/(\d+)\.(\d+)\.(\d+)/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function Ba(e,n){for(let t=0;t<3;t++){if(e[t]>n[t])return!0;if(e[t]<n[t])return!1}return!0}var qR=gf(ff);function mf(e){let n=e(["--version"]);if(n.spawnError==="ENOENT")throw new cs;if(n.spawnError)throw new cs;let t=gf(n.stdout);if(t&&!Ba(t,qR))throw new $a(n.stdout.trim()||null)}function XR(e,n,t){let r=e(["plugin","marketplace","list","--json"]);if(r.code!==0)return!1;try{let o=JSON.parse(r.stdout);if(!Array.isArray(o))return!1;let s=o.find(i=>i?.name===us);return s===void 0||s.path!==n?!1:s.source==="directory"?t(s.path):!0}catch{return!1}}function ds(e){let n=e(["plugin","list","--json"]);if(n.code===0)try{let t=JSON.parse(n.stdout);if(!Array.isArray(t))return;let r=t.find(o=>o?.id===Te);return r==null?void 0:{version:typeof r.version=="string"?r.version:void 0}}catch{return}}function Ua(e){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(e??"");return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function ZR(e){try{let n=(0,br.readFileSync)((0,Qn.join)(e,".claude-plugin","plugin.json"),"utf8"),t=JSON.parse(n)?.version;return typeof t=="string"&&t.length>0?t:void 0}catch{return}}function eE(e){return ds(e)!==void 0}function nE(e){let n=e(["plugin","list","--json"]);if(n.code!==0)return!0;let t;try{t=JSON.parse(n.stdout)}catch{return!0}return Array.isArray(t)?t.some(r=>{let o=r?.id;return typeof o=="string"&&o.endsWith(`@${us}`)}):!0}function tE(){let e=oE.url;return e?(0,Qn.dirname)((0,pf.fileURLToPath)(e)):typeof __dirname<"u"?__dirname:process.cwd()}function rE(e){let n=e??tE();for(;;){let t=(0,Qn.join)(n,"plugin");if((0,br.existsSync)((0,Qn.join)(t,".claude-plugin","marketplace.json")))return t;let r=(0,Qn.dirname)(n);if(r===n)break;n=r}throw new Error("Could not locate the bundled AgentTrail plugin scaffold (plugin/.claude-plugin/marketplace.json). The package may be published without its `plugin/` directory.")}var ps=`claude plugin update ${Te} --scope user`;function yf(e={}){let n=e.scope??"user",t=e.runner??ls,r=e.marketplaceSource??rE(),o=e.pathExists??br.existsSync;mf(t);let s={status:"already-installed",pluginId:Te,scope:n},i=e.packagedVersion??ZR(r),a=ds(t),d=Ua(a?.version),c=Ua(i);if(a!==void 0&&d&&c&&!Ba(c,d))return{...s,note:`A newer AgentTrail plugin (${a.version}) is installed than this CLI ships (${i}); it was left as is.`};if(!XR(t,r,o)){let l=t(["plugin","marketplace","add",r,"--scope",n]);if(l.code!==0)throw new Ir("marketplace add",l.code,l.stderr)}let u=ds(t);if(u!==void 0){if(e.refresh!==!0)return s;let l=u.version,f=Ua(l);if(f===null||c===null){let h=f===null?"installed":"packaged",S=f===null?l:i;return{...s,warning:`Could not read the ${h} AgentTrail plugin version${S===void 0?"":` as x.y.z (got "${S}")`}, so the plugin was not updated. If Claude Code is running an older AgentTrail plugin, run \`${ps}\`, then restart Claude Code.`}}if(Ba(f,c))return s;let m=t(["plugin","update",Te,"--scope",n]),g=ds(t);return g?.version===i?{status:"refreshed",pluginId:Te,scope:n,foundVersion:l,expectedVersion:i}:{status:"refresh-failed",pluginId:Te,scope:n,foundVersion:l,expectedVersion:i,...g?.version===void 0?{}:{afterVersion:g.version},refreshError:m.code!==0?m.stderr.trim()||`exit ${m.code??"null"}`:g===void 0?"the update exited 0, but the plugin list could not be read afterwards":`the update exited 0, but the installed version is ${g.version??"unreadable"}`}}let p=t(["plugin","install",Te,"--scope",n]);if(p.code!==0)throw new Ir("install",p.code,p.stderr);return{status:"installed",pluginId:Te,scope:n}}function hf(e={}){let n=e.scope??"user",t=e.runner??ls;if(mf(t),!eE(t))return{status:"not-installed",pluginId:Te,scope:n};let r=t(["plugin","uninstall",Te,"--scope",n]);if(r.code!==0)throw new Ir("uninstall",r.code,r.stderr);return nE(t)||t(["plugin","marketplace","remove",us,"--scope",n]),{status:"removed",pluginId:Te,scope:n}}var Sf=require("fs"),Rf=require("path");var sE=448,iE=384;function Ef(e,n,t={}){let r=t.writeFile??((s,i,a)=>D(s,i,a!==void 0?{mode:a}:{}));(t.mkdir??((s,i)=>(0,Sf.mkdirSync)(s,{recursive:!0,mode:i})))((0,Rf.dirname)(e),sE),r(e,`${JSON.stringify(n,null,2)}
|
|
53
53
|
`,iE)}var fs=[zs,qs,Xs,Zs,qt,re,te];function kf(e,n={}){return Dt(w(e),fs,n)}function If(e){try{return(0,Cr.realpathSync)(e)}catch{return(0,bf.resolve)(e)}}function Pt(e,n){return If(e)===If(n)}function aE(e,n){return`enforcement NOT enabled in this repo: ${e}, and the enforcement settings are per-machine, so they are not written into a file git would share (capture still active). ${n?"To turn it on, stop tracking that file (`git rm --cached .claude/settings.local.json`, then commit) and run setup again.":"To turn it on, remove the `.gitignore` rule that re-includes `.claude/settings.local.json` and run setup again."}`}async function Ga(e,n){let t=e.timeoutMs??lt,r=n.settingsIO??{},o=Pt(e.settingsRoot,e.home);if(!o){let f=Ue(e.settingsRoot,nn,{...n.git?{git:n.git}:{}});if(!f.ok)return{enforced:!1,reason:"local-settings-tracked",message:aE(f.reason,f.tracked),snapshotCached:!1}}let s=Zd({apiBase:e.apiBase,timeoutMs:t,orgId:e.orgId});o?Ne(e.settingsRoot,s,r):tn(e.settingsRoot,s,r);let i=ec({token:e.token}),a={git:n.git??B,env:n.env??process.env};o&&e.migrate===!0?Zn(e.settingsRoot,i,r,{dotfiles:a}):o&&kr(e.settingsRoot,r)[re]!==void 0?Zn(e.settingsRoot,i,r,{dotfiles:a}):tn(e.settingsRoot,i,r);let d;try{d=await mr({url:pt(e.apiBase),token:e.token,timeoutMs:t},n.fetchFn)}catch(f){if(f instanceof He)return{enforced:!1,reason:"unreachable",message:"could not reach AgentTrail to verify enforcement \u2014 enforcement NOT enabled (capture still active). Re-run `npx -y @agenttrail/cli@latest setup --agent claude` when online.",snapshotCached:!1};throw f}if(d.kind==="unauthorized")return e.deviceTokenPath?{enforced:!1,reason:"device-pending",message:"the policy endpoint rejected this device credential (401) \u2014 your device session was likely revoked or has expired. Re-authenticate with `npx -y @agenttrail/cli@latest login --agent claude`, then re-run `npx -y @agenttrail/cli@latest setup --agent claude`. Enforcement NOT enabled; capture is active.",snapshotCached:!1}:{enforced:!1,reason:"key-rejected",message:"the policy endpoint rejected this credential (401) \u2014 enforcement NOT enabled. Check the API key and re-run `npx -y @agenttrail/cli@latest setup --agent claude`. Capture is active.",snapshotCached:!1};if(d.kind==="tier-disabled")return{enforced:!1,reason:"tier-disabled",message:"AgentTrail refused the enforcement check (403) \u2014 enforcement could not be verified, so it is NOT enabled (capture still active). Re-run `npx -y @agenttrail/cli@latest setup --agent claude`; if it persists, contact support.",snapshotCached:!1};Ef(so(e.home),d.snapshot,n.snapshotIO);let c,u,p={};try{let f=e.migrate===!0,m=n.installPlugin?n.installPlugin(n.runner,{refresh:f}):yf({...n.runner?{runner:n.runner}:{},refresh:f});c=m.status,u=dE(m),p={...m.warning?{pluginWarning:m.warning}:{},...m.note?{pluginNote:m.note}:{}}}catch(f){return{enforced:!1,reason:"install-failed",message:`enforcement plugin install failed (${f.message}) \u2014 enforcement NOT enabled (capture still active).`,snapshotCached:!0}}o?Ne(e.settingsRoot,ei,r):tn(e.settingsRoot,ei,r);let l=o||e.migrate!==!0?!1:Dt(w(e.settingsRoot),fs,r);return{enforced:!0,reason:"enforced",message:`real-time enforcement ENABLED (${u}).`,pluginStatus:c,...p,snapshotCached:!0,migrated:l}}function dE(e){let{foundVersion:n,expectedVersion:t,afterVersion:r}=e;switch(e.status){case"refreshed":return`plugin updated from ${n} to ${t}. Restart Claude Code so it loads the new enforcement hook; until then it keeps running the old one`;case"refresh-failed":return r===void 0?`updating the plugin from ${n} to ${t} could not be confirmed, because its installed version could not be read afterwards (${e.refreshError??"no reason given"}). Run \`${ps}\`, restart Claude Code, and check \`claude plugin list --json\``:`the installed plugin is ${r}: updating it to ${t} did not take (${e.refreshError??"no reason given"}). The ${r} hook still enforces. To update it, run \`${ps}\`, then restart Claude Code`;case"already-installed":return"plugin already-installed";default:return`plugin ${e.status}`}}async function Cf(e,n){let t=n.settingsIO??{},r=e.timeoutMs??lt;if(!e.token)return{enforced:!1,reason:"no-credential",changed:!1};if(!Pt(e.settingsRoot,e.home)&&!Ue(e.settingsRoot,nn,{...n.git?{git:n.git}:{}}).ok)return{enforced:!1,reason:"local-settings-tracked",changed:!1};let o;try{o=await mr({url:pt(e.apiBase),token:e.token,timeoutMs:r},n.fetchFn)}catch(c){if(c instanceof He)return{enforced:!1,reason:"unreachable",changed:!1};throw c}if(o.kind==="unauthorized"||o.kind==="tier-disabled"){let c=Pt(e.settingsRoot,e.home),u=kr(e.settingsRoot,t,!c)[te]!==void 0;u&&c?Dt(w(e.settingsRoot),[te],t):u&&Dt(G(e.settingsRoot),[te],t,384);let p=!c&&kr(e.settingsRoot,t)[te]!==void 0;return{enforced:!1,reason:o.kind==="unauthorized"?"credential-rejected":"tier-disabled",changed:u&&!p}}let s=Pt(e.settingsRoot,e.home),i=kr(e.settingsRoot,t,!s),a=s&&i[re]!==void 0?i:kr(e.settingsRoot,t,!0);if(i[te]!==void 0&&a[re]===e.token)return{enforced:!0,reason:"already-enforced",changed:!1};let d=await Ga(e,n);return d.enforced?{enforced:!0,reason:"enforced",changed:!0}:{enforced:!1,reason:d.reason==="install-failed"||d.reason==="local-settings-tracked"?d.reason:"unreachable",changed:!1}}function kr(e,n,t=!1){let r=t?G(e):w(e),o=n.readFile??(s=>(0,Cr.readFileSync)(s,"utf8"));try{let s=JSON.parse(o(r));if(typeof s!="object"||s===null)return{};let i=s.env;return typeof i=="object"&&i!==null?i:{}}catch{return{}}}function _f(e,n={}){let t=!1;try{t=hf(e.runner?{runner:e.runner}:{}).status==="removed"}catch{}return Dt(G(e.settingsRoot),fs,n,384),Dt(w(e.settingsRoot),fs,n),{pluginRemoved:t}}function Dt(e,n,t,r){let o=t.readFile??(u=>(0,Cr.readFileSync)(u,"utf8")),s=t.writeFile??((u,p,l)=>D(u,p,l!==void 0?{mode:l}:{})),i;try{let u=JSON.parse(o(e));if(typeof u!="object"||u===null)return!1;i=u}catch{return!1}let a=i.env;if(typeof a!="object"||a===null)return!1;let d=a,c=n.filter(u=>u in d);if(c.length===0)return!1;for(let u of c)delete d[u];return s(e,`${JSON.stringify(i,null,2)}
|
|
54
54
|
`,r),!0}var Nf=require("child_process"),he=require("fs"),jf=require("os"),hn=require("path");var Ke=require("fs"),gs=require("path");var cE=/^[A-Za-z0-9._-]{1,128}$/;function Ha(e){return typeof e=="string"&&cE.test(e)&&e!=="."&&e!==".."}function Ka(e){return(0,gs.join)(e,".agenttrail","session-upload")}function Tf(e,n){if(!Ha(n))throw new Error("unsafe session id");return(0,gs.join)(Ka(e),`${n}.json`)}function Of(e,n,t={}){let r=t.readFile??(s=>(0,Ke.readFileSync)(s,"utf8")),o={version:1,traces:{},updatedAt:""};try{let s=JSON.parse(r(Tf(e,n)));return s?.version!==1||typeof s.traces!="object"||s.traces===null?o:{version:1,traces:s.traces,updatedAt:s.updatedAt??""}}catch{return o}}function xf(e,n,t,r={}){let o=r.writeFile??((i,a,d)=>D(i,a,d!==void 0?{mode:d}:{}));(r.mkdir??((i,a)=>(0,Ke.mkdirSync)(i,{recursive:!0,mode:a})))(Ka(e),448),o(Tf(e,n),`${JSON.stringify(t)}
|
|
55
55
|
`,384)}var uE=720*60*60*1e3;function Af(e,n=Date.now()){let t=0;try{let r=Ka(e);for(let o of(0,Ke.readdirSync)(r).slice(0,2e3)){if(!o.endsWith(".json"))continue;let s=(0,gs.join)(r,o);try{n-(0,Ke.statSync)(s).mtimeMs>uE&&((0,Ke.unlinkSync)(s),t++)}catch{}}}catch{}return t}var wf=require("crypto"),vf=require("fs");var lE=64*1024*1024,pE=3*1024*1024,fE=2,Nt={traces:0,sent:0,spans:0,failedRequests:0,redactions:0};function gE(e,n){if(e===n)return!0;let t=n.endsWith("/")||n.endsWith("\\")?n:`${n}/`;return e.startsWith(t)||e.startsWith(t.replace(/\/$/,"\\"))}function mE(e){let n=new Map;for(let r of e.spans){let o=n.get(r.traceId);o?o.push(r):n.set(r.traceId,[r])}let t=[];for(let[r,o]of n){let s=JSON.stringify({resource:e.resource,scope:e.scope,spans:o});t.push({traceId:r,spans:o,hash:(0,wf.createHash)("sha256").update(s).digest("hex"),bytes:Buffer.byteLength(s)})}return t}function yE(e,n){let t=[],r=[],o=0;for(let s of e)r.length>0&&o+s.bytes>n&&(t.push(r),r=[],o=0),r.push(s),o+=s.bytes;return r.length>0&&t.push(r),t}async function Pf(e,n={}){try{if((n.statSize??(g=>(0,vf.statSync)(g).size))(e.transcriptPath)>lE)return{status:"skipped",reason:"transcript too large",...Nt}}catch{return{status:"skipped",reason:"transcript not found",...Nt}}let t;try{t=await Go(e.transcriptPath,e.sessionId,n.lineSource)}catch(m){return{status:"skipped",reason:m instanceof Bn?"transcript has no messages yet":"unreadable transcript",...Nt}}if(!t.cwd||!gE(t.cwd,e.projectRoot))return{status:"skipped",reason:"session recorded outside this project",...Nt};let r=e.skipIfVersion?.(t.version);if(r)return{status:"skipped",reason:r,...Nt};let o=Jo(t,{orgId:e.orgId,projectId:e.projectId,developerId:e.developerId,batchId:"",captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:Je(xe),provenance:"live"}),s=mE(o),i=Of(e.homeDir,e.sessionId,n.stateIO),a=s.filter(m=>i.traces[m.traceId]!==m.hash),d=o.redactions.total;if(a.length===0)return{status:"unchanged",...Nt,traces:s.length,redactions:d};let c={...i.traces},u=0,p=0,l=0,f;for(let m of yE(a,e.maxRequestBytes??pE)){let g=$e({...o,spans:m.flatMap(S=>S.spans)}),h=await pn(g,{endpoint:e.endpoint,token:e.token,maxRetries:fE},n.upload);if(f=h.httpStatus??f,h.status==="ok"){for(let S of m)c[S.traceId]=S.hash;u+=m.length,p+=m.reduce((S,b)=>S+b.spans.length,0)}else l++}if(u>0)try{xf(e.homeDir,e.sessionId,{version:1,traces:c,updatedAt:(n.now?.()??new Date).toISOString()},n.stateIO)}catch{}return{status:l>0?"failed":"uploaded",...l>0?{reason:"ingest rejected or unreachable"}:{},traces:s.length,sent:u,spans:p,failedRequests:l,httpStatus:f,redactions:d}}var Ff="AGENTTRAIL_SESSION_UPLOAD_WORKER",Mf="AGENTTRAIL_SESSION_UPLOAD_PAYLOAD",hE=12e4,SE=2e3,RE=512*1024;function Lf(e){return(0,hn.join)(e,".agenttrail","session-upload.log")}function EE(e,n){try{let t=Lf(e);(0,he.mkdirSync)((0,hn.dirname)(t),{recursive:!0,mode:448});try{(0,he.statSync)(t).size>RE&&(0,he.renameSync)(t,`${t}.1`)}catch{}(0,he.appendFileSync)(t,`${JSON.stringify({at:new Date().toISOString(),...n})}
|
|
56
56
|
`,{mode:384}),(0,he.chmodSync)(t,384)}catch{}}function Df(e){let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null)return;let t=n;if(!(t.hook_event_name!=="Stop"&&t.hook_event_name!=="SessionEnd")&&Ha(t.session_id)&&!(typeof t.transcript_path!="string"||!(0,hn.isAbsolute)(t.transcript_path))&&t.transcript_path.endsWith(".jsonl")&&!(typeof t.cwd!="string"||!(0,hn.isAbsolute)(t.cwd)))return{session_id:t.session_id,transcript_path:t.transcript_path,cwd:t.cwd,hook_event_name:t.hook_event_name}}function IE(e){let n=process.argv[1];if(!n)return;let t=(0,Nf.spawn)(process.execPath,[n,...process.argv.slice(2)],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,[Ff]:"1",[Mf]:e}});t.on("error",()=>{}),t.unref()}async function Uf(e){let n=e.log??(t=>EE(e.homeDir,t));try{if(e.env[Ff]==="1"){let o=Df(e.env[Mf]??"");if(!o)return n({outcome:"skipped",reason:"no payload"}),0;e.armDeadline?.(hE);let s=await bE(o,e);return n({event:o.hook_event_name,session:o.session_id,outcome:s.status,...s.reason?{reason:s.reason}:{},traces:s.traces,sent:s.sent,spans:s.spans,...s.httpStatus!==void 0?{httpStatus:s.httpStatus}:{},...s.project?{project:s.project}:{}}),0}let t=e.readStdin?await e.readStdin():"",r=Df(t);return r?((e.spawnWorker??IE)(JSON.stringify(r)),0):(n({outcome:"skipped",reason:"not a Stop or SessionEnd hook payload"}),0)}catch(t){return n({outcome:"failed",reason:`unexpected: ${t?.name??"error"}`}),0}}function yn(e){return{status:"skipped",reason:e,traces:0,sent:0,spans:0,failedRequests:0,redactions:0}}async function bE(e,n){try{let t;try{t=zt(e.cwd,{allowGlobal:!1})}catch{return yn("unreadable .agenttrail.json")}if(t.source!=="project"||!t.config||!t.configPath)return yn("no AgentTrail project here");let r=t.config,o=(0,hn.dirname)(t.configPath),s;try{s=Gt(n.endpointFlag?.trim()||n.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X)}catch{return yn("invalid ingest endpoint")}let i=ro(t,n.env),a,d;if(i)a=i,d=r.orgId;else{await kE(n,o,s);let l=L(n.homeDir,n.loginEnv?.credentialsIO);if(!l)return yn("not signed in");if(dn(l,n.loginEnv?.now))return yn("sign-in expired");if(l.org_id!==r.orgId)return yn("signed in to a different org");a=l.ingest_token,d=l.org_id}let c={env:n.env,...n.managedPaths?{managedPaths:n.managedPaths}:{}};if(ii(n.homeDir,d,c))return yn("the user settings export this session to AgentTrail");let u=pc(o);return e.hook_event_name==="Stop"?await(n.sleep??(l=>new Promise(f=>setTimeout(f,l))))(SE):Af(n.homeDir),{...await Pf({homeDir:n.homeDir,sessionId:e.session_id,transcriptPath:e.transcript_path,projectRoot:o,endpoint:s,token:a,orgId:d,projectId:r.projectId??ne(d,r.projectSlug),developerId:r.developerId,captureContent:ho(o,n.homeDir,r.captureContent,c),skipIfVersion:l=>u&&l!==null&&lc(l,tc)<0?"this Claude Code version exports the session from the project settings":void 0},{upload:n.upload,stateIO:n.stateIO}),project:o}}catch(t){return yn(`unexpected: ${t?.name??"error"}`)}}async function kE(e,n,t){try{let r={apiEndpoint:Qe(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In),ingestEndpoint:t,homeDir:e.homeDir,settingsRoot:n,host:(0,jf.hostname)(),log:()=>{},...e.loginEnv?{}:{device:ot(e.homeDir)},...e.loginEnv};await Eo(r)}catch{}}function $f(e,n){let t={},r=Lf(e);for(let o of[`${r}.1`,r]){let s;try{s=(0,he.readFileSync)(o,"utf8")}catch{continue}for(let i of s.split(`
|
|
57
|
-
`)){if(i.trim()==="")continue;let a;try{a=JSON.parse(i)}catch{continue}a.project!==n||typeof a.at!="string"||(t.lastRun={at:a.at,outcome:a.outcome,...a.reason?{reason:a.reason}:{}},(a.sent??0)>0&&(t.lastSent={at:a.at,sent:a.sent??0}))}}return t}var Bf=require("os");function Gf(e,n={}){let t,r;if(e.projectSlug)t=e.projectSlug,r="explicit";else{let b=Nn(e.cwd);if(!b)throw new Error("Could not derive a project slug (no git remote, no usable directory name). Pass --project <slug>.");t=b.slug,r=b.source}if(!e.global&&!e.team){let b=[Y,nn];for(let E of b){let k=io(e.cwd,E,n);if(k)throw new sn(ft(E,k))}for(let E of b){let k=Ue(e.cwd,E,n);if(!k.ok)throw new sn(ft(E,k))}}let o=ne(e.orgId,t),s=Le(e.orgId,pe),i=e.team?void 0:e.apiKey,a={orgId:e.orgId,projectSlug:t,projectId:o,agentId:s,...e.developerId?{developerId:e.developerId}:{},...i?{apiKey:i}:{},...e.captureContent!==void 0?{captureContent:e.captureContent}:{}},d=n.home??(0,Bf.homedir)(),c=e.global?d:e.cwd,u=e.global?(()=>{let b=uo(a,n);return{path:b.path,gitignoreModified:!1,mode:b.mode}})():co(e.cwd,a,n,{committable:e.team===!0}),p=e.endpoint??X,l=e.global?void 0:ut(e.cwd),f={orgId:e.orgId,projectId:o,agentId:s,developerId:e.developerId,apiKey:i,team:e.team,captureContent:e.captureContent,endpoint:e.endpoint,project:l},m=!e.global&&!e.team,g=null,h,S=null;if(m){h=Ne(c,go(f),n);let b=mo(c,n,{captureContent:e.captureContent});S={hooksChanged:Zt(c,{endpoint:e.endpoint},n).changed,removedKeys:b}}else{h=Ne(c,Dr(f),n);let b=td(f);Object.keys(b).length>0&&(g=tn(c,b,n))}return e.team&&kf(c,n),!e.global&&!e.team&&ao(e.cwd,n),{projectSlug:t,projectId:o,slugSource:r,agentId:s,agenttrailConfigPath:u.path,gitignoreModified:u.gitignoreModified,agenttrailConfigMode:u.mode,settings:h,localSettings:g,team:e.team??!1,global:e.global??!1,captureContent:e.captureContent??!1,resolvedEndpoint:p,sessionUpload:S}}var Va=require("fs");var _E=require("crypto"),Ve=require("fs"),Jn=require("path");var CE=require("crypto");var Hf=100,TE=2e3,OE=3e3;var xE={mkdir:(e,n)=>(0,Ve.mkdirSync)(e,{recursive:!0,mode:n}),writeFile:(e,n,t)=>(0,Ve.writeFileSync)(e,n,{mode:t}),readDir:e=>(0,Ve.readdirSync)(e),readFile:e=>(0,Ve.readFileSync)(e,"utf8"),remove:e=>(0,Ve.rmSync)(e,{force:!0})};function AE(e){return{...xE,...e??{}}}function wE(e){return(0,Jn.join)((0,Jn.dirname)(e),"pending-decisions")}function vE(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/policies/decisions`}async function Kf(e,n,t={}){let r=0;try{let o=AE(t.io),s=wE(e.snapshotPath),i;try{i=o.readDir(s).filter(d=>d.endsWith(".json")).sort()}catch{return 0}let a=Date.now()+OE;for(let d=0;d<i.length;d+=Hf){if(Date.now()>=a)return r;let c=[];for(let g of i.slice(d,d+Hf))try{c.push({file:g,item:JSON.parse(o.readFile((0,Jn.join)(s,g)))})}catch{o.remove((0,Jn.join)(s,g))}if(c.length===0)continue;let u=new AbortController,p=setTimeout(()=>u.abort(),Math.min(TE,Math.max(0,a-Date.now()))),l;try{l=await n(vE(e.apiBase),{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({decisions:c.map(g=>g.item)}),signal:u.signal})}finally{clearTimeout(p)}if(l.status!==200)return r;let f=await l.json(),m=new Set(f.results.map(g=>g.id));for(let g of c)m.has(g.item.id)&&(o.remove((0,Jn.join)(s,g.file)),r++)}return r}catch{return r}}function PE(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/machines/enforcement`}function DE(e){let n=(e.now??(()=>new Date))().toISOString(),t={machine_id:e.machineId,install_id:e.installId,enforced:e.enforced,reported_at:n};return!e.enforced&&e.reason!==void 0&&(t.reason=e.reason),e.installScope!==void 0&&(t.install_scope=e.installScope),e.installScope==="project"&&e.projectId!==void 0&&(t.project_id=e.projectId),t}async function Vf(e,n){let t=new AbortController,r=setTimeout(()=>t.abort(),2e3);try{return(await n(PE(e.apiBase),{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(DE(e)),signal:t.signal})).ok}catch{return!1}finally{clearTimeout(r)}}function Wf(e){if(!e.enforced)switch(e.reason){case"credential-rejected":return"credential-rejected";case"tier-disabled":return"tier-disabled";case"install-failed":return"install-failed";case"unreachable":return"unreachable";case"no-credential":return"disabled";default:return"disabled"}}function NE(e){if(e.changed){if(e.enforced)return"AgentTrail: real-time enforcement re-enabled \u2014 active from your next Claude Code session.";if(e.reason==="credential-rejected")return"AgentTrail: enforcement turned OFF \u2014 this device credential was rejected. Run `npx -y @agenttrail/cli@latest login --agent claude` to restore it. Capture is unaffected.";if(e.reason==="tier-disabled")return"AgentTrail: enforcement turned OFF \u2014 the policy endpoint refused the check. Capture is unaffected."}}function jE(e,n){let t=L(e.homeDir,e.credentialsIO);if(t?.ingest_token)return t.ingest_token;try{let o=K(G(e.settingsRoot),n.readFile??(s=>(0,Va.readFileSync)(s,"utf8")))?.env;if(typeof o=="object"&&o!==null){let s=o[re];if(typeof s=="string"&&s.length>0)return s}}catch{}}var FE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ME(e,n){try{let t=K(e,n)?.env?.[ve];if(typeof t!="string")return;for(let r of t.split(",")){let o=r.indexOf("=");if(o<0||r.slice(0,o).trim()!==Kt)continue;let s=decodeURIComponent(r.slice(o+1).trim());return FE.test(s)?s.toLowerCase():void 0}}catch{}}function Qf(e,n){try{let t=K(e,n)?.env?.[ve];return typeof t=="string"&&t.split(",").some(r=>r.startsWith(`${De}=`))}catch{return!1}}function LE(e,n,t=r=>(0,Va.readFileSync)(r,"utf8")){if(Pt(e,n))return{installScope:"global"};let r=ME(w(e),t);return r!==void 0?{installScope:"project",projectId:r}:!Qf(w(e),t)&&Qf(w(n),t)?{installScope:"global"}:{installScope:"project"}}async function Jf(e,n){try{let t=jE(e,n);if(!t)return{reported:!1};let r={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},o=await Cf({settingsRoot:e.settingsRoot,apiBase:e.apiEndpoint,token:t,deviceTokenPath:t.startsWith("dlv_ingest_"),home:e.homeDir},{fetchFn:n.fetchFn,settingsIO:r}),s=NE(o);s&&e.log?.(s);let i={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},a=await Vf({apiBase:e.apiEndpoint,token:t,machineId:Yr(e.homeDir,i),installId:Td(e.homeDir,e.settingsRoot,i),enforced:o.enforced,...Wf(o)?{reason:Wf(o)}:{},...
|
|
57
|
+
`)){if(i.trim()==="")continue;let a;try{a=JSON.parse(i)}catch{continue}a.project!==n||typeof a.at!="string"||(t.lastRun={at:a.at,outcome:a.outcome,...a.reason?{reason:a.reason}:{}},(a.sent??0)>0&&(t.lastSent={at:a.at,sent:a.sent??0}))}}return t}var Bf=require("os");function Gf(e,n={}){let t,r;if(e.projectSlug)t=e.projectSlug,r="explicit";else{let b=Nn(e.cwd);if(!b)throw new Error("Could not derive a project slug (no git remote, no usable directory name). Pass --project <slug>.");t=b.slug,r=b.source}if(!e.global&&!e.team){let b=[Y,nn];for(let E of b){let k=io(e.cwd,E,n);if(k)throw new sn(ft(E,k))}for(let E of b){let k=Ue(e.cwd,E,n);if(!k.ok)throw new sn(ft(E,k))}}let o=ne(e.orgId,t),s=Le(e.orgId,pe),i=e.team?void 0:e.apiKey,a={orgId:e.orgId,projectSlug:t,projectId:o,agentId:s,...e.developerId?{developerId:e.developerId}:{},...i?{apiKey:i}:{},...e.captureContent!==void 0?{captureContent:e.captureContent}:{}},d=n.home??(0,Bf.homedir)(),c=e.global?d:e.cwd,u=e.global?(()=>{let b=uo(a,n);return{path:b.path,gitignoreModified:!1,mode:b.mode}})():co(e.cwd,a,n,{committable:e.team===!0}),p=e.endpoint??X,l=e.global?void 0:ut(e.cwd),f={orgId:e.orgId,projectId:o,agentId:s,developerId:e.developerId,apiKey:i,team:e.team,captureContent:e.captureContent,endpoint:e.endpoint,project:l},m=!e.global&&!e.team,g=null,h,S=null;if(m){h=Ne(c,go(f),n);let b=mo(c,n,{captureContent:e.captureContent});S={hooksChanged:Zt(c,{endpoint:e.endpoint},n).changed,removedKeys:b}}else{h=Ne(c,Dr(f),n);let b=td(f);Object.keys(b).length>0&&(g=tn(c,b,n))}return e.team&&kf(c,n),!e.global&&!e.team&&ao(e.cwd,n),{projectSlug:t,projectId:o,slugSource:r,agentId:s,agenttrailConfigPath:u.path,gitignoreModified:u.gitignoreModified,agenttrailConfigMode:u.mode,settings:h,localSettings:g,team:e.team??!1,global:e.global??!1,captureContent:e.captureContent??!1,resolvedEndpoint:p,sessionUpload:S}}var Va=require("fs");var _E=require("crypto"),Ve=require("fs"),Jn=require("path");var CE=require("crypto");var Hf=100,TE=2e3,OE=3e3;var xE={mkdir:(e,n)=>(0,Ve.mkdirSync)(e,{recursive:!0,mode:n}),writeFile:(e,n,t)=>(0,Ve.writeFileSync)(e,n,{mode:t}),readDir:e=>(0,Ve.readdirSync)(e),readFile:e=>(0,Ve.readFileSync)(e,"utf8"),remove:e=>(0,Ve.rmSync)(e,{force:!0})};function AE(e){return{...xE,...e??{}}}function wE(e){return(0,Jn.join)((0,Jn.dirname)(e),"pending-decisions")}function vE(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/policies/decisions`}async function Kf(e,n,t={}){let r=0;try{let o=AE(t.io),s=wE(e.snapshotPath),i;try{i=o.readDir(s).filter(d=>d.endsWith(".json")).sort()}catch{return 0}let a=Date.now()+OE;for(let d=0;d<i.length;d+=Hf){if(Date.now()>=a)return r;let c=[];for(let g of i.slice(d,d+Hf))try{c.push({file:g,item:JSON.parse(o.readFile((0,Jn.join)(s,g)))})}catch{o.remove((0,Jn.join)(s,g))}if(c.length===0)continue;let u=new AbortController,p=setTimeout(()=>u.abort(),Math.min(TE,Math.max(0,a-Date.now()))),l;try{l=await n(vE(e.apiBase),{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({decisions:c.map(g=>g.item)}),signal:u.signal})}finally{clearTimeout(p)}if(l.status!==200)return r;let f=await l.json(),m=new Set(f.results.map(g=>g.id));for(let g of c)m.has(g.item.id)&&(o.remove((0,Jn.join)(s,g.file)),r++)}return r}catch{return r}}function PE(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/machines/enforcement`}function DE(e){let n=(e.now??(()=>new Date))().toISOString(),t={machine_id:e.machineId,install_id:e.installId,enforced:e.enforced,reported_at:n};return!e.enforced&&e.reason!==void 0&&(t.reason=e.reason),e.installScope!==void 0&&(t.install_scope=e.installScope),e.installScope==="project"&&e.projectId!==void 0&&(t.project_id=e.projectId),t}async function Vf(e,n){let t=new AbortController,r=setTimeout(()=>t.abort(),2e3);try{return(await n(PE(e.apiBase),{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(DE(e)),signal:t.signal})).ok}catch{return!1}finally{clearTimeout(r)}}function Wf(e){if(!e.enforced)switch(e.reason){case"credential-rejected":return"credential-rejected";case"tier-disabled":return"tier-disabled";case"install-failed":return"install-failed";case"unreachable":return"unreachable";case"no-credential":return"disabled";default:return"disabled"}}function NE(e){if(e.changed){if(e.enforced)return"AgentTrail: real-time enforcement re-enabled \u2014 active from your next Claude Code session.";if(e.reason==="credential-rejected")return"AgentTrail: enforcement turned OFF \u2014 this device credential was rejected. Run `npx -y @agenttrail/cli@latest login --agent claude` to restore it. Capture is unaffected.";if(e.reason==="tier-disabled")return"AgentTrail: enforcement turned OFF \u2014 the policy endpoint refused the check. Capture is unaffected."}}function jE(e,n){let t=L(e.homeDir,e.credentialsIO);if(t?.ingest_token)return t.ingest_token;try{let o=K(G(e.settingsRoot),n.readFile??(s=>(0,Va.readFileSync)(s,"utf8")))?.env;if(typeof o=="object"&&o!==null){let s=o[re];if(typeof s=="string"&&s.length>0)return s}}catch{}}var FE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ME(e,n){try{let t=K(e,n)?.env?.[ve];if(typeof t!="string")return;for(let r of t.split(",")){let o=r.indexOf("=");if(o<0||r.slice(0,o).trim()!==Kt)continue;let s=decodeURIComponent(r.slice(o+1).trim());return FE.test(s)?s.toLowerCase():void 0}}catch{}}function Qf(e,n){try{let t=K(e,n)?.env?.[ve];return typeof t=="string"&&t.split(",").some(r=>r.startsWith(`${De}=`))}catch{return!1}}function LE(e,n,t=r=>(0,Va.readFileSync)(r,"utf8")){if(Pt(e,n))return{installScope:"global"};let r=ME(w(e),t);return r!==void 0?{installScope:"project",projectId:r}:!Qf(w(e),t)&&Qf(w(n),t)?{installScope:"global"}:{installScope:"project"}}function UE(e,n,t){return e==="global"?t:n}async function Jf(e,n){try{let t=jE(e,n);if(!t)return{reported:!1};let r={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},o=await Cf({settingsRoot:e.settingsRoot,apiBase:e.apiEndpoint,token:t,deviceTokenPath:t.startsWith("dlv_ingest_"),home:e.homeDir},{fetchFn:n.fetchFn,settingsIO:r}),s=NE(o);s&&e.log?.(s);let i={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},a=LE(e.settingsRoot,e.homeDir,n.readFile),d=await Vf({apiBase:e.apiEndpoint,token:t,machineId:Yr(e.homeDir,i),installId:Td(e.homeDir,UE(a.installScope,e.settingsRoot,e.homeDir),i),enforced:o.enforced,...Wf(o)?{reason:Wf(o)}:{},...a},n.fetchFn),c=await Kf({apiBase:e.apiEndpoint,token:t,snapshotPath:n.snapshotPath||process.env[zd]?.trim()||so(e.homeDir)},n.fetchFn,n.pendingDecisionsIO?{io:n.pendingDecisionsIO}:{});return{healed:o,reported:d,flushed:c}}catch{return{reported:!1}}}function Yf(e,{timeoutMs:n=250,maxBytes:t=1048576}={}){return e.isTTY?Promise.resolve(""):new Promise(r=>{let o=[],s=0,i=c=>{let u=typeof c=="string"?Buffer.from(c):c,p=t-s;o.push(u.length>p?u.subarray(0,p):u),s+=Math.min(u.length,p),s>=t&&a()},a=()=>{clearTimeout(d),e.off("data",i),e.off("end",a),e.pause(),r(Buffer.concat(o).toString("utf8"))},d=setTimeout(a,n);e.on("data",i),e.on("end",a),e.on("error",a)})}var rg="NOTE: no git remote found \u2014 this project's identity is derived from its directory name and may be unstable across machines (the same repo at a different path becomes a different project). Add an `origin` git remote for a stable identity.",_r=`agenttrail \u2014 connect an AI coding agent to AgentTrail
|
|
58
58
|
|
|
59
59
|
Usage:
|
|
60
60
|
agenttrail setup --agent <claude|cursor|codex> [options]
|
|
@@ -176,7 +176,7 @@ Backfill with --agent cursor (import this project's Cursor sessions):
|
|
|
176
176
|
cost, because a Cursor session file holds none; and its times are approximate and
|
|
177
177
|
marked as such. Conversations already captured live are skipped. Set the project
|
|
178
178
|
up first, in the project: \`npx -y @agenttrail/cli@latest setup --agent cursor\`.
|
|
179
|
-
Full detail: docs/integrations/cursor.md`;function $E(e){return(0,tg.parseArgs)({args:[...e],allowPositionals:!0,options:{org:{type:"string"},project:{type:"string"},developer:{type:"string"},key:{type:"string"},endpoint:{type:"string"},"api-endpoint":{type:"string"},refresh:{type:"boolean",default:!1},team:{type:"boolean",default:!1},global:{type:"boolean",default:!1},"capture-content":{type:"boolean",default:!1},"no-capture-content":{type:"boolean",default:!1},scan:{type:"boolean",default:!1},import:{type:"boolean",default:!1},status:{type:"boolean",default:!1},resume:{type:"boolean",default:!1},reimport:{type:"boolean",default:!1},since:{type:"string"},"dry-run":{type:"boolean",default:!1},content:{type:"boolean",default:!1},concurrency:{type:"string"},help:{type:"boolean",short:"h",default:!1},agent:{type:"string"},unregister:{type:"boolean",default:!1},yes:{type:"boolean",short:"y",default:!1}}})}function BE(e){let n=e.trim().match(/^(\d+)\s*([smhd])?$/i);if(!n)return null;let t=Number(n[1]),r=(n[2]??"").toLowerCase();return t*(r==="d"?864e5:r==="h"?36e5:r==="m"?6e4:r==="s"?1e3:1)}async function Wa(e,n){if(e.prompt)return(await e.prompt(n)).trim();if(!process.stdin.isTTY)return;let t=(0,ng.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(n)).trim()}finally{t.close()}}function og(e){return typeof e.isInteractive=="boolean"?e.isInteractive:!!process.stdin.isTTY}async function GE(e,n){let t=!!n.team,r=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim();if(!t&&!r)return HE(e,n);let o=!!n.global,s=e.persistIO?.home??(0,U.homedir)(),i=dg(n,o?s:e.cwd,s,e.persistIO?.readFile),a=i.on,d=n.org?.trim()||e.env.AGENTTRAIL_ORG_ID?.trim();if(d||(d=await Wa(e,"AgentTrail org id (UUID): ")),!d)return e.error("error: --org <uuid> is required (or set AGENTTRAIL_ORG_ID)."),1;let c;if(t)(n.key||e.env.AGENTTRAIL_API_KEY)&&e.log("note: --team never writes an API key. Each developer supplies it at runtime via AGENTTRAIL_API_KEY / OTEL_EXPORTER_OTLP_HEADERS.");else if(c=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim(),c||(c=await Wa(e,"AgentTrail API key (dlv_live_...): ")),!c)return e.error("error: an API key is required in single-dev mode. Pass --key, set AGENTTRAIL_API_KEY, or use --team."),1;let u=!o&&!t?cg(e,e.cwd):void 0;if(ug(e,i,u),o&&e.error("WARNING: --global configures EVERY Claude Code session on this machine \u2014 including personal and side projects \u2014 to export to AgentTrail. This is a privacy / cost / GDPR consideration. Prefer per-project setup unless you intend machine-wide capture."),!o){let g=(0,Se.basename)(Dn(e.cwd));g&&we(g).length>En&&e.error(`WARNING: project "${g}" exceeds the ${En}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`)}let p=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim(),l;if(p)try{l=Gt(p)}catch(g){return e.error(`error: ${g.message}`),1}let f;try{f=Gf({cwd:e.cwd,orgId:d,apiKey:c,projectSlug:n.project?.trim()||void 0,developerId:n.developer?.trim()||void 0,team:t,global:o,captureContent:a,endpoint:l},e.persistIO??{})}catch(g){if(!(g instanceof sn))throw g;return e.error(`error: setup refused: ${g.message}${ag(e.cwd)}`),1}let m=o?e.persistIO?.home??(0,U.homedir)():e.cwd;if(Fr(m,e.persistIO??{}),e.fetchFn&&c){let g=n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In;await ig(e,{settingsRoot:m,apiBase:g,token:c,deviceTokenPath:!1,home:e.persistIO?.home??(0,U.homedir)(),orgId:d})}return f.slugSource==="directory"&&e.error(rg),e.log(`Project: ${f.projectSlug} \u2192 project.id ${f.projectId}`),e.log(`Endpoint: ${f.resolvedEndpoint}`),e.log(`Wrote ${f.agenttrailConfigPath} (mode 0${f.agenttrailConfigMode.toString(8)})`+(f.gitignoreModified?" (+ .gitignore)":"")),e.log(`Wrote ${f.settings.path} (${f.settings.merged?"merged":"created"})`),f.localSettings&&e.log(`Wrote ${f.localSettings.path} (${f.localSettings.merged?"merged":"created"}, mode 0600, ${o?"":"kept out of git \u2014 "}holds the API key; do NOT commit)`),f.sessionUpload&&sg(e,f.sessionUpload.removedKeys),t&&e.log('Team mode: config is key-free and safe to commit. Each developer must export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer $AGENTTRAIL_API_KEY".'),e.log(Ja(a&&u===void 0,u)),0}async function HE(e,n){let t;try{t=jt(e,n)}catch(S){return e.error(`error: ${S.message}`),1}let r=!!n.global,o=t.settingsRoot,s=r?e.persistIO?.home??(0,U.homedir)():o,i=dg(n,s,e.persistIO?.home??(0,U.homedir)(),e.persistIO?.readFile),a=i.on,d=r?void 0:cg(e,o);ug(e,i,d);let c=n.project?.trim(),u,p;if(c)u=c,p="explicit";else{let S=Nn(o);u=S?.slug??"default",p=S?.source??"directory"}if(t={...t,projectSlug:u,captureContent:a,global:r,settingsRoot:s,setup:!0},!r){let S=Ue(o,nn,e.persistIO??{});if(!S.ok)return e.error(`error: setup refused: ${ft(nn,S)}${ag(o)}`),1}let l=L(t.homeDir,t.credentialsIO);try{if(l&&!dn(l,t.now)){bc(t,l),e.log(`Using existing AgentTrail credentials (org ${l.org_id}).`),e.log(rt);let S=t.device?.confirmedName("claude");S!==void 0&&e.log(`Device name: ${S}`)}else{if(!og(e))return e.error("error: device login needs a browser to authorize. Run `npx -y @agenttrail/cli@latest setup --agent claude` in an interactive terminal, or pass --key / use --team for headless/CI."),1;l=await fi(t),await sI(e,n,t),l=L(t.homeDir,t.credentialsIO)??l}}catch(S){return e.error(`error: ${S.message}`),1}let f={orgId:l.org_id,projectSlug:u,projectId:ne(l.org_id,u),agentId:Le(l.org_id,pe),captureContent:a},m=r?void 0:Ue(t.settingsRoot,Y,e.persistIO??{}),g=m!==void 0&&!m.ok&&m.tracked,h=r?uo(f,e.persistIO??{}):g?void 0:co(t.settingsRoot,f,e.persistIO??{});return r||ao(o,e.persistIO??{}),p==="directory"&&e.error(rg),e.log(`Project: ${u} \u2192 project.id ${f.projectId}`),e.log(`API endpoint (device-auth): ${t.apiEndpoint}`),e.log(`Endpoint: ${t.ingestEndpoint}`),e.log(h?`Wrote ${h.path} (mode 0${h.mode.toString(8)}, device login \u2014 no API key stored)`:`Left ${Y} as it is: this repo tracks it.`),e.log(Ja(a&&d===void 0,d)),r||sg(e,[]),e.fetchFn&&await ig(e,{settingsRoot:t.settingsRoot,apiBase:t.apiEndpoint,token:l.ingest_token,deviceTokenPath:!0,home:e.persistIO?.home??(0,U.homedir)(),orgId:l.org_id}),e.log("Device login active \u2014 telemetry capture is ON. `status` reports capture ACTIVE + the enforcement state."),0}function sg(e,n){e.log("Session data: uploaded after each turn by the Stop and SessionEnd hooks in .claude/settings.json (Claude Code ignores OpenTelemetry exporter settings in project files)."),n.length>0&&e.log(`Removed the OpenTelemetry exporter settings an earlier setup wrote to this project, which Claude Code ignores there: ${n.join(", ")}.`)}async function ig(e,n){if(e.fetchFn)try{let t=await Ga({...n,migrate:!0},{fetchFn:e.fetchFn,runner:e.pluginRunner,settingsIO:e.persistIO,snapshotIO:e.persistIO});e.log(`Real-time enforcement: ${t.enforced?"ON":"OFF"} \u2014 ${t.message}`),t.pluginNote&&e.log(t.pluginNote),t.pluginWarning&&e.error(`warning: ${t.pluginWarning}`),t.migrated&&e.log("Moved the enforcement settings an older setup left in .claude/settings.json to .claude/settings.local.json. If .claude/settings.json is committed, commit this change so teammates stop inheriting them.")}catch(t){e.error(`warning: enforcement wiring failed: ${t.message} (capture is active).`)}}function KE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd;try{let o=K(w(t),d=>(0,Yn.readFileSync)(d,"utf8")),s=ic(o);if(s!==void 0)return{endpoint:ac(s)??X,onDisk:!0};let a=o?.env?.[en];if(typeof a=="string"&&a.length>0)return{endpoint:a,onDisk:!0}}catch{}return{endpoint:e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X,onDisk:!1}}function VE(e){let n;try{n=zt(e.cwd)}catch(a){return e.error(`error: ${a.message}`),1}if(!n.config||n.source===null)return e.log("AgentTrail exporter: INACTIVE (no .agenttrail.json in this project; no global config)."),n.gitRoot&&e.log(`Git root: ${n.gitRoot}`),0;let t=ro(n,e.env),r=WE(e,n);e.log(r.sends?"AgentTrail exporter: ACTIVE":"AgentTrail exporter: CONFIGURED, but no session data is sent (see Session data below)"),e.log(`Config source: ${n.source} (${n.configPath})`),e.log(`Org: ${n.config.orgId}`),e.log(`Project: ${n.config.projectSlug} \u2192 ${n.config.projectId??"(unresolved)"}`);let o=KE(e,n);e.log(`Endpoint: ${o.endpoint}${o.onDisk?"":" (no on-disk endpoint found; env-or-default)"}`);try{let a=Qe(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In);e.log(`API endpoint (device-auth): ${a}`)}catch{}e.log(`API key: ${t?"present":"MISSING (set AGENTTRAIL_API_KEY, or use device login)"}`);let s=zE(e,n);e.log(Ja(s===void 0&&qE(e,n),s));for(let a of r.lines)e.log(a);e.log(`Real-time enforcement: ${JE(e,n)}`),e.log(QE(e,n));let i=pi(e.persistIO?.home??(0,U.homedir)());return i&&e.log(i),0}function WE(e,n){if(n.source!=="project"||!n.configPath||!n.config)return{sends:!0,lines:[]};let t=(0,Se.dirname)(n.configPath),r=e.persistIO?.home??(0,U.homedir)(),o=ai(t,r,n.config.orgId,Or(e)),s=[];if(o.path==="otel")s.push("Session data: OpenTelemetry export (from your user settings, ~/.claude/settings.json).");else if(o.path==="upload"){s.push("Session data: session upload after each turn (Stop and SessionEnd hooks).");let i=$f(r,t);s.push(i.lastSent?`Last session upload: ${i.lastSent.at} (${i.lastSent.sent} turn(s) sent).`:"Last session upload: none yet (the first finishes after your next turn in Claude Code)."),i.lastRun&&i.lastRun.outcome==="failed"&&s.push(`WARNING: the latest upload attempt failed at ${i.lastRun.at}${i.lastRun.reason?` (${i.lastRun.reason})`:""}. Details: ~/.agenttrail/session-upload.log.`)}else s.push(`Session data: NOT SENT \u2014 no session upload hooks in this project. ${Tr}.`);return o.ignoredProjectKeys.length>0&&o.path!=="otel"&&s.push(`WARNING: OpenTelemetry exporter settings sit only in this project's .claude files, where Claude Code ignores them: ${o.ignoredProjectKeys.join(", ")}. ${Tr} to remove them.`),{sends:o.path!=="none",lines:s}}function QE(e,n){let t=e.persistIO?.home??(0,U.homedir)(),r=n.source==="global"||!n.configPath?t:(0,Se.dirname)(n.configPath),o=Tn(t).device_name??"Unnamed device",s=Od(t),i=xd(t,r),a=[s?`machine ${s.slice(0,8)}`:void 0,i?`install ${i.slice(0,8)}`:void 0].filter(d=>d!==void 0);return`Device: ${o}${a.length>0?` (${a.join(", ")})`:""}`}function Qa(e){try{let t=JSON.parse((0,Yn.readFileSync)(e,"utf8"))?.env;return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function JE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd,r=Qa(G(t)),o=Qa(w(t)),s=typeof r[re]=="string"&&r[re]!=="";return r[te]==="1"?s?"ON":`ON but no token, so every tool call is denied. ${Tr}`:o[te]!=="1"?"OFF":n.source==="global"?"ON":s?`ON (set in .claude/settings.json by an older setup). ${Tr} to move it.`:`ON in .claude/settings.json but no token on this machine, so every tool call is denied. Remove AGENTTRAIL_PEP_ENFORCE from .claude/settings.json, or ${Tr.toLowerCase()}.`}var Tr="Run `npx -y @agenttrail/cli@latest setup --agent claude` in this repo";function ag(e){return Qa(w(e))[te]==="1"?" This repo's .claude/settings.json also sets AGENTTRAIL_PEP_ENFORCE (from an older setup); remove it, or teammates without a token have every tool call denied.":""}function Ja(e,n){return!e&&n!==void 0?`Content capture: OFF (metadata and tokens only): ${n} switches it off, and setup cannot override that. Change it there to turn capture on.`:e?"Content capture: ON (prompts, commands, file paths and tool output; secrets and PII are scrubbed at ingest, pattern-based and not exhaustive). Turn it off with `setup --agent claude --no-capture-content`.":"Content capture: OFF (metadata and tokens only). Turn it on with `setup --agent claude --capture-content`."}function zf(e,n){let t;try{t=JSON.parse(n(e))?.env}catch{return"absent"}let r=Pe.filter(o=>t?.[o]!==void 0);return r.length===0?"absent":r.every(o=>t?.[o]==="1")?"on":"off"}function dg(e,n,t,r=o=>(0,Yn.readFileSync)(o,"utf8")){if(e["no-capture-content"])return{on:!1};if(e["capture-content"])return{on:!0};let o=w(n),s=zf(o,r);if(s==="off")return{on:!1,keptOptOut:{from:"install",path:o}};if(s==="absent"&&n!==t){if(YE(n,r)===!0)return{on:!0};let a=w(t);if(zf(a,r)==="off")return{on:!1,keptOptOut:{from:"user",path:a}}}return{on:!0}}function YE(e,n){try{let t=JSON.parse(n((0,Se.join)(e,Y)));return typeof t?.captureContent=="boolean"?t.captureContent:void 0}catch{return}}function cg(e,n){return yo(n,e.persistIO?.home??(0,U.homedir)(),Or(e))}function Or(e){return{env:e.env,...e.persistIO?.readFile?{read:e.persistIO.readFile}:{},...e.managedPaths?{managedPaths:e.managedPaths}:{}}}function ug(e,n,t){if(t!==void 0){e.log(`note: content capture stays OFF for this project because ${t} switches it off. Change it there to turn capture on; setup cannot override it.`);return}if(n.on){e.error(Mr("claude"));return}let r=n.keptOptOut;r!==void 0&&e.log(r.from==="user"?`note: content capture stays OFF because of the user-level opt-out in ${r.path}. Pass --capture-content to turn it on for this project.`:`note: content capture stays OFF because ${r.path} already turns it off (a content flag is not "1"). Pass --capture-content to turn it on.`)}function qf(e){let n;try{n=JSON.parse((0,Yn.readFileSync)(w(e),"utf8"))?.env}catch{return"absent"}return Pe.filter(r=>n?.[r]!==void 0).length===0?"absent":Pe.every(r=>n?.[r]==="1")?"all-on":"defines-some"}function zE(e,n){if(n.source!=="project"||!n.config||!n.configPath)return;let t=(0,Se.dirname)(n.configPath);return yo(t,e.persistIO?.home??(0,U.homedir)(),Or(e))}function qE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd;if(n.source==="project"&&n.config){let s=e.persistIO?.home??(0,U.homedir)();if(ai(t,s,n.config.orgId,Or(e)).path==="upload")return ho(t,s,n.config.captureContent,Or(e))}let r=qf(t);if(r==="all-on")return!0;if(r==="defines-some")return!1;let o=e.persistIO?.home??(0,U.homedir)();return o!==t&&qf(o)==="all-on"}function XE(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=(0,eg.spawn)(n,[e],{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}function jt(e,n){let t=Qe(n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In),r=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X;return{...{apiEndpoint:t,ingestEndpoint:r,homeDir:(0,U.homedir)(),settingsRoot:e.cwd,host:(0,U.hostname)(),openBrowser:XE,...e.loginEnv?{}:{device:ot((0,U.homedir)())},log:e.log},...e.loginEnv}}async function ZE(e){if(!e.readStdin)return!1;let n=await e.readStdin();if(n.trim()==="")return!1;try{return Xi(JSON.parse(n))}catch{return!1}}async function eI(e,n){if(n.refresh&&await ZE(e))return 0;let t;try{return t=jt(e,n),n.refresh?await Eo(t):await fi(t),0}catch(r){return e.error(`error: ${r.message}`),1}finally{if(n.refresh&&t){fc(e.env.CLAUDE_PROJECT_DIR?.trim()||t.settingsRoot,t.homeDir,t.settingsIO??e.persistIO??{},{git:t.git??e.persistIO?.git});let r=t.fetchFn;await Jf(t,{fetchFn:r?(s,i)=>r(String(s),i):fetch}).catch(()=>{})}}}async function nI(e,n){try{let t=jt(e,n);return await Cc(t),e.pluginRunner&&_f({settingsRoot:t.settingsRoot,runner:e.pluginRunner},e.persistIO??{}).pluginRemoved&&e.log("Removed the AgentTrail enforcement plugin."),0}catch(t){return e.error(`error: ${t.message}`),1}}function tI(e,n){let t="Warning: couldn't check which sessions AgentTrail already has, so ";return e?`${t}this preview counted ALL sessions as importable. Nothing was uploaded, so nothing was duplicated \u2014 but a real import while the check is failing may create duplicates beside live or earlier-imported data.`:n>0?`${t}ALL were imported \u2014 this run may have created duplicates beside live or earlier-imported data.`:`${t}none were skipped as already-recorded. Nothing was imported, so nothing was duplicated \u2014 re-run when AgentTrail is reachable.`}async function rI(e,n){let t=[n.scan,n.import,n.status,n.resume].filter(Boolean).length;if(t===0)return e.error("error: backfill needs one of --scan | --import | --status | --resume."),1;if(t>1)return e.error("error: pass exactly one of --scan | --import | --status | --resume."),1;let r=e.persistIO?.home??(0,U.homedir)(),o=Dn(e.cwd),s=_=>e.log(JSON.stringify(_)),i={...e.backfillDeps,emit:e.backfillDeps?.emit??s};if(n.scan)return await Wl({projectRoot:o},i),0;if(n.status)return Ql({homeDir:r},i),e.log("note: this import record is machine-wide; backfill imports themselves are scoped to the project you run them in."),0;let a=!!n.resume,d=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X,c=L(r,e.loginEnv?.credentialsIO),u=!!n["dry-run"],p=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim(),l=p||c?.ingest_token;if(!l)return e.error("error: no credentials \u2014 run `npx -y @agenttrail/cli@latest setup --agent claude` / `npx -y @agenttrail/cli@latest login --agent claude` first, or pass --key / set AGENTTRAIL_API_KEY."),1;let f,m,g=!1;if(p)e.error("note: running under an API key, so we can't check your plan's retention window here \u2014 importing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0;else if(c&&u)c.org_tier?(m=c.org_tier,f=Date.now()-zn[c.org_tier]*24*60*60*1e3):(e.error("note: couldn't determine your plan's retention window (no tier on record) \u2014 listing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0);else if(c){let _;try{_=jt(e,n)}catch(T){return e.error(`error: ${T.message}`),1}let C=await kc(_);C.ingestToken&&(l=C.ingestToken),C.tier?(m=C.tier,f=Date.now()-zn[C.tier]*24*60*60*1e3):(e.error("note: couldn't determine your plan's retention window (tier lookup failed) \u2014 importing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0)}let h=n.org?.trim()||e.env.AGENTTRAIL_ORG_ID?.trim()||c?.org_id,S;try{let _=zt(e.cwd);h??=_.config?.orgId,S=_.config?.developerId}catch{}if(!h)return e.error("error: could not resolve org id (use device login, --org, or a .agenttrail.json)."),1;let b;if(n.since){let _=BE(n.since);if(_===null)return e.error(`error: invalid --since '${n.since}' (e.g. 7d, 24h, 30m).`),1;b=Date.now()-_}let E;if(n.concurrency){let _=Number(n.concurrency);if(!Number.isInteger(_)||_<1)return e.error(`error: invalid --concurrency '${n.concurrency}' (positive integer).`),1;E=_}let k=!!n.content;k&&e.error("note: --content uploads prompt/tool content. Shape-matching secrets (AWS keys, connection strings, JWTs, .env-style KEY=value with a secret-ish key name, \u2026) and the output of enumerated secret-manager fetches (`op read`, `op item get`, aws/gcloud/vault/az) are EDGE-scrubbed on this machine before upload; a shapeless secret fetched by any other command (a wrapper script, `kubectl get secret`) \u2014 or by an enumerated command nested inside a command substitution, e.g. `export FOO=$(op read \u2026)` \u2014 is NOT edge-scrubbed. AgentTrail applies your org's scrubbing config again server-side on arrival, redacting the same shapes a second time unless your org has turned scrubbing off. Use `--dry-run --content` to preview exactly what would be redacted before anything leaves the machine.");let I=await Jl({homeDir:r,endpoint:d,token:l,orgId:h,developerId:S,captureContent:k,concurrency:E,dryRun:u,reimport:!!n.reimport,projectRoot:o,sinceMs:b,retentionCutoffMs:f},a,i),y=ct(o)??(0,Se.basename)(o);if(e.log(`Backfill ${u?"(dry-run) ":""}complete: ${I.imported} imported from this project (${y}), ${I.skipped} skipped, ${I.failed} failed, ${I.quarantined} quarantined (of ${I.total}).`),I.dedupSkipped>0&&e.log(`Skipped ${I.dedupSkipped} session(s) already recorded (live capture or an earlier import).`),I.dedupOk||e.log(tI(u,I.imported)),I.excludedOtherProject>0&&e.log(`${I.excludedOtherProject} session(s) on this machine belong to other projects and were not included (backfill imports only the project you run it in).`),I.excludedUnknownCwd>0&&e.log(`${I.excludedUnknownCwd} session(s) were excluded because their working directory couldn't be determined from the transcript (a parse limitation on our side).`),e.log("Only this project is imported \u2014 personal and side projects on this machine are never included unless you cd into them and re-run `backfill --import`."),e.log(""),I.retentionSkipped>0&&m){let _=zn[m],C=`${I.retentionSkipped} of ${I.total} session(s) predate your ${m} plan's ${_}-day retention window and weren't stored`,T=Ss(m);T?e.log(`${C} \u2014 upgrade to ${T} to keep ${zn[T]} days, then re-run to import anything inside the wider window.`):e.log(`${C}.`)}g&&e.log("We couldn't check your plan's retention window on this login, so sessions older than it will be removed server-side."),e.log(`Estimated ~${I.estimatedActions} action(s) in this import (a size estimate, not a governed-action count; first import is free). Preview a run with --dry-run before importing; --since limits it to recently-active sessions.`);let R=I.redactions;if(R.total>0){let _=Object.entries(R.byType).sort((C,T)=>T[1]-C[1]||C[0].localeCompare(T[0])).map(([C,T])=>`${C}\xD7${T}`).join(", ");e.log(`Edge-scrubbed ${R.total} secret(s) across the run before upload (by type: ${_}).`)}return I.failed>0?1:0}var Xf=64;function Zf(e){return`npx -y @agenttrail/cli@latest device rename --agent ${e} "<name>"`}function lg(e,n,t){switch(t.kind){case"renamed":return e.log(`Device name: ${t.name}`),0;case"rejected":return e.error(`That name was not accepted; your device keeps its current name${t.name?` (${t.name})`:""}. Your sign-in is unchanged.`),1;case"unsupported":return e.error("The AgentTrail server did not confirm a device name (it may not support device names yet). Your sign-in is unchanged."),1;case"not-logged-in":return e.error(`error: not logged in; run \`${V(n,"login")}\` first.`),1}}function pg(e){let n=e.trim();return n===""?{error:"a device name cannot be empty."}:[...n].length>Xf?{error:`a device name is at most ${Xf} characters.`}:{name:n}}async function fg(e,n,t,r){let o=`usage: agenttrail device rename --agent ${n} "<name>"`;if(t[1]!=="rename")return e.error(`error: ${o}`),1;let s=pg(t.slice(2).join(" "));if("error"in s)return e.error(`error: ${s.error} ${o}`),1;try{return lg(e,n,await r(s.name))}catch(i){return e.error(`error: ${i.message}`),1}}function oI(e){let n=e.CI?.trim().toLowerCase();return n!==void 0&&n!==""&&n!=="0"&&n!=="false"}async function sI(e,n,t){let r=t.device?.confirmedName("claude");if(r===void 0)return;if(!og(e)||n.yes||oI(e.env)){e.log(`Device name: ${r} (rename it with \`${Zf("claude")}\`).`);return}let o=await Wa(e,`Device name [${r}]: `);if(o===void 0||o.trim()===""||o.trim()===r){e.log(`Device name: ${r}`);return}let s=pg(o);if("error"in s){e.error(`${s.error[0]?.toUpperCase()}${s.error.slice(1)} Keeping "${r}".`);return}try{lg(e,"claude",await gi(t,s.name))}catch(i){e.error(`warning: could not rename the device (${i.message}); it keeps "${r}". Rename it later with \`${Zf("claude")}\`.`)}}function ms(e,n){let t=jt(e,n);return{apiEndpoint:t.apiEndpoint,ingestEndpoint:t.ingestEndpoint,homeDir:t.homeDir,host:t.host,fetchFn:t.fetchFn,sleepFn:t.sleepFn,now:t.now,openBrowser:t.openBrowser,credentialsIO:t.credentialsIO,lockIO:t.lockIO,device:t.device,log:t.log}}async function iI(e,n){try{let t=ms(e,n);return n.refresh?await Sd(t):await Wr(t),0}catch(t){return e.error(`error: ${t.message}`),1}}function aI(e,n,t,r){let o={io:e,flags:t,sessionEnv:()=>ms(e,t)};switch(n){case"login":return iI(e,t);case"logout":return af(o);case"status":case"doctor":return uf(o);case"setup":return tf(o);case"backfill":return Ll(o);case"capture":return gg(e);case"device":return fg(e,"cursor",r,s=>hd(ms(e,t),s))}}function dI(e,n,t){let r={io:e,flags:t,sessionEnv:()=>ms(e,t)};switch(n){case"login":return Za(r);case"logout":return zl(r);case"status":case"doctor":return ql(r,n);case"setup":return Yl(r);case"backfill":return _c(r);case"capture":return gg(e);case"device":return Re(r,"device")}}function gg(e){return e.error("error: capture is the Claude Code session upload hook; use --agent claude."),1}function cI(e,n,t,r){switch(n){case"setup":return GE(e,t);case"login":return eI(e,t);case"logout":return nI(e,t);case"status":case"doctor":return VE(e);case"backfill":return rI(e,t);case"capture":return Uf({env:e.env,homeDir:e.persistIO?.home??(0,U.homedir)(),endpointFlag:t.endpoint,readStdin:e.readStdin,...e.managedPaths?{managedPaths:e.managedPaths}:{},...e.captureOverrides});case"device":return fg(e,"claude",r,o=>gi(jt(e,t),o))}}var uI=["setup","login","logout","status","doctor","backfill","capture","device"];function lI(e){return uI.includes(e)}function pI(e){for(let n of e){if(n==="--")return!1;if(n==="-h"||n==="--help")return!0}return!1}function fI(e){let n=ad(e.argv);if(n.kind==="chosen")return n.agent;e.error(`error: ${id}`),n.kind==="invalid"&&e.error(n.reason)}async function mg(e){if(pI(e.argv))return e.log(_r),0;if(e.argv.length===0)return e.log(_r),1;let n=fI(e);if(n===void 0)return 1;let t;try{t=$E(e.argv)}catch(i){return e.error(`error: ${i.message}`),e.error(_r),1}let{values:r,positionals:o}=t;if(o.length===0)return e.log(_r),1;let s=o[0];if(!lI(s))return e.error(`error: unknown command '${s}'.`),e.error(_r),1;if(s==="setup"&&r["capture-content"]&&r["no-capture-content"])return e.error("error: pass --capture-content or --no-capture-content, not both."),1;switch(n){case"claude":return cI(e,s,r,o);case"cursor":return aI(e,s,r,o);case"codex":return dI(e,s,r)}return Vt(n)}function yg(e,n=Yn.realpathSync){if(!e)return!1;let t=e;try{t=n(e)}catch{}return/[\\/]cli[\\/]index\.(c?js|ts)$/.test(t)}yg(process.argv[1])&&mg({cwd:process.cwd(),env:process.env,argv:process.argv.slice(2),isInteractive:!!process.stdin.isTTY,fetchFn:fetch,pluginRunner:ls,readStdin:()=>Yf(process.stdin),captureOverrides:{armDeadline:e=>{setTimeout(()=>process.exit(0),e).unref()}},log:e=>process.stdout.write(`${e}
|
|
179
|
+
Full detail: docs/integrations/cursor.md`;function BE(e){return(0,tg.parseArgs)({args:[...e],allowPositionals:!0,options:{org:{type:"string"},project:{type:"string"},developer:{type:"string"},key:{type:"string"},endpoint:{type:"string"},"api-endpoint":{type:"string"},refresh:{type:"boolean",default:!1},team:{type:"boolean",default:!1},global:{type:"boolean",default:!1},"capture-content":{type:"boolean",default:!1},"no-capture-content":{type:"boolean",default:!1},scan:{type:"boolean",default:!1},import:{type:"boolean",default:!1},status:{type:"boolean",default:!1},resume:{type:"boolean",default:!1},reimport:{type:"boolean",default:!1},since:{type:"string"},"dry-run":{type:"boolean",default:!1},content:{type:"boolean",default:!1},concurrency:{type:"string"},help:{type:"boolean",short:"h",default:!1},agent:{type:"string"},unregister:{type:"boolean",default:!1},yes:{type:"boolean",short:"y",default:!1}}})}function GE(e){let n=e.trim().match(/^(\d+)\s*([smhd])?$/i);if(!n)return null;let t=Number(n[1]),r=(n[2]??"").toLowerCase();return t*(r==="d"?864e5:r==="h"?36e5:r==="m"?6e4:r==="s"?1e3:1)}async function Wa(e,n){if(e.prompt)return(await e.prompt(n)).trim();if(!process.stdin.isTTY)return;let t=(0,ng.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(n)).trim()}finally{t.close()}}function og(e){return typeof e.isInteractive=="boolean"?e.isInteractive:!!process.stdin.isTTY}async function HE(e,n){let t=!!n.team,r=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim();if(!t&&!r)return KE(e,n);let o=!!n.global,s=e.persistIO?.home??(0,U.homedir)(),i=dg(n,o?s:e.cwd,s,e.persistIO?.readFile),a=i.on,d=n.org?.trim()||e.env.AGENTTRAIL_ORG_ID?.trim();if(d||(d=await Wa(e,"AgentTrail org id (UUID): ")),!d)return e.error("error: --org <uuid> is required (or set AGENTTRAIL_ORG_ID)."),1;let c;if(t)(n.key||e.env.AGENTTRAIL_API_KEY)&&e.log("note: --team never writes an API key. Each developer supplies it at runtime via AGENTTRAIL_API_KEY / OTEL_EXPORTER_OTLP_HEADERS.");else if(c=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim(),c||(c=await Wa(e,"AgentTrail API key (dlv_live_...): ")),!c)return e.error("error: an API key is required in single-dev mode. Pass --key, set AGENTTRAIL_API_KEY, or use --team."),1;let u=!o&&!t?cg(e,e.cwd):void 0;if(ug(e,i,u),o&&e.error("WARNING: --global configures EVERY Claude Code session on this machine \u2014 including personal and side projects \u2014 to export to AgentTrail. This is a privacy / cost / GDPR consideration. Prefer per-project setup unless you intend machine-wide capture."),!o){let g=(0,Se.basename)(Dn(e.cwd));g&&we(g).length>En&&e.error(`WARNING: project "${g}" exceeds the ${En}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`)}let p=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim(),l;if(p)try{l=Gt(p)}catch(g){return e.error(`error: ${g.message}`),1}let f;try{f=Gf({cwd:e.cwd,orgId:d,apiKey:c,projectSlug:n.project?.trim()||void 0,developerId:n.developer?.trim()||void 0,team:t,global:o,captureContent:a,endpoint:l},e.persistIO??{})}catch(g){if(!(g instanceof sn))throw g;return e.error(`error: setup refused: ${g.message}${ag(e.cwd)}`),1}let m=o?e.persistIO?.home??(0,U.homedir)():e.cwd;if(Fr(m,e.persistIO??{}),e.fetchFn&&c){let g=n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In;await ig(e,{settingsRoot:m,apiBase:g,token:c,deviceTokenPath:!1,home:e.persistIO?.home??(0,U.homedir)(),orgId:d})}return f.slugSource==="directory"&&e.error(rg),e.log(`Project: ${f.projectSlug} \u2192 project.id ${f.projectId}`),e.log(`Endpoint: ${f.resolvedEndpoint}`),e.log(`Wrote ${f.agenttrailConfigPath} (mode 0${f.agenttrailConfigMode.toString(8)})`+(f.gitignoreModified?" (+ .gitignore)":"")),e.log(`Wrote ${f.settings.path} (${f.settings.merged?"merged":"created"})`),f.localSettings&&e.log(`Wrote ${f.localSettings.path} (${f.localSettings.merged?"merged":"created"}, mode 0600, ${o?"":"kept out of git \u2014 "}holds the API key; do NOT commit)`),f.sessionUpload&&sg(e,f.sessionUpload.removedKeys),t&&e.log('Team mode: config is key-free and safe to commit. Each developer must export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer $AGENTTRAIL_API_KEY".'),e.log(Ja(a&&u===void 0,u)),0}async function KE(e,n){let t;try{t=jt(e,n)}catch(S){return e.error(`error: ${S.message}`),1}let r=!!n.global,o=t.settingsRoot,s=r?e.persistIO?.home??(0,U.homedir)():o,i=dg(n,s,e.persistIO?.home??(0,U.homedir)(),e.persistIO?.readFile),a=i.on,d=r?void 0:cg(e,o);ug(e,i,d);let c=n.project?.trim(),u,p;if(c)u=c,p="explicit";else{let S=Nn(o);u=S?.slug??"default",p=S?.source??"directory"}if(t={...t,projectSlug:u,captureContent:a,global:r,settingsRoot:s,setup:!0},!r){let S=Ue(o,nn,e.persistIO??{});if(!S.ok)return e.error(`error: setup refused: ${ft(nn,S)}${ag(o)}`),1}let l=L(t.homeDir,t.credentialsIO);try{if(l&&!dn(l,t.now)){bc(t,l),e.log(`Using existing AgentTrail credentials (org ${l.org_id}).`),e.log(rt);let S=t.device?.confirmedName("claude");S!==void 0&&e.log(`Device name: ${S}`)}else{if(!og(e))return e.error("error: device login needs a browser to authorize. Run `npx -y @agenttrail/cli@latest setup --agent claude` in an interactive terminal, or pass --key / use --team for headless/CI."),1;l=await fi(t),await iI(e,n,t),l=L(t.homeDir,t.credentialsIO)??l}}catch(S){return e.error(`error: ${S.message}`),1}let f={orgId:l.org_id,projectSlug:u,projectId:ne(l.org_id,u),agentId:Le(l.org_id,pe),captureContent:a},m=r?void 0:Ue(t.settingsRoot,Y,e.persistIO??{}),g=m!==void 0&&!m.ok&&m.tracked,h=r?uo(f,e.persistIO??{}):g?void 0:co(t.settingsRoot,f,e.persistIO??{});return r||ao(o,e.persistIO??{}),p==="directory"&&e.error(rg),e.log(`Project: ${u} \u2192 project.id ${f.projectId}`),e.log(`API endpoint (device-auth): ${t.apiEndpoint}`),e.log(`Endpoint: ${t.ingestEndpoint}`),e.log(h?`Wrote ${h.path} (mode 0${h.mode.toString(8)}, device login \u2014 no API key stored)`:`Left ${Y} as it is: this repo tracks it.`),e.log(Ja(a&&d===void 0,d)),r||sg(e,[]),e.fetchFn&&await ig(e,{settingsRoot:t.settingsRoot,apiBase:t.apiEndpoint,token:l.ingest_token,deviceTokenPath:!0,home:e.persistIO?.home??(0,U.homedir)(),orgId:l.org_id}),e.log("Device login active \u2014 telemetry capture is ON. `status` reports capture ACTIVE + the enforcement state."),0}function sg(e,n){e.log("Session data: uploaded after each turn by the Stop and SessionEnd hooks in .claude/settings.json (Claude Code ignores OpenTelemetry exporter settings in project files)."),n.length>0&&e.log(`Removed the OpenTelemetry exporter settings an earlier setup wrote to this project, which Claude Code ignores there: ${n.join(", ")}.`)}async function ig(e,n){if(e.fetchFn)try{let t=await Ga({...n,migrate:!0},{fetchFn:e.fetchFn,runner:e.pluginRunner,settingsIO:e.persistIO,snapshotIO:e.persistIO});e.log(`Real-time enforcement: ${t.enforced?"ON":"OFF"} \u2014 ${t.message}`),t.pluginNote&&e.log(t.pluginNote),t.pluginWarning&&e.error(`warning: ${t.pluginWarning}`),t.migrated&&e.log("Moved the enforcement settings an older setup left in .claude/settings.json to .claude/settings.local.json. If .claude/settings.json is committed, commit this change so teammates stop inheriting them.")}catch(t){e.error(`warning: enforcement wiring failed: ${t.message} (capture is active).`)}}function VE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd;try{let o=K(w(t),d=>(0,Yn.readFileSync)(d,"utf8")),s=ic(o);if(s!==void 0)return{endpoint:ac(s)??X,onDisk:!0};let a=o?.env?.[en];if(typeof a=="string"&&a.length>0)return{endpoint:a,onDisk:!0}}catch{}return{endpoint:e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X,onDisk:!1}}function WE(e){let n;try{n=zt(e.cwd)}catch(a){return e.error(`error: ${a.message}`),1}if(!n.config||n.source===null)return e.log("AgentTrail exporter: INACTIVE (no .agenttrail.json in this project; no global config)."),n.gitRoot&&e.log(`Git root: ${n.gitRoot}`),0;let t=ro(n,e.env),r=QE(e,n);e.log(r.sends?"AgentTrail exporter: ACTIVE":"AgentTrail exporter: CONFIGURED, but no session data is sent (see Session data below)"),e.log(`Config source: ${n.source} (${n.configPath})`),e.log(`Org: ${n.config.orgId}`),e.log(`Project: ${n.config.projectSlug} \u2192 ${n.config.projectId??"(unresolved)"}`);let o=VE(e,n);e.log(`Endpoint: ${o.endpoint}${o.onDisk?"":" (no on-disk endpoint found; env-or-default)"}`);try{let a=Qe(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In);e.log(`API endpoint (device-auth): ${a}`)}catch{}e.log(`API key: ${t?"present":"MISSING (set AGENTTRAIL_API_KEY, or use device login)"}`);let s=qE(e,n);e.log(Ja(s===void 0&&XE(e,n),s));for(let a of r.lines)e.log(a);e.log(`Real-time enforcement: ${YE(e,n)}`),e.log(JE(e,n));let i=pi(e.persistIO?.home??(0,U.homedir)());return i&&e.log(i),0}function QE(e,n){if(n.source!=="project"||!n.configPath||!n.config)return{sends:!0,lines:[]};let t=(0,Se.dirname)(n.configPath),r=e.persistIO?.home??(0,U.homedir)(),o=ai(t,r,n.config.orgId,Or(e)),s=[];if(o.path==="otel")s.push("Session data: OpenTelemetry export (from your user settings, ~/.claude/settings.json).");else if(o.path==="upload"){s.push("Session data: session upload after each turn (Stop and SessionEnd hooks).");let i=$f(r,t);s.push(i.lastSent?`Last session upload: ${i.lastSent.at} (${i.lastSent.sent} turn(s) sent).`:"Last session upload: none yet (the first finishes after your next turn in Claude Code)."),i.lastRun&&i.lastRun.outcome==="failed"&&s.push(`WARNING: the latest upload attempt failed at ${i.lastRun.at}${i.lastRun.reason?` (${i.lastRun.reason})`:""}. Details: ~/.agenttrail/session-upload.log.`)}else s.push(`Session data: NOT SENT \u2014 no session upload hooks in this project. ${Tr}.`);return o.ignoredProjectKeys.length>0&&o.path!=="otel"&&s.push(`WARNING: OpenTelemetry exporter settings sit only in this project's .claude files, where Claude Code ignores them: ${o.ignoredProjectKeys.join(", ")}. ${Tr} to remove them.`),{sends:o.path!=="none",lines:s}}function JE(e,n){let t=e.persistIO?.home??(0,U.homedir)(),r=n.source==="global"||!n.configPath?t:(0,Se.dirname)(n.configPath),o=Tn(t).device_name??"Unnamed device",s=Od(t),i=xd(t,r),a=[s?`machine ${s.slice(0,8)}`:void 0,i?`install ${i.slice(0,8)}`:void 0].filter(d=>d!==void 0);return`Device: ${o}${a.length>0?` (${a.join(", ")})`:""}`}function Qa(e){try{let t=JSON.parse((0,Yn.readFileSync)(e,"utf8"))?.env;return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function YE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd,r=Qa(G(t)),o=Qa(w(t)),s=typeof r[re]=="string"&&r[re]!=="";return r[te]==="1"?s?"ON":`ON but no token, so every tool call is denied. ${Tr}`:o[te]!=="1"?"OFF":n.source==="global"?"ON":s?`ON (set in .claude/settings.json by an older setup). ${Tr} to move it.`:`ON in .claude/settings.json but no token on this machine, so every tool call is denied. Remove AGENTTRAIL_PEP_ENFORCE from .claude/settings.json, or ${Tr.toLowerCase()}.`}var Tr="Run `npx -y @agenttrail/cli@latest setup --agent claude` in this repo";function ag(e){return Qa(w(e))[te]==="1"?" This repo's .claude/settings.json also sets AGENTTRAIL_PEP_ENFORCE (from an older setup); remove it, or teammates without a token have every tool call denied.":""}function Ja(e,n){return!e&&n!==void 0?`Content capture: OFF (metadata and tokens only): ${n} switches it off, and setup cannot override that. Change it there to turn capture on.`:e?"Content capture: ON (prompts, commands, file paths and tool output; secrets and PII are scrubbed at ingest, pattern-based and not exhaustive). Turn it off with `setup --agent claude --no-capture-content`.":"Content capture: OFF (metadata and tokens only). Turn it on with `setup --agent claude --capture-content`."}function zf(e,n){let t;try{t=JSON.parse(n(e))?.env}catch{return"absent"}let r=Pe.filter(o=>t?.[o]!==void 0);return r.length===0?"absent":r.every(o=>t?.[o]==="1")?"on":"off"}function dg(e,n,t,r=o=>(0,Yn.readFileSync)(o,"utf8")){if(e["no-capture-content"])return{on:!1};if(e["capture-content"])return{on:!0};let o=w(n),s=zf(o,r);if(s==="off")return{on:!1,keptOptOut:{from:"install",path:o}};if(s==="absent"&&n!==t){if(zE(n,r)===!0)return{on:!0};let a=w(t);if(zf(a,r)==="off")return{on:!1,keptOptOut:{from:"user",path:a}}}return{on:!0}}function zE(e,n){try{let t=JSON.parse(n((0,Se.join)(e,Y)));return typeof t?.captureContent=="boolean"?t.captureContent:void 0}catch{return}}function cg(e,n){return yo(n,e.persistIO?.home??(0,U.homedir)(),Or(e))}function Or(e){return{env:e.env,...e.persistIO?.readFile?{read:e.persistIO.readFile}:{},...e.managedPaths?{managedPaths:e.managedPaths}:{}}}function ug(e,n,t){if(t!==void 0){e.log(`note: content capture stays OFF for this project because ${t} switches it off. Change it there to turn capture on; setup cannot override it.`);return}if(n.on){e.error(Mr("claude"));return}let r=n.keptOptOut;r!==void 0&&e.log(r.from==="user"?`note: content capture stays OFF because of the user-level opt-out in ${r.path}. Pass --capture-content to turn it on for this project.`:`note: content capture stays OFF because ${r.path} already turns it off (a content flag is not "1"). Pass --capture-content to turn it on.`)}function qf(e){let n;try{n=JSON.parse((0,Yn.readFileSync)(w(e),"utf8"))?.env}catch{return"absent"}return Pe.filter(r=>n?.[r]!==void 0).length===0?"absent":Pe.every(r=>n?.[r]==="1")?"all-on":"defines-some"}function qE(e,n){if(n.source!=="project"||!n.config||!n.configPath)return;let t=(0,Se.dirname)(n.configPath);return yo(t,e.persistIO?.home??(0,U.homedir)(),Or(e))}function XE(e,n){let t=n.source==="global"?(0,U.homedir)():n.configPath?(0,Se.dirname)(n.configPath):n.gitRoot??e.cwd;if(n.source==="project"&&n.config){let s=e.persistIO?.home??(0,U.homedir)();if(ai(t,s,n.config.orgId,Or(e)).path==="upload")return ho(t,s,n.config.captureContent,Or(e))}let r=qf(t);if(r==="all-on")return!0;if(r==="defines-some")return!1;let o=e.persistIO?.home??(0,U.homedir)();return o!==t&&qf(o)==="all-on"}function ZE(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=(0,eg.spawn)(n,[e],{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}function jt(e,n){let t=Qe(n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||In),r=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X;return{...{apiEndpoint:t,ingestEndpoint:r,homeDir:(0,U.homedir)(),settingsRoot:e.cwd,host:(0,U.hostname)(),openBrowser:ZE,...e.loginEnv?{}:{device:ot((0,U.homedir)())},log:e.log},...e.loginEnv}}async function eI(e){if(!e.readStdin)return!1;let n=await e.readStdin();if(n.trim()==="")return!1;try{return Xi(JSON.parse(n))}catch{return!1}}async function nI(e,n){if(n.refresh&&await eI(e))return 0;let t;try{return t=jt(e,n),n.refresh?await Eo(t):await fi(t),0}catch(r){return e.error(`error: ${r.message}`),1}finally{if(n.refresh&&t){fc(e.env.CLAUDE_PROJECT_DIR?.trim()||t.settingsRoot,t.homeDir,t.settingsIO??e.persistIO??{},{git:t.git??e.persistIO?.git});let r=t.fetchFn;await Jf(t,{fetchFn:r?(s,i)=>r(String(s),i):fetch}).catch(()=>{})}}}async function tI(e,n){try{let t=jt(e,n);return await Cc(t),e.pluginRunner&&_f({settingsRoot:t.settingsRoot,runner:e.pluginRunner},e.persistIO??{}).pluginRemoved&&e.log("Removed the AgentTrail enforcement plugin."),0}catch(t){return e.error(`error: ${t.message}`),1}}function rI(e,n){let t="Warning: couldn't check which sessions AgentTrail already has, so ";return e?`${t}this preview counted ALL sessions as importable. Nothing was uploaded, so nothing was duplicated \u2014 but a real import while the check is failing may create duplicates beside live or earlier-imported data.`:n>0?`${t}ALL were imported \u2014 this run may have created duplicates beside live or earlier-imported data.`:`${t}none were skipped as already-recorded. Nothing was imported, so nothing was duplicated \u2014 re-run when AgentTrail is reachable.`}async function oI(e,n){let t=[n.scan,n.import,n.status,n.resume].filter(Boolean).length;if(t===0)return e.error("error: backfill needs one of --scan | --import | --status | --resume."),1;if(t>1)return e.error("error: pass exactly one of --scan | --import | --status | --resume."),1;let r=e.persistIO?.home??(0,U.homedir)(),o=Dn(e.cwd),s=_=>e.log(JSON.stringify(_)),i={...e.backfillDeps,emit:e.backfillDeps?.emit??s};if(n.scan)return await Wl({projectRoot:o},i),0;if(n.status)return Ql({homeDir:r},i),e.log("note: this import record is machine-wide; backfill imports themselves are scoped to the project you run them in."),0;let a=!!n.resume,d=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||X,c=L(r,e.loginEnv?.credentialsIO),u=!!n["dry-run"],p=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim(),l=p||c?.ingest_token;if(!l)return e.error("error: no credentials \u2014 run `npx -y @agenttrail/cli@latest setup --agent claude` / `npx -y @agenttrail/cli@latest login --agent claude` first, or pass --key / set AGENTTRAIL_API_KEY."),1;let f,m,g=!1;if(p)e.error("note: running under an API key, so we can't check your plan's retention window here \u2014 importing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0;else if(c&&u)c.org_tier?(m=c.org_tier,f=Date.now()-zn[c.org_tier]*24*60*60*1e3):(e.error("note: couldn't determine your plan's retention window (no tier on record) \u2014 listing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0);else if(c){let _;try{_=jt(e,n)}catch(T){return e.error(`error: ${T.message}`),1}let C=await kc(_);C.ingestToken&&(l=C.ingestToken),C.tier?(m=C.tier,f=Date.now()-zn[C.tier]*24*60*60*1e3):(e.error("note: couldn't determine your plan's retention window (tier lookup failed) \u2014 importing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0)}let h=n.org?.trim()||e.env.AGENTTRAIL_ORG_ID?.trim()||c?.org_id,S;try{let _=zt(e.cwd);h??=_.config?.orgId,S=_.config?.developerId}catch{}if(!h)return e.error("error: could not resolve org id (use device login, --org, or a .agenttrail.json)."),1;let b;if(n.since){let _=GE(n.since);if(_===null)return e.error(`error: invalid --since '${n.since}' (e.g. 7d, 24h, 30m).`),1;b=Date.now()-_}let E;if(n.concurrency){let _=Number(n.concurrency);if(!Number.isInteger(_)||_<1)return e.error(`error: invalid --concurrency '${n.concurrency}' (positive integer).`),1;E=_}let k=!!n.content;k&&e.error("note: --content uploads prompt/tool content. Shape-matching secrets (AWS keys, connection strings, JWTs, .env-style KEY=value with a secret-ish key name, \u2026) and the output of enumerated secret-manager fetches (`op read`, `op item get`, aws/gcloud/vault/az) are EDGE-scrubbed on this machine before upload; a shapeless secret fetched by any other command (a wrapper script, `kubectl get secret`) \u2014 or by an enumerated command nested inside a command substitution, e.g. `export FOO=$(op read \u2026)` \u2014 is NOT edge-scrubbed. AgentTrail applies your org's scrubbing config again server-side on arrival, redacting the same shapes a second time unless your org has turned scrubbing off. Use `--dry-run --content` to preview exactly what would be redacted before anything leaves the machine.");let I=await Jl({homeDir:r,endpoint:d,token:l,orgId:h,developerId:S,captureContent:k,concurrency:E,dryRun:u,reimport:!!n.reimport,projectRoot:o,sinceMs:b,retentionCutoffMs:f},a,i),y=ct(o)??(0,Se.basename)(o);if(e.log(`Backfill ${u?"(dry-run) ":""}complete: ${I.imported} imported from this project (${y}), ${I.skipped} skipped, ${I.failed} failed, ${I.quarantined} quarantined (of ${I.total}).`),I.dedupSkipped>0&&e.log(`Skipped ${I.dedupSkipped} session(s) already recorded (live capture or an earlier import).`),I.dedupOk||e.log(rI(u,I.imported)),I.excludedOtherProject>0&&e.log(`${I.excludedOtherProject} session(s) on this machine belong to other projects and were not included (backfill imports only the project you run it in).`),I.excludedUnknownCwd>0&&e.log(`${I.excludedUnknownCwd} session(s) were excluded because their working directory couldn't be determined from the transcript (a parse limitation on our side).`),e.log("Only this project is imported \u2014 personal and side projects on this machine are never included unless you cd into them and re-run `backfill --import`."),e.log(""),I.retentionSkipped>0&&m){let _=zn[m],C=`${I.retentionSkipped} of ${I.total} session(s) predate your ${m} plan's ${_}-day retention window and weren't stored`,T=Ss(m);T?e.log(`${C} \u2014 upgrade to ${T} to keep ${zn[T]} days, then re-run to import anything inside the wider window.`):e.log(`${C}.`)}g&&e.log("We couldn't check your plan's retention window on this login, so sessions older than it will be removed server-side."),e.log(`Estimated ~${I.estimatedActions} action(s) in this import (a size estimate, not a governed-action count; first import is free). Preview a run with --dry-run before importing; --since limits it to recently-active sessions.`);let R=I.redactions;if(R.total>0){let _=Object.entries(R.byType).sort((C,T)=>T[1]-C[1]||C[0].localeCompare(T[0])).map(([C,T])=>`${C}\xD7${T}`).join(", ");e.log(`Edge-scrubbed ${R.total} secret(s) across the run before upload (by type: ${_}).`)}return I.failed>0?1:0}var Xf=64;function Zf(e){return`npx -y @agenttrail/cli@latest device rename --agent ${e} "<name>"`}function lg(e,n,t){switch(t.kind){case"renamed":return e.log(`Device name: ${t.name}`),0;case"rejected":return e.error(`That name was not accepted; your device keeps its current name${t.name?` (${t.name})`:""}. Your sign-in is unchanged.`),1;case"unsupported":return e.error("The AgentTrail server did not confirm a device name (it may not support device names yet). Your sign-in is unchanged."),1;case"not-logged-in":return e.error(`error: not logged in; run \`${V(n,"login")}\` first.`),1}}function pg(e){let n=e.trim();return n===""?{error:"a device name cannot be empty."}:[...n].length>Xf?{error:`a device name is at most ${Xf} characters.`}:{name:n}}async function fg(e,n,t,r){let o=`usage: agenttrail device rename --agent ${n} "<name>"`;if(t[1]!=="rename")return e.error(`error: ${o}`),1;let s=pg(t.slice(2).join(" "));if("error"in s)return e.error(`error: ${s.error} ${o}`),1;try{return lg(e,n,await r(s.name))}catch(i){return e.error(`error: ${i.message}`),1}}function sI(e){let n=e.CI?.trim().toLowerCase();return n!==void 0&&n!==""&&n!=="0"&&n!=="false"}async function iI(e,n,t){let r=t.device?.confirmedName("claude");if(r===void 0)return;if(!og(e)||n.yes||sI(e.env)){e.log(`Device name: ${r} (rename it with \`${Zf("claude")}\`).`);return}let o=await Wa(e,`Device name [${r}]: `);if(o===void 0||o.trim()===""||o.trim()===r){e.log(`Device name: ${r}`);return}let s=pg(o);if("error"in s){e.error(`${s.error[0]?.toUpperCase()}${s.error.slice(1)} Keeping "${r}".`);return}try{lg(e,"claude",await gi(t,s.name))}catch(i){e.error(`warning: could not rename the device (${i.message}); it keeps "${r}". Rename it later with \`${Zf("claude")}\`.`)}}function ms(e,n){let t=jt(e,n);return{apiEndpoint:t.apiEndpoint,ingestEndpoint:t.ingestEndpoint,homeDir:t.homeDir,host:t.host,fetchFn:t.fetchFn,sleepFn:t.sleepFn,now:t.now,openBrowser:t.openBrowser,credentialsIO:t.credentialsIO,lockIO:t.lockIO,device:t.device,log:t.log}}async function aI(e,n){try{let t=ms(e,n);return n.refresh?await Sd(t):await Wr(t),0}catch(t){return e.error(`error: ${t.message}`),1}}function dI(e,n,t,r){let o={io:e,flags:t,sessionEnv:()=>ms(e,t)};switch(n){case"login":return aI(e,t);case"logout":return af(o);case"status":case"doctor":return uf(o);case"setup":return tf(o);case"backfill":return Ll(o);case"capture":return gg(e);case"device":return fg(e,"cursor",r,s=>hd(ms(e,t),s))}}function cI(e,n,t){let r={io:e,flags:t,sessionEnv:()=>ms(e,t)};switch(n){case"login":return Za(r);case"logout":return zl(r);case"status":case"doctor":return ql(r,n);case"setup":return Yl(r);case"backfill":return _c(r);case"capture":return gg(e);case"device":return Re(r,"device")}}function gg(e){return e.error("error: capture is the Claude Code session upload hook; use --agent claude."),1}function uI(e,n,t,r){switch(n){case"setup":return HE(e,t);case"login":return nI(e,t);case"logout":return tI(e,t);case"status":case"doctor":return WE(e);case"backfill":return oI(e,t);case"capture":return Uf({env:e.env,homeDir:e.persistIO?.home??(0,U.homedir)(),endpointFlag:t.endpoint,readStdin:e.readStdin,...e.managedPaths?{managedPaths:e.managedPaths}:{},...e.captureOverrides});case"device":return fg(e,"claude",r,o=>gi(jt(e,t),o))}}var lI=["setup","login","logout","status","doctor","backfill","capture","device"];function pI(e){return lI.includes(e)}function fI(e){for(let n of e){if(n==="--")return!1;if(n==="-h"||n==="--help")return!0}return!1}function gI(e){let n=ad(e.argv);if(n.kind==="chosen")return n.agent;e.error(`error: ${id}`),n.kind==="invalid"&&e.error(n.reason)}async function mg(e){if(fI(e.argv))return e.log(_r),0;if(e.argv.length===0)return e.log(_r),1;let n=gI(e);if(n===void 0)return 1;let t;try{t=BE(e.argv)}catch(i){return e.error(`error: ${i.message}`),e.error(_r),1}let{values:r,positionals:o}=t;if(o.length===0)return e.log(_r),1;let s=o[0];if(!pI(s))return e.error(`error: unknown command '${s}'.`),e.error(_r),1;if(s==="setup"&&r["capture-content"]&&r["no-capture-content"])return e.error("error: pass --capture-content or --no-capture-content, not both."),1;switch(n){case"claude":return uI(e,s,r,o);case"cursor":return dI(e,s,r,o);case"codex":return cI(e,s,r)}return Vt(n)}function yg(e,n=Yn.realpathSync){if(!e)return!1;let t=e;try{t=n(e)}catch{}return/[\\/]cli[\\/]index\.(c?js|ts)$/.test(t)}yg(process.argv[1])&&mg({cwd:process.cwd(),env:process.env,argv:process.argv.slice(2),isInteractive:!!process.stdin.isTTY,fetchFn:fetch,pluginRunner:ls,readStdin:()=>Yf(process.stdin),captureOverrides:{armDeadline:e=>{setTimeout(()=>process.exit(0),e).unref()}},log:e=>process.stdout.write(`${e}
|
|
180
180
|
`),error:e=>process.stderr.write(`${e}
|
|
181
181
|
`)}).then(e=>{process.exitCode=e}).catch(e=>{process.stderr.write(`fatal: ${e.message}
|
|
182
182
|
`),process.exitCode=1});0&&(module.exports={isCliEntry,run});
|
package/dist/cli/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Da as a,Ea as b}from"../chunk-
|
|
2
|
+
import{Da as a,Ea as b}from"../chunk-77RT6DZY.js";export{b as isCliEntry,a as run};
|