UNPKG

@anthropic-ai/claude-agent-sdk

Version:

SDK for building AI agents with Claude Code's capabilities. Programmatically interact with Claude to build autonomous agents that can understand codebases, edit files, and execute workflows.

20 lines (17 loc) • 17.8 kB
// (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance. // Version: 0.3.333 //! symbol-dispose-prelude: defines Symbol.dispose and Symbol.asyncDispose if missing, for this bundle's `using`. if (typeof Symbol.dispose !== 'symbol') { try { Symbol.dispose = Symbol.for('Symbol.dispose') } catch {} } if (typeof Symbol.asyncDispose !== 'symbol') { try { Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose') } catch {} } import{d,a,c,W,n,ir,I,_e,ot,i,t}from"./core-7ryne2zb.mjs";import{randomBytes as nr}from"crypto";import*as Oe from"fs/promises";import{closeSync as Gt,constants as h,fchmodSync as Jt,fstatSync as qt,ftruncateSync as Qt,lstatSync as zt,openSync as Zt,readFileSync as en,readSync as rn,realpathSync as tn,renameSync as nn,unlinkSync as on,writeFileSync as sn}from"fs";import{lstat as P,open as L,realpath as or,rename as Se,stat as sr,unlink as T,writeFile as ar}from"fs/promises";import{basename as be,dirname as N,isAbsolute as Ne,join as Re}from"path";import{readdir as Ot,readFile as le}from"fs/promises";import{release as ze}from"os";import{homedir as Ke}from"os";import{join as k}from"path";var j=Ke();function H(e){if(typeof e!=="string")throw TypeError("Expected a string");if(/[/\\\0]/.test(e))throw Error("Expected a folder name");let{env:r,platform:o}=process,s=`${e}-nodejs`;return{cache:o==="darwin"?k(j,"Library","Caches",s):o==="win32"?k(r.LOCALAPPDATA||k(j,"AppData","Local"),s,"Cache"):k(r.XDG_CACHE_HOME||k(j,".cache"),s)}}var zr=H("claude-cli");function Ge(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return"essential-traffic";if(process.env.DISABLE_TELEMETRY)return"no-telemetry";if(d(process.env.DO_NOT_TRACK))return"no-telemetry";return"default"}function oe(){return Ge()==="essential-traffic"}var Je=100,qe=1000;class ae{recentErrors=[];queue=[];droppedBeforeSink=0;sink=null;hardFailMode=void 0;maxRememberedChars=void 0;remember(e){if(this.recentErrors.length>=Je)this.recentErrors.shift();let r=this.maxRememberedChars;this.recentErrors.push(r===void 0||e.error.length<=r?e:{...e,error:`error text not remembered: it has ${e.error.length} characters, over this process's fixed limit of ${r} per error`})}dispatch(e){if(this.sink===null){if(this.queue.length>=qe){this.droppedBeforeSink++;return}this.queue.push(e);return}switch(e.type){case"error":this.sink.logError(e.error);break;case"mcpError":this.sink.logMCPError(e.serverName,e.error);break;case"mcpDebug":this.sink.logMCPDebug(e.serverName,e.message);break}}attachSink(e){if(this.sink!==null)return;this.sink=e;let r=this.queue;this.queue=[];for(let o of r)this.dispatch(o)}isHardFailMode(){return this.hardFailMode??=process.argv.includes("--hard-fail"),this.hardFailMode}reset(){this.recentErrors=[],this.queue=[],this.droppedBeforeSink=0,this.sink=null,this.hardFailMode=void 0,this.maxRememberedChars=void 0}}var se=new ae;function we(e){let r=W(e);try{if(d(process.env.CLAUDE_CODE_USE_BEDROCK)||d(process.env.CLAUDE_CODE_USE_VERTEX)||d(process.env.CLAUDE_CODE_USE_FOUNDRY)||d(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||d(process.env.CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD)||d(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||oe())return;let s={error:ir(r),timestamp:new Date().toISOString()};se.remember(s),se.dispatch({type:"error",error:r})}catch{}}var Qe=a({value:!1},(e)=>{e.value=!1});function ce(){return Qe.value}function Ht(){if(ce())return;try{return i().readFileSync("/proc/version",{encoding:"utf8"}).toLowerCase()}catch{return}}function Xe(e){return e.includes("microsoft")||e.includes("wsl")}class ue{sources;primedProcVersion;fallbackProcVersion;fallbackProcVersionRead=!1;platform;wslVersion=null;macOSMajorVersion=null;linuxDistroInfo;constructor(e){this.sources=e}kernelString(){if(this.primedProcVersion!==void 0)return this.primedProcVersion;if(!this.fallbackProcVersionRead)this.fallbackProcVersion=this.sources.readProcVersionSync(),this.fallbackProcVersionRead=!0;return this.fallbackProcVersion}getPlatform(){if(this.platform!==void 0)return this.platform;try{if(this.sources.platform==="darwin")this.platform="macos";else if(this.sources.platform==="win32")this.platform="windows";else if(this.sources.platform==="linux")if(this.sources.env.WSL_DISTRO_NAME||this.sources.env.WSL_INTEROP)this.platform="wsl";else{let e=this.kernelString();this.platform=e!==void 0&&Xe(e)?"wsl":"linux"}else this.platform="unknown"}catch(e){we(e),this.platform="unknown"}return this.platform}getWslVersion(){if(this.wslVersion!==null)return this.wslVersion;if(this.sources.platform!=="linux"){this.wslVersion=void 0;return}let e=this.kernelString();if(e===void 0){this.wslVersion=void 0;return}let r=e.match(/wsl(\d+)/);if(r&&r[1])this.wslVersion=r[1];else if(e.includes("microsoft"))this.wslVersion="1";else this.wslVersion=void 0;return this.wslVersion}getMacOSMajorVersion(){if(this.macOSMajorVersion!==null)return this.macOSMajorVersion;if(this.sources.platform!=="darwin"){this.macOSMajorVersion=void 0;return}let e=this.sources.osRelease().match(/^(\d+)\./);if(!e||!e[1]){this.macOSMajorVersion=void 0;return}let r=parseInt(e[1],10);return this.macOSMajorVersion=r<=24?r-9:Math.max(r,26),this.macOSMajorVersion}getLinuxDistroInfo(){return this.linuxDistroInfo??=this.readLinuxDistroInfo()}async readLinuxDistroInfo(){if(this.sources.platform!=="linux")return;let e={linuxKernel:this.sources.osRelease()};try{let r=await this.sources.readOsRelease();for(let o of r.split(` `)){let s=o.match(/^(ID|VERSION_ID)=(.*)$/);if(s&&s[1]&&s[2]){let l=s[2].replace(/^"|"$/g,"");if(s[1]==="ID")e.linuxDistroId=l;else e.linuxDistroVersion=l}}}catch{}return e}async prime(){if(this.primedProcVersion!==void 0||this.sources.platform!=="linux")return;try{let e=await this.sources.readProcVersion();this.primedProcVersion=e.toLowerCase()}catch(e){t(`Failed to read /proc/version for WSL detection: ${e}`,{level:"error"});return}this.platform=void 0,this.wslVersion=null}}var Ze;function er(){return Ze??=new ue({platform:process.platform,env:process.env,readProcVersionSync:Ht,readProcVersion:()=>le("/proc/version",{encoding:"utf8"}),osRelease:ze,readOsRelease:()=>le("/etc/os-release","utf8")})}function u(){return er().getPlatform()}var rr=!1;function fe(){return rr}function tr(){return!1}function de({served:e}){if(!fe())return!1;return e?!1:tr()}var Ue=process.platform==="darwin"?16777216:process.platform==="linux"||process.platform==="android"?524288:0,It=process.platform==="darwin"?536870912:0,Mt=process.platform==="linux"||process.platform==="android"?2097152:0;var Vt=new Set("drvfs 9p virtiofs cifs smb3 smbfs nfs nfs4 ntfs ntfs3 fuseblk vfat exfat msdos".split(" ")),Yt=new Set(["ext2 ext3 ext4 xfs btrfs zfs f2fs jfs reiserfs nilfs2 bcachefs tmpfs ramfs rootfs squashfs erofs","proc sysfs devtmpfs devpts mqueue hugetlbfs cgroup cgroup2 pstore bpf debugfs tracefs securityfs","configfs fusectl binfmt_misc nsfs rpc_pipefs efivarfs selinuxfs nfsd"].flatMap((e)=>e.split(" ")));function me(e){return e.replace(/\\([0-7]{3})/g,(r,o)=>String.fromCharCode(parseInt(o,8)))}var cr=new Set(["EXDEV","EPERM","EEXIST","EBUSY"]);function pe(e,r){return e==="EACCES"||e==="EPERM"&&r==="/dev/null"}function lr(e,r,o){return o!==void 0&&N(o)!==N(r)&&N(e)!==N(r)}function ur(){return de({served:!1})}function fr(e,r){return`Could not rewrite ${e} in place: this file has other names on disk (it is hard-linked, ${r} names in all), and writing it in place would change the file under every one of those names. The file was not changed. If another program has this file open, close it and try again. Otherwise, save to another path.`}function K(e){return Object.assign(new c(`Could not rewrite ${e} in place: it is a link or other special file, or this file system cannot confirm it is the file that was opened.`,"in-place write refused: a link, a special file or no file id at the target"),{code:"ELOOP",path:e})}async function he(e,r){let o;try{o=await P(e,{bigint:!0})}catch(s){if(n(s)!=="ENOENT")return s instanceof Error?s:K(e);return ge(e)}if(!o.isFile()||_e(o.ino)||_e(r.ino))return K(e);if(o.nlink>1n)return Te(e,Number(o.nlink));return ot(o,r)?ge(e):void 0}function ge(e){return Object.assign(new c(`Could not rewrite ${e} in place: could not confirm that this path still leads to the file that was opened. The file was not changed. If another program has this file open, close it and try again. Otherwise, save to another path.`,"in-place write refused: could not confirm the path leads to the opened file"),{code:"EAGAIN",path:e})}function Te(e,r){return Object.assign(new c(fr(e,r),"in-place write refused: the target has other names (a hard link)"),{code:"EMLINK",path:e})}var Pe=new Set(["EPERM","EBUSY","EACCES"]);function dr(e){return`${e}.tmp.${nr(4).toString("hex")}`}var Ae=4,Le=50,ve=Array.from({length:Ae-1},()=>Le);var xe=[100,200,400],wn=xe.length+2,mr=ve.slice(1),J=a(new Set,(e)=>e.clear()),pr=26985,hr=50,gr="/proc/self/mounts",Er=1048576,q=a(new Set,(e)=>e.clear()),yn=new Int32Array(new SharedArrayBuffer(4));function ke(e,r,o=Ae-1){if(process.platform!=="win32")return!1;let s=n(e);return s!==void 0&&Pe.has(s)&&r<o}var Fe=128;async function wr(e){try{return((await P(e)).mode&Fe)===0}catch{return!1}}async function yr(e,r,o=ve){let s=!1;for(let l=0;;l++)try{return await e(),s}catch(p){if(ke(p,l,o.length)){if(l===0&&r!==void 0&&await wr(r))throw p;s=!0,await I(o[l]);continue}throw p}}function Or(e,r){let o=n(e);if(o!==void 0&&Pe.has(o)&&Ne(r))J.add(r)}async function Sr(e,r,o=Se,s=!1){let l=async()=>o(e,r),p=!s&&!J.has(r);try{await l();return}catch(m){if(!ke(m,0))throw m;try{if(((await P(r)).mode&Fe)===0)throw m}catch(S){if(S===m)throw m;p&&=n(S)!=="ENOENT"}}await I(Le);try{await yr(l,void 0,p?xe:mr)}catch(m){if(p)Or(m,r);throw m}}var br=new Set(["ENOSPC","EIO","EDQUOT","EFBIG"]),_r=new Set([...br,"EROFS","ENOENT"]),Nr=67108864,Q=process.platform==="win32"?0:h.O_NONBLOCK;async function Rr(e,r,o=process.platform){return(await De(e,r,o)).kind==="pass"}async function De(e,r,o=process.platform){if(o!=="win32")return{kind:"pass"};try{return{kind:(await P(e)).isFile()?"pass":"refuse"}}catch(s){if(n(s)==="ENOENT")return{kind:r?"pass":"refuse"};return{kind:"failed",error:s}}}async function Ce(e,r=!1){if(!r){let s=await De(e,!0);if(s.kind==="refuse")return{kind:"unavailable",screened:{kind:"refuse"}};if(s.kind==="failed")return{kind:"unavailable",screened:s}}let o;try{o=await L(e,process.platform==="win32"?h.O_RDONLY:h.O_RDONLY|(r?0:h.O_NOFOLLOW)|Q)}catch(s){return n(s)==="ENOENT"?{kind:"absent"}:{kind:"unavailable"}}try{let s=await o.stat({bigint:!0});if(!s.isFile()||s.size>BigInt(Nr))return{kind:"unavailable"};return{kind:"snapshot",bytes:new Uint8Array(await o.readFile()),mode:Number(s.mode)&4095,ino:s.ino}}catch{return{kind:"unavailable"}}finally{await o.close().catch(()=>{})}}async function Tr(e,r,o=!1){if(!o&&!await Rr(e,!0))return!1;let s;try{s=await L(e,process.platform==="win32"?"w":h.O_WRONLY|h.O_CREAT|h.O_TRUNC|(o?0:h.O_NOFOLLOW)|Q,r.mode)}catch{return!1}try{if(!(await s.stat()).isFile())return await s.close().catch(()=>{}),!1;return await s.writeFile(r.bytes),await s.chmod(r.mode).catch(()=>{}),await s.close(),!0}catch{return await s.close().catch(()=>{}),!1}}async function Pr(e,r,o){try{await e.truncate(0);let s=0;while(s<r.length){let{bytesWritten:l}=await e.write(r,s,r.length-s,s);if(l===0)return!1;s+=l}return await e.chmod(o).catch(()=>{}),!0}catch{return!1}}async function Ar(e,r,o,s){try{let l=await P(e,{bigint:!0});if(!l.isFile())return!1;if(ot(l,r))return!0;if(n(s)!=="ESTALE")return!1;let p=await Ce(e);return p.kind==="snapshot"&&!Lr(p.bytes,o)}catch{return!1}}function Lr(e,r){let o=typeof r==="string"?Buffer.from(r):r;return e.length<=o.length&&Buffer.compare(e,o.subarray(0,e.length))===0}var vr={restored:"original target restored",removed:"partial target removed",partial:"target left partial — treat contents as torn",untouched:"target untouched",replaced:"another writer's file left at the target"};function F(e,r,o){try{if(e instanceof Error)e.message=`${e.message}; ${r!==void 0?`new contents preserved at ${r}; `:""}${vr[o]}`,Object.assign(e,{...r!==void 0&&{preservedTmp:r},targetOutcome:o})}catch{}return e}function Ie(e){let r=n(e);return r==="EINVAL"||r==="ENOTSUP"||r==="EPERM"||r==="ENOSYS"}async function Ee(e,r){try{await e.sync()}catch(o){if(!Ie(o)&&!(r&&n(o)==="EBADF"))throw o}}class X extends Error{target;constructor(e){super("beforePublish refused the write; nothing was published");this.target=e;this.name="PublishRefusedError"}}async function xr(e,r){if(r===void 0||process.platform==="win32")return e;try{await(await L(r,h.O_RDONLY|h.O_DIRECTORY|h.O_NOFOLLOW)).close()}catch(o){switch(n(o)){case"ENOENT":case"ELOOP":case"ENOTDIR":return e;case"EACCES":case"EPERM":if(await kr(r))return e;throw o;default:throw o}}return Re(r,be(e))}async function kr(e){let r=process.getuid?.();if(r===void 0)return!1;try{return(await P(e)).uid!==r}catch{return!1}}var ye=3;async function Fr(e,r){if(r!=="win32")return!1;try{return await P(e),!0}catch(o){return n(o)==="ENOENT"?!1:{cause:o}}}function Dr(e,r){return Object.assign(Error("EEXIST: name already taken (exclusive create)",typeof r==="object"?{cause:r.cause}:void 0),{code:"EEXIST",syscall:"lstat",path:e})}async function Me(e,r,o){for(let s=1;;s++){let l=dr(e),p=await Fr(l,r);if(p!==!1){if(s<ye)continue;throw Dr(l,p)}try{return await o(l)}catch(m){if(n(m)==="EEXIST"&&s<ye)continue;throw m}}}async function Cr(e,r,o,s=process.platform){return Me(e,s,async(l)=>{try{return await ar(l,r,{encoding:"utf8",mode:o,flag:"wx"}),l}catch(p){if(n(p)!=="EEXIST")await T(l).catch(()=>{});throw p}})}async function Ir(e,r,o=process.platform){return Me(e,o,async(s)=>({fh:await L(s,o==="win32"?"wx":h.O_WRONLY|h.O_CREAT|h.O_EXCL,r),tmp:s}))}function Be(e){if(Ne(e)&&!e.startsWith("/proc/"))q.add(e)}function Mr(e){q.delete(e),J.delete(e)}function Br(e,r,o,s){if(process.platform!=="linux"||n(e)!=="EBUSY"||N(r)!==N(o)||q.has(o))return!1;if(s)return Be(o),!1;return!0}function Ur(e,r){return e.split(` `).some((o)=>me(o.split(" ")[1]??"")===r)}async function Wr(e,r,o,s){if(!Br(e,r,o,s))return!1;try{if((await Oe.statfs(N(o))).type!==pr)return!1}catch{return!1}let l=!1;try{let p=await L(gr,h.O_RDONLY|Ue);try{let m=Buffer.allocUnsafe(Er),S=0;while(S<m.length){let{bytesRead:R}=await p.read(m,S,m.length-S,null);if(R===0)break;S+=R}let D=Re(await or(N(o)),be(o));l=Ur(m.toString("utf8",0,S),D)}finally{await p.close()}}catch{}if(l)return Be(o),!1;return await T(r).catch(()=>{}),await I(hr),!0}async function pt(e,r,o,s){return gn(e,r,{mode:o,renameFn:s})}function gn(e,r,o){return G(e,r,o,!1)}async function G(e,r,o,s){let{mode:l,createMode:p,exactMode:m,flush:S,flushForgivesEbadf:D,followSymlinks:R,inPlaceOnTempCreateRefused:z,stagingDir:Z,renameFn:Ve,beforePublish:C}=o,v=o.refuseLinks===!0&&R!==!0,B=v&&process.platform==="win32",V=l??p,ee=()=>{if(C!==void 0&&!C())throw new X(e)},re=await xr(e,Z),Ye=R===!0||process.platform==="win32"?0:h.O_NOFOLLOW,_,x=!1,Y=!1,te=async(w)=>{let f=await Ce(e,R===!0),y=f.kind==="snapshot"&&!v?f:void 0,O=f.kind==="snapshot"&&v?f:void 0;if(B&&f.kind==="unavailable"&&f.screened!==void 0)throw f.screened.kind==="failed"?f.screened.error:K(e);ee();let g=await L(e,process.platform==="win32"?h.O_WRONLY|(B?0:h.O_CREAT):h.O_WRONLY|h.O_CREAT|Ye|Q,m??V),E;try{E=await g.stat({bigint:!0})}catch(b){throw await g.close().catch(()=>{}),x=w!==void 0,F(b,w,"untouched")}let A=E.isCharacterDevice();if(!E.isFile()&&!A)throw await g.close().catch(()=>{}),Object.assign(Error("refusing the in-place arm on a non-regular target"),{code:"ENXIO",path:e});if(!A&&E.nlink>1n&&(v||ur()))throw await g.close().catch(()=>{}),Te(e,Number(E.nlink));if(C!==void 0&&!C()){if(await g.close().catch(()=>{}),f.kind==="absent"&&E.size===0n&&!A)await T(e).catch(()=>{});throw new X(e)}if(v&&(!A||B)){let b=await he(e,E);if(b!==void 0)throw await g.close().catch(()=>{}),b}let M=!1;try{if(!A)await g.truncate(0),M=!0;await g.writeFile(r,{encoding:"utf8"});let b=A?void 0:m??(f.kind!=="absent"?l:void 0);if(b!==void 0)await g.chmod(b).catch(()=>{});if(S===!0)await Ee(g,D===!0);await g.close()}catch(b){let ie=M&&await Ar(e,E,r,b),je=M&&!ie&&O?.ino!==void 0&&O.ino===E.ino&&await he(e,E)===void 0&&await Pr(g,O.bytes,O.mode)&&await g.close().then(()=>!0,()=>!1);if(await g.close().catch(()=>{}),!M)throw x=w!==void 0,F(b,w,"untouched");if(x=w!==void 0,ie)throw F(b,w,"replaced");let He=je||y!==void 0&&await Tr(e,y,R===!0)?"restored":await T(e).then(()=>!0,($e)=>n($e)==="ENOENT")?"removed":"partial";throw F(b,w,He)}let ne=w??_;if(ne!==void 0)await T(ne).catch(()=>{})};try{try{if(m!==void 0||S===!0){let f=await Ir(re,m??V),y=f.fh;_=f.tmp;let O=!1,g;try{if(await y.writeFile(r,{encoding:"utf8"}),m!==void 0)try{await y.chmod(m)}catch(E){if(!Ie(E))throw E}if(S===!0)await Ee(y,D===!0)}catch(E){O=!0,g=E}if(!O)Y=!0;try{await y.close()}catch(E){if(!O)throw x=!0,F(E,_,"untouched")}if(O)throw g}else _=await Cr(re,r,V),Y=!0}catch(f){if(z!==!0)throw f;if(Y)throw f;if(!pe(n(f),e))throw f;if(!await sr(e).then(()=>!0,()=>!1))throw f;await te(void 0);return}if(_===void 0)throw Error("staging block exited without a staging file");let w=_;try{let f=Ve??Se;await Sr(w,e,(y,O)=>(ee(),f(y,O))),Mr(e)}catch(f){let y=n(f),O=lr(w,e,Z);if(O&&y==="EXDEV"&&o.sandboxMayBeOn===!1){await T(w).catch(()=>{}),_=void 0,await G(e,r,{...o,stagingDir:void 0},s);return}let g=z===!0&&O&&pe(y,e);if(y===void 0||!(cr.has(y)||g||s&&!_r.has(y)))throw f;if(await Wr(f,w,e,s)){_=void 0,await G(e,r,o,!0);return}await te(w)}}catch(w){if(_!==void 0&&!x)await T(_).catch(()=>{});throw w}}import{constants as We}from"fs";var Vr=process.platform==="win32"?0:We.O_NONBLOCK,U=process.platform==="win32"?0:We.O_NOFOLLOW|Vr; export{we,Ht,Xe,u,Ue,pt,gn,U};