@shumai-one/shumai-agent 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/bin/chunk-07a5rjnq.js +2 -0
  2. package/bin/chunk-1a493esq.js +2 -0
  3. package/bin/chunk-1y3q1jce.js +2 -0
  4. package/bin/chunk-2mcnt6jh.js +8 -0
  5. package/bin/chunk-33n9p9q4.js +3 -0
  6. package/bin/chunk-40bcg5we.js +2 -0
  7. package/bin/chunk-4926dhzq.js +4 -0
  8. package/bin/chunk-4q9h14c1.js +3 -0
  9. package/bin/chunk-5n4wvh5p.js +3 -0
  10. package/bin/chunk-6195gx01.js +8 -0
  11. package/bin/chunk-8jd9p0bt.js +45 -0
  12. package/bin/chunk-8tj47emj.js +2 -0
  13. package/bin/chunk-9bpp5v13.js +13320 -0
  14. package/bin/chunk-a4xcn19j.js +3 -0
  15. package/bin/chunk-as1vqgag.js +2 -0
  16. package/bin/chunk-b2205272.js +3 -0
  17. package/bin/chunk-bbz8hcag.js +2 -0
  18. package/bin/chunk-cwq65x99.js +2 -0
  19. package/bin/chunk-dc4f80kq.js +2 -0
  20. package/bin/chunk-e7m6nsvr.js +3 -0
  21. package/bin/chunk-edkxjkdy.js +2 -0
  22. package/bin/chunk-fvz08he3.js +2 -0
  23. package/bin/chunk-gekdwjxf.js +2 -0
  24. package/bin/chunk-gqtret3n.js +2 -0
  25. package/bin/chunk-grtavkr4.js +3 -0
  26. package/bin/chunk-h65eqsrp.js +7 -0
  27. package/bin/chunk-hbmbvjjq.js +3 -0
  28. package/bin/chunk-jkx975yd.js +2 -0
  29. package/bin/chunk-jt36jdn3.js +2 -0
  30. package/bin/chunk-k975ym8c.js +7 -0
  31. package/bin/chunk-kd561cva.js +2 -0
  32. package/bin/chunk-m8jmvj7p.js +3 -0
  33. package/bin/chunk-nmxr1m3s.js +2 -0
  34. package/bin/chunk-nwjh8gnr.js +3 -0
  35. package/bin/chunk-s1e2nv5w.js +5 -0
  36. package/bin/chunk-sbtjx4y3.js +2 -0
  37. package/bin/chunk-sfx1j3yr.js +11 -0
  38. package/bin/chunk-sq5rat8t.js +2 -0
  39. package/bin/chunk-td2tpqfb.js +12 -0
  40. package/bin/chunk-tdah647g.js +13 -0
  41. package/bin/chunk-vnn8sej7.js +24 -0
  42. package/bin/chunk-vv932dz6.js +2 -0
  43. package/bin/chunk-vvvkt1vd.js +2 -0
  44. package/bin/chunk-wdvv14a7.js +2 -0
  45. package/bin/chunk-wg6xrc3y.js +3 -0
  46. package/bin/chunk-wzysrq4c.js +16 -0
  47. package/bin/chunk-xp2anj2s.js +3 -0
  48. package/bin/chunk-y2adfzyt.js +2 -0
  49. package/bin/chunk-zdkpvcak.js +4 -0
  50. package/bin/shumai-agent-app.js +912 -666
  51. package/package.json +18 -18
  52. package/prisma/migrations/20260904022457_add_agent_id_to_assets_and_audit_logs/migration.sql +17 -0
  53. package/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql +15 -0
  54. package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
  55. package/prisma/schema.prisma +10 -0
  56. package/bin/chunk-1ep7nnzp.js +0 -5
  57. package/bin/chunk-1jq2vgrd.js +0 -3
  58. package/bin/chunk-2ntm65jn.js +0 -3
  59. package/bin/chunk-3nh1p64q.js +0 -12
  60. package/bin/chunk-41gh01qj.js +0 -3
  61. package/bin/chunk-4n1309xp.js +0 -2
  62. package/bin/chunk-616f7y5x.js +0 -8
  63. package/bin/chunk-6a9h5d64.js +0 -3
  64. package/bin/chunk-6dp3ybh2.js +0 -3
  65. package/bin/chunk-6nd8f70y.js +0 -4
  66. package/bin/chunk-6vs3gb9g.js +0 -2
  67. package/bin/chunk-7dyx5m0f.js +0 -6
  68. package/bin/chunk-7j3qbvwc.js +0 -7
  69. package/bin/chunk-9h5qhgqx.js +0 -13
  70. package/bin/chunk-b9s67nd8.js +0 -2
  71. package/bin/chunk-c14kvr2r.js +0 -11
  72. package/bin/chunk-cb5p7shk.js +0 -12240
  73. package/bin/chunk-ccx6803n.js +0 -44
  74. package/bin/chunk-cm4dpd3k.js +0 -4
  75. package/bin/chunk-dd2tfwzy.js +0 -45
  76. package/bin/chunk-dk9vz5tv.js +0 -4
  77. package/bin/chunk-e6691p0v.js +0 -3
  78. package/bin/chunk-e9d2ah8y.js +0 -3
  79. package/bin/chunk-fvmb8en4.js +0 -24
  80. package/bin/chunk-gegf6d3m.js +0 -2
  81. package/bin/chunk-gx9vdcbm.js +0 -2
  82. package/bin/chunk-j427r7a5.js +0 -2
  83. package/bin/chunk-jperx2a8.js +0 -6
  84. package/bin/chunk-k4jm2gt4.js +0 -3
  85. package/bin/chunk-m29dphbf.js +0 -3
  86. package/bin/chunk-mpgy1y53.js +0 -3
  87. package/bin/chunk-n1t3he2k.js +0 -3
  88. package/bin/chunk-pmdb6y7t.js +0 -2
  89. package/bin/chunk-qx9njyk7.js +0 -3
  90. package/bin/chunk-r5h7vczc.js +0 -3
  91. package/bin/chunk-spm76160.js +0 -2
  92. package/bin/chunk-t8k09sgb.js +0 -3
  93. package/bin/chunk-tvef1ck8.js +0 -2
  94. package/bin/chunk-v4j6yxch.js +0 -3
  95. package/bin/chunk-vjzrmneg.js +0 -2
  96. package/bin/chunk-x25enwfz.js +0 -3
  97. package/bin/chunk-xg9xscqz.js +0 -1
  98. package/bin/chunk-xqg06q7q.js +0 -2
  99. package/bin/chunk-xvbd9e2b.js +0 -8
  100. package/bin/chunk-y2z3xj0m.js +0 -12
  101. package/bin/chunk-ywhrsshf.js +0 -2
  102. package/bin/chunk-z512b49m.js +0 -3
  103. package/bin/chunk-z58rb52r.js +0 -3
  104. package/bin/chunk-zazbsz25.js +0 -3
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ import{y}from"./chunk-e7m6nsvr.js";import"./chunk-s1e2nv5w.js";import{Ie}from"./chunk-4q9h14c1.js";import{ce,ue,de}from"./chunk-td2tpqfb.js";import{Y}from"./chunk-nwjh8gnr.js";import{F,Q}from"./chunk-33n9p9q4.js";import{L,B}from"./chunk-xp2anj2s.js";import{U}from"./chunk-m8jmvj7p.js";import{xe,ze,ve,I,S,Je}from"./shumai-agent-app.js";var re=new Set;function ne(e){return re.add(e),()=>{re.delete(e)}}function oe(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var Ce={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function j(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||y(r)||y(n)||""}function Oe(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function Ae(e,t,r){let n=j("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function Le(e,t){let r=Oe(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||Ce[n]||0;if(!Ae(s,o,t))return"";let i=j(`${n}_proxy`,t)||j("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var We="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function se(e,t){let r=Le(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${We} Got ${n.protocol}`);return n}function Ne(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var H=Ne(),Pe="https://chatgpt.com/backend-api",Me="https://api.openai.com/auth",De=0,ie=1000,qe=60000,Be=15000,Ue=3,ye=new Set(["openai","openai-codex","opencode"]),$e=1009,Fe="websocket_connection_limit_reached",He="previous_response_not_found",Ke=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ge(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,t){if(e===429&&Ge(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function je(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class ee extends Error{}function Ve(e,t){let r=t?.maxRetryDelayMs??qe;if(r>0&&e>r)throw new ee(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function ae(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function le(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ye(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let t=Ye();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Ue}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var Qe=(e,t,r)=>{let n=new I;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",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=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=Ct(o),l=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=Y(a),d=et(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let E=c||Je(),f=Ot(e.headers,r?.headers,i,o,c),_=At(e.headers,r?.headers,i,o,E),m=JSON.stringify(d),p=le(r?.timeoutMs),C=le(r?.websocketConnectTimeoutMs),b=r?.transport||"auto",w=!1,h=b!=="sse"&&Se(a);if(h)fe(a);if(b!=="sse"&&!h){let g=!1,T=!1,A=!1;while(!0){g=!1;try{if(await xt(rt(e.baseUrl),d,_,s,n,e,()=>{if(g=!0,!w)w=!0,n.push({type:"start",partial:s})},p,C,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(x){let D=r?.signal?.aborted,q=!g&&st(x),N=it(x);if(!D&&N&&!A){A=!0;continue}if(!D&&q&&!T){T=!0;continue}if(D||ot(x)&&!q)throw x;if(ve(s,ze("provider_transport_failure",x,{configuredTransport:b,fallbackTransport:g?void 0:"sse",eventsEmitted:g,phase:g?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),mt(a,x),g)throw x;fe(a);break}}}let O=Ze(m);if(O)f.set("content-encoding","zstd");let W=O??m,k,M,X=r?.maxRetries??De;for(let g=0;g<=X;g++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let T=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,A=oe([r?.signal,T]);try{k=await fetch(we(e.baseUrl),{method:"POST",headers:f,body:W,signal:A.signal})}catch(N){if(T?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw N}finally{A.cleanup()}if(await r?.onResponse?.({status:k.status,headers:U(k.headers)},e),k.ok)break;let x=await k.text();if(g<X&&Xe(k.status,x)){let N=je(k.headers),Re=N===void 0?ie*2**g:Ve(N,r);await ae(Re,r?.signal);continue}let D=new Response(x,{status:k.status,statusText:k.statusText}),q=await vt(D);throw Error(q.friendlyMessage||q.message)}catch(T){if(T instanceof Error){if(T.name==="AbortError"||T.message==="Request was aborted")throw Error("Request was aborted")}if(M=T instanceof Error?T:Error(String(T)),g<X&&!(M instanceof ee)&&!M.message.includes("usage limit")){let A=ie*2**g;await ae(A,r?.signal);continue}throw M}}if(!k?.ok)throw M??Error("Failed after retries");if(!k.body)throw Error("No response body");if(!w)w=!0,n.push({type:"start",partial:s});if(await nt(k,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=Q(F(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},jt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=B(e,t,r,n),o=r?.reasoning?S(e,r.reasoning):void 0;return Qe(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function et(e,t,r,n,s=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ie(t,e.compat?.supportsToolSearch??!1),a=ce(e,t,ye,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=ue(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function tt(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function be(e,t,r){let n=tt(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function he(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function we(e){let r=(e&&e.trim().length>0?e:Pe).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function rt(e){let t=new URL(we(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function nt(e,t,r,n,s,o){await de(ge(ut(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:he,applyServiceTierPricing:(i,l)=>be(i,l,n)})}class P extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class z extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function ot(e){return e instanceof P||e instanceof z}function st(e){return e instanceof P&&e.code===Fe}function it(e){return e instanceof P&&e.code===He}function at(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*ge(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=at(t);throw new P(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new P(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:ct(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function ct(e){if(typeof e!=="string")return;return Ke.has(e)?e:void 0}async function*ut(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
3
+
4
+ `);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let d=c.split(`
5
+ `).filter((u)=>u.startsWith("data:")).map((u)=>u.slice(5).trim());if(d.length>0){let u=d.join(`
6
+ `).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(E){throw new z(`Invalid Codex SSE JSON: ${xe(E)}`,{cause:E,payload:u})}}a=s.indexOf(`
7
+
8
+ `)}}}finally{t?.removeEventListener("abort",o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var lt="responses_websockets=2026-02-06",ft=300000,dt=3300000,R=new Map,J=new Map,G=new Set;function te(e){let t=J.get(e);if(!t)t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},J.set(e,t);return t}function Vt(e){let t=J.get(e);return t?{...t}:void 0}function Yt(e){if(e){J.delete(e),G.delete(e);return}J.clear(),G.clear()}function pt(e){let t=(r)=>{if(r.idleTimer)clearTimeout(r.idleTimer);v(r.socket,1000,"debug_close")};if(e){let r=R.get(e);if(r)t(r);R.delete(e);return}for(let r of R.values())t(r);R.clear()}ne(pt);function Se(e){return e?G.has(e):!1}function fe(e){if(!e)return;let t=te(e);t.sseFallbacks++,t.websocketFallbackActive=Se(e)}function mt(e,t){if(!e)return;G.add(e);let r=te(e);r.websocketFailures++,r.lastWebSocketError=xe(t),r.websocketFallbackActive=!0}var V=null;async function yt(e){if(!e&&V)return V;if(typeof process<"u"&&process.versions?.bun){let r=class extends WebSocket{constructor(n,s){let o={};if(Array.isArray(s)||typeof s==="string")o={protocols:s};else o={...s};let i=se(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...o,...i?{proxy:i.toString()}:{}})}};if(!e)V=r;return r}let t=globalThis.WebSocket;if(typeof t!=="function")return null;return t}class Ee extends Error{code;reason;wasClean;constructor(e,t){super(e);this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function bt(e){let t=e.readyState;return typeof t==="number"?t:void 0}function K(e){let t=bt(e);return t===void 0||t===1}function ht(e){return Date.now()-e.createdAt>=dt}function v(e,t=1000,r="done"){try{e.close(t,r)}catch{}}function pe(e,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;v(t.socket,1000,"idle_timeout"),R.delete(e)},ft)}async function Z(e,t,r,n=Be,s){let o=await yt(s);if(!o)throw Error("WebSocket transport is not available in this runtime");let i=U(t);return delete i["OpenAI-Beta"],new Promise((l,a)=>{let c=!1,d,u;try{u=new o(e,{headers:i})}catch(b){a(b instanceof Error?b:Error(String(b)));return}let E=()=>{if(d)clearTimeout(d),d=void 0;u.removeEventListener("open",_),u.removeEventListener("error",m),u.removeEventListener("close",p),r?.removeEventListener("abort",C)},f=(b,w)=>{if(c)return;if(c=!0,E(),w)v(u,1000,w);a(b)},_=()=>{if(c)return;c=!0,E(),l(u)},m=(b)=>{f(_e(b))},p=(b)=>{f(ke(b))},C=()=>{f(Error("Request was aborted"),"aborted")};if(u.addEventListener("open",_),u.addEventListener("error",m),u.addEventListener("close",p),r?.addEventListener("abort",C),n>0)d=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(r?.aborted)C()})}async function wt(e,t,r,n,s,o){if(!r){let c=await Z(e,t,n,s,o);return{socket:c,reused:!1,release:()=>v(c)}}let i=R.get(r);if(i){if(i.idleTimer)clearTimeout(i.idleTimer),i.idleTimer=void 0;if(!i.busy&&ht(i))v(i.socket,1000,"connection_age_limit"),R.delete(r);else if(!i.busy&&K(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:c}={})=>{if(!c||!K(i.socket)){v(i.socket),R.delete(r);return}i.busy=!1,pe(r,i)}};if(i.busy){let c=await Z(e,t,n,s,o);return{socket:c,reused:!1,release:()=>{v(c)}}}if(!K(i.socket))v(i.socket),R.delete(r)}let l=await Z(e,t,n,s,o),a={socket:l,busy:!0,createdAt:Date.now()};return R.set(r,a),{socket:l,entry:a,reused:!1,release:({keep:c}={})=>{if(!c||!K(a.socket)){if(v(a.socket),a.idleTimer)clearTimeout(a.idleTimer);if(R.get(r)===a)R.delete(r);return}a.busy=!1,pe(r,a)}}}function _e(e){if(e&&typeof e==="object"){let t="message"in e?e.message:void 0;if(typeof t==="string"&&t.length>0)return Error(t);let r="error"in e?e.error:void 0;if(r instanceof Error&&r.message.length>0)return r;if(r&&typeof r==="object"&&"message"in r){let n=r.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function ke(e){if(e&&typeof e==="object"){let t="code"in e?e.code:void 0,r="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,s=typeof t==="number"?` ${t}`:"",o=typeof r==="string"&&r.length>0?` ${r}`:"";if(!o&&t===$e)o=" message too big";return new Ee(`WebSocket closed${s}${o}`.trim(),{code:typeof t==="number"?t:void 0,reason:typeof r==="string"&&r.length>0?r:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function gt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==="object"&&"arrayBuffer"in e){let r=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(r))}return null}async function*St(e,t,r){let n=[],s=null,o=!1,i=null,l=!1,a=()=>{if(!s)return;let f=s;s=null,f()},c=(f)=>{(async()=>{let _=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(_=await gt(f.data),!_)return;let m=JSON.parse(_),p=typeof m.type==="string"?m.type:"";if(p==="response.completed"||p==="response.done"||p==="response.incomplete")l=!0,o=!0;n.push(m),a()}catch(m){i=new z(`Invalid Codex WebSocket JSON: ${xe(m)}`,{cause:m,payload:_}),o=!0,a()}})()},d=(f)=>{i=_e(f),o=!0,a()},u=(f)=>{if(l){o=!0,a();return}if(!i)i=ke(f);o=!0,a()},E=()=>{i=Error("Request was aborted"),o=!0,a()};e.addEventListener("message",c),e.addEventListener("error",d),e.addEventListener("close",u),t?.addEventListener("abort",E);try{while(!0){if(t?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(o)break;let f;await new Promise((_,m)=>{if(s=_,r!==void 0&&r>0)f=setTimeout(()=>{let p=Error(`WebSocket idle timeout after ${r}ms`);i=p,o=!0,s=null,v(e,1000,"idle_timeout"),m(p)},r)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!l)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",c),e.removeEventListener("error",d),e.removeEventListener("close",u),t?.removeEventListener("abort",E)}}function me(e){let{input:t,previous_response_id:r,...n}=e;return n}function Et(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function _t(e,t){return JSON.stringify(me(e))===JSON.stringify(me(t))}function kt(e,t){if(!_t(e,t.lastRequestBody))return;let r=e.input??[],n=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(r.length<n.length)return;let s=r.slice(0,n.length);if(!Et(s,n))return;return r.slice(n.length)}function Tt(e,t){let r=e.continuation;if(!r)return t;let n=kt(t,r);if(!n||!r.lastResponseId)return e.continuation=void 0,t;return{...t,previous_response_id:r.lastResponseId,input:n}}async function*Rt(e,t){let r=!1;for await(let n of e){if(!r)r=!0,t();yield n}}async function xt(e,t,r,n,s,o,i,l,a,c,d,u){let{socket:E,entry:f,reused:_,release:m}=await wt(e,r,c,u?.signal,a,u?.env),p=!0,C=u?.transport==="websocket-cached"||u?.transport==="auto",b=t,w=C&&f?Tt(f,b):b,h=c?te(c):void 0;if(h){if(h.requests++,_)h.connectionsReused++;else h.connectionsCreated++;if(C)h.cachedContextRequests++;if(w.store===!0)h.storeTrueRequests++;if(h.lastInputItems=w.input?.length??0,w.previous_response_id)h.deltaRequests++,h.lastDeltaInputItems=w.input?.length??0,h.lastPreviousResponseId=w.previous_response_id;else h.fullContextRequests++,h.lastDeltaInputItems=void 0,h.lastPreviousResponseId=void 0}try{if(E.send(JSON.stringify({type:"response.create",...w})),await de(Rt(ge(St(E,u?.signal,l)),i),n,s,o,{serviceTier:u?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:he,applyServiceTierPricing:(O,W)=>be(O,W,o)}),u?.signal?.aborted)p=!1;else if(C&&f&&n.responseId){let O=ce(o,{messages:[n]},ye,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter((W)=>W.type!=="function_call_output"&&W.type!=="custom_tool_call_output");f.continuation={lastRequestBody:b,lastResponseId:n.responseId,lastResponseItems:O}}}catch(O){if(f)f.continuation=void 0;throw p=!1,O}finally{m({keep:p})}}async function vt(e){let t=await e.text(),r=t||e.statusText||"Request failed",n;try{let o=JSON.parse(t)?.error;if(o){let i=o.code||o.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let l=o.plan_type?` (${o.plan_type.toLowerCase()} plan)`:"",a=o.resets_at?Math.max(0,Math.round((o.resets_at*1000-Date.now())/60000)):void 0,c=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${l}.${c}`.trim()}r=o.message||n||r}}catch{}return{message:r,friendlyMessage:n}}function Ct(e){try{let t=e.split(".");if(t.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(t[1]))?.[Me]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function Te(e,t,r,n){let s=new Headers(e);for(let[i,l]of Object.entries(t||{}))if(l===null)s.delete(i);else s.set(i,l);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",r),s.set("originator","pi");let o=H?`pi (${H.platform()} ${H.release()}; ${H.arch()})`:"pi (browser)";return s.set("User-Agent",o),s}function Ot(e,t,r,n,s){let o=Te(e,t,r,n);if(o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s)o.set("session-id",s),o.set("x-client-request-id",s);return o}function At(e,t,r,n,s){let o=Te(e,t,r,n);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",lt),o.set("x-client-request-id",s),o.set("session-id",s),o}export{pt as closeOpenAICodexWebSocketSessions,Vt as getOpenAICodexWebSocketDebugStats,Yt as resetOpenAICodexWebSocketDebugStats,Qe as stream,jt as streamSimple};
@@ -0,0 +1,45 @@
1
+ // @bun
2
+ import{pt,R}from"./chunk-s1e2nv5w.js";import{y}from"./chunk-e7m6nsvr.js";import{Ie}from"./chunk-4q9h14c1.js";import{ye,Ce}from"./chunk-b2205272.js";import{j}from"./chunk-grtavkr4.js";import{d,M,dt,B,_t,O}from"./chunk-xp2anj2s.js";import{U}from"./chunk-m8jmvj7p.js";import{I,v}from"./shumai-agent-app.js";function p(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 ar=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ar=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 Q(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var Ae=(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 g extends Error{}class E extends g{constructor(e,t,r,s,n){super(`${E.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 ce({message:r,cause:Ae(t)});let n=t,o=n?.error?.type;if(e===400)return new Oe(e,n,r,s,o);if(e===401)return new Ne(e,n,r,s,o);if(e===403)return new Le(e,n,r,s,o);if(e===404)return new Fe(e,n,r,s,o);if(e===409)return new qe(e,n,r,s,o);if(e===422)return new Be(e,n,r,s,o);if(e===429)return new je(e,n,r,s,o);if(e>=500)return new Ue(e,n,r,s,o);return new E(e,n,r,s,o)}}class N extends E{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ce extends E{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class $e extends ce{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Oe extends E{}class Ne extends E{}class Le extends E{}class Fe extends E{}class qe extends E{}class Be extends E{}class je extends E{}class Ue extends E{}var Us=/^[a-z][a-z0-9+.-]*:/i,Wr=(e)=>Us.test(e),ir=(e)=>(ir=Array.isArray,ir(e)),cr=ir;function At(e){if(typeof e!=="object")return{};return e??{}}function lr(e){if(!e)return!0;for(let t in e)return!1;return!0}function Dr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Jr=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t};var It=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Vr=(e)=>new Promise((t)=>setTimeout(t,e));var re="0.91.1";var zr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Hs(){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 Ws=()=>{let e=Hs();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":re,"X-Stainless-OS":Kr(Deno.build.os),"X-Stainless-Arch":Xr(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":re,"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":re,"X-Stainless-OS":Kr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Xr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Ds();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":re,"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":re,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ds(){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 Xr=(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"},Kr=(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"},Gr,Qr=()=>Gr??(Gr=Ws());function Yr(){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 ur(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function $t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ur({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 He(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 Zr(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 es=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function ts(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 g(`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 ns(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 rs;function We(e){let t;return(rs??(t=new globalThis.TextEncoder,rs=t.encode.bind(t)))(e)}var ss;function hr(e){let t;return(ss??(t=new globalThis.TextDecoder,ss=t.decode.bind(t)))(e)}var q,H;class se{constructor(){q.set(this,void 0),H.set(this,void 0),p(this,q,new Uint8Array,"f"),p(this,H,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?We(e):e;p(this,q,ns([a(this,q,"f"),t]),"f");let r=[],s;while((s=Xs(a(this,q,"f"),a(this,H,"f")))!=null){if(s.carriage&&a(this,H,"f")==null){p(this,H,s.index,"f");continue}if(a(this,H,"f")!=null&&(s.index!==a(this,H,"f")+1||s.carriage)){r.push(hr(a(this,q,"f").subarray(0,a(this,H,"f")-1))),p(this,q,a(this,q,"f").subarray(a(this,H,"f")),"f"),p(this,H,null,"f");continue}let n=a(this,H,"f")!==null?s.preceding-1:s.preceding,o=hr(a(this,q,"f").subarray(0,n));r.push(o),p(this,q,a(this,q,"f").subarray(s.index),"f"),p(this,H,null,"f")}return r}flush(){if(!a(this,q,"f").length)return[];return this.decode(`
3
+ `)}}q=new WeakMap,H=new WeakMap;se.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);se.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Xs(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 os(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 Ot={off:0,error:200,warn:300,info:400,debug:500},dr=(e,t,r)=>{if(!e)return;if(Dr(Ot,e))return e;A(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ot))}`);return};function De(){}function Ct(e,t,r){if(!t||Ot[e]>Ot[r])return De;else return t[e].bind(t)}var Ks={error:De,warn:De,info:De,debug:De},as=new WeakMap;function A(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Ks;let s=as.get(t);if(s&&s[0]===r)return s[1];let n={error:Ct("error",t,r),warn:Ct("warn",t,r),info:Ct("info",t,r),debug:Ct("debug",t,r)};return as.set(t,[r,n]),n}var Y=(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 Je;class W{constructor(e,t,r){this.iterator=e,Je.set(this,void 0),this.controller=t,p(this,Je,r,"f")}static fromSSEResponse(e,t,r){let s=!1,n=r?A(r):console;async function*o(){if(s)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let i of Gs(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=It(i.data)??i.data,w=h?.error?.type;throw new E(void 0,h,void 0,e.headers,w)}}c=!0}catch(i){if(Q(i))return;throw i}finally{if(!c)t.abort()}}return new W(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let c=new se,i=He(e);for await(let h of i)for(let w of c.decode(h))yield w;for(let h of c.flush())yield h}async function*o(){if(s)throw new g("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(Q(i))return;throw i}finally{if(!c)t.abort()}}return new W(o,t,r)}[(Je=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 W(()=>s(e),this.controller,a(this,Je,"f")),new W(()=>s(t),this.controller,a(this,Je,"f"))]}toReadableStream(){let e=this,t;return ur({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=We(JSON.stringify(s)+`
5
+ `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Gs(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new g("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 g("Attempted to iterate over a response with no body")}let r=new is,s=new se,n=He(e.body);for await(let o of zs(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*zs(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"?We(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=os(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class is{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]=Qs(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 Qs(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 Nt(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,c=await(async()=>{if(t.options.stream){if(A(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller);return W.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 fr(l,r)}return await r.text()})();return A(e).debug(`[${s}] response parsed`,Y({retryOfRequestLogID:n,url:r.url,status:r.status,body:c,durationMs:Date.now()-o})),c}function fr(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 Ve;class le extends Promise{constructor(e,t,r=Nt){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ve.set(this,void 0),p(this,Ve,e,"f")}_thenUnwrap(e){return new le(a(this,Ve,"f"),this.responsePromise,async(t,r)=>fr(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,Ve,"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)}}Ve=new WeakMap;var Lt;class pr{constructor(e,t,r,s){Lt.set(this,void 0),p(this,Lt,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 g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,Lt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(Lt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class Ft extends le{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await Nt(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class G extends pr{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:{...At(this.options.query),before_id:t}}}let e=this.last_id;if(!e)return null;return{...this.options,query:{...At(this.options.query),after_id:e}}}}class k extends pr{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:{...At(this.options.query),page:e}}}}var gr=()=>{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 ue(e,t,r){return gr(),new File(e,t??"unknown_file",r)}function Xe(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 _r=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function";var _e=async(e,t,r=!0)=>({...e,body:await en(e.body,t,r)}),cs=new WeakMap;function Zs(e){let t=typeof e==="function"?e:e.fetch,r=cs.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 cs.set(t,s),s}var en=async(e,t,r=!0)=>{if(!await Zs(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])=>mr(s,n,o,r))),s},tn=(e)=>e instanceof Blob&&("name"in e);var mr=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,ue([await r.blob()],Xe(r,s),n))}else if(_r(r))e.append(t,ue([await new Response($t(r)).blob()],Xe(r,s)));else if(tn(r))e.append(t,ue([r],Xe(r,s),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map((n)=>mr(e,t+"[]",n,s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([n,o])=>mr(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 ls=(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",rn=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&ls(e),sn=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function qt(e,t,r){if(gr(),e=await e,t||(t=Xe(e,!0)),rn(e)){if(e instanceof File&&t==null&&r==null)return e;return ue([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r})}if(sn(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ue(await br(n),t,r)}let s=await br(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 ue(s,t,r)}async function br(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ls(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_r(e))for await(let r of e)t.push(...await br(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${nn(e)}`)}return t}function nn(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class x{constructor(e){this._client=e}}var us=Symbol.for("brand.privateNullableHeaders");function*an(e){if(!e)return;if(us 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(cr(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=cr(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 an(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{[us]:!0,values:t,nulls:r}};function ds(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hs=Object.freeze(Object.create(null)),cn=(e=ds)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],c=r.reduce((_,b,l)=>{if(/[?#]/.test(b))n=!0;let m=s[l],S=(n?encodeURIComponent:e)(""+m);if(l!==s.length&&(m==null||typeof m==="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??hs)??hs)?.toString))S=m+"",o.push({start:_.length+b.length,length:S.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`});return _+b+(l===s.length?"":S)},""),i=c.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,w;while((w=h.exec(i))!==null)o.push({start:w.index,length:w[0].length,error:`Value "${w[0]}" can't be safely passed as a path parameter`});if(o.sort((_,b)=>_.start-b.start),o.length>0){let _=0,b=o.reduce((l,m)=>{let S=" ".repeat(m.start-_),C="^".repeat(m.length);return _=m.start+m.length,l+S+C},"");throw new g(`Path parameters result in path with invalid segments:
7
+ ${o.map((l)=>l.error).join(`
8
+ `)}
9
+ ${c}
10
+ ${b}`)}return c},f=cn(ds);class Ke extends x{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(f`/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(f`/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",k,{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(f`/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(f`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}var Ge=Symbol("anthropic.sdk.stainlessHelper");function Bt(e){return typeof e==="object"&&e!==null&&Ge in e}function yr(e,t){let r=new Set;if(e){for(let s of e)if(Bt(s))r.add(s[Ge])}if(t)for(let s of t){if(Bt(s))r.add(s[Ge]);if(Array.isArray(s.content)){for(let n of s.content)if(Bt(n))r.add(n[Ge])}}return Array.from(r)}function jt(e,t){let r=yr(e,t);if(r.length===0)return{};return{"x-stainless-helper":r.join(", ")}}function fs(e){if(Bt(e))return{"x-stainless-helper":e[Ge]};return{}}class ze extends x{list(e={},t){let{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",G,{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(f`/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(f`/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(f`/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",_e({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},fs(s.file),t?.headers])},this._client))}}class Qe extends x{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(f`/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",G,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class Ye extends x{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(f`/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(f`/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",k,{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(f`/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 x{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(f`/v1/agents/${e}/versions?beta=true`,k,{query:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class be extends x{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(f`/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(f`/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",k,{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(f`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}be.Versions=Ze;class et extends x{create(e,t,r){let{view:s,betas:n,...o}=t;return this._client.post(f`/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(f`/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(f`/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(f`/v1/memory_stores/${e}/memories?beta=true`,k,{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(f`/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 tt extends x{retrieve(e,t,r){let{memory_store_id:s,betas:n,...o}=t;return this._client.get(f`/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(f`/v1/memory_stores/${e}/memory_versions?beta=true`,k,{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(f`/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 he extends x{constructor(){super(...arguments);this.memories=new et(this._client),this.memoryVersions=new tt(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(f`/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(f`/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",k,{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(f`/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(f`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}he.Memories=et;he.MemoryVersions=tt;var Ut={"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 ps(e){return e?.output_format??e?.output_config?.format}function wr(e,t,r){let s=ps(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 xr(e,t,r)}function xr(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=ps(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 g(`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},we=(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),we(e);break;case"number":let r=t.value[t.value.length-1];if(r==="."||r==="-")return e=e.slice(0,e.length-1),we(e);case"string":let s=e[e.length-2];if(s?.type==="delimiter")return e=e.slice(0,e.length-1),we(e);else if(s?.type==="brace"&&s.value==="{")return e=e.slice(0,e.length-1),we(e);break;case"delimiter":return e=e.slice(0,e.length-1),we(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},Ht=(e)=>JSON.parse(xn(wn(we(yn(e)))));var X,ne,xe,rt,Wt,st,nt,Dt,ot,Z,at,Jt,Vt,de,Xt,Kt,it,Sr,ms,Gt,kr,Pr,Rr,gs,_s="__json_buf";function bs(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}class ct{constructor(e,t){X.add(this),this.messages=[],this.receivedMessages=[],ne.set(this,void 0),xe.set(this,null),this.controller=new AbortController,rt.set(this,void 0),Wt.set(this,()=>{}),st.set(this,()=>{}),nt.set(this,void 0),Dt.set(this,()=>{}),ot.set(this,()=>{}),Z.set(this,{}),at.set(this,!1),Jt.set(this,!1),Vt.set(this,!1),de.set(this,!1),Xt.set(this,void 0),Kt.set(this,void 0),it.set(this,void 0),Gt.set(this,(r)=>{if(p(this,Jt,!0,"f"),Q(r))r=new N;if(r instanceof N)return p(this,Vt,!0,"f"),this._emit("abort",r);if(r instanceof g)return this._emit("error",r);if(r instanceof Error){let s=new g(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new g(String(r)))}),p(this,rt,new Promise((r,s)=>{p(this,Wt,r,"f"),p(this,st,s,"f")}),"f"),p(this,nt,new Promise((r,s)=>{p(this,Dt,r,"f"),p(this,ot,s,"f")}),"f"),a(this,rt,"f").catch(()=>{}),a(this,nt,"f").catch(()=>{}),p(this,xe,e,"f"),p(this,it,t?.logger??console,"f")}get response(){return a(this,Xt,"f")}get request_id(){return a(this,Kt,"f")}async withResponse(){p(this,de,!0,"f");let e=await a(this,rt,"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 ct(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new ct(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return p(n,xe,{...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,Gt,"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,X,"m",kr).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,X,"m",Pr).call(this,i);if(c.controller.signal?.aborted)throw new N;a(this,X,"m",Rr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;p(this,Xt,e,"f"),p(this,Kt,e?.headers.get("request-id"),"f"),a(this,Wt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,at,"f")}get errored(){return a(this,Jt,"f")}get aborted(){return a(this,Vt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,Z,"f")[e]||(a(this,Z,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,Z,"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,Z,"f")[e]||(a(this,Z,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(p(this,de,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){p(this,de,!0,"f"),await a(this,nt,"f")}get currentMessage(){return a(this,ne,"f")}async finalMessage(){return await this.done(),a(this,X,"m",Sr).call(this)}async finalText(){return await this.done(),a(this,X,"m",ms).call(this)}_emit(e,...t){if(a(this,at,"f"))return;if(e==="end")p(this,at,!0,"f"),a(this,Dt,"f").call(this);let r=a(this,Z,"f")[e];if(r)a(this,Z,"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,st,"f").call(this,s),a(this,ot,"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,st,"f").call(this,s),a(this,ot,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,X,"m",Sr).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,X,"m",kr).call(this),this._connected(null);let n=W.fromReadableStream(e,this.controller);for await(let o of n)a(this,X,"m",Pr).call(this,o);if(n.controller.signal?.aborted)throw new N;a(this,X,"m",Rr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(ne=new WeakMap,xe=new WeakMap,rt=new WeakMap,Wt=new WeakMap,st=new WeakMap,nt=new WeakMap,Dt=new WeakMap,ot=new WeakMap,Z=new WeakMap,at=new WeakMap,Jt=new WeakMap,Vt=new WeakMap,de=new WeakMap,Xt=new WeakMap,Kt=new WeakMap,it=new WeakMap,Gt=new WeakMap,X=new WeakSet,Sr=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ms=function(){if(this.receivedMessages.length===0)throw new g("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 g("stream ended without producing a content block with type=text");return t.join(" ")},kr=function(){if(this.ended)return;p(this,ne,void 0,"f")},Pr=function(t){if(this.ended)return;let r=a(this,X,"m",gs).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(bs(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:ys(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(wr(r,a(this,xe,"f"),{logger:a(this,it,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{p(this,ne,r,"f");break}case"content_block_start":case"message_delta":break}},Rr=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=a(this,ne,"f");if(!t)throw new g("request ended without sending any chunks");return p(this,ne,void 0,"f"),wr(t,a(this,xe,"f"),{logger:a(this,it,"f")})},gs=function(t){let r=a(this,ne,"f");if(t.type==="message_start"){if(r)throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new g(`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&&bs(s)){let n=s[_s]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,_s,{value:n,enumerable:!1,writable:!0}),n)try{o.input=Ht(n)}catch(c){let i=new g(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${n}`);a(this,Gt,"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:ys(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 W(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ys(e){}class Se 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 ws=1e5,xs=`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,ke,fe,T,F,D,ee,oe,ut,Ss,vr;function ks(){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,ke.set(this,!1),fe.set(this,!1),T.set(this,void 0),F.set(this,void 0),D.set(this,void 0),ee.set(this,void 0),oe.set(this,void 0),ut.set(this,0),p(this,T,{params:{...t,messages:structuredClone(t.messages)}},"f");let n=["BetaToolRunner",...yr(t.tools,t.messages)].join(", ");if(p(this,F,{...r,headers:u([{"x-stainless-helper":n},r?.headers])},"f"),p(this,oe,ks(),"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*[(ke=new WeakMap,fe=new WeakMap,T=new WeakMap,F=new WeakMap,D=new WeakMap,ee=new WeakMap,oe=new WeakMap,ut=new WeakMap,lt=new WeakSet,Ss=async function(){let t=a(this,T,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(a(this,D,"f")!==void 0)try{let h=await a(this,D,"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??ws;if(r<s)return!1;let n=t.model??a(this,T,"f").params.model,o=t.summaryPrompt??xs,c=a(this,T,"f").params.messages;if(c[c.length-1].role==="assistant"){let h=c[c.length-1];if(Array.isArray(h.content)){let w=h.content.filter((_)=>_.type!=="tool_use");if(w.length===0)c.pop();else h.content=w}}let i=await this.client.beta.messages.create({model:n,messages:[...c,{role:"user",content:[{type:"text",text:o}]}],max_tokens:a(this,T,"f").params.max_tokens},{signal:a(this,F,"f").signal,headers:u([a(this,F,"f").headers,{"x-stainless-helper":"compaction"}])});if(i.content[0]?.type!=="text")throw new g("Expected text response for compaction");return a(this,T,"f").params.messages=[{role:"user",content:i.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,ke,"f"))throw new g("Cannot iterate over a consumed stream");p(this,ke,!0,"f"),p(this,fe,!0,"f"),p(this,ee,void 0,"f");try{while(!0){let t;try{if(a(this,T,"f").params.max_iterations&&a(this,ut,"f")>=a(this,T,"f").params.max_iterations)break;p(this,fe,!1,"f"),p(this,ee,void 0,"f"),p(this,ut,(e=a(this,ut,"f"),e++,e),"f"),p(this,D,void 0,"f");let{max_iterations:r,compactionControl:s,...n}=a(this,T,"f").params;if(n.stream)t=this.client.beta.messages.stream({...n},a(this,F,"f")),p(this,D,t.finalMessage(),"f"),a(this,D,"f").catch(()=>{}),yield t;else p(this,D,this.client.beta.messages.create({...n,stream:!1},a(this,F,"f")),"f"),yield a(this,D,"f");if(!await a(this,lt,"m",Ss).call(this)){if(!a(this,fe,"f")){let{role:i,content:h}=await a(this,D,"f");a(this,T,"f").params.messages.push({role:i,content:h})}let c=await a(this,lt,"m",vr).call(this,a(this,T,"f").params.messages.at(-1));if(c)a(this,T,"f").params.messages.push(c);else if(!a(this,fe,"f"))break}}finally{if(t)t.abort()}}if(!a(this,D,"f"))throw new g("ToolRunner concluded without a message from the server");a(this,oe,"f").resolve(await a(this,D,"f"))}catch(t){throw p(this,ke,!1,"f"),a(this,oe,"f").promise.catch(()=>{}),a(this,oe,"f").reject(t),p(this,oe,ks(),"f"),t}}setMessagesParams(e){if(typeof e==="function")a(this,T,"f").params=e(a(this,T,"f").params);else a(this,T,"f").params=e;p(this,fe,!0,"f"),p(this,ee,void 0,"f")}setRequestOptions(e){if(typeof e==="function")p(this,F,e(a(this,F,"f")),"f");else p(this,F,{...a(this,F,"f"),...e},"f")}async generateToolResponse(e=a(this,F,"f").signal){let t=await a(this,D,"f")??this.params.messages.at(-1);if(!t)return null;return a(this,lt,"m",vr).call(this,t,e)}done(){return a(this,oe,"f").promise}async runUntilDone(){if(!a(this,ke,"f"))for await(let e of this);return this.done()}get params(){return a(this,T,"f").params}pushMessages(...e){this.setMessagesParams((t)=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}vr=async function(t,r=a(this,F,"f").signal){if(a(this,ee,"f")!==void 0)return a(this,ee,"f");return p(this,ee,Sn(a(this,T,"f").params,t,{...a(this,F,"f"),signal:r}),"f"),a(this,ee,"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 Se?i.content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class Pe{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new se;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 g("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 g("Attempted to iterate over a response with no body")}return new Pe(He(e.body),t)}}class ft extends x{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(f`/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",G,{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(f`/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(f`/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 g(`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)=>Pe.fromResponse(c.response,c.controller))}}var Ps={"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 ae extends x{constructor(){super(...arguments);this.batches=new ft(this._client)}create(e,t){let r=Rs(e),{betas:s,...n}=r;if(n.model in Ps)console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Ps[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=Ut[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,i)}let c=jt(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)=>xr(r,e,{logger:this._client.logger??console}))}stream(e,t){return ct.createMessage(this,e,t)}countTokens(e,t){let r=Rs(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 Rs(e){if(!e.output_format)return e;if(e.output_config?.format)throw new g("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}}}ae.Batches=ft;ae.BetaToolRunner=ht;ae.ToolError=Se;class mt extends x{list(e,t={},r){let{betas:s,...n}=t??{};return this._client.getAPIList(f`/v1/sessions/${e}/events?beta=true`,k,{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(f`/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(f`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}class gt extends x{retrieve(e,t,r){let{session_id:s,betas:n}=t;return this._client.get(f`/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(f`/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(f`/v1/sessions/${e}/resources?beta=true`,k,{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(f`/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(f`/v1/sessions/${e}/resources?beta=true`,{body:n,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class pe extends x{constructor(){super(...arguments);this.events=new mt(this._client),this.resources=new gt(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(f`/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(f`/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",k,{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(f`/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(f`/v1/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}pe.Events=mt;pe.Resources=gt;class bt extends x{create(e,t={},r){let{betas:s,...n}=t??{};return this._client.post(f`/v1/skills/${e}/versions?beta=true`,_e({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(f`/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(f`/v1/skills/${e}/versions?beta=true`,k,{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(f`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class Re extends x{constructor(){super(...arguments);this.versions=new bt(this._client)}create(e={},t){let{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",_e({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(f`/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",k,{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(f`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}}Re.Versions=bt;class yt extends x{create(e,t,r){let{betas:s,...n}=t;return this._client.post(f`/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(f`/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(f`/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(f`/v1/vaults/${e}/credentials?beta=true`,k,{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(f`/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(f`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...n??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}class ve extends x{constructor(){super(...arguments);this.credentials=new yt(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(f`/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(f`/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",k,{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(f`/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(f`/v1/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}ve.Credentials=yt;class L extends x{constructor(){super(...arguments);this.models=new Qe(this._client),this.messages=new ae(this._client),this.agents=new be(this._client),this.environments=new Ke(this._client),this.sessions=new pe(this._client),this.vaults=new ve(this._client),this.memoryStores=new he(this._client),this.files=new ze(this._client),this.skills=new Re(this._client),this.userProfiles=new Ye(this._client)}}L.Models=Qe;L.Messages=ae;L.Agents=be;L.Environments=Ke;L.Sessions=pe;L.Vaults=ve;L.MemoryStores=he;L.Files=ze;L.Skills=Re;L.UserProfiles=Ye;class Ee extends x{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 vs(e){return e?.output_config?.format}function Er(e,t,r){let s=vs(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 Mr(e,t,r)}function Mr(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=vs(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 g(`Failed to parse structured output: ${s}`)}}var K,ie,Me,wt,zt,xt,St,Qt,kt,te,Pt,Yt,Zt,me,er,tr,Rt,Tr,Es,Ar,Ir,$r,Cr,Ms,Ts="__json_buf";function As(e){return e.type==="tool_use"||e.type==="server_tool_use"}class vt{constructor(e,t){K.add(this),this.messages=[],this.receivedMessages=[],ie.set(this,void 0),Me.set(this,null),this.controller=new AbortController,wt.set(this,void 0),zt.set(this,()=>{}),xt.set(this,()=>{}),St.set(this,void 0),Qt.set(this,()=>{}),kt.set(this,()=>{}),te.set(this,{}),Pt.set(this,!1),Yt.set(this,!1),Zt.set(this,!1),me.set(this,!1),er.set(this,void 0),tr.set(this,void 0),Rt.set(this,void 0),Ar.set(this,(r)=>{if(p(this,Yt,!0,"f"),Q(r))r=new N;if(r instanceof N)return p(this,Zt,!0,"f"),this._emit("abort",r);if(r instanceof g)return this._emit("error",r);if(r instanceof Error){let s=new g(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new g(String(r)))}),p(this,wt,new Promise((r,s)=>{p(this,zt,r,"f"),p(this,xt,s,"f")}),"f"),p(this,St,new Promise((r,s)=>{p(this,Qt,r,"f"),p(this,kt,s,"f")}),"f"),a(this,wt,"f").catch(()=>{}),a(this,St,"f").catch(()=>{}),p(this,Me,e,"f"),p(this,Rt,t?.logger??console,"f")}get response(){return a(this,er,"f")}get request_id(){return a(this,tr,"f")}async withResponse(){p(this,me,!0,"f");let e=await a(this,wt,"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 vt(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){let n=new vt(t,{logger:s});for(let o of t.messages)n._addMessageParam(o);return p(n,Me,{...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,Ar,"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,K,"m",Ir).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,K,"m",$r).call(this,i);if(c.controller.signal?.aborted)throw new N;a(this,K,"m",Cr).call(this)}finally{if(s&&n)s.removeEventListener("abort",n)}}_connected(e){if(this.ended)return;p(this,er,e,"f"),p(this,tr,e?.headers.get("request-id"),"f"),a(this,zt,"f").call(this,e),this._emit("connect")}get ended(){return a(this,Pt,"f")}get errored(){return a(this,Yt,"f")}get aborted(){return a(this,Zt,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,te,"f")[e]||(a(this,te,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,te,"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,te,"f")[e]||(a(this,te,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(p(this,me,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){p(this,me,!0,"f"),await a(this,St,"f")}get currentMessage(){return a(this,ie,"f")}async finalMessage(){return await this.done(),a(this,K,"m",Tr).call(this)}async finalText(){return await this.done(),a(this,K,"m",Es).call(this)}_emit(e,...t){if(a(this,Pt,"f"))return;if(e==="end")p(this,Pt,!0,"f"),a(this,Qt,"f").call(this);let r=a(this,te,"f")[e];if(r)a(this,te,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!a(this,me,"f")&&!r?.length)Promise.reject(s);a(this,xt,"f").call(this,s),a(this,kt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!a(this,me,"f")&&!r?.length)Promise.reject(s);a(this,xt,"f").call(this,s),a(this,kt,"f").call(this,s),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",a(this,K,"m",Tr).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,K,"m",Ir).call(this),this._connected(null);let n=W.fromReadableStream(e,this.controller);for await(let o of n)a(this,K,"m",$r).call(this,o);if(n.controller.signal?.aborted)throw new N;a(this,K,"m",Cr).call(this)}finally{if(r&&s)r.removeEventListener("abort",s)}}[(ie=new WeakMap,Me=new WeakMap,wt=new WeakMap,zt=new WeakMap,xt=new WeakMap,St=new WeakMap,Qt=new WeakMap,kt=new WeakMap,te=new WeakMap,Pt=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,me=new WeakMap,er=new WeakMap,tr=new WeakMap,Rt=new WeakMap,Ar=new WeakMap,K=new WeakSet,Tr=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Es=function(){if(this.receivedMessages.length===0)throw new g("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 g("stream ended without producing a content block with type=text");return t.join(" ")},Ir=function(){if(this.ended)return;p(this,ie,void 0,"f")},$r=function(t){if(this.ended)return;let r=a(this,K,"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(As(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:Is(t.delta)}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Er(r,a(this,Me,"f"),{logger:a(this,Rt,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{p(this,ie,r,"f");break}case"content_block_start":case"message_delta":break}},Cr=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=a(this,ie,"f");if(!t)throw new g("request ended without sending any chunks");return p(this,ie,void 0,"f"),Er(t,a(this,Me,"f"),{logger:a(this,Rt,"f")})},Ms=function(t){let r=a(this,ie,"f");if(t.type==="message_start"){if(r)throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new g(`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&&As(s)){let n=s[Ts]||"";n+=t.delta.partial_json;let o={...s};if(Object.defineProperty(o,Ts,{value:n,enumerable:!1,writable:!0}),n)o.input=Ht(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:Is(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 W(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Is(e){}class Et extends x{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(f`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",G,{query:e,...t})}delete(e,t){return this._client.delete(f`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(f`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new g(`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)=>Pe.fromResponse(n.response,n.controller))}}class ge extends x{constructor(){super(...arguments);this.batches=new Et(this._client)}create(e,t){if(e.model in $s)console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${$s[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=Ut[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,n)}let s=jt(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)=>Mr(r,e,{logger:this._client.logger??console}))}stream(e,t){return vt.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}var $s={"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"];ge.Batches=Et;class Te extends x{retrieve(e,t={},r){let{betas:s}=t??{};return this._client.get(f`/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",G,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}var Mt=(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 Or,Nr,rr,Cs,Os="\\n\\nHuman:",Ns="\\n\\nAssistant:";class P{constructor({baseURL:e=Mt("ANTHROPIC_BASE_URL"),apiKey:t=Mt("ANTHROPIC_API_KEY")??null,authToken:r=Mt("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){Or.add(this),rr.set(this,void 0);let n={apiKey:t,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!n.dangerouslyAllowBrowser&&zr())throw new g(`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??Nr.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=dr(n.logLevel,"ClientOptions.logLevel",this)??dr(Mt("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??Yr(),p(this,rr,es,"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 ts(e)}getUserAgent(){return`${this.constructor.name}/JS ${re}`}defaultIdempotencyKey(){return`stainless-node-retry-${ar()}`}makeStatusError(e,t,r,s){return E.generate(e,t,r,s)}buildURL(e,t,r){let s=!a(this,Or,"m",Cs).call(this)&&r||this.baseURL,n=Wr(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(n.searchParams);if(!lr(o)||!lr(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 g("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 le(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"),w=r===void 0?"":`, retryOf: ${r}`,_=Date.now();if(A(this).debug(`[${h}] sending request`,Y({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:o.headers})),s.signal?.aborted)throw new N;let b=new AbortController,l=await this.fetchWithTimeout(c,o,i,b).catch(Ae),m=Date.now();if(l instanceof globalThis.Error){let J=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new N;let V=Q(l)||/timed? ?out/i.test(String(l)+("cause"in l?String(l.cause):""));if(t)return A(this).info(`[${h}] connection ${V?"timed out":"failed"} - ${J}`),A(this).debug(`[${h}] connection ${V?"timed out":"failed"} (${J})`,Y({retryOfRequestLogID:r,url:c,durationMs:m-_,message:l.message})),this.retryRequest(s,t,r??h);if(A(this).info(`[${h}] connection ${V?"timed out":"failed"} - error; no more retries left`),A(this).debug(`[${h}] connection ${V?"timed out":"failed"} (error; no more retries left)`,Y({retryOfRequestLogID:r,url:c,durationMs:m-_,message:l.message})),V)throw new $e;throw new ce({cause:l})}let S=[...l.headers.entries()].filter(([J])=>J==="request-id").map(([J,V])=>", "+J+": "+JSON.stringify(V)).join(""),C=`[${h}${w}${S}] ${o.method} ${c} ${l.ok?"succeeded":"failed"} with status ${l.status} in ${m-_}ms`;if(!l.ok){let J=await this.shouldRetry(l);if(t&&J){let Tt=`retrying, ${t} attempts remaining`;return await Zr(l.body),A(this).info(`${C} - ${Tt}`),A(this).debug(`[${h}] response error (${Tt})`,Y({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:m-_})),this.retryRequest(s,t,r??h,l.headers)}let V=J?"error; no more retries left":"error; not retryable";A(this).info(`${C} - ${V}`);let jr=await l.text().catch((Tt)=>Ae(Tt).message),Ur=It(jr),Hr=Ur?void 0:jr;throw A(this).debug(`[${h}] response error (${V})`,Y({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,message:Hr,durationMs:Date.now()-_})),this.makeStatusError(l.status,Ur,Hr,l.headers)}return A(this).info(C),A(this).debug(`[${h}] response start`,Y({retryOfRequestLogID:r,url:l.url,status:l.status,headers:l.headers,durationMs:m-_})),{response:l,options:s,controller:b,requestLogID:h,retryOfRequestLogID:r,startTime:_}}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 Ft(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),w=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body,_={signal:s.signal,...w?{duplex:"half"}:{},method:"GET",...c};if(o)_.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,_)}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 Vr(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 g("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)Jr("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:h,body:w}=this.buildBody({options:r}),_=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:_,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&w instanceof globalThis.ReadableStream&&{duplex:"half"},...w&&{body:w},...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))}:{},...Qr(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:$t(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return a(this,rr,"f").call(this,{body:e,headers:r})}}Nr=P,rr=new WeakMap,Or=new WeakSet,Cs=function(){return this.baseURL!=="https://api.anthropic.com"};P.Anthropic=Nr;P.HUMAN_PROMPT=Os;P.AI_PROMPT=Ns;P.DEFAULT_TIMEOUT=600000;P.AnthropicError=g;P.APIError=E;P.APIConnectionError=ce;P.APIConnectionTimeoutError=$e;P.APIUserAbortError=N;P.NotFoundError=Fe;P.ConflictError=qe;P.RateLimitError=je;P.BadRequestError=Oe;P.AuthenticationError=Ne;P.InternalServerError=Ue;P.PermissionDeniedError=Le;P.UnprocessableEntityError=Be;P.toFile=qt;class z extends P{constructor(){super(...arguments);this.completions=new Ee(this),this.messages=new ge(this),this.models=new Te(this),this.beta=new L(this)}}z.Completions=Ee;z.Messages=ge;z.Models=Te;z.Beta=L;function Fs(e,t){if(e)return e;if(y("PI_CACHE_RETENTION",t)==="long")return"long";return"short"}function Fn(e,t,r){let s=Fs(t,r);if(s==="none")return{retention:s};let n=s==="long"&&or(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])),nr=(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 d(e.map((n)=>n.text).join(`
42
+ `));let r=e.map((n)=>{if(n.type==="text")return{type:"text",text:d(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 or(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 Lr(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Fr(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 qs(e,t,r){if(t)return;if(Fr(r,"authorization")||Fr(r,"x-api-key")||Fr(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 Bs(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 qr(e,t){if(e==="")return Bs(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 sr(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:w}=await r.read();if(w)break;o+=s.decode(h,{stream:!0});let _=sr(o);while(_){o=_.rest;let b=qr(_.line,n);if(b)yield b;_=sr(o)}}o+=s.decode();let c=sr(o);while(c){o=c.rest;let h=qr(c.line,n);if(h)yield h;c=sr(o)}if(o.length>0){let h=qr(o,n);if(h)yield h}let i=Bs(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=pt(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 Br=(e,t,r)=>{let s=new I;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;qs(e.provider,l,r?.headers);let m;if(e.provider==="github-copilot"){let V=ye(t.messages);m=Ce({messages:t.messages,hasImages:V})}let C=Fs(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,J=Yn(e,l,r?.interleavedThinking??!0,so(e,t),r?.headers,m,C);o=J.client,c=J.isOAuthToken}let i=Zn(e,t,c,r),h=await r?.onPayload?.(i,e);if(h!==void 0)i=h;let w={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},_=await j(()=>o.messages.create({...i,stream:!0},w).asResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:_.status,headers:U(_.headers)},e),s.push({type:"start",partial:n});let b=n.content;for await(let l of Gn(_,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,v(e,n.usage);else if(l.type==="content_block_start"){if(l.content_block.type==="text"){let m={type:"text",text:"",index:l.index};n.content.push(m),s.push({type:"text_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="thinking"){let m={type:"thinking",thinking:"",thinkingSignature:"",index:l.index};n.content.push(m),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="redacted_thinking"){let m={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:l.content_block.data,redacted:!0,index:l.index};n.content.push(m),s.push({type:"thinking_start",contentIndex:n.content.length-1,partial:n})}else if(l.content_block.type==="tool_use"){let m={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(m),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 m=b.findIndex((C)=>C.index===l.index),S=b[m];if(S&&S.type==="text")S.text+=l.delta.text,s.push({type:"text_delta",contentIndex:m,delta:l.delta.text,partial:n})}else if(l.delta.type==="thinking_delta"){let m=b.findIndex((C)=>C.index===l.index),S=b[m];if(S&&S.type==="thinking")S.thinking+=l.delta.thinking,s.push({type:"thinking_delta",contentIndex:m,delta:l.delta.thinking,partial:n})}else if(l.delta.type==="input_json_delta"){let m=b.findIndex((C)=>C.index===l.index),S=b[m];if(S&&S.type==="toolCall")S.partialJson+=l.delta.partial_json,S.arguments=R(S.partialJson),s.push({type:"toolcall_delta",contentIndex:m,delta:l.delta.partial_json,partial:n})}else if(l.delta.type==="signature_delta"){let m=b.findIndex((C)=>C.index===l.index),S=b[m];if(S&&S.type==="thinking")S.thinkingSignature=S.thinkingSignature||"",S.thinkingSignature+=l.delta.signature}}else if(l.type==="content_block_stop"){let m=b.findIndex((C)=>C.index===l.index),S=b[m];if(S){if(delete S.index,S.type==="text")s.push({type:"text_end",contentIndex:m,content:S.text,partial:n});else if(S.type==="thinking")s.push({type:"thinking_end",contentIndex:m,content:S.thinking,partial:n});else if(S.type==="toolCall")S.arguments=R(S.partialJson),delete S.partialJson,s.push({type:"toolcall_end",contentIndex:m,toolCall:S,partial:n})}}else if(l.type==="message_delta"){if(l.delta.stop_reason){let m=no(l.delta.stop_reason,l.delta.stop_details);if(n.stopReason=m.stopReason,m.errorMessage)n.errorMessage=m.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 m=l.usage.output_tokens_details?.thinking_tokens;if(m!=null)n.usage.reasoning=m}n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite,v(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)=>{qs(e.provider,r?.apiKey,r?.headers);let s=B(e,t,r,r?.apiKey);if(!r?.reasoning)return Br(e,t,{...s,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let c=zn(e,r.reasoning);return Br(e,t,{...s,thinkingEnabled:!0,effort:c})}let n=_t(s.maxTokens,e.maxTokens,r.reasoning,r.thinkingBudgets),o=dt(e,t,n.maxTokens);return Br(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 z({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Lr({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 z({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Lr({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 w=c&&or(e).sendSessionAffinityHeaders?{"x-session-affinity":c}:{},_=Lr({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},w,e.headers,n);return{client:new z({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:_}),isOAuthToken:!1}}function Zn(e,t,r,s){let{cacheControl:n}=Fn(e,s?.cacheRetention,s?.env),o=or(e),c=O(t.messages,e,eo),i=r?nr:(m)=>m,h=Ie({...t,messages:c},o.supportsToolReferences,i),w=h.immediate,_=[...h.deferred.values()];if(w.length===0&&_.length>0)w=_,_=[];let b=new Set(_.map((m)=>i(m.name))),l={model:e.id,messages:ro(c,r,n,o.allowEmptySignature,b,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:d(t.systemPrompt),...n?{cache_control:n}:{}})}else if(t.systemPrompt)l.system=[{type:"text",text:d(t.systemPrompt),...n?{cache_control:n}:{}}];if(s?.temperature!==void 0&&!s?.thinkingEnabled&&o.supportsTemperature)l.temperature=s.temperature;if(w.length>0||_.length>0)l.tools=[...Ls(w,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?n:void 0),...Ls(_,r,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)];if(e.reasoning){if(s?.thinkingEnabled){let m=s.thinkingDisplay??"summarized";if(e.compat?.forceAdaptiveThinking===!0){if(l.thinking={type:"adaptive",display:m},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:m}}else if(s?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null)l.thinking={type:"disabled"}}if(s?.metadata){let m=s.metadata.user_id;if(typeof m==="string")l.metadata={user_id:m}}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?nr(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 w=e[h];if(w.role==="user")if(typeof w.content==="string"){if(w.content.trim().length>0)c.push({role:"user",content:d(w.content)})}else{let b=w.content.map((l)=>{if(l.type==="text")return{type:"text",text:d(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(b.length===0)continue;c.push({role:"user",content:b})}else if(w.role==="assistant"){let _=[];for(let b of w.content)if(b.type==="text"){if(b.text.trim().length===0)continue;_.push({type:"text",text:d(b.text)})}else if(b.type==="thinking"){if(b.redacted){_.push({type:"redacted_thinking",data:b.thinkingSignature});continue}let l=b.thinkingSignature,m=!!l&&l.trim().length>0;if(b.thinking.trim().length===0&&!m)continue;if(!m)_.push(s?{type:"thinking",thinking:d(b.thinking),signature:""}:{type:"text",text:d(b.thinking)});else _.push({type:"thinking",thinking:d(b.thinking),signature:l})}else if(b.type==="toolCall")_.push({type:"tool_use",id:b.id,name:t?nr(b.name):b.name,input:b.arguments??{}});if(_.length===0)continue;c.push({role:"assistant",content:_})}else if(w.role==="toolResult"){let _=[],b=[],l=h;while(l<e.length&&e[l].role==="toolResult"){let m=to(e[l],t,n,i,o);_.push(m.toolResult),b.push(...m.siblingContent),l++}h=l-1,c.push({role:"user",content:[..._,...b]})}}if(r&&c.length>0){let h=c[c.length-1];if(h.role==="user"){if(Array.isArray(h.content)){let w=h.content[h.content.length-1];if(w&&(w.type==="text"||w.type==="image"||w.type==="tool_result"))w.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&&!or(e).supportsEagerToolInputStreaming}function Ls(e,t,r,s,n,o=!1){if(!e)return[];return e.map((c,i)=>{let h=M(c,s),w=c.parameters,_={type:"object",properties:w.properties??{},required:w.required??[]},b=h===!0?{...c.parameters,..._}:_;return{name:t?nr(c.name):c.name,description:c.description,...r?{eager_input_streaming:!0}:{},...h===!0?{strict:!0}:{},input_schema:b,...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{Br as stream,Yl as streamSimple};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ot,st,mt}from"./shumai-agent-app.js";export{ot as ENV_KEY,st as ENV_SECRET,mt as fromEnv};