pulls.review 0.1.0 → 0.2.1
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 +16 -0
- package/bin.mjs +2 -0
- package/dist/client/assets/ChatWidget-BsnoQ6oS.js +1 -0
- package/dist/client/assets/DisplayFileIcon-DzBo3Ez5.js +151 -0
- package/dist/client/assets/GithubAvatar-CSsUV5vf.js +1 -0
- package/dist/client/assets/LandingHero-BkTBSu71.js +1 -0
- package/dist/client/assets/_repo_-Dcgj3PGg.js +22 -0
- package/dist/client/assets/analyze-509KQQBC.js +1 -0
- package/dist/client/assets/andromeeda-vGVdxbeo.js +1 -0
- package/dist/client/assets/anthropic-messages-Cd2DkgOC.js +41 -0
- package/dist/client/assets/aurora-x-CDeNXAV0.js +1 -0
- package/dist/client/assets/ayu-dark-DluEY0Gj.js +1 -0
- package/dist/client/assets/ayu-light-C3h-C4tm.js +1 -0
- package/dist/client/assets/ayu-mirage-Bqwy1Gya.js +1 -0
- package/dist/client/assets/browser-agent-rpc-BXhoSh1z-DrxWeI3_.js +1 -0
- package/dist/client/assets/c-BNQJhXlP.js +1 -0
- package/dist/client/assets/catppuccin-frappe-C9Q5zVZY.js +1 -0
- package/dist/client/assets/catppuccin-latte-CtsyrtPq.js +1 -0
- package/dist/client/assets/catppuccin-macchiato-R8nAf1vR.js +1 -0
- package/dist/client/assets/catppuccin-mocha-DjuaAJKi.js +1 -0
- package/dist/client/assets/clojure-DqKBuwfJ.js +1 -0
- package/dist/client/assets/cpp-7GgD5o7L.js +1 -0
- package/dist/client/assets/csharp-oqKa8noW.js +1 -0
- package/dist/client/assets/css-DlBQoFxe.js +1 -0
- package/dist/client/assets/dark-plus-Cs2F2srj.js +1 -0
- package/dist/client/assets/de-Bq9RfdAn.js +1 -0
- package/dist/client/assets/diff-BKQFn0my.js +37 -0
- package/dist/client/assets/diff-Bx6SazPw.js +1 -0
- package/dist/client/assets/diff-woXpYk--.js +1 -0
- package/dist/client/assets/diffs-store-ncE62OUU.js +1510 -0
- package/dist/client/assets/dist-Dh0a8u-Y.js +1 -0
- package/dist/client/assets/docker-IyjqRm3v.js +1 -0
- package/dist/client/assets/dracula-BHWKrbxM.js +1 -0
- package/dist/client/assets/dracula-soft-5eyTD99u.js +1 -0
- package/dist/client/assets/elixir-D3n0XgqJ.js +1 -0
- package/dist/client/assets/en-8hQdak1X.js +1 -0
- package/dist/client/assets/error-CJ3RHG07.js +1 -0
- package/dist/client/assets/es-QcvEBShr.js +1 -0
- package/dist/client/assets/everforest-dark-sB-x3p7T.js +1 -0
- package/dist/client/assets/everforest-light-Df2xbC6M.js +1 -0
- package/dist/client/assets/fr-DAWKVvDP.js +1 -0
- package/dist/client/assets/github-dark-C-LZuMrd.js +1 -0
- package/dist/client/assets/github-dark-default-DXG-b-1a.js +1 -0
- package/dist/client/assets/github-dark-dimmed-Bx1FflLF.js +1 -0
- package/dist/client/assets/github-dark-high-contrast-B_tTalzw.js +1 -0
- package/dist/client/assets/github-light-EUqPIrTm.js +1 -0
- package/dist/client/assets/github-light-default-BXViO-2h.js +1 -0
- package/dist/client/assets/github-light-high-contrast-B68TUdTA.js +1 -0
- package/dist/client/assets/go-rLFTqkRN.js +1 -0
- package/dist/client/assets/graphql-ki1Ij_uk.js +1 -0
- package/dist/client/assets/groovy-CacY0gHj.js +1 -0
- package/dist/client/assets/gruvbox-dark-hard-C820rvS2.js +1 -0
- package/dist/client/assets/gruvbox-dark-medium-BPjhmG05.js +1 -0
- package/dist/client/assets/gruvbox-dark-soft-MrdJrrXF.js +1 -0
- package/dist/client/assets/gruvbox-light-hard-BC_s9l72.js +1 -0
- package/dist/client/assets/gruvbox-light-medium-BAWPOn9u.js +1 -0
- package/dist/client/assets/gruvbox-light-soft-BSMLrYjP.js +1 -0
- package/dist/client/assets/haskell-D8IpX4py.js +1 -0
- package/dist/client/assets/horizon-CE9ld1lL.js +1 -0
- package/dist/client/assets/horizon-bright-DSNQnXHK.js +1 -0
- package/dist/client/assets/houston-CsvMBhTu.js +1 -0
- package/dist/client/assets/html-BC8aFsRK.js +1 -0
- package/dist/client/assets/i18n-CGV_MDS8.js +2 -0
- package/dist/client/assets/id-NIGs9Xhn.js +1 -0
- package/dist/client/assets/index-BCCy9wJJ.js +2 -0
- package/dist/client/assets/index-BDPZiDIt.css +1 -0
- package/dist/client/assets/ini-B5eOa1yu.js +1 -0
- package/dist/client/assets/install-B-q5w2uE.js +4 -0
- package/dist/client/assets/it-DjRuurmk.js +1 -0
- package/dist/client/assets/ja-BAKkDsQ5.js +1 -0
- package/dist/client/assets/java-D7h0NA_A.js +1 -0
- package/dist/client/assets/javascript-DcMHgNcu.js +1 -0
- package/dist/client/assets/json-qhed-kSA.js +1 -0
- package/dist/client/assets/jsonc-CYpm1nAK.js +1 -0
- package/dist/client/assets/jsx-BUUYi3qs.js +1 -0
- package/dist/client/assets/kanagawa-dragon-Bozd7klA.js +1 -0
- package/dist/client/assets/kanagawa-lotus-BmuOG9ZW.js +1 -0
- package/dist/client/assets/kanagawa-wave-BML5mF2J.js +1 -0
- package/dist/client/assets/ko-DHculY2W.js +1 -0
- package/dist/client/assets/kotlin-DhhofPvG.js +1 -0
- package/dist/client/assets/laserwave-C_8bwKvT.js +1 -0
- package/dist/client/assets/less-DVTAwKKz.js +1 -0
- package/dist/client/assets/light-plus-DVQuIRkW.js +1 -0
- package/dist/client/assets/llm-DYDmh8Ki.js +2 -0
- package/dist/client/assets/llm-store-CVM33nlB.js +2 -0
- package/dist/client/assets/locales-SpkpwNqX.js +1 -0
- package/dist/client/assets/lua-DCW0Dwo5.js +1 -0
- package/dist/client/assets/make-Dixweg8N.js +1 -0
- package/dist/client/assets/markdown-BYOwaDjH.js +1 -0
- package/dist/client/assets/material-theme-Bm3Qr25_.js +1 -0
- package/dist/client/assets/material-theme-darker-2IIEA8gg.js +1 -0
- package/dist/client/assets/material-theme-lighter-uhdI0v04.js +1 -0
- package/dist/client/assets/material-theme-ocean-CHQ94UKr.js +1 -0
- package/dist/client/assets/material-theme-palenight-B5W6OYN7.js +1 -0
- package/dist/client/assets/mdx-DQZ5AkYe.js +1 -0
- package/dist/client/assets/min-dark-BSWPekZh.js +1 -0
- package/dist/client/assets/min-light-DDpmG2fV.js +1 -0
- package/dist/client/assets/monokai-B_bV9PQ9.js +1 -0
- package/dist/client/assets/nginx-C4fSytnP.js +1 -0
- package/dist/client/assets/night-owl-DhmEMT88.js +1 -0
- package/dist/client/assets/night-owl-light-eJ-hLW7d.js +1 -0
- package/dist/client/assets/node.browser-BX-QLlU2.js +1 -0
- package/dist/client/assets/node.browser-DFtqp6Hr.js +1 -0
- package/dist/client/assets/nord-Cb4Vim4T.js +1 -0
- package/dist/client/assets/objective-c-D1A_Heim.js +1 -0
- package/dist/client/assets/objective-cpp-BsSzOQcm.js +1 -0
- package/dist/client/assets/one-dark-pro-CLwyXe_n.js +1 -0
- package/dist/client/assets/one-light-D7Lr4KcI.js +1 -0
- package/dist/client/assets/openai-completions-CSvY9IVo.js +21 -0
- package/dist/client/assets/pages-B5mEqsbn.js +1 -0
- package/dist/client/assets/pages-local-x_ACBinc.js +1 -0
- package/dist/client/assets/pages-web-DitAPN6U.js +21 -0
- package/dist/client/assets/patch-parser-k3Vbbmi0.js +5 -0
- package/dist/client/assets/perl-C8GHouAq.js +1 -0
- package/dist/client/assets/php-BahmaYs0.js +1 -0
- package/dist/client/assets/pierre-dark-CpLgRqie.js +1 -0
- package/dist/client/assets/pierre-dark-protanopia-deuteranopia-B35FxJx-.js +1 -0
- package/dist/client/assets/pierre-dark-soft-kZQmAZld.js +1 -0
- package/dist/client/assets/pierre-dark-tritanopia-CpjhbsIL.js +1 -0
- package/dist/client/assets/pierre-dark-vibrant-CpQYzh95.js +1 -0
- package/dist/client/assets/pierre-light-CoaEpmwp.js +1 -0
- package/dist/client/assets/pierre-light-protanopia-deuteranopia-0fSaH845.js +1 -0
- package/dist/client/assets/pierre-light-soft-lWLdNTOI.js +1 -0
- package/dist/client/assets/pierre-light-tritanopia-CEbqgOJL.js +1 -0
- package/dist/client/assets/pierre-light-vibrant-D80Fkn33.js +1 -0
- package/dist/client/assets/plastic-DQwYfKfQ.js +1 -0
- package/dist/client/assets/poimandres-DRFjx7u4.js +1 -0
- package/dist/client/assets/portalTarget-C60SzJiK.js +1 -0
- package/dist/client/assets/preload-helper-BaNbYf_w.js +1 -0
- package/dist/client/assets/proto-DB4EqR-F.js +1 -0
- package/dist/client/assets/pt-BR-LLtJ99P6.js +1 -0
- package/dist/client/assets/python-gzcpVVnB.js +1 -0
- package/dist/client/assets/r-C5FwQflr.js +1 -0
- package/dist/client/assets/red-DX1BQOs8.js +1 -0
- package/dist/client/assets/rolldown-runtime-Dd_uD5pT.js +1 -0
- package/dist/client/assets/rose-pine-aMsaMD1D.js +1 -0
- package/dist/client/assets/rose-pine-dawn-8PwUyIlP.js +1 -0
- package/dist/client/assets/rose-pine-moon-DO-qXg-I.js +1 -0
- package/dist/client/assets/ru-DvkrOLxc.js +1 -0
- package/dist/client/assets/ruby-CfFGiaYl.js +1 -0
- package/dist/client/assets/runtime-dom.esm-bundler-CqL7__VR.js +2 -0
- package/dist/client/assets/rust-Cfkwpbl8.js +1 -0
- package/dist/client/assets/scala-BiFt_7mu.js +1 -0
- package/dist/client/assets/scss-C-_0yqZd.js +1 -0
- package/dist/client/assets/shellscript-CLZ0U2zV.js +1 -0
- package/dist/client/assets/shiki-wasm-noop-Gxv9UHE7.js +1 -0
- package/dist/client/assets/slack-dark-DnToyrRv.js +1 -0
- package/dist/client/assets/slack-ochin-B2OO5cIa.js +1 -0
- package/dist/client/assets/snazzy-light-4G7pJPwS.js +1 -0
- package/dist/client/assets/solarized-dark-UdsmMDCL.js +1 -0
- package/dist/client/assets/solarized-light-C1IUL_tW.js +1 -0
- package/dist/client/assets/source-hSji-yvG.js +2 -0
- package/dist/client/assets/sql-BsFa4tDR.js +1 -0
- package/dist/client/assets/swift-CyEgAFGc.js +1 -0
- package/dist/client/assets/synthwave-84-nFMaYfgc.js +1 -0
- package/dist/client/assets/terraform-DswuEJGm.js +1 -0
- package/dist/client/assets/time-ago-Bdao9Hh1.js +1 -0
- package/dist/client/assets/tokyo-night-oM2G3aXe.js +1 -0
- package/dist/client/assets/toml-CcmNWLt0.js +1 -0
- package/dist/client/assets/transform-messages-C8U1xonk.js +3 -0
- package/dist/client/assets/tsx-DvWhG4dC.js +1 -0
- package/dist/client/assets/typescript-BTGs5etX.js +1 -0
- package/dist/client/assets/upload-GnI9kmJu.js +1 -0
- package/dist/client/assets/uploadSession-BUj4FNau.js +1 -0
- package/dist/client/assets/useDocumentTitle-nuqxXiNo.js +185 -0
- package/dist/client/assets/vesper-DdrHHSXu.js +1 -0
- package/dist/client/assets/vitesse-black-fwtXNY1n.js +1 -0
- package/dist/client/assets/vitesse-dark-BZCL-v6S.js +1 -0
- package/dist/client/assets/vitesse-light-VbXTXTou.js +1 -0
- package/dist/client/assets/vue-BbYmdtmv.js +1 -0
- package/dist/client/assets/vue-html-BXjKVtKk.js +1 -0
- package/dist/client/assets/vue-i18n-DVI_S4Q5.js +5 -0
- package/dist/client/assets/xml-BsprbK0m.js +1 -0
- package/dist/client/assets/yaml-rwi0_p6S.js +1 -0
- package/dist/client/assets/zh-CN-BIibd6kG.js +1 -0
- package/dist/client/assets/zh-TW-3FtUHjoZ.js +1 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +44 -0
- package/dist/client/og-dark.png +0 -0
- package/dist/client/og.png +0 -0
- package/dist/client/robots.txt +2 -0
- package/dist/devframe-CX5butdC.mjs +493 -0
- package/dist/devframe.mjs +2 -0
- package/dist/index.mjs +59 -118
- package/package.json +17 -9
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{Kt as e,Qt as t,Ut as n,Wt as r,Xt as i,Yt as a,Zt as o,en as s}from"./useDocumentTitle-nuqxXiNo.js";import{_ as c,a as l,b as u,c as d,d as f,f as p,g as m,h,l as g,m as ee,o as _,p as v,r as te,s as ne,t as y,u as re,v as b,x as ie}from"./transform-messages-C8U1xonk.js";function x(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 S(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)}var ae=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ae=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 C(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var w=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)},T=class extends Error{},E=class e extends T{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}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 oe({message:r,cause:w(n)});let a=n?.error;return t===400?new ce(t,a,r,i):t===401?new le(t,a,r,i):t===403?new ue(t,a,r,i):t===404?new de(t,a,r,i):t===409?new fe(t,a,r,i):t===422?new pe(t,a,r,i):t===429?new me(t,a,r,i):t>=500?new he(t,a,r,i):new e(t,a,r,i)}},D=class extends E{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},oe=class extends E{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},se=class extends oe{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ce=class extends E{},le=class extends E{},ue=class extends E{},de=class extends E{},fe=class extends E{},pe=class extends E{},me=class extends E{},he=class extends E{},ge=class extends T{constructor(){super(`Could not parse response content as the length limit was reached`)}},_e=class extends T{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},ve=class extends Error{constructor(e){super(e)}},ye=class extends E{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},be=class extends T{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},xe=/^[a-z][a-z0-9+.-]*:/i,Se=e=>xe.test(e),O=e=>(O=Array.isArray,O(e)),Ce=O;function we(e){return typeof e==`object`?e??{}:{}}function Te(e){if(!e)return!0;for(let t in e)return!1;return!0}function Ee(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function De(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Oe=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new T(`${e} must be an integer`);if(t<0)throw new T(`${e} must be a positive integer`);return t},ke=e=>{try{return JSON.parse(e)}catch{return}},Ae=e=>new Promise(t=>setTimeout(t,e)),je=`6.40.0`,Me=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Ne(){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`}var Pe=()=>{let e=Ne();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":je,"X-Stainless-OS":Le(Deno.build.os),"X-Stainless-Arch":Ie(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":je,"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":je,"X-Stainless-OS":Le(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ie(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Fe();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":je,"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":je,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Fe(){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}var Ie=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Le=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`),Re,ze=()=>Re??=Pe();function Be(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ve(...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 He(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ve({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ue(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 We(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}var Ge=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Ke=`RFC3986`,qe=e=>String(e),Je={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:qe},Ye=(e,t)=>(Ye=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ye(e,t)),k=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Xe=1024,Ze=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Xe){let t=a.length>=Xe?a.slice(e,e+Xe):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=k[r];continue}if(r<2048){n[n.length]=k[192|r>>6]+k[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=k[224|r>>12]+k[128|r>>6&63]+k[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=k[240|r>>18]+k[128|r>>12&63]+k[128|r>>6&63]+k[128|r&63]}o+=n.join(``)}return o};function Qe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function $e(e,t){if(O(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var et={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},tt=function(e,t){Array.prototype.push.apply(e,O(t)?t:[t])},nt,A={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Ze,encodeValuesOnly:!1,format:Ke,formatter:qe,indices:!1,serializeDate(e){return(nt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function rt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var it={};function at(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,ee){let _=e,v=ee,te=0,ne=!1;for(;(v=v.get(it))!==void 0&&!ne;){let t=v.get(e);if(te+=1,t!==void 0){if(t===te)throw RangeError(`Cyclic object value`);ne=!0}v.get(it)===void 0&&(te=0)}if(typeof l==`function`?_=l(t,_):_ instanceof Date?_=f?.(_):n===`comma`&&O(_)&&(_=$e(_,function(e){return e instanceof Date?f?.(e):e})),_===null){if(a)return c&&!h?c(t,A.encoder,g,`key`,p):t;_=``}if(rt(_)||Qe(_)){if(c){let e=h?t:c(t,A.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(_,A.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(_))]}let y=[];if(_===void 0)return y;let re;if(n===`comma`&&O(_))h&&c&&(_=$e(_,c)),re=[{value:_.length>0?_.join(`,`)||null:void 0}];else if(O(l))re=l;else{let e=Object.keys(_);re=u?e.sort(u):e}let b=s?String(t).replace(/\./g,`%2E`):String(t),ie=r&&O(_)&&_.length===1?b+`[]`:b;if(i&&O(_)&&_.length===0)return ie+`[]`;for(let t=0;t<re.length;++t){let v=re[t],ne=typeof v==`object`&&v.value!==void 0?v.value:_[v];if(o&&ne===null)continue;let b=d&&s?v.replace(/\./g,`%2E`):v,x=O(_)?typeof n==`function`?n(ie,b):ie:ie+(d?`.`+b:`[`+b+`]`);ee.set(e,te);let S=new WeakMap;S.set(it,ee),tt(y,at(ne,x,n,r,i,a,o,s,n===`comma`&&h&&O(_)?null:c,l,u,d,f,p,m,h,g,S))}return y}function ot(e=A){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||A.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Ke;if(e.format!==void 0){if(!Ye(Je,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Je[n],i=A.filter;(typeof e.filter==`function`||O(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in et?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:A.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:A.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:A.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:A.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:A.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?A.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:A.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:A.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:A.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:A.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:A.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:A.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:A.strictNullHandling}}function st(e,t={}){let n=e,r=ot(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):O(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=et[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||tt(o,at(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function ct(e){return st(e,{arrayFormat:`brackets`})}function lt(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}var ut;function dt(e){let t;return(ut??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var ft;function pt(e){let t;return(ft??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var j,M,mt=class{constructor(){j.set(this,void 0),M.set(this,void 0),x(this,j,new Uint8Array,`f`),x(this,M,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?dt(e):e;x(this,j,lt([S(this,j,`f`),t]),`f`);let n=[],r;for(;(r=ht(S(this,j,`f`),S(this,M,`f`)))!=null;){if(r.carriage&&S(this,M,`f`)==null){x(this,M,r.index,`f`);continue}if(S(this,M,`f`)!=null&&(r.index!==S(this,M,`f`)+1||r.carriage)){n.push(pt(S(this,j,`f`).subarray(0,S(this,M,`f`)-1))),x(this,j,S(this,j,`f`).subarray(S(this,M,`f`)),`f`),x(this,M,null,`f`);continue}let e=S(this,M,`f`)===null?r.preceding:r.preceding-1,t=pt(S(this,j,`f`).subarray(0,e));n.push(t),x(this,j,S(this,j,`f`).subarray(r.index),`f`),x(this,M,null,`f`)}return n}flush(){return S(this,j,`f`).length?this.decode(`
|
|
2
|
+
`):[]}};j=new WeakMap,M=new WeakMap,mt.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),mt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ht(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 gt(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}var _t={off:0,error:200,warn:300,info:400,debug:500},vt=(e,t,n)=>{if(e){if(Ee(_t,e))return e;N(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(_t))}`)}};function yt(){}function bt(e,t,n){return!t||_t[e]>_t[n]?yt:t[e].bind(t)}var xt={error:yt,warn:yt,info:yt,debug:yt},St=new WeakMap;function N(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return xt;let r=St.get(t);if(r&&r[0]===n)return r[1];let i={error:bt(`error`,t,n),warn:bt(`warn`,t,n),info:bt(`info`,t,n),debug:bt(`debug`,t,n)};return St.set(t,[n,i]),i}var Ct=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()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),wt,Tt=class e{constructor(e,t,n){this.iterator=e,wt.set(this,void 0),this.controller=t,x(this,wt,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?N(r):console;async function*s(){if(a)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of Et(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new E(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new E(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(C(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new mt,n=Ue(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 T("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(C(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(wt=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,S(this,wt,`f`)),new e(()=>i(n),this.controller,S(this,wt,`f`))]}toReadableStream(){let e=this,t;return Ve({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=dt(JSON.stringify(n)+`
|
|
4
|
+
`);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 T(`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 T(`Attempted to iterate over a response with no body`);let n=new Ot,r=new mt,i=Ue(e.body);for await(let e of Dt(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*Dt(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`?dt(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=gt(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var Ot=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(`
|
|
5
|
+
`),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]=kt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function kt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function At(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return N(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Tt.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);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:jt(await n.json(),n):await n.text()})();return N(e).debug(`[${r}] response parsed`,Ct({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function jt(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var Mt,Nt=class e extends Promise{constructor(e,t,n=At){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Mt.set(this,void 0),x(this,Mt,e,`f`)}_thenUnwrap(t){return new e(S(this,Mt,`f`),this.responsePromise,async(e,n)=>jt(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(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(S(this,Mt,`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)}};Mt=new WeakMap;var Pt,Ft=class{constructor(e,t,n,r){Pt.set(this,void 0),x(this,Pt,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 T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,Pt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},It=class extends Nt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await At(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Lt=class extends Ft{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},P=class extends Ft{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...we(this.options.query),after:t}}:null}},F=class extends Ft{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...we(this.options.query),after:e}}:null}},I=class extends Ft{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...we(this.options.query),after:e}}:null}},Rt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},zt=`urn:ietf:params:oauth:grant-type:token-exchange`,Bt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Be()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:zt,subject_token:await this.config.provider.getToken(),subject_token_type:Rt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new ye(t.status,n,t.headers):E.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json(),r=n.expires_in||3600,i=Date.now()+r*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},Vt=()=>{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 Ht(e,t,n){return Vt(),new File(e,t??`unknown_file`,n)}function Ut(e){return(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))||``).split(/[\\/]/).pop()||void 0}var Wt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Gt=async(e,t)=>Zt(e.body)?{...e,body:await Jt(e.body,t)}:e,L=async(e,t)=>({...e,body:await Jt(e.body,t)}),Kt=new WeakMap;function qt(e){let t=typeof e==`function`?e:e.fetch,n=Kt.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 Kt.set(t,r),r}var Jt=async(e,t)=>{if(!await qt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Qt(n,e,t))),n},Yt=e=>e instanceof Blob&&`name`in e,Xt=e=>typeof e==`object`&&!!e&&(e instanceof Response||Wt(e)||Yt(e)),Zt=e=>{if(Xt(e))return!0;if(Array.isArray(e))return e.some(Zt);if(e&&typeof e==`object`){for(let t in e)if(Zt(e[t]))return!0}return!1},Qt=async(e,t,n)=>{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)e.append(t,Ht([await n.blob()],Ut(n)));else if(Wt(n))e.append(t,Ht([await new Response(He(n)).blob()],Ut(n)));else if(Yt(n))e.append(t,n,Ut(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Qt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Qt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},$t=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`,en=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&$t(e),tn=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function nn(e,t,n){if(Vt(),e=await e,en(e))return e instanceof File?e:Ht([await e.arrayBuffer()],e.name);if(tn(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),Ht(await rn(r),t,n)}let r=await rn(e);if(t||=Ut(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Ht(r,t,n)}async function rn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if($t(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Wt(e))for await(let n of e)t.push(...await rn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${an(e)}`)}return t}function an(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var R=class{constructor(e){this._client=e}};function on(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var sn=Object.freeze(Object.create(null)),z=((e=on)=>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??sn)??sn)?.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 T(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
6
|
+
`)}\n${a}\n${t}`)}return a})(on),cn=class extends R{list(e,t={},n){return this._client.getAPIList(z`/chat/completions/${e}/messages`,P,{query:t,...n,__security:{bearerAuth:!0}})}};function ln(e){return e!==void 0&&`function`in e&&e.function!==void 0}function un(e){return e?.$brand===`auto-parseable-response-format`}function dn(e){return e?.$brand===`auto-parseable-tool`}function fn(e,t){return!t||!_n(t)?{...e,choices:e.choices.map(e=>(vn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:pn(e,t)}function pn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new ge;if(e.finish_reason===`content_filter`)throw new _e;return vn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>hn(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?mn(t,e.message.content):null}}});return{...e,choices:n}}function mn(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function hn(e,t){let n=e.tools?.find(e=>ln(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:dn(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function gn(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>ln(e)&&e.function?.name===t.function.name);return ln(n)&&(dn(n)||n?.function.strict||!1)}function _n(e){return un(e.response_format)?!0:e.tools?.some(e=>dn(e)||e.type===`function`&&e.function.strict===!0)??!1}function vn(e){for(let t of e||[])if(t.type!==`function`)throw new T(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function yn(e){for(let t of e??[]){if(t.type!==`function`)throw new T(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new T(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var bn=e=>e?.role===`assistant`,xn=e=>e?.role===`tool`,Sn,Cn,wn,Tn,En,Dn,On,B,kn,An,jn,Mn,Nn,Pn=class{constructor(){Sn.add(this),this.controller=new AbortController,Cn.set(this,void 0),wn.set(this,()=>{}),Tn.set(this,()=>{}),En.set(this,void 0),Dn.set(this,()=>{}),On.set(this,()=>{}),B.set(this,{}),kn.set(this,!1),An.set(this,!1),jn.set(this,!1),Mn.set(this,!1),x(this,Cn,new Promise((e,t)=>{x(this,wn,e,`f`),x(this,Tn,t,`f`)}),`f`),x(this,En,new Promise((e,t)=>{x(this,Dn,e,`f`),x(this,On,t,`f`)}),`f`),S(this,Cn,`f`).catch(()=>{}),S(this,En,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},S(this,Sn,`m`,Nn).bind(this))},0)}_connected(){this.ended||(S(this,wn,`f`).call(this),this._emit(`connect`))}get ended(){return S(this,kn,`f`)}get errored(){return S(this,An,`f`)}get aborted(){return S(this,jn,`f`)}abort(){this.controller.abort()}on(e,t){return(S(this,B,`f`)[e]||(S(this,B,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=S(this,B,`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(S(this,B,`f`)[e]||(S(this,B,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{x(this,Mn,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){x(this,Mn,!0,`f`),await S(this,En,`f`)}_emit(e,...t){if(S(this,kn,`f`))return;e===`end`&&(x(this,kn,!0,`f`),S(this,Dn,`f`).call(this));let n=S(this,B,`f`)[e];if(n&&(S(this,B,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!S(this,Mn,`f`)&&!n?.length&&Promise.reject(e),S(this,Tn,`f`).call(this,e),S(this,On,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!S(this,Mn,`f`)&&!n?.length&&Promise.reject(e),S(this,Tn,`f`).call(this,e),S(this,On,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Cn=new WeakMap,wn=new WeakMap,Tn=new WeakMap,En=new WeakMap,Dn=new WeakMap,On=new WeakMap,B=new WeakMap,kn=new WeakMap,An=new WeakMap,jn=new WeakMap,Mn=new WeakMap,Sn=new WeakSet,Nn=function(e){if(x(this,An,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new D),e instanceof D)return x(this,jn,!0,`f`),this._emit(`abort`,e);if(e instanceof T)return this._emit(`error`,e);if(e instanceof Error){let t=new T(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new T(String(e)))};function Fn(e){return typeof e.parse==`function`}var V,In,Ln,Rn,zn,Bn,Vn,Hn,Un=10,Wn=class extends Pn{constructor(){super(...arguments),V.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),xn(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(bn(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new T(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),S(this,V,`m`,In).call(this)}async finalMessage(){return await this.done(),S(this,V,`m`,Ln).call(this)}async finalFunctionToolCall(){return await this.done(),S(this,V,`m`,Rn).call(this)}async finalFunctionToolCallResult(){return await this.done(),S(this,V,`m`,zn).call(this)}async totalUsage(){return await this.done(),S(this,V,`m`,Bn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=S(this,V,`m`,Ln).call(this);t&&this._emit(`finalMessage`,t);let n=S(this,V,`m`,In).call(this);n&&this._emit(`finalContent`,n);let r=S(this,V,`m`,Rn).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=S(this,V,`m`,zn).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,S(this,V,`m`,Bn).call(this))}async _createChatCompletion(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),S(this,V,`m`,Vn).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(pn(i,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let r=`tool`,{tool_choice:i=`auto`,stream:a,...o}=t,s=typeof i!=`string`&&i.type===`function`&&i?.function?.name,{maxChatCompletions:c=Un}=n||{},l=t.tools.map(e=>{if(dn(e)){if(!e.$callback)throw new T("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(let e of l)e.type===`function`&&(u[e.function.name||e.function.function.name]=e.function);let d=`tools`in t?l.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){let t=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:d,messages:[...this.messages]},n)).choices[0]?.message;if(!t)throw new T(`missing message in ChatCompletion response`);if(!t.tool_calls?.length)return;for(let e of t.tool_calls){if(e.type!==`function`)continue;let t=e.id,{name:n,arguments:i}=e.function,a=u[n];if(!a){let e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}if(s&&s!==n){let e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(s)} requested. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}let o;try{o=Fn(a)?await a.parse(i):i}catch(e){let n=e instanceof Error?e.message:String(e);this._addMessage({role:r,tool_call_id:t,content:n});continue}let c=await a.function(o,this),l=S(this,V,`m`,Hn).call(this,c);if(this._addMessage({role:r,tool_call_id:t,content:l}),s)return}}}};V=new WeakSet,In=function(){return S(this,V,`m`,Ln).call(this).content??null},Ln=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(bn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new T(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Rn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},zn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(xn(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},Bn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Vn=function(e){if(e.n!=null&&e.n>1)throw new T(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},Hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Gn=class e extends Wn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),bn(e)&&e.content&&this._emit(`content`,e.content)}},H={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Kn=class extends Error{},qn=class extends Error{};function Jn(e,t=H.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Yn(e.trim(),t)}var Yn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Kn(`${e} at position ${r}`)},a=e=>{throw new qn(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||H.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||H.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||H.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||H.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||H.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||H.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(H.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&H.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(H.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(H.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(H.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&H.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(H.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(H.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&H.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
7
|
+
\r `.includes(e[r]);)r++};return o()},Xn=e=>Jn(e,H.ALL^H.NUM),U,W,Zn,G,Qn,$n,er,tr,nr,rr,ir,ar,or=class e extends Wn{constructor(e){super(),U.add(this),W.set(this,void 0),Zn.set(this,void 0),G.set(this,void 0),x(this,W,e,`f`),x(this,Zn,[],`f`)}get currentChatCompletionSnapshot(){return S(this,G,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion;let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),S(this,U,`m`,Qn).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of i)S(this,U,`m`,er).call(this,e);if(i.controller.signal?.aborted)throw new D;return this._addChatCompletion(S(this,U,`m`,rr).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),S(this,U,`m`,Qn).call(this),this._connected();let r=Tt.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(S(this,U,`m`,rr).call(this)),S(this,U,`m`,er).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new D;return this._addChatCompletion(S(this,U,`m`,rr).call(this))}[(W=new WeakMap,Zn=new WeakMap,G=new WeakMap,U=new WeakSet,Qn=function(){this.ended||x(this,G,void 0,`f`)},$n=function(e){let t=S(this,Zn,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},S(this,Zn,`f`)[e.index]=t,t)},er=function(e){if(this.ended)return;let t=S(this,U,`m`,ar).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=S(this,U,`m`,$n).call(this,e);e.finish_reason&&(S(this,U,`m`,nr).call(this,e),r.current_tool_call_index!=null&&S(this,U,`m`,tr).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(S(this,U,`m`,nr).call(this,e),r.current_tool_call_index!=null&&S(this,U,`m`,tr).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},tr=function(e,t){if(S(this,U,`m`,$n).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=S(this,W,`f`)?.tools?.find(e=>ln(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:dn(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},nr=function(e){let t=S(this,U,`m`,$n).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=S(this,U,`m`,ir).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},rr=function(){if(this.ended)throw new T(`stream has ended, this shouldn't happen`);let e=S(this,G,`f`);if(!e)throw new T(`request ended without sending any chunks`);return x(this,G,void 0,`f`),x(this,Zn,[],`f`),sr(e,S(this,W,`f`))},ir=function(){let e=S(this,W,`f`)?.response_format;return un(e)?e:null},ar=function(e){var t,n,r,i;let a=S(this,G,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=x(this,G,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l){if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}}if(s&&(e.finish_reason=s,S(this,W,`f`)&&_n(S(this,W,`f`)))){if(s===`length`)throw new ge;if(s===`content_filter`)throw new _e}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&S(this,U,`m`,ir).call(this)&&(e.message.parsed=Xn(e.message.content))),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,gn(S(this,W,`f`),s)&&(s.function.parsed_arguments=Xn(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,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 Tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function sr(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return fn({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new T(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new T(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new T(`missing function_call.arguments for choice ${r}`);if(!c)throw new T(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new T(`missing choices[${r}].tool_calls[${n}].id\n${cr(e)}`);if(a==null)throw new T(`missing choices[${r}].tool_calls[${n}].type\n${cr(e)}`);if(l==null)throw new T(`missing choices[${r}].tool_calls[${n}].function.name\n${cr(e)}`);if(c==null)throw new T(`missing choices[${r}].tool_calls[${n}].function.arguments\n${cr(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function cr(e){return JSON.stringify(e)}var lr=class e extends or{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},ur=class extends R{constructor(){super(...arguments),this.messages=new cn(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,P,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return yn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>pn(t,e))}runTools(e,t){return e.stream?lr.runTools(this._client,e,t):Gn.runTools(this._client,e,t)}stream(e,t){return or.createChatCompletion(this._client,e,t)}};ur.Messages=cn;var dr=class extends R{constructor(){super(...arguments),this.completions=new ur(this._client)}};dr.Completions=ur;var fr=class extends R{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,P,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},pr=class extends R{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},mr=class extends R{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(z`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,Lt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,Lt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},hr=class extends R{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},gr=class extends R{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},_r=class extends R{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,I,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},vr=class extends R{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},yr=class extends R{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},br=class extends R{create(e,t,n){return this._client.post(z`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/groups/${e}/roles`,I,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},xr=class extends R{create(e,t,n){return this._client.post(z`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/groups/${e}/users`,I,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Sr=class extends R{constructor(){super(...arguments),this.users=new xr(this._client),this.roles=new br(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,I,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Sr.Users=xr,Sr.Roles=br;var Cr=class extends R{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/api_keys`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},wr=class extends R{list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/certificates`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(z`/organization/projects/${e}/certificates/activate`,Lt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(z`/organization/projects/${e}/certificates/deactivate`,Lt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},Tr=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Er=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Dr=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},Or=class extends R{listRateLimits(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/rate_limits`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},kr=class extends R{create(e,t,n){return this._client.post(z`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/projects/${e}/roles`,I,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Ar=class extends R{create(e,t,n){return this._client.post(z`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/service_accounts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},jr=class extends R{create(e,t,n){return this._client.post(z`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/spend_alerts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Mr=class extends R{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(z`/projects/${r}/groups/${e}/roles`,I,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Nr=class extends R{constructor(){super(...arguments),this.roles=new Mr(this._client)}create(e,t,n){return this._client.post(z`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(z`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/groups`,I,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Nr.Roles=Mr;var Pr=class extends R{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(z`/projects/${r}/users/${e}/roles`,I,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Fr=class extends R{constructor(){super(...arguments),this.roles=new Pr(this._client)}create(e,t,n){return this._client.post(z`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/users`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Fr.Roles=Pr;var K=class extends R{constructor(){super(...arguments),this.users=new Fr(this._client),this.serviceAccounts=new Ar(this._client),this.apiKeys=new Cr(this._client),this.rateLimits=new Or(this._client),this.modelPermissions=new Dr(this._client),this.hostedToolPermissions=new Er(this._client),this.groups=new Nr(this._client),this.roles=new kr(this._client),this.dataRetention=new Tr(this._client),this.spendAlerts=new jr(this._client),this.certificates=new wr(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(z`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};K.Users=Fr,K.ServiceAccounts=Ar,K.APIKeys=Cr,K.RateLimits=Or,K.ModelPermissions=Dr,K.HostedToolPermissions=Er,K.Groups=Nr,K.Roles=kr,K.DataRetention=Tr,K.SpendAlerts=jr,K.Certificates=wr;var Ir=class extends R{create(e,t,n){return this._client.post(z`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/users/${e}/roles`,I,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Lr=class extends R{constructor(){super(...arguments),this.roles=new Ir(this._client)}retrieve(e,t){return this._client.get(z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Lr.Roles=Ir;var q=class extends R{constructor(){super(...arguments),this.auditLogs=new pr(this._client),this.adminAPIKeys=new fr(this._client),this.usage=new yr(this._client),this.invites=new gr(this._client),this.users=new Lr(this._client),this.groups=new Sr(this._client),this.roles=new _r(this._client),this.dataRetention=new hr(this._client),this.spendAlerts=new vr(this._client),this.certificates=new mr(this._client),this.projects=new K(this._client)}};q.AuditLogs=pr,q.AdminAPIKeys=fr,q.Usage=yr,q.Invites=gr,q.Users=Lr,q.Groups=Sr,q.Roles=_r,q.DataRetention=hr,q.SpendAlerts=vr,q.Certificates=mr,q.Projects=K;var Rr=class extends R{constructor(){super(...arguments),this.organization=new q(this._client)}};Rr.Organization=q;var zr=Symbol(`brand.privateNullableHeaders`);function*Br(e){if(!e)return;if(zr 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():Ce(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=Ce(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])}}var J=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Br(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{[zr]:!0,values:t,nulls:n}},Vr=class extends R{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:J([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Hr=class extends R{create(e,t){return this._client.post(`/audio/transcriptions`,L({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Ur=class extends R{create(e,t){return this._client.post(`/audio/translations`,L({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Wr=class extends R{constructor(){super(...arguments),this.transcriptions=new Hr(this._client),this.translations=new Ur(this._client),this.speech=new Vr(this._client)}};Wr.Transcriptions=Hr,Wr.Translations=Ur,Wr.Speech=Vr;var Gr=class extends R{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,P,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},Kr=class extends R{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/assistants/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,P,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},qr=class extends R{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Jr=class extends R{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Yr=class extends R{constructor(){super(...arguments),this.sessions=new qr(this._client),this.transcriptionSessions=new Jr(this._client)}};Yr.Sessions=qr,Yr.TranscriptionSessions=Jr;var Xr=class extends R{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/chatkit/sessions/${e}/cancel`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},Zr=class extends R{retrieve(e,t){return this._client.get(z`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,F,{query:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(z`/chatkit/threads/${e}/items`,F,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Qr=class extends R{constructor(){super(...arguments),this.sessions=new Xr(this._client),this.threads=new Zr(this._client)}};Qr.Sessions=Xr,Qr.Threads=Zr;var $r=class extends R{create(e,t,n){return this._client.post(z`/threads/${e}/messages`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(z`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/messages/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/threads/${e}/messages`,P,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(z`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ei=class extends R{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(z`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(z`/threads/${r}/runs/${e}/steps`,P,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ti=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},ni=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},Y,ri,ii,X,ai,Z,oi,si,ci,li,Q,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si=class extends Pn{constructor(){super(...arguments),Y.add(this),ii.set(this,[]),X.set(this,{}),ai.set(this,{}),Z.set(this,void 0),oi.set(this,void 0),si.set(this,void 0),ci.set(this,void 0),li.set(this,void 0),Q.set(this,void 0),ui.set(this,void 0),di.set(this,void 0),fi.set(this,void 0)}[(ii=new WeakMap,X=new WeakMap,ai=new WeakMap,Z=new WeakMap,oi=new WeakMap,si=new WeakMap,ci=new WeakMap,li=new WeakMap,Q=new WeakMap,ui=new WeakMap,di=new WeakMap,fi=new WeakMap,Y=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,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})}}static fromReadableStream(e){let t=new ri;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let r=Tt.fromReadableStream(e,this.controller);for await(let e of r)S(this,Y,`m`,pi).call(this,e);if(r.controller.signal?.aborted)throw new D;return this._addRun(S(this,Y,`m`,mi).call(this))}toReadableStream(){return new Tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new ri;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)S(this,Y,`m`,pi).call(this,e);if(o.controller.signal?.aborted)throw new D;return this._addRun(S(this,Y,`m`,mi).call(this))}static createThreadAssistantStream(e,t,n){let r=new ri;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new ri;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return S(this,ui,`f`)}currentRun(){return S(this,di,`f`)}currentMessageSnapshot(){return S(this,Z,`f`)}currentRunStepSnapshot(){return S(this,fi,`f`)}async finalRunSteps(){return await this.done(),Object.values(S(this,X,`f`))}async finalMessages(){return await this.done(),Object.values(S(this,ai,`f`))}async finalRun(){if(await this.done(),!S(this,oi,`f`))throw Error(`Final run was not received.`);return S(this,oi,`f`)}async _createThreadAssistantStream(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort()));let i={...t,stream:!0},a=await e.createAndRun(i,{...n,signal:this.controller.signal});this._connected();for await(let e of a)S(this,Y,`m`,pi).call(this,e);if(a.controller.signal?.aborted)throw new D;return this._addRun(S(this,Y,`m`,mi).call(this))}async _createAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)S(this,Y,`m`,pi).call(this,e);if(o.controller.signal?.aborted)throw new D;return this._addRun(S(this,Y,`m`,mi).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(De(t)&&De(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!De(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};ri=Si,pi=function(e){if(!this.ended)switch(x(this,ui,e,`f`),S(this,Y,`m`,_i).call(this,e),e.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:S(this,Y,`m`,xi).call(this,e);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:S(this,Y,`m`,gi).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:S(this,Y,`m`,hi).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},mi=function(){if(this.ended)throw new T(`stream has ended, this shouldn't happen`);if(!S(this,oi,`f`))throw Error(`Final run has not been received`);return S(this,oi,`f`)},hi=function(e){let[t,n]=S(this,Y,`m`,yi).call(this,e,S(this,Z,`f`));x(this,Z,t,`f`),S(this,ai,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=S(this,si,`f`)){if(S(this,ci,`f`))switch(S(this,ci,`f`).type){case`text`:this._emit(`textDone`,S(this,ci,`f`).text,S(this,Z,`f`));break;case`image_file`:this._emit(`imageFileDone`,S(this,ci,`f`).image_file,S(this,Z,`f`))}x(this,si,n.index,`f`)}x(this,ci,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(S(this,si,`f`)!==void 0){let t=e.data.content[S(this,si,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,S(this,Z,`f`));break;case`text`:this._emit(`textDone`,t.text,S(this,Z,`f`))}}S(this,Z,`f`)&&this._emit(`messageDone`,e.data),x(this,Z,void 0,`f`)}},gi=function(e){let t=S(this,Y,`m`,vi).call(this,e);switch(x(this,fi,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==S(this,li,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(S(this,Q,`f`)&&this._emit(`toolCallDone`,S(this,Q,`f`)),x(this,li,e.index,`f`),x(this,Q,t.step_details.tool_calls[e.index],`f`),S(this,Q,`f`)&&this._emit(`toolCallCreated`,S(this,Q,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:x(this,fi,void 0,`f`),e.data.step_details.type==`tool_calls`&&S(this,Q,`f`)&&(this._emit(`toolCallDone`,S(this,Q,`f`)),x(this,Q,void 0,`f`)),this._emit(`runStepDone`,e.data,t)}},_i=function(e){S(this,ii,`f`).push(e),this._emit(`event`,e)},vi=function(e){switch(e.event){case`thread.run.step.created`:return S(this,X,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=S(this,X,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=ri.accumulateDelta(t,n.delta);S(this,X,`f`)[e.data.id]=r}return S(this,X,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:S(this,X,`f`)[e.data.id]=e.data}if(S(this,X,`f`)[e.data.id])return S(this,X,`f`)[e.data.id];throw Error(`No snapshot available`)},yi=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=S(this,Y,`m`,bi).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},bi=function(e,t){return ri.accumulateDelta(t,e)},xi=function(e){switch(x(this,di,e.data,`f`),e.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:x(this,oi,e.data,`f`),S(this,Q,`f`)&&(this._emit(`toolCallDone`,S(this,Q,`f`)),x(this,Q,void 0,`f`))}};var Ci=class extends R{constructor(){super(...arguments),this.steps=new ei(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(z`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(z`/threads/${r}/runs/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/runs/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/threads/${e}/runs`,P,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(z`/threads/${r}/runs/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Si.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ae(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Si.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Si.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Ci.Steps=ei;var wi=class extends R{constructor(){super(...arguments),this.runs=new Ci(this._client),this.messages=new $r(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/threads/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Si.createThreadAssistantStream(e,this._client.beta.threads,t)}};wi.Runs=Ci,wi.Messages=$r;var Ti=class extends R{constructor(){super(...arguments),this.realtime=new Yr(this._client),this.chatkit=new Qr(this._client),this.assistants=new Kr(this._client),this.threads=new wi(this._client)}};Ti.Realtime=Yr,Ti.ChatKit=Qr,Ti.Assistants=Kr,Ti.Threads=wi;var Ei=class extends R{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Di=class extends R{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(z`/containers/${r}/files/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Oi=class extends R{constructor(){super(...arguments),this.content=new Di(this._client)}create(e,t,n){return this._client.post(z`/containers/${e}/files`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(z`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/containers/${e}/files`,P,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(z`/containers/${r}/files/${e}`,{...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};Oi.Content=Di;var ki=class extends R{constructor(){super(...arguments),this.files=new Oi(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,P,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};ki.Files=Oi;var Ai=class extends R{create(e,t,n){let{include:r,...i}=t;return this._client.post(z`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(z`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/conversations/${e}/items`,F,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(z`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},ji=class extends R{constructor(){super(...arguments),this.items=new Ai(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};ji.Items=Ai;var Mi=class extends R{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&N(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(N(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=ti(t)}),e)))}},Ni=class extends R{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(z`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(z`/evals/${r}/runs/${e}/output_items`,P,{query:i,...n,__security:{bearerAuth:!0}})}},Pi=class extends R{constructor(){super(...arguments),this.outputItems=new Ni(this._client)}create(e,t,n){return this._client.post(z`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/evals/${e}/runs`,P,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Pi.OutputItems=Ni;var Fi=class extends R{constructor(){super(...arguments),this.runs=new Pi(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,P,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Fi.Runs=Pi;var Ii=class extends R{create(e,t){return this._client.post(`/files`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,P,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(z`/files/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Ae(t),a=await this.retrieve(e),Date.now()-i>n)throw new se({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Li=class extends R{},Ri=class extends R{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},zi=class extends R{constructor(){super(...arguments),this.graders=new Ri(this._client)}};zi.Graders=Ri;var Bi=class extends R{create(e,t,n){return this._client.getAPIList(z`/fine_tuning/checkpoints/${e}/permissions`,Lt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(z`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/fine_tuning/checkpoints/${e}/permissions`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(z`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Vi=class extends R{constructor(){super(...arguments),this.permissions=new Bi(this._client)}};Vi.Permissions=Bi;var Hi=class extends R{list(e,t={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/checkpoints`,P,{query:t,...n,__security:{bearerAuth:!0}})}},Ui=class extends R{constructor(){super(...arguments),this.checkpoints=new Hi(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,P,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/events`,P,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};Ui.Checkpoints=Hi;var Wi=class extends R{constructor(){super(...arguments),this.methods=new Li(this._client),this.jobs=new Ui(this._client),this.checkpoints=new Vi(this._client),this.alpha=new zi(this._client)}};Wi.Methods=Li,Wi.Jobs=Ui,Wi.Checkpoints=Vi,Wi.Alpha=zi;var Gi=class extends R{},Ki=class extends R{constructor(){super(...arguments),this.graderModels=new Gi(this._client)}};Ki.GraderModels=Gi;var qi=class extends R{createVariation(e,t){return this._client.post(`/images/variations`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,L({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ji=class extends R{retrieve(e,t){return this._client.get(z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,Lt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},Yi=class extends R{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},Xi=class extends R{accept(e,t,n){return this._client.post(z`/realtime/calls/${e}/accept`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(z`/realtime/calls/${e}/hangup`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(z`/realtime/calls/${e}/refer`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(z`/realtime/calls/${e}/reject`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},Zi=class extends R{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},Qi=class extends R{constructor(){super(...arguments),this.clientSecrets=new Zi(this._client),this.calls=new Xi(this._client)}};Qi.ClientSecrets=Zi,Qi.Calls=Xi;function $i(e,t){return!t||!na(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:ea(e,t)}function ea(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:aa(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:ta(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||oa(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function ta(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function na(e){return!!un(e.text?.format)}function ra(e){return e?.$brand===`auto-parseable-tool`}function ia(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function aa(e,t){let n=ia(e.tools??[],t.name);return{...t,...t,parsed_arguments:ra(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function oa(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var sa,ca,la,ua,da,fa,pa,ma,ha=class e extends Pn{constructor(e){super(),sa.add(this),ca.set(this,void 0),la.set(this,void 0),ua.set(this,void 0),x(this,ca,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),S(this,sa,`m`,da).call(this);let i,a=null;`response_id`in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of i)S(this,sa,`m`,fa).call(this,e,a);if(i.controller.signal?.aborted)throw new D;return S(this,sa,`m`,pa).call(this)}[(ca=new WeakMap,la=new WeakMap,ua=new WeakMap,sa=new WeakSet,da=function(){this.ended||x(this,la,void 0,`f`)},fa=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=S(this,sa,`m`,ma).call(this,e);switch(n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new T(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new T(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new T(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new T(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e)}},pa=function(){if(this.ended)throw new T(`stream has ended, this shouldn't happen`);let e=S(this,la,`f`);if(!e)throw new T(`request ended without sending any events`);x(this,la,void 0,`f`);let t=ga(e,S(this,ca,`f`));return x(this,ua,t,`f`),t},ma=function(e){let t=S(this,la,`f`);if(!t){if(e.type!==`response.created`)throw new T(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=x(this,la,e.response,`f`),t}switch(e.type){case`response.output_item.added`:t.output.push(e.item);break;case`response.content_part.added`:{let n=t.output[e.output_index];if(!n)throw new T(`missing output at index ${e.output_index}`);let r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?n.content.push(i):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(i));break}case`response.output_text.delta`:{let n=t.output[e.output_index];if(!n)throw new T(`missing output at index ${e.output_index}`);if(n.type===`message`){let t=n.content[e.content_index];if(!t)throw new T(`missing content at index ${e.content_index}`);if(t.type!==`output_text`)throw new T(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case`response.function_call_arguments.delta`:{let n=t.output[e.output_index];if(!n)throw new T(`missing output at index ${e.output_index}`);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.reasoning_text.delta`:{let n=t.output[e.output_index];if(!n)throw new T(`missing output at index ${e.output_index}`);if(n.type===`reasoning`){let t=n.content?.[e.content_index];if(!t)throw new T(`missing content at index ${e.content_index}`);if(t.type!==`reasoning_text`)throw new T(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.completed`:x(this,la,e.response,`f`)}return t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,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})}}async finalResponse(){await this.done();let e=S(this,ua,`f`);if(!e)throw new T(`stream ended without producing a ChatCompletion`);return e}};function ga(e,t){return $i(e,t)}var _a=class extends R{list(e,t={},n){return this._client.getAPIList(z`/responses/${e}/input_items`,P,{query:t,...n,__security:{bearerAuth:!0}})}},va=class extends R{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},ya=class extends R{constructor(){super(...arguments),this.inputItems=new _a(this._client),this.inputTokens=new va(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&oa(e),e))}retrieve(e,t={},n){return this._client.get(z`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&oa(e),e))}delete(e,t){return this._client.delete(z`/responses/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ea(t,e))}stream(e,t){return ha.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(z`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};ya.InputItems=_a,ya.InputTokens=va;var ba=class extends R{retrieve(e,t){return this._client.get(z`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},xa=class extends R{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(z`/skills/${r}/versions/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Sa=class extends R{constructor(){super(...arguments),this.content=new xa(this._client)}create(e,t={},n){return this._client.post(z`/skills/${e}/versions`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/skills/${e}/versions`,P,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Sa.Content=xa;var Ca=class extends R{constructor(){super(...arguments),this.content=new ba(this._client),this.versions=new Sa(this._client)}create(e={},t){return this._client.post(`/skills`,Gt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,P,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Ca.Content=ba,Ca.Versions=Sa;var wa=class extends R{create(e,t,n){return this._client.post(z`/uploads/${e}/parts`,L({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Ta=class extends R{constructor(){super(...arguments),this.parts=new wa(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(z`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};Ta.Parts=wa;var Ea=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},Da=class extends R{create(e,t,n){return this._client.post(z`/vector_stores/${e}/file_batches`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(z`/vector_stores/${r}/file_batches/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(z`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(z`/vector_stores/${r}/file_batches/${e}/files`,P,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ae(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await Ea(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},Oa=class extends R{create(e,t,n){return this._client.post(z`/vector_stores/${e}/files`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(z`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(z`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/vector_stores/${e}/files`,P,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(z`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ae(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(z`/vector_stores/${r}/files/${e}/content`,Lt,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ka=class extends R{constructor(){super(...arguments),this.files=new Oa(this._client),this.fileBatches=new Da(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/vector_stores/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,P,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(z`/vector_stores/${e}/search`,Lt,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};ka.Files=Oa,ka.FileBatches=Da;var Aa=class extends R{create(e,t){return this._client.post(`/videos`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,F,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(z`/videos/${e}/content`,{query:t,...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,L({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(z`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(z`/videos/${e}/remix`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},ja,Ma,Na,Pa=class extends R{constructor(){super(...arguments),ja.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");S(this,ja,`m`,Ma).call(this,n);let i=J([t]).values,a=S(this,ja,`m`,Na).call(this,i,`webhook-signature`),o=S(this,ja,`m`,Na).call(this,i,`webhook-timestamp`),s=S(this,ja,`m`,Na).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new ve(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new ve(`Webhook timestamp is too old`);if(c>l+r)throw new ve(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new ve(`The given webhook signature does not match the expected signature`)}};ja=new WeakSet,Ma=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Na=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Fa,Ia,La,Ra,za=`workload-identity-auth`,$=class{constructor({baseURL:e=ni(`OPENAI_BASE_URL`),apiKey:t=ni(`OPENAI_API_KEY`)??null,adminAPIKey:n=ni(`OPENAI_ADMIN_KEY`)??null,organization:r=ni(`OPENAI_ORG_ID`)??null,project:i=ni(`OPENAI_PROJECT_ID`)??null,webhookSecret:a=ni(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:o,...s}={}){Fa.add(this),La.set(this,void 0),this.completions=new Ei(this),this.chat=new dr(this),this.embeddings=new Mi(this),this.files=new Ii(this),this.images=new qi(this),this.audio=new Wr(this),this.moderations=new Yi(this),this.models=new Ji(this),this.fineTuning=new Wi(this),this.graders=new Ki(this),this.vectorStores=new ka(this),this.webhooks=new Pa(this),this.beta=new Ti(this),this.batches=new Gr(this),this.uploads=new Ta(this),this.admin=new Rr(this),this.responses=new ya(this),this.realtime=new Qi(this),this.conversations=new ji(this),this.evals=new Fi(this),this.containers=new ki(this),this.skills=new Ca(this),this.videos=new Aa(this);let c={apiKey:t,adminAPIKey:n,organization:r,project:i,webhookSecret:a,workloadIdentity:o,...s,baseURL:e||`https://api.openai.com/v1`};if(t&&o)throw new T("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!t&&!n&&!o)throw new T("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!c.dangerouslyAllowBrowser&&Me())throw new T(`It looks like you're running in a browser-like environment.
|
|
8
|
+
|
|
9
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
10
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
11
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
12
|
+
|
|
13
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
14
|
+
|
|
15
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
16
|
+
`);this.baseURL=c.baseURL,this.timeout=c.timeout??Ia.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l=`warn`;this.logLevel=l,this.logLevel=vt(c.logLevel,`ClientOptions.logLevel`,this)??vt(ni(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Be(),x(this,La,Ge,`f`);let u=ni(`OPENAI_CUSTOM_HEADERS`);if(u){let e={};for(let t of u.split(`
|
|
17
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}c.defaultHeaders=J([e,c.defaultHeaders])}this._options=c,o&&(this._workloadIdentityAuth=new Bt(o,this.fetch)),this.apiKey=typeof t==`string`?t:null,this.adminAPIKey=n,this.organization=r,this.project=i,this.webhookSecret=a}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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return J([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return J([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return J([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return J([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return ct(e)}getUserAgent(){return`${this.constructor.name}/JS ${je}`}defaultIdempotencyKey(){return`stainless-node-retry-${ae()}`}makeStatusError(e,t,n,r){return E.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof T?e:new T(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new T(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!S(this,Fa,`m`,Ra).call(this)&&n||this.baseURL,i=Se(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!Te(a)||!Te(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}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 Nt(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(N(this).debug(`[${c}] sending request`,Ct({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new D;let d=r.__security??{bearerAuth:!0},f=new AbortController,p=await this.fetchWithAuth(o,a,s,f,d).catch(w),m=Date.now();if(p instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new D;let i=C(p)||/timed? ?out/i.test(String(p)+(`cause`in p?String(p.cause):``));if(t)return N(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),N(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,Ct({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),this.retryRequest(r,t,n??c);throw N(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),N(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,Ct({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),p instanceof ye||p instanceof be?p:i?new se:new oe({message:Ba(p),cause:p})}let h=`[${c}${l}${[...p.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${p.ok?`succeeded`:`failed`} with status ${p.status} in ${m-u}ms`;if(!p.ok){if(p.status===401&&this._workloadIdentityAuth&&d.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await We(p.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??c);let e=await this.shouldRetry(p);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await We(p.body),N(this).info(`${h} - ${e}`),N(this).debug(`[${c}] response error (${e})`,Ct({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),this.retryRequest(r,t,n??c,p.headers)}let i=e?`error; no more retries left`:`error; not retryable`;N(this).info(`${h} - ${i}`);let a=await p.text().catch(e=>w(e).message),o=ke(a),s=o?void 0:a;throw N(this).debug(`[${c}] response error (${i})`,Ct({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(p.status,o,s,p.headers)}return N(this).info(h),N(this).debug(`[${c}] response start`,Ct({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),{response:p,options:r,controller:f,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 It(this,n,e)}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${za}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}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 Ae(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}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&&Oe(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{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=J([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))}:{},...ze(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=J([t]),r=globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream,i=!r&&(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||globalThis.Blob!==void 0&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);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||r?{bodyHeaders:void 0,body:e,isStreamingBody:!i}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:He(e),isStreamingBody:!0}: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),isStreamingBody:!1}:{...S(this,La,`f`).call(this,{body:e,headers:n}),isStreamingBody:!1}}};Ia=$,La=new WeakMap,Fa=new WeakSet,Ra=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=Ia,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=T,$.APIError=E,$.APIConnectionError=oe,$.APIConnectionTimeoutError=se,$.APIUserAbortError=D,$.NotFoundError=de,$.ConflictError=fe,$.RateLimitError=me,$.BadRequestError=ce,$.AuthenticationError=le,$.InternalServerError=he,$.PermissionDeniedError=ue,$.UnprocessableEntityError=pe,$.InvalidWebhookSignatureError=ve,$.toFile=nn,$.Completions=Ei,$.Chat=dr,$.Embeddings=Mi,$.Files=Ii,$.Images=qi,$.Audio=Wr,$.Moderations=Yi,$.Models=Ji,$.FineTuning=Wi,$.Graders=Ki,$.VectorStores=ka,$.Webhooks=Pa,$.Beta=Ti,$.Batches=Gr,$.Uploads=Ta,$.Admin=Rr,$.Responses=ya,$.Realtime=Qi,$.Conversations=ji,$.Evals=Fi,$.Containers=ki,$.Skills=Ca,$.Videos=Aa;function Ba(e){if(Va(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function Va(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var Ha=4e3;function Ua(e){if(!(e instanceof Error))return{message:Za(e),messageCarriesBody:!1};let t=e,n=Wa(t),r=Ga(t),i=r===void 0||e.message.includes(r);return{status:n,body:r,message:e.message,messageCarriesBody:i}}function Wa(e){if(typeof e.statusCode==`number`)return e.statusCode;if(typeof e.status==`number`)return e.status;if(typeof e.$metadata?.httpStatusCode==`number`)return e.$metadata.httpStatusCode;if(typeof e.$response?.statusCode==`number`)return e.$response.statusCode}function Ga(e){let t=Ka(e);if(t===void 0)return;let n=t.trim();if(n.length!==0)return Xa(n,Ha)}function Ka(e){if(typeof e.body==`string`)return e.body;if(Ja(e.error))return Za(e.error);let t=e.$response?.body;if(typeof t==`string`)return t;if(!qa(t)&&Ja(t))return Za(t)}function qa(e){return typeof e==`object`&&!!e&&`pipe`in e&&typeof e.pipe==`function`}function Ja(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.keys(e).length>0}function Ya(e,t){return e.messageCarriesBody||e.status===void 0||e.body===void 0?t!==void 0&&e.status!==void 0?`${t} (${e.status}): ${e.message}`:e.message:t===void 0?`${e.status}: ${e.body}`:`${t} (${e.status}): ${e.body}`}function Xa(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated ${e.length-t} chars]`}function Za(e){try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function Qa(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(n>>>0).toString(36)+(t>>>0).toString(36)}function $a(e){if(e===void 0)return;let t=Array.from(e);return t.length<=64?e:t.slice(0,64).join(``)}function eo(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 to(e,t,n){if(t)return t;if(eo(n,`authorization`)||eo(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function no(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function ro(e){return e.type===`text`}function io(e){return e.type===`thinking`}function ao(e){return e.type===`toolCall`}function oo(e){return e.type===`image`}function so(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function co(e){return(e.id===void 0||e.id===null||typeof e.id==`string`)&&(e.format===void 0||typeof e.format==`string`)&&(e.index===void 0||typeof e.index==`number`)}function lo(e){if(!so(e)||!co(e))return!1;switch(e.type){case`reasoning.summary`:return typeof e.summary==`string`;case`reasoning.encrypted`:return typeof e.data==`string`;case`reasoning.text`:return typeof e.text==`string`&&(e.signature===void 0||e.signature===null||typeof e.signature==`string`);default:return!1}}function uo(e){if(e)try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0&&t.every(lo)?t:void 0}catch{return}}function fo(e){if(e)try{let t=JSON.parse(e);return lo(t)&&t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&t.data.length>0?t:void 0}catch{return}}function po(e,t){e.id??=t.id,e.format||=t.format,e.index??=t.index}function mo(e,t){let n=e[e.length-1];if(t.type===`reasoning.text`&&n?.type===`reasoning.text`){n.text+=t.text,n.signature||=t.signature,po(n,t);return}if(t.type===`reasoning.summary`&&n?.type===`reasoning.summary`){n.summary+=t.summary,po(n,t);return}e.push({...t})}var ho=[`reasoning`,`reasoning_content`,`reasoning_text`];function go(e){return ho.includes(e)}function _o(e,t){return e||(c(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}var vo=(t,n,r)=>{let i=new s,o=a(n,zo(t).supportsMidConvoSystemMessages);return(async()=>{let n={role:`assistant`,content:[],api:t.api,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()},a,s=e=>{a!==void 0&&(e.thinkingSignature=JSON.stringify(a))};try{let c=to(t.provider,r?.apiKey,r?.headers),l=zo(t),d=re(e(o.messages),l.supportsOpenAIGrammarTools),f=_o(r?.cacheRetention,r?.env),p=f===`none`?void 0:r?.sessionId,h=bo(t,o,c,r?.headers,r?.fetch,p,l),ee=xo(t,o,r,l,f,d),_=await r?.onPayload?.(ee,t);_!==void 0&&(ee=_);let v={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:0},{data:te,response:ne}=await m(()=>h.chat.completions.create(ee,v).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});await r?.onResponse?.({status:ne.status,headers:ie(ne.headers)},t),i.push({type:`start`,partial:n});let y=null,b=null,x=!1,S=new Map,ae=new Map,C=n.content,w=e=>C.indexOf(e),T=e=>{let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``},E=(e,t,n)=>{let r=e.customInput;if(!r)return;let i=g(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i},D=e=>{let t=w(e);if(t!==-1){if(e.type===`text`)i.push({type:`text_end`,contentIndex:t,content:e.text,partial:n});else if(e.type===`thinking`)s(e),i.push({type:`thinking_end`,contentIndex:t,content:e.thinking,partial:n});else if(e.type===`toolCall`){if(e.customInput){let r=E(e,T(e),!0);r!==void 0&&i.push({type:`toolcall_delta`,contentIndex:t,delta:r,partial:n})}else e.arguments=u(e.partialArgs);delete e.partialArgs,delete e.customInput,delete e.streamIndex,i.push({type:`toolcall_end`,contentIndex:t,toolCall:e,partial:n})}}},oe=()=>(y||(y={type:`text`,text:``},C.push(y),i.push({type:`text_start`,contentIndex:w(y),partial:n})),y),se=e=>(b||(b={type:`thinking`,thinking:``,thinkingSignature:e},C.push(b),i.push({type:`thinking_start`,contentIndex:w(b),partial:n})),b),ce=e=>{let t=typeof e.index==`number`?e.index:void 0,r=e.function?.name??e.custom?.name??``,a=t===void 0?void 0:S.get(t);if(!a&&e.id&&(a=ae.get(e.id)),!a){let o=e.custom&&!e.function?d.get(r)??`input`:void 0,s=o!==void 0;a={type:`toolCall`,id:e.id||``,name:r,arguments:s?{[o]:``}:{},partialArgs:s?void 0:``,customInput:s?{property:o,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:t},t!==void 0&&S.set(t,a),e.id&&ae.set(e.id,a),C.push(a),i.push({type:`toolcall_start`,contentIndex:w(a),partial:n})}if(t!==void 0&&a.streamIndex===void 0&&(a.streamIndex=t,S.set(t,a)),e.id&&ae.set(e.id,a),!a.name&&r&&(a.name=r),e.custom&&!e.function&&!a.customInput){let e=d.get(a.name)??`input`;a.arguments={[e]:``},a.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete a.partialArgs}return a};for await(let e of te){if(!e||typeof e!=`object`)continue;n.responseId||=e.id,typeof e.model==`string`&&e.model.length>0&&e.model!==t.id&&(n.responseModel||=e.model),e.usage&&(n.usage=Io(e.usage,t));let r=Array.isArray(e.choices)?e.choices[0]:void 0;if(r){if(!e.usage&&r.usage&&(n.usage=Io(r.usage,t)),r.finish_reason){n.rawStopReason=r.finish_reason;let e=Lo(r.finish_reason);n.stopReason=e.stopReason,e.errorMessage&&(n.errorMessage=e.errorMessage),x=!0}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let e=oe();e.text+=r.delta.content,i.push({type:`text_delta`,contentIndex:w(e),delta:r.delta.content,partial:n})}let e=[`reasoning_content`,`reasoning`,`reasoning_text`],o=r.delta,s=null;for(let t of e){let e=o[t];if(typeof e==`string`&&e.length>0){s=t;break}}if(s){let e=o[s];if(typeof e==`string`&&e.length>0){let r=se(t.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=e,i.push({type:`thinking_delta`,contentIndex:w(r),delta:e,partial:n})}}if(r?.delta?.tool_calls)for(let e of r.delta.tool_calls){let t=ce(e);!t.id&&e.id&&(t.id=e.id,ae.set(e.id,t));let r=e.function?.name??e.custom?.name;!t.name&&r&&(t.name=r);let a=``;e.function?.arguments?(a=e.function.arguments,t.partialArgs=(t.partialArgs??``)+e.function.arguments,t.arguments=u(t.partialArgs)):e.custom?.input&&(a=E(t,T(t)+e.custom.input,!1)??``),i.push({type:`toolcall_delta`,contentIndex:w(t),delta:a,partial:n})}let c=r.delta.reasoning_details;if(Array.isArray(c))for(let e of c)lo(e)&&(se(``),a??=[],mo(a,e))}}}for(let e of C)D(e);if(r?.signal?.aborted||n.stopReason===`aborted`)throw Error(`Request was aborted`);if(!x&&!l.supportsFinishReason&&(n.stopReason=n.content.some(e=>e.type===`toolCall`)?`toolUse`:`stop`),n.stopReason===`error`)throw Error(n.errorMessage||`Provider returned an error stop reason`);if(l.supportsFinishReason&&!x||n.stopReason===`pending`)throw Error(`Stream ended without finish_reason`);i.push({type:`done`,reason:n.stopReason,message:n}),i.end()}catch(e){for(let e of n.content)e.type===`thinking`&&s(e),delete e.index,delete e.partialArgs,delete e.customInput,delete e.streamIndex;n.stopReason=r?.signal?.aborted?`aborted`:`error`,n.errorMessage=Ya(Ua(e));let t=e?.error?.metadata?.raw;t&&!n.errorMessage.includes(String(t))&&(n.errorMessage+=`\n${t}`),i.push({type:`error`,reason:n.stopReason,error:n}),i.end()}})(),i},yo=(e,t,n)=>{to(e.provider,n?.apiKey,n?.headers);let i={...te(e,t,n,n?.apiKey),toolChoice:n?.toolChoice},a=n?.reasoning?r(e,n.reasoning):void 0,o=a===`off`?void 0:a;return vo(e,t,{...i,reasoningEffort:o,thinkingBudgets:n?.thinkingBudgets})};function bo(e,t,n,r,i,a,o=zo(e)){let s={"User-Agent":b(),...e.headers};if(e.provider===`github-copilot`){let e=d(t.messages),n=ne({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&o.sendSessionAffinityHeaders&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a,s[`x-session-affinity`]=a)),r&&Object.assign(s,r),new $({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function xo(t,n,r,a=zo(t),o=_o(r?.cacheRetention,r?.env),s=re(e(n.messages),a.supportsOpenAIGrammarTools)){let c=i(n.messages,a.supportsMidConvoSystemMessages===!0&&a.supportsMidConvoToolAdditions===!0),l=Po(t,n,a,{grammarToolInputProperties:s}),u=Eo(a,o),d={model:t.id,messages:l,stream:!0,prompt_cache_key:t.baseUrl.includes(`api.openai.com`)&&o!==`none`||o===`long`&&a.supportsLongCacheRetention?$a(r?.sessionId):void 0,prompt_cache_retention:o===`long`&&a.supportsLongCacheRetention?`24h`:void 0};a.supportsUsageInStreaming!==!1&&(d.stream_options={include_usage:!0}),a.supportsStore&&(d.store=!1),r?.maxTokens&&(a.maxTokensField===`max_tokens`?d.max_tokens=r.maxTokens:d.max_completion_tokens=r.maxTokens),r?.temperature!==void 0&&(d.temperature=r.temperature),c.requestTools.length>0?(d.tools=Fo(c.requestTools,a),a.zaiToolStream&&(d.tool_stream=!0)):no(n.messages)&&(d.tools=[]),u&&Do(l,d.tools,u),r?.toolChoice&&(d.tool_choice=r.toolChoice),a.vllmPriority!==void 0&&(d.priority=a.vllmPriority);let f=So(a),p=Co(t,r,d);if(a.thinkingFormat===`zai`&&t.reasoning){let e=d;if(e.thinking=r?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},r?.reasoningEffort&&a.supportsReasoningEffort){let n=t.thinkingLevelMap?.[r.reasoningEffort],i=n===void 0?r.reasoningEffort:n;typeof i==`string`&&(e.reasoning_effort=i)}}else if(a.thinkingFormat===`qwen`&&t.reasoning){if(d.enable_thinking=!!r?.reasoningEffort,r?.reasoningEffort&&a.supportsReasoningEffort){let e=t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;typeof e==`string`&&(d.reasoning_effort=e)}}else if(a.thinkingFormat===`qwen-chat-template`&&t.reasoning)d.chat_template_kwargs={enable_thinking:!!r?.reasoningEffort,preserve_thinking:!0};else if(a.thinkingFormat===`chat-template`&&t.reasoning){let e=wo(t,r,a.chatTemplateKwargs,p);e&&(d.chat_template_kwargs=e)}else if(a.thinkingFormat===`baseten`&&t.reasoning){let e=d,n=wo(t,r,a.chatTemplateArgs,p);if(n&&(e.chat_template_args=n),a.supportsReasoningEffort){let n=r?.reasoningEffort,i=n?t.thinkingLevelMap?.[n]:t.thinkingLevelMap?.off,a=i===void 0?n:i;typeof a==`string`&&(e.reasoning_effort=a)}}else if(a.thinkingFormat===`deepseek`&&t.reasoning)r?.reasoningEffort?d.thinking={type:`enabled`}:t.thinkingLevelMap?.off!==null&&(d.thinking={type:`disabled`}),r?.reasoningEffort&&a.supportsReasoningEffort&&(d.reasoning_effort=t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort);else if(a.thinkingFormat===`openrouter`&&t.reasoning){let e=d;r?.reasoningEffort?e.reasoning={effort:t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort}:t.thinkingLevelMap?.off!==null&&(e.reasoning={effort:t.thinkingLevelMap?.off??`none`})}else if(a.thinkingFormat===`ant-ling`&&t.reasoning&&r?.reasoningEffort){let e=t.thinkingLevelMap?.[r.reasoningEffort];typeof e==`string`&&(d.reasoning={effort:e})}else if(a.thinkingFormat===`together`&&t.reasoning){let e=d;e.reasoning={enabled:!!r?.reasoningEffort},r?.reasoningEffort&&a.supportsReasoningEffort&&(e.reasoning_effort=t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort)}else if(a.thinkingFormat===`string-thinking`&&t.reasoning){let e=d;r?.reasoningEffort?e.thinking=t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:t.thinkingLevelMap?.off!==null&&(e.thinking=t.thinkingLevelMap?.off??`none`)}else if(r?.reasoningEffort&&t.reasoning&&a.supportsReasoningEffort)d.reasoning_effort=t.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;else if(!r?.reasoningEffort&&t.reasoning&&a.supportsReasoningEffort){let e=t.thinkingLevelMap?.off;typeof e==`string`&&(d.reasoning_effort=e)}if(f&&p!==void 0&&Object.assign(d,{[f]:p}),t.compat?.openRouterRouting&&(d.provider=t.compat.openRouterRouting),t.compat?.vercelGatewayRouting){let e=t.compat.vercelGatewayRouting;if(e.only||e.order){let t={};e.only&&(t.only=e.only),e.order&&(t.order=e.order),d.providerOptions={gateway:t}}}return r?.samplingParams&&Object.assign(d,r.samplingParams),d}function So(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return`thinking_token_budget`}function Co(e,t,n){if(!t?.reasoningEffort||!e.reasoning)return;let r=n.max_tokens??n.max_completion_tokens??e.maxTokens,i=l(_(t.reasoningEffort,t.thinkingBudgets),r);return i>0?i:void 0}function wo(e,t,n,r){let i={};for(let[a,o]of Object.entries(n)){let n=To(e,t,o,r);n!==void 0&&(i[a]=n)}return Object.keys(i).length>0?i:void 0}function To(e,t,n,r){if(typeof n!=`object`||!n)return n;let i=t?.reasoningEffort;if(!i&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!i;if(n.$var===`thinking.budget`)return r;let a=i?e.thinkingLevelMap?.[i]:e.thinkingLevelMap?.off;return a===void 0?i:typeof a==`string`?a:void 0}function Eo(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function Do(e,t,n){Oo(e,n),Ao(t,n),ko(e,n)}function Oo(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){jo(n,t);return}}function ko(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`||r.role===`tool`)&&Mo(r,t))return}}function Ao(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function jo(e,t){return No(e,t)}function Mo(e,t){return e.role===`user`||e.role===`assistant`||e.role===`tool`?No(e,t):!1}function No(e,t){let n=e.content;if(typeof n==`string`)return n.length!==0&&(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function Po(e,n,r,s){let c=a(n,r.supportsMidConvoSystemMessages),l=[],u=t=>{if(t.includes(`|`)){let e=t.indexOf(`|`),n=t.slice(0,e).replace(/[^a-zA-Z0-9_-]/g,`_`),r=t.slice(e+1).replace(/[^a-zA-Z0-9_-]/g,`_`),i=r.length>0?`${n}_${r}`:n;if(i.length<=40)return i;let a=Qa(t).slice(0,8);return`${n.slice(0,Math.max(1,40-a.length-1))}_${a}`}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},d=y(c.messages,e,e=>u(e)),p=i(c.messages,r.supportsMidConvoSystemMessages===!0&&r.supportsMidConvoToolAdditions===!0),m=e.reasoning&&r.supportsDeveloperRole?`developer`:`system`,g=null;for(let n=0;n<d.length;n++){let i=d[n];if(r.requiresAssistantAfterToolResult&&g===`toolResult`&&i.role===`user`&&l.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`system`){let e=n>0&&p.anchorsAdditions?i.toolsAdded??[]:[];if(e.length>0){let t={role:`system`,tools:Fo(e,r)};l.push(t)}let a=n===0?o(i):t(i);a.length>0&&l.push({role:m,content:h(a)})}else if(i.role===`user`){if(typeof i.content==`string`)l.push({role:`user`,content:h(i.content)});else{let e=i.content.filter(e=>e.type!==`text`||e.text.length>0).map(e=>e.type===`text`?{type:`text`,text:h(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;l.push({role:`user`,content:e})}}else if(i.role===`assistant`){let t={role:`assistant`,content:r.requiresAssistantAfterToolResult?``:null},n=i.content.filter(ro).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:h(e.text)})),a=n.map(e=>e.text).join(``),o=i.content.filter(io),c=i.content.filter(ao),u=o.map(e=>uo(e.thinkingSignature)).find(e=>e!==void 0),d=c.map(e=>fo(e.thoughtSignature)).filter(e=>e!==void 0),p=u??(d.length>0?d:void 0),m=o.filter(e=>e.thinking.trim().length>0);if(m.length>0){if(r.requiresThinkingAsText)t.content=[{type:`text`,text:m.map(e=>h(e.thinking)).join(`
|
|
18
|
+
|
|
19
|
+
`)},...n];else if(a.length>0&&(t.content=a),!p){let n=m[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&go(n)&&(t[n]=m.map(e=>e.thinking).join(`
|
|
20
|
+
`))}}else a.length>0&&(t.content=a);c.length>0&&(t.tool_calls=c.map(e=>{let t=s?.grammarToolInputProperties?.get(e.name);return t===void 0?{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}:{id:e.id,type:`custom`,custom:{name:e.name,input:h(f(e.name,e.arguments,t))}}})),p&&(t.reasoning_details=p),r.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let g=t.content;if(!(g!=null&&g.length>0)&&!t.tool_calls)continue;l.push(t)}else if(i.role===`toolResult`){let t=[],i=n;for(;i<d.length&&d[i].role===`toolResult`;i++){let n=d[i],a=n.content.filter(ro).map(e=>e.text).join(`
|
|
21
|
+
`),o=n.content.some(e=>e.type===`image`),s=a.length>0?a:o?`(see attached image)`:`(no tool output)`,c={role:`tool`,content:h(s),tool_call_id:n.toolCallId};if(r.requiresToolResultName&&n.toolName&&(c.name=n.toolName),l.push(c),o&&e.input.includes(`image`))for(let e of n.content)oo(e)&&t.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}n=i-1,t.length>0?(r.requiresAssistantAfterToolResult&&l.push({role:`assistant`,content:`I have processed the tool results.`}),l.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...t]}),g=`user`):g=`toolResult`;continue}g=i.role}return l}function Fo(e,t){return e.map(e=>{let n=v(e,t.supportsOpenAIGrammarTools);if(n)return{type:`custom`,custom:{name:e.name,description:e.description,format:{type:`grammar`,grammar:{syntax:n.format,definition:n.definition}}}};let r=ee(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:p(e,r),...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Io(e,t){let r=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,r-i-a),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:i,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return n(t,c),c}function Lo(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function Ro(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||t===`zai-coding-cn`||n.includes(`api.z.ai`)||n.includes(`open.bigmodel.cn`),i=t===`together`||n.includes(`api.together.ai`)||n.includes(`api.together.xyz`),a=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),o=t===`openrouter`||n.includes(`openrouter.ai`),s=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),c=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),l=t===`nvidia`||n.includes(`integrate.api.nvidia.com`),u=t===`ant-ling`||n.includes(`api.ant-ling.com`),d=t===`cerebras`||n.includes(`cerebras.ai`),f=t===`deepseek`||n.toLowerCase().includes(`deepseek.com`),p=l||d||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||f||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,m=n.includes(`chutes.ai`)||f||a||c||i||l||u||r,h=t===`xai`||n.includes(`api.x.ai`),g=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),ee=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!p,supportsDeveloperRole:g||!p&&!o,supportsReasoningEffort:!h&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:m?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:f,thinkingFormat:f?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:ee,sendSessionAffinityHeaders:o,sessionAffinityFormat:o?`openrouter`:`openai`,supportsLongCacheRetention:!(i||s||c||l||u)}}function zo(e){let t=Ro(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??t.supportsFinishReason,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??t.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??t.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??t.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??t.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??t.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention,vllmPriority:e.compat.vllmPriority}:t}export{Po as convertMessages,vo as stream,yo as streamSimple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e,c as t,g as n,h as r,x as i}from"./source-hSji-yvG.js";var a=`pulls.review`,o={repoInfo:`repo-info`,sourceKey:`source-key`,sourceFetch:`source-fetch`,sourceFingerprint:`source-fingerprint`,sourceLoadFile:`source-load-file`,storageGetItem:`storage-get-item`,storageSetItem:`storage-set-item`,storageRemoveItem:`storage-remove-item`,storageGetKeys:`storage-get-keys`,githubToken:`github-token`},s=Symbol(`local-rpc`),c=r({currentBranch:n(i()),defaultBranch:n(r({name:i(),ref:i()})),branches:t(i()),tags:t(i()),commits:t(r({sha:i(),subject:i()}))});async function l(t){return e(c,await t.call(o.repoInfo))}function u(e){switch(e.kind){case`compare`:return`/compare/${e.range}`;case`branch`:return`/branch/${e.branch}`;case`worktree`:return`/worktree`;case`commit`:return`/commit/${e.sha}`}}async function d(e,t){switch(e.kind){case`compare`:return e.range;case`branch`:{let n=(await l(t)).defaultBranch;if(!n)throw Error(`No default branch (origin/HEAD, main or master) to compare against.`);return`${n.ref}...${e.branch}`}case`worktree`:return``;case`commit`:return e.sha}}function f(e){let t=(e,t)=>String(e.params[t]);return[{path:`/compare/:range(.+)`,component:e,props:e=>({page:{kind:`compare`,range:t(e,`range`)}})},{path:`/branch/:branch(.+)`,component:e,props:e=>({page:{kind:`branch`,branch:t(e,`branch`)}})},{path:`/worktree`,component:e,props:{page:{kind:`worktree`}}},{path:`/commit/:sha`,component:e,props:e=>({page:{kind:`commit`,sha:t(e,`sha`)}})}]}export{s as a,d as i,l as n,a as o,u as r,o as s,f as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$n as e,C as t,Er as n,Et as r,Fn as i,G as a,Gt as o,H as s,Kt as c,Lt as l,Nt as u,Q as d,Sr as f,Tt as p,U as m,Un as h,V as g,W as _,Xn as v,Yt as y,Z as b,_ as x,ct as S,et as C,gn as w,j as T,n as E,nn as D,on as O,pn as k,qt as A,ut as j,v as M,vn as N,wr as P,wt as F,x as I,xn as L,yt as R,zt as z}from"./vue-i18n-DVI_S4Q5.js";import{C as B,w as V}from"./runtime-dom.esm-bundler-CqL7__VR.js";import{Ct as ee,Dt as H,Ot as U,St as W,_t as te,bt as G,ht as ne,kt as K,mt as re,t as ie,vt as q,wt as ae,xt as J,yt as Y}from"./useDocumentTitle-nuqxXiNo.js";import{s as oe}from"./index-BCCy9wJJ.js";import{r as se}from"./dist-Dh0a8u-Y.js";import{a as ce,n as le,r as X}from"./pages-B5mEqsbn.js";import{a as ue,c as de,d as fe,f as pe,h as me,i as he,l as ge,m as _e,n as ve,o as ye,p as be,r as xe,s as Se,t as Ce,u as we}from"./portalTarget-C60SzJiK.js";import{i as Te,n as Ee,r as De,t as Oe}from"./LandingHero-BkTBSu71.js";function ke(e,t,n){let r=e.findIndex(e=>K(e,t)),i=e.findIndex(e=>K(e,n));if(r===-1||i===-1)return[];let[a,o]=[r,i].sort((e,t)=>e-t);return e.slice(a,o+1)}var Ae=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Bopomofo}]/u,je=/android/i;function Me(){return typeof navigator<`u`&&je.test(navigator.userAgent)}function Ne(e){let t=h(!1),n=h(!0),i=h(!1),a=g(()=>t.value&&n.value);function o(){t.value=!0,n.value=!0,i.value=!1}function s(e){e.data&&(Ae.test(e.data)?(n.value=!0,i.value=!0):Me()&&!i.value&&(n.value=!1))}function c(n){r(()=>{t.value=!1,e?.(n)})}return{isComposing:t,shouldDeferInput:a,handleCompositionStart:o,handleCompositionUpdate:s,handleCompositionEnd:c}}function Pe(t){let n=g(()=>e(t)),r=g(()=>new Intl.Collator(`en`,{usage:`search`,...n.value}));return{startsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),r.value.compare(e.slice(0,t.length),t)===0),endsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),r.value.compare(e.slice(-t.length),t)===0),contains:(e,t)=>{if(t.length===0)return!0;if(e=e.normalize(`NFC`),t=t.normalize(`NFC`),t.length>e.length)return!1;let n=r.value.compare;if(e.includes(t))return!0;let i=t.length;for(let r=0;r+i<=e.length;r++)if(n(t,e.slice(r,r+i))===0)return!0;return!1}}}function Fe(){return{ALT:`Alt`,ARROW_DOWN:`ArrowDown`,ARROW_LEFT:`ArrowLeft`,ARROW_RIGHT:`ArrowRight`,ARROW_UP:`ArrowUp`,BACKSPACE:`Backspace`,CAPS_LOCK:`CapsLock`,CONTROL:`Control`,DELETE:`Delete`,END:`End`,ENTER:`Enter`,ESCAPE:`Escape`,F1:`F1`,F10:`F10`,F11:`F11`,F12:`F12`,F2:`F2`,F3:`F3`,F4:`F4`,F5:`F5`,F6:`F6`,F7:`F7`,F8:`F8`,F9:`F9`,HOME:`Home`,META:`Meta`,PAGE_DOWN:`PageDown`,PAGE_UP:`PageUp`,SHIFT:`Shift`,SPACE:` `,TAB:`Tab`,CTRL:`Control`,ASTERISK:`*`,SPACE_CODE:`Space`}}function Ie(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Z(e,t,n)):Z(e,t,n)}function Z(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:K(e,t)}var[Q,Le]=U(`ListboxRoot`),[Re,ze]=U(`ListboxHighlightScroll`),Be=C({__name:`ListboxRoot`,props:{modelValue:{type:null,required:!1},defaultValue:{type:null,required:!1},multiple:{type:Boolean,required:!1},orientation:{type:String,required:!1,default:`vertical`},dir:{type:String,required:!1},disabled:{type:Boolean,required:!1},selectionBehavior:{type:String,required:!1,default:`toggle`},highlightOnHover:{type:Boolean,required:!1},by:{type:[String,Function],required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`highlight`,`entryFocus`,`leave`],setup(t,{expose:n,emit:i}){let a=t,o=i,{multiple:s,highlightOnHover:l,orientation:u,disabled:d,selectionBehavior:f,dir:p}=v(a),{getItems:g,getItem:y}=te({isProvider:!0}),{handleTypeaheadSearch:b}=ge(),{primitiveElement:S,currentElement:C}=q(),w=Fe(),T=ae(p),E=Re(null);ze({suppressHighlightScroll:h(!1),onHighlightScrollRequest:()=>{}});let D=ee(C),O=h(),A=h(!1),j=h(!0),P=x(a,`modelValue`,o,{defaultValue:a.defaultValue??(s.value?[]:void 0),passive:a.modelValue===void 0,deep:!0});function F(e){if(A.value=!0,a.multiple){let t=Array.isArray(P.value)?[...P.value]:[],n=t.findIndex(t=>Z(t,e,a.by));a.selectionBehavior===`toggle`?(n===-1?t.push(e):t.splice(n,1),P.value=t):(P.value=[e],O.value=e)}else a.selectionBehavior===`toggle`&&Z(P.value,e,a.by)?P.value=void 0:P.value=e;setTimeout(()=>{A.value=!1},1)}let L=h(null),R=h(null),B=h(!1),V=h(!1),H=M(),U=M(),W=M();function G(){return g().map(e=>e.ref).filter(e=>e.dataset.disabled!==``)}function K(e,t=!0,n){if(!e)return;L.value=e;let r=E?.suppressHighlightScroll.value??!1;(n??j.value)&&(r?L.value.focus({preventScroll:!0}):L.value.focus()),r?E?.onHighlightScrollRequest(t?()=>{let e=L.value;e?.isConnected&&e.scrollIntoView({block:`nearest`})}:void 0):t&&L.value.scrollIntoView({block:`nearest`});let i=y(e);o(`highlight`,i)}function ie(e){if(B.value)W.trigger(e);else{let t=g().find(t=>Z(t.value,e,a.by));t&&(L.value=t.ref,K(t.ref))}}function J(e){if(L.value&&L.value.isConnected){if(e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault(),e.stopPropagation(),V.value||L.value.click()}}function oe(e){if(j.value){if(A.value=!0,B.value)U.trigger(e);else{let t=e.altKey||e.ctrlKey||e.metaKey;if(t&&e.key===`a`&&s.value){let t=g(),n=t.map(e=>e.value);P.value=[...n],e.preventDefault();let r=t.at(-1);r&&K(r.ref)}else if(!t){let t=b(e.key,g());t&&K(t)}}setTimeout(()=>{A.value=!1},1)}}function se(){V.value=!0}function ce(){r(()=>{V.value=!1})}function le(){r(()=>{de(new KeyboardEvent(`keydown`,{key:`PageUp`}))})}function X(e){let t=L.value;t?.isConnected&&(R.value=t),L.value=null,o(`leave`,e)}function ue(e){let t=new CustomEvent(`listbox.entryFocus`,{bubbles:!1,cancelable:!0});if(e.currentTarget?.dispatchEvent(t),o(`entryFocus`,t),!t.defaultPrevented){if(R.value)K(R.value);else{let e=G()?.[0];K(e)}}}function de(e){let t=re(e,u.value,T.value);if(!t)return;let n=G();if(L.value){if(t===`last`)n.reverse();else if(t===`prev`||t===`next`){t===`prev`&&n.reverse();let e=n.indexOf(L.value);n=n.slice(e+1)}fe(e,n[0])}if(n.length){let e=!L.value&&t===`prev`?n.length-1:0;K(n[e])}if(B.value)return U.trigger(e)}function fe(e,t){if(!B.value&&a.selectionBehavior===`replace`&&s.value&&Array.isArray(P.value)&&(!e.altKey&&!e.ctrlKey&&!e.metaKey||e.shiftKey)&&e.shiftKey){let n=g().filter(e=>e.ref.dataset.disabled!==``),r=n.find(e=>e.ref===t)?.value;if(e.key===w.END?r=n.at(-1)?.value:e.key===w.HOME&&(r=n[0]?.value),!r||!O.value)return;let i=ke(n.map(e=>e.value),O.value,r);P.value=i}}async function pe(e,t=!0){if(I){if(await r(),B.value)H.trigger({event:e,scroll:t});else{let e=G(),n=e.find(e=>e.dataset.state===`checked`),r=t?void 0:!1;n?K(n,t,r):e.length&&K(e[0],t,r)}}}let me=!1;return k(P,()=>{if(!A.value){let e=me;me=!0,r(()=>{pe(void 0,e)})}},{immediate:!0,deep:!0}),n({highlightedElement:L,highlightItem:ie,highlightFirstItem:le,highlightSelected:pe,getItems:g}),Le({modelValue:P,onValueChange:F,multiple:s,orientation:u,dir:T,disabled:d,highlightOnHover:l,highlightedElement:L,isVirtual:B,virtualFocusHook:H,virtualKeydownHook:U,virtualHighlightHook:W,by:a.by,firstValue:O,selectionBehavior:f,focusable:j,onLeave:X,onEnter:ue,changeHighlight:K,onKeydownEnter:J,onKeydownNavigation:de,onKeydownTypeAhead:oe,onCompositionStart:se,onCompositionEnd:ce,highlightFirstItem:le}),(t,n)=>(z(),m(e(Y),{ref_key:`primitiveElement`,ref:S,as:t.as,"as-child":t.asChild,dir:e(T),"data-disabled":e(d)?``:void 0,onPointerleave:X,onFocusout:n[0]||=async t=>{let n=t.relatedTarget||t.target;await r(),L.value&&e(C)&&!e(C).contains(n)&&X(t)}},{default:N(()=>[c(t.$slots,`default`,{modelValue:e(P)}),e(D)&&t.name?(z(),m(e(ne),{key:0,name:t.name,value:e(P),disabled:e(d),required:t.required},null,8,[`name`,`value`,`disabled`,`required`])):_(`v-if`,!0)]),_:3},8,[`as`,`as-child`,`dir`,`data-disabled`]))}}),Ve=C({__name:`ListboxContent`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(n){let{CollectionSlot:r}=te(),i=Q(),a=t(!1,10);return(t,n)=>(z(),m(e(r),null,{default:N(()=>[d(e(Y),{role:`listbox`,as:t.as,"as-child":t.asChild,tabindex:e(i).focusable.value?e(i).highlightedElement.value?`-1`:`0`:`-1`,"aria-orientation":e(i).orientation.value,"aria-multiselectable":!!e(i).multiple.value,"data-orientation":e(i).orientation.value,onMousedown:n[0]||=V(e=>a.value=!0,[`left`]),onFocus:n[1]||=t=>{e(a)||e(i).onEnter(t)},onKeydown:[n[2]||=B(t=>{(e(i).orientation.value!==`vertical`||t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)&&(e(i).orientation.value!==`horizontal`||t.key!==`ArrowUp`&&t.key!==`ArrowDown`)&&(t.preventDefault(),e(i).focusable.value&&e(i).onKeydownNavigation(t))},[`down`,`up`,`left`,`right`,`home`,`end`]),B(e(i).onKeydownEnter,[`enter`]),e(i).onKeydownTypeAhead]},{default:N(()=>[c(t.$slots,`default`)]),_:3},8,[`as`,`as-child`,`tabindex`,`aria-orientation`,`aria-multiselectable`,`data-orientation`,`onKeydown`])]),_:3}))}}),He=C({__name:`ListboxFilter`,props:{modelValue:{type:String,required:!1},autoFocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`input`}},emits:[`update:modelValue`],setup(t,{emit:n}){let r=t,i=x(r,`modelValue`,n,{defaultValue:``,passive:r.modelValue===void 0}),a=Q(),{primitiveElement:o,currentElement:s}=q(),d=g(()=>r.disabled||a.disabled.value||!1),f=h();w(()=>f.value=a.highlightedElement.value?.id),u(()=>{a.focusable.value=!1,setTimeout(()=>{r.autoFocus&&s.value?.focus()},1)}),l(()=>{a.focusable.value=!0});let{isComposing:p,shouldDeferInput:_,handleCompositionStart:v,handleCompositionUpdate:y,handleCompositionEnd:b}=Ne(e=>{i.value=e.target.value,a.onCompositionEnd(),a.highlightFirstItem()});function S(){a.onCompositionStart(),v()}function C(e){_.value||(i.value=e.target.value,a.highlightFirstItem())}function T(e){p.value||(e.preventDefault(),a.onKeydownNavigation(e))}function E(e){p.value||a.onKeydownEnter(e)}return(t,n)=>(z(),m(e(Y),{ref_key:`primitiveElement`,ref:o,as:t.as,"as-child":t.asChild,value:e(i),disabled:d.value?``:void 0,"data-disabled":d.value?``:void 0,"aria-disabled":d.value??void 0,"aria-activedescendant":f.value,type:`text`,onKeydown:[B(T,[`down`,`up`,`home`,`end`]),B(E,[`enter`])],onInput:C,onCompositionstart:S,onCompositionupdate:e(y),onCompositionend:e(b)},{default:N(()=>[c(t.$slots,`default`,{modelValue:e(i)})]),_:3},8,[`as`,`as-child`,`value`,`disabled`,`data-disabled`,`aria-disabled`,`aria-activedescendant`,`onCompositionupdate`,`onCompositionend`]))}}),Ue=`listbox.select`,[We,Ge]=U(`ListboxItem`),Ke=C({__name:`ListboxItem`,props:{value:{type:null,required:!0},disabled:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`div`}},emits:[`select`],setup(t,{emit:n}){let r=t,i=n,a=J(void 0,`reka-listbox-item`),{CollectionItem:o}=te(),{forwardRef:s,currentElement:l}=W(),u=Q(),f=g(()=>l.value!=null&&l.value===u.highlightedElement.value),h=g(()=>Ie(u.modelValue.value,r.value,u.by)),_=g(()=>u.disabled.value||r.disabled);async function v(e){i(`select`,e),!e?.defaultPrevented&&!_.value&&e&&(u.onValueChange(r.value),u.changeHighlight(l.value))}function y(e){let t={originalEvent:e,value:r.value};me(Ue,v,t)}return Ge({isSelected:h}),(t,n)=>(z(),m(e(o),{value:t.value},{default:N(()=>[L([f.value,h.value,_.value,e(u).focusable.value,...Object.entries(t.$attrs).flat()],()=>d(e(Y),p({id:e(a)},t.$attrs,{ref:e(s),role:`option`,tabindex:e(u).focusable.value?f.value?`0`:`-1`:-1,"aria-selected":h.value,as:t.as,"as-child":t.asChild,disabled:_.value?``:void 0,"data-disabled":_.value?``:void 0,"data-highlighted":f.value?``:void 0,"data-state":h.value?`checked`:`unchecked`,onClick:y,onKeydown:B(V(y,[`prevent`]),[`space`]),onPointermove:n[0]||=()=>{e(u).highlightedElement.value!==e(l)&&e(u).highlightOnHover.value&&e(u).changeHighlight(e(l),!1,!1)}}),{default:N(()=>[c(t.$slots,`default`)]),_:3},16,[`id`,`tabindex`,`aria-selected`,`as`,`as-child`,`disabled`,`data-disabled`,`data-highlighted`,`data-state`,`onKeydown`]),n,1)]),_:3},8,[`value`]))}});function qe(e){let t=h(`inline`),n=h(!1),r=h(),i=g(()=>t.value===`popper`&&!n.value),a;ze({suppressHighlightScroll:i,onHighlightScrollRequest(e){a=e}});function o(e,i){(r.value!==e||t.value!==i)&&(n.value=!1,a=void 0),r.value=e,t.value=i}function s(i){if(r.value!==i||t.value!==`popper`||n.value)return;n.value=!0;let o=a;a=void 0,e.value&&o?.()}function c(e){r.value===e&&(r.value=void 0,t.value=`inline`,n.value=!1,a=void 0)}return{onContentPositionChange:o,onContentPlaced:s,onContentUnmount:c}}var[$,Je]=U(`ComboboxRoot`),[Ye,Xe]=U(`AutocompleteRoot`),Ze=C({__name:`AutocompleteRoot`,props:{modelValue:{type:String,required:!1},defaultValue:{type:String,required:!1},open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},dir:{type:String,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},resetSearchTermOnBlur:{type:Boolean,required:!1,default:!1},openOnFocus:{type:Boolean,required:!1,default:!1},openOnClick:{type:Boolean,required:!1,default:!1},ignoreFilter:{type:Boolean,required:!1},highlightOnHover:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`highlight`,`update:open`],setup(t,{expose:n,emit:i}){let a=t,o=i,{primitiveElement:s,currentElement:l}=q(),{disabled:f,ignoreFilter:_,openOnFocus:y,openOnClick:b,dir:C,highlightOnHover:w}=v(a),T=ae(C),E=x(a,`modelValue`,o,{defaultValue:a.defaultValue??``,passive:a.modelValue===void 0}),D=x(a,`open`,o,{defaultValue:a.defaultOpen,passive:a.open===void 0}),O=g({get:()=>E.value,set:e=>{e==null?E.value=``:E.value=String(e)}});async function k(e){D.value=e,e?(H.value=E.value||``,await r(),s.value?.highlightSelected(),j.value=!0,F.value?.focus()):(j.value=!1,H.value=``,setTimeout(()=>{!e&&a.resetSearchTermOnBlur&&A.trigger()},1))}let A=M(),j=h(!1),P=h(!1),F=h(),I=h(),L=g(()=>s.value?.highlightedElement??void 0),R=qe(D),B=h(new Map),V=h(new Map),{contains:ee}=Pe({sensitivity:`base`}),H=h(``),U=g(e=>{if(!H.value||a.ignoreFilter||P.value)return{count:B.value.size,items:e?.items??new Map,groups:e?.groups??new Set(V.value.keys())};let t=0,n=new Map,r=new Set;for(let[e,r]of B.value){let i=ee(r,H.value);n.set(e,+!!i),i&&t++}for(let[e,t]of V.value)for(let i of t)if(n.get(i)>0){r.add(e);break}return{count:t,items:n,groups:r}}),W=S();return u(()=>{W?.exposed&&(W.exposed.highlightItem=s.value?.highlightItem,W.exposed.highlightFirstItem=s.value?.highlightFirstItem,W.exposed.highlightSelected=s.value?.highlightSelected)}),n({filtered:U,highlightedElement:L,highlightItem:s.value?.highlightItem,highlightFirstItem:s.value?.highlightFirstItem,highlightSelected:s.value?.highlightSelected}),Je({modelValue:O,multiple:h(!1),disabled:f,open:D,onOpenChange:k,...R,contentId:``,isUserInputted:j,isVirtual:P,inputElement:F,highlightedElement:L,onInputElementChange:e=>F.value=e,triggerElement:I,onTriggerElementChange:e=>I.value=e,parentElement:l,resetSearchTermOnSelect:h(!1),onResetSearchTerm:A.on,allItems:B,allGroups:V,filterSearch:H,filterState:U,ignoreFilter:_,openOnFocus:y,openOnClick:b,resetModelValueOnClear:h(!0)}),Xe({modelValue:E}),(t,n)=>(z(),m(e(ue),null,{default:N(()=>[d(e(Be),p({ref_key:`primitiveElement`,ref:s},t.$attrs,{modelValue:O.value,"onUpdate:modelValue":n[0]||=e=>O.value=e,style:{pointerEvents:e(D)?`auto`:void 0},as:t.as,"as-child":t.asChild,dir:e(T),name:t.name,required:t.required,disabled:e(f),"highlight-on-hover":e(w),onHighlight:n[1]||=e=>o(`highlight`,e)}),{default:N(()=>[c(t.$slots,`default`,{open:e(D),modelValue:e(E)})]),_:3},16,[`modelValue`,`style`,`as`,`as-child`,`dir`,`name`,`required`,`disabled`,`highlight-on-hover`])]),_:3}))}}),Qe=C({__name:`AutocompleteInput`,props:{modelValue:{type:String,required:!1},autoFocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`input`}},emits:[`update:modelValue`],setup(t,{emit:n}){let a=t,o=n,s=$(),l=Ye(),d=Q(),{primitiveElement:f,currentElement:p}=q(),h=x(a,`modelValue`,o,{passive:a.modelValue===void 0});l.modelValue.value&&(h.value=l.modelValue.value),u(()=>{p.value&&s.onInputElementChange(p.value)});let{isComposing:g,shouldDeferInput:_,handleCompositionStart:v,handleCompositionUpdate:y,handleCompositionEnd:b}=Ne(e=>{let t=e.target;t&&C(t.value)});function S(e){g.value||(e.preventDefault(),s.open.value||s.onOpenChange(!0))}function C(e){s.open.value?s.filterSearch.value=e:(s.onOpenChange(!0),r(()=>{e&&(s.filterSearch.value=e,d.highlightFirstItem())})),l.modelValue.value=e}function w(e){_.value||C(e.target.value)}function T(){s.openOnFocus.value&&!s.open.value&&s.onOpenChange(!0)}function E(){s.openOnClick.value&&!s.open.value&&s.onOpenChange(!0)}return k(l.modelValue,e=>{let t=e??``;h.value!==t&&(h.value=t)}),s.onResetSearchTerm(()=>{h.value=l.modelValue.value??``}),k(s.filterState,(e,t)=>{!s.isVirtual.value&&t.count===0&&d.highlightFirstItem()}),(t,n)=>(z(),m(e(He),{ref_key:`primitiveElement`,ref:f,modelValue:e(h),"onUpdate:modelValue":n[0]||=e=>i(h)?h.value=e:null,as:t.as,"as-child":t.asChild,"auto-focus":t.autoFocus,disabled:t.disabled,"aria-expanded":e(s).open.value,"aria-controls":e(s).contentId,"aria-autocomplete":`list`,role:`combobox`,autocomplete:`off`,onClick:E,onInput:w,onKeydown:B(S,[`down`,`up`]),onFocus:T,onCompositionstart:e(v),onCompositionupdate:e(y),onCompositionend:e(b)},{default:N(()=>[c(t.$slots,`default`)]),_:3},8,[`modelValue`,`as`,`as-child`,`auto-focus`,`disabled`,`aria-expanded`,`aria-controls`,`onCompositionstart`,`onCompositionupdate`,`onCompositionend`]))}}),$e=C({__name:`ComboboxAnchor`,props:{reference:{type:null,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(t){let{forwardRef:n}=W();return(t,r)=>(z(),m(e(he),{"as-child":``,reference:t.reference},{default:N(()=>[d(e(Y),p({ref:e(n),"as-child":t.asChild,as:t.as},t.$attrs),{default:N(()=>[c(t.$slots,`default`)]),_:3},16,[`as-child`,`as`])]),_:3},8,[`reference`]))}}),[et,tt]=U(`ComboboxContent`),nt=C({__name:`ComboboxContentImpl`,props:{position:{type:String,required:!1,default:`inline`},bodyLock:{type:Boolean,required:!1},hideWhenEmpty:{type:Boolean,required:!1},memoDependencies:{type:Array,required:!1},side:{type:null,required:!1},sideOffset:{type:Number,required:!1},sideFlip:{type:Boolean,required:!1},align:{type:null,required:!1},alignOffset:{type:Number,required:!1},alignFlip:{type:Boolean,required:!1},avoidCollisions:{type:Boolean,required:!1},collisionBoundary:{type:null,required:!1},collisionPadding:{type:[Number,Object],required:!1},arrowPadding:{type:Number,required:!1},hideShiftedArrow:{type:Boolean,required:!1},sticky:{type:String,required:!1},hideWhenDetached:{type:Boolean,required:!1},positionStrategy:{type:String,required:!1},updatePositionStrategy:{type:String,required:!1},disableUpdateOnLayoutShift:{type:Boolean,required:!1},prioritizePosition:{type:Boolean,required:!1},reference:{type:null,required:!1},dir:{type:String,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},disableOutsidePointerEvents:{type:Boolean,required:!1}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`],setup(t,{emit:n}){let r=t,i=n,{position:a}=v(r),o=$(),s=Symbol(`ComboboxContent`);k(a,e=>o.onContentPositionChange(s,e),{immediate:!0});let f=g(()=>o.ignoreFilter.value?o.allItems.value.size===0:o.filterState.value.count===0),{forwardRef:_,currentElement:b}=W();_e(r.bodyLock),be(),we(o.parentElement);let x=g(()=>r.position===`popper`?r:{}),S=pe(x.value),C={boxSizing:`border-box`,"--reka-combobox-content-transform-origin":`var(--reka-popper-transform-origin)`,"--reka-combobox-content-available-width":`var(--reka-popper-available-width)`,"--reka-combobox-content-available-height":`var(--reka-popper-available-height)`,"--reka-combobox-trigger-width":`var(--reka-popper-anchor-width)`,"--reka-combobox-trigger-height":`var(--reka-popper-anchor-height)`};tt({position:a});let w=h(!1);u(()=>{o.inputElement.value&&(w.value=b.value.contains(o.inputElement.value),w.value&&o.inputElement.value.focus())}),l(()=>{o.onContentUnmount(s);let e=H();w.value&&(!e||e===document.body)&&o.triggerElement.value?.focus()});function T(e){if(o.parentElement.value?.contains(e))return!0;let t=(e instanceof Element?e.closest(`label`):null)?.control;return!!t&&!!o.parentElement.value?.contains(t)}let E={placed:()=>o.onContentPlaced(s)};return(t,n)=>(z(),m(e(Ve),{"as-child":``},{default:N(()=>[d(e(Se),{"as-child":``,onMountAutoFocus:n[5]||=V(()=>{},[`prevent`]),onUnmountAutoFocus:n[6]||=V(()=>{},[`prevent`])},{default:N(()=>[d(e(de),{"as-child":``,"disable-outside-pointer-events":t.disableOutsidePointerEvents,onDismiss:n[0]||=t=>e(o).onOpenChange(!1),onFocusOutside:n[1]||=e=>{T(e.target)&&e.preventDefault(),i(`focusOutside`,e)},onInteractOutside:n[2]||=e=>i(`interactOutside`,e),onEscapeKeyDown:n[3]||=e=>i(`escapeKeyDown`,e),onPointerDownOutside:n[4]||=e=>{T(e.target)&&e.preventDefault(),i(`pointerDownOutside`,e)}},{default:N(()=>[(z(),m(y(e(a)===`popper`?e(xe):e(Y)),p({...t.$attrs,...e(S)},{id:e(o).contentId,ref:e(_),"memo-dependencies":e(a)===`popper`?[e(o).filterSearch.value,e(o).filterState.value]:void 0,"data-state":e(o).open.value?`open`:`closed`,"data-empty":f.value?``:void 0,style:{display:r.hideWhenEmpty&&f.value?`none`:`flex`,flexDirection:`column`,outline:`none`,...e(a)===`popper`?C:{}}},D(e(a)===`popper`?E:{})),{default:N(()=>[c(t.$slots,`default`)]),_:3},16,[`id`,`memo-dependencies`,`data-state`,`data-empty`,`style`]))]),_:3},8,[`disable-outside-pointer-events`])]),_:3})]),_:3}))}}),rt=C({__name:`ComboboxContent`,props:{forceMount:{type:Boolean,required:!1},position:{type:String,required:!1},bodyLock:{type:Boolean,required:!1},hideWhenEmpty:{type:Boolean,required:!1},memoDependencies:{type:Array,required:!1},side:{type:null,required:!1},sideOffset:{type:Number,required:!1},sideFlip:{type:Boolean,required:!1},align:{type:null,required:!1},alignOffset:{type:Number,required:!1},alignFlip:{type:Boolean,required:!1},avoidCollisions:{type:Boolean,required:!1},collisionBoundary:{type:null,required:!1},collisionPadding:{type:[Number,Object],required:!1},arrowPadding:{type:Number,required:!1},hideShiftedArrow:{type:Boolean,required:!1},sticky:{type:String,required:!1},hideWhenDetached:{type:Boolean,required:!1},positionStrategy:{type:String,required:!1},updatePositionStrategy:{type:String,required:!1},disableUpdateOnLayoutShift:{type:Boolean,required:!1},prioritizePosition:{type:Boolean,required:!1},reference:{type:null,required:!1},dir:{type:String,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},disableOutsidePointerEvents:{type:Boolean,required:!1}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`],setup(t,{emit:n}){let r=fe(t,n),{forwardRef:i}=W(),a=$();return a.contentId||=J(void 0,`reka-combobox-content`),(t,n)=>(z(),m(e(G),{present:t.forceMount||e(a).open.value},{default:N(()=>[d(nt,p({...e(r),...t.$attrs},{ref:e(i)}),{default:N(()=>[c(t.$slots,`default`)]),_:3},16)]),_:3},8,[`present`]))}}),[it,at]=U(`ComboboxGroup`),ot=C({__name:`ComboboxItem`,props:{textValue:{type:String,required:!1},value:{type:null,required:!0},disabled:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`select`],setup(t,{emit:r}){let i=t,a=r,o=J(void 0,`reka-combobox-item`),s=$(),d=it(null),{primitiveElement:f,currentElement:h}=q();if(i.value===``)throw Error(`A <ComboboxItem /> must have a value prop that is not an empty string. This is because the Combobox value can be set to an empty string to clear the selection and show the placeholder.`);let v=g(()=>{if(s.isVirtual.value||s.ignoreFilter.value||!s.filterSearch.value)return!0;{let e=s.filterState.value.items.get(o);return e===void 0||e>0}});return u(()=>{s.allItems.value.set(o,i.textValue||h.value.textContent||h.value.innerText);let e=d?.id;e&&(s.allGroups.value.has(e)?s.allGroups.value.get(e)?.add(o):s.allGroups.value.set(e,new Set([o])))}),l(()=>{s.allItems.value.delete(o)}),(t,r)=>v.value?L([v.value,e(s).filterSearch.value,e(s).disabled.value,t.disabled,i.value,i.as,i.asChild,...Object.values(t.$attrs)],()=>(z(),m(e(Ke),p({key:0},i,{id:e(o),ref_key:`primitiveElement`,ref:f,disabled:e(s).disabled.value||t.disabled,onSelect:r[0]||=n=>{a(`select`,n),!n.defaultPrevented&&(!e(s).multiple.value&&!t.disabled&&!e(s).disabled.value?(n.preventDefault(),e(s).onOpenChange(!1),e(s).modelValue.value=i.value):e(s).multiple.value&&e(s).inputElement.value?.focus())}}),{default:N(()=>[c(t.$slots,`default`,{},()=>[b(n(t.value),1)])]),_:3},16,[`id`,`disabled`])),r,1):_(`v-if`,!0)}}),st=C({__name:`ComboboxPortal`,props:{to:{type:null,required:!1},disabled:{type:Boolean,required:!1},defer:{type:Boolean,required:!1},forceMount:{type:Boolean,required:!1}},setup(t){let n=t;return(t,r)=>(z(),m(e(ye),P(j(n)),{default:N(()=>[c(t.$slots,`default`)]),_:3},16))}}),ct=C({__name:`ComboboxViewport`,props:{nonce:{type:String,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(t){let n=t,{forwardRef:r}=W(),{nonce:i}=v(n),o=ve(i),s=$();return(t,i)=>(z(),a(T,null,[d(e(Y),p({...t.$attrs,...n},{ref:e(r),"data-reka-combobox-viewport":``,role:`presentation`,style:{position:`relative`,flex:e(s).isVirtual.value?void 0:1,overflow:`auto`}}),{default:N(()=>[c(t.$slots,`default`)]),_:3},16,[`style`]),d(e(Y),{as:`style`,nonce:e(o)},{default:N(()=>i[0]||=[b(` /* Hide scrollbars cross-browser and enable momentum scroll for touch devices */ [data-reka-combobox-viewport] { scrollbar-width:none; -ms-overflow-style: none; -webkit-overflow-scrolling: touch; } [data-reka-combobox-viewport]::-webkit-scrollbar { display: none; } `)]),_:1,__:[0]},8,[`nonce`])],64))}}),lt={class:`truncate`},ut=C({inheritAttrs:!1,__name:`RefAutocomplete`,props:F({suggestions:{},placeholder:{},icon:{}},{modelValue:{default:``},modelModifiers:{}}),emits:[`update:modelValue`],setup(t){let r=O(t,`modelValue`),i=Ce(()=>void 0),c={branch:`i-ph:git-branch-duotone`,tag:`i-ph:tag-duotone`};return(l,u)=>(z(),m(e(Ze),{modelValue:r.value,"onUpdate:modelValue":u[0]||=e=>r.value=e,"open-on-focus":``,"open-on-click":``},{default:N(()=>[d(e($e),p(l.$attrs,{class:`h-9 min-w-0 inline-flex items-center gap-2 border border-base rounded bg-raised px-2 text-sm transition focus-within:ring-2 focus-within:ring-primary-500/40`}),{default:N(()=>[t.icon?(z(),a(`span`,{key:0,class:f([t.icon,`shrink-0 op-fade`]),"aria-hidden":`true`},null,2)):_(``,!0),d(e(Qe),{placeholder:t.placeholder,"aria-label":t.placeholder,class:`min-w-0 flex-1 bg-transparent color-base font-mono outline-none placeholder:op-mute`},null,8,[`placeholder`,`aria-label`])]),_:1},16),d(e(st),{to:e(i)},{default:N(()=>[d(e(rt),{position:`popper`,"side-offset":6,class:`z-dropdown max-h-72 min-w-[--reka-combobox-trigger-width] overflow-auto border border-base rounded-lg bg-glass:75 p-1 shadow-lg`,"data-af-animate":``},{default:N(()=>[d(e(ct),null,{default:N(()=>[(z(!0),a(T,null,o(t.suggestions,t=>(z(),m(e(ot),{key:`${t.kind}:${t.name}`,value:t.name,class:`flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm color-base font-mono outline-none transition data-[highlighted]:bg-hover`},{default:N(()=>[s(`span`,{class:f([c[t.kind],`shrink-0 op-fade`]),"aria-hidden":`true`},null,2),s(`span`,lt,n(t.name),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`to`])]),_:1},8,[`modelValue`]))}}),dt={class:`relative min-h-screen flex flex-col`},ft={class:`mxa max-w-6xl w-full flex flex-1 flex-col px-6 py-16 sm:py-20`},pt={class:`grid items-start gap-12 lg:grid-cols-[minmax(0,1fr)_minmax(0,30rem)] lg:gap-16`},mt={class:`flex flex-col gap-8`},ht={class:`max-w-md text-sm leading-relaxed op-fade`},gt={class:`flex flex-col gap-3`},_t={class:`text-xs font-mono op-fade`},vt={class:`flex flex-wrap gap-2`},yt={class:`text-xs op-fade`},bt={class:`min-w-0 flex flex-col gap-6`},xt={key:0,class:`flex flex-col gap-2`},St={class:`text-xs font-mono op-fade`},Ct={class:`flex flex-col border border-base rounded-lg py-1`},wt={class:`min-w-0 flex-1 truncate font-mono`},Tt=[`title`],Et={key:1,class:`flex flex-col gap-2`},Dt={class:`text-xs font-mono op-fade`},Ot={class:`flex flex-col border border-base rounded-lg py-1`},kt={class:`shrink-0 text-xs op-fade`},At={class:`min-w-0 flex-1 truncate`},jt=10,Mt=C({__name:`index`,setup(t){let r=R(ce),i=oe(),{t:c}=E(),l=h(),f=h(``),p=h(``),v=g(()=>[...(l.value?.branches??[]).map(e=>({name:e,kind:`branch`})),...(l.value?.tags??[]).map(e=>({name:e,kind:`tag`}))]),y=g(()=>{let e=l.value?.currentBranch;return e&&e!==l.value?.defaultBranch?.name?e:void 0}),x=g(()=>(l.value?.branches??[]).filter(e=>e!==l.value?.defaultBranch?.name).slice(0,jt));u(async()=>{l.value=await le(r),f.value||=l.value.defaultBranch?.ref??``,p.value||=l.value.currentBranch??`HEAD`});function S(){i.push(X({kind:`compare`,range:`${f.value.trim()}...${p.value.trim()}`}))}return ie(()=>c(`local.picker.title`)),(t,r)=>{let i=A(`RouterLink`);return z(),a(`div`,dt,[d(De),s(`main`,ft,[s(`section`,pt,[s(`div`,mt,[d(Oe),s(`p`,ht,n(t.$t(`local.picker.tagline`)),1),s(`form`,{class:`max-w-md flex items-stretch gap-2`,onSubmit:V(S,[`prevent`])},[d(ut,{modelValue:f.value,"onUpdate:modelValue":r[0]||=e=>f.value=e,suggestions:v.value,placeholder:t.$t(`local.picker.base`),icon:`i-ph:git-branch-duotone`,class:`flex-1`},null,8,[`modelValue`,`suggestions`,`placeholder`]),r[2]||=s(`span`,{class:`self-center font-mono op-fade`,"aria-hidden":`true`},`...`,-1),d(ut,{modelValue:p.value,"onUpdate:modelValue":r[1]||=e=>p.value=e,suggestions:v.value,placeholder:t.$t(`local.picker.head`),class:`flex-1`},null,8,[`modelValue`,`suggestions`,`placeholder`]),d(se,{type:`submit`,variant:`primary`,class:`pl-3 pr-4`,icon:`i-ph-arrow-right-bold`,disabled:!f.value.trim()||!p.value.trim()},{default:N(()=>[b(n(t.$t(`local.picker.compare`)),1)]),_:1},8,[`disabled`])],32),s(`div`,gt,[s(`h2`,_t,n(t.$t(`local.picker.shortcuts`)),1),s(`div`,vt,[y.value&&l.value?.defaultBranch?(z(),m(Ee,{key:0,to:e(X)({kind:`branch`,branch:y.value}),parent:y.value},{default:N(()=>[s(`span`,yt,n(t.$t(`local.picker.against`,{base:l.value.defaultBranch.ref})),1)]),_:1},8,[`to`,`parent`])):_(``,!0),d(Ee,{to:e(X)({kind:`worktree`}),parent:t.$t(`local.picker.worktree`)},null,8,[`to`,`parent`])])])]),s(`div`,bt,[x.value.length&&l.value?.defaultBranch?(z(),a(`section`,xt,[s(`h2`,St,n(t.$t(`local.picker.branches`)),1),s(`ul`,Ct,[(z(!0),a(T,null,o(x.value,o=>(z(),a(`li`,{key:o},[d(i,{to:e(X)({kind:`branch`,branch:o}),class:`flex items-center gap-2 px-3 py-1.5 text-sm transition hover:bg-hover`},{default:N(()=>[r[3]||=s(`span`,{class:`i-ph:git-branch-duotone shrink-0 op-fade`,"aria-hidden":`true`},null,-1),s(`span`,wt,n(o),1),o===y.value?(z(),a(`span`,{key:0,class:`i-ph:check-circle-duotone shrink-0 color-accent-teal`,title:t.$t(`local.picker.current`)},null,8,Tt)):_(``,!0)]),_:2},1032,[`to`])]))),128))])])):_(``,!0),l.value?.commits.length?(z(),a(`section`,Et,[s(`h2`,Dt,n(t.$t(`local.picker.recentCommits`)),1),s(`ul`,Ot,[(z(!0),a(T,null,o(l.value.commits,t=>(z(),a(`li`,{key:t.sha},[d(i,{to:e(X)({kind:`commit`,sha:t.sha}),title:t.subject,class:`flex items-center gap-3 px-3 py-1.5 text-sm transition hover:bg-hover`},{default:N(()=>[s(`code`,kt,n(t.sha.slice(0,7)),1),s(`span`,At,n(t.subject),1)]),_:2},1032,[`to`,`title`])]))),128))])])):_(``,!0)])])]),d(Te)])}}});export{Mt as default};
|