@agenttrail/cli 0.0.0-stage → 0.2.0
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/LICENSE +202 -0
- package/README.md +292 -2
- package/dist/chunk-WMGYTOQC.js +163 -0
- package/dist/cli/index.cjs +159 -0
- package/dist/cli/index.js +2 -0
- package/dist/cursor/capture-hook.mjs +2 -0
- package/dist/cursor/flush.mjs +6 -0
- package/dist/cursor/pep-hook.mjs +4877 -0
- package/dist/index.cjs +163 -0
- package/dist/index.d.cts +662 -0
- package/dist/index.d.ts +662 -0
- package/dist/index.js +1 -0
- package/package.json +48 -3
- package/plugin/.claude-plugin/marketplace.json +22 -0
- package/plugin/.claude-plugin/plugin.json +11 -0
- package/plugin/README.md +32 -0
- package/plugin/hooks/hooks.json +16 -0
- package/plugin/scripts/pep-hook.mjs +4877 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var yo=Object.defineProperty;var pp=Object.getOwnPropertyDescriptor;var fp=Object.getOwnPropertyNames;var gp=Object.prototype.hasOwnProperty;var mp=(e,n)=>{for(var t in n)yo(e,t,{get:n[t],enumerable:!0})},yp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of fp(n))!gp.call(e,o)&&o!==t&&yo(e,o,{get:()=>n[o],enumerable:!(r=pp(n,o))||r.enumerable});return e};var hp=e=>yp(yo({},"__esModule",{value:!0}),e);var Dh={};mp(Dh,{isCliEntry:()=>cp,run:()=>dp});module.exports=hp(Dh);var ep=require("child_process"),On=require("fs"),W=require("os"),xn=require("path"),np=require("readline/promises"),tp=require("util");var Li="pubsub:sse:org:",Sp=`${Li}*`;var Ue={mode:"standard"};var ho=["Free","Pro","Team","Business","Enterprise"];var Rp=new Set(["Pro","Team","Business","Enterprise"]);function So(e){let n=ho.indexOf(e);return ho.slice(n+1).find(t=>Rp.has(t))??null}var An={Free:7,Pro:14,Team:30,Business:90,Enterprise:365};function Ae(e,n){return e.io.error(`error: \`${n} --agent codex\` is not yet available.`),1}function Ui(e){return Ae(e,"login")}var Dn=require("fs"),vn=require("path");var Bi=require("crypto"),w=require("fs"),P=require("path");var ut="agenttrail.agent.vendor",Ro="agenttrail.tool.vendor_name",Eo=255,lt="agenttrail.usage.reported",Io="agenttrail.time.approximate",bo="agenttrail.span.synthetic",ko="agenttrail.subagent.conversation_id";var Co="agenttrail.turn.closed_by";var To="agenttrail.mcp.server_unknown",_o="agenttrail.pep.blocked";var Oo="18a5d968-0fa2-5c8a-88da-0b29d80105d4",pt="7f050af4-796e-5b05-94c2-dba78bcdc7c2",he="https://ingest.agenttrail.sh";function xo(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 Ao="ef5f62d8-0a65-5a09-be97-07afd9bdab87",wo="7d12feb9-faf4-5d1a-b711-9362724c66b3";var ne="claude-code";var bp="CLAUDE_CODE_ENABLE_TELEMETRY",kp="CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",Cp="OTEL_TRACES_EXPORTER",Tp="OTEL_EXPORTER_OTLP_PROTOCOL",Po="OTEL_EXPORTER_OTLP_ENDPOINT",$e="OTEL_EXPORTER_OTLP_HEADERS",vo="OTEL_RESOURCE_ATTRIBUTES",ft=["OTEL_LOG_USER_PROMPTS","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_TOOL_CONTENT"],gt="agenttrail.org.id",Do="agenttrail.project.id",No="agenttrail.agent.id",Fo=ut,jo="agenttrail.developer.id",Mo="agenttrail.project",rn=255;function Re(e){return encodeURIComponent(e)}function _p(e){let n=[`${gt}=${Re(e.orgId)}`,`${Do}=${Re(e.projectId)}`];if(e.agentId&&n.push(`${No}=${Re(e.agentId)}`),n.push(`${Fo}=${Re(ne)}`),e.developerId&&n.push(`${jo}=${Re(e.developerId)}`),e.project){let t=Re(e.project);t.length<=rn&&n.push(`${Mo}=${t}`)}return n.join(",")}function mt(e){let n={[bp]:"1",[kp]:"1",[Cp]:"otlp",[Tp]:"http/protobuf",[Po]:e.endpoint??he,[vo]:_p(e)};if(e.captureContent!==void 0){let t=e.captureContent?"1":"0";for(let r of ft)n[r]=t}return n}function Gi(e){return e.team||!e.apiKey?{}:{[$e]:`Authorization=Bearer ${e.apiKey}`}}function Lo(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];Se(s)&&Se(o)?t[r]=Lo(s,o):t[r]=o}return t}function Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Zt=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 Op(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Be(e,n){let t;try{t=n(e)}catch(o){if(Op(o))return null;throw o}let r;try{r=JSON.parse(t)}catch{throw new Zt(e,"not valid JSON")}if(!Se(r))throw new Zt(e,"not a JSON object");return r}function U(e,n,t={}){let r=e,o=!0;try{r=(0,w.realpathSync)(e)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=(0,w.lstatSync)(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=(0,P.resolve)((0,P.dirname)(r),(0,w.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,w.statSync)(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${(0,Bi.randomBytes)(6).toString("hex")}`;try{(0,w.writeFileSync)(i,n,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&(0,w.chmodSync)(i,s),(0,w.renameSync)(i,r)}catch(a){try{(0,w.unlinkSync)(i)}catch{}throw a}}function M(e){return(0,P.join)(e,".claude","settings.json")}function te(e){return(0,P.join)(e,".claude","settings.local.json")}var Ge=".claude/settings.local.json";function we(e,n,t={}){let r=te(e),o=t.readFile??(p=>(0,w.readFileSync)(p,"utf8")),s=t.writeFile??((p,l,f)=>U(p,l,f!==void 0?{mode:f}:{})),i=t.mkdir??(p=>(0,w.mkdirSync)(p,{recursive:!0})),a=Be(r,o),d=a??{},c=a!==null,u=Lo(d,{env:n});return i((0,P.dirname)(r)),s(r,`${JSON.stringify(u,null,2)}
|
|
3
|
+
`,384),{path:r,env:n,merged:c}}function Pe(e,n,t={},r={}){let o=Ki(e,{env:n},t,r);return{path:o.path,env:n,merged:o.merged}}function Ki(e,n,t={},r={}){let o=M(e),s=t.readFile??(l=>(0,w.readFileSync)(l,"utf8")),i=t.writeFile??((l,f,m)=>U(l,f,m!==void 0?{mode:m}:{})),a=t.mkdir??(l=>(0,w.mkdirSync)(l,{recursive:!0})),d=Be(o,s),c=d??{},u=d!==null,p=Lo(c,n);return a((0,P.dirname)(o)),r.mode!==void 0?i(o,`${JSON.stringify(p,null,2)}
|
|
4
|
+
`,r.mode):i(o,`${JSON.stringify(p,null,2)}
|
|
5
|
+
`),{path:o,merged:u}}var wn=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 er(e){return e.slice((0,P.dirname)(e).length).replace(/^[/\\]+/,"")}function Hi(e){try{return(0,w.realpathSync)(e)}catch{let n=e;for(let t=0;t<8;t++)try{if(!(0,w.lstatSync)(n).isSymbolicLink())break;n=(0,P.resolve)((0,P.dirname)(n),(0,w.readlinkSync)(n))}catch{break}try{return(0,P.join)((0,w.realpathSync)((0,P.dirname)(n)),er(n))}catch{return(0,P.resolve)(n)}}}function xp(e){return(0,P.dirname)(Hi(e))}function Ap(e){try{return(0,P.join)((0,w.realpathSync)((0,P.dirname)(e)),er(e))}catch{return(0,P.resolve)(e)}}function $i(e){try{return(0,w.realpathSync)(e)}catch{return(0,P.resolve)(e)}}function wp(e){let n=xp(e);for(;;){try{return(0,w.lstatSync)((0,P.join)(n,".git")),n}catch{}let t=(0,P.dirname)(n);if(t===n)return;n=t}}var Pp=[".cfg",".dotfiles",".dotfiles.git",".dots",".local/share/yadm/repo.git",".config/yadm/repo.git",".yadm/repo.git"];function vp(e,n){let t;try{t=(0,w.statSync)(n)}catch{return}let r=[er(e)],o=(0,P.dirname)(e);for(;;){try{let i=(0,w.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(er(o)),o=s}}function Dp(e,n,t){let r=[],o=t.env?.GIT_DIR?.trim();o&&r.push({gitDir:(0,P.resolve)(e,o),workTree:$i((0,P.resolve)(e,t.env?.GIT_WORK_TREE?.trim()||e))});for(let a of Pp){let d=(0,P.join)(e,a);try{(0,w.lstatSync)(d)}catch{continue}r.push({gitDir:d,workTree:$i(e)})}let s=[...new Set([Ap(n),Hi(n)])],i;for(let{gitDir:a,workTree:d}of r)for(let c of s){let u=vp(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 Pn(e,n,t={},r={}){let o=M(e),s=wp(o);if(s!==void 0)throw new wn(o,s);if(r.dotfiles){let i=Dp(e,o,r.dotfiles);if(i&&i.state!=="untracked")throw new wn(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 Pe(e,n,t,{mode:384})}var Vi="npx -y @agenttrail/cli@latest login --refresh --agent claude",Np=["agenttrail login --refresh","npx -y @agenttrail/claude-code-exporter@latest login --refresh"];function Fp(){return{hooks:[{type:"command",command:Vi}]}}function yt(e,n={}){let t=M(e),r=n.readFile??(p=>(0,w.readFileSync)(p,"utf8")),o=[],s=Be(t,r),i=Se(s)?s.hooks:void 0,a=Se(i)?i.SessionStart:void 0;Array.isArray(a)&&(o=a);let d=o.map(p=>{if(!Se(p)||!Array.isArray(p.hooks))return p;let l=p.hooks.filter(f=>!(Se(f)&&typeof f.command=="string"&&Np.includes(f.command)));return{...p,hooks:l}}).filter(p=>!(Se(p)&&Array.isArray(p.hooks)&&p.hooks.length===0)),u=d.some(p=>Se(p)&&Array.isArray(p.hooks)&&p.hooks.some(l=>Se(l)&&l.command===Vi))?d:[...d,Fp()];return Ki(e,{hooks:{SessionStart:u}},n)}var jp=448;function Ee(e,n="claude"){switch(n){case"claude":return(0,vn.join)(e,".agenttrail","credentials.json");case"cursor":return(0,vn.join)(e,".agenttrail","cursor","credentials.json");case"codex":return(0,vn.join)(e,".agenttrail","codex","credentials.json")}return Mp(n)}function Mp(e){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(e)}.`)}function K(e,n={},t="claude"){let r=n.readFile??(o=>(0,Dn.readFileSync)(o,"utf8"));try{let o=JSON.parse(r(Ee(e,t)));return Lp(o)?o:null}catch{return null}}function Nn(e,n,t={},r="claude"){let o=Ee(e,r),s=t.writeFile??((a,d,c)=>U(a,d,c!==void 0?{mode:c}:{}));return(t.mkdir??((a,d)=>(0,Dn.mkdirSync)(a,{recursive:!0,mode:d})))((0,vn.dirname)(o),jp),s(o,`${JSON.stringify(n,null,2)}
|
|
6
|
+
`,384),o}function Qi(e,n={},t="claude"){let r=n.unlink??(o=>(0,Dn.unlinkSync)(o));try{r(Ee(e,t))}catch{}}function Lp(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.refresh_token=="string"&&typeof n.ingest_token=="string"&&typeof n.ingest_token_expires_at=="string"&&typeof n.org_id=="string"&&typeof n.host=="string"&&typeof n.endpoint=="string"&&(n.api_endpoint===void 0||typeof n.api_endpoint=="string")}var Wi={claude:"claude-code",cursor:"cursor",codex:"codex"};function H(e,n){return`npx -y @agenttrail/cli@latest ${n} --agent ${e}`}var Ji="choose --agent claude, --agent cursor or --agent codex";function ht(e){throw new Error(`AgentTrail has no path for the agent ${JSON.stringify(e)}.`)}var Up=40,$p={claude:!0,cursor:!0,codex:!0};function Bp(e){return Object.hasOwn($p,e)?e:void 0}function Yi(e){let n=[];for(let o=0;o<e.length;o++){let s=e[o];if(s==="--")break;if(s==="--agent"){let i=e[o+1];i===void 0||i.startsWith("-")?n.push(void 0):(n.push(i),o++)}else s.startsWith("--agent=")&&n.push(s.slice(8))}if(n.length===0)return{kind:"missing"};if(n.length>1)return{kind:"invalid",reason:"--agent was given more than once."};let t=n[0];if(t===void 0||t==="")return{kind:"invalid",reason:"--agent needs a value."};let r=Bp(t);return r!==void 0?{kind:"chosen",agent:r}:{kind:"invalid",reason:`unknown agent ${JSON.stringify(t.slice(0,Up))}.`}}var Gp=" sends prompt and tool content to AgentTrail \u2014 user prompts, Bash commands and their output, and the contents of files the agent reads. Secret-shaped values (API 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 scrubbed server-side before storage. Scrubbing is shape-based and NOT exhaustive: a structureless secret fetched by any other command (a wrapper script, `kubectl get secret`), or by an enumerated command nested in a command substitution (`export FOO=$(op read \u2026)`), can still be stored \u2014 and nothing is scrubbed at all if your org has turned scrubbing off. Identity fields (user.email, user.id) are retained in plaintext by design (ADR-0005).";function Kp(e){switch(e){case"claude":return" This client never scrubs live capture \u2014 scrubbing is server-side and server-authoritative.";case"cursor":return" This client edge-scrubs the same shapes on your machine before anything is queued, and the server scrubs again on arrival \u2014 so the residues above are what survives both passes. Values are capped at 8192 characters after scrubbing: a size limit on what is kept, not a protection.";case"codex":throw new Error("The --capture-content warning for Codex is not written yet.")}return ht(e)}function nr(e){return(e==="claude"?"WARNING: Content capture":"WARNING: --capture-content")+Gp+Kp(e)}var St="https://api.agenttrail.sh",qi="/api/v1";function on(e){let n;try{n=new URL(e)}catch{throw new Error(`invalid api endpoint '${e}': must be an absolute http(s) URL (e.g. https://api.agenttrail.sh or http://localhost:3000).`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid api endpoint '${e}': protocol must be http: or https: (got '${n.protocol}').`);let t=n.href.replace(/\/$/,"");return t.endsWith(qi)?t:`${t}${qi}`}var tr=(e,n)=>fetch(e,n),Hp=e=>new Promise(n=>setTimeout(n,e));function rr(e,n){return`${e.replace(/\/$/,"")}${n}`}async function or(e,n,t){let r=await e(n,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(t)}),o=null;try{o=await r.json()}catch{o=null}return{status:r.status,ok:r.ok,data:o}}async function zi(e,n=tr,t={}){let{ok:r,status:o,data:s}=await or(n,rr(e,"/auth/device/start"),{...t});if(!r||!Vp(s))throw new Error(`device/start failed (HTTP ${o})`);return s}async function Xi(e,n,t){let r=t.fetchFn??tr,o=t.sleepFn??Hp,s=t.now??(()=>Date.now()),a=(t.openedAt??s())+t.expiresIn*1e3,d=Math.max(1,t.interval),c=rr(e,"/auth/device/token"),u=`device code expired; run \`npx -y @agenttrail/cli@latest login --agent ${t.agent??"claude"}\` again.`;for(;;){if(s()>=a)throw new Error(u);let{ok:p,data:l}=await or(r,c,{device_code:n});if(p&&ea(l))return l;if(na(l))switch(l.error){case"authorization_pending":break;case"slow_down":d+=5;break;case"expired_token":throw new Error(u);case"access_denied":throw new Error("authorization was denied.");default:throw new Error(`device authorization failed: ${l.error}`)}else throw new Error("unexpected response from device/token.");await o(d*1e3)}}async function Fn(e,n,t=tr){let{ok:r,status:o,data:s}=await or(t,rr(e,"/auth/device/refresh"),{refresh_token:n});if(!r||!ea(s)){let i=na(s)?s.error:`HTTP ${o}`;throw new Error(`device/refresh failed: ${i}`)}return s}async function Zi(e,n,t=tr){await or(t,rr(e,"/auth/device/revoke"),{refresh_token:n})}function Vp(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.device_code=="string"&&typeof n.user_code=="string"&&typeof n.verification_uri=="string"&&typeof n.expires_in=="number"&&typeof n.interval=="number"}function ea(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.ingest_token=="string"&&typeof n.refresh_token=="string"&&typeof n.expires_in=="number"&&typeof n.org_id=="string"}function na(e){return typeof e!="object"||e===null?!1:typeof e.error=="string"}var le=require("fs"),Qp=3e4,Wp=(e,n)=>{let t=(0,le.openSync)(e,"wx");try{(0,le.writeSync)(t,n)}finally{(0,le.closeSync)(t)}},Jp=e=>{try{(0,le.rmSync)(e,{force:!0})}catch{}},Yp=e=>{try{let n=(0,le.statSync)(e);return Date.now()-n.mtimeMs}catch{return null}};async function ve(e,n){let t=e.io??{},r=t.acquire??Wp,o=t.release??Jp,s=t.age??Yp,i=t.now??(()=>Date.now()),a=t.sleep??(l=>new Promise(f=>setTimeout(f,l))),d=e.staleMs??Qp,c=e.timeoutMs??1e4,u=e.retryMs??50,p=i()+c;for(;;)try{r(e.lockPath,`${process.pid} ${new Date(i()).toISOString()}
|
|
7
|
+
`);break}catch{let l=s(e.lockPath);if(l!==null&&l>d){o(e.lockPath);continue}if(i()>=p)throw new Error(`could not acquire refresh lock (${e.lockPath}); another refresh is in progress.`);await a(u)}try{return await n()}finally{o(e.lockPath)}}var ra=1440*60*1e3;function oa(e){switch(e){case"claude":return!1;case"cursor":case"codex":return!0}return ht(e)}function sa(e,n){return oa(e.agent)?{apiEndpoint:n.api_endpoint??e.apiEndpoint,ingestEndpoint:n.endpoint}:{apiEndpoint:e.apiEndpoint,ingestEndpoint:e.ingestEndpoint}}async function sr(e){let n=await zi(e.apiEndpoint,e.fetchFn,{client:Wi[e.agent]});e.log(`
|
|
8
|
+
To authorize this device, visit:
|
|
9
|
+
${n.verification_uri}`),e.log(`and enter the code:
|
|
10
|
+
${n.user_code}
|
|
11
|
+
`);let t=n.verification_uri_complete??n.verification_uri;if(e.openBrowser)try{e.openBrowser(t)}catch{}return e.log("Waiting for authorization..."),Xi(e.apiEndpoint,n.device_code,{interval:n.interval,expiresIn:n.expires_in,fetchFn:e.fetchFn,sleepFn:e.sleepFn,now:e.now,openedAt:e.now?.(),agent:e.agent})}function jn(e,n,t=e){return{refresh_token:n.refresh_token,ingest_token:n.ingest_token,ingest_token_expires_at:new Date((e.now?.()??Date.now())+n.expires_in*1e3).toISOString(),org_id:n.org_id,host:e.host,endpoint:t.ingestEndpoint,...n.org_tier?{org_tier:n.org_tier}:{},...oa(e.agent)?{api_endpoint:t.apiEndpoint}:{}}}function ta(e,n){let t=Date.parse(e.ingest_token_expires_at);if(Number.isNaN(t))return!0;let r=n?.()??Date.now();return t-r<=ra}async function ir(e,n){let t=`Not logged in; run \`${H(e.agent,"login")}\`.`,r=K(e.homeDir,e.credentialsIO,e.agent);if(!r)return e.log(t),"not-logged-in";if(!ta(r,e.now))return e.log("Ingest token is fresh; nothing to do."),"no-op";let o=`${Ee(e.homeDir,e.agent)}.lock`;return ve({lockPath:o,io:e.lockIO},async()=>{let s=K(e.homeDir,e.credentialsIO,e.agent);if(!s)return e.log(t),"not-logged-in";if(!ta(s,e.now))return e.log("Ingest token is fresh; nothing to do."),"no-op";let i=sa(e,s),a=await Fn(i.apiEndpoint,s.refresh_token,e.fetchFn);return n(a,i),e.log("Refreshed ingest token."),"rotated"})}async function ar(e){let n=K(e.homeDir,e.credentialsIO,e.agent);if(n)try{await Zi(sa(e,n).apiEndpoint,n.refresh_token,e.fetchFn)}catch{}return Qi(e.homeDir,e.credentialsIO,e.agent),n}function Uo(e){return{...e,agent:"cursor"}}function ia(e,n,t=e){let r=jn(e,n,t);return Nn(e.homeDir,r,e.credentialsIO,"cursor"),r}async function dr(e){let n=Uo(e),t=await sr(n),r=ia(n,t);return e.log(`
|
|
12
|
+
Logged in for Cursor. Traces will be attributed to org ${r.org_id}.`),r}function aa(e){let n=Uo(e);return ir(n,(t,r)=>ia(n,t,r))}async function da(e){let n=await ar(Uo(e));e.log(n?"Logged out of Cursor.":"Not logged in for Cursor; nothing to do.")}function Ie(e){return K(e.homeDir,e.credentialsIO,"cursor")}var fe=require("fs"),Rr=require("path");var ha=require("child_process"),pr=require("path");var pa=require("crypto"),Y=require("fs"),an=require("path");var $=require("fs"),sn=require("path"),Ke=448,N=384,ca=0;function ua(e,n=process.pid){return ca+=1,(0,sn.join)((0,sn.dirname)(e),`.${(0,sn.basename)(e)}.${n}.${ca}.tmp`)}var O={readFile(e){return(0,$.readFileSync)(e)},writeFileAtomic(e,n,t){(0,$.mkdirSync)((0,sn.dirname)(e),{recursive:!0,mode:Ke});let r=ua(e);try{(0,$.writeFileSync)(r,n,{mode:t}),(0,$.chmodSync)(r,t),(0,$.renameSync)(r,e)}catch(o){throw(0,$.rmSync)(r,{force:!0}),o}},mkdirp(e,n){(0,$.mkdirSync)(e,{recursive:!0,mode:n})},remove(e){(0,$.rmSync)(e,{recursive:!0,force:!0})},exists(e){return(0,$.existsSync)(e)},readdir(e){return(0,$.readdirSync)(e).sort()}};var la=require("crypto"),B=require("path");function v(e,n){let t=(0,B.join)(e,".agenttrail",n),r=(0,B.join)(t,"runtime");return{root:t,credentials:(0,B.join)(t,"credentials.json"),install:(0,B.join)(t,"install.json"),projects:(0,B.join)(t,"projects.json"),runtime:r,captureHook:(0,B.join)(r,"capture-hook.mjs"),flush:(0,B.join)(r,"flush.mjs"),queueKey:(0,B.join)(t,"queue.key"),enforcement:(0,B.join)(t,"enforcement.json"),pepSnapshot:(0,B.join)(t,"pep-snapshot.json"),queue:(0,B.join)(t,"queue"),turns:(0,B.join)(t,"turns"),senderLock:(0,B.join)(t,"sender.lock"),senderState:(0,B.join)(t,"sender-state.json"),backfillState:(0,B.join)(t,"backfill-state.json")}}function He(e,n,t){return(0,B.join)(v(e,n).queue,t)}function cr(e,n,t){return(0,B.join)(v(e,n).turns,`${t}.json`)}function ur(e){return(0,la.createHash)("sha256").update(e,"utf8").digest("hex").slice(0,16)}function qp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $o(e){return e?.code==="ENOENT"}var G={readText(e){try{return(0,Y.readFileSync)(e,"utf8")}catch(n){if($o(n))return;throw n}},fileMode(e){try{return(0,Y.statSync)(e).mode&511}catch(n){if($o(n))return;throw n}},writeText(e,n,t){(0,Y.mkdirSync)((0,an.dirname)(e),{recursive:!0,mode:Ke}),U(e,n,{mode:t})},deleteFile(e){try{(0,Y.unlinkSync)(e)}catch(n){if(!$o(n))throw n}},dirExists(e){return(0,Y.existsSync)(e)},removeDirIfEmpty(e){try{(0,Y.readdirSync)(e).length===0&&(0,Y.rmdirSync)(e)}catch{}}};function Go(e,n){return(0,an.join)(v(e,n).root,"hooks-backups")}function lr(e,n,t){let r=(0,pa.createHash)("sha256").update(t,"utf8").digest("hex").slice(0,16);return(0,an.join)(Go(e,n),`${r}.json`)}function fa(e,n,t,r){let o=r.readText(lr(e,n,t));if(o!==void 0)try{let s=JSON.parse(o);if(qp(s)&&s.v===1&&typeof s.existed=="boolean")return s}catch{}}var Bo=e=>({path:e,changed:!1,created:!1,deleted:!1,restored:!1,removed:0});function ga(e){return e===void 0||(e&128)!==0}function ma(e,n,t,r,o={}){let s=o.io??G,i,a;try{i=s.readText(t),a=s.fileMode(t)}catch(u){return{ok:!1,reason:`${t} cannot be read \u2014 ${u.message}`}}let d=r(i);if(!d.ok)return{ok:!1,reason:`${t} ${d.reason}`};if(!d.changed)return{ok:!0,change:Bo(t)};if(!ga(a))return{ok:!1,reason:`${t} is read-only`};let c=s.dirExists((0,an.dirname)(t));try{if(fa(e,n,t,s)===void 0){let p={v:1,path:t,existed:i!==void 0,...i!==void 0?{text:i}:{},dirExisted:c};s.writeText(lr(e,n,t),`${JSON.stringify(p,null,2)}
|
|
13
|
+
`,N)}if(s.readText(t)!==i)return{ok:!1,reason:`${t} changed while setup was running; run it again`};s.writeText(t,d.text,a??N)}catch(u){return{ok:!1,reason:`${t} could not be written \u2014 ${u.message}`}}return{ok:!0,change:{path:t,changed:!0,created:i===void 0,deleted:!1,restored:!1,removed:d.removed}}}function ya(e,n,t,r,o,s={}){let i=s.io??G,a,d;try{a=i.readText(t),d=i.fileMode(t)}catch(m){return{ok:!1,reason:`${t} cannot be read \u2014 ${m.message}`}}if(a===void 0)return{ok:!0,change:Bo(t)};let c=r.remove(a,o);if(!c.ok)return{ok:!1,reason:`${t} ${c.reason}`};if(!c.changed)return{ok:!0,change:Bo(t)};if(!ga(d))return{ok:!1,reason:`${t} is read-only`};let u=fa(e,n,t,i),p=r.hasAnyOurs(c.text),l=!1,f=!1;try{if(i.readText(t)!==a)return{ok:!1,reason:`${t} changed while it was being cleaned up; run again`};!p&&u?.existed===!0&&u.text!==void 0&&!r.hasAnyOurs(u.text)&&r.sameApartFromOurs(c.text,u.text)?(i.writeText(t,u.text,d??N),l=!0):!p&&u?.existed===!1&&c.empty&&s.keepFile!==!0?(i.deleteFile(t),f=!0,u.dirExisted===!1&&i.removeDirIfEmpty((0,an.dirname)(t))):i.writeText(t,c.text,d??N),p||i.deleteFile(lr(e,n,t))}catch(m){return{ok:!1,reason:`${t} could not be written \u2014 ${m.message}`}}return{ok:!0,change:{path:t,changed:!0,created:!1,deleted:f,restored:l,removed:c.removed}}}var zp=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_PREFIX","GIT_CEILING_DIRECTORIES"],L=(e,n)=>{let t={...process.env};for(let r of zp)delete t[r];try{return{code:0,stdout:(0,ha.execFileSync)("git",[...e],{cwd:n,env:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3})}}catch(r){let o=r.status;return{code:typeof o=="number"?o:-1,stdout:String(r.stdout??"")}}};function De(e,n=L){return n(["rev-parse","--git-dir"],e).code===0}function be(e,n,t=L){let{code:r}=t(["ls-files","--error-unmatch","--",n],e);return r===0?"tracked":r===1?"untracked":"unknown"}function dn(e,n,t=L){return t(["check-ignore","-q","--",n],e).code===0}function Rt(e,n=L){let{code:t,stdout:r}=n(["rev-parse","--git-path","info/exclude"],e);if(t!==0)return;let o=r.trim();if(o!=="")return(0,pr.isAbsolute)(o)?o:(0,pr.join)(e,o)}function Et(e){return`/${e.replace(/[\\*?[\]]/g,t=>`\\${t}`).replace(/ $/,"\\ ")}`}function Sa(e){return e===void 0||e===""?[]:e.replace(/\n$/,"").split(`
|
|
14
|
+
`)}function fr(e,n,t,r={}){let o=r.git??L,s=r.io??G;if(!De(e,o))return{ok:!0,state:"not-a-repo"};if(dn(e,n,o))return{ok:!0,state:"already-ignored"};let i=Rt(e,o);if(i===void 0)return{ok:!1,reason:"git could not say where this repo's info/exclude file is"};let a=Et(n),d;try{d=s.readText(i);let u=[...Sa(d),t,a];s.writeText(i,`${u.join(`
|
|
15
|
+
`)}
|
|
16
|
+
`,s.fileMode(i)??420)}catch(c){return{ok:!1,reason:`${i} could not be written \u2014 ${c.message}`}}if(dn(e,n,o))return{ok:!0,state:"added"};try{s.writeText(i,d??"",s.fileMode(i)??420)}catch{}return{ok:!1,reason:`git still does not ignore ${n} after ${i} was extended; a .gitignore rule re-includes it`}}function Ra(e,n,t,r={}){let o=r.git??L,s=r.io??G,i=Rt(e,o);if(i===void 0)return!1;let a;try{a=s.readText(i)}catch{return!1}if(a===void 0)return!1;let d=Et(n),c=Sa(a),u=[];for(let l=0;l<c.length;l++){if(c[l]===t&&c[l+1]===d){l+=1;continue}u.push(c[l])}if(u.length===c.length)return!1;let p=u.length===0?"":`${u.join(`
|
|
17
|
+
`)}
|
|
18
|
+
`;try{s.writeText(i,p,s.fileMode(i)??420)}catch{return!1}return!0}var Ca=require("child_process"),Qo=require("path"),Wo=require("uuid");var Ln=require("fs"),Ia=require("os"),un=require("path");var Mn=require("zod");var Ve="agenttrail.ingest.mode",Qe="agenttrail.ingest.batch_id",cn="backfill";var gr=Mn.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"must be a UUID"),Xp=Mn.z.string().min(1).refine(e=>e.startsWith("dlv_"),{message:"AgentTrail API key must start with 'dlv_'"}),Zp=Mn.z.object({orgId:gr,projectSlug:Mn.z.string().min(1),projectId:gr.optional(),agentId:gr.optional(),developerId:gr.optional(),apiKey:Xp.optional(),captureContent:Mn.z.boolean().optional()}).strict();function mr(e){return Zp.parse(e)}var V=".agenttrail.json";function Ko(e=(0,Ia.homedir)()){return(0,un.join)(e,".agenttrail","config.json")}function ba(e){return(0,Ln.existsSync)((0,un.join)(e,".git"))}function Ea(e){let n=(0,Ln.readFileSync)(e,"utf8"),t;try{t=JSON.parse(n)}catch(r){throw new Error(`Malformed ${V} at ${e}: not valid JSON (${r.message})`)}return mr(t)}function Ho(e){let n=e;for(;;){let t=(0,un.join)(n,V);if((0,Ln.existsSync)(t))return t;if(ba(n))return null;let r=(0,un.dirname)(n);if(r===n)return null;n=r}}function yr(e){let n=e;for(;;){if(ba(n))return n;let t=(0,un.dirname)(n);if(t===n)return null;n=t}}function ln(e){return yr(e)??e}function Vo(e,n={}){let t=yr(e),r=Ho(e);if(r)return{config:Ea(r),source:"project",configPath:r,gitRoot:t};if(n.allowGlobal!==!1){let o=n.globalPath??Ko();if((0,Ln.existsSync)(o))return{config:Ea(o),source:"global",configPath:o,gitRoot:t}}return{config:null,source:null,configPath:null,gitRoot:t}}function ka(e,n=process.env){let t=n.AGENTTRAIL_API_KEY?.trim();return t||(e.config?.apiKey??null)}function hr(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ta(e){let n=e.trim().replace(/\.git$/,""),t=n.match(/^[^@]+@[^:]+:(.+)$/);if(t)return t[1]||null;let r=n.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return r&&r[1]||null}function _a(e){try{return(0,Ca.execFileSync)("git",["remote","get-url","origin"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function pn(e,n={}){let r=(n.readGitRemote??_a)(e);if(r){let s=Ta(r);if(s){let i=hr(s);if(i)return{slug:i,source:"remote"}}}let o=hr((0,Qo.basename)(e));return o?{slug:o,source:"directory"}:null}function fn(e,n={}){return pn(e,n)?.slug??null}function Un(e,n={}){let r=(n.readGitRemote??_a)(e);if(r){let s=Ta(r)?.split("/").pop()?.trim();if(s)return s}return(0,Qo.basename)(ln(e))}function re(e,n){return(0,Wo.v5)(`${e}:${n}`,Oo)}function pe(e,n){return(0,Wo.v5)(`${e}:${n}`,pt)}var Oa=require("os"),xa=require("path");var q="AGENTTRAIL_PEP_ENFORCE",Jo="AGENTTRAIL_PEP_URL",Yo="AGENTTRAIL_PEP_HOLD_URL",qo="AGENTTRAIL_PEP_SNAPSHOT_URL",z="AGENTTRAIL_PEP_TOKEN",zo="AGENTTRAIL_PEP_TIMEOUT_MS",It="AGENTTRAIL_PEP_ORG_ID",Aa="AGENTTRAIL_PEP_SNAPSHOT_PATH";var $n=3e3;function Sr(e=(0,Oa.homedir)()){return(0,xa.join)(e,".agenttrail","pep-snapshot.json")}function ef(e){let n=e?.trim();return n&&n.length>0?n:void 0}function wa(e){return`${on(e)}/policies/evaluate`}function Bn(e){return`${on(e)}/policies/compiled-snapshot`}function Pa(e){return`${on(e)}/policies/hold`}function va(e){let n={[Jo]:wa(e.apiBase),[Yo]:Pa(e.apiBase),[qo]:Bn(e.apiBase),[zo]:String(e.timeoutMs??$n)};return e.orgId&&(n[It]=e.orgId),n}var Xo={[q]:"1"};function Da(e){let n=ef(e.token);return n?{[z]:n}:{}}function ja(e){if(e.global)return;let n=Un(e.settingsRoot);return n&&Re(n).length>rn&&e.log(`WARNING: project "${n}" exceeds the ${rn}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`),n}function Er(e){return{agent:"claude",apiEndpoint:e.apiEndpoint,ingestEndpoint:e.ingestEndpoint,homeDir:e.homeDir,host:e.host,fetchFn:e.fetchFn,sleepFn:e.sleepFn,now:e.now,openBrowser:e.openBrowser,credentialsIO:e.credentialsIO,lockIO:e.lockIO,log:e.log}}var nf="dlv_ingest_",bt=class extends Error{path;constructor(n,t,r){let o=t?.message??String(t);super(r==="read"?`could not check whether ${n} holds a stale AgentTrail token (${o}); fix or move the file.`:`could not update the device token in ${n} (${o}). Enforcement and capture from that project will send its old, rejected token; fix or move the file, then re-run \`npx -y @agenttrail/cli@latest setup --agent claude\`.`),this.name="PepTokenMirrorError",this.path=n}},Ma=/^Authorization=Bearer (dlv_ingest_[^\s,]+)$/,es=[{key:z,tokenOf:e=>e.startsWith(nf)?e:void 0,render:e=>e},{key:$e,tokenOf:e=>Ma.exec(e)?.[1],render:e=>`Authorization=Bearer ${e}`}];function tf(e){let n=[],t=e[It];typeof t=="string"&&t!==""&&n.push(t);let r=e[vo];if(typeof r=="string")for(let o of r.split(",")){let s=o.indexOf("=");if(!(s<0||o.slice(0,s).trim()!==gt))try{let i=decodeURIComponent(o.slice(s+1).trim());i!==""&&n.push(i)}catch{}}return n}function Na(e,n){let t={};for(let r of es){let o=e[r.key];if(typeof o!="string")continue;let s=r.tokenOf(o);s!==void 0&&s!==n&&(t[r.key]=r.render(n))}return t}function La(e,n,t,r){let o=e.settingsIO?.readFile??(l=>(0,fe.readFileSync)(l,"utf8")),s=l=>{let f;try{f=Be(l,o)}catch(g){throw new bt(l,g,"read")}let m=f?.env;return m!==null&&typeof m=="object"?m:void 0},i=[],a=[],d=(l,f,m)=>{if(Object.keys(m).length===0)return;let g=l.user?f:s(M(l.root))??{},h=tf({...g,...f}).find(R=>R!==t);if(h!==void 0){a.push({path:l.path,configuredOrgId:h});return}i.push({target:l,updates:m})},c;for(let l of new Set([e.settingsRoot,e.homeDir])){let f=te(l),m=s(f);l===e.homeDir&&(c=m),m&&d({root:l,path:f,user:!1},m,Na(m,n))}let u=M(e.homeDir),p=s(u);if(p){let l=Na(p,n);for(let f of r.adopt?es:[]){if(f.key in p)continue;let m=c?.[f.key];typeof m=="string"&&f.tokenOf(m)!==void 0&&(l[f.key]=f.render(n))}d({root:e.homeDir,path:u,user:!0},{...c??{},...p},l)}return{stale:i,otherOrg:a}}function Ua(e,n,t){for(let{path:r,configuredOrgId:o}of n.otherOrg)e.log(`WARNING: ${r} holds a stale AgentTrail token for org ${o}, but you are logged in to org ${t}; it was left unchanged. Re-run setup in that project to reconnect it.`)}function ns(e,n,t,r){let o=La(e,n,t,{adopt:r.interactive});Ua(e,o,t);for(let{target:s,updates:i}of o.stale)try{s.user?Pn(s.root,i,e.settingsIO,{dotfiles:r.interactive?Zo(e):{...Zo(e),log:void 0}}):we(s.root,i,e.settingsIO)}catch(a){if(a instanceof wn){(r.interactive||$a(e,"user-settings-refused-warned"))&&e.log(`WARNING: ${a.message}`);continue}throw new bt(s.path,a,"write")}}function Zo(e){return{git:e.git??L,env:e.processEnv??process.env,log:e.log}}var rf=1440*60*1e3;function $a(e,n){let t=(0,Rr.join)(e.homeDir,".agenttrail",n),r=e.now?.()??Date.now();try{if(r-(0,fe.statSync)(t).mtimeMs<rf)return!1}catch{}try{(0,fe.mkdirSync)((0,Rr.join)(e.homeDir,".agenttrail"),{recursive:!0,mode:448}),(0,fe.writeFileSync)(t,"")}catch{}return!0}function Ba(e,n){let t={[$e]:`Authorization=Bearer ${n}`};e.global?Pn(e.settingsRoot,t,e.settingsIO,{dotfiles:Zo(e)}):we(e.settingsRoot,t,e.settingsIO)}function ts(e,n={}){let t=n.readFile??(s=>(0,fe.readFileSync)(s,"utf8")),r=s=>{try{let i=Be(s,t)?.env;return typeof i=="object"&&i!==null?i:{}}catch{return{}}},o=r(te(e))[$e];if(!(typeof o!="string"||Ma.exec(o)===null)&&!($e in r(M(e))))return`Capture token not in ${M(e)}, so Claude Code sessions outside your home folder upload nothing. Run \`npx -y @agenttrail/cli@latest setup --agent claude --global\` to repair.`}function rs(e,n,t){let r=jn(Er(e),n);if(Nn(e.homeDir,r,e.credentialsIO),t.registerHook&&Ba(e,n.ingest_token),ns(e,n.ingest_token,n.org_id,{interactive:t.registerHook}),t.registerHook){let o=e.projectSlug??fn(e.settingsRoot)??"default";Pe(e.settingsRoot,mt({orgId:n.org_id,projectId:re(n.org_id,o),agentId:pe(n.org_id,ne),endpoint:e.ingestEndpoint,captureContent:e.captureContent,project:ja(e)}),e.settingsIO),yt(e.settingsRoot,e.settingsIO)}return r}function Gn(e,n){let t=Date.parse(e.ingest_token_expires_at);return Number.isNaN(t)?!0:t<=(n?.()??Date.now())}function Ga(e,n){Ba(e,n.ingest_token);let t=e.projectSlug??fn(e.settingsRoot)??"default";Pe(e.settingsRoot,mt({orgId:n.org_id,projectId:re(n.org_id,t),agentId:pe(n.org_id,ne),endpoint:e.ingestEndpoint,captureContent:e.captureContent,project:ja(e)}),e.settingsIO),yt(e.settingsRoot,e.settingsIO),ns(e,n.ingest_token,n.org_id,{interactive:!0})}async function os(e){let n=await sr(Er(e)),t=rs(e,n,{registerHook:!0});return e.log(`
|
|
19
|
+
Logged in. Traces will be attributed to org ${t.org_id}.`),e.log("A SessionStart hook was registered to refresh the token; it freshens the NEXT session, not the current one."),t}async function Ka(e){let n=await ir(Er(e),s=>rs(e,s,{registerHook:!1})),t=ts(e.homeDir,e.settingsIO);t&&$a(e,"user-settings-repair-hinted")&&e.log(t);let r=n==="no-op"?K(e.homeDir,e.credentialsIO):void 0;if(!r)return n;let o=La(e,r.ingest_token,r.org_id,{adopt:!1});return o.stale.length===0?(Ua(e,o,r.org_id),n):(await ve({lockPath:`${Ee(e.homeDir)}.lock`,io:e.lockIO},async()=>{let s=K(e.homeDir,e.credentialsIO);s&&ns(e,s.ingest_token,s.org_id,{interactive:!1})}),n)}async function Ha(e){let n=K(e.homeDir,e.credentialsIO);if(!n)return{};let t=`${Ee(e.homeDir)}.lock`;try{return await ve({lockPath:t,io:e.lockIO},async()=>{let r=await Fn(e.apiEndpoint,n.refresh_token,e.fetchFn);try{let o=rs(e,r,{registerHook:!1});return{ingestToken:o.ingest_token,tier:o.org_tier}}catch(o){if(!(o instanceof bt))throw o;e.log(`WARNING: ${o.message}`);let s=K(e.homeDir,e.credentialsIO);return{ingestToken:r.ingest_token,tier:s?.org_tier??n.org_tier}}})}catch{return{tier:n.org_tier}}}async function Va(e){let n=null;try{n=await ar(Er(e))}finally{of(e.settingsRoot,e.settingsIO),Fa(te(e.homeDir),e.settingsIO,384),Fa(M(e.homeDir),e.settingsIO)}e.log(n?"Logged out.":"Not logged in; nothing to do.")}function Fa(e,n={},t){let r=n.readFile??(c=>(0,fe.readFileSync)(c,"utf8")),o=n.writeFile??((c,u,p)=>U(c,u,p!==void 0?{mode:p}:{})),s;try{let c=JSON.parse(r(e));if(typeof c!="object"||c===null||Array.isArray(c))return;s=c}catch{return}let i=s.env;if(typeof i!="object"||i===null)return;let a=i,d=!1;for(let c of es){let u=a[c.key];typeof u!="string"||c.tokenOf(u)===void 0||(delete a[c.key],c.key===z&&delete a[q],d=!0)}d&&o(e,`${JSON.stringify(s,null,2)}
|
|
20
|
+
`,t)}function of(e,n={}){let t=(0,Rr.join)(e,".claude","settings.local.json"),r=n.readFile??(a=>(0,fe.readFileSync)(a,"utf8")),o=n.writeFile??((a,d,c)=>U(a,d,c!==void 0?{mode:c}:{})),s;try{let a=r(t),d=JSON.parse(a);if(typeof d!="object"||d===null)return;s=d}catch{return}let i=s.env;typeof i=="object"&&i!==null&&$e in i&&(delete i[$e],o(t,`${JSON.stringify(s,null,2)}
|
|
21
|
+
`,384))}function Qa(e){return Ae(e,"backfill")}function J(e,n){return n?`[REDACTED:${e}:${n}]`:`[REDACTED:${e}]`}var Wa=String.raw`(?:\b|(?<=\\[nrtfb])|(?<=\\u[0-9A-Fa-f]{4})|(?<=\x1b\[[0-9;:?]{0,32}[@-~])|(?<=\\(?:u001[bB]|x1[bB]|033)\[[0-9;:?]{0,32}[@-~])|(?<=\x1b\([0-9A-Za-z])|(?<=\\(?:u001[bB]|x1[bB]|033)\([0-9A-Za-z]))`;function ae(e,n){return new RegExp(`${Wa}${e}`,n)}var sf=ae(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),af=new RegExp(`((?:aws[_-]?)?secret[_-]?access[_-]?key)(["']?\\s*[=:]\\s*["']?)((?![0-9a-f]{40}(?![A-Za-z0-9/+=]))[A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])`,"gi"),df=ae(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),cf=ae(String.raw`(?:(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255}\b|github_pat_[A-Za-z0-9_]{22,255}\b)`,"g"),uf=ae(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`,"g"),lf=ae(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`,"gi"),pf=ae(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),ff=ae(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`,"g"),gf=/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,mf=ae(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`,"gi"),yf=(()=>{let n="([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API[_-]?KEY|APIKEY|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|CLIENT[_-]?SECRET|AUTH[_-]?TOKEN|CREDENTIALS?)[A-Z0-9_]*)",t=`(?:(")([^"\uE000]{4,})"|(')([^'\uE000]{4,})'|([^\\s"',;\uE000]{4,}))`;return new RegExp(`${Wa}${n}(["']?\\s*[=:]\\s*)${t}`,"gi")})(),hf=ae(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`,"g"),Sf=ae(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`,"g"),Rf=ae(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`,"g"),Ef=ae(String.raw`(?:\+?\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?)?\d{2,4}[ .-]\d{2,4}[ .-]\d{2,4}\b`,"g"),Ja=[{id:"aws-access-key-id",kind:"secret",category:"aws",severity:"high",tier:"permissive",regex:sf,placeholder:()=>J("secret:aws")},{id:"pem-private-key",kind:"secret",category:"private-key",severity:"high",tier:"permissive",regex:gf,placeholder:()=>J("secret:private-key")},{id:"jwt",kind:"secret",category:"jwt",severity:"high",tier:"permissive",regex:ff,placeholder:()=>J("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:cf,placeholder:()=>J("secret:github")},{id:"slack-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:uf,placeholder:()=>J("secret:slack")},{id:"openai-key",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:df,placeholder:()=>J("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:pf,placeholder:()=>J("secret:connection-string")},{id:"basic-auth-url",kind:"secret",category:"basic-auth",severity:"high",tier:"permissive",regex:mf,placeholder:e=>`${e[1].toLowerCase()}://${J("secret:basic-auth")}@`},{id:"bearer-token",kind:"secret",category:"token",severity:"medium",tier:"permissive",regex:lf,placeholder:()=>`Bearer ${J("secret:bearer")}`},{id:"aws-secret-access-key",kind:"secret",category:"aws",severity:"medium",tier:"standard",regex:af,placeholder:e=>`${e[1]}${e[2]}${J("secret:aws-secret")}`},{id:"env-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:yf,placeholder:e=>{let n=e[3]??e[5]??"";return`${e[1]}${e[2]}${n}${J("secret:env")}${n}`}},{id:"email",kind:"pii",category:"email",severity:"low",tier:"standard",regex:hf,placeholder:()=>J("pii:email")},{id:"ssn",kind:"pii",category:"ssn",severity:"high",tier:"standard",regex:Sf,placeholder:()=>J("pii:ssn")},{id:"credit-card",kind:"pii",category:"credit-card",severity:"high",tier:"standard",regex:Rf,placeholder:()=>J("pii:credit-card")},{id:"phone",kind:"pii",category:"phone",severity:"low",tier:"strict",regex:Ef,placeholder:()=>J("pii:phone")}],Ya=new Set(["credit-card"]);function qa(e){let n=e.replace(/\D/g,"");if(n.length<13||n.length>19)return!1;let t=0,r=!1;for(let o=n.length-1;o>=0;o--){let s=n.charCodeAt(o)-48;r&&(s*=2,s>9&&(s-=9)),t+=s,r=!r}return t%10===0}var If={permissive:new Set(["permissive"]),standard:new Set(["permissive","standard"]),strict:new Set(["permissive","standard","strict"])},Kn="\uE000",bf=new RegExp(`${Kn}(\\d+)${Kn}`,"g");function za(e){return`${Kn}${e}${Kn}`}function kf(e,n=!1){if(e==="off")return[];let t=If[e];return Ja.filter(r=>r.id==="phone"?t.has("strict")||n:t.has(r.tier))}function Cf(e){if(!e||e.length===0)return[];let n=[];for(let t of e)try{n.push(new RegExp(t,"g"))}catch{}return n}function Tf(e,n,t,r){let o=Ya.has(n.id);return e.replace(n.regex,(...s)=>{let i=s[0];if(o&&!qa(i))return i;let a=s.slice(0,s.length-2);t[n.id]=(t[n.id]??0)+1;let d=r.length;return r.push(n.placeholder(a)),za(d)})}function gn(e){return e.mode==="off"?null:{patterns:kf(e.mode,e.enablePhone),denylist:Cf(e.denylistPatterns)}}function Xa(e,n){if(e.length===0)return{text:e,redactions:{},total:0};let{patterns:t,denylist:r}=n;return t.length===0&&r.length===0?{text:e,redactions:{},total:0}:_f(e,t,r)}function _f(e,n,t){let r={},o=[],s=e.includes(Kn)?e.split(Kn).join(""):e;for(let a of n)s=Tf(s,a,r,o);for(let a=0;a<t.length;a++)s=s.replace(t[a],()=>{r.custom=(r.custom??0)+1;let d=o.length;return o.push("[REDACTED:custom]"),za(d)});if(o.length===0)return{text:e,redactions:{},total:0};s=s.replace(bf,(a,d)=>o[Number(d)]);let i=0;for(let a in r)i+=r[a];return{text:s,redactions:r,total:i}}var Za=require("path");var ss="cursor",Ir="cursor",D="cursor",br={agent:ss,vendor:Ir,stateDir:D};function F(e){return v(e,D)}function Hn(e,n){return He(e,D,n)}function ed(e){return(0,Za.join)(e,".cursor","projects")}function mn(e){return e.replace(/^\/+/,"").replace(/[/. -]/g,"-")}function kt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nd(e){return typeof e=="string"&&e!==""}function Of(e,n){if(!kt(n))return{key:e};let t=nd(n.root)?n.root:void 0,r=Array.isArray(n.subfolders)?n.subfolders.map(o=>kt(o)&&nd(o.path)?o.path:void 0).filter(o=>o!==void 0):[];return{key:e,...t!==void 0?{root:t}:{},...r.length>0?{subfolders:r}:{}}}function xf(e,n){let t;try{t=JSON.parse(e)}catch{return}if(!kt(t)||t.v!==1||!kt(t.projects))return;let r={},o=[];for(let[s,i]of Object.entries(t.projects))n(s,i)?r[s]=i:o.push(Of(s,i));return{registry:{v:1,projects:r},skipped:o}}var is=Object.freeze({v:1,projects:Object.freeze({})});function rd(e,n,t=O){let r;try{if(!t.exists(e))return{kind:"missing"};r=t.readFile(e).toString("utf8")}catch{return{kind:"unreadable"}}let o=xf(r,n);return o===void 0?{kind:"unreadable"}:{kind:"ok",registry:o.registry,skipped:o.skipped}}function td(e){return e.length>1?e.replace(/\/+$/,""):e}function Af(e,n){let t=td(e),r=td(n);return r===t||r.startsWith(t.endsWith("/")?t:`${t}/`)}function wf(e,n){return[...e,...n!==void 0?[n]:[]].filter(r=>typeof r=="string"&&r!=="")}function od(e,n,t){let r=wf(n,t),o;for(let s of Object.values(e.projects))r.some(i=>Af(s.root,i))&&(o===void 0||s.root.length>o.root.length)&&(o=s);return o}function sd(e,n){if(e.kind==="unreadable")throw n();return e.kind==="ok"?e.registry:is}function as(e,n){return kt(e)?Object.fromEntries(Object.entries(e).filter(([t])=>!n.has(t))):{}}function id(e){return`${JSON.stringify(e,null,2)}
|
|
22
|
+
`}function ad(e,n,t=O){let r=(()=>{try{return t.exists(e)?t.readFile(e).toString("utf8"):void 0}catch{return}})(),o=id(n);return r===o?"unchanged":(t.writeFileAtomic(e,o,N),"written")}function dd(e,n,t,r=O){if(n.projects[t]===void 0)return!1;let o={...n.projects};return delete o[t],r.writeFileAtomic(e,id({v:1,projects:o}),N),!0}function kr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ne(e){return typeof e=="string"&&e!==""}function cd(e){return e==="project"||e==="user"}var vf=new Set(["flag","agenttrail-json","derived"]);function Df(e){return kr(e)&&Ne(e.path)&&Ne(e.transcriptFolder)&&cd(e.install)&&Ne(e.registeredAt)}function Nf(e,n){return kr(n)?n.projectKey===e&&Ne(n.root)&&Ne(n.transcriptFolder)&&Ne(n.orgId)&&Ne(n.projectSlug)&&Ne(n.projectId)&&vf.has(n.projectSource)&&typeof n.projectLabel=="string"&&(n.developerId===void 0||typeof n.developerId=="string")&&typeof n.captureContent=="boolean"&&cd(n.install)&&Ne(n.registeredAt)&&(n.subfolders===void 0||Array.isArray(n.subfolders)&&n.subfolders.every(Df)):!1}var ud=is;function X(e,n=O){return rd(F(e).projects,Nf,n)}function ds(e,n,t){return od(e,n,t)}function cs(e){let n=[];for(let t of Object.values(e.projects)){t.install==="user"&&n.push(t.root);for(let r of t.subfolders??[])r.install==="user"&&n.push(r.path)}return[...new Set(n)].sort()}var We=class extends Error{constructor(n){super(`cannot read ${F(n).projects}. Nothing was changed. Fix or delete that file, then run setup again.`),this.name="CursorRegistryError"}};function ld(e,n){return sd(X(e,n),()=>new We(e))}var Ff=new Set(["projectKey","root","transcriptFolder","orgId","projectSlug","projectId","projectSource","projectLabel","developerId","captureContent","install","registeredAt","enforce","subfolders"]),jf=new Set(["path","transcriptFolder","install","registeredAt"]);function pd(e,n,t=O){let r=ld(e,t),o=r.projects[n.projectKey],s=kr(o)&&Array.isArray(o.subfolders)?o.subfolders:[],i=n.subfolders?.map(c=>{let u=s.find(p=>kr(p)&&p.path===c.path);return{...as(u,jf),...c}}),a={...as(o,Ff),...n,...i!==void 0?{subfolders:i}:{}},d={v:1,projects:{...r.projects,[n.projectKey]:a}};return ad(F(e).projects,d,t)}function fd(e,n,t=O){return dd(F(e).projects,ld(e,t),n,t)}var Ct=Object.freeze({v:1,dropped:Object.freeze({}),unknownKinds:Object.freeze({}),pepDecisions:Object.freeze({seen:0,filledToolUseId:0,orphaned:0}),projects:Object.freeze({})});function Tt(){return{dropped:{},unknownKinds:{},pepDecisions:{seen:0,filledToolUseId:0,orphaned:0},projects:{}}}function ps(e){return e.lastUploadAtMs===void 0&&e.lastError===void 0&&Object.keys(e.dropped).length===0&&Object.keys(e.unknownKinds).length===0&&e.pepDecisions.seen===0&&e.pepDecisions.filledToolUseId===0&&e.pepDecisions.orphaned===0&&Object.keys(e.projects).length===0}function de(e,n){e[n]=(e[n]??0)+1}function _t(e,n){let t=e.projects[n];if(t!==void 0)return t;let r={dropped:{}};return e.projects[n]=r,r}function yn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function us(e){if(!yn(e))return{};let n={};for(let[t,r]of Object.entries(e))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(n[t]=r);return n}function gd(e){if(!yn(e))return;let{version:n,seenAtMs:t}=e;if(!(typeof n!="string"||n==="")&&!(typeof t!="number"||!Number.isFinite(t)))return{version:n,seenAtMs:t}}function Vn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Cr(e,n){return n!==void 0?{[e]:n}:{}}function Qn(e,n){return e===void 0?void 0:e[n]}function hd(e,n){if(e===void 0)return Ct;let t;try{t=JSON.parse(e)}catch{return Ct}if(!yn(t)||t.v!==1)return Ct;let r=yn(t.pepDecisions)?t.pepDecisions:{},o={};if(yn(t.projects))for(let[c,u]of Object.entries(t.projects)){if(!yn(u))continue;let p=gd(u[n]),l=Vn(u.lastUploadAtMs);o[c]={...Cr(n,p),...l!==void 0?{lastUploadAtMs:l}:{},dropped:us(u.dropped)}}let s=yn(t.lastError)?t.lastError:void 0,i=Vn(s?.atMs),a=gd(t[n]),d=Vn(t.lastUploadAtMs);return{v:1,...d!==void 0?{lastUploadAtMs:d}:{},...i!==void 0&&typeof s?.message=="string"?{lastError:{atMs:i,message:s.message}}:{},dropped:us(t.dropped),unknownKinds:us(t.unknownKinds),pepDecisions:{seen:Vn(r.seen)??0,filledToolUseId:Vn(r.filledToolUseId)??0,orphaned:Vn(r.orphaned)??0},...Cr(n,a),projects:o}}function Sd(e){return`${JSON.stringify(e)}
|
|
23
|
+
`}function Ot(e,n,t,r=O){try{return hd(r.readFile(v(e,n).senderState).toString("utf8"),t)}catch{return Ct}}function fs(e,n,t,r=O){r.writeFileAtomic(v(e,n).senderState,Sd(t),N)}function ls(e,n){let t={...e};for(let[r,o]of Object.entries(n))t[r]=(t[r]??0)+o;return t}function md(e,n){return n===void 0?e:e===void 0||n.seenAtMs>=e.seenAtMs?n:e}function yd(e,n){return n===void 0?e:e===void 0?n:Math.max(e,n)}function gs(e,n,t){let r={...e.projects};for(let[a,d]of Object.entries(n.projects)){let c=r[a]??{},u=md(Qn(c,t),Qn(d,t)),p=yd(c.lastUploadAtMs,d.lastUploadAtMs);r[a]={...Cr(t,u),...p!==void 0?{lastUploadAtMs:p}:{},dropped:ls(c.dropped??{},d.dropped)}}let o=Object.values(n.projects).reduce((a,d)=>md(a,Qn(d,t)),Qn(e,t)),s=yd(e.lastUploadAtMs,n.lastUploadAtMs),i=n.lastError??e.lastError;return{v:1,...s!==void 0?{lastUploadAtMs:s}:{},...i!==void 0?{lastError:i}:{},dropped:ls(e.dropped,n.dropped),unknownKinds:ls(e.unknownKinds,n.unknownKinds),pepDecisions:{seen:e.pepDecisions.seen+n.pepDecisions.seen,filledToolUseId:e.pepDecisions.filledToolUseId+n.pepDecisions.filledToolUseId,orphaned:e.pepDecisions.orphaned+n.pepDecisions.orphaned},...Cr(t,o),projects:r}}function Rd(e,n,t,r,o=O){let s=Ot(e,n,t,o);return r===void 0?Qn(s,t):Qn(s.projects[r],t)??void 0}function Ed(e,n,t,r,o=O){let s=Ot(e,n,t,o),i=r===void 0?void 0:s.projects[r],a=i?.lastUploadAtMs??s.lastUploadAtMs,d=i!==void 0&&Object.keys(i.dropped??{}).length>0?i.dropped??{}:s.dropped,c=Object.keys(d).length>0;if(!(a===void 0&&s.lastError===void 0&&!c))return{...a!==void 0?{lastUploadAt:new Date(a).toISOString()}:{},...s.lastError!==void 0?{lastError:`${s.lastError.message} (${new Date(s.lastError.atMs).toISOString()})`}:{},...c?{dropped:d}:{}}}var Tr="cursorVersion";function Id(e,n,t=O){return Rd(e,D,Tr,n,t)}function bd(e,n,t=O){return Ed(e,D,Tr,n,t)}function kd(e){return Object.entries(e).map(([n,t])=>({key:n,value:{stringValue:t}}))}function Je(e){return{resourceSpans:(Array.isArray(e)?e:[e]).map(t=>({resource:{attributes:kd(t.resource.attributes)},scopeSpans:[{scope:{name:t.scope.name,version:t.scope.version},spans:t.spans.map(r=>{let o={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,name:r.name,kind:r.kind,startTimeUnixNano:r.startTimeUnixNano,endTimeUnixNano:r.endTimeUnixNano,attributes:kd(r.attributes)};return r.error&&(o.status={code:2}),o})}]}))}}var Fd=require("crypto");var hs=require("uuid");var Wn="user_prompt",Cd="gen_ai.completion",ge="full_command",hn="file_path",Ye="gen_ai.tool.call.result",xt=new Set([Wn,Cd,ge,hn,Ye]);function Td(e,n){return!n||e.length===0?{}:{[Wn]:e}}function _d(e,n){return!n||e.length===0?{}:{[Cd]:e}}function Od(e,n,t){if(!t)return{};let r={},o=e.command;typeof o=="string"&&o.length>0&&(r[ge]=o);let s=e.file_path??e.path??e.notebook_path;return typeof s=="string"&&s.length>0&&(r[hn]=s),n&&n.length>0&&(r[Ye]=n),r}var _r="secret-manager-output",Or=`[REDACTED:secret:${_r}]`,Mf=[/^op\s+read(\s|$)/,/^op\s+item\s+get(\s|$)/,/^aws\s+secretsmanager\s+get-secret-value(\s|$)/,/^gcloud\s+secrets\s+versions\s+access(\s|$)/,/^vault\s+read(\s|$)/,/^vault\s+kv\s+get(\s|$)/,/^az\s+keyvault\s+secret\s+show(\s|$)/],Lf=/&&|\|\||;|\|/,Uf=/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;function $f(e){let n=e.trimStart().replace(Uf,"");return Mf.some(t=>t.test(n))}function Bf(e){if(e.length===0)return!1;for(let n of e.split(Lf))if($f(n))return!0;return!1}var Gf=new Set;function xd(e,n){let t=e[n.commandKey];if(typeof t!="string"||!Bf(t))return Gf;let r=new Set;for(let o of Object.keys(e)){let s=e[o];if(!(typeof s!="string"||s.length===0)){if(n.resultKeys?.has(o)){r.add(o);continue}n.resultKeyPrefixes?.some(i=>o.startsWith(i))&&r.add(o)}}return r}var Kf={commandKey:ge,resultKeys:new Set([Ye])};function xr(e,n,t={}){let r={},o={},s=0;if(n===null){for(let[a,d]of Object.entries(e))r[a]=d;return{attributes:r,redactedCount:0,byType:{}}}let i=xd(t.correlationCommand===void 0?e:{...e,[ge]:t.correlationCommand},Kf);for(let[a,d]of Object.entries(e)){if(typeof d!="string"||d.length===0){r[a]=d;continue}if(i.has(a)){r[a]=Or,o[_r]=(o[_r]??0)+1,s+=1;continue}if(!xt.has(a)){r[a]=d;continue}let c=Xa(d,n);if(r[a]=c.text,c.total>0){s+=c.total;for(let u in c.redactions)o[u]=(o[u]??0)+c.redactions[u]}}return{attributes:r,redactedCount:s,byType:o}}var Ar=8192;var Ad=16*1024,wr=Ar+Ad;function ms(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hf(e){return e.length>Ar?e.slice(0,Ar):e}function wd(e){return e.length>wr?e.slice(0,wr+1):e}function Vf(e,n){let t=0,r=Math.min(e.length,n.length);for(;t<r&&e.charCodeAt(e.length-1-t)===n.charCodeAt(n.length-1-t);)t+=1;return t}function Pd(e,n){let t={},r=new Map;for(let[a,d]of Object.entries(e))if(xt.has(a)&&d.length>wr){let c=d.slice(0,wr);t[a]=c,r.set(a,c)}else t[a]=d;let o=e[ge],s=xr(t,n,o===void 0?{}:{correlationCommand:o}),i={};for(let[a,d]of Object.entries(s.attributes)){if(!xt.has(a)){i[a]=d;continue}let c=r.get(a),u=d;if(c!==void 0&&u!==Or){let p=Math.min(Ad,Vf(c,u));u=u.slice(0,u.length-p)}i[a]=Hf(u)}return{attributes:i,redactedCount:s.redactedCount,byType:s.byType}}function ys(e,n){if(n!==void 0)return e?.startsWith(n)?e:n}function Qf(e,n){if(typeof e.event!="string"||!n.has(e.event)||typeof e.capturedAtMs!="number"||!Number.isFinite(e.capturedAtMs))return!1;let t=e.tool;return t===void 0?!0:ms(t)&&typeof t.vendorTool=="string"&&typeof t.argsHash=="string"&&ms(t.call)&&typeof t.call.tool=="string"}function Wf(e){return typeof e.decidedAtMs=="number"&&Number.isFinite(e.decidedAtMs)&&typeof e.decisionMs=="number"&&typeof e.hookEvent=="string"&&typeof e.vendorTool=="string"&&typeof e.argsHash=="string"&&typeof e.verdict=="string"&&typeof e.blocked=="boolean"}function vd(e,n){let t;try{t=JSON.parse(e)}catch{return}if(!ms(t))return;let r=t,o=()=>({kind:"unknown",rawKind:typeof r.kind=="string"?r.kind:String(r.kind),rawV:r.v});return r.v!==1?o():r.kind==="capture"&&Qf(r,n)||r.kind==="pep-decision"&&Wf(r)?r:o()}function jd(e,n){return(0,hs.v5)(`${e}:${n}`,pt)}var Md="agenttrail.org.id",Ld="agenttrail.project.id",Ud="agenttrail.agent.id",$d="agenttrail.developer.id",Bd="agenttrail.project",Gd="gen_ai.conversation.id",Kd="session.id",Hd="gen_ai.request.model",Vd="llm_request.context",Qd="tool_name",Wd="gen_ai.tool.name",Jd="gen_ai.tool.call.id",Ss="gen_ai.usage.input_tokens",Rs="gen_ai.usage.output_tokens",Es="gen_ai.usage.cache_read.input_tokens",Is="gen_ai.usage.cache_creation.input_tokens",Jf="interaction",Dd=1,Yf=3,qf=Object.freeze({[Md]:"metadata",[Ld]:"metadata",[Ud]:"metadata",[ut]:"metadata",[$d]:"metadata",[Bd]:"metadata",[lt]:"metadata",[Ve]:"metadata",[Qe]:"metadata",[Io]:"metadata",[Gd]:"metadata",[Kd]:"metadata",[Co]:"metadata",[Hd]:"metadata",[Vd]:"metadata",[bo]:"metadata",[Ss]:"metadata",[Rs]:"metadata",[Es]:"metadata",[Is]:"metadata",[Qd]:"metadata",[Wd]:"metadata",[Ro]:"metadata",[Jd]:"metadata",[To]:"metadata",[_o]:"metadata",[ko]:"metadata",[Wn]:"content",[ge]:"content",[hn]:"content",[Ye]:"content"});function Pr(e,n,t){let r=t==="import"?`import:${n.conversationId}:${n.importKey??n.importOrdinal??0}`:`live:${n.conversationId}:${n.generationId??""}`;return(0,hs.v5)(r,e).replace(/-/g,"")}function Jn(e,n){let t=typeof n=="string"?n:`tool:${n.tool}`;return(0,Fd.createHash)("sha256").update(`${e}:${t}`).digest("hex").slice(0,16)}function bs(e){return e.correlationId??`ordinal:${e.ordinal}`}function ks(e,n){return Jn(e,{tool:bs(n)})}function Nd(e){if(!Number.isFinite(e)||e<=0)return"0";let n=Math.floor(e),t=Math.round((e-n)*1e6);return(BigInt(n)*1000000n+BigInt(t)).toString()}function zf(e,n,t){let r={...n};if(e.call.tool!==""&&(r[Qd]=e.call.tool,r[Wd]=e.call.tool),e.vendorTool!==""&&(r[Ro]=e.vendorTool),e.correlationId!==null&&(r[Jd]=e.correlationId),e.mcpServerUnknown===!0&&(r[To]="true"),e.pepBlocked===!0&&e.failed&&(r[_o]="true"),e.subagentConversationId!==void 0&&(r[ko]=e.subagentConversationId),t){let{full_command:o,file_path:s}=e.call.args;o!==void 0&&(r[ge]=o),s!==void 0&&(r[hn]=s),e.output!==void 0&&(r[Ye]=e.output)}return r}function Xf(e,n,t){let r=t.mode==="import",o=Pr(e.traceNamespace,n,t.mode),s=Jn(o,"root"),i=n.endMs,a=t.include,d=!r&&n.usage!==null&&n.model!==null,c={};n.conversationId!==""&&(c[Gd]=n.conversationId,c[Kd]=n.conversationId);let u=r?{[Io]:"true",[Ve]:cn,...t.batchId?{[Qe]:t.batchId}:{}}:{},p=[];if(i!==null&&(a?.root??!0)){let l=n.closedBy??(r?"import":void 0);p.push({spanId:s,parentSpanId:"",name:e.rootSpanName,kind:Dd,startMs:n.startMs,endMs:i,attributes:{...c,...l!==void 0?{[Co]:l}:{},...t.captureContent&&n.prompt?{[Wn]:n.prompt}:{},...d?{}:{[lt]:"false"},...u},error:n.status==="error"})}!r&&i!==null&&n.model!==null&&(a?.model??!0)&&p.push({spanId:Jn(o,"model"),parentSpanId:s,name:`chat ${n.model.name}`,kind:Yf,startMs:n.startMs,endMs:n.model.endMs,attributes:{...c,[Hd]:n.model.name,[Vd]:Jf,[bo]:"true",...d&&n.usage!==null?e.usageAttributes(n.usage):{[lt]:"false"}},error:!1});for(let l of n.tools){let f=l.endMs??i;f!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(bs(l))||p.push({spanId:ks(o,l),parentSpanId:l.parentTaskKey===void 0?s:Jn(o,{tool:l.parentTaskKey}),name:l.call.tool===""?"execute_tool":`execute_tool ${l.call.tool}`,kind:Dd,startMs:l.startMs,endMs:f,attributes:{...zf(l,c,t.captureContent),...u},error:l.failed}))}return p}function Yd(e,n,t,r){let o=t.mode==="import",s=Pr(e.traceNamespace,n,t.mode),i=t.resolvedScrubbers??null,a=0,d={},c=Xf(e,n,t).map(p=>{let l=Pd(p.attributes,i);a+=l.redactedCount;for(let[m,g]of Object.entries(l.byType))d[m]=(d[m]??0)+g;let f=l.attributes;return{traceId:s,spanId:p.spanId,parentSpanId:p.parentSpanId,name:p.name,kind:p.kind,startTimeUnixNano:Nd(p.startMs),endTimeUnixNano:Nd(Math.max(p.endMs,p.startMs)),attributes:f,error:p.error}});return{resource:{attributes:{[Md]:t.orgId,[Ld]:t.project.projectId,[Ud]:r,[ut]:e.vendor,...t.project.developerId?{[$d]:t.project.developerId}:{},...t.project.projectLabel?{[Bd]:t.project.projectLabel}:{},[lt]:o?"false":"true",...o?{[Ve]:cn}:{},...o&&t.batchId?{[Qe]:t.batchId}:{}}},scope:{name:e.scopeName,version:t.scopeVersion},spans:c,redactions:{total:a,byType:d}}}function Ts(e){return jd(e,Ir)}var Zf="agenttrail-cursor";function _s(e,n){return Pr(zd.traceNamespace,{conversationId:e.conversationId,generationId:e.generationId,...e.importOrdinal!==void 0?{importOrdinal:e.importOrdinal}:{}},n)}function eg(e){if(!("importKey"in e))return e;let{importKey:n,...t}=e;return t}function Os(e,n){return Jn(e,n)}function ng(e,n){return ks(e,n)}var Cs=new Set(["subagentStart","subagentStop"]),tg=new Set(["postToolUse","postToolUseFailure","afterFileEdit"]),rg=Object.freeze({conversationId:"",generationId:null,startMs:0,endMs:null,model:null,usage:null,tools:Object.freeze([])});function og(e){if(e===null||typeof e!="object")return!1;let n=e;return n.kind==="capture"&&typeof n.capturedAtMs=="number"&&Number.isFinite(n.capturedAtMs)}function xs(e){let n=e.tool?.durationMs;return n!==void 0&&Number.isFinite(n)&&n>=0?e.capturedAtMs-n:e.capturedAtMs}function sg(e,n){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(n(r))return r}}function ig(e){let n=e.find(t=>t.event==="beforeSubmitPrompt"&&t.conversationId!==null);if(n?.conversationId)return n.conversationId;for(let t of e){if(!Cs.has(t.event))continue;let r=t.subagent?.parentConversationId??t.conversationId;if(r)return r}for(let t of["stop","afterAgentResponse"]){let r=sg(e,o=>o.event===t&&o.conversationId!==null);if(r?.conversationId)return r.conversationId}return e.find(t=>t.conversationId!==null)?.conversationId??""}function ag(e){switch(e){case"completed":return"success";case"aborted":return"aborted";case"error":return"error";default:return"unknown"}}function dg(e,n,t){let r=e.tool;if(r?.mcpServerUnknown!==!0)return;let o=n.filter(a=>!t.has(a)&&a.tool?.vendorTool===r.vendorTool&&a.conversationId===e.conversationId&&a.generationId===e.generationId&&a.capturedAtMs<=e.capturedAtMs),s=o.filter(a=>r.durationMs!==void 0&&a.tool?.durationMs===r.durationMs),i;for(let a of s.length>0?s:o)(i===void 0||a.capturedAtMs>=i.capturedAtMs)&&(i=a);return i!==void 0&&t.add(i),i}function cg(e,n,t,r){let o=e.tool,s=t?.tool,i=s===void 0?o.call:{tool:s.call.tool,args:s.call.args.full_command!==void 0?s.call.args:o.call.args},a=e.content?.output??e.content?.error;return{ordinal:n,vendorTool:o.vendorTool,call:i,correlationId:o.correlationId,startMs:xs(e),endMs:e.capturedAtMs,failed:o.failed===!0,...a!==void 0?{output:a}:{},...s===void 0&&o.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...o.pepBlocked===!0?{pepBlocked:!0}:{},isTask:!1,...r(e.conversationId)?{}:{foreignConversationId:e.conversationId},placedAtMs:e.capturedAtMs}}function ug(e,n,t){let{post:r,start:o,stop:s}=e,i=o??s,a=o?.capturedAtMs??(r!==void 0?xs(r):s?.capturedAtMs??0),d=i?.subagent?.parentConversationId??i?.conversationId??null,c=r?.content?.output??r?.content?.error;return{ordinal:n,vendorTool:r?.tool?.vendorTool??"Task",call:r?.tool?.call??{tool:"Task",args:{}},correlationId:e.key,startMs:a,endMs:s?.capturedAtMs??r?.capturedAtMs??null,failed:r?.tool?.failed===!0||s?.status==="error",...c!==void 0?{output:c}:{},isTask:!0,...t(d)?{}:{foreignConversationId:d},placedAtMs:a}}function lg(e,n){let t;for(let r of n)r.ordinal>=e.ordinal||r.correlationId===null||r.startMs>e.placedAtMs||r.endMs!==null&&e.placedAtMs>r.endMs||(t===void 0||r.startMs>=t.startMs)&&(t=r);return t}function qd(e,n){let t=e.map((y,S)=>({record:y,index:S})).filter(({record:y})=>og(y)).sort((y,S)=>y.record.capturedAtMs-S.record.capturedAtMs||y.index-S.index).map(({record:y})=>y);if(t.length===0)return rg;let r=ig(t),o=y=>y===null||y===r,s=t.find(y=>o(y.conversationId)&&!Cs.has(y.event)&&y.generationId!==null)?.generationId??null,i=_s({conversationId:r,generationId:s},"live"),a=y=>{let S=n?.get(y);return typeof S=="number"&&Number.isFinite(S)?S:void 0},d=[],c=new Map,u=y=>{let S=y===null?void 0:c.get(y);if(S!==void 0)return S;let T={key:y};return d.push(T),y!==null&&c.set(y,T),T};for(let y of t)if(tg.has(y.event)&&y.tool!==void 0){let S=u(y.tool.correlationId);S.post??=y}else if(Cs.has(y.event)){let S=y.subagent?.subagentId??null;if(S===null)continue;let T=u(S);y.event==="subagentStart"?T.start??=y:T.stop=y}let p=t.filter(y=>y.event==="afterMCPExecution"&&y.tool!==void 0),l=new Set,f=d.map((y,S)=>{let T=y.start!==void 0||y.stop!==void 0?ug(y,S,o):cg(y.post,S,dg(y.post,p,l),o),C=a(ng(i,T));return C===void 0?T:{...T,startMs:C}}),m=f.filter(y=>y.isTask),g=f.map(y=>{let S=y.foreignConversationId===void 0?void 0:lg(y,m);return{vendorTool:y.vendorTool,call:y.call,correlationId:y.correlationId,ordinal:y.ordinal,startMs:y.startMs,endMs:y.endMs,failed:y.failed,...y.output!==void 0?{output:y.output}:{},...y.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...y.pepBlocked===!0?{pepBlocked:!0}:{},...y.foreignConversationId!==void 0?{subagentConversationId:y.foreignConversationId}:{},...S?.correlationId?{parentTaskKey:S.correlationId}:{}}}),h,R,k,E=Number.POSITIVE_INFINITY;for(let y of t)E=Math.min(E,xs(y)),o(y.conversationId)&&(y.event==="beforeSubmitPrompt"?h??=y.content?.prompt:y.event==="afterAgentResponse"?R=y:y.event==="stop"&&(k=y));let b=R?.model??k?.model??null,I=R?.capturedAtMs??k?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(Os(i,"root"))??E,endMs:k?.capturedAtMs??null,...k!==void 0?{closedBy:"stop",status:ag(k.status)}:{},...h!==void 0?{prompt:h}:{},model:b!==null&&I!==void 0?{name:b,endMs:I}:null,usage:k?.usage??null,tools:g}}function vr(e){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):0}function pg(e){let n=vr(e.cacheReadTokens),t=vr(e.cacheWriteTokens);return{[Ss]:String(Math.max(0,vr(e.inputTokens)-n-t)),[Rs]:String(vr(e.outputTokens)),[Es]:String(n),[Is]:String(t)}}var zd={vendor:Ir,scopeName:Zf,traceNamespace:wo,rootSpanName:"invoke_agent Cursor",usageAttributes:pg};function Dr(e,n){return Yd(zd,eg(e),n,Ts(n.orgId))}var ec=600*1e3,At=600*1e3,As=1440*60*1e3,fg={idleSweepMs:ec,orphanWindowMs:At,retentionMs:As};function Fe(e,n){return`${e}\0${n??""}`}function gg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nc(e){let n;try{n=JSON.parse(e)}catch{return}if(!(!gg(n)||n.v!==1)&&!(typeof n.traceId!="string"||typeof n.projectKey!="string")&&typeof n.conversationId=="string"&&!(typeof n.lastRecordAtMs!="number"||!Number.isFinite(n.lastRecordAtMs))&&!(!Array.isArray(n.files)||!n.files.every(t=>typeof t=="string")))return n}function tc(e){return`${JSON.stringify(e)}
|
|
24
|
+
`}function ws(e,n,t=O){let r=v(e,n).turns,o;try{o=t.readdir(r)}catch{return{states:[],unreadable:[]}}let s=[],i=[];for(let a of o){if(!a.endsWith(".json"))continue;let d=`${r}/${a}`,c;try{c=nc(t.readFile(d).toString("utf8"))}catch{c=void 0}c===void 0?i.push(d):s.push(c)}return{states:s,unreadable:i}}function Yn(e,n,t,r=O){r.writeFileAtomic(cr(e,n,t.traceId),tc(t),N)}function Nr(e,n,t,r=O){r.remove(cr(e,n,t))}function rc(e){let n=/^(\d+)-(\d+)-(\d+)\.json$/.exec(e);if(n!==null)return{atMs:Number(n[1]),pid:Number(n[2]),seq:Number(n[3])}}function oc(e){return[...e].sort((n,t)=>n.atMs-t.atMs||n.pid-t.pid||n.seq-t.seq||n.name.localeCompare(t.name))}function Fr(e,n,t=O,r,o=""){let s;try{s=t.readdir(e)}catch{return{files:[],other:[]}}let i=[],a=[];for(let d of s){let c=rc(d);if(c===void 0){a.push(d);continue}let u=o===""?d:`${o}/${d}`,p=r?.get(u);if(p!==void 0){i.push(p);continue}let l;try{l=n(t.readFile(`${e}/${d}`).toString("utf8"))}catch{l=void 0}let f={name:d,...c,entry:l};r?.set(u,f),i.push(f)}return{files:oc(i),other:a}}function mg(e,n,t,r,o){return{v:1,traceId:n,projectKey:e,conversationId:t,generationId:r,files:[],starts:{},sent:{},lastRecordAtMs:o}}function Sn(e){return e.records.reduce((n,t)=>Math.max(n,t.capturedAtMs),e.loaded.lastRecordAtMs)}function sc(e,n){return e.records.find(t=>{if(!n.closesTurn(t))return!1;let r=n.turnOf(t);return r.conversationId!==null&&Fe(r.conversationId,r.generationId)===e.key})}function Xd(e,n,t){let r=sc(e,t);if(r!==void 0&&r.capturedAtMs<n)return!1;let o=e.loaded.closed;return o!==void 0&&o.atMs<n&&r===void 0?Sn(e)>o.atMs:!0}function Ps(e){let n=e.rules,t={...fg,...e.limits},r=[],o=new Map,s=new Set,i=[],a=[],d=[],c=new Map(e.files.map(g=>[g.name,g]));for(let g of e.states){if(g.projectKey!==e.projectKey)continue;let h={key:Fe(g.conversationId,g.generationId),loaded:g,records:[],decisions:[],files:[]};r.push(h),o.set(h.key,h)}let u=(g,h)=>{s.add(h.name),g.files.push(h.name);let R=h.entry;R!==void 0&&(R.kind==="capture"?g.records.push(R):R.kind==="pep-decision"&&g.decisions.push(R))};for(let g of r)for(let h of g.loaded.files){let R=c.get(h);R!==void 0&&u(g,R)}for(let g of r)for(let h of g.records)Zd(d,g,h,n);let p=(g,h)=>r.filter(R=>R.loaded.conversationId===g&&Xd(R,h,n)).sort((R,k)=>Sn(R)-Sn(k)).at(-1),l=g=>d.filter(h=>h.startAtMs<=g&&(h.stopAtMs===void 0||g<=h.stopAtMs)).sort((h,R)=>h.startAtMs-R.startAtMs).at(-1),f=(g,h)=>{let R=r.filter(k=>Xd(k,g.atMs,n)&&Math.abs(g.atMs-Sn(k))<=t.orphanWindowMs).sort((k,E)=>Sn(k)-Sn(E)).at(-1);if(R!==void 0){u(R,g);return}e.nowMs-g.atMs>=t.orphanWindowMs?a.push({file:g,reason:h}):i.push(g)};for(let g of e.files){if(s.has(g.name))continue;let h=g.entry;if(h===void 0){a.push({file:g,reason:"unreadable"});continue}if(h.kind==="unknown"){e.nowMs-g.atMs>=t.orphanWindowMs?a.push({file:g,reason:"unknown-kind"}):i.push(g);continue}if(h.kind==="pep-decision"){let b=n.decisionTurnOf(h),I=b.conversationId===null?void 0:o.get(Fe(b.conversationId,b.generationId));I!==void 0?u(I,g):e.nowMs-g.atMs>=t.orphanWindowMs?a.push({file:g,reason:"decision-orphan"}):i.push(g);continue}let R=h,k=n.subagentOf(R);if(k!==void 0){let b=k.parentConversationId,I=b===null?void 0:p(b,R.capturedAtMs);if(I===void 0){f(g,"orphan");continue}u(I,g),Zd(d,I,R,n);continue}let E=n.turnOf(R);if(E.conversationId!==null){let b=o.get(Fe(E.conversationId,E.generationId));if(b!==void 0){u(b,g);continue}if(n.opensTurn(R)){let y=e.traceIdFor({conversationId:E.conversationId,generationId:E.generationId}),S={key:Fe(E.conversationId,E.generationId),loaded:mg(e.projectKey,y,E.conversationId,E.generationId,R.capturedAtMs),records:[],decisions:[],files:[]};r.push(S),o.set(S.key,S),u(S,g);continue}let I=l(R.capturedAtMs);if(I!==void 0){u(I.builder,g);continue}}f(g,"orphan")}return{turns:r.filter(g=>g.files.length>0||g.loaded.files.length>0).map(g=>yg(g,e.nowMs,t,n)),pending:i,dropped:a,expired:[]}}function Zd(e,n,t,r){let o=r.subagentOf(t);if(o===void 0)return;if(o.edge==="start"){e.push({builder:n,subagentId:o.subagentId,startAtMs:t.capturedAtMs});return}let s=e.find(i=>i.builder===n&&i.subagentId===o.subagentId);s!==void 0&&(s.stopAtMs=t.capturedAtMs)}function yg(e,n,t,r){let o=[...e.records].sort((c,u)=>c.capturedAtMs-u.capturedAtMs),s=Sn(e),i=sc(e,r),a;i!==void 0?a={atMs:i.capturedAtMs,by:"stop"}:n-s>=t.idleSweepMs?a={atMs:s,by:"idle-sweep"}:e.loaded.closed!==void 0&&s<=e.loaded.closed.atMs&&(a=e.loaded.closed);let d={...e.loaded,files:[...e.files].sort(),lastRecordAtMs:s,...a!==void 0?{closed:a}:{}};return a===void 0&&"closed"in d&&delete d.closed,{state:d,records:o,decisions:e.decisions,files:d.files}}function vs(e,n,t=As){return e.filter(r=>r.files.length===0&&r.closed!==void 0&&n-r.lastRecordAtMs>=t)}var Fs=require("crypto");var hg=require("crypto"),Ds=8192;function Ns(e){return e.length>Ds?e.slice(0,Ds):e}function ic(e){try{return JSON.stringify(e)??""}catch{return""}}function jr(e){return Ns(Mr(e))}function Mr(e){if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return n!==null&&typeof n=="object"?ic(n):e}return e!==null&&typeof e=="object"?ic(e):"{}"}var js=32;function Ms(e,n,t=O){let r;try{r=t.readFile(v(e,n).queueKey)}catch{return}return r.length===js?new Uint8Array(r):void 0}function ac(e,n,t=O,r=Fs.randomBytes){return Ms(e,n,t)!==void 0?"kept":(t.writeFileAtomic(v(e,n).queueKey,r(js),N),"created")}var Rg=new Set(["preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeMCPExecution","afterMCPExecution","beforeReadFile","beforeTabFileRead","afterFileEdit","subagentStart","beforeSubmitPrompt","stop","afterAgentResponse","subagentStop","sessionEnd","sessionStart","afterAgentThought","workspaceOpen"]);function Ls(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{cursor_version:n,hook_event_name:t}=e;return typeof n=="string"?!0:typeof t=="string"&&Rg.has(t)}var $s="MCP:";var Ig=new Set(["GetDynamicTools","TodoWrite","CreatePlan","AskQuestion","SwitchMode","Await","Task","ReadLints","SemanticSearch","WebFetch","UpdateCurrentStep"]),bg=new Map([["Read","Read"],["StrReplace","Edit"],["Delete","Delete"]]);function pc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dc(e){return typeof e=="string"&&e!==""?e:void 0}function kg(e){return e.length>Eo?e.slice(0,Eo):e}function Cg(e){return/^(?:[\\/]|[A-Za-z]:[\\/])/.test(e)}function Tg(e,n){return`${e.replace(/[\\/]+$/,"")}/${n}`}function cc(e,n,t="Grep"){let r=dc(e),o=dc(n);return o!==void 0&&(r===void 0||Cg(o))?[{tool:t,args:{file_path:o}}]:r===void 0?[{tool:t,args:{}}]:o===void 0?[{tool:t,args:{file_path:r}}]:[{tool:t,args:{file_path:Tg(r,o)}},{tool:t,args:{file_path:r}}]}function uc(e,n){return typeof n=="string"?{tool:e,args:{full_command:Ns(n)}}:{tool:e,args:{}}}function Us(e,n){return typeof n=="string"?{tool:e,args:{file_path:n}}:{tool:e,args:{}}}function _g(e){return[Us("Write",e),Us("Edit",e)]}function Bs(e){let n=kg(e.name),t=pc(e.input)?e.input:{},r=i=>({kind:"action",vendorTool:n,candidates:i}),o=(i,a)=>{let d=`mcp__${typeof i=="string"?i:""}__${typeof a=="string"?a:""}`;return r([{tool:d,args:{full_command:jr(t.arguments)}}])};switch(e.name){case"Shell":return r([uc("Bash",t.command)]);case"WebSearch":return r([uc("WebSearch",t.search_term)]);case"Grep":return r(cc(t.path,t.glob));case"Glob":return r(cc(t.target_directory,t.glob_pattern,"Glob"));case"CallMcpTool":return o(t.server,t.toolName);case"CallDynamicTool":return o(t.namespace,t.toolName);case"Write":return r(_g(t.path))}let s=bg.get(e.name);return s!==void 0?r([Us(s,t.path)]):Ig.has(e.name)?{kind:"not-action",vendorTool:n}:{kind:"unmapped",vendorTool:n}}function fc(e){let n=pc(e.input)?e.input:{},t=r=>typeof r=="string"?r:void 0;switch(e.name){case"Shell":return t(n.command);case"WebSearch":return t(n.search_term);case"CallMcpTool":case"CallDynamicTool":return Mr(n.arguments)}}function gc(e,n=O){return Ms(e,D,n)}function mc(e,n=O,t){return ac(e,D,n,t)}var ce=Object.freeze(["beforeSubmitPrompt","postToolUse","postToolUseFailure","afterMCPExecution","afterAgentResponse","afterFileEdit","subagentStart","subagentStop","stop"]);var xg=new Set(ce);function Lr(e){return vd(e,xg)}function yc(e){return{conversationId:e.conversationId,generationId:e.generationId}}function hc(e){return{conversationId:e.conversationId,generationId:e.generationId}}function Sc(e){return e.event==="beforeSubmitPrompt"}function Rc(e){return e.event==="stop"}function Ec(e){if(!(e.event!=="subagentStart"&&e.event!=="subagentStop"))return{edge:e.event==="subagentStart"?"start":"stop",subagentId:e.subagent?.subagentId??null,parentConversationId:e.subagent?.parentConversationId??e.conversationId}}function Ic(e){return e==="postToolUse"||e==="postToolUseFailure"}function bc(e,n=O,t,r=""){return Fr(e,Lr,n,t,r)}var Ag="/v1/conversations/known";function wg(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}async function Ur(e,n,t={}){if(e.length===0)return{known:new Set,ok:!0};let r=t.fetch??globalThis.fetch,o=`${n.endpoint.replace(/\/$/,"")}${Ag}`,s=new Set;for(let i of wg(e,1e3)){let a;try{a=await r(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n.token}`},body:JSON.stringify({conversation_ids:i})})}catch{return{known:new Set,ok:!1}}if(!a.ok)return{known:new Set,ok:!1};let d;try{d=JSON.parse(await a.text())}catch{return{known:new Set,ok:!1}}if(Array.isArray(d.known))for(let c of d.known)typeof c=="string"&&s.add(c)}return{known:s,ok:!0}}var Pg=e=>new Promise(n=>setTimeout(n,e));function vg(e){let n=e.get("retry-after");if(!n)return null;let t=Number(n);return Number.isFinite(t)&&t>=0?t*1e3:null}async function qn(e,n,t={}){if(n.dryRun)return{status:"skipped",attempts:0};let r=t.fetch??globalThis.fetch,o=t.sleep??Pg,s=n.maxRetries??5,i=n.baseBackoffMs??500,a=`${n.endpoint.replace(/\/$/,"")}/v1/traces`,d=JSON.stringify(e),c=0,u="",p;for(;c<=s;){c++;let l;try{l=await r(a,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n.token}`},body:d})}catch(m){if(u=m.message,p=void 0,c>s)break;await o(kc(i,c,null));continue}if(p=l.status,l.ok)return{status:"ok",httpStatus:l.status,attempts:c};if(!(l.status===429||l.status>=500&&l.status<=599)||c>s){u=`HTTP ${l.status}: ${(await l.text().catch(()=>"")).slice(0,200)}`;break}await o(kc(i,c,vg(l.headers)))}return{status:"failed",httpStatus:p,attempts:c,error:u}}function kc(e,n,t){if(t!==null)return t;let r=e*2**(n-1),o=Math.floor(Math.random()*e);return Math.min(r+o,3e4)}async function wt(e,n,t){let r=new Array(e.length),o=Math.max(1,Math.min(n,e.length||1)),s=0;async function i(){for(;;){let a=s++;if(a>=e.length)return;r[a]=await t(e[a],a)}}return await Promise.all(Array.from({length:o},()=>i())),r}var xc=require("crypto");var Cc=require("crypto"),zn=require("fs"),$r=require("path");var Dg=448;function Tc(e){return(0,$r.join)(e,".agenttrail","backfill-state.json")}function Gs(e,n={}){let t=n.readFile??(r=>(0,zn.readFileSync)(r,"utf8"));try{let r=JSON.parse(t(Tc(e)));return r&&typeof r=="object"&&r.version===2&&r.sessions&&typeof r.sessions=="object"?{version:2,sessions:r.sessions}:{version:2,sessions:{}}}catch{return{version:2,sessions:{}}}}function _c(e,n,t={}){let r=Tc(e),o=t.writeFile??((i,a,d)=>U(i,a,d!==void 0?{mode:d}:{}));return(t.mkdir??((i,a)=>(0,zn.mkdirSync)(i,{recursive:!0,mode:a})))((0,$r.dirname)(r),Dg),o(r,`${JSON.stringify(n,null,2)}
|
|
25
|
+
`,384),r}function Rn(e,n,t){return{version:2,sessions:{...e.sessions,[n]:{...t,updatedAt:t.updatedAt??new Date().toISOString()}}}}function Pt(e,n,t){let r=e.sessions[n];return r?!(r.status==="done"&&r.sourceHash===t):!0}function Oc(e){return new Promise((n,t)=>{let r=(0,Cc.createHash)("sha256"),o=(0,zn.createReadStream)(e);o.on("data",s=>r.update(s)),o.on("error",t),o.on("end",()=>n(r.digest("hex")))})}var Ks=Object.freeze({version:2,sessions:Object.freeze({})});function Ac(e){return F(e).backfillState}function Hs(e,n=O){let t=Ac(e);try{if(!n.exists(t))return Ks;let r=JSON.parse(n.readFile(t).toString("utf8"));return r!==null&&typeof r=="object"&&r.version===2&&r.sessions!==null&&typeof r.sessions=="object"?{version:2,sessions:r.sessions}:Ks}catch{return Ks}}function wc(e,n,t=O){let r=Ac(e);return t.writeFileAtomic(r,`${JSON.stringify(n,null,2)}
|
|
26
|
+
`,N),r}function Pc(e){let n=(0,xc.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)}
|
|
27
|
+
`);return n.digest("hex")}var Gr=require("fs"),qe=require("path");var Nc=require("fs"),Fc=require("readline"),vt=class extends Error{constructor(t,r){super(t);this.sessionId=r;this.name="QuarantineError"}sessionId},Dt={async*readLines(e){let n=(0,Fc.createInterface)({input:(0,Nc.createReadStream)(e,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY});try{for await(let t of n)yield t}finally{n.close()}}};function ke(e){return typeof e=="string"&&e.length>0?e:null}function vc(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[]}function Dc(e){return e.filter(n=>n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
|
|
28
|
+
`)}function Ng(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&"text"in n?String(n.text):"").join(`
|
|
29
|
+
`):e==null?"":JSON.stringify(e)}async function jc(e,n,t=Dt){let r=null,o=null,s=null,i=null,a=null,d=null,c=0,u=[],p=[],l=new Map,f="";for await(let R of t.readLines(e)){let k=R.trim();if(k.length===0)continue;let E;try{E=JSON.parse(k)}catch{c++;continue}if(E===null||typeof E!="object"){c++;continue}r??=ke(E.sessionId),o??=ke(E.version),s??=ke(E.gitBranch),i??=ke(E.cwd);let b=ke(E.timestamp),I=ke(E.uuid)??"",y=E.isSidechain===!0,S=E.type;if(b&&(S==="user"||S==="assistant")&&(a??=b,d=b),S==="assistant"&&E.message){let T=vc(E.message.content),C=[];for(let _ of T)_.type==="tool_use"&&ke(_.id)&&ke(_.name)&&C.push({toolUseId:_.id,name:_.name,input:_.input??{}});u.push({messageUuid:I,timestamp:b??d??"",model:ke(E.message.model)??"",usage:E.message.usage??{},text:Dc(T),toolUses:C,isSidechain:y,promptUuid:f})}else if(S==="user"&&E.message){let T=vc(E.message.content),C=!1;for(let _ of T)_.type==="tool_result"&&ke(_.tool_use_id)&&(C=!0,l.set(_.tool_use_id,{toolUseId:_.tool_use_id,isError:_.is_error===!0,content:Ng(_.content),timestamp:b??d??""}));if(!C){let _=Dc(T);_.length>0&&(p.push({messageUuid:I,timestamp:b??"",text:_,isSidechain:y}),y||(f=I))}}}let m=r??n;if(u.length===0&&p.length===0)throw new vt(`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 Fg="agent-transcripts",Mc="subagents";function jg(e){return[e.root,...(e.subfolders??[]).map(t=>t.path)].map(t=>({name:mn(t),path:t,found:!1}))}function Mg(e){let n=new Map;for(let t of Object.values(e.projects)){let r=mn(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 Uc={readdir(e){return(0,Gr.readdirSync)(e).sort()},stat(e){let n=(0,Gr.statSync)(e);return{size:n.size,mtimeMs:n.mtimeMs,birthtimeMs:Number.isFinite(n.birthtimeMs)?n.birthtimeMs:0,isDirectory:()=>n.isDirectory()}},readLines(e){return Dt.readLines(e)}};function Br(e,n){try{return[...e.readdir(n)].sort()}catch{return}}function Lc(e,n){try{return e.stat(n).isDirectory()}catch{return!1}}function Lg(e,n,t,r,o){let s=(0,qe.join)(n,r),i=Br(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,qe.join)(s,`${r}.jsonl`),!1),i.includes(Mc)){let c=(0,qe.join)(s,Mc);for(let u of Br(e,c)??[])u.endsWith(".jsonl")&&d((0,qe.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 $c(e,n,t,r,o=ed(t)){let s=Mg(n);if(s!==void 0)return{kind:"collision",...s};let i=jg(e),a=new Map(i.map(f=>[f.name,f])),d={notRead:0,unreadableFiles:0},c=[],u=[],p=0,l=new Set(Br(r,o)??[]);for(let f of l)a.has(f)||(p+=1);for(let f of i){let m=(0,qe.join)(o,f.name),g=(0,qe.join)(m,Fg);if(!l.has(f.name)||!Lc(r,g)){u.push({...f,found:!1});continue}u.push({...f,found:!0});for(let h of Br(r,g)??[]){let R=(0,qe.join)(g,h);if(!Lc(r,R)){h.endsWith(".jsonl")&&(d.notRead+=1);continue}let k=Lg(r,g,f.name,h,d);k!==void 0&&c.push(k)}}return{kind:"ok",projectsRoot:o,folders:u,sessions:c,otherFolders:p,notRead:d.notRead,unreadableFiles:d.unreadableFiles}}var Hc=require("path");var Kr=require("fs"),Bc=require("os"),Ce=require("path");function Ug(e=(0,Bc.homedir)()){return(0,Ce.join)(e,".claude","projects")}var $g=40;async function Bg(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<$g&&!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 Vs(e,n){if(e===null)return!1;let t=(0,Ce.relative)(n,e);return t===""||!t.startsWith("..")&&!(0,Ce.isAbsolute)(t)}async function Qs(e=Ug(),n,t={}){let r=t.readdir??(f=>(0,Kr.readdirSync)(f)),o=t.stat??(f=>(0,Kr.statSync)(f)),s=t.lineSource??Dt,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,Ce.join)(e,f),g;try{if(!o(m).isDirectory())continue;g=r(m)}catch{continue}let h=[];for(let R of g.sort()){if(!R.endsWith(".jsonl"))continue;let k=(0,Ce.join)(m,R),E=0,b=0;try{let y=o(k);E=y.size,b=y.mtimeMs}catch{continue}let I;try{I=await Bg(k,s)}catch{I={cwd:null,gitBranch:null,version:null,sessionId:null,messageCount:0}}if(i&&!Vs(I.cwd,n)){I.cwd===null?d++:a++;continue}h.push({sessionId:I.sessionId??(0,Ce.basename)(R,".jsonl"),file:k,project:f,cwd:I.cwd,gitBranch:I.gitBranch,version:I.version,sizeBytes:E,modifiedAt:new Date(b).toISOString(),messageCount:I.messageCount})}h.length>0&&(p.push({project:f,sessions:h}),l+=h.length)}return c(p,l)}var Ws={unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0};function Gc(e,n){return{unparseableLines:e.unparseableLines+n.unparseableLines,truncatedLastLines:e.truncatedLastLines+n.truncatedLastLines,unknownRecords:e.unknownRecords+n.unknownRecords,turnsEndedWithError:e.turnsEndedWithError+n.turnsEndedWithError}}function Hr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gg(e){return Array.isArray(e)?e:typeof e=="string"?[{type:"text",text:e}]:[]}async function Kc(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(!Hr(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"||!Hr(f)){i++;continue}if(l.role==="user"){o.push({messageUuid:"",timestamp:t.timestamp,text:"",isSidechain:t.isSidechain});continue}let m=[];Gg(f.content).forEach((g,h)=>{!Hr(g)||g.type!=="tool_use"||m.push({toolUseId:`${t.idPrefix}:${c}:${h}`,name:typeof g.name=="string"?g.name:"",input:Hr(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 Kg=1e3,MI={...Ws,notActions:0,unmapped:0};function Hg(e){let n=[],t=Bs(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,Hc.isAbsolute)(o))}function Vg(e,n){for(let t of e)for(let r of Hg(t))if(!Vs(r,n))return!0;return!1}function Qg(e,n){let t=e.args.full_command,r=ys(n,t);return r===void 0||r===t?e:{...e,args:{...e.args,full_command:wd(r)}}}function Wg(e,n,t,r){let o=e.length>0?(t-n)/e.length:0,s=[];return e.forEach((i,a)=>{let d=Bs(i);if(d.kind==="not-action"){r.notActions+=1;return}if(d.kind==="unmapped"){r.unmapped+=1;return}s.push({vendorTool:d.vendorTool,call:Qg(d.candidates[0],fc(i)),correlationId:null,ordinal:a,startMs:Math.round(n+a*o),endMs:Math.round(n+(a+1)*o),failed:!1})}),s}function Jg(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)*Kg),endMs:s}}async function Vc(e,n,t){let{conversationId:r}=e,o=[],s=Ws,i=0,a="";for(let[f,m]of e.files.entries())try{let g=await Kc(m.path,t,{timestamp:"",isSidechain:m.isSidechain,idPrefix:`${r}:${f}`});for(let h of g.turns)o.push({uses:h.toolUses});s=Gc(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(Vg(d,n))return{kind:"outside-root",conversationId:r};let c=Jg(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),R=Wg(f.uses,g,h,p);R.length!==0&&l.push({conversationId:r,generationId:null,importOrdinal:m,startMs:g,endMs:h,model:null,usage:null,tools:R})}),l.length===0?{kind:"empty",conversationId:r}:{kind:"imported",conversationId:r,turns:l,counts:{...s,...p}}}var Yg=6;function qg(e){return`bf_${e.toString(36)}_${Math.random().toString(36).slice(2,10)}`}function zg(e,n,t){let r=new Set,{files:o}=bc(Hn(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 Js(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 Qc(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 \`${H("cursor","setup")} --unregister\` in one of them, or move it, then import again.`),1}function Xg(e,n,t,r){let o=X(n,t);if(o.kind==="unreadable")return e.io.error(`error: ${F(n).projects} cannot be read. Fix or delete it, then run \`${H("cursor","setup")}\`.`),1;let s;try{s=r(e.io.cwd)}catch{s=e.io.cwd}let i=o.kind==="ok"?o.registry:ud,a=ds(i,[s],e.io.env.CURSOR_PROJECT_DIR);return a===void 0?(e.io.error(`error: ${s} is unregistered. Run \`${H("cursor","setup")}\` in the folder you open in Cursor, then import.`),1):{record:a,registry:i}}async function Zg(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=zg(t.home,e.projectKey,t.io),f=0,m=n.filter(S=>l.has(S.conversationId)?(f+=1,de(o,"queued"),r.emit?.({event:"queued-skip",conversationId:S.conversationId}),!1):!0),g=0,h=!0,R=m;if(!t.reimport){let S=await Ur(m.map(T=>T.conversationId),{endpoint:t.endpoint,token:t.token},{fetch:r.upload?.fetch});h=S.ok,S.ok&&S.known.size>0&&(R=m.filter(T=>S.known.has(T.conversationId)?(g+=1,r.emit?.({event:"dedup-skip",conversationId:T.conversationId}),!1):!0))}let k=Hs(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=Ts(t.orgId),b=gn(Ue),I=await wt(R,t.concurrency,async S=>{let T=Pc(S.files);if(t.resume&&!Pt(k,S.conversationId,T))return{session:S,sourceHash:T,kind:"skipped"};let C=await Vc(S,e.root,t.scanIO);if(C.kind!=="imported")return{session:S,sourceHash:T,kind:C.kind,error:"error"in C?C.error:""};let _=em(C.turns,{record:e,orgId:t.orgId,agentId:E,captureContent:t.captureContent,batchId:t.batchId,resolvedScrubbers:b}),j=await qn(Je(_),{endpoint:t.endpoint,token:t.token,dryRun:t.dryRun},r.upload);return{session:S,sourceHash:T,kind:j.status==="failed"?"failed":"done",counts:C.counts,body:_,httpStatus:j.httpStatus,error:j.error}});for(let S of I){let T=S.session.conversationId;if(S.kind==="skipped")u+=1;else if(S.kind==="outside-root")de(o,"outside-root");else if(S.kind==="empty")de(o,"empty");else if(S.kind==="unreadable")de(o,"unreadable"),k=Rn(k,T,{status:"quarantined",sourceHash:S.sourceHash,batchId:t.batchId,error:S.error});else{let C=S.body;p+=C.spans.length,a+=C.redactions.total;for(let[_,j]of Object.entries(C.redactions.byType))i[_]=(i[_]??0)+j;for(let _ of Object.keys(s))s[_]+=S.counts?.[_]??0;S.kind==="failed"?(c+=1,S.httpStatus!==void 0&&de(o,`rejected-${S.httpStatus}`)):d+=1,k=Rn(k,T,{status:S.kind,sourceHash:S.sourceHash,batchId:t.batchId,error:S.error})}r.emit?.({event:"session",conversationId:T,status:S.kind,spans:S.kind==="done"||S.kind==="failed"?S.body?.spans.length:0,httpStatus:S.httpStatus})}t.dryRun||wc(t.home,k,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,...nm(y)}),y}function em(e,n){let t=e.map(o=>Dr(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 nm(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 Wc(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??Uc,d=n.realpath??(I=>I),c=Xg(e,s,i,d);if(typeof c=="number")return c;let{record:u,registry:p}=c,l=$c(u,p,s,a);if(t.status){let I=Hs(s,i),y=Object.entries(I.sessions);e.io.log(`Cursor import record: ${F(s).backfillState}`),e.io.log(` conversations recorded: ${y.length}`);for(let[S,T]of y)e.io.log(` ${S}: ${T.status} (batch ${T.batchId}, ${T.updatedAt})`);return l.kind==="ok"?Js(e,l):Qc(e,l),n.emit?.({event:"status",sessions:I.sessions}),0}if(l.kind==="collision")return Qc(e,l);if(t.scan)return Js(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=Ie(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 \`${H("cursor","login")}\`, or pass --endpoint and --key.`),1;let R=Yg;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;R=I}let k=!!t.content||u.captureContent;if(k&&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"],b=await Zg(u,l.sessions,{home:s,io:i,scanIO:a,endpoint:m,token:g,orgId:h,captureContent:k,dryRun:E,reimport:!!t.reimport,resume:!!t.resume,concurrency:R,batchId:qg((n.now??Date.now)()),otherFolders:l.otherFolders,notRead:l.notRead},n);Js(e,l),e.io.log(`Cursor import ${E?"(dry-run) ":""}complete for ${u.projectSlug}: ${b.imported} imported, ${b.failed} failed, ${b.skipped} unchanged (of ${b.total} conversations), ${b.spans} spans.`),b.queuedSkipped>0&&e.io.log(`${b.queuedSkipped} conversation(s) are still queued for live upload and were left to the sender.`),b.dedupSkipped>0&&e.io.log(`${b.dedupSkipped} conversation(s) AgentTrail already holds (live capture or an earlier import) were skipped.`),b.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(b.dropped))e.io.log(`Not imported (${I}): ${y}`);return b.otherFolders>0&&e.io.log(`${b.otherFolders} folder(s) under ${l.projectsRoot} belong to other projects and were not opened.`),e.io.log(""),b.redactions.total>0&&e.io.log(`Edge-scrubbed ${b.redactions.total} secret-shaped value(s) on this machine before upload (${Object.keys(b.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."),b.failed>0?1:0}var Zc=require("path");var Jc=require("crypto"),Yc=require("uuid");function qc(e,n){return(0,Yc.v5)(`${e}:${n}`,Ao).replace(/-/g,"")}function Vr(e,n,t){return(0,Jc.createHash)("sha256").update(`${e}:${n}:${t}`).digest("hex").slice(0,16)}function tm(e,n){return e===""?n:n===""||Date.parse(e)>=Date.parse(n)?e:n}function rm(e,n,t,r){let{sessionId:o,toolResults:s}=e,i=[],a=null;for(let d of r){let c=Vr(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=Vr(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 zc(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=Vr(n,p.promptId,"root"),f=rm(e,p.promptId,l,d.get(p.promptId)??[]),m=f.map(R=>R.startTs).find(R=>R!==""),g=p.ts!==""?p.ts:m??e.firstTimestamp??"",h=g;for(let R of f)h=tm(h,R.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 om=1,sm=3;function Xn(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function im(e){let n=Xn(e.input_tokens),t=Xn(e.output_tokens),r=Xn(e.cache_read_input_tokens),o=Xn(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=Xn(e.cache_creation.ephemeral_5m_input_tokens),a=Xn(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 Xc(e){let n=Date.parse(e);return Number.isNaN(n)?"0":(BigInt(n)*1000000n).toString()}function am(e,n,t,r){let o={[Ve]:cn,[Qe]:t.batchId,"session.id":n.sessionId,...r?{[Mo]:r}:{}};if(e.role==="agent")return{...o,...Td(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,...im(s.usage),..._d(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,...Od(e.tool.input,e.toolResult?.content,t.captureContent)};return e.failed&&(s["otel.status_code"]="ERROR"),s}return o}function eu(e,n){let t=zc(e),r=e.cwd?(0,Zc.basename)(ln(e.cwd)):null,o=n.resolved??null,s=0,i={},a=t.map(c=>{let u=xr(am(c,e,n,r),o);s+=u.redactedCount;for(let p in u.byType)i[p]=(i[p]??0)+u.byType[p];return{traceId:qc(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"?sm:om,startTimeUnixNano:Xc(c.startTs),endTimeUnixNano:Xc(c.endTs),attributes:u.attributes,error:c.failed}}),d={[gt]:n.orgId,[Do]:n.projectId,[No]:pe(n.orgId,ne),[Fo]:ne,[Ve]:cn,[Qe]:n.batchId};return n.developerId&&(d[jo]=n.developerId),{resource:{attributes:d},scope:{name:"claude-code-backfill",version:n.scopeVersion??"0.0.0"},spans:a,redactions:{total:s,byType:i}}}var dm=6;function cm(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function um(e){if(e.cwd){let n=fn(e.cwd);if(n)return n}return hr(e.project)||"default"}function lm(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 nu(e,n={}){let t=await Qs(e.projectsRoot,e.projectRoot,{...n.scanIO,lineSource:n.lineSource??n.scanIO?.lineSource});return n.emit?.({event:"scan",...t}),t}function tu(e,n={}){let t=Gs(e.homeDir,n.checkpointIO);return n.emit?.({event:"status",sessions:t.sessions}),t}async function ru(e,n,t={}){let r=gm(),o=t.hashFile??Oc,s=gn(e.scrubConfig??Ue),i=await Qs(e.projectsRoot,e.projectRoot,{...t.scanIO,lineSource:t.lineSource??t.scanIO?.lineSource}),a=lm(i,e),d=a.length,c=Math.max(1,e.concurrency??dm),u=Gs(e.homeDir,t.checkpointIO),p=await wt(a,c,async _=>{try{return await o(_.file)}catch(j){return`unhashable:${j.message}`}}),l=new Map;a.forEach((_,j)=>{l.set(_.sessionId,p[j])});let f=0,m=!0,g=a;if(!e.reimport){let _=await Ur(a.map(j=>j.sessionId),{endpoint:e.endpoint,token:e.token},{fetch:t.upload?.fetch});if(m=_.ok,_.ok&&_.known.size>0){let j=[];for(let x of a)fm(_.known,u,x.sessionId,l.get(x.sessionId)??"")?(f++,t.emit?.({event:"dedup-skip",sessionId:x.sessionId})):j.push(x);g=j}}t.emit?.({event:"import-start",batchId:r,total:d,dedupSkipped:f,dedupOk:m,dryRun:e.dryRun??!1});let h=[],R=0,k=0,E=0,b=0,I=0,y=0,S=0,T={};for(let _ of cm(g,c)){let j=await wt(_,c,async x=>{let oe=l.get(x.sessionId)??"";if(n&&!Pt(u,x.sessionId,oe))return{item:x,kind:"skipped",sourceHash:oe};let Le;try{Le=await jc(x.file,x.sessionId,t.lineSource)}catch(dt){let tn=(dt instanceof vt,dt.message);return{item:x,kind:"quarantined",sourceHash:oe,error:tn}}if(e.retentionCutoffMs!==void 0&&Date.parse(Le.firstTimestamp)<e.retentionCutoffMs)return{item:x,kind:"skipped-retention",sourceHash:oe};let nn=re(e.orgId,um(x)),ye=eu(Le,{orgId:e.orgId,projectId:nn,developerId:e.developerId,batchId:r,captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:s}),at=await qn(Je(ye),{endpoint:e.endpoint,token:e.token,dryRun:e.dryRun},t.upload);return{item:x,kind:at.status==="failed"?"failed":"done",sourceHash:oe,spans:ye.spans.length,error:at.error,upload:at,redactions:ye.redactions}});for(let x of j){if(x.redactions){S+=x.redactions.total;for(let oe in x.redactions.byType)T[oe]=(T[oe]??0)+x.redactions.byType[oe]}x.kind==="skipped"?k++:x.kind==="skipped-retention"?I++:x.kind==="quarantined"?(b++,u=Rn(u,x.item.sessionId,{status:"quarantined",sourceHash:x.sourceHash,batchId:r,error:x.error})):(x.kind==="failed"?E++:R++,y+=x.spans??0,u=Rn(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})}_c(e.homeDir,u,t.checkpointIO)}let C={total:d,imported:R,skipped:k,failed:E,quarantined:b,retentionSkipped:I,dedupSkipped:f,dedupOk:m,estimatedActions:y,outcomes:h,redactions:{total:S,byType:T},excludedOtherProject:i.excludedOtherProject??0,excludedUnknownCwd:i.excludedUnknownCwd??0};return t.emit?.({event:"import-done",batchId:r,...pm(C),dedupOk:C.dedupOk,redactions:C.redactions}),C}function pm(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 fm(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 gm(){return`bf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function ou(e){return Ae(e,"setup")}function su(e){return Ae(e,"logout")}function iu(e,n="status"){return Ae(e,n)}var Me=require("fs"),Q=require("path");var au=require("fs"),Nt=require("path");var mm=15e3,ym=200;async function du(e,n,t,r={}){let o=r.io??O,s=v(e,n).root;return o.mkdirp(s,Ke),ve({lockPath:(0,Nt.join)(s,"install.lock"),io:r.lockIO,timeoutMs:mm},t)}function cu(e,n,t,r){let o=v(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=He(e,n,a);t.exists(d)&&(s+=t.readdir(d).filter(c=>c.endsWith(".json")).length)}catch{}return s}async function uu(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=v(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(ym,u()));return o.exists(d)?{waited:p,stillLocked:!0}:(await a({home:e,maxRunMs:u()}),{waited:p,stillLocked:!1})}function lu(e,n,t){let r=yr(e);return r!==null?t(r):n.filter(s=>e===s||e.startsWith(s.endsWith(Nt.sep)?s:`${s}${Nt.sep}`)).sort((s,i)=>i.length-s.length)[0]??e}function pu(e,n,t){let r=Un(e),o=t.project?.trim();if(o)return{slug:o,id:re(n,o),source:"flag",label:r};let s=Ho(e);if(s!==null)try{let a=mr(JSON.parse((0,au.readFileSync)(s,"utf8"))),d=a.orgId===n&&a.projectId!==void 0?a.projectId:re(n,a.projectSlug);return{slug:a.projectSlug,id:d,source:"agenttrail-json",label:r}}catch(a){return{error:`${s} cannot be read as a ${V} (${a.message}). Fix it, or pass --project <slug>.`}}let i=pn(e);return i===null?{error:"could not work out a project slug for this folder. Pass --project <slug>."}:{slug:i.slug,id:re(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 hm=require("fs");function Ys(e,n,t=O){let r=Zn(e,t),o=r===void 0?n:{...n,writtenAt:r.writtenAt};return r!==void 0&&JSON.stringify(r)===JSON.stringify(o)?!1:(t.writeFileAtomic(F(e).enforcement,`${JSON.stringify(o,null,2)}
|
|
30
|
+
`,N),!0)}function Zn(e,n=O){let t;try{let o=F(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 fu="cursor";var si=require("path");var mu=require("child_process"),Wr=require("fs");var Ft=class extends Error{constructor(n){super(n),this.name="HookCommandError"}},Sm=/["$`\\\r\n\0]/,Rm=/^[A-Za-z0-9_.:=/-]+$/;function Qr(e){if(Sm.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 En(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 gu(e,n,t,r=o=>new Ft(o)){for(let o of[e,n]){let s=Qr(o);if(s!==void 0)throw r(s)}for(let o of t)if(!Rm.test(o))throw r(`${JSON.stringify(o)} is not a fixed hook argument`);return[En(e),En(n),...t].join(" ")}var qs="{}",jt="CURSOR_PROJECT_DIR",ze=class extends Ft{constructor(n){super(n),this.name="CursorGateError"}},Em=/[\r\n\0]/;function ti(e){if(Em.test(e))return`${JSON.stringify(e)} holds a line break, which the gate cannot match`}function Im(e,n,t){return gu(e,n,t,r=>new ze(r))}function In(e,n,t){return Im(e,n,["--agent",ss,"--scope",t])}var zs='m() { case "$1" in ',Xs=`) return 0 ;; esac; return 1; }; if m "$${jt}"; then exec `,Zs=`; fi; p=$(cd -P -- "$${jt}" 2>/dev/null && pwd -P); if [ -n "$p" ] && m "$p"; then exec `,ei=`; fi; printf "${qs}"`,ni="/bin/sh -c ";function bm(e){let n=e.endsWith("/")?e:`${e}/`;return`${En(e)}|${En(n)}*`}function Jr(e,n){if(e.length===0)throw new ze("a gated command needs at least one connected folder");let t=[];for(let o of e){let s=ti(o);if(s!==void 0)throw new ze(s);t.push(bm(o))}let r=zs+t.join("|")+Xs+n+Zs+n+ei;return ni+En(r)}function yu(e,n){let t=n,r="",o=!1;for(;;){let s=e[t];if(s===void 0||s==="|"||s===")")break;if(o)throw new ze("a gate pattern ends at its star");if(s==="'"){let i=e.indexOf("'",t+1);if(i===-1)throw new ze("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 ze("a character this generator never writes")}return{value:r,end:t,star:o}}function km(e){try{let n=yu(e,0);return n.end===e.length&&!n.star?n.value:void 0}catch{return}}function bn(e){if(!e.startsWith(ni))return;let n=km(e.slice(ni.length));if(n===void 0||!n.startsWith(zs))return;let t=[],r=zs.length;try{for(;;){let d=yu(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(Xs,r))return;let o=n.slice(r+Xs.length),s=o.indexOf(Zs);if(s===-1||!o.endsWith(ei))return;let i=o.slice(0,s),a=o.slice(s+Zs.length,o.length-ei.length);return i===a?{folders:t,helper:i}:void 0}function ri(e){return typeof e=="string"&&bn(e)!==void 0}function hu(e,n){let t=bn(e);if(t!==void 0)return Jr(n,t.helper)}var Cm="/nonexistent/agenttrail-gate-dry-run";function Tm(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,Wr.accessSync)(r,Wr.constants.X_OK),t.push(r)}catch{}return t}function Su(e,n={}){let t=n.env??process.env,r=n.shells===void 0?Tm(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,mu.execFileSync)(o,["-c",e],{input:"",encoding:"utf8",timeout:n.timeoutMs??5e3,env:{...t,[jt]:Cm},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!==qs)return{ok:!1,shells:r,reason:`${o} answered ${JSON.stringify(s)} for an unconnected workspace, not ${qs}`}}return{ok:!0,shells:r}}function Ru(e=process.platform){return e!=="win32"}var Mt="3.21.16",_m=/^(\d+)\.(\d+)\.(\d+)$/;function Eu(e){if(typeof e!="string")return;let n=_m.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 Om(e,n){return e.major!==n.major?e.major-n.major:e.minor!==n.minor?e.minor-n.minor:e.patch-n.patch}function Iu(e){let n=Eu(e);if(n===void 0)return"unknown";let t=Eu(Mt);return t===void 0?"unknown":Om(n,t)>=0?"supported":"too-old"}var xm=require("fs"),Te=class extends Error{constructor(n){super(`PDP unreachable: ${n}`),this.name="PdpUnreachableError"}},Am=/^This feature requires the (Pro|Team|Business|Enterprise) plan or higher\.$/;async function wm(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"&&Am.test(o)}function Pm(e){return new Te(`${e} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`)}async function vm(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 Te(a)}finally{clearTimeout(s)}}async function Lt(e,n){let t=await vm(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 Te("200 snapshot with unparseable JSON body")}if(!Dm(r))throw new Te("200 with malformed PolicyCompiledSnapshot");return{kind:"ok",snapshot:r}}if(t.status===403){if(await wm(t))return{kind:"tier-disabled"};throw Pm("snapshot")}if(t.status===401)return{kind:"unauthorized"};throw new Te(`unexpected snapshot status ${t.status}`)}function Dm(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 oi(e,n){try{let t=await Lt(e,n);return t.kind==="ok"?{outcome:"ok",snapshot:t.snapshot}:{outcome:t.kind==="unauthorized"?"unauthorized":"forbidden"}}catch{return{outcome:"unreachable"}}}var kn="pep-hook.mjs",bu={preToolUse:600,beforeMCPExecution:600,beforeShellExecution:30},ii=Object.keys(bu);function Yr(e){return typeof e=="string"&&e.includes(kn)&&/(?:^|\s)--agent cursor(?=\s|$)/.test(e)}function ai(e){return Object.fromEntries(ii.map(n=>[n,[{command:e,timeout:bu[n]??600,failClosed:!0}]]))}function ku(e,n){return In(e,(0,si.join)(n,kn),"project")}function di(e,n){return In(e,(0,si.join)(n,kn),"user")}var Fm=!0;function jm(e){return!(e.row0Verified??Fm)||!e.hasUserScopeFolders?!1:e.version==="supported"}function Cu(e){let n=Iu(e.rawCursorVersion);return{v:1,enabled:n==="supported",apiBase:e.apiBase,orgId:e.orgId,agentId:e.agentId,timeoutMs:e.timeoutMs,userScopeHandoff:jm({hasUserScopeFolders:e.hasUserScopeFolders,version:n,...e.row0Verified===void 0?{}:{row0Verified:e.row0Verified}}),cursorVersion:e.rawCursorVersion,versionSupport:n,writtenAt:e.now.toISOString()}}var Mm="/Applications/Cursor.app/Contents/Info.plist",Lm=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]*)<\/string>/;function Tu(e=t=>O.readFile(t).toString("utf8"),n=Mm){try{let r=Lm.exec(e(n))?.[1]?.trim();return r===void 0||r===""?null:r}catch{return null}}function _u(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 qr(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 ${Mt} 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 Gu=require("fs"),Ku=require("os");var Nu=require("crypto");function Ou(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:Um(a,n,t),filledToolUseId:i}}function Um(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 $m=require("fs");var ci=".dropped",Bm="c";function xu(e){return e===Bm?"queue-full":`mark-${e}`}var Au=require("crypto"),Z=require("fs"),wu=5e3,ui=2e4,Ut={acquire(e,n){let t=(0,Z.openSync)(e,"wx",384);try{(0,Z.writeSync)(t,n)}finally{(0,Z.closeSync)(t)}},release(e){try{(0,Z.rmSync)(e,{force:!0})}catch{}},age(e){try{return Date.now()-(0,Z.statSync)(e).mtimeMs}catch{return null}},read(e){try{return(0,Z.readFileSync)(e,"utf8")}catch{return null}},touch(e){try{let n=new Date;(0,Z.utimesSync)(e,n,n)}catch{}},now:()=>Date.now()};function Pu(e,n=Ut){let t=n.age(e);return t!==null&&t<=ui&&t>=-ui}function Gm(e,n){return`${e} ${new Date(n).toISOString()} ${(0,Au.randomBytes)(8).toString("hex")}
|
|
31
|
+
`}function zr(e,n=Ut,t=process.pid){let r=Gm(t,n.now()),o=()=>{try{return n.acquire(e,r),!0}catch{return!1}};if(!o()&&(Pu(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<wu?!0:(s=i,n.read(e)!==r?!1:(n.touch(e),!0))},release(){n.read(e)===r&&n.release(e)}}}var Fu=35e5,Km=new Set([400,413,422]),li={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function pi(e){return(0,Nu.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 ju(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 Mu(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!==pi(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function Lu(e,n,t=Fu){let r=[],o=[];for(let s of n){let i=[...o,s];if(Buffer.byteLength(JSON.stringify(Je({...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 Xr(e,n,t){de(e.totals.dropped,t),de(e.report,t),n!==void 0&&de(_t(e.totals,n).dropped,t)}async function Hm(e,n,t){let r=async()=>(n.posts+=1,qn(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 Vm(e,n,t,r){if(t.length===n.length)return!1;let o=new Set(t),s=Fe(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&&Fe(a.conversationId,a.generationId)===s})}function Qm(e){let{closed:n,...t}=e;return t}async function Wm(e,n,t){let{adapter:r,deps:o,mem:s}=e,i=o.now(),a=Ou(t.records,t.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=t.state,p=Vm(r,a.records,d,u)?Qm(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}:vu(e,u,t,a.filledToolUseId);let f=ju(o.builder.assemble(d,void 0,t.decisions),p);if(p.closed!==void 0&&r.usageOf!==void 0){let b=r.usageOf({conversationId:u.conversationId,generationId:u.generationId},{home:o.home,env:o.env??process.env,io:o.io});b!==null&&(f={...f,usage:b})}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:R}=Mu(m.spans,u,g),k=0;for(let b of Lu(m,h)){let I=await Hm(o,n,Je({...m,spans:b}));if(I.ok){let y={...u.sent},S={...u.starts};for(let C of b)y[C.spanId]=pi(C),S[C.spanId]=R[C.spanId]??C.startTimeUnixNano;u={...u,sent:y,starts:S},k+=b.length;let T=o.now();s.totals.lastUploadAtMs=T,_t(s.totals,n.project.projectKey).lastUploadAtMs=T,Yn(o.home,r.stateDir,u,o.io);continue}if(I.status!==void 0&&Km.has(I.status)){let y={...u.sent};for(let S of b)y[S.spanId]=`dropped:${I.status}`,Xr(s,n.project.projectKey,`rejected-${I.status}`);u={...u,sent:y},Yn(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:k,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(b=>u.sent[b.spanId]!==void 0)?{...vu(e,u,t,a.filledToolUseId),sent:k}:{state:u,sent:k,drained:!1,open:l}}function vu(e,n,t,r){let{adapter:o,deps:s,mem:i}=e,a={...n,files:[]};Yn(s.home,o.stateDir,a,s.io);let d=He(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 Jm(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=_t(o.totals,n),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function Ym(e,n,t){let{deps:r,mem:o}=e,s=`${t}/${ci}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))Xr(o,n,xu(a))}catch{}r.io.remove(i)}}function qm(e,n){let t=/^\.(\d+)-\d+-\d+\.json\./.exec(e);if(!(t===null||!e.endsWith(".tmp")))return n-Number(t[1])}function Du(e){let{adapter:n,deps:t,mem:r}=e;if(!ps(r.totals))try{if(!t.io.exists(v(t.home,n.stateDir).projects)){r.totals=Tt();return}fs(t.home,n.stateDir,gs(Ot(t.home,n.stateDir,n.versionKey,t.io),r.totals,n.versionKey),t.io),r.totals=Tt()}catch{}}function Uu(e,n,t){try{return t.readdir(v(e,n).queue)}catch{return[]}}async function zm(e,n){let{adapter:t,deps:r,mem:o}=e,s=r.now(),i=r.credentials();if(i===null)return Xm(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 Uu(r.home,t.stateDir,r.io)){let h=He(r.home,t.stateDir,g),{files:R,other:k}=Fr(h,y=>t.parseQueueEntry(y),r.io,o.cache,h);k.includes(ci)&&Ym(e,g,h);for(let y of k){let S=qm(y,s);S!==void 0&&S>=At&&r.io.remove(`${h}/${y}`)}if(R.length===0)continue;for(let y of R)u=Math.max(u,y.atMs);Jm(e,g,R);let E=Ps({projectKey:g,files:R,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:S}of E.dropped){Xr(o,g,S);let T=y.entry;T?.kind==="unknown"&&de(o.totals.unknownKinds,T.rawKind),S==="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 b=a.kind==="ok"?a.registry.projects[g]:void 0;if(b===void 0){if(d+=E.turns.reduce((y,S)=>y+S.files.length,0),a.kind==="ok"){for(let y of E.turns)if(!(s-y.state.lastRecordAtMs<At)){for(let S of y.files)Xr(o,g,"unregistered"),r.io.remove(`${h}/${S}`),o.cache.delete(`${h}/${S}`);o.states.delete(y.state.traceId),Nr(r.home,t.stateDir,y.state.traceId,r.io)}}continue}let I={project:b,credentials:i,posts:o.posts};for(let y of E.turns){let S;try{S=await Wm(e,I,y)}catch(T){S={state:y.state,sent:0,drained:!1,open:y.state.closed===void 0,fatal:"network",error:T instanceof Error?T.message:String(T)},Zm(e,y.state)}if(o.states.set(S.state.traceId,S.state),p+=S.sent,S.drained)for(let T of y.files)o.cache.delete(`${h}/${T}`);else d+=y.files.length,S.open&&(c+=1);if(S.fatal!==void 0){l=!0,m=S.error??m,o.totals.lastError={atMs:r.now(),message:S.error??(S.fatal==="auth"?"not signed in":"upload failed")},S.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 Xm(e,n={}){return{entries:0,openTurns:0,newestRecordMs:e,sent:0,failed:!1,...n}}function Zm(e,n){try{Yn(e.deps.home,e.adapter.stateDir,n,e.deps.io)}catch{}}function ey(e,n,t){for(let r of Uu(e,n,t))try{if(t.readdir(He(e,n,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function ny(e,n,t,r){return e.failed?r:e.openTurns===0?n.pollIdleMs:t-e.newestRecordMs<=n.flowWindowMs?n.pollFlowingMs:n.pollOpenMs}async function $u(e,n,t={}){let r=v(n.home,e.stateDir),o=zr(r.senderLock,n.lockIO,n.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=ws(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:Tt(),report:{},scrubbers:gn(Ue),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 zm(a,t);u+=1,p+=g.sent,l=g.error??l,Du(a);for(let h of vs([...i.states.values()],n.now()))Nr(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,!ey(n.home,e.stateDir,n.io)||(o=zr(r.senderLock,n.lockIO,n.pid),o===void 0))break;continue}await n.sleep(ny(g,n.limits,n.now(),m)),g.failed&&(m=Math.min(m*2,n.limits.pollIdleMs*12))}}finally{Du(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:p,dropped:i.report,...l!==void 0?{lastError:l}:{}}}function Bu(e,n,t){try{let r=JSON.parse(t.readFile(v(e,n).install).toString("utf8"));return typeof r.cliVersion=="string"?r.cliVersion:void 0}catch{return}}var ty=2e3,ry={traceId:e=>_s(e,"live"),spanId:(e,n)=>Os(e,n),assemble:e=>qd(e),build:(e,n)=>Dr(e,n)};function oy(e,n,t=ty){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($s)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:n-o.capturedAtMs>=t})}function sy(e){if(e.cursorVersion!==null)return{version:e.cursorVersion,seenAtMs:e.capturedAtMs}}var iy={...br,versionKey:Tr,versionOf:sy,readRegistry:(e,n)=>X(e,n),parseQueueEntry:e=>Lr(e),turnOf:yc,decisionTurnOf:hc,opensTurn:Sc,closesTurn:Rc,subagentOf:Ec,fillableEvent:Ic,holdBack:(e,n)=>oy(e,n)};function ay(e,n={}){return $u(iy,e,n)}async function dy(e,n,t){let r=Ie({homeDir:e});return r===null?null:r.ingest_token!==n?r:ve({lockPath:`${Ee(e,"cursor")}.lock`},async()=>{let o=Ie({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=await Fn(s,o.refresh_token,t),a=jn({agent:"cursor",apiEndpoint:s,ingestEndpoint:o.endpoint,homeDir:e,host:o.host,log:()=>{}},i,{apiEndpoint:s,ingestEndpoint:o.endpoint});return Nn(e,a,{},"cursor"),a}catch{return null}})}function cy(e={}){let n=e.home??(0,Ku.homedir)(),t=e.io??O;return{home:n,io:t,lockIO:Ut,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:ry,pid:process.pid,limits:li,credentials:()=>Ie({homeDir:n}),refresh:r=>dy(n,r),claimFile:(r,o)=>{try{return(0,Gu.renameSync)(r,o),!0}catch{return!1}},scopeVersion:Bu(n,D,t)??"0.0.0",...e}}async function fi(e={}){try{await ay(cy(e.deps??{}),e)}catch{}return 0}function uy(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}uy()&&fi().then(e=>{process.exitCode=e});var Zr="# agenttrail: Cursor capture hooks (agenttrail setup --agent cursor)";function Hu(e,n,t={}){return fr(e,n,Zr,t)}function gi(e,n,t={}){return Ra(e,n,Zr,t)}var Vu="capture-hook.mjs",ly="pep-hook.mjs",Qu=/(?:^|\s)--agent cursor(?=\s|$)/;function $t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function et(e){return typeof e=="string"&&e.includes(Vu)&&Qu.test(e)}function Wu(e){return typeof e!="string"?!1:ri(e)?!0:Qu.test(e)?e.includes(Vu)||e.includes(ly):!1}function Xe(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(!$t(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&&!$t(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 py(e){return`${JSON.stringify(e,null,2)}
|
|
32
|
+
`}function Bt(e){return Array.isArray(e)?`[${e.map(Bt).join(",")}]`:$t(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Bt(e[t])}`).join(",")}}`:JSON.stringify(e)}function mi(e,n,t,r){let o=py(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 eo(e){return $t(e)&&typeof e.command=="string"?e.command:void 0}function Gt(e,n,t){let r=Xe(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=eo(p);return l!==void 0&&t(l)}),c=n[i]??[];if(Bt(d)===Bt(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,mi(r.doc,e,s,o)}function yi(e,n){if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=Xe(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=eo(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,mi(t.doc,e,o,r)}function hi(e,n){if(n.length===0)return yi(e,ri);if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=Xe(e);if(!t.ok)return t;let r={};for(let[o,s]of Object.entries(t.hooks))r[o]=s.map(i=>{let a=eo(i);if(a===void 0||!$t(i))return i;let d=hu(a,n);return d===void 0||d===a?i:{...i,command:d}});return t.doc.hooks=r,mi(t.doc,e,0,r)}function nt(e,n){let t=Xe(e);if(!t.ok)return[];let r=[];for(let[o,s]of Object.entries(t.hooks))for(let i of s){let a=eo(i);a!==void 0&&n(a)&&r.push({event:o,entry:i})}return r}function fy(e,n){let t=o=>{let s=yi(o,Wu);if(!s.ok)return;let i=Xe(s.text);if(!i.ok)return;let a=Object.fromEntries(Object.entries(i.hooks).filter(([,d])=>d.length>0));return Bt({...i.doc,hooks:a})},r=t(e);return r!==void 0&&r===t(n)}var Si={refusal:e=>{let n=Xe(e);return n.ok?void 0:n.reason},remove:(e,n)=>yi(e,n),hasAnyOurs:e=>nt(e,Wu).length>0,sameApartFromOurs:(e,n)=>fy(e,n)};function Ju(e){return Go(e,D)}function tt(e,n,t,r={}){return ma(e,D,n,t,r)}function Ri(e,n,t,r={}){return ya(e,D,n,Si,t,r)}var Yu=require("crypto"),ue=require("path"),qu=require("url");var gy={};function zu(){let e=gy.url;return e?(0,ue.dirname)((0,qu.fileURLToPath)(e)):typeof __dirname<"u"?__dirname:process.cwd()}function Xu(e,n,t=zu(),r=o=>O.exists(o)){let o=t;for(;;){for(let i of[(0,ue.join)(o,e),(0,ue.join)(o,"dist",e)])if(r((0,ue.join)(i,n)))return i;let s=(0,ue.dirname)(o);if(s===o)return;o=s}}function Ii(e=zu(),n=O){let t=e;for(;;){let r=(0,ue.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,ue.dirname)(t);if(o===t)return"unknown";t=o}}function Ei(e){return(0,Yu.createHash)("sha256").update(e).digest("hex")}function no(e,n,t=O){let r=v(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 Zu(e,n,t,r){let o=r.io??O,s=v(e,n);o.mkdirp(s.runtime,Ke);let i={},a=[];for(let p of t){let l=o.readFile((0,ue.join)(r.sourceDir,p)),f=Ei(l);i[p]=f;let m=(0,ue.join)(s.runtime,p),g;try{g=o.exists(m)?Ei(o.readFile(m)):void 0}catch{g=void 0}g!==f&&(o.writeFileAtomic(m,l,N),a.push(p))}let d=no(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)}
|
|
33
|
+
`,N),{runtimeDir:s.runtime,copied:a,record:c,recordWritten:!u}}function el(e,n,t,r=O){let o=v(e,n),s=no(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,ue.join)(o.runtime,a),c;try{c=r.exists(d)?Ei(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 rt=["capture-hook.mjs","flush.mjs","pep-hook.mjs"],to=["capture-hook.mjs","flush.mjs"];function nl(e,n=t=>O.exists(t)){return Xu(D,rt[0],e,n)}function tl(e,n=O){return no(e,D,n)}function rl(e,n){return Zu(e,D,rt,n)}function Kt(e,n=O,t=rt){return el(e,D,t,n)}var my={stop:5},yy=2,al=".cursor",dl="hooks.json",ol=1e4;async function ki(e,n,t={}){return du(e,D,n,t)}function hy(e,n){return{command:n,timeout:my[e]??yy}}function ot(e){return et(e)||Yr(e)}function bi(e,n){return{...cl(e),...n===void 0?{}:ai(n)}}function cl(e){return Object.fromEntries(ce.map(n=>[n,[hy(n,e)]]))}function Sy(e,n){return In(e,(0,Q.join)(n,"capture-hook.mjs"),"project")}function ro(e,n){return In(e,(0,Q.join)(n,"capture-hook.mjs"),"user")}function je(e){return(0,Q.join)(e,al,dl)}function ee(e){return(0,Q.join)(e,al,dl)}function oo(e,n){return(0,Q.relative)(e,je(n)).split(Q.sep).join("/")}var _C={...br,runtimeFiles:rt,captureRuntimeFiles:to,captureEvents:ce,projectHooksPath:je,userHooksPath:ee,hooksFormat:Si,mergeEntries:(e,n,t)=>Gt(e,n,t),isOurs:ot,captureEntries:cl,enforcementEntries:ai,command:In,gateEnvVar:jt,excludeMarker:Zr,transcriptFolderOf:mn};function Ry(e,n){let t;try{t=n.readText(e)}catch(s){return`${e} cannot be read \u2014 ${s.message}`}let r=Xe(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 ul(e,n,t){return lu(e,n,t)}function Ey(e,n,t){return pu(e,n,t)}function sl(e,n){let t=r=>(r??"").replace(/\/+$/,"");return t(e)===t(n)}async function Iy(e,n,t){let r=t.login??dr,o=Ie(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&&(!sl(o.endpoint,n.ingestEndpoint)||!sl(o.api_endpoint??n.apiEndpoint,n.apiEndpoint));return o&&!Gn(o,n.now)&&!i?{creds:o,reused:!0,endpointChanged:!1}:{creds:await r(n),reused:!1,endpointChanged:i}}function il(e,n,t,r){let o=t.git??L,s=t.hooksIO??G;if(!(0,Me.existsSync)(n))return{path:n,install:r??"project"};if(!De(e,o))return{path:n,install:"project",excluded:"not-a-repo"};let i=oo(e,n),a=be(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=Hu(e,i,{git:o,io:s});return d.ok?{path:n,install:"project",excluded:d.state}:{path:n,install:"user",note:d.reason}}function Ci(e,n,t,r,o){let s=o.hooksIO??G,i=ee(e);if(n.length===0){let l=Ri(e,i,ot,{io:s});if(!l.ok)return{ok:!1,reason:l.reason};let f=tt(e,i,m=>hi(m,[]),{io:s});return f.ok?{ok:!0,changed:l.change.changed||f.change.changed}:{ok:!1,reason:f.reason}}if(!Ru(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=Jr(n,t),d=r===void 0?void 0:Jr(n,r),c=(o.dryRun??Su)(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=tt(e,i,l=>Gt(l,bi(a,d),ot),{io:s});if(!u.ok)return{ok:!1,reason:u.reason};let p=tt(e,i,l=>hi(l,n),{io:s});return p.ok?{ok:!0,changed:u.change.changed||p.change.changed}:{ok:!1,reason:p.reason}}var by=["key","team","global"];async function ll(e,n={}){let t=e.flags;if(t.unregister===!0)return ky(e,n);let r=by.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: ${H("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??G,d=n.realpath??(C=>Me.realpathSync.native(C)),c=n.nodePath??process.execPath,u,p;try{let C=X(s,i);if(C.kind==="unreadable")throw new We(s);p=C.kind==="ok"?Object.values(C.registry.projects).map(x=>x.root):[];let _=d(e.io.cwd),j=ul(_,p,d);u={root:j,folder:_,isSubfolder:_!==j}}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 _=ti(C);_!==void 0&&l.push(_)}let m=n.runtimeSourceDir??nl();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 rt)i.exists((0,Q.join)(m,C))||l.push(`the built Cursor runtime is incomplete: ${(0,Q.join)(m,C)} is missing`);let g=F(s).runtime;for(let C of[c,(0,Q.join)(g,"capture-hook.mjs")]){let _=Qr(C);_!==void 0&&l.push(_)}let h=[je(u.root),...u.isSubfolder?[je(u.folder)]:[],ee(s)];for(let C of h){let _=Ry(C,a);_!==void 0&&l.push(_)}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 R=m,k,E,b;try{({creds:k,reused:E,endpointChanged:b}=await Iy(e,o,n))}catch(C){return e.io.error(`error: ${C.message}`),1}let I=Ey(u.root,k.org_id,t);if("error"in I)return e.io.error(`error: ${I.error}`),1;let y=t.developer?.trim()||void 0,S=!!t["capture-content"],T=(n.now??(()=>new Date))();try{return await ki(s,async()=>{let C=[];rl(s,{sourceDir:R,nodePath:c,cliVersion:n.cliVersion??Ii(),now:T,io:i}),mc(s,i);let _=X(s,i);if(_.kind==="unreadable")throw new We(s);let j=_.kind==="ok"?_.registry:{v:1,projects:{}},x=ur(u.root),oe=j.projects[x],Le=new Map((oe?.subfolders??[]).map(A=>[A.path,A]));u.isSubfolder&&!Le.has(u.folder)&&Le.set(u.folder,{path:u.folder,transcriptFolder:mn(u.folder),install:"project",registeredAt:T.toISOString()});let nn=il(u.root,u.root,n),ye=[...Le.values()].map(A=>il(u.root,A.path,n,A.install));for(let A of[nn,...ye])A.note!==void 0&&C.push(`${A.path}: ${A.note}`);let at={projectKey:x,root:u.root,transcriptFolder:mn(u.root),orgId:k.org_id,projectSlug:I.slug,projectId:I.id,projectSource:I.source,projectLabel:I.label,...y!==void 0?{developerId:y}:{},captureContent:S,install:nn.install,registeredAt:oe?.registeredAt??T.toISOString(),...ye.length>0?{subfolders:ye.map(A=>({...Le.get(A.path),install:A.install}))}:{}},dt=(n.cursorVersion??Tu)(),tn=Cu({apiBase:k.api_endpoint??k.endpoint,orgId:k.org_id,agentId:pe(k.org_id,fu),timeoutMs:$n,rawCursorVersion:dt,hasUserScopeFolders:[nn,...ye].some(A=>A.install==="user"),now:T}),se=tn;if(tn.enabled){let A=await oi({url:Bn(tn.apiBase),token:k.ingest_token,timeoutMs:tn.timeoutMs},n.fetchFn??fetch);if(A.outcome==="ok")A.snapshot!==void 0&&i.writeFileAtomic(F(s).pepSnapshot,`${JSON.stringify(A.snapshot)}
|
|
34
|
+
`,N);else{let xe=_u(A.outcome);se={...tn,enabled:!1,userScopeHandoff:!1,probeNote:xe},C.push(xe)}}pd(s,{...at,enforce:se.enabled},i),se.enabled&&Ys(s,se,i);let Fi=Sy(c,g),ji=se.enabled?ku(c,g):void 0,ct=[];for(let A of[nn,...ye]){if(!(0,Me.existsSync)(A.path))continue;let xe=je(A.path);if(A.install==="project"){let ie=tt(s,xe,Xt=>Gt(Xt,bi(Fi,ji),ot),{io:a});ie.ok||ct.push(ie.reason)}else{let ie=pl(s,u.root,A.path,n);ie.ok||ct.push(ie.reason),gi(u.root,oo(u.root,A.path),{git:n.git??L,io:a})}}for(let A of Object.values(j.projects)){if(A.projectKey===x)continue;let xe=[{path:A.root,install:A.install},...(A.subfolders??[]).map(ie=>({path:ie.path,install:ie.install}))];for(let ie of xe){if(ie.install!=="project"||!(0,Me.existsSync)(ie.path))continue;let Xt=tt(s,je(ie.path),lp=>Gt(lp,bi(Fi,A.enforce===!0?ji:void 0),ot),{io:a});Xt.ok||C.push(Xt.reason)}}let Mi=X(s,i),up=Mi.kind==="ok"?cs(Mi.registry):[],zt=Ci(s,up,ro(c,g),se.enabled?di(c,g):void 0,n);if(zt.ok?zt.note!==void 0&&C.push(zt.note):ct.push(zt.reason),ct.length>0){for(let A of ct)e.io.error(`error: ${A}`);return 1}se.enabled||Ys(s,se,i),E?(e.io.log(`Sign-in: REUSED \u2014 this project is connected to org ${k.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: \`${H("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 ${k.org_id}, device ${k.host}).`),b&&e.io.log(`Every connected project now sends to ${k.endpoint}.`),e.io.log(`Project: ${I.slug} -> project.id ${I.id}`),I.note!==void 0&&e.io.error(I.note);for(let A of[nn,...ye]){if(!(0,Me.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: ${ce.length} capture entries in ${je(A.path)}${A.excluded==="not-a-repo"?"":" (kept out of git)"}`:`Capture: ${ce.length} capture entries for ${A.path} in ${ee(s)}, gated to your connected folders`)}for(let A of C)e.io.error(`note: ${A}`);S?(e.io.log("Content capture: ON (prompts, commands, paths and tool output; scrubbed on this machine before anything is queued)."),e.io.error(nr("cursor"))):e.io.log("Content capture: OFF (metadata and tokens only; turn it on with --capture-content).");{let A=qr({record:se,projectEnforced:se.enabled,problems:Kt(s,i,[kn]),entriesInstalled:se.enabled});e.io.log(A.headline),se.enabled&&e.io.log(` ${ii.length} enforcement entries written alongside the capture ones, fail-closed.`);for(let xe of A.details)e.io.log(` ${xe}`)}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 \`${H("cursor","status")}\`.`),0},n)}catch(C){return e.io.error(`error: ${C.message}`),1}}async function ky(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=>Me.realpathSync.native(a)),i=n.nodePath??process.execPath;try{return await ki(r,async()=>{let a=X(r,o);if(a.kind==="unreadable")throw new We(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(R=>R.root),u=ul(d,c,s),p=a.registry.projects[ur(u)]??Object.values(a.registry.projects).filter(R=>d===R.root||d.startsWith(`${R.root}${Q.sep}`)).sort((R,k)=>k.root.length-R.root.length)[0];if(p===void 0)return e.io.log(`${d} is not a connected Cursor project; nothing to remove.`),0;let l=fl(r,p,n);if(l.failures.length>0){for(let R of l.failures)e.io.error(`error: ${R}`);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(([R])=>R!==p.projectKey))},m=Zn(r,o)?.enabled===!0,g=Ci(r,cs(f),ro(i,F(r).runtime),m?di(i,F(r).runtime):void 0,n);if(!g.ok)return e.io.error(`error: ${g.reason}`),1;fd(r,p.projectKey,o);let h=gl(r,o,p.projectKey);o.remove(Hn(r,p.projectKey)),e.io.log(`Disconnected ${p.root} (project ${p.projectSlug}).`);for(let R of l.folders)e.io.log(`Removed our entries from ${R}`);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; \`${H("cursor","logout")}\` signs it out and removes the rest.`),0},n)}catch(a){return e.io.error(`error: ${a.message}`),1}}function pl(e,n,t,r){let o=r.git??L,s=r.hooksIO??G,i=je(t),a=De(n,o)&&be(n,oo(n,t),o)==="tracked";return Ri(e,i,ot,{io:s,keepFile:a})}function fl(e,n,t){let r=t.hooksIO??G,o=t.git??L,s=[],i=[],a=[n.root,...(n.subfolders??[]).map(d=>d.path)];for(let d of a){let c=je(d),u=pl(e,n.root,d,t);u.ok?u.change.changed&&s.push(c):i.push(u.reason),(0,Me.existsSync)((0,Q.dirname)((0,Q.dirname)(c)))&&gi(n.root,oo(n.root,d),{git:o,io:r})}return{folders:s,failures:i}}function gl(e,n,t){return cu(e,D,n,t)}async function Cy(e){try{await fi({maxRunMs:e.maxRunMs,closeOpenTurns:!0,deps:{home:e.home}})}catch{}}async function Ty(e,n,t={}){return uu(e,D,n,{...t,run:t.run??Cy})}var _y={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 Oy(e){let n=F(e);return[...Object.entries(n).filter(([r])=>!(r in _y)).map(([,r])=>r),Ju(e)]}async function ml(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 ki(r,async()=>{let i=await(n.flush??Ty)(r,ol),a=X(r,o);if(a.kind==="unreadable"){e.io.error(`error: ${new We(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=fl(r,l,n);c.push(...f.folders);for(let m of f.failures)e.io.error(`error: ${m}`),s=!0}let u=Ci(r,[],"",void 0,n);u.ok?u.changed&&c.push(ee(r)):(e.io.error(`error: ${u.reason}`),s=!0);for(let l of c)e.io.log(`Removed our entries from ${l}`);let p=gl(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=Oy(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 ${ol/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 da(t)}catch(i){e.io.error(`error: ${i.message}`),s=!0}return s?1:0}var hl=require("fs"),Cn=require("path");var xy="3.21.16";function yl(e){return[{path:e.root,install:e.install,record:e},...(e.subfolders??[]).map(n=>({path:n.path,install:n.install,record:e}))]}function Ay(e,n){return n===e||n.startsWith(e.endsWith(Cn.sep)?e:`${e}${Cn.sep}`)}function wy(e,n,t){let r=Hn(e,t);try{return n.exists(r)?n.readdir(r).filter(o=>o.endsWith(".json")).length:0}catch{return 0}}function Py(e,n,t){let r=t.hooksIO??G,o=n.install==="project"?(0,Cn.join)(n.path,".cursor","hooks.json"):ee(e),s;try{s=r.readText(o)}catch{return}let i=nt(s,Yr);return n.install==="project"?i.length>0:i.some(a=>(bn(a.entry.command)?.folders??[]).includes(n.path))}function vy(e,n,t){let r=t.hooksIO??G,o=t.git??L,s=[],i=(0,Cn.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=nt(u,et);p.length!==ce.length&&s.push(`${i} holds ${p.length} of our ${ce.length} entries; run setup again`);let l=i.slice(n.record.root.length+1).split(Cn.sep).join("/");return be(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 ${ee(e)}`),s}let a;try{a=r.readText(ee(e))}catch(u){return s.push(`${ee(e)} cannot be read \u2014 ${u.message}`),s}let d=nt(a,et);return d.length!==ce.length?(s.push(`${ee(e)} holds ${d.length} of our ${ce.length} gated entries; run setup again`),s):(new Set(d.flatMap(u=>bn(u.entry.command)?.folders??[])).has(n.path)||s.push(`the gate in ${ee(e)} does not list ${n.path}; run setup again there`),s)}function Sl(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??G,i=n.realpath??(E=>hl.realpathSync.native(E)),a=Ie(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(Gn(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 \`${H("cursor","login")}\`.`);let d=X(r,o);if(d.kind==="unreadable")return e.io.log(`Capture: BROKEN \u2014 ${F(r).projects} cannot be read. Fix or delete it, then run \`${H("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 ${F(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(yl),l=p.filter(E=>Ay(E.path,u)).sort((E,b)=>b.path.length-E.path.length)[0];if(l===void 0){if(e.io.log(`Capture: NOT INSTALLED for ${u}. Run \`${H("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"),gc(r,o)===void 0&&E.push(`${F(r).queueKey} is missing or damaged; the capture hook records nothing without it`),E.push(...Kt(r,o,to)),E.push(...vy(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 b of E)e.io.log(` ${b}`);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: ${wy(r,o,l.record.projectKey)}`)}{let E=Zn(r,o),b=qr({record:E,projectEnforced:l?.record.enforce,problems:Kt(r,o,[kn]),entriesInstalled:l===void 0?void 0:Py(r,l,n)});e.io.log(b.headline);for(let I of b.details)e.io.log(` ${I}`)}let f=(()=>{try{return(n.versionSeen??Id)(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 ${xy}, 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 b of yl(E))e.io.log(` ${b.path}: ${b.install==="project"?"entries in its own .cursor/hooks.json":`gated entries in ${ee(r)}`}`)}}let g=ee(r),h;try{h=s.readText(g)}catch{h=void 0}let R=nt(h,et);if(R.length>0){let E=[...new Set(R.flatMap(y=>bn(y.entry.command)?.folders??[]))].sort(),b=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(b)])&&e.io.log(` does not match the registry (${b.join(", ")||"no folder"}); run \`${H("cursor","setup")}\` again`);let I=ro(tl(r,o)?.nodePath??n.nodePath??process.execPath,F(r).runtime);R.every(y=>bn(y.entry.command)?.helper===I)||e.io.log(" one gated entry runs another Node or another copy; run setup again")}let k=(n.senderSummary??((E,b)=>bd(E,b,o)))(r,l?.record.projectKey);k?.lastUploadAt!==void 0&&e.io.log(`Last upload: ${k.lastUploadAt}`),k?.lastError!==void 0&&e.io.log(`Last error: ${k.lastError}`);for(let[E,b]of Object.entries(k?.dropped??{}))e.io.log(`Dropped (${E}): ${b}`);return 0}var Jt=require("fs"),vl=require("path");var en=require("fs"),Ht=require("path");var Ze=class extends Error{name="SetupRefusedError"};function st(e,n){let t=n.tracked?`stop tracking it (\`git rm --cached ${e}\`, then commit) and run setup again`:`make git ignore it (remove the \`.gitignore\` rule that re-includes ${e}) and run setup again`,r=e===V?"would hold your API key":"holds this machine's credential and enforcement settings";return`${n.reason}. ${e} ${r}, so nothing was written and AgentTrail is not connected in this repo. To fix it, ${t}.`}function Rl(e,n,t={}){let r=t.git??L;if(!De(e,r))return;let o=El(e,n,r);if(o===void 0)return{ok:!1,tracked:!1,reason:`git could not say where ${n} is in this repo`};let s=be(o.top,o.repoRel,r);if(s==="tracked")return{ok:!1,tracked:!0,reason:`this repo tracks ${n}`};if(s==="unknown")return{ok:!1,tracked:!1,reason:`git could not say whether this repo tracks ${n}`}}var Dy="# agenttrail: per-machine files written by `agenttrail setup --agent claude`";function El(e,n,t){let r=t(["rev-parse","--show-toplevel"],e),o=t(["rev-parse","--show-prefix"],e);if(!(r.code!==0||o.code!==0||r.stdout.trim()===""))return{top:r.stdout.trim(),repoRel:`${o.stdout.trim()}${n}`}}function _e(e,n,t={}){let r=t.git??L;if(!De(e,r))return{ok:!0,state:"not-a-repo"};let o=El(e,n,r);if(o===void 0)return{ok:!1,tracked:!1,reason:`git could not say where ${n} is in this repo`};let s=be(o.top,o.repoRel,r);if(s==="tracked")return{ok:!1,tracked:!0,reason:`this repo tracks ${n}`};if(s==="unknown")return{ok:!1,tracked:!1,reason:`git could not say whether this repo tracks ${n}`};let i=fr(o.top,o.repoRel,Dy,{git:r,...t.excludeIO?{io:t.excludeIO}:{}});return i.ok?Ny(o.top,o.repoRel,r,t.excludeIO??G)?i:{ok:!1,tracked:!1,reason:`git does not ignore the temporary copies of ${n} that a write leaves for a moment`}:{ok:!1,tracked:!1,reason:i.reason}}function Ny(e,n,t,r){let o=`${n}.tmp-0-sample`;if(dn(e,o,t))return!0;let s=Rt(e,t);if(s===void 0)return!1;let i=r.readText(s),a=i===void 0||i===""?[]:i.replace(/\n$/,"").split(`
|
|
35
|
+
`),d=`${Et(n)}.tmp-*`,c=r.fileMode(s)??420;try{r.writeText(s,`${[...a,d].join(`
|
|
36
|
+
`)}
|
|
37
|
+
`,c)}catch{return!1}if(dn(e,o,t))return!0;try{r.writeText(s,i??"",c)}catch{}return!1}var Fy=[V,`${V}.tmp-*`,".claude/settings.local.json",".claude/settings.local.json.tmp-*"];function so(e,n={}){let t=n.git??L;if(!De(e,t))return!1;let r=(0,Ht.join)(e,".gitignore"),o=n.readFile??(h=>(0,en.readFileSync)(h,"utf8")),s=n.writeFile??((h,R)=>U(h,R));if(!(n.exists??(h=>(0,en.existsSync)(h)))(r))return!1;let a=o(r),d=be(e,".gitignore",t)==="tracked",c=d?t(["show",":./.gitignore"],e):void 0,u=new Set(c!==void 0&&c.code===0?c.stdout.split(`
|
|
38
|
+
`).map(h=>h.trim()):[]),p=new Set(Fy.filter(h=>!u.has(h))),l=a.split(`
|
|
39
|
+
`),f=l.filter(h=>!p.has(h.trim()));if(f.length===l.length)return!1;let m=f.join(`
|
|
40
|
+
`);if(s(r,m),![V,".claude/settings.local.json"].every(h=>{let R=_e(e,h,n);return R.ok?dn(e,h,t):R.tracked}))return s(r,a),!1;if(m.trim()===""&&!d)try{(n.unlink??en.unlinkSync)(r)}catch{}return!0}function io(e,n,t={},r={}){let o=(0,Ht.join)(e,V),s=t.writeFile??((c,u,p)=>U(c,u,p!==void 0?{mode:p}:{})),i=typeof n.apiKey=="string"&&n.apiKey.length>0,a=!1;if(!r.committable||i){let c=_e(e,V,t);if(i&&!c.ok)throw new Ze(st(V,c))}let d=i?384:420;return s(o,`${JSON.stringify(n,null,2)}
|
|
41
|
+
`,d),{path:o,gitignoreModified:a,mode:d}}var jy=448;function ao(e,n={}){let t=Ko(n.home),r=n.writeFile??((i,a,d)=>U(i,a,d!==void 0?{mode:d}:{}));(n.mkdir??((i,a)=>(0,en.mkdirSync)(i,{recursive:!0,mode:a})))((0,Ht.dirname)(t),jy);let s=384;return r(t,`${JSON.stringify(e,null,2)}
|
|
42
|
+
`,s),{path:t,mode:s}}var Il=require("child_process"),Qt=require("fs"),Tn=require("path"),bl=require("url"),Vy={},lo="agenttrail",My="agenttrail",me=`${My}@${lo}`,kl="2.1.211",po=e=>{let n=(0,Il.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??""}},uo=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"}},_i=class extends Error{constructor(t,r=kl){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},Vt=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 Cl(e){let n=e.match(/(\d+)\.(\d+)\.(\d+)/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function Oi(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 Ly=Cl(kl);function Tl(e){let n=e(["--version"]);if(n.spawnError==="ENOENT")throw new uo;if(n.spawnError)throw new uo;let t=Cl(n.stdout);if(t&&!Oi(t,Ly))throw new _i(n.stdout.trim()||null)}function Uy(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===lo);return s===void 0||s.path!==n?!1:s.source==="directory"?t(s.path):!0}catch{return!1}}function co(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===me);return r==null?void 0:{version:typeof r.version=="string"?r.version:void 0}}catch{return}}function Ti(e){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(e??"");return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function $y(e){try{let n=(0,Qt.readFileSync)((0,Tn.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 By(e){return co(e)!==void 0}function Gy(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(`@${lo}`)}):!0}function Ky(){let e=Vy.url;return e?(0,Tn.dirname)((0,bl.fileURLToPath)(e)):typeof __dirname<"u"?__dirname:process.cwd()}function Hy(e){let n=e??Ky();for(;;){let t=(0,Tn.join)(n,"plugin");if((0,Qt.existsSync)((0,Tn.join)(t,".claude-plugin","marketplace.json")))return t;let r=(0,Tn.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 fo=`claude plugin update ${me} --scope user`;function _l(e={}){let n=e.scope??"user",t=e.runner??po,r=e.marketplaceSource??Hy(),o=e.pathExists??Qt.existsSync;Tl(t);let s={status:"already-installed",pluginId:me,scope:n},i=e.packagedVersion??$y(r),a=co(t),d=Ti(a?.version),c=Ti(i);if(a!==void 0&&d&&c&&!Oi(c,d))return{...s,note:`A newer AgentTrail plugin (${a.version}) is installed than this CLI ships (${i}); it was left as is.`};if(!Uy(t,r,o)){let l=t(["plugin","marketplace","add",r,"--scope",n]);if(l.code!==0)throw new Vt("marketplace add",l.code,l.stderr)}let u=co(t);if(u!==void 0){if(e.refresh!==!0)return s;let l=u.version,f=Ti(l);if(f===null||c===null){let h=f===null?"installed":"packaged",R=f===null?l:i;return{...s,warning:`Could not read the ${h} AgentTrail plugin version${R===void 0?"":` as x.y.z (got "${R}")`}, so the plugin was not updated. If Claude Code is running an older AgentTrail plugin, run \`${fo}\`, then restart Claude Code.`}}if(Oi(f,c))return s;let m=t(["plugin","update",me,"--scope",n]),g=co(t);return g?.version===i?{status:"refreshed",pluginId:me,scope:n,foundVersion:l,expectedVersion:i}:{status:"refresh-failed",pluginId:me,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",me,"--scope",n]);if(p.code!==0)throw new Vt("install",p.code,p.stderr);return{status:"installed",pluginId:me,scope:n}}function Ol(e={}){let n=e.scope??"user",t=e.runner??po;if(Tl(t),!By(t))return{status:"not-installed",pluginId:me,scope:n};let r=t(["plugin","uninstall",me,"--scope",n]);if(r.code!==0)throw new Vt("uninstall",r.code,r.stderr);return Gy(t)||t(["plugin","marketplace","remove",lo,"--scope",n]),{status:"removed",pluginId:me,scope:n}}var xl=require("fs"),Al=require("path");var Qy=448,Wy=384;function wl(e,n,t={}){let r=t.writeFile??((s,i,a)=>U(s,i,a!==void 0?{mode:a}:{}));(t.mkdir??((s,i)=>(0,xl.mkdirSync)(s,{recursive:!0,mode:i})))((0,Al.dirname)(e),Qy),r(e,`${JSON.stringify(n,null,2)}
|
|
43
|
+
`,Wy)}var mo=[Jo,Yo,qo,zo,It,z,q];function Dl(e,n={}){return it(M(e),mo,n)}function Pl(e){try{return(0,Jt.realpathSync)(e)}catch{return(0,vl.resolve)(e)}}function go(e,n){return Pl(e)===Pl(n)}function Jy(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 xi(e,n){let t=e.timeoutMs??$n,r=n.settingsIO??{},o=go(e.settingsRoot,e.home);if(!o){let f=_e(e.settingsRoot,Ge,{...n.git?{git:n.git}:{}});if(!f.ok)return{enforced:!1,reason:"local-settings-tracked",message:Jy(f.reason,f.tracked),snapshotCached:!1}}let s=va({apiBase:e.apiBase,timeoutMs:t,orgId:e.orgId});o?Pe(e.settingsRoot,s,r):we(e.settingsRoot,s,r);let i=Da({token:e.token}),a={git:n.git??L,env:n.env??process.env};o&&e.migrate===!0?Pn(e.settingsRoot,i,r,{dotfiles:a}):o&&Wt(e.settingsRoot,r)[z]!==void 0?Pn(e.settingsRoot,i,r,{dotfiles:a}):we(e.settingsRoot,i,r);let d;try{d=await Lt({url:Bn(e.apiBase),token:e.token,timeoutMs:t},n.fetchFn)}catch(f){if(f instanceof Te)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};wl(Sr(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}):_l({...n.runner?{runner:n.runner}:{},refresh:f});c=m.status,u=Yy(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?Pe(e.settingsRoot,Xo,r):we(e.settingsRoot,Xo,r);let l=o||e.migrate!==!0?!1:it(M(e.settingsRoot),mo,r);return{enforced:!0,reason:"enforced",message:`real-time enforcement ENABLED (${u}).`,pluginStatus:c,...p,snapshotCached:!0,migrated:l}}function Yy(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 \`${fo}\`, 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 \`${fo}\`, then restart Claude Code`;case"already-installed":return"plugin already-installed";default:return`plugin ${e.status}`}}async function Nl(e,n){let t=n.settingsIO??{},r=e.timeoutMs??$n;if(!e.token)return{enforced:!1,reason:"no-credential",changed:!1};if(!go(e.settingsRoot,e.home)&&!_e(e.settingsRoot,Ge,{...n.git?{git:n.git}:{}}).ok)return{enforced:!1,reason:"local-settings-tracked",changed:!1};let o;try{o=await Lt({url:Bn(e.apiBase),token:e.token,timeoutMs:r},n.fetchFn)}catch(c){if(c instanceof Te)return{enforced:!1,reason:"unreachable",changed:!1};throw c}if(o.kind==="unauthorized"||o.kind==="tier-disabled"){let c=go(e.settingsRoot,e.home),u=Wt(e.settingsRoot,t,!c)[q]!==void 0;u&&c?it(M(e.settingsRoot),[q],t):u&&it(te(e.settingsRoot),[q],t,384);let p=!c&&Wt(e.settingsRoot,t)[q]!==void 0;return{enforced:!1,reason:o.kind==="unauthorized"?"credential-rejected":"tier-disabled",changed:u&&!p}}let s=go(e.settingsRoot,e.home),i=Wt(e.settingsRoot,t,!s),a=s&&i[z]!==void 0?i:Wt(e.settingsRoot,t,!0);if(i[q]!==void 0&&a[z]===e.token)return{enforced:!0,reason:"already-enforced",changed:!1};let d=await xi(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 Wt(e,n,t=!1){let r=t?te(e):M(e),o=n.readFile??(s=>(0,Jt.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 Fl(e,n={}){let t=!1;try{t=Ol(e.runner?{runner:e.runner}:{}).status==="removed"}catch{}return it(te(e.settingsRoot),mo,n,384),it(M(e.settingsRoot),mo,n),{pluginRemoved:t}}function it(e,n,t,r){let o=t.readFile??(u=>(0,Jt.readFileSync)(u,"utf8")),s=t.writeFile??((u,p,l)=>U(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)}
|
|
44
|
+
`,r),!0}var jl=require("os");function Ml(e,n={}){let t,r;if(e.projectSlug)t=e.projectSlug,r="explicit";else{let k=pn(e.cwd);if(!k)throw new Error("Could not derive a project slug (no git remote, no usable directory name). Pass --project <slug>.");t=k.slug,r=k.source}if(!e.global&&!e.team){let k=[V,Ge];for(let E of k){let b=Rl(e.cwd,E,n);if(b)throw new Ze(st(E,b))}for(let E of k){let b=_e(e.cwd,E,n);if(!b.ok)throw new Ze(st(E,b))}}let o=re(e.orgId,t),s=pe(e.orgId,ne),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,jl.homedir)(),c=e.global?d:e.cwd,u=e.global?(()=>{let k=ao(a,n);return{path:k.path,gitignoreModified:!1,mode:k.mode}})():io(e.cwd,a,n,{committable:e.team===!0}),p=e.endpoint??he,l=e.global?void 0:Un(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=mt(f),g=Pe(c,m,n),h=Gi(f),R=null;return Object.keys(h).length>0&&(R=we(c,h,n)),e.team&&Dl(c,n),!e.global&&!e.team&&so(e.cwd,n),{projectSlug:t,projectId:o,slugSource:r,agentId:s,agenttrailConfigPath:u.path,gitignoreModified:u.gitignoreModified,agenttrailConfigMode:u.mode,settings:g,localSettings:R,team:e.team??!1,global:e.global??!1,captureContent:e.captureContent??!1,resolvedEndpoint:p}}var Jl=require("fs");var zy=require("crypto"),Oe=require("fs"),_n=require("path");var qy=require("crypto");var Ll=100,Xy=2e3,Zy=3e3;var eh={mkdir:(e,n)=>(0,Oe.mkdirSync)(e,{recursive:!0,mode:n}),writeFile:(e,n,t)=>(0,Oe.writeFileSync)(e,n,{mode:t}),readDir:e=>(0,Oe.readdirSync)(e),readFile:e=>(0,Oe.readFileSync)(e,"utf8"),remove:e=>(0,Oe.rmSync)(e,{force:!0})};function nh(e){return{...eh,...e??{}}}function th(e){return(0,_n.join)((0,_n.dirname)(e),"pending-decisions")}function rh(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/policies/decisions`}async function Ul(e,n,t={}){let r=0;try{let o=nh(t.io),s=th(e.snapshotPath),i;try{i=o.readDir(s).filter(d=>d.endsWith(".json")).sort()}catch{return 0}let a=Date.now()+Zy;for(let d=0;d<i.length;d+=Ll){if(Date.now()>=a)return r;let c=[];for(let g of i.slice(d,d+Ll))try{c.push({file:g,item:JSON.parse(o.readFile((0,_n.join)(s,g)))})}catch{o.remove((0,_n.join)(s,g))}if(c.length===0)continue;let u=new AbortController,p=setTimeout(()=>u.abort(),Math.min(Xy,Math.max(0,a-Date.now()))),l;try{l=await n(rh(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,_n.join)(s,g.file)),r++)}return r}catch{return r}}var Ai=require("crypto"),$l=require("fs"),wi=require("path");var Bl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function oh(e){return(0,wi.join)(e,".agenttrail","machine-id")}function sh(e){return(0,wi.join)(e,".agenttrail","installs.json")}function Gl(e,n){try{return(e.readFile??(t=>(0,$l.readFileSync)(t,"utf8")))(n)}catch{return}}function Kl(e,n,t){(e.writeFile??((o,s,i)=>U(o,s,i!==void 0?{mode:i}:{})))(n,t,384)}function Hl(e,n={}){let t=oh(e),r=Gl(n,t)?.trim();if(r&&Bl.test(r))return r;let o=(0,Ai.randomUUID)();return Kl(n,t,`${o}
|
|
45
|
+
`),o}function Vl(e,n,t={}){let r=sh(e),o={},s=Gl(t,r);if(s)try{let d=JSON.parse(s);typeof d=="object"&&d!==null&&!Array.isArray(d)&&(o=d)}catch{o={}}let i=o[n];if(typeof i=="string"&&Bl.test(i))return i;let a=(0,Ai.randomUUID)();return o[n]=a,Kl(t,r,`${JSON.stringify(o,null,2)}
|
|
46
|
+
`),a}function ih(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/machines/enforcement`}function ah(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:{...t,reason:e.reason}}async function Ql(e,n){let t=new AbortController,r=setTimeout(()=>t.abort(),2e3);try{return(await n(ih(e.apiBase),{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(ah(e)),signal:t.signal})).ok}catch{return!1}finally{clearTimeout(r)}}function Wl(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 dh(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 ch(e,n){let t=K(e.homeDir,e.credentialsIO);if(t?.ingest_token)return t.ingest_token;try{let o=Be(te(e.settingsRoot),n.readFile??(s=>(0,Jl.readFileSync)(s,"utf8")))?.env;if(typeof o=="object"&&o!==null){let s=o[z];if(typeof s=="string"&&s.length>0)return s}}catch{}}async function Yl(e,n){try{let t=ch(e,n);if(!t)return{reported:!1};let r={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},o=await Nl({settingsRoot:e.settingsRoot,apiBase:e.apiEndpoint,token:t,deviceTokenPath:t.startsWith("dlv_ingest_"),home:e.homeDir},{fetchFn:n.fetchFn,settingsIO:r}),s=dh(o);s&&e.log?.(s);let i={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},a=await Ql({apiBase:e.apiEndpoint,token:t,machineId:Hl(e.homeDir,i),installId:Vl(e.homeDir,e.settingsRoot,i),enforced:o.enforced,...Wl(o)?{reason:Wl(o)}:{}},n.fetchFn),d=await Ul({apiBase:e.apiEndpoint,token:t,snapshotPath:n.snapshotPath||process.env[Aa]?.trim()||Sr(e.homeDir)},n.fetchFn,n.pendingDecisionsIO?{io:n.pendingDecisionsIO}:{});return{healed:o,reported:a,flushed:d}}catch{return{reported:!1}}}function ql(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 rp="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.",Yt=`agenttrail \u2014 connect an AI coding agent to AgentTrail
|
|
47
|
+
|
|
48
|
+
Usage:
|
|
49
|
+
agenttrail setup --agent <claude|cursor|codex> [options]
|
|
50
|
+
agenttrail login --agent <claude|cursor|codex> [--refresh] [options]
|
|
51
|
+
agenttrail logout --agent <claude|cursor|codex> [options]
|
|
52
|
+
agenttrail status --agent <claude|cursor|codex>
|
|
53
|
+
agenttrail backfill --agent <claude|cursor|codex> --scan | --import | --status | --resume [options]
|
|
54
|
+
|
|
55
|
+
Every command needs --agent: claude for Claude Code, cursor for Cursor, codex
|
|
56
|
+
for Codex (not yet available).
|
|
57
|
+
|
|
58
|
+
One command to install: run \`setup\` with no API key. It opens the browser to
|
|
59
|
+
authorize this device (OAuth device-auth), then writes the config, and \`status\`
|
|
60
|
+
reports capture ACTIVE.
|
|
61
|
+
|
|
62
|
+
claude \`status\` also reports your real-time enforcement state. For CI /
|
|
63
|
+
headless, pass --key or --team instead of the browser.
|
|
64
|
+
cursor \`status\` also reports your real-time enforcement state. Enforcement
|
|
65
|
+
needs Cursor ${Mt} or later; an older Cursor is captured only.
|
|
66
|
+
Setup always uses the browser, per project, and --key, --team and
|
|
67
|
+
--global are refused.
|
|
68
|
+
codex Not yet available: every command refuses --agent codex and changes
|
|
69
|
+
nothing.
|
|
70
|
+
|
|
71
|
+
Options:
|
|
72
|
+
--agent <claude|cursor|codex>
|
|
73
|
+
Required on every command: the agent to connect.
|
|
74
|
+
--org <uuid> Org UUID the API key belongs to.
|
|
75
|
+
--project <slug> Project slug (default: derived from git remote / dir name).
|
|
76
|
+
--developer <uuid> Per-machine developer id (optional).
|
|
77
|
+
--key <dlv_...> (claude only) API key for the CI/headless path (default:
|
|
78
|
+
$AGENTTRAIL_API_KEY). When omitted (and not --team), \`setup\`
|
|
79
|
+
uses browser device-auth. Refused for --agent cursor.
|
|
80
|
+
--endpoint <url> OTLP ingest base URL (default: $AGENTTRAIL_INGEST_ENDPOINT,
|
|
81
|
+
else ${he}). e.g. a self-hosted
|
|
82
|
+
ingest: --endpoint http://localhost:4318.
|
|
83
|
+
--api-endpoint <url> AgentTrail API base URL for device-auth (setup/login/logout).
|
|
84
|
+
Accepts a bare origin (e.g. https://api.agenttrail.sh or
|
|
85
|
+
http://localhost:3000); the CLI derives the /api/v1 base.
|
|
86
|
+
(default: $AGENTTRAIL_API_ENDPOINT, else ${St}).
|
|
87
|
+
--refresh (login) Refresh the on-disk ingest token ONLY if it is
|
|
88
|
+
within ~1 day of expiry; otherwise a no-op. The
|
|
89
|
+
SessionStart hook runs this every session.
|
|
90
|
+
--team (claude only) Write committable, key-free config (auth header
|
|
91
|
+
from env). Refused for --agent cursor.
|
|
92
|
+
--global (claude only) Configure ~/.claude + ~/.agenttrail/config.json
|
|
93
|
+
(per-user). Refused for --agent cursor: Cursor setup is
|
|
94
|
+
per-project, and \`logout\` clears the machine.
|
|
95
|
+
--no-capture-content
|
|
96
|
+
(claude) Turn OFF prompt/tool-content capture (prompts,
|
|
97
|
+
commands, file paths and tool output): metadata and tokens
|
|
98
|
+
only. A rerun of setup keeps an earlier opt-out.
|
|
99
|
+
--capture-content claude: turn capture back ON after --no-capture-content.
|
|
100
|
+
cursor: turn ON content capture.
|
|
101
|
+
Secret- and PII-shaped values and enumerated secret-manager
|
|
102
|
+
outputs (\`op read\`, \u2026) are scrubbed at ingest before
|
|
103
|
+
storage; scrubbing is shape-based, so a structureless secret
|
|
104
|
+
can still be stored. claude: this client sends content as
|
|
105
|
+
Claude Code emits it and never scrubs it here. cursor: content
|
|
106
|
+
is edge-scrubbed on this machine before it is queued, and the
|
|
107
|
+
server scrubs it again.
|
|
108
|
+
Default for Claude Code: content capture ON. Default for
|
|
109
|
+
Cursor: metadata + tokens only.
|
|
110
|
+
--unregister (setup --agent cursor) Remove this project's Cursor capture
|
|
111
|
+
entries and its registry row, leaving other projects set up.
|
|
112
|
+
-h, --help Show this help.
|
|
113
|
+
|
|
114
|
+
Backfill with --agent claude (import past Claude Code sessions from ~/.claude/projects):
|
|
115
|
+
--import / --scan cover ONLY the project you run them in \u2014 matched on each
|
|
116
|
+
session's recorded working directory, mirroring per-project \`setup\`. There is
|
|
117
|
+
no flag to widen this; cd into another project and re-run to import it.
|
|
118
|
+
(--status is machine-wide \u2014 see below.)
|
|
119
|
+
--scan List THIS project's transcripts (JSON inventory). Uploads nothing.
|
|
120
|
+
--import Parse + upload THIS project's sessions to AgentTrail. Sessions
|
|
121
|
+
AgentTrail already holds (captured live OR imported before,
|
|
122
|
+
unchanged) are skipped so nothing is duplicated; for those
|
|
123
|
+
already-recorded sessions --import and --resume now behave
|
|
124
|
+
alike. Use --reimport to force.
|
|
125
|
+
--status Show the import checkpoint (~/.agenttrail/backfill-state.json).
|
|
126
|
+
Machine-wide (records every import on this machine).
|
|
127
|
+
--resume Continue a prior import (skip done, retry failed).
|
|
128
|
+
--reimport Import even sessions AgentTrail already holds (skip the dedup
|
|
129
|
+
check). Use after the per-turn migration, or to re-send a
|
|
130
|
+
session captured live.
|
|
131
|
+
--since <dur> Only sessions newer than e.g. 7d / 24h / 30m. Claude only:
|
|
132
|
+
a Cursor session file carries no time of its own, so
|
|
133
|
+
\`backfill --agent cursor\` refuses the flag rather than
|
|
134
|
+
ignoring it.
|
|
135
|
+
--dry-run Map + validate, but do not upload. (The read-only "already
|
|
136
|
+
recorded?" check still runs so the preview's skip count is
|
|
137
|
+
real.) With --content this is the honest pre-flight: shows
|
|
138
|
+
what would be edge-redacted before anything leaves the machine.
|
|
139
|
+
--content Include prompt/tool content. Shape-matching secrets and
|
|
140
|
+
enumerated secret-manager outputs (\`op read\`, \u2026) are
|
|
141
|
+
EDGE-scrubbed on this machine before upload; a shapeless
|
|
142
|
+
secret fetched by any other command (a wrapper script,
|
|
143
|
+
\`kubectl get secret\`) \u2014 or by an enumerated command nested in
|
|
144
|
+
a command substitution, e.g. \`export FOO=$(op read \u2026)\` \u2014 is
|
|
145
|
+
not. The server then applies your org's full config.
|
|
146
|
+
Default: metadata + tokens only.
|
|
147
|
+
--concurrency <n> Max parallel uploads (default 6).
|
|
148
|
+
|
|
149
|
+
Backfill with --agent cursor (import this project's Cursor sessions):
|
|
150
|
+
Same verbs and flags as above \u2014 --scan, --import, --resume, --status, --content,
|
|
151
|
+
--dry-run, --reimport, --concurrency \u2014 with three differences: --since is not
|
|
152
|
+
supported (above); an import carries no prompt text, no model, no tokens and no
|
|
153
|
+
cost, because a Cursor session file holds none; and its times are approximate and
|
|
154
|
+
marked as such. Conversations already captured live are skipped. Set the project
|
|
155
|
+
up first, in the project: \`npx -y @agenttrail/cli@latest setup --agent cursor\`.
|
|
156
|
+
Full detail: docs/integrations/cursor.md`;function uh(e){return(0,tp.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}}})}function lh(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 zl(e,n){if(e.prompt)return(await e.prompt(n)).trim();if(!process.stdin.isTTY)return;let t=(0,np.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(n)).trim()}finally{t.close()}}function ph(e){return typeof e.isInteractive=="boolean"?e.isInteractive:!!process.stdin.isTTY}async function fh(e,n){let t=!!n.team,r=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim();if(!t&&!r)return gh(e,n);let o=!!n.global,s=e.persistIO?.home??(0,W.homedir)(),i=ip(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 zl(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 zl(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;if(ap(e,i),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 m=(0,xn.basename)(ln(e.cwd));m&&Re(m).length>rn&&e.error(`WARNING: project "${m}" exceeds the ${rn}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`)}let u=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim(),p;if(u)try{p=xo(u)}catch(m){return e.error(`error: ${m.message}`),1}let l;try{l=Ml({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:p},e.persistIO??{})}catch(m){if(!(m instanceof Ze))throw m;return e.error(`error: setup refused: ${m.message}${sp(e.cwd)}`),1}let f=o?e.persistIO?.home??(0,W.homedir)():e.cwd;if(yt(f,e.persistIO??{}),e.fetchFn&&c){let m=n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||St;await op(e,{settingsRoot:f,apiBase:m,token:c,deviceTokenPath:!1,home:e.persistIO?.home??(0,W.homedir)(),orgId:d})}return l.slugSource==="directory"&&e.error(rp),e.log(`Project: ${l.projectSlug} \u2192 project.id ${l.projectId}`),e.log(`Endpoint: ${l.resolvedEndpoint}`),e.log(`Wrote ${l.agenttrailConfigPath} (mode 0${l.agenttrailConfigMode.toString(8)})`+(l.gitignoreModified?" (+ .gitignore)":"")),e.log(`Wrote ${l.settings.path} (${l.settings.merged?"merged":"created"})`),l.localSettings&&e.log(`Wrote ${l.localSettings.path} (${l.localSettings.merged?"merged":"created"}, mode 0600, ${o?"":"kept out of git \u2014 "}holds the API key; do NOT commit)`),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(Di(a)),0}async function gh(e,n){let t;try{t=qt(e,n)}catch(h){return e.error(`error: ${h.message}`),1}let r=!!n.global,o=t.settingsRoot,s=r?e.persistIO?.home??(0,W.homedir)():o,i=ip(n,s,e.persistIO?.home??(0,W.homedir)(),e.persistIO?.readFile),a=i.on;ap(e,i);let d=n.project?.trim(),c,u;if(d)c=d,u="explicit";else{let h=pn(o);c=h?.slug??"default",u=h?.source??"directory"}if(t={...t,projectSlug:c,captureContent:a,global:r,settingsRoot:s},!r){let h=_e(o,Ge,e.persistIO??{});if(!h.ok)return e.error(`error: setup refused: ${st(Ge,h)}${sp(o)}`),1}let p=K(t.homeDir,t.credentialsIO);try{if(p&&!Gn(p,t.now))Ga(t,p),e.log(`Using existing AgentTrail credentials (org ${p.org_id}).`);else{if(!ph(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;p=await os(t)}}catch(h){return e.error(`error: ${h.message}`),1}let l={orgId:p.org_id,projectSlug:c,projectId:re(p.org_id,c),agentId:pe(p.org_id,ne),captureContent:a},f=r?void 0:_e(t.settingsRoot,V,e.persistIO??{}),m=f!==void 0&&!f.ok&&f.tracked,g=r?ao(l,e.persistIO??{}):m?void 0:io(t.settingsRoot,l,e.persistIO??{});return r||so(o,e.persistIO??{}),u==="directory"&&e.error(rp),e.log(`Project: ${c} \u2192 project.id ${l.projectId}`),e.log(`API endpoint (device-auth): ${t.apiEndpoint}`),e.log(`Endpoint: ${t.ingestEndpoint}`),e.log(g?`Wrote ${g.path} (mode 0${g.mode.toString(8)}, device login \u2014 no API key stored)`:`Left ${V} as it is: this repo tracks it.`),e.log(Di(a)),e.fetchFn&&await op(e,{settingsRoot:t.settingsRoot,apiBase:t.apiEndpoint,token:p.ingest_token,deviceTokenPath:!0,home:e.persistIO?.home??(0,W.homedir)(),orgId:p.org_id}),e.log("Device login active \u2014 telemetry capture is ON. `status` reports capture ACTIVE + the enforcement state."),0}async function op(e,n){if(e.fetchFn)try{let t=await xi({...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 mh(e,n){let t=n.source==="global"?(0,W.homedir)():n.configPath?(0,xn.dirname)(n.configPath):n.gitRoot??e.cwd;try{let o=(0,On.readFileSync)(M(t),"utf8"),a=JSON.parse(o)?.env?.[Po];if(typeof a=="string"&&a.length>0)return{endpoint:a,onDisk:!0}}catch{}return{endpoint:e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||he,onDisk:!1}}function yh(e){let n;try{n=Vo(e.cwd)}catch(s){return e.error(`error: ${s.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=ka(n,e.env);e.log("AgentTrail exporter: ACTIVE"),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 r=mh(e,n);e.log(`Endpoint: ${r.endpoint}${r.onDisk?"":" (no on-disk endpoint found; env-or-default)"}`);try{let s=on(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||St);e.log(`API endpoint (device-auth): ${s}`)}catch{}e.log(`API key: ${t?"present":"MISSING (set AGENTTRAIL_API_KEY, or use device login)"}`),e.log(Di(Sh(e,n))),e.log(`Real-time enforcement: ${hh(e,n)}`);let o=ts(e.persistIO?.home??(0,W.homedir)());return o&&e.log(o),0}function vi(e){try{let t=JSON.parse((0,On.readFileSync)(e,"utf8"))?.env;return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function hh(e,n){let t=n.source==="global"?(0,W.homedir)():n.configPath?(0,xn.dirname)(n.configPath):n.gitRoot??e.cwd,r=vi(te(t)),o=vi(M(t)),s=typeof r[z]=="string"&&r[z]!=="";return r[q]==="1"?s?"ON":`ON but no token, so every tool call is denied. ${Pi}`:o[q]!=="1"?"OFF":n.source==="global"?"ON":s?`ON (set in .claude/settings.json by an older setup). ${Pi} 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 ${Pi.toLowerCase()}.`}var Pi="Run `npx -y @agenttrail/cli@latest setup --agent claude` in this repo";function sp(e){return vi(M(e))[q]==="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 Di(e){return 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 Xl(e,n){let t;try{t=JSON.parse(n(e))?.env}catch{return"absent"}let r=ft.filter(o=>t?.[o]!==void 0);return r.length===0?"absent":r.every(o=>t?.[o]==="1")?"on":"off"}function ip(e,n,t,r=o=>(0,On.readFileSync)(o,"utf8")){if(e["no-capture-content"])return{on:!1};if(e["capture-content"])return{on:!0};let o=M(n),s=Xl(o,r);if(s==="off")return{on:!1,keptOptOut:{from:"install",path:o}};if(s==="absent"&&n!==t){let i=M(t);if(Xl(i,r)==="off")return{on:!1,keptOptOut:{from:"user",path:i}}}return{on:!0}}function ap(e,n){if(n.on){e.error(nr("claude"));return}let t=n.keptOptOut;t!==void 0&&e.log(t.from==="user"?`note: content capture stays OFF because of the user-level opt-out in ${t.path}. Pass --capture-content to turn it on for this project.`:`note: content capture stays OFF because ${t.path} already turns it off (a content flag is not "1"). Pass --capture-content to turn it on.`)}function Zl(e){let n;try{n=JSON.parse((0,On.readFileSync)(M(e),"utf8"))?.env}catch{return"absent"}return ft.filter(r=>n?.[r]!==void 0).length===0?"absent":ft.every(r=>n?.[r]==="1")?"all-on":"defines-some"}function Sh(e,n){let t=n.source==="global"?(0,W.homedir)():n.configPath?(0,xn.dirname)(n.configPath):n.gitRoot??e.cwd,r=Zl(t);if(r==="all-on")return!0;if(r==="defines-some")return!1;let o=e.persistIO?.home??(0,W.homedir)();return o!==t&&Zl(o)==="all-on"}function Rh(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=(0,ep.spawn)(n,[e],{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}function qt(e,n){let t=on(n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||St),r=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||he;return{...{apiEndpoint:t,ingestEndpoint:r,homeDir:(0,W.homedir)(),settingsRoot:e.cwd,host:(0,W.hostname)(),openBrowser:Rh,log:e.log},...e.loginEnv}}async function Eh(e){if(!e.readStdin)return!1;let n=await e.readStdin();if(n.trim()==="")return!1;try{return Ls(JSON.parse(n))}catch{return!1}}async function Ih(e,n){if(n.refresh&&await Eh(e))return 0;let t;try{return t=qt(e,n),n.refresh?await Ka(t):await os(t),0}catch(r){return e.error(`error: ${r.message}`),1}finally{if(n.refresh&&t){let r=t.fetchFn;await Yl(t,{fetchFn:r?(s,i)=>r(String(s),i):fetch}).catch(()=>{})}}}async function bh(e,n){try{let t=qt(e,n);return await Va(t),e.pluginRunner&&Fl({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 kh(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 Ch(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,W.homedir)(),o=ln(e.cwd),s=T=>e.log(JSON.stringify(T)),i={...e.backfillDeps,emit:e.backfillDeps?.emit??s};if(n.scan)return await nu({projectRoot:o},i),0;if(n.status)return tu({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()||he,c=K(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()-An[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 T;try{T=qt(e,n)}catch(_){return e.error(`error: ${_.message}`),1}let C=await Ha(T);C.ingestToken&&(l=C.ingestToken),C.tier?(m=C.tier,f=Date.now()-An[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,R;try{let T=Vo(e.cwd);h??=T.config?.orgId,R=T.config?.developerId}catch{}if(!h)return e.error("error: could not resolve org id (use device login, --org, or a .agenttrail.json)."),1;let k;if(n.since){let T=lh(n.since);if(T===null)return e.error(`error: invalid --since '${n.since}' (e.g. 7d, 24h, 30m).`),1;k=Date.now()-T}let E;if(n.concurrency){let T=Number(n.concurrency);if(!Number.isInteger(T)||T<1)return e.error(`error: invalid --concurrency '${n.concurrency}' (positive integer).`),1;E=T}let b=!!n.content;b&&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 ru({homeDir:r,endpoint:d,token:l,orgId:h,developerId:R,captureContent:b,concurrency:E,dryRun:u,reimport:!!n.reimport,projectRoot:o,sinceMs:k,retentionCutoffMs:f},a,i),y=fn(o)??(0,xn.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(kh(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 T=An[m],C=`${I.retentionSkipped} of ${I.total} session(s) predate your ${m} plan's ${T}-day retention window and weren't stored`,_=So(m);_?e.log(`${C} \u2014 upgrade to ${_} to keep ${An[_]} 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 S=I.redactions;if(S.total>0){let T=Object.entries(S.byType).sort((C,_)=>_[1]-C[1]||C[0].localeCompare(_[0])).map(([C,_])=>`${C}\xD7${_}`).join(", ");e.log(`Edge-scrubbed ${S.total} secret(s) across the run before upload (by type: ${T}).`)}return I.failed>0?1:0}function Ni(e,n){let t=qt(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,log:t.log}}async function Th(e,n){try{let t=Ni(e,n);return n.refresh?await aa(t):await dr(t),0}catch(t){return e.error(`error: ${t.message}`),1}}function _h(e,n,t){let r={io:e,flags:t,sessionEnv:()=>Ni(e,t)};switch(n){case"login":return Th(e,t);case"logout":return ml(r);case"status":case"doctor":return Sl(r);case"setup":return ll(r);case"backfill":return Wc(r)}}function Oh(e,n,t){let r={io:e,flags:t,sessionEnv:()=>Ni(e,t)};switch(n){case"login":return Ui(r);case"logout":return su(r);case"status":case"doctor":return iu(r,n);case"setup":return ou(r);case"backfill":return Qa(r)}}function xh(e,n,t){switch(n){case"setup":return fh(e,t);case"login":return Ih(e,t);case"logout":return bh(e,t);case"status":case"doctor":return yh(e);case"backfill":return Ch(e,t)}}var Ah=["setup","login","logout","status","doctor","backfill"];function wh(e){return Ah.includes(e)}function Ph(e){for(let n of e){if(n==="--")return!1;if(n==="-h"||n==="--help")return!0}return!1}function vh(e){let n=Yi(e.argv);if(n.kind==="chosen")return n.agent;e.error(`error: ${Ji}`),n.kind==="invalid"&&e.error(n.reason)}async function dp(e){if(Ph(e.argv))return e.log(Yt),0;if(e.argv.length===0)return e.log(Yt),1;let n=vh(e);if(n===void 0)return 1;let t;try{t=uh(e.argv)}catch(i){return e.error(`error: ${i.message}`),e.error(Yt),1}let{values:r,positionals:o}=t;if(o.length===0)return e.log(Yt),1;let s=o[0];if(!wh(s))return e.error(`error: unknown command '${s}'.`),e.error(Yt),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 xh(e,s,r);case"cursor":return _h(e,s,r);case"codex":return Oh(e,s,r)}return ht(n)}function cp(e,n=On.realpathSync){if(!e)return!1;let t=e;try{t=n(e)}catch{}return/[\\/]cli[\\/]index\.(c?js|ts)$/.test(t)}cp(process.argv[1])&&dp({cwd:process.cwd(),env:process.env,argv:process.argv.slice(2),isInteractive:!!process.stdin.isTTY,fetchFn:fetch,pluginRunner:po,readStdin:()=>ql(process.stdin),log:e=>process.stdout.write(`${e}
|
|
157
|
+
`),error:e=>process.stderr.write(`${e}
|
|
158
|
+
`)}).then(e=>{process.exitCode=e}).catch(e=>{process.stderr.write(`fatal: ${e.message}
|
|
159
|
+
`),process.exitCode=1});0&&(module.exports={isCliEntry,run});
|