@famonfa/mono 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/bin/mono.mjs +211 -0
  2. package/node_modules/@anthropic-ai/claude-agent-sdk/LICENSE.md +1 -0
  3. package/node_modules/@anthropic-ai/claude-agent-sdk/README.md +69 -0
  4. package/node_modules/@anthropic-ai/claude-agent-sdk/agentSdkTypes.d.ts +1 -0
  5. package/node_modules/@anthropic-ai/claude-agent-sdk/bridge.d.ts +396 -0
  6. package/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +142 -0
  7. package/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.d.ts +208 -0
  8. package/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +145 -0
  9. package/node_modules/@anthropic-ai/claude-agent-sdk/core-36zyfan5.mjs +52 -0
  10. package/node_modules/@anthropic-ai/claude-agent-sdk/core-5682eevd.mjs +27 -0
  11. package/node_modules/@anthropic-ai/claude-agent-sdk/core-nne0e2ds.mjs +40 -0
  12. package/node_modules/@anthropic-ai/claude-agent-sdk/core-xpxe8nzb.mjs +26 -0
  13. package/node_modules/@anthropic-ai/claude-agent-sdk/core.d.ts +22 -0
  14. package/node_modules/@anthropic-ai/claude-agent-sdk/core.mjs +34 -0
  15. package/node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.d.ts +1 -0
  16. package/node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js +156 -0
  17. package/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +82 -0
  18. package/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +90 -0
  19. package/node_modules/@anthropic-ai/claude-agent-sdk/package.json +94 -0
  20. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk-tools.d.ts +4222 -0
  21. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts +10277 -0
  22. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +169 -0
  23. package/node_modules/ws/LICENSE +20 -0
  24. package/node_modules/ws/README.md +548 -0
  25. package/node_modules/ws/browser.js +8 -0
  26. package/node_modules/ws/index.js +22 -0
  27. package/node_modules/ws/lib/buffer-util.js +131 -0
  28. package/node_modules/ws/lib/constants.js +19 -0
  29. package/node_modules/ws/lib/event-target.js +292 -0
  30. package/node_modules/ws/lib/extension.js +203 -0
  31. package/node_modules/ws/lib/limiter.js +55 -0
  32. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  33. package/node_modules/ws/lib/receiver.js +743 -0
  34. package/node_modules/ws/lib/sender.js +607 -0
  35. package/node_modules/ws/lib/stream.js +161 -0
  36. package/node_modules/ws/lib/subprotocol.js +62 -0
  37. package/node_modules/ws/lib/validation.js +152 -0
  38. package/node_modules/ws/lib/websocket-server.js +562 -0
  39. package/node_modules/ws/lib/websocket.js +1421 -0
  40. package/node_modules/ws/package.json +74 -0
  41. package/node_modules/ws/wrapper.mjs +21 -0
  42. package/package.json +126 -3
  43. package/skills/workspace/SKILL.md +108 -0
  44. package/src/api.mjs +298 -0
  45. package/src/chats.mjs +446 -0
  46. package/src/commands.mjs +100 -0
  47. package/src/groups.mjs +84 -0
  48. package/src/launcher.mjs +276 -0
  49. package/src/main.mjs +42 -0
  50. package/src/paths.mjs +44 -0
  51. package/src/projects.mjs +199 -0
  52. package/src/refresh.mjs +124 -0
  53. package/src/remote.mjs +137 -0
  54. package/src/sessions.mjs +422 -0
  55. package/src/store.mjs +253 -0
  56. package/web/apple-touch-icon.png +0 -0
  57. package/web/assets/index-DGdmgZ2P.css +1 -0
  58. package/web/assets/index-TOP7citk.js +55 -0
  59. package/web/icon-192.png +0 -0
  60. package/web/icon-512.png +0 -0
  61. package/web/icon.svg +1 -0
  62. package/web/index.html +19 -0
  63. package/web/manifest.webmanifest +13 -0
  64. package/README.md +0 -3
