@anthropic-ai/claude-agent-sdk 0.3.280 → 0.3.282

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/core.mjs ADDED
@@ -0,0 +1,41 @@
1
+ // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
2
+
3
+ // Version: 0.3.282
4
+
5
+ // symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
6
+ // scripts grep for this line's tag. Runs before any module body. bun lowers
7
+ // `using` to a helper that keys disposal on the registry symbol when the
8
+ // well-known one is missing, while disposable objects key on the well-known
9
+ // global directly; on engines without a native `Symbol.dispose` (Safari/iOS,
10
+ // Firefox ESR, `node:vm` contexts on Node <=22 such as Jest's `node`
11
+ // environment and vitest's vm pools, and Node before 18.18 / 20.4) the two
12
+ // disagree and every lowered `using` throws. Registering both symbols first
13
+ // makes the keys agree; a no-op where they are native, and a locked-down
14
+ // `Symbol` (SES lockdown) keeps today's behaviour instead of failing to load.
15
+ if (typeof Symbol.dispose !== 'symbol') {
16
+ try {
17
+ Symbol.dispose = Symbol.for('Symbol.dispose')
18
+ } catch {}
19
+ }
20
+ if (typeof Symbol.asyncDispose !== 'symbol') {
21
+ try {
22
+ Symbol.asyncDispose = Symbol.for('Symbol.asyncDispose')
23
+ } catch {}
24
+ }
25
+ import{Ae,a,i,o,G,l,b,lt,ct,D,R,n,Te,Xe,_,Je,I,x,ut,g,xe,C,H,vt,xt,Qe,De,ft,gt,mt,ht,Q,ie,ze,Ge,h,nt,_t,t,A,e,it,W,r,ae,Et,bt,ee,le,Ot}from"./core-5drmq1nt.mjs";import{execFile as qa}from"child_process";import{randomUUID as za}from"crypto";import{mkdir as $r,mkdtemp as np,readFile as Va,rm as Ya,writeFile as Os}from"fs/promises";import{createRequire as Ja}from"module";import{homedir as Hr,tmpdir as Xa}from"os";import{dirname as Ts,isAbsolute as Qa,join as V,posix as Za,resolve as Vt,sep as ec,win32 as tc}from"path";import{fileURLToPath as rc}from"url";import{setMaxListeners as ho}from"events";var yo=50;function tt(s=yo){let c=new AbortController;return ho(s,c.signal),c}var Wc=new FinalizationRegistry(({parentSignalRef:s,handler:c})=>{s.deref()?.removeEventListener("abort",c)});var qc={"user-cancel":new DOMException("user-cancel","AbortError"),"remote-cancel":new DOMException("remote-cancel","AbortError"),shutdown:new DOMException("shutdown","AbortError"),interrupt:new DOMException("interrupt","AbortError"),"turn-abort":new DOMException("turn-abort","AbortError"),background:new DOMException("background","AbortError"),"refusal-fallback-edit":new DOMException("refusal-fallback-edit","AbortError"),"recovery-timeout":new DOMException("recovery-timeout","AbortError"),"permission-stop":new DOMException("permission-stop","AbortError")};var So="server-fallback-tombstone";var zc=new DOMException(So,"AbortError");var bo="subagent-park",Vc=new DOMException(bo,"AbortError");import{spawn as bi}from"child_process";import{existsSync as wi}from"fs";import{createInterface as Ei}from"readline";import{StringDecoder as _i}from"string_decoder";var wo=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var ir={bearer:[/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer <token>"],basic:[/(:\s*)Basic\s+[A-Za-z0-9+/=]{8,}/gi,"$1Basic <token>"],sk:[/\bsk-[A-Za-z0-9_-]{20,}/g,"<token>"]},Eo=[/\bBearer\s{1,512}(?=[A-Za-z0-9._~+/=-]{16})(?:eyJ|(?=[A-Za-z0-9._~+/=-]{0,64}[0-9=]))/i,/:\s{0,512}Basic\s{1,512}(?=[A-Za-z0-9+/=]{16})(?=[A-Za-z0-9+/=]{0,64}[0-9=])/i,/\bsk-(?=[A-Za-z0-9_-]{20})(?=[A-Za-z0-9_-]{0,64}[0-9])/];var Jc=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${Me("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${Me("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),cn=[[rt("sk-ant-","[A-Za-z0-9_-]",8,ar(8)),"<token>"],[rt("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,ar(20)),"<token>"]],ln=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],_o=`(?:${ln.join("|")})`,un=[[new RegExp(`(^|[^A-Za-z0-9+])${_o}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],dn=[[rt("gh[opusr]_","[A-Za-z0-9]",20,Me("[A-Za-z0-9]")),"<token>"],[/github_pat_[A-Za-z0-9_]{82,}/g,"<token>"],[/sq0(?:atp|csp)-[A-Za-z0-9_-]{22,}/g,"<token>"],[/(^|[^A-Za-z0-9+/])EAAA[A-Za-z0-9+/=%_-]{56,}/g,"$1<token>"],[rt("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,Me("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[rt("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",Me("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${Me("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[wo,"hooks.slack.com/<redacted>"]],vo=[/\bey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,"<jwt>"],ko=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,fn=[[/(^|[^A-Za-z0-9+_-])AIza[A-Za-z0-9_-]{35}(?![A-Za-z0-9+=_-])/g,"$1<token>"],[/(^|[^A-Za-z0-9+_-])GOCSPX-[A-Za-z0-9_-]{28}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],pn=[[/(^|[^A-Za-z0-9+_-])[sr]k_(?:live|test|prod)_(?=[A-Za-z0-9]{0,64}[0-9])[A-Za-z0-9]{24,}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],Co=[ir.bearer,ir.basic,...cn,ir.sk,...un],Ro=[...dn,vo,...fn,...pn],Xc=[[new RegExp(`sk-${ar(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...ln.map((s)=>[new RegExp(`${s}[A-Z2-7]{16}`,"g"),"<token>"]),[/AIza[\w-]{35}/g,"<token>"],[/GOCSPX-[\w-]{28,}/g,"<token>"],[/[sr]k_(?:live|test|prod)_[A-Za-z0-9]{24,}/g,"<token>"]];function st(s){return[...Co,...Ro].reduce((c,[u,d])=>c.replace(u,d),String(s))}var Qc=[...Eo,...[...cn,...un,...dn,...fn,...pn].map(([s])=>new RegExp(s.source,s.flags.replaceAll("g",""))),ko];function rt(s,c,u,d,f="",p="",m="g"){let y=`${c}{${u},}${f}`;return new RegExp(`(?:\\b${s}${p}${y}|${s}${d}${y})`,m)}function Me(s){return`(?=${s}{0,64}[0-9])`}function ar(s){return`(?=[A-Za-z0-9_-]{0,64}?(?=[A-Za-z0-9]{${s}})(?=[A-Za-z0-9]{0,64}[0-9])(?=[A-Za-z0-9]{0,64}[A-Za-z]))`}import{randomUUID as gi}from"crypto";import{join as Pn}from"path";import{AsyncLocalStorage as ii}from"async_hooks";import{constants as ai}from"fs";import{appendFile as ci,copyFile as li,lstat as ui,mkdir as di,open as _n,readdir as vn,readFile as kn,stat as fi,unlink as pi,writeFile as fr}from"fs/promises";import{randomBytes as xo}from"crypto";import{closeSync as dl,constants as z,fchmodSync as fl,fstatSync as pl,ftruncateSync as ml,lstatSync as gl,openSync as hl,readFileSync as yl,renameSync as Sl,unlinkSync as bl,writeFileSync as wl}from"fs";import{lstat as Lt,open as at,rename as yn,stat as Ao,unlink as ot,writeFile as Oo}from"fs/promises";import{basename as Mo,join as Do}from"path";var Io=!1;function mn(){return Io}function To(){return!1}function gn({served:s}){if(!mn())return!1;return s?!1:To()}var No=new Set(["EXDEV","EPERM","EEXIST","EBUSY"]);function Lo(){return gn({served:!1})}function jo(s,c){return`Could not rewrite ${s} in place: this file has other names on disk (it is hard-linked, ${c} names in all), and writing it in place would change the file under every one of those names. Remove the extra links, then try again.`}function Fo(s,c){return Object.assign(new l(jo(s,c),"in-place write refused: the target has other names (a hard link)"),{code:"EMLINK",path:s})}var Ko=new Set(["EPERM","EBUSY","EACCES"]);function Bo(s){return`${s}.tmp.${xo(4).toString("hex")}`}var Uo=4,$o=50,Pl=new Int32Array(new SharedArrayBuffer(4));function Ho(s,c){if(process.platform!=="win32")return!1;let u=n(s);return u!==void 0&&Ko.has(u)&&c<Uo-1}var Go=128;async function Wo(s){try{return((await Lt(s)).mode&Go)===0}catch{return!1}}async function qo(s,c){let u=!1;for(let d=0;;d++)try{return await s(),u}catch(f){if(Ho(f,d)){if(d===0&&c!==void 0&&await Wo(c))throw f;u=!0,await I($o);continue}throw f}}function zo(s,c,u=yn){return qo(()=>u(s,c),c)}var Vo=67108864,ur=process.platform==="win32"?0:z.O_NONBLOCK;async function Sn(s,c,u=process.platform){return(await Yo(s,c,u)).kind==="pass"}async function Yo(s,c,u=process.platform){if(u!=="win32")return{kind:"pass"};try{return{kind:(await Lt(s)).isFile()?"pass":"refuse"}}catch(d){if(n(d)==="ENOENT")return{kind:c?"pass":"refuse"};return{kind:"failed",error:d}}}async function Jo(s,c=!1){if(!c&&!await Sn(s,!0))return{kind:"unavailable"};let u;try{u=await at(s,process.platform==="win32"?z.O_RDONLY:z.O_RDONLY|(c?0:z.O_NOFOLLOW)|ur)}catch(d){return n(d)==="ENOENT"?{kind:"absent"}:{kind:"unavailable"}}try{let d=await u.stat();if(!d.isFile()||d.size>Vo)return{kind:"unavailable"};return{kind:"snapshot",bytes:new Uint8Array(await u.readFile()),mode:d.mode&4095}}catch{return{kind:"unavailable"}}finally{await u.close().catch(()=>{})}}async function Xo(s,c,u=!1){if(!u&&!await Sn(s,!0))return!1;let d;try{d=await at(s,process.platform==="win32"?"w":z.O_WRONLY|z.O_CREAT|z.O_TRUNC|(u?0:z.O_NOFOLLOW)|ur,c.mode)}catch{return!1}try{if(!(await d.stat()).isFile())return await d.close().catch(()=>{}),!1;return await d.writeFile(c.bytes),await d.chmod(c.mode).catch(()=>{}),await d.close(),!0}catch{return await d.close().catch(()=>{}),!1}}function Nt(s,c,u){try{if(s instanceof Error)s.message=`${s.message}; ${c!==void 0?`new contents preserved at ${c}; `:""}${u==="restored"?"original target restored":u==="removed"?"partial target removed":u==="untouched"?"target untouched":"target left partial — treat contents as torn"}`,Object.assign(s,{...c!==void 0&&{preservedTmp:c},targetOutcome:u})}catch{}return s}function cr(s){let c=n(s);return c==="EINVAL"||c==="ENOTSUP"||c==="EPERM"||c==="ENOSYS"}class lr extends Error{target;constructor(s){super("beforePublish refused the write; nothing was published");this.target=s;this.name="PublishRefusedError"}}async function Qo(s,c){if(c===void 0||process.platform==="win32")return s;try{await(await at(c,z.O_RDONLY|z.O_DIRECTORY|z.O_NOFOLLOW)).close()}catch(u){switch(n(u)){case"ENOENT":case"ELOOP":case"ENOTDIR":return s;case"EACCES":case"EPERM":if(await Zo(c))return s;throw u;default:throw u}}return Do(c,Mo(s))}async function Zo(s){let c=process.getuid?.();if(c===void 0)return!1;try{return(await Lt(s)).uid!==c}catch{return!1}}var hn=3;async function ei(s,c){if(c!=="win32")return!1;try{return await Lt(s),!0}catch(u){return n(u)==="ENOENT"?!1:{cause:u}}}function ti(s,c){return Object.assign(Error("EEXIST: name already taken (exclusive create)",typeof c==="object"?{cause:c.cause}:void 0),{code:"EEXIST",syscall:"lstat",path:s})}async function bn(s,c,u){for(let d=1;;d++){let f=Bo(s),p=await ei(f,c);if(p!==!1){if(d<hn)continue;throw ti(f,p)}try{return await u(f)}catch(m){if(n(m)==="EEXIST"&&d<hn)continue;throw m}}}async function ri(s,c,u,d=process.platform){return bn(s,d,async(f)=>{try{return await Oo(f,c,{encoding:"utf8",mode:u,flag:"wx"}),f}catch(p){if(n(p)!=="EEXIST")await ot(f).catch(()=>{});throw p}})}async function ni(s,c,u=process.platform){return bn(s,u,async(d)=>({fh:await at(d,u==="win32"?"wx":z.O_WRONLY|z.O_CREAT|z.O_EXCL,c),tmp:d}))}async function wn(s,c,u,d){return si(s,c,{mode:u,renameFn:d})}async function si(s,c,u){let{mode:d,createMode:f,exactMode:p,flush:m,followSymlinks:y,inPlaceOnTempCreateRefused:S,stagingDir:w,renameFn:E,beforePublish:v}=u,k=d??f,P=()=>{if(v!==void 0&&!v())throw new lr(s)},O=await Qo(s,w),N=y===!0||process.platform==="win32"?0:z.O_NOFOLLOW,M,j=!1,Y=!1,pe=async(K)=>{let B=await Jo(s,y===!0),U=B.kind==="snapshot"?B:void 0;P();let F=await at(s,process.platform==="win32"?z.O_WRONLY|z.O_CREAT:z.O_WRONLY|z.O_CREAT|N|ur,p??k),Z;try{Z=await F.stat()}catch(fe){throw await F.close().catch(()=>{}),j=K!==void 0,Nt(fe,K,"untouched")}let q=Z.isCharacterDevice();if(!Z.isFile()&&!q)throw await F.close().catch(()=>{}),Object.assign(Error("refusing the in-place arm on a non-regular target"),{code:"ENXIO",path:s});if(!q&&Z.nlink>1&&Lo())throw await F.close().catch(()=>{}),Fo(s,Z.nlink);if(v!==void 0&&!v()){if(await F.close().catch(()=>{}),B.kind==="absent"&&Z.size===0&&!q)await ot(s).catch(()=>{});throw new lr(s)}let he=!1;try{if(!q)await F.truncate(0),he=!0;await F.writeFile(c,{encoding:"utf8"});let fe=q?void 0:p??(B.kind!=="absent"?d:void 0);if(fe!==void 0)await F.chmod(fe).catch(()=>{});if(m===!0)try{await F.sync()}catch(ce){if(!cr(ce))throw ce}await F.close()}catch(fe){if(await F.close().catch(()=>{}),!he)throw j=K!==void 0,Nt(fe,K,"untouched");j=K!==void 0;let $e=U!==void 0&&await Xo(s,U,y===!0)?"restored":await ot(s).then(()=>!0,(Re)=>n(Re)==="ENOENT")?"removed":"partial";throw Nt(fe,K,$e)}let Ee=K??M;if(Ee!==void 0)await ot(Ee).catch(()=>{})};try{try{if(p!==void 0||m===!0){let B=await ni(O,p??k),U=B.fh;M=B.tmp;let F=!1,Z;try{if(await U.writeFile(c,{encoding:"utf8"}),p!==void 0)try{await U.chmod(p)}catch(q){if(!cr(q))throw q}if(m===!0)try{await U.sync()}catch(q){if(!cr(q))throw q}}catch(q){F=!0,Z=q}if(!F)Y=!0;try{await U.close()}catch(q){if(!F)throw j=!0,Nt(q,M,"untouched")}if(F)throw Z}else M=await ri(O,c,k),Y=!0}catch(B){if(S!==!0)throw B;if(Y)throw B;if(n(B)!=="EACCES")throw B;if(!await Ao(s).then(()=>!0,()=>!1))throw B;await pe(void 0);return}if(M===void 0)throw Error("staging block exited without a staging file");let K=M;try{let B=E??yn;await zo(K,s,(U,F)=>(P(),B(U,F)))}catch(B){let U=n(B);if(U===void 0||!No.has(U))throw B;await pe(K)}}catch(K){if(M!==void 0&&!j)await ot(M).catch(()=>{});throw K}}import{constants as En}from"fs";var oi=process.platform==="win32"?0:En.O_NONBLOCK,dr=process.platform==="win32"?0:En.O_NOFOLLOW|oi;class Rn{read(s){return kn(s,"utf8")}readBytes(s){return kn(s)}write(s,c,u){return fr(s,c,{encoding:"utf8",mode:u})}async mkdir(s,c){try{await di(s,{recursive:!0,mode:c})}catch(u){if(n(u)!=="EEXIST")throw u}}atomicWrite(s,c,u){return wn(s,c,u)}delete(s){return pi(s)}list(s){return vn(s)}append(s,c,u){return ci(s,c,{encoding:"utf8",mode:u})}writeExclusive(s,c,u){return fr(s,c,{encoding:"utf8",flag:"wx",mode:u})}writeBytesExclusive(s,c,u){return fr(s,c,{flag:"wx",mode:u})}copy(s,c){return li(s,c)}async stat(s){return{mtimeMs:(await fi(s)).mtimeMs}}async lstat(s){try{let c=await ui(s);return{isSymbolicLink:c.isSymbolicLink(),isFile:c.isFile(),isDirectory:c.isDirectory(),mtimeMs:c.mtimeMs,nlink:c.nlink}}catch(c){if(n(c)==="ENOENT")return;throw c}}async listEntries(s){return(await vn(s,{withFileTypes:!0})).map((u)=>({name:u.name,isDirectory:u.isDirectory(),isFile:u.isFile()}))}async readRange(s,c,u){pr("readRange","offset",c),pr("readRange","length",u);let d=await _n(s,"r");try{return await Cn(d,c,u)}finally{await d.close()}}async readTail(s,c,u){pr("readTail","maxBytes",c);let d=u?.noFollow?ai.O_RDONLY|dr:"r",f=await _n(s,d);try{let p=await f.stat();if(u?.noFollow&&!p.isFile())throw Object.assign(Error("ENXIO: not a regular file"),{code:"ENXIO",path:s});let{size:m}=p,y=Math.min(c,m);return await Cn(f,m-y,y)}finally{await f.close()}}}function pr(s,c,u){if(!Number.isInteger(u)||u<0)throw RangeError(`${s}: ${c} must be a non-negative integer, got ${u}`)}async function Cn(s,c,u){if(u===0)return Buffer.alloc(0);let d=Buffer.alloc(u),f=0;while(f<u){let{bytesRead:p}=await s.read(d,f,u-f,c+f);if(p===0)break;f+=p}return f===u?d:Buffer.from(d.subarray(0,f))}var mi=new ii;function mr(){return mi.getStore()??new Rn}class In{debugFilePath=void 0;initPromise=null;logStem=null}var hi=new i(()=>new In);function Tn(){return hi.of(C().host)}function xn(s){if(s.initPromise)return s.initPromise;if(!Ge("DEBUG_CLAUDE_AGENT_SDK"))return s.debugFilePath=null,s.initPromise=Promise.resolve(),s.initPromise;let c=Pn(h(),"debug");return s.logStem=`sdk-${gi()}`,s.debugFilePath=Pn(c,`${s.logStem}.txt`),process.stderr.write(`SDK debug logs: ${s.debugFilePath}
26
+ `),s.initPromise=mr().mkdir(c).catch(()=>{}),s.initPromise}function yi(s){return s.logStem===null?null:{namespace:"log",sessionId:s.logStem,channel:"debug"}}function An(){let s=Tn();return xn(s),s.debugFilePath??null}function oe(s,c){let u=Tn();if(u.debugFilePath===null)return;let f=`${new Date().toISOString()} ${s}
27
+ `;xn(u).then(()=>{if(c!==void 0){let p=yi(u);if(p!==null)c.append(p,[{data:f}]).catch(()=>{});return}if(u.debugFilePath)mr().append(u.debugFilePath,f).catch(()=>{})})}function Si(s){let c=s.trim();return c.startsWith("{")&&c.endsWith("}")}function On(s,c){let u={...s};if(!c)return u;let d=c.enabled===!0&&c.failIfUnavailable===void 0?{...c,failIfUnavailable:!0}:c,f=u.settings;if(f&&!Si(f))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let p={sandbox:d};if(f)try{p={...A(f),sandbox:d}}catch{}return u.settings=t(p),u}function gr(s,c,u){let d=String(u);if(d.length>1&&d.startsWith("-"))s.push(`--${c}=${d}`);else s.push(`--${c}`,d)}var vi=2000,hr=2048,Nn="sdk-exit-after-stderr-drained",ki=200;function yr(s){return s==="exit"?Nn:s}class Ln{#e=new Set;#t=!1;#r=()=>this.killAll();track(s){if(this.#e.add(s),!this.#t)this.#t=!0,process.on("exit",this.#r)}untrack(s){this.#e.delete(s)}isTracking(s){return this.#e.has(s)}get size(){return this.#e.size}killAll(){for(let s of this.#e)if(!s.killed)if(process.platform==="win32")try{s.stdin.end()}catch{}else s.kill("SIGTERM")}reset(){process.off("exit",this.#r),this.#t=!1,this.#e.clear()}}var jt=new Ln,Ci=/[(),\u0000-\u001f\u007f-\u009f]/;function Ri(s){if(typeof s!=="string"||s.trim()==="")throw Error("Skill names must be non-empty strings.");if(!De(s))throw new l(`Invalid skill name ${t(s)}: the name contains an unpaired surrogate, which cannot survive the UTF-8 encoding of the CLI invocation; no skill discovered from the filesystem can have such a name.`,"skill name with unpaired surrogate rejected");if(s!==s.trim())throw new l(`Invalid skill name ${t(s)}: leading or trailing whitespace is not allowed — the Skill tool trims the invoked name, so a padded rule can never match. Remove the padding.`,"skill name with surrounding whitespace rejected");if(Ci.test(s))throw new l(`Invalid skill name ${t(s)}: parentheses, commas, and control characters are not allowed in skill names. Skill names match the skill's directory name (or 'plugin:skill' for plugin-qualified skills); rename the skill if its directory name contains these characters.`,"invalid skill name rejected");if(s==="*")throw Error("Invalid skill name '*': use skills: 'all' to enable every skill.");if(s.endsWith(":*")||s.endsWith(" *"))throw new l(`Invalid skill name ${t(s)}: wildcard-suffix names are not allowed; list each skill by its exact name.`,"wildcard-suffix skill name rejected");if(s.startsWith("/"))throw new l(`Invalid skill name ${t(s)}: skill names may not start with '/'. Skills are invoked as slash commands, but the skills option takes the skill's canonical name — the directory name, or 'plugin:skill'.`,"skill name with leading slash rejected");if(s.includes("\\\\"))throw new l(`Invalid skill name ${t(s)}: consecutive backslashes are not allowed — the permission-rule parser collapses escaped backslashes, so the rule would name a different skill. Rename the skill.`,"skill name with consecutive backslashes rejected");if(s.endsWith("\\"))throw new l(`Invalid skill name ${t(s)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return s}class br{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";exitListeners=[];abortHandler;forwardedAbort=tt();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(s){this.options=s;if(this.abortController=s.abortController||tt(),s.deferSpawn)this.spawnPromise=new Promise((c,u)=>{this.spawnResolve=c,this.spawnReject=u}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(c){throw this.spawnAbort(D(c)),c}let s=this.pendingWrites;if(this.pendingWrites=[],this.spawnResolve)this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0;for(let c of s)this.write(c);if(this.pendingEndInput)this.pendingEndInput=!1,this.processStdin?.end()}spawnAbort(s){if(this.spawnReject)this.spawnReject(s),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[]}updateEnv(s){if(this.options.env)Object.assign(this.options.env,s);else this.options.env={...s}}updateResume(s){this.options.resume=s}getDefaultExecutable(){return ie()?"bun":"node"}spawnLocalProcess(s){let{command:c,args:u,cwd:d,env:f,signal:p}=s,m=bi(c,u,{cwd:d,stdio:["pipe","pipe","pipe"],signal:p,env:f,windowsHide:!0}),y=new _i("utf8"),S=!1,w=!1,E=!1,v,k=o(f.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;m.stderr.on("data",(N)=>{if(E)return;let M=y.write(N);if(this.stderrTail+=M,this.stderrTail.length>2*hr)this.stderrTail=Qe(st(this.stderrTail),hr);if(k)oe(M),this.options.stderr?.(M)}),m.stderr.on("error",(N)=>{oe(`[ProcessTransport] stderr read failed: ${N.code??N.message}`)});let P=()=>{if(E)return;if(E=!0,v)clearTimeout(v);m.emit(Nn,m.exitCode,m.signalCode);let N=m.stderr;if(xi(N))N.unref();else N.destroy()};return m.stderr.once("close",()=>{if(this.stderrTail+=y.end(),S=!0,w)P()}),m.once("exit",()=>{if(w=!0,this.ready=!1,S)P();else v=setTimeout(P,ki)}),{stdin:m.stdin,stdout:m.stdout,get killed(){return m.killed},get exitCode(){return m.exitCode},get signalCode(){return m.signalCode},kill:m.kill.bind(m),on:(N,M)=>m.on(yr(N),M),once:(N,M)=>m.once(yr(N),M),off:(N,M)=>m.off(yr(N),M)}}initialize(){try{let{additionalDirectories:s=[],projectConfigRoot:c,agent:u,betas:d,cwd:f,executable:p=this.getDefaultExecutable(),executableArgs:m=[],extraArgs:y={},pathToClaudeCodeExecutable:S,env:w={...process.env},thinkingConfig:E,maxTurns:v,maxBudgetUsd:k,taskBudget:P,model:O,fallbackModel:N,jsonSchema:M,permissionMode:j,allowDangerouslySkipPermissions:Y,permissionPromptToolName:pe,permissionPrompts:K,continueConversation:B,resume:U,settingSources:F,skills:Z,disallowedTools:q=[],tools:he,mcpServers:Ee,strictMcpConfig:fe,canUseTool:ce,includePartialMessages:$e,plugins:Re,pluginsViaInitialize:It,sandbox:Qt}=this.options,{allowedTools:_e=[]}=this.options;if(Z!==void 0){let L=Z==="all"?["Skill"]:Z.map((ne)=>`Skill(${Ri(ne)})`),ue=new Set(_e);_e=[..._e,...L.filter((ne)=>!ue.has(ne))]}let T=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(E){switch(E.type){case"enabled":if(E.budgetTokens===void 0)T.push("--thinking","adaptive");else T.push("--max-thinking-tokens",E.budgetTokens.toString());break;case"disabled":T.push("--thinking","disabled");break;case"adaptive":T.push("--thinking","adaptive");break}if(E.type!=="disabled"&&E.display)T.push("--thinking-display",E.display)}if(this.options.effort)T.push("--effort",this.options.effort);if(v)T.push("--max-turns",v.toString());if(k!==void 0)T.push("--max-budget-usd",k.toString());if(P)T.push("--task-budget",P.total.toString());if(O)T.push("--model",O);if(u)T.push("--agent",u);if(d&&d.length>0)T.push("--betas",d.join(","));if(M)T.push("--json-schema",t(M));if(this.options.debugFile)T.push("--debug-file",this.options.debugFile);else if(this.options.debug)T.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let L=An();if(L)T.push("--debug-file",L)}if(ce){if(pe)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");T.push("--permission-prompt-tool","stdio")}else if(pe)T.push("--permission-prompt-tool",pe);if(K)T.push("--permission-prompts",K);if(B)T.push("--continue");if(U)T.push(`--resume=${U}`);if(this.options.channels&&this.options.channels.length>0)for(let L of this.options.channels)gr(T,"channels",L);if(_e.length>0)T.push("--allowedTools",_e.join(","));if(q.length>0)T.push("--disallowedTools",q.join(","));if(he!==void 0)if(Array.isArray(he))if(he.length===0)T.push("--tools","");else T.push("--tools",he.join(","));else T.push("--tools","default");if(Ee&&Object.keys(Ee).length>0)T.push("--mcp-config",t({mcpServers:Ee}));if(F!==void 0)T.push(`--setting-sources=${F.join(",")}`);if(fe)T.push("--strict-mcp-config");if(j)T.push("--permission-mode",j);if(Y)T.push("--allow-dangerously-skip-permissions");if(N){if(O&&N===O)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");T.push("--fallback-model",N)}if(this.options.includeHookEvents)T.push("--include-hook-events");if($e)T.push("--include-partial-messages");if(this.options.sessionMirror)T.push("--session-mirror");if(c!==void 0)T.push(`--project-config-root=${c}`);for(let L of s)T.push("--add-dir",L);if(It)T.push("--await-initialize");else if(Re&&Re.length>0)for(let L of Re)if(L.type==="local")T.push(L.skipMcpDiscovery?"--plugin-dir-no-mcp":"--plugin-dir",L.path);else throw Error(`Unsupported plugin type: ${L.type}`);if(this.options.forkSession)T.push("--fork-session");if(this.options.resumeSessionAt)T.push(`--resume-session-at=${this.options.resumeSessionAt}`);if(this.options.resumeDropsTurn!==void 0)T.push(`--resume-drops-turn=${this.options.resumeDropsTurn}`);if(this.options.sessionId)T.push(`--session-id=${this.options.sessionId}`);if(this.options.persistSession===!1)T.push("--no-session-persistence");if(this.options.managedSettings)T.push("--managed-settings",this.options.managedSettings);let Tt={...y??{}};if(this.options.settings)Tt.settings=this.options.settings;let At=On(Tt,Qt);for(let[L,ue]of Object.entries(At))if(ue===null)T.push(`--${L}`);else gr(T,L,ue);if(!w.CLAUDE_CODE_ENTRYPOINT)w.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete w.NODE_OPTIONS,o(w.DEBUG_CLAUDE_AGENT_SDK))w.DEBUG="1";else delete w.DEBUG;let He=Pi(S),We=He?S:p,qe=He?[...m,...T]:[...m,S,...T],Ve={command:We,args:qe,cwd:f,env:w,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)oe(`Spawning Claude Code (custom): ${We} ${qe.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(Ve);else oe(`Spawning Claude Code: ${We} ${qe.join(" ")}`),this.process=this.spawnLocalProcess(Ve);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(L)=>{oe(`[ProcessTransport] stdin write failed (child likely exited): ${L.code??L.message}`),this.ready=!1}),jt.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let Pe=this.process;Pe.on("error",(L)=>{this.ready=!1;let ue=L,ne=ue.syscall!==void 0?ue.syscall.startsWith("spawn"):Je(L);if(ne&&!Pe.killed)jt.untrack(Pe);if(this.abortController.signal.aborted)this.exitError=Ft(),b(L,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(ne&&Je(L)){let{message:Ie,telemetryMessage:Zt,errorClass:Mt}=Ii(S,He),de={telemetryMessage:`${Zt}${Sr(L)}`,errorClass:Mt,code:Te(L)};this.exitError=b(ReferenceError(Ie),de),b(L,de),oe(this.exitError.message)}else{let Ie={telemetryMessage:ne?`Failed to spawn Claude Code process${Sr(L)}`:`Claude Code process error${Sr(L)}`,errorClass:ne?"spawn_failed":"process_error",code:Te(L)};this.exitError=b(Error(`Failed to spawn Claude Code process: ${st(L.message)}`),Ie),b(L,Ie),oe(this.exitError.message)}}),Pe.on("exit",(L,ue)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=Ft();else{let ne=this.getProcessExitError(L,ue);if(ne)this.exitError=ne,oe(ne.message)}}),this.ready=!this.abortController.signal.aborted}catch(s){throw this.ready=!1,s}}getProcessExitError(s,c){if(s!==0&&s!==null){let u=Number.isInteger(s)?s:void 0;return b(Error(`Claude Code process exited with code ${s}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process exited with code ${u??"unknown"}`,errorClass:"process_exited_nonzero",exitCode:u})}else if(c){let u=/^SIG[A-Z0-9]{1,8}$/.test(c)?c:"unknown";return b(Error(`Claude Code process terminated by signal ${c}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process terminated by signal ${u}`,errorClass:"process_killed_by_signal",signal:u})}return}formatStderrTail(){let s=Qe(st(this.stderrTail),hr).trim();return s?`. stderr: ${s}`:""}write(s){if(this.abortController.signal.aborted)throw Mn();if(this.spawnResolve){this.pendingWrites.push(s);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){oe("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw b(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${lt(this.exitError)??"untagged exit error"}`,errorClass:Dn(this.exitError,"errorClass"),code:Te(this.exitError),exitCode:Ti(this.exitError),signal:Dn(this.exitError,"signal")});oe(`[ProcessTransport] Writing to stdin: ${s.substring(0,100)}`);try{if(!this.processStdin.write(s))oe("[ProcessTransport] Write buffer full, data queued")}catch(c){throw this.ready=!1,Error(`Failed to write to process stdin: ${R(c)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?Ft():Error("Query closed before spawn")),this.processStdin)this.processStdin.end(),this.processStdin=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;let s=this.process?.exitCode??null,c=this.process?.signalCode??null,u=!this.exitEventDelivered&&(s!==null&&s>=0||c!==null),d;if(u){if(this.exitEventDelivered=!0,d=this.abortController.signal.aborted?Ft():this.getProcessExitError(s,c),d&&!this.exitError)this.exitError=d}let f=this.exitListeners;this.exitListeners=[];for(let{callback:y,handler:S}of f)if(this.process?.off("exit",S),u)try{y(d)}catch(w){oe(`[ProcessTransport] onExit callback threw during close(): ${R(w)}`)}let p=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},m=this.process;if(m&&!m.killed&&m.exitCode===null&&m.signalCode==null)setTimeout((y,S)=>{if(y.exitCode!==null||y.signalCode!=null){S();return}if(process.platform==="win32"){setTimeout((w,E)=>{if(w.exitCode===null)w.kill("SIGKILL");E()},5000,y,S).unref();return}y.kill("SIGTERM"),setTimeout((w)=>{if(w.exitCode===null)w.kill("SIGKILL")},5000,y).unref(),S()},vi,m,p).unref(),m.once("exit",()=>jt.untrack(m));else if(m)jt.untrack(m),p();this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise)await this.spawnPromise,this.spawnPromise=void 0;if(!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let s=Ei({input:this.processStdout}),c=this.process?(()=>{let u=this.process,d=()=>s.close();return u.on("error",d),()=>u.off("error",d)})():void 0;if(this.exitError)s.close();try{for await(let u of s)if(u.trim()){let d;try{d=A(u)}catch(f){oe(`Non-JSON stdout: ${u}`);continue}yield d}if(this.exitError)throw this.exitError;await this.waitForExit()}finally{c?.(),s.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}if(this.processStdin)this.processStdin.end()}onExit(s){if(!this.process)return()=>{};let c=(u,d)=>{let f=this.getProcessExitError(u,d);s(f)};return this.process.on("exit",c),this.exitListeners.push({callback:s,handler:c}),()=>{if(this.process)this.process.off("exit",c);let u=this.exitListeners.findIndex((d)=>d.handler===c);if(u!==-1)this.exitListeners.splice(u,1)}}async waitForExit(){if(this.exitError)throw this.exitError;if(!this.process||this.process.exitCode===0||this.process.killed&&this.exitEventDelivered)return;return new Promise((s,c)=>{let u=(f,p)=>{if(this.abortController.signal.aborted){c(Mn());return}let m=this.getProcessExitError(f,p);if(m)c(m);else s()};this.process.once("exit",u);let d=(f)=>{this.process.off("exit",u),c(f)};this.process.once("error",d),this.process.once("exit",()=>{this.process.off("error",d)})})}}function Pi(s){return![".js",".mjs",".tsx",".ts",".jsx"].some((u)=>s.endsWith(u))}function Ii(s,c){let u=c?"native binary":"executable",d=st(s);if(wi(s))return{message:c?`Claude Code native binary at ${d} exists but failed to launch. This usually means the binary does not match this system's libc — e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${d} exists but failed to launch.`,telemetryMessage:`Claude Code ${u} exists at the configured path but failed to launch`,errorClass:"executable_launch_failed"};return{message:c?`Claude Code native binary not found at ${d}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${d}. Is options.pathToClaudeCodeExecutable set?`,telemetryMessage:`Claude Code ${u} not found at the configured path`,errorClass:"executable_not_found"}}function Sr(s){let c=Te(s);return c===void 0?"":` (${c})`}function Ft(){return b(new Q("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function Mn(){return b(new Q("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function Dn(s,c){let u=Object.hasOwn(s,c)?Reflect.get(s,c):void 0;return typeof u==="string"?u:void 0}function Ti(s){let c=Object.hasOwn(s,"exitCode")?Reflect.get(s,"exitCode"):void 0;return typeof c==="number"?c:void 0}function xi(s){return typeof Reflect.get(s,"unref")==="function"}import{existsSync as Ai}from"fs";var Ne="@anthropic-ai/claude-agent-sdk";function Oi(){if(process.platform!=="linux")return!1;let s=typeof process.report?.getReport==="function"?process.report.getReport():null;return s!=null&&s.header?.glibcVersionRuntime===void 0}function jn(s,c={}){let u=c.platform??process.platform,d=c.arch??process.arch,f=c.exists??Ai,p=c.preferMusl??Oi(),m="claude",y=u==="win32"?".exe":"",w=(u==="android"?[`${Ne}-linux-${d}-android`]:u==="linux"?p?[`${Ne}-linux-${d}-musl`,`${Ne}-linux-${d}`]:[`${Ne}-linux-${d}`,`${Ne}-linux-${d}-musl`]:[`${Ne}-${u}-${d}`]).map((E)=>`${E}/claude${y}`);for(let E of w)try{let v=s(E);if(f(v))return v}catch{}return null}var Mi=["signed_out","identity_changed","transient","refresh_failed"];function Fn(s){return Mi.some((c)=>c===s)}class wr{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(s){this.returned=s}get ended(){return this.isDone}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((s,c)=>{this.readResolve=s,this.readReject=c})}enqueue(s){if(this.readResolve){let c=this.readResolve;this.readResolve=void 0,this.readReject=void 0,c({done:!1,value:s})}else this.queue.push(s)}done(){if(this.isDone=!0,this.readResolve){let s=this.readResolve;this.readResolve=void 0,this.readReject=void 0,s({done:!0,value:void 0})}}error(s){if(this.hasError=s,this.readReject){let c=this.readReject;this.readResolve=void 0,this.readReject=void 0,c(s)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}function Er(s,c){W("tengu_feature_ok",{feature_name:G(s),...c})}function Di(s,c,u){W("tengu_feature_bad",{...u,feature_name:G(s),error_code:Xe(c)})}function Kt(s,c,u){W("tengu_feature_sad",{...u,feature_name:G(s),error_code:Xe(c)})}async function X(s,c,u){try{let d=await c();return Er(s),d}catch(d){throw Di(s,u?.(d)??"error"),d}}function Kn(s){return"method"in s&&"id"in s&&s.id!==null}var Bn=Object.freeze({}),Un=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),_u=Symbol("swallow");class _r{sendMcpMessage;isClosed=!1;constructor(s){this.sendMcpMessage=s}onclose;onerror;onmessage;async start(){}async send(s){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(s)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var $n=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var Hn="2025-11-25";var Ni="notifications/tools/list_changed";function Gn(s){return r(s)&&!("id"in s)&&s.method===Ni}function dt(s){return typeof s==="number"&&Number.isInteger(s)&&s>0?s:void 0}var Wn=250,Bt="sdk-manifest-capture:",Le=Symbol("suppressControlResponse");class Ut{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new wr;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;lastErrorResultText;latestCommands;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(s){this.isSingleUserTurn=s}setTranscriptMirrorBatcher(s){this.transcriptMirrorBatcher=s}reportMirrorError(s,c){let u={type:"system",subtype:"mirror_error",error:c,key:s,uuid:Ae(),session_id:s.sessionId};this.inputStream.enqueue(u)}addCleanupCallback(s){if(this.cleanupPerformed)s();else this.cleanupCallbacks.push(s)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpServers.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0||this.workSecretAnswerer!==void 0}remoteControlCallGeneration=0;workSecretAnswerer;constructor(s,c,u,d,f,p=new Map,m,y,S,w,E,v,k=!1){this.transport=s;this.isSingleUserTurn=c;this.canUseTool=u;this.hooks=d;this.abortController=f;this.jsonSchema=m;this.initConfig=y;this.onElicitation=S;this.getOAuthToken=w;this.getHostAuthToken=E;this.onUserDialog=v;this.verbatimPrompts=k;for(let[P,O]of p)this.connectSdkMcpServer(P,O);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((P)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,P()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{})}setError(s){this.inputStream.error(s)}async stopTask(s){await this.request({subtype:"stop_task",task_id:s})}async backgroundTasks(s){return(await this.request({subtype:"background_tasks",tool_use_id:s})).response.backgrounded??!0}close(){this.cleanup()}cleanup(s){if(this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=s,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(s),this.cleanupPromise}async performCleanup(s){for(let c of this.cleanupCallbacks)try{c()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let c of this.cancelControllers.values())c.abort();this.cancelControllers.clear(),this.transport.close()}catch(c){e(`[Query.cleanup] transport.close() failed: ${R(c)}`,{level:"error"})}try{let c=s??vr();for(let{reject:u}of this.pendingControlResponses.values())u(c);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:u}of this.pendingMcpResponses.values())u(c);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:u}of this.sdkMcpServers.values())u.close().catch(()=>{});if(this.sdkMcpServers.clear(),s)this.inputStream.error(s);else this.inputStream.done()}catch(c){}if(this.transport.waitForExit){let c=new AbortController;try{await Promise.race([this.transport.waitForExit(),I(2000,c.signal)])}catch{}finally{c.abort()}}}next(...[s]){return this.sdkMessages.next(...[s])}async return(s){return await this.cleanup(),this.sdkMessages.return(s)}async throw(s){return await this.cleanup(),this.sdkMessages.throw(s)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let s of this.transport.readMessages()){if(s.type==="control_response"){let c=this.pendingControlResponses.get(s.response.request_id);if(c)c.handler(s.response);else{if(this.unmatchedControlResponses.size>=Ut.UNMATCHED_CONTROL_RESPONSES_MAX){let u=this.unmatchedControlResponses.keys().next().value;if(u!==void 0)this.unmatchedControlResponses.delete(u)}this.unmatchedControlResponses.set(s.response.request_id,s.response)}continue}else if(s.type==="control_request"){this.handleControlRequest(s);continue}else if(s.type==="control_cancel_request"){this.handleControlCancelRequest(s);continue}else if(s.type==="keep_alive")continue;else if(s.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(s.filePath,s.entries);continue}if(s.type==="system"&&s.subtype==="commands_changed"&&Array.isArray(s.commands))this.latestCommands=s.commands;if(s.type==="system"&&(s.subtype==="post_turn_summary"||s.subtype==="task_summary"||s.subtype==="session_metadata")){this.inputStream.enqueue(s);continue}if(s.type==="active_goal"){this.inputStream.enqueue(s);continue}if(s.type==="autocompact_state"){this.inputStream.enqueue(s);continue}if(s.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let c=s.is_error?s.subtype==="success"?s.result:s.errors.map((u)=>u.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=c||void 0,this.firstResultReceived=!0,this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.isSingleUserTurn)e("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput()}else if(!(s.type==="system"&&s.subtype==="session_state_changed"))this.lastErrorResultText=void 0;this.inputStream.enqueue(s)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(s){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.lastErrorResultText!==void 0&&!(s instanceof Q)&&s?.name!=="SSEHttpError"){let c=b(Error(`Claude Code returned an error result: ${this.lastErrorResultText}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});e(`[Query.readMessages] Replacing exit error with result text. Original: ${R(s)}`),this.inputStream.error(c),this.cleanup(c);return}this.inputStream.error(s),this.cleanup(s)}}async handleControlRequest(s){if(this.cleanupPerformed){e(`[Query.handleControlRequest] Request ${s.request_id} (${s.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(s.request_id)){e(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${s.request_id} (${s.request.subtype}) — skipping`);return}let c=new AbortController;this.cancelControllers.set(s.request_id,c);try{let u;try{let d=await this.processControlRequest(s,c.signal);if(this.cleanupPerformed)return;if(d===Le)return;let f={type:"control_response",response:{subtype:"success",request_id:s.request_id,response:d}};u=t(f)+`
28
+ `}catch(d){if(this.cleanupPerformed)return;let f={type:"control_response",response:{subtype:"error",request_id:s.request_id,error:R(d)}};u=t(f)+`
29
+ `}try{await Promise.resolve(this.transport.write(u))}catch(d){e(`[Query.handleControlRequest] Response write failed: ${R(d)}`,{level:"error"})}}finally{if(this.cancelControllers.get(s.request_id)===c)this.cancelControllers.delete(s.request_id)}}handleControlCancelRequest(s){let c=this.cancelControllers.get(s.request_id);if(c)c.abort(),this.cancelControllers.delete(s.request_id)}async processControlRequest(s,c){if($n.some((u)=>u===s.request.subtype))return e(`[Query.processControlRequest] ${s.request.subtype} ${s.request_id} is for the machine serving this session's tools — leaving it unanswered`),Le;if(s.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let u=s.request.computer_folder,d=await this.canUseTool(s.request.tool_name,s.request.input,{signal:c,suggestions:s.request.permission_suggestions,blockedPath:s.request.blocked_path,...s.request.mcp_server&&{mcpServer:{name:s.request.mcp_server.name,source:s.request.mcp_server.source}},decisionReason:s.request.decision_reason,title:s.request.title,displayName:s.request.display_name,description:s.request.description,defaultToNo:s.request.default_to_no,suppressAlwaysAllowRule:s.request.suppress_always_allow_rule,toolUseID:s.request.tool_use_id,agentID:s.request.agent_id,requestId:s.request_id,...typeof s.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:s.request.requires_user_interaction},...typeof s.request.server_prompt==="string"&&{serverPrompt:s.request.server_prompt},...typeof u==="object"&&u!==null&&"path"in u&&typeof u.path==="string"&&"computer_name"in u&&typeof u.computer_name==="string"&&{computerFolder:{path:u.path,computer_name:u.computer_name}},...s.request.matched_ask_rule&&{matchedAskRule:{source:s.request.matched_ask_rule.source,toolName:s.request.matched_ask_rule.tool_name,...s.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:s.request.matched_ask_rule.rule_content}}}});if(d===null)return Le;return{...d,toolUseID:s.request.tool_use_id}}else if(s.request.subtype==="hook_callback")return await this.handleHookCallbacks(s.request.callback_id,s.request.input,s.request.tool_use_id,c);else if(s.request.subtype==="mcp_message"){let u=s.request,d=this.sdkMcpServers.get(u.server_name)?.transport;if(!d)throw Error(`SDK MCP server not found: ${u.server_name}`);if(Kn(u.message))return{mcp_response:await this.handleMcpControlRequest(u.server_name,u,d)};else{if(d.onmessage)d.onmessage(u.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(s.request.subtype==="elicitation"){let u=s.request;if(this.onElicitation){let d=await this.onElicitation({serverName:u.mcp_server_name,message:u.message,mode:u.mode,url:u.url,elicitationId:u.elicitation_id,requestedSchema:u.requested_schema,title:u.title,displayName:u.display_name,description:u.description},{signal:c,requestId:s.request_id});if(d===null)return Le;return d}return{action:"decline"}}else if(s.request.subtype==="request_user_dialog"){if(this.onUserDialog){let u=await this.onUserDialog({dialogKind:s.request.dialog_kind,payload:s.request.payload,toolUseID:s.request.tool_use_id},{signal:c,requestId:s.request_id});if(u===null)return Le;return u}return e(`[Query] No onUserDialog handler for request_user_dialog (kind=${s.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),W("tengu_request_user_dialog_response_ignored",{shape:G("auto_cancel")}),Le}else if(s.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let u,d=await this.getOAuthToken({signal:c,onDecline:(f)=>{if(Fn(f))u=f}})??null;return d===null&&u!==void 0?{accessToken:d,reason:u}:{accessToken:d}}else if(s.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let u=await this.getHostAuthToken({signal:c})??null;return typeof u==="string"||u===null?{authToken:u}:u}else if(s.request.subtype==="remote_control_work_secret"){let u=this.workSecretAnswerer;if(!u)throw Error("refreshWorkSecret callback is not provided.");if(!qn(u.sessionId,s.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await u.refresh(u.sessionId,{signal:c})||null}}throw Error("Unsupported control request subtype: "+s.request.subtype)}async*readSdkMessages(){try{for await(let s of this.inputStream)this.transport.markDelivered?.(s),yield s}finally{await this.cleanup()}}async initialize({first:s}={first:!1}){if(!s&&!this.initializeHasBeenWritten)await this.initializeWritten;let c,u;try{if(s&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){c=await this.captureSdkMcpServerManifests();for(let m of this.sdkMcpToolsChangedDuringCapture){let y=c!==void 0&&Object.hasOwn(c,m)?c[m]:void 0;if(y?.toolsListResult!==void 0)c[m]={initializeResult:y.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let p=this.buildInitializeRequest(c);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=s;try{u=this.request(p)}finally{this.writingFirstInitialize=!1}}finally{if(s)this.markInitializeWritten()}let f=(await u).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&f.plugins_applied!==!0)e(`[Query.initialize] Claude Code reported plugins_applied=${String(f.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return f}buildInitializeRequest(s){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[p,m]of Object.entries(this.hooks))if(m.length>0)this.initHooksPayload[p]=m.map((y)=>{let S=[];for(let w of y.hooks){let E=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(E,w),S.push(E)}return{matcher:y.matcher,hookCallbackIds:S,timeout:y.timeout}})}let c=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,u=Array.from(this.sdkMcpServers).flatMap(([p,{timeout:m}])=>m!==void 0?[[p,{timeout:m}]]:[]),d=u.length>0?Object.fromEntries(u):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:c,sdkMcpServerConfigs:d,sdkMcpServerManifests:s,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let s=performance.now(),c=new Map,u=!1,d=async(v,k)=>{try{if(await this.sdkMcpServers.get(v)?.connection,u)return;let P=await this.handleMcpControlRequest(v,{server_name:v,message:{jsonrpc:"2.0",id:Bt+"initialize",method:"initialize",params:{protocolVersion:Hn,capabilities:Bn,clientInfo:{...Un,version:"0.3.282"}}}},k);if(u)return;if(!("result"in P)){e(`[Query.captureSdkMcpServerManifests] '${v}' answered initialize with an error; leaving it to the CLI: ${t(P)}`,{level:"warn"});return}let O=P.result;k.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let N=O.capabilities,M=typeof N==="object"&&N!==null&&"tools"in N&&N.tools!==void 0&&N.tools!==null,j;if(M){let K=await this.handleMcpControlRequest(v,{server_name:v,message:{jsonrpc:"2.0",id:Bt+"tools-list",method:"tools/list"}},k);if(u)return;if(!("result"in K)){e(`[Query.captureSdkMcpServerManifests] '${v}' answered tools/list with an error; leaving it to the CLI: ${t(K)}`,{level:"warn"});return}if(K.result.nextCursor===void 0)j=K.result}let pe=A(t(j===void 0?{initializeResult:O}:{initializeResult:O,toolsListResult:j}));c.set(v,{transport:k,manifest:pe})}catch(P){if(!u)e(`[Query.captureSdkMcpServerManifests] '${v}': ${P}; the CLI will handshake it over the control channel`,{level:"warn"})}},f=Array.from(this.sdkMcpServers,([v,{transport:k}])=>d(v,k)),p=Promise.all(f).then(()=>"settled"),m=new Promise((v)=>{this.stopSdkMcpManifestCapture=()=>v("closed")}),y=await ut(Promise.race([p,m]),Wn);u=!0,this.stopSdkMcpManifestCapture=void 0;let S=Math.round(performance.now()-s),w={servers:f.length,captured:c.size,elapsed_ms:S};if(y==="closed"){Kt("sdk_mcp_manifest_capture","closed",w);return}if(y===void 0)e(`[Query.captureSdkMcpServerManifests] ${c.size}/${f.length} in-process MCP servers captured within ${Wn} ms; the rest will handshake over the control channel`,{level:"warn"}),Kt("sdk_mcp_manifest_capture","deadline",w);else if(c.size<f.length)Kt("sdk_mcp_manifest_capture","partial",w);else Er("sdk_mcp_manifest_capture",w);if(c.size===0)return;let E=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([v,k])=>{let P=c.get(v);return P!==void 0&&P.transport===k.transport?[[v,P.manifest]]:[]}));if(Object.keys(E).length===0)return;return e(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(E).join(", ")}] captured in ${S} ms`),E}async interrupt(s){return X("sdk_interrupt",async()=>{let c=await this.request({subtype:"interrupt",...s?.cancelQueued===!0&&{cancel_queued:!0}}),u=c.response?.still_queued;if(!Array.isArray(u))return;let d=c.response?.cancelled;return{still_queued:u.filter((f)=>typeof f==="string"),...Array.isArray(d)&&{cancelled:d.filter((f)=>typeof f==="string")}}})}async setPermissionMode(s){await this.request({subtype:"set_permission_mode",mode:s})}async setMcpPermissionModeOverride(s,c){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:s,mode:c})).response??{}}async setChromeBrowserHints(s){await this.request({subtype:"set_chrome_browser_hints",...s})}async setPromptSuggestionsPaused(s){await this.request({subtype:"set_prompt_suggestions_paused",paused:s})}awaitControlResponse(s){return this.transport.expectControlResponse?.(s),new Promise((c,u)=>{let d=(p)=>{if(p.subtype==="success"){let{pending_permission_requests:m,pending_user_dialog_requests:y,...S}=p;c(S)}else u(new l(p.error,"awaitControlResponse: CLI error verdict"));if(p.pending_permission_requests||p.pending_user_dialog_requests)e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){u(vr());return}let f=this.unmatchedControlResponses.get(s);if(f){this.unmatchedControlResponses.delete(s),d(f);return}this.pendingControlResponses.set(s,{handler:(p)=>{this.pendingControlResponses.delete(s),d(p)},reject:u})})}async setModel(s){await this.request({subtype:"set_model",model:s})}async setMaxThinkingTokens(s,c){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:s,thinking_display:c})}async applyFlagSettings(s){return X("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:s})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(s,c){return X("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:s,settings:c})})}async rewindFiles(s,c){return X("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:s,dry_run:c?.dryRun})).response)}async cancelAsyncMessage(s){return(await this.request({subtype:"cancel_async_message",message_uuid:s})).response.cancelled}async seedReadState(s,c){await this.request({subtype:"seed_read_state",path:s,mtime:c})}async setCwd(s,c){return X("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:s,...c?.trustAccepted!==void 0&&{trust_accepted:c.trustAccepted},...c?.trustedDirectory!==void 0&&{trusted_directory:c.trustedDirectory}})).response)}async claimSession(s){let c=X("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...s,include_initialize:s.include_initialize??!0})).response),u=this.initialization;return this.initialization=c.then(async(d)=>{if(d?.initialize===void 0)return u;let f=d.initialize,p=await u.then((S)=>({hooks_applied:S.hooks_applied,plugins_applied:S.plugins_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0})),m=f.hooks_applied??p.hooks_applied,y=f.plugins_applied??p.plugins_applied;return{...f,...m!==void 0&&{hooks_applied:m},...y!==void 0&&{plugins_applied:y}}},()=>u),this.initialization.catch(()=>{}),c}async enableRemoteControl(s,c,u){let d=++this.remoteControlCallGeneration,f=this.workSecretAnswerer,p=u?.reattachSessionId||(u?.workSecret===void 0?void 0:Li(u.workSecret)),m=s&&u?.workSecret!==void 0&&u.refreshWorkSecret&&p!==void 0?{sessionId:p,refresh:u.refreshWorkSecret}:void 0;this.workSecretAnswerer=m;let y;try{y=(await this.request({subtype:"remote_control",enabled:s,...c!==void 0&&{name:c},reattach_session_id:u?.reattachSessionId,keep_session_on_exit:u?.keepSessionOnExit,work_secret:u?.workSecret})).response}catch(S){if(d===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw S}if(s&&d===this.remoteControlCallGeneration){let S=y.bridge_session_id,w=[m,f];this.workSecretAnswerer=typeof S==="string"?w.find((E)=>E!==void 0&&qn(E.sessionId,S)):void 0}return y}async submitFeedback(s,c){return(await this.request({subtype:"submit_feedback",description:s,surface:c?.surface,draft_id:c?.draft_id,type:c?.type,title:c?.title,area:c?.area,attach_transcript:c?.attach_transcript})).response}async renameSession(s,c){await this.request({subtype:"rename_session",title:s,source:"host",session_id:c})}async generateSessionTitle(s,c){return X("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:s,persist:c?.persist})).response.title)}async askSideQuestion(s,c){return X("sdk_side_question",async()=>{let d=(await this.request({subtype:"side_question",question:s,...c?.history?.length&&{history:[...c.history]}},c)).response;return d.response===null?null:{response:d.response,synthetic:d.synthetic??!1,...d.refusal_fallback&&{refusalFallback:{originalModel:d.refusal_fallback.original_model,fallbackModel:d.refusal_fallback.fallback_model,content:d.refusal_fallback.content}}}},()=>c?.signal?.aborted?"cancelled":"error")}async launchUltrareview(s,c){return(await this.request({subtype:"ultrareview_launch",args:s,confirm:c?.confirm??!1})).response}async messageRated(s){await this.request({subtype:"message_rated",messageUuid:s.messageUuid,sentiment:s.sentiment,surface:s.surface,cleared:s.cleared??!1})}processPendingPermissionRequests(s){for(let c of s)if(c.request.subtype==="can_use_tool")this.handleControlRequest(c).catch(()=>{})}processPendingUserDialogRequests(s){for(let c of s)if(c.request.subtype==="request_user_dialog")this.handleControlRequest(c).catch(()=>{})}request(s,c){let u=c?.signal;if(u?.aborted)return Promise.reject(D(u.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(vr());let d=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(d);let f={request_id:d,type:"control_request",request:s},p=s.subtype==="initialize";return new Promise((m,y)=>{let S,w=!1,E=(O)=>{this.pendingControlResponses.delete(d),S?.(),m(O)},v=(O)=>{this.pendingControlResponses.delete(d),S?.(),y(O)};if(u){let O=()=>{if(v(D(u.reason??"Control request aborted")),!w)return;try{Promise.resolve(this.transport.write(t({type:"control_cancel_request",request_id:d})+`
30
+ `)).catch(()=>{})}catch{}};u.addEventListener("abort",O,{once:!0}),S=()=>{u.removeEventListener("abort",O)}}this.pendingControlResponses.set(d,{handler:(O)=>{if(O.subtype==="success")E(O);else v(b(Error(O.error),{telemetryMessage:`Claude Code control request failed (${s.subtype})`,errorClass:"control_request_failed"}));if(!p&&(O.pending_permission_requests||O.pending_user_dialog_requests))e(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${s.subtype})`);else{if(O.pending_permission_requests)this.processPendingPermissionRequests(O.pending_permission_requests);if(O.pending_user_dialog_requests)this.processPendingUserDialogRequests(O.pending_user_dialog_requests)}},reject:v});let k=t(f)+`
31
+ `,P=()=>{if(u?.aborted)return;return w=!0,this.transport.write(k)};try{(this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(P()):this.initializeWritten.then(P)).catch(v)}catch(O){v(O)}})}initializationResult(){return this.initialization}writeAfterInitialize(s){if(this.initializeHasBeenWritten)return Promise.resolve(this.transport.write(s));return this.initializeWritten.then(()=>this.transport.write(s))}reinitialize(){return X("sdk_reinitialize",()=>this.initialize({first:!1}))}async supportedCommands(){let{commands:s}=await this.initialization;return this.latestCommands??s}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(s){await this.request({subtype:"mcp_reconnect",serverName:s})}async toggleMcpServer(s,c){return X("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:s,enabled:c})})}async readMcpResource(s,c){return(await this.request({subtype:"mcp_read_resource",serverName:s,uri:c})).response}async enableChannel(s){return X("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:s})})}async mcpAuthenticate(s,c){return(await this.request({subtype:"mcp_authenticate",serverName:s,redirectUri:c})).response}async mcpClearAuth(s){return(await this.request({subtype:"mcp_clear_auth",serverName:s})).response}async mcpSubmitOAuthCallbackUrl(s,c){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:s,callbackUrl:c})).response}async claudeAuthenticate(s){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:s})).response}async claudeOAuthCallback(s,c){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:s,state:c})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(s){return(await this.request({subtype:"get_context_usage",...s})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(s){return(await this.request({subtype:"get_usage",...s?.skipBehaviors&&{skip_behaviors:!0}})).response}async getMemoryDialog(){return(await this.request({subtype:"get_memory_dialog"})).response}async getSkillsDialog(){return(await this.request({subtype:"get_skills_dialog"})).response}async getStatus(){return(await this.request({subtype:"get_status"})).response}async exportConversation(){return(await this.request({subtype:"export_conversation"})).response}async getChromeDialog(){return(await this.request({subtype:"get_chrome_dialog"})).response}async getChromeBrowsers(){return(await this.request({subtype:"get_chrome_browsers"})).response}async selectChromeBrowser(s){return(await this.request({subtype:"select_chrome_browser",device_id:s})).response}async getSandboxDialog(){return(await this.request({subtype:"get_sandbox_dialog"})).response}async readFile(s,c){try{return(await this.request({subtype:"read_file",path:s,max_bytes:c?.maxBytes,encoding:c?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(s){return X("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...s?.holdOnCacheImpact&&{hold_on_cache_impact:!0}})).response)}async reloadSkills(){return X("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return X("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(s){return X("sdk_mcp_set_servers",async()=>{let c={},u={};for(let[y,S]of Object.entries(s))if(S.type==="sdk"&&"instance"in S)c[y]=S;else u[y]=S;let d=new Set(this.sdkMcpServers.keys()),f=new Set(Object.keys(c));for(let y of d)if(!f.has(y))await this.disconnectSdkMcpServer(y);for(let[y,S]of Object.entries(c)){let w=this.sdkMcpServers.get(y);if(!w)this.connectSdkMcpServer(y,S);else if(dt(S.timeout)!==w.timeout)e(`[Query.setMcpServers] MCP server '${y}' is already registered; its timeout change is ignored until the server is removed and re-added`)}let p={};for(let y of Object.keys(c)){let S=this.sdkMcpServers.get(y)?.timeout;p[y]={type:"sdk",name:y,...S!==void 0&&{timeout:S}}}return(await this.request({subtype:"mcp_set_servers",servers:{...u,...p}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(s){e("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let c=0;for await(let u of s){if(c++,e(`[Query.streamInput] Processing message ${c}: ${u.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(t(this.verbatimPrompts?{...u,client_composed:!0}:u)+`
32
+ `))}if(e(`[Query.streamInput] Finished processing ${c} messages from input stream`),c>0&&this.hasBidirectionalNeeds())e("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult();e("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(c){if(!(c instanceof Q))throw c}}waitForFirstResult(){if(this.firstResultReceived)return e("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve();return new Promise((s)=>{let c=this.abortController?.signal;if(this.cleanupPerformed||c?.aborted){s();return}let u=()=>s();c?.addEventListener("abort",u,{once:!0}),this.addCleanupCallback(()=>{c?.removeEventListener("abort",u),s()}),this.firstResultReceivedResolve=()=>{c?.removeEventListener("abort",u),s()}})}handleHookCallbacks(s,c,u,d){let f=this.hookCallbacks.get(s);if(!f)throw Error(`No hook callback found for ID: ${s}`);return f(c,u,{signal:d})}connectSdkMcpServer(s,c){let u=new _r((f)=>this.sendMcpServerMessageToCli(s,f)),d=c.instance.connect(u).catch((f)=>{if(this.sdkMcpServers.get(s)?.transport===u)this.sdkMcpServers.delete(s);e(`[Query.connectSdkMcpServer] Failed to connect MCP server '${s}': ${f}`,{level:"error"})});this.sdkMcpServers.set(s,{transport:u,timeout:dt(c.timeout),connection:d})}async disconnectSdkMcpServer(s){let c=this.sdkMcpServers.get(s);if(c){let u=`${s}:${Bt}`;for(let[d,f]of this.pendingMcpResponses)if(d.startsWith(u))this.pendingMcpResponses.delete(d),f.reject(Error("MCP server was removed during the manifest capture"));if(await c.transport.close(),this.sdkMcpServers.get(s)===c)this.sdkMcpServers.delete(s)}}sendMcpServerMessageToCli(s,c){if("id"in c&&c.id!==null&&c.id!==void 0){let d=`${s}:${c.id}`,f=this.pendingMcpResponses.get(d);if(f){f.resolve(c),this.pendingMcpResponses.delete(d);return}if(typeof c.id==="string"&&c.id.startsWith(Bt)){e(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${s}' (${c.id})`);return}}let u={type:"control_request",request_id:Ae(),request:{subtype:"mcp_message",server_name:s,message:c}};if(!this.initializeHasBeenWritten&&Gn(c))this.sdkMcpToolsChangedDuringCapture.add(s);this.writeAfterInitialize(t(u)+`
33
+ `).catch((d)=>{e(`[Query.sendMcpServerMessageToCli] Transport write failed: ${d}`,{level:"error"})})}handleMcpControlRequest(s,c,u){let d="id"in c.message?c.message.id:null,f=`${s}:${d}`;return new Promise((p,m)=>{let y=()=>{this.pendingMcpResponses.delete(f)},S=(E)=>{y(),p(E)},w=(E)=>{y(),m(E)};if(this.pendingMcpResponses.set(f,{resolve:S,reject:w}),u.onmessage)u.onmessage(c.message);else{y(),m(Error("No message handler registered"));return}})}}function vr(){return Error("Query closed before response received")}function qn(s,c){if(s===c)return!0;let u=s.slice(s.lastIndexOf("_")+1),d=c.slice(c.lastIndexOf("_")+1);return u.length>=4&&u===d}function Li(s){try{let c=A(Buffer.from(s,"base64url").toString("utf8"));if(typeof c!=="object"||c===null||!("session_ingress_token"in c)||typeof c.session_ingress_token!=="string")return;let u=c.session_ingress_token,f=(u.startsWith("sk-ant-si-")?u.slice(10):u).split(".");if(f.length!==3||!f[1])return;let p=A(Buffer.from(f[1],"base64url").toString("utf8"));return typeof p==="object"&&p!==null&&"session_id"in p&&typeof p.session_id==="string"&&p.session_id?p.session_id:void 0}catch{return}}var kr=500,Cr=1048576;var ji=[200,800];class Rr{send;pending=[];pendingEntries=0;pendingBytes=0;flushPromise=null;sendTimeoutMs;onError;maxPendingEntries;maxPendingBytes;backoffMs;constructor(s,c){this.send=s;let{sendTimeoutMs:u=60000,onError:d,maxPendingEntries:f=kr,maxPendingBytes:p=Cr,backoffMs:m=ji}=c??{};this.sendTimeoutMs=u,this.onError=d,this.maxPendingEntries=f,this.maxPendingBytes=p,this.backoffMs=m}enqueue(s,c){let u=t(c).length;if(this.pending.push({filePath:s,entries:c,bytes:u}),this.pendingEntries+=c.length,this.pendingBytes+=u,this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)this.flushPromise=this.drain(),this.flushPromise.catch(()=>{})}async flush(){let s=this.drain();if(this.flushPromise=s,await s,this.flushPromise===s)this.flushPromise=null}async drain(){let s=this.flushPromise,c=this.pending.splice(0);if(this.pendingEntries=0,this.pendingBytes=0,s)await s;if(c.length===0)return;await this.doFlush(c)}async doFlush(s){let c=new Map;for(let u of s){let d=c.get(u.filePath);if(d)d.push(...u.entries);else c.set(u.filePath,u.entries.slice())}for(let[u,d]of c)await this.sendWithRetry(u,d)}async sendWithRetry(s,c){let u=this.backoffMs.length+1,d=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${s}`,f,p=1;for(;p<=u;p++)try{await x(this.send(s,c),this.sendTimeoutMs,d),f=void 0;break}catch(m){if(f=D(m),f.message===d)break;let y=this.backoffMs[p-1];if(y===void 0)break;await I(y)}if(f){e(`[TranscriptMirrorBatcher] flush failed for ${s} after ${p} attempt(s): ${f}`,{level:"error"});try{this.onError?.(s,f)}catch(m){e(`[TranscriptMirrorBatcher] onError callback threw: ${m}`,{level:"error"})}}}}var zn=typeof globalThis==="object"?globalThis:global;var ye="1.9.0";var Vn=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Fi(s){var c=new Set([s]),u=new Set,d=s.match(Vn);if(!d)return function(){return!1};var f={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};if(f.prerelease!=null)return function(S){return S===s};function p(y){return u.add(y),!1}function m(y){return c.add(y),!0}return function(S){if(c.has(S))return!0;if(u.has(S))return!1;var w=S.match(Vn);if(!w)return p(S);var E={major:+w[1],minor:+w[2],patch:+w[3],prerelease:w[4]};if(E.prerelease!=null)return p(S);if(f.major!==E.major)return p(S);if(f.major===0){if(f.minor===E.minor&&f.patch<=E.patch)return m(S);return p(S)}if(f.minor<=E.minor)return m(S);return p(S)}}var Yn=Fi(ye);var Ki=ye.split(".")[0],pt=Symbol.for("opentelemetry.js.api."+Ki),yt=zn;function je(s,c,u,d){var f;if(d===void 0)d=!1;var p=yt[pt]=(f=yt[pt])!==null&&f!==void 0?f:{version:ye};if(!d&&p[s]){var m=Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return u.error(m.stack||m.message),!1}if(p.version!==ye){var m=Error("@opentelemetry/api: Registration of version v"+p.version+" for "+s+" does not match previously registered API v"+ye);return u.error(m.stack||m.message),!1}return p[s]=c,u.debug("@opentelemetry/api: Registered a global for "+s+" v"+ye+"."),!0}function Se(s){var c,u,d=(c=yt[pt])===null||c===void 0?void 0:c.version;if(!d||!Yn(d))return;return(u=yt[pt])===null||u===void 0?void 0:u[s]}function Fe(s,c){c.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+ye+".");var u=yt[pt];if(u)delete u[s]}var Bi=function(s,c){var u=typeof Symbol==="function"&&s[Symbol.iterator];if(!u)return s;var d=u.call(s),f,p=[],m;try{while((c===void 0||c-- >0)&&!(f=d.next()).done)p.push(f.value)}catch(y){m={error:y}}finally{try{if(f&&!f.done&&(u=d.return))u.call(d)}finally{if(m)throw m.error}}return p},Ui=function(s,c,u){if(u||arguments.length===2){for(var d=0,f=c.length,p;d<f;d++)if(p||!(d in c)){if(!p)p=Array.prototype.slice.call(c,0,d);p[d]=c[d]}}return s.concat(p||Array.prototype.slice.call(c))},Jn=function(){function s(c){this._namespace=c.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){var c=[];for(var u=0;u<arguments.length;u++)c[u]=arguments[u];return St("debug",this._namespace,c)},s.prototype.error=function(){var c=[];for(var u=0;u<arguments.length;u++)c[u]=arguments[u];return St("error",this._namespace,c)},s.prototype.info=function(){var c=[];for(var u=0;u<arguments.length;u++)c[u]=arguments[u];return St("info",this._namespace,c)},s.prototype.warn=function(){var c=[];for(var u=0;u<arguments.length;u++)c[u]=arguments[u];return St("warn",this._namespace,c)},s.prototype.verbose=function(){var c=[];for(var u=0;u<arguments.length;u++)c[u]=arguments[u];return St("verbose",this._namespace,c)},s}();function St(s,c,u){var d=Se("diag");if(!d)return;return u.unshift(c),d[s].apply(d,Ui([],Bi(u),!1))}var re;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(re||(re={}));function Xn(s,c){if(s<re.NONE)s=re.NONE;else if(s>re.ALL)s=re.ALL;c=c||{};function u(d,f){var p=c[d];if(typeof p==="function"&&s>=f)return p.bind(c);return function(){}}return{error:u("error",re.ERROR),warn:u("warn",re.WARN),info:u("info",re.INFO),debug:u("debug",re.DEBUG),verbose:u("verbose",re.VERBOSE)}}var $i=function(s,c){var u=typeof Symbol==="function"&&s[Symbol.iterator];if(!u)return s;var d=u.call(s),f,p=[],m;try{while((c===void 0||c-- >0)&&!(f=d.next()).done)p.push(f.value)}catch(y){m={error:y}}finally{try{if(f&&!f.done&&(u=d.return))u.call(d)}finally{if(m)throw m.error}}return p},Hi=function(s,c,u){if(u||arguments.length===2){for(var d=0,f=c.length,p;d<f;d++)if(p||!(d in c)){if(!p)p=Array.prototype.slice.call(c,0,d);p[d]=c[d]}}return s.concat(p||Array.prototype.slice.call(c))},Gi="diag",ve=function(){function s(){function c(f){return function(){var p=[];for(var m=0;m<arguments.length;m++)p[m]=arguments[m];var y=Se("diag");if(!y)return;return y[f].apply(y,Hi([],$i(p),!1))}}var u=this,d=function(f,p){var m,y,S;if(p===void 0)p={logLevel:re.INFO};if(f===u){var w=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return u.error((m=w.stack)!==null&&m!==void 0?m:w.message),!1}if(typeof p==="number")p={logLevel:p};var E=Se("diag"),v=Xn((y=p.logLevel)!==null&&y!==void 0?y:re.INFO,f);if(E&&!p.suppressOverrideMessage){var k=(S=Error().stack)!==null&&S!==void 0?S:"<failed to generate stacktrace>";E.warn("Current logger will be overwritten from "+k),v.warn("Current logger will overwrite one already registered from "+k)}return je("diag",v,u,!0)};u.setLogger=d,u.disable=function(){Fe(Gi,u)},u.createComponentLogger=function(f){return new Jn(f)},u.verbose=c("verbose"),u.debug=c("debug"),u.info=c("info"),u.warn=c("warn"),u.error=c("error")}return s.instance=function(){if(!this._instance)this._instance=new s;return this._instance},s}();var Wi=function(s,c){var u=typeof Symbol==="function"&&s[Symbol.iterator];if(!u)return s;var d=u.call(s),f,p=[],m;try{while((c===void 0||c-- >0)&&!(f=d.next()).done)p.push(f.value)}catch(y){m={error:y}}finally{try{if(f&&!f.done&&(u=d.return))u.call(d)}finally{if(m)throw m.error}}return p},qi=function(s){var c=typeof Symbol==="function"&&Symbol.iterator,u=c&&s[c],d=0;if(u)return u.call(s);if(s&&typeof s.length==="number")return{next:function(){if(s&&d>=s.length)s=void 0;return{value:s&&s[d++],done:!s}}};throw TypeError(c?"Object is not iterable.":"Symbol.iterator is not defined.")},Qn=function(){function s(c){this._entries=c?new Map(c):new Map}return s.prototype.getEntry=function(c){var u=this._entries.get(c);if(!u)return;return Object.assign({},u)},s.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(c){var u=Wi(c,2),d=u[0],f=u[1];return[d,f]})},s.prototype.setEntry=function(c,u){var d=new s(this._entries);return d._entries.set(c,u),d},s.prototype.removeEntry=function(c){var u=new s(this._entries);return u._entries.delete(c),u},s.prototype.removeEntries=function(){var c,u,d=[];for(var f=0;f<arguments.length;f++)d[f]=arguments[f];var p=new s(this._entries);try{for(var m=qi(d),y=m.next();!y.done;y=m.next()){var S=y.value;p._entries.delete(S)}}catch(w){c={error:w}}finally{try{if(y&&!y.done&&(u=m.return))u.call(m)}finally{if(c)throw c.error}}return p},s.prototype.clear=function(){return new s},s}();var Sd=ve.instance();function Zn(s){if(s===void 0)s={};return new Qn(new Map(Object.entries(s)))}function es(s){return Symbol.for(s)}var zi=function(){function s(c){var u=this;u._currentContext=c?new Map(c):new Map,u.getValue=function(d){return u._currentContext.get(d)},u.setValue=function(d,f){var p=new s(u._currentContext);return p._currentContext.set(d,f),p},u.deleteValue=function(d){var f=new s(u._currentContext);return f._currentContext.delete(d),f}}return s}(),ts=new zi;var rs={get:function(s,c){if(s==null)return;return s[c]},keys:function(s){if(s==null)return[];return Object.keys(s)}},ns={set:function(s,c,u){if(s==null)return;s[c]=u}};var Vi=function(s,c){var u=typeof Symbol==="function"&&s[Symbol.iterator];if(!u)return s;var d=u.call(s),f,p=[],m;try{while((c===void 0||c-- >0)&&!(f=d.next()).done)p.push(f.value)}catch(y){m={error:y}}finally{try{if(f&&!f.done&&(u=d.return))u.call(d)}finally{if(m)throw m.error}}return p},Yi=function(s,c,u){if(u||arguments.length===2){for(var d=0,f=c.length,p;d<f;d++)if(p||!(d in c)){if(!p)p=Array.prototype.slice.call(c,0,d);p[d]=c[d]}}return s.concat(p||Array.prototype.slice.call(c))},ss=function(){function s(){}return s.prototype.active=function(){return ts},s.prototype.with=function(c,u,d){var f=[];for(var p=3;p<arguments.length;p++)f[p-3]=arguments[p];return u.call.apply(u,Yi([d],Vi(f),!1))},s.prototype.bind=function(c,u){return u},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var Ji=function(s,c){var u=typeof Symbol==="function"&&s[Symbol.iterator];if(!u)return s;var d=u.call(s),f,p=[],m;try{while((c===void 0||c-- >0)&&!(f=d.next()).done)p.push(f.value)}catch(y){m={error:y}}finally{try{if(f&&!f.done&&(u=d.return))u.call(d)}finally{if(m)throw m.error}}return p},Xi=function(s,c,u){if(u||arguments.length===2){for(var d=0,f=c.length,p;d<f;d++)if(p||!(d in c)){if(!p)p=Array.prototype.slice.call(c,0,d);p[d]=c[d]}}return s.concat(p||Array.prototype.slice.call(c))},Pr="context",Qi=new ss,$t=function(){function s(){}return s.getInstance=function(){if(!this._instance)this._instance=new s;return this._instance},s.prototype.setGlobalContextManager=function(c){return je(Pr,c,ve.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(c,u,d){var f,p=[];for(var m=3;m<arguments.length;m++)p[m-3]=arguments[m];return(f=this._getContextManager()).with.apply(f,Xi([c,u,d],Ji(p),!1))},s.prototype.bind=function(c,u){return this._getContextManager().bind(c,u)},s.prototype._getContextManager=function(){return Se(Pr)||Qi},s.prototype.disable=function(){this._getContextManager().disable(),Fe(Pr,ve.instance())},s}();var Ir=$t.getInstance();var os=function(){function s(){}return s.prototype.inject=function(c,u){},s.prototype.extract=function(c,u){return c},s.prototype.fields=function(){return[]},s}();var Tr=es("OpenTelemetry Baggage Key");function xr(s){return s.getValue(Tr)||void 0}function is(){return xr($t.getInstance().active())}function as(s,c){return s.setValue(Tr,c)}function cs(s){return s.deleteValue(Tr)}var Ar="propagation",Zi=new os,ls=function(){function s(){this.createBaggage=Zn,this.getBaggage=xr,this.getActiveBaggage=is,this.setBaggage=as,this.deleteBaggage=cs}return s.getInstance=function(){if(!this._instance)this._instance=new s;return this._instance},s.prototype.setGlobalPropagator=function(c){return je(Ar,c,ve.instance())},s.prototype.inject=function(c,u,d){if(d===void 0)d=ns;return this._getGlobalPropagator().inject(c,u,d)},s.prototype.extract=function(c,u,d){if(d===void 0)d=rs;return this._getGlobalPropagator().extract(c,u,d)},s.prototype.fields=function(){return this._getGlobalPropagator().fields()},s.prototype.disable=function(){Fe(Ar,ve.instance())},s.prototype._getGlobalPropagator=function(){return Se(Ar)||Zi},s}();var Or=ls.getInstance();import{copyFile as ea,readFile as ta,rm as ds,writeFile as fs}from"fs/promises";import{homedir as us}from"os";import{join as Mr}from"path";function ps(s){return{globalConfig:Mr(s||us(),".claude.json"),userSettings:Mr(s||Mr(us(),".claude"),"settings.json")}}function Dr(s,c,u,d){return s!==void 0&&c===u?{backend:s,key:d}:void 0}async function Ke(s,c,u,d){if(d)return ra(d,s,c,u);try{if(u)await fs(c,u(await ta(s)),{mode:384});else await ea(s,c)}catch(f){if(n(f)===void 0)throw f;if(!_(f))await ds(c,{force:!0}).catch(()=>{}),e(`sessionStore resume: skipping ${s} (${n(f)})`)}}async function ra({backend:s,key:c},u,d,f){let p=await s.read([c]);if(!p.ok){if(p.error.code==="InvalidArgument")throw new l(`sessionStore resume: invalid v5 key for ${u}: ${p.error.argument}${p.error.reason?` (${p.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");e(`sessionStore resume: skipping ${u} (${p.error.code})`);return}let m=p.value.items[0];if(!m?.found)return;let y=Buffer.from(m.value);try{await fs(d,f?f(y):y,{mode:384})}catch(S){if(n(S)===void 0)throw S;if(!_(S))await ds(d,{force:!0}).catch(()=>{}),e(`sessionStore resume: skipping ${u} (${n(S)})`)}}import{createHash as na}from"crypto";import{homedir as ef,userInfo as sa}from"os";var ms="-credentials";function gs(s=""){let c=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,u=c!==void 0?!c:!process.env.CLAUDE_CONFIG_DIR,d=c!==void 0?c.normalize("NFC"):h(),f=u?"":`-${na("sha256").update(d).digest("hex").substring(0,8)}`;return`Claude Code${bt().OAUTH_FILE_SUFFIX}${s}${f}`}var oa=/^[a-zA-Z0-9._-]+$/;function hs(){if(process.platform==="win32")return"claude-code-user";let s;try{s=process.env.USER||sa().username}catch{s="claude-code-user"}if(!oa.test(s))return"claude-code-user";return s}class ys{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var of=new i(()=>new ys);import{once as Es}from"events";import{constants as wt,createWriteStream as ba}from"fs";import{lstat as wa,open as Ea,lstat as If,readdir as Gt,realpath as _a,rename as Tf,stat as xf}from"fs/promises";import{basename as va,dirname as ka,isAbsolute as Of,join as ke}from"path";async function Nr(s,c,u){let d=Math.max(1,Math.floor(u?.maxPages??1e4)),f;for(let p=0;p<d;p++){if(u?.budget!==void 0){if(u.budget.pagesLeft<1)return{status:"capped"};u.budget.pagesLeft--}let m=await s(f);if(!m.ok)return{status:"error",error:m.error};if(await c(m.value.items),u?.until?.())return{status:"done"};if(f=m.value.cursor,!f)return{status:"done"}}return{status:"capped"}}import{execFile as ha}from"child_process";import{promisify as ya}from"util";import{execFileSync as ia}from"child_process";import{lstatSync as aa}from"fs";import{join as ca}from"path";function la(){return process.platform==="win32"}class bs{resolved=new Map;lookup(s){return this.resolved.get(s)}remember(s,c){this.resolved.set(s,c)}forget(s){this.resolved.delete(s)}}var ua=new i(()=>new bs),da=5000;function Ss(s){try{return aa(s,{throwIfNoEntry:!1})===void 0}catch{return!1}}var fa=new Set([".com",".exe",".bat",".cmd"]);function pa(s){let c=s.toLowerCase().replace(/.*[\\/]/,"").replace(/[. ]+$/,""),u=c.lastIndexOf(".");return u>0&&fa.has(c.slice(u))}function ma(s,c=!1){let u=ua.of(C().host),d=u.lookup(s);if(d!==void 0)if(d!==null){if(!Ss(d))return d;u.forget(s)}else{if(!c)return d;u.forget(s)}let f=ze("SYSTEMROOT")||"C:\\Windows",p=ca(f,"System32","where.exe");try{let y=ia(p,[s],{stdio:"pipe",encoding:"utf8",timeout:da,windowsHide:!0,env:process.env}).trim().split(/\r?\n/).filter(Boolean),S=process.cwd(),w=!1;for(let E of y){if(Ss(E))continue;if(xe(E,S)){w=!0;continue}if(!pa(E))continue;return u.remember(s,E),E}if(y.length>0&&!w)u.remember(s,null);return null}catch(m){if(ga(m))u.remember(s,null);return null}}function ga(s){if(s===null||typeof s!=="object")return!1;let c="status"in s?s.status:void 0,u="signal"in s?s.signal:void 0,d="code"in s?s.code:void 0;return c===1&&!u&&!d}function ws(s,c=!1){if(!la())return s;if(s.includes("/")||s.includes("\\"))return s;return ma(s,c)}var Sa=ya(ha);async function Ht(s){let c=ws("git");if(c===null)return[];try{let{stdout:u}=await Sa(c,["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=","worktree","list","--porcelain"],{cwd:s,timeout:5000,windowsHide:!0});if(!u)return[];return u.split(`
34
+ `).filter((d)=>d.startsWith("worktree ")).map((d)=>g(d.slice(9)))}catch{return[]}}var Be=65536;var Ca=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ge(s){if(typeof s!=="string")return null;return Ca.test(s)?s:null}function Ra(s,c,u){return Pa(s,u,c)}function Pa(s,c,u){let d=u===void 0?void 0:`"type":"${u}"`,f=`"${c}":`,p=s.length;while(p>0){let m=s.lastIndexOf(`
35
+ `,p-1),y=s.slice(m+1,p);if(p=m,y.includes(f)&&(d===void 0||y.includes(d)))try{let S=JSON.parse(y);if(typeof S==="object"&&S!==null&&(u===void 0||S.type===u)){let w=S[c];if(typeof w==="string")return w}}catch{}if(m<0)break}return}function Ia(s,c){let u=`"${c}":`,d=0;while(d<s.length){let f=s.indexOf(`
36
+ `,d),p=f<0?s.slice(d):s.slice(d,f);if(d=f<0?s.length:f+1,p.includes(u))try{let m=JSON.parse(p);if(typeof m==="object"&&m!==null){let y=m[c];if(typeof y==="string")return y}}catch{}}return}function Lr(s,c){return s?.realWorkspacePath===void 0?void 0:{hoverRestOn:c,realPath:s.realWorkspacePath}}async function jr(s,c,u){return Ta(s,c,"w",u)}async function Ta(s,c,u,d){if(d!==void 0&&d.hoverRestOn&&(u==="w"||c.length>0))return xa(d.source,c,u);let f=ba(s,{mode:384,flags:u});try{for(let p of c)if(!f.write(JSON.stringify(p)+`
37
+ `))await Es(f,"drain");f.end(),await Es(f,"finish")}catch(p){throw f.destroy(),p}}async function xa(s,c,u){let{backend:d,key:f}=s,p=c.map((y)=>({data:JSON.stringify(y)+`
38
+ `}));if(u==="w"){let y=await d.replaceRecords(f,p,{publishDiscipline:"inPlace",mode:384});if(!y.ok)throw Error("transcript stream replace failed",{cause:y.error});return}let m=await d.append(f,p);if(!m.ok)throw Error("transcript stream append failed",{cause:m.error})}var _s=process.platform==="win32"?wt.O_RDONLY:wt.O_RDONLY|wt.O_NOFOLLOW|wt.O_NONBLOCK;async function Aa(s){let{backend:c,key:u}=s;try{let d=await c.read([{key:u,offset:0,length:Be},{key:u,tail:Be}]);if(!d.ok)return null;let[f,p]=d.value.items;if(!f.found||f.value.length===0)return null;let m=vs(f.value),y=p.found&&p.value.length>0?vs(p.value):m;return{head:m,tail:y,mtimeMs:f.mtimeMs,totalBytes:f.totalBytes}}catch{return null}}function vs(s){return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("utf8")}var Bf=Buffer.from('"type":"user"'),Uf=Buffer.from('"type":"assistant"');function Fr(s,c){if(s.kind!=="scope"||s.scope.namespace!=="transcript"||s.scope.projectKey===void 0||s.scope.sessionId!==void 0||!c(s.scope.projectKey))return;return s.scope.projectKey}function ks(s){return{skipScopeStats:!0,skipKeyStats:!0,...s!==void 0&&{cursor:s}}}async function Oa(s,c){if(c!==void 0&&c.hoverRestOn)return Cs(c.source);try{if(_s===wt.O_RDONLY){if(!(await wa(s)).isFile())return null}let u=await Ea(s,_s);try{let d=await u.stat();if(!d.isFile())return null;let f=Buffer.allocUnsafe(Be),p=await u.read(f,0,Be,0);if(p.bytesRead===0)return null;let m=f.toString("utf8",0,p.bytesRead),y=Math.max(0,d.size-Be),S=m;if(y>0){let w=await u.read(f,0,Be,y);S=f.toString("utf8",0,w.bytesRead)}return{mtime:d.mtime.getTime(),size:d.size,head:m,tail:S}}finally{await u.close()}}catch{return null}}async function Cs(s){let c=await Aa(s);if(c===null)return null;return{mtime:Math.trunc(c.mtimeMs),size:c.totalBytes,head:c.head,tail:c.tail}}var Ue=200;function Ma(s){return Math.abs(it(s)).toString(36)}function Wt(s){return s.replace(/[^a-zA-Z0-9]/g,"-")}function kt(s){let c=Wt(s);if(c.length<=Ue)return c;return`${c.slice(0,Ue)}-${Ma(s)}`}function be(){return ke(h(),"projects")}function Ct(s){return _t()??kt(s)}function Kr(s){let c=kt(s);return c===Ct(s)?void 0:c}function Rt(s,c=be()){return ke(c,Ct(s))}function qt(s,c){let u=va(s);return ka(s)===be()&&c(u)?u:void 0}async function Br(s,c){try{if(c!==void 0&&c.hoverRestOn){let u=await c.realPath(s);return g(u.ok&&u.value.found?u.value.path:s)}return g(await _a(s))}catch{return g(s)}}async function zt(s,c,u,d){let f=d!==void 0&&d.hoverRestOn?d.source:void 0,p=f===void 0?void 0:qt(s,f.isKeySegment);if(f!==void 0&&p!==void 0){let S=await Da(p,c,u,f);if(S!==void 0)return S}let m=Wt(c),y;try{y=await Gt(s,{withFileTypes:!0})}catch{return!1}for(let S of y){if(!S.isFile()||!S.name.endsWith(".jsonl"))continue;let w=await Oa(ke(s,S.name));if(w===null)continue;if(Rs(w,m,u))return!0}return!1}function Rs(s,c,u){let d=Ra(s.tail,"relocated","relocatedCwd")??Ia(s.head,"cwd");if(d===void 0)return!1;let f=Wt(g(d));return u?f.toLowerCase()===c.toLowerCase():f===c}async function Da(s,c,u,d){let{backend:f,transcriptKey:p,isKeySegment:m}=d,y=Wt(c),S=!1,w=new Set;try{let E=await Nr((v)=>f.listEntries({namespace:"transcript",projectKey:s},ks(v)),async(v)=>{for(let k of v){if(k.kind!=="key"||k.key.namespace!=="transcript"||k.key.projectKey!==s||k.key.agentId!==void 0||!m(k.key.sessionId)||w.has(k.key.sessionId))continue;let P=k.key.sessionId,O=await Cs({backend:f,key:p(s,P)});if(O===null)continue;if(w.add(P),Rs(O,y,u)){S=!0;return}}},{until:()=>S});if(S)return!0;if(E.status!=="done")return}catch{return}return!1}async function Pt(s,c,u=be()){if(c!==void 0&&c.hoverRestOn)return Na(s,c);let d=Rt(s,u),f=[];try{await Gt(d),f.push(d)}catch{}let p=Kr(s);if(p!==void 0){let v=ke(u,p);try{await Gt(v),f.push(v)}catch{}return f}let m=kt(s);if(m.length<=Ue)return f;let y=process.platform==="win32",S=(v)=>y?v.toLowerCase():v,w=S(m.slice(0,Ue)+"-"),E=S(d);try{for(let v of await Gt(u,{withFileTypes:!0})){if(!v.isDirectory()||!S(v.name).startsWith(w))continue;let k=ke(u,v.name);if(S(k)!==E&&await zt(k,s,y))f.push(k)}}catch{}return f}async function Na(s,c){let u=await La(c.source);if(u===null){let d=Kr(s);return[Rt(s),...d!==void 0?[ke(be(),d)]:[]]}return ja(s,u,process.platform==="win32",c)}async function La(s){let{backend:c,isKeySegment:u}=s,d=[],f=new Set,p=0;try{if((await Nr((y)=>c.listEntries({namespace:"transcript"},ks(y)),(y)=>{for(let S of y){let w=Fr(S,u);if(w!==void 0&&!f.has(w))f.add(w),d.push(w)}p++})).status==="error")return p===0?null:d}catch{return p===0?null:d}return d}async function ja(s,c,u,d){let f=Ct(s),p=Rt(s),m=Kr(s),y=m===void 0&&f.length>Ue?f.slice(0,Ue)+"-":void 0,S=be(),w=(j)=>u?j.toLowerCase():j,E=y!==void 0?w(y):void 0,v=w(f),k=!1,P,O=[],N=new Set;for(let j of c)if(j===f)k=!0;else if(m!==void 0){if(P===void 0&&w(j)===w(m))P=ke(S,j)}else if(E!==void 0&&w(j).startsWith(E)&&w(j)!==v&&!N.has(w(j)))N.add(w(j)),O.push(j);let M=[];for(let j of O){let Y=ke(S,j);if(await zt(Y,s,u,d))M.push(Y)}return[...k?[p]:[],...P!==void 0?[P]:[],...M]}var $f=Buffer.from('"compact_boundary"');var Hf=Buffer.from('{"type":"attribution-snapshot"'),Gf=Buffer.from('{"type":"system"'),Fa=10,Wf=Buffer.from([Fa]);function Ka(s,c){if(s==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let u=c.filter((d)=>d.length>0&&!d.includes("("));if(u.length===0)return;return`canUseTool will not be invoked for: ${u.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function Ps(s,c,u){if(!s)return;let d=Ka(c,u);if(d===void 0)return;process.emitWarning(d,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as Ba}from"fs";import{isAbsolute as Ua,relative as $a,resolve as Ha,sep as Ga}from"path";function Wa(s){let c=Ha(s??"."),u;try{u=Ba(c)}catch{u=c}return g(u)}function Ce(s,c){let u=Wa(s);if(c===void 0)return Ct(u);return(c.CLAUDE_CONFIG_DIR?nt(c.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??kt(u)}function Is(s){return typeof s==="object"&&s!==null&&"type"in s&&s.type==="agent_metadata"}function Ur(s,c){let u=$a(c,s),d=u.split(Ga);if(d[0]===".."||Ua(u))return null;if(d.length<2)return null;let f=d[0],p=d[1];if(d.length===2&&p.endsWith(".jsonl"))return{projectKey:f,sessionId:p.replace(/\.jsonl$/,"")};if(d.length>=4){let m=d.slice(2),y=m.length-1;return m[y]=m.at(-1).replace(/\.jsonl$/,""),{projectKey:f,sessionId:p,subpath:m.join("/")}}return null}process.env.NoDefaultCurrentDirectoryInExePath="1";var nc=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function xs(s){let c;try{c=A(ae(s.toString("utf8")))}catch{return s}if(!As(c))return s;let u=!1;for(let f of nc)if(Object.hasOwn(c,f))delete c[f],u=!0;let d=c.env;if(As(d)&&Object.hasOwn(d,"CLAUDE_CONFIG_DIR"))delete d.CLAUDE_CONFIG_DIR,u=!0;return u?t(c):s}function As(s){return s!==null&&typeof s==="object"&&!Array.isArray(s)}async function sc(s,c){if(!s)return;let u=s;try{let d=A(s);if(d?.claudeAiOauth?.refreshToken)delete d.claudeAiOauth.refreshToken,u=t(d)}catch{}await Os(c,u,{mode:384})}function oc(){if(process.platform!=="darwin")return Promise.resolve(void 0);let s=gs(ms);return new Promise((c)=>{qa("security",["find-generic-password","-a",hs(),"-w","-s",s],{encoding:"utf-8",timeout:5000,windowsHide:!0},(u,d)=>c(u?void 0:d.trim()||void 0))})}async function Ms(s,c,u,d,f=60000,p){if(!ge(c))return;let m=Ce(u,d),y=await x(s.load({projectKey:m,sessionId:c}),f,`SessionStore.load() timed out after ${f}ms for session ${c}`);if(!y||y.length===0)return;let S=V(Xa(),`claude-resume-${za()}`);try{let w=V(S,"projects",m);await $r(w,{recursive:!0,mode:448});let E=V(w,`${c}.jsonl`);await jr(E,y);let v=d?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,k=v??V(Hr(),".claude"),P;try{P=await Va(V(k,".credentials.json"),"utf-8")}catch(Y){if(!_(Y))throw Y}if(!v&&!(d??process.env).ANTHROPIC_API_KEY&&!(d??process.env).CLAUDE_CODE_OAUTH_TOKEN)P=await oc()??P;await sc(P,V(S,".credentials.json"));let O=ps(ze("CLAUDE_CONFIG_DIR")),N=v||Hr(),M=V(N,".claude.json");await Ke(M,V(S,".claude.json"),void 0,Dr(p,M,O.globalConfig,ee.globalConfig())),await Ke(V(k,".config.json"),V(S,".config.json"));for(let Y of Et)if(Y)await Ke(V(N,`.claude${Y}.json`),V(S,`.claude${Y}.json`));let j=V(k,"settings.json");if(await Ke(j,V(S,"settings.json"),xs,Dr(p,j,O.userSettings,ee.userSettings())),await Ke(V(k,"cowork_settings.json"),V(S,"cowork_settings.json"),xs),s.listSubkeys)await ic(s,{projectKey:m,sessionId:c},V(w,c),f);return S}catch(w){throw await Yt(S),w}}async function ic(s,c,u,d){let f=await x(s.listSubkeys({projectKey:c.projectKey,sessionId:c.sessionId}),d,`SessionStore.listSubkeys() timed out after ${d}ms for session ${c.sessionId}`);for(let p of f){let m=Vt(u,p+".jsonl");if(!p||Qa(p)||p.split(/[\\/]/).includes("..")||!m.startsWith(u+ec)){e(`[SessionStore] skipping unsafe subpath from listSubkeys: ${p}`,{level:"warn"});continue}let y=await x(s.load({projectKey:c.projectKey,sessionId:c.sessionId,subpath:p}),d,`SessionStore.load() timed out after ${d}ms for session ${c.sessionId} subpath ${p}`);if(!y||y.length===0)continue;let S=[],w=[];for(let E of y)if(Is(E))S.push(E);else w.push(E);if(w.length>0)await $r(Ts(m),{recursive:!0}),await jr(m,w);if(S.length>0){let E=S.at(-1),v=Vt(u,p+".meta.json");await $r(Ts(v),{recursive:!0});let{type:k,...P}=E;await Os(v,t(P),{mode:384})}}}function ac(s){let c=s?.accepted===!0&&(typeof s.directory!=="string"||!(Za.isAbsolute(s.directory)||tc.isAbsolute(s.directory)))?void 0:s;if(s!==void 0&&c===void 0)e("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return c}function Gr(s,c){let{isSingleUserTurn:u,resumeConfigDir:d,deferSpawn:f}=c,{systemPrompt:p,settings:m,managedSettings:y,settingSources:S,sandbox:w,...E}=s??{},v,k,P,O;if(p===void 0)v="";else if(typeof p==="string")v=p;else if(Array.isArray(p))v=p;else if(p.type==="custom")v=p.prompt,O=p.snapshot;else if(p.type==="preset")k=p.append,P=p.excludeDynamicSections,O=p.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.282";let{abortController:N=tt(),additionalDirectories:M=[],projectConfigRoot:j,agent:Y,agents:pe,allowedTools:K=[],betas:B,canUseTool:U,continue:F,cwd:Z,debug:q,debugFile:he,disallowedTools:Ee=[],tools:fe,env:ce,executable:$e=ie()?"bun":"node",executableArgs:Re=[],extraArgs:It={},fallbackModel:Qt,enableFileCheckpointing:_e,toolConfig:T,forkSession:Tt,hooks:At,includeHookEvents:He,includePartialMessages:We,forwardSubagentText:qe,verbatimPrompts:Ve=!1,onElicitation:Pe,onUserDialog:L,supportedDialogKinds:ue,perTaskStopAffordance:ne,rapidFollowupPreempt:Ie,workspaceTrust:Zt,persistSession:Mt,sessionStore:de,sessionStoreFlush:Qs,thinking:Ye,effort:Zs,maxThinkingTokens:er,maxTurns:eo,maxBudgetUsd:to,taskBudget:ro,mcpServers:Vr,model:no,outputFormat:Yr,permissionMode:so,allowDangerouslySkipPermissions:oo=!1,permissionPromptToolName:io,permissionPrompts:ao,plugins:Dt,pluginDelivery:tr="argv",getOAuthToken:Jr,getHostAuthToken:Xr,workload:Qr,resume:Zr,resumeSessionAt:co,resumeDropsTurn:lo,sessionId:uo,skills:en,stderr:fo,strictMcpConfig:po}=E,tn=so??(s?.resolvePermissionModeInCli?void 0:"default");if(de&&Mt===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(ue!==void 0&&ue.length>0&&!L)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let mo=ac(Zt);if(de&&F&&!Zr&&!de.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(de&&_e)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(de&&E.spawnClaudeCodeProcess)e("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(Ps(!!U,tn??"default",K),tr!=="argv"&&tr!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let rn=tr==="initialize"&&Dt!==void 0&&Dt.length>0,rr=E.pathToClaudeCodeExecutable;if(!rr){let te=rc(import.meta.url),se=Ja(te),me=jn((Oe)=>se.resolve(Oe));if(!me)throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);rr=me}let nn=Yr?.type==="json_schema"?Yr.schema:void 0,J=ce?{...ce}:{...process.env};if(!J.CLAUDE_CODE_ENTRYPOINT)J.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!J.CLAUDE_AGENT_SDK_VERSION)J.CLAUDE_AGENT_SDK_VERSION="0.3.282";if(_e)J.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(Jr)J.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(Xr)J.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(T?.askUserQuestion?.previewFormat)J.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=T.askUserQuestion.previewFormat;for(let[te,se]of[[T?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[T?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"]])if(te)J[se]="1";else if(!ce){for(let me of Object.keys(J))if(me.toUpperCase()===se)delete J[me]}let nr={};if(Or.inject(Ir.active(),nr),"traceparent"in nr){for(let te of["TRACEPARENT","TRACESTATE"])if(!(te in(ce??{})))delete J[te]}for(let[te,se]of Object.entries(nr)){let me=te.toUpperCase();if(!(me in(ce??{})))J[me]=se}let sn={},on=new Map;if(Vr)for(let[te,se]of Object.entries(Vr))if(se.type==="sdk"&&se.instance)on.set(te,se);else sn[te]=se;let Ze;if(Ye)switch(Ye.type){case"adaptive":Ze={type:"adaptive",display:Ye.display};break;case"enabled":Ze={type:"enabled",budgetTokens:Ye.budgetTokens,display:Ye.display};break;case"disabled":Ze={type:"disabled"};break}else if(er!==void 0)Ze=er===0?{type:"disabled"}:{type:"enabled",budgetTokens:er};if(d){if(J.CLAUDE_CONFIG_DIR=d,process.platform==="win32")J.CLAUDE_SECURESTORAGE_CONFIG_DIR=ce?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??ce?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let an=new br({abortController:N,additionalDirectories:M,projectConfigRoot:j,agent:Y,betas:B,cwd:Z,debug:q,debugFile:he,executable:$e,executableArgs:Re,extraArgs:Qr?{...It,workload:Qr}:It,pathToClaudeCodeExecutable:rr,env:J,forkSession:Tt,stderr:fo,thinkingConfig:Ze,effort:Zs,maxTurns:eo,maxBudgetUsd:to,taskBudget:ro,model:no,fallbackModel:Qt,jsonSchema:nn,permissionMode:tn,allowDangerouslySkipPermissions:oo,permissionPromptToolName:io,permissionPrompts:ao,continueConversation:de?void 0:F,resume:Zr,resumeSessionAt:co,resumeDropsTurn:lo,sessionId:uo,settings:typeof m==="object"?t(m):m,managedSettings:y?t(y):void 0,settingSources:S,skills:en,allowedTools:K,disallowedTools:Ee,tools:fe,mcpServers:sn,strictMcpConfig:po,canUseTool:!!U,hooks:!!At,includeHookEvents:He,includePartialMessages:We,persistSession:Mt,sessionMirror:!!de,plugins:Dt,pluginsViaInitialize:rn,sandbox:w,spawnClaudeCodeProcess:E.spawnClaudeCodeProcess,deferSpawn:f}),go={systemPrompt:v,appendSystemPrompt:k,planModeInstructions:E.planModeInstructions,systemPromptSnapshot:O,appendSubagentSystemPrompt:E.appendSubagentSystemPrompt,toolAliases:E.toolAliases,excludeDynamicSections:P,agents:pe,title:E.title,skills:en,webSearchIsolationExemptMcpServers:E.webSearchIsolationExemptMcpServers,promptSuggestions:E.promptSuggestions,agentProgressSummaries:E.agentProgressSummaries,forwardSubagentText:qe,supportedDialogKinds:ue,perTaskStopAffordance:ne,rapidFollowupPreempt:Ie,workspaceTrust:mo,plugins:rn?Dt:void 0,captureSdkMcpManifests:!Ge("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},sr=new Ut(an,u,U,At,N,on,nn,go,Pe,Jr,Xr,L,Ve);if(de){let te=()=>V(J.CLAUDE_CONFIG_DIR??V(Hr(),".claude"),"projects"),se=Qs==="eager",me=new Rr(async(Oe,or)=>{let et=Ur(Oe,te());if(et)await de.append(et,or);else e(`[SessionStore] dropping mirror frame: filePath ${Oe} is not under ${te()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Oe,or)=>{let et=Ur(Oe,te());if(et)sr.reportMirrorError(et,or.message)},maxPendingEntries:se?0:kr,maxPendingBytes:se?0:Cr});sr.setTranscriptMirrorBatcher(me)}return{queryInstance:sr,transport:an,abortController:N,processEnv:J,verbatimPrompts:Ve}}function Wr(s,c,u,d){if(typeof c==="string")s.writeAfterInitialize(t({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:c}]},parent_tool_use_id:null,...d&&{client_composed:!0}})+`
39
+ `).catch((f)=>u.abort(f));else s.streamInput(c).catch((f)=>u.abort(f))}var cc=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function Yt(s){for(let c=0;;c++)try{return await Ya(s,{recursive:!0,force:!0})}catch(u){if(c>=4||!cc.has(n(u)??""))return;await I((c+1)*100)}}function lc(s,c){s.waitForExit().catch(()=>{}).finally(()=>Yt(c))}function uc({prompt:s,options:c}){if((c?.resume||c?.continue)&&c?.sessionStore)return dc(s,c);let{queryInstance:u,abortController:d,verbatimPrompts:f}=Gr(c,{isSingleUserTurn:typeof s==="string"});return Wr(u,s,d,f),u}function dc(s,c){let{queryInstance:u,transport:d,abortController:f,processEnv:p,verbatimPrompts:m}=Gr({...c},{isSingleUserTurn:typeof s==="string",deferSpawn:!0}),y=Vt(c.cwd??"."),S=c.sessionStore,w=c.loadTimeoutMs??60000,E=c.resume;return(async()=>{if(!E)E=(await x(S.listSessions(Ce(y,c.env)),w,`SessionStore.listSessions() timed out after ${w}ms`)).slice().sort((P,O)=>O.mtime-P.mtime)[0]?.sessionId;if(!E)return;return Ms(S,E,y,c.env,c.loadTimeoutMs)})().then((k)=>{if(k){d.updateResume(E);let P={CLAUDE_CONFIG_DIR:k};if(process.platform==="win32"){let O=c.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??c.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";P.CLAUDE_SECURESTORAGE_CONFIG_DIR=O,p.CLAUDE_SECURESTORAGE_CONFIG_DIR=O}d.updateEnv(P),p.CLAUDE_CONFIG_DIR=k,u.addCleanupCallback(()=>lc(d,k))}if(!u.isClosed())d.spawn()}).catch((k)=>{let P=D(k);d.spawnAbort(P),u.setError(P)}),Wr(u,s,f,m),u}async function fc(s={}){return(await pc(s)).warm}async function pc({options:s,initializeTimeoutMs:c=60000}){let u,d=s?.resume;if((d||s?.continue)&&s?.sessionStore){let y=Vt(s.cwd??".");if(!d){if(!s.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let S=s.loadTimeoutMs??60000;d=(await x(s.sessionStore.listSessions(Ce(y,s.env)),S,`SessionStore.listSessions() timed out after ${S}ms`)).slice().sort((E,v)=>v.mtime-E.mtime)[0]?.sessionId}if(d)u=await Ms(s.sessionStore,d,y,s.env,s.loadTimeoutMs)}let f,p,m;try{let O=function(){if(P)return;P=!0,v.close()},y=Gr(u&&d&&d!==s?.resume?{...s,resume:d}:s,{isSingleUserTurn:!1,resumeConfigDir:u});f=y.queryInstance;let{transport:S,abortController:w,verbatimPrompts:E}=y;p=S;let v=y.queryInstance;if(u){let M=u;v.addCleanupCallback(()=>{m=S.waitForExit().catch(()=>{}).then(()=>Yt(M))})}let k=`Subprocess initialization did not complete within ${c}ms — check authentication and network connectivity`;await x(v.initializationResult(),c,k).catch((M)=>{throw ct(M,k)?b(M,{telemetryMessage:`Subprocess initialization did not complete within ${c}ms`,errorClass:"initialize_timeout"}):M});let P=!1;return{warm:{query(M){if(P)throw Error("WarmQuery.query() can only be called once");P=!0;try{Wr(v,M,w,E)}catch(j){throw v.close(),j}if(typeof M==="string")v.setIsSingleUserTurn(!0);return v},close:O,async[Symbol.asyncDispose](){P=!0,v.close(),await m}},query:v,transport:S}}catch(y){if(f?.close(),u&&!m){let S=p;m=(S?S.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>Yt(u))}throw await m,y}}import{randomUUID as Js}from"crypto";import{constants as Us}from"fs";import{open as kc,readdir as Gs,rm as $s,stat as Cc}from"fs/promises";import{join as we}from"path";class Ds{available=void 0;probing=void 0;procUnreadableLogged=!1}var rm=new i(()=>new Ds);var Ns=["commands","agents","output-styles","skills","workflows","routines","themes","rules","session-env","uploads","mcp-skill-archives","usage-data","mcp-discovery-cache"];var vm=new Set(Ns),km=`must be one of the userConfigDir directory names (${Ns.join(", ")})`,Ls=["installed","marketplaces","flagged","catalog","inUseSweep"];var Cm=new Set(Ls),Rm=`must be one of the pluginRegistry files (${Ls.join(", ")})`,js=["manifest","catalog"];var Pm=new Set(js),Im=`must be one of the marketplaceCache forms (${js.join(", ")})`;var Fs=["world"];var Tm=new Set(Fs),xm=`must be one of the session journal names (${Fs.join(", ")})`;var Ks=["backup","corrupted"];var Am=new Set(Ks),Om=`must be one of the global-config copy kinds (${Ks.join(", ")})`;var bc="cloud-snapshots";var wc=new Set(["memory","tiny_memory","bagel",bc,"bridge-pointer.json",".session-aliases"]);var Bs=".cast",Mm=`<stamp>${Bs} inside a session's folder is that session's terminal recording stream: address it as keys.recording(projectKey, sessionId, stamp)`;var Ec=[".ccr-tip.json",".precompact.json",Bs],Dm=`must not end with ${Ec.join(", ")}: those name a session's project-level sibling files`;var _c=".dir-sync.json",Nm=`must not end with ${_c}: that names a cloud session's directory-sync record at the project level`;var Lm=`${[...wc].join(", ")} are reserved: they name project-level entries, not sessions`;var vc="timeline.jsonl",jm=`${vc} is the job's timeline stream: address it as keys.jobTimeline(jobId)`;function Jt(s){return s===void 0?void 0:{source:s,hoverRestOn:a()}}var Rc=64;function zr(s){return a()?s:void 0}async function Ws(s,c,u={},d){if(!ge(s))throw Error(`Invalid sessionId: ${s}`);if(!c.trim())throw Error("title must be non-empty");let f=t({type:"custom-title",customTitle:c.trim(),sessionId:s})+`
40
+ `;await Ys(s,f,u,zr(d))}async function qs(s,c,u={},d){if(!ge(s))throw Error(`Invalid sessionId: ${s}`);if(c!==null){let p=le(c).trim();if(!p)throw Error("tag must be non-empty (use null to clear)");c=p}let f=t({type:"tag",tag:c??"",sessionId:s})+`
41
+ `;await Ys(s,f,u,zr(d))}async function zs(s,c={},u){if(!ge(s))throw Error(`Invalid sessionId: ${s}`);let d=zr(u);for(let f of await Ic(c,d)){if(a()&&d!==void 0){let y=qt(f,d.isKeySegment);if(y!==void 0){if(await Pc(y,s,d))return;continue}}let p=we(f,`${s}.jsonl`),m;try{({size:m}=await Cc(p))}catch(y){let S=n(y);if(S==="ENOENT"||S==="ENOTDIR")continue;throw y}if(m===0)continue;await $s(p,{force:!0}),await $s(we(f,s),{recursive:!0,force:!0});return}throw Error(c.dir?`Session ${s} not found in project directory for ${c.dir}`:`Session ${s} not found in any project directory`)}async function Pc(s,c,u){let{backend:d,transcriptKey:f}=u,p=f(s,c),m=await d.statMeta(p);if(!m.ok){if(m.error.code==="NotFound")return!1;throw Error("Session delete: transcript unreadable via storage",{cause:m.error})}if((m.value.storedBytes??m.value.size)===0)return!1;for(let S of["transcript","sidecar"]){let w=await d.deleteScope({namespace:S,projectKey:s,sessionId:c});if(!w.ok)throw Error("Session delete: session directory not deletable via storage",{cause:w.error})}let y=await d.delete(p);if(!y.ok)throw Error("Session delete: transcript not deletable via storage",{cause:y.error});return!0}async function Ic(s,c){if(s.dir){let d=await Br(s.dir,Lr(c,a())),f=await Hs(d,c),p;try{p=await Ht(d)}catch{p=[]}for(let m of p){if(m===d)continue;f.push(...await Hs(m,c))}return f}let u=be();if(a()&&c!==void 0){let d=await Vs(c);if(d===void 0)return[];if(d.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return d.names.map((f)=>we(u,f))}try{return(await Gs(u,{withFileTypes:!0})).filter((f)=>f.isDirectory()||f.isSymbolicLink()).map((f)=>we(u,f.name))}catch{return[]}}async function Hs(s,c){let u=Jt(c);if(u===void 0||!u.hoverRestOn)return Pt(s);let d=await Pt(s,u),f=Rt(s),p=process.platform==="win32",m=[];for(let y of d)if(y===f||await zt(y,s,p,u))m.push(y);return m}async function Vs(s){let c=[],u,d=0;try{do{let f=await s.backend.listEntries({namespace:"transcript"},{skipScopeStats:!0,...u!==void 0&&{cursor:u}});if(!f.ok)return d===0?void 0:{names:c,laterPageFailed:!0};for(let p of f.value.items){let m=Fr(p,s.isKeySegment);if(m!==void 0)c.push(m)}u=f.value.cursor}while(u&&++d<Rc);return{names:c,laterPageFailed:Boolean(u)}}catch{return d===0&&c.length===0?void 0:{names:c,laterPageFailed:!0}}}async function Ys(s,c,u,d){let f=`${s}.jsonl`;if(u.dir){let y=await Br(u.dir,Lr(d,a()));for(let w of await Pt(y,Jt(d)))if(await Xt(we(w,f),c,qr(w,s,d)))return;let S;try{S=await Ht(y)}catch{S=[]}for(let w of S){if(w===y)continue;for(let E of await Pt(w,Jt(d)))if(await Xt(we(E,f),c,qr(E,s,d)))return}throw Error(`Session ${s} not found in project directory for ${u.dir}`)}let p=be();if(a()&&d!==void 0){let y=await Vs(d);if(y===void 0)throw new l(`Session ${s} not found (no projects directory)`,"Session not found (no projects directory)");let{names:S}=y;for(let w of S){let E=we(p,w);if(await Xt(we(E,f),c,qr(E,s,d)))return}throw new l(`Session ${s} not found in any project directory`,"Session not found in any project directory")}let m;try{m=await Gs(p)}catch{throw Error(`Session ${s} not found (no projects directory)`)}for(let y of m)if(await Xt(we(p,y,f),c))return;throw Error(`Session ${s} not found in any project directory`)}async function Xt(s,c,u){if(a()&&u!==void 0)return Tc(u,c);let d;try{d=await kc(s,Us.O_WRONLY|Us.O_APPEND)}catch(f){let p=n(f);if(p==="ENOENT"||p==="ENOTDIR")return!1;throw f}try{let{size:f}=await d.stat();if(f===0)return!1;let p=process.platform==="win32"?f:void 0,m=Buffer.from(c,"utf8"),y=0;while(y<m.length){let{bytesWritten:S}=await d.write(m,y,m.length-y,p);if(S<=0)throw new l(`tryAppend: short write to ${s} stalled with ${m.length-y} bytes remaining`,"tryAppend: zero-progress short write");if(y+=S,p!==void 0)p+=S}return!0}finally{await d.close()}}async function Tc({backend:s,key:c},u){let d=await s.append(c,[{data:u}],{precondition:{type:"ifExists",nonEmpty:!0}});if(!d.ok){if(d.error.code==="NotFound")return!1;throw Error("Session append: transcript not writable via storage",{cause:d.error})}return!0}function qr(s,c,u){if(!a()||u===void 0)return;let d=qt(s,u.isKeySegment);return d===void 0?void 0:{backend:u.backend,key:u.transcriptKey(d,c)}}async function xc(s,c,u){if(u?.sessionStore)return Mc(u.sessionStore,s,c,u.dir);return Ws(s,c,u)}async function Ac(s,c,u){if(u?.sessionStore)return Dc(u.sessionStore,s,c,u.dir);return qs(s,c,u)}async function Oc(s,c){if(!ge(s))throw new l(`Invalid sessionId: ${s}`,"deleteSession: invalid sessionId (must be a UUID)");if(c?.sessionStore){if(!c.sessionStore.delete)return;let u=Ce(c.dir);await c.sessionStore.delete({projectKey:u,sessionId:s});return}return zs(s,c)}async function Mc(s,c,u,d){if(!ge(c))throw new l(`Invalid sessionId: ${c}`,"renameSession: invalid sessionId (must be a UUID)");if(!u.trim())throw Error("title must be non-empty");let f=Ce(d);await s.append({projectKey:f,sessionId:c},[{type:"custom-title",customTitle:u.trim(),sessionId:c,uuid:Js(),timestamp:new Date().toISOString()}])}async function Dc(s,c,u,d){if(!ge(c))throw new l(`Invalid sessionId: ${c}`,"tagSession: invalid sessionId (must be a UUID)");if(u!==null){let p=le(u).trim();if(!p)throw Error("tag must be non-empty (use null to clear)");u=p}let f=Ce(d);await s.append({projectKey:f,sessionId:c},[{type:"tag",tag:u??"",sessionId:c,uuid:Js(),timestamp:new Date().toISOString()}])}import{McpServer as Nc}from"@modelcontextprotocol/sdk/server/mcp.js";import{globalRegistry as Xs}from"zod/v4";function Lc(s,c,u,d,f){let p={};if(f?.searchHint)p["anthropic/searchHint"]=f.searchHint;if(f?.alwaysLoad)p["anthropic/alwaysLoad"]=!0;return{name:s,description:c,inputSchema:u,handler:d,annotations:f?.annotations,_meta:Object.keys(p).length>0?p:void 0}}function jc(s){let c=new Nc({name:s.name,version:s.version??"1.0.0"},{capabilities:{tools:s.tools?{}:void 0},instructions:s.instructions});if(s.tools)s.tools.forEach((d)=>{for(let f of Object.values(d.inputSchema)){if(!Fc(f))continue;let p=f.description;if(p&&!Xs.has(f))Xs.add(f,{description:p})}c.registerTool(d.name,{description:d.description,inputSchema:d.inputSchema,annotations:d.annotations,_meta:s.alwaysLoad?{"anthropic/alwaysLoad":!0,...d._meta}:d._meta},d.handler)});let u=dt(s.timeout);return{type:"sdk",name:s.name,instance:c,...u!==void 0&&{timeout:u}}}function Fc(s){return typeof s==="object"&&s!==null&&"_zod"in s}async function Kc(s){let{resolveSettingsForSdk:c}=await import("./core-276encc2.mjs");return c(s)}var Bc=new Set(["bypassPermissions","auto","acceptEdits"]),Uc=new Set(["project"]),$c=new Set(["project","local"]);function Hc(s){let c=s.effective.permissions?.defaultMode;if(!c||!Bc.has(c))return s.effective;for(let u=s.sources.length-1;u>=0;u--){let d=s.sources[u];if(d.settings.permissions?.defaultMode!==void 0){if((Ot.includes(c)?$c:Uc).has(d.source)){let{defaultMode:p,...m}=s.effective.permissions??{};return{...s.effective,permissions:m}}return s.effective}}return s.effective}export{Q as AbortError,vt as EXIT_REASONS,H as HOOK_EVENTS,gt as ORG_POLICY_LIMIT_PREFIXES,xt as SYSTEM_PROMPT_DYNAMIC_BOUNDARY,ft as USAGE_LIMIT_ERROR_PREFIXES,ht as USAGE_TRANSITION_PREFIXES,mt as USAGE_WARNING_PREFIXES,jc as createSdkMcpServer,Oc as deleteSession,Hc as filterEscalatingDefaultMode,uc as query,xc as renameSession,Kc as resolveSettings,fc as startup,Ac as tagSession,Lc as tool};
package/manifest.json CHANGED
@@ -1,56 +1,53 @@
1
1
  {
2
- "version": "2.1.280",
2
+ "version": "2.1.282",
3
3
  "manifestSignatureEnforcement": "flag",
4
- "commit": "80abbfe7d7232280011ff01a21ae3338f4c6e372",
5
- "modsCommit": "8187baaaafb3a9ada02d3d6fb4e8d68587aef6b0",
6
- "buildDate": "2026-09-21T20:55:27Z",
4
+ "commit": "88e628ac87357ab077f78e21f78aee6156f01ab3",
5
+ "modsCommit": "d78be9481b889e11186ec4578b4f5e9301396e25",
6
+ "buildDate": "2026-09-24T04:11:54Z",
7
7
  "platforms": {
8
8
  "darwin-arm64": {
9
9
  "binary": "claude",
10
- "checksum": "387a5c5dcdbb815085edf0baf79591f9d8894efe922bceaf3d75b1b08055229d",
11
- "size": 217254576
10
+ "checksum": "fcfd837103965c64de34a6b9b94370d77a347ea71819715a27d5f0ef01775ea4",
11
+ "size": 222245312
12
12
  },
13
13
  "darwin-x64": {
14
14
  "binary": "claude",
15
- "checksum": "c1d32d87630482250633208ab77855429b24010ae3086a7ff7539b57b93168d4",
16
- "size": 225565024
15
+ "checksum": "5c34b00b5c0f3862b76011015c334e91904c4593afea7a5451e00746ad7934c1",
16
+ "size": 230651344
17
17
  },
18
18
  "linux-arm64": {
19
19
  "binary": "claude",
20
- "checksum": "92f2b4fd05d0bdcf7b9a0d4e0ecef4a1e4b368b290cd8fd07cff9a50013f45a2",
21
- "size": 233103352
20
+ "checksum": "6764ffc39e9fed425a493ff61ea28506d1ba83996ce81a48d1177dbb393419c9",
21
+ "size": 238084088
22
22
  },
23
23
  "linux-x64": {
24
24
  "binary": "claude",
25
- "checksum": "1e08503dbdf3c2cb0d706d32f3408277388d1c76ef108673e8fe42c1b322925b",
26
- "size": 233709640
25
+ "checksum": "3afe8535c0cc33f0e24f7b25dab7a1727b8b592196f8496a8bc302ba2161eed3",
26
+ "size": 238767288
27
27
  },
28
28
  "linux-arm64-musl": {
29
29
  "binary": "claude",
30
- "checksum": "6a9f349dccd1c74ab854f1877c5ebdf074998571d0177e26c1f7f46f29e0f971",
31
- "size": 225457992
30
+ "checksum": "5c3b3c9904f84b59d01c4e7f5c9305a4fc1981b18b26745688c9c1dab9cb25ae",
31
+ "size": 230438720
32
32
  },
33
33
  "linux-x64-musl": {
34
34
  "binary": "claude",
35
- "checksum": "8d25ffbf600882d7b985706cc10ea45995060637ed009b5700b65e162bb00b96",
36
- "size": 227467360
35
+ "checksum": "e01fc77a210c54acf69205db13d8d50d11fa6ac62b81b6c6201de8440c293b0d",
36
+ "size": 232525912
37
37
  },
38
38
  "win32-x64": {
39
39
  "binary": "claude.exe",
40
- "checksum": "0e4195524b73eb77efbdf3e2b36de5322a29f0ca575dfd2d9b4f946b1d425469",
41
- "size": 237100192
40
+ "checksum": "fc0e3af017705624b9e1bce913f72761864ff994804514da1f5e41380fca4484",
41
+ "size": 242171040
42
42
  },
43
43
  "win32-arm64": {
44
44
  "binary": "claude.exe",
45
- "checksum": "f49980314f4c0418079979723ffd6c0d00d57e60b26fd95c53e53155ed913bdf",
46
- "size": 225107104
45
+ "checksum": "a7f3db85706ca2ca123ea9088e565f10a657a15a0f5d7b9b34283609d857de25",
46
+ "size": 229716640
47
47
  }
48
48
  },
49
49
  "sdkCompat": {
50
50
  "testedWrapperVersions": [
51
- "0.3.240",
52
- "0.3.241",
53
- "0.3.242",
54
51
  "0.3.243",
55
52
  "0.3.245",
56
53
  "0.3.246",
@@ -65,6 +62,7 @@
65
62
  "0.3.260",
66
63
  "0.3.261",
67
64
  "0.3.263",
65
+ "0.3.265",
68
66
  "0.3.266",
69
67
  "0.3.267",
70
68
  "0.3.268",
@@ -77,7 +75,9 @@
77
75
  "0.3.275",
78
76
  "0.3.276",
79
77
  "0.3.277",
80
- "0.3.278"
78
+ "0.3.278",
79
+ "0.3.280",
80
+ "0.3.281"
81
81
  ],
82
82
  "harnessSchema": 1
83
83
  }
package/manifest.zst.json CHANGED
@@ -1,64 +1,61 @@
1
1
  {
2
- "version": "2.1.280",
2
+ "version": "2.1.282",
3
3
  "manifestSignatureEnforcement": "flag",
4
- "commit": "80abbfe7d7232280011ff01a21ae3338f4c6e372",
5
- "modsCommit": "8187baaaafb3a9ada02d3d6fb4e8d68587aef6b0",
6
- "buildDate": "2026-09-21T20:56:45Z",
4
+ "commit": "88e628ac87357ab077f78e21f78aee6156f01ab3",
5
+ "modsCommit": "d78be9481b889e11186ec4578b4f5e9301396e25",
6
+ "buildDate": "2026-09-24T04:15:55Z",
7
7
  "platforms": {
8
8
  "darwin-arm64": {
9
9
  "binary": "claude.zst",
10
- "checksum": "214fafd9d60bc0397cb68747b765ab752be4b53303c176ad885c4cafbe30826f",
11
- "size": 72900982,
10
+ "checksum": "24d8df8b46f586b34de052785dfe48b1b87253e298aa7deefe90115742203a34",
11
+ "size": 74623769,
12
12
  "bundle": {
13
- "checksum": "5882f558c44d569dd35047588143a536711d4e415bebf94da1543a25e5bc5898",
14
- "size": 72903461
13
+ "checksum": "a772c6fe9f376aaff3dea002799075779a674d3eccbd3a0e6a51dc3e5fec8fbe",
14
+ "size": 74632542
15
15
  }
16
16
  },
17
17
  "darwin-x64": {
18
18
  "binary": "claude.zst",
19
- "checksum": "2b5ca074d02ea5dd507db0a90ba55847e297061ca3e987ddc49ea89ae0ff2e7e",
20
- "size": 77008555,
19
+ "checksum": "e9186c596fa94ab38281d48e4d63de409af21693210da6bc5e2e8be359ab1afd",
20
+ "size": 78765139,
21
21
  "bundle": {
22
- "checksum": "bf78bfd5af2400f39d21378198f689c3856d7a11aeb9919b012f27143e946cbf",
23
- "size": 77013965
22
+ "checksum": "6c3bec078e786fbb82242abfc5a640c63870bdb15e7a160f01f8bcfc0c2efc04",
23
+ "size": 78769287
24
24
  }
25
25
  },
26
26
  "linux-arm64": {
27
27
  "binary": "claude.zst",
28
- "checksum": "6a01f30418f35122a672ccf74bed64aba5119ad47c71548a3b447cc9fec48c81",
29
- "size": 82030081
28
+ "checksum": "8713924ab6e0d6a887582fa6ce9a60c3bb8b3f7393f84fda3c3b10815083a5bc",
29
+ "size": 83741828
30
30
  },
31
31
  "linux-x64": {
32
32
  "binary": "claude.zst",
33
- "checksum": "27910e2ae704d8f2e8024897d8fdf1e7710807baf4f6982c0e3797c058315384",
34
- "size": 82761570
33
+ "checksum": "4a3f8c0033f5ce1cbb6454a91da57e0a2807372772f4bfacb8d50d9f77ed9331",
34
+ "size": 84467065
35
35
  },
36
36
  "linux-arm64-musl": {
37
37
  "binary": "claude.zst",
38
- "checksum": "32dbe8a94da9689791688e0febfb88c39897ad67f055853e7ae1b6d11c4b4e39",
39
- "size": 80444179
38
+ "checksum": "a6930e25465432eeba78babcbc3a8c05fec92766768093bea4d07a78053da6c1",
39
+ "size": 82151974
40
40
  },
41
41
  "linux-x64-musl": {
42
42
  "binary": "claude.zst",
43
- "checksum": "2b2e206987e357997bf5c06baf697379b5980a7cc6f1462ca70a6757ece58890",
44
- "size": 81193598
43
+ "checksum": "0203212b59740d4a19dcd3963da280c6458e49134c94c3a0760aecd9596c645b",
44
+ "size": 82897876
45
45
  },
46
46
  "win32-x64": {
47
47
  "binary": "claude.exe.zst",
48
- "checksum": "cb50dbe5b595b52925d753b10d5907748a4137e7f0bff84d03ea60cd9a28eaf9",
49
- "size": 85069447
48
+ "checksum": "aefae8091a92ce977047cb0d45d05935e92e30d7894e304d8bb3188c14916c8c",
49
+ "size": 86770961
50
50
  },
51
51
  "win32-arm64": {
52
52
  "binary": "claude.exe.zst",
53
- "checksum": "705dccf9d924d471e32efa19157283da2cdd0b8cfc71d7e0a9e3ec4d13ac381b",
54
- "size": 81530251
53
+ "checksum": "1a6cbd27f4d53e3af049ac843bed908a63736818f76203f00b970653b0d7f399",
54
+ "size": 83099205
55
55
  }
56
56
  },
57
57
  "sdkCompat": {
58
58
  "testedWrapperVersions": [
59
- "0.3.240",
60
- "0.3.241",
61
- "0.3.242",
62
59
  "0.3.243",
63
60
  "0.3.245",
64
61
  "0.3.246",
@@ -73,6 +70,7 @@
73
70
  "0.3.260",
74
71
  "0.3.261",
75
72
  "0.3.263",
73
+ "0.3.265",
76
74
  "0.3.266",
77
75
  "0.3.267",
78
76
  "0.3.268",
@@ -85,7 +83,9 @@
85
83
  "0.3.275",
86
84
  "0.3.276",
87
85
  "0.3.277",
88
- "0.3.278"
86
+ "0.3.278",
87
+ "0.3.280",
88
+ "0.3.281"
89
89
  ],
90
90
  "harnessSchema": 1
91
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anthropic-ai/claude-agent-sdk",
3
- "version": "0.3.280",
3
+ "version": "0.3.282",
4
4
  "main": "sdk.mjs",
5
5
  "types": "sdk.d.ts",
6
6
  "exports": {
@@ -8,6 +8,10 @@
8
8
  "types": "./sdk.d.ts",
9
9
  "default": "./sdk.mjs"
10
10
  },
11
+ "./core": {
12
+ "types": "./core.d.ts",
13
+ "default": "./core.mjs"
14
+ },
11
15
  "./extract": {
12
16
  "types": "./extractFromBunfs.d.ts",
13
17
  "default": "./extractFromBunfs.js"
@@ -57,18 +61,20 @@
57
61
  "zod": "^4.0.0"
58
62
  },
59
63
  "optionalDependencies": {
60
- "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.280",
61
- "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.280",
62
- "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.280",
63
- "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.280",
64
- "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.280",
65
- "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.280",
66
- "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.280",
67
- "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.280"
64
+ "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.282",
65
+ "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.282",
66
+ "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.282",
67
+ "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.282",
68
+ "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.282",
69
+ "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.282",
70
+ "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.282",
71
+ "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.282"
68
72
  },
69
73
  "files": [
70
74
  "sdk.mjs",
71
75
  "sdk.d.ts",
76
+ "core.mjs",
77
+ "core.d.ts",
72
78
  "sdk-tools.d.ts",
73
79
  "agentSdkTypes.d.ts",
74
80
  "bridge.mjs",
@@ -78,7 +84,9 @@
78
84
  "extractFromBunfs.js",
79
85
  "extractFromBunfs.d.ts",
80
86
  "manifest.json",
81
- "manifest.zst.json"
87
+ "manifest.zst.json",
88
+ "core-276encc2.mjs",
89
+ "core-5drmq1nt.mjs"
82
90
  ],
83
- "claudeCodeVersion": "2.1.280"
91
+ "claudeCodeVersion": "2.1.282"
84
92
  }