@pen.dev/cli 0.3.3 → 0.3.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.
- package/README.md +13 -6
- package/dist/anthropic-messages-COZrsSdY.mjs +40 -0
- package/dist/azure-openai-responses-Dmf1EaVz.mjs +2 -0
- package/dist/browserAll-BZYrVO32.mjs +2 -0
- package/dist/{dist-BEo0Z8Vf.mjs → dist-D9ROAuw3.mjs} +348 -319
- package/dist/{dist-BY6vOcMF.mjs → dist-DGrygXHh.mjs} +2 -2
- package/dist/{error-body-D2Mrqb4g.mjs → error-body-BBlqjbe7.mjs} +1 -1
- package/dist/google-generative-ai-BMEzR_34.mjs +2 -0
- package/dist/google-shared-DXgnvvDU.mjs +318 -0
- package/dist/google-vertex-In7qdx36.mjs +2 -0
- package/dist/index.mjs +2 -2
- package/dist/mistral-conversations-DdYjdrRy.mjs +5 -0
- package/dist/models-BBd5zwn6.mjs +2 -0
- package/dist/{multipart-parser-DX5ZDxQv.mjs → multipart-parser-BdmM0fdd.mjs} +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/package.json +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.d.ts +3 -0
- package/dist/node_modules/@highagency/pencil-wasm/pencil.js +1 -1
- package/dist/node_modules/@highagency/pencil-wasm/pencil.wasm +0 -0
- package/dist/openai-CbFQ5q5I.mjs +18 -0
- package/dist/openai-codex-responses-CD-2hfWB.mjs +8 -0
- package/dist/openai-completions-DamtYjy7.mjs +6 -0
- package/dist/openai-responses-DgeWdtm-.mjs +2 -0
- package/dist/openai-responses-shared-DKseiGAg.mjs +11 -0
- package/dist/{openrouter-images-BbBWg9zF.mjs → openrouter-images-gArAwqnL.mjs} +1 -1
- package/dist/out/mcp-server-darwin-arm64 +0 -0
- package/dist/out/mcp-server-darwin-x64 +0 -0
- package/dist/out/mcp-server-linux-arm64 +0 -0
- package/dist/out/mcp-server-linux-x64 +0 -0
- package/dist/out/mcp-server-windows-arm64.exe +0 -0
- package/dist/out/mcp-server-windows-x64.exe +0 -0
- package/dist/out/skills/pen-dev/SKILL.md +204 -0
- package/dist/out/skills/pen-dev/execute.md +364 -0
- package/dist/out/skills/pen-dev/guide/code.md +198 -0
- package/dist/out/skills/pen-dev/guide/components.md +45 -0
- package/dist/out/skills/pen-dev/guide/design-system.md +556 -0
- package/dist/out/skills/pen-dev/guide/landing-page.md +31 -0
- package/dist/out/skills/pen-dev/guide/mobile-app.md +31 -0
- package/dist/out/skills/pen-dev/guide/slides.md +222 -0
- package/dist/out/skills/pen-dev/guide/table.md +37 -0
- package/dist/out/skills/pen-dev/guide/tailwind.md +328 -0
- package/dist/out/skills/pen-dev/guide/web-app.md +245 -0
- package/dist/out/skills/pen-dev/pen-schema.md +202 -0
- package/dist/out/skills/pen-dev/scripts-and-shaders.md +94 -0
- package/dist/pi-user-agent-m9a4CjJo.mjs +2 -0
- package/dist/{src-B_lvnEtX.mjs → src-KoDMTA_Q.mjs} +1 -1
- package/dist/transform-messages-BHnJzowk.mjs +2 -0
- package/dist/webworkerAll-CB00nbs9.mjs +2 -0
- package/package.json +3 -3
- package/dist/anthropic-messages-Bf-fvkNu.mjs +0 -40
- package/dist/azure-openai-responses-CzgVqECr.mjs +0 -2
- package/dist/browserAll-8jKh1NRi.mjs +0 -2
- package/dist/completionchunk-BQtPqA8U.mjs +0 -28
- package/dist/google-generative-ai-DSOqI0LF.mjs +0 -2
- package/dist/google-shared-CetPT_Vt.mjs +0 -318
- package/dist/google-vertex-CPtOc5oU.mjs +0 -2
- package/dist/mistral-conversations-CUsdbDQ8.mjs +0 -10
- package/dist/models-CwK5xZH9.mjs +0 -2
- package/dist/openai-Brr_V-tF.mjs +0 -17
- package/dist/openai-codex-responses-Cb5pfH5S.mjs +0 -8
- package/dist/openai-completions-BvTlcCeP.mjs +0 -6
- package/dist/openai-responses-IuaLTEHh.mjs +0 -2
- package/dist/openai-responses-shared-D4d0NbBE.mjs +0 -11
- package/dist/otel-CaADOqYZ.mjs +0 -4
- package/dist/transform-messages-CSBQpmXO.mjs +0 -2
- package/dist/webworkerAll-BD-7VH16.mjs +0 -2
- /package/dist/{dist-BnoSGZKP.mjs → dist-D8tvRm1b.mjs} +0 -0
- /package/dist/{emscripten-module.browser-F76W5DM6-CNibWX-6.mjs → emscripten-module.browser-F76W5DM6-DWhj_jYh.mjs} +0 -0
- /package/dist/{emscripten-module.browser-XIKQQPVU-BNfdGnMe.mjs → emscripten-module.browser-XIKQQPVU-Dmh4no3c.mjs} +0 -0
- /package/dist/{ffi-C5tLdQO9.mjs → ffi-BroAqW9B.mjs} +0 -0
- /package/dist/{ffi-BuJ13coi.mjs → ffi-DwdyvnFx.mjs} +0 -0
- /package/dist/{from-py2TfO8m.mjs → from-Choxbpmr.mjs} +0 -0
- /package/dist/{github-copilot-headers-DZOfokGy.mjs → github-copilot-headers-DCj7hJoC.mjs} +0 -0
- /package/dist/{hash-Kp92CI9R.mjs → hash-DNYCELl4.mjs} +0 -0
- /package/dist/{html-GGJ1fTRB.mjs → html-DEPARSNH.mjs} +0 -0
- /package/dist/{init-B9LSomNH.mjs → init-DwIpBeuP.mjs} +0 -0
- /package/dist/{module-ES6BEMUI-DwQ9nTMF.mjs → module-ES6BEMUI-DUGQwtIb.mjs} +0 -0
- /package/dist/{module-asyncify-2EFITU5U-B54Mkt6K.mjs → module-asyncify-2EFITU5U-U7fqmMTF.mjs} +0 -0
- /package/dist/{openai-prompt-cache-t4kk9puG.mjs → openai-prompt-cache-tVHrB8oW.mjs} +0 -0
- /package/dist/{photon_rs-BySSRmP5.mjs → photon_rs-o0nbTM4F.mjs} +0 -0
- /package/dist/{provider-retry-BM3ArvaW.mjs → provider-retry-wOYAq0sa.mjs} +0 -0
- /package/dist/{sanitize-unicode-CHjuq5rK.mjs → sanitize-unicode-Byz9nlLd.mjs} +0 -0
- /package/dist/{standalone-DYT2Zg6I.mjs → standalone-DwaYVpTH.mjs} +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pen.dev/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "CLI tool for running the pen.dev AI agent manipulating .pen design files",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
},
|
|
11
11
|
"scripts": {
|
|
12
12
|
"build": "tsdown && npm run bundle:chmod && npm run bundle:mcp && npm run bundle:wasm && npm run bundle:pen-libs && npm run bundle:skill",
|
|
13
|
-
"bundle:skill": "cp ../../SKILL.md ./SKILL.md",
|
|
13
|
+
"bundle:skill": "cp ../../SKILL.md ./SKILL.md && rm -rf dist/out/skills && mkdir -p dist/out/skills && cp -Rp ../../skills/pen-dev dist/out/skills/",
|
|
14
14
|
"build:prod": "npm run build && node scripts/obfuscate.js",
|
|
15
15
|
"bundle:mcp": "mkdir -p dist/out && cp ../../servers/mcp/mcp-server-* dist/out/ && chmod +x dist/out/mcp-server-*",
|
|
16
16
|
"bundle:wasm": "node scripts/copy-pencil-wasm.mjs",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"typescript": "^5.0.0"
|
|
62
62
|
},
|
|
63
63
|
"engines": {
|
|
64
|
-
"node": ">=
|
|
64
|
+
"node": ">=22.0.0"
|
|
65
65
|
},
|
|
66
66
|
"files": [
|
|
67
67
|
"dist",
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{t}from"./models-CwK5xZH9.mjs";import{n,t as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{t as a}from"./deferred-tools-D8j2Ra6f.mjs";import{t as o}from"./headers-BvGum5dc.mjs";import{t as s}from"./provider-retry-BM3ArvaW.mjs";import{t as c}from"./sanitize-unicode-CHjuq5rK.mjs";import{i as l,l as u,n as d,r as f,t as p}from"./transform-messages-CSBQpmXO.mjs";import{n as ee,t as m}from"./github-copilot-headers-DZOfokGy.mjs";function h(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function g(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function ne(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const re=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var _=class extends Error{},v=class e extends _{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ie({message:r,cause:re(n)});let a=n,o=a?.error?.type;return t===400?new oe(t,a,r,i,o):t===401?new se(t,a,r,i,o):t===403?new ce(t,a,r,i,o):t===404?new le(t,a,r,i,o):t===409?new ue(t,a,r,i,o):t===422?new de(t,a,r,i,o):t===429?new fe(t,a,r,i,o):t>=500?new pe(t,a,r,i,o):new e(t,a,r,i,o)}},y=class extends v{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ie=class extends v{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},ae=class extends ie{constructor({message:e}={}){super({message:e??`Request timed out.`})}},oe=class extends v{},se=class extends v{},ce=class extends v{},le=class extends v{},ue=class extends v{},de=class extends v{},fe=class extends v{},pe=class extends v{};const me=/^[a-z][a-z0-9+.-]*:/i,he=e=>me.test(e);let ge=e=>(ge=Array.isArray,ge(e)),_e=ge;function ve(e){return typeof e==`object`?e??{}:{}}function ye(e){if(!e)return!0;for(let t in e)return!1;return!0}function be(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const xe=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new _(`${e} must be an integer`);if(t<0)throw new _(`${e} must be a positive integer`);return t},Se=e=>{try{return JSON.parse(e)}catch{return}},Ce=e=>new Promise(t=>setTimeout(t,e)),b=`0.91.1`,we=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Te(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const Ee=()=>{let e=Te();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":b,"X-Stainless-OS":ke(Deno.build.os),"X-Stainless-Arch":Oe(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":b,"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":b,"X-Stainless-OS":ke(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Oe(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=De();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":b,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":b,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function De(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const Oe=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ke=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let Ae;const je=()=>Ae??=Ee();function Me(){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 Ne(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Pe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ne({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Fe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ie(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Le=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Re(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new _(`Cannot stringify type ${typeof t}; 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 ze(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let He;function Ue(e){let t;return(He??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var x,S,We=class{constructor(){x.set(this,void 0),S.set(this,void 0),h(this,x,new Uint8Array,`f`),h(this,S,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Ve(e):e;h(this,x,ze([g(this,x,`f`),t]),`f`);let n=[],r;for(;(r=Ge(g(this,x,`f`),g(this,S,`f`)))!=null;){if(r.carriage&&g(this,S,`f`)==null){h(this,S,r.index,`f`);continue}if(g(this,S,`f`)!=null&&(r.index!==g(this,S,`f`)+1||r.carriage)){n.push(Ue(g(this,x,`f`).subarray(0,g(this,S,`f`)-1))),h(this,x,g(this,x,`f`).subarray(g(this,S,`f`)),`f`),h(this,S,null,`f`);continue}let e=g(this,S,`f`)===null?r.preceding:r.preceding-1,t=Ue(g(this,x,`f`).subarray(0,e));n.push(t),h(this,x,g(this,x,`f`).subarray(r.index),`f`),h(this,S,null,`f`)}return n}flush(){return g(this,x,`f`).length?this.decode(`
|
|
3
|
-
`):[]}};x=new WeakMap,S=new WeakMap,We.NEWLINE_CHARS=new Set([`
|
|
4
|
-
`,`\r`]),We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ge(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 Ke(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const qe={off:0,error:200,warn:300,info:400,debug:500},Je=(e,t,n)=>{if(e){if(be(qe,e))return e;w(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(qe))}`)}};function C(){}function Ye(e,t,n){return!t||qe[e]>qe[n]?C:t[e].bind(t)}const Xe={error:C,warn:C,info:C,debug:C};let Ze=new WeakMap;function w(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Xe;let r=Ze.get(t);if(r&&r[0]===n)return r[1];let i={error:Ye(`error`,t,n),warn:Ye(`warn`,t,n),info:Ye(`info`,t,n),debug:Ye(`debug`,t,n)};return Ze.set(t,[n,i]),i}const T=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Qe,$e=class e{constructor(e,t,n){this.iterator=e,Qe.set(this,void 0),this.controller=t,h(this,Qe,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?w(r):console;async function*o(){if(i)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of et(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=Se(e.data)??e.data,r=n?.error?.type;throw new v(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(ne(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new We,n=Fe(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(ne(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Qe=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,g(this,Qe,`f`)),new e(()=>i(n),this.controller,g(this,Qe,`f`))]}toReadableStream(){let e=this,t;return Ne({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Ve(JSON.stringify(n)+`
|
|
5
|
-
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*et(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new _(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new _(`Attempted to iterate over a response with no body`);let n=new nt,r=new We,i=Fe(e.body);for await(let e of tt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*tt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ke(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var nt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
6
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=rt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function rt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function it(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return w(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):$e.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:at(await n.json(),n):await n.text()})();return w(e).debug(`[${r}] response parsed`,T({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function at(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`request-id`),enumerable:!1})}var ot,st=class e extends Promise{constructor(e,t,n=it){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,ot.set(this,void 0),h(this,ot,e,`f`)}_thenUnwrap(t){return new e(g(this,ot,`f`),this.responsePromise,async(e,n)=>at(t(await this.parseResponse(e,n),n),n.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(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(g(this,ot,`f`),e)),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)}};ot=new WeakMap;var ct,lt=class{constructor(e,t,n,r){ct.set(this,void 0),h(this,ct,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await g(this,ct,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ct=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ut=class extends st{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await it(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},dt=class extends lt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...ve(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...ve(this.options.query),after_id:e}}:null}},E=class extends lt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...ve(this.options.query),page:e}}:null}};const ft=()=>{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 D(e,t,n){return ft(),new File(e,t??`unknown_file`,n)}function pt(e,t){let n=typeof e==`object`&&!!e&&(`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?n.split(/[\\/]/).pop()||void 0:n}const mt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,ht=async(e,t,n=!0)=>({...e,body:await vt(e.body,t,n)}),gt=new WeakMap;function _t(e){let t=typeof e==`function`?e:e.fetch,n=gt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return gt.set(t,r),r}const vt=async(e,t,n=!0)=>{if(!await _t(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>bt(r,e,t,n))),r},yt=e=>e instanceof Blob&&`name`in e,bt=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,D([await n.blob()],pt(n,r),i))}else if(mt(n))e.append(t,D([await new Response(Pe(n)).blob()],pt(n,r)));else if(yt(n))e.append(t,D([n],pt(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>bt(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>bt(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},xt=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,St=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&xt(e),Ct=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function wt(e,t,n){if(ft(),e=await e,t||=pt(e,!0),St(e))return e instanceof File&&t==null&&n==null?e:D([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(Ct(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),D(await Tt(r),t,n)}let r=await Tt(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return D(r,t,n)}async function Tt(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(xt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(mt(e))for await(let n of e)t.push(...await Tt(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Et(e)}`)}return t}function Et(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var O=class{constructor(e){this._client=e}};const Dt=Symbol.for(`brand.privateNullableHeaders`);function*Ot(e){if(!e)return;if(Dt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():_e(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=_e(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const k=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Ot(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Dt]:!0,values:t,nulls:n}};function kt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const At=Object.freeze(Object.create(null)),A=((e=kt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??At)??At)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new _(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
7
|
-
`)}\n${a}\n${t}`)}return a})(kt);var jt=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/environments/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/environments/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};const Mt=Symbol(`anthropic.sdk.stainlessHelper`);function Nt(e){return typeof e==`object`&&!!e&&Mt in e}function Pt(e,t){let n=new Set;if(e)for(let t of e)Nt(t)&&n.add(t[Mt]);if(t){for(let e of t)if(Nt(e)&&n.add(e[Mt]),Array.isArray(e.content))for(let t of e.content)Nt(t)&&n.add(t[Mt])}return Array.from(n)}function Ft(e,t){let n=Pt(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function It(e){return Nt(e)?{"x-stainless-helper":e[Mt]}:{}}var Lt=class extends O{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,dt,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}/content?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,ht({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},It(r.file),t?.headers])},this._client))}},Rt=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}?beta=true`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,dt,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},zt=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/user_profiles/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},Bt=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/agents/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Vt=class extends O{constructor(){super(...arguments),this.versions=new Bt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(A`/v1/agents/${e}?beta=true`,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/agents/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/agents/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Vt.Versions=Bt;var Ht=class extends O{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post(A`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memories?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Ut=class extends O{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post(A`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Wt=class extends O{constructor(){super(...arguments),this.memories=new Ht(this._client),this.memoryVersions=new Ut(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Wt.Memories=Ht,Wt.MemoryVersions=Ut;const Gt={"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 Kt(e){return e?.output_format??e?.output_config?.format}function qt(e,t,n){let r=Kt(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1});return Object.defineProperty(t,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Jt(e,t,n)}function Jt(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Yt(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},`parsed_output`,{value:i,enumerable:!1});return Object.defineProperty(a,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Yt(e,t){let n=Kt(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new _(`Failed to parse structured output: ${e}`)}}const Xt=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},Zt=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),Zt(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),Zt(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),Zt(e);break;case`delimiter`:return e=e.slice(0,e.length-1),Zt(e)}return e},Qt=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},$t=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},en=e=>JSON.parse($t(Qt(Zt(Xt(e)))));var j,M,N,tn,nn,rn,P,an,F,I,L,on,sn,R,cn,ln,un,dn,fn,pn,mn,hn,gn,_n;const vn=`__json_buf`;function yn(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var bn=class e{constructor(e,t){j.add(this),this.messages=[],this.receivedMessages=[],M.set(this,void 0),N.set(this,null),this.controller=new AbortController,tn.set(this,void 0),nn.set(this,()=>{}),rn.set(this,()=>{}),P.set(this,void 0),an.set(this,()=>{}),F.set(this,()=>{}),I.set(this,{}),L.set(this,!1),on.set(this,!1),sn.set(this,!1),R.set(this,!1),cn.set(this,void 0),ln.set(this,void 0),un.set(this,void 0),pn.set(this,e=>{if(h(this,on,!0,`f`),ne(e)&&(e=new y),e instanceof y)return h(this,sn,!0,`f`),this._emit(`abort`,e);if(e instanceof _)return this._emit(`error`,e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new _(String(e)))}),h(this,tn,new Promise((e,t)=>{h(this,nn,e,`f`),h(this,rn,t,`f`)}),`f`),h(this,P,new Promise((e,t)=>{h(this,an,e,`f`),h(this,F,t,`f`)}),`f`),g(this,tn,`f`).catch(()=>{}),g(this,P,`f`).catch(()=>{}),h(this,N,e,`f`),h(this,un,t?.logger??console,`f`)}get response(){return g(this,cn,`f`)}get request_id(){return g(this,ln,`f`)}async withResponse(){h(this,R,!0,`f`);let e=await g(this,tn,`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(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return h(a,N,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},g(this,pn,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{g(this,j,`m`,mn).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)g(this,j,`m`,hn).call(this,e);if(i.controller.signal?.aborted)throw new y;g(this,j,`m`,gn).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(h(this,cn,e,`f`),h(this,ln,e?.headers.get(`request-id`),`f`),g(this,nn,`f`).call(this,e),this._emit(`connect`))}get ended(){return g(this,L,`f`)}get errored(){return g(this,on,`f`)}get aborted(){return g(this,sn,`f`)}abort(){this.controller.abort()}on(e,t){return(g(this,I,`f`)[e]||(g(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=g(this,I,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(g(this,I,`f`)[e]||(g(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{h(this,R,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){h(this,R,!0,`f`),await g(this,P,`f`)}get currentMessage(){return g(this,M,`f`)}async finalMessage(){return await this.done(),g(this,j,`m`,dn).call(this)}async finalText(){return await this.done(),g(this,j,`m`,fn).call(this)}_emit(e,...t){if(g(this,L,`f`))return;e===`end`&&(h(this,L,!0,`f`),g(this,an,`f`).call(this));let n=g(this,I,`f`)[e];if(n&&(g(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!g(this,R,`f`)&&!n?.length&&Promise.reject(e),g(this,rn,`f`).call(this,e),g(this,F,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!g(this,R,`f`)&&!n?.length&&Promise.reject(e),g(this,rn,`f`).call(this,e),g(this,F,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,g(this,j,`m`,dn).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{g(this,j,`m`,mn).call(this),this._connected(null);let t=$e.fromReadableStream(e,this.controller);for await(let e of t)g(this,j,`m`,hn).call(this,e);if(t.controller.signal?.aborted)throw new y;g(this,j,`m`,gn).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(M=new WeakMap,N=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,P=new WeakMap,an=new WeakMap,F=new WeakMap,I=new WeakMap,L=new WeakMap,on=new WeakMap,sn=new WeakMap,R=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,pn=new WeakMap,j=new WeakSet,dn=function(){if(this.receivedMessages.length===0)throw new _(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},fn=function(){if(this.receivedMessages.length===0)throw new _(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new _(`stream ended without producing a content block with type=text`);return e.join(` `)},mn=function(){this.ended||h(this,M,void 0,`f`)},hn=function(e){if(this.ended)return;let t=g(this,j,`m`,_n).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:yn(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(qt(t,g(this,N,`f`),{logger:g(this,un,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:h(this,M,t,`f`);break;case`content_block_start`:case`message_delta`:break}},gn=function(){if(this.ended)throw new _(`stream has ended, this shouldn't happen`);let e=g(this,M,`f`);if(!e)throw new _(`request ended without sending any chunks`);return h(this,M,void 0,`f`),qt(e,g(this,N,`f`),{logger:g(this,un,`f`)})},_n=function(e){let t=g(this,M,`f`);if(e.type===`message_start`){if(t)throw new _(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new _(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&yn(n)){let r=n[vn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,vn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=en(r)}catch(e){let t=new _(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);g(this,pn,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},xn=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},Sn,z,B,V,H,U,W,G,Cn,wn,Tn;function En(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Dn=class{constructor(e,t,n){Sn.add(this),this.client=e,z.set(this,!1),B.set(this,!1),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),G.set(this,void 0),Cn.set(this,0),h(this,V,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...Pt(t.tools,t.messages)].join(`, `);h(this,H,{...n,headers:k([{"x-stainless-helper":r},n?.headers])},`f`),h(this,G,En(),`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*[(z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,Cn=new WeakMap,Sn=new WeakSet,wn=async function(){let e=g(this,V,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(g(this,U,`f`)!==void 0)try{let e=await g(this,U,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??g(this,V,`f`).params.model,i=e.summaryPrompt??`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:
|
|
8
|
-
1. Task Overview
|
|
9
|
-
The user's core request and success criteria
|
|
10
|
-
Any clarifications or constraints they specified
|
|
11
|
-
2. Current State
|
|
12
|
-
What has been completed so far
|
|
13
|
-
Files created, modified, or analyzed (with paths if relevant)
|
|
14
|
-
Key outputs or artifacts produced
|
|
15
|
-
3. Important Discoveries
|
|
16
|
-
Technical constraints or requirements uncovered
|
|
17
|
-
Decisions made and their rationale
|
|
18
|
-
Errors encountered and how they were resolved
|
|
19
|
-
What approaches were tried that didn't work (and why)
|
|
20
|
-
4. Next Steps
|
|
21
|
-
Specific actions needed to complete the task
|
|
22
|
-
Any blockers or open questions to resolve
|
|
23
|
-
Priority order if multiple steps remain
|
|
24
|
-
5. Context to Preserve
|
|
25
|
-
User preferences or style requirements
|
|
26
|
-
Domain-specific details that aren't obvious
|
|
27
|
-
Any promises made to the user
|
|
28
|
-
Be concise but complete—err 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.
|
|
29
|
-
Wrap your summary in <summary></summary> tags.`,a=g(this,V,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:g(this,V,`f`).params.max_tokens},{signal:g(this,H,`f`).signal,headers:k([g(this,H,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new _(`Expected text response for compaction`);return g(this,V,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(g(this,z,`f`))throw new _(`Cannot iterate over a consumed stream`);h(this,z,!0,`f`),h(this,B,!0,`f`),h(this,W,void 0,`f`);try{for(;;){let t;try{if(g(this,V,`f`).params.max_iterations&&g(this,Cn,`f`)>=g(this,V,`f`).params.max_iterations)break;h(this,B,!1,`f`),h(this,W,void 0,`f`),h(this,Cn,(e=g(this,Cn,`f`),e++,e),`f`),h(this,U,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=g(this,V,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},g(this,H,`f`)),h(this,U,t.finalMessage(),`f`),g(this,U,`f`).catch(()=>{}),yield t):(h(this,U,this.client.beta.messages.create({...i,stream:!1},g(this,H,`f`)),`f`),yield g(this,U,`f`)),!await g(this,Sn,`m`,wn).call(this)){if(!g(this,B,`f`)){let{role:e,content:t}=await g(this,U,`f`);g(this,V,`f`).params.messages.push({role:e,content:t})}let e=await g(this,Sn,`m`,Tn).call(this,g(this,V,`f`).params.messages.at(-1));if(e)g(this,V,`f`).params.messages.push(e);else if(!g(this,B,`f`))break}}finally{t&&t.abort()}}if(!g(this,U,`f`))throw new _(`ToolRunner concluded without a message from the server`);g(this,G,`f`).resolve(await g(this,U,`f`))}catch(e){throw h(this,z,!1,`f`),g(this,G,`f`).promise.catch(()=>{}),g(this,G,`f`).reject(e),h(this,G,En(),`f`),e}}setMessagesParams(e){typeof e==`function`?g(this,V,`f`).params=e(g(this,V,`f`).params):g(this,V,`f`).params=e,h(this,B,!0,`f`),h(this,W,void 0,`f`)}setRequestOptions(e){typeof e==`function`?h(this,H,e(g(this,H,`f`)),`f`):h(this,H,{...g(this,H,`f`),...e},`f`)}async generateToolResponse(e=g(this,H,`f`).signal){let t=await g(this,U,`f`)??this.params.messages.at(-1);return t?g(this,Sn,`m`,Tn).call(this,t,e):null}done(){return g(this,G,`f`).promise}async runUntilDone(){if(!g(this,z,`f`))for await(let e of this);return this.done()}get params(){return g(this,V,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};Tn=async function(e,t=g(this,H,`f`).signal){return g(this,W,`f`)===void 0&&h(this,W,On(g(this,V,`f`).params,e,{...g(this,H,`f`),signal:t}),`f`),g(this,W,`f`)};async function On(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof xn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var kn=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new We;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new _(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new _(`Attempted to iterate over a response with no body`);return new e(Fe(t.body),n)}},An=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,dt,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new _(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:k([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>kn.fromResponse(t.response,t.controller))}};const jn={"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`},Mn=[`claude-mythos-preview`,`claude-opus-4-6`];var Nn=class extends O{constructor(){super(...arguments),this.batches=new An(this._client)}create(e,t){let n=Pn(e),{betas:r,...i}=n;i.model in jn&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${jn[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),Mn.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.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 a=this._client._options.timeout;if(!i.stream&&a==null){let e=Gt[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=Ft(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:k([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Jt(t,e,{logger:this._client.logger??console}))}stream(e,t){return bn.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=Pn(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new Dn(this._client,e,t)}};function Pn(e){if(!e.output_format)return e;if(e.output_config?.format)throw new _(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}Nn.Batches=An,Nn.BetaToolRunner=Dn,Nn.ToolError=xn;var Fn=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/events?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},In=class extends O{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post(A`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/resources?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Ln=class extends O{constructor(){super(...arguments),this.events=new Fn(this._client),this.resources=new In(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/sessions/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Ln.Events=Fn,Ln.Resources=In;var Rn=class extends O{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(A`/v1/skills/${e}/versions?beta=true`,ht({body:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/skills/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},zn=class extends O{constructor(){super(...arguments),this.versions=new Rn(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,ht({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};zn.Versions=Rn;var Bn=class extends O{create(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/vaults/${e}/credentials?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Vn=class extends O{constructor(){super(...arguments),this.credentials=new Bn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/vaults/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Vn.Credentials=Bn;var K=class extends O{constructor(){super(...arguments),this.models=new Rt(this._client),this.messages=new Nn(this._client),this.agents=new Vt(this._client),this.environments=new jt(this._client),this.sessions=new Ln(this._client),this.vaults=new Vn(this._client),this.memoryStores=new Wt(this._client),this.files=new Lt(this._client),this.skills=new zn(this._client),this.userProfiles=new zt(this._client)}};K.Models=Rt,K.Messages=Nn,K.Agents=Vt,K.Environments=jt,K.Sessions=Ln,K.Vaults=Vn,K.MemoryStores=Wt,K.Files=Lt,K.Skills=zn,K.UserProfiles=zt;var Hn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Un(e){return e?.output_config?.format}function Wn(e,t,n){let r=Un(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1}):e),parsed_output:null}:Gn(e,t,n)}function Gn(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Kn(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},`parsed_output`,{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Kn(e,t){let n=Un(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new _(`Failed to parse structured output: ${e}`)}}var q,J,Y,qn,Jn,Yn,Xn,Zn,Qn,X,$n,er,tr,Z,nr,rr,ir,ar,or,sr,cr,lr,ur,dr;const fr=`__json_buf`;function pr(e){return e.type===`tool_use`||e.type===`server_tool_use`}var mr=class e{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],J.set(this,void 0),Y.set(this,null),this.controller=new AbortController,qn.set(this,void 0),Jn.set(this,()=>{}),Yn.set(this,()=>{}),Xn.set(this,void 0),Zn.set(this,()=>{}),Qn.set(this,()=>{}),X.set(this,{}),$n.set(this,!1),er.set(this,!1),tr.set(this,!1),Z.set(this,!1),nr.set(this,void 0),rr.set(this,void 0),ir.set(this,void 0),sr.set(this,e=>{if(h(this,er,!0,`f`),ne(e)&&(e=new y),e instanceof y)return h(this,tr,!0,`f`),this._emit(`abort`,e);if(e instanceof _)return this._emit(`error`,e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new _(String(e)))}),h(this,qn,new Promise((e,t)=>{h(this,Jn,e,`f`),h(this,Yn,t,`f`)}),`f`),h(this,Xn,new Promise((e,t)=>{h(this,Zn,e,`f`),h(this,Qn,t,`f`)}),`f`),g(this,qn,`f`).catch(()=>{}),g(this,Xn,`f`).catch(()=>{}),h(this,Y,e,`f`),h(this,ir,t?.logger??console,`f`)}get response(){return g(this,nr,`f`)}get request_id(){return g(this,rr,`f`)}async withResponse(){h(this,Z,!0,`f`);let e=await g(this,qn,`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(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return h(a,Y,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},g(this,sr,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{g(this,q,`m`,cr).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)g(this,q,`m`,lr).call(this,e);if(i.controller.signal?.aborted)throw new y;g(this,q,`m`,ur).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(h(this,nr,e,`f`),h(this,rr,e?.headers.get(`request-id`),`f`),g(this,Jn,`f`).call(this,e),this._emit(`connect`))}get ended(){return g(this,$n,`f`)}get errored(){return g(this,er,`f`)}get aborted(){return g(this,tr,`f`)}abort(){this.controller.abort()}on(e,t){return(g(this,X,`f`)[e]||(g(this,X,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=g(this,X,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(g(this,X,`f`)[e]||(g(this,X,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{h(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){h(this,Z,!0,`f`),await g(this,Xn,`f`)}get currentMessage(){return g(this,J,`f`)}async finalMessage(){return await this.done(),g(this,q,`m`,ar).call(this)}async finalText(){return await this.done(),g(this,q,`m`,or).call(this)}_emit(e,...t){if(g(this,$n,`f`))return;e===`end`&&(h(this,$n,!0,`f`),g(this,Zn,`f`).call(this));let n=g(this,X,`f`)[e];if(n&&(g(this,X,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!g(this,Z,`f`)&&!n?.length&&Promise.reject(e),g(this,Yn,`f`).call(this,e),g(this,Qn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!g(this,Z,`f`)&&!n?.length&&Promise.reject(e),g(this,Yn,`f`).call(this,e),g(this,Qn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,g(this,q,`m`,ar).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{g(this,q,`m`,cr).call(this),this._connected(null);let t=$e.fromReadableStream(e,this.controller);for await(let e of t)g(this,q,`m`,lr).call(this,e);if(t.controller.signal?.aborted)throw new y;g(this,q,`m`,ur).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(J=new WeakMap,Y=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,X=new WeakMap,$n=new WeakMap,er=new WeakMap,tr=new WeakMap,Z=new WeakMap,nr=new WeakMap,rr=new WeakMap,ir=new WeakMap,sr=new WeakMap,q=new WeakSet,ar=function(){if(this.receivedMessages.length===0)throw new _(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},or=function(){if(this.receivedMessages.length===0)throw new _(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new _(`stream ended without producing a content block with type=text`);return e.join(` `)},cr=function(){this.ended||h(this,J,void 0,`f`)},lr=function(e){if(this.ended)return;let t=g(this,q,`m`,dr).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:pr(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Wn(t,g(this,Y,`f`),{logger:g(this,ir,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:h(this,J,t,`f`);break;case`content_block_start`:case`message_delta`:break}},ur=function(){if(this.ended)throw new _(`stream has ended, this shouldn't happen`);let e=g(this,J,`f`);if(!e)throw new _(`request ended without sending any chunks`);return h(this,J,void 0,`f`),Wn(e,g(this,Y,`f`),{logger:g(this,ir,`f`)})},dr=function(e){let t=g(this,J,`f`);if(e.type===`message_start`){if(t)throw new _(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new _(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&pr(n)){let r=n[fr]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,fr,{value:r,enumerable:!1,writable:!0}),r&&(i.input=en(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},hr=class extends O{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(A`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,dt,{query:e,...t})}delete(e,t){return this._client.delete(A`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(A`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new _(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:k([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>kn.fromResponse(t.response,t.controller))}},gr=class extends O{constructor(){super(...arguments),this.batches=new hr(this._client)}create(e,t){e.model in _r&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${_r[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),vr.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 n=this._client._options.timeout;if(!e.stream&&n==null){let t=Gt[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=Ft(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:k([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Gn(t,e,{logger:this._client.logger??console}))}stream(e,t){return mr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}};const _r={"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`},vr=[`claude-mythos-preview`,`claude-opus-4-6`];gr.Batches=hr;var yr=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,dt,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}};const br=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var xr,Sr,Cr,wr,Q=class{constructor({baseURL:e=br(`ANTHROPIC_BASE_URL`),apiKey:t=br(`ANTHROPIC_API_KEY`)??null,authToken:n=br(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){xr.add(this),Cr.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&we())throw new _(`It looks like you're running in a browser-like environment.
|
|
30
|
-
|
|
31
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
32
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
33
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
34
|
-
|
|
35
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
36
|
-
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Sr.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Je(i.logLevel,`ClientOptions.logLevel`,this)??Je(br(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Me(),h(this,Cr,Le,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}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`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))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 k([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return k([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Re(e)}getUserAgent(){return`${this.constructor.name}/JS ${b}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return v.generate(e,t,n,r)}buildURL(e,t,n){let r=!g(this,xr,`m`,wr).call(this)&&n||this.baseURL,i=he(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ye(a)||!ye(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new _(`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 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}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,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new st(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(w(this).debug(`[${c}] sending request`,T({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new y;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(re),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new y;let i=ne(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return w(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),w(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,T({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw w(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),w(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,T({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new ae:new ie({cause:f})}let ee=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Ie(f.body),w(this).info(`${ee} - ${e}`),w(this).debug(`[${c}] response error (${e})`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;w(this).info(`${ee} - ${i}`);let a=await f.text().catch(e=>re(e).message),o=Se(a),s=o?void 0:a;throw w(this).debug(`[${c}] response error (${i})`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return w(this).info(ee),w(this).debug(`[${c}] response start`,T({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ut(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Ce(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new _(`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 n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&xe(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=k([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...je(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=k([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Pe(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:g(this,Cr,`f`).call(this,{body:e,headers:n})}};Sr=Q,Cr=new WeakMap,xr=new WeakSet,wr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=Sr,Q.HUMAN_PROMPT=`\\n\\nHuman:`,Q.AI_PROMPT=`\\n\\nAssistant:`,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=_,Q.APIError=v,Q.APIConnectionError=ie,Q.APIConnectionTimeoutError=ae,Q.APIUserAbortError=y,Q.NotFoundError=le,Q.ConflictError=ue,Q.RateLimitError=fe,Q.BadRequestError=oe,Q.AuthenticationError=se,Q.InternalServerError=pe,Q.PermissionDeniedError=ce,Q.UnprocessableEntityError=de,Q.toFile=wt;var $=class extends Q{constructor(){super(...arguments),this.completions=new Hn(this),this.messages=new gr(this),this.models=new yr(this),this.beta=new K(this)}};$.Completions=Hn,$.Messages=gr,$.Models=yr,$.Beta=K;function Tr(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function Er(e,t,n){let r=Tr(t,n);if(r===`none`)return{retention:r};let i=r===`long`&&jr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:r,cacheControl:{type:`ephemeral`,...i&&{ttl:i}}}}const Dr=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),Or=e=>Dr.get(e.toLowerCase())??e,kr=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function Ar(e){if(!e.some(e=>e.type===`image`))return c(e.map(e=>e.text).join(`
|
|
37
|
-
`));let t=e.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}});return t.some(e=>e.type===`text`)||t.unshift({type:`text`,text:`(see attached image)`}),t}function jr(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??Mr(e)}}function Mr(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 n=Number(t[1]),r=t[2]&&t[2].length<8?Number(t[2]):0;return n>4||n===4&&r>=5}function Nr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}function Pr(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function Fr(e,t,n){if(!t&&!(Pr(n,`authorization`)||Pr(n,`x-api-key`)||Pr(n,`cf-aig-authorization`)))throw Error(`No API key for provider: ${e}`)}const Ir=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Lr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
38
|
-
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Rr(e,t){if(e===``)return Lr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function zr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
39
|
-
`);return t===-1?n:n===-1?t:Math.min(t,n)}function Br(e){let t=zr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
|
|
40
|
-
`&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Vr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Br(a);for(;s;){a=s.rest;let e=Rr(s.line,i);e&&(yield e),s=Br(a)}}a+=r.decode();let e=Br(a);for(;e;){a=e.rest;let t=Rr(e.line,i);t&&(yield t),e=Br(a)}if(a.length>0){let e=Rr(a,i);e&&(yield e)}let o=Lr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Hr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,i=!1;for await(let a of Vr(e.body,t)){if(a.event===`error`)throw Error(a.data);if(Ir.has(a.event??``))try{let e=r(a.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(i=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${a.event}: ${t}; data=${a.data}; raw=${a.raw.join(`\\n`)}`)}}if(n&&!i)throw Error(`Anthropic stream ended before message_stop`)}const Ur=(r,i,a)=>{let c=new e;return(async()=>{let e={role:`assistant`,content:[],api:r.api,provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let l,u;if(a?.client)l=a.client,u=!1;else{let e=a?.apiKey;Fr(r.provider,e,a?.headers);let t;if(r.provider===`github-copilot`){let e=ee(i.messages);t=m({messages:i.messages,hasImages:e})}let n=Tr(a?.cacheRetention,a?.env)===`none`?void 0:a?.sessionId,o=qr(r,e,a?.interleavedThinking??!0,Qr(r,i),a?.headers,a?.fetch,t,n);l=o.client,u=o.isOAuthToken}let d=Jr(r,i,u,a),f=await a?.onPayload?.(d,r);f!==void 0&&(d=f);let p={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},maxRetries:0},h=await s(()=>l.messages.create({...d,stream:!0},p).asResponse(),{maxRetries:a?.maxRetries,maxRetryDelayMs:a?.maxRetryDelayMs,signal:a?.signal});await a?.onResponse?.({status:h.status,headers:o(h.headers)},r),c.push({type:`start`,partial:e});let g=e.content;for await(let o of Hr(h,a?.signal))if(o.type===`message_start`)e.responseId=o.message.id,e.usage.input=o.message.usage.input_tokens||0,e.usage.output=o.message.usage.output_tokens||0,e.usage.cacheRead=o.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=o.message.usage.cache_creation_input_tokens||0,e.usage.cacheWrite1h=o.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(r,e.usage);else if(o.type===`content_block_start`){if(o.content_block.type===`text`){let t={type:`text`,text:``,index:o.index};e.content.push(t),c.push({type:`text_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`thinking`){let t={type:`thinking`,thinking:``,thinkingSignature:``,index:o.index};e.content.push(t),c.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`redacted_thinking`){let t={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:o.content_block.data,redacted:!0,index:o.index};e.content.push(t),c.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`tool_use`){let t={type:`toolCall`,id:o.content_block.id,name:u?kr(o.content_block.name,i.tools):o.content_block.name,arguments:o.content_block.input??{},partialJson:``,index:o.index};e.content.push(t),c.push({type:`toolcall_start`,contentIndex:e.content.length-1,partial:e})}}else if(o.type===`content_block_delta`){if(o.delta.type===`text_delta`){let t=g.findIndex(e=>e.index===o.index),n=g[t];n&&n.type===`text`&&(n.text+=o.delta.text,c.push({type:`text_delta`,contentIndex:t,delta:o.delta.text,partial:e}))}else if(o.delta.type===`thinking_delta`){let t=g.findIndex(e=>e.index===o.index),n=g[t];n&&n.type===`thinking`&&(n.thinking+=o.delta.thinking,c.push({type:`thinking_delta`,contentIndex:t,delta:o.delta.thinking,partial:e}))}else if(o.delta.type===`input_json_delta`){let t=g.findIndex(e=>e.index===o.index),r=g[t];r&&r.type===`toolCall`&&(r.partialJson+=o.delta.partial_json,r.arguments=n(r.partialJson),c.push({type:`toolcall_delta`,contentIndex:t,delta:o.delta.partial_json,partial:e}))}else if(o.delta.type===`signature_delta`){let e=g[g.findIndex(e=>e.index===o.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=o.delta.signature)}}else if(o.type===`content_block_stop`){let t=g.findIndex(e=>e.index===o.index),r=g[t];r&&(delete r.index,r.type===`text`?c.push({type:`text_end`,contentIndex:t,content:r.text,partial:e}):r.type===`thinking`?c.push({type:`thinking_end`,contentIndex:t,content:r.thinking,partial:e}):r.type===`toolCall`&&(r.arguments=n(r.partialJson),delete r.partialJson,c.push({type:`toolcall_end`,contentIndex:t,toolCall:r,partial:e})))}else if(o.type===`message_delta`){if(o.delta.stop_reason){e.rawStopReason=o.delta.stop_reason;let t=ei(o.delta.stop_reason,o.delta.stop_details);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage)}if(o.usage){o.usage.input_tokens!=null&&(e.usage.input=o.usage.input_tokens),o.usage.output_tokens!=null&&(e.usage.output=o.usage.output_tokens),o.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=o.usage.cache_read_input_tokens),o.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=o.usage.cache_creation_input_tokens);let t=o.usage.output_tokens_details?.thinking_tokens;t!=null&&(e.usage.reasoning=t)}e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(r,e.usage)}if(a?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`Anthropic stream ended without a stop reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);c.push({type:`done`,reason:e.stopReason,message:e}),c.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:JSON.stringify(t),c.push({type:`error`,reason:e.stopReason,error:e}),c.end()}})(),c};function Wr(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}const Gr=(e,t,n)=>{Fr(e.provider,n?.apiKey,n?.headers);let r=f(e,t,n,n?.apiKey);if(!n?.reasoning)return Ur(e,t,{...r,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let i=Wr(e,n.reasoning);return Ur(e,t,{...r,thinkingEnabled:!0,effort:i})}let i=d(r.maxTokens,e.maxTokens,n.reasoning,n.thinkingBudgets),a=l(e,t,i.maxTokens);return Ur(e,t,{...r,maxTokens:a,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(i.thinkingBudget,Math.max(0,a-1024))})};function Kr(e){return e.includes(`sk-ant-oat`)}function qr(e,t,n,r,i,a,o,s){let c=n&&e.compat?.forceAdaptiveThinking!==!0,l=[];if(r&&l.push(`fine-grained-tool-streaming-2025-05-14`),c&&l.push(`interleaved-thinking-2025-05-14`),e.provider===`github-copilot`)return{client:new $({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:Nr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...l.length>0?{"anthropic-beta":l.join(`,`)}:{}},e.headers,o,i)}),isOAuthToken:!1};if(t&&Kr(t))return{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:Nr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...l].join(`,`),"user-agent":`claude-cli/2.1.75`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0};let u=s&&jr(e).sendSessionAffinityHeaders?{"x-session-affinity":s}:{},d=Nr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...l.length>0?{"anthropic-beta":l.join(`,`)}:{}},u,e.headers,i);return{client:new $({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:d}),isOAuthToken:!1}}function Jr(e,t,n,r){let{cacheControl:i}=Er(e,r?.cacheRetention,r?.env),o=jr(e),s=p(t.messages,e,Yr),l=n?Or:e=>e,u=a({...t,messages:s},o.supportsToolReferences,l),d=u.immediate,f=[...u.deferred.values()];d.length===0&&f.length>0&&(d=f,f=[]);let ee=new Set(f.map(e=>l(e.name))),m={model:e.id,messages:Zr(s,n,i,o.allowEmptySignature,ee,l),max_tokens:r?.maxTokens??e.maxTokens,stream:!0};if(n?(m.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&m.system.push({type:`text`,text:c(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(m.system=[{type:`text`,text:c(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&o.supportsTemperature&&(m.temperature=r.temperature),(d.length>0||f.length>0)&&(m.tools=[...$r(d,n,o.supportsEagerToolInputStreaming,o.supportsStrictTools,o.supportsCacheControlOnTools?i:void 0),...$r(f,n,o.supportsEagerToolInputStreaming,o.supportsStrictTools,void 0,!0)]),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;e.compat?.forceAdaptiveThinking===!0?(m.thinking={type:`adaptive`,display:t},r.effort&&(m.output_config=(r.effort,{effort:r.effort}))):m.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null&&(m.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(m.metadata={user_id:e})}return r?.toolChoice&&(typeof r.toolChoice==`string`?m.tool_choice={type:r.toolChoice}:m.tool_choice=r.toolChoice),m}function Yr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Xr(e,t,n,r,i){let a=[];for(let o of e.addedToolNames??[]){let e=i(o);!n.has(e)||r.has(e)||(r.add(e),a.push({type:`tool_reference`,tool_name:t?Or(o):o}))}let o=Ar(e.content);return{toolResult:{type:`tool_result`,tool_use_id:e.toolCallId,content:a.length>0?a:o,is_error:e.isError},siblingContent:a.length===0?[]:typeof o==`string`?[{type:`text`,text:o}]:o}}function Zr(e,t,n,r=!1,i=new Set,a=e=>e){let o=[],s=new Set;for(let n=0;n<e.length;n++){let l=e[n];if(l.role===`user`)if(typeof l.content==`string`)l.content.trim().length>0&&o.push({role:`user`,content:c(l.content)});else{let e=l.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}}).filter(e=>e.type===`text`?e.text.trim().length>0:!0);if(e.length===0)continue;o.push({role:`user`,content:e})}else if(l.role===`assistant`){let e=[];for(let n of l.content)if(n.type===`text`){if(n.text.trim().length===0)continue;e.push({type:`text`,text:c(n.text)})}else if(n.type===`thinking`){if(n.redacted){e.push({type:`redacted_thinking`,data:n.thinkingSignature});continue}let t=n.thinkingSignature,i=!!t&&t.trim().length>0;if(n.thinking.trim().length===0&&!i)continue;i?e.push({type:`thinking`,thinking:c(n.thinking),signature:t}):e.push(r?{type:`thinking`,thinking:c(n.thinking),signature:``}:{type:`text`,text:c(n.thinking)})}else n.type===`toolCall`&&e.push({type:`tool_use`,id:n.id,name:t?Or(n.name):n.name,input:n.arguments??{}});if(e.length===0)continue;o.push({role:`assistant`,content:e})}else if(l.role===`toolResult`){let r=[],c=[],l=n;for(;l<e.length&&e[l].role===`toolResult`;){let n=Xr(e[l],t,i,s,a);r.push(n.toolResult),c.push(...n.siblingContent),l++}n=l-1,o.push({role:`user`,content:[...r,...c]})}}if(n&&o.length>0){let e=o[o.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=n)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:n}])}return o}function Qr(e,t){return!!t.tools?.length&&!jr(e).supportsEagerToolInputStreaming}function $r(e,t,n,r,i,a=!1){return e?e.map((o,s)=>{let c=u(o,r),l=o.parameters,d={type:`object`,properties:l.properties??{},required:l.required??[]},f=c===!0?{...o.parameters,...d}:d;return{name:t?Or(o.name):o.name,description:o.description,...n?{eager_input_streaming:!0}:{},...c===!0?{strict:!0}:{},input_schema:f,...a?{defer_loading:!0}:{},...i&&s===e.length-1?{cache_control:i}:{}}}):[]}function ei(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`,errorMessage:`Provider stopped with: sensitive`};default:throw Error(`Unhandled stop reason: ${e}`)}}export{Ur as stream,Gr as streamSimple};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t}from"./models-CwK5xZH9.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as n}from"./provider-env-CL5ShLlj.mjs";import{t as r}from"./headers-BvGum5dc.mjs";import{t as i}from"./provider-retry-BM3ArvaW.mjs";import{o as a,r as o}from"./transform-messages-CSBQpmXO.mjs";import{t as s}from"./openai-Brr_V-tF.mjs";import{n as c,t as l}from"./error-body-D2Mrqb4g.mjs";import{t as u}from"./openai-prompt-cache-t4kk9puG.mjs";import{n as d,r as f,t as p}from"./openai-responses-shared-D4d0NbBE.mjs";const m=new Set([`openai`,`openai-codex`,`opencode`,`azure-openai-responses`]);function h(e){let t=new Map;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let[r,i]=e.split(`=`,2);!r||!i||t.set(r.trim(),i.trim())}return t}function g(e,t){return t?.azureDeploymentName?t.azureDeploymentName:h(n(`AZURE_OPENAI_DEPLOYMENT_NAME_MAP`,t?.env)).get(e.id)||e.id}function _(e){return l(c(e),`Azure OpenAI API error`)}const v=(t,n,o)=>{let s=new e;return(async()=>{let e=g(t,o),c={role:`assistant`,content:[],api:`azure-openai-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let l=o?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let u=C(t,l,o),d=a(n.tools,t.compat?.supportsOpenAIGrammarTools??!1),p=w(t,n,o,e,d),m=await o?.onPayload?.(p,t);m!==void 0&&(p=m);let h={...o?.signal?{signal:o.signal}:{},...o?.timeoutMs===void 0?{}:{timeout:o.timeoutMs},maxRetries:0},{data:g,response:_}=await i(()=>u.responses.create(p,h).withResponse(),{maxRetries:o?.maxRetries,maxRetryDelayMs:o?.maxRetryDelayMs,signal:o?.signal});if(await o?.onResponse?.({status:_.status,headers:r(_.headers)},t),s.push({type:`start`,partial:c}),await f(g,c,s,t,{grammarToolInputProperties:d}),o?.signal?.aborted)throw Error(`Request was aborted`);if(c.stopReason===`pending`)throw Error(`Azure OpenAI Responses stream ended without a stop reason`);if(c.stopReason===`aborted`||c.stopReason===`error`)throw Error(`An unknown error occurred`);s.push({type:`done`,reason:c.stopReason,message:c}),s.end()}catch(e){for(let e of c.content)delete e.index,delete e.partialJson,delete e.customInput;c.stopReason=o?.signal?.aborted?`aborted`:`error`,c.errorMessage=_(e),s.push({type:`error`,reason:c.stopReason,error:c}),s.end()}})(),s},y=(e,n,r)=>{let i=r?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let a=o(e,n,r,i),s=r?.reasoning?t(e,r.reasoning):void 0,c=s===`off`?void 0:s;return v(e,n,{...a,reasoningEffort:c})};function b(e){let t=e.trim().replace(/\/+$/,``),n;try{n=new URL(t)}catch{throw Error(`Invalid Azure OpenAI base URL: ${e}`)}let r=n.hostname.endsWith(`.openai.azure.com`)||n.hostname.endsWith(`.cognitiveservices.azure.com`)||n.hostname.endsWith(`.ai.azure.com`),i=n.pathname.replace(/\/+$/,``);return r&&(i===``||i===`/`||i===`/openai`||i===`/openai/v1/responses`)&&(n.pathname=`/openai/v1`,n.search=``),n.toString().replace(/\/+$/,``)}function x(e){return`https://${e}.openai.azure.com/openai/v1`}function S(e,t){let r=t?.azureApiVersion||n(`AZURE_OPENAI_API_VERSION`,t?.env)||`v1`,i=t?.azureBaseUrl?.trim()||n(`AZURE_OPENAI_BASE_URL`,t?.env)?.trim()||void 0,a=t?.azureResourceName||n(`AZURE_OPENAI_RESOURCE_NAME`,t?.env),o=i;if(!o&&a&&(o=x(a)),!o&&e.baseUrl&&(o=e.baseUrl),!o)throw Error(`Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.`);return{baseUrl:b(o),apiVersion:r}}function C(e,t,n){let r={...e.headers};n?.headers&&Object.assign(r,n.headers);let{baseUrl:i,apiVersion:a}=S(e,n);return new s({apiKey:t,apiVersion:a,dangerouslyAllowBrowser:!0,fetch:n?.fetch,defaultHeaders:r,baseURL:i})}function w(e,t,n,r,i=a(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o={model:r,input:p(e,t,m,{grammarToolInputProperties:i}),stream:!0,prompt_cache_key:u(n?.sessionId),store:!1};return n?.maxTokens&&(o.max_output_tokens=Math.max(n.maxTokens,16)),n?.temperature!==void 0&&(o.temperature=n?.temperature),t.tools&&t.tools.length>0&&(o.tools=d(t.tools,{supportsStrictMode:e.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1})),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}export{v as stream,y as streamSimple};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
function e(e){return{ok:!0,value:e}}function t(e){return{ok:!1,error:e}}async function n(e){let t=await e;if(!t.ok)throw t.error;return t.value}const r=Object.freeze({status:`aborted`});function i(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var a=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};const o={};function s(e){return e&&Object.assign(o,e),o}function c(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function l(e,t){return typeof t==`bigint`?t.toString():t}function u(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function d(e){return e==null}function f(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function p(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function m(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}throw Error(`cached value already set`)},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function h(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function g(e){return JSON.stringify(e)}const ee=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function te(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ne=u(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function _(e){if(te(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(te(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}const re=new Set([`string`,`number`,`symbol`]);function v(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function y(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function b(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ie(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const ae={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function oe(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return y(e,{...e._zod.def,shape:n,checks:[]})}function se(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return y(e,{...e._zod.def,shape:n,checks:[]})}function ce(e,t){if(!_(t))throw Error(`Invalid input to extend: expected a plain object`);return y(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return h(this,`shape`,n),n},checks:[]})}function le(e,t){return y(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return h(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function ue(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return y(t,{...t._zod.def,shape:i,checks:[]})}function de(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return y(t,{...t._zod.def,shape:i,checks:[]})}function x(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function S(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function C(e){return typeof e==`string`?e:e?.message}function w(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=C(e.inst?._zod.def?.error?.(e))??C(t?.error?.(e))??C(n.customError?.(e))??C(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function fe(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function T(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const pe=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),Object.defineProperty(e,`message`,{get(){return JSON.stringify(t,l,2)},enumerable:!0}),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},E=i(`$ZodError`,pe),me=i(`$ZodError`,pe,{Parent:Error});function he(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function ge(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}function _e(e){let t=[];for(let n of e)typeof n==`number`?t.push(`[${n}]`):typeof n==`symbol`?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push(`.`),t.push(n));return t.join(``)}function ve(e){let t=[],n=[...e.issues].sort((e,t)=>e.path.length-t.path.length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${_e(e.path)}`);return t.join(`
|
|
3
|
-
`)}const ye=e=>(t,n,r,i)=>{let o=r?Object.assign(r,{async:!1}):{async:!1},c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise)throw new a;if(c.issues.length){let t=new(i?.Err??e)(c.issues.map(e=>w(e,o,s())));throw ee(t,i?.callee),t}return c.value},be=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>w(e,a,s())));throw ee(t,i?.callee),t}return o.value},xe=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new a;return o.issues.length?{success:!1,error:new(e??E)(o.issues.map(e=>w(e,i,s())))}:{success:!0,data:o.value}},Se=xe(me),Ce=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>w(e,i,s())))}:{success:!0,data:a.value}},we=Ce(me),Te=/^[cC][^\s-]{8,}$/,Ee=/^[0-9a-z]+$/,De=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Oe=/^[0-9a-vA-V]{20}$/,ke=/^[A-Za-z0-9]{27}$/,Ae=/^[a-zA-Z0-9_-]{21}$/,je=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Me=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ne=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Pe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Fe(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const Ie=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Le=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Re=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ze=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Be=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ve=/^[A-Za-z0-9_-]*$/,He=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ue=/^\+(?:[0-9]){6,14}[0-9]$/,We=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Ge=RegExp(`^${We}$`);function Ke(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qe(e){return RegExp(`^${Ke(e)}$`)}function Je(e){let t=Ke({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${We}T(?:${r})$`)}const Ye=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Xe=/^\d+$/,Ze=/^-?\d+(?:\.\d+)?/i,Qe=/true|false/i,$e=/^[^A-Z]*$/,et=/^[^a-z]*$/,D=i(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),tt={number:`number`,bigint:`bigint`,object:`date`},nt=i(`$ZodCheckLessThan`,(e,t)=>{D.init(e,t);let n=tt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rt=i(`$ZodCheckGreaterThan`,(e,t)=>{D.init(e,t);let n=tt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),it=i(`$ZodCheckMultipleOf`,(e,t)=>{D.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):p(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),at=i(`$ZodCheckNumberFormat`,(e,t)=>{D.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ae[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Xe)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),ot=i(`$ZodCheckMaxLength`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=fe(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),st=i(`$ZodCheckMinLength`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=fe(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ct=i(`$ZodCheckLengthEquals`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=fe(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),O=i(`$ZodCheckStringFormat`,(e,t)=>{var n,r;D.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),lt=i(`$ZodCheckRegex`,(e,t)=>{O.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ut=i(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=$e,O.init(e,t)}),dt=i(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=et,O.init(e,t)}),ft=i(`$ZodCheckIncludes`,(e,t)=>{D.init(e,t);let n=v(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),pt=i(`$ZodCheckStartsWith`,(e,t)=>{D.init(e,t);let n=RegExp(`^${v(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),mt=i(`$ZodCheckEndsWith`,(e,t)=>{D.init(e,t);let n=RegExp(`.*${v(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ht=i(`$ZodCheckOverwrite`,(e,t)=>{D.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var gt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
4
|
-
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
5
|
-
`))}};const _t={major:4,minor:0,patch:0},k=i(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_t;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=x(e),i;for(let o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&n?.async===!1)throw new a;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(r||=x(e,t))});else{if(e.issues.length===t)continue;r||=x(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let o=e._zod.parse(n,i);if(o instanceof Promise){if(i.async===!1)throw new a;return o.then(e=>t(e,r,i))}return t(o,r,i)}}e[`~standard`]={validate:t=>{try{let n=Se(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return we(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),vt=i(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ye(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),A=i(`$ZodStringFormat`,(e,t)=>{O.init(e,t),vt.init(e,t)}),yt=i(`$ZodGUID`,(e,t)=>{t.pattern??=Me,A.init(e,t)}),bt=i(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Ne(e)}else t.pattern??=Ne();A.init(e,t)}),xt=i(`$ZodEmail`,(e,t)=>{t.pattern??=Pe,A.init(e,t)}),St=i(`$ZodURL`,(e,t)=>{A.init(e,t),e._zod.check=n=>{try{let r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:He.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith(`/`)&&a.endsWith(`/`)?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Ct=i(`$ZodEmoji`,(e,t)=>{t.pattern??=Fe(),A.init(e,t)}),wt=i(`$ZodNanoID`,(e,t)=>{t.pattern??=Ae,A.init(e,t)}),Tt=i(`$ZodCUID`,(e,t)=>{t.pattern??=Te,A.init(e,t)}),Et=i(`$ZodCUID2`,(e,t)=>{t.pattern??=Ee,A.init(e,t)}),Dt=i(`$ZodULID`,(e,t)=>{t.pattern??=De,A.init(e,t)}),Ot=i(`$ZodXID`,(e,t)=>{t.pattern??=Oe,A.init(e,t)}),kt=i(`$ZodKSUID`,(e,t)=>{t.pattern??=ke,A.init(e,t)}),At=i(`$ZodISODateTime`,(e,t)=>{t.pattern??=Je(t),A.init(e,t)}),jt=i(`$ZodISODate`,(e,t)=>{t.pattern??=Ge,A.init(e,t)}),Mt=i(`$ZodISOTime`,(e,t)=>{t.pattern??=qe(t),A.init(e,t)}),Nt=i(`$ZodISODuration`,(e,t)=>{t.pattern??=je,A.init(e,t)}),Pt=i(`$ZodIPv4`,(e,t)=>{t.pattern??=Ie,A.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),Ft=i(`$ZodIPv6`,(e,t)=>{t.pattern??=Le,A.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),It=i(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Re,A.init(e,t)}),Lt=i(`$ZodCIDRv6`,(e,t)=>{t.pattern??=ze,A.init(e,t),e._zod.check=n=>{let[r,i]=n.value.split(`/`);try{if(!i)throw Error();let e=Number(i);if(`${e}`!==i||e<0||e>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Rt(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const zt=i(`$ZodBase64`,(e,t)=>{t.pattern??=Be,A.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{Rt(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Bt(e){if(!Ve.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Rt(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Vt=i(`$ZodBase64URL`,(e,t)=>{t.pattern??=Ve,A.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{Bt(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Ht=i(`$ZodE164`,(e,t)=>{t.pattern??=Ue,A.init(e,t)});function Ut(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Wt=i(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{Ut(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Gt=i(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ze,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Kt=i(`$ZodNumber`,(e,t)=>{at.init(e,t),Gt.init(e,t)}),qt=i(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=Qe,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Jt=i(`$ZodAny`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),Yt=i(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),Xt=i(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),Zt=i(`$ZodVoid`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`void`,code:`invalid_type`,input:r,inst:e}),t}}),Qt=i(`$ZodDate`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let i=n.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||n.issues.push({expected:`date`,code:`invalid_type`,input:i,...a?{received:`Invalid Date`}:{},inst:e}),n}});function $t(e,t,n){e.issues.length&&t.issues.push(...S(n,e.issues)),t.value[n]=e.value}const en=i(`$ZodArray`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>$t(t,n,e))):$t(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function tn(e,t,n){e.issues.length&&t.issues.push(...S(n,e.issues)),t.value[n]=e.value}function nn(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...S(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const rn=i(`$ZodObject`,(e,t)=>{k.init(e,t);let n=u(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof k))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=ie(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});m(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new gt([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=g(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=g(e);t.write(`
|
|
6
|
-
if (${n}.issues.length) {
|
|
7
|
-
if (input[${r}] === undefined) {
|
|
8
|
-
if (${r} in input) {
|
|
9
|
-
newResult[${r}] = undefined;
|
|
10
|
-
}
|
|
11
|
-
} else {
|
|
12
|
-
payload.issues = payload.issues.concat(
|
|
13
|
-
${n}.issues.map((iss) => ({
|
|
14
|
-
...iss,
|
|
15
|
-
path: iss.path ? [${r}, ...iss.path] : [${r}],
|
|
16
|
-
}))
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
} else if (${n}.value === undefined) {
|
|
20
|
-
if (${r} in input) newResult[${r}] = undefined;
|
|
21
|
-
} else {
|
|
22
|
-
newResult[${r}] = ${n}.value;
|
|
23
|
-
}
|
|
24
|
-
`)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
25
|
-
if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
26
|
-
...iss,
|
|
27
|
-
path: iss.path ? [${g(e)}, ...iss.path] : [${g(e)}]
|
|
28
|
-
})));`),t.write(`newResult[${g(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=te,s=!o.jitless,c=s&&ne.value,l=t.catchall,d;e._zod.parse=(o,u)=>{d??=n.value;let f=o.value;if(!a(f))return o.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),o;let p=[];if(s&&c&&u?.async===!1&&u.jitless!==!0)i||=r(t.shape),o=i(o,u);else{o.value={};let e=d.shape;for(let t of d.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},u),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?nn(e,o,t,f):tn(e,o,t))):i?nn(r,o,t,f):tn(r,o,t)}}if(!l)return p.length?Promise.all(p).then(()=>o):o;let m=[],h=d.keySet,g=l._zod,ee=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(ee===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},u);t instanceof Promise?p.push(t.then(t=>tn(t,o,e))):tn(t,o,e)}return m.length&&o.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>o):o}});function an(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>w(e,r,s())))}),t}const on=i(`$ZodUnion`,(e,t)=>{k.init(e,t),m(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),m(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),m(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),m(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>f(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>an(t,n,e,r)):an(a,n,e,r)}}),sn=i(`$ZodIntersection`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>ln(e,t,n)):ln(e,i,a)}});function cn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(_(e)&&_(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=cn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=cn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ln(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),x(e))return e;let r=cn(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const un=i(`$ZodRecord`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!_(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...S(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...S(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let c=t.keyType._zod.run({value:o,issues:[]},r);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(c.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:c.issues.map(e=>w(e,r,s())),input:o,path:[o],inst:e}),n.value[c.value]=c.value;continue}let l=t.valueType._zod.run({value:i[o],issues:[]},r);l instanceof Promise?a.push(l.then(e=>{e.issues.length&&n.issues.push(...S(o,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...S(o,l.issues)),n.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>n):n}}),dn=i(`$ZodEnum`,(e,t)=>{k.init(e,t);let n=c(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>re.has(typeof e)).map(e=>typeof e==`string`?v(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),fn=i(`$ZodLiteral`,(e,t)=>{k.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?v(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),pn=i(`$ZodTransform`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new a;return e.value=r,e}}),mn=i(`$ZodOptional`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),m(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),hn=i(`$ZodNullable`,(e,t)=>{k.init(e,t),m(e._zod,`optin`,()=>t.innerType._zod.optin),m(e._zod,`optout`,()=>t.innerType._zod.optout),m(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)}|null)$`):void 0}),m(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),gn=i(`$ZodDefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>_n(e,t)):_n(r,t)}});function _n(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const vn=i(`$ZodPrefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yn=i(`$ZodNonOptional`,(e,t)=>{k.init(e,t),m(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>bn(t,e)):bn(i,e)}});function bn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const xn=i(`$ZodCatch`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,m(e._zod,`optout`,()=>t.innerType._zod.optout),m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>w(e,n,s()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>w(e,n,s()))},input:e.value}),e.issues=[]),e)}}),Sn=i(`$ZodPipe`,(e,t)=>{k.init(e,t),m(e._zod,`values`,()=>t.in._zod.values),m(e._zod,`optin`,()=>t.in._zod.optin),m(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Cn(e,t,n)):Cn(r,t,n)}});function Cn(e,t,n){return x(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const wn=i(`$ZodReadonly`,(e,t)=>{k.init(e,t),m(e._zod,`propValues`,()=>t.innerType._zod.propValues),m(e._zod,`values`,()=>t.innerType._zod.values),m(e._zod,`optin`,()=>t.innerType._zod.optin),m(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Tn):Tn(r)}});function Tn(e){return e.value=Object.freeze(e.value),e}const En=i(`$ZodLazy`,(e,t)=>{k.init(e,t),m(e._zod,`innerType`,()=>t.getter()),m(e._zod,`pattern`,()=>e._zod.innerType._zod.pattern),m(e._zod,`propValues`,()=>e._zod.innerType._zod.propValues),m(e._zod,`optin`,()=>e._zod.innerType._zod.optin),m(e._zod,`optout`,()=>e._zod.innerType._zod.optout),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Dn=i(`$ZodCustom`,(e,t)=>{D.init(e,t),k.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>On(t,n,r,e));On(i,n,r,e)}});function On(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(T(e))}}var kn=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function An(){return new kn}const j=An();function jn(e,t){return new e({type:`string`,...b(t)})}function Mn(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...b(t)})}function Nn(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...b(t)})}function Pn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...b(t)})}function Fn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...b(t)})}function In(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...b(t)})}function Ln(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...b(t)})}function Rn(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...b(t)})}function zn(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...b(t)})}function Bn(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...b(t)})}function Vn(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...b(t)})}function Hn(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...b(t)})}function Un(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...b(t)})}function Wn(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...b(t)})}function Gn(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...b(t)})}function Kn(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...b(t)})}function qn(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...b(t)})}function Jn(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...b(t)})}function Yn(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...b(t)})}function Xn(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...b(t)})}function Zn(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...b(t)})}function Qn(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...b(t)})}function $n(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...b(t)})}function er(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...b(t)})}function tr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...b(t)})}function nr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...b(t)})}function rr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...b(t)})}function ir(e,t){return new e({type:`number`,checks:[],...b(t)})}function ar(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...b(t)})}function or(e,t){return new e({type:`boolean`,...b(t)})}function sr(e,t){return new e({type:`boolean`,coerce:!0,...b(t)})}function cr(e){return new e({type:`any`})}function lr(e){return new e({type:`unknown`})}function ur(e,t){return new e({type:`never`,...b(t)})}function dr(e,t){return new e({type:`void`,...b(t)})}function fr(e,t){return new e({type:`date`,...b(t)})}function pr(e,t){return new nt({check:`less_than`,...b(t),value:e,inclusive:!1})}function M(e,t){return new nt({check:`less_than`,...b(t),value:e,inclusive:!0})}function mr(e,t){return new rt({check:`greater_than`,...b(t),value:e,inclusive:!1})}function N(e,t){return new rt({check:`greater_than`,...b(t),value:e,inclusive:!0})}function hr(e,t){return new it({check:`multiple_of`,...b(t),value:e})}function gr(e,t){return new ot({check:`max_length`,...b(t),maximum:e})}function P(e,t){return new st({check:`min_length`,...b(t),minimum:e})}function _r(e,t){return new ct({check:`length_equals`,...b(t),length:e})}function vr(e,t){return new lt({check:`string_format`,format:`regex`,...b(t),pattern:e})}function yr(e){return new ut({check:`string_format`,format:`lowercase`,...b(e)})}function br(e){return new dt({check:`string_format`,format:`uppercase`,...b(e)})}function xr(e,t){return new ft({check:`string_format`,format:`includes`,...b(t),includes:e})}function Sr(e,t){return new pt({check:`string_format`,format:`starts_with`,...b(t),prefix:e})}function Cr(e,t){return new mt({check:`string_format`,format:`ends_with`,...b(t),suffix:e})}function F(e){return new ht({check:`overwrite`,tx:e})}function wr(e){return F(t=>t.normalize(e))}function Tr(){return F(e=>e.trim())}function Er(){return F(e=>e.toLowerCase())}function Dr(){return F(e=>e.toUpperCase())}function Or(e,t,n){return new e({type:`array`,element:t,...b(n)})}function kr(e,t,n){let r=b(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Ar(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...b(n)})}const jr=i(`ZodISODateTime`,(e,t)=>{At.init(e,t),z.init(e,t)});function Mr(e){return er(jr,e)}const Nr=i(`ZodISODate`,(e,t)=>{jt.init(e,t),z.init(e,t)});function Pr(e){return tr(Nr,e)}const Fr=i(`ZodISOTime`,(e,t)=>{Mt.init(e,t),z.init(e,t)});function Ir(e){return nr(Fr,e)}const Lr=i(`ZodISODuration`,(e,t)=>{Nt.init(e,t),z.init(e,t)});function Rr(e){return rr(Lr,e)}const zr=(e,t)=>{E.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>ge(e,t)},flatten:{value:t=>he(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};i(`ZodError`,zr);const I=i(`ZodError`,zr,{Parent:Error}),Br=ye(I),Vr=be(I),Hr=xe(I),Ur=Ce(I),L=i(`ZodType`,(e,t)=>(k.init(e,t),e.def=t,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Br(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Hr(e,t,n),e.parseAsync=async(t,n)=>Vr(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ur(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(ea(t,n)),e.superRefine=t=>e.check(ta(t)),e.overwrite=t=>e.check(F(t)),e.optional=()=>Fi(e),e.nullable=()=>Y(e),e.nullish=()=>Fi(Y(e)),e.nonoptional=t=>Hi(e,t),e.array=()=>W(e),e.or=t=>K([e,t]),e.and=t=>Di(e,t),e.transform=t=>Ki(e,Ni(t)),e.default=t=>Ri(e,t),e.prefault=t=>Bi(e,t),e.catch=t=>Wi(e,t),e.pipe=t=>Ki(e,t),e.readonly=()=>Ji(e),e.describe=t=>{let n=e.clone();return j.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return j.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return j.get(e);let n=e.clone();return j.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Wr=i(`_ZodString`,(e,t)=>{vt.init(e,t),L.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(vr(...t)),e.includes=(...t)=>e.check(xr(...t)),e.startsWith=(...t)=>e.check(Sr(...t)),e.endsWith=(...t)=>e.check(Cr(...t)),e.min=(...t)=>e.check(P(...t)),e.max=(...t)=>e.check(gr(...t)),e.length=(...t)=>e.check(_r(...t)),e.nonempty=(...t)=>e.check(P(1,...t)),e.lowercase=t=>e.check(yr(t)),e.uppercase=t=>e.check(br(t)),e.trim=()=>e.check(Tr()),e.normalize=(...t)=>e.check(wr(...t)),e.toLowerCase=()=>e.check(Er()),e.toUpperCase=()=>e.check(Dr())}),Gr=i(`ZodString`,(e,t)=>{vt.init(e,t),Wr.init(e,t),e.email=t=>e.check(Mn(Kr,t)),e.url=t=>e.check(Rn(Jr,t)),e.jwt=t=>e.check($n(li,t)),e.emoji=t=>e.check(zn(Yr,t)),e.guid=t=>e.check(Nn(qr,t)),e.uuid=t=>e.check(Pn(B,t)),e.uuidv4=t=>e.check(Fn(B,t)),e.uuidv6=t=>e.check(In(B,t)),e.uuidv7=t=>e.check(Ln(B,t)),e.nanoid=t=>e.check(Bn(Xr,t)),e.guid=t=>e.check(Nn(qr,t)),e.cuid=t=>e.check(Vn(Zr,t)),e.cuid2=t=>e.check(Hn(Qr,t)),e.ulid=t=>e.check(Un($r,t)),e.base64=t=>e.check(Xn(oi,t)),e.base64url=t=>e.check(Zn(si,t)),e.xid=t=>e.check(Wn(ei,t)),e.ksuid=t=>e.check(Gn(ti,t)),e.ipv4=t=>e.check(Kn(ni,t)),e.ipv6=t=>e.check(qn(ri,t)),e.cidrv4=t=>e.check(Jn(ii,t)),e.cidrv6=t=>e.check(Yn(ai,t)),e.e164=t=>e.check(Qn(ci,t)),e.datetime=t=>e.check(Mr(t)),e.date=t=>e.check(Pr(t)),e.time=t=>e.check(Ir(t)),e.duration=t=>e.check(Rr(t))});function R(e){return jn(Gr,e)}const z=i(`ZodStringFormat`,(e,t)=>{A.init(e,t),Wr.init(e,t)}),Kr=i(`ZodEmail`,(e,t)=>{xt.init(e,t),z.init(e,t)}),qr=i(`ZodGUID`,(e,t)=>{yt.init(e,t),z.init(e,t)}),B=i(`ZodUUID`,(e,t)=>{bt.init(e,t),z.init(e,t)}),Jr=i(`ZodURL`,(e,t)=>{St.init(e,t),z.init(e,t)}),Yr=i(`ZodEmoji`,(e,t)=>{Ct.init(e,t),z.init(e,t)}),Xr=i(`ZodNanoID`,(e,t)=>{wt.init(e,t),z.init(e,t)}),Zr=i(`ZodCUID`,(e,t)=>{Tt.init(e,t),z.init(e,t)}),Qr=i(`ZodCUID2`,(e,t)=>{Et.init(e,t),z.init(e,t)}),$r=i(`ZodULID`,(e,t)=>{Dt.init(e,t),z.init(e,t)}),ei=i(`ZodXID`,(e,t)=>{Ot.init(e,t),z.init(e,t)}),ti=i(`ZodKSUID`,(e,t)=>{kt.init(e,t),z.init(e,t)}),ni=i(`ZodIPv4`,(e,t)=>{Pt.init(e,t),z.init(e,t)}),ri=i(`ZodIPv6`,(e,t)=>{Ft.init(e,t),z.init(e,t)}),ii=i(`ZodCIDRv4`,(e,t)=>{It.init(e,t),z.init(e,t)}),ai=i(`ZodCIDRv6`,(e,t)=>{Lt.init(e,t),z.init(e,t)}),oi=i(`ZodBase64`,(e,t)=>{zt.init(e,t),z.init(e,t)}),si=i(`ZodBase64URL`,(e,t)=>{Vt.init(e,t),z.init(e,t)}),ci=i(`ZodE164`,(e,t)=>{Ht.init(e,t),z.init(e,t)}),li=i(`ZodJWT`,(e,t)=>{Wt.init(e,t),z.init(e,t)}),ui=i(`ZodNumber`,(e,t)=>{Gt.init(e,t),L.init(e,t),e.gt=(t,n)=>e.check(mr(t,n)),e.gte=(t,n)=>e.check(N(t,n)),e.min=(t,n)=>e.check(N(t,n)),e.lt=(t,n)=>e.check(pr(t,n)),e.lte=(t,n)=>e.check(M(t,n)),e.max=(t,n)=>e.check(M(t,n)),e.int=t=>e.check(V(t)),e.safe=t=>e.check(V(t)),e.positive=t=>e.check(mr(0,t)),e.nonnegative=t=>e.check(N(0,t)),e.negative=t=>e.check(pr(0,t)),e.nonpositive=t=>e.check(M(0,t)),e.multipleOf=(t,n)=>e.check(hr(t,n)),e.step=(t,n)=>e.check(hr(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function di(e){return ir(ui,e)}const fi=i(`ZodNumberFormat`,(e,t)=>{Kt.init(e,t),ui.init(e,t)});function V(e){return ar(fi,e)}const pi=i(`ZodBoolean`,(e,t)=>{qt.init(e,t),L.init(e,t)});function mi(e){return or(pi,e)}const hi=i(`ZodAny`,(e,t)=>{Jt.init(e,t),L.init(e,t)});function H(){return cr(hi)}const gi=i(`ZodUnknown`,(e,t)=>{Yt.init(e,t),L.init(e,t)});function U(){return lr(gi)}const _i=i(`ZodNever`,(e,t)=>{Xt.init(e,t),L.init(e,t)});function vi(e){return ur(_i,e)}const yi=i(`ZodVoid`,(e,t)=>{Zt.init(e,t),L.init(e,t)});function bi(e){return dr(yi,e)}const xi=i(`ZodDate`,(e,t)=>{Qt.init(e,t),L.init(e,t),e.min=(t,n)=>e.check(N(t,n)),e.max=(t,n)=>e.check(M(t,n));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function Si(e){return fr(xi,e)}const Ci=i(`ZodArray`,(e,t)=>{en.init(e,t),L.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(P(t,n)),e.nonempty=t=>e.check(P(1,t)),e.max=(t,n)=>e.check(gr(t,n)),e.length=(t,n)=>e.check(_r(t,n)),e.unwrap=()=>e.element});function W(e,t){return Or(Ci,e,t)}const wi=i(`ZodObject`,(e,t)=>{rn.init(e,t),L.init(e,t),m(e,`shape`,()=>t.shape),e.keyof=()=>Ai(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:U()}),e.loose=()=>e.clone({...e._zod.def,catchall:U()}),e.strict=()=>e.clone({...e._zod.def,catchall:vi()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>ce(e,t),e.merge=t=>le(e,t),e.pick=t=>oe(e,t),e.omit=t=>se(e,t),e.partial=(...t)=>ue(Pi,e,t[0]),e.required=(...t)=>de(Vi,e,t[0])});function G(e,t){return new wi({type:`object`,get shape(){return h(this,`shape`,{...e}),this.shape},...b(t)})}const Ti=i(`ZodUnion`,(e,t)=>{on.init(e,t),L.init(e,t),e.options=t.options});function K(e,t){return new Ti({type:`union`,options:e,...b(t)})}const Ei=i(`ZodIntersection`,(e,t)=>{sn.init(e,t),L.init(e,t)});function Di(e,t){return new Ei({type:`intersection`,left:e,right:t})}const Oi=i(`ZodRecord`,(e,t)=>{un.init(e,t),L.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function q(e,t,n){return new Oi({type:`record`,keyType:e,valueType:t,...b(n)})}const ki=i(`ZodEnum`,(e,t)=>{dn.init(e,t),L.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ki({...t,checks:[],...b(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ki({...t,checks:[],...b(r),entries:i})}});function Ai(e,t){return new ki({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...b(t)})}const ji=i(`ZodLiteral`,(e,t)=>{fn.init(e,t),L.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function J(e,t){return new ji({type:`literal`,values:Array.isArray(e)?e:[e],...b(t)})}const Mi=i(`ZodTransform`,(e,t)=>{pn.init(e,t),L.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(T(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(T(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ni(e){return new Mi({type:`transform`,transform:e})}const Pi=i(`ZodOptional`,(e,t)=>{mn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Fi(e){return new Pi({type:`optional`,innerType:e})}const Ii=i(`ZodNullable`,(e,t)=>{hn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Y(e){return new Ii({type:`nullable`,innerType:e})}const Li=i(`ZodDefault`,(e,t)=>{gn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ri(e,t){return new Li({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const zi=i(`ZodPrefault`,(e,t)=>{vn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Bi(e,t){return new zi({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const Vi=i(`ZodNonOptional`,(e,t)=>{yn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Hi(e,t){return new Vi({type:`nonoptional`,innerType:e,...b(t)})}const Ui=i(`ZodCatch`,(e,t)=>{xn.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wi(e,t){return new Ui({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const Gi=i(`ZodPipe`,(e,t)=>{Sn.init(e,t),L.init(e,t),e.in=t.in,e.out=t.out});function Ki(e,t){return new Gi({type:`pipe`,in:e,out:t})}const qi=i(`ZodReadonly`,(e,t)=>{wn.init(e,t),L.init(e,t)});function Ji(e){return new qi({type:`readonly`,innerType:e})}const Yi=i(`ZodLazy`,(e,t)=>{En.init(e,t),L.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Xi(e){return new Yi({type:`lazy`,getter:e})}const Zi=i(`ZodCustom`,(e,t)=>{Dn.init(e,t),L.init(e,t)});function Qi(e){let t=new D({check:`custom`});return t._zod.check=e,t}function $i(e,t){return kr(Zi,e??(()=>!0),t)}function ea(e,t={}){return Ar(Zi,e,t)}function ta(e){let t=Qi(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(T(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(T(r))}},e(n.value,n)));return t}var na=class extends Error{rawValue;rawMessage;static[Symbol.hasInstance](e){return!(!(e instanceof Error)||!(`rawValue`in e)||!(`rawMessage`in e)||!(`pretty`in e)||typeof e.pretty!=`function`)}constructor(e,t,n){super(`${e}: ${t}`),this.name=`SDKValidationError`,this.cause=t,this.rawValue=n,this.rawMessage=e}pretty(){return this.cause instanceof E?`${this.rawMessage}\n${ra(this.cause)}`:this.toString()}};function ra(e){return ve(e)}function X(e,t){let n={};if(!Object.keys(t).length)return n=e,n;for(let[r,i]of Object.entries(e)){let e=t[r];e!==null&&(n[e??r]=i)}return n}function ia(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function aa(n,r,i){try{return e(r(n))}catch(e){return t(new na(i,e,n))}}function oa(e){return Z++,e}let Z=0,sa=0;function ca(){sa++;let e=Z;return{end:t=>{let n=Z-e;return Z=e+(t??n),--sa===0&&(Z=0),n}}}function Q(e){return K([...Object.values(e).map(e=>J(e)),R().transform(e=>oa(e))])}function la(e){return K([...Object.values(e).filter(e=>typeof e==`number`).map(e=>J(e)),V().transform(e=>oa(e))])}function ua(e){return R()}function da(e){return V()}const fa=Symbol(`UNKNOWN`);function pa(e){return typeof e==`object`&&!!e&&fa in e}function ma(e,t,n={}){let{unknownValue:r=`UNKNOWN`,outputPropertyName:i}=n;return U().transform(n=>{let a=Object.defineProperties({raw:n,[i??e]:r,isUnknown:!0},{[fa]:{value:!0,enumerable:!1,configurable:!1}});if(!(typeof n==`object`&&n))return a;let o=n[e];if(typeof o!=`string`||!(o in t))return a;let s=t[o];if(!s)return a;let c=ca(),l=s.safeParse(n);return l.success?(c.end(),i&&(l.data[i]=o),l.data):(c.end(0),a)})}const ha=/^\d{4}-\d{2}-\d{2}$/;var ga=class e{serialized;static today(){return new e(new Date)}constructor(e){if(typeof e==`string`&&!ha.test(e))throw RangeError(`RFCDate: date strings must be in the format YYYY-MM-DD: `+e);let t=new Date(e);if(isNaN(+t))throw RangeError(`RFCDate: invalid date provided: `+e);if(this.serialized=t.toISOString().slice(0,10),!ha.test(this.serialized))throw TypeError(`RFCDate: failed to build valid date with given value: ${e} serialized to ${this.serialized}`)}toJSON(){return this.toString()}toString(){return this.serialized}};function $(e){return U().transform((t,n)=>{let i=[],a=e.map(()=>[]),o=ca();for(let[n,r]of e.entries()){let e=ca(),o=r.safeParse(t),s=e.end();if(o.success){i.push({data:o.data,inexactCount:s,zeroDefaultCount:0,fieldCount:-1});continue}a[n].push(...o.error.issues)}if(i.length===0)return o.end(0),n.addIssue({input:t,code:`invalid_union`,errors:a}),r;let s=i[0];for(let e of i)i.length>1&&(e.fieldCount=va(e.data)),s=_a(e,s);return o.end(s.inexactCount),s.data})}function _a(e,t){let n=e.inexactCount===0;if(n!==(t.inexactCount===0))return n?e:t;let r=e.fieldCount-e.zeroDefaultCount,i=t.fieldCount-t.zeroDefaultCount;return r===i?e.inexactCount<t.inexactCount?e:t:r>i?e:t}function va(e){let t=0,n=[e],r=0;for(;r<n.length;){let e=n[r++];if(e===void 0||pa(e))continue;let i=typeof e;if(e===null||i===`number`||i===`string`||i===`boolean`||i===`bigint`||e instanceof Date||e instanceof ga){t++;continue}if(Array.isArray(e)){n.push(...e);continue}i===`object`&&n.push(...Object.values(e))}return t}const ya=G({type:J(`input_audio`),input_audio:R()}).transform(e=>X(e,{input_audio:`inputAudio`})),ba=G({type:J(`input_audio`),inputAudio:R()}).transform(e=>X(e,{inputAudio:`input_audio`})),xa=G({type:J(`document_url`).default(`document_url`),document_url:R(),document_name:Y(R()).optional()}).transform(e=>X(e,{document_url:`documentUrl`,document_name:`documentName`})),Sa=G({type:J(`document_url`).default(`document_url`),documentUrl:R(),documentName:Y(R()).optional()}).transform(e=>X(e,{documentUrl:`document_url`,documentName:`document_name`})),Ca=G({type:J(`file`).default(`file`),file_id:R()}).transform(e=>X(e,{file_id:`fileId`})),wa=G({type:J(`file`).default(`file`),fileId:R()}).transform(e=>X(e,{fileId:`file_id`})),Ta={Low:`low`,Auto:`auto`,High:`high`},Ea=Q(Ta),Da=ua(Ta),Oa=G({url:R(),detail:Y(Ea).optional()}),ka=G({url:R(),detail:Y(Da).optional()});$([Oa,R()]),$([ka,R()]);const Aa=G({type:J(`image_url`).default(`image_url`),image_url:$([Oa,R()])}).transform(e=>X(e,{image_url:`imageUrl`})),ja=G({type:J(`image_url`).default(`image_url`),imageUrl:$([ka,R()])}).transform(e=>X(e,{imageUrl:`image_url`}));$([V(),R()]),$([V(),R()]);const Ma=G({type:J(`reference`).default(`reference`),reference_ids:W($([V(),R()]))}).transform(e=>X(e,{reference_ids:`referenceIds`})),Na=G({type:J(`reference`).default(`reference`),referenceIds:W($([V(),R()]))}).transform(e=>X(e,{referenceIds:`reference_ids`})),Pa=G({type:J(`text`).default(`text`),text:R()}),Fa=G({type:J(`text`).default(`text`),text:R()}),Ia={WebSearch:`web_search`,WebSearchPremium:`web_search_premium`,CodeInterpreter:`code_interpreter`,ImageGeneration:`image_generation`,DocumentLibrary:`document_library`},La=Q(Ia),Ra=ua(Ia);$([La,R()]),$([Ra,R()]);const za=G({type:J(`tool_reference`).default(`tool_reference`),tool:$([La,R()]),title:R(),url:Y(R()).optional(),favicon:Y(R()).optional(),description:Y(R()).optional()}),Ba=G({type:J(`tool_reference`).default(`tool_reference`),tool:$([Ra,R()]),title:R(),url:Y(R()).optional(),favicon:Y(R()).optional(),description:Y(R()).optional()});$([za,Pa,Ma]),$([Ba,Fa,Na]);const Va=G({type:J(`thinking`).default(`thinking`),thinking:W($([za,Pa,Ma])),signature:Y(R()).optional(),closed:mi().optional()}),Ha=G({type:J(`thinking`).default(`thinking`),thinking:W($([Ba,Fa,Na])),signature:Y(R()).optional(),closed:mi().optional()}),Ua=ma(`type`,{image_url:Aa.and(G({type:J(`image_url`)})),document_url:xa.and(G({type:J(`document_url`)})),text:Pa.and(G({type:J(`text`)})),reference:Ma.and(G({type:J(`reference`)})),file:Ca.and(G({type:J(`file`)})),thinking:Va.and(G({type:J(`thinking`)})),input_audio:ya}),Wa=K([ja.and(G({type:J(`image_url`)})),Sa.and(G({type:J(`document_url`)})),Fa.and(G({type:J(`text`)})),Na.and(G({type:J(`reference`)})),wa.and(G({type:J(`file`)})),Ha.and(G({type:J(`thinking`)})),ba]);$([q(R(),H()),R()]),$([q(R(),H()),R()]);const Ga=G({name:R(),arguments:$([q(R(),H()),R()])}),Ka=G({name:R(),arguments:$([q(R(),H()),R()])}),qa=G({id:R().default(`null`),type:R().optional(),function:Ga,index:V().default(0)}),Ja=G({id:R().default(`null`),type:R().optional(),function:Ka,index:V().default(0)});$([R(),W(Ua)]);const Ya=G({role:Y(R()).optional(),content:Y($([R(),W(Ua)])).optional(),tool_calls:Y(W(qa)).optional(),tool_call_id:Y(R()).optional(),index:Y(V()).optional(),metadata:Y(q(R(),H())).optional()}).transform(e=>X(e,{tool_calls:`toolCalls`,tool_call_id:`toolCallId`})),Xa=G({prompt_tokens:V().default(0),completion_tokens:V().default(0),total_tokens:V().default(0),prompt_audio_seconds:Y(V()).optional()}).catchall(H()).transform(e=>X(e,{prompt_tokens:`promptTokens`,completion_tokens:`completionTokens`,total_tokens:`totalTokens`,prompt_audio_seconds:`promptAudioSeconds`})),Za=G({promptTokens:V().default(0),completionTokens:V().default(0),totalTokens:V().default(0),promptAudioSeconds:Y(V()).optional()}).catchall(H()).transform(e=>({...X(e,{promptTokens:`prompt_tokens`,completionTokens:`completion_tokens`,totalTokens:`total_tokens`,promptAudioSeconds:`prompt_audio_seconds`})})),Qa=Q({Stop:`stop`,Length:`length`,Error:`error`,ToolCalls:`tool_calls`}),$a=G({index:V(),delta:Ya,finish_reason:Y(Qa)}).transform(e=>X(e,{finish_reason:`finishReason`})),eo=G({id:R(),object:R().optional(),created:V().optional(),model:R(),usage:Xa.optional(),choices:W($a)});function to(e){return aa(e,e=>eo.parse(JSON.parse(e)),`Failed to parse 'CompletionChunk' from JSON`)}export{j as $,ia as A,Si as B,$ as C,ua as D,la as E,bi as F,di as G,Xi as H,H as I,R as J,G as K,W as L,ra as M,pi as N,da as O,Ai as P,kn as Q,mi as R,Sa as S,Q as T,J as U,V,Y as W,Mr as X,K as Y,sr as Z,Fa as _,Ya as a,n as at,wa as b,Ua as c,Ha as d,E as et,za as f,Pa as g,Ra as h,Za as i,e as it,X as j,aa as k,Wa as l,La as m,to as n,r as nt,qa as o,Ba as p,q,Xa as r,t as rt,Ja as s,eo as t,c as tt,Va as u,Aa as v,ma as w,xa as x,ja as y,$i as z};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t,t as n}from"./models-CwK5xZH9.mjs";import{n as r}from"./headers-BvGum5dc.mjs";import{t as i}from"./sanitize-unicode-CHjuq5rK.mjs";import{r as a}from"./transform-messages-CSBQpmXO.mjs";import{n as o,t as s}from"./error-body-D2Mrqb4g.mjs";import{a as c,c as l,i as u,n as d,o as f,r as p,s as m,t as h}from"./google-shared-CetPT_Vt.mjs";let g=0;const _=(t,r,i)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:`google-generative-ai`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{if(i?.fetch&&i.fetch!==globalThis.fetch)throw Error(`Custom fetch is not supported by the Google Generative AI adapter`);let o=i?.apiKey;if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=y(t,o,i?.headers),c=b(t,r,i),l=await i?.onPayload?.(c,t);l!==void 0&&(c=l);let d=await s.models.generateContentStream(c);a.push({type:`start`,partial:e});let m=null,h=e.content,_=()=>h.length-1;for await(let r of d){e.responseId||=r.responseId;let i=r.candidates?.[0];if(i?.content?.parts)for(let t of i.content.parts){if(t.text!==void 0){let n=p(t);(!m||n&&m.type!==`thinking`||!n&&m.type!==`text`)&&(m&&(m.type===`text`?a.push({type:`text_end`,contentIndex:h.length-1,content:m.text,partial:e}):a.push({type:`thinking_end`,contentIndex:_(),content:m.thinking,partial:e})),n?(m={type:`thinking`,thinking:``,thinkingSignature:void 0},e.content.push(m),a.push({type:`thinking_start`,contentIndex:_(),partial:e})):(m={type:`text`,text:``},e.content.push(m),a.push({type:`text_start`,contentIndex:_(),partial:e}))),m.type===`thinking`?(m.thinking+=t.text,m.thinkingSignature=f(m.thinkingSignature,t.thoughtSignature),a.push({type:`thinking_delta`,contentIndex:_(),delta:t.text,partial:e})):(m.text+=t.text,m.textSignature=f(m.textSignature,t.thoughtSignature),a.push({type:`text_delta`,contentIndex:_(),delta:t.text,partial:e}))}if(t.functionCall){m&&=(m.type===`text`?a.push({type:`text_end`,contentIndex:_(),content:m.text,partial:e}):a.push({type:`thinking_end`,contentIndex:_(),content:m.thinking,partial:e}),null);let n=t.functionCall.id,r={type:`toolCall`,id:!n||e.content.some(e=>e.type===`toolCall`&&e.id===n)?`${t.functionCall.name}_${Date.now()}_${++g}`:n,name:t.functionCall.name||``,arguments:t.functionCall.args??{},...t.thoughtSignature&&{thoughtSignature:t.thoughtSignature}};e.content.push(r),a.push({type:`toolcall_start`,contentIndex:_(),partial:e}),a.push({type:`toolcall_delta`,contentIndex:_(),delta:JSON.stringify(r.arguments),partial:e}),a.push({type:`toolcall_end`,contentIndex:_(),toolCall:r,partial:e})}}i?.finishReason&&(e.rawStopReason=i.finishReason,e.stopReason=u(i.finishReason),e.content.some(e=>e.type===`toolCall`)&&(e.stopReason=`toolUse`)),r.usageMetadata&&(e.usage={input:(r.usageMetadata.promptTokenCount||0)-(r.usageMetadata.cachedContentTokenCount||0),output:(r.usageMetadata.candidatesTokenCount||0)+(r.usageMetadata.thoughtsTokenCount||0),cacheRead:r.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:r.usageMetadata.thoughtsTokenCount||0,totalTokens:r.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},n(t,e.usage))}if(m&&(m.type===`text`?a.push({type:`text_end`,contentIndex:_(),content:m.text,partial:e}):a.push({type:`thinking_end`,contentIndex:_(),content:m.thinking,partial:e})),i?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`Google stream ended without a finish reason`);if(e.stopReason===`aborted`||e.stopReason===`error`){let t=e.rawStopReason?`Provider stopped with: ${e.rawStopReason}`:`An unknown error occurred`;throw Error(t)}a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)`index`in t&&delete t.index;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=s(o(t)),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},v=(e,n,r)=>{let i=r?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let o=a(e,n,r,i);if(!r?.reasoning)return _(e,n,{...o,thinking:{enabled:!1}});let s=t(e,r.reasoning),c=s===`off`?`high`:s,l=e;return S(l)||C(l)||x(l)?_(e,n,{...o,thinking:{enabled:!0,level:T(c,l)}}):_(e,n,{...o,thinking:{enabled:!0,budgetTokens:E(l,c,r.thinkingBudgets)}})};function y(e,t,n){let i={};e.baseUrl&&(i.baseUrl=e.baseUrl,i.apiVersion=``);let a=r({...e.headers,...n});return a&&(i.headers=a),new l({apiKey:t,httpOptions:Object.keys(i).length>0?i:void 0})}function b(e,t,n={}){let r=h(e,t),a={};n.temperature!==void 0&&(a.temperature=n.temperature),n.maxTokens!==void 0&&(a.maxOutputTokens=n.maxTokens);let o=t.tools?.length?c(t.tools,n.toolChoice,m(e.id)):void 0,s={...Object.keys(a).length>0&&a,...t.systemPrompt&&{systemInstruction:i(t.systemPrompt)},...t.tools&&t.tools.length>0&&{tools:d(t.tools)},...o!==void 0&&{toolConfig:{functionCallingConfig:{mode:o}}}};if(n.thinking?.enabled&&e.reasoning){let e={includeThoughts:!0};n.thinking.level===void 0?n.thinking.budgetTokens!==void 0&&(e.thinkingBudget=n.thinking.budgetTokens):e.thinkingLevel=n.thinking.level,s.thinkingConfig=e}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(s.thinkingConfig=w(e));if(n.signal){if(n.signal.aborted)throw Error(`Request aborted`);s.abortSignal=n.signal}return{model:e.id,contents:r,config:s}}function x(e){return/gemma-?4/.test(e.id.toLowerCase())}function S(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function C(e){let t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(t)||t===`gemini-flash-latest`||t===`gemini-flash-lite-latest`}function w(e){return S(e)?{thinkingLevel:`LOW`}:C(e)||x(e)?{thinkingLevel:`MINIMAL`}:{thinkingBudget:0}}function T(e,t){if(S(t))switch(e){case`minimal`:case`low`:return`LOW`;case`medium`:case`high`:return`HIGH`}if(x(t))switch(e){case`minimal`:case`low`:return`MINIMAL`;case`medium`:case`high`:return`HIGH`}switch(e){case`minimal`:return`MINIMAL`;case`low`:return`LOW`;case`medium`:return`MEDIUM`;case`high`:return`HIGH`}}function E(e,t,n){return n?.[t]===void 0?e.id.includes(`2.5-pro`)?{minimal:128,low:2048,medium:8192,high:32768}[t]:e.id.includes(`2.5-flash-lite`)?{minimal:512,low:2048,medium:8192,high:24576}[t]:e.id.includes(`2.5-flash`)?{minimal:128,low:2048,medium:8192,high:24576}[t]:-1:n[t]}export{_ as stream,v as streamSimple};
|