@agenttrail/cli 0.2.2 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-77RT6DZY.js +186 -0
- package/dist/cli/index.cjs +63 -50
- package/dist/cli/index.js +1 -1
- package/dist/cursor/capture-hook.mjs +5 -5
- package/dist/cursor/flush.mjs +13 -11
- package/dist/index.cjs +65 -52
- package/dist/index.d.cts +17 -2
- package/dist/index.d.ts +17 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/marketplace.json +2 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/dist/chunk-EFOSESFZ.js +0 -173
package/dist/chunk-EFOSESFZ.js
DELETED
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
import{spawn as gb}from"child_process";import{readFileSync as To,realpathSync as mb}from"fs";import{homedir as K,hostname as yb}from"os";import{basename as Jp,dirname as Vt,join as hb}from"path";import{createInterface as Sb}from"readline/promises";import{parseArgs as Rb}from"util";var fa="pubsub:sse:org:",sf=`${fa}*`;var me={mode:"standard"};var _o=["Free","Pro","Team","Business","Enterprise"];var af=new Set(["Pro","Team","Business","Enterprise"]);function Oo(e){let n=_o.indexOf(e);return _o.slice(n+1).find(t=>af.has(t))??null}var Cn={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 ga(e){return Ae(e,"login")}import{mkdirSync as kf,readFileSync as Tf,unlinkSync as _f}from"fs";import{dirname as Of,join as zo}from"path";import{randomBytes as uf}from"crypto";import{chmodSync as lf,lstatSync as qt,mkdirSync as ya,readFileSync as $o,readlinkSync as ha,realpathSync as ct,renameSync as pf,statSync as Uo,unlinkSync as ff,writeFileSync as gf}from"fs";import{dirname as ue,join as Tn,resolve as en}from"path";var st="agenttrail.agent.vendor",xo="agenttrail.tool.vendor_name",Ao=255,it="agenttrail.usage.reported",wo="agenttrail.time.approximate",vo="agenttrail.span.synthetic",Po="agenttrail.subagent.conversation_id";var No="agenttrail.turn.closed_by";var Do="agenttrail.mcp.server_unknown",jo="agenttrail.pep.blocked";var Fo="18a5d968-0fa2-5c8a-88da-0b29d80105d4",at="7f050af4-796e-5b05-94c2-dba78bcdc7c2",J="https://ingest.agenttrail.sh";function dt(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 Lo="ef5f62d8-0a65-5a09-be97-07afd9bdab87",Mo="7d12feb9-faf4-5d1a-b711-9362724c66b3";var ie="claude-code";var ut="CLAUDE_CODE_ENABLE_TELEMETRY",Bo="CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",_n="OTEL_TRACES_EXPORTER",Go="OTEL_EXPORTER_OTLP_PROTOCOL",Le="OTEL_EXPORTER_OTLP_ENDPOINT",H="OTEL_EXPORTER_OTLP_HEADERS",nn="OTEL_RESOURCE_ATTRIBUTES",Se=["OTEL_LOG_USER_PROMPTS","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_TOOL_CONTENT"],Me="agenttrail.org.id",Ko="agenttrail.project.id",Ho="agenttrail.agent.id",Vo=st,Wo="agenttrail.developer.id",Qo="agenttrail.project",tn=255;function he(e){return encodeURIComponent(e)}function Jo(e){let n=[`${Me}=${he(e.orgId)}`,`${Ko}=${he(e.projectId)}`];if(e.agentId&&n.push(`${Ho}=${he(e.agentId)}`),n.push(`${Vo}=${he(ie)}`),e.developerId&&n.push(`${Wo}=${he(e.developerId)}`),e.project){let t=he(e.project);t.length<=tn&&n.push(`${Qo}=${t}`)}return n.join(",")}function Xt(e){let n={[ut]:"1",[Bo]:"1",[_n]:"otlp",[Go]:"http/protobuf",[Le]:e.endpoint??J,[nn]:Jo(e)};if(e.captureContent!==void 0){let t=e.captureContent?"1":"0";for(let r of Se)n[r]=t}return n}function Sa(e){return e.team||!e.apiKey?{}:{[H]:`Authorization=Bearer ${e.apiKey}`}}function Yo(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];ye(s)&&ye(o)?t[r]=Yo(s,o):t[r]=o}return t}function ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Yt=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 mf(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function V(e,n){let t;try{t=n(e)}catch(o){if(mf(o))return null;throw o}let r;try{r=JSON.parse(t)}catch{throw new Yt(e,"not valid JSON")}if(!ye(r))throw new Yt(e,"not a JSON object");return r}function P(e,n,t={}){let r=e,o=!0;try{r=ct(e)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=qt(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=en(ue(r),ha(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=Uo(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${uf(6).toString("hex")}`;try{gf(i,n,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&lf(i,s),pf(i,r)}catch(a){try{ff(i)}catch{}throw a}}function w(e){return Tn(e,".claude","settings.json")}function M(e){return Tn(e,".claude","settings.local.json")}var Ue=".claude/settings.local.json";function $e(e,n,t={}){let r=M(e),o=t.readFile??(p=>$o(p,"utf8")),s=t.writeFile??((p,l,f)=>P(p,l,f!==void 0?{mode:f}:{})),i=t.mkdir??(p=>ya(p,{recursive:!0})),a=V(r,o),d=a??{},c=a!==null,u=Yo(d,{env:n});return i(ue(r)),s(r,`${JSON.stringify(u,null,2)}
|
|
2
|
-
`,384),{path:r,env:n,merged:c}}function Re(e,n,t={},r={}){let o=Zt(e,{env:n},t,r);return{path:o.path,env:n,merged:o.merged}}function Zt(e,n,t={},r={}){let o=w(e),s=t.readFile??(l=>$o(l,"utf8")),i=t.writeFile??((l,f,m)=>P(l,f,m!==void 0?{mode:m}:{})),a=t.mkdir??(l=>ya(l,{recursive:!0})),d=V(o,s),c=d??{},u=d!==null,p=Yo(c,n);return a(ue(o)),r.mode!==void 0?i(o,`${JSON.stringify(p,null,2)}
|
|
3
|
-
`,r.mode):i(o,`${JSON.stringify(p,null,2)}
|
|
4
|
-
`),{path:o,merged:u}}var kn=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 zt(e){return e.slice(ue(e).length).replace(/^[/\\]+/,"")}function Ra(e){try{return ct(e)}catch{let n=e;for(let t=0;t<8;t++)try{if(!qt(n).isSymbolicLink())break;n=en(ue(n),ha(n))}catch{break}try{return Tn(ct(ue(n)),zt(n))}catch{return en(n)}}}function yf(e){return ue(Ra(e))}function hf(e){try{return Tn(ct(ue(e)),zt(e))}catch{return en(e)}}function ma(e){try{return ct(e)}catch{return en(e)}}function Sf(e){let n=yf(e);for(;;){try{return qt(Tn(n,".git")),n}catch{}let t=ue(n);if(t===n)return;n=t}}var Rf=[".cfg",".dotfiles",".dotfiles.git",".dots",".local/share/yadm/repo.git",".config/yadm/repo.git",".yadm/repo.git"];function Ef(e,n){let t;try{t=Uo(n)}catch{return}let r=[zt(e)],o=ue(e);for(;;){try{let i=Uo(o);if(i.dev===t.dev&&i.ino===t.ino)return r.reverse().join("/")}catch{return}let s=ue(o);if(s===o)return;r.push(zt(o)),o=s}}function bf(e,n,t){let r=[],o=t.env?.GIT_DIR?.trim();o&&r.push({gitDir:en(e,o),workTree:ma(en(e,t.env?.GIT_WORK_TREE?.trim()||e))});for(let a of Rf){let d=Tn(e,a);try{qt(d)}catch{continue}r.push({gitDir:d,workTree:ma(e)})}let s=[...new Set([hf(n),Ra(n)])],i;for(let{gitDir:a,workTree:d}of r)for(let c of s){let u=Ef(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 On(e,n,t={},r={}){let o=w(e),s=Sf(o);if(s!==void 0)throw new kn(o,s);if(r.dotfiles){let i=bf(e,o,r.dotfiles);if(i&&i.state!=="untracked")throw new kn(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 Re(e,n,t,{mode:384})}var er="npx -y @agenttrail/cli@latest login --refresh --agent claude",If=["agenttrail login --refresh","npx -y @agenttrail/claude-code-exporter@latest login --refresh"];function Cf(){return{hooks:[{type:"command",command:er}]}}function nr(e,n={}){let t=w(e),r=n.readFile??(p=>$o(p,"utf8")),o=[],s=V(t,r),i=ye(s)?s.hooks:void 0,a=ye(i)?i.SessionStart:void 0;Array.isArray(a)&&(o=a);let d=o.map(p=>{if(!ye(p)||!Array.isArray(p.hooks))return p;let l=p.hooks.filter(f=>!(ye(f)&&typeof f.command=="string"&&If.includes(f.command)));return{...p,hooks:l}}).filter(p=>!(ye(p)&&Array.isArray(p.hooks)&&p.hooks.length===0)),u=d.some(p=>ye(p)&&Array.isArray(p.hooks)&&p.hooks.some(l=>ye(l)&&l.command===er))?d:[...d,Cf()];return Zt(e,{hooks:{SessionStart:u}},n)}var xf=448;function Ee(e,n="claude"){switch(n){case"claude":return zo(e,".agenttrail","credentials.json");case"cursor":return zo(e,".agenttrail","cursor","credentials.json");case"codex":return zo(e,".agenttrail","codex","credentials.json")}return Af(n)}function Af(e){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(e)}.`)}function $(e,n={},t="claude"){let r=n.readFile??(o=>Tf(o,"utf8"));try{let o=JSON.parse(r(Ee(e,t)));return wf(o)?o:null}catch{return null}}function xn(e,n,t={},r="claude"){let o=Ee(e,r),s=t.writeFile??((a,d,c)=>P(a,d,c!==void 0?{mode:c}:{}));return(t.mkdir??((a,d)=>kf(a,{recursive:!0,mode:d})))(Of(o),xf),s(o,`${JSON.stringify(n,null,2)}
|
|
5
|
-
`,384),o}function Ea(e,n={},t="claude"){let r=n.unlink??(o=>_f(o));try{r(Ee(e,t))}catch{}}function wf(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 ba={claude:"claude-code",cursor:"cursor",codex:"codex"};function W(e,n){return`npx -y @agenttrail/cli@latest ${n} --agent ${e}`}var Ia="choose --agent claude, --agent cursor or --agent codex";function lt(e){throw new Error(`AgentTrail has no path for the agent ${JSON.stringify(e)}.`)}var vf=40,Pf={claude:!0,cursor:!0,codex:!0};function Nf(e){return Object.hasOwn(Pf,e)?e:void 0}function Ca(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=Nf(t);return r!==void 0?{kind:"chosen",agent:r}:{kind:"invalid",reason:`unknown agent ${JSON.stringify(t.slice(0,vf))}.`}}var Df=" 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 jf(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 lt(e)}function tr(e){return(e==="claude"?"WARNING: Content capture":"WARNING: --capture-content")+Df+jf(e)}var rn="https://api.agenttrail.sh",ka="/api/v1";function we(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(ka)?t:`${t}${ka}`}var rr=(e,n)=>fetch(e,n),Ff=e=>new Promise(n=>setTimeout(n,e));function or(e,n){return`${e.replace(/\/$/,"")}${n}`}async function sr(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 Ta(e,n=rr,t={}){let{ok:r,status:o,data:s}=await sr(n,or(e,"/auth/device/start"),{...t});if(!r||!Lf(s))throw new Error(`device/start failed (HTTP ${o})`);return s}async function _a(e,n,t){let r=t.fetchFn??rr,o=t.sleepFn??Ff,s=t.now??(()=>Date.now()),a=(t.openedAt??s())+t.expiresIn*1e3,d=Math.max(1,t.interval),c=or(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 sr(r,c,{device_code:n});if(p&&xa(l))return l;if(Aa(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 An(e,n,t=rr){let{ok:r,status:o,data:s}=await sr(t,or(e,"/auth/device/refresh"),{refresh_token:n});if(!r||!xa(s)){let i=Aa(s)?s.error:`HTTP ${o}`;throw new Error(`device/refresh failed: ${i}`)}return s}async function Oa(e,n,t=rr){await sr(t,or(e,"/auth/device/revoke"),{refresh_token:n})}function Lf(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 xa(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 Aa(e){return typeof e!="object"||e===null?!1:typeof e.error=="string"}import{closeSync as Mf,openSync as Uf,readFileSync as sC,rmSync as $f,statSync as Bf,writeSync as Gf}from"fs";var Kf=3e4,Hf=(e,n)=>{let t=Uf(e,"wx");try{Gf(t,n)}finally{Mf(t)}},Vf=e=>{try{$f(e,{force:!0})}catch{}},Wf=e=>{try{let n=Bf(e);return Date.now()-n.mtimeMs}catch{return null}};async function ve(e,n){let t=e.io??{},r=t.acquire??Hf,o=t.release??Vf,s=t.age??Wf,i=t.now??(()=>Date.now()),a=t.sleep??(l=>new Promise(f=>setTimeout(f,l))),d=e.staleMs??Kf,c=e.timeoutMs??1e4,u=e.retryMs??50,p=i()+c;for(;;)try{r(e.lockPath,`${process.pid} ${new Date(i()).toISOString()}
|
|
6
|
-
`);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 va=1440*60*1e3;function Pa(e){switch(e){case"claude":return!1;case"cursor":case"codex":return!0}return lt(e)}function Na(e,n){return Pa(e.agent)?{apiEndpoint:n.api_endpoint??e.apiEndpoint,ingestEndpoint:n.endpoint}:{apiEndpoint:e.apiEndpoint,ingestEndpoint:e.ingestEndpoint}}async function ir(e){let n=await Ta(e.apiEndpoint,e.fetchFn,{client:ba[e.agent]});e.log(`
|
|
7
|
-
To authorize this device, visit:
|
|
8
|
-
${n.verification_uri}`),e.log(`and enter the code:
|
|
9
|
-
${n.user_code}
|
|
10
|
-
`);let t=n.verification_uri_complete??n.verification_uri;if(e.openBrowser)try{e.openBrowser(t)}catch{}return e.log("Waiting for authorization..."),_a(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 wn(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}:{},...Pa(e.agent)?{api_endpoint:t.apiEndpoint}:{}}}function wa(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<=va}async function ar(e,n){let t=`Not logged in; run \`${W(e.agent,"login")}\`.`,r=$(e.homeDir,e.credentialsIO,e.agent);if(!r)return e.log(t),"not-logged-in";if(!wa(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=$(e.homeDir,e.credentialsIO,e.agent);if(!s)return e.log(t),"not-logged-in";if(!wa(s,e.now))return e.log("Ingest token is fresh; nothing to do."),"no-op";let i=Na(e,s),a=await An(i.apiEndpoint,s.refresh_token,e.fetchFn);return n(a,i),e.log("Refreshed ingest token."),"rotated"})}async function dr(e){let n=$(e.homeDir,e.credentialsIO,e.agent);if(n)try{await Oa(Na(e,n).apiEndpoint,n.refresh_token,e.fetchFn)}catch{}return Ea(e.homeDir,e.credentialsIO,e.agent),n}function qo(e){return{...e,agent:"cursor"}}function Da(e,n,t=e){let r=wn(e,n,t);return xn(e.homeDir,r,e.credentialsIO,"cursor"),r}async function cr(e){let n=qo(e),t=await ir(n),r=Da(n,t);return e.log(`
|
|
11
|
-
Logged in for Cursor. Traces will be attributed to org ${r.org_id}.`),r}function ja(e){let n=qo(e);return ar(n,(t,r)=>Da(n,t,r))}async function Fa(e){let n=await dr(qo(e));e.log(n?"Logged out of Cursor.":"Not logged in for Cursor; nothing to do.")}function be(e){return $(e.homeDir,e.credentialsIO,"cursor")}import{mkdirSync as Kg,readFileSync as wr,statSync as Hg,writeFileSync as Vg}from"fs";import{join as bs}from"path";import{execFileSync as lg}from"child_process";import{isAbsolute as pg,join as fg}from"path";import{createHash as tg}from"crypto";import{existsSync as rg,mkdirSync as og,readdirSync as sg,readFileSync as ig,rmdirSync as ag,statSync as dg,unlinkSync as cg}from"fs";import{dirname as es,join as Ga}from"path";import{chmodSync as Qf,existsSync as Jf,mkdirSync as La,readdirSync as Yf,readFileSync as zf,renameSync as qf,rmSync as Ma,writeFileSync as Xf}from"fs";import{basename as Zf,dirname as $a,join as eg}from"path";var Be=448,D=384,Ua=0;function Ba(e,n=process.pid){return Ua+=1,eg($a(e),`.${Zf(e)}.${n}.${Ua}.tmp`)}var O={readFile(e){return zf(e)},writeFileAtomic(e,n,t){La($a(e),{recursive:!0,mode:Be});let r=Ba(e);try{Xf(r,n,{mode:t}),Qf(r,t),qf(r,e)}catch(o){throw Ma(r,{force:!0}),o}},mkdirp(e,n){La(e,{recursive:!0,mode:n})},remove(e){Ma(e,{recursive:!0,force:!0})},exists(e){return Jf(e)},readdir(e){return Yf(e).sort()}};import{createHash as ng}from"crypto";import{join as Q}from"path";function v(e,n){let t=Q(e,".agenttrail",n),r=Q(t,"runtime");return{root:t,credentials:Q(t,"credentials.json"),install:Q(t,"install.json"),projects:Q(t,"projects.json"),runtime:r,captureHook:Q(r,"capture-hook.mjs"),flush:Q(r,"flush.mjs"),queueKey:Q(t,"queue.key"),enforcement:Q(t,"enforcement.json"),pepSnapshot:Q(t,"pep-snapshot.json"),queue:Q(t,"queue"),turns:Q(t,"turns"),senderLock:Q(t,"sender.lock"),senderState:Q(t,"sender-state.json"),backfillState:Q(t,"backfill-state.json")}}function Ge(e,n,t){return Q(v(e,n).queue,t)}function ur(e,n,t){return Q(v(e,n).turns,`${t}.json`)}function lr(e){return ng("sha256").update(e,"utf8").digest("hex").slice(0,16)}function ug(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xo(e){return e?.code==="ENOENT"}var G={readText(e){try{return ig(e,"utf8")}catch(n){if(Xo(n))return;throw n}},fileMode(e){try{return dg(e).mode&511}catch(n){if(Xo(n))return;throw n}},writeText(e,n,t){og(es(e),{recursive:!0,mode:Be}),P(e,n,{mode:t})},deleteFile(e){try{cg(e)}catch(n){if(!Xo(n))throw n}},dirExists(e){return rg(e)},removeDirIfEmpty(e){try{sg(e).length===0&&ag(e)}catch{}}};function ns(e,n){return Ga(v(e,n).root,"hooks-backups")}function pr(e,n,t){let r=tg("sha256").update(t,"utf8").digest("hex").slice(0,16);return Ga(ns(e,n),`${r}.json`)}function Ka(e,n,t,r){let o=r.readText(pr(e,n,t));if(o!==void 0)try{let s=JSON.parse(o);if(ug(s)&&s.v===1&&typeof s.existed=="boolean")return s}catch{}}var Zo=e=>({path:e,changed:!1,created:!1,deleted:!1,restored:!1,removed:0});function Ha(e){return e===void 0||(e&128)!==0}function Va(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:Zo(t)};if(!Ha(a))return{ok:!1,reason:`${t} is read-only`};let c=s.dirExists(es(t));try{if(Ka(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(pr(e,n,t),`${JSON.stringify(p,null,2)}
|
|
12
|
-
`,D)}if(s.readText(t)!==i)return{ok:!1,reason:`${t} changed while setup was running; run it again`};s.writeText(t,d.text,a??D)}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 Wa(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:Zo(t)};let c=r.remove(a,o);if(!c.ok)return{ok:!1,reason:`${t} ${c.reason}`};if(!c.changed)return{ok:!0,change:Zo(t)};if(!Ha(d))return{ok:!1,reason:`${t} is read-only`};let u=Ka(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??D),l=!0):!p&&u?.existed===!1&&c.empty&&s.keepFile!==!0?(i.deleteFile(t),f=!0,u.dirExisted===!1&&i.removeDirIfEmpty(es(t))):i.writeText(t,c.text,d??D),p||i.deleteFile(pr(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 gg=["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 gg)delete t[r];try{return{code:0,stdout:lg("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 le(e,n=L){return n(["rev-parse","--git-dir"],e).code===0}function Ie(e,n,t=L){let{code:r}=t(["ls-files","--error-unmatch","--",n],e);return r===0?"tracked":r===1?"untracked":"unknown"}function on(e,n,t=L){return t(["check-ignore","-q","--",n],e).code===0}function pt(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 pg(o)?o:fg(e,o)}function ft(e){return`/${e.replace(/[\\*?[\]]/g,t=>`\\${t}`).replace(/ $/,"\\ ")}`}function Qa(e){return e===void 0||e===""?[]:e.replace(/\n$/,"").split(`
|
|
13
|
-
`)}function fr(e,n,t,r={}){let o=r.git??L,s=r.io??G;if(!le(e,o))return{ok:!0,state:"not-a-repo"};if(on(e,n,o))return{ok:!0,state:"already-ignored"};let i=pt(e,o);if(i===void 0)return{ok:!1,reason:"git could not say where this repo's info/exclude file is"};let a=ft(n),d;try{d=s.readText(i);let u=[...Qa(d),t,a];s.writeText(i,`${u.join(`
|
|
14
|
-
`)}
|
|
15
|
-
`,s.fileMode(i)??420)}catch(c){return{ok:!1,reason:`${i} could not be written \u2014 ${c.message}`}}if(on(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 Ja(e,n,t,r={}){let o=r.git??L,s=r.io??G,i=pt(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=ft(n),c=Qa(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(`
|
|
16
|
-
`)}
|
|
17
|
-
`;try{s.writeText(i,p,s.fileMode(i)??420)}catch{return!1}return!0}import{execFileSync as Rg}from"child_process";import{basename as Xa}from"path";import{v5 as Za}from"uuid";import{existsSync as ts,readFileSync as hg}from"fs";import{homedir as Sg}from"os";import{dirname as za,join as rs}from"path";import{z as gt}from"zod";var sn="agenttrail.ingest.mode",an="agenttrail.ingest.batch_id",vn="backfill";var gr=gt.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"),mg=gt.string().min(1).refine(e=>e.startsWith("dlv_"),{message:"AgentTrail API key must start with 'dlv_'"}),yg=gt.object({orgId:gr,projectSlug:gt.string().min(1),projectId:gr.optional(),agentId:gr.optional(),developerId:gr.optional(),apiKey:mg.optional(),captureContent:gt.boolean().optional()}).strict();function mr(e){return yg.parse(e)}var B=".agenttrail.json";function os(e=Sg()){return rs(e,".agenttrail","config.json")}function qa(e){return ts(rs(e,".git"))}function Ya(e){let n=hg(e,"utf8"),t;try{t=JSON.parse(n)}catch(r){throw new Error(`Malformed ${B} at ${e}: not valid JSON (${r.message})`)}return mr(t)}function ss(e){let n=e;for(;;){let t=rs(n,B);if(ts(t))return t;if(qa(n))return null;let r=za(n);if(r===n)return null;n=r}}function Pn(e){let n=e;for(;;){if(qa(n))return n;let t=za(n);if(t===n)return null;n=t}}function dn(e){return Pn(e)??e}function mt(e,n={}){let t=Pn(e),r=ss(e);if(r)return{config:Ya(r),source:"project",configPath:r,gitRoot:t};if(n.allowGlobal!==!1){let o=n.globalPath??os();if(ts(o))return{config:Ya(o),source:"global",configPath:o,gitRoot:t}}return{config:null,source:null,configPath:null,gitRoot:t}}function yr(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 ed(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 nd(e){try{return Rg("git",["remote","get-url","origin"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function cn(e,n={}){let r=(n.readGitRemote??nd)(e);if(r){let s=ed(r);if(s){let i=hr(s);if(i)return{slug:i,source:"remote"}}}let o=hr(Xa(e));return o?{slug:o,source:"directory"}:null}function Nn(e,n={}){return cn(e,n)?.slug??null}function Dn(e,n={}){let r=(n.readGitRemote??nd)(e);if(r){let s=ed(r)?.split("/").pop()?.trim();if(s)return s}return Xa(dn(e))}function z(e,n){return Za(`${e}:${n}`,Fo)}function Ce(e,n){return Za(`${e}:${n}`,at)}import{homedir as Eg}from"os";import{join as bg}from"path";var q="AGENTTRAIL_PEP_ENFORCE",is="AGENTTRAIL_PEP_URL",as="AGENTTRAIL_PEP_HOLD_URL",ds="AGENTTRAIL_PEP_SNAPSHOT_URL",X="AGENTTRAIL_PEP_TOKEN",cs="AGENTTRAIL_PEP_TIMEOUT_MS",yt="AGENTTRAIL_PEP_ORG_ID",td="AGENTTRAIL_PEP_SNAPSHOT_PATH";var jn=3e3;function Sr(e=Eg()){return bg(e,".agenttrail","pep-snapshot.json")}function Ig(e){let n=e?.trim();return n&&n.length>0?n:void 0}function rd(e){return`${we(e)}/policies/evaluate`}function Fn(e){return`${we(e)}/policies/compiled-snapshot`}function od(e){return`${we(e)}/policies/hold`}function sd(e){let n={[is]:rd(e.apiBase),[as]:od(e.apiBase),[ds]:Fn(e.apiBase),[cs]:String(e.timeoutMs??jn)};return e.orgId&&(n[yt]=e.orgId),n}var us={[q]:"1"};function id(e){let n=Ig(e.token);return n?{[X]:n}:{}}import{mkdirSync as vg,readdirSync as Pg,readFileSync as Mn}from"fs";import{dirname as Ng,join as ps}from"path";import{existsSync as ad,mkdirSync as Cg,readFileSync as dd,unlinkSync as kg}from"fs";import{dirname as Tg,join as ls}from"path";var _g=B,Ke=class extends Error{name="SetupRefusedError"};function Ln(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===B?"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 Rr(e,n,t={}){let r=t.git??L;if(!le(e,r))return;let o=cd(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=Ie(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 Og="# agenttrail: per-machine files written by `agenttrail setup --agent claude`";function cd(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 ke(e,n,t={}){let r=t.git??L;if(!le(e,r))return{ok:!0,state:"not-a-repo"};let o=cd(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=Ie(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,Og,{git:r,...t.excludeIO?{io:t.excludeIO}:{}});return i.ok?xg(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 xg(e,n,t,r){let o=`${n}.tmp-0-sample`;if(on(e,o,t))return!0;let s=pt(e,t);if(s===void 0)return!1;let i=r.readText(s),a=i===void 0||i===""?[]:i.replace(/\n$/,"").split(`
|
|
18
|
-
`),d=`${ft(n)}.tmp-*`,c=r.fileMode(s)??420;try{r.writeText(s,`${[...a,d].join(`
|
|
19
|
-
`)}
|
|
20
|
-
`,c)}catch{return!1}if(on(e,o,t))return!0;try{r.writeText(s,i??"",c)}catch{}return!1}var Ag=[B,`${B}.tmp-*`,".claude/settings.local.json",".claude/settings.local.json.tmp-*"];function Er(e,n={}){let t=n.git??L;if(!le(e,t))return!1;let r=ls(e,".gitignore"),o=n.readFile??(h=>dd(h,"utf8")),s=n.writeFile??((h,S)=>P(h,S));if(!(n.exists??(h=>ad(h)))(r))return!1;let a=o(r),d=Ie(e,".gitignore",t)==="tracked",c=d?t(["show",":./.gitignore"],e):void 0,u=new Set(c!==void 0&&c.code===0?c.stdout.split(`
|
|
21
|
-
`).map(h=>h.trim()):[]),p=new Set(Ag.filter(h=>!u.has(h))),l=a.split(`
|
|
22
|
-
`),f=l.filter(h=>!p.has(h.trim()));if(f.length===l.length)return!1;let m=f.join(`
|
|
23
|
-
`);if(s(r,m),![B,".claude/settings.local.json"].every(h=>{let S=ke(e,h,n);return S.ok?on(e,h,t):S.tracked}))return s(r,a),!1;if(m.trim()===""&&!d)try{(n.unlink??kg)(r)}catch{}return!0}function ik(e,n={},t=_g){let r=ls(e,".gitignore"),o=n.readFile??(f=>dd(f,"utf8")),s=n.writeFile??((f,m)=>P(f,m)),i=n.exists??(f=>ad(f)),a=[t,`${t}.tmp-*`],d="";i(r)&&(d=o(r));let c=new Set(d.split(`
|
|
24
|
-
`).map(f=>f.trim())),u=a.filter(f=>!c.has(f));if(u.length===0)return!1;let p=d.length>0&&!d.endsWith(`
|
|
25
|
-
`),l=`${d}${p?`
|
|
26
|
-
`:""}${u.join(`
|
|
27
|
-
`)}
|
|
28
|
-
`;return s(r,l),!0}function br(e,n,t={},r={}){let o=ls(e,B),s=t.writeFile??((c,u,p)=>P(c,u,p!==void 0?{mode:p}:{})),i=typeof n.apiKey=="string"&&n.apiKey.length>0,a=!1;if(!r.committable||i){let c=ke(e,B,t);if(i&&!c.ok)throw new Ke(Ln(B,c))}let d=i?384:420;return s(o,`${JSON.stringify(n,null,2)}
|
|
29
|
-
`,d),{path:o,gitignoreModified:a,mode:d}}var wg=448;function Ir(e,n={}){let t=os(n.home),r=n.writeFile??((i,a,d)=>P(i,a,d!==void 0?{mode:d}:{}));(n.mkdir??((i,a)=>Cg(i,{recursive:!0,mode:a})))(Tg(t),wg);let s=384;return r(t,`${JSON.stringify(e,null,2)}
|
|
30
|
-
`,s),{path:t,mode:s}}var Cr="npx -y @agenttrail/cli@latest capture --agent claude",gs=["Stop","SessionEnd"],Dg=15,ud="2.1.282",jg=[ut,Bo,_n,Go,Le,H,"OTEL_LOG_RAW_API_BODIES"],ld=/^https?:\/\/[A-Za-z0-9.:\-_/~%]+$/,pd=/^Authorization=Bearer dlv_[^\s,]+$/;function Fg(e){if(e===void 0||e===J)return Cr;if(!ld.test(e))throw new Error(`the ingest endpoint ${e} has characters a hook command can't carry`);return`${Cr} --endpoint ${e}`}function ms(e){return typeof e=="string"&&(e===Cr||e.startsWith(`${Cr} `))}function Lg(e,n){return e==="Stop"?{type:"command",command:n,async:!0}:{type:"command",command:n,timeout:Dg}}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mg(e,n){return JSON.stringify(e)===JSON.stringify(n)}function Ug(e,n){let t=!1,r=!1,o=e.map(s=>{if(!Y(s)||!Array.isArray(s.hooks))return s;let i=s.hooks.filter(a=>!Y(a)||!ms(a.command)?!0:!t&&Mg(a,n)?(t=!0,!0):(r=!0,!1));return i.length===s.hooks.length?s:{...s,hooks:i}}).filter(s=>!(Y(s)&&Array.isArray(s.hooks)&&s.hooks.length===0));return t?r?o:e:[...o,{hooks:[n]}]}function ys(e){let n=e&&Y(e.hooks)?e.hooks:{},t={};for(let r of gs){let o=n[r];t[r]=Array.isArray(o)?o:[]}return t}function fd(e){let n=ys(e);return gs.every(t=>n[t].some(r=>Y(r)&&Array.isArray(r.hooks)&&r.hooks.some(o=>Y(o)&&ms(o.command))))}function gd(e){for(let n of Object.values(ys(e)))for(let t of n)if(!(!Y(t)||!Array.isArray(t.hooks))){for(let r of t.hooks)if(Y(r)&&ms(r.command))return r.command}}function md(e){if(e===void 0)return;let n=/ --endpoint (\S+)/.exec(e);return n?n[1]:void 0}function ht(e,n={},t={}){let r=w(e),o=t.readFile??(c=>Mn(c,"utf8")),s=V(r,o),i=Fg(n.endpoint),a=ys(s),d={};for(let c of gs){let u=Ug(a[c],Lg(c,i));u!==a[c]&&(d[c]=u)}return Object.keys(d).length===0?{path:r,changed:!1}:(Zt(e,{hooks:d},t),{path:r,changed:!0})}function _r(e){let n={[nn]:Jo(e)};if(e.captureContent===!1)for(let t of Se)n[t]="0";return n}function yd(e){let n=e[nn];return typeof n=="string"&&n.split(",").some(t=>t.startsWith(`${Me}=`))}function hd(e,n=!1){let t=[];for(let r of jg)r in e&&(r===_n&&e[r]==="none"||t.push(r));for(let r of Se)r in e&&(n||e[r]==="1")&&t.push(r);return t}function Sd(e,n){let t=V(e,n);return t&&Y(t.env)?t.env:{}}function Or(e,n={},t={}){let r=n.readFile??(p=>Mn(p,"utf8")),o=n.writeFile??((p,l,f)=>P(p,l,f!==void 0?{mode:f}:{})),s=n.mkdir??(p=>vg(p,{recursive:!0})),i=[],a=w(e),d=V(a,r);if(d&&Y(d.env)&&yd(d.env)){let p={...d.env},l=hd(p,t.captureContent===!0),f=m=>Se.includes(m)&&p[m]!=="1";i.push(...l.filter(m=>!f(m)));for(let m of l)delete p[m];l.length>0&&(s(Ng(a)),o(a,`${JSON.stringify({...d,env:p},null,2)}
|
|
31
|
-
`))}let c=M(e),u=V(c,r);if(u&&Y(u.env)){let p=u.env[H];if(typeof p=="string"&&pd.test(p)){let l={...u.env};delete l[H],i.push(`${H} (settings.local.json)`),o(c,`${JSON.stringify({...u,env:l},null,2)}
|
|
32
|
-
`,384)}}return i}function Rd(e,n){let t=e.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0),r=n.split(/[.+-]/).map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++){let s=(t[o]??0)-(r[o]??0);if(s!==0)return s}return 0}function $g(e){let n=e[nn];if(typeof n!="string")return[];let t=[];for(let r of n.split(",")){let o=r.indexOf("=");if(!(o<0||r.slice(0,o).trim()!==Me))try{t.push(decodeURIComponent(r.slice(o+1).trim()))}catch{}}return t}function Bg(e){let n=e[_n];return e[ut]==="1"&&typeof n=="string"&&n.split(",").includes("otlp")&&typeof e[Le]=="string"&&typeof e[H]=="string"}function kr(e,n){try{return Sd(e,n)}catch{return{}}}function Gg(e=process.platform,n=t=>Pg(t)){let t=e==="darwin"?"/Library/Application Support/ClaudeCode":e==="win32"?"C:\\Program Files\\ClaudeCode":"/etc/claude-code",r=[ps(t,"managed-settings.json")];try{let o=ps(t,"managed-settings.d");for(let s of n(o).sort())s.endsWith(".json")&&r.push(ps(o,s))}catch{}return r}function Tr(e,n){try{return{env:Sd(e,n),failed:!1}}catch{return{env:{},failed:!0}}}function hs(e,n){let t=n.read??(a=>Mn(a,"utf8")),r=n.managedPaths??Gg(),o=r.map(a=>Tr(a,t)),s=[w(e),M(e)],i=s.map(a=>Tr(a,t));return{read:t,managed:o,user:i,managedPaths:r,userPaths:s}}function Ss(e,n,t={}){let{managed:r,user:o}=hs(e,t),s=[...o,...r].map(c=>c.env),i=Object.assign({},...s),a=i[_n];return i[ut]==="1"&&typeof a=="string"&&a.split(",").includes("otlp")&&typeof i[Le]=="string"&&s.some(c=>$g(c).includes(n))}function Ed(e,n=t=>Mn(t,"utf8")){return Bg({...kr(w(e),n),...kr(M(e),n)})}function Rs(e,n,t,r={}){let o=r.read??(u=>Mn(u,"utf8")),s=null;try{s=V(w(e),o)}catch{s=null}let i=s&&Y(s.env)?s.env:{},a=kr(M(e),o),d=[...hd(i),...typeof a[H]=="string"?[`${H} (settings.local.json)`]:[]];return{path:Ss(n,t,r)?"otel":fd(s)?"upload":"none",ignoredProjectKeys:d}}function Es(e,n){try{return Rr(e,".claude/settings.json",n?{git:n}:{})!==void 0?!0:Pn(e)!==null&&!le(e,n)}catch{return!0}}function bd(e,n,t={},r={}){try{if(e===n||Es(e,r.git))return!1;let o=t.readFile??(l=>Mn(l,"utf8")),s=V(w(e),o);if(!s||fd(s))return!1;let i=Y(s.env)?s.env:{};if(!yd(i))return!1;let a=Y(s.hooks)?s.hooks.SessionStart:void 0;if(!(Array.isArray(a)&&a.some(l=>Y(l)&&Array.isArray(l.hooks)&&l.hooks.some(f=>Y(f)&&f.command===er))))return!1;let c=kr(M(e),o)[H];if(typeof c!="string"||!pd.test(c))return!1;let u=i[Le],p;if(typeof u=="string"&&u!==J){if(!ld.test(u))return!1;p=u}return ht(e,{endpoint:p},t).changed}catch{return!1}}function fs(e){let n=Se.filter(t=>e[t]!==void 0);return n.length===0?"absent":n.every(t=>e[t]==="1")?"on":"off"}function xr(e,n,t={}){let{read:r,managed:o,user:s,managedPaths:i,userPaths:a}=hs(n,t);return[...o.map((u,p)=>[i[p],u]),...s.map((u,p)=>[a[p],u]),[M(e),Tr(M(e),r)],["your environment",{env:{...t.env},failed:!1}]].find(([,u])=>u.failed||fs(u.env)==="off")?.[0]}function Ar(e,n,t,r={}){let{read:o,managed:s,user:i}=hs(n,r);if(xr(e,n,r)!==void 0)return!1;let a=Tr(w(e),o);return a.failed||fs(a.env)==="off"?!1:t!==void 0?t:[...s,i[0]].some(d=>fs(d.env)==="on")}function Wg(e){if(e.global)return;let n=Dn(e.settingsRoot);return n&&he(n).length>tn&&e.log(`WARNING: project "${n}" exceeds the ${tn}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`),n}function vr(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 Qg="dlv_ingest_",St=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}},kd=/^Authorization=Bearer (dlv_ingest_[^\s,]+)$/,Cs=[{key:X,tokenOf:e=>e.startsWith(Qg)?e:void 0,render:e=>e},{key:H,tokenOf:e=>kd.exec(e)?.[1],render:e=>`Authorization=Bearer ${e}`}];function Jg(e){let n=[],t=e[yt];typeof t=="string"&&t!==""&&n.push(t);let r=e[nn];if(typeof r=="string")for(let o of r.split(",")){let s=o.indexOf("=");if(!(s<0||o.slice(0,s).trim()!==Me))try{let i=decodeURIComponent(o.slice(s+1).trim());i!==""&&n.push(i)}catch{}}return n}function Id(e,n){let t={};for(let r of Cs){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 Td(e,n,t,r){let o=e.settingsIO?.readFile??(l=>wr(l,"utf8")),s=l=>{let f;try{f=V(l,o)}catch(g){throw new St(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(w(l.root))??{},h=Jg({...g,...f}).find(S=>S!==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=M(l),m=s(f);l===e.homeDir&&(c=m),m&&d({root:l,path:f,user:!1},m,Id(m,n))}let u=w(e.homeDir),p=s(u);if(p){let l=Id(p,n);for(let f of r.adopt?Cs:[]){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 _d(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 ks(e,n,t,r){let o=Td(e,n,t,{adopt:r.interactive});_d(e,o,t);for(let{target:s,updates:i}of o.stale)try{s.user?On(s.root,i,e.settingsIO,{dotfiles:r.interactive?Is(e):{...Is(e),log:void 0}}):$e(s.root,i,e.settingsIO)}catch(a){if(a instanceof kn){(r.interactive||Od(e,"user-settings-refused-warned"))&&e.log(`WARNING: ${a.message}`);continue}throw new St(s.path,a,"write")}}function Is(e){return{git:e.git??L,env:e.processEnv??process.env,log:e.log}}var Yg=1440*60*1e3;function Od(e,n){let t=bs(e.homeDir,".agenttrail",n),r=e.now?.()??Date.now();try{if(r-Hg(t).mtimeMs<Yg)return!1}catch{}try{Kg(bs(e.homeDir,".agenttrail"),{recursive:!0,mode:448}),Vg(t,"")}catch{}return!0}function xd(e,n){if(!e.global)return;let t={[H]:`Authorization=Bearer ${n}`};On(e.settingsRoot,t,e.settingsIO,{dotfiles:Is(e)})}function Ad(e,n){if(!e.global&&!e.setup&&Es(e.settingsRoot,e.git)){e.log(`Left ${w(e.settingsRoot)} unchanged: this repo tracks it (or git could not say), so a login does not edit it. Run \`npx -y @agenttrail/cli@latest setup --agent claude\` here to connect this project.`);return}let t=e.projectSlug??Nn(e.settingsRoot)??"default",r={orgId:n,projectId:z(n,t),agentId:Ce(n,ie),captureContent:e.captureContent,project:Wg(e)};e.global?Re(e.settingsRoot,Xt({...r,endpoint:e.ingestEndpoint}),e.settingsIO):(Re(e.settingsRoot,_r(r),e.settingsIO),Or(e.settingsRoot,e.settingsIO,{captureContent:e.captureContent}),ht(e.settingsRoot,{endpoint:e.ingestEndpoint},e.settingsIO)),nr(e.settingsRoot,e.settingsIO)}function Ts(e,n={}){let t=n.readFile??(s=>wr(s,"utf8")),r=s=>{try{let i=V(s,t)?.env;return typeof i=="object"&&i!==null?i:{}}catch{return{}}},o=r(M(e))[H];if(!(typeof o!="string"||kd.exec(o)===null)&&!(H in r(w(e))))return`Capture token not in ${w(e)}, so Claude Code sessions outside your home folder upload nothing. Run \`npx -y @agenttrail/cli@latest setup --agent claude --global\` to repair.`}function _s(e,n,t){let r=wn(vr(e),n);return xn(e.homeDir,r,e.credentialsIO),t.registerHook&&xd(e,n.ingest_token),ks(e,n.ingest_token,n.org_id,{interactive:t.registerHook}),t.registerHook&&Ad(e,n.org_id),r}function He(e,n){let t=Date.parse(e.ingest_token_expires_at);return Number.isNaN(t)?!0:t<=(n?.()??Date.now())}function wd(e,n){xd(e,n.ingest_token),Ad(e,n.org_id),ks(e,n.ingest_token,n.org_id,{interactive:!0})}async function Os(e){let n=await ir(vr(e)),t=_s(e,n,{registerHook:!0});return e.log(`
|
|
33
|
-
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 Pr(e){let n=await ar(vr(e),s=>_s(e,s,{registerHook:!1})),t=Ts(e.homeDir,e.settingsIO);t&&Od(e,"user-settings-repair-hinted")&&e.log(t);let r=n==="no-op"?$(e.homeDir,e.credentialsIO):void 0;if(!r)return n;let o=Td(e,r.ingest_token,r.org_id,{adopt:!1});return o.stale.length===0?(_d(e,o,r.org_id),n):(await ve({lockPath:`${Ee(e.homeDir)}.lock`,io:e.lockIO},async()=>{let s=$(e.homeDir,e.credentialsIO);s&&ks(e,s.ingest_token,s.org_id,{interactive:!1})}),n)}async function vd(e){let n=$(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 An(e.apiEndpoint,n.refresh_token,e.fetchFn);try{let o=_s(e,r,{registerHook:!1});return{ingestToken:o.ingest_token,tier:o.org_tier}}catch(o){if(!(o instanceof St))throw o;e.log(`WARNING: ${o.message}`);let s=$(e.homeDir,e.credentialsIO);return{ingestToken:r.ingest_token,tier:s?.org_tier??n.org_tier}}})}catch{return{tier:n.org_tier}}}async function Pd(e){let n=null;try{n=await dr(vr(e))}finally{zg(e.settingsRoot,e.settingsIO),Cd(M(e.homeDir),e.settingsIO,384),Cd(w(e.homeDir),e.settingsIO)}e.log(n?"Logged out.":"Not logged in; nothing to do.")}function Cd(e,n={},t){let r=n.readFile??(c=>wr(c,"utf8")),o=n.writeFile??((c,u,p)=>P(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 Cs){let u=a[c.key];typeof u!="string"||c.tokenOf(u)===void 0||(delete a[c.key],c.key===X&&delete a[q],d=!0)}d&&o(e,`${JSON.stringify(s,null,2)}
|
|
34
|
-
`,t)}function zg(e,n={}){let t=bs(e,".claude","settings.local.json"),r=n.readFile??(a=>wr(a,"utf8")),o=n.writeFile??((a,d,c)=>P(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&&H in i&&(delete i[H],o(t,`${JSON.stringify(s,null,2)}
|
|
35
|
-
`,384))}function Nd(e){return Ae(e,"backfill")}var qg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Xg=/[A-Z][a-z]{3,}|[a-z]{4,}|[A-Z]{4,}/g,Zg=new Set("api app auth backend billing blue build canary checkout cluster controller default deploy deployment dev east frontend gateway green ingest ingress internal job main migration north prod production release replica rollout service south staging stage test web west worker".split(" "));function em(e){let n=new Map;for(let r of e)n.set(r,(n.get(r)??0)+1);let t=0;for(let r of n.values()){let o=r/e.length;t-=o*Math.log2(o)}return t}function nm(e){let n=0;for(let t of e.match(Xg)??[])n+=t.length;return n/e.replace(/[-_]/g,"").length>=.7}function tm(e){let n=e.split(/[-_]/);return n.length<5||n.some(t=>t.length>12)?!1:n.filter(t=>Zg.has(t.toLowerCase())).length>=3}function Dd(e){return e.length<32||qg.test(e)||/^sha(?:1|224|256|384|512)-/i.test(e)||nm(e)||tm(e)||/\d{8,}/.test(e)||e.split(/[-_]/).some(n=>n.length>=32&&/^[0-9a-fA-F]+$/.test(n))||/^[0-9a-fA-F]+$/.test(e)||!/[A-Za-z]/.test(e)||!/[0-9]/.test(e)?!1:em(e)>=4}var rm=/^(?:mysql\w*|mariadb[\w-]*)$/i,xs=/(?:^|[\s'"`(;|&/])(?:mysql\w*|mariadb[\w-]*)(?=$|[\s'"`);|&\\])/i,om=/[\s,:}\]]/;function sm(e){let n=e[3],t=n==="\\"&&e[4]==='"'?e[5]:n==='"'||n==="'"?e[4]:void 0;return t!==void 0&&om.test(t)}function im(e){return e.length===5?e.endsWith("''")||e.endsWith('""'):e.length===7&&e.endsWith('\\"\\"')}var jd=new RegExp(xs.source,"gi"),am=/^[A-Za-z_]\w*=/,dm="\uE000",cm=new Set(["then","do","else","elif","!","{","RUN","CMD","ENTRYPOINT"]),um=/^(?:[\w.-]+:|-|\*|\d+[.)]|[$%>#]|[\w.-]+@[\w.-]+:\S*[#$%>])$/,lm=new Map([["sudo",new Set(["-u","-g","-p","-C","-D","-r","-t","-U","--user","--group","--prompt","--chdir","--role","--type"])],["doas",new Set(["-u","-C"])],["env",new Set(["-u","-C","-S","--unset","--chdir","--split-string"])],["nice",new Set(["-n","--adjustment"])],["ionice",new Set(["-c","-n","-p","--class","--classdata"])],["stdbuf",new Set(["-i","-o","-e"])],["timeout",new Set(["-s","-k","--signal","--kill-after"])],["xargs",new Set(["-n","-I","-L","-P","-d","-s","-E","-a","--max-args","--replace","--max-procs","--delimiter","--arg-file"])],["nohup",new Set],["time",new Set(["-f","-o","--format","--output"])],["exec",new Set(["-a"])],["command",new Set],["watch",new Set(["-n","-d","--interval"])],["strace",new Set(["-o","-e","-p","-s"])],["chroot",new Set(["--userspec","--groups"])],["gosu",new Set],["su-exec",new Set],["eval",new Set],["npx",new Set(["-p","--package"])],["dotenv",new Set(["-e","-v","-p"])]]),pm=new Set(["timeout","chroot","gosu","su-exec"]),Fd=new Set(["-u","-w","-e","--user","--workdir","--env","--env-file","--detach-keys"]),fm=new Set([...Fd,"-a","-c","-h","-l","-m","-p","-v","--add-host","--annotation","--arch","--attach","--blkio-weight","--blkio-weight-device","--cap-add","--cap-drop","--cgroup-parent","--cgroupns","--cidfile","--cpu-period","--cpu-quota","--cpu-rt-period","--cpu-rt-runtime","--cpu-shares","--cpus","--cpuset-cpus","--cpuset-mems","--device","--device-cgroup-rule","--device-read-bps","--device-read-iops","--device-write-bps","--device-write-iops","--dns","--dns-option","--dns-search","--domainname","--entrypoint","--expose","--gpus","--gidmap","--group-add","--health-cmd","--health-interval","--health-retries","--health-start-interval","--health-start-period","--health-timeout","--hostname","--ip","--ip6","--ipc","--isolation","--kernel-memory","--label","--label-file","--link","--link-local-ip","--log-driver","--log-opt","--mac-address","--memory","--memory-reservation","--memory-swap","--memory-swappiness","--mount","--name","--net","--network","--network-alias","--oom-score-adj","--os","--pid","--pids-limit","--platform","--pod","--publish","--pull","--restart","--runtime","--secret","--security-opt","--shm-size","--stop-signal","--stop-timeout","--storage-opt","--sysctl","--tmpfs","--uidmap","--ulimit","--userns","--uts","--volume","--volume-driver","--volumes-from"]),gm=new Set(["-H","-c","-l","-n","-a","--host","--context","--config","--log-level","--tlscacert","--tlscert","--tlskey","--connection","--url","--identity","--root","--runroot","--storage-driver","--namespace","--address","--snapshotter"]),mm=new Set(["-f","-p","--file","--project-name","--project-directory","--env-file","--profile","--ansi","--progress","--parallel"]),ym=new Set(["-u","-w","-e","-l","-v","-p","--user","--workdir","--env","--index","--label","--volume","--publish","--name","--entrypoint"]),hm=new Set(["-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w","-B"]),Ld=new Set([";","|","&","(",")","`",`
|
|
36
|
-
`,"\r","{","}"]);function Md(e){let n=e.replace(/['"\\]/g,""),t=n.lastIndexOf("/");return(t===-1?n:n.slice(t+1)).toLowerCase()}function Sm(e,n){if(n.has(e))return!0;if(e.startsWith("--"))return!1;for(let t=1;t<e.length;t++)if(n.has(`-${e[t]}`))return t===e.length-1;return!1}function Un(e,n,t){let r=n;for(;r<e.length;){let o=e[r];if(o==="--")return r+1;if(!o.startsWith("-")||o==="-")return r;r+=Sm(o,t)?2:1}return r}function Rm(e,n,t){for(let r=n;r<t;r++){let o=e[r],s=o==="--entrypoint"?e[r+1]:o.startsWith("--entrypoint=")?o.slice(13):void 0;if(s!==void 0)return s.replace(/['"]/g,"")===""?null:s}return null}function Em(e){let n=0,t=!0;for(let r=0;r<=e.length&&n<e.length;r++){let o=e[n];if(t&&um.test(o)){n++;continue}if(t=!1,am.test(o)||cm.has(o)||o.includes(dm)){n++;continue}let s=Md(o),i=lm.get(s);if(i){n=Un(e,n+1,i),pm.has(s)&&n++;continue}let a=s==="docker"||s==="podman"||s==="nerdctl",d=a?Un(e,n+1,gm):n+1;if(a&&e[d]==="container"&&d++,s==="docker-compose"||a&&e[d]==="compose"){let c=Un(e,s==="docker-compose"?n+1:d+1,mm);if(e[c]!=="exec"&&e[c]!=="run")return o;n=Un(e,c+1,ym)+1;continue}if(a&&(e[d]==="exec"||e[d]==="run")){let c=e[d]==="run",u=Un(e,d+1,c?fm:Fd),p=c?Rm(e,d+1,u):null;if(p!==null)return p;n=u+1;continue}if(s==="kubectl"||s==="oc"){let c=e.indexOf("--",n),u=c===-1?[]:e.slice(n,c);if(!u.includes("exec")&&!u.includes("run")&&!u.includes("debug"))return null;n=c+1;continue}if(s==="ssh"){n=Un(e,n+1,hm)+1;continue}return o}return null}function Ud(e){let n=Em(e);return n!==null&&rm.test(Md(n))}function bm(e,n,t,r){for(let o=t;o+n.length<=r;o++)if($d(e,o)||e.startsWith(n,o)&&(n==='\\"'||e[o-1]!=="\\"))return o;return-1}function $d(e,n){let t=e[n];return t===`
|
|
37
|
-
`||t==="\r"?!0:t==="\\"&&(e[n+1]==="n"||e[n+1]==="r")}function Im(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===46||e===45}function Cm(e,n,t){let r=e[n]==="\\",o=n+(r?2:1),s=o;for(;s<o+65&&s<t&&Im(e.charCodeAt(s));)s++;if(s===o||s-o>64)return 0;if(r){if(e[s]!=="\\"||e[s+1]!=='"')return 0;s+=2}else{if(e[s]!=='"')return 0;s++}for(;s<t&&(e[s]===" "||e[s]===" ");)s++;return s<t&&e[s]===":"?s+1-n:0}function km(e,n,t){let r=Math.max(n,t-8),o=t-1;for(;o>=r&&(e[o]===" "||e[o]===" ");)o--;if(o<r)return!1;let s=e[o];if(s===":"||s===","||s==="["||s==="{")return!0;if(s!=="c")return!1;let i=o-1;for(;i>=r&&/[A-Za-z]/.test(e[i]);)i--;return i>=r&&e[i]==="-"&&(i===r||e[i-1]===" "||e[i-1]===" ")}function Tm(e,n,t){let r=Math.max(t,n-64),o=n;for(;o>r&&e[o-1]!==" "&&e[o-1]!==" ";)o--;return o}var Ve=null;function _m(e,n){let t=Math.max(0,n-512),r,o,s,i,a,d;for(Ve&&Ve.text===e&&Ve.i<=n&&Ve.i>=t?{i:r,at:o,found:s,blank:i,inside:a,word:d}=Ve:(r=t,o=t,s=t===0,i=!0,a=null,d=!1),Ve=null;r<n;){let c=e[r],u=e[r+1];if(c==="\\"){if(u==="n"||u==="r"){o=r+2,s=!0,i=!0,a=null,r+=2;continue}if(u==="\\"){r+=e[r+2]==="\\"&&e[r+3]==="n"?4:2,i=!1;continue}if(u===`
|
|
38
|
-
`||u==="\r"){r+=2;continue}if(u==="u"&&e.startsWith("0026",r+2)){o=r+6,s=!0,i=!0,r+=6;continue}}let p=c==="\\"&&u==='"'?'\\"':c==='"'||c==="'"?c:null;if(p){let l=Cm(e,r,n);if(l>0){r+=l,o=r,s=!0,i=!0,a=null;continue}let f=e[r+p.length];if(p===a&&d&&(f===" "||f===" ")){r+=p.length,i=!1,a=null;continue}if(p===a||!i&&(f===","||f==="]"||f==="}")){r+=p.length,o=r,s=!0,i=!0,a=null;continue}if(i||km(e,o,r)){r+=p.length,o=r,s=!0,i=!0,a=p,d=!0;continue}let m=bm(e,p,r+p.length,n);if(m===-1)return Ve={text:e,i:r,at:o,found:s,blank:i,inside:a,word:d},{start:Tm(e,r,o),unsure:!0,inside:a};if($d(e,m)){r+=p.length,i=!1;continue}r=m+p.length,i=!1;continue}Ld.has(c)?(o=r+1,s=!0,i=!0,d=!1,(c===`
|
|
39
|
-
`||c==="\r")&&(a=null)):c!==" "&&c!==" "?i=!1:d=!1,r++}return Ve={text:e,i:r,at:o,found:s,blank:i,inside:a,word:d},s&&o>=t?{start:o,unsure:!1,inside:a}:{start:Math.max(t,n-210),unsure:!0,outside:!0,inside:null}}var te=null;function Om(e,n,t){for((!te||te.text!==e||te.end>t)&&(te={text:e,last:-1,next:-1,end:t}),te.end=t;te.next<t;){te.next!==-1&&(te.last=te.next),jd.lastIndex=te.next===-1?0:te.next+1;let r=jd.exec(e);te.next=r?r.index:Number.POSITIVE_INFINITY}return te.last>=n}function xm(e,n){let t=n-1,r=e[t];if(r!==")"&&r!=="`")return!1;let o=-1;for(let d=t-1;d>=Math.max(0,t-64);d--)if(r===")"?e[d]==="("&&e[d-1]==="$":e[d]==="`"){o=d;break}if(o===-1)return!1;let s=r===")"?o-2:o-1,i=s-8;for(;s>=0&&s>i&&(e[s]===" "||e[s]===" ");)s--;let a=e[s];return s>=0&&!Ld.has(a)&&a!=='"'&&a!=="'"?!1:xs.test(e.slice(o+1,t))}function Am(e,n,t){let r=-1;if(t[0]==="[")r=n;else for(let s=n-1;s>=Math.max(0,n-512);s--){let i=e[s];if(i==="["){r=s;break}if(i==="]"||i===`
|
|
40
|
-
`)break}if(r===-1)return!1;let o=e.slice(r+1,n).split(",").map(s=>s.trim().replace(/["\\]/g,""));return Ud(o)}function Bd(e,n,t){if(e[0]==="["||e[0]===",")return Am(t,n,e);if(im(e))return!1;let r=_m(t,n);if(r.inside!==null&&e.startsWith(r.inside,3)||r.unsure&&sm(e))return!1;if(r.outside)return Om(t,r.start,n);let o=t.slice(r.start,n);if(r.unsure)return xs.test(o);let s=o.trim().split(/\s+/);return Ud(s)||xm(t,r.start)}function U(e,n){return n?`[REDACTED:${e}:${n}]`:`[REDACTED:${e}]`}var ws=String.raw`(?<=\\[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])`,Hd=`(?:\\b|${ws})`,vs=`(?:(?<![A-Za-z0-9_-])|${ws})`,Vd=String.raw`(?<!\[REDACTED:)`,Rt=String.raw`(?!["']?\[REDACTED:[a-z0-9:-]+\]["']?(?:[\s,;}\])]|$))`;function ae(e,n){return new RegExp(`${Hd}${e}`,n)}var wm=ae(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),vm=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"),Pm=ae(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),Nm=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"),Dm=ae(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`,"g"),jm=ae(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`,"gi"),Fm=ae(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),Lm=ae(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`,"g"),Mm=/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,Um=ae(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`,"gi"),$m=(()=>{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(`${Hd}${Vd}${n}(["']?\\s*[=:]\\s*)${Rt}${t}`,"gi")})(),Z="\uE000",Bm=new RegExp(`${vs}${Vd}([A-Z0-9]+(?:_[A-Z0-9]+)*_KEY(?==|["']\\s*:)|(?![Ii]dempotency-)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*-[Kk][Ee][Yy](?=["']?\\s*:))(["']?\\s*[=:]\\s*)${Rt}(?!["']?[~.]{0,2}/)(?:(")([^"${Z}]{4,})"|(')([^'${Z}]{4,})'|([^\\s"',;${Z}]{4,}))`,"g"),Gm=new RegExp(`${vs}((?:Proxy-)?Authorization["']?\\s*[=:]\\s*["']?)((?:Basic|Token|Digest|Negotiate|ApiKey|Api-Key)\\s+)?(?!Bearer\\s)${Rt}([^\\s"',;${Z}]{8,})`,"gi"),Gd="(?:[Mm][Yy][Ss][Qq][Ll]|[Mm][Aa][Rr][Ii][Aa][Dd][Bb])",As=`[^\\s"'\`;|&)\\\\${Z}]`,Wd='(?:\\\\\\\\|\\\\(?!["\\\\]))',Qd=`${As}*(?:${Wd}${As}*)*`,Km=`(?=${As}|${Wd})${Qd}`,Hm=`(?:'[^'\\n${Z}]*'|\\$'(?:[^'\\\\\\n${Z}]|\\\\[^\\n${Z}]){0,1024}'|\\\\"[^"\\\\\\n${Z}]*\\\\"|"[^"\\n${Z}]*")`,Vm=new RegExp(`(\\s-p)(?<=${Gd}(?:\\\\\\n|[^\\n]){0,200}\\s-p)${Rt}(?:${Hm}${Qd}|${Km})|([[,]\\s{0,8}\\\\?"-p)(?<=${Gd}[^\\n]{0,200}"-p)${Rt}[^"\\\\\\n${Z}]+(?=\\\\?")`,"g"),Wm=new RegExp([`${vs}([A-Za-z0-9_]*(?:ACCOUNT[_-]?ID|CF_ACCOUNT|CLOUDFLARE_ACCOUNT|AWS_ACCOUNT|GOOGLE_CLOUD_PROJECT|GCLOUD_PROJECT|GCP_PROJECT|CORE_PROJECT))(["']?\\s*[=:]\\s*)(["']?)([^\\s"',;<[${Z}][^\\s"',;${Z}]*)\\3`,`(--(?:account-id|account|owner-id|account-number))(=|\\s+)(["']?)(\\d{12}|[0-9a-f]{32})\\7(?![A-Za-z0-9])`,"(?<=\\barn:aws[a-z-]*:[a-z0-9-]*:[a-z0-9-]*:)\\d{12}(?![A-Za-z0-9])",`(?<=\\b(?:gcloud|gsutil|bq|firebase)\\b[^\\n;|&${Z}]{0,200}?)(--project(?:_id|-id)?)(=|\\s+)(["']?)([a-z][a-z0-9-]{4,28}[a-z0-9])\\11(?![A-Za-z0-9-])`].join("|"),"gi"),Qm=new RegExp(`(?:(?<![A-Za-z0-9_+/.%-])|${ws})(?<!==)(?<!sha(?:1|224|256|384|512)[-:])(?<!base64,)[A-Za-z0-9_-]{${32},}(?![A-Za-z0-9_+/=.%-])`,"g"),Jm=new RegExp(`[A-Za-z0-9_-]{${32}}`);function Nr(e,n,t,r){let o=t??"";return`${e}${n}${o}${r}${o}`}var Ym=ae(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`,"g"),zm=ae(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`,"g"),qm=ae(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`,"g"),Xm=ae(String.raw`(?:\+?\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?)?\d{2,4}[ .-]\d{2,4}[ .-]\d{2,4}\b`,"g"),Jd=[{id:"aws-access-key-id",kind:"secret",category:"aws",severity:"high",tier:"permissive",regex:wm,placeholder:()=>U("secret:aws")},{id:"pem-private-key",kind:"secret",category:"private-key",severity:"high",tier:"permissive",regex:Mm,placeholder:()=>U("secret:private-key")},{id:"jwt",kind:"secret",category:"jwt",severity:"high",tier:"permissive",regex:Lm,placeholder:()=>U("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Nm,placeholder:()=>U("secret:github")},{id:"slack-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Dm,placeholder:()=>U("secret:slack")},{id:"openai-key",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Pm,placeholder:()=>U("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:Fm,placeholder:()=>U("secret:connection-string")},{id:"basic-auth-url",kind:"secret",category:"basic-auth",severity:"high",tier:"permissive",regex:Um,placeholder:e=>`${e[1].toLowerCase()}://${U("secret:basic-auth")}@`},{id:"bearer-token",kind:"secret",category:"token",severity:"medium",tier:"permissive",regex:jm,placeholder:()=>`Bearer ${U("secret:bearer")}`},{id:"aws-secret-access-key",kind:"secret",category:"aws",severity:"medium",tier:"standard",regex:vm,placeholder:e=>`${e[1]}${e[2]}${U("secret:aws-secret")}`},{id:"env-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:$m,placeholder:e=>{let n=e[3]??e[5]??"";return`${e[1]}${e[2]}${n}${U("secret:env")}${n}`}},{id:"key-name-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:Bm,prefilter:/_KEY|-key/i,placeholder:e=>Nr(e[1]??"",e[2]??"",e[3]??e[5],U("secret:env"))},{id:"authorization-header",kind:"secret",category:"token",severity:"medium",tier:"standard",regex:Gm,prefilter:/authorization/i,placeholder:e=>`${e[1]??""}${e[2]??""}${U("secret:auth")}`},{id:"mysql-password-flag",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:Vm,prefilter:/mysql|mariadb/i,accept:Bd,placeholder:e=>`${e[1]??e[2]??""}${U("secret:password")}`},{id:"cloud-account-id",kind:"pii",category:"cloud-account",severity:"low",tier:"standard",regex:Wm,prefilter:/account|project|owner-id|arn:aws/i,placeholder:e=>{let n=U("pii:account");return e[1]!==void 0?Nr(e[1],e[2]??"",e[3],n):e[5]!==void 0?Nr(e[5],e[6]??"",e[7],n):e[9]!==void 0?Nr(e[9],e[10]??"",e[11],n):n}},{id:"generic-secret",kind:"secret",category:"generic",severity:"low",tier:"standard",regex:Qm,prefilter:Jm,accept:Dd,placeholder:()=>U("secret:generic")},{id:"email",kind:"pii",category:"email",severity:"low",tier:"standard",regex:Ym,placeholder:()=>U("pii:email")},{id:"ssn",kind:"pii",category:"ssn",severity:"high",tier:"standard",regex:zm,placeholder:()=>U("pii:ssn")},{id:"credit-card",kind:"pii",category:"credit-card",severity:"high",tier:"standard",regex:qm,placeholder:()=>U("pii:credit-card")},{id:"phone",kind:"pii",category:"phone",severity:"low",tier:"strict",regex:Xm,placeholder:()=>U("pii:phone")}],Yd=new Set(["credit-card"]);function zd(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 Zm={permissive:new Set(["permissive"]),standard:new Set(["permissive","standard"]),strict:new Set(["permissive","standard","strict"])},$n="\uE000",ey=new RegExp(`${$n}(\\d+)${$n}`,"g");function qd(e){return`${$n}${e}${$n}`}function ny(e,n=!1){if(e==="off")return[];let t=Zm[e];return Jd.filter(r=>r.id==="phone"?t.has("strict")||n:t.has(r.tier))}function ty(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 ry(e,n,t,r){if(n.prefilter&&!n.prefilter.test(e))return e;let o=Yd.has(n.id);return e.replace(n.regex,(...s)=>{let i=s[0];if(o&&!zd(i)||n.accept&&!n.accept(i,s[s.length-2],s[s.length-1]))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)),qd(d)})}function Pe(e){return e.mode==="off"?null:{patterns:ny(e.mode,e.enablePhone),denylist:ty(e.denylistPatterns)}}function Xd(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}:oy(e,t,r)}function oy(e,n,t){let r={},o=[],s=e.includes($n)?e.split($n).join(""):e;for(let a of n)s=ry(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]"),qd(d)});if(o.length===0)return{text:e,redactions:{},total:0};s=s.replace(ey,(a,d)=>o[Number(d)]);let i=0;for(let a in r)i+=r[a];return{text:s,redactions:r,total:i}}import{join as sy}from"path";var Ps="cursor",Dr="cursor",N="cursor",jr={agent:Ps,vendor:Dr,stateDir:N};function j(e){return v(e,N)}function Bn(e,n){return Ge(e,N,n)}function Zd(e){return sy(e,".cursor","projects")}function un(e){return e.replace(/^\/+/,"").replace(/[/. -]/g,"-")}function Et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ec(e){return typeof e=="string"&&e!==""}function iy(e,n){if(!Et(n))return{key:e};let t=ec(n.root)?n.root:void 0,r=Array.isArray(n.subfolders)?n.subfolders.map(o=>Et(o)&&ec(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 ay(e,n){let t;try{t=JSON.parse(e)}catch{return}if(!Et(t)||t.v!==1||!Et(t.projects))return;let r={},o=[];for(let[s,i]of Object.entries(t.projects))n(s,i)?r[s]=i:o.push(iy(s,i));return{registry:{v:1,projects:r},skipped:o}}var Ns=Object.freeze({v:1,projects:Object.freeze({})});function tc(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=ay(r,n);return o===void 0?{kind:"unreadable"}:{kind:"ok",registry:o.registry,skipped:o.skipped}}function nc(e){return e.length>1?e.replace(/\/+$/,""):e}function dy(e,n){let t=nc(e),r=nc(n);return r===t||r.startsWith(t.endsWith("/")?t:`${t}/`)}function cy(e,n){return[...e,...n!==void 0?[n]:[]].filter(r=>typeof r=="string"&&r!=="")}function rc(e,n,t){let r=cy(n,t),o;for(let s of Object.values(e.projects))r.some(i=>dy(s.root,i))&&(o===void 0||s.root.length>o.root.length)&&(o=s);return o}function oc(e,n){if(e.kind==="unreadable")throw n();return e.kind==="ok"?e.registry:Ns}function Ds(e,n){return Et(e)?Object.fromEntries(Object.entries(e).filter(([t])=>!n.has(t))):{}}function sc(e){return`${JSON.stringify(e,null,2)}
|
|
41
|
-
`}function ic(e,n,t=O){let r=(()=>{try{return t.exists(e)?t.readFile(e).toString("utf8"):void 0}catch{return}})(),o=sc(n);return r===o?"unchanged":(t.writeFileAtomic(e,o,D),"written")}function ac(e,n,t,r=O){if(n.projects[t]===void 0)return!1;let o={...n.projects};return delete o[t],r.writeFileAtomic(e,sc({v:1,projects:o}),D),!0}function Fr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ne(e){return typeof e=="string"&&e!==""}function dc(e){return e==="project"||e==="user"}var ly=new Set(["flag","agenttrail-json","derived"]);function py(e){return Fr(e)&&Ne(e.path)&&Ne(e.transcriptFolder)&&dc(e.install)&&Ne(e.registeredAt)}function fy(e,n){return Fr(n)?n.projectKey===e&&Ne(n.root)&&Ne(n.transcriptFolder)&&Ne(n.orgId)&&Ne(n.projectSlug)&&Ne(n.projectId)&&ly.has(n.projectSource)&&typeof n.projectLabel=="string"&&(n.developerId===void 0||typeof n.developerId=="string")&&typeof n.captureContent=="boolean"&&dc(n.install)&&Ne(n.registeredAt)&&(n.subfolders===void 0||Array.isArray(n.subfolders)&&n.subfolders.every(py)):!1}var cc=Ns;function ee(e,n=O){return tc(j(e).projects,fy,n)}function js(e,n,t){return rc(e,n,t)}function Fs(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 ${j(n).projects}. Nothing was changed. Fix or delete that file, then run setup again.`),this.name="CursorRegistryError"}};function uc(e,n){return oc(ee(e,n),()=>new We(e))}var gy=new Set(["projectKey","root","transcriptFolder","orgId","projectSlug","projectId","projectSource","projectLabel","developerId","captureContent","install","registeredAt","enforce","subfolders"]),my=new Set(["path","transcriptFolder","install","registeredAt"]);function lc(e,n,t=O){let r=uc(e,t),o=r.projects[n.projectKey],s=Fr(o)&&Array.isArray(o.subfolders)?o.subfolders:[],i=n.subfolders?.map(c=>{let u=s.find(p=>Fr(p)&&p.path===c.path);return{...Ds(u,my),...c}}),a={...Ds(o,gy),...n,...i!==void 0?{subfolders:i}:{}},d={v:1,projects:{...r.projects,[n.projectKey]:a}};return ic(j(e).projects,d,t)}function pc(e,n,t=O){return ac(j(e).projects,uc(e,t),n,t)}var bt=Object.freeze({v:1,dropped:Object.freeze({}),unknownKinds:Object.freeze({}),pepDecisions:Object.freeze({seen:0,filledToolUseId:0,orphaned:0}),projects:Object.freeze({})});function It(){return{dropped:{},unknownKinds:{},pepDecisions:{seen:0,filledToolUseId:0,orphaned:0},projects:{}}}function Us(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 Ct(e,n){let t=e.projects[n];if(t!==void 0)return t;let r={dropped:{}};return e.projects[n]=r,r}function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ls(e){if(!ln(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 fc(e){if(!ln(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 Gn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Lr(e,n){return n!==void 0?{[e]:n}:{}}function Kn(e,n){return e===void 0?void 0:e[n]}function yc(e,n){if(e===void 0)return bt;let t;try{t=JSON.parse(e)}catch{return bt}if(!ln(t)||t.v!==1)return bt;let r=ln(t.pepDecisions)?t.pepDecisions:{},o={};if(ln(t.projects))for(let[c,u]of Object.entries(t.projects)){if(!ln(u))continue;let p=fc(u[n]),l=Gn(u.lastUploadAtMs);o[c]={...Lr(n,p),...l!==void 0?{lastUploadAtMs:l}:{},dropped:Ls(u.dropped)}}let s=ln(t.lastError)?t.lastError:void 0,i=Gn(s?.atMs),a=fc(t[n]),d=Gn(t.lastUploadAtMs);return{v:1,...d!==void 0?{lastUploadAtMs:d}:{},...i!==void 0&&typeof s?.message=="string"?{lastError:{atMs:i,message:s.message}}:{},dropped:Ls(t.dropped),unknownKinds:Ls(t.unknownKinds),pepDecisions:{seen:Gn(r.seen)??0,filledToolUseId:Gn(r.filledToolUseId)??0,orphaned:Gn(r.orphaned)??0},...Lr(n,a),projects:o}}function hc(e){return`${JSON.stringify(e)}
|
|
42
|
-
`}function kt(e,n,t,r=O){try{return yc(r.readFile(v(e,n).senderState).toString("utf8"),t)}catch{return bt}}function $s(e,n,t,r=O){r.writeFileAtomic(v(e,n).senderState,hc(t),D)}function Ms(e,n){let t={...e};for(let[r,o]of Object.entries(n))t[r]=(t[r]??0)+o;return t}function gc(e,n){return n===void 0?e:e===void 0||n.seenAtMs>=e.seenAtMs?n:e}function mc(e,n){return n===void 0?e:e===void 0?n:Math.max(e,n)}function Bs(e,n,t){let r={...e.projects};for(let[a,d]of Object.entries(n.projects)){let c=r[a]??{},u=gc(Kn(c,t),Kn(d,t)),p=mc(c.lastUploadAtMs,d.lastUploadAtMs);r[a]={...Lr(t,u),...p!==void 0?{lastUploadAtMs:p}:{},dropped:Ms(c.dropped??{},d.dropped)}}let o=Object.values(n.projects).reduce((a,d)=>gc(a,Kn(d,t)),Kn(e,t)),s=mc(e.lastUploadAtMs,n.lastUploadAtMs),i=n.lastError??e.lastError;return{v:1,...s!==void 0?{lastUploadAtMs:s}:{},...i!==void 0?{lastError:i}:{},dropped:Ms(e.dropped,n.dropped),unknownKinds:Ms(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},...Lr(t,o),projects:r}}function Sc(e,n,t,r,o=O){let s=kt(e,n,t,o);return r===void 0?Kn(s,t):Kn(s.projects[r],t)??void 0}function Rc(e,n,t,r,o=O){let s=kt(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 Mr="cursorVersion";function Ec(e,n,t=O){return Sc(e,N,Mr,n,t)}function bc(e,n,t=O){return Rc(e,N,Mr,n,t)}function Ic(e){return Object.entries(e).map(([n,t])=>({key:n,value:{stringValue:t}}))}function Te(e){return{resourceSpans:(Array.isArray(e)?e:[e]).map(t=>({resource:{attributes:Ic(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:Ic(r.attributes)};return r.error&&(o.status={code:2}),o})}]}))}}import{createHash as Oy}from"crypto";import{v5 as Dc}from"uuid";var Hn="user_prompt",Cc="gen_ai.completion",pe="full_command",pn="file_path",Qe="gen_ai.tool.call.result",Tt=new Set([Hn,Cc,pe,pn,Qe]);function kc(e,n){return!n||e.length===0?{}:{[Hn]:e}}function Tc(e,n){return!n||e.length===0?{}:{[Cc]:e}}function _c(e,n,t){if(!t)return{};let r={},o=e.command;typeof o=="string"&&o.length>0&&(r[pe]=o);let s=e.file_path??e.path??e.notebook_path;return typeof s=="string"&&s.length>0&&(r[pn]=s),n&&n.length>0&&(r[Qe]=n),r}var Ur="secret-manager-output",$r=`[REDACTED:secret:${Ur}]`,yy=[/^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|$)/],hy=/&&|\|\||;|\|/,Sy=/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;function Ry(e){let n=e.trimStart().replace(Sy,"");return yy.some(t=>t.test(n))}function Ey(e){if(e.length===0)return!1;for(let n of e.split(hy))if(Ry(n))return!0;return!1}var by=new Set;function Oc(e,n){let t=e[n.commandKey];if(typeof t!="string"||!Ey(t))return by;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 Iy={commandKey:pe,resultKeys:new Set([Qe])};function Br(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=Oc(t.correlationCommand===void 0?e:{...e,[pe]:t.correlationCommand},Iy);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]=$r,o[Ur]=(o[Ur]??0)+1,s+=1;continue}if(!Tt.has(a)){r[a]=d;continue}let c=Xd(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 Gr=8192;var xc=16*1024,Kr=Gr+xc;function Gs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Cy(e){return e.length>Gr?e.slice(0,Gr):e}function Ac(e){return e.length>Kr?e.slice(0,Kr+1):e}function ky(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 wc(e,n){let t={},r=new Map;for(let[a,d]of Object.entries(e))if(Tt.has(a)&&d.length>Kr){let c=d.slice(0,Kr);t[a]=c,r.set(a,c)}else t[a]=d;let o=e[pe],s=Br(t,n,o===void 0?{}:{correlationCommand:o}),i={};for(let[a,d]of Object.entries(s.attributes)){if(!Tt.has(a)){i[a]=d;continue}let c=r.get(a),u=d;if(c!==void 0&&u!==$r){let p=Math.min(xc,ky(c,u));u=u.slice(0,u.length-p)}i[a]=Cy(u)}return{attributes:i,redactedCount:s.redactedCount,byType:s.byType}}function Ks(e,n){if(n!==void 0)return e?.startsWith(n)?e:n}function Ty(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:Gs(t)&&typeof t.vendorTool=="string"&&typeof t.argsHash=="string"&&Gs(t.call)&&typeof t.call.tool=="string"}function _y(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 vc(e,n){let t;try{t=JSON.parse(e)}catch{return}if(!Gs(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"&&Ty(r,n)||r.kind==="pep-decision"&&_y(r)?r:o()}function jc(e,n){return Dc(`${e}:${n}`,at)}var Fc="agenttrail.org.id",Lc="agenttrail.project.id",Mc="agenttrail.agent.id",Uc="agenttrail.developer.id",$c="agenttrail.project",Bc="gen_ai.conversation.id",Gc="session.id",Kc="gen_ai.request.model",Hc="llm_request.context",Vc="tool_name",Wc="gen_ai.tool.name",Qc="gen_ai.tool.call.id",Hs="gen_ai.usage.input_tokens",Vs="gen_ai.usage.output_tokens",Ws="gen_ai.usage.cache_read.input_tokens",Qs="gen_ai.usage.cache_creation.input_tokens",xy="interaction",Pc=1,Ay=3,wy=Object.freeze({[Fc]:"metadata",[Lc]:"metadata",[Mc]:"metadata",[st]:"metadata",[Uc]:"metadata",[$c]:"metadata",[it]:"metadata",[sn]:"metadata",[an]:"metadata",[wo]:"metadata",[Bc]:"metadata",[Gc]:"metadata",[No]:"metadata",[Kc]:"metadata",[Hc]:"metadata",[vo]:"metadata",[Hs]:"metadata",[Vs]:"metadata",[Ws]:"metadata",[Qs]:"metadata",[Vc]:"metadata",[Wc]:"metadata",[xo]:"metadata",[Qc]:"metadata",[Do]:"metadata",[jo]:"metadata",[Po]:"metadata",[Hn]:"content",[pe]:"content",[pn]:"content",[Qe]:"content"});function Hr(e,n,t){let r=t==="import"?`import:${n.conversationId}:${n.importKey??n.importOrdinal??0}`:`live:${n.conversationId}:${n.generationId??""}`;return Dc(r,e).replace(/-/g,"")}function Vn(e,n){let t=typeof n=="string"?n:`tool:${n.tool}`;return Oy("sha256").update(`${e}:${t}`).digest("hex").slice(0,16)}function Js(e){return e.correlationId??`ordinal:${e.ordinal}`}function Ys(e,n){return Vn(e,{tool:Js(n)})}function Nc(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 vy(e,n,t){let r={...n};if(e.call.tool!==""&&(r[Vc]=e.call.tool,r[Wc]=e.call.tool),e.vendorTool!==""&&(r[xo]=e.vendorTool),e.correlationId!==null&&(r[Qc]=e.correlationId),e.mcpServerUnknown===!0&&(r[Do]="true"),e.pepBlocked===!0&&e.failed&&(r[jo]="true"),e.subagentConversationId!==void 0&&(r[Po]=e.subagentConversationId),t){let{full_command:o,file_path:s}=e.call.args;o!==void 0&&(r[pe]=o),s!==void 0&&(r[pn]=s),e.output!==void 0&&(r[Qe]=e.output)}return r}function Py(e,n,t){let r=t.mode==="import",o=Hr(e.traceNamespace,n,t.mode),s=Vn(o,"root"),i=n.endMs,a=t.include,d=!r&&n.usage!==null&&n.model!==null,c={};n.conversationId!==""&&(c[Bc]=n.conversationId,c[Gc]=n.conversationId);let u=r?{[wo]:"true",[sn]:vn,...t.batchId?{[an]: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:Pc,startMs:n.startMs,endMs:i,attributes:{...c,...l!==void 0?{[No]:l}:{},...t.captureContent&&n.prompt?{[Hn]:n.prompt}:{},...d?{}:{[it]:"false"},...u},error:n.status==="error"})}!r&&i!==null&&n.model!==null&&(a?.model??!0)&&p.push({spanId:Vn(o,"model"),parentSpanId:s,name:`chat ${n.model.name}`,kind:Ay,startMs:n.startMs,endMs:n.model.endMs,attributes:{...c,[Kc]:n.model.name,[Hc]:xy,[vo]:"true",...d&&n.usage!==null?e.usageAttributes(n.usage):{[it]:"false"}},error:!1});for(let l of n.tools){let f=l.endMs??i;f!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(Js(l))||p.push({spanId:Ys(o,l),parentSpanId:l.parentTaskKey===void 0?s:Vn(o,{tool:l.parentTaskKey}),name:l.call.tool===""?"execute_tool":`execute_tool ${l.call.tool}`,kind:Pc,startMs:l.startMs,endMs:f,attributes:{...vy(l,c,t.captureContent),...u},error:l.failed}))}return p}function Jc(e,n,t,r){let o=t.mode==="import",s=Hr(e.traceNamespace,n,t.mode),i=t.resolvedScrubbers??null,a=0,d={},c=Py(e,n,t).map(p=>{let l=wc(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:Nc(p.startMs),endTimeUnixNano:Nc(Math.max(p.endMs,p.startMs)),attributes:f,error:p.error}});return{resource:{attributes:{[Fc]:t.orgId,[Lc]:t.project.projectId,[Mc]:r,[st]:e.vendor,...t.project.developerId?{[Uc]:t.project.developerId}:{},...t.project.projectLabel?{[$c]:t.project.projectLabel}:{},[it]:o?"false":"true",...o?{[sn]:vn}:{},...o&&t.batchId?{[an]:t.batchId}:{}}},scope:{name:e.scopeName,version:t.scopeVersion},spans:c,redactions:{total:a,byType:d}}}function qs(e){return jc(e,Dr)}var Ny="agenttrail-cursor";function Xs(e,n){return Hr(zc.traceNamespace,{conversationId:e.conversationId,generationId:e.generationId,...e.importOrdinal!==void 0?{importOrdinal:e.importOrdinal}:{}},n)}function Dy(e){if(!("importKey"in e))return e;let{importKey:n,...t}=e;return t}function Zs(e,n){return Vn(e,n)}function jy(e,n){return Ys(e,n)}var zs=new Set(["subagentStart","subagentStop"]),Fy=new Set(["postToolUse","postToolUseFailure","afterFileEdit"]),Ly=Object.freeze({conversationId:"",generationId:null,startMs:0,endMs:null,model:null,usage:null,tools:Object.freeze([])});function My(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 ei(e){let n=e.tool?.durationMs;return n!==void 0&&Number.isFinite(n)&&n>=0?e.capturedAtMs-n:e.capturedAtMs}function Uy(e,n){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(n(r))return r}}function $y(e){let n=e.find(t=>t.event==="beforeSubmitPrompt"&&t.conversationId!==null);if(n?.conversationId)return n.conversationId;for(let t of e){if(!zs.has(t.event))continue;let r=t.subagent?.parentConversationId??t.conversationId;if(r)return r}for(let t of["stop","afterAgentResponse"]){let r=Uy(e,o=>o.event===t&&o.conversationId!==null);if(r?.conversationId)return r.conversationId}return e.find(t=>t.conversationId!==null)?.conversationId??""}function By(e){switch(e){case"completed":return"success";case"aborted":return"aborted";case"error":return"error";default:return"unknown"}}function Gy(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 Ky(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:ei(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 Hy(e,n,t){let{post:r,start:o,stop:s}=e,i=o??s,a=o?.capturedAtMs??(r!==void 0?ei(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 Vy(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 Yc(e,n){let t=e.map((y,R)=>({record:y,index:R})).filter(({record:y})=>My(y)).sort((y,R)=>y.record.capturedAtMs-R.record.capturedAtMs||y.index-R.index).map(({record:y})=>y);if(t.length===0)return Ly;let r=$y(t),o=y=>y===null||y===r,s=t.find(y=>o(y.conversationId)&&!zs.has(y.event)&&y.generationId!==null)?.generationId??null,i=Xs({conversationId:r,generationId:s},"live"),a=y=>{let R=n?.get(y);return typeof R=="number"&&Number.isFinite(R)?R:void 0},d=[],c=new Map,u=y=>{let R=y===null?void 0:c.get(y);if(R!==void 0)return R;let T={key:y};return d.push(T),y!==null&&c.set(y,T),T};for(let y of t)if(Fy.has(y.event)&&y.tool!==void 0){let R=u(y.tool.correlationId);R.post??=y}else if(zs.has(y.event)){let R=y.subagent?.subagentId??null;if(R===null)continue;let T=u(R);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,R)=>{let T=y.start!==void 0||y.stop!==void 0?Hy(y,R,o):Ky(y.post,R,Gy(y.post,p,l),o),k=a(jy(i,T));return k===void 0?T:{...T,startMs:k}}),m=f.filter(y=>y.isTask),g=f.map(y=>{let R=y.foreignConversationId===void 0?void 0:Vy(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}:{},...R?.correlationId?{parentTaskKey:R.correlationId}:{}}}),h,S,I,E=Number.POSITIVE_INFINITY;for(let y of t)E=Math.min(E,ei(y)),o(y.conversationId)&&(y.event==="beforeSubmitPrompt"?h??=y.content?.prompt:y.event==="afterAgentResponse"?S=y:y.event==="stop"&&(I=y));let C=S?.model??I?.model??null,b=S?.capturedAtMs??I?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(Zs(i,"root"))??E,endMs:I?.capturedAtMs??null,...I!==void 0?{closedBy:"stop",status:By(I.status)}:{},...h!==void 0?{prompt:h}:{},model:C!==null&&b!==void 0?{name:C,endMs:b}:null,usage:I?.usage??null,tools:g}}function Vr(e){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Wy(e){let n=Vr(e.cacheReadTokens),t=Vr(e.cacheWriteTokens);return{[Hs]:String(Math.max(0,Vr(e.inputTokens)-n-t)),[Vs]:String(Vr(e.outputTokens)),[Ws]:String(n),[Qs]:String(t)}}var zc={vendor:Dr,scopeName:Ny,traceNamespace:Mo,rootSpanName:"invoke_agent Cursor",usageAttributes:Wy};function Wr(e,n){return Jc(zc,Dy(e),n,qs(n.orgId))}var Zc=600*1e3,_t=600*1e3,ni=1440*60*1e3,Qy={idleSweepMs:Zc,orphanWindowMs:_t,retentionMs:ni};function De(e,n){return`${e}\0${n??""}`}function Jy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eu(e){let n;try{n=JSON.parse(e)}catch{return}if(!(!Jy(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 nu(e){return`${JSON.stringify(e)}
|
|
43
|
-
`}function ti(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=eu(t.readFile(d).toString("utf8"))}catch{c=void 0}c===void 0?i.push(d):s.push(c)}return{states:s,unreadable:i}}function Wn(e,n,t,r=O){r.writeFileAtomic(ur(e,n,t.traceId),nu(t),D)}function Qr(e,n,t,r=O){r.remove(ur(e,n,t))}function tu(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 ru(e){return[...e].sort((n,t)=>n.atMs-t.atMs||n.pid-t.pid||n.seq-t.seq||n.name.localeCompare(t.name))}function Jr(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=tu(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:ru(i),other:a}}function Yy(e,n,t,r,o){return{v:1,traceId:n,projectKey:e,conversationId:t,generationId:r,files:[],starts:{},sent:{},lastRecordAtMs:o}}function fn(e){return e.records.reduce((n,t)=>Math.max(n,t.capturedAtMs),e.loaded.lastRecordAtMs)}function ou(e,n){return e.records.find(t=>{if(!n.closesTurn(t))return!1;let r=n.turnOf(t);return r.conversationId!==null&&De(r.conversationId,r.generationId)===e.key})}function qc(e,n,t){let r=ou(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?fn(e)>o.atMs:!0}function ri(e){let n=e.rules,t={...Qy,...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:De(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 S=h.entry;S!==void 0&&(S.kind==="capture"?g.records.push(S):S.kind==="pep-decision"&&g.decisions.push(S))};for(let g of r)for(let h of g.loaded.files){let S=c.get(h);S!==void 0&&u(g,S)}for(let g of r)for(let h of g.records)Xc(d,g,h,n);let p=(g,h)=>r.filter(S=>S.loaded.conversationId===g&&qc(S,h,n)).sort((S,I)=>fn(S)-fn(I)).at(-1),l=g=>d.filter(h=>h.startAtMs<=g&&(h.stopAtMs===void 0||g<=h.stopAtMs)).sort((h,S)=>h.startAtMs-S.startAtMs).at(-1),f=(g,h)=>{let S=r.filter(I=>qc(I,g.atMs,n)&&Math.abs(g.atMs-fn(I))<=t.orphanWindowMs).sort((I,E)=>fn(I)-fn(E)).at(-1);if(S!==void 0){u(S,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 C=n.decisionTurnOf(h),b=C.conversationId===null?void 0:o.get(De(C.conversationId,C.generationId));b!==void 0?u(b,g):e.nowMs-g.atMs>=t.orphanWindowMs?a.push({file:g,reason:"decision-orphan"}):i.push(g);continue}let S=h,I=n.subagentOf(S);if(I!==void 0){let C=I.parentConversationId,b=C===null?void 0:p(C,S.capturedAtMs);if(b===void 0){f(g,"orphan");continue}u(b,g),Xc(d,b,S,n);continue}let E=n.turnOf(S);if(E.conversationId!==null){let C=o.get(De(E.conversationId,E.generationId));if(C!==void 0){u(C,g);continue}if(n.opensTurn(S)){let y=e.traceIdFor({conversationId:E.conversationId,generationId:E.generationId}),R={key:De(E.conversationId,E.generationId),loaded:Yy(e.projectKey,y,E.conversationId,E.generationId,S.capturedAtMs),records:[],decisions:[],files:[]};r.push(R),o.set(R.key,R),u(R,g);continue}let b=l(S.capturedAtMs);if(b!==void 0){u(b.builder,g);continue}}f(g,"orphan")}return{turns:r.filter(g=>g.files.length>0||g.loaded.files.length>0).map(g=>zy(g,e.nowMs,t,n)),pending:i,dropped:a,expired:[]}}function Xc(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 zy(e,n,t,r){let o=[...e.records].sort((c,u)=>c.capturedAtMs-u.capturedAtMs),s=fn(e),i=ou(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 oi(e,n,t=ni){return e.filter(r=>r.files.length===0&&r.closed!==void 0&&n-r.lastRecordAtMs>=t)}import{createHmac as GT,randomBytes as Xy}from"crypto";import{createHash as UT}from"crypto";var si=8192;function ii(e){return e.length>si?e.slice(0,si):e}function su(e){try{return JSON.stringify(e)??""}catch{return""}}function Yr(e){return ii(zr(e))}function zr(e){if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return n!==null&&typeof n=="object"?su(n):e}return e!==null&&typeof e=="object"?su(e):"{}"}var ai=32;function di(e,n,t=O){let r;try{r=t.readFile(v(e,n).queueKey)}catch{return}return r.length===ai?new Uint8Array(r):void 0}function iu(e,n,t=O,r=Xy){return di(e,n,t)!==void 0?"kept":(t.writeFileAtomic(v(e,n).queueKey,r(ai),D),"created")}var Zy=new Set(["preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeMCPExecution","afterMCPExecution","beforeReadFile","beforeTabFileRead","afterFileEdit","subagentStart","beforeSubmitPrompt","stop","afterAgentResponse","subagentStop","sessionEnd","sessionStart","afterAgentThought","workspaceOpen"]);function ci(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"&&Zy.has(t)}var li="MCP:";var nh=new Set(["GetDynamicTools","TodoWrite","CreatePlan","AskQuestion","SwitchMode","Await","Task","ReadLints","SemanticSearch","WebFetch","UpdateCurrentStep"]),th=new Map([["Read","Read"],["StrReplace","Edit"],["Delete","Delete"]]);function lu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function au(e){return typeof e=="string"&&e!==""?e:void 0}function rh(e){return e.length>Ao?e.slice(0,Ao):e}function oh(e){return/^(?:[\\/]|[A-Za-z]:[\\/])/.test(e)}function sh(e,n){return`${e.replace(/[\\/]+$/,"")}/${n}`}function du(e,n,t="Grep"){let r=au(e),o=au(n);return o!==void 0&&(r===void 0||oh(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:sh(r,o)}},{tool:t,args:{file_path:r}}]}function cu(e,n){return typeof n=="string"?{tool:e,args:{full_command:ii(n)}}:{tool:e,args:{}}}function ui(e,n){return typeof n=="string"?{tool:e,args:{file_path:n}}:{tool:e,args:{}}}function ih(e){return[ui("Write",e),ui("Edit",e)]}function pi(e){let n=rh(e.name),t=lu(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:Yr(t.arguments)}}])};switch(e.name){case"Shell":return r([cu("Bash",t.command)]);case"WebSearch":return r([cu("WebSearch",t.search_term)]);case"Grep":return r(du(t.path,t.glob));case"Glob":return r(du(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(ih(t.path))}let s=th.get(e.name);return s!==void 0?r([ui(s,t.path)]):nh.has(e.name)?{kind:"not-action",vendorTool:n}:{kind:"unmapped",vendorTool:n}}function pu(e){let n=lu(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 zr(n.arguments)}}function fu(e,n=O){return di(e,N,n)}function gu(e,n=O,t){return iu(e,N,n,t)}var ce=Object.freeze(["beforeSubmitPrompt","postToolUse","postToolUseFailure","afterMCPExecution","afterAgentResponse","afterFileEdit","subagentStart","subagentStop","stop"]);var dh=new Set(ce);function qr(e){return vc(e,dh)}function mu(e){return{conversationId:e.conversationId,generationId:e.generationId}}function yu(e){return{conversationId:e.conversationId,generationId:e.generationId}}function hu(e){return e.event==="beforeSubmitPrompt"}function Su(e){return e.event==="stop"}function Ru(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 Eu(e){return e==="postToolUse"||e==="postToolUseFailure"}function bu(e,n=O,t,r=""){return Jr(e,qr,n,t,r)}var ch="/v1/conversations/known";function uh(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}async function Xr(e,n,t={}){if(e.length===0)return{known:new Set,ok:!0};let r=t.fetch??globalThis.fetch,o=`${n.endpoint.replace(/\/$/,"")}${ch}`,s=new Set;for(let i of uh(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 lh=e=>new Promise(n=>setTimeout(n,e));function ph(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 Je(e,n,t={}){if(n.dryRun)return{status:"skipped",attempts:0};let r=t.fetch??globalThis.fetch,o=t.sleep??lh,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(Iu(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(Iu(i,c,ph(l.headers)))}return{status:"failed",httpStatus:p,attempts:c,error:u}}function Iu(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 Ot(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}import{createHash as Rh}from"crypto";import{createHash as Cu}from"crypto";import{createReadStream as fh,mkdirSync as gh,readFileSync as mh}from"fs";import{dirname as yh,join as hh}from"path";var Sh=448;function ku(e){return hh(e,".agenttrail","backfill-state.json")}function fi(e,n={}){let t=n.readFile??(r=>mh(r,"utf8"));try{let r=JSON.parse(t(ku(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 Tu(e,n,t={}){let r=ku(e),o=t.writeFile??((i,a,d)=>P(i,a,d!==void 0?{mode:d}:{}));return(t.mkdir??((i,a)=>gh(i,{recursive:!0,mode:a})))(yh(r),Sh),o(r,`${JSON.stringify(n,null,2)}
|
|
44
|
-
`,384),r}function gn(e,n,t){return{version:2,sessions:{...e.sessions,[n]:{...t,updatedAt:t.updatedAt??new Date().toISOString()}}}}function xt(e,n,t){let r=e.sessions[n];return r?!(r.status==="done"&&r.sourceHash===t):!0}function _u(e){return new Promise((n,t)=>{let r=Cu("sha256"),o=fh(e);o.on("data",s=>r.update(s)),o.on("error",t),o.on("end",()=>n(r.digest("hex")))})}function V_(e){return Cu("sha256").update(e).digest("hex")}var gi=Object.freeze({version:2,sessions:Object.freeze({})});function Ou(e){return j(e).backfillState}function mi(e,n=O){let t=Ou(e);try{if(!n.exists(t))return gi;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}:gi}catch{return gi}}function xu(e,n,t=O){let r=Ou(e);return t.writeFileAtomic(r,`${JSON.stringify(n,null,2)}
|
|
45
|
-
`,D),r}function Au(e){let n=Rh("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)}
|
|
46
|
-
`);return n.digest("hex")}import{readdirSync as Ch,statSync as kh}from"fs";import{join as yn}from"path";import{createReadStream as Eh}from"fs";import{createInterface as bh}from"readline";var mn=class extends Error{constructor(t,r){super(t);this.sessionId=r;this.name="QuarantineError"}sessionId},At={async*readLines(e){let n=bh({input:Eh(e,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY});try{for await(let t of n)yield t}finally{n.close()}}};function _e(e){return typeof e=="string"&&e.length>0?e:null}function wu(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[]}function vu(e){return e.filter(n=>n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
|
|
47
|
-
`)}function Ih(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&"text"in n?String(n.text):"").join(`
|
|
48
|
-
`):e==null?"":JSON.stringify(e)}async function Zr(e,n,t=At){let r=null,o=null,s=null,i=null,a=null,d=null,c=0,u=[],p=[],l=new Map,f="";for await(let S of t.readLines(e)){let I=S.trim();if(I.length===0)continue;let E;try{E=JSON.parse(I)}catch{c++;continue}if(E===null||typeof E!="object"){c++;continue}r??=_e(E.sessionId),o??=_e(E.version),s??=_e(E.gitBranch),i??=_e(E.cwd);let C=_e(E.timestamp),b=_e(E.uuid)??"",y=E.isSidechain===!0,R=E.type;if(C&&(R==="user"||R==="assistant")&&(a??=C,d=C),R==="assistant"&&E.message){let T=wu(E.message.content),k=[];for(let _ of T)_.type==="tool_use"&&_e(_.id)&&_e(_.name)&&k.push({toolUseId:_.id,name:_.name,input:_.input??{}});u.push({messageUuid:b,timestamp:C??d??"",model:_e(E.message.model)??"",usage:E.message.usage??{},text:vu(T),toolUses:k,isSidechain:y,promptUuid:f})}else if(R==="user"&&E.message){let T=wu(E.message.content),k=!1;for(let _ of T)_.type==="tool_result"&&_e(_.tool_use_id)&&(k=!0,l.set(_.tool_use_id,{toolUseId:_.tool_use_id,isError:_.is_error===!0,content:Ih(_.content),timestamp:C??d??""}));if(!k){let _=vu(T);_.length>0&&(p.push({messageUuid:b,timestamp:C??"",text:_,isSidechain:y}),y||(f=b))}}}let m=r??n;if(u.length===0&&p.length===0)throw new mn(`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 Th="agent-transcripts",Pu="subagents";function _h(e){return[e.root,...(e.subfolders??[]).map(t=>t.path)].map(t=>({name:un(t),path:t,found:!1}))}function Oh(e){let n=new Map;for(let t of Object.values(e.projects)){let r=un(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 Du={readdir(e){return Ch(e).sort()},stat(e){let n=kh(e);return{size:n.size,mtimeMs:n.mtimeMs,birthtimeMs:Number.isFinite(n.birthtimeMs)?n.birthtimeMs:0,isDirectory:()=>n.isDirectory()}},readLines(e){return At.readLines(e)}};function eo(e,n){try{return[...e.readdir(n)].sort()}catch{return}}function Nu(e,n){try{return e.stat(n).isDirectory()}catch{return!1}}function xh(e,n,t,r,o){let s=yn(n,r),i=eo(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(yn(s,`${r}.jsonl`),!1),i.includes(Pu)){let c=yn(s,Pu);for(let u of eo(e,c)??[])u.endsWith(".jsonl")&&d(yn(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 ju(e,n,t,r,o=Zd(t)){let s=Oh(n);if(s!==void 0)return{kind:"collision",...s};let i=_h(e),a=new Map(i.map(f=>[f.name,f])),d={notRead:0,unreadableFiles:0},c=[],u=[],p=0,l=new Set(eo(r,o)??[]);for(let f of l)a.has(f)||(p+=1);for(let f of i){let m=yn(o,f.name),g=yn(m,Th);if(!l.has(f.name)||!Nu(r,g)){u.push({...f,found:!1});continue}u.push({...f,found:!0});for(let h of eo(r,g)??[]){let S=yn(g,h);if(!Nu(r,S)){h.endsWith(".jsonl")&&(d.notRead+=1);continue}let I=xh(r,g,f.name,h,d);I!==void 0&&c.push(I)}}return{kind:"ok",projectsRoot:o,folders:u,sessions:c,otherFolders:p,notRead:d.notRead,unreadableFiles:d.unreadableFiles}}import{isAbsolute as Uh}from"path";import{readdirSync as Ah,statSync as wh}from"fs";import{homedir as vh}from"os";import{basename as Ph,isAbsolute as Nh,join as yi,relative as Dh}from"path";function jh(e=vh()){return yi(e,".claude","projects")}var Fh=40;async function Lh(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<Fh&&!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 hi(e,n){if(e===null)return!1;let t=Dh(n,e);return t===""||!t.startsWith("..")&&!Nh(t)}async function Si(e=jh(),n,t={}){let r=t.readdir??(f=>Ah(f)),o=t.stat??(f=>wh(f)),s=t.lineSource??At,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=yi(e,f),g;try{if(!o(m).isDirectory())continue;g=r(m)}catch{continue}let h=[];for(let S of g.sort()){if(!S.endsWith(".jsonl"))continue;let I=yi(m,S),E=0,C=0;try{let y=o(I);E=y.size,C=y.mtimeMs}catch{continue}let b;try{b=await Lh(I,s)}catch{b={cwd:null,gitBranch:null,version:null,sessionId:null,messageCount:0}}if(i&&!hi(b.cwd,n)){b.cwd===null?d++:a++;continue}h.push({sessionId:b.sessionId??Ph(S,".jsonl"),file:I,project:f,cwd:b.cwd,gitBranch:b.gitBranch,version:b.version,sizeBytes:E,modifiedAt:new Date(C).toISOString(),messageCount:b.messageCount})}h.length>0&&(p.push({project:f,sessions:h}),l+=h.length)}return c(p,l)}var Ri={unparseableLines:0,truncatedLastLines:0,unknownRecords:0,turnsEndedWithError:0};function Fu(e,n){return{unparseableLines:e.unparseableLines+n.unparseableLines,truncatedLastLines:e.truncatedLastLines+n.truncatedLastLines,unknownRecords:e.unknownRecords+n.unknownRecords,turnsEndedWithError:e.turnsEndedWithError+n.turnsEndedWithError}}function no(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mh(e){return Array.isArray(e)?e:typeof e=="string"?[{type:"text",text:e}]:[]}async function Lu(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(!no(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"||!no(f)){i++;continue}if(l.role==="user"){o.push({messageUuid:"",timestamp:t.timestamp,text:"",isSidechain:t.isSidechain});continue}let m=[];Mh(f.content).forEach((g,h)=>{!no(g)||g.type!=="tool_use"||m.push({toolUseId:`${t.idPrefix}:${c}:${h}`,name:typeof g.name=="string"?g.name:"",input:no(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 $h=1e3,hO={...Ri,notActions:0,unmapped:0};function Bh(e){let n=[],t=pi(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=>Uh(o))}function Gh(e,n){for(let t of e)for(let r of Bh(t))if(!hi(r,n))return!0;return!1}function Kh(e,n){let t=e.args.full_command,r=Ks(n,t);return r===void 0||r===t?e:{...e,args:{...e.args,full_command:Ac(r)}}}function Hh(e,n,t,r){let o=e.length>0?(t-n)/e.length:0,s=[];return e.forEach((i,a)=>{let d=pi(i);if(d.kind==="not-action"){r.notActions+=1;return}if(d.kind==="unmapped"){r.unmapped+=1;return}s.push({vendorTool:d.vendorTool,call:Kh(d.candidates[0],pu(i)),correlationId:null,ordinal:a,startMs:Math.round(n+a*o),endMs:Math.round(n+(a+1)*o),failed:!1})}),s}function Vh(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)*$h),endMs:s}}async function Mu(e,n,t){let{conversationId:r}=e,o=[],s=Ri,i=0,a="";for(let[f,m]of e.files.entries())try{let g=await Lu(m.path,t,{timestamp:"",isSidechain:m.isSidechain,idPrefix:`${r}:${f}`});for(let h of g.turns)o.push({uses:h.toolUses});s=Fu(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(Gh(d,n))return{kind:"outside-root",conversationId:r};let c=Vh(e,o.length),u=o.length>0?(c.endMs-c.startMs)/o.length:0,p={notActions:0,unmapped:0},l=[];return o.forEach((f,m)=>{let g=Math.round(c.startMs+m*u),h=Math.round(c.startMs+(m+1)*u),S=Hh(f.uses,g,h,p);S.length!==0&&l.push({conversationId:r,generationId:null,importOrdinal:m,startMs:g,endMs:h,model:null,usage:null,tools:S})}),l.length===0?{kind:"empty",conversationId:r}:{kind:"imported",conversationId:r,turns:l,counts:{...s,...p}}}var Wh=6;function Qh(e){return`bf_${e.toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Jh(e,n,t){let r=new Set,{files:o}=bu(Bn(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 Ei(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 Uu(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 \`${W("cursor","setup")} --unregister\` in one of them, or move it, then import again.`),1}function Yh(e,n,t,r){let o=ee(n,t);if(o.kind==="unreadable")return e.io.error(`error: ${j(n).projects} cannot be read. Fix or delete it, then run \`${W("cursor","setup")}\`.`),1;let s;try{s=r(e.io.cwd)}catch{s=e.io.cwd}let i=o.kind==="ok"?o.registry:cc,a=js(i,[s],e.io.env.CURSOR_PROJECT_DIR);return a===void 0?(e.io.error(`error: ${s} is unregistered. Run \`${W("cursor","setup")}\` in the folder you open in Cursor, then import.`),1):{record:a,registry:i}}async function zh(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=Jh(t.home,e.projectKey,t.io),f=0,m=n.filter(R=>l.has(R.conversationId)?(f+=1,de(o,"queued"),r.emit?.({event:"queued-skip",conversationId:R.conversationId}),!1):!0),g=0,h=!0,S=m;if(!t.reimport){let R=await Xr(m.map(T=>T.conversationId),{endpoint:t.endpoint,token:t.token},{fetch:r.upload?.fetch});h=R.ok,R.ok&&R.known.size>0&&(S=m.filter(T=>R.known.has(T.conversationId)?(g+=1,r.emit?.({event:"dedup-skip",conversationId:T.conversationId}),!1):!0))}let I=mi(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=qs(t.orgId),C=Pe(me),b=await Ot(S,t.concurrency,async R=>{let T=Au(R.files);if(t.resume&&!xt(I,R.conversationId,T))return{session:R,sourceHash:T,kind:"skipped"};let k=await Mu(R,e.root,t.scanIO);if(k.kind!=="imported")return{session:R,sourceHash:T,kind:k.kind,error:"error"in k?k.error:""};let _=qh(k.turns,{record:e,orgId:t.orgId,agentId:E,captureContent:t.captureContent,batchId:t.batchId,resolvedScrubbers:C}),F=await Je(Te(_),{endpoint:t.endpoint,token:t.token,dryRun:t.dryRun},r.upload);return{session:R,sourceHash:T,kind:F.status==="failed"?"failed":"done",counts:k.counts,body:_,httpStatus:F.httpStatus,error:F.error}});for(let R of b){let T=R.session.conversationId;if(R.kind==="skipped")u+=1;else if(R.kind==="outside-root")de(o,"outside-root");else if(R.kind==="empty")de(o,"empty");else if(R.kind==="unreadable")de(o,"unreadable"),I=gn(I,T,{status:"quarantined",sourceHash:R.sourceHash,batchId:t.batchId,error:R.error});else{let k=R.body;p+=k.spans.length,a+=k.redactions.total;for(let[_,F]of Object.entries(k.redactions.byType))i[_]=(i[_]??0)+F;for(let _ of Object.keys(s))s[_]+=R.counts?.[_]??0;R.kind==="failed"?(c+=1,R.httpStatus!==void 0&&de(o,`rejected-${R.httpStatus}`)):d+=1,I=gn(I,T,{status:R.kind,sourceHash:R.sourceHash,batchId:t.batchId,error:R.error})}r.emit?.({event:"session",conversationId:T,status:R.kind,spans:R.kind==="done"||R.kind==="failed"?R.body?.spans.length:0,httpStatus:R.httpStatus})}t.dryRun||xu(t.home,I,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,...Xh(y)}),y}function qh(e,n){let t=e.map(o=>Wr(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 Xh(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 $u(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(b){return e.io.error(`error: ${b.message}`),1}let s=o.homeDir,i=n.io??O,a=n.scanIO??Du,d=n.realpath??(b=>b),c=Yh(e,s,i,d);if(typeof c=="number")return c;let{record:u,registry:p}=c,l=ju(u,p,s,a);if(t.status){let b=mi(s,i),y=Object.entries(b.sessions);e.io.log(`Cursor import record: ${j(s).backfillState}`),e.io.log(` conversations recorded: ${y.length}`);for(let[R,T]of y)e.io.log(` ${R}: ${T.status} (batch ${T.batchId}, ${T.updatedAt})`);return l.kind==="ok"?Ei(e,l):Uu(e,l),n.emit?.({event:"status",sessions:b.sessions}),0}if(l.kind==="collision")return Uu(e,l);if(t.scan)return Ei(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=be(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 \`${W("cursor","login")}\`, or pass --endpoint and --key.`),1;let S=Wh;if(t.concurrency){let b=Number(t.concurrency);if(!Number.isInteger(b)||b<1)return e.io.error(`error: invalid --concurrency '${t.concurrency}' (positive integer).`),1;S=b}let I=!!t.content||u.captureContent;if(I&&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"],C=await zh(u,l.sessions,{home:s,io:i,scanIO:a,endpoint:m,token:g,orgId:h,captureContent:I,dryRun:E,reimport:!!t.reimport,resume:!!t.resume,concurrency:S,batchId:Qh((n.now??Date.now)()),otherFolders:l.otherFolders,notRead:l.notRead},n);Ei(e,l),e.io.log(`Cursor import ${E?"(dry-run) ":""}complete for ${u.projectSlug}: ${C.imported} imported, ${C.failed} failed, ${C.skipped} unchanged (of ${C.total} conversations), ${C.spans} spans.`),C.queuedSkipped>0&&e.io.log(`${C.queuedSkipped} conversation(s) are still queued for live upload and were left to the sender.`),C.dedupSkipped>0&&e.io.log(`${C.dedupSkipped} conversation(s) AgentTrail already holds (live capture or an earlier import) were skipped.`),C.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[b,y]of Object.entries(C.dropped))e.io.log(`Not imported (${b}): ${y}`);return C.otherFolders>0&&e.io.log(`${C.otherFolders} folder(s) under ${l.projectsRoot} belong to other projects and were not opened.`),e.io.log(""),C.redactions.total>0&&e.io.log(`Edge-scrubbed ${C.redactions.total} secret-shaped value(s) on this machine before upload (${Object.keys(C.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."),C.failed>0?1:0}import{basename as rS}from"path";import{createHash as Zh}from"crypto";import{v5 as eS}from"uuid";function Bu(e,n){return eS(`${e}:${n}`,Lo).replace(/-/g,"")}function to(e,n,t){return Zh("sha256").update(`${e}:${n}:${t}`).digest("hex").slice(0,16)}function nS(e,n){return e===""?n:n===""||Date.parse(e)>=Date.parse(n)?e:n}function tS(e,n,t,r){let{sessionId:o,toolResults:s}=e,i=[],a=null;for(let d of r){let c=to(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=to(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 Gu(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=to(n,p.promptId,"root"),f=tS(e,p.promptId,l,d.get(p.promptId)??[]),m=f.map(S=>S.startTs).find(S=>S!==""),g=p.ts!==""?p.ts:m??e.firstTimestamp??"",h=g;for(let S of f)h=nS(h,S.endTs);u.push({role:"agent",spanId:l,parentSpanId:"",promptId:p.promptId,startTs:g,endTs:h,failed:!1,promptText:p.text}),u.push(...f)}return u}var oS=1,sS=3,iS="claude-code-backfill",aS="claude-code-session-upload";function Qn(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function dS(e){let n=Qn(e.input_tokens),t=Qn(e.output_tokens),r=Qn(e.cache_read_input_tokens),o=Qn(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=Qn(e.cache_creation.ephemeral_5m_input_tokens),a=Qn(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 Ku(e){let n=Date.parse(e);return Number.isNaN(n)?"0":(BigInt(n)*1000000n).toString()}function Hu(e){return e.provenance==="live"?{}:{[sn]:vn,[an]:e.batchId}}function cS(e,n,t,r){let o={...Hu(t),"session.id":n.sessionId,...r?{[Qo]:r}:{}};if(e.role==="agent")return{...o,...kc(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,...dS(s.usage),...Tc(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,..._c(e.tool.input,e.toolResult?.content,t.captureContent)};return e.failed&&(s["otel.status_code"]="ERROR"),s}return o}function ro(e,n){let t=Gu(e),r=e.cwd?rS(dn(e.cwd)):null,o=n.resolved??null,s=0,i={},a=t.map(c=>{let u=Br(cS(c,e,n,r),o);s+=u.redactedCount;for(let p in u.byType)i[p]=(i[p]??0)+u.byType[p];return{traceId:Bu(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"?sS:oS,startTimeUnixNano:Ku(c.startTs),endTimeUnixNano:Ku(c.endTs),attributes:u.attributes,error:c.failed}}),d={[Me]:n.orgId,[Ko]:n.projectId,[Ho]:Ce(n.orgId,ie),[Vo]:ie,...Hu(n)};return n.developerId&&(d[Wo]=n.developerId),{resource:{attributes:d},scope:{name:n.provenance==="live"?aS:iS,version:n.scopeVersion??"0.0.0"},spans:a,redactions:{total:s,byType:i}}}var uS=6;function lS(e,n){let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function pS(e){if(e.cwd){let n=Nn(e.cwd);if(n)return n}return hr(e.project)||"default"}function fS(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 Vu(e,n={}){let t=await Si(e.projectsRoot,e.projectRoot,{...n.scanIO,lineSource:n.lineSource??n.scanIO?.lineSource});return n.emit?.({event:"scan",...t}),t}function Wu(e,n={}){let t=fi(e.homeDir,n.checkpointIO);return n.emit?.({event:"status",sessions:t.sessions}),t}async function Qu(e,n,t={}){let r=yS(),o=t.hashFile??_u,s=Pe(e.scrubConfig??me),i=await Si(e.projectsRoot,e.projectRoot,{...t.scanIO,lineSource:t.lineSource??t.scanIO?.lineSource}),a=fS(i,e),d=a.length,c=Math.max(1,e.concurrency??uS),u=fi(e.homeDir,t.checkpointIO),p=await Ot(a,c,async _=>{try{return await o(_.file)}catch(F){return`unhashable:${F.message}`}}),l=new Map;a.forEach((_,F)=>{l.set(_.sessionId,p[F])});let f=0,m=!0,g=a;if(!e.reimport){let _=await Xr(a.map(F=>F.sessionId),{endpoint:e.endpoint,token:e.token},{fetch:t.upload?.fetch});if(m=_.ok,_.ok&&_.known.size>0){let F=[];for(let x of a)mS(_.known,u,x.sessionId,l.get(x.sessionId)??"")?(f++,t.emit?.({event:"dedup-skip",sessionId:x.sessionId})):F.push(x);g=F}}t.emit?.({event:"import-start",batchId:r,total:d,dedupSkipped:f,dedupOk:m,dryRun:e.dryRun??!1});let h=[],S=0,I=0,E=0,C=0,b=0,y=0,R=0,T={};for(let _ of lS(g,c)){let F=await Ot(_,c,async x=>{let re=l.get(x.sessionId)??"";if(n&&!xt(u,x.sessionId,re))return{item:x,kind:"skipped",sourceHash:re};let Fe;try{Fe=await Zr(x.file,x.sessionId,t.lineSource)}catch(rt){let Ze=(rt instanceof mn,rt.message);return{item:x,kind:"quarantined",sourceHash:re,error:Ze}}if(e.retentionCutoffMs!==void 0&&Date.parse(Fe.firstTimestamp)<e.retentionCutoffMs)return{item:x,kind:"skipped-retention",sourceHash:re};let Xe=z(e.orgId,pS(x)),ge=ro(Fe,{orgId:e.orgId,projectId:Xe,developerId:e.developerId,batchId:r,captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:s}),tt=await Je(Te(ge),{endpoint:e.endpoint,token:e.token,dryRun:e.dryRun},t.upload);return{item:x,kind:tt.status==="failed"?"failed":"done",sourceHash:re,spans:ge.spans.length,error:tt.error,upload:tt,redactions:ge.redactions}});for(let x of F){if(x.redactions){R+=x.redactions.total;for(let re in x.redactions.byType)T[re]=(T[re]??0)+x.redactions.byType[re]}x.kind==="skipped"?I++:x.kind==="skipped-retention"?b++:x.kind==="quarantined"?(C++,u=gn(u,x.item.sessionId,{status:"quarantined",sourceHash:x.sourceHash,batchId:r,error:x.error})):(x.kind==="failed"?E++:S++,y+=x.spans??0,u=gn(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})}Tu(e.homeDir,u,t.checkpointIO)}let k={total:d,imported:S,skipped:I,failed:E,quarantined:C,retentionSkipped:b,dedupSkipped:f,dedupOk:m,estimatedActions:y,outcomes:h,redactions:{total:R,byType:T},excludedOtherProject:i.excludedOtherProject??0,excludedUnknownCwd:i.excludedUnknownCwd??0};return t.emit?.({event:"import-done",batchId:r,...gS(k),dedupOk:k.dedupOk,redactions:k.redactions}),k}function gS(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 mS(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 yS(){return`bf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Ju(e){return Ae(e,"setup")}function Yu(e){return Ae(e,"logout")}function zu(e,n="status"){return Ae(e,n)}import{existsSync as Ut,realpathSync as Wl}from"fs";import{dirname as Gl,join as In,relative as vR,sep as Yi}from"path";import{readFileSync as hS}from"fs";import{join as SS,sep as qu}from"path";var RS=15e3,ES=200;async function Xu(e,n,t,r={}){let o=r.io??O,s=v(e,n).root;return o.mkdirp(s,Be),ve({lockPath:SS(s,"install.lock"),io:r.lockIO,timeoutMs:RS},t)}function Zu(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=Ge(e,n,a);t.exists(d)&&(s+=t.readdir(d).filter(c=>c.endsWith(".json")).length)}catch{}return s}async function el(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(ES,u()));return o.exists(d)?{waited:p,stillLocked:!0}:(await a({home:e,maxRunMs:u()}),{waited:p,stillLocked:!1})}function nl(e,n,t){let r=Pn(e);return r!==null?t(r):n.filter(s=>e===s||e.startsWith(s.endsWith(qu)?s:`${s}${qu}`)).sort((s,i)=>i.length-s.length)[0]??e}function tl(e,n,t){let r=Dn(e),o=t.project?.trim();if(o)return{slug:o,id:z(n,o),source:"flag",label:r};let s=ss(e);if(s!==null)try{let a=mr(JSON.parse(hS(s,"utf8"))),d=a.orgId===n&&a.projectId!==void 0?a.projectId:z(n,a.projectSlug);return{slug:a.projectSlug,id:d,source:"agenttrail-json",label:r}}catch(a){return{error:`${s} cannot be read as a ${B} (${a.message}). Fix it, or pass --project <slug>.`}}let i=cn(e);return i===null?{error:"could not work out a project slug for this folder. Pass --project <slug>."}:{slug:i.slug,id:z(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}}import{realpathSync as Ox}from"fs";function bi(e,n,t=O){let r=Jn(e,t),o=r===void 0?n:{...n,writtenAt:r.writtenAt};return r!==void 0&&JSON.stringify(r)===JSON.stringify(o)?!1:(t.writeFileAtomic(j(e).enforcement,`${JSON.stringify(o,null,2)}
|
|
49
|
-
`,D),!0)}function Jn(e,n=O){let t;try{let o=j(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 rl="cursor";import{join as ll}from"path";import{execFileSync as CS}from"child_process";import{accessSync as kS,constants as TS}from"fs";var wt=class extends Error{constructor(n){super(n),this.name="HookCommandError"}},bS=/["$`\\\r\n\0]/,IS=/^[A-Za-z0-9_.:=/-]+$/;function oo(e){if(bS.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 hn(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 ol(e,n,t,r=o=>new wt(o)){for(let o of[e,n]){let s=oo(o);if(s!==void 0)throw r(s)}for(let o of t)if(!IS.test(o))throw r(`${JSON.stringify(o)} is not a fixed hook argument`);return[hn(e),hn(n),...t].join(" ")}var Ii="{}",vt="CURSOR_PROJECT_DIR",Ye=class extends wt{constructor(n){super(n),this.name="CursorGateError"}},_S=/[\r\n\0]/;function xi(e){if(_S.test(e))return`${JSON.stringify(e)} holds a line break, which the gate cannot match`}function OS(e,n,t){return ol(e,n,t,r=>new Ye(r))}function Sn(e,n,t){return OS(e,n,["--agent",Ps,"--scope",t])}var Ci='m() { case "$1" in ',ki=`) return 0 ;; esac; return 1; }; if m "$${vt}"; then exec `,Ti=`; fi; p=$(cd -P -- "$${vt}" 2>/dev/null && pwd -P); if [ -n "$p" ] && m "$p"; then exec `,_i=`; fi; printf "${Ii}"`,Oi="/bin/sh -c ";function xS(e){let n=e.endsWith("/")?e:`${e}/`;return`${hn(e)}|${hn(n)}*`}function so(e,n){if(e.length===0)throw new Ye("a gated command needs at least one connected folder");let t=[];for(let o of e){let s=xi(o);if(s!==void 0)throw new Ye(s);t.push(xS(o))}let r=Ci+t.join("|")+ki+n+Ti+n+_i;return Oi+hn(r)}function sl(e,n){let t=n,r="",o=!1;for(;;){let s=e[t];if(s===void 0||s==="|"||s===")")break;if(o)throw new Ye("a gate pattern ends at its star");if(s==="'"){let i=e.indexOf("'",t+1);if(i===-1)throw new Ye("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 Ye("a character this generator never writes")}return{value:r,end:t,star:o}}function AS(e){try{let n=sl(e,0);return n.end===e.length&&!n.star?n.value:void 0}catch{return}}function Rn(e){if(!e.startsWith(Oi))return;let n=AS(e.slice(Oi.length));if(n===void 0||!n.startsWith(Ci))return;let t=[],r=Ci.length;try{for(;;){let d=sl(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(ki,r))return;let o=n.slice(r+ki.length),s=o.indexOf(Ti);if(s===-1||!o.endsWith(_i))return;let i=o.slice(0,s),a=o.slice(s+Ti.length,o.length-_i.length);return i===a?{folders:t,helper:i}:void 0}function Ai(e){return typeof e=="string"&&Rn(e)!==void 0}function il(e,n){let t=Rn(e);if(t!==void 0)return so(n,t.helper)}var wS="/nonexistent/agenttrail-gate-dry-run";function vS(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{kS(r,TS.X_OK),t.push(r)}catch{}return t}function al(e,n={}){let t=n.env??process.env,r=n.shells===void 0?vS(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=CS(o,["-c",e],{input:"",encoding:"utf8",timeout:n.timeoutMs??5e3,env:{...t,[vt]:wS},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!==Ii)return{ok:!1,shells:r,reason:`${o} answered ${JSON.stringify(s)} for an unconnected workspace, not ${Ii}`}}return{ok:!0,shells:r}}function dl(e=process.platform){return e!=="win32"}var Pt="3.21.16",PS=/^(\d+)\.(\d+)\.(\d+)$/;function cl(e){if(typeof e!="string")return;let n=PS.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 NS(e,n){return e.major!==n.major?e.major-n.major:e.minor!==n.minor?e.minor-n.minor:e.patch-n.patch}function ul(e){let n=cl(e);if(n===void 0)return"unknown";let t=cl(Pt);return t===void 0?"unknown":NS(n,t)>=0?"supported":"too-old"}import{readFileSync as Vx}from"fs";var Oe=class extends Error{constructor(n){super(`PDP unreachable: ${n}`),this.name="PdpUnreachableError"}},DS=/^This feature requires the (Pro|Team|Business|Enterprise) plan or higher\.$/;async function jS(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"&&DS.test(o)}function FS(e){return new Oe(`${e} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`)}async function LS(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 Oe(a)}finally{clearTimeout(s)}}async function Nt(e,n){let t=await LS(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 Oe("200 snapshot with unparseable JSON body")}if(!MS(r))throw new Oe("200 with malformed PolicyCompiledSnapshot");return{kind:"ok",snapshot:r}}if(t.status===403){if(await jS(t))return{kind:"tier-disabled"};throw FS("snapshot")}if(t.status===401)return{kind:"unauthorized"};throw new Oe(`unexpected snapshot status ${t.status}`)}function MS(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 wi(e,n){try{let t=await Nt(e,n);return t.kind==="ok"?{outcome:"ok",snapshot:t.snapshot}:{outcome:t.kind==="unauthorized"?"unauthorized":"forbidden"}}catch{return{outcome:"unreachable"}}}var En="pep-hook.mjs",pl={preToolUse:600,beforeMCPExecution:600,beforeShellExecution:30},vi=Object.keys(pl);function io(e){return typeof e=="string"&&e.includes(En)&&/(?:^|\s)--agent cursor(?=\s|$)/.test(e)}function Pi(e){return Object.fromEntries(vi.map(n=>[n,[{command:e,timeout:pl[n]??600,failClosed:!0}]]))}function fl(e,n){return Sn(e,ll(n,En),"project")}function Ni(e,n){return Sn(e,ll(n,En),"user")}var $S=!0;function BS(e){return!(e.row0Verified??$S)||!e.hasUserScopeFolders?!1:e.version==="supported"}function gl(e){let n=ul(e.rawCursorVersion);return{v:1,enabled:n==="supported",apiBase:e.apiBase,orgId:e.orgId,agentId:e.agentId,timeoutMs:e.timeoutMs,userScopeHandoff:BS({hasUserScopeFolders:e.hasUserScopeFolders,version:n,...e.row0Verified===void 0?{}:{row0Verified:e.row0Verified}}),cursorVersion:e.rawCursorVersion,versionSupport:n,writtenAt:e.now.toISOString()}}var GS="/Applications/Cursor.app/Contents/Info.plist",KS=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]*)<\/string>/;function ml(e=t=>O.readFile(t).toString("utf8"),n=GS){try{let r=KS.exec(e(n))?.[1]?.trim();return r===void 0||r===""?null:r}catch{return null}}function yl(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 ao(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 ${Pt} 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"]}}import{renameSync as mR}from"fs";import{homedir as yR}from"os";import{createHash as nR}from"crypto";function hl(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:HS(a,n,t),filledToolUseId:i}}function HS(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})}import{appendFileSync as oA}from"fs";var Di=".dropped",VS="c";function Sl(e){return e===VS?"queue-full":`mark-${e}`}import{randomBytes as WS}from"crypto";import{closeSync as QS,openSync as JS,readFileSync as YS,rmSync as zS,statSync as qS,utimesSync as XS,writeSync as ZS}from"fs";var Rl=5e3,ji=2e4,Dt={acquire(e,n){let t=JS(e,"wx",384);try{ZS(t,n)}finally{QS(t)}},release(e){try{zS(e,{force:!0})}catch{}},age(e){try{return Date.now()-qS(e).mtimeMs}catch{return null}},read(e){try{return YS(e,"utf8")}catch{return null}},touch(e){try{let n=new Date;XS(e,n,n)}catch{}},now:()=>Date.now()};function El(e,n=Dt){let t=n.age(e);return t!==null&&t<=ji&&t>=-ji}function eR(e,n){return`${e} ${new Date(n).toISOString()} ${WS(8).toString("hex")}
|
|
50
|
-
`}function co(e,n=Dt,t=process.pid){let r=eR(t,n.now()),o=()=>{try{return n.acquire(e,r),!0}catch{return!1}};if(!o()&&(El(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<Rl?!0:(s=i,n.read(e)!==r?!1:(n.touch(e),!0))},release(){n.read(e)===r&&n.release(e)}}}var Cl=35e5,tR=new Set([400,413,422]),Fi={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function Li(e){return nR("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 kl(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 Tl(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!==Li(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function _l(e,n,t=Cl){let r=[],o=[];for(let s of n){let i=[...o,s];if(Buffer.byteLength(JSON.stringify(Te({...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 uo(e,n,t){de(e.totals.dropped,t),de(e.report,t),n!==void 0&&de(Ct(e.totals,n).dropped,t)}async function rR(e,n,t){let r=async()=>(n.posts+=1,Je(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 oR(e,n,t,r){if(t.length===n.length)return!1;let o=new Set(t),s=De(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&&De(a.conversationId,a.generationId)===s})}function sR(e){let{closed:n,...t}=e;return t}async function iR(e,n,t){let{adapter:r,deps:o,mem:s}=e,i=o.now(),a=hl(t.records,t.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=t.state,p=oR(r,a.records,d,u)?sR(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}:bl(e,u,t,a.filledToolUseId);let f=kl(o.builder.assemble(d,void 0,t.decisions),p);if(p.closed!==void 0&&r.usageOf!==void 0){let C=r.usageOf({conversationId:u.conversationId,generationId:u.generationId},{home:o.home,env:o.env??process.env,io:o.io});C!==null&&(f={...f,usage:C})}let m=o.builder.build(f,{orgId:n.credentials.org_id,project:{projectId:n.project.projectId,projectLabel:n.project.projectLabel,...n.project.developerId!==void 0?{developerId:n.project.developerId}:{}},captureContent:n.project.captureContent,mode:"live",scopeVersion:o.scopeVersion,resolvedScrubbers:s.scrubbers}),g=new Set;l&&(g.add(o.builder.spanId(u.traceId,"root")),g.add(o.builder.spanId(u.traceId,"model")));let{spans:h,starts:S}=Tl(m.spans,u,g),I=0;for(let C of _l(m,h)){let b=await rR(o,n,Te({...m,spans:C}));if(b.ok){let y={...u.sent},R={...u.starts};for(let k of C)y[k.spanId]=Li(k),R[k.spanId]=S[k.spanId]??k.startTimeUnixNano;u={...u,sent:y,starts:R},I+=C.length;let T=o.now();s.totals.lastUploadAtMs=T,Ct(s.totals,n.project.projectKey).lastUploadAtMs=T,Wn(o.home,r.stateDir,u,o.io);continue}if(b.status!==void 0&&tR.has(b.status)){let y={...u.sent};for(let R of C)y[R.spanId]=`dropped:${b.status}`,uo(s,n.project.projectKey,`rejected-${b.status}`);u={...u,sent:y},Wn(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:I,drained:!1,open:l,fatal:b.status===401?"auth":"network",...b.error!==void 0?{error:b.error}:{}}}return u.closed!==void 0&&!c&&m.spans.every(C=>u.sent[C.spanId]!==void 0)?{...bl(e,u,t,a.filledToolUseId),sent:I}:{state:u,sent:I,drained:!1,open:l}}function bl(e,n,t,r){let{adapter:o,deps:s,mem:i}=e,a={...n,files:[]};Wn(s.home,o.stateDir,a,s.io);let d=Ge(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 aR(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=Ct(o.totals,n),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function dR(e,n,t){let{deps:r,mem:o}=e,s=`${t}/${Di}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))uo(o,n,Sl(a))}catch{}r.io.remove(i)}}function cR(e,n){let t=/^\.(\d+)-\d+-\d+\.json\./.exec(e);if(!(t===null||!e.endsWith(".tmp")))return n-Number(t[1])}function Il(e){let{adapter:n,deps:t,mem:r}=e;if(!Us(r.totals))try{if(!t.io.exists(v(t.home,n.stateDir).projects)){r.totals=It();return}$s(t.home,n.stateDir,Bs(kt(t.home,n.stateDir,n.versionKey,t.io),r.totals,n.versionKey),t.io),r.totals=It()}catch{}}function Ol(e,n,t){try{return t.readdir(v(e,n).queue)}catch{return[]}}async function uR(e,n){let{adapter:t,deps:r,mem:o}=e,s=r.now(),i=r.credentials();if(i===null)return lR(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 Ol(r.home,t.stateDir,r.io)){let h=Ge(r.home,t.stateDir,g),{files:S,other:I}=Jr(h,y=>t.parseQueueEntry(y),r.io,o.cache,h);I.includes(Di)&&dR(e,g,h);for(let y of I){let R=cR(y,s);R!==void 0&&R>=_t&&r.io.remove(`${h}/${y}`)}if(S.length===0)continue;for(let y of S)u=Math.max(u,y.atMs);aR(e,g,S);let E=ri({projectKey:g,files:S,states:[...o.states.values()],nowMs:s,traceIdFor:y=>r.builder.traceId(y),...n.closeOpenTurns===!0?{limits:{idleSweepMs:0}}:{},rules:t});for(let{file:y,reason:R}of E.dropped){uo(o,g,R);let T=y.entry;T?.kind==="unknown"&&de(o.totals.unknownKinds,T.rawKind),R==="decision-orphan"&&(o.totals.pepDecisions.orphaned+=1,o.totals.pepDecisions.seen+=1),r.io.remove(`${h}/${y.name}`),o.cache.delete(`${h}/${y.name}`)}d+=E.pending.length;let C=a.kind==="ok"?a.registry.projects[g]:void 0;if(C===void 0){if(d+=E.turns.reduce((y,R)=>y+R.files.length,0),a.kind==="ok"){for(let y of E.turns)if(!(s-y.state.lastRecordAtMs<_t)){for(let R of y.files)uo(o,g,"unregistered"),r.io.remove(`${h}/${R}`),o.cache.delete(`${h}/${R}`);o.states.delete(y.state.traceId),Qr(r.home,t.stateDir,y.state.traceId,r.io)}}continue}let b={project:C,credentials:i,posts:o.posts};for(let y of E.turns){let R;try{R=await iR(e,b,y)}catch(T){R={state:y.state,sent:0,drained:!1,open:y.state.closed===void 0,fatal:"network",error:T instanceof Error?T.message:String(T)},pR(e,y.state)}if(o.states.set(R.state.traceId,R.state),p+=R.sent,R.drained)for(let T of y.files)o.cache.delete(`${h}/${T}`);else d+=y.files.length,R.open&&(c+=1);if(R.fatal!==void 0){l=!0,m=R.error??m,o.totals.lastError={atMs:r.now(),message:R.error??(R.fatal==="auth"?"not signed in":"upload failed")},R.fatal==="auth"&&(f="auth");break}}if(o.posts=b.posts,i=b.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 lR(e,n={}){return{entries:0,openTurns:0,newestRecordMs:e,sent:0,failed:!1,...n}}function pR(e,n){try{Wn(e.deps.home,e.adapter.stateDir,n,e.deps.io)}catch{}}function fR(e,n,t){for(let r of Ol(e,n,t))try{if(t.readdir(Ge(e,n,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function gR(e,n,t,r){return e.failed?r:e.openTurns===0?n.pollIdleMs:t-e.newestRecordMs<=n.flowWindowMs?n.pollFlowingMs:n.pollOpenMs}async function xl(e,n,t={}){let r=v(n.home,e.stateDir),o=co(r.senderLock,n.lockIO,n.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=ti(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:It(),report:{},scrubbers:Pe(me),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 uR(a,t);u+=1,p+=g.sent,l=g.error??l,Il(a);for(let h of oi([...i.states.values()],n.now()))Qr(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,!fR(n.home,e.stateDir,n.io)||(o=co(r.senderLock,n.lockIO,n.pid),o===void 0))break;continue}await n.sleep(gR(g,n.limits,n.now(),m)),g.failed&&(m=Math.min(m*2,n.limits.pollIdleMs*12))}}finally{Il(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:p,dropped:i.report,...l!==void 0?{lastError:l}:{}}}function Al(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 hR=2e3,SR={traceId:e=>Xs(e,"live"),spanId:(e,n)=>Zs(e,n),assemble:e=>Yc(e),build:(e,n)=>Wr(e,n)};function RR(e,n,t=hR){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(li)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:n-o.capturedAtMs>=t})}function ER(e){if(e.cursorVersion!==null)return{version:e.cursorVersion,seenAtMs:e.capturedAtMs}}var bR={...jr,versionKey:Mr,versionOf:ER,readRegistry:(e,n)=>ee(e,n),parseQueueEntry:e=>qr(e),turnOf:mu,decisionTurnOf:yu,opensTurn:hu,closesTurn:Su,subagentOf:Ru,fillableEvent:Eu,holdBack:(e,n)=>RR(e,n)};function IR(e,n={}){return xl(bR,e,n)}async function CR(e,n,t){let r=be({homeDir:e});return r===null?null:r.ingest_token!==n?r:ve({lockPath:`${Ee(e,"cursor")}.lock`},async()=>{let o=be({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 An(s,o.refresh_token,t),a=wn({agent:"cursor",apiEndpoint:s,ingestEndpoint:o.endpoint,homeDir:e,host:o.host,log:()=>{}},i,{apiEndpoint:s,ingestEndpoint:o.endpoint});return xn(e,a,{},"cursor"),a}catch{return null}})}function kR(e={}){let n=e.home??yR(),t=e.io??O;return{home:n,io:t,lockIO:Dt,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:SR,pid:process.pid,limits:Fi,credentials:()=>be({homeDir:n}),refresh:r=>CR(n,r),claimFile:(r,o)=>{try{return mR(r,o),!0}catch{return!1}},scopeVersion:Al(n,N,t)??"0.0.0",...e}}async function Mi(e={}){try{await IR(kR(e.deps??{}),e)}catch{}return 0}function TR(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}TR()&&Mi().then(e=>{process.exitCode=e});var lo="# agenttrail: Cursor capture hooks (agenttrail setup --agent cursor)";function wl(e,n,t={}){return fr(e,n,lo,t)}function Ui(e,n,t={}){return Ja(e,n,lo,t)}var vl="capture-hook.mjs",_R="pep-hook.mjs",Pl=/(?:^|\s)--agent cursor(?=\s|$)/;function jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yn(e){return typeof e=="string"&&e.includes(vl)&&Pl.test(e)}function Nl(e){return typeof e!="string"?!1:Ai(e)?!0:Pl.test(e)?e.includes(vl)||e.includes(_R):!1}function ze(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(!jt(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&&!jt(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 OR(e){return`${JSON.stringify(e,null,2)}
|
|
51
|
-
`}function Ft(e){return Array.isArray(e)?`[${e.map(Ft).join(",")}]`:jt(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ft(e[t])}`).join(",")}}`:JSON.stringify(e)}function $i(e,n,t,r){let o=OR(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 po(e){return jt(e)&&typeof e.command=="string"?e.command:void 0}function Lt(e,n,t){let r=ze(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=po(p);return l!==void 0&&t(l)}),c=n[i]??[];if(Ft(d)===Ft(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,$i(r.doc,e,s,o)}function Bi(e,n){if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=ze(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=po(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,$i(t.doc,e,o,r)}function Gi(e,n){if(n.length===0)return Bi(e,Ai);if(e===void 0)return{ok:!0,text:"",changed:!1,removed:0,empty:!0};let t=ze(e);if(!t.ok)return t;let r={};for(let[o,s]of Object.entries(t.hooks))r[o]=s.map(i=>{let a=po(i);if(a===void 0||!jt(i))return i;let d=il(a,n);return d===void 0||d===a?i:{...i,command:d}});return t.doc.hooks=r,$i(t.doc,e,0,r)}function zn(e,n){let t=ze(e);if(!t.ok)return[];let r=[];for(let[o,s]of Object.entries(t.hooks))for(let i of s){let a=po(i);a!==void 0&&n(a)&&r.push({event:o,entry:i})}return r}function xR(e,n){let t=o=>{let s=Bi(o,Nl);if(!s.ok)return;let i=ze(s.text);if(!i.ok)return;let a=Object.fromEntries(Object.entries(i.hooks).filter(([,d])=>d.length>0));return Ft({...i.doc,hooks:a})},r=t(e);return r!==void 0&&r===t(n)}var Ki={refusal:e=>{let n=ze(e);return n.ok?void 0:n.reason},remove:(e,n)=>Bi(e,n),hasAnyOurs:e=>zn(e,Nl).length>0,sameApartFromOurs:(e,n)=>xR(e,n)};function Dl(e){return ns(e,N)}function qn(e,n,t,r={}){return Va(e,N,n,t,r)}function Hi(e,n,t,r={}){return Wa(e,N,n,Ki,t,r)}import{createHash as AR}from"crypto";import{dirname as Wi,join as bn}from"path";import{fileURLToPath as wR}from"url";function jl(){let e=import.meta.url;return e?Wi(wR(e)):typeof __dirname<"u"?__dirname:process.cwd()}function Fl(e,n,t=jl(),r=o=>O.exists(o)){let o=t;for(;;){for(let i of[bn(o,e),bn(o,"dist",e)])if(r(bn(i,n)))return i;let s=Wi(o);if(s===o)return;o=s}}function Qi(e=jl(),n=O){let t=e;for(;;){let r=bn(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=Wi(t);if(o===t)return"unknown";t=o}}function Vi(e){return AR("sha256").update(e).digest("hex")}function fo(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 Ll(e,n,t,r){let o=r.io??O,s=v(e,n);o.mkdirp(s.runtime,Be);let i={},a=[];for(let p of t){let l=o.readFile(bn(r.sourceDir,p)),f=Vi(l);i[p]=f;let m=bn(s.runtime,p),g;try{g=o.exists(m)?Vi(o.readFile(m)):void 0}catch{g=void 0}g!==f&&(o.writeFileAtomic(m,l,D),a.push(p))}let d=fo(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)}
|
|
52
|
-
`,D),{runtimeDir:s.runtime,copied:a,record:c,recordWritten:!u}}function Ml(e,n,t,r=O){let o=v(e,n),s=fo(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=bn(o.runtime,a),c;try{c=r.exists(d)?Vi(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 Xn=["capture-hook.mjs","flush.mjs","pep-hook.mjs"],go=["capture-hook.mjs","flush.mjs"];function Ul(e,n=t=>O.exists(t)){return Fl(N,Xn[0],e,n)}function $l(e,n=O){return fo(e,N,n)}function Bl(e,n){return Ll(e,N,Xn,n)}function Mt(e,n=O,t=Xn){return Ml(e,N,t,n)}var PR={stop:5},NR=2,Ql=".cursor",Jl="hooks.json",Kl=1e4;async function zi(e,n,t={}){return Xu(e,N,n,t)}function DR(e,n){return{command:n,timeout:PR[e]??NR}}function Zn(e){return Yn(e)||io(e)}function Ji(e,n){return{...Yl(e),...n===void 0?{}:Pi(n)}}function Yl(e){return Object.fromEntries(ce.map(n=>[n,[DR(n,e)]]))}function jR(e,n){return Sn(e,In(n,"capture-hook.mjs"),"project")}function mo(e,n){return Sn(e,In(n,"capture-hook.mjs"),"user")}function je(e){return In(e,Ql,Jl)}function ne(e){return In(e,Ql,Jl)}function yo(e,n){return vR(e,je(n)).split(Yi).join("/")}var ww={...jr,runtimeFiles:Xn,captureRuntimeFiles:go,captureEvents:ce,projectHooksPath:je,userHooksPath:ne,hooksFormat:Ki,mergeEntries:(e,n,t)=>Lt(e,n,t),isOurs:Zn,captureEntries:Yl,enforcementEntries:Pi,command:Sn,gateEnvVar:vt,excludeMarker:lo,transcriptFolderOf:un};function FR(e,n){let t;try{t=n.readText(e)}catch(s){return`${e} cannot be read \u2014 ${s.message}`}let r=ze(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 zl(e,n,t){return nl(e,n,t)}function LR(e,n,t){return tl(e,n,t)}function Hl(e,n){let t=r=>(r??"").replace(/\/+$/,"");return t(e)===t(n)}async function MR(e,n,t){let r=t.login??cr,o=be(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&&(!Hl(o.endpoint,n.ingestEndpoint)||!Hl(o.api_endpoint??n.apiEndpoint,n.apiEndpoint));return o&&!He(o,n.now)&&!i?{creds:o,reused:!0,endpointChanged:!1}:{creds:await r(n),reused:!1,endpointChanged:i}}function Vl(e,n,t,r){let o=t.git??L,s=t.hooksIO??G;if(!Ut(n))return{path:n,install:r??"project"};if(!le(e,o))return{path:n,install:"project",excluded:"not-a-repo"};let i=yo(e,n),a=Ie(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=wl(e,i,{git:o,io:s});return d.ok?{path:n,install:"project",excluded:d.state}:{path:n,install:"user",note:d.reason}}function qi(e,n,t,r,o){let s=o.hooksIO??G,i=ne(e);if(n.length===0){let l=Hi(e,i,Zn,{io:s});if(!l.ok)return{ok:!1,reason:l.reason};let f=qn(e,i,m=>Gi(m,[]),{io:s});return f.ok?{ok:!0,changed:l.change.changed||f.change.changed}:{ok:!1,reason:f.reason}}if(!dl(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=so(n,t),d=r===void 0?void 0:so(n,r),c=(o.dryRun??al)(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=qn(e,i,l=>Lt(l,Ji(a,d),Zn),{io:s});if(!u.ok)return{ok:!1,reason:u.reason};let p=qn(e,i,l=>Gi(l,n),{io:s});return p.ok?{ok:!0,changed:u.change.changed||p.change.changed}:{ok:!1,reason:p.reason}}var UR=["key","team","global"];async function ql(e,n={}){let t=e.flags;if(t.unregister===!0)return $R(e,n);let r=UR.filter(k=>!!t[k]);if(r.length>0)return e.io.error(`error: ${r.map(k=>`--${k}`).join(", ")} ${r.length===1?"is":"are"} for Claude Code. Cursor setup signs this device in with your browser and connects this project: ${W("cursor","setup")}`),1;let o;try{o=e.sessionEnv()}catch(k){return e.io.error(`error: ${k.message}`),1}let s=o.homeDir,i=n.io??O,a=n.hooksIO??G,d=n.realpath??(k=>Wl.native(k)),c=n.nodePath??process.execPath,u,p;try{let k=ee(s,i);if(k.kind==="unreadable")throw new We(s);p=k.kind==="ok"?Object.values(k.registry.projects).map(x=>x.root):[];let _=d(e.io.cwd),F=zl(_,p,d);u={root:F,folder:_,isSubfolder:_!==F}}catch(k){return e.io.error(`error: ${k.message}`),1}let l=[],f=(()=>{try{return d(s)}catch{return s}})();(u.root===f||f.startsWith(`${u.root}${Yi}`))&&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 k of[u.root,u.folder]){let _=xi(k);_!==void 0&&l.push(_)}let m=n.runtimeSourceDir??Ul();if(m===void 0)l.push("could not find the built Cursor runtime (dist/cursor/capture-hook.mjs) in this installation");else for(let k of Xn)i.exists(In(m,k))||l.push(`the built Cursor runtime is incomplete: ${In(m,k)} is missing`);let g=j(s).runtime;for(let k of[c,In(g,"capture-hook.mjs")]){let _=oo(k);_!==void 0&&l.push(_)}let h=[je(u.root),...u.isSubfolder?[je(u.folder)]:[],ne(s)];for(let k of h){let _=FR(k,a);_!==void 0&&l.push(_)}if(l.length>0||m===void 0){for(let k of l)e.io.error(`error: ${k}`);return e.io.error("Nothing was changed."),1}let S=m,I,E,C;try{({creds:I,reused:E,endpointChanged:C}=await MR(e,o,n))}catch(k){return e.io.error(`error: ${k.message}`),1}let b=LR(u.root,I.org_id,t);if("error"in b)return e.io.error(`error: ${b.error}`),1;let y=t.developer?.trim()||void 0,R=!!t["capture-content"],T=(n.now??(()=>new Date))();try{return await zi(s,async()=>{let k=[];Bl(s,{sourceDir:S,nodePath:c,cliVersion:n.cliVersion??Qi(),now:T,io:i}),gu(s,i);let _=ee(s,i);if(_.kind==="unreadable")throw new We(s);let F=_.kind==="ok"?_.registry:{v:1,projects:{}},x=lr(u.root),re=F.projects[x],Fe=new Map((re?.subfolders??[]).map(A=>[A.path,A]));u.isSubfolder&&!Fe.has(u.folder)&&Fe.set(u.folder,{path:u.folder,transcriptFolder:un(u.folder),install:"project",registeredAt:T.toISOString()});let Xe=Vl(u.root,u.root,n),ge=[...Fe.values()].map(A=>Vl(u.root,A.path,n,A.install));for(let A of[Xe,...ge])A.note!==void 0&&k.push(`${A.path}: ${A.note}`);let tt={projectKey:x,root:u.root,transcriptFolder:un(u.root),orgId:I.org_id,projectSlug:b.slug,projectId:b.id,projectSource:b.source,projectLabel:b.label,...y!==void 0?{developerId:y}:{},captureContent:R,install:Xe.install,registeredAt:re?.registeredAt??T.toISOString(),...ge.length>0?{subfolders:ge.map(A=>({...Fe.get(A.path),install:A.install}))}:{}},rt=(n.cursorVersion??ml)(),Ze=gl({apiBase:I.api_endpoint??I.endpoint,orgId:I.org_id,agentId:Ce(I.org_id,rl),timeoutMs:jn,rawCursorVersion:rt,hasUserScopeFolders:[Xe,...ge].some(A=>A.install==="user"),now:T}),oe=Ze;if(Ze.enabled){let A=await wi({url:Fn(Ze.apiBase),token:I.ingest_token,timeoutMs:Ze.timeoutMs},n.fetchFn??fetch);if(A.outcome==="ok")A.snapshot!==void 0&&i.writeFileAtomic(j(s).pepSnapshot,`${JSON.stringify(A.snapshot)}
|
|
53
|
-
`,D);else{let xe=yl(A.outcome);oe={...Ze,enabled:!1,userScopeHandoff:!1,probeNote:xe},k.push(xe)}}lc(s,{...tt,enforce:oe.enabled},i),oe.enabled&&bi(s,oe,i);let ua=jR(c,g),la=oe.enabled?fl(c,g):void 0,ot=[];for(let A of[Xe,...ge]){if(!Ut(A.path))continue;let xe=je(A.path);if(A.install==="project"){let se=qn(s,xe,Jt=>Lt(Jt,Ji(ua,la),Zn),{io:a});se.ok||ot.push(se.reason)}else{let se=Xl(s,u.root,A.path,n);se.ok||ot.push(se.reason),Ui(u.root,yo(u.root,A.path),{git:n.git??L,io:a})}}for(let A of Object.values(F.projects)){if(A.projectKey===x)continue;let xe=[{path:A.root,install:A.install},...(A.subfolders??[]).map(se=>({path:se.path,install:se.install}))];for(let se of xe){if(se.install!=="project"||!Ut(se.path))continue;let Jt=qn(s,je(se.path),of=>Lt(of,Ji(ua,A.enforce===!0?la:void 0),Zn),{io:a});Jt.ok||k.push(Jt.reason)}}let pa=ee(s,i),rf=pa.kind==="ok"?Fs(pa.registry):[],Qt=qi(s,rf,mo(c,g),oe.enabled?Ni(c,g):void 0,n);if(Qt.ok?Qt.note!==void 0&&k.push(Qt.note):ot.push(Qt.reason),ot.length>0){for(let A of ot)e.io.error(`error: ${A}`);return 1}oe.enabled||bi(s,oe,i),E?(e.io.log(`Sign-in: REUSED \u2014 this project is connected to org ${I.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: \`${W("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 ${I.org_id}, device ${I.host}).`),C&&e.io.log(`Every connected project now sends to ${I.endpoint}.`),e.io.log(`Project: ${b.slug} -> project.id ${b.id}`),b.note!==void 0&&e.io.error(b.note);for(let A of[Xe,...ge]){if(!Ut(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 ${ne(s)}, gated to your connected folders`)}for(let A of k)e.io.error(`note: ${A}`);R?(e.io.log("Content capture: ON (prompts, commands, paths and tool output; scrubbed on this machine before anything is queued)."),e.io.error(tr("cursor"))):e.io.log("Content capture: OFF (metadata and tokens only; turn it on with --capture-content).");{let A=ao({record:oe,projectEnforced:oe.enabled,problems:Mt(s,i,[En]),entriesInstalled:oe.enabled});e.io.log(A.headline),oe.enabled&&e.io.log(` ${vi.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 \`${W("cursor","status")}\`.`),0},n)}catch(k){return e.io.error(`error: ${k.message}`),1}}async function $R(e,n={}){let t;try{t=e.sessionEnv()}catch(a){return e.io.error(`error: ${a.message}`),1}let r=t.homeDir,o=n.io??O,s=n.realpath??(a=>Wl.native(a)),i=n.nodePath??process.execPath;try{return await zi(r,async()=>{let a=ee(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(S=>S.root),u=zl(d,c,s),p=a.registry.projects[lr(u)]??Object.values(a.registry.projects).filter(S=>d===S.root||d.startsWith(`${S.root}${Yi}`)).sort((S,I)=>I.root.length-S.root.length)[0];if(p===void 0)return e.io.log(`${d} is not a connected Cursor project; nothing to remove.`),0;let l=Zl(r,p,n);if(l.failures.length>0){for(let S of l.failures)e.io.error(`error: ${S}`);return e.io.error("The project is still connected; fix the file above and run this again."),1}let f={v:1,projects:Object.fromEntries(Object.entries(a.registry.projects).filter(([S])=>S!==p.projectKey))},m=Jn(r,o)?.enabled===!0,g=qi(r,Fs(f),mo(i,j(r).runtime),m?Ni(i,j(r).runtime):void 0,n);if(!g.ok)return e.io.error(`error: ${g.reason}`),1;pc(r,p.projectKey,o);let h=ep(r,o,p.projectKey);o.remove(Bn(r,p.projectKey)),e.io.log(`Disconnected ${p.root} (project ${p.projectSlug}).`);for(let S of l.folders)e.io.log(`Removed our entries from ${S}`);return h>0&&e.io.log(`Dropped ${h} queued event(s) that had not been sent.`),e.io.log(`This device stays signed in for Cursor; \`${W("cursor","logout")}\` signs it out and removes the rest.`),0},n)}catch(a){return e.io.error(`error: ${a.message}`),1}}function Xl(e,n,t,r){let o=r.git??L,s=r.hooksIO??G,i=je(t),a=le(n,o)&&Ie(n,yo(n,t),o)==="tracked";return Hi(e,i,Zn,{io:s,keepFile:a})}function Zl(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=Xl(e,n.root,d,t);u.ok?u.change.changed&&s.push(c):i.push(u.reason),Ut(Gl(Gl(c)))&&Ui(n.root,yo(n.root,d),{git:o,io:r})}return{folders:s,failures:i}}function ep(e,n,t){return Zu(e,N,n,t)}async function BR(e){try{await Mi({maxRunMs:e.maxRunMs,closeOpenTurns:!0,deps:{home:e.home}})}catch{}}async function GR(e,n,t={}){return el(e,N,n,{...t,run:t.run??BR})}var KR={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 HR(e){let n=j(e);return[...Object.entries(n).filter(([r])=>!(r in KR)).map(([,r])=>r),Dl(e)]}async function np(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 zi(r,async()=>{let i=await(n.flush??GR)(r,Kl),a=ee(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=Zl(r,l,n);c.push(...f.folders);for(let m of f.failures)e.io.error(`error: ${m}`),s=!0}let u=qi(r,[],"",void 0,n);u.ok?u.changed&&c.push(ne(r)):(e.io.error(`error: ${u.reason}`),s=!0);for(let l of c)e.io.log(`Removed our entries from ${l}`);let p=ep(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=HR(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 ${Kl/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 Fa(t)}catch(i){e.io.error(`error: ${i.message}`),s=!0}return s?1:0}import{realpathSync as VR}from"fs";import{join as rp,sep as Xi}from"path";var WR="3.21.16";function tp(e){return[{path:e.root,install:e.install,record:e},...(e.subfolders??[]).map(n=>({path:n.path,install:n.install,record:e}))]}function QR(e,n){return n===e||n.startsWith(e.endsWith(Xi)?e:`${e}${Xi}`)}function JR(e,n,t){let r=Bn(e,t);try{return n.exists(r)?n.readdir(r).filter(o=>o.endsWith(".json")).length:0}catch{return 0}}function YR(e,n,t){let r=t.hooksIO??G,o=n.install==="project"?rp(n.path,".cursor","hooks.json"):ne(e),s;try{s=r.readText(o)}catch{return}let i=zn(s,io);return n.install==="project"?i.length>0:i.some(a=>(Rn(a.entry.command)?.folders??[]).includes(n.path))}function zR(e,n,t){let r=t.hooksIO??G,o=t.git??L,s=[],i=rp(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=zn(u,Yn);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(Xi).join("/");return Ie(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 ${ne(e)}`),s}let a;try{a=r.readText(ne(e))}catch(u){return s.push(`${ne(e)} cannot be read \u2014 ${u.message}`),s}let d=zn(a,Yn);return d.length!==ce.length?(s.push(`${ne(e)} holds ${d.length} of our ${ce.length} gated entries; run setup again`),s):(new Set(d.flatMap(u=>Rn(u.entry.command)?.folders??[])).has(n.path)||s.push(`the gate in ${ne(e)} does not list ${n.path}; run setup again there`),s)}function op(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=>VR.native(E)),a=be(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(He(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 \`${W("cursor","login")}\`.`);let d=ee(r,o);if(d.kind==="unreadable")return e.io.log(`Capture: BROKEN \u2014 ${j(r).projects} cannot be read. Fix or delete it, then run \`${W("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 ${j(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(tp),l=p.filter(E=>QR(E.path,u)).sort((E,C)=>C.path.length-E.path.length)[0];if(l===void 0){if(e.io.log(`Capture: NOT INSTALLED for ${u}. Run \`${W("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"),fu(r,o)===void 0&&E.push(`${j(r).queueKey} is missing or damaged; the capture hook records nothing without it`),E.push(...Mt(r,o,go)),E.push(...zR(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 C of E)e.io.log(` ${C}`);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: ${JR(r,o,l.record.projectKey)}`)}{let E=Jn(r,o),C=ao({record:E,projectEnforced:l?.record.enforce,problems:Mt(r,o,[En]),entriesInstalled:l===void 0?void 0:YR(r,l,n)});e.io.log(C.headline);for(let b of C.details)e.io.log(` ${b}`)}let f=(()=>{try{return(n.versionSeen??Ec)(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 ${WR}, 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 C of tp(E))e.io.log(` ${C.path}: ${C.install==="project"?"entries in its own .cursor/hooks.json":`gated entries in ${ne(r)}`}`)}}let g=ne(r),h;try{h=s.readText(g)}catch{h=void 0}let S=zn(h,Yn);if(S.length>0){let E=[...new Set(S.flatMap(y=>Rn(y.entry.command)?.folders??[]))].sort(),C=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(C)])&&e.io.log(` does not match the registry (${C.join(", ")||"no folder"}); run \`${W("cursor","setup")}\` again`);let b=mo($l(r,o)?.nodePath??n.nodePath??process.execPath,j(r).runtime);S.every(y=>Rn(y.entry.command)?.helper===b)||e.io.log(" one gated entry runs another Node or another copy; run setup again")}let I=(n.senderSummary??((E,C)=>bc(E,C,o)))(r,l?.record.projectKey);I?.lastUploadAt!==void 0&&e.io.log(`Last upload: ${I.lastUploadAt}`),I?.lastError!==void 0&&e.io.log(`Last error: ${I.lastError}`);for(let[E,C]of Object.entries(I?.dropped??{}))e.io.log(`Dropped (${E}): ${C}`);return 0}import{readFileSync as gp,realpathSync as pE}from"fs";import{resolve as fE}from"path";import{spawnSync as qR}from"child_process";import{existsSync as sp,readFileSync as XR}from"fs";import{dirname as ip,join as ea}from"path";import{fileURLToPath as ZR}from"url";var Ro="agenttrail",eE="agenttrail",fe=`${eE}@${Ro}`,ap="2.1.211",Eo=e=>{let n=qR("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??""}},So=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"}},na=class extends Error{constructor(t,r=ap){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},$t=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 dp(e){let n=e.match(/(\d+)\.(\d+)\.(\d+)/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function ta(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 nE=dp(ap);function cp(e){let n=e(["--version"]);if(n.spawnError==="ENOENT")throw new So;if(n.spawnError)throw new So;let t=dp(n.stdout);if(t&&!ta(t,nE))throw new na(n.stdout.trim()||null)}function tE(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===Ro);return s===void 0||s.path!==n?!1:s.source==="directory"?t(s.path):!0}catch{return!1}}function ho(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===fe);return r==null?void 0:{version:typeof r.version=="string"?r.version:void 0}}catch{return}}function Zi(e){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(e??"");return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function rE(e){try{let n=XR(ea(e,".claude-plugin","plugin.json"),"utf8"),t=JSON.parse(n)?.version;return typeof t=="string"&&t.length>0?t:void 0}catch{return}}function oE(e){return ho(e)!==void 0}function sE(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(`@${Ro}`)}):!0}function iE(){let e=import.meta.url;return e?ip(ZR(e)):typeof __dirname<"u"?__dirname:process.cwd()}function aE(e){let n=e??iE();for(;;){let t=ea(n,"plugin");if(sp(ea(t,".claude-plugin","marketplace.json")))return t;let r=ip(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 bo=`claude plugin update ${fe} --scope user`;function up(e={}){let n=e.scope??"user",t=e.runner??Eo,r=e.marketplaceSource??aE(),o=e.pathExists??sp;cp(t);let s={status:"already-installed",pluginId:fe,scope:n},i=e.packagedVersion??rE(r),a=ho(t),d=Zi(a?.version),c=Zi(i);if(a!==void 0&&d&&c&&!ta(c,d))return{...s,note:`A newer AgentTrail plugin (${a.version}) is installed than this CLI ships (${i}); it was left as is.`};if(!tE(t,r,o)){let l=t(["plugin","marketplace","add",r,"--scope",n]);if(l.code!==0)throw new $t("marketplace add",l.code,l.stderr)}let u=ho(t);if(u!==void 0){if(e.refresh!==!0)return s;let l=u.version,f=Zi(l);if(f===null||c===null){let h=f===null?"installed":"packaged",S=f===null?l:i;return{...s,warning:`Could not read the ${h} AgentTrail plugin version${S===void 0?"":` as x.y.z (got "${S}")`}, so the plugin was not updated. If Claude Code is running an older AgentTrail plugin, run \`${bo}\`, then restart Claude Code.`}}if(ta(f,c))return s;let m=t(["plugin","update",fe,"--scope",n]),g=ho(t);return g?.version===i?{status:"refreshed",pluginId:fe,scope:n,foundVersion:l,expectedVersion:i}:{status:"refresh-failed",pluginId:fe,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",fe,"--scope",n]);if(p.code!==0)throw new $t("install",p.code,p.stderr);return{status:"installed",pluginId:fe,scope:n}}function lp(e={}){let n=e.scope??"user",t=e.runner??Eo;if(cp(t),!oE(t))return{status:"not-installed",pluginId:fe,scope:n};let r=t(["plugin","uninstall",fe,"--scope",n]);if(r.code!==0)throw new $t("uninstall",r.code,r.stderr);return sE(t)||t(["plugin","marketplace","remove",Ro,"--scope",n]),{status:"removed",pluginId:fe,scope:n}}import{mkdirSync as dE}from"fs";import{dirname as cE}from"path";var uE=448,lE=384;function pp(e,n,t={}){let r=t.writeFile??((s,i,a)=>P(s,i,a!==void 0?{mode:a}:{}));(t.mkdir??((s,i)=>dE(s,{recursive:!0,mode:i})))(cE(e),uE),r(e,`${JSON.stringify(n,null,2)}
|
|
54
|
-
`,lE)}var Co=[is,as,ds,cs,yt,X,q];function mp(e,n={}){return et(w(e),Co,n)}function fp(e){try{return pE(e)}catch{return fE(e)}}function Io(e,n){return fp(e)===fp(n)}function gE(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 ra(e,n){let t=e.timeoutMs??jn,r=n.settingsIO??{},o=Io(e.settingsRoot,e.home);if(!o){let f=ke(e.settingsRoot,Ue,{...n.git?{git:n.git}:{}});if(!f.ok)return{enforced:!1,reason:"local-settings-tracked",message:gE(f.reason,f.tracked),snapshotCached:!1}}let s=sd({apiBase:e.apiBase,timeoutMs:t,orgId:e.orgId});o?Re(e.settingsRoot,s,r):$e(e.settingsRoot,s,r);let i=id({token:e.token}),a={git:n.git??L,env:n.env??process.env};o&&e.migrate===!0?On(e.settingsRoot,i,r,{dotfiles:a}):o&&Bt(e.settingsRoot,r)[X]!==void 0?On(e.settingsRoot,i,r,{dotfiles:a}):$e(e.settingsRoot,i,r);let d;try{d=await Nt({url:Fn(e.apiBase),token:e.token,timeoutMs:t},n.fetchFn)}catch(f){if(f instanceof Oe)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};pp(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}):up({...n.runner?{runner:n.runner}:{},refresh:f});c=m.status,u=mE(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?Re(e.settingsRoot,us,r):$e(e.settingsRoot,us,r);let l=o||e.migrate!==!0?!1:et(w(e.settingsRoot),Co,r);return{enforced:!0,reason:"enforced",message:`real-time enforcement ENABLED (${u}).`,pluginStatus:c,...p,snapshotCached:!0,migrated:l}}function mE(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 \`${bo}\`, 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 \`${bo}\`, then restart Claude Code`;case"already-installed":return"plugin already-installed";default:return`plugin ${e.status}`}}async function yp(e,n){let t=n.settingsIO??{},r=e.timeoutMs??jn;if(!e.token)return{enforced:!1,reason:"no-credential",changed:!1};if(!Io(e.settingsRoot,e.home)&&!ke(e.settingsRoot,Ue,{...n.git?{git:n.git}:{}}).ok)return{enforced:!1,reason:"local-settings-tracked",changed:!1};let o;try{o=await Nt({url:Fn(e.apiBase),token:e.token,timeoutMs:r},n.fetchFn)}catch(c){if(c instanceof Oe)return{enforced:!1,reason:"unreachable",changed:!1};throw c}if(o.kind==="unauthorized"||o.kind==="tier-disabled"){let c=Io(e.settingsRoot,e.home),u=Bt(e.settingsRoot,t,!c)[q]!==void 0;u&&c?et(w(e.settingsRoot),[q],t):u&&et(M(e.settingsRoot),[q],t,384);let p=!c&&Bt(e.settingsRoot,t)[q]!==void 0;return{enforced:!1,reason:o.kind==="unauthorized"?"credential-rejected":"tier-disabled",changed:u&&!p}}let s=Io(e.settingsRoot,e.home),i=Bt(e.settingsRoot,t,!s),a=s&&i[X]!==void 0?i:Bt(e.settingsRoot,t,!0);if(i[q]!==void 0&&a[X]===e.token)return{enforced:!0,reason:"already-enforced",changed:!1};let d=await ra(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 Bt(e,n,t=!1){let r=t?M(e):w(e),o=n.readFile??(s=>gp(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 hp(e,n={}){let t=!1;try{t=lp(e.runner?{runner:e.runner}:{}).status==="removed"}catch{}return et(M(e.settingsRoot),Co,n,384),et(w(e.settingsRoot),Co,n),{pluginRemoved:t}}function et(e,n,t,r){let o=t.readFile??(u=>gp(u,"utf8")),s=t.writeFile??((u,p,l)=>P(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)}
|
|
55
|
-
`,r),!0}import{spawn as vE}from"child_process";import{appendFileSync as PE,chmodSync as NE,mkdirSync as DE,readFileSync as jE,renameSync as FE,statSync as LE}from"fs";import{hostname as ME}from"os";import{dirname as Tp,isAbsolute as Cp,join as UE}from"path";import{mkdirSync as yE,readdirSync as hE,readFileSync as SE,statSync as RE,unlinkSync as EE}from"fs";import{join as oa}from"path";var bE=/^[A-Za-z0-9._-]{1,128}$/;function sa(e){return typeof e=="string"&&bE.test(e)&&e!=="."&&e!==".."}function ia(e){return oa(e,".agenttrail","session-upload")}function Sp(e,n){if(!sa(n))throw new Error("unsafe session id");return oa(ia(e),`${n}.json`)}function Rp(e,n,t={}){let r=t.readFile??(s=>SE(s,"utf8")),o={version:1,traces:{},updatedAt:""};try{let s=JSON.parse(r(Sp(e,n)));return s?.version!==1||typeof s.traces!="object"||s.traces===null?o:{version:1,traces:s.traces,updatedAt:s.updatedAt??""}}catch{return o}}function Ep(e,n,t,r={}){let o=r.writeFile??((i,a,d)=>P(i,a,d!==void 0?{mode:d}:{}));(r.mkdir??((i,a)=>yE(i,{recursive:!0,mode:a})))(ia(e),448),o(Sp(e,n),`${JSON.stringify(t)}
|
|
56
|
-
`,384)}var IE=720*60*60*1e3;function bp(e,n=Date.now()){let t=0;try{let r=ia(e);for(let o of hE(r).slice(0,2e3)){if(!o.endsWith(".json"))continue;let s=oa(r,o);try{n-RE(s).mtimeMs>IE&&(EE(s),t++)}catch{}}}catch{}return t}import{createHash as CE}from"crypto";import{statSync as kE}from"fs";var TE=64*1024*1024,_E=3*1024*1024,OE=2,nt={traces:0,sent:0,spans:0,failedRequests:0,redactions:0};function xE(e,n){if(e===n)return!0;let t=n.endsWith("/")||n.endsWith("\\")?n:`${n}/`;return e.startsWith(t)||e.startsWith(t.replace(/\/$/,"\\"))}function AE(e){let n=new Map;for(let r of e.spans){let o=n.get(r.traceId);o?o.push(r):n.set(r.traceId,[r])}let t=[];for(let[r,o]of n){let s=JSON.stringify({resource:e.resource,scope:e.scope,spans:o});t.push({traceId:r,spans:o,hash:CE("sha256").update(s).digest("hex"),bytes:Buffer.byteLength(s)})}return t}function wE(e,n){let t=[],r=[],o=0;for(let s of e)r.length>0&&o+s.bytes>n&&(t.push(r),r=[],o=0),r.push(s),o+=s.bytes;return r.length>0&&t.push(r),t}async function Ip(e,n={}){try{if((n.statSize??(g=>kE(g).size))(e.transcriptPath)>TE)return{status:"skipped",reason:"transcript too large",...nt}}catch{return{status:"skipped",reason:"transcript not found",...nt}}let t;try{t=await Zr(e.transcriptPath,e.sessionId,n.lineSource)}catch(m){return{status:"skipped",reason:m instanceof mn?"transcript has no messages yet":"unreadable transcript",...nt}}if(!t.cwd||!xE(t.cwd,e.projectRoot))return{status:"skipped",reason:"session recorded outside this project",...nt};let r=e.skipIfVersion?.(t.version);if(r)return{status:"skipped",reason:r,...nt};let o=ro(t,{orgId:e.orgId,projectId:e.projectId,developerId:e.developerId,batchId:"",captureContent:e.captureContent,scopeVersion:e.scopeVersion,resolved:Pe(me),provenance:"live"}),s=AE(o),i=Rp(e.homeDir,e.sessionId,n.stateIO),a=s.filter(m=>i.traces[m.traceId]!==m.hash),d=o.redactions.total;if(a.length===0)return{status:"unchanged",...nt,traces:s.length,redactions:d};let c={...i.traces},u=0,p=0,l=0,f;for(let m of wE(a,e.maxRequestBytes??_E)){let g=Te({...o,spans:m.flatMap(S=>S.spans)}),h=await Je(g,{endpoint:e.endpoint,token:e.token,maxRetries:OE},n.upload);if(f=h.httpStatus??f,h.status==="ok"){for(let S of m)c[S.traceId]=S.hash;u+=m.length,p+=m.reduce((S,I)=>S+I.spans.length,0)}else l++}if(u>0)try{Ep(e.homeDir,e.sessionId,{version:1,traces:c,updatedAt:(n.now?.()??new Date).toISOString()},n.stateIO)}catch{}return{status:l>0?"failed":"uploaded",...l>0?{reason:"ingest rejected or unreachable"}:{},traces:s.length,sent:u,spans:p,failedRequests:l,httpStatus:f,redactions:d}}var _p="AGENTTRAIL_SESSION_UPLOAD_WORKER",Op="AGENTTRAIL_SESSION_UPLOAD_PAYLOAD",$E=12e4,BE=2e3,GE=512*1024;function xp(e){return UE(e,".agenttrail","session-upload.log")}function KE(e,n){try{let t=xp(e);DE(Tp(t),{recursive:!0,mode:448});try{LE(t).size>GE&&FE(t,`${t}.1`)}catch{}PE(t,`${JSON.stringify({at:new Date().toISOString(),...n})}
|
|
57
|
-
`,{mode:384}),NE(t,384)}catch{}}function kp(e){let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null)return;let t=n;if(!(t.hook_event_name!=="Stop"&&t.hook_event_name!=="SessionEnd")&&sa(t.session_id)&&!(typeof t.transcript_path!="string"||!Cp(t.transcript_path))&&t.transcript_path.endsWith(".jsonl")&&!(typeof t.cwd!="string"||!Cp(t.cwd)))return{session_id:t.session_id,transcript_path:t.transcript_path,cwd:t.cwd,hook_event_name:t.hook_event_name}}function HE(e){let n=process.argv[1];if(!n)return;let t=vE(process.execPath,[n,...process.argv.slice(2)],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,[_p]:"1",[Op]:e}});t.on("error",()=>{}),t.unref()}async function Ap(e){let n=e.log??(t=>KE(e.homeDir,t));try{if(e.env[_p]==="1"){let o=kp(e.env[Op]??"");if(!o)return n({outcome:"skipped",reason:"no payload"}),0;e.armDeadline?.($E);let s=await VE(o,e);return n({event:o.hook_event_name,session:o.session_id,outcome:s.status,...s.reason?{reason:s.reason}:{},traces:s.traces,sent:s.sent,spans:s.spans,...s.httpStatus!==void 0?{httpStatus:s.httpStatus}:{},...s.project?{project:s.project}:{}}),0}let t=e.readStdin?await e.readStdin():"",r=kp(t);return r?((e.spawnWorker??HE)(JSON.stringify(r)),0):(n({outcome:"skipped",reason:"not a Stop or SessionEnd hook payload"}),0)}catch(t){return n({outcome:"failed",reason:`unexpected: ${t?.name??"error"}`}),0}}function qe(e){return{status:"skipped",reason:e,traces:0,sent:0,spans:0,failedRequests:0,redactions:0}}async function VE(e,n){try{let t;try{t=mt(e.cwd,{allowGlobal:!1})}catch{return qe("unreadable .agenttrail.json")}if(t.source!=="project"||!t.config||!t.configPath)return qe("no AgentTrail project here");let r=t.config,o=Tp(t.configPath),s;try{s=dt(n.endpointFlag?.trim()||n.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||J)}catch{return qe("invalid ingest endpoint")}let i=yr(t,n.env),a,d;if(i)a=i,d=r.orgId;else{await WE(n,o,s);let l=$(n.homeDir,n.loginEnv?.credentialsIO);if(!l)return qe("not signed in");if(He(l,n.loginEnv?.now))return qe("sign-in expired");if(l.org_id!==r.orgId)return qe("signed in to a different org");a=l.ingest_token,d=l.org_id}let c={env:n.env,...n.managedPaths?{managedPaths:n.managedPaths}:{}};if(Ss(n.homeDir,d,c))return qe("the user settings export this session to AgentTrail");let u=Ed(o);return e.hook_event_name==="Stop"?await(n.sleep??(l=>new Promise(f=>setTimeout(f,l))))(BE):bp(n.homeDir),{...await Ip({homeDir:n.homeDir,sessionId:e.session_id,transcriptPath:e.transcript_path,projectRoot:o,endpoint:s,token:a,orgId:d,projectId:r.projectId??z(d,r.projectSlug),developerId:r.developerId,captureContent:Ar(o,n.homeDir,r.captureContent,c),skipIfVersion:l=>u&&l!==null&&Rd(l,ud)<0?"this Claude Code version exports the session from the project settings":void 0},{upload:n.upload,stateIO:n.stateIO}),project:o}}catch(t){return qe(`unexpected: ${t?.name??"error"}`)}}async function WE(e,n,t){try{let r={apiEndpoint:we(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||rn),ingestEndpoint:t,homeDir:e.homeDir,settingsRoot:n,host:ME(),log:()=>{},...e.loginEnv};await Pr(r)}catch{}}function wp(e,n){let t={},r=xp(e);for(let o of[`${r}.1`,r]){let s;try{s=jE(o,"utf8")}catch{continue}for(let i of s.split(`
|
|
58
|
-
`)){if(i.trim()==="")continue;let a;try{a=JSON.parse(i)}catch{continue}a.project!==n||typeof a.at!="string"||(t.lastRun={at:a.at,outcome:a.outcome,...a.reason?{reason:a.reason}:{}},(a.sent??0)>0&&(t.lastSent={at:a.at,sent:a.sent??0}))}}return t}import{homedir as QE}from"os";function vp(e,n={}){let t,r;if(e.projectSlug)t=e.projectSlug,r="explicit";else{let I=cn(e.cwd);if(!I)throw new Error("Could not derive a project slug (no git remote, no usable directory name). Pass --project <slug>.");t=I.slug,r=I.source}if(!e.global&&!e.team){let I=[B,Ue];for(let E of I){let C=Rr(e.cwd,E,n);if(C)throw new Ke(Ln(E,C))}for(let E of I){let C=ke(e.cwd,E,n);if(!C.ok)throw new Ke(Ln(E,C))}}let o=z(e.orgId,t),s=Ce(e.orgId,ie),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??QE(),c=e.global?d:e.cwd,u=e.global?(()=>{let I=Ir(a,n);return{path:I.path,gitignoreModified:!1,mode:I.mode}})():br(e.cwd,a,n,{committable:e.team===!0}),p=e.endpoint??J,l=e.global?void 0:Dn(e.cwd),f={orgId:e.orgId,projectId:o,agentId:s,developerId:e.developerId,apiKey:i,team:e.team,captureContent:e.captureContent,endpoint:e.endpoint,project:l},m=!e.global&&!e.team,g=null,h,S=null;if(m){h=Re(c,_r(f),n);let I=Or(c,n,{captureContent:e.captureContent});S={hooksChanged:ht(c,{endpoint:e.endpoint},n).changed,removedKeys:I}}else{h=Re(c,Xt(f),n);let I=Sa(f);Object.keys(I).length>0&&(g=$e(c,I,n))}return e.team&&mp(c,n),!e.global&&!e.team&&Er(e.cwd,n),{projectSlug:t,projectId:o,slugSource:r,agentId:s,agenttrailConfigPath:u.path,gitignoreModified:u.gitignoreModified,agenttrailConfigMode:u.mode,settings:h,localSettings:g,team:e.team??!1,global:e.global??!1,captureContent:e.captureContent??!1,resolvedEndpoint:p,sessionUpload:S}}import{readFileSync as lb}from"fs";import{randomUUID as oP}from"crypto";import{mkdirSync as JE,readdirSync as YE,readFileSync as zE,rmSync as qE,writeFileSync as XE}from"fs";import{dirname as ZE,join as ko}from"path";import{createHash as eP}from"crypto";var Pp=100,eb=2e3,nb=3e3;var tb={mkdir:(e,n)=>JE(e,{recursive:!0,mode:n}),writeFile:(e,n,t)=>XE(e,n,{mode:t}),readDir:e=>YE(e),readFile:e=>zE(e,"utf8"),remove:e=>qE(e,{force:!0})};function rb(e){return{...tb,...e??{}}}function ob(e){return ko(ZE(e),"pending-decisions")}function sb(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/policies/decisions`}async function Np(e,n,t={}){let r=0;try{let o=rb(t.io),s=ob(e.snapshotPath),i;try{i=o.readDir(s).filter(d=>d.endsWith(".json")).sort()}catch{return 0}let a=Date.now()+nb;for(let d=0;d<i.length;d+=Pp){if(Date.now()>=a)return r;let c=[];for(let g of i.slice(d,d+Pp))try{c.push({file:g,item:JSON.parse(o.readFile(ko(s,g)))})}catch{o.remove(ko(s,g))}if(c.length===0)continue;let u=new AbortController,p=setTimeout(()=>u.abort(),Math.min(eb,Math.max(0,a-Date.now()))),l;try{l=await n(sb(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(ko(s,g.file)),r++)}return r}catch{return r}}import{randomUUID as Dp}from"crypto";import{readFileSync as ib}from"fs";import{join as jp}from"path";var Fp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ab(e){return jp(e,".agenttrail","machine-id")}function db(e){return jp(e,".agenttrail","installs.json")}function Lp(e,n){try{return(e.readFile??(t=>ib(t,"utf8")))(n)}catch{return}}function Mp(e,n,t){(e.writeFile??((o,s,i)=>P(o,s,i!==void 0?{mode:i}:{})))(n,t,384)}function Up(e,n={}){let t=ab(e),r=Lp(n,t)?.trim();if(r&&Fp.test(r))return r;let o=Dp();return Mp(n,t,`${o}
|
|
59
|
-
`),o}function $p(e,n,t={}){let r=db(e),o={},s=Lp(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"&&Fp.test(i))return i;let a=Dp();return o[n]=a,Mp(t,r,`${JSON.stringify(o,null,2)}
|
|
60
|
-
`),a}function cb(e){let n=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(n)?n:`${n}/api/v1`}/machines/enforcement`}function ub(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 Bp(e,n){let t=new AbortController,r=setTimeout(()=>t.abort(),2e3);try{return(await n(cb(e.apiBase),{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(ub(e)),signal:t.signal})).ok}catch{return!1}finally{clearTimeout(r)}}function Gp(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 pb(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 fb(e,n){let t=$(e.homeDir,e.credentialsIO);if(t?.ingest_token)return t.ingest_token;try{let o=V(M(e.settingsRoot),n.readFile??(s=>lb(s,"utf8")))?.env;if(typeof o=="object"&&o!==null){let s=o[X];if(typeof s=="string"&&s.length>0)return s}}catch{}}async function Kp(e,n){try{let t=fb(e,n);if(!t)return{reported:!1};let r={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},o=await yp({settingsRoot:e.settingsRoot,apiBase:e.apiEndpoint,token:t,deviceTokenPath:t.startsWith("dlv_ingest_"),home:e.homeDir},{fetchFn:n.fetchFn,settingsIO:r}),s=pb(o);s&&e.log?.(s);let i={...n.readFile?{readFile:n.readFile}:{},...n.writeFile?{writeFile:n.writeFile}:{}},a=await Bp({apiBase:e.apiEndpoint,token:t,machineId:Up(e.homeDir,i),installId:$p(e.homeDir,e.settingsRoot,i),enforced:o.enforced,...Gp(o)?{reason:Gp(o)}:{}},n.fetchFn),d=await Np({apiBase:e.apiEndpoint,token:t,snapshotPath:n.snapshotPath||process.env[td]?.trim()||Sr(e.homeDir)},n.fetchFn,n.pendingDecisionsIO?{io:n.pendingDecisionsIO}:{});return{healed:o,reported:a,flushed:d}}catch{return{reported:!1}}}function Hp(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 Yp="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.",Gt=`agenttrail \u2014 connect an AI coding agent to AgentTrail
|
|
61
|
-
|
|
62
|
-
Usage:
|
|
63
|
-
agenttrail setup --agent <claude|cursor|codex> [options]
|
|
64
|
-
agenttrail login --agent <claude|cursor|codex> [--refresh] [options]
|
|
65
|
-
agenttrail logout --agent <claude|cursor|codex> [options]
|
|
66
|
-
agenttrail status --agent <claude|cursor|codex>
|
|
67
|
-
agenttrail backfill --agent <claude|cursor|codex> --scan | --import | --status | --resume [options]
|
|
68
|
-
|
|
69
|
-
Every command needs --agent: claude for Claude Code, cursor for Cursor, codex
|
|
70
|
-
for Codex (not yet available).
|
|
71
|
-
|
|
72
|
-
One command to install: run \`setup\` with no API key. It opens the browser to
|
|
73
|
-
authorize this device (OAuth device-auth), then writes the config, and \`status\`
|
|
74
|
-
reports capture ACTIVE.
|
|
75
|
-
|
|
76
|
-
claude \`status\` also reports your real-time enforcement state. For CI /
|
|
77
|
-
headless, pass --key or --team instead of the browser.
|
|
78
|
-
cursor \`status\` also reports your real-time enforcement state. Enforcement
|
|
79
|
-
needs Cursor ${Pt} or later; an older Cursor is captured only.
|
|
80
|
-
Setup always uses the browser, per project, and --key, --team and
|
|
81
|
-
--global are refused.
|
|
82
|
-
codex Not yet available: every command refuses --agent codex and changes
|
|
83
|
-
nothing.
|
|
84
|
-
|
|
85
|
-
Options:
|
|
86
|
-
--agent <claude|cursor|codex>
|
|
87
|
-
Required on every command: the agent to connect.
|
|
88
|
-
--org <uuid> Org UUID the API key belongs to.
|
|
89
|
-
--project <slug> Project slug (default: derived from git remote / dir name).
|
|
90
|
-
--developer <uuid> Per-machine developer id (optional).
|
|
91
|
-
--key <dlv_...> (claude only) API key for the CI/headless path (default:
|
|
92
|
-
$AGENTTRAIL_API_KEY). When omitted (and not --team), \`setup\`
|
|
93
|
-
uses browser device-auth. Refused for --agent cursor.
|
|
94
|
-
--endpoint <url> OTLP ingest base URL (default: $AGENTTRAIL_INGEST_ENDPOINT,
|
|
95
|
-
else ${J}). e.g. a self-hosted
|
|
96
|
-
ingest: --endpoint http://localhost:4318.
|
|
97
|
-
--api-endpoint <url> AgentTrail API base URL for device-auth (setup/login/logout).
|
|
98
|
-
Accepts a bare origin (e.g. https://api.agenttrail.sh or
|
|
99
|
-
http://localhost:3000); the CLI derives the /api/v1 base.
|
|
100
|
-
(default: $AGENTTRAIL_API_ENDPOINT, else ${rn}).
|
|
101
|
-
--refresh (login) Refresh the on-disk ingest token ONLY if it is
|
|
102
|
-
within ~1 day of expiry; otherwise a no-op. The
|
|
103
|
-
SessionStart hook runs this every session.
|
|
104
|
-
--team (claude only) Write committable, key-free config (auth header
|
|
105
|
-
from env). Refused for --agent cursor.
|
|
106
|
-
--global (claude only) Configure ~/.claude + ~/.agenttrail/config.json
|
|
107
|
-
(per-user). Refused for --agent cursor: Cursor setup is
|
|
108
|
-
per-project, and \`logout\` clears the machine.
|
|
109
|
-
--no-capture-content
|
|
110
|
-
(claude) Turn OFF prompt/tool-content capture (prompts,
|
|
111
|
-
commands, file paths and tool output): metadata and tokens
|
|
112
|
-
only. A rerun of setup keeps an earlier opt-out.
|
|
113
|
-
--capture-content claude: turn capture back ON after --no-capture-content.
|
|
114
|
-
cursor: turn ON content capture.
|
|
115
|
-
Secret- and PII-shaped values and enumerated secret-manager
|
|
116
|
-
outputs (\`op read\`, \u2026) are scrubbed at ingest before
|
|
117
|
-
storage; scrubbing is shape-based, so a structureless secret
|
|
118
|
-
can still be stored. claude: this client sends content as
|
|
119
|
-
Claude Code emits it and never scrubs it here. cursor: content
|
|
120
|
-
is edge-scrubbed on this machine before it is queued, and the
|
|
121
|
-
server scrubs it again.
|
|
122
|
-
Default for Claude Code: content capture ON. Default for
|
|
123
|
-
Cursor: metadata + tokens only.
|
|
124
|
-
--unregister (setup --agent cursor) Remove this project's Cursor capture
|
|
125
|
-
entries and its registry row, leaving other projects set up.
|
|
126
|
-
-h, --help Show this help.
|
|
127
|
-
|
|
128
|
-
Backfill with --agent claude (import past Claude Code sessions from ~/.claude/projects):
|
|
129
|
-
--import / --scan cover ONLY the project you run them in \u2014 matched on each
|
|
130
|
-
session's recorded working directory, mirroring per-project \`setup\`. There is
|
|
131
|
-
no flag to widen this; cd into another project and re-run to import it.
|
|
132
|
-
(--status is machine-wide \u2014 see below.)
|
|
133
|
-
--scan List THIS project's transcripts (JSON inventory). Uploads nothing.
|
|
134
|
-
--import Parse + upload THIS project's sessions to AgentTrail. Sessions
|
|
135
|
-
AgentTrail already holds (captured live OR imported before,
|
|
136
|
-
unchanged) are skipped so nothing is duplicated; for those
|
|
137
|
-
already-recorded sessions --import and --resume now behave
|
|
138
|
-
alike. Use --reimport to force.
|
|
139
|
-
--status Show the import checkpoint (~/.agenttrail/backfill-state.json).
|
|
140
|
-
Machine-wide (records every import on this machine).
|
|
141
|
-
--resume Continue a prior import (skip done, retry failed).
|
|
142
|
-
--reimport Import even sessions AgentTrail already holds (skip the dedup
|
|
143
|
-
check). Use after the per-turn migration, or to re-send a
|
|
144
|
-
session captured live.
|
|
145
|
-
--since <dur> Only sessions newer than e.g. 7d / 24h / 30m. Claude only:
|
|
146
|
-
a Cursor session file carries no time of its own, so
|
|
147
|
-
\`backfill --agent cursor\` refuses the flag rather than
|
|
148
|
-
ignoring it.
|
|
149
|
-
--dry-run Map + validate, but do not upload. (The read-only "already
|
|
150
|
-
recorded?" check still runs so the preview's skip count is
|
|
151
|
-
real.) With --content this is the honest pre-flight: shows
|
|
152
|
-
what would be edge-redacted before anything leaves the machine.
|
|
153
|
-
--content Include prompt/tool content. Shape-matching secrets and
|
|
154
|
-
enumerated secret-manager outputs (\`op read\`, \u2026) are
|
|
155
|
-
EDGE-scrubbed on this machine before upload; a shapeless
|
|
156
|
-
secret fetched by any other command (a wrapper script,
|
|
157
|
-
\`kubectl get secret\`) \u2014 or by an enumerated command nested in
|
|
158
|
-
a command substitution, e.g. \`export FOO=$(op read \u2026)\` \u2014 is
|
|
159
|
-
not. The server then applies your org's full config.
|
|
160
|
-
Default: metadata + tokens only.
|
|
161
|
-
--concurrency <n> Max parallel uploads (default 6).
|
|
162
|
-
|
|
163
|
-
Backfill with --agent cursor (import this project's Cursor sessions):
|
|
164
|
-
Same verbs and flags as above \u2014 --scan, --import, --resume, --status, --content,
|
|
165
|
-
--dry-run, --reimport, --concurrency \u2014 with three differences: --since is not
|
|
166
|
-
supported (above); an import carries no prompt text, no model, no tokens and no
|
|
167
|
-
cost, because a Cursor session file holds none; and its times are approximate and
|
|
168
|
-
marked as such. Conversations already captured live are skipped. Set the project
|
|
169
|
-
up first, in the project: \`npx -y @agenttrail/cli@latest setup --agent cursor\`.
|
|
170
|
-
Full detail: docs/integrations/cursor.md`;function Eb(e){return Rb({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 bb(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 Vp(e,n){if(e.prompt)return(await e.prompt(n)).trim();if(!process.stdin.isTTY)return;let t=Sb({input:process.stdin,output:process.stdout});try{return(await t.question(n)).trim()}finally{t.close()}}function Ib(e){return typeof e.isInteractive=="boolean"?e.isInteractive:!!process.stdin.isTTY}async function Cb(e,n){let t=!!n.team,r=n.key?.trim()||e.env.AGENTTRAIL_API_KEY?.trim();if(!t&&!r)return kb(e,n);let o=!!n.global,s=e.persistIO?.home??K(),i=Zp(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 Vp(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 Vp(e,"AgentTrail API key (dlv_live_...): ")),!c)return e.error("error: an API key is required in single-dev mode. Pass --key, set AGENTTRAIL_API_KEY, or use --team."),1;let u=!o&&!t?ef(e,e.cwd):void 0;if(nf(e,i,u),o&&e.error("WARNING: --global configures EVERY Claude Code session on this machine \u2014 including personal and side projects \u2014 to export to AgentTrail. This is a privacy / cost / GDPR consideration. Prefer per-project setup unless you intend machine-wide capture."),!o){let g=Jp(dn(e.cwd));g&&he(g).length>tn&&e.error(`WARNING: project "${g}" exceeds the ${tn}-char telemetry resource-attribute limit once URL-encoded; omitting agenttrail.project. Traces will carry no project label.`)}let p=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim(),l;if(p)try{l=dt(p)}catch(g){return e.error(`error: ${g.message}`),1}let f;try{f=vp({cwd:e.cwd,orgId:d,apiKey:c,projectSlug:n.project?.trim()||void 0,developerId:n.developer?.trim()||void 0,team:t,global:o,captureContent:a,endpoint:l},e.persistIO??{})}catch(g){if(!(g instanceof Ke))throw g;return e.error(`error: setup refused: ${g.message}${Xp(e.cwd)}`),1}let m=o?e.persistIO?.home??K():e.cwd;if(nr(m,e.persistIO??{}),e.fetchFn&&c){let g=n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||rn;await qp(e,{settingsRoot:m,apiBase:g,token:c,deviceTokenPath:!1,home:e.persistIO?.home??K(),orgId:d})}return f.slugSource==="directory"&&e.error(Yp),e.log(`Project: ${f.projectSlug} \u2192 project.id ${f.projectId}`),e.log(`Endpoint: ${f.resolvedEndpoint}`),e.log(`Wrote ${f.agenttrailConfigPath} (mode 0${f.agenttrailConfigMode.toString(8)})`+(f.gitignoreModified?" (+ .gitignore)":"")),e.log(`Wrote ${f.settings.path} (${f.settings.merged?"merged":"created"})`),f.localSettings&&e.log(`Wrote ${f.localSettings.path} (${f.localSettings.merged?"merged":"created"}, mode 0600, ${o?"":"kept out of git \u2014 "}holds the API key; do NOT commit)`),f.sessionUpload&&zp(e,f.sessionUpload.removedKeys),t&&e.log('Team mode: config is key-free and safe to commit. Each developer must export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer $AGENTTRAIL_API_KEY".'),e.log(da(a&&u===void 0,u)),0}async function kb(e,n){let t;try{t=Wt(e,n)}catch(S){return e.error(`error: ${S.message}`),1}let r=!!n.global,o=t.settingsRoot,s=r?e.persistIO?.home??K():o,i=Zp(n,s,e.persistIO?.home??K(),e.persistIO?.readFile),a=i.on,d=r?void 0:ef(e,o);nf(e,i,d);let c=n.project?.trim(),u,p;if(c)u=c,p="explicit";else{let S=cn(o);u=S?.slug??"default",p=S?.source??"directory"}if(t={...t,projectSlug:u,captureContent:a,global:r,settingsRoot:s,setup:!0},!r){let S=ke(o,Ue,e.persistIO??{});if(!S.ok)return e.error(`error: setup refused: ${Ln(Ue,S)}${Xp(o)}`),1}let l=$(t.homeDir,t.credentialsIO);try{if(l&&!He(l,t.now))wd(t,l),e.log(`Using existing AgentTrail credentials (org ${l.org_id}).`);else{if(!Ib(e))return e.error("error: device login needs a browser to authorize. Run `npx -y @agenttrail/cli@latest setup --agent claude` in an interactive terminal, or pass --key / use --team for headless/CI."),1;l=await Os(t)}}catch(S){return e.error(`error: ${S.message}`),1}let f={orgId:l.org_id,projectSlug:u,projectId:z(l.org_id,u),agentId:Ce(l.org_id,ie),captureContent:a},m=r?void 0:ke(t.settingsRoot,B,e.persistIO??{}),g=m!==void 0&&!m.ok&&m.tracked,h=r?Ir(f,e.persistIO??{}):g?void 0:br(t.settingsRoot,f,e.persistIO??{});return r||Er(o,e.persistIO??{}),p==="directory"&&e.error(Yp),e.log(`Project: ${u} \u2192 project.id ${f.projectId}`),e.log(`API endpoint (device-auth): ${t.apiEndpoint}`),e.log(`Endpoint: ${t.ingestEndpoint}`),e.log(h?`Wrote ${h.path} (mode 0${h.mode.toString(8)}, device login \u2014 no API key stored)`:`Left ${B} as it is: this repo tracks it.`),e.log(da(a&&d===void 0,d)),r||zp(e,[]),e.fetchFn&&await qp(e,{settingsRoot:t.settingsRoot,apiBase:t.apiEndpoint,token:l.ingest_token,deviceTokenPath:!0,home:e.persistIO?.home??K(),orgId:l.org_id}),e.log("Device login active \u2014 telemetry capture is ON. `status` reports capture ACTIVE + the enforcement state."),0}function zp(e,n){e.log("Session data: uploaded after each turn by the Stop and SessionEnd hooks in .claude/settings.json (Claude Code ignores OpenTelemetry exporter settings in project files)."),n.length>0&&e.log(`Removed the OpenTelemetry exporter settings an earlier setup wrote to this project, which Claude Code ignores there: ${n.join(", ")}.`)}async function qp(e,n){if(e.fetchFn)try{let t=await ra({...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 Tb(e,n){let t=n.source==="global"?K():n.configPath?Vt(n.configPath):n.gitRoot??e.cwd;try{let o=V(w(t),d=>To(d,"utf8")),s=gd(o);if(s!==void 0)return{endpoint:md(s)??J,onDisk:!0};let a=o?.env?.[Le];if(typeof a=="string"&&a.length>0)return{endpoint:a,onDisk:!0}}catch{}return{endpoint:e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||J,onDisk:!1}}function _b(e){let n;try{n=mt(e.cwd)}catch(a){return e.error(`error: ${a.message}`),1}if(!n.config||n.source===null)return e.log("AgentTrail exporter: INACTIVE (no .agenttrail.json in this project; no global config)."),n.gitRoot&&e.log(`Git root: ${n.gitRoot}`),0;let t=yr(n,e.env),r=Ob(e,n);e.log(r.sends?"AgentTrail exporter: ACTIVE":"AgentTrail exporter: CONFIGURED, but no session data is sent (see Session data below)"),e.log(`Config source: ${n.source} (${n.configPath})`),e.log(`Org: ${n.config.orgId}`),e.log(`Project: ${n.config.projectSlug} \u2192 ${n.config.projectId??"(unresolved)"}`);let o=Tb(e,n);e.log(`Endpoint: ${o.endpoint}${o.onDisk?"":" (no on-disk endpoint found; env-or-default)"}`);try{let a=we(e.env.AGENTTRAIL_API_ENDPOINT?.trim()||rn);e.log(`API endpoint (device-auth): ${a}`)}catch{}e.log(`API key: ${t?"present":"MISSING (set AGENTTRAIL_API_KEY, or use device login)"}`);let s=wb(e,n);e.log(da(s===void 0&&vb(e,n),s));for(let a of r.lines)e.log(a);e.log(`Real-time enforcement: ${xb(e,n)}`);let i=Ts(e.persistIO?.home??K());return i&&e.log(i),0}function Ob(e,n){if(n.source!=="project"||!n.configPath||!n.config)return{sends:!0,lines:[]};let t=Vt(n.configPath),r=e.persistIO?.home??K(),o=Rs(t,r,n.config.orgId,Ht(e)),s=[];if(o.path==="otel")s.push("Session data: OpenTelemetry export (from your user settings, ~/.claude/settings.json).");else if(o.path==="upload"){s.push("Session data: session upload after each turn (Stop and SessionEnd hooks).");let i=wp(r,t);s.push(i.lastSent?`Last session upload: ${i.lastSent.at} (${i.lastSent.sent} turn(s) sent).`:"Last session upload: none yet (the first finishes after your next turn in Claude Code)."),i.lastRun&&i.lastRun.outcome==="failed"&&s.push(`WARNING: the latest upload attempt failed at ${i.lastRun.at}${i.lastRun.reason?` (${i.lastRun.reason})`:""}. Details: ~/.agenttrail/session-upload.log.`)}else s.push(`Session data: NOT SENT \u2014 no session upload hooks in this project. ${Kt}.`);return o.ignoredProjectKeys.length>0&&o.path!=="otel"&&s.push(`WARNING: OpenTelemetry exporter settings sit only in this project's .claude files, where Claude Code ignores them: ${o.ignoredProjectKeys.join(", ")}. ${Kt} to remove them.`),{sends:o.path!=="none",lines:s}}function aa(e){try{let t=JSON.parse(To(e,"utf8"))?.env;return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function xb(e,n){let t=n.source==="global"?K():n.configPath?Vt(n.configPath):n.gitRoot??e.cwd,r=aa(M(t)),o=aa(w(t)),s=typeof r[X]=="string"&&r[X]!=="";return r[q]==="1"?s?"ON":`ON but no token, so every tool call is denied. ${Kt}`:o[q]!=="1"?"OFF":n.source==="global"?"ON":s?`ON (set in .claude/settings.json by an older setup). ${Kt} 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 ${Kt.toLowerCase()}.`}var Kt="Run `npx -y @agenttrail/cli@latest setup --agent claude` in this repo";function Xp(e){return aa(w(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 da(e,n){return!e&&n!==void 0?`Content capture: OFF (metadata and tokens only): ${n} switches it off, and setup cannot override that. Change it there to turn capture on.`:e?"Content capture: ON (prompts, commands, file paths and tool output; secrets and PII are scrubbed at ingest, pattern-based and not exhaustive). Turn it off with `setup --agent claude --no-capture-content`.":"Content capture: OFF (metadata and tokens only). Turn it on with `setup --agent claude --capture-content`."}function Wp(e,n){let t;try{t=JSON.parse(n(e))?.env}catch{return"absent"}let r=Se.filter(o=>t?.[o]!==void 0);return r.length===0?"absent":r.every(o=>t?.[o]==="1")?"on":"off"}function Zp(e,n,t,r=o=>To(o,"utf8")){if(e["no-capture-content"])return{on:!1};if(e["capture-content"])return{on:!0};let o=w(n),s=Wp(o,r);if(s==="off")return{on:!1,keptOptOut:{from:"install",path:o}};if(s==="absent"&&n!==t){if(Ab(n,r)===!0)return{on:!0};let a=w(t);if(Wp(a,r)==="off")return{on:!1,keptOptOut:{from:"user",path:a}}}return{on:!0}}function Ab(e,n){try{let t=JSON.parse(n(hb(e,B)));return typeof t?.captureContent=="boolean"?t.captureContent:void 0}catch{return}}function ef(e,n){return xr(n,e.persistIO?.home??K(),Ht(e))}function Ht(e){return{env:e.env,...e.persistIO?.readFile?{read:e.persistIO.readFile}:{},...e.managedPaths?{managedPaths:e.managedPaths}:{}}}function nf(e,n,t){if(t!==void 0){e.log(`note: content capture stays OFF for this project because ${t} switches it off. Change it there to turn capture on; setup cannot override it.`);return}if(n.on){e.error(tr("claude"));return}let r=n.keptOptOut;r!==void 0&&e.log(r.from==="user"?`note: content capture stays OFF because of the user-level opt-out in ${r.path}. Pass --capture-content to turn it on for this project.`:`note: content capture stays OFF because ${r.path} already turns it off (a content flag is not "1"). Pass --capture-content to turn it on.`)}function Qp(e){let n;try{n=JSON.parse(To(w(e),"utf8"))?.env}catch{return"absent"}return Se.filter(r=>n?.[r]!==void 0).length===0?"absent":Se.every(r=>n?.[r]==="1")?"all-on":"defines-some"}function wb(e,n){if(n.source!=="project"||!n.config||!n.configPath)return;let t=Vt(n.configPath);return xr(t,e.persistIO?.home??K(),Ht(e))}function vb(e,n){let t=n.source==="global"?K():n.configPath?Vt(n.configPath):n.gitRoot??e.cwd;if(n.source==="project"&&n.config){let s=e.persistIO?.home??K();if(Rs(t,s,n.config.orgId,Ht(e)).path==="upload")return Ar(t,s,n.config.captureContent,Ht(e))}let r=Qp(t);if(r==="all-on")return!0;if(r==="defines-some")return!1;let o=e.persistIO?.home??K();return o!==t&&Qp(o)==="all-on"}function Pb(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=gb(n,[e],{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}function Wt(e,n){let t=we(n["api-endpoint"]?.trim()||e.env.AGENTTRAIL_API_ENDPOINT?.trim()||rn),r=n.endpoint?.trim()||e.env.AGENTTRAIL_INGEST_ENDPOINT?.trim()||J;return{...{apiEndpoint:t,ingestEndpoint:r,homeDir:K(),settingsRoot:e.cwd,host:yb(),openBrowser:Pb,log:e.log},...e.loginEnv}}async function Nb(e){if(!e.readStdin)return!1;let n=await e.readStdin();if(n.trim()==="")return!1;try{return ci(JSON.parse(n))}catch{return!1}}async function Db(e,n){if(n.refresh&&await Nb(e))return 0;let t;try{return t=Wt(e,n),n.refresh?await Pr(t):await Os(t),0}catch(r){return e.error(`error: ${r.message}`),1}finally{if(n.refresh&&t){bd(e.env.CLAUDE_PROJECT_DIR?.trim()||t.settingsRoot,t.homeDir,t.settingsIO??e.persistIO??{},{git:t.git??e.persistIO?.git});let r=t.fetchFn;await Kp(t,{fetchFn:r?(s,i)=>r(String(s),i):fetch}).catch(()=>{})}}}async function jb(e,n){try{let t=Wt(e,n);return await Pd(t),e.pluginRunner&&hp({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 Fb(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 Lb(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??K(),o=dn(e.cwd),s=T=>e.log(JSON.stringify(T)),i={...e.backfillDeps,emit:e.backfillDeps?.emit??s};if(n.scan)return await Vu({projectRoot:o},i),0;if(n.status)return Wu({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()||J,c=$(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()-Cn[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=Wt(e,n)}catch(_){return e.error(`error: ${_.message}`),1}let k=await vd(T);k.ingestToken&&(l=k.ingestToken),k.tier?(m=k.tier,f=Date.now()-Cn[k.tier]*24*60*60*1e3):(e.error("note: couldn't determine your plan's retention window (tier lookup failed) \u2014 importing all selected sessions. Your plan's retention still applies automatically server-side."),g=!0)}let h=n.org?.trim()||e.env.AGENTTRAIL_ORG_ID?.trim()||c?.org_id,S;try{let T=mt(e.cwd);h??=T.config?.orgId,S=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 I;if(n.since){let T=bb(n.since);if(T===null)return e.error(`error: invalid --since '${n.since}' (e.g. 7d, 24h, 30m).`),1;I=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 C=!!n.content;C&&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 b=await Qu({homeDir:r,endpoint:d,token:l,orgId:h,developerId:S,captureContent:C,concurrency:E,dryRun:u,reimport:!!n.reimport,projectRoot:o,sinceMs:I,retentionCutoffMs:f},a,i),y=Nn(o)??Jp(o);if(e.log(`Backfill ${u?"(dry-run) ":""}complete: ${b.imported} imported from this project (${y}), ${b.skipped} skipped, ${b.failed} failed, ${b.quarantined} quarantined (of ${b.total}).`),b.dedupSkipped>0&&e.log(`Skipped ${b.dedupSkipped} session(s) already recorded (live capture or an earlier import).`),b.dedupOk||e.log(Fb(u,b.imported)),b.excludedOtherProject>0&&e.log(`${b.excludedOtherProject} session(s) on this machine belong to other projects and were not included (backfill imports only the project you run it in).`),b.excludedUnknownCwd>0&&e.log(`${b.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(""),b.retentionSkipped>0&&m){let T=Cn[m],k=`${b.retentionSkipped} of ${b.total} session(s) predate your ${m} plan's ${T}-day retention window and weren't stored`,_=Oo(m);_?e.log(`${k} \u2014 upgrade to ${_} to keep ${Cn[_]} days, then re-run to import anything inside the wider window.`):e.log(`${k}.`)}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 ~${b.estimatedActions} action(s) in this import (a size estimate, not a governed-action count; first import is free). Preview a run with --dry-run before importing; --since limits it to recently-active sessions.`);let R=b.redactions;if(R.total>0){let T=Object.entries(R.byType).sort((k,_)=>_[1]-k[1]||k[0].localeCompare(_[0])).map(([k,_])=>`${k}\xD7${_}`).join(", ");e.log(`Edge-scrubbed ${R.total} secret(s) across the run before upload (by type: ${T}).`)}return b.failed>0?1:0}function ca(e,n){let t=Wt(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 Mb(e,n){try{let t=ca(e,n);return n.refresh?await ja(t):await cr(t),0}catch(t){return e.error(`error: ${t.message}`),1}}function Ub(e,n,t){let r={io:e,flags:t,sessionEnv:()=>ca(e,t)};switch(n){case"login":return Mb(e,t);case"logout":return np(r);case"status":case"doctor":return op(r);case"setup":return ql(r);case"backfill":return $u(r);case"capture":return tf(e)}}function $b(e,n,t){let r={io:e,flags:t,sessionEnv:()=>ca(e,t)};switch(n){case"login":return ga(r);case"logout":return Yu(r);case"status":case"doctor":return zu(r,n);case"setup":return Ju(r);case"backfill":return Nd(r);case"capture":return tf(e)}}function tf(e){return e.error("error: capture is the Claude Code session upload hook; use --agent claude."),1}function Bb(e,n,t){switch(n){case"setup":return Cb(e,t);case"login":return Db(e,t);case"logout":return jb(e,t);case"status":case"doctor":return _b(e);case"backfill":return Lb(e,t);case"capture":return Ap({env:e.env,homeDir:e.persistIO?.home??K(),endpointFlag:t.endpoint,readStdin:e.readStdin,...e.managedPaths?{managedPaths:e.managedPaths}:{},...e.captureOverrides})}}var Gb=["setup","login","logout","status","doctor","backfill","capture"];function Kb(e){return Gb.includes(e)}function Hb(e){for(let n of e){if(n==="--")return!1;if(n==="-h"||n==="--help")return!0}return!1}function Vb(e){let n=Ca(e.argv);if(n.kind==="chosen")return n.agent;e.error(`error: ${Ia}`),n.kind==="invalid"&&e.error(n.reason)}async function Wb(e){if(Hb(e.argv))return e.log(Gt),0;if(e.argv.length===0)return e.log(Gt),1;let n=Vb(e);if(n===void 0)return 1;let t;try{t=Eb(e.argv)}catch(i){return e.error(`error: ${i.message}`),e.error(Gt),1}let{values:r,positionals:o}=t;if(o.length===0)return e.log(Gt),1;let s=o[0];if(!Kb(s))return e.error(`error: unknown command '${s}'.`),e.error(Gt),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 Bb(e,s,r);case"cursor":return Ub(e,s,r);case"codex":return $b(e,s,r)}return lt(n)}function Qb(e,n=mb){if(!e)return!1;let t=e;try{t=n(e)}catch{}return/[\\/]cli[\\/]index\.(c?js|ts)$/.test(t)}Qb(process.argv[1])&&Wb({cwd:process.cwd(),env:process.env,argv:process.argv.slice(2),isInteractive:!!process.stdin.isTTY,fetchFn:fetch,pluginRunner:Eo,readStdin:()=>Hp(process.stdin),captureOverrides:{armDeadline:e=>{setTimeout(()=>process.exit(0),e).unref()}},log:e=>process.stdout.write(`${e}
|
|
171
|
-
`),error:e=>process.stderr.write(`${e}
|
|
172
|
-
`)}).then(e=>{process.exitCode=e}).catch(e=>{process.stderr.write(`fatal: ${e.message}
|
|
173
|
-
`),process.exitCode=1});export{Fo as a,at as b,J as c,dt as d,ie as e,Se as f,he as g,Jo as h,Xt as i,w as j,Re as k,Ee as l,$ as m,xn as n,Ea as o,rn as p,Ta as q,_a as r,An as s,Oa as t,Kf as u,ve as v,yg as w,mr as x,B as y,os as z,ss as A,Pn as B,dn as C,mt as D,yr as E,hr as F,ed as G,nd as H,cn as I,Nn as J,z as K,Ce as L,ik as M,br as N,Ir as O,va as P,Os as Q,Pr as R,Pd as S,ku as T,fi as U,Tu as V,gn as W,xt as X,_u as Y,V_ as Z,Bu as _,to as $,Gu as aa,ro as ba,mn as ca,At as da,Zr as ea,jh as fa,hi as ga,Si as ha,Te as ia,Je as ja,Ot as ka,Vu as la,Wu as ma,Qu as na,Ro as oa,eE as pa,fe as qa,ap as ra,Eo as sa,So as ta,na as ua,$t as va,dp as wa,ta as xa,cp as ya,aE as za,up as Aa,lp as Ba,vp as Ca,Wb as Da,Qb as Ea};
|