@shumai-one/shumai-agent 0.6.0 → 0.6.2
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-023w4q1f.js +2 -0
- package/bin/chunk-29r6a67p.js +2 -0
- package/bin/chunk-2exf93nx.js +3 -0
- package/bin/chunk-3ev1fh2w.js +3 -0
- package/bin/chunk-3kt4k4jg.js +11 -0
- package/bin/chunk-62n25c3m.js +2 -0
- package/bin/chunk-6pf9rgk6.js +2 -0
- package/bin/{chunk-yk14703k.js → chunk-7bn1mjf2.js} +2 -2
- package/bin/chunk-7pwsjw9r.js +8 -0
- package/bin/{chunk-vnn8sej7.js → chunk-847yv5m2.js} +10 -10
- package/bin/chunk-9fqyh49m.js +2 -0
- package/bin/chunk-a5rn622e.js +7 -0
- package/bin/chunk-akj1v1zj.js +5 -0
- package/bin/{chunk-w5h5ctmd.js → chunk-am25vkck.js} +2 -2
- package/bin/chunk-at5qzp08.js +7 -0
- package/bin/chunk-b2n9g75s.js +2 -0
- package/bin/chunk-b767451d.js +3 -0
- package/bin/chunk-bsxxt20c.js +2 -0
- package/bin/{chunk-yd3kbedy.js → chunk-crc78aby.js} +2 -2
- package/bin/chunk-ee8rt9we.js +2 -0
- package/bin/chunk-eh6xcwvv.js +16 -0
- package/bin/chunk-fgabndrh.js +4 -0
- package/bin/chunk-fq1tf20c.js +45 -0
- package/bin/chunk-g7ad4dw4.js +2 -0
- package/bin/chunk-g7v8pfhe.js +2 -0
- package/bin/chunk-gx33h4rt.js +3 -0
- package/bin/chunk-hnpr396w.js +12 -0
- package/bin/chunk-hssdv3mc.js +2 -0
- package/bin/chunk-m3saxrzj.js +13 -0
- package/bin/chunk-mnd4dn3q.js +2 -0
- package/bin/chunk-nmygzasv.js +2 -0
- package/bin/chunk-nwz9f1dy.js +2 -0
- package/bin/chunk-p5nhcxwg.js +3 -0
- package/bin/chunk-pbdctjg4.js +2 -0
- package/bin/chunk-pphsqcqt.js +2 -0
- package/bin/chunk-pqa01d4g.js +2 -0
- package/bin/{chunk-7w6jsrka.js → chunk-q0x8yqms.js} +2 -2
- package/bin/chunk-q5w77y3e.js +2 -0
- package/bin/chunk-rf428t28.js +2 -0
- package/bin/chunk-rkcsrrvy.js +497 -0
- package/bin/chunk-rtqengn3.js +2 -0
- package/bin/chunk-rx0fmt6n.js +4 -0
- package/bin/chunk-ss91akc0.js +2 -0
- package/bin/{chunk-dsa7hrkt.js → chunk-stex0y7j.js} +2 -2
- package/bin/chunk-vngxwvwv.js +2 -0
- package/bin/chunk-w0e5ek1r.js +2 -0
- package/bin/chunk-x71z4a2a.js +3 -0
- package/bin/chunk-z19gfsnw.js +3 -0
- package/bin/chunk-z3gbypjs.js +2 -0
- package/bin/chunk-zphx997k.js +8 -0
- package/bin/shumai-agent-app.js +862 -1062
- package/package.json +7 -7
- package/prisma/migrations/20261026024507_hash_api_tokens/migration.sql +28 -0
- package/prisma/migrations/20261026031904_add_audit_log_via/migration.sql +2 -0
- package/prisma/migrations/20261029024626_add_oauth_and_jwks/migration.sql +205 -0
- package/prisma/migrations/20261029030321_default_empty_arrays_oauth/migration.sql +25 -0
- package/prisma/schema.prisma +186 -1
- package/bin/chunk-28e1j4am.js +0 -2
- package/bin/chunk-2gyngq15.js +0 -11
- package/bin/chunk-2n1dj1cv.js +0 -2
- package/bin/chunk-46jd4vhk.js +0 -45
- package/bin/chunk-56c9m0pd.js +0 -2
- package/bin/chunk-5yd2h4j1.js +0 -2
- package/bin/chunk-6ddtb9e6.js +0 -2
- package/bin/chunk-7qprxs9y.js +0 -2
- package/bin/chunk-8kyt2vpr.js +0 -7
- package/bin/chunk-8z4drz4c.js +0 -8
- package/bin/chunk-av6bexjx.js +0 -3
- package/bin/chunk-bhgneh6h.js +0 -2
- package/bin/chunk-c26v3b7f.js +0 -3
- package/bin/chunk-cam5rwb7.js +0 -2
- package/bin/chunk-e5amq469.js +0 -16
- package/bin/chunk-e5s9dk8d.js +0 -2
- package/bin/chunk-g80kdkky.js +0 -2
- package/bin/chunk-gmfm23kd.js +0 -2
- package/bin/chunk-h3dvj1c7.js +0 -12
- package/bin/chunk-hg8pmr2h.js +0 -2
- package/bin/chunk-jheky96k.js +0 -3
- package/bin/chunk-jtsbe34h.js +0 -4
- package/bin/chunk-k71cxhsn.js +0 -2
- package/bin/chunk-m4801ex4.js +0 -2
- package/bin/chunk-mfyektx6.js +0 -2
- package/bin/chunk-mryt63fx.js +0 -2
- package/bin/chunk-n75x7as6.js +0 -3
- package/bin/chunk-p0sycvda.js +0 -3
- package/bin/chunk-ph0978mm.js +0 -3
- package/bin/chunk-q032segv.js +0 -2
- package/bin/chunk-qnh6wt00.js +0 -2
- package/bin/chunk-qve2p771.js +0 -2
- package/bin/chunk-sgv9dhyw.js +0 -2
- package/bin/chunk-sk26g8gq.js +0 -5
- package/bin/chunk-tsfemjnp.js +0 -4
- package/bin/chunk-w2xc1r8f.js +0 -3
- package/bin/chunk-w5jhww1y.js +0 -8
- package/bin/chunk-w82m268v.js +0 -2
- package/bin/chunk-xpx7v1cz.js +0 -2
- package/bin/chunk-ynv1dwvb.js +0 -7
- package/bin/chunk-ywmjzwj6.js +0 -13
- package/bin/chunk-z65d9fhw.js +0 -2
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Hr,Z}from"./chunk-akj1v1zj.js";import{F}from"./chunk-7bn1mjf2.js";import{it}from"./chunk-q0x8yqms.js";import{at,ct}from"./chunk-crc78aby.js";import{Ne}from"./chunk-am25vkck.js";import{R,pe,$r,j,mn,Ae}from"./chunk-z19gfsnw.js";import{ne}from"./chunk-2exf93nx.js";import{Q,ie}from"./chunk-rkcsrrvy.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 sr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return sr=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 D(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var Ee=(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 se({message:r,cause:Ee(t)});let n=t,o=n?.error?.type;if(e===400)return new Te(e,n,r,s,o);if(e===401)return new Ie(e,n,r,s,o);if(e===403)return new $e(e,n,r,s,o);if(e===404)return new Ce(e,n,r,s,o);if(e===409)return new Oe(e,n,r,s,o);if(e===422)return new Le(e,n,r,s,o);if(e===429)return new Fe(e,n,r,s,o);if(e>=500)return new qe(e,n,r,s,o);return new k(e,n,r,s,o)}}class M extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class se extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Me extends se{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Te extends k{}class Ie extends k{}class $e extends k{}class Ce extends k{}class Oe extends k{}class Le extends k{}class Fe extends k{}class qe extends k{}var js=/^[a-z][a-z0-9+.-]*:/i,Ur=(e)=>js.test(e),nr=(e)=>(nr=Array.isArray,nr(e)),or=nr;function Et(e){if(typeof e!=="object")return{};return e??{}}function ar(e){if(!e)return!0;for(let t in e)return!1;return!0}function Wr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Dr=(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 Mt=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Jr=(e)=>new Promise((t)=>setTimeout(t,e));var G="0.91.1";var Gr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Us(){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 Hs=()=>{let e=Us();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":G,"X-Stainless-OS":Xr(Deno.build.os),"X-Stainless-Arch":Vr(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":G,"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":G,"X-Stainless-OS":Xr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Vr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Ws();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":G,"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":G,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ws(){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 Vr=(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"},Xr=(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"},Kr,zr=()=>Kr??(Kr=Hs());function Qr(){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 ir(...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 Tt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ir({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 Be(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 Yr(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 Zr=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function es(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 ss(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 ts;function je(e){let t;return(ts??(t=new globalThis.TextEncoder,ts=t.encode.bind(t)))(e)}var rs;function cr(e){let t;return(rs??(t=new globalThis.TextDecoder,rs=t.decode.bind(t)))(e)}var I,C;class z{constructor(){I.set(this,void 0),C.set(this,void 0),f(this,I,new Uint8Array,"f"),f(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?je(e):e;f(this,I,ss([a(this,I,"f"),t]),"f");let r=[],s;while((s=Vs(a(this,I,"f"),a(this,C,"f")))!=null){if(s.carriage&&a(this,C,"f")==null){f(this,C,s.index,"f");continue}if(a(this,C,"f")!=null&&(s.index!==a(this,C,"f")+1||s.carriage)){r.push(cr(a(this,I,"f").subarray(0,a(this,C,"f")-1))),f(this,I,a(this,I,"f").subarray(a(this,C,"f")),"f"),f(this,C,null,"f");continue}let n=a(this,C,"f")!==null?s.preceding-1:s.preceding,o=cr(a(this,I,"f").subarray(0,n));r.push(o),f(this,I,a(this,I,"f").subarray(s.index),"f"),f(this,C,null,"f")}return r}flush(){if(!a(this,I,"f").length)return[];return this.decode(`
|
|
3
|
+
`)}}I=new WeakMap,C=new WeakMap;z.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);z.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Vs(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 ns(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 It={off:0,error:200,warn:300,info:400,debug:500},lr=(e,t,r)=>{if(!e)return;if(Wr(It,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(It))}`);return};function Ue(){}function At(e,t,r){if(!t||It[e]>It[r])return Ue;else return t[e].bind(t)}var Xs={error:Ue,warn:Ue,info:Ue,debug:Ue},os=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Xs;let s=os.get(t);if(s&&s[0]===r)return s[1];let n={error:At("error",t,r),warn:At("warn",t,r),info:At("info",t,r),debug:At("debug",t,r)};return os.set(t,[r,n]),n}var J=(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 He;class O{constructor(e,t,r){this.iterator=e,He.set(this,void 0),this.controller=t,f(this,He,r,"f")}static fromSSEResponse(e,t,r){let s=!1,n=r?v(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 Ks(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=Mt(i.data)??i.data,b=h?.error?.type;throw new k(void 0,h,void 0,e.headers,b)}}c=!0}catch(i){if(D(i))return;throw i}finally{if(!c)t.abort()}}return new O(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let c=new z,i=Be(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(D(i))return;throw i}finally{if(!c)t.abort()}}return new O(o,t,r)}[(He=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 O(()=>s(e),this.controller,a(this,He,"f")),new O(()=>s(t),this.controller,a(this,He,"f"))]}toReadableStream(){let e=this,t;return ir({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=je(JSON.stringify(s)+`
|
|
5
|
+
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Ks(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 as,s=new z,n=Be(e.body);for await(let o of Gs(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*Gs(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"?je(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=ns(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class as{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(`
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=zs(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function zs(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function $t(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,c=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller);return O.fromSSEResponse(r,t.controller)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let h=r.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let l=await r.json();return ur(l,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,J({retryOfRequestLogID:n,url:r.url,status:r.status,body:c,durationMs:Date.now()-o})),c}function ur(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}var We;class oe extends Promise{constructor(e,t,r=$t){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,We.set(this,void 0),f(this,We,e,"f")}_thenUnwrap(e){return new oe(a(this,We,"f"),this.responsePromise,async(t,r)=>ur(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(a(this,We,"f"),e));return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}We=new WeakMap;var Ct;class hr{constructor(e,t,r,s){Ct.set(this,void 0),f(this,Ct,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,Ct,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(Ct=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class Ot extends oe{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await $t(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class H extends hr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let t=this.first_id;if(!t)return null;return{...this.options,query:{...Et(this.options.query),before_id:t}}}let e=this.last_id;if(!e)return null;return{...this.options,query:{...Et(this.options.query),after_id:e}}}}class x extends hr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;if(!e)return null;return{...this.options,query:{...Et(this.options.query),page:e}}}}var fr=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ae(e,t,r){return fr(),new File(e,t??"unknown_file",r)}function De(e,t){let r=typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"";return t?r.split(/[\\/]/).pop()||void 0:r}var pr=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function";var me=async(e,t,r=!0)=>({...e,body:await Zs(e.body,t,r)}),is=new WeakMap;function Ys(e){let t=typeof e==="function"?e:e.fetch,r=is.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return is.set(t,s),s}var Zs=async(e,t,r=!0)=>{if(!await Ys(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>dr(s,n,o,r))),s},en=(e)=>e instanceof Blob&&("name"in e);var dr=async(e,t,r,s)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");if(o)n={type:o};e.append(t,ae([await r.blob()],De(r,s),n))}else if(pr(r))e.append(t,ae([await new Response(Tt(r)).blob()],De(r,s)));else if(en(r))e.append(t,ae([r],De(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map((n)=>dr(e,t+"[]",n,s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([n,o])=>dr(e,`${t}[${n}]`,o,s)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var cs=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",tn=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&cs(e),rn=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Nt(e,t,r){if(fr(),e=await e,t||(t=De(e,!0)),tn(e)){if(e instanceof File&&t==null&&r==null)return e;return ae([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r})}if(rn(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ae(await mr(n),t,r)}let s=await mr(e);if(!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return ae(s,t,r)}async function mr(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(cs(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(pr(e))for await(let r of e)t.push(...await mr(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${sn(e)}`)}return t}function sn(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class y{constructor(e){this._client=e}}var ls=Symbol.for("brand.privateNullableHeaders");function*on(e){if(!e)return;if(ls in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(or(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=or(s[1])?s[1]:[s[1]],c=!1;for(let i of o){if(i===void 0)continue;if(t&&!c)c=!0,yield[n,null];yield[n,i]}}}var u=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,c]of on(s)){let i=o.toLowerCase();if(!n.has(i))t.delete(o),n.add(i);if(c===null)t.delete(o),r.add(i);else t.append(o,c),r.delete(i)}}return{[ls]:!0,values:t,nulls:r}};function hs(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var us=Object.freeze(Object.create(null)),an=(e=hs)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],c=r.reduce((g,_,l)=>{if(/[?#]/.test(_))n=!0;let p=s[l],w=(n?encodeURIComponent:e)(""+p);if(l!==s.length&&(p==null||typeof p==="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??us)??us)?.toString))w=p+"",o.push({start:g.length+_.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`});return g+_+(l===s.length?"":w)},""),i=c.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,b;while((b=h.exec(i))!==null)o.push({start:b.index,length:b[0].length,error:`Value "${b[0]}" can't be safely passed as a path parameter`});if(o.sort((g,_)=>g.start-_.start),o.length>0){let g=0,_=o.reduce((l,p)=>{let w=" ".repeat(p.start-g),E="^".repeat(p.length);return g=p.start+p.length,l+w+E},"");throw new m(`Path parameters result in path with invalid segments:
|
|
7
|
+
${o.map((l)=>l.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${c}
|
|
10
|
+
${_}`)}return c},d=an(hs);class Je 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 Ve=Symbol("anthropic.sdk.stainlessHelper");function Lt(e){return typeof e==="object"&&e!==null&&Ve in e}function gr(e,t){let r=new Set;if(e){for(let s of e)if(Lt(s))r.add(s[Ve])}if(t)for(let s of t){if(Lt(s))r.add(s[Ve]);if(Array.isArray(s.content)){for(let n of s.content)if(Lt(n))r.add(n[Ve])}}return Array.from(r)}function Ft(e,t){let r=gr(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function ds(e){if(Lt(e))return{"x-stainless-helper":e[Ve]};return{}}class Xe extends y{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",H,{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",me({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},ds(s.file),t?.headers])},this._client))}}class Ke 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",H,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class Ge 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 ze 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 ge extends y{constructor(){super(...arguments);this.versions=new ze(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])})}}ge.Versions=ze;class Qe 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 Ye 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 ce extends y{constructor(){super(...arguments);this.memories=new Qe(this._client),this.memoryVersions=new Ye(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])})}}ce.Memories=Qe;ce.MemoryVersions=Ye;var qt={"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 fs(e){return e?.output_format??e?.output_config?.format}function _r(e,t,r){let s=fs(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 br(e,t,r)}function br(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=bn(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 bn(e,t){let r=fs(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 yn=(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},_e=(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),_e(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),_e(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),_e(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),_e(e);break;case"delimiter":return e=e.slice(0,e.length-1),_e(e);break}return e},wn=(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},xn=(e)=>{let t="";return e.map((r)=>{switch(r.type){case"string":t+='"'+r.value+'"';break;default:t+=r.value;break}}),t},Bt=(e)=>JSON.parse(xn(wn(_e(yn(e)))));var B,Y,be,Ze,jt,et,tt,Ut,rt,V,st,Ht,Wt,le,Dt,Jt,nt,yr,ps,Vt,wr,xr,Sr,ms,gs="__json_buf";function _s(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ot{constructor(e,t){B.add(this),this.messages=[],this.receivedMessages=[],Y.set(this,void 0),be.set(this,null),this.controller=new AbortController,Ze.set(this,void 0),jt.set(this,()=>{}),et.set(this,()=>{}),tt.set(this,void 0),Ut.set(this,()=>{}),rt.set(this,()=>{}),V.set(this,{}),st.set(this,!1),Ht.set(this,!1),Wt.set(this,!1),le.set(this,!1),Dt.set(this,void 0),Jt.set(this,void 0),nt.set(this,void 0),Vt.set(this,(r)=>{if(f(this,Ht,!0,"f"),D(r))r=new M;if(r instanceof M)return f(this,Wt,!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,Ze,new Promise((r,s)=>{f(this,jt,r,"f"),f(this,et,s,"f")}),"f"),f(this,tt,new Promise((r,s)=>{f(this,Ut,r,"f"),f(this,rt,s,"f")}),"f"),a(this,Ze,"f").catch(()=>{}),a(this,tt,"f").catch(()=>{}),f(this,be,e,"f"),f(this,nt,t?.logger??console,"f")}get response(){return a(this,Dt,"f")}get request_id(){return a(this,Jt,"f")}async withResponse(){f(this,le,!0,"f");let e=await a(this,Ze,"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 ot(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ot(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,be,{...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,Vt,"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,B,"m",wr).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,B,"m",xr).call(this,i);if(c.controller.signal?.aborted)throw new M;a(this,B,"m",Sr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,Dt,e,"f"),f(this,Jt,e?.headers.get("request-id"),"f"),a(this,jt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,st,"f")}get errored(){return a(this,Ht,"f")}get aborted(){return a(this,Wt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,V,"f")[e]||(a(this,V,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,V,"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,V,"f")[e]||(a(this,V,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,le,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,le,!0,"f"),await a(this,tt,"f")}get currentMessage(){return a(this,Y,"f")}async finalMessage(){return await this.done(),a(this,B,"m",yr).call(this)}async finalText(){return await this.done(),a(this,B,"m",ps).call(this)}_emit(e,...t){if(a(this,st,"f"))return;if(e==="end")f(this,st,!0,"f"),a(this,Ut,"f").call(this);let r=a(this,V,"f")[e];if(r)a(this,V,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,le,"f")&&!r?.length)Promise.reject(s);a(this,et,"f").call(this,s),a(this,rt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,le,"f")&&!r?.length)Promise.reject(s);a(this,et,"f").call(this,s),a(this,rt,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,B,"m",yr).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,B,"m",wr).call(this),this._connected(null);let n=O.fromReadableStream(e,this.controller);for await(let o of n)a(this,B,"m",xr).call(this,o);if(n.controller.signal?.aborted)throw new M;a(this,B,"m",Sr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(Y=new WeakMap,be=new WeakMap,Ze=new WeakMap,jt=new WeakMap,et=new WeakMap,tt=new WeakMap,Ut=new WeakMap,rt=new WeakMap,V=new WeakMap,st=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,le=new WeakMap,Dt=new WeakMap,Jt=new WeakMap,nt=new WeakMap,Vt=new WeakMap,B=new WeakSet,yr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ps=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(" ")},wr=function(){if(this.ended)return;f(this,Y,void 0,"f")},xr=function(t){if(this.ended)return;let r=a(this,B,"m",ms).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(_s(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:bs(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(_r(r,a(this,be,"f"),{logger:a(this,nt,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,Y,r,"f");break}case"content_block_start":case"message_delta":break}},Sr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,Y,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,Y,void 0,"f"),_r(t,a(this,be,"f"),{logger:a(this,nt,"f")})},ms=function(t){let r=a(this,Y,"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&&_s(s)){let n=s[gs]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,gs,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Bt(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,Vt,"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:bs(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 O(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function bs(e){}class ye 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 ys=1e5,ws=`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
|
+
1. Task Overview
|
|
12
|
+
The user's core request and success criteria
|
|
13
|
+
Any clarifications or constraints they specified
|
|
14
|
+
2. Current State
|
|
15
|
+
What has been completed so far
|
|
16
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
17
|
+
Key outputs or artifacts produced
|
|
18
|
+
3. Important Discoveries
|
|
19
|
+
Technical constraints or requirements uncovered
|
|
20
|
+
Decisions made and their rationale
|
|
21
|
+
Errors encountered and how they were resolved
|
|
22
|
+
What approaches were tried that didn't work (and why)
|
|
23
|
+
4. Next Steps
|
|
24
|
+
Specific actions needed to complete the task
|
|
25
|
+
Any blockers or open questions to resolve
|
|
26
|
+
Priority order if multiple steps remain
|
|
27
|
+
5. Context to Preserve
|
|
28
|
+
User preferences or style requirements
|
|
29
|
+
Domain-specific details that aren't obvious
|
|
30
|
+
Any promises made to the user
|
|
31
|
+
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
32
|
+
Wrap your summary in <summary></summary> tags.`;var lt,we,ue,P,A,N,X,ee,ut,xs,kr;function Ss(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class ht{constructor(e,t,r){lt.add(this),this.client=e,we.set(this,!1),ue.set(this,!1),P.set(this,void 0),A.set(this,void 0),N.set(this,void 0),X.set(this,void 0),ee.set(this,void 0),ut.set(this,0),f(this,P,{params:{...t,messages:structuredClone(t.messages)}},"f");let n=["BetaToolRunner",...gr(t.tools,t.messages)].join(", ");if(f(this,A,{...r,headers:u([{"x-stainless-helper":n},r?.headers])},"f"),f(this,ee,Ss(),"f"),t.compactionControl?.enabled)console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(we=new WeakMap,ue=new WeakMap,P=new WeakMap,A=new WeakMap,N=new WeakMap,X=new WeakMap,ee=new WeakMap,ut=new WeakMap,lt=new WeakSet,xs=async function(){let t=a(this,P,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(a(this,N,"f")!==void 0)try{let h=await a(this,N,"f");r=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}let s=t.contextTokenThreshold??ys;if(r<s)return!1;let n=t.model??a(this,P,"f").params.model,o=t.summaryPrompt??ws,c=a(this,P,"f").params.messages;if(c[c.length-1].role==="assistant"){let h=c[c.length-1];if(Array.isArray(h.content)){let b=h.content.filter((g)=>g.type!=="tool_use");if(b.length===0)c.pop();else h.content=b}}let i=await this.client.beta.messages.create({model:n,messages:[...c,{role:"user",content:[{type:"text",text:o}]}],max_tokens:a(this,P,"f").params.max_tokens},{signal:a(this,A,"f").signal,headers:u([a(this,A,"f").headers,{"x-stainless-helper":"compaction"}])});if(i.content[0]?.type!=="text")throw new m("Expected text response for compaction");return a(this,P,"f").params.messages=[{role:"user",content:i.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,we,"f"))throw new m("Cannot iterate over a consumed stream");f(this,we,!0,"f"),f(this,ue,!0,"f"),f(this,X,void 0,"f");try{while(!0){let t;try{if(a(this,P,"f").params.max_iterations&&a(this,ut,"f")>=a(this,P,"f").params.max_iterations)break;f(this,ue,!1,"f"),f(this,X,void 0,"f"),f(this,ut,(e=a(this,ut,"f"),e++,e),"f"),f(this,N,void 0,"f");let{max_iterations:r,compactionControl:s,...n}=a(this,P,"f").params;if(n.stream)t=this.client.beta.messages.stream({...n},a(this,A,"f")),f(this,N,t.finalMessage(),"f"),a(this,N,"f").catch(()=>{}),yield t;else f(this,N,this.client.beta.messages.create({...n,stream:!1},a(this,A,"f")),"f"),yield a(this,N,"f");if(!await a(this,lt,"m",xs).call(this)){if(!a(this,ue,"f")){let{role:i,content:h}=await a(this,N,"f");a(this,P,"f").params.messages.push({role:i,content:h})}let c=await a(this,lt,"m",kr).call(this,a(this,P,"f").params.messages.at(-1));if(c)a(this,P,"f").params.messages.push(c);else if(!a(this,ue,"f"))break}}finally{if(t)t.abort()}}if(!a(this,N,"f"))throw new m("ToolRunner concluded without a message from the server");a(this,ee,"f").resolve(await a(this,N,"f"))}catch(t){throw f(this,we,!1,"f"),a(this,ee,"f").promise.catch(()=>{}),a(this,ee,"f").reject(t),f(this,ee,Ss(),"f"),t}}setMessagesParams(e){if(typeof e==="function")a(this,P,"f").params=e(a(this,P,"f").params);else a(this,P,"f").params=e;f(this,ue,!0,"f"),f(this,X,void 0,"f")}setRequestOptions(e){if(typeof e==="function")f(this,A,e(a(this,A,"f")),"f");else f(this,A,{...a(this,A,"f"),...e},"f")}async generateToolResponse(e=a(this,A,"f").signal){let t=await a(this,N,"f")??this.params.messages.at(-1);if(!t)return null;return a(this,lt,"m",kr).call(this,t,e)}done(){return a(this,ee,"f").promise}async runUntilDone(){if(!a(this,we,"f"))for await(let e of this);return this.done()}get params(){return a(this,P,"f").params}pushMessages(...e){this.setMessagesParams((t)=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}kr=async function(t,r=a(this,A,"f").signal){if(a(this,X,"f")!==void 0)return a(this,X,"f");return f(this,X,Sn(a(this,P,"f").params,t,{...a(this,A,"f"),signal:r}),"f"),a(this,X,"f")};async function Sn(e,t=e.messages.at(-1),r){if(!t||t.role!=="assistant"||!t.content||typeof t.content==="string")return null;let s=t.content.filter((o)=>o.type==="tool_use");if(s.length===0)return null;return{role:"user",content:await Promise.all(s.map(async(o)=>{let c=e.tools.find((i)=>("name"in i?i.name:i.mcp_server_name)===o.name);if(!c||!("run"in c))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let i=o.input;if("parse"in c&&c.parse)i=c.parse(i);let h=await c.run(i,{toolUseBlock:o,signal:r?.signal});return{type:"tool_result",tool_use_id:o.id,content:h}}catch(i){return{type:"tool_result",tool_use_id:o.id,content:i instanceof ye?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class xe{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new z;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(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")}return new xe(Be(e.body),t)}}class dt extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",H,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:s}=t??{};return this._client.post(d`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let s=await this.retrieve(e);if(!s.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:n}=t??{};return this._client.get(s.results_url,{...r,headers:u([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,c)=>xe.fromResponse(c.response,c.controller))}}var ks={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},Pn=["claude-mythos-preview","claude-opus-4-6"];class te extends y{constructor(){super(...arguments);this.batches=new dt(this._client)}create(e,t){let r=Ps(e),{betas:s,...n}=r;if(n.model in ks)console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${ks[n.model]}
|
|
33
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Pn.includes(n.model)&&n.thinking&&n.thinking.type==="enabled")console.warn(`Using Claude with ${n.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let o=this._client._options.timeout;if(!n.stream&&o==null){let i=qt[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,i)}let c=Ft(n.tools,n.messages);return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??600000,...t,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},c,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then((r)=>br(r,e,{logger:this._client.logger??console}))}stream(e,t){return ot.createMessage(this,e,t)}countTokens(e,t){let r=Ps(e),{betas:s,...n}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:u([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new ht(this._client,e,t)}}function Ps(e){if(!e.output_format)return e;if(e.output_config?.format)throw new m("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...r}=e;return{...r,output_config:{...e.output_config,format:t}}}te.Batches=dt;te.BetaToolRunner=ht;te.ToolError=ye;class ft extends y{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/events?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/events?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}class pt extends y{retrieve(e,t,r){let{session_id:s,betas:n}=t;return this._client.get(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{session_id:s,betas:n,...o}=t;return this._client.post(d`/v1/sessions/${s}/resources/${e}?beta=true`,{body: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/sessions/${e}/resources?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{session_id:s,betas:n}=t;return this._client.delete(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/sessions/${e}/resources?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class he extends y{constructor(){super(...arguments);this.events=new ft(this._client),this.resources=new pt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/sessions?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/sessions/${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/sessions/${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/sessions?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/sessions/${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/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}he.Events=ft;he.Resources=pt;class mt extends y{create(e,t={},r){let{betas:s,...n}=t??{};return this._client.post(d`/v1/skills/${e}/versions?beta=true`,me({body:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){let{skill_id:s,betas:n}=t;return this._client.get(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(d`/v1/skills/${e}/versions?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:s,betas:n}=t;return this._client.delete(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class Se extends y{constructor(){super(...arguments);this.versions=new mt(this._client)}create(e={},t){let{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",me({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",x,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:s}=t??{};return this._client.delete(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}}Se.Versions=mt;class gt extends y{create(e,t,r){let{betas:s,...n}=t;return this._client.post(d`/v1/vaults/${e}/credentials?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){let{vault_id:s,betas:n}=t;return this._client.get(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){let{vault_id:s,betas:n,...o}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{body: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/vaults/${e}/credentials?beta=true`,x,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){let{vault_id:s,betas:n}=t;return this._client.delete(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){let{vault_id:s,betas:n}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ke extends y{constructor(){super(...arguments);this.credentials=new gt(this._client)}create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/vaults?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/vaults/${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/vaults/${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/vaults?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/vaults/${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/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ke.Credentials=gt;class T extends y{constructor(){super(...arguments);this.models=new Ke(this._client),this.messages=new te(this._client),this.agents=new ge(this._client),this.environments=new Je(this._client),this.sessions=new he(this._client),this.vaults=new ke(this._client),this.memoryStores=new ce(this._client),this.files=new Xe(this._client),this.skills=new Se(this._client),this.userProfiles=new Ge(this._client)}}T.Models=Ke;T.Messages=te;T.Agents=ge;T.Environments=Je;T.Sessions=he;T.Vaults=ke;T.MemoryStores=ce;T.Files=Xe;T.Skills=Se;T.UserProfiles=Ge;class Pe extends y{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??600000,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function Rs(e){return e?.output_config?.format}function Pr(e,t,r){let s=Rs(t);if(!t||!("parse"in(s??{})))return{...e,content:e.content.map((n)=>{if(n.type==="text")return Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return n}),parsed_output:null};return Rr(e,t,r)}function Rr(e,t,r){let s=null,n=e.content.map((o)=>{if(o.type==="text"){let c=Cn(t,o.text);if(s===null)s=c;return Object.defineProperty({...o},"parsed_output",{value:c,enumerable:!1})}return o});return{...e,content:n,parsed_output:s}}function Cn(e,t){let r=Rs(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 U,re,Re,_t,Xt,bt,yt,Kt,wt,K,xt,Gt,zt,de,Qt,Yt,St,vr,vs,Er,Mr,Tr,Ar,Es,Ms="__json_buf";function Ts(e){return e.type==="tool_use"||e.type==="server_tool_use"}class kt{constructor(e,t){U.add(this),this.messages=[],this.receivedMessages=[],re.set(this,void 0),Re.set(this,null),this.controller=new AbortController,_t.set(this,void 0),Xt.set(this,()=>{}),bt.set(this,()=>{}),yt.set(this,void 0),Kt.set(this,()=>{}),wt.set(this,()=>{}),K.set(this,{}),xt.set(this,!1),Gt.set(this,!1),zt.set(this,!1),de.set(this,!1),Qt.set(this,void 0),Yt.set(this,void 0),St.set(this,void 0),Er.set(this,(r)=>{if(f(this,Gt,!0,"f"),D(r))r=new M;if(r instanceof M)return f(this,zt,!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,_t,new Promise((r,s)=>{f(this,Xt,r,"f"),f(this,bt,s,"f")}),"f"),f(this,yt,new Promise((r,s)=>{f(this,Kt,r,"f"),f(this,wt,s,"f")}),"f"),a(this,_t,"f").catch(()=>{}),a(this,yt,"f").catch(()=>{}),f(this,Re,e,"f"),f(this,St,t?.logger??console,"f")}get response(){return a(this,Qt,"f")}get request_id(){return a(this,Yt,"f")}async withResponse(){f(this,de,!0,"f");let e=await a(this,_t,"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 kt(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new kt(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return f(n,Re,{...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,Er,"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,U,"m",Mr).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,U,"m",Tr).call(this,i);if(c.controller.signal?.aborted)throw new M;a(this,U,"m",Ar).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;f(this,Qt,e,"f"),f(this,Yt,e?.headers.get("request-id"),"f"),a(this,Xt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,xt,"f")}get errored(){return a(this,Gt,"f")}get aborted(){return a(this,zt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,K,"f")[e]||(a(this,K,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,K,"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,K,"f")[e]||(a(this,K,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(f(this,de,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){f(this,de,!0,"f"),await a(this,yt,"f")}get currentMessage(){return a(this,re,"f")}async finalMessage(){return await this.done(),a(this,U,"m",vr).call(this)}async finalText(){return await this.done(),a(this,U,"m",vs).call(this)}_emit(e,...t){if(a(this,xt,"f"))return;if(e==="end")f(this,xt,!0,"f"),a(this,Kt,"f").call(this);let r=a(this,K,"f")[e];if(r)a(this,K,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,de,"f")&&!r?.length)Promise.reject(s);a(this,bt,"f").call(this,s),a(this,wt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,de,"f")&&!r?.length)Promise.reject(s);a(this,bt,"f").call(this,s),a(this,wt,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,U,"m",vr).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,U,"m",Mr).call(this),this._connected(null);let n=O.fromReadableStream(e,this.controller);for await(let o of n)a(this,U,"m",Tr).call(this,o);if(n.controller.signal?.aborted)throw new M;a(this,U,"m",Ar).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(re=new WeakMap,Re=new WeakMap,_t=new WeakMap,Xt=new WeakMap,bt=new WeakMap,yt=new WeakMap,Kt=new WeakMap,wt=new WeakMap,K=new WeakMap,xt=new WeakMap,Gt=new WeakMap,zt=new WeakMap,de=new WeakMap,Qt=new WeakMap,Yt=new WeakMap,St=new WeakMap,Er=new WeakMap,U=new WeakSet,vr=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},vs=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(" ")},Mr=function(){if(this.ended)return;f(this,re,void 0,"f")},Tr=function(t){if(this.ended)return;let r=a(this,U,"m",Es).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(Ts(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}default:As(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Pr(r,a(this,Re,"f"),{logger:a(this,St,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{f(this,re,r,"f");break}case"content_block_start":case"message_delta":break}},Ar=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=a(this,re,"f");if(!t)throw new m("request ended without sending any chunks");return f(this,re,void 0,"f"),Pr(t,a(this,Re,"f"),{logger:a(this,St,"f")})},Es=function(t){let r=a(this,re,"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.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,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;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&&Ts(s)){let n=s[Ms]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,Ms,{value:n,enumerable:!1,writable:!0}),n)o.input=Bt(n);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}default:As(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 O(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function As(e){}class Pt extends y{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",H,{query:e,...t})}delete(e,t){return this._client.delete(d`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(d`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:u([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,n)=>xe.fromResponse(n.response,n.controller))}}class fe extends y{constructor(){super(...arguments);this.batches=new Pt(this._client)}create(e,t){if(e.model in Is)console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Is[e.model]}
|
|
34
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Nn.includes(e.model)&&e.thinking&&e.thinking.type==="enabled")console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let n=qt[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,n)}let s=Ft(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??600000,...t,headers:u([s,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then((r)=>Rr(r,e,{logger:this._client.logger??console}))}stream(e,t){return kt.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}var Is={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},Nn=["claude-mythos-preview","claude-opus-4-6"];fe.Batches=Pt;class ve extends y{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(d`/v1/models/${e}`,{...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",H,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}var Rt=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0;return};var Ir,Cr,Zt,$s,Cs="\\n\\nHuman:",Os="\\n\\nAssistant:";class S{constructor({baseURL:e=Rt("ANTHROPIC_BASE_URL"),apiKey:t=Rt("ANTHROPIC_API_KEY")??null,authToken:r=Rt("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){Ir.add(this),Zt.set(this,void 0);let n={apiKey:t,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!n.dangerouslyAllowBrowser&&Gr())throw new m(`It looks like you're running in a browser-like environment.
|
|
35
|
+
|
|
36
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
37
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
38
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
39
|
+
|
|
40
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
41
|
+
`);this.baseURL=n.baseURL,this.timeout=n.timeout??Cr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=lr(n.logLevel,"ClientOptions.logLevel",this)??lr(Rt("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??Qr(),f(this,Zt,Zr,"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 es(e)}getUserAgent(){return`${this.constructor.name}/JS ${G}`}defaultIdempotencyKey(){return`stainless-node-retry-${sr()}`}makeStatusError(e,t,r,s){return k.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,Ir,"m",$s).call(this)&&r||this.baseURL,n=Ur(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!ar(o)||!ar(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 oe(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(v(this).debug(`[${h}] sending request`,J({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new M;let _=new AbortController,l=await this.fetchWithTimeout(c,o,i,_).catch(Ee),p=Date.now();if(l instanceof globalThis.Error){let L=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new M;let q=D(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return v(this).info(`[${h}] connection ${q?"timed out":"failed"} - ${L}`),v(this).debug(`[${h}] connection ${q?"timed out":"failed"} (${L})`,J({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),this.retryRequest(s,t,r??h);if(v(this).info(`[${h}] connection ${q?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${h}] connection ${q?"timed out":"failed"} (error; no more retries left)`,J({retryOfRequestLogID:r,url:c,durationMs:p-g,message:l.message})),q)throw new Me;throw new se({cause:l})}let w=[...l.headers.entries()].filter(([L])=>L==="request-id").map(([L,q])=>", "+L+": "+JSON.stringify(q)).join(""),E=`[${h}${b}${w}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${p-g}ms`;if(!l.ok){let L=await this.shouldRetry(l);if(t&&L){let vt=`retrying, ${t} attempts remaining`;return await Yr(l.body),v(this).info(`${E} - ${vt}`),v(this).debug(`[${h}] response error (${vt})`,J({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:p-g})),this.retryRequest(s,t,r??h,l.headers)}let q=L?"error; no more retries left":"error; not retryable";v(this).info(`${E} - ${q}`);let qr=await l.text().catch((vt)=>Ee(vt).message),Br=Mt(qr),jr=Br?void 0:qr;throw v(this).debug(`[${h}] response error (${q})`,J({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:jr,durationMs:Date.now()-g})),this.makeStatusError(l.status,Br,jr,l.headers)}return v(this).info(E),v(this).debug(`[${h}] response start`,J({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 Ot(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 Jr(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)Dr("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))}:{},...zr(),...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:Tt(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,Zt,"f").call(this,{body:e,headers:r})}}Cr=S,Zt=new WeakMap,Ir=new WeakSet,$s=function(){return this.baseURL!=="https://api.anthropic.com"};S.Anthropic=Cr;S.HUMAN_PROMPT=Cs;S.AI_PROMPT=Os;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=m;S.APIError=k;S.APIConnectionError=se;S.APIConnectionTimeoutError=Me;S.APIUserAbortError=M;S.NotFoundError=Ce;S.ConflictError=Oe;S.RateLimitError=Fe;S.BadRequestError=Te;S.AuthenticationError=Ie;S.InternalServerError=qe;S.PermissionDeniedError=$e;S.UnprocessableEntityError=Le;S.toFile=Nt;class W extends S{constructor(){super(...arguments);this.completions=new Pe(this),this.messages=new fe(this),this.models=new ve(this),this.beta=new T(this)}}W.Completions=Pe;W.Messages=fe;W.Models=ve;W.Beta=T;function Ls(e,t){if(e)return e;if(F("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function Fn(e,t,r){let s=Ls(t,r);if(s==="none")return{retention:s};let n=s==="long"&&rr(e).supportsLongCacheRetention?"1h":void 0;return{retention:s,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}var qn="2.1.75",Bn=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],jn=new Map(Bn.map((e)=>[e.toLowerCase(),e])),tr=(e)=>jn.get(e.toLowerCase())??e,Un=(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 Hn(e){if(!e.some((n)=>n.type==="image"))return R(e.map((n)=>n.text).join(`
|
|
42
|
+
`));let r=e.map((n)=>{if(n.type==="text")return{type:"text",text:R(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 Wn="fine-grained-tool-streaming-2025-05-14",Dn="interleaved-thinking-2025-05-14";function rr(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??Jn(e)}}function Jn(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 Or(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Nr(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 Fs(e,t,r){if(t)return;if(Nr(r,"authorization")||Nr(r,"x-api-key")||Nr(r,"cf-aig-authorization"))return;throw Error(`No API key for provider: ${e}`)}var Vn=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function qs(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
43
|
+
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Lr(e,t){if(e==="")return qs(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 Xn(e){let t=e.indexOf("\r"),r=e.indexOf(`
|
|
44
|
+
`);if(t===-1)return r;if(r===-1)return t;return Math.min(t,r)}function er(e){let t=Xn(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*Kn(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=er(o);while(g){o=g.rest;let _=Lr(g.line,n);if(_)yield _;g=er(o)}}o+=s.decode();let c=er(o);while(c){o=c.rest;let h=Lr(c.line,n);if(h)yield h;c=er(o)}if(o.length>0){let h=Lr(o,n);if(h)yield h}let i=qs(n);if(i)yield i}finally{r.releaseLock()}}async function*Gn(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 Kn(e.body,t)){if(n.event==="error")throw Error(n.data);if(!Vn.has(n.event??""))continue;try{let o=Hr(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 Fr=(e,t,r)=>{let s=new Q;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;Fs(e.provider,l,r?.headers);let p;if(e.provider==="github-copilot"){let q=at(t.messages);p=ct({messages:t.messages,hasImages:q})}let E=Ls(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,L=Yn(e,l,r?.interleavedThinking??!0,so(e,t),r?.headers,p,E);o=L.client,c=L.isOAuthToken}let i=Zn(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 Ne(()=>o.messages.create({...i,stream:!0},b).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:g.status,headers:ne(g.headers)},e),s.push({type:"start",partial:n});let _=n.content;for await(let l of Gn(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,ie(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?Un(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((E)=>E.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((E)=>E.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((E)=>E.index===l.index),w=_[p];if(w&&w.type==="toolCall")w.partialJson+=l.delta.partial_json,w.arguments=Z(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((E)=>E.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((E)=>E.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=Z(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=no(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,ie(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 zn(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 Yl=(e,t,r)=>{Fs(e.provider,r?.apiKey,r?.headers);let s=j(e,t,r,r?.apiKey);if(!r?.reasoning)return Fr(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=zn(e,r.reasoning);return Fr(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=mn(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=$r(e,t,n.maxTokens);return Fr(e,t,{...s,maxTokens:o,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(n.thinkingBudget,Math.max(0,o-1024))})};function Qn(e){return e.includes("sk-ant-oat")}function Yn(e,t,r,s,n,o,c){let i=r&&e.compat?.forceAdaptiveThinking!==!0,h=[];if(s)h.push(Wn);if(i)h.push(Dn);if(e.provider==="github-copilot")return{client:new W({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Or({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},e.headers,o,n)}),isOAuthToken:!1};if(t&&Qn(t))return{client:new W({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Or({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${qn}`,"x-app":"cli"},e.headers,n)}),isOAuthToken:!0};let b=c&&rr(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},g=Or({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},b,e.headers,n);return{client:new W({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:g}),isOAuthToken:!1}}function Zn(e,t,r,s){let{cacheControl:n}=Fn(e,s?.cacheRetention,s?.env),o=rr(e),c=Ae(t.messages,e,eo),i=r?tr:(p)=>p,h=it({...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:ro(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:R(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:R(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=[...Ns(b,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...Ns(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 eo(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function to(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?tr(i):i})}let c=Hn(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 ro(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:R(b.content)})}else{let _=b.content.map((l)=>{if(l.type==="text")return{type:"text",text:R(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:R(_.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:R(_.thinking),signature:""}:{type:"text",text:R(_.thinking)});else g.push({type:"thinking",thinking:R(_.thinking),signature:l})}else if(_.type==="toolCall")g.push({type:"tool_use",id:_.id,name:t?tr(_.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=to(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 so(e,t){return!!t.tools?.length&&!rr(e).supportsEagerToolInputStreaming}function Ns(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=pe(c,s),b=c.parameters,g={type:"object",properties:b.properties??{},required:b.required??[]},_=h===!0?{...c.parameters,...g}:g;return{name:t?tr(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 no(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{Fr as stream,Yl as streamSimple};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{le,q,P,oe,z,me,L,we,ge,N,Fe,ve,be}from"./chunk-rkcsrrvy.js";var{awsEndpointFunctions:Te,emitWarningIfUnsupportedVersion:Oe,createDefaultUserAgentProvider:Re,NODE_APP_ID_CONFIG_OPTIONS:De,getAwsRegionExtensionConfiguration:ke,resolveAwsRegionExtensionConfiguration:$e,resolveUserAgentConfig:Ne,resolveHostHeaderConfig:Ue,getUserAgentPlugin:qe,getHostHeaderPlugin:He,getLoggerPlugin:Me,getRecursionDetectionPlugin:Ge}=N(),{NoAuthSigner:je,getHttpAuthSchemeEndpointRuleSetPlugin:Ke,DefaultIdentityProviderConfig:Ve,getHttpSigningPlugin:ze}=ge(),{normalizeProvider:B,getSmithyContext:Le,ServiceException:Be,NoOpLogger:We,emitWarningIfUnsupportedVersion:Ye,loadConfigsForDefaultMode:Je,getDefaultExtensionConfiguration:Xe,resolveDefaultRuntimeConfig:Qe,Client:W,makeBuilder:Ze,createAggregatedClient:et}=q(),{Command:tt}=q();var Vr=tt,zr=W;var{resolveDefaultsModeConfig:rt,loadConfig:h,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:ot,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:nt,NODE_REGION_CONFIG_OPTIONS:st,NODE_REGION_CONFIG_FILE_OPTIONS:it,resolveRegionConfig:ct}=P(),{BinaryDecisionDiagram:at,EndpointCache:pt,decideEndpoint:dt,customEndpointFunctions:ut,resolveEndpointConfig:lt,getEndpointPlugin:ht}=oe(),{parseUrl:_t,getHttpHandlerExtensionConfiguration:gt,resolveHttpHandlerRuntimeConfig:Et,getContentLengthPlugin:mt}=L(),{DEFAULT_RETRY_MODE:xt,NODE_RETRY_MODE_CONFIG_OPTIONS:ft,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:St,resolveRetryConfig:vt,getRetryPlugin:Pt}=we(),{TypeRegistry:Y,getSchemaSerdePlugin:It}=le(),{resolveAwsSdkSigV4Config:Ct,AwsSdkSigV4Signer:At,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:yt}=ve(),{toUtf8:Tt,fromUtf8:Ot,toBase64:Rt,fromBase64:Dt,calculateBodyLength:kt}=z(),{streamCollector:$t,NodeHttpHandler:wt}=be(),{AwsRestJsonProtocol:Nt}=Fe(),{Sha256:bt}=me(),Ut=async(e,t,n)=>({operation:Le(t).operation,region:await B(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Ft(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function qt(e){return{schemeId:"smithy.api#noAuth"}}var Ht=(e)=>{let t=[];switch(e.operation){case"CreateToken":{t.push(qt());break}default:t.push(Ft(e))}return t},Mt=(e)=>{let t=Ct(e);return Object.assign(t,{authSchemePreference:B(e.authSchemePreference??[])})},Gt=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),jt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Kt="3.997.43",Vt={version:Kt},E="ref",_=-1,x=!0,G="isSet",J="PartitionResult",f="booleanEquals",b="getAttr",j={[E]:"Endpoint"},U={[E]:J},g={},K=[{[E]:"Region"}],V={conditions:[[G,[j]],[G,K],["aws.partition",K,J],[f,[{[E]:"UseFIPS"},x]],[f,[{[E]:"UseDualStack"},x]],[f,[{fn:b,argv:[U,"supportsDualStack"]},x]],[f,[{fn:b,argv:[U,"supportsFIPS"]},x]],["stringEquals",[{fn:b,argv:[U,"name"]},"aws-us-gov"]]],results:[[_],[_,"Invalid Configuration: FIPS and custom endpoint are not supported"],[_,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[j,g],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[_,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",g],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",g],[_,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",g],[_,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",g],[_,"Invalid Configuration: Missing Region"]]},zt=2,c=1e8,Lt=new Int32Array([-1,1,-1,0,13,3,1,4,c+12,2,5,c+12,3,8,6,4,7,c+11,5,c+9,c+10,4,11,9,6,10,c+8,7,c+6,c+7,5,12,c+5,6,c+4,c+5,3,c+1,14,4,c+2,c+3]),Bt=at.from(Lt,zt,V.conditions,V.results),Wt=new pt({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Yt=(e,t={})=>Wt.get(e,()=>dt(Bt,{endpointParams:e,logger:t.logger}));ut.aws=Te;class i extends Be{constructor(e){super(e);Object.setPrototypeOf(this,i.prototype)}}class S extends i{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,S.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class v extends i{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,v.prototype),this.error=e.error,this.error_description=e.error_description}}class I extends i{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,I.prototype),this.error=e.error,this.error_description=e.error_description}}class C extends i{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.error_description=e.error_description}}class A extends i{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,A.prototype),this.error=e.error,this.error_description=e.error_description}}class y extends i{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,y.prototype),this.error=e.error,this.error_description=e.error_description}}class T extends i{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}class O extends i{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,O.prototype),this.error=e.error,this.error_description=e.error_description}}class R extends i{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,R.prototype),this.error=e.error,this.error_description=e.error_description}}class D extends i{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,D.prototype),this.error=e.error,this.error_description=e.error_description}}class k extends i{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,k.prototype),this.error=e.error,this.error_description=e.error_description}}var Jt="AccessDeniedException",Xt="AuthorizationPendingException",Qt="AccessToken",Zt="ClientSecret",er="CreateToken",tr="CreateTokenRequest",rr="CreateTokenResponse",or="CodeVerifier",nr="ExpiredTokenException",sr="InvalidClientException",ir="InvalidGrantException",cr="InvalidRequestException",ar="InternalServerException",pr="InvalidScopeException",dr="IdToken",ur="RefreshToken",lr="SlowDownException",hr="UnauthorizedClientException",_r="UnsupportedGrantTypeException",gr="accessToken",l="client",Er="clientId",mr="clientSecret",xr="codeVerifier",fr="code",Sr="deviceCode",r="error",vr="expiresIn",d="error_description",Pr="grantType",Ir="http",u="httpError",Cr="idToken",X="reason",Q="refreshToken",Ar="redirectUri",Z="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",yr="scope",Tr="server",Or="tokenType",o="com.amazonaws.ssooidc",ee=Y.for(Z),te=[-3,Z,"SSOOIDCServiceException",0,[],[]];ee.registerError(te,i);var a=Y.for(o),re=[-3,o,Jt,{[r]:l,[u]:400},[r,X,d],[0,0,0]];a.registerError(re,S);var ne=[-3,o,Xt,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(ne,v);var se=[-3,o,nr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(se,I);var ie=[-3,o,ar,{[r]:Tr,[u]:500},[r,d],[0,0]];a.registerError(ie,C);var ce=[-3,o,sr,{[r]:l,[u]:401},[r,d],[0,0]];a.registerError(ce,A);var ae=[-3,o,ir,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(ae,y);var pe=[-3,o,cr,{[r]:l,[u]:400},[r,X,d],[0,0,0]];a.registerError(pe,T);var de=[-3,o,pr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(de,O);var ue=[-3,o,lr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(ue,R);var he=[-3,o,hr,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(he,D);var _e=[-3,o,_r,{[r]:l,[u]:400},[r,d],[0,0]];a.registerError(_e,k);var Ee=[ee,a],Rr=[0,o,Qt,8,0],Dr=[0,o,Zt,8,0],kr=[0,o,or,8,0],$r=[0,o,dr,8,0],xe=[0,o,ur,8,0],fe=[3,o,tr,0,[Er,mr,Pr,Sr,fr,Q,yr,Ar,xr],[0,[()=>Dr,0],0,0,0,[()=>xe,0],64,0,[()=>kr,0]],3],Se=[3,o,rr,0,[gr,Or,vr,Q,Cr],[[()=>Rr,0],0,1,[()=>xe,0],[()=>$r,0]]],Pe=[9,o,er,{[Ir]:["POST","/token",200]},()=>fe,()=>Se],wr=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??Dt,base64Encoder:e?.base64Encoder??Rt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Yt,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Ht,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new At},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new je}],logger:e?.logger??new We,protocol:e?.protocol??Nt,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:Ee,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",sha256:e?.sha256??bt,urlParser:e?.urlParser??_t,utf8Decoder:e?.utf8Decoder??Ot,utf8Encoder:e?.utf8Encoder??Tt}),Nr=(e)=>{Ye(process.version);let t=rt(e),n=()=>t().then(Je),p=wr(e);Oe(process.version);let s={profile:e?.profile,logger:p.logger};return{...p,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??h(yt,s),bodyLengthChecker:e?.bodyLengthChecker??kt,defaultUserAgentProvider:e?.defaultUserAgentProvider??Re({serviceId:p.serviceId,clientVersion:Vt.version}),maxAttempts:e?.maxAttempts??h(St,e),region:e?.region??h(st,{...it,...s}),requestHandler:wt.create(e?.requestHandler??n),retryMode:e?.retryMode??h({...ft,default:async()=>(await n()).retryMode||xt},e),streamCollector:e?.streamCollector??$t,useDualstackEndpoint:e?.useDualstackEndpoint??h(nt,s),useFipsEndpoint:e?.useFipsEndpoint??h(ot,s),userAgentAppId:e?.userAgentAppId??h(De,s)}},br=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:n,credentials:p}=e;return{setHttpAuthScheme(s){let m=t.findIndex((w)=>w.schemeId===s.schemeId);if(m===-1)t.push(s);else t.splice(m,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){n=s},httpAuthSchemeProvider(){return n},setCredentials(s){p=s},credentials(){return p}}},Ur=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),Fr=(e,t)=>{let n=Object.assign(ke(e),Xe(e),gt(e),br(e));return t.forEach((p)=>p.configure(n)),Object.assign(e,$e(n),Qe(n),Et(n),Ur(n))};class F extends W{config;constructor(...[e]){let t=Nr(e||{});super(t);this.initConfig=t;let n=Gt(t),p=Ne(n),s=vt(p),m=ct(s),w=Ue(m),Ie=lt(w),Ce=Mt(Ie),Ae=Fr(Ce,e?.extensions||[]);this.config=Ae,this.middlewareStack.use(It(this.config)),this.middlewareStack.use(qe(this.config)),this.middlewareStack.use(Pt(this.config)),this.middlewareStack.use(mt(this.config)),this.middlewareStack.use(He(this.config)),this.middlewareStack.use(Me(this.config)),this.middlewareStack.use(Ge(this.config)),this.middlewareStack.use(Ke(this.config,{httpAuthSchemeParametersProvider:Ut,identityProviderConfigProvider:async(ye)=>new Ve({"aws.auth#sigv4":ye.credentials})})),this.middlewareStack.use(ze(this.config))}destroy(){super.destroy()}}var qr=Ze(jt,"AWSSSOOIDCService","SSOOIDCClient",ht),Hr={},Mr=(e,t,n,p)=>[];class H extends qr(Hr,Mr,"CreateToken",Pe){}var Gr={CreateTokenCommand:H};class M extends F{}et(Gr,M);var jr={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},Kr={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};var Lr=S,Br=re,Wr=jr,Yr=v,Jr=ne,Xr=Pe,Qr=H,Zr=fe,eo=Se,to=I,ro=se,oo=C,no=ie,so=A,io=ce,co=y,ao=ae,po=T,uo=pe,lo=Kr,ho=O,_o=de,go=M,Eo=F,mo=i,xo=te,fo=R,So=ue,vo=D,Po=he,Io=k,Co=_e,Ao=Ee;export{Vr as $Command,zr as __Client,Lr as AccessDeniedException,Br as AccessDeniedException$,Wr as AccessDeniedExceptionReason,Yr as AuthorizationPendingException,Jr as AuthorizationPendingException$,Xr as CreateToken$,Qr as CreateTokenCommand,Zr as CreateTokenRequest$,eo as CreateTokenResponse$,to as ExpiredTokenException,ro as ExpiredTokenException$,oo as InternalServerException,no as InternalServerException$,so as InvalidClientException,io as InvalidClientException$,co as InvalidGrantException,ao as InvalidGrantException$,po as InvalidRequestException,uo as InvalidRequestException$,lo as InvalidRequestExceptionReason,ho as InvalidScopeException,_o as InvalidScopeException$,go as SSOOIDC,Eo as SSOOIDCClient,mo as SSOOIDCServiceException,xo as SSOOIDCServiceException$,fo as SlowDownException,So as SlowDownException$,vo as UnauthorizedClientException,Po as UnauthorizedClientException$,Io as UnsupportedGrantTypeException,Co as UnsupportedGrantTypeException$,Ao as errorTypeRegistries};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{P,N}from"./chunk-rkcsrrvy.js";import{E}from"./chunk-mnd4dn3q.js";var p=E(P());var U=(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 v=E(N());var c=E(P());var j=300000,_="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var q=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-g7v8pfhe.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 W=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-g7v8pfhe.js");return(await q(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var X=E(P());var I=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new X.TokenProviderError(`Token is expired. ${_}`,!1)};var z=E(P());var m=(e,o,r=!1)=>{if(typeof o>"u")throw new z.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${_}`,!1)};var J=E(P());import{promises as ee}from"fs";var{writeFile:oe}=ee,V=(e,o)=>{let r=J.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return oe(r,t)};var Y=new Map,R=(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()>j)return a;let d=Y.get(i)??0;if(Date.now()-d<30000)return I(a),a;m("clientId",s.clientId,!0),m("clientSecret",s.clientSecret,!0),m("refreshToken",s.refreshToken,!0);try{Y.set(i,Date.now());let l=await W(s,O,e,o);m("accessToken",l.accessToken),m("expiresIn",l.expiresIn);let x=new Date(Date.now()+l.expiresIn*1000);try{await V(i,{...s,accessToken:l.accessToken,expiresAt:x.toISOString(),refreshToken:l.refreshToken})}catch(h){}return{token:l.accessToken,expiration:x}}catch(l){return I(a),a}};var w=E(P()),C=!1,F=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 R({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-29r6a67p.js"),Z=i||new h(Object.assign({},f??{},{logger:f?.logger??S?.logger??g?.logger,region:f?.region??t,userAgentAppId:f?.userAgentAppId??S?.userAgentAppId??g?.userAgentAppId})),D;try{D=await Z.send(new y({accountId:r,roleName:n,accessToken:x}))}catch(u){throw new w.CredentialsProviderError(u,{tryNextLink:C,logger:a})}let{roleCredentials:{accessKeyId:L,secretAccessKey:M,sessionToken:b,expiration:G,credentialScope:K,accountId:H}={}}=D;if(!L||!M||!b||!G)throw new w.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:C,logger:a});let A={accessKeyId:L,secretAccessKey:M,sessionToken:b,expiration:new Date(G),...K&&{credentialScope:K},...H&&{accountId:H}};if(o)v.setCredentialFeature(A,"CREDENTIALS_SSO","s");else v.setCredentialFeature(A,"CREDENTIALS_SSO_LEGACY","u");return A};var B=E(P()),Q=(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 B.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
|
+
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var se=(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(!U(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}=Q(s,e.logger);return F({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 F({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{se as fromSSO};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Z}from"./chunk-akj1v1zj.js";import{Qe}from"./chunk-stex0y7j.js";import{R,Vt,Wt,pe,wt,Ae}from"./chunk-z19gfsnw.js";import{ie}from"./chunk-rkcsrrvy.js";function v(i,o){let a={v:1,id:i};if(o)a.phase=o;return JSON.stringify(a)}function C(i){if(!i)return;if(i.startsWith("{"))try{let o=JSON.parse(i);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:i}}function J(i,o){let a=o.filter((l)=>l.type==="text").map((l)=>l.text).join(`
|
|
3
|
+
`),u=o.filter((l)=>l.type==="image"),p=a.length>0;if(u.length===0||!i.input.includes("image"))return R(p?a:u.length>0?"(see attached image)":"(no tool output)");let f=[];if(p)f.push({type:"input_text",text:R(a)});for(let l of u)f.push({type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});return f}function Ve(i,o,a,u){let p=[],f=new Set,l=(r)=>{let c=r.replace(/[^a-zA-Z0-9_-]/g,"_");return(c.length>64?c.slice(0,64):c).replace(/_+$/,"")},y=(r)=>{let c=`fc_${Qe(r)}`;return c.length>64?c.slice(0,64):c},m=(r,c,t)=>{if(!a.has(i.provider))return l(r);if(!r.includes("|"))return l(r);let[e,n]=r.split("|"),s=l(e),g=t.provider!==i.provider||t.api!==i.api?y(n):l(n);if(!g.startsWith("fc_"))g=l(`fc_${g}`);return`${s}|${g}`},h=Ae(o.messages,i,m);if((u?.includeSystemPrompt??!0)&&o.systemPrompt){let r=i.compat,c=i.reasoning&&r?.supportsDeveloperRole!==!1?"developer":"system";p.push({role:c,content:R(o.systemPrompt)})}let x=0;for(let r of h){if(r.role==="user")if(typeof r.content==="string")p.push({role:"user",content:[{type:"input_text",text:R(r.content)}]});else{let c=r.content.map((t)=>{if(t.type==="text")return{type:"input_text",text:R(t.text)};return{type:"input_image",detail:"auto",image_url:`data:${t.mimeType};base64,${t.data}`}});if(c.length===0)continue;p.push({role:"user",content:c})}else if(r.role==="assistant"){let c=[],t=r,e=t.model!==i.id&&t.provider===i.provider&&t.api===i.api,n=0;for(let s of r.content)if(s.type==="thinking"){if(s.thinkingSignature){let d=JSON.parse(s.thinkingSignature);c.push(d)}}else if(s.type==="text"){let d=s,g=C(d.textSignature),b=n===0?`msg_pi_${x}`:`msg_pi_${x}_${n}`;n++;let _=g?.id;if(!_)_=b;else if(_.length>64)_=`msg_${Qe(_)}`;c.push({type:"message",role:"assistant",content:[{type:"output_text",text:R(d.text),annotations:[]}],status:"completed",id:_,phase:g?.phase})}else if(s.type==="toolCall"){let d=s,[g,b]=d.id.split("|"),_=u?.grammarToolInputProperties?.get(d.name),k=b;if(e&&k?.startsWith("fc_")||_===void 0&&!k?.startsWith("fc_"))k=void 0;if(_!==void 0)c.push({type:"custom_tool_call",id:k,call_id:g,name:d.name,input:R(Vt(d.name,d.arguments,_))});else c.push({type:"function_call",id:k,call_id:g,name:d.name,arguments:JSON.stringify(d.arguments)})}if(c.length===0)continue;p.push(...c)}else if(r.role==="toolResult"){let[c]=r.toolCallId.split("|"),t=J(i,r.content);if(u?.grammarToolInputProperties?.has(r.toolName))p.push({type:"custom_tool_call_output",call_id:c,output:t});else p.push({type:"function_call_output",call_id:c,output:t});let e=[];for(let n of r.addedToolNames??[]){let s=u?.deferredTools?.get(n);if(!s||f.has(n))continue;f.add(n),e.push(s)}if(e.length>0){let n=e.map((d)=>d.name),s=`pi_tool_load_${Qe(`${r.toolCallId}:${n.join(",")}`)}`;p.push({type:"tool_search_call",call_id:s,execution:"client",status:"completed",arguments:{query:n.join(" "),limit:n.length}}),p.push({type:"tool_search_output",call_id:s,execution:"client",status:"completed",tools:We(e,{...u?.toolOptions,deferLoading:!0})})}}x++}return p}function We(i,o){let a=o?.strict===void 0?!1:o.strict,u=o?.supportsStrictMode??!0,p=o?.supportsOpenAIGrammarTools??!1;return i.map((f)=>{let l=wt(f,p);if(l)return{type:"custom",name:f.name,description:f.description,format:{type:"grammar",syntax:l.format,definition:l.definition},...o?.deferLoading?{defer_loading:!0}:{}};let y=pe(f,u),m={type:"function",name:f.name,description:f.description,parameters:f.parameters,...o?.deferLoading?{defer_loading:!0}:{}};if(u)m.strict=y??a;return m})}function T(i){let o=i.customInput?.property;if(o===void 0)return"";let a=i.arguments[o];return typeof a==="string"?a:""}function S(i,o,a){let u=i.customInput;if(!u)return;let p=Wt(u.jsonBuffer,u.property,o,a);return i.arguments={[u.property]:o},p}async function Je(i,o,a,u,p){let f=!1,l=new Map,y=new Map,m=(t,e)=>{let n=l.get(t);return n?.type===e?n:void 0},h=(t,e)=>{if(e===void 0)return;a.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},I=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=p?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",d={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(d);let g={type:"toolCall",block:d,contentIndex:o.content.length-1};return l.set(t,g),a.push({type:"toolcall_start",contentIndex:g.contentIndex,partial:o}),g}return},x=(t,e)=>l.get(t)??I(t,e),r=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=y.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},c=(t)=>{if(f=!0,r(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,s=e?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-s),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:s,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(ie(u,o.usage),p?.applyServiceTierPricing){let e=p.resolveServiceTier?p.resolveServiceTier(t?.service_tier,p.serviceTier):t?.service_tier??p.serviceTier;p.applyServiceTierPricing(o.usage,e)}if(o.stopReason=w(t?.status),o.content.some((e)=>e.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of i)if(t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")I(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
4
|
+
|
|
5
|
+
`,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
6
|
+
|
|
7
|
+
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=Z(e.block.partialJson),h(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=Z(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)h(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;h(e,S(e.block,T(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;h(e,S(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item,n=x(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((g)=>g.text).join(`
|
|
8
|
+
|
|
9
|
+
`)||"",d=e.content?.map((g)=>g.text).join(`
|
|
10
|
+
|
|
11
|
+
`)||"";n.block.thinking=s||d||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),y.set(e.id,n.block),a.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),l.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=v(e.id,e.phase??void 0),a.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),l.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0)n.block.arguments=Z(e.arguments||n.block.partialJson||"{}"),delete n.block.partialJson,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index);else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput)h(n,S(n.block,e.input??T(n.block),!0)),delete n.block.customInput,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index)}else if(t.type==="response.completed"||t.type==="response.incomplete")c(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){f=!0;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!f)throw Error("OpenAI Responses stream ended before a terminal response event")}function w(i){if(!i)return"stop";switch(i){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:throw Error(`Unhandled stop reason: ${i}`)}}
|
|
12
|
+
export{Ve,We,Je};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{T,ze}from"./chunk-rkcsrrvy.js";function B(u,f){if(typeof u==="string"&&typeof f==="string")return u.toLowerCase()===f.toLowerCase();return u===f}function k(u,f){if(typeof u!=="string")return f.includes(u);return f.some((w)=>typeof w==="string"&&u.toLowerCase()===w.toLowerCase())}function J(u,f){return!k(u,f)}function v(u,f){if(typeof u!=="string"||typeof f!=="string")return!1;return u.toLowerCase().includes(f.toLowerCase())}function _(u,f){if(typeof u!=="string"||typeof f!=="string")return!1;return u.toLowerCase().startsWith(f.toLowerCase())}function x(u,f){if(typeof u!=="string"||typeof f!=="string")return!1;return u.toLowerCase().endsWith(f.toLowerCase())}function N(u){let f=new Map;for(let w of u)f.set(w.id,w);return f}function F(u,f,w){let L=new Set([...Object.keys(f),...Object.keys(w)]);for(let j of L){if(!(j in w)){delete u[j];continue}let d=N(f[j]??[]),m=w[j]??[],R=N(m),M=u[j]??[],A=[],O=new Set;for(let n of M){let r=n.id,l=d.get(r),c=R.get(r);if(l!==void 0&&c===void 0)continue;if(c!==void 0&&z(l,c))A.push(c);else A.push(n);O.add(r)}for(let n of m)if(!d.has(n.id)&&!O.has(n.id))A.push(n);u[j]=A}}function z(u,f){if(u===void 0)return!0;return JSON.stringify(u)!==JSON.stringify(f)}var G=(u,f)=>{let w=null,L=(d)=>ze({config:{adapterId:"memory",adapterName:"Memory Adapter",usePlural:!1,debugLogs:f?.debugLogs||!1,supportsArrays:!0,customTransformInput(m){if(m.options.advanced?.database?.generateId==="serial"&&m.field==="id"&&m.action==="create")return d[m.model].length+1;return m.data},transaction:async(m)=>{let R=structuredClone(d),M=structuredClone(d),A=await m(L(M)(w));return F(d,R,M),A}},adapter:({getFieldName:m,getDefaultFieldName:R,options:M})=>{let A=(n,r,l)=>{if(!r)return n;return n.sort((c,o)=>{let a=m({model:l,field:r.field}),s=c[a],g=o[a],y=0;if(s==null&&g==null)y=0;else if(s==null)y=-1;else if(g==null)y=1;else if(typeof s==="string"&&typeof g==="string")y=s.localeCompare(g);else if(s instanceof Date&&g instanceof Date)y=s.getTime()-g.getTime();else if(typeof s==="number"&&typeof g==="number")y=s-g;else if(typeof s==="boolean"&&typeof g==="boolean")y=s===g?0:s?1:-1;else y=String(s).localeCompare(String(g));return r.direction==="asc"?y:-y})};function O(n,r,l,c,o){let a=(()=>{let y=d[r];if(!y)throw T.error(`[MemoryAdapter] Model ${r} not found in the DB`,Object.keys(d)),Error(`Model ${r} not found`);let h=(e,p)=>{let{field:i,value:t,operator:S,mode:I="sensitive"}=p,b=I==="insensitive"&&(typeof t==="string"||Array.isArray(t)&&t.every((E)=>typeof E==="string"));switch(S){case"in":if(!Array.isArray(t))throw Error("Value must be an array");if(b)return k(e[i],t);return t.includes(e[i]);case"not_in":if(!Array.isArray(t))throw Error("Value must be an array");if(b)return J(e[i],t);return!t.includes(e[i]);case"contains":if(b)return v(e[i],t);return e[i]?.includes(t);case"starts_with":if(b)return _(e[i],t);return e[i].startsWith(t);case"ends_with":if(b)return x(e[i],t);return e[i].endsWith(t);case"ne":return b?!B(e[i],t):e[i]!==t;case"gt":return t!=null&&Boolean(e[i]>t);case"gte":return t!=null&&Boolean(e[i]>=t);case"lt":return t!=null&&Boolean(e[i]<t);case"lte":return t!=null&&Boolean(e[i]<=t);default:if(b)return B(e[i],t);if(t===null)return e[i]==null;return e[i]===t}},C=y.filter((e)=>{if(!n.length||n.length===0)return!0;let p=h(e,n[0]);for(let i of n){let t=h(e,i);if(i.connector==="OR")p=p||t;else p=p&&t}return p});if(o?.length&&o.length>0)C=C.map((e)=>Object.fromEntries(Object.entries(e).filter(([p])=>o.includes(R({model:l,field:p})))));return C})();if(!c)return a;let s=new Map,g=new Map;for(let y of a){let h=String(y.id);if(!s.has(h)){let e={...y};for(let[p,i]of Object.entries(c)){let t=p;if(i.relation==="one-to-one")e[t]=null;else e[t]=[],g.set(`${h}-${p}`,new Set)}s.set(h,e)}let C=s.get(h);for(let[e,p]of Object.entries(c)){let i=e,t=d[i];if(!t)throw T.error(`[MemoryAdapter] JoinOption model ${i} not found in the DB`,Object.keys(d)),Error(`JoinOption model ${i} not found`);let S=t.filter((I)=>I[p.on.to]===y[p.on.from]);if(p.relation==="one-to-one")C[i]=S[0]||null;else{let I=g.get(`${h}-${e}`),b=p.limit??100,E=0;for(let W of S){if(E>=b)break;if(!I.has(W.id))C[i].push(W),I.add(W.id),E++}}}}return Array.from(s.values())}return{create:async({model:n,data:r})=>{if(M.advanced?.database?.generateId==="serial")r.id=d[n].length+1;if(!d[n])d[n]=[];return d[n].push(r),r},findOne:async({model:n,modelKey:r=n,where:l,select:c,join:o})=>{let a=O(l,n,r,o,c);if(o){let s=a;if(!s.length)return null;return s[0]}return a[0]||null},findMany:async({model:n,modelKey:r=n,where:l,sortBy:c,limit:o,select:a,offset:s,join:g})=>{let y=O(l||[],n,r,g,a);if(g){let C=y;if(!C.length)return[];A(C,c,r);let e=C;if(s!==void 0)e=e.slice(s);if(o!==void 0)e=e.slice(0,o);return e}let h=A(y,c,r);if(s!==void 0)h=h.slice(s);if(o!==void 0)h=h.slice(0,o);return h||[]},count:async({model:n,modelKey:r=n,where:l})=>{if(l)return O(l,n,r).length;return d[n].length},update:async({model:n,modelKey:r=n,where:l,update:c})=>{if(l.length===0)return null;let o=O(l,n,r);return o.forEach((a)=>{Object.assign(a,c)}),o[0]||null},delete:async({model:n,modelKey:r=n,where:l})=>{if(l.length===0)return;let c=d[n],o=O(l,n,r);d[n]=c.filter((a)=>!o.includes(a))},deleteMany:async({model:n,modelKey:r=n,where:l})=>{let c=d[n],o=O(l,n,r),a=0;return d[n]=c.filter((s)=>{if(o.includes(s))return a++,!1;return!o.includes(s)}),a},consumeOne:async({model:n,modelKey:r=n,where:l})=>{let c=d[n],o=O(l,n,r)[0];if(!o)return null;return d[n]=c.filter((a)=>a!==o),o},incrementOne:async({model:n,modelKey:r=n,where:l,increment:c,set:o})=>{let a=O(l,n,r)[0];if(!a)return null;for(let[s,g]of Object.entries(c))a[s]=(typeof a[s]==="number"?a[s]:0)+g;if(o)Object.assign(a,o);return a},updateMany:async({model:n,modelKey:r=n,where:l,update:c})=>{let o=O(l,n,r);return o.forEach((a)=>{Object.assign(a,c)}),o.length}}}}),j=L(u);return(d)=>(w=d,j(d))};export{G as memoryAdapter};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{A,C}from"./chunk-mnd4dn3q.js";var Y=A(function(wt,X){var I=1000,M=I*60,N=M*60,P=N*24,Oe=P*7,Se=P*365.25;X.exports=function(e,r){r=r||{};var t=typeof e;if(t==="string"&&e.length>0)return Pe(e);else if(t==="number"&&isFinite(e))return r.long?Ae(e):je(e);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Pe(e){if(e=String(e),e.length>100)return;var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!r)return;var t=parseFloat(r[1]),n=(r[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Se;case"weeks":case"week":case"w":return t*Oe;case"days":case"day":case"d":return t*P;case"hours":case"hour":case"hrs":case"hr":case"h":return t*N;case"minutes":case"minute":case"mins":case"min":case"m":return t*M;case"seconds":case"second":case"secs":case"sec":case"s":return t*I;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}function je(e){var r=Math.abs(e);if(r>=P)return Math.round(e/P)+"d";if(r>=N)return Math.round(e/N)+"h";if(r>=M)return Math.round(e/M)+"m";if(r>=I)return Math.round(e/I)+"s";return e+"ms"}function Ae(e){var r=Math.abs(e);if(r>=P)return T(e,r,P,"day");if(r>=N)return T(e,r,N,"hour");if(r>=M)return T(e,r,M,"minute");if(r>=I)return T(e,r,I,"second");return e+" ms"}function T(e,r,t,n){var s=r>=t*1.5;return Math.round(e/t)+" "+n+(s?"s":"")}});var G=A(function(Ft,ee){function Ee(e){t.debug=t,t.default=t,t.coerce=w,t.disable=l,t.enable=s,t.enabled=_,t.humanize=Y(),t.destroy=B,Object.keys(e).forEach((o)=>{t[o]=e[o]}),t.names=[],t.skips=[],t.formatters={};function r(o){let i=0;for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c),i|=0;return t.colors[Math.abs(i)%t.colors.length]}t.selectColor=r;function t(o){let i,c=null,a,g;function f(...d){if(!f.enabled)return;let v=f,b=Number(new Date),O=b-(i||b);if(v.diff=O,v.prev=i,v.curr=b,i=b,d[0]=t.coerce(d[0]),typeof d[0]!=="string")d.unshift("%O");let F=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(S,E)=>{if(S==="%%")return"%";F++;let V=t.formatters[E];if(typeof V==="function"){let xe=d[F];S=V.call(v,xe),d.splice(F,1),F--}return S}),t.formatArgs.call(v,d),(v.log||t.log).apply(v,d)}if(f.namespace=o,f.useColors=t.useColors(),f.color=t.selectColor(o),f.extend=n,f.destroy=t.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(c!==null)return c;if(a!==t.namespaces)a=t.namespaces,g=t.enabled(o);return g},set:(d)=>{c=d}}),typeof t.init==="function")t.init(f);return f}function n(o,i){let c=t(this.namespace+(typeof i>"u"?":":i)+o);return c.log=this.log,c}function s(o){t.save(o),t.namespaces=o,t.names=[],t.skips=[];let i=(typeof o==="string"?o:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let c of i)if(c[0]==="-")t.skips.push(c.slice(1));else t.names.push(c)}function u(o,i){let c=0,a=0,g=-1,f=0;while(c<o.length)if(a<i.length&&(i[a]===o[c]||i[a]==="*"))if(i[a]==="*")g=a,f=c,a++;else c++,a++;else if(g!==-1)a=g+1,f++,c=f;else return!1;while(a<i.length&&i[a]==="*")a++;return a===i.length}function l(){let o=[...t.names,...t.skips.map((i)=>"-"+i)].join(",");return t.enable(""),o}function _(o){for(let i of t.skips)if(u(o,i))return!1;for(let i of t.names)if(u(o,i))return!0;return!1}function w(o){if(o instanceof Error)return o.stack||o.message;return o}function B(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ee.exports=Ee});var te=A(function(J,H){J.formatArgs=Me;J.save=Ne;J.load=qe;J.useColors=Ie;J.storage=Be();J.destroy=(()=>{let e=!1;return()=>{if(!e)e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();J.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ie(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Me(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+H.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;e.splice(1,0,r,"color: inherit");let t=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(s)=>{if(s==="%%")return;if(t++,s==="%c")n=t}),e.splice(n,0,r)}J.log=console.debug||console.log||(()=>{});function Ne(e){try{if(e)J.storage.setItem("debug",e);else J.storage.removeItem("debug")}catch(r){}}function qe(){let e;try{e=J.storage.getItem("debug")||J.storage.getItem("DEBUG")}catch(r){}if(!e&&typeof process<"u"&&"env"in process)e=process.env.DEBUG;return e}function Be(){try{return localStorage}catch(e){}}H.exports=G()(J);var{formatters:De}=H.exports;De.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}});var oe=A(function(W,R){var re=C("tty"),x=C("util");W.init=Qe;W.log=We;W.formatArgs=Ge;W.save=Ze;W.load=Ke;W.useColors=ze;W.destroy=x.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");W.colors=[6,2,3,4,5,1];try{let e=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(e&&(e.stderr||e).level>=2)W.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(e){}W.inspectOpts=Object.keys(process.env).filter((e)=>/^debug_/i.test(e)).reduce((e,r)=>{let t=r.substring(6).toLowerCase().replace(/_([a-z])/g,(s,u)=>u.toUpperCase()),n=process.env[r];if(/^(yes|on|true|enabled)$/i.test(n))n=!0;else if(/^(no|off|false|disabled)$/i.test(n))n=!1;else if(n==="null")n=null;else n=Number(n);return e[t]=n,e},{});function ze(){return"colors"in W.inspectOpts?Boolean(W.inspectOpts.colors):re.isatty(process.stderr.fd)}function Ge(e){let{namespace:r,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),u=` ${s};1m${r} \x1B[0m`;e[0]=u+e[0].split(`
|
|
3
|
+
`).join(`
|
|
4
|
+
`+u),e.push(s+"m+"+R.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=Je()+r+" "+e[0]}function Je(){if(W.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function We(...e){return process.stderr.write(x.formatWithOptions(W.inspectOpts,...e)+`
|
|
5
|
+
`)}function Ze(e){if(e)process.env.DEBUG=e;else delete process.env.DEBUG}function Ke(){return process.env.DEBUG}function Qe(e){e.inspectOpts={};let r=Object.keys(W.inspectOpts);for(let t=0;t<r.length;t++)e.inspectOpts[r[t]]=W.inspectOpts[r[t]]}R.exports=G()(W);var{formatters:ne}=R.exports;ne.o=function(e){return this.inspectOpts.colors=this.useColors,x.inspect(e,this.inspectOpts).split(`
|
|
6
|
+
`).map((r)=>r.trim()).join(" ")};ne.O=function(e){return this.inspectOpts.colors=this.useColors,x.inspect(e,this.inspectOpts)}});var K=A(function(St,Z){if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Z.exports=te();else Z.exports=oe()});var ue=A(function(p){var st=p&&p.__createBinding||(Object.create?function(e,r,t,n){if(n===void 0)n=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,n,s)}:function(e,r,t,n){if(n===void 0)n=t;e[n]=r[t]}),ot=p&&p.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),ie=p&&p.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))st(r,e,t)}return ot(r,e),r};Object.defineProperty(p,"__esModule",{value:!0});p.req=p.json=p.toBuffer=void 0;var it=ie(C("http")),ct=ie(C("https"));async function ce(e){let r=0,t=[];for await(let n of e)r+=n.length,t.push(n);return Buffer.concat(t,r)}p.toBuffer=ce;async function ut(e){let t=(await ce(e)).toString("utf8");try{return JSON.parse(t)}catch(n){let s=n;throw s.message+=` (input: ${t})`,s}}p.json=ut;function at(e,r={}){let n=((typeof e==="string"?e:e.href).startsWith("https:")?ct:it).request(e,r),s=new Promise((u,l)=>{n.once("response",u).once("error",l).end()});return n.then=s.then.bind(s),n}p.req=at});var he=A(function(h){var fe=h&&h.__createBinding||(Object.create?function(e,r,t,n){if(n===void 0)n=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,n,s)}:function(e,r,t,n){if(n===void 0)n=t;e[n]=r[t]}),ft=h&&h.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),le=h&&h.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))fe(r,e,t)}return ft(r,e),r},lt=h&&h.__exportStar||function(e,r){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t))fe(r,e,t)};Object.defineProperty(h,"__esModule",{value:!0});h.Agent=void 0;var dt=le(C("net")),ae=le(C("http")),de=C("https");lt(ue(),h);var m=Symbol("AgentBaseInternalState");class pe extends ae.Agent{constructor(e){super(e);this[m]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==="boolean")return e.secureEndpoint;if(typeof e.protocol==="string")return e.protocol==="https:"}let{stack:r}=Error();if(typeof r!=="string")return!1;return r.split(`
|
|
7
|
+
`).some((t)=>t.indexOf("(https.js:")!==-1||t.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[e])this.sockets[e]=[];let r=new dt.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let t=this.sockets[e],n=t.indexOf(r);if(n!==-1){if(t.splice(n,1),this.totalSocketCount--,t.length===0)delete this.sockets[e]}}getName(e){if(this.isSecureEndpoint(e))return de.Agent.prototype.getName.call(this,e);return super.getName(e)}createSocket(e,r,t){let n={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(n),u=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,n)).then((l)=>{if(this.decrementSockets(s,u),l instanceof ae.Agent)try{return l.addRequest(e,n)}catch(_){return t(_)}this[m].currentSocket=l,super.createSocket(e,r,t)},(l)=>{this.decrementSockets(s,u),t(l)})}createConnection(){let e=this[m].currentSocket;if(this[m].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[m].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){if(this[m])this[m].defaultPort=e}get protocol(){return this[m].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){if(this[m])this[m].protocol=e}}h.Agent=pe});var Ce=A(function(q){var pt=q&&q.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(q,"__esModule",{value:!0});q.parseProxyResponse=void 0;var ht=pt(K()),U=(0,ht.default)("https-proxy-agent:parse-proxy-response");function Ct(e){return new Promise((r,t)=>{let n=0,s=[];function u(){let o=e.read();if(o)B(o);else e.once("readable",u)}function l(){e.removeListener("end",_),e.removeListener("error",w),e.removeListener("readable",u)}function _(){l(),U("onend"),t(Error("Proxy connection ended before receiving CONNECT response"))}function w(o){l(),U("onerror %o",o),t(o)}function B(o){s.push(o),n+=o.length;let i=Buffer.concat(s,n),c=i.indexOf(`\r
|
|
8
|
+
\r
|
|
9
|
+
`);if(c===-1){U("have not received end of HTTP headers yet..."),u();return}let a=i.slice(0,c).toString("ascii").split(`\r
|
|
10
|
+
`),g=a.shift();if(!g)return e.destroy(),t(Error("No header received from proxy CONNECT response"));let f=g.split(" "),d=+f[1],v=f.slice(2).join(" "),b={};for(let O of a){if(!O)continue;let F=O.indexOf(":");if(F===-1)return e.destroy(),t(Error(`Invalid header from proxy CONNECT response: "${O}"`));let L=O.slice(0,F).toLowerCase(),S=O.slice(F+1).trimStart(),E=b[L];if(typeof E==="string")b[L]=[E,S];else if(Array.isArray(E))E.push(S);else b[L]=S}U("got proxy server response: %o %o",g,b),l(),r({connect:{statusCode:d,statusText:v,headers:b},buffered:i})}e.on("error",w),e.on("end",_),u()})}q.parseProxyResponse=Ct});var _t=A(function(y){var yt=y&&y.__createBinding||(Object.create?function(e,r,t,n){if(n===void 0)n=t;var s=Object.getOwnPropertyDescriptor(r,t);if(!s||("get"in s?!r.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return r[t]}};Object.defineProperty(e,n,s)}:function(e,r,t,n){if(n===void 0)n=t;e[n]=r[t]}),gt=y&&y.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),me=y&&y.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null){for(var t in e)if(t!=="default"&&Object.prototype.hasOwnProperty.call(e,t))yt(r,e,t)}return gt(r,e),r},ve=y&&y.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(y,"__esModule",{value:!0});y.HttpsProxyAgent=void 0;var z=me(C("net")),ye=me(C("tls")),bt=ve(C("assert")),mt=ve(K()),_e=he(),we=C("url"),Fe=Ce(),k=(0,mt.default)("https-proxy-agent"),ge=(e)=>{if(e.servername===void 0&&e.host&&!z.isIP(e.host))return{...e,servername:e.host};return e};class Q extends _e.Agent{constructor(e,r){super(r);this.options={path:void 0},this.proxy=typeof e==="string"?new we.URL(e):e,this.proxyHeaders=r?.headers??{},k("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let t=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),n=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...r?be(r,"headers"):null,host:t,port:n}}async connect(e,r){let{proxy:t}=this;if(!r.host)throw TypeError('No "host" provided');let n;if(t.protocol==="https:")k("Creating `tls.Socket`: %o",this.connectOpts),n=ye.connect(ge(this.connectOpts));else k("Creating `net.Socket`: %o",this.connectOpts),n=z.connect(this.connectOpts);let s=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},u=z.isIPv6(r.host)?`[${r.host}]`:r.host,l=`CONNECT ${u}:${r.port} HTTP/1.1\r
|
|
11
|
+
`;if(t.username||t.password){let i=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(i).toString("base64")}`}if(s.Host=`${u}:${r.port}`,!s["Proxy-Connection"])s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let i of Object.keys(s))l+=`${i}: ${s[i]}\r
|
|
12
|
+
`;let _=Fe.parseProxyResponse(n);n.write(`${l}\r
|
|
13
|
+
`);let{connect:w,buffered:B}=await _;if(e.emit("proxyConnect",w),this.emit("proxyConnect",w,e),w.statusCode===200){if(e.once("socket",vt),r.secureEndpoint)return k("Upgrading socket connection to TLS"),ye.connect({...be(ge(r),"host","path","port"),socket:n});return n}n.destroy();let o=new z.Socket({writable:!1});return o.readable=!0,e.once("socket",(i)=>{k("Replaying proxy buffer for failed request"),(0,bt.default)(i.listenerCount("data")>0),i.push(B),i.push(null)}),o}}Q.protocols=["http","https"];y.HttpsProxyAgent=Q;function vt(e){e.resume()}function be(e,...r){let t={},n;for(n in e)if(!r.includes(n))t[n]=e[n];return t}});export default _t();
|