@anthropic-ai/claude-agent-sdk 0.3.307 → 0.3.308
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bridge.mjs +2 -2
- package/browser-sdk.js +2 -2
- package/{core-dk3ky68t.mjs → core-36zyfan5.mjs} +2 -2
- package/{core-magja67b.mjs → core-5682eevd.mjs} +2 -2
- package/{core-s632fyaa.mjs → core-nne0e2ds.mjs} +1 -1
- package/{core-3qt252mw.mjs → core-xpxe8nzb.mjs} +1 -1
- package/core.mjs +5 -5
- package/manifest.json +19 -20
- package/manifest.zst.json +23 -24
- package/package.json +14 -14
- package/sdk.mjs +3 -3
package/bridge.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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
2
|
|
|
3
|
-
// Version: 0.3.
|
|
3
|
+
// Version: 0.3.308
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -74,7 +74,7 @@ maxBuffer exceeded`,maxBufferExceeded:!0}:{stdout:"",stderr:"",code:1,maxBufferE
|
|
|
74
74
|
`);return s===-1?"":r.stack.slice(s+1)})();try{if(!n.stack)n.stack=o;else if(o){let s=o.indexOf(`
|
|
75
75
|
`),i=s===-1?-1:o.indexOf(`
|
|
76
76
|
`,s+1),a=i===-1?"":o.slice(i+1);if(!String(n.stack).endsWith(a))n.stack+=`
|
|
77
|
-
`+o}}catch(s){}}throw n}}_request(e,t){if(typeof e==="string")t=t||{},t.url=e;else t=e||{};t=tn(this.defaults,t);let{transitional:n,paramsSerializer:r,headers:o}=t;if(n!==void 0)bi.assertOptions(n,{silentJSONParsing:$t.transitional($t.boolean),forcedJSONParsing:$t.transitional($t.boolean),clarifyTimeoutError:$t.transitional($t.boolean),legacyInterceptorReqResOrdering:$t.transitional($t.boolean)},!1);if(r!=null)if(S.isFunction(r))t.paramsSerializer={serialize:r};else bi.assertOptions(r,{encode:$t.function,serialize:$t.function},!0);if(t.allowAbsoluteUrls!==void 0);else if(this.defaults.allowAbsoluteUrls!==void 0)t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls;else t.allowAbsoluteUrls=!0;bi.assertOptions(t,{baseUrl:$t.spelling("baseURL"),withXsrfToken:$t.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&S.merge(o.common,o[t.method]);o&&S.forEach(["delete","get","head","post","put","patch","common"],(m)=>{delete o[m]}),t.headers=ke.concat(s,o);let i=[],a=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen==="function"&&h.runWhen(t)===!1)return;a=a&&h.synchronous;let _=t.transitional||dr;if(_&&_.legacyInterceptorReqResOrdering)i.unshift(h.fulfilled,h.rejected);else i.push(h.fulfilled,h.rejected)});let c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let l,d=0,p;if(!a){let m=[Ru.bind(this),void 0];m.unshift(...i),m.push(...c),p=m.length,l=Promise.resolve(t);while(d<p)l=l.then(m[d++],m[d++]);return l}p=i.length;let f=t;while(d<p){let m=i[d++],h=i[d++];try{f=m(f)}catch(_){h.call(this,_);break}}try{l=Ru.call(this,f)}catch(m){return Promise.reject(m)}d=0,p=c.length;while(d<p)l=l.then(c[d++],c[d++]);return l}getUri(e){e=tn(this.defaults,e);let t=Wr(e.baseURL,e.url,e.allowAbsoluteUrls);return Gr(t,e.params,e.paramsSerializer)}}S.forEach(["delete","get","head","options"],function(t){Si.prototype[t]=function(n,r){return this.request(tn(r||{},{method:t,url:n,data:(r||{}).data}))}});S.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(tn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Si.prototype[t]=n(),Si.prototype[t+"Form"]=n(!0)});var xi=Si;class mf{constructor(e){if(typeof e!=="function")throw TypeError("executor must be a function.");let t;this.promise=new Promise(function(o){t=o});let n=this;this.promise.then((r)=>{if(!n._listeners)return;let o=n._listeners.length;while(o-- >0)n._listeners[o](r);n._listeners=null}),this.promise.then=(r)=>{let o,s=new Promise((i)=>{n.subscribe(i),o=i}).then(r);return s.cancel=function(){n.unsubscribe(o)},s},e(function(o,s,i){if(n.reason)return;n.reason=new It(o,s,i),t(n.reason)})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}if(this._listeners)this._listeners.push(e);else this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);if(t!==-1)this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=(n)=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new mf(function(r){e=r}),cancel:e}}}var Zv=mf;function hf(e){return function(n){return e.apply(null,n)}}function gf(e){return S.isObject(e)&&e.isAxiosError===!0}var _f={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(_f).forEach(([e,t])=>{_f[t]=e});var Xv=_f;function Jv(e){let t=new xi(e),n=ri(xi.prototype.request,t);return S.extend(n,xi.prototype,t,{allOwnKeys:!0}),S.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Jv(tn(e,o))},n}var We=Jv(Bo);We.Axios=xi;We.CanceledError=It;We.CancelToken=Zv;We.isCancel=fi;We.VERSION=Yr;We.toFormData=lr;We.AxiosError=D;We.Cancel=We.CanceledError;We.all=function(t){return Promise.all(t)};We.spread=hf;We.isAxiosError=gf;We.mergeConfig=tn;We.AxiosHeaders=ke;We.formToJSON=(e)=>pu(S.isHTMLForm(e)?new FormData(e):e);We.getAdapter=Au.getAdapter;We.HttpStatusCode=Xv;We.default=We;var Bn=We;var{Axios:gLe,AxiosError:_Le,CanceledError:yLe,isCancel:ELe,CancelToken:bLe,VERSION:SLe,all:xLe,Cancel:vLe,isAxiosError:CLe,spread:ALe,toFormData:RLe,AxiosHeaders:TLe,HttpStatusCode:wLe,formToJSON:OLe,getAdapter:kLe,mergeConfig:ILe}=Bn;var mK=/^req_[A-Za-z0-9_-]{1,36}$/;function Qv(e){return typeof e==="string"&&mK.test(e)}var hK=/cloudflare/i;function zo(e){let t=e("request-id");if(typeof t==="string"&&Qv(t.trim()))return"origin";let n=e("cf-ray"),r=e("server");if(typeof n==="string"&&n!==""||typeof r==="string"&&hK.test(r))return"nonorigin_cf";return"nonorigin_other"}function wu(e){return e==="nonorigin_cf"||e==="nonorigin_other"}qn();he();re();var $O=/(?<![^\s\p{P}])\p{M}+/gu;bs();it();function M9(e){return Vw(B9(jc(e))).replace(/ {2,}/g," ").trim()}var F9=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/g,U9=4;function B9(e){let t=e;for(let n=0;n<U9;n++){let r=t.replace(F9,"");if(r===t)break;t=r}return t}function Ki(e,t=160){return $9(M9(j9(e,t)).normalize("NFC").replace(/[`\uff40\u02cb\u1fef\u2035]/g,"'").replace($O,""),t)}var H9=new RegExp(`[^\\S ]|[${wn}]`,"u");function jO(e,t){return e.length<=t&&!H9.test(e)&&Ki(e,t)===e.replaceAll("`","'")}function $9(e,t=2000){return e.length>t?`${Tn(e,t)}…`:e}function j9(e,t){let n=Tn(e,t*8);if(n.length===e.length)return n;let r=/\x1b(?:[\]PX^_][^\x1b\x07]*\x1b?|\[[\x30-\x3f]*[\x20-\x2f]*)$/.exec(n);if(r===null)return n;let o=e.slice(r.index);return(o[1]==="["?/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/.test(o):/^\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/.test(o))?n.slice(0,r.index):n}re();$e();function GO(e){return typeof e==="string"&&/^[a-z0-9_]{1,64}$/.test(e)}function Kt(){return"claude-code/0.3.307"}function On(e=process.env.CLAUDE_CODE_ENTRYPOINT){switch(e){case"claude-vscode":return"claude_code_vscode";case"remote":case"remote_baku":case"remote_cowork":case"remote_desktop":case"remote_mobile":case"remote_projects":return"claude_code_remote";case"claude-in-teams":return"claude_code_remote";case"sdk-cli":case"sdk-ts":case"sdk-py":return"claude_code_sdk";case"mcp":return"claude_code_mcp";case"claude-code-github-action":return"claude_code_github_action";case"local-agent":return"claude_code_local_agent";case"claude_in_slack":return"claude_in_slack";case"claude-in-slack":return"claude-in-slack";case"cli":default:return"claude_code_cli"}}Yn();he();re();Jh();$e();var Y9=["session_ingress_token","environment_secret","access_token","secret","token"],KGe=new RegExp(`"(${Y9.join("|")})"\\s*:\\s*"[^"]*"`,"g");function Jc(e){if(!e||typeof e!=="object")return;if("message"in e&&typeof e.message==="string")return e.message;if("error"in e&&e.error!==null&&typeof e.error==="object"&&"message"in e.error&&typeof e.error.message==="string")return e.error.message;return}function zO(e){let t=Jc(e);return t?qi(t,"error_message"):void 0}function qi(e,t){if(jO(e,1024))return e;b(`[error-detail] left the service's text (${t}) out of the error shown: it has ${e.length} UTF-16 units and is not one plain line of at most 1,024 units`),ve("tengu_service_error_detail_not_plain",{length:e.length,source:Me(t)});return}tl();var gxe="2023-06-01";function BN(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","anthropic-version":gxe,"anthropic-client-platform":On(),"User-Agent":Kt()}}function _xe(e){return e!==null&&typeof e==="object"&&"terminal"in e&&e.terminal===!0}function yxe(e){if(e===null||typeof e!=="object"||!("error"in e)||e.error===null||typeof e.error!=="object")return!1;let t=e.error,n="type"in t?t.type:void 0,r="resource_type"in t?t.resource_type:void 0,o="reason"in t?t.reason:void 0;return n==="not_found_error"&&r==="session_grouping"||o==="public_grouping_hosted_only"||o==="feature_disabled"}function HN(e){if(e===401)return"oauth_rejected";if(e===408||e===429||e>=500)return"transient";return"rejected"}async function Exe(e,t,n,r,o,s,i,a,c,l,d){let p=`${e}/v1/code/sessions`,f={cwd:i??Rn(),...a&&{model:a}};if(s&&"gitRepoUrl"in s){await Promise.resolve().then(() => UN());let{sources:g,outcomes:E,report:x}=await FN(s.gitRepoUrl,s.branch,s.defaultBranch);if(x.branchDropped&&x.warnMessage){let v=`${x.branchDropped}:${s.gitRepoUrl}:${s.branch}`;if(!l||l.lastKey!==v){if(l)l.lastKey=v;b(`[code-session] ${x.warnMessage}`)}}else if(l)l.lastKey=null;if(g.length>0||E.length>0)f.sources=g,f.outcomes=E,f.reuse_outcome_branches=!0}let m;try{m=await Bn.post(p,{title:n,bridge:{},...o?.length&&{tags:o},...c&&{session_grouping_id:c},config:f},{headers:BN(t),timeout:r,validateStatus:(_)=>_<500})}catch(_){return b(`[code-session] Session create request failed: ${j(_)}`),null}if(m.status!==200&&m.status!==201){let _=Jc(m.data);b(`[code-session] Session create failed ${m.status}${_?`: ${_}`:""}`);let g=zO(m.data);if(m.status===401)d?.();if(m.status>=400&&m.status<500&&yxe(m.data))return{terminal:!0,reason:"grouping_rejected",status:m.status,detail:g};switch(HN(m.status)){case"oauth_rejected":return{terminal:!1,reason:"oauth_rejected"};case"transient":return null;case"rejected":return{terminal:!0,reason:"request_rejected",status:m.status,detail:g}}}let h=m.data;if(!h||typeof h!=="object"||!("session"in h)||!h.session||typeof h.session!=="object"||!("id"in h.session)||typeof h.session.id!=="string"||!h.session.id.startsWith("cse_")||!ek(h.session.id))return b(`[code-session] No usable session.id (cse_*) in response: ${xe(h).slice(0,200)}`),{terminal:!0,reason:"malformed_response",status:m.status,detail:void 0};return h.session.id}function bxe(e){return e!==null&&"terminal"in e&&e.terminal===!0}function Sxe(e){return typeof e==="object"&&e!==null&&"terminal"in e&&e.terminal===!1}function $N(e){let t=ty(e);if(t!==void 0&&"resource"in t){let n=t.resource;if(n==="untrusted_device"||n==="session_stale_relogin")return n}return}function xxe(e){if($N(e)==="untrusted_device"){let t=ty(e),n=t!==void 0&&"sub_reason"in t?t.sub_reason:void 0;if(n===void 0||n===null||n==="")return{kind:"token_refused"};if(typeof n!=="string")return{kind:"unrecognized",subReason:`(${typeof n}, not a string)`};switch(n){case"bound_unattested":return{kind:"token_refused"};case"served_call_unsigned":return{kind:"signature_wanted",subReason:n};default:if(GO(n))return{kind:"unrecognized",subReason:n};return b(`[code-session] a 403's sub_reason is too long or not snake_case, so a placeholder is passed on. As sent (${n.length} characters; cleaned, first 64): ${Ki(n,64)}`),{kind:"unrecognized",subReason:"(string, too long or not snake_case)"}}}return}function ty(e){return e!==null&&typeof e==="object"&&"error"in e&&e.error!==null&&typeof e.error==="object"?e.error:void 0}function vxe(e,t,n,r,o,s){return Cxe(e,t,n,r,o,s,void 0)}async function Cxe(e,t,n,r,o,s,i){if(!Axe(e,"/bridge"))return{terminal:!0,reason:"invalid_session_id"};let a=`${t}/v1/code/sessions/${e}/bridge`,c=BN(n);if(o)c["X-Trusted-Device-Token"]=o;let l;try{l=await Bn.post(a,i===void 0?{}:{expected_epoch:i.expectedEpoch},{headers:c,timeout:r,validateStatus:(f)=>f<500})}catch(f){return b(`[code-session] /bridge request failed: ${j(f)}`),null}if(l.status!==200){let f=Jc(l.data);if(b(`[code-session] /bridge failed ${l.status}${f?`: ${f}`:""}`),l.status===401)s?.();if(i!==void 0&&l.status===409){let h=ty(l.data),_=i.expectedEpoch,g=[ey(h!==void 0&&"expected_epoch"in h?h.expected_epoch:void 0),ey(h!==void 0&&"actual_epoch"in h?h.actual_epoch:void 0)];i.onRefused(g.includes(_)?g.find((E)=>E!==void 0&&E>_):void 0)}let m;if(l.status===403){let h=$N(l.data);if(h==="untrusted_device"){let _=xxe(l.data);return{terminal:!0,reason:h,..._&&{refusal:_}}}if(h)return{terminal:!0,reason:h};m=zo((_)=>l.headers?.[_]),b(`[code-session] /bridge 403 source=${m}`)}switch(HN(l.status)){case"oauth_rejected":return{terminal:!1,reason:"oauth_rejected"};case"transient":return null;case"rejected":return{terminal:!0,reason:"request_rejected",status:l.status,...m&&{source:m}}}}let d=l.data;if(d===null||typeof d!=="object"||!("worker_jwt"in d)||typeof d.worker_jwt!=="string"||!("expires_in"in d)||typeof d.expires_in!=="number"||!("api_base_url"in d)||typeof d.api_base_url!=="string"||!("worker_epoch"in d))return b(`[code-session] /bridge response malformed (need worker_jwt, expires_in, api_base_url, worker_epoch): ${xe(d).slice(0,200)}`),{terminal:!0,reason:"malformed_response",status:200};let p=ey(d.worker_epoch);if(p===void 0)return b(`[code-session] /bridge worker_epoch invalid: ${xe(d.worker_epoch)}`),{terminal:!0,reason:"malformed_response",status:200};return{worker_jwt:d.worker_jwt,api_base_url:d.api_base_url,expires_in:d.expires_in,worker_epoch:p,mcp_config:Rxe(d),...{}}}function Axe(e,t){try{return el(e,"sessionId"),!0}catch(n){return b(`[code-session] ${t}: ${j(n)}`),!1}}function Rxe(e){if(!("mcp_config"in e))return;let t=e.mcp_config;if(t!==null&&typeof t==="object"&&"content"in t&&typeof t.content==="string"&&t.content.length>0)return{content:t.content};return}function ey(e){let t=typeof e==="string"?Number(e):e;return typeof t==="number"&&Number.isSafeInteger(t)?t:void 0}he();re();import{randomUUID as $a}from"crypto";var ny=["invalid_request","catalog_unknown","not_found","restricted_by_org","unavailable_for_account","not_offered","alias_1m_disabled","alias_1m_unsupported","blocked_by_hook","check_failed","check_rejected","credits_required","rate_limit","auth_failed","model_not_current","verdict_pending","internal_error"],Txe=["invalid_mode","bypass_restricted","bypass_disabled","bypass_not_launched","auto_mode_settings","auto_mode_circuit_breaker","auto_mode_fast_mode","auto_mode_model","auto_mode_unavailable"],wxe=["remote_control_auth","remote_control_terminal","remote_control_ended_elsewhere","remote_control_policy_disabled"];var Oxe=["workspace_diff_pending"],kxe=["stale_worker_epoch","invalid_worker_epoch"],Ixe=["read_denied"],Int=[...ny,...Txe,...wxe,...Oxe,...kxe,...Ixe];he();it();var Pxe=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF]|[\uDC00-\uDFFF]/g;function Dxe(e){return e.replace(Pxe,(t)=>t.length===2?t:"")}var Lxe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}\u2800]|(?!\u0020)\p{Zs}/gu;function wt(e){if(typeof e!=="string")return"";return Tn(Nxe(e.length>4096?e.slice(0,4096):e),1024)}function Nxe(e){if(typeof e!=="string")return"";let t=e;for(let n=0;n<64;n++){let r=Dxe(t).replace(Lxe,"");if(r===t)return r;t=r}return""}re();_t();var GN=8000;async function WN({verdict:e,deadlineMs:t,respond:n,inform:r}){let o=(d)=>{if(Array.isArray(d))r(d.filter((p)=>typeof p==="string").map(wt))},s=e.then((d)=>d??{ok:!0}),i;try{i=await vn(s,t)}catch(d){return b(`set_model verdict rejected: ${j(d)}`,{level:"error"}),n({subtype:"error",error:"set_model failed",error_code:"internal_error"})}if(i===void 0)return s.then((d)=>o(d.ok?[...Array.isArray(d.notices)?d.notices:[],"The pending model switch was applied"]:jN(d.error)),(d)=>{b(`set_model verdict rejected after the deadline reply: ${j(d)}`,{level:"error"}),o(["The pending model switch failed"])}),n({subtype:"error",error:"This model switch is still pending (an earlier model change, a check with the API or a PreModelSwitch hook has not finished); it will apply when that completes unless it is refused",error_code:"verdict_pending"});let a=typeof i.model==="string"?wt(i.model):void 0;if(i.ok){if(i.notices)o(i.notices);return n(a===void 0?{subtype:"success"}:{subtype:"success",response:{model:a}})}let c=i.code,l=ny.find((d)=>d===c);return n({subtype:"error",error:jN(i.error).map(wt).join(`
|
|
77
|
+
`+o}}catch(s){}}throw n}}_request(e,t){if(typeof e==="string")t=t||{},t.url=e;else t=e||{};t=tn(this.defaults,t);let{transitional:n,paramsSerializer:r,headers:o}=t;if(n!==void 0)bi.assertOptions(n,{silentJSONParsing:$t.transitional($t.boolean),forcedJSONParsing:$t.transitional($t.boolean),clarifyTimeoutError:$t.transitional($t.boolean),legacyInterceptorReqResOrdering:$t.transitional($t.boolean)},!1);if(r!=null)if(S.isFunction(r))t.paramsSerializer={serialize:r};else bi.assertOptions(r,{encode:$t.function,serialize:$t.function},!0);if(t.allowAbsoluteUrls!==void 0);else if(this.defaults.allowAbsoluteUrls!==void 0)t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls;else t.allowAbsoluteUrls=!0;bi.assertOptions(t,{baseUrl:$t.spelling("baseURL"),withXsrfToken:$t.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&S.merge(o.common,o[t.method]);o&&S.forEach(["delete","get","head","post","put","patch","common"],(m)=>{delete o[m]}),t.headers=ke.concat(s,o);let i=[],a=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen==="function"&&h.runWhen(t)===!1)return;a=a&&h.synchronous;let _=t.transitional||dr;if(_&&_.legacyInterceptorReqResOrdering)i.unshift(h.fulfilled,h.rejected);else i.push(h.fulfilled,h.rejected)});let c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let l,d=0,p;if(!a){let m=[Ru.bind(this),void 0];m.unshift(...i),m.push(...c),p=m.length,l=Promise.resolve(t);while(d<p)l=l.then(m[d++],m[d++]);return l}p=i.length;let f=t;while(d<p){let m=i[d++],h=i[d++];try{f=m(f)}catch(_){h.call(this,_);break}}try{l=Ru.call(this,f)}catch(m){return Promise.reject(m)}d=0,p=c.length;while(d<p)l=l.then(c[d++],c[d++]);return l}getUri(e){e=tn(this.defaults,e);let t=Wr(e.baseURL,e.url,e.allowAbsoluteUrls);return Gr(t,e.params,e.paramsSerializer)}}S.forEach(["delete","get","head","options"],function(t){Si.prototype[t]=function(n,r){return this.request(tn(r||{},{method:t,url:n,data:(r||{}).data}))}});S.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(tn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Si.prototype[t]=n(),Si.prototype[t+"Form"]=n(!0)});var xi=Si;class mf{constructor(e){if(typeof e!=="function")throw TypeError("executor must be a function.");let t;this.promise=new Promise(function(o){t=o});let n=this;this.promise.then((r)=>{if(!n._listeners)return;let o=n._listeners.length;while(o-- >0)n._listeners[o](r);n._listeners=null}),this.promise.then=(r)=>{let o,s=new Promise((i)=>{n.subscribe(i),o=i}).then(r);return s.cancel=function(){n.unsubscribe(o)},s},e(function(o,s,i){if(n.reason)return;n.reason=new It(o,s,i),t(n.reason)})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}if(this._listeners)this._listeners.push(e);else this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);if(t!==-1)this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=(n)=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new mf(function(r){e=r}),cancel:e}}}var Zv=mf;function hf(e){return function(n){return e.apply(null,n)}}function gf(e){return S.isObject(e)&&e.isAxiosError===!0}var _f={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(_f).forEach(([e,t])=>{_f[t]=e});var Xv=_f;function Jv(e){let t=new xi(e),n=ri(xi.prototype.request,t);return S.extend(n,xi.prototype,t,{allOwnKeys:!0}),S.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Jv(tn(e,o))},n}var We=Jv(Bo);We.Axios=xi;We.CanceledError=It;We.CancelToken=Zv;We.isCancel=fi;We.VERSION=Yr;We.toFormData=lr;We.AxiosError=D;We.Cancel=We.CanceledError;We.all=function(t){return Promise.all(t)};We.spread=hf;We.isAxiosError=gf;We.mergeConfig=tn;We.AxiosHeaders=ke;We.formToJSON=(e)=>pu(S.isHTMLForm(e)?new FormData(e):e);We.getAdapter=Au.getAdapter;We.HttpStatusCode=Xv;We.default=We;var Bn=We;var{Axios:gLe,AxiosError:_Le,CanceledError:yLe,isCancel:ELe,CancelToken:bLe,VERSION:SLe,all:xLe,Cancel:vLe,isAxiosError:CLe,spread:ALe,toFormData:RLe,AxiosHeaders:TLe,HttpStatusCode:wLe,formToJSON:OLe,getAdapter:kLe,mergeConfig:ILe}=Bn;var mK=/^req_[A-Za-z0-9_-]{1,36}$/;function Qv(e){return typeof e==="string"&&mK.test(e)}var hK=/cloudflare/i;function zo(e){let t=e("request-id");if(typeof t==="string"&&Qv(t.trim()))return"origin";let n=e("cf-ray"),r=e("server");if(typeof n==="string"&&n!==""||typeof r==="string"&&hK.test(r))return"nonorigin_cf";return"nonorigin_other"}function wu(e){return e==="nonorigin_cf"||e==="nonorigin_other"}qn();he();re();var $O=/(?<![^\s\p{P}])\p{M}+/gu;bs();it();function M9(e){return Vw(B9(jc(e))).replace(/ {2,}/g," ").trim()}var F9=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/g,U9=4;function B9(e){let t=e;for(let n=0;n<U9;n++){let r=t.replace(F9,"");if(r===t)break;t=r}return t}function Ki(e,t=160){return $9(M9(j9(e,t)).normalize("NFC").replace(/[`\uff40\u02cb\u1fef\u2035]/g,"'").replace($O,""),t)}var H9=new RegExp(`[^\\S ]|[${wn}]`,"u");function jO(e,t){return e.length<=t&&!H9.test(e)&&Ki(e,t)===e.replaceAll("`","'")}function $9(e,t=2000){return e.length>t?`${Tn(e,t)}…`:e}function j9(e,t){let n=Tn(e,t*8);if(n.length===e.length)return n;let r=/\x1b(?:[\]PX^_][^\x1b\x07]*\x1b?|\[[\x30-\x3f]*[\x20-\x2f]*)$/.exec(n);if(r===null)return n;let o=e.slice(r.index);return(o[1]==="["?/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/.test(o):/^\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/.test(o))?n.slice(0,r.index):n}re();$e();function GO(e){return typeof e==="string"&&/^[a-z0-9_]{1,64}$/.test(e)}function Kt(){return"claude-code/0.3.308"}function On(e=process.env.CLAUDE_CODE_ENTRYPOINT){switch(e){case"claude-vscode":return"claude_code_vscode";case"remote":case"remote_baku":case"remote_cowork":case"remote_desktop":case"remote_mobile":case"remote_projects":return"claude_code_remote";case"claude-in-teams":return"claude_code_remote";case"sdk-cli":case"sdk-ts":case"sdk-py":return"claude_code_sdk";case"mcp":return"claude_code_mcp";case"claude-code-github-action":return"claude_code_github_action";case"local-agent":return"claude_code_local_agent";case"claude_in_slack":return"claude_in_slack";case"claude-in-slack":return"claude-in-slack";case"cli":default:return"claude_code_cli"}}Yn();he();re();Jh();$e();var Y9=["session_ingress_token","environment_secret","access_token","secret","token"],KGe=new RegExp(`"(${Y9.join("|")})"\\s*:\\s*"[^"]*"`,"g");function Jc(e){if(!e||typeof e!=="object")return;if("message"in e&&typeof e.message==="string")return e.message;if("error"in e&&e.error!==null&&typeof e.error==="object"&&"message"in e.error&&typeof e.error.message==="string")return e.error.message;return}function zO(e){let t=Jc(e);return t?qi(t,"error_message"):void 0}function qi(e,t){if(jO(e,1024))return e;b(`[error-detail] left the service's text (${t}) out of the error shown: it has ${e.length} UTF-16 units and is not one plain line of at most 1,024 units`),ve("tengu_service_error_detail_not_plain",{length:e.length,source:Me(t)});return}tl();var gxe="2023-06-01";function BN(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","anthropic-version":gxe,"anthropic-client-platform":On(),"User-Agent":Kt()}}function _xe(e){return e!==null&&typeof e==="object"&&"terminal"in e&&e.terminal===!0}function yxe(e){if(e===null||typeof e!=="object"||!("error"in e)||e.error===null||typeof e.error!=="object")return!1;let t=e.error,n="type"in t?t.type:void 0,r="resource_type"in t?t.resource_type:void 0,o="reason"in t?t.reason:void 0;return n==="not_found_error"&&r==="session_grouping"||o==="public_grouping_hosted_only"||o==="feature_disabled"}function HN(e){if(e===401)return"oauth_rejected";if(e===408||e===429||e>=500)return"transient";return"rejected"}async function Exe(e,t,n,r,o,s,i,a,c,l,d){let p=`${e}/v1/code/sessions`,f={cwd:i??Rn(),...a&&{model:a}};if(s&&"gitRepoUrl"in s){await Promise.resolve().then(() => UN());let{sources:g,outcomes:E,report:x}=await FN(s.gitRepoUrl,s.branch,s.defaultBranch);if(x.branchDropped&&x.warnMessage){let v=`${x.branchDropped}:${s.gitRepoUrl}:${s.branch}`;if(!l||l.lastKey!==v){if(l)l.lastKey=v;b(`[code-session] ${x.warnMessage}`)}}else if(l)l.lastKey=null;if(g.length>0||E.length>0)f.sources=g,f.outcomes=E,f.reuse_outcome_branches=!0}let m;try{m=await Bn.post(p,{title:n,bridge:{},...o?.length&&{tags:o},...c&&{session_grouping_id:c},config:f},{headers:BN(t),timeout:r,validateStatus:(_)=>_<500})}catch(_){return b(`[code-session] Session create request failed: ${j(_)}`),null}if(m.status!==200&&m.status!==201){let _=Jc(m.data);b(`[code-session] Session create failed ${m.status}${_?`: ${_}`:""}`);let g=zO(m.data);if(m.status===401)d?.();if(m.status>=400&&m.status<500&&yxe(m.data))return{terminal:!0,reason:"grouping_rejected",status:m.status,detail:g};switch(HN(m.status)){case"oauth_rejected":return{terminal:!1,reason:"oauth_rejected"};case"transient":return null;case"rejected":return{terminal:!0,reason:"request_rejected",status:m.status,detail:g}}}let h=m.data;if(!h||typeof h!=="object"||!("session"in h)||!h.session||typeof h.session!=="object"||!("id"in h.session)||typeof h.session.id!=="string"||!h.session.id.startsWith("cse_")||!ek(h.session.id))return b(`[code-session] No usable session.id (cse_*) in response: ${xe(h).slice(0,200)}`),{terminal:!0,reason:"malformed_response",status:m.status,detail:void 0};return h.session.id}function bxe(e){return e!==null&&"terminal"in e&&e.terminal===!0}function Sxe(e){return typeof e==="object"&&e!==null&&"terminal"in e&&e.terminal===!1}function $N(e){let t=ty(e);if(t!==void 0&&"resource"in t){let n=t.resource;if(n==="untrusted_device"||n==="session_stale_relogin")return n}return}function xxe(e){if($N(e)==="untrusted_device"){let t=ty(e),n=t!==void 0&&"sub_reason"in t?t.sub_reason:void 0;if(n===void 0||n===null||n==="")return{kind:"token_refused"};if(typeof n!=="string")return{kind:"unrecognized",subReason:`(${typeof n}, not a string)`};switch(n){case"bound_unattested":return{kind:"token_refused"};case"served_call_unsigned":return{kind:"signature_wanted",subReason:n};default:if(GO(n))return{kind:"unrecognized",subReason:n};return b(`[code-session] a 403's sub_reason is too long or not snake_case, so a placeholder is passed on. As sent (${n.length} characters; cleaned, first 64): ${Ki(n,64)}`),{kind:"unrecognized",subReason:"(string, too long or not snake_case)"}}}return}function ty(e){return e!==null&&typeof e==="object"&&"error"in e&&e.error!==null&&typeof e.error==="object"?e.error:void 0}function vxe(e,t,n,r,o,s){return Cxe(e,t,n,r,o,s,void 0)}async function Cxe(e,t,n,r,o,s,i){if(!Axe(e,"/bridge"))return{terminal:!0,reason:"invalid_session_id"};let a=`${t}/v1/code/sessions/${e}/bridge`,c=BN(n);if(o)c["X-Trusted-Device-Token"]=o;let l;try{l=await Bn.post(a,i===void 0?{}:{expected_epoch:i.expectedEpoch},{headers:c,timeout:r,validateStatus:(f)=>f<500})}catch(f){return b(`[code-session] /bridge request failed: ${j(f)}`),null}if(l.status!==200){let f=Jc(l.data);if(b(`[code-session] /bridge failed ${l.status}${f?`: ${f}`:""}`),l.status===401)s?.();if(i!==void 0&&l.status===409){let h=ty(l.data),_=i.expectedEpoch,g=[ey(h!==void 0&&"expected_epoch"in h?h.expected_epoch:void 0),ey(h!==void 0&&"actual_epoch"in h?h.actual_epoch:void 0)];i.onRefused(g.includes(_)?g.find((E)=>E!==void 0&&E>_):void 0)}let m;if(l.status===403){let h=$N(l.data);if(h==="untrusted_device"){let _=xxe(l.data);return{terminal:!0,reason:h,..._&&{refusal:_}}}if(h)return{terminal:!0,reason:h};m=zo((_)=>l.headers?.[_]),b(`[code-session] /bridge 403 source=${m}`)}switch(HN(l.status)){case"oauth_rejected":return{terminal:!1,reason:"oauth_rejected"};case"transient":return null;case"rejected":return{terminal:!0,reason:"request_rejected",status:l.status,...m&&{source:m}}}}let d=l.data;if(d===null||typeof d!=="object"||!("worker_jwt"in d)||typeof d.worker_jwt!=="string"||!("expires_in"in d)||typeof d.expires_in!=="number"||!("api_base_url"in d)||typeof d.api_base_url!=="string"||!("worker_epoch"in d))return b(`[code-session] /bridge response malformed (need worker_jwt, expires_in, api_base_url, worker_epoch): ${xe(d).slice(0,200)}`),{terminal:!0,reason:"malformed_response",status:200};let p=ey(d.worker_epoch);if(p===void 0)return b(`[code-session] /bridge worker_epoch invalid: ${xe(d.worker_epoch)}`),{terminal:!0,reason:"malformed_response",status:200};return{worker_jwt:d.worker_jwt,api_base_url:d.api_base_url,expires_in:d.expires_in,worker_epoch:p,mcp_config:Rxe(d),...{}}}function Axe(e,t){try{return el(e,"sessionId"),!0}catch(n){return b(`[code-session] ${t}: ${j(n)}`),!1}}function Rxe(e){if(!("mcp_config"in e))return;let t=e.mcp_config;if(t!==null&&typeof t==="object"&&"content"in t&&typeof t.content==="string"&&t.content.length>0)return{content:t.content};return}function ey(e){let t=typeof e==="string"?Number(e):e;return typeof t==="number"&&Number.isSafeInteger(t)?t:void 0}he();re();import{randomUUID as $a}from"crypto";var ny=["invalid_request","catalog_unknown","not_found","restricted_by_org","unavailable_for_account","not_offered","alias_1m_disabled","alias_1m_unsupported","blocked_by_hook","check_failed","check_rejected","credits_required","rate_limit","auth_failed","model_not_current","verdict_pending","internal_error"],Txe=["invalid_mode","bypass_restricted","bypass_disabled","bypass_not_launched","auto_mode_settings","auto_mode_circuit_breaker","auto_mode_fast_mode","auto_mode_model","auto_mode_unavailable"],wxe=["remote_control_auth","remote_control_terminal","remote_control_ended_elsewhere","remote_control_policy_disabled"];var Oxe=["workspace_diff_pending"],kxe=["stale_worker_epoch","invalid_worker_epoch"],Ixe=["read_denied"],Int=[...ny,...Txe,...wxe,...Oxe,...kxe,...Ixe];he();it();var Pxe=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF]|[\uDC00-\uDFFF]/g;function Dxe(e){return e.replace(Pxe,(t)=>t.length===2?t:"")}var Lxe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}\u2800]|(?!\u0020)\p{Zs}/gu;function wt(e){if(typeof e!=="string")return"";return Tn(Nxe(e.length>4096?e.slice(0,4096):e),1024)}function Nxe(e){if(typeof e!=="string")return"";let t=e;for(let n=0;n<64;n++){let r=Dxe(t).replace(Lxe,"");if(r===t)return r;t=r}return""}re();_t();var GN=8000;async function WN({verdict:e,deadlineMs:t,respond:n,inform:r}){let o=(d)=>{if(Array.isArray(d))r(d.filter((p)=>typeof p==="string").map(wt))},s=e.then((d)=>d??{ok:!0}),i;try{i=await vn(s,t)}catch(d){return b(`set_model verdict rejected: ${j(d)}`,{level:"error"}),n({subtype:"error",error:"set_model failed",error_code:"internal_error"})}if(i===void 0)return s.then((d)=>o(d.ok?[...Array.isArray(d.notices)?d.notices:[],"The pending model switch was applied"]:jN(d.error)),(d)=>{b(`set_model verdict rejected after the deadline reply: ${j(d)}`,{level:"error"}),o(["The pending model switch failed"])}),n({subtype:"error",error:"This model switch is still pending (an earlier model change, a check with the API or a PreModelSwitch hook has not finished); it will apply when that completes unless it is refused",error_code:"verdict_pending"});let a=typeof i.model==="string"?wt(i.model):void 0;if(i.ok){if(i.notices)o(i.notices);return n(a===void 0?{subtype:"success"}:{subtype:"success",response:{model:a}})}let c=i.code,l=ny.find((d)=>d===c);return n({subtype:"error",error:jN(i.error).map(wt).join(`
|
|
78
78
|
`),...l!==void 0&&{error_code:l},...a!==void 0&&{model:a}})}function jN(e){return typeof e==="string"?e.split(`
|
|
79
79
|
`):[""]}var rd={output_tokens_details:{thinking_tokens:0},input_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,output_tokens:0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard",fallback_credit:null};Iu();function zN(e){return e.send_now===!0&&e.cancel_queued!==!0}function KN(e,t){return{type:"control_response",response:{subtype:"success",request_id:e,response:t}}}function qN(e,t,n,r){return{type:"control_response",response:{subtype:"error",request_id:e,error:t,...n!==void 0&&{error_code:n},...r!==void 0&&{model:r}}}}function wa(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function oy(e,t="|"){return e.map((n)=>ay(n)).join(t)}function Oa(e,t){if(typeof t==="bigint")return t.toString();return t}class YN{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function od(e){return new YN(e)}function ZN(e){return e===null||e===void 0}function sd(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function XN(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function hn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function id(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Qn(e){return id(e._zod.def)??e._zod.def.shape}function JN(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return hn(this,t,r),r},enumerable:!0,configurable:!0})}function QN(e,t,n){if(t in e)hn(e,t,n);else e[t]=n}function bo(e,t,n,r){let o=Qn(t);for(let s of n){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)JN(e,s,()=>{let a=t._zod.def.shape[s];return r?r(a,s):a});else QN(e,s,r?r(i.value,s):i.value)}}function Mxe(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)JN(e,n,()=>t[n]);else QN(e,n,r.value)}}function Nt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function eM(e){return JSON.stringify(e)}function tM(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var sy="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ta(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var nM=od(()=>{if(Et.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function So(e){if(Ta(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Ta(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function iy(e){if(So(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var rM=new Set(["string","number","symbol"]);function Lr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function In(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function G(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ay(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function oM(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ad=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),uy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Fxe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s={};return bo(s,e,ud(e,t)),In(e,Nt(n,{shape:s,checks:[]}))}function ud(e,t){let n=Qn(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function Uxe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(ud(e,t)),i={};return bo(i,e,Reflect.ownKeys(Qn(e)).filter((a)=>!s.has(a))),In(e,Nt(n,{shape:i,checks:[]}))}function Bxe(e,t){if(!So(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Qn(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return In(e,Nt(e._zod.def,{shape:sM(e,t)}))}function sM(e,t){let n={};return bo(n,e,Reflect.ownKeys(Qn(e))),Mxe(n,t),n}function Hxe(e,t){if(!So(t))throw Error("Invalid input to safeExtend: expected a plain object");return In(e,Nt(e._zod.def,{shape:sM(e,t)}))}function $xe(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};bo(n,e,Reflect.ownKeys(Qn(e))),bo(n,t,Reflect.ownKeys(Qn(t)));let r=Nt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return In(e,r)}function iM(e,t,n,r="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(ud(t,n)):void 0,c={};return bo(c,t,Reflect.ownKeys(Qn(t)),e&&((l,d)=>a&&!a.has(d)?l:new e({type:"optional",innerType:l}))),In(t,Nt(t._zod.def,{shape:c,checks:[]}))}function jxe(e,t,n){let r=n?new Set(ud(t,n)):void 0,o={};return bo(o,t,Reflect.ownKeys(Qn(t)),(s,i)=>r&&!r.has(i)?s:new e({type:"nonoptional",innerType:s})),In(t,Nt(t._zod.def,{shape:o}))}function Pn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function aM(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function tr(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ra(e){return typeof e==="string"?e:e?.message}function cy(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function Dn(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Ra(e.inst?._zod.def?.error?.(e))??Ra(s?.(e))??Ra(t?.error?.(e))??Ra(n.customError?.(e))??Ra(n.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}var Gxe=/[\uD800-\uDBFF]/;function cd(e){let t=e.length;if(!Gxe.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function ld(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function uM(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function xo(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function cM(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else VN(e,n,r.value)}for(let n of Object.getOwnPropertySymbols(t))VN(e,n,t[n])}function er(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ly(e,t,n){return er(e,t,n,!1)}function lM(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return er(this,n,r(this))},set(o){er(this,n,o)}})}return t}function VN(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:er(this,t,n.bind(this))},set(r){er(this,t,r)}})}function Wxe(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var ry,Dr=!1,zxe={configurable:!0,get(){Dr=!0;return}};function ye(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&ry!==e._zod){ry=void 0;return}ry=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,zxe);let o=Dr;Dr=!1;try{let s=n(this);if(Dr)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return Dr=Dr||o,s}catch(s){throw delete this[t],Dr=Dr||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Kxe(e,t,n,r){let o=Wxe(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:s})}})}var qxe="~constantCatch";function dM(e){let t=()=>e;return t[qxe]=!0,t}var pM;var dy={value:void 0,enumerable:!1},fM="captureStackTrace"in Error?Error:null;function Vxe(e){let t=fM;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return fM=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,r){let o={};function s(f){this.def=f,this.constr=p,this.traits=new Set}s.prototype=o;let i=n,a=i&&new WeakSet;function c(f,m){if(!f._zod){dy.value=new s(m);try{Object.defineProperty(f,"_zod",dy)}finally{dy.value=void 0}}if(f._zod.traits.has(e))return;if(f._zod.traits.add(e),t(f,m),a){let _=Object.getPrototypeOf(f),g=f._zod.constr.prototype,E=_;while(E&&E!==g)E=Object.getPrototypeOf(E);let x=E??_;if(!a.has(x))a.add(x),cM(x,i)}let h=p.prototype;for(let _ in h){if(!Object.prototype.hasOwnProperty.call(h,_))continue;if(!(_ in f))f[_]=h[_].bind(f)}}let l=r?.Parent??Object;class d extends l{}Object.defineProperty(d,"name",{value:e});function p(f){let m=r?.Parent?Vxe(d):this;c(m,f);let h=m._zod.deferred;if(h){for(let g of h)g();m._zod.deferred=void 0}let _=globalThis.__zod_globalConfig?.postProcessor;if(_)_(m);return m}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:(f)=>{if(r?.Parent&&f instanceof r.Parent)return!0;return f?._zod?.traits?.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class Ln extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ka extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(pM=globalThis).__zod_globalConfig??(pM.__zod_globalConfig={});var Et=globalThis.__zod_globalConfig;function Mt(e){if(e)Object.assign(Et,e);return Et}function Yxe(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Oa,2)),e.message}function Zxe(e){this._zod.message=e}var Xxe={get:Yxe,set:Zxe,enumerable:!0,configurable:!0},fy={value:void 0,enumerable:!1},mM=new WeakSet([Object.prototype,Error.prototype]),hM=(e,t)=>{e.name="$ZodError",fy.value=t,Object.defineProperty(e,"issues",fy),fy.value=void 0,Object.defineProperty(e,"message",Xxe);let n=Object.getPrototypeOf(e);if(!mM.has(n))mM.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},gM=w("$ZodError",hM),Vnt=w("$ZodError",hM,void 0,{Parent:Error});function Jxe(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function _M(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)Jxe(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function yM(e,t=(n)=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(t(i));else{let c=n,l=0;while(l<a.length){let d=a[l],p=l===a.length-1;if(d==="_errors"){if(p)c._errors.push(t(i));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,d))Object.defineProperty(c,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=c[d];if(p)f._errors.push(t(i));c=f,l++}}}};return r(e),n}function dd(e,t){return{callee:t?.callee??e,Err:t?.Err}}var pd=(e)=>{let t=(n,r,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new Ln;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Dn(l,i,Mt())));throw sy(c,s?.callee??t),c}return a.value};return t};var fd=(e)=>{let t=async(n,r,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Dn(l,i,Mt())));throw sy(c,s?.callee??t),c}return a.value};return t};var md=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ln;return s.issues.length?EM(e,s.issues,o):{success:!0,data:s.value}};function EM(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>Dn(o,n,Mt()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}var hd=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?EM(e,s.issues,o):{success:!0,data:s.value}};var Qxe=Symbol.for("zod.compile.invalid"),eve=Symbol.for("zod.compile.fallback"),my=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Qxe)return!0;if(r.definite===!0&&n===void 0)return!1}return tve(e,t,n)};function tve(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)r[eve]=!0,s=o({value:t,issues:[]},r);else s=e._zod.run({value:t,issues:[]},r);if(s instanceof Promise)throw new Ln;return s.issues.length===0}var hy=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},bM=(e)=>{let t=pd(e),n=(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(r,o,a,dd(n,i))};return n};var SM=(e)=>{let t=pd(e),n=(r,o,s,i)=>t(r,o,s,dd(n,i));return n};var xM=(e)=>{let t=fd(e),n=async(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(r,o,a,dd(n,i))};return n};var vM=(e)=>{let t=fd(e),n=async(r,o,s,i)=>await t(r,o,s,dd(n,i));return n};var CM=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return md(e)(t,n,o)};var AM=(e)=>(t,n,r)=>md(e)(t,n,r);var RM=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return hd(e)(t,n,o)};var TM=(e)=>async(t,n,r)=>hd(e)(t,n,r);var wM=/^[cC][0-9a-z]{6,}$/,OM=/^[0-9a-z]+$/,kM=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,IM=/^[0-9a-vA-V]{20}$/,PM=/^[A-Za-z0-9]{27}$/,DM=/^[a-zA-Z0-9_-]{21}$/;function LM(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var NM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var MM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_y=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var FM=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var nve="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function UM(){return new RegExp(nve,"u")}var BM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,HM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var $M=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,jM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,GM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WM=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var zM=/^https?$/,KM=/^\+[1-9]\d{6,14}$/;var qM="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function rve(e){return new RegExp(`^${e}$`)}var VM=rve(qM);function gy(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function YM(e){return new RegExp(`^${gy(e)}$`)}function ZM(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${gy({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${gy({precision:e.precision})}`:n;return new RegExp(`^${qM}T(?:${r})$`)}var XM=/^[\s\S]{0,}$/;var yy=/^-?\d+$/,Ia=/^-?\d+(?:\.\d+)?$/,JM=/^(?:true|false)$/i;var QM=/^[^A-Z]*$/,e1=/^[^a-z]*$/;var et=w("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var Ey=(e)=>{let t=e.value;return!ZN(t)&&t.length!==void 0},gd={number:"number",bigint:"bigint",object:"date"},by=w("$ZodCheckLessThan",(e,t)=>{et.init(e,t);let n=gd[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:gd[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Sy=w("$ZodCheckGreaterThan",(e,t)=>{et.init(e,t);let n=gd[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:gd[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),t1=w("$ZodCheckMultipleOf",(e,t)=>{et.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):XN(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),n1=w("$ZodCheckNumberFormat",(e,t)=>{et.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=ad[t.format];e._zod.check=(i)=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<o)i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var r1=w("$ZodCheckMaxLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=Ey),e._zod.check=(r)=>{let o=r.value,s=o.length;if((typeof o==="string"&&s>t.maximum?cd(o):s)<=t.maximum)return;let a=ld(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),o1=w("$ZodCheckMinLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=Ey),e._zod.check=(r)=>{let o=r.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?cd(o):s)>=t.minimum)return;let a=ld(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),s1=w("$ZodCheckLengthEquals",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=Ey),e._zod.check=(r)=>{let o=r.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?cd(o):s;if(i===t.length)return;let a=ld(o),c=i>t.length;r.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Da=w("$ZodCheckStringFormat",(e,t)=>{var n,r;if(et.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),i1=w("$ZodCheckRegex",(e,t)=>{Da.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),a1=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=QM),Da.init(e,t)}),u1=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=e1),Da.init(e,t)}),c1=w("$ZodCheckIncludes",(e,t)=>{et.init(e,t);let n=Lr(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),l1=w("$ZodCheckStartsWith",(e,t)=>{et.init(e,t);let n=new RegExp(`^${Lr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),d1=w("$ZodCheckEndsWith",(e,t)=>{et.init(e,t);let n=new RegExp(`.*${Lr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var p1=w("$ZodCheckOverwrite",(e,t)=>{et.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class xy{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
80
80
|
`).filter((s)=>s),r=Math.min(...n.map((s)=>s.length-s.trimStart().length)),o=n.map((s)=>s.slice(r)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
package/browser-sdk.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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
2
|
|
|
3
|
-
// Version: 0.3.
|
|
3
|
+
// Version: 0.3.308
|
|
4
4
|
|
|
5
5
|
// symbol-dispose-prelude: bun build --banner for every SDK bundle; the build
|
|
6
6
|
// scripts grep for this line's tag. Runs before any module body. bun lowers
|
|
@@ -35,7 +35,7 @@ var oL=Object.create;var{getPrototypeOf:iL,defineProperty:jm,getOwnPropertyNames
|
|
|
35
35
|
`;if(this.toStderr){this.deps.writeToStderr(r);return}this.write(r)}write(e){let t=this.getWriter(),n=B4;if(this.storageV5!==void 0){if(n={sessionId:this.deps.sessionId(),fromBackend:Sh.getStore()===!0},n.fromBackend)this.backendLinesLogged++}if(t.write({origin:n,content:e}),this.exiting)t.flush()}async flush(){let e=this.backendLinesLogged;if(this.writer?.flush(),await this.drained(),this.storageV5!==void 0&&this.successor)return this.successor.flush();for(let t=0;this.backendLinesLogged!==e&&t<3;t++)e=this.backendLinesLogged,this.writer?.flush(),await this.drained();if(this.backlog.droppedCount>0&&this.backlog.length===0&&!this.successor)this.write(""),this.writer?.flush(),await this.drained()}async drained(){if(this.isAppendStuck())return;let e=this.backlog.chain.then(()=>!0);do if(await ol(e,FR))return;while(!this.isAppendStuck())}isAppendStuck(){let e=this.backlog,{appendSince:t}=e;if(e.stuck==="no"&&t!==0&&Date.now()-t>=j4)e.stuck="suspected",setTimeout(q4,FR,e,t).unref();return e.stuck==="yes"}dispose(e){this.redirect=e;try{this.writer?.dispose()}finally{this.redirect=null,this.writer=null}}succeed(e){this.runtimeDebugEnabled=e.runtimeDebugEnabled,this.hasFormattedOutput=e.hasFormattedOutput,this.unflushedChunks=e.unflushedChunks,this.backlog=e.backlog,this.exitHandlerRegistered=e.exitHandlerRegistered,e.successor=this,e.dispose((t)=>{this.write(t)})}handleExit(){if(this.successor){this.successor.handleExit();return}if(this.exiting=!0,this.backlog.droppedCount>0)try{this.write("")}catch{}this.writer?.flush(),this.drainSync()}async maybeRotate(e,t,n=L4){let o=Wn()&&this.storageV5!==void 0?this.storageV5.hostFiles:void 0;if(this.writtenBytes<0)if(o){let r=await o.stat(Hh(e));this.writtenBytes=r.ok&&r.value.kind!=="absent"?r.value.size:0}else this.writtenBytes=await D4(e).then((r)=>r.size).catch(()=>0);else this.writtenBytes+=t;if(this.writtenBytes<=n||this.rotating)return;this.rotating=!0;try{let r=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;if(o){let i=Hh(e),s=Hh(r),a=await o.rename(i,s);if(!a.ok&&!V4(a.error)){if(await o.delete(s,{missingOk:!0}),!(await o.rename(i,s)).ok)await o.delete(i,{missingOk:!0})}}else try{await UR(e,r)}catch(i){if(!El(i))await Kh(r).catch(()=>{}),await UR(e,r).catch(()=>Kh(e).catch(()=>{}))}this.writtenBytes=0}finally{this.rotating=!1}}shouldLog(e){if(this.deps.isTestEnvironment&&!this.toStderr&&this.filePath===null)return!1;if(!this.deps.isAnt&&!this.isDebugMode())return!1;if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;return GT(e,this.filter)}resolveDirToFile(e){return this.resolvedLogPath=mt(e,`${this.deps.sessionId()}.txt`),this.resolvedLogPath}async appendGroup(e,t,n,o){if(this.storageV5!==void 0&&e.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,n);return}if(e.target===null||!this.writesFiles())return;if(o)await zR(bt(e.target),{recursive:!0}).catch(()=>{});let r=e;try{await Fh(e.target,n)}catch(i){if(!Wg(i))throw i;if(this.storageV5===void 0)r={...e,target:this.resolveDirToFile(e.target)},await Fh(r.target,n);else{if(this.overrideDirectory=e.target,r=qR(t,e.configHome,e.target,e.target),r.arm==="v5"){await this.appendV5AndMark(this.storageV5,t,n);return}await zR(bt(r.target),{recursive:!0}).catch(()=>{});try{await Fh(r.target,n)}catch{return}}}if(r.rotate){if(this.storageV5!==void 0&&r.target!==this.rotationTarget)this.rotationTarget=r.target,this.writtenBytes=-1;await this.maybeRotate(r.target,Buffer.byteLength(n)).catch(HR)}if(r.pointLatest)this.markLatestSymlink()}async appendV5AndMark(e,t,n){let o=Wn(),r=o&&!this.latestMarked&&!this.latestRefused,i=await BR(e,t.sessionId,n,r);if(i==="refused")this.latestRefused=!0,i=await BR(e,t.sessionId,n,!1),this.log("debug log: the storage backend refused markLatest; <debug folder>/latest is not pointed in this process",{level:"warn"});if(i!=="landed")return;if(r&&!this.latestRefused)this.latestMarked=!0;else if(!o)this.markLatestSymlink()}markLatestSymlink(){if(!this.latestMarked&&this.writesFiles())this.latestMarked=!0,this.updateLatestSymlink()}isSessionDiskless(){try{return this.deps.diskless?.()===!0}catch{return!0}}writesFiles(){if(this.isSessionDiskless())return!1;try{return this.deps.defaultFile?.()!==!1||this.filePath!==null||this.deps.env.CLAUDE_CODE_DEBUG_LOGS_DIR!==void 0}catch{return!1}}async appendOldestChunks(){let e=this.backlog,t=this.unflushedChunks[0],n=t?.queued;if(n===void 0)return;let o=0,r=0,i=!1;for(let{content:s,queued:a}of this.unflushedChunks){if(a===void 0||a.owner!==n.owner||a.decision.arm!==n.decision.arm||a.decision.target!==n.decision.target||a.origin.sessionId!==n.origin.sessionId||a.origin.fromBackend!==n.origin.fromBackend||o>0&&r+s.length>U4)break;o++,r+=s.length,i||=a.needMkdir}if(e.appendSince=Date.now(),await n.owner.appendGroup(n.decision,n.origin,this.unflushedChunks.slice(0,o).map((s)=>s.content).join(""),i).catch(HR),e.appendSince=0,e.stuck="no",this.unflushedChunks[0]===t)this.unflushedChunks.splice(0,o),e.length-=r}drainSync(){if(this.unflushedChunks.length===0)return;if(this.backlog.length=0,!this.drainsSyncAtExit()||!this.writesFiles()||this.isAppendStuck()){this.unflushedChunks.length=0;return}let e=[];for(let t of this.unflushedChunks.splice(0)){if(t.target===null)continue;let n=e.at(-1);if(n!==void 0&&n.armed===t.armed&&(!t.armed||n.target===t.target))n.parts.push(t);else e.push({target:t.target,armed:t.armed,parts:[t]})}for(let{target:t,armed:n,parts:o}of e){let r=n?t:this.logPath(),i=o.map((s)=>s.content).join("");try{Ws().mkdirSync(bt(r))}catch{}try{Ws().appendFileSync(r,i)}catch(s){if(Wg(s))try{if(!n)Ws().appendFileSync(this.resolveDirToFile(r),i);else{let a=(c,d)=>{try{Ws().appendFileSync(mt(r,`${c}.txt`),d)}catch{}},u=o[0]?.sessionId,l="";for(let c of o){if(c.sessionId!==u)a(u,l),u=c.sessionId,l="";l+=c.content}a(u,l)}}catch{}}}}droppedLineTotal(){return this.backlog.droppedTotal}takeDroppedNote(){let{droppedCount:e}=this.backlog;if(e===0)return"";return this.backlog.droppedCount=0,`${new Date().toISOString()} [WARN] debug messages not logged: ${e} since the line above, because writes to this log were over 10 s behind, with over 1 MiB waiting
|
|
36
36
|
`}groupLines(e){let t=e[0];if(t===void 0)return[];let n=this.filePath??this.deps.env.CLAUDE_CODE_DEBUG_LOGS_DIR??null,o=this.isSessionDiskless();if(o&&(this.storageV5===void 0||n!==null))return[];if(this.storageV5===void 0)return[{decision:{target:this.logPath(),arm:"raw",configHome:"",rotate:!0,pointLatest:!0},origin:t.origin,lines:e}];let r=[];for(let i of e){if(o&&i.origin.fromBackend)continue;let s=r.at(-1);if(s!==void 0&&s.origin.sessionId===i.origin.sessionId&&s.origin.fromBackend===i.origin.fromBackend)s.lines.push(i);else r.push({decision:o?H4:qR(i.origin,this.deps.configHomeDir(),n,this.overrideDirectory),origin:i.origin,lines:[i]})}return r}getWriter(){if(this.writer)return this.writer;let e=null,t=this.storageV5!==void 0;if(this.writer=HT({writeBatch:(n)=>{if(this.redirect){this.redirect(n.map((i)=>i.content).join(""));return}if(this.exiting){for(let i of this.groupLines(n))this.unflushedChunks.push({target:i.decision.target,sessionId:i.origin.sessionId,armed:t,content:this.takeDroppedNote()+i.lines.map((s)=>s.content).join("")});this.drainSync();return}let o=this.writesFiles(),r=this.backlog;this.isAppendStuck();for(let i of this.groupLines(n)){if(i.decision.arm==="raw"&&!o)continue;if(r.droppedCount>0?r.length>=jR/2:r.length>=jR&&Date.now()-(this.unflushedChunks[0]?.queued?.at??1/0)>=z4){r.droppedCount+=i.lines.length,r.droppedTotal+=i.lines.length;continue}let s=this.takeDroppedNote()+i.lines.map((l)=>l.content).join("");if(s==="")continue;let a=i.decision.arm==="raw"?bt(i.decision.target):null,u=a!==null&&(i.origin.fromBackend||e!==a);if(a!==null)e=a;this.unflushedChunks.push({target:i.decision.target,sessionId:i.origin.sessionId,armed:t,content:s,queued:{at:Date.now(),owner:this,decision:i.decision,origin:i.origin,needMkdir:u}}),r.length+=s.length,r.chain=F4(()=>r.chain.then(this.appendOldest))}},sizeOf:(n)=>n.content.length,flushIntervalMs:1000,maxBufferSize:100,immediateMode:this.isDebugMode()}),this.deps.registerCleanup(async()=>{this.writer?.dispose(),await this.drained()}),!this.exitHandlerRegistered)this.exitHandlerRegistered=!0,this.deps.onExit(this.handleExit.bind(this));return this.writer}async updateLatestSymlink(){try{let e=this.logPath(),t=mt(bt(e),"latest");await Kh(t).catch(()=>{}),await M4(e,t)}catch{}}}class ZR{instance=void 0;init={};defaultFile=!0;limits=void 0;setInstance(e){this.instance=e}setInit(e){this.init=e}disableDefaultFile(){this.defaultFile=!1}setLimits(e){this.limits=e}}var W4=new kt(()=>new ZR);function G4(){return ii(W4)}function J4(e,t){return new VR({argv:process.argv,env:process.env,sessionId:()=>jT(),configHomeDir:()=>wh(),onExit:(n)=>{process.on("exit",n)},registerCleanup:(n)=>{BT(n)},writeToStderr:(n)=>{nR(n,{mayDrop:!0})},isAnt:t?.isAnt??!1,isTestEnvironment:t?.isTestEnvironment??!1,launchIdentity:t,storageV5:e.init.storageV5!==void 0&&e.init.configHome===JT()?e.init.storageV5:void 0,syncExitDrain:e.init.syncExitDrain,diskless:()=>yh(),defaultFile:()=>e.defaultFile,limits:()=>e.limits})}function X4(){let e=G4(),t=e.instance;if(t)return t;let n=J4(e);return e.setInstance(n),n}function _e(e,t={level:"debug"}){X4().log(e,t)}var Lue=(()=>{let e=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(e!==void 0){let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t}return 1/0})();var Y4={[Symbol.dispose](){}};function Q4(){return Y4}var gt=Q4;function lt(e,t,n){let r=[];try{const o=at(r,gt`JSON.stringify(${WR(e)})`,0);return JSON.stringify(e,t,n)}catch(i){var s=i,a=1}finally{ut(r,s,a)}}var pn=(e,t)=>{let o=[];try{const n=at(o,gt`JSON.parse(${WR(e)})`,0);return typeof t>"u"?JSON.parse(e):JSON.parse(e,t)}catch(r){var i=r,s=1}finally{ut(o,i,s)}};function WR(e){return typeof e==="string"?e.length:e}class ho{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}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((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}dropNewestQueued(e){let t=this.queue.findLastIndex(e);if(t!==-1)this.queue.splice(t,1)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var Bh="startup_mark";var GR=64;var eK=1000;function tK(){return{eventQueue:[],sink:null,droppedEventCount:0}}function nK(e,t){if(e.eventQueue.length>=eK)e.eventQueue.shift(),e.droppedEventCount++;e.eventQueue.push(t)}class JR{state=tK()}var rK=new kt(()=>new JR);function oK(){return ii(rK)}function li(e,t){let n=oK().state;if(n.sink===null){nK(n,{eventName:e,metadata:t,async:!1});return}n.sink.logEvent(e,t)}function Vh(e,t){li("tengu_feature_ok",{...t,feature_name:ni(e)})}function iK(e,t,n){li("tengu_feature_bad",{...n,feature_name:ni(e),error_code:Zg(t)})}function ql(e,t,n){li("tengu_feature_sad",{...n,feature_name:ni(e),error_code:Zg(t)})}async function ht(e,t,n){try{let o=await t();return Vh(e),o}catch(o){throw iK(e,n?.(o)??"error"),o}}function yo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function XR(e){return"method"in e&&"id"in e&&e.id!==null}var YR=Object.freeze({}),QR=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),Yue=Symbol("swallow");class Zh{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var e$=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var t$="2025-11-25";var sK="notifications/tools/list_changed";function n$(e){return yo(e)&&!("id"in e)&&e.method===sK}function Bl(e){return typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0}var aK={always_allow:!0,always_ask:!0,always_deny:!0};function uK(e){return typeof e==="string"&&Object.hasOwn(aK,e)}function r$(e){if(!yo(e)||typeof e.name!=="string")return;let{name:t,permission_policy:n}=e;if(n===void 0)return{policy:{name:t},rewritten:!1};return uK(n)?{policy:{name:t,permission_policy:n},rewritten:!1}:{policy:{name:t,permission_policy:"always_ask"},rewritten:!0}}function o$(e,t){if(e===void 0||t===void 0)return e===t;return e.length===t.length&&e.every((n,o)=>n.name===t[o]?.name&&n.permission_policy===t[o]?.permission_policy)}function Wh(e){if(!yo(e))return{settings:{},ignored:[]};let{timeout:t,disableAutoBackground:n,tools:o}=e,r=Bl(t),i=[];if(t!==void 0&&r===void 0)i.push("timeout");if(n!==void 0&&typeof n!=="boolean")i.push("disableAutoBackground");let s=lK(o);if(Gh(e)!==void 0)i.push("tools");return{settings:{...r!==void 0&&{timeout:r},...n===!0&&{disableAutoBackground:n},...s!==void 0&&{tools:s}},ignored:i}}function Gh(e){let t=yo(e)?e.tools:void 0;if(t===void 0)return;if(!Array.isArray(t))return{kind:"not_a_list"};let n=0,o=0;for(let r of t){let i=r$(r);if(i===void 0)n++;else if(i.rewritten)o++}return n+o>0?{kind:"entries",dropped:n,rewritten:o,kept:t.length-n}:void 0}function i$(e){if(e.kind==="not_a_list")return"tools[] is not a list; no per-tool policy taken";let t=[];if(e.dropped>0)t.push(`dropped ${e.dropped} malformed tools[] ${e.dropped===1?"entry":"entries"}`);if(e.rewritten>0)t.push(`read ${e.rewritten} tools[] ${e.rewritten===1?"entry":"entries"} with an invalid permission_policy as always_ask`);return`${t.join(", ")}; kept ${e.kept}`}function lK(e){if(!Array.isArray(e))return;let t=[];for(let n of e){let o=r$(n);if(o!==void 0)t.push(o.policy)}return t}var s$=250,Vl="sdk-manifest-capture:",ci=Symbol("suppressControlResponse");function a$(e,t,n){for(let o of n){let r=o==="tools"?Gh(t):void 0;_e(r?`[Query] MCP server '${e}': ${i$(r)}`:`[Query] MCP server '${e}': ignoring malformed ${o} in its config`)}}class Zl{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 ho;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(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let n={type:"system",subtype:"mirror_error",error:t,key:e,uuid:Go(),session_id:e.sessionId};this.inputStream.enqueue(n)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}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(e,t,n,o,r,i=new Map,s,a,u,l,c,d,p=!1,f=Tw){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=n;this.hooks=o;this.abortController=r;this.jsonSchema=s;this.initConfig=a;this.onElicitation=u;this.getOAuthToken=l;this.getHostAuthToken=c;this.onUserDialog=d;this.verbatimPrompts=p;this.runEndCeilingMs=f;for(let[m,g]of i)this.connectSdkMcpServer(m,g);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((m)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,m()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{})}setError(e){this.inputStream.error(e)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((t)=>t.type==="system"&&t.subtype==="hook_progress"&&t.hook_id===e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let t of this.cleanupCallbacks)try{t()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let t of this.cancelControllers.values())t.abort();this.cancelControllers.clear(),this.transport.close()}catch(t){_e(`[Query.cleanup] transport.close() failed: ${mr(t)}`,{level:"error"})}try{let t=e??Jh();for(let{reject:n}of this.pendingControlResponses.values())n(t);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:n}of this.pendingMcpResponses.values())n(t);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:n}of this.sdkMcpServers.values())n.close().catch(()=>{});if(this.sdkMcpServers.clear(),e)this.inputStream.error(e);else this.inputStream.done()}catch(t){}if(this.transport.waitForExit){let t=new AbortController;try{await Promise.race([this.transport.waitForExit(),Zo(2000,t.signal)])}catch{}finally{t.abort()}}}next(...[e]){return this.sdkMessages.next(...[e])}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let t=this.pendingControlResponses.get(e.response.request_id);if(t)t.handler(e.response);else{if(this.unmatchedControlResponses.size>=Zl.UNMATCHED_CONTROL_RESPONSES_MAX){let n=this.unmatchedControlResponses.keys().next().value;if(n!==void 0)this.unmatchedControlResponses.delete(n)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive"){if(Bh in e){let t=e[Bh];if(typeof t==="string"&&t.length<=GR)this.startupMark={mark:t,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=e.is_error?e.subtype==="success"?e.result:e.errors.map((n)=>n.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.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(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else{if(this.lastErrorResultText=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(e)}catch(t){_e(`[Query.readMessages] The frame observer threw: ${mr(t)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(t!==void 0&&!(e instanceof ln)&&e?.name!=="SSEHttpError"){let n=Vg(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});_e(`[Query.readMessages] Replacing exit error with result text. Original: ${mr(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){_e(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){_e(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let t=new AbortController;this.cancelControllers.set(e.request_id,t);try{let n;try{let o=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(o===ci)return;let r={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:o}};n=lt(r)+`
|
|
37
37
|
`}catch(o){if(this.cleanupPerformed)return;let r={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:mr(o)}};n=lt(r)+`
|
|
38
|
-
`}try{await Promise.resolve(this.transport.write(n))}catch(o){_e(`[Query.handleControlRequest] Response write failed: ${mr(o)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(e$.some((n)=>n===e.request.subtype))return _e(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),ci;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,o=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(o===null)return ci;return{...o,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let n=e.request,o=this.sdkMcpServers.get(n.server_name)?.transport;if(!o)throw Error(`SDK MCP server not found: ${n.server_name}`);if(XR(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,o)};else{if(o.onmessage)o.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(o===null)return ci;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(n===null)return ci;return n}return _e(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),li("tengu_request_user_dialog_response_ignored",{shape:ni("auto_cancel")}),ci}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,o=await this.getOAuthToken({signal:t,onDecline:(r)=>{if(Cw(r))n=r}})??null;return o===null&&n!==void 0?{accessToken:o,reason:n}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!u$(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,n;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let s of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,s)?t[s]:void 0;if(a?.toolsListResult!==void 0)t[s]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let i=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{n=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let r=(await n).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&r.plugins_applied!==!0)_e(`[Query.initialize] Claude Code reported plugins_applied=${String(r.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 r}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[i,s]of Object.entries(this.hooks))if(s.length>0)this.initHooksPayload[i]=s.map((a)=>{let u=[];for(let l of a.hooks){let c=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(c,l),u.push(c)}return{matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:o,sdkMcpServerManifests:e,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 e=performance.now(),t=new Map,n=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,n)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"initialize",method:"initialize",params:{protocolVersion:t$,capabilities:YR,clientInfo:{...QR,version:"0.3.307"}}}},p);if(n)return;if(!("result"in f)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${lt(f)}`,{level:"warn"});return}let m=f.result;p.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let g=m.capabilities,h=typeof g==="object"&&g!==null&&"tools"in g&&g.tools!==void 0&&g.tools!==null,v;if(h){let P=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"tools-list",method:"tools/list"}},p);if(n)return;if(!("result"in P)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${lt(P)}`,{level:"warn"});return}if(P.result.nextCursor===void 0)v=P.result}let b=pn(lt(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:b})}catch(f){if(!n)_e(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},r=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(r).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await ol(Promise.race([i,s]),s$);n=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:r.length,captured:t.size,elapsed_ms:u};if(a==="closed"){ql("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)_e(`[Query.captureSdkMcpServerManifests] ${t.size}/${r.length} in-process MCP servers captured within ${s$} ms; the rest will handshake over the control channel`,{level:"warn"}),ql("sdk_mcp_manifest_capture","deadline",l);else if(t.size<r.length)ql("sdk_mcp_manifest_capture","partial",l);else Vh("sdk_mcp_manifest_capture",l);if(t.size===0)return;let c=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([d,p])=>{let f=t.get(d);return f!==void 0&&f.transport===p.transport?[[d,f.manifest]]:[]}));if(Object.keys(c).length===0)return;return _e(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(c).join(", ")}] captured in ${u} ms`),c}async interrupt(e){return ht("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let o=t.response?.cancelled;return{still_queued:n.filter((r)=>typeof r==="string"),...Array.isArray(o)&&{cancelled:o.filter((r)=>typeof r==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,...u}=i;t(u)}else n(new $l(i.error,"awaitControlResponse: CLI error verdict"));if(i.pending_permission_requests||i.pending_user_dialog_requests)_e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Jh());return}let r=this.unmatchedControlResponses.get(e);if(r){this.unmatchedControlResponses.delete(e),o(r);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:n})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return ht("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return ht("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return ht("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return ht("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=ht("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return n;let r=o.initialize,i=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied,code_running_mcp_tools_applied:l.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),s=r.hooks_applied??i.hooks_applied,a=r.plugins_applied??i.plugins_applied,u=r.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...r,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{code_running_mcp_tools_applied:u}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let o=++this.remoteControlCallGeneration,r=this.workSecretAnswerer,i=n?.reattachSessionId||(n?.workSecret===void 0?void 0:dK(n.workSecret)),s=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:n.refreshWorkSecret}:void 0;this.workSecretAnswerer=s;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.workSecret})).response}catch(u){if(o===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw u}if(e&&o===this.remoteControlCallGeneration){let u=a.bridge_session_id,l=[s,r];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&u$(c.sessionId,u)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return ht("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return ht("sdk_side_question",async()=>{let o=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return o.response===null?null:{response:o.response,synthetic:o.synthetic??!1,...o.refusal_fallback&&{refusalFallback:{originalModel:o.refusal_fallback.original_model,fallbackModel:o.refusal_fallback.fallback_model,content:o.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(ri(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Jh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let r={request_id:o,type:"control_request",request:e},i=e.subtype==="initialize";return new Promise((s,a)=>{let u,l=!1,c=(m)=>{this.pendingControlResponses.delete(o),u?.(),s(m)},d=(m)=>{this.pendingControlResponses.delete(o),u?.(),a(m)};if(n){let m=()=>{if(d(ri(n.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(lt({type:"control_cancel_request",request_id:o})+`
|
|
38
|
+
`}try{await Promise.resolve(this.transport.write(n))}catch(o){_e(`[Query.handleControlRequest] Response write failed: ${mr(o)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(e$.some((n)=>n===e.request.subtype))return _e(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),ci;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,o=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(o===null)return ci;return{...o,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let n=e.request,o=this.sdkMcpServers.get(n.server_name)?.transport;if(!o)throw Error(`SDK MCP server not found: ${n.server_name}`);if(XR(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,o)};else{if(o.onmessage)o.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let o=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(o===null)return ci;return o}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(n===null)return ci;return n}return _e(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),li("tengu_request_user_dialog_response_ignored",{shape:ni("auto_cancel")}),ci}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,o=await this.getOAuthToken({signal:t,onDecline:(r)=>{if(Cw(r))n=r}})??null;return o===null&&n!==void 0?{accessToken:o,reason:n}:{accessToken:o}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!u$(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...o}=e.request;return this.uiHost.copy(o,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...o}=e.request;return this.uiHost.promptRead(o,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...o}=e.request;return this.uiHost.promptFill(o,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...o}=e.request;return this.uiHost.promptSuggest(o,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...o}=e.request;return this.uiHost.readSelection(o,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,n;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let s of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,s)?t[s]:void 0;if(a?.toolsListResult!==void 0)t[s]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let i=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{n=this.request(i)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let r=(await n).response;if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&r.plugins_applied!==!0)_e(`[Query.initialize] Claude Code reported plugins_applied=${String(r.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 r}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[i,s]of Object.entries(this.hooks))if(s.length>0)this.initHooksPayload[i]=s.map((a)=>{let u=[];for(let l of a.hooks){let c=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(c,l),u.push(c)}return{matcher:a.matcher,hookCallbackIds:u,timeout:a.timeout}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([i,{settings:s}])=>Object.keys(s).length>0?[[i,s]]:[]),o=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:o,sdkMcpServerManifests:e,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 e=performance.now(),t=new Map,n=!1,o=async(d,p)=>{try{if(await this.sdkMcpServers.get(d)?.connection,n)return;let f=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"initialize",method:"initialize",params:{protocolVersion:t$,capabilities:YR,clientInfo:{...QR,version:"0.3.308"}}}},p);if(n)return;if(!("result"in f)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered initialize with an error; leaving it to the CLI: ${lt(f)}`,{level:"warn"});return}let m=f.result;p.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let g=m.capabilities,h=typeof g==="object"&&g!==null&&"tools"in g&&g.tools!==void 0&&g.tools!==null,v;if(h){let P=await this.handleMcpControlRequest(d,{server_name:d,message:{jsonrpc:"2.0",id:Vl+"tools-list",method:"tools/list"}},p);if(n)return;if(!("result"in P)){_e(`[Query.captureSdkMcpServerManifests] '${d}' answered tools/list with an error; leaving it to the CLI: ${lt(P)}`,{level:"warn"});return}if(P.result.nextCursor===void 0)v=P.result}let b=pn(lt(v===void 0?{initializeResult:m}:{initializeResult:m,toolsListResult:v}));t.set(d,{transport:p,manifest:b})}catch(f){if(!n)_e(`[Query.captureSdkMcpServerManifests] '${d}': ${f}; the CLI will handshake it over the control channel`,{level:"warn"})}},r=Array.from(this.sdkMcpServers,([d,{transport:p}])=>o(d,p)),i=Promise.all(r).then(()=>"settled"),s=new Promise((d)=>{this.stopSdkMcpManifestCapture=()=>d("closed")}),a=await ol(Promise.race([i,s]),s$);n=!0,this.stopSdkMcpManifestCapture=void 0;let u=Math.round(performance.now()-e),l={servers:r.length,captured:t.size,elapsed_ms:u};if(a==="closed"){ql("sdk_mcp_manifest_capture","closed",l);return}if(a===void 0)_e(`[Query.captureSdkMcpServerManifests] ${t.size}/${r.length} in-process MCP servers captured within ${s$} ms; the rest will handshake over the control channel`,{level:"warn"}),ql("sdk_mcp_manifest_capture","deadline",l);else if(t.size<r.length)ql("sdk_mcp_manifest_capture","partial",l);else Vh("sdk_mcp_manifest_capture",l);if(t.size===0)return;let c=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([d,p])=>{let f=t.get(d);return f!==void 0&&f.transport===p.transport?[[d,f.manifest]]:[]}));if(Object.keys(c).length===0)return;return _e(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(c).join(", ")}] captured in ${u} ms`),c}async interrupt(e){return ht("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let o=t.response?.cancelled;return{still_queued:n.filter((r)=>typeof r==="string"),...Array.isArray(o)&&{cancelled:o.filter((r)=>typeof r==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let o=(i)=>{if(i.subtype==="success"){let{pending_permission_requests:s,pending_user_dialog_requests:a,...u}=i;t(u)}else n(new $l(i.error,"awaitControlResponse: CLI error verdict"));if(i.pending_permission_requests||i.pending_user_dialog_requests)_e("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Jh());return}let r=this.unmatchedControlResponses.get(e);if(r){this.unmatchedControlResponses.delete(e),o(r);return}this.pendingControlResponses.set(e,{handler:(i)=>{this.pendingControlResponses.delete(e),o(i)},reject:n})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return ht("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return ht("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return ht("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return ht("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=ht("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(o)=>{if(o?.initialize===void 0)return n;let r=o.initialize,i=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied,code_running_mcp_tools_applied:l.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),s=r.hooks_applied??i.hooks_applied,a=r.plugins_applied??i.plugins_applied,u=r.code_running_mcp_tools_applied??i.code_running_mcp_tools_applied;return{...r,...s!==void 0&&{hooks_applied:s},...a!==void 0&&{plugins_applied:a},...u!==void 0&&{code_running_mcp_tools_applied:u}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let o=++this.remoteControlCallGeneration,r=this.workSecretAnswerer,i=n?.reattachSessionId||(n?.workSecret===void 0?void 0:dK(n.workSecret)),s=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&i!==void 0?{sessionId:i,refresh:n.refreshWorkSecret}:void 0;this.workSecretAnswerer=s;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.workSecret})).response}catch(u){if(o===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw u}if(e&&o===this.remoteControlCallGeneration){let u=a.bridge_session_id,l=[s,r];this.workSecretAnswerer=typeof u==="string"?l.find((c)=>c!==void 0&&u$(c.sessionId,u)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return ht("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return ht("sdk_side_question",async()=>{let o=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return o.response===null?null:{response:o.response,synthetic:o.synthetic??!1,...o.refusal_fallback&&{refusalFallback:{originalModel:o.refusal_fallback.original_model,fallbackModel:o.refusal_fallback.fallback_model,content:o.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(ri(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Jh());let o=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(o);let r={request_id:o,type:"control_request",request:e},i=e.subtype==="initialize";return new Promise((s,a)=>{let u,l=!1,c=(m)=>{this.pendingControlResponses.delete(o),u?.(),s(m)},d=(m)=>{this.pendingControlResponses.delete(o),u?.(),a(m)};if(n){let m=()=>{if(d(ri(n.reason??"Control request aborted")),!l)return;try{Promise.resolve(this.transport.write(lt({type:"control_cancel_request",request_id:o})+`
|
|
39
39
|
`)).catch(()=>{})}catch{}};n.addEventListener("abort",m,{once:!0}),u=()=>{n.removeEventListener("abort",m)}}this.pendingControlResponses.set(o,{handler:(m)=>{if(m.subtype==="success")c(m);else d(Vg(Error(m.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof m.error_code==="string"&&cK.test(m.error_code)?m.error_code:void 0}));if(!i&&(m.pending_permission_requests||m.pending_user_dialog_requests))_e(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`);else{if(m.pending_permission_requests)this.processPendingPermissionRequests(m.pending_permission_requests);if(m.pending_user_dialog_requests)this.processPendingUserDialogRequests(m.pending_user_dialog_requests)}},reject:d});let p=lt(r)+`
|
|
40
40
|
`,f=()=>{if(n?.aborted)return;return l=!0,this.transport.write(p)};try{(this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(f()):this.initializeWritten.then(f)).catch(d)}catch(m){d(m)}})}initializationResult(){return this.initialization}writeAfterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(this.transport.write(e));return this.initializeWritten.then(()=>this.transport.write(e))}reinitialize(){return ht("sdk_reinitialize",()=>this.initialize({first:!1}))}async supportedCommands(){let{commands:e}=await this.initialization;return this.latestCommands??e}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,t){return ht("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:t})})}async readMcpResource(e,t){return(await this.request({subtype:"mcp_read_resource",serverName:e,uri:t})).response}async enableChannel(e){return ht("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,t){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:t})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,t){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:t})).response}async claudeAuthenticate(e){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e})).response}async claudeOAuthCallback(e,t){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:t})).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(e){return(await this.request({subtype:"get_context_usage",...e})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(e){return(await this.request({subtype:"get_usage",...e?.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(e,t){return(await this.request(e,t)).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(e){return(await this.request({subtype:"select_chrome_browser",device_id:e})).response}async getSandboxDialog(){return(await this.request({subtype:"get_sandbox_dialog"})).response}async readFile(e,t){try{return(await this.request({subtype:"read_file",path:e,max_bytes:t?.maxBytes,encoding:t?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(e){return ht("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...e?.holdOnCacheImpact&&{hold_on_cache_impact:!0},...e?.addPlugins&&e.addPlugins.length>0&&{add_plugins:e.addPlugins}})).response)}async reloadSkills(){return ht("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return ht("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return ht("sdk_mcp_set_servers",async()=>{let t={},n={};for(let[a,u]of Object.entries(e))if(u.type==="sdk"&&"instance"in u)t[a]=u;else n[a]=u;let o=new Set(this.sdkMcpServers.keys()),r=new Set(Object.keys(t));for(let a of o)if(!r.has(a))await this.disconnectSdkMcpServer(a);for(let[a,u]of Object.entries(t)){let l=this.sdkMcpServers.get(a);if(!l){this.connectSdkMcpServer(a,u);continue}let{settings:c,ignored:d}=Wh(u);if(a$(a,u,d),c.timeout!==l.settings.timeout||c.disableAutoBackground!==l.settings.disableAutoBackground)_e(`[Query.setMcpServers] MCP server '${a}' is already registered, so the different timeout or disableAutoBackground passed to setMcpServers is ignored; remove and re-add the server to change it`);if(c.tools!==void 0&&!o$(c.tools,l.settings.tools))_e(c.tools.length===0?`[Query.setMcpServers] MCP server '${a}': per-tool policy cleared`:`[Query.setMcpServers] MCP server '${a}': per-tool policy replaced (${c.tools.length} ${c.tools.length===1?"entry":"entries"})`),l.settings={...l.settings,tools:c.tools}}let i={};for(let a of Object.keys(t))i[a]={type:"sdk",name:a,...this.sdkMcpServers.get(a)?.settings};return(await this.request({subtype:"mcp_set_servers",servers:{...n,...i}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){_e("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let t=0;for await(let n of e){if(t++,_e(`[Query.streamInput] Processing message ${t}: ${n.type}`),this.abortController?.signal.aborted)break;this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),await Promise.resolve(this.transport.write(lt(this.verbatimPrompts?{...n,client_composed:!0}:n)+`
|
|
41
41
|
`))}if(_e(`[Query.streamInput] Finished processing ${t} messages from input stream`),t>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(t){if(!(t instanceof ln))throw t}}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,Rw)),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((e)=>{let t=this.abortController?.signal;if(this.cleanupPerformed||t?.aborted){e();return}let n=()=>e();t?.addEventListener("abort",n,{once:!0}),this.addCleanupCallback(()=>{t?.removeEventListener("abort",n),e()}),this.runEndedResolve=()=>{t?.removeEventListener("abort",n),e()}})}handleHookCallbacks(e,t,n,o){let r=this.hookCallbacks.get(e);if(!r)throw Error(`No hook callback found for ID: ${e}`);return r(t,n,{signal:o})}connectSdkMcpServer(e,t){let n=new Zh((s)=>this.sendMcpServerMessageToCli(e,s)),o=t.instance.connect(n).catch((s)=>{if(this.sdkMcpServers.get(e)?.transport===n)this.sdkMcpServers.delete(e);_e(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${s}`,{level:"error"})}),{settings:r,ignored:i}=Wh(t);a$(e,t,i),this.sdkMcpServers.set(e,{transport:n,settings:r,connection:o})}async disconnectSdkMcpServer(e){let t=this.sdkMcpServers.get(e);if(t){let n=`${e}:${Vl}`;for(let[o,r]of this.pendingMcpResponses)if(o.startsWith(n))this.pendingMcpResponses.delete(o),r.reject(Error("MCP server was removed during the manifest capture"));if(await t.transport.close(),this.sdkMcpServers.get(e)===t)this.sdkMcpServers.delete(e)}}sendMcpServerMessageToCli(e,t){if("id"in t&&t.id!==null&&t.id!==void 0){let o=`${e}:${t.id}`,r=this.pendingMcpResponses.get(o);if(r){r.resolve(t),this.pendingMcpResponses.delete(o);return}if(typeof t.id==="string"&&t.id.startsWith(Vl)){_e(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:Go(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&n$(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.writeAfterInitialize(lt(n)+`
|