@@ -0,0 +1,22 @@
1
+ export {
2
+ AbortError,
3
+ BUILTIN_TOOL_NAMES,
4
+ createSdkMcpServer,
5
+ deleteSession,
6
+ EXIT_REASONS,
7
+ filterEscalatingDefaultMode,
8
+ HOOK_EVENTS,
9
+ LEGACY_TOOL_NAME_ALIASES,
10
+ ORG_POLICY_LIMIT_PREFIXES,
11
+ query,
12
+ renameSession,
13
+ resolveSettings,
14
+ startup,
15
+ SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
16
+ tagSession,
17
+ tool,
18
+ USAGE_LIMIT_ERROR_PREFIXES,
19
+ USAGE_TRANSITION_PREFIXES,
20
+ USAGE_WARNING_PREFIXES,
21
+ } from './sdk.js'
22
+ export type * from './sdk.js'
@@ -0,0 +1,34 @@
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.308
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{Re,i,o,A,ee,l,w,Vt,N,d,r,We,Rt,g,Ot,Ne,U,I,ct,x,J,yn,bn,oe,wt,qe,Xt,Qt,en,tn,nn,rn,Xe,me,Se,Ue,ft,gt,T,n,y,e,ln,ye,K,be,ie,t,Et,cn,Nt,Ut,un,Ce,dn,fn,Ae,j,Bt,le,gn,Gt,_n}from"./core-nne0e2ds.mjs";import{execFile as Zo}from"child_process";import{randomUUID as Jo}from"crypto";import{mkdir as _r,mkdtemp as Yc,readFile as ei,rm as ti,writeFile as Ys}from"fs/promises";import{createRequire as ri}from"module";import{homedir as yr,tmpdir as si}from"os";import{dirname as Ws,isAbsolute as ni,join as z,posix as oi,resolve as St,sep as ii,win32 as ai}from"path";import{fileURLToPath as li}from"url";import{setMaxListeners as xn}from"events";var On=50;function He(s=On){let a=new AbortController;return xn(s,a.signal),a}var Bi=new FinalizationRegistry(({parentSignalRef:s,handler:a})=>{s.deref()?.removeEventListener("abort",a)});var Dn="ask-withdrawn-by-asker",zi=new DOMException(Dn,"AbortError");var Hi={"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 In="server-fallback-tombstone";var qi=new DOMException(In,"AbortError");var Nn="subagent-park",Gi=new DOMException(Nn,"AbortError");import{spawn as io}from"child_process";import{existsSync as ao}from"fs";import{createInterface as lo}from"readline";import{StringDecoder as co}from"string_decoder";var Ln=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var $t={bearer:[/\bBearer\s+(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%[0-9A-Fa-f]{2}){7})[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]+|%[0-9A-Fa-f]{2})*/gi,"Bearer <token>"],basic:[/(:\s*)Basic\s+[A-Za-z0-9+/=]{8,}/gi,"$1Basic <token>"],sk:[/\bsk-[A-Za-z0-9_-]{20,}/g,"<token>"]},Kn=[/\bBearer\s{1,512}(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){15})(?:eyJ|(?=(?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){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 Vi=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${ke("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${ke("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),Nr=[[Ge("sk-ant-","[A-Za-z0-9_-]",8,jt(8)),"<token>"],[Ge("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,jt(20)),"<token>"]],Lr=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],Fn=`(?:${Lr.join("|")})`,Kr=[[new RegExp(`(^|[^A-Za-z0-9+])${Fn}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],Fr=[[Ge("gh[opusr]_","[A-Za-z0-9]",20,ke("[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>"],[Ge("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,ke("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[Ge("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",ke("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${ke("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[Ln,"hooks.slack.com/<redacted>"]];var Un=[new RegExp("(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*)((?:[A-Za-z0-9_-]*?-)??)ey[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*","g"),"$1<jwt>"],$n=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,Ur=[[/(^|[^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>"]],$r=[[/(^|[^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>"]],jn=[$t.bearer,$t.basic,...Nr,$t.sk,...Kr],Bn=[...Fr,Un,...Ur,...$r],Qi=[[new RegExp(`sk-${jt(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...Lr.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 Ve(s){return[...jn,...Bn].reduce((a,[c,u])=>a.replace(c,u),String(s))}var Yi=[...Kn,...[...Nr,...Kr,...Fr,...Ur,...$r].map(([s])=>new RegExp(s.source,s.flags.replaceAll("g",""))),$n];function Ge(s,a,c,u,p="",f="",m="g"){let h=`${a}{${c},}${p}`;return new RegExp(`(?:\\b${s}${f}${h}|${s}${u}${h})`,m)}function ke(s){return`(?=${s}{0,64}[0-9])`}function jt(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 Zn}from"crypto";import{join as Gr}from"path";import{AsyncLocalStorage as zn}from"async_hooks";import{constants as Hn}from"fs";import{appendFile as qn,copyFile as Gn,lstat as Wn,mkdir as Vn,open as jr,readdir as Br,readFile as zr,stat as Qn,unlink as Yn,writeFile as zt}from"fs/promises";class qr{read(s){return zr(s,"utf8")}readBytes(s){return zr(s)}write(s,a,c){return zt(s,a,{encoding:"utf8",mode:c})}async mkdir(s,a){try{await Vn(s,{recursive:!0,mode:a})}catch(c){if(r(c)!=="EEXIST")throw c}}atomicWrite(s,a,c){return ln(s,a,c)}delete(s){return Yn(s)}list(s){return Br(s)}append(s,a,c){return qn(s,a,{encoding:"utf8",mode:c})}writeExclusive(s,a,c){return zt(s,a,{encoding:"utf8",flag:"wx",mode:c})}writeBytesExclusive(s,a,c){return zt(s,a,{flag:"wx",mode:c})}copy(s,a){return Gn(s,a)}async stat(s){return{mtimeMs:(await Qn(s)).mtimeMs}}async lstat(s){try{let a=await Wn(s);return{isSymbolicLink:a.isSymbolicLink(),isFile:a.isFile(),isDirectory:a.isDirectory(),mtimeMs:a.mtimeMs,nlink:a.nlink}}catch(a){if(r(a)==="ENOENT")return;throw a}}async listEntries(s){return(await Br(s,{withFileTypes:!0})).map((c)=>({name:c.name,isDirectory:c.isDirectory(),isFile:c.isFile()}))}async readRange(s,a,c){Ht("readRange","offset",a),Ht("readRange","length",c);let u=await jr(s,"r");try{return await Hr(u,a,c)}finally{await u.close()}}async readTail(s,a,c){Ht("readTail","maxBytes",a);let u=c?.noFollow?Hn.O_RDONLY|ye:"r",p=await jr(s,u);try{let f=await p.stat();if(c?.noFollow&&!f.isFile())throw Object.assign(Error("ENXIO: not a regular file"),{code:"ENXIO",path:s});let{size:m}=f,h=Math.min(a,m);return await Hr(p,m-h,h)}finally{await p.close()}}}function Ht(s,a,c){if(!Number.isInteger(c)||c<0)throw RangeError(`${s}: ${a} must be a non-negative integer, got ${c}`)}async function Hr(s,a,c){if(c===0)return Buffer.alloc(0);let u=Buffer.alloc(c),p=0;while(p<c){let{bytesRead:f}=await s.read(u,p,c-p,a+p);if(f===0)break;p+=f}return p===c?u:Buffer.from(u.subarray(0,p))}var Xn=new zn;function qt(){return Xn.getStore()??new qr}class Wr{debugFilePath=void 0;initPromise=null;logStem=null}var Jn=new i(()=>new Wr);function Vr(){return Jn.of(x().host)}function Qr(s){if(s.initPromise)return s.initPromise;if(!gt("DEBUG_CLAUDE_AGENT_SDK"))return s.debugFilePath=null,s.initPromise=Promise.resolve(),s.initPromise;let a=Gr(T(),"debug");return s.logStem=`sdk-${Zn()}`,s.debugFilePath=Gr(a,`${s.logStem}.txt`),process.stderr.write(`SDK debug logs: ${s.debugFilePath}
26
+ `),s.initPromise=qt().mkdir(a).catch(()=>{}),s.initPromise}function eo(s){return s.logStem===null?null:{namespace:"log",sessionId:s.logStem,channel:"debug"}}function Yr(){let s=Vr();return Qr(s),s.debugFilePath??null}function W(s,a){let c=Vr();if(c.debugFilePath===null)return;let p=`${new Date().toISOString()} ${s}
27
+ `;Qr(c).then(()=>{if(a!==void 0){let f=eo(c);if(f!==null)a.append(f,[{data:p}]).catch(()=>{});return}if(c.debugFilePath)qt().append(c.debugFilePath,p).catch(()=>{})})}function to(s){let a=s.trim();return a.startsWith("{")&&a.endsWith("}")}var ro=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),so=new Set(["ripgrep","network.tlsTerminate"]),no=new Set(["__proto__","constructor","prototype"]),oo=["httpProxyPort","socksProxyPort"];function Xr(s,a,c=""){let u=K(s)?{...s}:{};for(let[p,f]of Object.entries(a)){if(no.has(p)||f===void 0)continue;let m=c?`${c}.${p}`:p,h=Object.hasOwn(u,p)?u[p]:void 0;if(ro.has(m)&&Array.isArray(h)&&Array.isArray(f))u[p]=A([...h,...f]);else if(K(h)&&K(f)&&!so.has(m))u[p]=Xr(h,f,m);else u[p]=f}return u}function Zr(s,a){let c={...s};if(!a)return c;let u=c.settings;if(u&&!to(u))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let p={};if(u)try{p=y(u)}catch{}let f=Xr(p.sandbox,a),m=a.credentials?.files,h=a.filesystem!==void 0||Array.isArray(m)&&m.some((v)=>K(v)&&v.mode==="deny"),S=f.filesystem;if(h&&a.filesystem?.disabled===void 0&&K(S)&&S.disabled===!0)delete S.disabled;let C=a.network,b=C?.allowedDomains!==void 0||(C?.deniedDomains?.length??0)>0||C?.strictAllowlist===!0,_=f.network;if(b&&K(_)){for(let v of oo)if(C?.[v]===void 0&&_[v]!==void 0)delete _[v]}if(a.enabled===!0&&f.failIfUnavailable===void 0)f.failIfUnavailable=!0;return c.settings=n({...p,sandbox:f}),c}function O(s,a){return`${s}=${a}`}function ot(s,a){let c=String(a);if(c.length>1&&c.startsWith("-"))return[O(s,c)];return[s,c]}function Jr(s,a,c){s.push(...ot(`--${a}`,c))}var uo=2000,Wt=2048,rs="sdk-exit-after-stderr-drained",po=200;function Yt(s){return s==="exit"?rs:s}class ss{#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 it=new ss,fo=/[(),\u0000-\u001f\u007f-\u009f]/;function mo(s){if(typeof s!=="string"||s.trim()==="")throw Error("Skill names must be non-empty strings.");if(!qe(s))throw new l(`Invalid skill name ${n(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 ${n(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(fo.test(s))throw new l(`Invalid skill name ${n(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 ${n(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 ${n(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 ${n(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 ${n(s)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return s}class Jt{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";exitListeners=[];abortHandler;forwardedAbort=He();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(s){this.options=s;if(this.abortController=s.abortController||He(),s.deferSpawn)this.spawnPromise=new Promise((a,c)=>{this.spawnResolve=a,this.spawnReject=c}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(a){throw this.spawnAbort(N(a)),a}let s=this.pendingWrites;if(this.pendingWrites=[],this.spawnResolve)this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0;for(let a of s)this.write(a);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 Se()?"bun":"node"}spawnLocalProcess(s){let{command:a,args:c,cwd:u,env:p,signal:f}=s,m=io(a,c,{cwd:u,stdio:["pipe","pipe","pipe"],signal:f,env:p,windowsHide:!0});if(m.pid!==void 0&&this.options.onProcessSpawned)try{this.options.onProcessSpawned(m.pid)}catch(P){W(`onProcessSpawned threw: ${d(P)}`)}let h=new co("utf8"),S=!1,C=!1,b=!1,_,v=o(p.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;m.stderr.on("data",(P)=>{if(b)return;let F=h.write(P);if(this.stderrTail+=F,this.stderrTail.length>2*Wt)this.stderrTail=wt(Ve(this.stderrTail),Wt);if(v)W(F),this.options.stderr?.(F)}),m.stderr.on("error",(P)=>{W(`[ProcessTransport] stderr read failed: ${P.code??P.message}`)});let R=()=>{if(b)return;if(b=!0,_)clearTimeout(_);m.emit(rs,m.exitCode,m.signalCode);let P=m.stderr;if(_o(P))P.unref();else P.destroy()};return m.stderr.once("close",()=>{if(this.stderrTail+=h.end(),S=!0,C)R()}),m.once("exit",()=>{if(C=!0,this.ready=!1,S)R();else _=setTimeout(R,po)}),{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:(P,F)=>m.on(Yt(P),F),once:(P,F)=>m.once(Yt(P),F),off:(P,F)=>m.off(Yt(P),F)}}initialize(){try{let{additionalDirectories:s=[],projectConfigRoot:a,agent:c,betas:u,cwd:p,executable:f=this.getDefaultExecutable(),executableArgs:m=[],extraArgs:h={},pathToClaudeCodeExecutable:S,env:C={...process.env},thinkingConfig:b,maxTurns:_,maxBudgetUsd:v,taskBudget:R,model:E,fallbackModel:P,jsonSchema:F,permissionMode:D,allowDangerouslySkipPermissions:H,permissionPromptToolName:ue,permissionPrompts:Z,continueConversation:Je,resume:et,settingSources:he,skills:_e,disallowedTools:tt=[],tools:De,mcpServers:Ie,strictMcpConfig:Ct,canUseTool:vt,includePartialMessages:te,plugins:Le,pluginsViaInitialize:kt,sandbox:rt}=this.options,{allowedTools:de=[]}=this.options;if(_e!==void 0){let M=_e==="all"?["Skill"]:_e.map((G)=>`Skill(${mo(G)})`),Y=new Set(de);de=[...de,...M.filter((G)=>!Y.has(G))]}let k=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(b){switch(b.type){case"enabled":if(b.budgetTokens===void 0)k.push("--thinking=adaptive");else k.push(O("--max-thinking-tokens",b.budgetTokens));break;case"disabled":k.push("--thinking=disabled");break;case"adaptive":k.push("--thinking=adaptive");break}if(b.type!=="disabled"&&b.display)k.push(O("--thinking-display",b.display))}if(this.options.effort)k.push(O("--effort",this.options.effort));if(_)k.push(O("--max-turns",_));if(v!==void 0)k.push(O("--max-budget-usd",v));if(R)k.push(O("--task-budget",R.total));if(E)k.push(O("--model",E));if(c)k.push(O("--agent",c));if(u&&u.length>0)k.push(O("--betas",u.join(",")));if(F)k.push(O("--json-schema",n(F)));if(this.options.debugFile)k.push(O("--debug-file",this.options.debugFile));else if(this.options.debug)k.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let M=Yr();if(M)k.push(O("--debug-file",M))}if(vt){if(ue)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");k.push("--permission-prompt-tool=stdio")}else if(ue)k.push(O("--permission-prompt-tool",ue));if(Z)k.push(O("--permission-prompts",Z));if(Je)k.push("--continue");if(et)k.push(O("--resume",et));if(this.options.channels&&this.options.channels.length>0)for(let M of this.options.channels)k.push(O("--channels",M));if(de.length>0)k.push(O("--allowedTools",de.join(",")));if(tt.length>0)k.push(O("--disallowedTools",tt.join(",")));if(De!==void 0)if(Array.isArray(De))k.push(O("--tools",De.join(",")));else k.push("--tools=default");if(Ie&&Object.keys(Ie).length>0)k.push(...ot("--mcp-config",n({mcpServers:Ie})));if(he!==void 0)k.push(O("--setting-sources",he.join(",")));if(Ct)k.push("--strict-mcp-config");if(D)k.push(O("--permission-mode",D));if(H)k.push("--allow-dangerously-skip-permissions");if(P){if(E&&P===E)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");k.push(O("--fallback-model",P))}if(this.options.includeHookEvents)k.push("--include-hook-events");if(te)k.push("--include-partial-messages");if(this.options.sessionMirror)k.push("--session-mirror");if(a!==void 0)k.push(O("--project-config-root",a));for(let M of s)k.push(O("--add-dir",M));if(kt)k.push("--await-initialize");else if(Le&&Le.length>0)for(let M of Le)if(M.type==="local")k.push(M.skipMcpDiscovery?O("--plugin-dir-no-mcp",M.path):O("--plugin-dir",M.path));else throw Error(`Unsupported plugin type: ${M.type}`);if(this.options.forkSession)k.push("--fork-session");if(this.options.resumeSessionAt)k.push(O("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)k.push(O("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)k.push(O("--session-id",this.options.sessionId));if(this.options.persistSession===!1)k.push("--no-session-persistence");if(this.options.managedSettings)k.push(...ot("--managed-settings",this.options.managedSettings));let pe={...h??{}};if(this.options.settings)pe.settings=this.options.settings;let At=Zr(pe,rt);for(let[M,Y]of Object.entries(At))if(Y===null)k.push(`--${M}`);else Jr(k,M,Y);if(!C.CLAUDE_CODE_ENTRYPOINT)C.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete C.NODE_OPTIONS,o(C.DEBUG_CLAUDE_AGENT_SDK))C.DEBUG="1";else delete C.DEBUG;let Ee=go(S),Ke=Ee?S:f,Fe=Ee?[...m,...k]:[...m,S,...k],st={command:Ke,args:Fe,cwd:p,env:C,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)W(`Spawning Claude Code (custom): ${Ke} ${Fe.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(st);else W(`Spawning Claude Code: ${Ke} ${Fe.join(" ")}`),this.process=this.spawnLocalProcess(st);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(M)=>{W(`[ProcessTransport] stdin write failed (child likely exited): ${M.code??M.message}`),this.ready=!1}),it.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let fe=this.process;fe.on("error",(M)=>{this.ready=!1;let Y=M,G=Y.syscall!==void 0?Y.syscall.startsWith("spawn"):Ot(M);if(G&&!fe.killed)it.untrack(fe);if(this.abortController.signal.aborted)this.exitError=at(),w(M,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(G&&Ot(M)){let{message:ve,telemetryMessage:Tt,errorClass:Pt}=ho(S,Ee),$e={telemetryMessage:`${Tt}${Zt(M)}`,errorClass:Pt,code:We(M)};this.exitError=w(ReferenceError(ve),$e),w(M,$e),W(this.exitError.message)}else{let ve={telemetryMessage:G?`Failed to spawn Claude Code process${Zt(M)}`:`Claude Code process error${Zt(M)}`,errorClass:G?"spawn_failed":"process_error",code:We(M)};this.exitError=w(Error(`Failed to spawn Claude Code process: ${Ve(M.message)}`),ve),w(M,ve),W(this.exitError.message)}}),fe.on("exit",(M,Y)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=at();else{let G=this.getProcessExitError(M,Y);if(G)this.exitError=G,W(G.message)}}),this.ready=!this.abortController.signal.aborted}catch(s){throw this.ready=!1,s}}getProcessExitError(s,a){if(s!==0&&s!==null){let c=Number.isInteger(s)?s:void 0;return w(Error(`Claude Code process exited with code ${s}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process exited with code ${c??"unknown"}`,errorClass:"process_exited_nonzero",exitCode:c})}else if(a){let c=/^SIG[A-Z0-9]{1,8}$/.test(a)?a:"unknown";return w(Error(`Claude Code process terminated by signal ${a}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process terminated by signal ${c}`,errorClass:"process_killed_by_signal",signal:c})}return}formatStderrTail(){let s=wt(Ve(this.stderrTail),Wt).trim();return s?`. stderr: ${s}`:""}write(s){if(this.abortController.signal.aborted)throw es();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){W("[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 w(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${Vt(this.exitError)??"untagged exit error"}`,errorClass:ts(this.exitError,"errorClass"),code:We(this.exitError),exitCode:So(this.exitError),signal:ts(this.exitError,"signal")});W(`[ProcessTransport] Writing to stdin: ${s.substring(0,100)}`);try{if(!this.processStdin.write(s))W("[ProcessTransport] Write buffer full, data queued")}catch(a){throw this.ready=!1,Error(`Failed to write to process stdin: ${d(a)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?at():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,a=this.process?.signalCode??null,c=!this.exitEventDelivered&&(s!==null&&s>=0||a!==null),u;if(c){if(this.exitEventDelivered=!0,u=this.abortController.signal.aborted?at():this.getProcessExitError(s,a),u&&!this.exitError)this.exitError=u}let p=this.exitListeners;this.exitListeners=[];for(let{callback:h,handler:S}of p)if(this.process?.off("exit",S),c)try{h(u)}catch(C){W(`[ProcessTransport] onExit callback threw during close(): ${d(C)}`)}let f=()=>{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((h,S)=>{if(h.exitCode!==null||h.signalCode!=null){S();return}if(process.platform==="win32"){setTimeout((C,b)=>{if(C.exitCode===null)C.kill("SIGKILL");b()},5000,h,S).unref();return}h.kill("SIGTERM"),setTimeout((C)=>{if(C.exitCode===null)C.kill("SIGKILL")},5000,h).unref(),S()},uo,m,f).unref(),m.once("exit",()=>it.untrack(m));else if(m)it.untrack(m),f();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=lo({input:this.processStdout}),a=this.process?(()=>{let c=this.process,u=()=>s.close();return c.on("error",u),()=>c.off("error",u)})():void 0;if(this.exitError)s.close();try{for await(let c of s)if(c.trim()){let u;try{u=y(c)}catch(p){W(`Non-JSON stdout: ${c}`);continue}yield u}if(this.exitError)throw this.exitError;await this.waitForExit()}finally{a?.(),s.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}if(this.processStdin)this.processStdin.end()}onExit(s){if(!this.process)return()=>{};let a=(c,u)=>{let p=this.getProcessExitError(c,u);s(p)};return this.process.on("exit",a),this.exitListeners.push({callback:s,handler:a}),()=>{if(this.process)this.process.off("exit",a);let c=this.exitListeners.findIndex((u)=>u.handler===a);if(c!==-1)this.exitListeners.splice(c,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,a)=>{let c=(p,f)=>{if(this.abortController.signal.aborted){a(es());return}let m=this.getProcessExitError(p,f);if(m)a(m);else s()};this.process.once("exit",c);let u=(p)=>{this.process.off("exit",c),a(p)};this.process.once("error",u),this.process.once("exit",()=>{this.process.off("error",u)})})}}function go(s){return![".js",".mjs",".tsx",".ts",".jsx"].some((c)=>s.endsWith(c))}function ho(s,a){let c=a?"native binary":"executable",u=Ve(s);if(ao(s))return{message:a?`Claude Code native binary at ${u} 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 ${u} exists but failed to launch.`,telemetryMessage:`Claude Code ${c} exists at the configured path but failed to launch`,errorClass:"executable_launch_failed"};return{message:a?`Claude Code native binary not found at ${u}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${u}. Is options.pathToClaudeCodeExecutable set?`,telemetryMessage:`Claude Code ${c} not found at the configured path`,errorClass:"executable_not_found"}}function Zt(s){let a=We(s);return a===void 0?"":` (${a})`}function at(){return w(new me("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function es(){return w(new me("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function ts(s,a){let c=Object.hasOwn(s,a)?Reflect.get(s,a):void 0;return typeof c==="string"?c:void 0}function So(s){let a=Object.hasOwn(s,"exitCode")?Reflect.get(s,"exitCode"):void 0;return typeof a==="number"?a:void 0}function _o(s){return typeof Reflect.get(s,"unref")==="function"}import{existsSync as yo}from"fs";var Te="@anthropic-ai/claude-agent-sdk";function bo(){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 ns(s,a={}){let c=a.platform??process.platform,u=a.arch??process.arch,p=a.exists??yo,f=a.preferMusl??bo(),m="claude",h=c==="win32"?".exe":"",C=(c==="android"?[`${Te}-linux-${u}-android`]:c==="linux"?f?[`${Te}-linux-${u}-musl`,`${Te}-linux-${u}`]:[`${Te}-linux-${u}`,`${Te}-linux-${u}-musl`]:[`${Te}-${c}-${u}`]).map((b)=>`${b}/claude${h}`);for(let b of C)try{let _=s(b);if(p(_))return _}catch{}return null}function os({supportedDialogKinds:s,onUserDialog:a}){if(s!==void 0&&s.length>0&&!a)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.")}var Co=["signed_out","identity_changed","transient","refresh_failed"];function is(s){return Co.some((a)=>a===s)}var lt=600000;class er{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,a)=>{this.readResolve=s,this.readReject=a})}enqueue(s){if(this.readResolve){let a=this.readResolve;this.readResolve=void 0,this.readReject=void 0,a({done:!1,value:s})}else this.queue.push(s)}dropNewestQueued(s){let a=this.queue.findLastIndex(s);if(a!==-1)this.queue.splice(a,1)}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 a=this.readReject;this.readResolve=void 0,this.readReject=void 0,a(s)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var tr="startup_mark",as="startupMark",ls="startupMarkAgeMs",cs=64;function rr(s,a){ie("tengu_feature_ok",{...a,feature_name:ee(s)})}function Eo(s,a,c){ie("tengu_feature_bad",{...c,feature_name:ee(s),error_code:Rt(a)})}function ut(s,a,c){ie("tengu_feature_sad",{...c,feature_name:ee(s),error_code:Rt(a)})}async function q(s,a,c){try{let u=await a();return rr(s),u}catch(u){throw Eo(s,c?.(u)??"error"),u}}function us(s){return"method"in s&&"id"in s&&s.id!==null}var ds=Object.freeze({}),ps=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),Va=Symbol("swallow");class sr{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 fs=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var ms="2025-11-25";var vo="notifications/tools/list_changed";function gs(s){return t(s)&&!("id"in s)&&s.method===vo}var hs=250,dt="sdk-manifest-capture:",Pe=Symbol("suppressControlResponse");function Ss(s,a,c){for(let u of c){let p=u==="tools"?Ut(a):void 0;e(p?`[Query] MCP server '${s}': ${un(p)}`:`[Query] MCP server '${s}': ignoring malformed ${u} in its config`)}}class pt{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;runEndCeilingMs;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new er;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;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(s){this.isSingleUserTurn=s}setTranscriptMirrorBatcher(s){this.transcriptMirrorBatcher=s}reportMirrorError(s,a){let c={type:"system",subtype:"mirror_error",error:a,key:s,uuid:Re(),session_id:s.sessionId};this.inputStream.enqueue(c)}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;uiHost;workSecretAnswerer;constructor(s,a,c,u,p,f=new Map,m,h,S,C,b,_,v=!1,R=lt){this.transport=s;this.isSingleUserTurn=a;this.canUseTool=c;this.hooks=u;this.abortController=p;this.jsonSchema=m;this.initConfig=h;this.onElicitation=S;this.getOAuthToken=C;this.getHostAuthToken=b;this.onUserDialog=_;this.verbatimPrompts=v;this.runEndCeilingMs=R;for(let[E,P]of f)this.connectSdkMcpServer(E,P);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((E)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,E()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{})}setError(s){this.inputStream.error(s)}setFrameObserver(s){this.frameObserver=s}dropUnreadHookProgress(s){this.inputStream.dropNewestQueued((a)=>a.type==="system"&&a.subtype==="hook_progress"&&a.hook_id===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.clearRunEndCeiling(),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 a of this.cleanupCallbacks)try{a()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let a of this.cancelControllers.values())a.abort();this.cancelControllers.clear(),this.transport.close()}catch(a){e(`[Query.cleanup] transport.close() failed: ${d(a)}`,{level:"error"})}try{let a=s??nr();for(let{reject:c}of this.pendingControlResponses.values())c(a);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:c}of this.pendingMcpResponses.values())c(a);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:c}of this.sdkMcpServers.values())c.close().catch(()=>{});if(this.sdkMcpServers.clear(),s)this.inputStream.error(s);else this.inputStream.done()}catch(a){}if(this.transport.waitForExit){let a=new AbortController;try{await Promise.race([this.transport.waitForExit(),U(2000,a.signal)])}catch{}finally{a.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 a=this.pendingControlResponses.get(s.response.request_id);if(a)a.handler(s.response);else{if(this.unmatchedControlResponses.size>=pt.UNMATCHED_CONTROL_RESPONSES_MAX){let c=this.unmatchedControlResponses.keys().next().value;if(c!==void 0)this.unmatchedControlResponses.delete(c)}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"){if(tr in s){let a=s[tr];if(typeof a==="string"&&a.length<=cs)this.startupMark={mark:a,atMs:Date.now()}}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 a=s.is_error?s.subtype==="success"?s.result:s.errors.map((c)=>c.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=a||void 0,this.modelLessTurnEnded=s.subtype==="success"&&!s.is_error&&s.num_turns===0&&s.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(s.type==="system"&&s.subtype==="session_state_changed"){if(this.sessionState=s.state,s.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,s.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in s&&s.sdk_host_only===!0)continue}else{if(this.lastErrorResultText=void 0,s.type==="system"&&s.subtype==="init")this.modelLessTurnEnded=!1;else if(s.type!=="system"||s.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((s.type==="assistant"||s.type==="stream_event")&&s.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(s)}catch(a){e(`[Query.readMessages] The frame observer threw: ${d(a)}`,{level:"error"})}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();let a=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(a!==void 0&&!(s instanceof me)&&s?.name!=="SSEHttpError"){let c=w(Error(`Claude Code returned an error result: ${a}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});e(`[Query.readMessages] Replacing exit error with result text. Original: ${d(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 a=new AbortController;this.cancelControllers.set(s.request_id,a);try{let c;try{let u=await this.processControlRequest(s,a.signal);if(this.cleanupPerformed)return;if(u===Pe)return;let p={type:"control_response",response:{subtype:"success",request_id:s.request_id,response:u}};c=n(p)+`
28
+ `}catch(u){if(this.cleanupPerformed)return;let p={type:"control_response",response:{subtype:"error",request_id:s.request_id,error:d(u)}};c=n(p)+`
29
+ `}try{await Promise.resolve(this.transport.write(c))}catch(u){e(`[Query.handleControlRequest] Response write failed: ${d(u)}`,{level:"error"})}}finally{if(this.cancelControllers.get(s.request_id)===a)this.cancelControllers.delete(s.request_id)}}handleControlCancelRequest(s){let a=this.cancelControllers.get(s.request_id);if(a)a.abort(),this.cancelControllers.delete(s.request_id)}async processControlRequest(s,a){if(fs.some((c)=>c===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`),Pe;if(s.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let c=s.request.computer_folder,u=await this.canUseTool(s.request.tool_name,s.request.input,{signal:a,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,...typeof s.request.decision_reason_type==="string"&&{decisionReasonType:s.request.decision_reason_type},...typeof s.request.decision_reason_code==="string"&&{decisionReasonCode:s.request.decision_reason_code},...typeof s.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:s.request.server_policy_ask_only},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,...typeof s.request.plugin==="string"&&{plugin:s.request.plugin},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 c==="object"&&c!==null&&"path"in c&&typeof c.path==="string"&&"computer_name"in c&&typeof c.computer_name==="string"&&{computerFolder:{path:c.path,computer_name:c.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(u===null)return Pe;return{...u,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,a);else if(s.request.subtype==="mcp_message"){let c=s.request,u=this.sdkMcpServers.get(c.server_name)?.transport;if(!u)throw Error(`SDK MCP server not found: ${c.server_name}`);if(us(c.message))return{mcp_response:await this.handleMcpControlRequest(c.server_name,c,u)};else{if(u.onmessage)u.onmessage(c.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(s.request.subtype==="elicitation"){let c=s.request;if(this.onElicitation){let u=await this.onElicitation({serverName:c.mcp_server_name,message:c.message,mode:c.mode,url:c.url,elicitationId:c.elicitation_id,requestedSchema:c.requested_schema,title:c.title,displayName:c.display_name,description:c.description},{signal:a,requestId:s.request_id});if(u===null)return Pe;return u}return{action:"decline"}}else if(s.request.subtype==="request_user_dialog"){if(this.onUserDialog){let c=await this.onUserDialog({dialogKind:s.request.dialog_kind,payload:s.request.payload,toolUseID:s.request.tool_use_id},{signal:a,requestId:s.request_id});if(c===null)return Pe;return c}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`),ie("tengu_request_user_dialog_response_ignored",{shape:ee("auto_cancel")}),Pe}else if(s.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let c,u=await this.getOAuthToken({signal:a,onDecline:(p)=>{if(is(p))c=p}})??null;return u===null&&c!==void 0?{accessToken:u,reason:c}:{accessToken:u}}else if(s.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let c=await this.getHostAuthToken({signal:a})??null;return typeof c==="string"||c===null?{authToken:c}:c}else if(s.request.subtype==="remote_control_work_secret"){let c=this.workSecretAnswerer;if(!c)throw Error("refreshWorkSecret callback is not provided.");if(!_s(c.sessionId,s.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await c.refresh(c.sessionId,{signal:a})||null}}if(s.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:c,...u}=s.request;return this.uiHost.copy(u,{signal:a})}if(s.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:c,...u}=s.request;return this.uiHost.promptRead(u,{signal:a})}if(s.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:c,...u}=s.request;return this.uiHost.promptFill(u,{signal:a})}if(s.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:c,...u}=s.request;return this.uiHost.promptSuggest(u,{signal:a})}if(s.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:c,...u}=s.request;return this.uiHost.readSelection(u,{signal:a})}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 a,c;try{if(s&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){a=await this.captureSdkMcpServerManifests();for(let m of this.sdkMcpToolsChangedDuringCapture){let h=a!==void 0&&Object.hasOwn(a,m)?a[m]:void 0;if(h?.toolsListResult!==void 0)a[m]={initializeResult:h.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let f=this.buildInitializeRequest(a);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=s;try{c=this.request(f)}finally{this.writingFirstInitialize=!1}}finally{if(s)this.markInitializeWritten()}let p=(await c).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&p.plugins_applied!==!0)e(`[Query.initialize] Claude Code reported plugins_applied=${String(p.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 p}buildInitializeRequest(s){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[f,m]of Object.entries(this.hooks))if(m.length>0)this.initHooksPayload[f]=m.map((h)=>{let S=[];for(let C of h.hooks){let b=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(b,C),S.push(b)}return{matcher:h.matcher,hookCallbackIds:S,timeout:h.timeout}})}let a=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,c=Array.from(this.sdkMcpServers).flatMap(([f,{settings:m}])=>Object.keys(m).length>0?[[f,m]]:[]),u=c.length>0?Object.fromEntries(c):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:a,sdkMcpServerConfigs:u,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,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,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,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let s=performance.now(),a=new Map,c=!1,u=async(_,v)=>{try{if(await this.sdkMcpServers.get(_)?.connection,c)return;let R=await this.handleMcpControlRequest(_,{server_name:_,message:{jsonrpc:"2.0",id:dt+"initialize",method:"initialize",params:{protocolVersion:ms,capabilities:ds,clientInfo:{...ps,version:"0.3.308"}}}},v);if(c)return;if(!("result"in R)){e(`[Query.captureSdkMcpServerManifests] '${_}' answered initialize with an error; leaving it to the CLI: ${n(R)}`,{level:"warn"});return}let E=R.result;v.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let P=E.capabilities,F=typeof P==="object"&&P!==null&&"tools"in P&&P.tools!==void 0&&P.tools!==null,D;if(F){let Z=await this.handleMcpControlRequest(_,{server_name:_,message:{jsonrpc:"2.0",id:dt+"tools-list",method:"tools/list"}},v);if(c)return;if(!("result"in Z)){e(`[Query.captureSdkMcpServerManifests] '${_}' answered tools/list with an error; leaving it to the CLI: ${n(Z)}`,{level:"warn"});return}if(Z.result.nextCursor===void 0)D=Z.result}let ue=y(n(D===void 0?{initializeResult:E}:{initializeResult:E,toolsListResult:D}));a.set(_,{transport:v,manifest:ue})}catch(R){if(!c)e(`[Query.captureSdkMcpServerManifests] '${_}': ${R}; the CLI will handshake it over the control channel`,{level:"warn"})}},p=Array.from(this.sdkMcpServers,([_,{transport:v}])=>u(_,v)),f=Promise.all(p).then(()=>"settled"),m=new Promise((_)=>{this.stopSdkMcpManifestCapture=()=>_("closed")}),h=await ct(Promise.race([f,m]),hs);c=!0,this.stopSdkMcpManifestCapture=void 0;let S=Math.round(performance.now()-s),C={servers:p.length,captured:a.size,elapsed_ms:S};if(h==="closed"){ut("sdk_mcp_manifest_capture","closed",C);return}if(h===void 0)e(`[Query.captureSdkMcpServerManifests] ${a.size}/${p.length} in-process MCP servers captured within ${hs} ms; the rest will handshake over the control channel`,{level:"warn"}),ut("sdk_mcp_manifest_capture","deadline",C);else if(a.size<p.length)ut("sdk_mcp_manifest_capture","partial",C);else rr("sdk_mcp_manifest_capture",C);if(a.size===0)return;let b=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([_,v])=>{let R=a.get(_);return R!==void 0&&R.transport===v.transport?[[_,R.manifest]]:[]}));if(Object.keys(b).length===0)return;return e(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(b).join(", ")}] captured in ${S} ms`),b}async interrupt(s){return q("sdk_interrupt",async()=>{let a=await this.request({subtype:"interrupt",...s?.cancelQueued===!0&&{cancel_queued:!0}}),c=a.response?.still_queued;if(!Array.isArray(c))return;let u=a.response?.cancelled;return{still_queued:c.filter((p)=>typeof p==="string"),...Array.isArray(u)&&{cancelled:u.filter((p)=>typeof p==="string")}}})}async setPermissionMode(s){await this.request({subtype:"set_permission_mode",mode:s})}startupMarkReached(){let s=this.startupMark;return s&&{mark:s.mark,ageMs:Math.max(0,Math.round(Date.now()-s.atMs))}}setUiHost(s){this.uiHost=s}async setMcpPermissionModeOverride(s,a){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:s,mode:a})).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((a,c)=>{let u=(f)=>{if(f.subtype==="success"){let{pending_permission_requests:m,pending_user_dialog_requests:h,...S}=f;a(S)}else c(new l(f.error,"awaitControlResponse: CLI error verdict"));if(f.pending_permission_requests||f.pending_user_dialog_requests)e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){c(nr());return}let p=this.unmatchedControlResponses.get(s);if(p){this.unmatchedControlResponses.delete(s),u(p);return}this.pendingControlResponses.set(s,{handler:(f)=>{this.pendingControlResponses.delete(s),u(f)},reject:c})})}async setModel(s){await this.request({subtype:"set_model",model:s})}async setMaxThinkingTokens(s,a){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:s,thinking_display:a})}async applyFlagSettings(s){return q("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 getTaskOutput(s){return(await this.request({subtype:"get_task_output",task_id:s})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(s,a){return q("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:s,settings:a})})}async rewindFiles(s,a){return q("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:s,dry_run:a?.dryRun})).response)}async cancelAsyncMessage(s){return(await this.request({subtype:"cancel_async_message",message_uuid:s})).response.cancelled}async seedReadState(s,a){await this.request({subtype:"seed_read_state",path:s,mtime:a})}async setCwd(s,a){return q("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:s,...a?.trustAccepted!==void 0&&{trust_accepted:a.trustAccepted},...a?.trustedDirectory!==void 0&&{trusted_directory:a.trustedDirectory}})).response)}async claimSession(s){let a=q("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...s,include_initialize:s.include_initialize??!0})).response),c=this.initialization;return this.initialization=a.then(async(u)=>{if(u?.initialize===void 0)return c;let p=u.initialize,f=await c.then((C)=>({hooks_applied:C.hooks_applied,plugins_applied:C.plugins_applied,code_running_mcp_tools_applied:C.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),m=p.hooks_applied??f.hooks_applied,h=p.plugins_applied??f.plugins_applied,S=p.code_running_mcp_tools_applied??f.code_running_mcp_tools_applied;return{...p,...m!==void 0&&{hooks_applied:m},...h!==void 0&&{plugins_applied:h},...S!==void 0&&{code_running_mcp_tools_applied:S}}},()=>c),this.initialization.catch(()=>{}),a}async enableRemoteControl(s,a,c){let u=++this.remoteControlCallGeneration,p=this.workSecretAnswerer,f=c?.reattachSessionId||(c?.workSecret===void 0?void 0:ko(c.workSecret)),m=s&&c?.workSecret!==void 0&&c.refreshWorkSecret&&f!==void 0?{sessionId:f,refresh:c.refreshWorkSecret}:void 0;this.workSecretAnswerer=m;let h;try{h=(await this.request({subtype:"remote_control",enabled:s,...a!==void 0&&{name:a},reattach_session_id:c?.reattachSessionId,keep_session_on_exit:c?.keepSessionOnExit,work_secret:c?.workSecret})).response}catch(S){if(u===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw S}if(s&&u===this.remoteControlCallGeneration){let S=h.bridge_session_id,C=[m,p];this.workSecretAnswerer=typeof S==="string"?C.find((b)=>b!==void 0&&_s(b.sessionId,S)):void 0}return h}async submitFeedback(s,a){return(await this.request({subtype:"submit_feedback",description:s,surface:a?.surface,draft_id:a?.draft_id,type:a?.type,title:a?.title,area:a?.area,attach_transcript:a?.attach_transcript,save_locally:a?.save_locally})).response}async renameSession(s,a){await this.request({subtype:"rename_session",title:s,source:"host",session_id:a})}async generateSessionTitle(s,a){return q("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:s,persist:a?.persist})).response.title)}async askSideQuestion(s,a){return q("sdk_side_question",async()=>{let u=(await this.request({subtype:"side_question",question:s,...a?.history?.length&&{history:[...a.history]}},a)).response;return u.response===null?null:{response:u.response,synthetic:u.synthetic??!1,...u.refusal_fallback&&{refusalFallback:{originalModel:u.refusal_fallback.original_model,fallbackModel:u.refusal_fallback.fallback_model,content:u.refusal_fallback.content}}}},()=>a?.signal?.aborted?"cancelled":"error")}async launchUltrareview(s,a){return(await this.request({subtype:"ultrareview_launch",args:s,confirm:a?.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 a of s)if(a.request.subtype==="can_use_tool")this.handleControlRequest({...a,request:{...a.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(s){for(let a of s)if(a.request.subtype==="request_user_dialog")this.handleControlRequest(a).catch(()=>{})}request(s,a){let c=a?.signal;if(c?.aborted)return Promise.reject(N(c.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(nr());let u=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(u);let p={request_id:u,type:"control_request",request:s},f=s.subtype==="initialize";return new Promise((m,h)=>{let S,C=!1,b=(E)=>{this.pendingControlResponses.delete(u),S?.(),m(E)},_=(E)=>{this.pendingControlResponses.delete(u),S?.(),h(E)};if(c){let E=()=>{if(_(N(c.reason??"Control request aborted")),!C)return;try{Promise.resolve(this.transport.write(n({type:"control_cancel_request",request_id:u})+`
30
+ `)).catch(()=>{})}catch{}};c.addEventListener("abort",E,{once:!0}),S=()=>{c.removeEventListener("abort",E)}}this.pendingControlResponses.set(u,{handler:(E)=>{if(E.subtype==="success")b(E);else _(w(Error(E.error),{telemetryMessage:`Claude Code control request failed (${s.subtype})`,errorClass:"control_request_failed",errorCode:typeof E.error_code==="string"&&wo.test(E.error_code)?E.error_code:void 0}));if(!f&&(E.pending_permission_requests||E.pending_user_dialog_requests))e(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${s.subtype})`);else{if(E.pending_permission_requests)this.processPendingPermissionRequests(E.pending_permission_requests);if(E.pending_user_dialog_requests)this.processPendingUserDialogRequests(E.pending_user_dialog_requests)}},reject:_});let v=n(p)+`
31
+ `,R=()=>{if(c?.aborted)return;return C=!0,this.transport.write(v)};try{(this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(R()):this.initializeWritten.then(R)).catch(_)}catch(E){_(E)}})}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 q("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,a){return q("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:s,enabled:a})})}async readMcpResource(s,a){return(await this.request({subtype:"mcp_read_resource",serverName:s,uri:a})).response}async enableChannel(s){return q("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:s})})}async mcpAuthenticate(s,a){return(await this.request({subtype:"mcp_authenticate",serverName:s,redirectUri:a})).response}async mcpClearAuth(s){return(await this.request({subtype:"mcp_clear_auth",serverName:s})).response}async mcpSubmitOAuthCallbackUrl(s,a){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:s,callbackUrl:a})).response}async claudeAuthenticate(s){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:s})).response}async claudeOAuthCallback(s,a){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:s,state:a})).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 readCloudSessions(s,a){return(await this.request(s,a)).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,a){try{return(await this.request({subtype:"read_file",path:s,max_bytes:a?.maxBytes,encoding:a?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(s){return q("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...s?.holdOnCacheImpact&&{hold_on_cache_impact:!0},...s?.addPlugins&&s.addPlugins.length>0&&{add_plugins:s.addPlugins}})).response)}async reloadSkills(){return q("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return q("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(s){return q("sdk_mcp_set_servers",async()=>{let a={},c={};for(let[h,S]of Object.entries(s))if(S.type==="sdk"&&"instance"in S)a[h]=S;else c[h]=S;let u=new Set(this.sdkMcpServers.keys()),p=new Set(Object.keys(a));for(let h of u)if(!p.has(h))await this.disconnectSdkMcpServer(h);for(let[h,S]of Object.entries(a)){let C=this.sdkMcpServers.get(h);if(!C){this.connectSdkMcpServer(h,S);continue}let{settings:b,ignored:_}=Nt(S);if(Ss(h,S,_),b.timeout!==C.settings.timeout||b.disableAutoBackground!==C.settings.disableAutoBackground)e(`[Query.setMcpServers] MCP server '${h}' is already registered, so the different timeout or disableAutoBackground passed to setMcpServers is ignored; remove and re-add the server to change it`);if(b.tools!==void 0&&!cn(b.tools,C.settings.tools))e(b.tools.length===0?`[Query.setMcpServers] MCP server '${h}': per-tool policy cleared`:`[Query.setMcpServers] MCP server '${h}': per-tool policy replaced (${b.tools.length} ${b.tools.length===1?"entry":"entries"})`),C.settings={...C.settings,tools:b.tools}}let f={};for(let h of Object.keys(a))f[h]={type:"sdk",name:h,...this.sdkMcpServers.get(h)?.settings};return(await this.request({subtype:"mcp_set_servers",servers:{...c,...f}})).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 a=0;for await(let c of s){if(a++,e(`[Query.streamInput] Processing message ${a}: ${c.type}`),this.abortController?.signal.aborted)break;this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),await Promise.resolve(this.transport.write(n(this.verbatimPrompts?{...c,client_composed:!0}:c)+`
32
+ `))}if(e(`[Query.streamInput] Finished processing ${a} messages from input stream`),a>0&&this.hasBidirectionalNeeds())e("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();e("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(a){if(!(a instanceof me))throw a}}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)e("[Query.readMessages] Run ended for single-turn query, closing stdin"),this.transport.endInput()}armRunEndCeiling(){if(this.clearRunEndCeiling(),this.runEnded||this.cleanupPerformed||this.runEndCeilingMs<=0)return;this.runEndCeilingTimer=setTimeout(()=>{e(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,be)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return e("[Query.waitForRunEnd] Run already ended, returning immediately"),Promise.resolve();return new Promise((s)=>{let a=this.abortController?.signal;if(this.cleanupPerformed||a?.aborted){s();return}let c=()=>s();a?.addEventListener("abort",c,{once:!0}),this.addCleanupCallback(()=>{a?.removeEventListener("abort",c),s()}),this.runEndedResolve=()=>{a?.removeEventListener("abort",c),s()}})}handleHookCallbacks(s,a,c,u){let p=this.hookCallbacks.get(s);if(!p)throw Error(`No hook callback found for ID: ${s}`);return p(a,c,{signal:u})}connectSdkMcpServer(s,a){let c=new sr((m)=>this.sendMcpServerMessageToCli(s,m)),u=a.instance.connect(c).catch((m)=>{if(this.sdkMcpServers.get(s)?.transport===c)this.sdkMcpServers.delete(s);e(`[Query.connectSdkMcpServer] Failed to connect MCP server '${s}': ${m}`,{level:"error"})}),{settings:p,ignored:f}=Nt(a);Ss(s,a,f),this.sdkMcpServers.set(s,{transport:c,settings:p,connection:u})}async disconnectSdkMcpServer(s){let a=this.sdkMcpServers.get(s);if(a){let c=`${s}:${dt}`;for(let[u,p]of this.pendingMcpResponses)if(u.startsWith(c))this.pendingMcpResponses.delete(u),p.reject(Error("MCP server was removed during the manifest capture"));if(await a.transport.close(),this.sdkMcpServers.get(s)===a)this.sdkMcpServers.delete(s)}}sendMcpServerMessageToCli(s,a){if("id"in a&&a.id!==null&&a.id!==void 0){let u=`${s}:${a.id}`,p=this.pendingMcpResponses.get(u);if(p){p.resolve(a),this.pendingMcpResponses.delete(u);return}if(typeof a.id==="string"&&a.id.startsWith(dt)){e(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${s}' (${a.id})`);return}}let c={type:"control_request",request_id:Re(),request:{subtype:"mcp_message",server_name:s,message:a}};if(!this.initializeHasBeenWritten&&gs(a))this.sdkMcpToolsChangedDuringCapture.add(s);this.writeAfterInitialize(n(c)+`
33
+ `).catch((u)=>{e(`[Query.sendMcpServerMessageToCli] Transport write failed: ${u}`,{level:"error"})})}handleMcpControlRequest(s,a,c){let u="id"in a.message?a.message.id:null,p=`${s}:${u}`;return new Promise((f,m)=>{let h=()=>{this.pendingMcpResponses.delete(p)},S=(b)=>{h(),f(b)},C=(b)=>{h(),m(b)};if(this.pendingMcpResponses.set(p,{resolve:S,reject:C}),c.onmessage)c.onmessage(a.message);else{h(),m(Error("No message handler registered"));return}})}}function nr(){return Error("Query closed before response received")}var wo=/^[a-z][a-z0-9_]{0,63}$/;function _s(s,a){if(s===a)return!0;let c=s.slice(s.lastIndexOf("_")+1),u=a.slice(a.lastIndexOf("_")+1);return c.length>=4&&c===u}function ko(s){try{let a=y(Buffer.from(s,"base64url").toString("utf8"));if(typeof a!=="object"||a===null||!("session_ingress_token"in a)||typeof a.session_ingress_token!=="string")return;let c=a.session_ingress_token,p=(c.startsWith("sk-ant-si-")?c.slice(10):c).split(".");if(p.length!==3||!p[1])return;let f=y(Buffer.from(p[1],"base64url").toString("utf8"));return typeof f==="object"&&f!==null&&"session_id"in f&&typeof f.session_id==="string"&&f.session_id?f.session_id:void 0}catch{return}}var or=500,ir=1048576;var Ro=[200,800];class ar{send;pending=[];pendingEntries=0;pendingBytes=0;flushPromise=null;sendTimeoutMs;onError;maxPendingEntries;maxPendingBytes;backoffMs;constructor(s,a){this.send=s;let{sendTimeoutMs:c=60000,onError:u,maxPendingEntries:p=or,maxPendingBytes:f=ir,backoffMs:m=Ro}=a??{};this.sendTimeoutMs=c,this.onError=u,this.maxPendingEntries=p,this.maxPendingBytes=f,this.backoffMs=m}enqueue(s,a){let c=n(a).length;if(this.pending.push({filePath:s,entries:a,bytes:c}),this.pendingEntries+=a.length,this.pendingBytes+=c,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,a=this.pending.splice(0);if(this.pendingEntries=0,this.pendingBytes=0,s)await s;if(a.length===0)return;await this.doFlush(a)}async doFlush(s){let a=new Map;for(let c of s){let u=a.get(c.filePath);if(u)u.push(...c.entries);else a.set(c.filePath,c.entries.slice())}for(let[c,u]of a)await this.sendWithRetry(c,u)}async sendWithRetry(s,a){let c=this.backoffMs.length+1,u=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${s}`,p,f=1;for(;f<=c;f++)try{await I(this.send(s,a),this.sendTimeoutMs,u),p=void 0;break}catch(m){if(p=N(m),p.message===u)break;let h=this.backoffMs[f-1];if(h===void 0)break;await U(h)}if(p){e(`[TranscriptMirrorBatcher] flush failed for ${s} after ${f} attempt(s): ${p}`,{level:"error"});try{this.onError?.(s,p)}catch(m){e(`[TranscriptMirrorBatcher] onError callback threw: ${m}`,{level:"error"})}}}}var ys=typeof globalThis==="object"?globalThis:global;var se="1.9.0";var bs=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ao(s){var a=new Set([s]),c=new Set,u=s.match(bs);if(!u)return function(){return!1};var p={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};if(p.prerelease!=null)return function(S){return S===s};function f(h){return c.add(h),!1}function m(h){return a.add(h),!0}return function(S){if(a.has(S))return!0;if(c.has(S))return!1;var C=S.match(bs);if(!C)return f(S);var b={major:+C[1],minor:+C[2],patch:+C[3],prerelease:C[4]};if(b.prerelease!=null)return f(S);if(p.major!==b.major)return f(S);if(p.major===0){if(p.minor===b.minor&&p.patch<=b.patch)return m(S);return f(S)}if(p.minor<=b.minor)return m(S);return f(S)}}var Cs=Ao(se);var To=se.split(".")[0],Qe=Symbol.for("opentelemetry.js.api."+To),Ye=ys;function Me(s,a,c,u){var p;if(u===void 0)u=!1;var f=Ye[Qe]=(p=Ye[Qe])!==null&&p!==void 0?p:{version:se};if(!u&&f[s]){var m=Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return c.error(m.stack||m.message),!1}if(f.version!==se){var m=Error("@opentelemetry/api: Registration of version v"+f.version+" for "+s+" does not match previously registered API v"+se);return c.error(m.stack||m.message),!1}return f[s]=a,c.debug("@opentelemetry/api: Registered a global for "+s+" v"+se+"."),!0}function ne(s){var a,c,u=(a=Ye[Qe])===null||a===void 0?void 0:a.version;if(!u||!Cs(u))return;return(c=Ye[Qe])===null||c===void 0?void 0:c[s]}function xe(s,a){a.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+se+".");var c=Ye[Qe];if(c)delete c[s]}var Po=function(s,a){var c=typeof Symbol==="function"&&s[Symbol.iterator];if(!c)return s;var u=c.call(s),p,f=[],m;try{while((a===void 0||a-- >0)&&!(p=u.next()).done)f.push(p.value)}catch(h){m={error:h}}finally{try{if(p&&!p.done&&(c=u.return))c.call(u)}finally{if(m)throw m.error}}return f},Mo=function(s,a,c){if(c||arguments.length===2){for(var u=0,p=a.length,f;u<p;u++)if(f||!(u in a)){if(!f)f=Array.prototype.slice.call(a,0,u);f[u]=a[u]}}return s.concat(f||Array.prototype.slice.call(a))},Es=function(){function s(a){this._namespace=a.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){var a=[];for(var c=0;c<arguments.length;c++)a[c]=arguments[c];return Ze("debug",this._namespace,a)},s.prototype.error=function(){var a=[];for(var c=0;c<arguments.length;c++)a[c]=arguments[c];return Ze("error",this._namespace,a)},s.prototype.info=function(){var a=[];for(var c=0;c<arguments.length;c++)a[c]=arguments[c];return Ze("info",this._namespace,a)},s.prototype.warn=function(){var a=[];for(var c=0;c<arguments.length;c++)a[c]=arguments[c];return Ze("warn",this._namespace,a)},s.prototype.verbose=function(){var a=[];for(var c=0;c<arguments.length;c++)a[c]=arguments[c];return Ze("verbose",this._namespace,a)},s}();function Ze(s,a,c){var u=ne("diag");if(!u)return;return c.unshift(a),u[s].apply(u,Mo([],Po(c),!1))}var V;(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"})(V||(V={}));function vs(s,a){if(s<V.NONE)s=V.NONE;else if(s>V.ALL)s=V.ALL;a=a||{};function c(u,p){var f=a[u];if(typeof f==="function"&&s>=p)return f.bind(a);return function(){}}return{error:c("error",V.ERROR),warn:c("warn",V.WARN),info:c("info",V.INFO),debug:c("debug",V.DEBUG),verbose:c("verbose",V.VERBOSE)}}var xo=function(s,a){var c=typeof Symbol==="function"&&s[Symbol.iterator];if(!c)return s;var u=c.call(s),p,f=[],m;try{while((a===void 0||a-- >0)&&!(p=u.next()).done)f.push(p.value)}catch(h){m={error:h}}finally{try{if(p&&!p.done&&(c=u.return))c.call(u)}finally{if(m)throw m.error}}return f},Oo=function(s,a,c){if(c||arguments.length===2){for(var u=0,p=a.length,f;u<p;u++)if(f||!(u in a)){if(!f)f=Array.prototype.slice.call(a,0,u);f[u]=a[u]}}return s.concat(f||Array.prototype.slice.call(a))},Do="diag",ae=function(){function s(){function a(p){return function(){var f=[];for(var m=0;m<arguments.length;m++)f[m]=arguments[m];var h=ne("diag");if(!h)return;return h[p].apply(h,Oo([],xo(f),!1))}}var c=this,u=function(p,f){var m,h,S;if(f===void 0)f={logLevel:V.INFO};if(p===c){var C=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return c.error((m=C.stack)!==null&&m!==void 0?m:C.message),!1}if(typeof f==="number")f={logLevel:f};var b=ne("diag"),_=vs((h=f.logLevel)!==null&&h!==void 0?h:V.INFO,p);if(b&&!f.suppressOverrideMessage){var v=(S=Error().stack)!==null&&S!==void 0?S:"<failed to generate stacktrace>";b.warn("Current logger will be overwritten from "+v),_.warn("Current logger will overwrite one already registered from "+v)}return Me("diag",_,c,!0)};c.setLogger=u,c.disable=function(){xe(Do,c)},c.createComponentLogger=function(p){return new Es(p)},c.verbose=a("verbose"),c.debug=a("debug"),c.info=a("info"),c.warn=a("warn"),c.error=a("error")}return s.instance=function(){if(!this._instance)this._instance=new s;return this._instance},s}();var Io=function(s,a){var c=typeof Symbol==="function"&&s[Symbol.iterator];if(!c)return s;var u=c.call(s),p,f=[],m;try{while((a===void 0||a-- >0)&&!(p=u.next()).done)f.push(p.value)}catch(h){m={error:h}}finally{try{if(p&&!p.done&&(c=u.return))c.call(u)}finally{if(m)throw m.error}}return f},No=function(s){var a=typeof Symbol==="function"&&Symbol.iterator,c=a&&s[a],u=0;if(c)return c.call(s);if(s&&typeof s.length==="number")return{next:function(){if(s&&u>=s.length)s=void 0;return{value:s&&s[u++],done:!s}}};throw TypeError(a?"Object is not iterable.":"Symbol.iterator is not defined.")},ws=function(){function s(a){this._entries=a?new Map(a):new Map}return s.prototype.getEntry=function(a){var c=this._entries.get(a);if(!c)return;return Object.assign({},c)},s.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(a){var c=Io(a,2),u=c[0],p=c[1];return[u,p]})},s.prototype.setEntry=function(a,c){var u=new s(this._entries);return u._entries.set(a,c),u},s.prototype.removeEntry=function(a){var c=new s(this._entries);return c._entries.delete(a),c},s.prototype.removeEntries=function(){var a,c,u=[];for(var p=0;p<arguments.length;p++)u[p]=arguments[p];var f=new s(this._entries);try{for(var m=No(u),h=m.next();!h.done;h=m.next()){var S=h.value;f._entries.delete(S)}}catch(C){a={error:C}}finally{try{if(h&&!h.done&&(c=m.return))c.call(m)}finally{if(a)throw a.error}}return f},s.prototype.clear=function(){return new s},s}();var Vl=ae.instance();function ks(s){if(s===void 0)s={};return new ws(new Map(Object.entries(s)))}function Rs(s){return Symbol.for(s)}var Lo=function(){function s(a){var c=this;c._currentContext=a?new Map(a):new Map,c.getValue=function(u){return c._currentContext.get(u)},c.setValue=function(u,p){var f=new s(c._currentContext);return f._currentContext.set(u,p),f},c.deleteValue=function(u){var p=new s(c._currentContext);return p._currentContext.delete(u),p}}return s}(),As=new Lo;var Ts={get:function(s,a){if(s==null)return;return s[a]},keys:function(s){if(s==null)return[];return Object.keys(s)}},Ps={set:function(s,a,c){if(s==null)return;s[a]=c}};var Ko=function(s,a){var c=typeof Symbol==="function"&&s[Symbol.iterator];if(!c)return s;var u=c.call(s),p,f=[],m;try{while((a===void 0||a-- >0)&&!(p=u.next()).done)f.push(p.value)}catch(h){m={error:h}}finally{try{if(p&&!p.done&&(c=u.return))c.call(u)}finally{if(m)throw m.error}}return f},Fo=function(s,a,c){if(c||arguments.length===2){for(var u=0,p=a.length,f;u<p;u++)if(f||!(u in a)){if(!f)f=Array.prototype.slice.call(a,0,u);f[u]=a[u]}}return s.concat(f||Array.prototype.slice.call(a))},Ms=function(){function s(){}return s.prototype.active=function(){return As},s.prototype.with=function(a,c,u){var p=[];for(var f=3;f<arguments.length;f++)p[f-3]=arguments[f];return c.call.apply(c,Fo([u],Ko(p),!1))},s.prototype.bind=function(a,c){return c},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var Uo=function(s,a){var c=typeof Symbol==="function"&&s[Symbol.iterator];if(!c)return s;var u=c.call(s),p,f=[],m;try{while((a===void 0||a-- >0)&&!(p=u.next()).done)f.push(p.value)}catch(h){m={error:h}}finally{try{if(p&&!p.done&&(c=u.return))c.call(u)}finally{if(m)throw m.error}}return f},$o=function(s,a,c){if(c||arguments.length===2){for(var u=0,p=a.length,f;u<p;u++)if(f||!(u in a)){if(!f)f=Array.prototype.slice.call(a,0,u);f[u]=a[u]}}return s.concat(f||Array.prototype.slice.call(a))},lr="context",jo=new Ms,mt=function(){function s(){}return s.getInstance=function(){if(!this._instance)this._instance=new s;return this._instance},s.prototype.setGlobalContextManager=function(a){return Me(lr,a,ae.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(a,c,u){var p,f=[];for(var m=3;m<arguments.length;m++)f[m-3]=arguments[m];return(p=this._getContextManager()).with.apply(p,$o([a,c,u],Uo(f),!1))},s.prototype.bind=function(a,c){return this._getContextManager().bind(a,c)},s.prototype._getContextManager=function(){return ne(lr)||jo},s.prototype.disable=function(){this._getContextManager().disable(),xe(lr,ae.instance())},s}();var cr=mt.getInstance();var xs=function(){function s(){}return s.prototype.inject=function(a,c){},s.prototype.extract=function(a,c){return a},s.prototype.fields=function(){return[]},s}();var ur=Rs("OpenTelemetry Baggage Key");function dr(s){return s.getValue(ur)||void 0}function Os(){return dr(mt.getInstance().active())}function Ds(s,a){return s.setValue(ur,a)}function Is(s){return s.deleteValue(ur)}var pr="propagation",Bo=new xs,Ns=function(){function s(){this.createBaggage=ks,this.getBaggage=dr,this.getActiveBaggage=Os,this.setBaggage=Ds,this.deleteBaggage=Is}return s.getInstance=function(){if(!this._instance)this._instance=new s;return this._instance},s.prototype.setGlobalPropagator=function(a){return Me(pr,a,ae.instance())},s.prototype.inject=function(a,c,u){if(u===void 0)u=Ps;return this._getGlobalPropagator().inject(a,c,u)},s.prototype.extract=function(a,c,u){if(u===void 0)u=Ts;return this._getGlobalPropagator().extract(a,c,u)},s.prototype.fields=function(){return this._getGlobalPropagator().fields()},s.prototype.disable=function(){xe(pr,ae.instance())},s.prototype._getGlobalPropagator=function(){return ne(pr)||Bo},s}();var fr=Ns.getInstance();var Ls=600000,ht=["SessionStart","Setup"];var mr=60000,Ks=Ls,Tc=mr+Ks,zo="startupHooksOpen",Ho=64;class gr{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(s,a=Ne,c){this.clock=a;this.onRunning=c;this.limitMs=s??mr,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=s==null?Ks:0}race(s){let a=new Promise((c,u)=>{this.rejectExpired=u});return this.arm(),Promise.race([s,a]).finally(()=>this.end())}note(s){if(this.rejectExpired===void 0||s.type!=="system")return;switch(s.subtype){case"hook_started":if(!ht.includes(s.hook_event)||this.followed.has(s.hook_id))return;if(this.followed.size<Ho)this.followed.add(s.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(s.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(s.hook_id)){if(this.unfollowedOpen===0||!ht.includes(s.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let s=Math.min(this.countedLeftMs,be);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=s,this.countedLeftMs>0)this.arm();else this.expire()},s)}countAgain(){let s=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=s,this.uncountedMs+=s,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let s=this.rejectExpired,a=`Subprocess initialization did not complete within ${this.limitMs}ms`,c=ht.join(" or "),u=Math.round(this.uncountedMs/1000),p=this.open(),f=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${oe(this.reported,"hook")}`,m=[`${a}.`,...u>0?[`Not counted: ${u} ${oe(u,"second")} in which Claude Code reported a ${c} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${c} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:p===0?`Claude Code reported ${f}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${f}, ${this.reported===1?"which had not finished":p===this.reported?"none of which had finished":`${p} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],h=Object.assign(w(Error(m.join(" ")),{telemetryMessage:a,errorClass:"initialize_timeout"}),{[zo]:p});this.end(),s?.(h)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}import{copyFile as qo,readFile as Go,rm as Us,writeFile as $s}from"fs/promises";import{homedir as Fs}from"os";import{join as hr}from"path";function js(s){return{globalConfig:hr(s||Fs(),".claude.json"),userSettings:hr(s||hr(Fs(),".claude"),"settings.json")}}function Sr(s,a,c,u){return s!==void 0&&a===c?{backend:s,key:u}:void 0}async function Oe(s,a,c,u){if(u)return Wo(u,s,a,c);try{if(c)await $s(a,c(await Go(s)),{mode:384});else await qo(s,a)}catch(p){if(r(p)===void 0)throw p;if(!g(p))await Us(a,{force:!0}).catch(()=>{}),e(`sessionStore resume: skipping ${s} (${r(p)})`)}}async function Wo({backend:s,key:a},c,u,p){let f=await s.read([a]);if(!f.ok){if(f.error.code==="InvalidArgument")throw new l(`sessionStore resume: invalid v5 key for ${c}: ${f.error.argument}${f.error.reason?` (${f.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");e(`sessionStore resume: skipping ${c} (${f.error.code})`);return}let m=f.value.items[0];if(!m?.found)return;let h=Buffer.from(m.value);try{await $s(u,p?p(h):h,{mode:384})}catch(S){if(r(S)===void 0)throw S;if(!g(S))await Us(u,{force:!0}).catch(()=>{}),e(`sessionStore resume: skipping ${c} (${r(S)})`)}}import{createHash as Vo}from"crypto";import{homedir as Uc,userInfo as Qo}from"os";var Bs="-credentials";function zs(s=""){let a=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,c=a!==void 0?!a:!process.env.CLAUDE_CONFIG_DIR,u=a!==void 0?a.normalize("NFC"):T(),p=c?"":`-${Vo("sha256").update(u).digest("hex").substring(0,8)}`;return`Claude Code${fn().OAUTH_FILE_SUFFIX}${s}${p}`}var Yo=/^[a-zA-Z0-9._-]+$/;function Hs(){if(process.platform==="win32")return"claude-code-user";let s;try{s=process.env.USER||Qo().username}catch{s="claude-code-user"}if(!Yo.test(s))return"claude-code-user";return s}class qs{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var Hc=new i(()=>new qs);function Xo(s,a){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 c=a.filter((u)=>u.length>0&&!u.includes("("));if(c.length===0)return;return`canUseTool will not be invoked for: ${c.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 Gs(s,a,c){if(!s)return;let u=Xo(a,c);if(u===void 0)return;process.emitWarning(u,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}process.env.NoDefaultCurrentDirectoryInExePath="1";var ci=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Vs(s){let a;try{a=y(Ce(s.toString("utf8")))}catch{return s}if(!Qs(a))return s;let c=!1;for(let p of ci)if(Object.hasOwn(a,p))delete a[p],c=!0;let u=a.env;if(Qs(u)&&Object.hasOwn(u,"CLAUDE_CONFIG_DIR"))delete u.CLAUDE_CONFIG_DIR,c=!0;return c?n(a):s}function Qs(s){return s!==null&&typeof s==="object"&&!Array.isArray(s)}async function ui(s,a){if(!s)return;let c=s;try{let u=y(s);if(u?.claudeAiOauth?.refreshToken)delete u.claudeAiOauth.refreshToken,c=n(u)}catch{}await Ys(a,c,{mode:384})}function di(){if(process.platform!=="darwin")return Promise.resolve(void 0);let s=zs(Bs);return new Promise((a)=>{Zo("security",["find-generic-password","-a",Hs(),"-w","-s",s],{encoding:"utf-8",timeout:5000,windowsHide:!0},(c,u)=>a(c?void 0:u.trim()||void 0))})}async function Xs(s,a,c,u,p=60000,f){if(!j(a))return;let m=le(c,u),h=await I(s.load({projectKey:m,sessionId:a}),p,`SessionStore.load() timed out after ${p}ms for session ${a}`);if(!h||h.length===0)return;let S=z(si(),`claude-resume-${Jo()}`);try{let C=z(S,"projects",m);await _r(C,{recursive:!0,mode:448});let b=z(C,`${a}.jsonl`);await Bt(b,h);let _=u?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,v=_??z(yr(),".claude"),R;try{R=await ei(z(v,".credentials.json"),"utf-8")}catch(H){if(!g(H))throw H}if(!_&&!(u??process.env).ANTHROPIC_API_KEY&&!(u??process.env).CLAUDE_CODE_OAUTH_TOKEN)R=await di()??R;await ui(R,z(S,".credentials.json"));let E=js(ft("CLAUDE_CONFIG_DIR")),P=_||yr(),F=z(P,".claude.json");await Oe(F,z(S,".claude.json"),void 0,Sr(f,F,E.globalConfig,Ae.globalConfig())),await Oe(z(v,".config.json"),z(S,".config.json"));for(let H of dn)if(H)await Oe(z(P,`.claude${H}.json`),z(S,`.claude${H}.json`));let D=z(v,"settings.json");if(await Oe(D,z(S,"settings.json"),Vs,Sr(f,D,E.userSettings,Ae.userSettings())),await Oe(z(v,"cowork_settings.json"),z(S,"cowork_settings.json"),Vs),s.listSubkeys)await pi(s,{projectKey:m,sessionId:a},z(C,a),p);return S}catch(C){throw await _t(S),C}}async function pi(s,a,c,u){let p=await I(s.listSubkeys({projectKey:a.projectKey,sessionId:a.sessionId}),u,`SessionStore.listSubkeys() timed out after ${u}ms for session ${a.sessionId}`);for(let f of p){let m=St(c,f+".jsonl");if(!f||ni(f)||f.split(/[\\/]/).includes("..")||!m.startsWith(c+ii)){e(`[SessionStore] skipping unsafe subpath from listSubkeys: ${f}`,{level:"warn"});continue}let h=await I(s.load({projectKey:a.projectKey,sessionId:a.sessionId,subpath:f}),u,`SessionStore.load() timed out after ${u}ms for session ${a.sessionId} subpath ${f}`);if(!h||h.length===0)continue;let S=[],C=[];for(let b of h)if(gn(b))S.push(b);else C.push(b);if(C.length>0)await _r(Ws(m),{recursive:!0}),await Bt(m,C);if(S.length>0){let b=S.at(-1),_=St(c,f+".meta.json");await _r(Ws(_),{recursive:!0});let{type:v,...R}=b;await Ys(_,n(R),{mode:384})}}}function fi(s){let a=s?.accepted===!0&&(typeof s.directory!=="string"||!(oi.isAbsolute(s.directory)||ai.isAbsolute(s.directory)))?void 0:s;if(s!==void 0&&a===void 0)e("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return a}function br(s,a){let{isSingleUserTurn:c,resumeConfigDir:u,deferSpawn:p,readsStartupMarks:f}=a,{systemPrompt:m,settings:h,managedSettings:S,settingSources:C,sandbox:b,..._}=s??{},v,R,E,P;if(m===void 0)v="";else if(typeof m==="string")v=m;else if(Array.isArray(m))v=m;else if(m.type==="custom")v=m.prompt,P=m.snapshot;else if(m.type==="preset")R=m.append,E=m.excludeDynamicSections,P=m.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.308";let{abortController:F=He(),additionalDirectories:D=[],projectConfigRoot:H,agent:ue,agents:Z,allowedTools:Je=[],betas:et,canUseTool:he,continue:_e,cwd:tt,debug:De,debugFile:Ie,disallowedTools:Ct=[],tools:vt,env:te,executable:Le=Se()?"bun":"node",executableArgs:kt=[],extraArgs:rt={},fallbackModel:de,enableFileCheckpointing:k,toolConfig:pe,forkSession:At,hooks:Ee,includeHookEvents:Ke,includePartialMessages:Fe,forwardSubagentText:st,verbatimPrompts:fe=!1,onElicitation:M,onUserDialog:Y,supportedDialogKinds:G,perTaskStopAffordance:ve,rapidFollowupPreempt:Tt,workspaceTrust:Pt,persistSession:$e,sessionStore:re,sessionStoreFlush:Js,thinking:je,effort:sn,maxThinkingTokens:Mt,maxTurns:on,maxBudgetUsd:an,taskBudget:pn,mcpServers:Er,model:mn,outputFormat:vr,permissionMode:hn,allowDangerouslySkipPermissions:Sn=!1,permissionPromptToolName:Cn,permissionPrompts:En,plugins:nt,pluginDelivery:xt="argv",getOAuthToken:wr,getHostAuthToken:kr,workload:Rr,resume:Ar,resumeSessionAt:vn,resumeDropsTurn:wn,sessionId:kn,skills:Tr,stderr:Rn,strictMcpConfig:An}=_,Pr=hn;if(re&&$e===!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.");os({supportedDialogKinds:G,onUserDialog:Y});let Tn=fi(Pt);if(re&&_e&&!Ar&&!re.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(re&&k)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(re&&_.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(Gs(!!he,Pr??"default",Je),xt!=="argv"&&xt!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let Mr=xt==="initialize"&&nt!==void 0&&nt.length>0,Dt=_.pathToClaudeCodeExecutable;if(!Dt){let B=li(import.meta.url),Q=ri(B),X=ns((we)=>Q.resolve(we));if(!X)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.`);Dt=X}let xr=vr?.type==="json_schema"?vr.schema:void 0,L=te?{...te}:{...process.env};if(!L.CLAUDE_CODE_ENTRYPOINT)L.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!L.CLAUDE_AGENT_SDK_VERSION)L.CLAUDE_AGENT_SDK_VERSION="0.3.308";if(k)L.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(L).some((B)=>B.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))L.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(f&&!Object.keys(L).some((B)=>B.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))L.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let It=Ue(L.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),Pn=Number.isFinite(It)&&It>=0?It:lt;if(wr)L.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(kr)L.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(pe?.askUserQuestion?.previewFormat)L.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=pe.askUserQuestion.previewFormat;for(let[B,Q]of[[pe?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[pe?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(B)L[Q]="1";else if(!te){for(let X of Object.keys(L))if(X.toUpperCase()===Q)delete L[X]}let Lt={};if(fr.inject(cr.active(),Lt),"traceparent"in Lt){for(let B of["TRACEPARENT","TRACESTATE"])if(!(B in(te??{})))delete L[B]}for(let[B,Q]of Object.entries(Lt)){let X=B.toUpperCase();if(!(X in(te??{})))L[X]=Q}let Or={},Dr=new Map;if(Er)for(let[B,Q]of Object.entries(Er))if(Q.type==="sdk"&&Q.instance)Dr.set(B,Q);else Or[B]=Q;let Be;if(je)switch(je.type){case"adaptive":Be={type:"adaptive",display:je.display};break;case"enabled":Be={type:"enabled",budgetTokens:je.budgetTokens,display:je.display};break;case"disabled":Be={type:"disabled"};break}else if(Mt!==void 0)Be=Mt===0?{type:"disabled"}:{type:"enabled",budgetTokens:Mt};if(u){if(L.CLAUDE_CONFIG_DIR=u,process.platform==="win32")L.CLAUDE_SECURESTORAGE_CONFIG_DIR=te?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??te?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let Ir=new Jt({abortController:F,additionalDirectories:D,projectConfigRoot:H,agent:ue,betas:et,cwd:tt,debug:De,debugFile:Ie,executable:Le,executableArgs:kt,extraArgs:Rr?{...rt,workload:Rr}:rt,pathToClaudeCodeExecutable:Dt,env:L,forkSession:At,stderr:Rn,thinkingConfig:Be,effort:sn,maxTurns:on,maxBudgetUsd:an,taskBudget:pn,model:mn,fallbackModel:de,jsonSchema:xr,permissionMode:Pr,allowDangerouslySkipPermissions:Sn,permissionPromptToolName:Cn,permissionPrompts:En,continueConversation:re?void 0:_e,resume:Ar,resumeSessionAt:vn,resumeDropsTurn:wn,sessionId:kn,settings:typeof h==="object"?n(h):h,managedSettings:S?n(S):void 0,settingSources:C,skills:Tr,allowedTools:Je,disallowedTools:Ct,tools:vt,mcpServers:Or,strictMcpConfig:An,canUseTool:!!he,hooks:!!Ee,includeHookEvents:Ke,includePartialMessages:Fe,persistSession:$e,sessionMirror:!!re,plugins:nt,pluginsViaInitialize:Mr,sandbox:b,spawnClaudeCodeProcess:_.spawnClaudeCodeProcess,onProcessSpawned:s?.onProcessSpawned,deferSpawn:p}),Mn={systemPrompt:v,appendSystemPrompt:R,planModeInstructions:_.planModeInstructions,systemPromptSnapshot:P,appendSubagentSystemPrompt:_.appendSubagentSystemPrompt,toolAliases:_.toolAliases,codeRunningMcpTools:_.codeRunningMcpTools,excludeDynamicSections:E,agents:Z,title:_.title,skills:Tr,webSearchIsolationExemptMcpServers:_.webSearchIsolationExemptMcpServers,promptSuggestions:_.promptSuggestions,agentProgressSummaries:_.agentProgressSummaries,forwardSubagentText:st,supportedDialogKinds:G,perTaskStopAffordance:ve,rapidFollowupPreempt:Tt,forwardNestedSubagentToolCalls:s?.forwardNestedSubagentToolCalls,workspaceTrust:Tn,plugins:Mr?nt:void 0,captureSdkMcpManifests:!gt("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},Kt=new pt(Ir,c,he,Ee,F,Dr,xr,Mn,M,wr,kr,Y,fe,Pn);if(re){let B=()=>z(L.CLAUDE_CONFIG_DIR??z(yr(),".claude"),"projects"),Q=Js==="eager",X=new ar(async(we,Ft)=>{let ze=Gt(we,B());if(ze)await re.append(ze,Ft);else e(`[SessionStore] dropping mirror frame: filePath ${we} is not under ${B()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(we,Ft)=>{let ze=Gt(we,B());if(ze)Kt.reportMirrorError(ze,Ft.message)},maxPendingEntries:Q?0:or,maxPendingBytes:Q?0:ir});Kt.setTranscriptMirrorBatcher(X)}return{queryInstance:Kt,transport:Ir,abortController:F,processEnv:L,verbatimPrompts:fe}}function Cr(s,a,c,u){if(typeof a==="string")s.writeAfterInitialize(n({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:a}]},parent_tool_use_id:null,...u&&{client_composed:!0}})+`
34
+ `).catch((p)=>c.abort(p));else s.streamInput(a).catch((p)=>c.abort(p))}var mi=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function _t(s){for(let a=0;;a++)try{return await ti(s,{recursive:!0,force:!0})}catch(c){if(a>=4||!mi.has(r(c)??""))return;await U((a+1)*100)}}function gi(s,a){s.waitForExit().catch(()=>{}).finally(()=>_t(a))}function hi({prompt:s,options:a}){if((a?.resume||a?.continue)&&a?.sessionStore)return Si(s,a);let{queryInstance:c,abortController:u,verbatimPrompts:p}=br(a,{isSingleUserTurn:typeof s==="string"});return Cr(c,s,u,p),c}function Si(s,a){let{queryInstance:c,transport:u,abortController:p,processEnv:f,verbatimPrompts:m}=br({...a},{isSingleUserTurn:typeof s==="string",deferSpawn:!0}),h=St(a.cwd??"."),S=a.sessionStore,C=a.loadTimeoutMs??60000,b=a.resume;return(async()=>{if(!b)b=(await I(S.listSessions(le(h,a.env)),C,`SessionStore.listSessions() timed out after ${C}ms`)).slice().sort((R,E)=>E.mtime-R.mtime)[0]?.sessionId;if(!b)return;return Xs(S,b,h,a.env,a.loadTimeoutMs)})().then((v)=>{if(v){u.updateResume(b);let R={CLAUDE_CONFIG_DIR:v};if(process.platform==="win32"){let E=a.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??a.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";R.CLAUDE_SECURESTORAGE_CONFIG_DIR=E,f.CLAUDE_SECURESTORAGE_CONFIG_DIR=E}u.updateEnv(R),f.CLAUDE_CONFIG_DIR=v,c.addCleanupCallback(()=>gi(u,v))}if(!c.isClosed())u.spawn()}).catch((v)=>{let R=N(v);u.spawnAbort(R),c.setError(R)}),Cr(c,s,p,m),c}async function _i(s={}){return(await yi(s)).warm}async function yi({options:s,initializeTimeoutMs:a}){let c,u=s?.resume;if((u||s?.continue)&&s?.sessionStore){let h=St(s.cwd??".");if(!u){if(!s.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let S=s.loadTimeoutMs??60000;u=(await I(s.sessionStore.listSessions(le(h,s.env)),S,`SessionStore.listSessions() timed out after ${S}ms`)).slice().sort((b,_)=>_.mtime-b.mtime)[0]?.sessionId}if(u)c=await Xs(s.sessionStore,u,h,s.env,s.loadTimeoutMs)}let p,f,m;try{let P=function(){if(E)return;E=!0,_.close()},h=br(c&&u&&u!==s?.resume?{...s,resume:u}:s,{isSingleUserTurn:!1,resumeConfigDir:c,readsStartupMarks:!0});p=h.queryInstance;let{transport:S,abortController:C,verbatimPrompts:b}=h;f=S;let _=h.queryInstance;if(c){let D=c;_.addCleanupCallback(()=>{m=S.waitForExit().catch(()=>{}).then(()=>_t(D))})}let R=new gr(a,Ne,s?.onStartupHooksRunning);_.setFrameObserver((D)=>{if(R.note(D),D.type==="system"&&D.subtype==="hook_progress")_.dropUnreadHookProgress(D.hook_id)});try{await R.race(_.initializationResult())}catch(D){if(D instanceof Error&&"errorClass"in D&&D.errorClass==="initialize_timeout"&&Object.isExtensible(D)){let H=_.startupMarkReached();Object.assign(D,{[as]:H?.mark??"none",...H&&{[ls]:H.ageMs}})}throw D}finally{_.setFrameObserver(void 0)}let E=!1;return{warm:{query(D){if(E)throw Error("WarmQuery.query() can only be called once");E=!0;try{Cr(_,D,C,b)}catch(H){throw _.close(),H}if(typeof D==="string")_.setIsSingleUserTurn(!0);return _},close:P,async[Symbol.asyncDispose](){E=!0,_.close(),await m}},query:_,transport:S}}catch(h){if(p?.close(),c&&!m){let S=f;m=(S?S.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>_t(c))}throw await m,h}}async function bi(s,a,c){let u=await import("./core-5682eevd.mjs");return u.renameSession(s,a,c)}async function Ci(s,a,c){let u=await import("./core-5682eevd.mjs");return u.tagSession(s,a,c)}async function Ei(s,a){let c=await import("./core-5682eevd.mjs");return c.deleteSession(s,a)}import{McpServer as vi}from"@modelcontextprotocol/sdk/server/mcp.js";import{normalizeObjectSchema as wi}from"@modelcontextprotocol/sdk/server/zod-compat.js";import{toJsonSchemaCompat as ki}from"@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";import{globalRegistry as Zs}from"zod/v4";import{version as ce}from"zod/v4/core";function Ri(s,a,c,u,p){let f={};if(p?.searchHint)f["anthropic/searchHint"]=p.searchHint;if(p?.alwaysLoad)f["anthropic/alwaysLoad"]=!0;return{name:s,description:a,inputSchema:c,handler:u,annotations:p?.annotations,_meta:Object.keys(f).length>0?f:void 0}}var Ai="CLAUDE_SDK_MCP_TOOL_SCHEMA_UNCONVERTIBLE";function Ti(s){let a=new vi({name:s.name,version:s.version??"1.0.0"},{capabilities:{tools:s.tools?{}:void 0},instructions:s.instructions});if(s.tools)s.tools.forEach((u)=>{let p=u.inputSchema;if(Mi(u.inputSchema)){let b=[];for(let[_,v]of Object.entries(u.inputSchema)){if(!bt(v)){b.push([_,v]);continue}let R=xi(v),E=v.description;if(E&&!Zs.has(R))Zs.add(R,{description:E});b.push([_,R])}p=Object.fromEntries(b)}let f=a.registerTool(u.name,{description:u.description,inputSchema:p,annotations:u.annotations,_meta:s.alwaysLoad?{"anthropic/alwaysLoad":!0,...u._meta}:u._meta},u.handler);if(!Object.getOwnPropertyDescriptor(f,"enabled")?.configurable||!Object.isExtensible(f))return;let h=f.enabled,S,C;Object.defineProperty(f,"enabled",{configurable:!0,enumerable:!0,get(){if(!h||S===f.inputSchema)return h;try{let b=wi(f.inputSchema);if(b)ki(b,{strictUnions:!0,pipeStrategy:"input"});return S=f.inputSchema,!0}catch(b){if(C!==f.inputSchema){C=f.inputSchema;let _=Xt(d(b),"."),v=[`Tool "${u.name}" on SDK MCP server "${s.name}" was left out of the server's tool list, because its input schema cannot be converted to JSON Schema${_?`: ${_}`:""}. The server's other tools are unaffected.`,...Pi(u.inputSchema,b)].join(" ");if(typeof process<"u"&&typeof process.emitWarning==="function")process.emitWarning(v,{code:Ai});else console.warn(v)}return!1}},set(b){h=b}})});let c=Et(s.timeout);return{type:"sdk",name:s.name,instance:a,...c!==void 0&&{timeout:c}}}function Pi(s,a){if(a instanceof ReferenceError)return["Something this tool's schema reads, such as a z.lazy target or a default value, is not defined yet. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back."];let p=`${ce.major}.${ce.minor}.${ce.patch}`,f=Object.values(s).filter(bt).map((_)=>_._zod?.version).find((_)=>typeof _?.major==="number"&&(_.major!==ce.major||_.minor!==ce.minor||_.patch!==ce.patch)),m=f&&`this tool's schema was built with zod ${f.major}.${f.minor}.${f.patch}, and this SDK converts schemas with its own zod ${p}`,h=`${ce.major}.${ce.minor}`;if(!(a instanceof TypeError)){let _=["Change this tool's schema so that every field can be converted."];if(m)_.push(`A different zod version can also cause this: ${m}, so building the schema with zod ${h} may fix it.`);return _}let S="a schema this tool uses is not defined yet, or a zod 3 schema is nested inside a zod 4 one. Define every schema this tool uses before passing the server to query(), startup() or setMcpServers(). Build the whole schema with zod 3 or with zod 4, not a mix of the two. A zod 4 z.lazy whose function has thrown once stays broken, so create the schema, its tool and the server again to get the tool back.";if(!f)return[`This can mean ${S}`];let C=[`The zod versions differ: ${m}. Conversion can fail across versions, so build the schema with zod ${h}, or use an SDK release that bundles your zod version.`],b=f.major===4&&f.minor<=3;if(b)C.push(`On zod ${f.major}.${f.minor}, a z.record given only one argument also causes this; pass both, as in z.record(keySchema, valueSchema).`);return C.push(`If ${b?"neither is the cause":"the version difference is not the cause"}, it can mean ${S}`),C}function bt(s){return typeof s==="object"&&s!==null&&"_zod"in s}function Mi(s){return typeof s==="object"&&s!==null&&!("_zod"in s)&&!("_def"in s)&&typeof s.parse!=="function"}function xi(s){if(!(Oi(s)?!ge(s,!0):yt(s)&&!ge(s,!1))||s._zod.optin!=="optional"||s._zod.optout!=="optional"||typeof s.clone!=="function")return s;let c=s.clone();return c._zod.optin="defaulted",c}function Oi(s){let a=s._zod.version;return a?.major===4&&a.minor<5}function ge(s,a,c=new Set){if(!bt(s)||c.has(s))return!1;c.add(s);let u=s._zod.def;switch(u.type){case"lazy":return!0;case"optional":return!a&&ge(u.innerType,a,c);case"nullable":case"catch":case"readonly":return ge(u.innerType,a,c);case"pipe":return ge(u.in,a,c)||ge(u.out,a,c);case"union":return u.options?.some((p)=>ge(p,a,c))??!1;default:return!1}}function yt(s,a=new Set){if(!bt(s)||a.has(s))return!1;a.add(s);let c=s._zod.def;switch(c.type){case"default":case"prefault":return!0;case"optional":case"nullable":case"catch":case"readonly":return yt(c.innerType,a);case"pipe":return yt(c.in,a);case"union":return c.options?.some((u)=>yt(u,a))??!1;default:return!1}}async function Di(s){let{resolveSettingsForSdk:a}=await import("./core-36zyfan5.mjs");return a(s)}var Ii=new Set(["bypassPermissions","auto","acceptEdits"]),Ni=new Set(["project"]),Li=new Set(["project","local"]);function Ki(s){let a=s.effective.permissions?.defaultMode;if(!a||!Ii.has(a))return s.effective;for(let c=s.sources.length-1;c>=0;c--){let u=s.sources[c];if(u.settings.permissions?.defaultMode!==void 0){if((_n.includes(a)?Li:Ni).has(u.source)){let{defaultMode:f,...m}=s.effective.permissions??{};return{...s.effective,permissions:m}}return s.effective}}return s.effective}export{me as AbortError,rn as BUILTIN_TOOL_NAMES,yn as EXIT_REASONS,J as HOOK_EVENTS,Xe as LEGACY_TOOL_NAME_ALIASES,en as ORG_POLICY_LIMIT_PREFIXES,bn as SYSTEM_PROMPT_DYNAMIC_BOUNDARY,Qt as USAGE_LIMIT_ERROR_PREFIXES,nn as USAGE_TRANSITION_PREFIXES,tn as USAGE_WARNING_PREFIXES,Ti as createSdkMcpServer,Ei as deleteSession,Ki as filterEscalatingDefaultMode,hi as query,bi as renameSession,Di as resolveSettings,_i as startup,Ci as tagSession,Ri as tool};
@@ -0,0 +1 @@
1
+ export function extractFromBunfs(embeddedPath: string): string
@@ -0,0 +1,156 @@
1
+ /* oxlint-disable custom-rules/no-sync-fs */
2
+ // Extracts a file from Bun's $bunfs virtual filesystem to a real temp directory
3
+ // so it can be spawned as a subprocess (child processes cannot access $bunfs).
4
+ //
5
+ // Ships verbatim (unbundled) as the @anthropic-ai/claude-agent-sdk `./extract`
6
+ // export — keep it standalone and Node-importable (no Bun globals, no
7
+ // local-relative imports).
8
+
9
+ import { createHash } from 'crypto'
10
+ import {
11
+ chmodSync,
12
+ existsSync,
13
+ lstatSync,
14
+ mkdirSync,
15
+ readFileSync,
16
+ renameSync,
17
+ unlinkSync,
18
+ writeFileSync,
19
+ } from 'fs'
20
+ import { tmpdir as osTmpdir } from 'os'
21
+ import { basename, join } from 'path'
22
+
23
+ // Inlined from src/utils/tempfile.ts — this file ships verbatim (unbundled) as
24
+ // the @anthropic-ai/claude-agent-sdk/extract export, so it must have zero
25
+ // local-relative imports. Keep behavior in sync with tempfile.ts#tmpdir.
26
+ function tmpdir() {
27
+ if (process.env.CLAUDE_CODE_TMPDIR) {
28
+ return process.env.CLAUDE_CODE_TMPDIR
29
+ }
30
+ if (process.platform === 'darwin') {
31
+ // oxlint-disable-next-line custom-rules/no-hardcoded-tmp -- mirrors tempfile.ts: macOS /tmp works fine; os.tmpdir() below is for Android-on-Linux where /tmp isn't writable.
32
+ return '/tmp'
33
+ }
34
+ return osTmpdir()
35
+ }
36
+
37
+ // Inlined from src/utils/tempfile.ts#claudeTempDir + verifyTempDirOwnership —
38
+ // keep behavior in sync. Per-UID Claude temp directory: `{tmpdir()}/claude-{uid}`
39
+ // on Unix, `{tmpdir()}/claude` on Windows (where %TEMP% is already per-user).
40
+ //
41
+ // Defense-in-depth against a local attacker pre-creating the extraction dir
42
+ // before the victim's first run: the content-hash dir name is fully predictable
43
+ // (sha256 of a public npm binary) under shared `/tmp`, and
44
+ // `mkdirSync({recursive:true})` is a silent no-op on a pre-existing dir without
45
+ // enforcing owner or mode. Without this check an attacker-owned directory would
46
+ // be used as-is, letting them swap the binary the SDK later spawns.
47
+ function safeTempBase() {
48
+ const dir = join(
49
+ tmpdir(),
50
+ process.platform === 'win32'
51
+ ? 'claude'
52
+ : `claude-${process.getuid?.() ?? 0}`,
53
+ )
54
+ // Gate on getuid (POSIX-only) rather than process.platform: getuid presence
55
+ // reflects the real OS. No-op on Windows where %TEMP% is already per-user.
56
+ if (typeof process.getuid === 'function') {
57
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
58
+ const uid = process.getuid()
59
+ const st = lstatSync(dir)
60
+ if (!st.isDirectory()) {
61
+ throw new Error(
62
+ `Temp directory ${dir} is not a directory (may be an attacker-planted symlink). Refusing to use it.`,
63
+ )
64
+ }
65
+ if (st.uid !== uid) {
66
+ throw new Error(
67
+ `Temp directory ${dir} is owned by uid ${st.uid}, expected ${uid}. Refusing to use it — another user may have pre-created it.`,
68
+ )
69
+ }
70
+ if ((st.mode & 0o777) !== 0o700) {
71
+ // Owner matches, so this is our own dir from a prior run with a looser
72
+ // umask rather than an attacker pre-create. Tighten it.
73
+ chmodSync(dir, 0o700)
74
+ }
75
+ } else {
76
+ // Windows: best-effort create; verification is skipped (%TEMP% is per-user).
77
+ try {
78
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
79
+ } catch {
80
+ // best-effort; see comment above
81
+ }
82
+ }
83
+ return dir
84
+ }
85
+
86
+ /**
87
+ * If `embeddedPath` is inside Bun's $bunfs virtual filesystem, extract it to a
88
+ * temp directory and return the real path. Otherwise return the path unchanged.
89
+ *
90
+ * Uses a content hash for the directory name so that:
91
+ * - Same binary version reuses the same extracted file (no accumulation)
92
+ * - Different versions get separate directories (no collision)
93
+ * - Concurrent instances are safe (atomic write via temp file + rename)
94
+ *
95
+ * @param {string} embeddedPath — path returned by `import ... with { type: 'file' }`
96
+ * @returns {string} — a real filesystem path that can be spawned as a subprocess
97
+ */
98
+ export function extractFromBunfs(embeddedPath) {
99
+ // Bun single-file embed: `/$bunfs/root/...` (POSIX) or `B:\~BUN\root\...`
100
+ // (Windows — Bun's StandaloneModuleGraph uses `~BUN`, not `$bunfs`, on Windows).
101
+ if (!embeddedPath.includes('$bunfs') && !embeddedPath.includes('~BUN')) {
102
+ return embeddedPath
103
+ }
104
+
105
+ try {
106
+ const content = readFileSync(embeddedPath)
107
+ const hash = createHash('sha256').update(content).digest('hex').slice(0, 16)
108
+ const tmpDir = join(safeTempBase(), `claude-agent-sdk-${hash}`)
109
+ // Preserve the embedded file's basename — ProcessTransport.isNativeBinary()
110
+ // decides whether to spawn directly or via node/bun based on extension, so
111
+ // a native binary must not come out named cli.js.
112
+ const fileName = basename(embeddedPath)
113
+ const tmpPath = join(tmpDir, fileName)
114
+ mkdirSync(tmpDir, { recursive: true, mode: 0o700 })
115
+ // The directory is content-hash-keyed, so an existing tmpPath is byte-
116
+ // identical to what we would write — short-circuit. This is a write
117
+ // idempotency check on a content-addressed path, not a read TOCTOU
118
+ // (the existence IS the contract). Without it, a second call (or a
119
+ // concurrent app instance) on Windows would hit EPERM/EBUSY renaming over
120
+ // the memory-mapped running .exe and fall back to the unspawnable $bunfs
121
+ // path. It also skips a redundant write+chmod on every call.
122
+ if (existsSync(tmpPath)) {
123
+ return tmpPath
124
+ }
125
+ // Write to a temp file and atomically rename to avoid truncation races —
126
+ // concurrent readers always see either the old complete file or the new one.
127
+ const tmpFile = join(tmpDir, `${fileName}.tmp.${process.pid}`)
128
+ writeFileSync(tmpFile, content)
129
+ chmodSync(tmpFile, 0o755)
130
+ try {
131
+ renameSync(tmpFile, tmpPath)
132
+ } catch (e) {
133
+ if ((e.code === 'EPERM' || e.code === 'EBUSY') && existsSync(tmpPath)) {
134
+ // Lost a concurrent first-time-extraction race on Windows: the winner's
135
+ // child holds tmpPath memory-mapped, so the loser's rename over it fails.
136
+ // The content-hash dir guarantees byte-identity, so the winner's file is
137
+ // exactly what we'd have written — use it.
138
+ try {
139
+ unlinkSync(tmpFile)
140
+ } catch {
141
+ // best-effort cleanup of our orphaned .tmp.{pid} file
142
+ }
143
+ return tmpPath
144
+ }
145
+ throw e
146
+ }
147
+ return tmpPath
148
+ } catch (err) {
149
+ // oxlint-disable-next-line no-console -- intentional user-facing warning in standalone SDK helper
150
+ console.warn(
151
+ `[claude-agent-sdk] Failed to extract CLI from $bunfs: ${err.message}. ` +
152
+ `Child processes cannot access $bunfs paths — the CLI will likely fail to start.`,
153
+ )
154
+ return embeddedPath
155
+ }
156
+ }
@@ -0,0 +1,82 @@
1
+ {
2
+ "version": "2.1.308",
3
+ "manifestSignatureEnforcement": "flag",
4
+ "commit": "320f66eb8f834be58a10c98283ebef19e3640c37",
5
+ "buildDate": "2026-10-22T03:48:37Z",
6
+ "platforms": {
7
+ "darwin-arm64": {
8
+ "binary": "claude",
9
+ "checksum": "ca923c86ac84b30574a82331a05b6e066c27477a926ceaffe46a845a33e4dd37",
10
+ "size": 274675680
11
+ },
12
+ "darwin-x64": {
13
+ "binary": "claude",
14
+ "checksum": "9a0bc140f5fb06e6366624d770371ef290e6731d1e84c4def5daf4df946d1b59",
15
+ "size": 285902384
16
+ },
17
+ "linux-arm64": {
18
+ "binary": "claude",
19
+ "checksum": "fdd22e6cbb734d580f5664c48df4294eeec850218ff07f186f9af30426396ee1",
20
+ "size": 292085944
21
+ },
22
+ "linux-x64": {
23
+ "binary": "claude",
24
+ "checksum": "356733f185fa988e6bf3aa9a555269fdd167982a2e2a80d3c8a78037bb92ad58",
25
+ "size": 292232560
26
+ },
27
+ "linux-arm64-musl": {
28
+ "binary": "claude",
29
+ "checksum": "b820bec20177aa09875515cf5ffadb445ecf814ec7c8ed51ba2f86c3090a692d",
30
+ "size": 284313472
31
+ },
32
+ "linux-x64-musl": {
33
+ "binary": "claude",
34
+ "checksum": "45cc10091e10ca658daa691e879058ba1d4752218c63577d1c7d54b0c7dc9a68",
35
+ "size": 285896848
36
+ },
37
+ "win32-x64": {
38
+ "binary": "claude.exe",
39
+ "checksum": "c9796ba22a9221586b36371b36f5b66198d66eb4badf6a4cf4a5f7b07becea53",
40
+ "size": 297376928
41
+ },
42
+ "win32-arm64": {
43
+ "binary": "claude.exe",
44
+ "checksum": "35b5af5dde46a775ccd5a4d15760913c6088cf7292e1b15f0b09b1fd3f93bfd2",
45
+ "size": 281453216
46
+ }
47
+ },
48
+ "sdkCompat": {
49
+ "testedWrapperVersions": [
50
+ "0.3.274",
51
+ "0.3.275",
52
+ "0.3.276",
53
+ "0.3.277",
54
+ "0.3.278",
55
+ "0.3.280",
56
+ "0.3.281",
57
+ "0.3.282",
58
+ "0.3.283",
59
+ "0.3.284",
60
+ "0.3.285",
61
+ "0.3.286",
62
+ "0.3.287",
63
+ "0.3.288",
64
+ "0.3.289",
65
+ "0.3.290",
66
+ "0.3.291",
67
+ "0.3.292",
68
+ "0.3.293",
69
+ "0.3.294",
70
+ "0.3.295",
71
+ "0.3.296",
72
+ "0.3.299",
73
+ "0.3.300",
74
+ "0.3.301",
75
+ "0.3.302",
76
+ "0.3.303",
77
+ "0.3.304",
78
+ "0.3.305"
79
+ ],
80
+ "harnessSchema": 1
81
+ }
82
+ }