@shumai-one/shumai 0.4.6 → 0.4.7
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/bin/{chunk-1bgsphyz.js → chunk-05tnmf8h.js} +2 -2
- package/bin/chunk-0xsgx9ep.js +1 -0
- package/bin/{chunk-3d5rm1d1.js → chunk-0ygtayqf.js} +1 -1
- package/bin/{chunk-crja7whq.js → chunk-11c93g1m.js} +2 -2
- package/bin/chunk-1ajgdv26.js +1 -0
- package/bin/{chunk-ba33nf0q.js → chunk-1ntn42d2.js} +3 -3
- package/bin/chunk-2kxhdnma.js +3 -0
- package/bin/chunk-30dsxm8s.js +1 -0
- package/bin/chunk-3b6h719s.js +3 -0
- package/bin/{chunk-pdh9bnyj.js → chunk-3g5pyw2e.js} +2 -2
- package/bin/{chunk-p75f5pgq.js → chunk-3h9c5ak3.js} +2 -2
- package/bin/{chunk-2qjfpmcf.js → chunk-3m5kwcj7.js} +1 -1
- package/bin/{chunk-w1wxzqqb.js → chunk-3p1bb08a.js} +2 -2
- package/bin/{chunk-6vxzkrsj.js → chunk-3r5yc5wm.js} +4 -4
- package/bin/{chunk-sab7tjxw.js → chunk-3tyk9xgf.js} +3 -3
- package/bin/{chunk-h9mka9br.js → chunk-4a88wwg2.js} +1 -1
- package/bin/{chunk-z08bqvkc.js → chunk-4f5pnnah.js} +14 -14
- package/bin/{chunk-dpc11hpd.js → chunk-4jgq9m51.js} +7 -7
- package/bin/{chunk-d7fwggt6.js → chunk-4m8gk79m.js} +1 -1
- package/bin/{chunk-b9hyc0a1.js → chunk-53vtc74g.js} +2 -2
- package/bin/{chunk-1kt5dzjv.js → chunk-58e1a3re.js} +2 -2
- package/bin/{chunk-dmvvt8va.js → chunk-5qkwpy8c.js} +2 -2
- package/bin/{chunk-07jszkhj.js → chunk-5rk7dyx9.js} +58 -58
- package/bin/{chunk-ga3pahzf.js → chunk-5v4s2kp4.js} +1 -1
- package/bin/{chunk-v8v8vdf7.js → chunk-5wp37g6w.js} +4 -4
- package/bin/{chunk-hs2r9qaw.js → chunk-628k58ek.js} +2 -2
- package/bin/{chunk-rp4pc6kz.js → chunk-6kdf411z.js} +1 -1
- package/bin/chunk-6ksrrayx.css +1 -0
- package/bin/chunk-6rjkbwz6.js +14 -0
- package/bin/{chunk-md5pcq46.js → chunk-781990k7.js} +4 -4
- package/bin/{chunk-ey3h4sct.js → chunk-887pj9xd.js} +2 -2
- package/bin/{chunk-1jybg56e.js → chunk-8b1w6bj9.js} +1 -1
- package/bin/{chunk-0wvhahzh.js → chunk-8gna37dd.js} +1 -1
- package/bin/{chunk-rmzcarv9.js → chunk-8sf106rq.js} +1 -1
- package/bin/{chunk-2jrjwaqr.js → chunk-8ystwvdt.js} +1 -1
- package/bin/{chunk-3j5njrpr.js → chunk-9v6eqa3n.js} +2 -2
- package/bin/{chunk-rsd164d9.js → chunk-9va1mzeq.js} +1 -1
- package/bin/{chunk-kmbjp5kp.js → chunk-an6nsq1t.js} +1 -1
- package/bin/{chunk-vzj2j11x.js → chunk-ayq8dskd.js} +1 -1
- package/bin/{chunk-y20sbaz5.js → chunk-b0rjvx5g.js} +1 -1
- package/bin/chunk-bgm76rzj.js +1 -0
- package/bin/chunk-btmxr226.js +1 -0
- package/bin/chunk-camzbwqh.js +2 -0
- package/bin/{chunk-t350k3s1.js → chunk-ccvjwhqq.js} +1 -1
- package/bin/{chunk-pgj2kjnn.js → chunk-dkzyv61a.js} +2 -2
- package/bin/{chunk-y56yvezn.js → chunk-dyq6h9ha.js} +1 -1
- package/bin/{chunk-teqprbd8.js → chunk-e17daz1x.js} +1 -1
- package/bin/{chunk-dbw8c1jj.js → chunk-ebf1r872.js} +4 -4
- package/bin/{chunk-2vzzd0q6.js → chunk-ebx3bd4c.js} +1 -1
- package/bin/{chunk-161rxeq2.js → chunk-ee3mrvqp.js} +1 -1
- package/bin/chunk-fg6zf2gb.js +2 -0
- package/bin/{chunk-6y4xkcte.js → chunk-fhazy8f9.js} +1 -1
- package/bin/{chunk-gqr5hxhj.js → chunk-fk712d68.js} +1 -1
- package/bin/{chunk-afnzb9ne.js → chunk-fvgb6rps.js} +2 -2
- package/bin/chunk-g9gmht89.js +2 -0
- package/bin/{chunk-1t51fp6n.js → chunk-gf4n4ahk.js} +1 -1
- package/bin/{chunk-gcjsw9yp.js → chunk-h3wr8nnk.js} +1 -1
- package/bin/chunk-htpjtarr.js +2 -0
- package/bin/{chunk-kg8eg9z3.js → chunk-hye75kp0.js} +2 -2
- package/bin/{chunk-3tg39jx7.js → chunk-j41mya13.js} +2 -2
- package/bin/chunk-j547gtag.js +2 -0
- package/bin/{chunk-a4056d0r.js → chunk-jde9r5mj.js} +1 -1
- package/bin/chunk-jf4kcad0.js +1 -0
- package/bin/{chunk-tgr86ac4.js → chunk-jt04mf5s.js} +1 -1
- package/bin/{chunk-hnhdq2wd.js → chunk-k3qypq3x.js} +1 -1
- package/bin/chunk-k5hnrtrt.js +1 -0
- package/bin/{chunk-mtb9fpj2.js → chunk-k810fstm.js} +1 -1
- package/bin/{chunk-3n4224c0.js → chunk-kg2c445x.js} +1 -1
- package/bin/{chunk-edqd8evk.js → chunk-kq2qbwx1.js} +1 -1
- package/bin/{chunk-7nvk7waw.js → chunk-m2h7a172.js} +1 -1
- package/bin/{chunk-brwbhbmc.js → chunk-m638fg4n.js} +5 -5
- package/bin/{chunk-3dgahs95.js → chunk-mm1a0zja.js} +1 -1
- package/bin/{chunk-hxyg5q2a.js → chunk-njabdtvb.js} +2 -2
- package/bin/{chunk-b6q287d1.js → chunk-njqf50vw.js} +1 -1
- package/bin/{chunk-47tn3vtg.js → chunk-nn5hyf6f.js} +1 -1
- package/bin/{chunk-t7bvde99.js → chunk-nnq8g9yy.js} +3 -3
- package/bin/{chunk-8cn7fx40.js → chunk-ny7qjn6s.js} +1 -1
- package/bin/{chunk-3d9tfxp4.js → chunk-p5fwjk5c.js} +1 -1
- package/bin/{chunk-s05cdax2.js → chunk-pa1fmskf.js} +1 -1
- package/bin/{chunk-a796sgcw.js → chunk-pcspeqwq.js} +2 -2
- package/bin/{chunk-yfr0hzb7.js → chunk-q1d7x1cc.js} +1 -1
- package/bin/{chunk-y1b3ck7m.js → chunk-q45n02fs.js} +1 -1
- package/bin/chunk-q6jsw0rr.js +211 -0
- package/bin/chunk-qjzyze00.js +1 -0
- package/bin/{chunk-2yr5k567.js → chunk-r55htzxr.js} +1 -1
- package/bin/{chunk-46wfxyd7.js → chunk-r7e2fmmx.js} +2 -2
- package/bin/{chunk-5kvc1gp2.js → chunk-rbagbd0e.js} +1 -1
- package/bin/{chunk-dz076sh7.js → chunk-rdscv38p.js} +1 -1
- package/bin/chunk-rfhmk32e.js +1 -0
- package/bin/{chunk-qs7855cz.js → chunk-rkafv27g.js} +2 -2
- package/bin/{chunk-hd6dnnyg.js → chunk-rkqpnyzx.js} +1 -1
- package/bin/{chunk-z6jpt0h6.js → chunk-s30fjvzs.js} +3 -3
- package/bin/{chunk-dj5a6kkh.js → chunk-s41mgkse.js} +1 -1
- package/bin/{chunk-988casfy.js → chunk-s63vj79f.js} +1 -1
- package/bin/{chunk-9d0thqcy.js → chunk-t3t7dcfq.js} +1 -1
- package/bin/{chunk-gsfcpcye.js → chunk-twyxs4z2.js} +1 -1
- package/bin/{chunk-1dqsf5qj.js → chunk-typ46eqd.js} +5 -5
- package/bin/chunk-v1sgrg0r.js +1 -0
- package/bin/{chunk-j9ks8bd7.js → chunk-vdnmq163.js} +1 -1
- package/bin/{chunk-jg2v25d2.js → chunk-vx66rms0.js} +2 -2
- package/bin/{chunk-9nvymwqj.js → chunk-wvq717b5.js} +2 -2
- package/bin/chunk-xbge27m4.js +1 -0
- package/bin/{chunk-ysv80zyb.js → chunk-xca338dw.js} +3 -3
- package/bin/chunk-xcsz1wp7.js +1 -0
- package/bin/{chunk-ehpfg3km.js → chunk-xznabrt2.js} +1 -1
- package/bin/{chunk-pvg3msgw.js → chunk-xzyfnfck.js} +3 -3
- package/bin/{chunk-9trnkbtr.js → chunk-ycw3rwhx.js} +3 -3
- package/bin/{chunk-qbqym9m6.js → chunk-yqvhgtez.js} +2 -2
- package/bin/{chunk-4syt6rn0.js → chunk-yr03tf5r.js} +2 -2
- package/bin/{chunk-n3xjwszr.js → chunk-z9jpgxf1.js} +1 -1
- package/bin/chunk-zb0az2tq.js +2 -0
- package/bin/{chunk-pwkby9h7.js → chunk-zbt4h7n0.js} +1 -1
- package/bin/{chunk-kk42xhgz.js → chunk-zcdqsp1e.js} +1 -1
- package/bin/chunk-zej27b5c.js +2 -0
- package/bin/{chunk-axmd242s.js → chunk-zmjtv19e.js} +1 -1
- package/bin/{chunk-7e5z637e.js → chunk-zr11zfwc.js} +1 -1
- package/bin/{chunk-k6avge95.js → chunk-zz0522zr.js} +4 -4
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +294 -293
- package/package.json +7 -7
- package/bin/chunk-0c67210c.js +0 -1
- package/bin/chunk-2z1pnt7h.js +0 -2
- package/bin/chunk-3vmapyk9.js +0 -1
- package/bin/chunk-886pnknh.js +0 -3
- package/bin/chunk-908pypkr.js +0 -1
- package/bin/chunk-952qwf17.js +0 -2
- package/bin/chunk-9a2tf0mh.js +0 -2
- package/bin/chunk-apfrw0wd.js +0 -3
- package/bin/chunk-batadmvr.js +0 -2
- package/bin/chunk-bvdvp192.js +0 -1
- package/bin/chunk-db1msmdh.js +0 -2
- package/bin/chunk-dkx3pmdz.js +0 -1
- package/bin/chunk-hacyjx1s.js +0 -1
- package/bin/chunk-he5nvmqw.js +0 -1
- package/bin/chunk-hyr1vtfp.js +0 -1
- package/bin/chunk-jh8q3885.js +0 -211
- package/bin/chunk-jzbrt2vk.js +0 -1
- package/bin/chunk-nqym3zbs.js +0 -1
- package/bin/chunk-sebbjvgv.css +0 -1
- package/bin/chunk-t8gv2ekj.js +0 -14
- package/bin/chunk-vm5tn0zm.js +0 -2
- package/bin/chunk-wmjp8dcm.js +0 -1
- package/bin/chunk-wy8dkyxj.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Dt}from"./chunk-
|
|
2
|
+
import{Dt}from"./chunk-s30fjvzs.js";import{$e}from"./chunk-781990k7.js";import{z}from"./chunk-yqvhgtez.js";var p=z($e());var G=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var N=z(Dt());var c=z($e());var K=300000,_="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var H=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-ccvjwhqq.js"),n=(f)=>o.clientConfig?.[f]??o.parentClientConfig?.[f]??r?.[f];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var U=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-ccvjwhqq.js");return(await H(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var j=z($e());var A=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new j.TokenProviderError(`Token is expired. ${_}`,!1)};var q=z($e());var m=(e,o,r=!1)=>{if(typeof o>"u")throw new q.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${_}`,!1)};var W=z($e());import{promises as Q}from"fs";var{writeFile:Z}=Q,X=(e,o)=>{let r=W.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return Z(r,t)};var J=new Map,I=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await c.parseKnownFiles(e),t=c.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new c.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new c.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let i=n.sso_session,g=(await c.loadSsoSessionData(e))[i];if(!g)throw new c.TokenProviderError(`Sso session '${i}' could not be found in shared credentials file.`,!1);for(let l of["sso_start_url","sso_region"])if(!g[l])throw new c.TokenProviderError(`Sso session '${i}' is missing required property '${l}'.`,!1);let{sso_start_url:S,sso_region:O}=g,s;try{s=await c.getSSOTokenFromFile(i)}catch(l){throw new c.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${_}`,!1)}m("accessToken",s.accessToken),m("expiresAt",s.expiresAt);let{accessToken:k,expiresAt:T}=s,a={token:k,expiration:new Date(T)};if(a.expiration.getTime()-Date.now()>K)return a;let d=J.get(i)??0;if(Date.now()-d<30000)return A(a),a;m("clientId",s.clientId,!0),m("clientSecret",s.clientSecret,!0),m("refreshToken",s.refreshToken,!0);try{J.set(i,Date.now());let l=await U(s,O,e,o);m("accessToken",l.accessToken),m("expiresIn",l.expiresIn);let x=new Date(Date.now()+l.expiresIn*1000);try{await X(i,{...s,accessToken:l.accessToken,expiresAt:x.toISOString(),refreshToken:l.refreshToken})}catch(h){}return{token:l.accessToken,expiration:x}}catch(l){return A(a),a}};var w=z($e()),C=!1,R=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:i,clientConfig:f,parentClientConfig:g,callerClientConfig:S,profile:O,filepath:s,configFilepath:k,ignoreCache:T,logger:a})=>{let d,l="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let u=await I({profile:O,filepath:s,configFilepath:k,ignoreCache:T,clientConfig:f,parentClientConfig:g,logger:a})({callerClientConfig:S});d={accessToken:u.token,expiresAt:new Date(u.expiration).toISOString()}}catch(u){throw new w.CredentialsProviderError(u.message,{tryNextLink:C,logger:a})}else try{d=await w.getSSOTokenFromFile(e)}catch(u){throw new w.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:C,logger:a})}if(new Date(d.expiresAt).getTime()-Date.now()<=0)throw new w.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:C,logger:a});let{accessToken:x}=d,{SSOClient:h,GetRoleCredentialsCommand:y}=await import("./chunk-nn5hyf6f.js"),B=i||new h(Object.assign({},f??{},{logger:f?.logger??S?.logger??g?.logger,region:f?.region??t,userAgentAppId:f?.userAgentAppId??S?.userAgentAppId??g?.userAgentAppId})),v;try{v=await B.send(new y({accountId:r,roleName:n,accessToken:x}))}catch(u){throw new w.CredentialsProviderError(u,{tryNextLink:C,logger:a})}let{roleCredentials:{accessKeyId:P,secretAccessKey:F,sessionToken:D,expiration:L,credentialScope:M,accountId:b}={}}=v;if(!P||!F||!D||!L)throw new w.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:C,logger:a});let E={accessKeyId:P,secretAccessKey:F,sessionToken:D,expiration:new Date(L),...M&&{credentialScope:M},...b&&{accountId:b}};if(o)N.setCredentialFeature(E,"CREDENTIALS_SSO","s");else N.setCredentialFeature(E,"CREDENTIALS_SSO_LEGACY","u");return E};var V=z($e()),Y=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:i}=e;if(!r||!t||!n||!i)throw new V.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
|
|
3
3
|
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var ee=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:t,ssoRegion:n,ssoRoleName:i,ssoSession:f}=e,{ssoClient:g}=e,S=p.getProfileName({profile:e.profile??o?.profile});if(!r&&!t&&!n&&!i&&!f){let s=(await p.parseKnownFiles(e))[S];if(!s)throw new p.CredentialsProviderError(`Profile ${S} was not found.`,{logger:e.logger});if(!G(s))throw new p.CredentialsProviderError(`Profile ${S} is not configured with SSO credentials.`,{logger:e.logger});if(s?.sso_session){let h=(await p.loadSsoSessionData(e))[s.sso_session],y=` configurations in profile ${S} and sso-session ${s.sso_session}`;if(n&&n!==h.sso_region)throw new p.CredentialsProviderError("Conflicting SSO region"+y,{tryNextLink:!1,logger:e.logger});if(r&&r!==h.sso_start_url)throw new p.CredentialsProviderError("Conflicting SSO start_url"+y,{tryNextLink:!1,logger:e.logger});s.sso_region=h.sso_region,s.sso_start_url=h.sso_start_url}let{sso_start_url:k,sso_account_id:T,sso_region:a,sso_role_name:d,sso_session:l}=Y(s,e.logger);return R({ssoStartUrl:k,ssoSession:l,ssoAccountId:T,ssoRegion:a,ssoRoleName:d,ssoClient:g,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})}else if(!r||!t||!n||!i)throw new p.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:e.logger});else return R({ssoStartUrl:r,ssoSession:f,ssoAccountId:t,ssoRegion:n,ssoRoleName:i,ssoClient:g,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})};export{ee as fromSSO};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{tf,Yr}from"./chunk-ycw3rwhx.js";import{cr}from"./chunk-3h9c5ak3.js";import{Fa}from"./chunk-5vvvgjvz.js";import{La,Za}from"./chunk-dscq4a4k.js";import{as}from"./chunk-628k58ek.js";import{qe,uo,ef,Cr,am,fo}from"./chunk-3g5pyw2e.js";import{ln}from"./chunk-gc6m7agb.js";import{cn}from"./chunk-05tnmf8h.js";import{Yt}from"./chunk-b3aqmcps.js";function f(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function a(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jt=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jt=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function U(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var ye=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class k extends m{constructor(e,t,r,s,n){super(`${k.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("request-id"),this.error=t,this.type=n??null}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Y({message:r,cause:ye(t)});let n=t,o=n?.error?.type;if(e===400)return new xe(e,n,r,s,o);if(e===401)return new Se(e,n,r,s,o);if(e===403)return new ke(e,n,r,s,o);if(e===404)return new Pe(e,n,r,s,o);if(e===409)return new Re(e,n,r,s,o);if(e===422)return new ve(e,n,r,s,o);if(e===429)return new Ee(e,n,r,s,o);if(e>=500)return new Me(e,n,r,s,o);return new k(e,n,r,s,o)}}class E extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Y extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class we extends Y{constructor({message:e}={}){super({message:e??"Request timed out."})}}class xe extends k{}class Se extends k{}class ke extends k{}class Pe extends k{}class Re extends k{}class ve extends k{}class Ee extends k{}class Me extends k{}var Is=/^[a-z][a-z0-9+.-]*:/i,Ar=(e)=>Is.test(e),Vt=(e)=>(Vt=Array.isArray,Vt(e)),Xt=Vt;function mt(e){if(typeof e!=="object")return{};return e??{}}function Kt(e){if(!e)return!0;for(let t in e)return!1;return!0}function Ir(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var $r=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var gt=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Or=(e)=>new Promise((t)=>setTimeout(t,e));var V="0.91.1";var qr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $s(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Cs=()=>{let e=$s();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(Deno.build.os),"X-Stainless-Arch":Nr(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":Lr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Os();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Os(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,c=s[3]||0;return{browser:t,version:`${n}.${o}.${c}`}}}return null}var Nr=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Lr=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fr,Br=()=>Fr??(Fr=Cs());function jr(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Gt(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Gt({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Te(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ur(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Hr=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function Wr(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new m(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function Vr(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Dr;function Ae(e){let t;return(Dr??(t=new globalThis.TextEncoder,Dr=t.encode.bind(t)))(e)}var Jr;function zt(e){let t;return(Jr??(t=new globalThis.TextDecoder,Jr=t.decode.bind(t)))(e)}var A,I;class X{constructor(){A.set(this,void 0),I.set(this,void 0),f(this,A,new Uint8Array,"f"),f(this,I,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ae(e):e;f(this,A,Vr([a(this,A,"f"),t]),"f");let r=[],s;while((s=Fs(a(this,A,"f"),a(this,I,"f")))!=null){if(s.carriage&&a(this,I,"f")==null){f(this,I,s.index,"f");continue}if(a(this,I,"f")!=null&&(s.index!==a(this,I,"f")+1||s.carriage)){r.push(zt(a(this,A,"f").subarray(0,a(this,I,"f")-1))),f(this,A,a(this,A,"f").subarray(a(this,I,"f")),"f"),f(this,I,null,"f");continue}let n=a(this,I,"f")!==null?s.preceding-1:s.preceding,o=zt(a(this,A,"f").subarray(0,n));r.push(o),f(this,A,a(this,A,"f").subarray(s.index),"f"),f(this,I,null,"f")}return r}flush(){if(!a(this,A,"f").length)return[];return this.decode(`
|
|
3
3
|
`)}}A=new WeakMap,I=new WeakMap;X.NEWLINE_CHARS=new Set([`
|
|
4
4
|
`,"\r"]);X.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Fs(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Xr(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var yt={off:0,error:200,warn:300,info:400,debug:500},Qt=(e,t,r)=>{if(!e)return;if(Ir(yt,e))return e;R(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(yt))}`);return};function Ie(){}function bt(e,t,r){if(!t||yt[e]>yt[r])return Ie;else return t[e].bind(t)}var qs={error:Ie,warn:Ie,info:Ie,debug:Ie},Kr=new WeakMap;function R(e){let t=e.logger,r=e.logLevel??"off";if(!t)return qs;let s=Kr.get(t);if(s&&s[0]===r)return s[1];let n={error:bt("error",t,r),warn:bt("warn",t,r),info:bt("info",t,r),debug:bt("debug",t,r)};return Kr.set(t,[r,n]),n}var H=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="x-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var $e;class C{constructor(e,t,r){this.iterator=e,$e.set(this,void 0),this.controller=t,f(this,$e,r,"f")}static fromSSEResponse(e,t,r){let s=!1,n=r?R(r):console;async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of Bs(e,t)){if(i.event==="completion")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="message_start"||i.event==="message_delta"||i.event==="message_stop"||i.event==="content_block_start"||i.event==="content_block_delta"||i.event==="content_block_stop"||i.event==="message"||i.event==="user.message"||i.event==="user.interrupt"||i.event==="user.tool_confirmation"||i.event==="user.custom_tool_result"||i.event==="agent.message"||i.event==="agent.thinking"||i.event==="agent.tool_use"||i.event==="agent.tool_result"||i.event==="agent.mcp_tool_use"||i.event==="agent.mcp_tool_result"||i.event==="agent.custom_tool_use"||i.event==="agent.thread_context_compacted"||i.event==="session.status_running"||i.event==="session.status_idle"||i.event==="session.status_rescheduled"||i.event==="session.status_terminated"||i.event==="session.error"||i.event==="session.deleted"||i.event==="span.model_request_start"||i.event==="span.model_request_end")try{yield JSON.parse(i.data)}catch(h){throw n.error("Could not parse message into JSON:",i.data),n.error("From chunk:",i.raw),h}if(i.event==="ping")continue;if(i.event==="error"){let h=gt(i.data)??i.data,b=h?.error?.type;throw new k(void 0,h,void 0,e.headers,b)}}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let c=new X,i=Te(e);for await(let h of i)for(let b of c.decode(h))yield b;for(let h of c.flush())yield h}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of n()){if(c)continue;if(i)yield JSON.parse(i)}c=!0}catch(i){if(U(i))return;throw i}finally{if(!c)t.abort()}}return new C(o,t,r)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new C(()=>s(e),this.controller,a(this,$e,"f")),new C(()=>s(t),this.controller,a(this,$e,"f"))]}toReadableStream(){let e=this,t;return Gt({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ae(JSON.stringify(s)+`
|
|
5
5
|
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Bs(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new Gr,s=new X,n=Te(e.body);for await(let o of js(n))for(let c of s.decode(o)){let i=r.decode(c);if(i)yield i}for(let o of s.flush()){let c=r.decode(o);if(c)yield c}}async function*js(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ae(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Xr(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class Gr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
|
|
@@ -7,7 +7,7 @@ import{Xd,Yr}from"./chunk-9trnkbtr.js";import{lr}from"./chunk-p75f5pgq.js";impor
|
|
|
7
7
|
${o.map((l)=>l.error).join(`
|
|
8
8
|
`)}
|
|
9
9
|
${c}
|
|
10
|
-
${_}`)}return c},d=Qs(ts);class Ne extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/environments/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}var Le=Symbol("anthropic.sdk.stainlessHelper");function Pt(e){return typeof e==="object"&&e!==null&&Le in e}function or(e,t){let r=new Set;if(e){for(let s of e)if(Pt(s))r.add(s[Le])}if(t)for(let s of t){if(Pt(s))r.add(s[Le]);if(Array.isArray(s.content)){for(let n of s.content)if(Pt(n))r.add(n[Le])}}return Array.from(r)}function Rt(e,t){let r=or(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function rs(e){if(Pt(e))return{"x-stainless-helper":e[Le]};return{}}class Fe extends y{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},rs(s.file),t?.headers])},this._client))}}class Be extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}?beta=true`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class je extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/user_profiles/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}class Ue extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/agents/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ce extends y{constructor(){super(...arguments);this.versions=new Ue(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s,...n}=t??{};return this._client.get(d`/v1/agents/${e}?beta=true`,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/agents/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ce.Versions=Ue;class He extends y{create(e,t,r){let{view:s,betas:n,...o}=t;return this._client.post(d`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:s,view:n,betas:o,...c}=t;return this._client.post(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:n},body:c,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memories?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:s,expected_content_sha256:n,betas:o}=t;return this._client.delete(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:n},...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class We extends y{retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memory_versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:s,betas:n}=t;return this._client.post(d`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class te extends y{constructor(){super(...arguments);this.memories=new He(this._client),this.memoryVersions=new We(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/memory_stores/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}te.Memories=He;te.MemoryVersions=We;var vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function ns(e){return e?.output_format??e?.output_config?.format}function ar(e,t,r){let s=ns(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null};return ir(e,t,r)}function ir(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=un(t,o.text);if(s===null)s=c;let i=Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),c},enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function un(e,t){let r=ns(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var hn=(e)=>{let t=0,r=[];while(t<e.length){let s=e[t];if(s==="\\"){t++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),t++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),t++;continue}if(s==="["){r.push({type:"paren",value:"["}),t++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),t++;continue}if(s===":"){r.push({type:"separator",value:":"}),t++;continue}if(s===","){r.push({type:"delimiter",value:","}),t++;continue}if(s==='"'){let i="",h=!1;s=e[++t];while(s!=='"'){if(t===e.length){h=!0;break}if(s==="\\"){if(t++,t===e.length){h=!0;break}i+=s+e[t],s=e[++t]}else i+=s,s=e[++t]}if(s=e[++t],!h)r.push({type:"string",value:i});continue}if(s&&/\s/.test(s)){t++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let i="";if(s==="-")i+=s,s=e[++t];while(s&&o.test(s)||s===".")i+=s,s=e[++t];r.push({type:"number",value:i});continue}let c=/[a-z]/i;if(s&&c.test(s)){let i="";while(s&&c.test(s)){if(t===e.length)break;i+=s,s=e[++t]}if(i=="true"||i=="false"||i==="null")r.push({type:"name",value:i});else{t++;continue}continue}t++}return r},le=(e)=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),le(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),le(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),le(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),le(e);break;case"delimiter":return e=e.slice(0,e.length-1),le(e);break}return e},dn=(e)=>{let t=[];if(e.map((r)=>{if(r.type==="brace")if(r.value==="{")t.push("}");else t.splice(t.lastIndexOf("}"),1);if(r.type==="paren")if(r.value==="[")t.push("]");else t.splice(t.lastIndexOf("]"),1)}),t.length>0)t.reverse().map((r)=>{if(r==="}")e.push({type:"brace",value:"}"});else if(r==="]")e.push({type:"paren",value:"]"})});return e},fn=(e)=>{let t="";return e.map((r)=>{switch(r.type){case"string":t+='"'+r.value+'"';break;default:t+=r.value;break}}),t},Et=(e)=>JSON.parse(fn(dn(le(hn(e)))));var F,K,ue,De,Mt,Je,Ve,Tt,Xe,W,Ke,At,It,re,$t,Ct,Ge,cr,os,Ot,ur,hr,dr,as,is="__json_buf";function cs(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ze{constructor(e,t){F.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),ue.set(this,null),this.controller=new AbortController,De.set(this,void 0),Mt.set(this,()=>{}),Je.set(this,()=>{}),Ve.set(this,void 0),Tt.set(this,()=>{}),Xe.set(this,()=>{}),W.set(this,{}),Ke.set(this,!1),At.set(this,!1),It.set(this,!1),re.set(this,!1),$t.set(this,void 0),Ct.set(this,void 0),Ge.set(this,void 0),Ot.set(this,(r)=>{if(f(this,At,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,It,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,De,new Promise((r,s)=>{f(this,Mt,r,"f"),f(this,Je,s,"f")}),"f"),f(this,Ve,new Promise((r,s)=>{f(this,Tt,r,"f"),f(this,Xe,s,"f")}),"f"),a(this,De,"f").catch(()=>{}),a(this,Ve,"f").catch(()=>{}),f(this,ue,e,"f"),f(this,Ge,t?.logger??console,"f")}get response(){return a(this,$t,"f")}get request_id(){return a(this,Ct,"f")}async withResponse(){f(this,re,!0,"f");let e=await a(this,De,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new ze(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ze(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,ue,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,Ot,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,F,"m",ur).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,F,"m",hr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,$t,e,"f"),f(this,Ct,e?.headers.get("request-id"),"f"),a(this,Mt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,Ke,"f")}get errored(){return a(this,At,"f")}get aborted(){return a(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,W,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,re,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,re,!0,"f"),await a(this,Ve,"f")}get currentMessage(){return a(this,K,"f")}async finalMessage(){return await this.done(),a(this,F,"m",cr).call(this)}async finalText(){return await this.done(),a(this,F,"m",os).call(this)}_emit(e,...t){if(a(this,Ke,"f"))return;if(e==="end")f(this,Ke,!0,"f"),a(this,Tt,"f").call(this);let r=a(this,W,"f")[e];if(r)a(this,W,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,F,"m",cr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,F,"m",ur).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,F,"m",hr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(K=new WeakMap,ue=new WeakMap,De=new WeakMap,Mt=new WeakMap,Je=new WeakMap,Ve=new WeakMap,Tt=new WeakMap,Xe=new WeakMap,W=new WeakMap,Ke=new WeakMap,At=new WeakMap,It=new WeakMap,re=new WeakMap,$t=new WeakMap,Ct=new WeakMap,Ge=new WeakMap,Ot=new WeakMap,F=new WeakSet,cr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},os=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter((r)=>r.type==="text").map((r)=>r.text);if(t.length===0)throw new m("stream ended without producing a content block with type=text");return t.join(" ")},ur=function(){if(this.ended)return;f(this,K,void 0,"f")},hr=function(t){if(this.ended)return;let r=a(this,F,"m",as).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(cs(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}case"compaction_delta":{if(s.type==="compaction"&&s.content)this._emit("compaction",s.content);break}default:ls(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(ar(r,a(this,ue,"f"),{logger:a(this,Ge,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,K,r,"f");break}case"content_block_start":case"message_delta":break}},dr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,K,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,K,void 0,"f"),ar(t,a(this,ue,"f"),{logger:a(this,Ge,"f")})},as=function(t){let r=a(this,K,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.iterations!=null)r.usage.iterations=t.usage.iterations;return r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&cs(s)){let n=s[is]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,is,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Et(n)}catch(c){let i=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${n}`);a(this,Ot,"f").call(this,i)}r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}case"compaction_delta":{if(s?.type==="compaction")r.content[t.index]={...s,content:(s.content||"")+t.delta.content};break}default:ls(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ls(e){}class he extends Error{constructor(e){let t=typeof e==="string"?e:e.map((r)=>{if(r.type==="text")return r.text;return`[${r.type}]`}).join(" ");super(t);this.name="ToolError",this.content=e}}var us=1e5,hs=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
10
|
+
${_}`)}return c},d=Qs(ts);class Ne extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/environments/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}var Le=Symbol("anthropic.sdk.stainlessHelper");function Pt(e){return typeof e==="object"&&e!==null&&Le in e}function or(e,t){let r=new Set;if(e){for(let s of e)if(Pt(s))r.add(s[Le])}if(t)for(let s of t){if(Pt(s))r.add(s[Le]);if(Array.isArray(s.content)){for(let n of s.content)if(Pt(n))r.add(n[Le])}}return Array.from(r)}function Rt(e,t){let r=or(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function rs(e){if(Pt(e))return{"x-stainless-helper":e[Le]};return{}}class Fe extends y{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",B,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){let{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",ie({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},rs(s.file),t?.headers])},this._client))}}class Be extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}?beta=true`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",B,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class je extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/user_profiles/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}class Ue extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/agents/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ce extends y{constructor(){super(...arguments);this.versions=new Ue(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s,...n}=t??{};return this._client.get(d`/v1/agents/${e}?beta=true`,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/agents/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ce.Versions=Ue;class He extends y{create(e,t,r){let{view:s,betas:n,...o}=t;return this._client.post(d`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{memory_store_id:s,view:n,betas:o,...c}=t;return this._client.post(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:n},body:c,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memories?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{memory_store_id:s,expected_content_sha256:n,betas:o}=t;return this._client.delete(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:n},...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class We extends y{retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(d`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memory_versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){let{memory_store_id:s,betas:n}=t;return this._client.post(d`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class te extends y{constructor(){super(...arguments);this.memories=new He(this._client),this.memoryVersions=new We(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/memory_stores/${e}?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}te.Memories=He;te.MemoryVersions=We;var vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function ss(e){return e?.output_format??e?.output_config?.format}function ar(e,t,r){let s=ss(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text"){let o=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null};return ir(e,t,r)}function ir(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=un(t,o.text);if(s===null)s=c;let i=Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),c},enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function un(e,t){let r=ss(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}var hn=(e)=>{let t=0,r=[];while(t<e.length){let s=e[t];if(s==="\\"){t++;continue}if(s==="{"){r.push({type:"brace",value:"{"}),t++;continue}if(s==="}"){r.push({type:"brace",value:"}"}),t++;continue}if(s==="["){r.push({type:"paren",value:"["}),t++;continue}if(s==="]"){r.push({type:"paren",value:"]"}),t++;continue}if(s===":"){r.push({type:"separator",value:":"}),t++;continue}if(s===","){r.push({type:"delimiter",value:","}),t++;continue}if(s==='"'){let i="",h=!1;s=e[++t];while(s!=='"'){if(t===e.length){h=!0;break}if(s==="\\"){if(t++,t===e.length){h=!0;break}i+=s+e[t],s=e[++t]}else i+=s,s=e[++t]}if(s=e[++t],!h)r.push({type:"string",value:i});continue}if(s&&/\s/.test(s)){t++;continue}let o=/[0-9]/;if(s&&o.test(s)||s==="-"||s==="."){let i="";if(s==="-")i+=s,s=e[++t];while(s&&o.test(s)||s===".")i+=s,s=e[++t];r.push({type:"number",value:i});continue}let c=/[a-z]/i;if(s&&c.test(s)){let i="";while(s&&c.test(s)){if(t===e.length)break;i+=s,s=e[++t]}if(i=="true"||i=="false"||i==="null")r.push({type:"name",value:i});else{t++;continue}continue}t++}return r},le=(e)=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),le(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),le(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),le(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),le(e);break;case"delimiter":return e=e.slice(0,e.length-1),le(e);break}return e},dn=(e)=>{let t=[];if(e.map((r)=>{if(r.type==="brace")if(r.value==="{")t.push("}");else t.splice(t.lastIndexOf("}"),1);if(r.type==="paren")if(r.value==="[")t.push("]");else t.splice(t.lastIndexOf("]"),1)}),t.length>0)t.reverse().map((r)=>{if(r==="}")e.push({type:"brace",value:"}"});else if(r==="]")e.push({type:"paren",value:"]"})});return e},fn=(e)=>{let t="";return e.map((r)=>{switch(r.type){case"string":t+='"'+r.value+'"';break;default:t+=r.value;break}}),t},Et=(e)=>JSON.parse(fn(dn(le(hn(e)))));var F,K,ue,De,Mt,Je,Ve,Tt,Xe,W,Ke,At,It,re,$t,Ct,Ge,lr,ns,Ot,ur,hr,dr,os,is="__json_buf";function cs(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ze{constructor(e,t){F.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),ue.set(this,null),this.controller=new AbortController,De.set(this,void 0),Mt.set(this,()=>{}),Je.set(this,()=>{}),Ve.set(this,void 0),Tt.set(this,()=>{}),Xe.set(this,()=>{}),W.set(this,{}),Ke.set(this,!1),At.set(this,!1),It.set(this,!1),re.set(this,!1),$t.set(this,void 0),Ct.set(this,void 0),Ge.set(this,void 0),Ot.set(this,(r)=>{if(f(this,At,!0,"f"),U(r))r=new E;if(r instanceof E)return f(this,It,!0,"f"),this._emit("abort",r);if(r instanceof m)return this._emit("error",r);if(r instanceof Error){let s=new m(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new m(String(r)))}),f(this,De,new Promise((r,s)=>{f(this,Mt,r,"f"),f(this,Je,s,"f")}),"f"),f(this,Ve,new Promise((r,s)=>{f(this,Tt,r,"f"),f(this,Xe,s,"f")}),"f"),a(this,De,"f").catch(()=>{}),a(this,Ve,"f").catch(()=>{}),f(this,ue,e,"f"),f(this,Ge,t?.logger??console,"f")}get response(){return a(this,$t,"f")}get request_id(){return a(this,Ct,"f")}async withResponse(){f(this,re,!0,"f");let e=await a(this,De,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new ze(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ze(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,ue,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,Ot,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){if(this.receivedMessages.push(e),t)this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal,n;if(s){if(s.aborted)this.controller.abort();n=this.controller.abort.bind(this.controller),s.addEventListener("abort",n)}try{a(this,F,"m",ur).call(this);let{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(let i of c)a(this,F,"m",hr).call(this,i);if(c.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,$t,e,"f"),f(this,Ct,e?.headers.get("request-id"),"f"),a(this,Mt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,Ke,"f")}get errored(){return a(this,At,"f")}get aborted(){return a(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,W,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(a(this,W,"f")[e]||(a(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,re,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,re,!0,"f"),await a(this,Ve,"f")}get currentMessage(){return a(this,K,"f")}async finalMessage(){return await this.done(),a(this,F,"m",lr).call(this)}async finalText(){return await this.done(),a(this,F,"m",ns).call(this)}_emit(e,...t){if(a(this,Ke,"f"))return;if(e==="end")f(this,Ke,!0,"f"),a(this,Tt,"f").call(this);let r=a(this,W,"f")[e];if(r)a(this,W,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,re,"f")&&!r?.length)Promise.reject(s);a(this,Je,"f").call(this,s),a(this,Xe,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,F,"m",lr).call(this))}async _fromReadableStream(e,t){let r=t?.signal,s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s)}try{a(this,F,"m",ur).call(this),this._connected(null);let n=C.fromReadableStream(e,this.controller);for await(let o of n)a(this,F,"m",hr).call(this,o);if(n.controller.signal?.aborted)throw new E;a(this,F,"m",dr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(K=new WeakMap,ue=new WeakMap,De=new WeakMap,Mt=new WeakMap,Je=new WeakMap,Ve=new WeakMap,Tt=new WeakMap,Xe=new WeakMap,W=new WeakMap,Ke=new WeakMap,At=new WeakMap,It=new WeakMap,re=new WeakMap,$t=new WeakMap,Ct=new WeakMap,Ge=new WeakMap,Ot=new WeakMap,F=new WeakSet,lr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ns=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter((r)=>r.type==="text").map((r)=>r.text);if(t.length===0)throw new m("stream ended without producing a content block with type=text");return t.join(" ")},ur=function(){if(this.ended)return;f(this,K,void 0,"f")},hr=function(t){if(this.ended)return;let r=a(this,F,"m",os).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text")this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{if(s.type==="text")this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{if(cs(s)&&s.input)this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{if(s.type==="thinking")this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{if(s.type==="thinking")this._emit("signature",s.signature);break}case"compaction_delta":{if(s.type==="compaction"&&s.content)this._emit("compaction",s.content);break}default:ls(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(ar(r,a(this,ue,"f"),{logger:a(this,Ge,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,K,r,"f");break}case"content_block_start":case"message_delta":break}},dr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,K,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,K,void 0,"f"),ar(t,a(this,ue,"f"),{logger:a(this,Ge,"f")})},os=function(t){let r=a(this,K,"f");if(t.type==="message_start"){if(r)throw new m(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new m(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":if(r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null)r.usage.input_tokens=t.usage.input_tokens;if(t.usage.cache_creation_input_tokens!=null)r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens;if(t.usage.cache_read_input_tokens!=null)r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens;if(t.usage.server_tool_use!=null)r.usage.server_tool_use=t.usage.server_tool_use;if(t.usage.iterations!=null)r.usage.iterations=t.usage.iterations;return r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text")r.content[t.index]={...s,text:(s.text||"")+t.delta.text};break}case"citations_delta":{if(s?.type==="text")r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]};break}case"input_json_delta":{if(s&&cs(s)){let n=s[is]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,is,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Et(n)}catch(c){let i=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${n}`);a(this,Ot,"f").call(this,i)}r.content[t.index]=o}break}case"thinking_delta":{if(s?.type==="thinking")r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking};break}case"signature_delta":{if(s?.type==="thinking")r.content[t.index]={...s,signature:t.delta.signature};break}case"compaction_delta":{if(s?.type==="compaction")r.content[t.index]={...s,content:(s.content||"")+t.delta.content};break}default:ls(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ls(e){}class he extends Error{constructor(e){let t=typeof e==="string"?e:e.map((r)=>{if(r.type==="text")return r.text;return`[${r.type}]`}).join(" ");super(t);this.name="ToolError",this.content=e}}var us=1e5,hs=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
11
11
|
1. Task Overview
|
|
12
12
|
The user's core request and success criteria
|
|
13
13
|
Any clarifications or constraints they specified
|
|
@@ -38,8 +38,8 @@ If you understand the risks and have appropriate mitigations in place,
|
|
|
38
38
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
39
39
|
|
|
40
40
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
41
|
-
`);this.baseURL=n.baseURL,this.timeout=n.timeout??Sr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=Qt(n.logLevel,"ClientOptions.logLevel",this)??Qt(ft("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??jr(),f(this,Ut,Hr,"f"),this._options=n,this.apiKey=typeof t==="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization"))return;if(this.apiKey&&e.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&e.get("authorization"))return;if(t.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null)return;return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null)return;return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Wr(e)}getUserAgent(){return`${this.constructor.name}/JS ${V}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jt()}`}makeStatusError(e,t,r,s){return k.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,xr,"m",ks).call(this)&&r||this.baseURL,n=Ar(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!Kt(o)||!Kt(c))t={...c,...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128000>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Z(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:c,timeout:i}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:c,options:s});let h="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(R(this).debug(`[${h}] sending request`,H({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new E;let _=new AbortController,l=await this.fetchWithTimeout(c,o,i,_).catch(ye),p=Date.now();if(l instanceof globalThis.Error){let N=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new E;let L=U(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return R(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${N}`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${N})`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),this.retryRequest(s,t,r??h);if(R(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),L)throw new we;throw new Y({cause:l})}let w=[...l.headers.entries()].filter(([N])=>N==="request-id").map(([N,L])=>", "+N+": "+JSON.stringify(L)).join(""),v=`[${h}${b}${w}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${p-g}ms`;if(!l.ok){let N=await this.shouldRetry(l);if(t&&N){let pt=`retrying, ${t} attempts remaining`;return await Ur(l.body),R(this).info(`${v} - ${pt}`),R(this).debug(`[${h}] response error (${pt})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),this.retryRequest(s,t,r??h,l.headers)}let L=N?"error; no more retries left":"error; not retryable";R(this).info(`${v} - ${L}`);let Er=await l.text().catch((pt)=>ye(pt).message),Mr=gt(Er),Tr=Mr?void 0:Er;throw R(this).debug(`[${h}] response error (${L})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:Tr,durationMs:Date.now()-g})),this.makeStatusError(l.status,Mr,Tr,l.headers)}return R(this).info(v),R(this).debug(`[${h}] response start`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),{response:l,options:s,controller:_,requestLogID:h,retryOfRequestLogID:r,startTime:g}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new St(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...c}=t||{},i=this._makeAbort(s);if(n)n.addEventListener("abort",i,{once:!0});let h=setTimeout(i,r),b=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...b?{duplex:"half"}:{},method:"GET",...c};if(o)g.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(h)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let i=parseFloat(o);if(!Number.isNaN(i))n=i}let c=s?.get("retry-after");if(c&&!n){let i=parseFloat(c);if(!Number.isNaN(i))n=i*1000;else n=Date.parse(c)-Date.now()}if(n===void 0){let i=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Or(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),c=1-Math.random()*0.25;return o*c*1000}calculateNonstreamingTimeout(e,t){if(3600000*e/128000>600000||t!=null&&e>t)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:c}=r,i=this.buildURL(n,o,c);if("timeout"in r)$r("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:b}=this.buildBody({options:r}),g=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:g,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=u([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Br(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:_t(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return a(this,Ut,"f").call(this,{body:e,headers:r})}}Sr=S,Ut=new WeakMap,xr=new WeakSet,ks=function(){return this.baseURL!=="https://api.anthropic.com"};S.Anthropic=Sr;S.HUMAN_PROMPT=Ps;S.AI_PROMPT=Rs;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=m;S.APIError=k;S.APIConnectionError=Y;S.APIConnectionTimeoutError=we;S.APIUserAbortError=E;S.NotFoundError=Pe;S.ConflictError=Re;S.RateLimitError=Ee;S.BadRequestError=xe;S.AuthenticationError=Se;S.InternalServerError=Me;S.PermissionDeniedError=ke;S.UnprocessableEntityError=ve;S.toFile=kt;class j extends S{constructor(){super(...arguments);this.completions=new ge(this),this.messages=new ae(this),this.models=new be(this),this.beta=new M(this)}}j.Completions=ge;j.Messages=ae;j.Models=be;j.Beta=M;function Es(e,t){if(e)return e;if(lr("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function Tn(e,t,r){let s=Es(t,r);if(s==="none")return{retention:s};let n=s==="long"&&Dt(e).supportsLongCacheRetention?"1h":void 0;return{retention:s,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}var An="2.1.75",In=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],$n=new Map(In.map((e)=>[e.toLowerCase(),e])),Wt=(e)=>$n.get(e.toLowerCase())??e,Cn=(e,t)=>{if(t&&t.length>0){let r=e.toLowerCase(),s=t.find((n)=>n.name.toLowerCase()===r);if(s)return s.name}return e};function On(e){if(!e.some((n)=>n.type==="image"))return qe(e.map((n)=>n.text).join(`
|
|
41
|
+
`);this.baseURL=n.baseURL,this.timeout=n.timeout??Sr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=Qt(n.logLevel,"ClientOptions.logLevel",this)??Qt(ft("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??jr(),f(this,Ut,Hr,"f"),this._options=n,this.apiKey=typeof t==="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization"))return;if(this.apiKey&&e.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&e.get("authorization"))return;if(t.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null)return;return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null)return;return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Wr(e)}getUserAgent(){return`${this.constructor.name}/JS ${V}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jt()}`}makeStatusError(e,t,r,s){return k.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,xr,"m",ks).call(this)&&r||this.baseURL,n=Ar(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!Kt(o)||!Kt(c))t={...c,...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128000>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Z(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:c,timeout:i}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:c,options:s});let h="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(R(this).debug(`[${h}] sending request`,H({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new E;let _=new AbortController,l=await this.fetchWithTimeout(c,o,i,_).catch(ye),p=Date.now();if(l instanceof globalThis.Error){let N=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new E;let L=U(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return R(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${N}`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${N})`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),this.retryRequest(s,t,r??h);if(R(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),R(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),L)throw new we;throw new Y({cause:l})}let w=[...l.headers.entries()].filter(([N])=>N==="request-id").map(([N,L])=>", "+N+": "+JSON.stringify(L)).join(""),v=`[${h}${b}${w}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${p-g}ms`;if(!l.ok){let N=await this.shouldRetry(l);if(t&&N){let pt=`retrying, ${t} attempts remaining`;return await Ur(l.body),R(this).info(`${v} - ${pt}`),R(this).debug(`[${h}] response error (${pt})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),this.retryRequest(s,t,r??h,l.headers)}let L=N?"error; no more retries left":"error; not retryable";R(this).info(`${v} - ${L}`);let Er=await l.text().catch((pt)=>ye(pt).message),Mr=gt(Er),Tr=Mr?void 0:Er;throw R(this).debug(`[${h}] response error (${L})`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:Tr,durationMs:Date.now()-g})),this.makeStatusError(l.status,Mr,Tr,l.headers)}return R(this).info(v),R(this).debug(`[${h}] response start`,H({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),{response:l,options:s,controller:_,requestLogID:h,retryOfRequestLogID:r,startTime:g}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new St(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...c}=t||{},i=this._makeAbort(s);if(n)n.addEventListener("abort",i,{once:!0});let h=setTimeout(i,r),b=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...b?{duplex:"half"}:{},method:"GET",...c};if(o)g.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(h)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let i=parseFloat(o);if(!Number.isNaN(i))n=i}let c=s?.get("retry-after");if(c&&!n){let i=parseFloat(c);if(!Number.isNaN(i))n=i*1000;else n=Date.parse(c)-Date.now()}if(n===void 0){let i=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Or(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),c=1-Math.random()*0.25;return o*c*1000}calculateNonstreamingTimeout(e,t){if(3600000*e/128000>600000||t!=null&&e>t)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:c}=r,i=this.buildURL(n,o,c);if("timeout"in r)$r("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:b}=this.buildBody({options:r}),g=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:g,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=u([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Br(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:_t(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return a(this,Ut,"f").call(this,{body:e,headers:r})}}Sr=S,Ut=new WeakMap,xr=new WeakSet,ks=function(){return this.baseURL!=="https://api.anthropic.com"};S.Anthropic=Sr;S.HUMAN_PROMPT=Ps;S.AI_PROMPT=Rs;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=m;S.APIError=k;S.APIConnectionError=Y;S.APIConnectionTimeoutError=we;S.APIUserAbortError=E;S.NotFoundError=Pe;S.ConflictError=Re;S.RateLimitError=Ee;S.BadRequestError=xe;S.AuthenticationError=Se;S.InternalServerError=Me;S.PermissionDeniedError=ke;S.UnprocessableEntityError=ve;S.toFile=kt;class j extends S{constructor(){super(...arguments);this.completions=new ge(this),this.messages=new ae(this),this.models=new be(this),this.beta=new M(this)}}j.Completions=ge;j.Messages=ae;j.Models=be;j.Beta=M;function Es(e,t){if(e)return e;if(cr("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function Tn(e,t,r){let s=Es(t,r);if(s==="none")return{retention:s};let n=s==="long"&&Dt(e).supportsLongCacheRetention?"1h":void 0;return{retention:s,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}var An="2.1.75",In=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],$n=new Map(In.map((e)=>[e.toLowerCase(),e])),Wt=(e)=>$n.get(e.toLowerCase())??e,Cn=(e,t)=>{if(t&&t.length>0){let r=e.toLowerCase(),s=t.find((n)=>n.name.toLowerCase()===r);if(s)return s.name}return e};function On(e){if(!e.some((n)=>n.type==="image"))return qe(e.map((n)=>n.text).join(`
|
|
42
42
|
`));let r=e.map((n)=>{if(n.type==="text")return{type:"text",text:qe(n.text)};return{type:"image",source:{type:"base64",media_type:n.mimeType,data:n.data}}});if(!r.some((n)=>n.type==="text"))r.unshift({type:"text",text:"(see attached image)"});return r}var Nn="fine-grained-tool-streaming-2025-05-14",Ln="interleaved-thinking-2025-05-14";function Dt(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1,supportsStrictTools:e.compat?.supportsStrictTools??!1,supportsToolReferences:e.compat?.supportsToolReferences??Fn(e)}}function Fn(e){if(e.provider!=="anthropic"||e.id.includes("haiku"))return!1;let t=e.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);if(!t)return!1;let r=Number(t[1]),s=t[2]&&t[2].length<8?Number(t[2]):0;return r>4||r===4&&s>=5}function kr(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Pr(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,n]of Object.entries(e))if(s.toLowerCase()===r&&n!==null&&n.trim().length>0)return!0;return!1}function Ms(e,t,r){if(t)return;if(Pr(r,"authorization")||Pr(r,"x-api-key")||Pr(r,"cf-aig-authorization"))return;throw Error(`No API key for provider: ${e}`)}var qn=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function Ts(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
43
43
|
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Rr(e,t){if(e==="")return Ts(t);if(t.raw.push(e),e.startsWith(":"))return null;let r=e.indexOf(":"),s=r===-1?e:e.slice(0,r),n=r===-1?"":e.slice(r+1);if(n.startsWith(" "))n=n.slice(1);if(s==="event")t.event=n;else if(s==="data")t.data.push(n);return null}function Bn(e){let t=e.indexOf("\r"),r=e.indexOf(`
|
|
44
44
|
`);if(t===-1)return r;if(r===-1)return t;return Math.min(t,r)}function Ht(e){let t=Bn(e);if(t===-1)return null;let r=t+1;if(e[t]==="\r"&&e[r]===`
|
|
45
|
-
`)r+=1;return{line:e.slice(0,t),rest:e.slice(r)}}async function*jn(e,t){let r=e.getReader(),s=new TextDecoder,n={event:null,data:[],raw:[]},o="";try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{value:h,done:b}=await r.read();if(b)break;o+=s.decode(h,{stream:!0});let g=Ht(o);while(g){o=g.rest;let _=Rr(g.line,n);if(_)yield _;g=Ht(o)}}o+=s.decode();let c=Ht(o);while(c){o=c.rest;let h=Rr(c.line,n);if(h)yield h;c=Ht(o)}if(o.length>0){let h=Rr(o,n);if(h)yield h}let i=Ts(n);if(i)yield i}finally{r.releaseLock()}}async function*Un(e,t){if(!e.body)throw Error("Attempted to iterate over an Anthropic response with no body");let r=!1,s=!1;for await(let n of jn(e.body,t)){if(n.event==="error")throw Error(n.data);if(!qn.has(n.event??""))continue;try{let o=Xd(n.data);if(o.type==="message_start")r=!0;else if(o.type==="message_stop")s=!0;yield o}catch(o){let c=o instanceof Error?o.message:String(o);throw Error(`Could not parse Anthropic SSE event ${n.event}: ${c}; data=${n.data}; raw=${n.raw.join("\\n")}`)}}if(r&&!s)throw Error("Anthropic stream ended before message_stop")}var vr=(e,t,r)=>{let s=new Yt;return(async()=>{let n={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,c;if(r?.client)o=r.client,c=!1;else{let l=r?.apiKey;Ms(e.provider,l,r?.headers);let p;if(e.provider==="github-copilot"){let L=La(t.messages);p=Za({messages:t.messages,hasImages:L})}let v=Es(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,N=Dn(e,l,r?.interleavedThinking??!0,Gn(e,t),r?.headers,p,v);o=N.client,c=N.isOAuthToken}let i=Jn(e,t,c,r),h=await r?.onPayload?.(i,e);if(h!==void 0)i=h;let b={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},g=await ss(()=>o.messages.create({...i,stream:!0},b).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:g.status,headers:ln(g.headers)},e),s.push({type:"start",partial:n});let _=n.content;for await(let l of Un(g,r?.signal))if(l.type==="message_start")n.responseId=l.message.id,n.usage.input=l.message.usage.input_tokens||0,n.usage.output=l.message.usage.output_tokens||0,n.usage.cacheRead=l.message.usage.cache_read_input_tokens||0,n.usage.cacheWrite=l.message.usage.cache_creation_input_tokens||0,n.usage.cacheWrite1h=l.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,cn(e,n.usage);else if(l.type==="content_block_start"){if(l.content_block.type==="text"){let p={type:"text",text:"",index:l.index};n.content.push(p),s.push({type:"text_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="thinking"){let p={type:"thinking",thinking:"",thinkingSignature:"",index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="redacted_thinking"){let p={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:l.content_block.data,redacted:!0,index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="tool_use"){let p={type:"toolCall",id:l.content_block.id,name:c?Cn(l.content_block.name,t.tools):l.content_block.name,arguments:l.content_block.input??{},partialJson:"",index:l.index};n.content.push(p),s.push({type:"toolcall_start",contentIndex:n.content.length-1,partial:n})}}else if(l.type==="content_block_delta"){if(l.delta.type==="text_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="text")w.text+=l.delta.text,s.push({type:"text_delta",contentIndex:p,delta:l.delta.text,partial:n})}else if(l.delta.type==="thinking_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinking+=l.delta.thinking,s.push({type:"thinking_delta",contentIndex:p,delta:l.delta.thinking,partial:n})}else if(l.delta.type==="input_json_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="toolCall")w.partialJson+=l.delta.partial_json,w.arguments=Yr(w.partialJson),s.push({type:"toolcall_delta",contentIndex:p,delta:l.delta.partial_json,partial:n})}else if(l.delta.type==="signature_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinkingSignature=w.thinkingSignature||"",w.thinkingSignature+=l.delta.signature}}else if(l.type==="content_block_stop"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w){if(delete w.index,w.type==="text")s.push({type:"text_end",contentIndex:p,content:w.text,partial:n});else if(w.type==="thinking")s.push({type:"thinking_end",contentIndex:p,content:w.thinking,partial:n});else if(w.type==="toolCall")w.arguments=Yr(w.partialJson),delete w.partialJson,s.push({type:"toolcall_end",contentIndex:p,toolCall:w,partial:n})}}else if(l.type==="message_delta"){if(l.delta.stop_reason){let p=zn(l.delta.stop_reason,l.delta.stop_details);if(n.stopReason=p.stopReason,p.errorMessage)n.errorMessage=p.errorMessage}if(l.usage){if(l.usage.input_tokens!=null)n.usage.input=l.usage.input_tokens;if(l.usage.output_tokens!=null)n.usage.output=l.usage.output_tokens;if(l.usage.cache_read_input_tokens!=null)n.usage.cacheRead=l.usage.cache_read_input_tokens;if(l.usage.cache_creation_input_tokens!=null)n.usage.cacheWrite=l.usage.cache_creation_input_tokens;let p=l.usage.output_tokens_details?.thinking_tokens;if(p!=null)n.usage.reasoning=p}n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,cn(e,n.usage)}if(r?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="aborted"||n.stopReason==="error")throw Error(n.errorMessage||"An unknown error occurred");s.push({type:"done",reason:n.stopReason,message:n}),s.end()}catch(o){for(let c of n.content)delete c.index,delete c.partialJson;n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=o instanceof Error?o.message:JSON.stringify(o),s.push({type:"error",reason:n.stopReason,error:n}),s.end()}})(),s};function Hn(e,t){let r=t?e.thinkingLevelMap?.[t]:void 0;if(typeof r==="string")return r;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var Gl=(e,t,r)=>{Ms(e.provider,r?.apiKey,r?.headers);let s=Cr(e,t,r,r?.apiKey);if(!r?.reasoning)return vr(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=Hn(e,r.reasoning);return vr(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=sm(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=Jd(e,t,n.maxTokens);return vr(e,t,{...s,maxTokens:o,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(n.thinkingBudget,Math.max(0,o-1024))})};function Wn(e){return e.includes("sk-ant-oat")}function Dn(e,t,r,s,n,o,c){let i=r&&e.compat?.forceAdaptiveThinking!==!0,h=[];if(s)h.push(Nn);if(i)h.push(Ln);if(e.provider==="github-copilot")return{client:new j({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},e.headers,o,n)}),isOAuthToken:!1};if(t&&Wn(t))return{client:new j({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${An}`,"x-app":"cli"},e.headers,n)}),isOAuthToken:!0};let b=c&&Dt(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},g=kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},b,e.headers,n);return{client:new j({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:g}),isOAuthToken:!1}}function Jn(e,t,r,s){let{cacheControl:n}=Tn(e,s?.cacheRetention,s?.env),o=Dt(e),c=fo(t.messages,e,Vn),i=r?Wt:(p)=>p,h=Fa({...t,messages:c},o.supportsToolReferences,i),b=h.immediate,g=[...h.deferred.values()];if(b.length===0&&g.length>0)b=g,g=[];let _=new Set(g.map((p)=>i(p.name))),l={model:e.id,messages:Kn(c,r,n,o.allowEmptySignature,_,i),max_tokens:s?.maxTokens??e.maxTokens,stream:!0};if(r){if(l.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...n?{cache_control:n}:{}}],t.systemPrompt)l.system.push({type:"text",text:qe(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:qe(t.systemPrompt),...n?{cache_control:n}:{}}];if(s?.temperature!==void 0&&!s?.thinkingEnabled&&o.supportsTemperature)l.temperature=s.temperature;if(b.length>0||g.length>0)l.tools=[...vs(b,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...vs(g,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)];if(e.reasoning){if(s?.thinkingEnabled){let p=s.thinkingDisplay??"summarized";if(e.compat?.forceAdaptiveThinking===!0){if(l.thinking={type:"adaptive",display:p},s.effort)l.output_config=s.effort==="xhigh"?{effort:s.effort}:{effort:s.effort}}else l.thinking={type:"enabled",budget_tokens:s.thinkingBudgetTokens||1024,display:p}}else if(s?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null)l.thinking={type:"disabled"}}if(s?.metadata){let p=s.metadata.user_id;if(typeof p==="string")l.metadata={user_id:p}}if(s?.toolChoice)if(typeof s.toolChoice==="string")l.tool_choice={type:s.toolChoice};else l.tool_choice=s.toolChoice;return l}function Vn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Xn(e,t,r,s,n){let o=[];for(let i of e.addedToolNames??[]){let h=n(i);if(!r.has(h)||s.has(h))continue;s.add(h),o.push({type:"tool_reference",tool_name:t?Wt(i):i})}let c=On(e.content);return{toolResult:{type:"tool_result",tool_use_id:e.toolCallId,content:o.length>0?o:c,is_error:e.isError},siblingContent:o.length===0?[]:typeof c==="string"?[{type:"text",text:c}]:c}}function Kn(e,t,r,s=!1,n=new Set,o=(c)=>c){let c=[],i=new Set;for(let h=0;h<e.length;h++){let b=e[h];if(b.role==="user")if(typeof b.content==="string"){if(b.content.trim().length>0)c.push({role:"user",content:qe(b.content)})}else{let _=b.content.map((l)=>{if(l.type==="text")return{type:"text",text:qe(l.text)};else return{type:"image",source:{type:"base64",media_type:l.mimeType,data:l.data}}}).filter((l)=>{if(l.type==="text")return l.text.trim().length>0;return!0});if(_.length===0)continue;c.push({role:"user",content:_})}else if(b.role==="assistant"){let g=[];for(let _ of b.content)if(_.type==="text"){if(_.text.trim().length===0)continue;g.push({type:"text",text:qe(_.text)})}else if(_.type==="thinking"){if(_.redacted){g.push({type:"redacted_thinking",data:_.thinkingSignature});continue}let l=_.thinkingSignature,p=!!l&&l.trim().length>0;if(_.thinking.trim().length===0&&!p)continue;if(!p)g.push(s?{type:"thinking",thinking:qe(_.thinking),signature:""}:{type:"text",text:qe(_.thinking)});else g.push({type:"thinking",thinking:qe(_.thinking),signature:l})}else if(_.type==="toolCall")g.push({type:"tool_use",id:_.id,name:t?Wt(_.name):_.name,input:_.arguments??{}});if(g.length===0)continue;c.push({role:"assistant",content:g})}else if(b.role==="toolResult"){let g=[],_=[],l=h;while(l<e.length&&e[l].role==="toolResult"){let p=Xn(e[l],t,n,i,o);g.push(p.toolResult),_.push(...p.siblingContent),l++}h=l-1,c.push({role:"user",content:[...g,..._]})}}if(r&&c.length>0){let h=c[c.length-1];if(h.role==="user"){if(Array.isArray(h.content)){let b=h.content[h.content.length-1];if(b&&(b.type==="text"||b.type==="image"||b.type==="tool_result"))b.cache_control=r}else if(typeof h.content==="string")h.content=[{type:"text",text:h.content,cache_control:r}]}}return c}function Gn(e,t){return!!t.tools?.length&&!Dt(e).supportsEagerToolInputStreaming}function vs(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=uo(c,s),b=c.parameters,g={type:"object",properties:b.properties??{},required:b.required??[]},_=h===!0?{...c.parameters,...g}:g;return{name:t?Wt(c.name):c.name,description:c.description,...r?{eager_input_streaming:!0}:{},...h===!0?{strict:!0}:{},input_schema:_,...o?{defer_loading:!0}:{},...n&&i===e.length-1?{cache_control:n}:{}}})}function zn(e,t){switch(e){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error"};default:throw Error(`Unhandled stop reason: ${e}`)}}export{vr as stream,Gl as streamSimple};
|
|
45
|
+
`)r+=1;return{line:e.slice(0,t),rest:e.slice(r)}}async function*jn(e,t){let r=e.getReader(),s=new TextDecoder,n={event:null,data:[],raw:[]},o="";try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{value:h,done:b}=await r.read();if(b)break;o+=s.decode(h,{stream:!0});let g=Ht(o);while(g){o=g.rest;let _=Rr(g.line,n);if(_)yield _;g=Ht(o)}}o+=s.decode();let c=Ht(o);while(c){o=c.rest;let h=Rr(c.line,n);if(h)yield h;c=Ht(o)}if(o.length>0){let h=Rr(o,n);if(h)yield h}let i=Ts(n);if(i)yield i}finally{r.releaseLock()}}async function*Un(e,t){if(!e.body)throw Error("Attempted to iterate over an Anthropic response with no body");let r=!1,s=!1;for await(let n of jn(e.body,t)){if(n.event==="error")throw Error(n.data);if(!qn.has(n.event??""))continue;try{let o=tf(n.data);if(o.type==="message_start")r=!0;else if(o.type==="message_stop")s=!0;yield o}catch(o){let c=o instanceof Error?o.message:String(o);throw Error(`Could not parse Anthropic SSE event ${n.event}: ${c}; data=${n.data}; raw=${n.raw.join("\\n")}`)}}if(r&&!s)throw Error("Anthropic stream ended before message_stop")}var vr=(e,t,r)=>{let s=new Yt;return(async()=>{let n={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,c;if(r?.client)o=r.client,c=!1;else{let l=r?.apiKey;Ms(e.provider,l,r?.headers);let p;if(e.provider==="github-copilot"){let L=La(t.messages);p=Za({messages:t.messages,hasImages:L})}let v=Es(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,N=Dn(e,l,r?.interleavedThinking??!0,Gn(e,t),r?.headers,p,v);o=N.client,c=N.isOAuthToken}let i=Jn(e,t,c,r),h=await r?.onPayload?.(i,e);if(h!==void 0)i=h;let b={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},g=await as(()=>o.messages.create({...i,stream:!0},b).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:g.status,headers:ln(g.headers)},e),s.push({type:"start",partial:n});let _=n.content;for await(let l of Un(g,r?.signal))if(l.type==="message_start")n.responseId=l.message.id,n.usage.input=l.message.usage.input_tokens||0,n.usage.output=l.message.usage.output_tokens||0,n.usage.cacheRead=l.message.usage.cache_read_input_tokens||0,n.usage.cacheWrite=l.message.usage.cache_creation_input_tokens||0,n.usage.cacheWrite1h=l.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,cn(e,n.usage);else if(l.type==="content_block_start"){if(l.content_block.type==="text"){let p={type:"text",text:"",index:l.index};n.content.push(p),s.push({type:"text_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="thinking"){let p={type:"thinking",thinking:"",thinkingSignature:"",index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="redacted_thinking"){let p={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:l.content_block.data,redacted:!0,index:l.index};n.content.push(p),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="tool_use"){let p={type:"toolCall",id:l.content_block.id,name:c?Cn(l.content_block.name,t.tools):l.content_block.name,arguments:l.content_block.input??{},partialJson:"",index:l.index};n.content.push(p),s.push({type:"toolcall_start",contentIndex:n.content.length-1,partial:n})}}else if(l.type==="content_block_delta"){if(l.delta.type==="text_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="text")w.text+=l.delta.text,s.push({type:"text_delta",contentIndex:p,delta:l.delta.text,partial:n})}else if(l.delta.type==="thinking_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinking+=l.delta.thinking,s.push({type:"thinking_delta",contentIndex:p,delta:l.delta.thinking,partial:n})}else if(l.delta.type==="input_json_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="toolCall")w.partialJson+=l.delta.partial_json,w.arguments=Yr(w.partialJson),s.push({type:"toolcall_delta",contentIndex:p,delta:l.delta.partial_json,partial:n})}else if(l.delta.type==="signature_delta"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w&&w.type==="thinking")w.thinkingSignature=w.thinkingSignature||"",w.thinkingSignature+=l.delta.signature}}else if(l.type==="content_block_stop"){let p=_.findIndex((v)=>v.index===l.index),w=_[p];if(w){if(delete w.index,w.type==="text")s.push({type:"text_end",contentIndex:p,content:w.text,partial:n});else if(w.type==="thinking")s.push({type:"thinking_end",contentIndex:p,content:w.thinking,partial:n});else if(w.type==="toolCall")w.arguments=Yr(w.partialJson),delete w.partialJson,s.push({type:"toolcall_end",contentIndex:p,toolCall:w,partial:n})}}else if(l.type==="message_delta"){if(l.delta.stop_reason){let p=zn(l.delta.stop_reason,l.delta.stop_details);if(n.stopReason=p.stopReason,p.errorMessage)n.errorMessage=p.errorMessage}if(l.usage){if(l.usage.input_tokens!=null)n.usage.input=l.usage.input_tokens;if(l.usage.output_tokens!=null)n.usage.output=l.usage.output_tokens;if(l.usage.cache_read_input_tokens!=null)n.usage.cacheRead=l.usage.cache_read_input_tokens;if(l.usage.cache_creation_input_tokens!=null)n.usage.cacheWrite=l.usage.cache_creation_input_tokens;let p=l.usage.output_tokens_details?.thinking_tokens;if(p!=null)n.usage.reasoning=p}n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,cn(e,n.usage)}if(r?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="aborted"||n.stopReason==="error")throw Error(n.errorMessage||"An unknown error occurred");s.push({type:"done",reason:n.stopReason,message:n}),s.end()}catch(o){for(let c of n.content)delete c.index,delete c.partialJson;n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=o instanceof Error?o.message:JSON.stringify(o),s.push({type:"error",reason:n.stopReason,error:n}),s.end()}})(),s};function Hn(e,t){let r=t?e.thinkingLevelMap?.[t]:void 0;if(typeof r==="string")return r;switch(t){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var Gl=(e,t,r)=>{Ms(e.provider,r?.apiKey,r?.headers);let s=Cr(e,t,r,r?.apiKey);if(!r?.reasoning)return vr(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=Hn(e,r.reasoning);return vr(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=am(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=ef(e,t,n.maxTokens);return vr(e,t,{...s,maxTokens:o,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(n.thinkingBudget,Math.max(0,o-1024))})};function Wn(e){return e.includes("sk-ant-oat")}function Dn(e,t,r,s,n,o,c){let i=r&&e.compat?.forceAdaptiveThinking!==!0,h=[];if(s)h.push(Nn);if(i)h.push(Ln);if(e.provider==="github-copilot")return{client:new j({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},e.headers,o,n)}),isOAuthToken:!1};if(t&&Wn(t))return{client:new j({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${An}`,"x-app":"cli"},e.headers,n)}),isOAuthToken:!0};let b=c&&Dt(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},g=kr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},b,e.headers,n);return{client:new j({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:g}),isOAuthToken:!1}}function Jn(e,t,r,s){let{cacheControl:n}=Tn(e,s?.cacheRetention,s?.env),o=Dt(e),c=fo(t.messages,e,Vn),i=r?Wt:(p)=>p,h=Fa({...t,messages:c},o.supportsToolReferences,i),b=h.immediate,g=[...h.deferred.values()];if(b.length===0&&g.length>0)b=g,g=[];let _=new Set(g.map((p)=>i(p.name))),l={model:e.id,messages:Kn(c,r,n,o.allowEmptySignature,_,i),max_tokens:s?.maxTokens??e.maxTokens,stream:!0};if(r){if(l.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...n?{cache_control:n}:{}}],t.systemPrompt)l.system.push({type:"text",text:qe(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:qe(t.systemPrompt),...n?{cache_control:n}:{}}];if(s?.temperature!==void 0&&!s?.thinkingEnabled&&o.supportsTemperature)l.temperature=s.temperature;if(b.length>0||g.length>0)l.tools=[...vs(b,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...vs(g,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)];if(e.reasoning){if(s?.thinkingEnabled){let p=s.thinkingDisplay??"summarized";if(e.compat?.forceAdaptiveThinking===!0){if(l.thinking={type:"adaptive",display:p},s.effort)l.output_config=s.effort==="xhigh"?{effort:s.effort}:{effort:s.effort}}else l.thinking={type:"enabled",budget_tokens:s.thinkingBudgetTokens||1024,display:p}}else if(s?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null)l.thinking={type:"disabled"}}if(s?.metadata){let p=s.metadata.user_id;if(typeof p==="string")l.metadata={user_id:p}}if(s?.toolChoice)if(typeof s.toolChoice==="string")l.tool_choice={type:s.toolChoice};else l.tool_choice=s.toolChoice;return l}function Vn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Xn(e,t,r,s,n){let o=[];for(let i of e.addedToolNames??[]){let h=n(i);if(!r.has(h)||s.has(h))continue;s.add(h),o.push({type:"tool_reference",tool_name:t?Wt(i):i})}let c=On(e.content);return{toolResult:{type:"tool_result",tool_use_id:e.toolCallId,content:o.length>0?o:c,is_error:e.isError},siblingContent:o.length===0?[]:typeof c==="string"?[{type:"text",text:c}]:c}}function Kn(e,t,r,s=!1,n=new Set,o=(c)=>c){let c=[],i=new Set;for(let h=0;h<e.length;h++){let b=e[h];if(b.role==="user")if(typeof b.content==="string"){if(b.content.trim().length>0)c.push({role:"user",content:qe(b.content)})}else{let _=b.content.map((l)=>{if(l.type==="text")return{type:"text",text:qe(l.text)};else return{type:"image",source:{type:"base64",media_type:l.mimeType,data:l.data}}}).filter((l)=>{if(l.type==="text")return l.text.trim().length>0;return!0});if(_.length===0)continue;c.push({role:"user",content:_})}else if(b.role==="assistant"){let g=[];for(let _ of b.content)if(_.type==="text"){if(_.text.trim().length===0)continue;g.push({type:"text",text:qe(_.text)})}else if(_.type==="thinking"){if(_.redacted){g.push({type:"redacted_thinking",data:_.thinkingSignature});continue}let l=_.thinkingSignature,p=!!l&&l.trim().length>0;if(_.thinking.trim().length===0&&!p)continue;if(!p)g.push(s?{type:"thinking",thinking:qe(_.thinking),signature:""}:{type:"text",text:qe(_.thinking)});else g.push({type:"thinking",thinking:qe(_.thinking),signature:l})}else if(_.type==="toolCall")g.push({type:"tool_use",id:_.id,name:t?Wt(_.name):_.name,input:_.arguments??{}});if(g.length===0)continue;c.push({role:"assistant",content:g})}else if(b.role==="toolResult"){let g=[],_=[],l=h;while(l<e.length&&e[l].role==="toolResult"){let p=Xn(e[l],t,n,i,o);g.push(p.toolResult),_.push(...p.siblingContent),l++}h=l-1,c.push({role:"user",content:[...g,..._]})}}if(r&&c.length>0){let h=c[c.length-1];if(h.role==="user"){if(Array.isArray(h.content)){let b=h.content[h.content.length-1];if(b&&(b.type==="text"||b.type==="image"||b.type==="tool_result"))b.cache_control=r}else if(typeof h.content==="string")h.content=[{type:"text",text:h.content,cache_control:r}]}}return c}function Gn(e,t){return!!t.tools?.length&&!Dt(e).supportsEagerToolInputStreaming}function vs(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=uo(c,s),b=c.parameters,g={type:"object",properties:b.properties??{},required:b.required??[]},_=h===!0?{...c.parameters,...g}:g;return{name:t?Wt(c.name):c.name,description:c.description,...r?{eager_input_streaming:!0}:{},...h===!0?{strict:!0}:{},input_schema:_,...o?{defer_loading:!0}:{},...n&&i===e.length-1?{cache_control:n}:{}}})}function zn(e,t){switch(e){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:t?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error"};default:throw Error(`Unhandled stop reason: ${e}`)}}export{vr as stream,Gl as streamSimple};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function c(e){if(!(e instanceof Error)||!("status"in e)||!("headers"in e))return!1;return(e.status===void 0||typeof e.status==="number")&&(e.headers===void 0||e.headers instanceof Headers)}function d(e){let t=e.headers?.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===void 0)return!0;return e.status===408||e.status===409||e.status===429||typeof e.status==="number"&&e.status>=500}function o(e,t,a){let r=t??60000;if(r>0&&e>r)throw Error(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s). ${a}`);return e}function l(e,t,a){let r=e.headers?.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(!Number.isNaN(s))return o(s,a,e.message)}let n=e.headers?.get("retry-after");if(n){let s=Number.parseFloat(n),f=Number.isNaN(s)?Date.parse(n)-Date.now():s*1000;return o(f,a,e.message)}return Math.min(0.5*2**t,8)*1000*(1-Math.random()*0.25)}function i(){let e=Error("Request aborted");return e.name="AbortError",e}function m(e,t){return new Promise((a,r)=>{if(t?.aborted){r(i());return}let n=()=>{clearTimeout(u),r(i())},u=setTimeout(()=>{t?.removeEventListener("abort",n),a()},Math.max(0,e));t?.addEventListener("abort",n,{once:!0})})}async function
|
|
3
|
-
export{
|
|
2
|
+
function c(e){if(!(e instanceof Error)||!("status"in e)||!("headers"in e))return!1;return(e.status===void 0||typeof e.status==="number")&&(e.headers===void 0||e.headers instanceof Headers)}function d(e){let t=e.headers?.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===void 0)return!0;return e.status===408||e.status===409||e.status===429||typeof e.status==="number"&&e.status>=500}function o(e,t,a){let r=t??60000;if(r>0&&e>r)throw Error(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s). ${a}`);return e}function l(e,t,a){let r=e.headers?.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(!Number.isNaN(s))return o(s,a,e.message)}let n=e.headers?.get("retry-after");if(n){let s=Number.parseFloat(n),f=Number.isNaN(s)?Date.parse(n)-Date.now():s*1000;return o(f,a,e.message)}return Math.min(0.5*2**t,8)*1000*(1-Math.random()*0.25)}function i(){let e=Error("Request aborted");return e.name="AbortError",e}function m(e,t){return new Promise((a,r)=>{if(t?.aborted){r(i());return}let n=()=>{clearTimeout(u),r(i())},u=setTimeout(()=>{t?.removeEventListener("abort",n),a()},Math.max(0,e));t?.addEventListener("abort",n,{once:!0})})}async function as(e,t={}){let a=t.maxRetries??0,r=a;for(;;)try{return await e()}catch(n){if(t.signal?.aborted)throw i();if(r<=0||!c(n)||!d(n))throw n;let u=a-r;r--,await m(l(n,u,t.maxRetryDelayMs),t.signal)}}
|
|
3
|
+
export{as};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Dt}from"./chunk-
|
|
2
|
+
import{Dt}from"./chunk-s30fjvzs.js";import{$e}from"./chunk-781990k7.js";import{z}from"./chunk-yqvhgtez.js";var a=z(Dt()),t=z($e());import{readFileSync as p}from"fs";var c=(e)=>async(s)=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");let{roleArn:o,roleSessionName:r,webIdentityToken:i,providerId:n,policyArns:m,policy:f,durationSeconds:g}=e,{roleAssumerWithWebIdentity:l}=e;if(!l){let{getDefaultRoleAssumerWithWebIdentity:E}=await import("./chunk-h3wr8nnk.js");l=E({...e.clientConfig,credentialProviderLogger:e.logger,parentClientConfig:{...s?.callerClientConfig,...e.parentClientConfig}},e.clientPlugins)}return l({RoleArn:o,RoleSessionName:r??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:i,ProviderId:n,PolicyArns:m,Policy:f,DurationSeconds:g})};var d="AWS_WEB_IDENTITY_TOKEN_FILE",_="AWS_ROLE_ARN",S="AWS_ROLE_SESSION_NAME",T=(e={})=>async(s)=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");let o=e?.webIdentityTokenFile??process.env[d],r=e?.roleArn??process.env[_],i=e?.roleSessionName??process.env[S];if(!o||!r)throw new t.CredentialsProviderError("Web identity configuration not specified",{logger:e.logger});let n=await c({...e,webIdentityToken:t.externalDataInterceptor?.getTokenRecord?.()[o]??p(o,{encoding:"ascii"}),roleArn:r,roleSessionName:i})(s);if(o===process.env[d])a.setCredentialFeature(n,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h");return n};export{T as fromTokenFile};
|