@shiplightai/mcp 0.1.48 → 0.1.50
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/chrome-extension/background.js +11 -2
- package/dist/agentHelpers-ZEELTQHQ-7LTM7RPI.js +4 -0
- package/dist/agentLogin-JJ76YIVR-ODLFUWNL.js +4 -0
- package/dist/chunk-2BZVD336.js +59 -0
- package/dist/chunk-3KLJZX63.js +34 -0
- package/dist/chunk-4DIUHKFB.js +200 -0
- package/dist/chunk-5GG34OWS.js +221 -0
- package/dist/chunk-5YN4X7LV.js +31 -0
- package/dist/chunk-67R4GP2H.js +4 -0
- package/dist/chunk-7W6YLS2E.js +22 -0
- package/dist/chunk-B7PRQ6ZM.js +4 -0
- package/dist/chunk-ETDHHU35.js +4 -0
- package/dist/chunk-FUPXB4VL.js +9 -0
- package/dist/chunk-HBXQFJ2K.js +4 -0
- package/dist/chunk-HHCLRZRA.js +15 -0
- package/dist/chunk-K7YTTSET.js +4 -0
- package/dist/chunk-KI54PAOH.js +192 -0
- package/dist/chunk-LM633YUO.js +4 -0
- package/dist/chunk-OZ36UVHR.js +3999 -0
- package/dist/chunk-PWGR4MG7.js +4 -0
- package/dist/chunk-UBUBM7F7.js +17 -0
- package/dist/chunk-VBI4DDSS.js +4 -0
- package/dist/chunk-X5NUVPAF.js +6 -0
- package/dist/chunk-XWDTDVL5.js +38 -0
- package/dist/chunk-Y64TKFRF.js +4237 -0
- package/dist/dist-CBGK26LV-CIQ64GXB.js +15 -0
- package/dist/dist-FVIJHOEK.js +4 -0
- package/dist/dist-N7YI5OTM.js +4 -0
- package/dist/dist-T3EAKPBA.js +4 -0
- package/dist/esm-7LSQY7YM.js +153 -0
- package/dist/fileFromPath-7DXRMRQU.js +19 -0
- package/dist/handler-QSEXJ3YG-BK26HZ5S.js +4 -0
- package/dist/import-meta-resolve-GTPXFCVK.js +6 -0
- package/dist/index.js +21 -9352
- package/dist/lib-ZSSBUTBS.js +588 -0
- package/dist/magic-string.es-LGBSB5S5.js +16 -0
- package/dist/multipart-parser-JC2L5VJI.js +5 -0
- package/dist/multipart-parser-TJWXZEMW-OF3QE73Z.js +5 -0
- package/dist/relayBrowserCache-QL6LD4JJ-RCZSXWM6.js +4 -0
- package/dist/server-SF3CTCCU.js +22 -0
- package/dist/src-B7EYCIZ4-XWOBV3GQ.js +6 -0
- package/dist/src-SYQHKG2Q.js +6 -0
- package/dist/task-5N7K2U7O-UX3BL63L.js +193 -0
- package/dist/token-AWIWOSVF.js +4 -0
- package/dist/token-QK7JKAKS.js +4 -0
- package/dist/token-util-GL5PN7CJ.js +4 -0
- package/dist/token-util-TEE5GKZ2.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __createRequire } from "module";
|
|
3
|
+
const require = __createRequire(import.meta.url);
|
|
4
|
+
import{b as Me,c as Kt,d as Jt,l as at,n as it,o as ot}from"./chunk-OZ36UVHR.js";import{a as le}from"./chunk-UBUBM7F7.js";import{h as Xs,l as Vs}from"./chunk-X5NUVPAF.js";import{b as Js,d as zt}from"./chunk-HBXQFJ2K.js";import{createRequire as pa}from"module";import{ZodFirstPartyTypeKind as A}from"zod/v3";import{ZodFirstPartyTypeKind as ya}from"zod/v3";import{ZodFirstPartyTypeKind as De}from"zod/v3";import{z as mt}from"zod";import{z as gt}from"zod";var Eo=pa(import.meta.url),fa=Symbol("Let zodToJsonSchema decide on which parser to use"),Ys={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},ma=e=>typeof e=="string"?{...Ys,name:e}:{...Ys,...e},ga=e=>{let t=ma(e),s=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function In(e,t,s,n){n?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function E(e,t,s,n,r){e[t]=s,In(e,t,n,r)}var Tn=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join("/")};function V(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Tn(t,e.currentPath):t.join("/")}}function ba(e,t){let s={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ya.ZodAny&&(s.items=T(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&E(s,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&E(s,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(E(s,"minItems",e.exactLength.value,e.exactLength.message,t),E(s,"maxItems",e.exactLength.value,e.exactLength.message,t)),s}function wa(e,t){let s={type:"integer",format:"int64"};if(!e.checks)return s;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?E(s,"minimum",n.value,n.message,t):E(s,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(s.exclusiveMinimum=!0),E(s,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?E(s,"maximum",n.value,n.message,t):E(s,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(s.exclusiveMaximum=!0),E(s,"maximum",n.value,n.message,t));break;case"multipleOf":E(s,"multipleOf",n.value,n.message,t);break}return s}function _a(){return{type:"boolean"}}function Pn(e,t){return T(e.type._def,t)}var va=(e,t)=>T(e.innerType._def,t);function En(e,t,s){let n=s??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,a)=>En(e,t,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xa(e,t)}}var xa=(e,t)=>{let s={type:"integer",format:"unix-time"};if(t.target==="openApi3")return s;for(let n of e.checks)switch(n.kind){case"min":E(s,"minimum",n.value,n.message,t);break;case"max":E(s,"maximum",n.value,n.message,t);break}return s};function Sa(e,t){return{...T(e.innerType._def,t),default:e.defaultValue()}}function Aa(e,t){return t.effectStrategy==="input"?T(e.schema._def,t):V(t)}function ka(e){return{type:"string",enum:Array.from(e.values)}}var $a=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Oa(e,t){let s=[T(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),T(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,r=[];return s.forEach(a=>{if($a(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...l}=a;i=l}else n=void 0;r.push(i)}}),r.length?{allOf:r,...n}:void 0}function Ia(e,t){let s=typeof e.value;return s!=="bigint"&&s!=="number"&&s!=="boolean"&&s!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:s==="bigint"?"integer":s,enum:[e.value]}:{type:s==="bigint"?"integer":s,const:e.value}}var Xt,ae={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Xt===void 0&&(Xt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Xt),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Rn(e,t){let s={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":E(s,"minLength",typeof s.minLength=="number"?Math.max(s.minLength,n.value):n.value,n.message,t);break;case"max":E(s,"maxLength",typeof s.maxLength=="number"?Math.min(s.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ie(s,"email",n.message,t);break;case"format:idn-email":ie(s,"idn-email",n.message,t);break;case"pattern:zod":K(s,ae.email,n.message,t);break}break;case"url":ie(s,"uri",n.message,t);break;case"uuid":ie(s,"uuid",n.message,t);break;case"regex":K(s,n.regex,n.message,t);break;case"cuid":K(s,ae.cuid,n.message,t);break;case"cuid2":K(s,ae.cuid2,n.message,t);break;case"startsWith":K(s,RegExp(`^${Vt(n.value,t)}`),n.message,t);break;case"endsWith":K(s,RegExp(`${Vt(n.value,t)}$`),n.message,t);break;case"datetime":ie(s,"date-time",n.message,t);break;case"date":ie(s,"date",n.message,t);break;case"time":ie(s,"time",n.message,t);break;case"duration":ie(s,"duration",n.message,t);break;case"length":E(s,"minLength",typeof s.minLength=="number"?Math.max(s.minLength,n.value):n.value,n.message,t),E(s,"maxLength",typeof s.maxLength=="number"?Math.min(s.maxLength,n.value):n.value,n.message,t);break;case"includes":{K(s,RegExp(Vt(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ie(s,"ipv4",n.message,t),n.version!=="v4"&&ie(s,"ipv6",n.message,t);break}case"base64url":K(s,ae.base64url,n.message,t);break;case"jwt":K(s,ae.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&K(s,ae.ipv4Cidr,n.message,t),n.version!=="v4"&&K(s,ae.ipv6Cidr,n.message,t);break}case"emoji":K(s,ae.emoji(),n.message,t);break;case"ulid":{K(s,ae.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ie(s,"binary",n.message,t);break}case"contentEncoding:base64":{E(s,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{K(s,ae.base64,n.message,t);break}}break}case"nanoid":K(s,ae.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return s}function Vt(e,t){return t.patternStrategy==="escape"?Pa(e):e}var Ta=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pa(e){let t="";for(let s=0;s<e.length;s++)Ta.has(e[s])||(t+="\\"),t+=e[s];return t}function ie(e,t,s,n){e.format||e.anyOf?.some(r=>r.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&n.errorMessages&&{errorMessage:{format:s}}})):E(e,"format",t,s,n)}function K(e,t,s,n){e.pattern||e.allOf?.some(r=>r.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Gs(t,n),...s&&n.errorMessages&&{errorMessage:{pattern:s}}})):E(e,"pattern",Gs(t,n),s,n)}function Gs(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=s.i?e.source.toLowerCase():e.source,r="",a=!1,i=!1,o=!1;for(let l=0;l<n.length;l++){if(a){r+=n[l],a=!1;continue}if(s.i){if(i){if(n[l].match(/[a-z]/)){o?(r+=n[l],r+=`${n[l-2]}-${n[l]}`.toUpperCase(),o=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(r+=n[l],o=!0):r+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){r+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(s.m){if(n[l]==="^"){r+=`(^|(?<=[\r
|
|
5
|
+
]))`;continue}else if(n[l]==="$"){r+=`($|(?=[\r
|
|
6
|
+
]))`;continue}}if(s.s&&n[l]==="."){r+=i?`${n[l]}\r
|
|
7
|
+
`:`[${n[l]}\r
|
|
8
|
+
]`;continue}r+=n[l],n[l]==="\\"?a=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return r}function jn(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===De.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:T(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??V(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let s={type:"object",additionalProperties:T(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return s;if(e.keyType?._def.typeName===De.ZodString&&e.keyType._def.checks?.length){let{type:n,...r}=Rn(e.keyType._def,t);return{...s,propertyNames:r}}else{if(e.keyType?._def.typeName===De.ZodEnum)return{...s,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===De.ZodBranded&&e.keyType._def.type._def.typeName===De.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...r}=Pn(e.keyType._def,t);return{...s,propertyNames:r}}}return s}function Ea(e,t){if(t.mapStrategy==="record")return jn(e,t);let s=T(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||V(t),n=T(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||V(t);return{type:"array",maxItems:125,items:{type:"array",items:[s,n],minItems:2,maxItems:2}}}function Ra(e){let t=e.values,s=Object.keys(e.values).filter(r=>typeof t[t[r]]!="number").map(r=>t[r]),n=Array.from(new Set(s.map(r=>typeof r)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function ja(e){return e.target==="openAi"?void 0:{not:V({...e,currentPath:[...e.currentPath,"not"]})}}function Na(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ot={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ca(e,t){if(t.target==="openApi3")return Qs(e,t);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(n=>n._def.typeName in Ot&&(!n._def.checks||!n._def.checks.length))){let n=s.reduce((r,a)=>{let i=Ot[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:n.length>1?n:n[0]}}else if(s.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=s.reduce((r,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(n.length===s.length){let r=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:s.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(s.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:s.reduce((n,r)=>[...n,...r._def.values.filter(a=>!n.includes(a))],[])};return Qs(e,t)}var Qs=(e,t)=>{let s=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,r)=>T(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return s.length?{anyOf:s}:void 0};function La(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ot[e.innerType._def.typeName],nullable:!0}:{type:[Ot[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=T(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=T(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function Ma(e,t){let s={type:"number"};if(!e.checks)return s;for(let n of e.checks)switch(n.kind){case"int":s.type="integer",In(s,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?E(s,"minimum",n.value,n.message,t):E(s,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(s.exclusiveMinimum=!0),E(s,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?E(s,"maximum",n.value,n.message,t):E(s,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(s.exclusiveMaximum=!0),E(s,"maximum",n.value,n.message,t));break;case"multipleOf":E(s,"multipleOf",n.value,n.message,t);break}return s}function Da(e,t){let s=t.target==="openAi",n={type:"object",properties:{}},r=[],a=e.shape();for(let o in a){let l=a[o];if(l===void 0||l._def===void 0)continue;let d=Ba(l);d&&s&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let h=T(l._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});h!==void 0&&(n.properties[o]=h,d||r.push(o))}r.length&&(n.required=r);let i=qa(e,t);return i!==void 0&&(n.additionalProperties=i),n}function qa(e,t){if(e.catchall._def.typeName!=="ZodNever")return T(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ba(e){try{return e.isOptional()}catch{return!0}}var Fa=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return T(e.innerType._def,t);let s=T(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return s?{anyOf:[{not:V(t)},s]}:V(t)},Ua=(e,t)=>{if(t.pipeStrategy==="input")return T(e.in._def,t);if(t.pipeStrategy==="output")return T(e.out._def,t);let s=T(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=T(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(r=>r!==void 0)}};function Wa(e,t){return T(e.type._def,t)}function Za(e,t){let s={type:"array",uniqueItems:!0,items:T(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&E(s,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&E(s,"maxItems",e.maxSize.value,e.maxSize.message,t),s}function Ha(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((s,n)=>T(s._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((s,n)=>n===void 0?s:[...s,n],[]),additionalItems:T(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((s,n)=>T(s._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((s,n)=>n===void 0?s:[...s,n],[])}}function za(e){return{not:V(e)}}function Ka(e){return V(e)}var Ja=(e,t)=>T(e.innerType._def,t),Xa=(e,t,s)=>{switch(t){case A.ZodString:return Rn(e,s);case A.ZodNumber:return Ma(e,s);case A.ZodObject:return Da(e,s);case A.ZodBigInt:return wa(e,s);case A.ZodBoolean:return _a();case A.ZodDate:return En(e,s);case A.ZodUndefined:return za(s);case A.ZodNull:return Na(s);case A.ZodArray:return ba(e,s);case A.ZodUnion:case A.ZodDiscriminatedUnion:return Ca(e,s);case A.ZodIntersection:return Oa(e,s);case A.ZodTuple:return Ha(e,s);case A.ZodRecord:return jn(e,s);case A.ZodLiteral:return Ia(e,s);case A.ZodEnum:return ka(e);case A.ZodNativeEnum:return Ra(e);case A.ZodNullable:return La(e,s);case A.ZodOptional:return Fa(e,s);case A.ZodMap:return Ea(e,s);case A.ZodSet:return Za(e,s);case A.ZodLazy:return()=>e.getter()._def;case A.ZodPromise:return Wa(e,s);case A.ZodNaN:case A.ZodNever:return ja(s);case A.ZodEffects:return Aa(e,s);case A.ZodAny:return V(s);case A.ZodUnknown:return Ka(s);case A.ZodDefault:return Sa(e,s);case A.ZodBranded:return Pn(e,s);case A.ZodReadonly:return Ja(e,s);case A.ZodCatch:return va(e,s);case A.ZodPipeline:return Ua(e,s);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(n=>{})(t)}};function T(e,t,s=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,s);if(o!==fa)return o}if(n&&!s){let o=Va(n,t);if(o!==void 0)return o}let r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);let a=Xa(e,e.typeName,t),i=typeof a=="function"?T(a(),t):a;if(i&&Ya(e,t,i),t.postProcess){let o=t.postProcess(i,e,t);return r.jsonSchema=i,o}return r.jsonSchema=i,i}var Va=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Tn(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((s,n)=>t.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),V(t)):t.$refStrategy==="seen"?V(t):void 0}},Ya=(e,t,s)=>(e.description&&(s.description=e.description,t.markdownDescription&&(s.markdownDescription=e.description)),s),Nn=(e,t)=>{let s=ga(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[d,h])=>({...l,[d]:T(h._def,{...s,currentPath:[...s.basePath,s.definitionPath,d]},!0)??V(s)}),{}):void 0,r=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=T(e._def,r===void 0?s:{...s,currentPath:[...s.basePath,s.definitionPath,r]},!1)??V(s),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i),s.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[s.openAiAnyTypeName]||(n[s.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:s.$refStrategy==="relative"?"1":[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join("/")}}));let o=r===void 0?n?{...a,[s.definitionPath]:n}:a:{$ref:[...s.$refStrategy==="relative"?[]:s.basePath,s.definitionPath,r].join("/"),[s.definitionPath]:{...n,[r]:a}};return s.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(s.target==="jsonSchema2019-09"||s.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),s.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function Yt(e){let t=Nn(e,{$refStrategy:"none"});if(t.$schema&&delete t.$schema,t.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${t.type}`);return Be(t),t}function qo(e){return Nn(e,{$refStrategy:"none"})}function Be(e){if(!(typeof e!="object"||e===null)){if(e.type==="object"&&(e.additionalProperties=!1,e.properties)){let t=Object.keys(e.properties);e.required=t;for(let s of Object.values(e.properties))Be(s)}e.type==="array"&&e.items&&Be(e.items);for(let t of["anyOf","oneOf","allOf"])Array.isArray(e[t])&&e[t].forEach(Be);for(let[t,s]of Object.entries(e))typeof s=="object"&&s!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(t)&&Be(s)}}var Ga=class{constructor(e){this.registry=e}getToolDefinitions(){return this.registry.getTools().filter(e=>e.availability.openai).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:Yt(e.schema),strict:!0}}))}getToolDefinitionsFiltered(e){let t=new Set(e);return this.registry.getTools().filter(s=>t.has(s.name)&&s.availability.openai).map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:Yt(s.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(e){let t=this.registry.get(e);if(t)return{type:"function",function:{name:t.name,description:t.description,parameters:Yt(t.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function Qa(e,t){let s=new Map;for(let l of t)l.hash&&l.url?s.set(l.hash,l.url):l.uuid&&l.url&&s.set(l.uuid,l.url);let n=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,r=[],a=0,i;for(;(i=n.exec(e))!==null;){let l=e.slice(a,i.index);l&&r.push({type:"text",text:l});let d=i[2];s.has(d)?r.push({type:"image",image:new URL(s.get(d))}):r.push({type:"text",text:i[0]}),a=i.index+i[0].length}let o=e.slice(a);return o&&r.push({type:"text",text:o}),r.length===0&&r.push({type:"text",text:e}),r}function ei(e){let t=[];for(let s of e){let n=s.content||"",r=s.images||[],a=Qa(n,r);t.length>0&&a.length>0&&t.push({type:"text",text:`
|
|
9
|
+
|
|
10
|
+
`}),t.push(...a)}return t}var Cn=!1;function Ln(e,t=Cn){if(t){let s=ei(e);if(s.length===0)return[];let n={type:"text",text:`
|
|
11
|
+
|
|
12
|
+
<retrieved_knowledge>
|
|
13
|
+
|
|
14
|
+
Below are expert curated knowledge that are retrieved from the knowledge base; APPLY THESE KNOWLEDGES IF THEY ARE RELEVANT TO THE TASK:
|
|
15
|
+
`},r={type:"text",text:`
|
|
16
|
+
|
|
17
|
+
</retrieved_knowledge>
|
|
18
|
+
|
|
19
|
+
`};return[n,...s,r]}else{let s=e.filter(n=>!n.images||n.images.length===0).map(n=>n.content||"").filter(n=>n.length>0).join(`
|
|
20
|
+
|
|
21
|
+
`);return s?[{type:"text",text:`
|
|
22
|
+
|
|
23
|
+
<retrieved_knowledge>
|
|
24
|
+
|
|
25
|
+
Below are expert curated knowledge that are retrieved from the knowledge base; APPLY THESE KNOWLEDGES IF THEY ARE RELEVANT TO THE TASK:
|
|
26
|
+
`},{type:"text",text:s},{type:"text",text:`
|
|
27
|
+
|
|
28
|
+
</retrieved_knowledge>
|
|
29
|
+
|
|
30
|
+
`}]:[]}}function ti(e,t=Cn){if(!t)return 0;let s=0;for(let n of e)n.images&&(s+=n.images.length);return s}function si(){let e=new Date,t=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).formatToParts(e),s=t.find(h=>h.type==="year").value,n=t.find(h=>h.type==="month").value,r=t.find(h=>h.type==="day").value,a=t.find(h=>h.type==="hour").value,i=t.find(h=>h.type==="minute").value,o=t.find(h=>h.type==="second").value,l=t.find(h=>h.type==="timeZoneName").value,d=String(e.getMilliseconds()).padStart(3,"0");return`${s}-${n}-${r} ${a}:${i}:${o}.${d} ${l}`}function ni(e){return`# Your Role
|
|
31
|
+
You are part of a end-to-end testing system that is designed to automate the testing of a website. Given an instruction in natural language, your job is to translate it into an action in the predefined actions. The instruction might not match any action in the predefined actions or might require to interact with an element that is not on the page. It's your job to detect these cases and return an empty action.
|
|
32
|
+
|
|
33
|
+
# Rules
|
|
34
|
+
## Action Selection Rules
|
|
35
|
+
- If the instruction requires a specific action, you must select that action. If no action matches the specific action, you must return an empty action so that testing system can aware of the situation.
|
|
36
|
+
- If asked to do nothing or ignore the instruction or something similar, you must select \`wait\` action of 1 second.
|
|
37
|
+
- If asked to verify something, you must select \`verify\` action.
|
|
38
|
+
- If asked to do accurate interaction, like selecting a specific chunk of text or drawing a bounding box, you must select \`perform_accurate_operation\` action.
|
|
39
|
+
- If asked to scroll, you decide if you need to \`scroll\` the page or \`scroll_on_element\`. also you need to calculate how much to scroll.
|
|
40
|
+
|
|
41
|
+
## Element Selection Rules
|
|
42
|
+
- If the instruction requires to interact with a specific element, you must select that element.
|
|
43
|
+
- If no element matches the specific element, you must return an empty action so that testing system can aware of the situation. NEVER click on alternative elements as a workaround. NEVER try to navigate to find the element (e.g. by scrolling, closing modals, clicking other buttons, or refreshing the page).
|
|
44
|
+
- Fail fast: If the exact target element is not visible on the current page, return an empty action immediately. The testing system will handle recovery.
|
|
45
|
+
- The type of the selected element doesn't have to match the target, for example, if the instruction requires to interact with an image but no image element matches, you can select a div that contains the image.
|
|
46
|
+
|
|
47
|
+
## Instruction Completion Analysis Rules
|
|
48
|
+
- Reasoning about the instruction completion is critical. You must analyze the instruction and your action to determine if your action will complete the instruction.
|
|
49
|
+
|
|
50
|
+
## Response Format Rules
|
|
51
|
+
- Respond using valid JSON format, which can be parsed by python json.loads():
|
|
52
|
+
{
|
|
53
|
+
"thought": "...", // step by step reasoning of your decision making process
|
|
54
|
+
"description": "...", // detailed description of the action to be performed. (e.g. click on the 'Submit' button to submit the form)
|
|
55
|
+
"action": {"one_action_name": {// action-specific parameter}},
|
|
56
|
+
"completes_instruction": true/false // boolean indicating whether the selected action fully performs what was asked. Set to true if the action directly executes the instruction, even if the instruction describes a purpose or goal (e.g. "scroll to find X", "click to navigate to Y"). Set to false only when the instruction explicitly requires multiple distinct actions and this action only covers part of them, or when no matching action exists (empty action).
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
Follow the rules above strictly.
|
|
60
|
+
|
|
61
|
+
# Action Space
|
|
62
|
+
${e}
|
|
63
|
+
|
|
64
|
+
# Examples
|
|
65
|
+
Example of \`verify\` action:
|
|
66
|
+
instruction: "Verify that the page title is 'Home'"
|
|
67
|
+
{
|
|
68
|
+
"thought": "I understand the instruction is to verify that the page title is 'Home'. I will use the \`verify\` action to verify the page title.", // Do not verify it yourself, just translate the instruction to the \`verify\` action
|
|
69
|
+
"description": "Verify that the page title is 'Home'",
|
|
70
|
+
"action": {"verify": {"statement": "the page title is 'Home'"}}, // the statement should be the same wording as the instruction, don't rephrase it
|
|
71
|
+
"completes_instruction": true // this action fully completes the instruction
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
Example of \`save_variable\` action:
|
|
75
|
+
instruction: "Extract and save the page title as page_title"
|
|
76
|
+
{
|
|
77
|
+
"thought": "I understand the instruction is to save the page title as page_title. The current page title is 'Home'. I will use the \`save_variable\` action to save the page title.",
|
|
78
|
+
"description": "Save the page title as variable page_title",
|
|
79
|
+
"action": {"save_variable": {"name": "page_title", "value": "Home"}}, // the value should be the same wording as the instruction, don't rephrase it
|
|
80
|
+
"completes_instruction": true // this action fully completes the instruction
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
Example of empty action when the target element is not on the page, or the instruction cannot be completed for any reason:
|
|
84
|
+
{
|
|
85
|
+
"thought": "The user wants me to click the 'Create Entry' button. However, the current page is a sign-in page and the only interactive element is the 'Sign In' button. The 'Create Entry' button is not present on the page. The previous attempt to click this button also failed. Therefore, I cannot complete the instruction and will return an empty action.",
|
|
86
|
+
"description": "Click the 'Create Entry' button.",
|
|
87
|
+
"action": {}, // empty action object to indicate the instruction cannot be completed
|
|
88
|
+
"completes_instruction": false
|
|
89
|
+
}
|
|
90
|
+
`}function ri(e){if(!e||e.length===0)return"";let t="";return e.forEach(([s,n],r)=>{t+=`(${r+1}) Description: ${s}
|
|
91
|
+
Feedback: ${n}
|
|
92
|
+
`}),`## Additional context
|
|
93
|
+
You just executed following steps in order:
|
|
94
|
+
${t}`}function ai(e,t,s,n,r,a,i=!1,o=si(),l=!1,d){let h=[],f=`
|
|
95
|
+
# Instruction
|
|
96
|
+
"${t}"
|
|
97
|
+
|
|
98
|
+
# Current webpage state
|
|
99
|
+
## Tab information:
|
|
100
|
+
${e.currentTabText}Available tabs:
|
|
101
|
+
${e.tabsText}
|
|
102
|
+
|
|
103
|
+
## Element interaction guidelines:
|
|
104
|
+
- Only use indexes that exist in the provided element list
|
|
105
|
+
- Each element has a unique index number (e.g., "[33]<button>")
|
|
106
|
+
- The bounding box and index of each element is marked on the screenshot.
|
|
107
|
+
- Elements marked with "[]Non-interactive text" are non-interactive (for context only)
|
|
108
|
+
- Elements are indented to show the structure of the element tree, with indentation level indicating depth
|
|
109
|
+
- When considering an element, also consider its children elements
|
|
110
|
+
- If an element is scrollable, it will be marked with "(SCROLLABLE)" (e.g., "[33](SCROLLABLE)<ul>"), use the \`scroll_on_element\` action to scroll on the element.
|
|
111
|
+
|
|
112
|
+
## Interactive elements from current page:
|
|
113
|
+
${e.elementsText}
|
|
114
|
+
`;if(h.push({type:"text",text:f}),i&&e.slicedScreenshotsBase64)for(let y of e.slicedScreenshotsBase64)h.push({type:"text",text:"The following images provided are sliced screenshots of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),h.push({type:"image",image:y});else a&&(h.push({type:"text",text:"The following image provided is a screenshot of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),h.push({type:"image",image:a}));if(r&&r.length>0){let y=Ln(r,l);h.push(...y)}let u="";if(u+=`
|
|
115
|
+
Current local time is ${o}.
|
|
116
|
+
`,s&&Object.keys(s).length>0){let y=[];for(let m of Object.keys(s))if(d?.has(m))y.push(` - ${m}: [SENSITIVE - value hidden]`);else{let S=s[m],k=typeof S=="string"?S:JSON.stringify(S);y.push(` - ${m}: "${k}"`)}u+=`
|
|
117
|
+
## Available Data Placeholders
|
|
118
|
+
The following placeholders are available for use in your actions:
|
|
119
|
+
${y.join(`
|
|
120
|
+
`)}
|
|
121
|
+
|
|
122
|
+
To use them, write Jinja-like template syntax: {{ placeholder_name }}
|
|
123
|
+
- Use the EXACT placeholder name as shown above
|
|
124
|
+
- Do NOT use the actual value directly
|
|
125
|
+
- The values shown are for context only to help you understand what data is available
|
|
126
|
+
- In action descriptions, describe what the placeholder represents in natural language (e.g., "Type the first user name" instead of "Type {{ firstUserName }}")
|
|
127
|
+
`}if(n&&n.length>0){let y=ri(n);u+=`
|
|
128
|
+
`+y}return u+=`
|
|
129
|
+
Based on the above information, please determine the right action to accomplish the task.
|
|
130
|
+
`,h.push({type:"text",text:u}),h}function v(e,t,s,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(e,s):r?r.value=s:t.set(e,s),s}function c(e,t,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(e):n?n.value:t.get(e)}var Mn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Mn=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function os(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var ls=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new 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 new Error(JSON.stringify(e))}catch{}}return new Error(e)},w=class extends Error{},Y=class cs extends w{constructor(t,s,n,r){super(`${cs.makeMessage(t,s,n)}`),this.status=t,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=s;let a=s;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(t,s,n){let r=s?.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,s,n,r){if(!t||!r)return new Lt({message:n,cause:ls(s)});let a=s?.error;return t===400?new Dn(t,a,n,r):t===401?new qn(t,a,n,r):t===403?new Bn(t,a,n,r):t===404?new Fn(t,a,n,r):t===409?new Un(t,a,n,r):t===422?new Wn(t,a,n,r):t===429?new Zn(t,a,n,r):t>=500?new Hn(t,a,n,r):new cs(t,a,n,r)}},se=class extends Y{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Lt=class extends Y{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},As=class extends Lt{constructor({message:e}={}){super({message:e??"Request timed out."})}},Dn=class extends Y{},qn=class extends Y{},Bn=class extends Y{},Fn=class extends Y{},Un=class extends Y{},Wn=class extends Y{},Zn=class extends Y{},Hn=class extends Y{},zn=class extends w{constructor(){super("Could not parse response content as the length limit was reached")}},Kn=class extends w{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Fe=class extends Error{constructor(e){super(e)}},ii=/^[a-z][a-z0-9+.-]*:/i,oi=e=>ii.test(e),X=e=>(X=Array.isArray,X(e)),en=X;function Jn(e){return typeof e!="object"?{}:e??{}}function li(e){if(!e)return!0;for(let t in e)return!1;return!0}function ci(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gt(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var ui=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new w(`${e} must be an integer`);if(t<0)throw new w(`${e} must be a positive integer`);return t},hi=e=>{try{return JSON.parse(e)}catch{return}},st=e=>new Promise(t=>setTimeout(t,e)),Te="6.25.0",di=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function pi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var fi=()=>{let e=pi();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Te,"X-Stainless-OS":sn(Deno.build.os),"X-Stainless-Arch":tn(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":Te,"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":Te,"X-Stainless-OS":sn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":tn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=mi();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Te,"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":Te,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function mi(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:s}of e){let n=s.exec(navigator.userAgent);if(n){let r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${r}.${a}.${i}`}}}return null}var tn=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",sn=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"),nn,gi=()=>nn??(nn=fi());function yi(){if(typeof fetch<"u")return fetch;throw new 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 Xn(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Vn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Xn({start(){},async pull(s){let{done:n,value:r}=await t.next();n?s.close():s.enqueue(r)},async cancel(){await t.return?.()}})}function Yn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let s=await t.read();return s?.done&&t.releaseLock(),s}catch(s){throw t.releaseLock(),s}},async return(){let s=t.cancel();return t.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function bi(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),s=t.cancel();t.releaseLock(),await s}var wi=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),Gn="RFC3986",Qn=e=>String(e),rn={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Qn},_i="RFC1738",us=(e,t)=>(us=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),us(e,t)),ce=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Qt=1024,vi=(e,t,s,n,r)=>{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)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Qt){let l=a.length>=Qt?a.slice(o,o+Qt):a,d=[];for(let h=0;h<l.length;++h){let f=l.charCodeAt(h);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||r===_i&&(f===40||f===41)){d[d.length]=l.charAt(h);continue}if(f<128){d[d.length]=ce[f];continue}if(f<2048){d[d.length]=ce[192|f>>6]+ce[128|f&63];continue}if(f<55296||f>=57344){d[d.length]=ce[224|f>>12]+ce[128|f>>6&63]+ce[128|f&63];continue}h+=1,f=65536+((f&1023)<<10|l.charCodeAt(h)&1023),d[d.length]=ce[240|f>>18]+ce[128|f>>12&63]+ce[128|f>>6&63]+ce[128|f&63]}i+=d.join("")}return i};function xi(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function an(e,t){if(X(e)){let s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}var er={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},tr=function(e,t){Array.prototype.push.apply(e,X(t)?t:[t])},on,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:vi,encodeValuesOnly:!1,format:Gn,formatter:Qn,indices:!1,serializeDate(e){return(on??(on=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Si(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var es={};function sr(e,t,s,n,r,a,i,o,l,d,h,f,u,y,m,S,k,I){let _=e,j=I,R=0,O=!1;for(;(j=j.get(es))!==void 0&&!O;){let $=j.get(e);if(R+=1,typeof $<"u"){if($===R)throw new RangeError("Cyclic object value");O=!0}typeof j.get(es)>"u"&&(R=0)}if(typeof d=="function"?_=d(t,_):_ instanceof Date?_=u?.(_):s==="comma"&&X(_)&&(_=an(_,function($){return $ instanceof Date?u?.($):$})),_===null){if(a)return l&&!S?l(t,D.encoder,k,"key",y):t;_=""}if(Si(_)||xi(_)){if(l){let $=S?t:l(t,D.encoder,k,"key",y);return[m?.($)+"="+m?.(l(_,D.encoder,k,"value",y))]}return[m?.(t)+"="+m?.(String(_))]}let P=[];if(typeof _>"u")return P;let N;if(s==="comma"&&X(_))S&&l&&(_=an(_,l)),N=[{value:_.length>0?_.join(",")||null:void 0}];else if(X(d))N=d;else{let $=Object.keys(_);N=h?$.sort(h):$}let W=o?String(t).replace(/\./g,"%2E"):String(t),G=n&&X(_)&&_.length===1?W+"[]":W;if(r&&X(_)&&_.length===0)return G+"[]";for(let $=0;$<N.length;++$){let Z=N[$],pe=typeof Z=="object"&&typeof Z.value<"u"?Z.value:_[Z];if(i&&pe===null)continue;let ne=f&&o?Z.replace(/\./g,"%2E"):Z,Ae=X(_)?typeof s=="function"?s(G,ne):G:G+(f?"."+ne:"["+ne+"]");I.set(e,R);let we=new WeakMap;we.set(es,I),tr(P,sr(pe,Ae,s,n,r,a,i,o,s==="comma"&&S&&X(_)?null:l,d,h,f,u,y,m,S,k,we))}return P}function Ai(e=D){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||D.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=Gn;if(typeof e.format<"u"){if(!us(rn,e.format))throw new TypeError("Unknown format option provided.");s=e.format}let n=rn[s],r=D.filter;(typeof e.filter=="function"||X(e.filter))&&(r=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in er?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=D.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:D.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:D.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?D.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:D.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:D.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:D.encodeValuesOnly,filter:r,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:D.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:D.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:D.strictNullHandling}}function ki(e,t={}){let s=e,n=Ai(t),r,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):X(n.filter)&&(a=n.filter,r=a);let i=[];if(typeof s!="object"||s===null)return"";let o=er[n.arrayFormat],l=o==="comma"&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);let d=new WeakMap;for(let u=0;u<r.length;++u){let y=r[u];n.skipNulls&&s[y]===null||tr(i,sr(s[y],y,o,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let h=i.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),h.length>0?f+h:""}function $i(e){let t=0;for(let r of e)t+=r.length;let s=new Uint8Array(t),n=0;for(let r of e)s.set(r,n),n+=r.length;return s}var ln;function ks(e){let t;return(ln??(t=new globalThis.TextEncoder,ln=t.encode.bind(t)))(e)}var cn;function un(e){let t;return(cn??(t=new globalThis.TextDecoder,cn=t.decode.bind(t)))(e)}var Q,ee,Mt=class{constructor(){Q.set(this,void 0),ee.set(this,void 0),v(this,Q,new Uint8Array,"f"),v(this,ee,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ks(e):e;v(this,Q,$i([c(this,Q,"f"),t]),"f");let s=[],n;for(;(n=Oi(c(this,Q,"f"),c(this,ee,"f")))!=null;){if(n.carriage&&c(this,ee,"f")==null){v(this,ee,n.index,"f");continue}if(c(this,ee,"f")!=null&&(n.index!==c(this,ee,"f")+1||n.carriage)){s.push(un(c(this,Q,"f").subarray(0,c(this,ee,"f")-1))),v(this,Q,c(this,Q,"f").subarray(c(this,ee,"f")),"f"),v(this,ee,null,"f");continue}let r=c(this,ee,"f")!==null?n.preceding-1:n.preceding,a=un(c(this,Q,"f").subarray(0,r));s.push(a),v(this,Q,c(this,Q,"f").subarray(n.index),"f"),v(this,ee,null,"f")}return s}flush(){return c(this,Q,"f").length?this.decode(`
|
|
131
|
+
`):[]}};Q=new WeakMap,ee=new WeakMap;Mt.NEWLINE_CHARS=new Set([`
|
|
132
|
+
`,"\r"]);Mt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Oi(e,t){for(let s=t??0;s<e.length;s++){if(e[s]===10)return{preceding:s,index:s+1,carriage:!1};if(e[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Ii(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 It={off:0,error:200,warn:300,info:400,debug:500},hn=(e,t,s)=>{if(e){if(ci(It,e))return e;B(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(It))}`)}};function Ue(){}function lt(e,t,s){return!t||It[e]>It[s]?Ue:t[e].bind(t)}var Ti={error:Ue,warn:Ue,info:Ue,debug:Ue},dn=new WeakMap;function B(e){let t=e.logger,s=e.logLevel??"off";if(!t)return Ti;let n=dn.get(t);if(n&&n[0]===s)return n[1];let r={error:lt("error",t,s),warn:lt("warn",t,s),info:lt("info",t,s),debug:lt("debug",t,s)};return dn.set(t,[s,r]),r}var _e=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,s])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":s]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),qe,et=class We{constructor(t,s,n){this.iterator=t,qe.set(this,void 0),this.controller=s,v(this,qe,n,"f")}static fromSSEResponse(t,s,n,r){let a=!1,i=n?B(n):console;async function*o(){if(a)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let l=!1;try{for await(let d of Pi(t,s))if(!l){if(d.data.startsWith("[DONE]")){l=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let h;try{h=JSON.parse(d.data)}catch(f){throw i.error("Could not parse message into JSON:",d.data),i.error("From chunk:",d.raw),f}if(h&&h.error)throw new Y(void 0,h.error,void 0,t.headers);yield r?{event:d.event,data:h}:h}else{let h;try{h=JSON.parse(d.data)}catch(f){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),f}if(d.event=="error")throw new Y(void 0,h.error,h.message,void 0);yield{event:d.event,data:h}}}l=!0}catch(d){if(os(d))return;throw d}finally{l||s.abort()}}return new We(o,s,n)}static fromReadableStream(t,s,n){let r=!1;async function*a(){let o=new Mt,l=Yn(t);for await(let d of l)for(let h of o.decode(d))yield h;for(let d of o.flush())yield d}async function*i(){if(r)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let l of a())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(os(l))return;throw l}finally{o||s.abort()}}return new We(i,s,n)}[(qe=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],s=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){let i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new We(()=>r(t),this.controller,c(this,qe,"f")),new We(()=>r(s),this.controller,c(this,qe,"f"))]}toReadableStream(){let t=this,s;return Xn({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{let{value:r,done:a}=await s.next();if(a)return n.close();let i=ks(JSON.stringify(r)+`
|
|
133
|
+
`);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){await s.return?.()}})}};async function*Pi(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");let s=new Ri,n=new Mt,r=Yn(e.body);for await(let a of Ei(r))for(let i of n.decode(a)){let o=s.decode(i);o&&(yield o)}for(let a of n.flush()){let i=s.decode(a);i&&(yield i)}}async function*Ei(e){let t=new Uint8Array;for await(let s of e){if(s==null)continue;let n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?ks(s):s,r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),t=r;let a;for(;(a=Ii(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}var Ri=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 r={event:this.event,data:this.data.join(`
|
|
134
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],r}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=ji(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ji(e,t){let s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function nr(e,t){let{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:a}=t,i=await(async()=>{if(t.options.stream)return B(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(s,t.controller,e,t.options.__synthesizeEventData);if(s.status===204)return null;if(t.options.__binaryResponse)return s;let o=s.headers.get("content-type")?.split(";")[0]?.trim();if(o?.includes("application/json")||o?.endsWith("+json")){if(s.headers.get("content-length")==="0")return;let l=await s.json();return rr(l,s)}return await s.text()})();return B(e).debug(`[${n}] response parsed`,_e({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function rr(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 Ze,ar=class ir extends Promise{constructor(t,s,n=nr){super(r=>{r(null)}),this.responsePromise=s,this.parseResponse=n,Ze.set(this,void 0),v(this,Ze,t,"f")}_thenUnwrap(t){return new ir(c(this,Ze,"f"),this.responsePromise,async(s,n)=>rr(t(await this.parseResponse(s,n),n),n.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,s]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:s,request_id:s.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(c(this,Ze,"f"),t))),this.parsedPromise}then(t,s){return this.parse().then(t,s)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Ze=new WeakMap;var ct,$s=class{constructor(e,t,s,n){ct.set(this,void 0),v(this,ct,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new w("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,ct,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ct=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ni=class extends ar{constructor(e,t,s){super(e,t,async(n,r)=>new s(n,r.response,await nr(n,r),r.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Dt=class extends $s{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends $s{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Jn(this.options.query),after:t}}:null}},Tt=class extends $s{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Jn(this.options.query),after:e}}:null}},or=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new 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 Ye(e,t,s){return or(),new File(e,t??"unknown_file",s)}function bt(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Os=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",tt=async(e,t)=>hs(e.body)?{...e,body:await lr(e.body,t)}:e,je=async(e,t)=>({...e,body:await lr(e.body,t)}),pn=new WeakMap;function Ci(e){let t=typeof e=="function"?e:e.fetch,s=pn.get(t);if(s)return s;let n=(async()=>{try{let r="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return pn.set(t,n),n}var lr=async(e,t)=>{if(!await Ci(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,r])=>ds(s,n,r))),s},cr=e=>e instanceof Blob&&"name"in e,Li=e=>typeof e=="object"&&e!==null&&(e instanceof Response||Os(e)||cr(e)),hs=e=>{if(Li(e))return!0;if(Array.isArray(e))return e.some(hs);if(e&&typeof e=="object"){for(let t in e)if(hs(e[t]))return!0}return!1},ds=async(e,t,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")e.append(t,String(s));else if(s instanceof Response)e.append(t,Ye([await s.blob()],bt(s)));else if(Os(s))e.append(t,Ye([await new Response(Vn(s)).blob()],bt(s)));else if(cr(s))e.append(t,s,bt(s));else if(Array.isArray(s))await Promise.all(s.map(n=>ds(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,r])=>ds(e,`${t}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},ur=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Mi=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&ur(e),Di=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function qi(e,t,s){if(or(),e=await e,Mi(e))return e instanceof File?e:Ye([await e.arrayBuffer()],e.name);if(Di(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ye(await ps(r),t,s)}let n=await ps(e);if(t||(t=bt(e)),!s?.type){let r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(s={...s,type:r})}return Ye(n,t,s)}async function ps(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ur(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Os(e))for await(let s of e)t.push(...await ps(s));else{let s=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${s?`; constructor: ${s}`:""}${Bi(e)}`)}return t}function Bi(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(t=>`"${t}"`).join(", ")}]`}var b=class{constructor(e){this._client=e}};function hr(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var fn=Object.freeze(Object.create(null)),Fi=(e=hr)=>function(t,...s){if(t.length===1)return t[0];let n=!1,r=[],a=t.reduce((d,h,f)=>{/[?#]/.test(h)&&(n=!0);let u=s[f],y=(n?encodeURIComponent:e)(""+u);return f!==s.length&&(u==null||typeof u=="object"&&u.toString===Object.getPrototypeOf(Object.getPrototypeOf(u.hasOwnProperty??fn)??fn)?.toString)&&(y=u+"",r.push({start:d.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),d+h+(f===s.length?"":y)},""),i=a.split(/[?#]/,1)[0],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=o.exec(i))!==null;)r.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(r.sort((d,h)=>d.start-h.start),r.length>0){let d=0,h=r.reduce((f,u)=>{let y=" ".repeat(u.start-d),m="^".repeat(u.length);return d=u.start+u.length,f+y+m},"");throw new w(`Path parameters result in path with invalid segments:
|
|
135
|
+
${r.map(f=>f.error).join(`
|
|
136
|
+
`)}
|
|
137
|
+
${a}
|
|
138
|
+
${h}`)}return a},p=Fi(hr),dr=class extends b{list(e,t={},s){return this._client.getAPIList(p`/chat/completions/${e}/messages`,C,{query:t,...s})}};function Pt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function Is(e){return e?.$brand==="auto-parseable-response-format"}function nt(e){return e?.$brand==="auto-parseable-tool"}function Ui(e,t){return!t||!pr(t)?{...e,choices:e.choices.map(s=>(fr(s.message.tool_calls),{...s,message:{...s.message,parsed:null,...s.message.tool_calls?{tool_calls:s.message.tool_calls}:void 0}}))}:Ts(e,t)}function Ts(e,t){let s=e.choices.map(n=>{if(n.finish_reason==="length")throw new zn;if(n.finish_reason==="content_filter")throw new Kn;return fr(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(r=>Zi(t,r))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Wi(t,n.message.content):null}}});return{...e,choices:s}}function Wi(e,t){return e.response_format?.type!=="json_schema"?null:e.response_format?.type==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Zi(e,t){let s=e.tools?.find(n=>Pt(n)&&n.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:nt(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}function Hi(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let s=e.tools?.find(n=>Pt(n)&&n.function?.name===t.function.name);return Pt(s)&&(nt(s)||s?.function.strict||!1)}function pr(e){return Is(e.response_format)?!0:e.tools?.some(t=>nt(t)||t.type==="function"&&t.function.strict===!0)??!1}function fr(e){for(let t of e||[])if(t.type!=="function")throw new w(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function zi(e){for(let t of e??[]){if(t.type!=="function")throw new w(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new w(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Et=e=>e?.role==="assistant",mr=e=>e?.role==="tool",fs,wt,_t,He,ze,vt,Ke,de,Je,Rt,jt,Pe,gr,Ps=class{constructor(){fs.add(this),this.controller=new AbortController,wt.set(this,void 0),_t.set(this,()=>{}),He.set(this,()=>{}),ze.set(this,void 0),vt.set(this,()=>{}),Ke.set(this,()=>{}),de.set(this,{}),Je.set(this,!1),Rt.set(this,!1),jt.set(this,!1),Pe.set(this,!1),v(this,wt,new Promise((e,t)=>{v(this,_t,e,"f"),v(this,He,t,"f")}),"f"),v(this,ze,new Promise((e,t)=>{v(this,vt,e,"f"),v(this,Ke,t,"f")}),"f"),c(this,wt,"f").catch(()=>{}),c(this,ze,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,fs,"m",gr).bind(this))},0)}_connected(){this.ended||(c(this,_t,"f").call(this),this._emit("connect"))}get ended(){return c(this,Je,"f")}get errored(){return c(this,Rt,"f")}get aborted(){return c(this,jt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,de,"f")[e]||(c(this,de,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=c(this,de,"f")[e];if(!s)return this;let n=s.findIndex(r=>r.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(c(this,de,"f")[e]||(c(this,de,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{v(this,Pe,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){v(this,Pe,!0,"f"),await c(this,ze,"f")}_emit(e,...t){if(c(this,Je,"f"))return;e==="end"&&(v(this,Je,!0,"f"),c(this,vt,"f").call(this));let s=c(this,de,"f")[e];if(s&&(c(this,de,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Pe,"f")&&!s?.length&&Promise.reject(n),c(this,He,"f").call(this,n),c(this,Ke,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Pe,"f")&&!s?.length&&Promise.reject(n),c(this,He,"f").call(this,n),c(this,Ke,"f").call(this,n),this._emit("end")}}_emitFinal(){}};wt=new WeakMap,_t=new WeakMap,He=new WeakMap,ze=new WeakMap,vt=new WeakMap,Ke=new WeakMap,de=new WeakMap,Je=new WeakMap,Rt=new WeakMap,jt=new WeakMap,Pe=new WeakMap,fs=new WeakSet,gr=function(e){if(v(this,Rt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new se),e instanceof se)return v(this,jt,!0,"f"),this._emit("abort",e);if(e instanceof w)return this._emit("error",e);if(e instanceof Error){let t=new w(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new w(String(e)))};function Ki(e){return typeof e.parse=="function"}var J,ms,Nt,gs,ys,bs,yr,br,Ji=10,wr=class extends Ps{constructor(){super(...arguments),J.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),mr(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Et(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new w("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,J,"m",ms).call(this)}async finalMessage(){return await this.done(),c(this,J,"m",Nt).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,J,"m",gs).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,J,"m",ys).call(this)}async totalUsage(){return await this.done(),c(this,J,"m",bs).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,J,"m",Nt).call(this);t&&this._emit("finalMessage",t);let s=c(this,J,"m",ms).call(this);s&&this._emit("finalContent",s);let n=c(this,J,"m",gs).call(this);n&&this._emit("finalFunctionToolCall",n);let r=c(this,J,"m",ys).call(this);r!=null&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",c(this,J,"m",bs).call(this))}async _createChatCompletion(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,J,"m",yr).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ts(r,t))}async _runChatCompletion(e,t,s){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){let n="tool",{tool_choice:r="auto",stream:a,...i}=t,o=typeof r!="string"&&r.type==="function"&&r?.function?.name,{maxChatCompletions:l=Ji}=s||{},d=t.tools.map(u=>{if(nt(u)){if(!u.$callback)throw new w("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),h={};for(let u of d)u.type==="function"&&(h[u.function.name||u.function.function.name]=u.function);let f="tools"in t?d.map(u=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<l;++u){let y=(await this._createChatCompletion(e,{...i,tool_choice:r,tools:f,messages:[...this.messages]},s)).choices[0]?.message;if(!y)throw new w("missing message in ChatCompletion response");if(!y.tool_calls?.length)return;for(let m of y.tool_calls){if(m.type!=="function")continue;let S=m.id,{name:k,arguments:I}=m.function,_=h[k];if(_){if(o&&o!==k){let P=`Invalid tool_call: ${JSON.stringify(k)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:S,content:P});continue}}else{let P=`Invalid tool_call: ${JSON.stringify(k)}. Available options are: ${Object.keys(h).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:S,content:P});continue}let j;try{j=Ki(_)?await _.parse(I):I}catch(P){let N=P instanceof Error?P.message:String(P);this._addMessage({role:n,tool_call_id:S,content:N});continue}let R=await _.function(j,this),O=c(this,J,"m",br).call(this,R);if(this._addMessage({role:n,tool_call_id:S,content:O}),o)return}}}};J=new WeakSet,ms=function(){return c(this,J,"m",Nt).call(this).content??null},Nt=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Et(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new w("stream ended without producing a ChatCompletionMessage with role=assistant")},gs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Et(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},ys=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(mr(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},bs=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},yr=function(e){if(e.n!=null&&e.n>1)throw new w("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},br=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Xi=class _r extends wr{static runTools(t,s,n){let r=new _r,a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,s,a)),r}_addMessage(t,s=!0){super._addMessage(t,s),Et(t)&&t.content&&this._emit("content",t.content)}},q={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},Vi=class extends Error{},Yi=class extends Error{};function Gi(e,t=q.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Qi(e.trim(),t)}var Qi=(e,t)=>{let s=e.length,n=0,r=u=>{throw new Vi(`${u} at position ${n}`)},a=u=>{throw new Yi(`${u} at position ${n}`)},i=()=>(f(),n>=s&&r("Unexpected end of input"),e[n]==='"'?o():e[n]==="{"?l():e[n]==="["?d():e.substring(n,n+4)==="null"||q.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||q.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||q.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||q.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||q.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||q.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):h()),o=()=>{let u=n,y=!1;for(n++;n<s&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(u,++n-Number(y)))}catch(m){a(String(m))}else if(q.STR&t)try{return JSON.parse(e.substring(u,n-Number(y))+'"')}catch{return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,f();let u={};try{for(;e[n]!=="}";){if(f(),n>=s&&q.OBJ&t)return u;let y=o();f(),n++;try{let m=i();Object.defineProperty(u,y,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(q.OBJ&t)return u;throw m}f(),e[n]===","&&n++}}catch{if(q.OBJ&t)return u;r("Expected '}' at end of object")}return n++,u},d=()=>{n++;let u=[];try{for(;e[n]!=="]";)u.push(i()),f(),e[n]===","&&n++}catch{if(q.ARR&t)return u;r("Expected ']' at end of array")}return n++,u},h=()=>{if(n===0){e==="-"&&q.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(q.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(y))}}let u=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(q.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(u,n))}catch{e.substring(u,n)==="-"&&q.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(y){a(String(y))}}},f=()=>{for(;n<s&&`
|
|
139
|
+
\r `.includes(e[n]);)n++};return i()},mn=e=>Gi(e,q.ALL^q.NUM),M,he,$e,ye,ts,ut,ss,ns,rs,ht,as,gn,vr=class ws extends wr{constructor(t){super(),M.add(this),he.set(this,void 0),$e.set(this,void 0),ye.set(this,void 0),v(this,he,t,"f"),v(this,$e,[],"f")}get currentChatCompletionSnapshot(){return c(this,ye,"f")}static fromReadableStream(t){let s=new ws(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){let r=new ws(s);return r._run(()=>r._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,s,n){super._createChatCompletion;let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,M,"m",ts).call(this);let a=await t.chat.completions.create({...s,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of a)c(this,M,"m",ss).call(this,i);if(a.controller.signal?.aborted)throw new se;return this._addChatCompletion(c(this,M,"m",ht).call(this))}async _fromReadableStream(t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,M,"m",ts).call(this),this._connected();let r=et.fromReadableStream(t,this.controller),a;for await(let i of r)a&&a!==i.id&&this._addChatCompletion(c(this,M,"m",ht).call(this)),c(this,M,"m",ss).call(this,i),a=i.id;if(r.controller.signal?.aborted)throw new se;return this._addChatCompletion(c(this,M,"m",ht).call(this))}[(he=new WeakMap,$e=new WeakMap,ye=new WeakMap,M=new WeakSet,ts=function(){this.ended||v(this,ye,void 0,"f")},ut=function(t){let s=c(this,$e,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,$e,"f")[t.index]=s,s)},ss=function(t){if(this.ended)return;let s=c(this,M,"m",gn).call(this,t);this._emit("chunk",t,s);for(let n of t.choices){let r=s.choices[n.index];n.delta.content!=null&&r.message?.role==="assistant"&&r.message?.content&&(this._emit("content",n.delta.content,r.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:r.message.content,parsed:r.message.parsed})),n.delta.refusal!=null&&r.message?.role==="assistant"&&r.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:r.message.refusal}),n.logprobs?.content!=null&&r.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:r.logprobs?.content??[]}),n.logprobs?.refusal!=null&&r.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:r.logprobs?.refusal??[]});let a=c(this,M,"m",ut).call(this,r);r.finish_reason&&(c(this,M,"m",rs).call(this,r),a.current_tool_call_index!=null&&c(this,M,"m",ns).call(this,r,a.current_tool_call_index));for(let i of n.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(c(this,M,"m",rs).call(this,r),a.current_tool_call_index!=null&&c(this,M,"m",ns).call(this,r,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of n.delta.tool_calls??[]){let o=r.message.tool_calls?.[i.index];o?.type&&(o?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:o.function?.name,index:i.index,arguments:o.function.arguments,parsed_arguments:o.function.parsed_arguments,arguments_delta:i.function?.arguments??""}):o?.type)}}},ns=function(t,s){if(c(this,M,"m",ut).call(this,t).done_tool_calls.has(s))return;let n=t.message.tool_calls?.[s];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if(n.type==="function"){let r=c(this,he,"f")?.tools?.find(a=>Pt(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:s,arguments:n.function.arguments,parsed_arguments:nt(r)?r.$parseRaw(n.function.arguments):r?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},rs=function(t){let s=c(this,M,"m",ut).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;let n=c(this,M,"m",as).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},ht=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let t=c(this,ye,"f");if(!t)throw new w("request ended without sending any chunks");return v(this,ye,void 0,"f"),v(this,$e,[],"f"),eo(t,c(this,he,"f"))},as=function(){let t=c(this,he,"f")?.response_format;return Is(t)?t:null},gn=function(t){var s,n,r,a;let i=c(this,ye,"f"),{choices:o,...l}=t;i?Object.assign(i,l):i=v(this,ye,{...l,choices:[]},"f");for(let{delta:d,finish_reason:h,index:f,logprobs:u=null,...y}of t.choices){let m=i.choices[f];if(m||(m=i.choices[f]={finish_reason:h,index:f,message:{},logprobs:u,...y}),u)if(!m.logprobs)m.logprobs=Object.assign({},u);else{let{content:O,refusal:P,...N}=u;Object.assign(m.logprobs,N),O&&((s=m.logprobs).content??(s.content=[]),m.logprobs.content.push(...O)),P&&((n=m.logprobs).refusal??(n.refusal=[]),m.logprobs.refusal.push(...P))}if(h&&(m.finish_reason=h,c(this,he,"f")&&pr(c(this,he,"f")))){if(h==="length")throw new zn;if(h==="content_filter")throw new Kn}if(Object.assign(m,y),!d)continue;let{content:S,refusal:k,function_call:I,role:_,tool_calls:j,...R}=d;if(Object.assign(m.message,R),k&&(m.message.refusal=(m.message.refusal||"")+k),_&&(m.message.role=_),I&&(m.message.function_call?(I.name&&(m.message.function_call.name=I.name),I.arguments&&((r=m.message.function_call).arguments??(r.arguments=""),m.message.function_call.arguments+=I.arguments)):m.message.function_call=I),S&&(m.message.content=(m.message.content||"")+S,!m.message.refusal&&c(this,M,"m",as).call(this)&&(m.message.parsed=mn(m.message.content))),j){m.message.tool_calls||(m.message.tool_calls=[]);for(let{index:O,id:P,type:N,function:W,...G}of j){let $=(a=m.message.tool_calls)[O]??(a[O]={});Object.assign($,G),P&&($.id=P),N&&($.type=N),W&&($.function??($.function={name:W.name??"",arguments:""})),W?.name&&($.function.name=W.name),W?.arguments&&($.function.arguments+=W.arguments,Hi(c(this,he,"f"),$)&&($.function.parsed_arguments=mn($.function.arguments)))}}}return i},Symbol.asyncIterator)](){let t=[],s=[],n=!1;return this.on("chunk",r=>{let a=s.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{n=!0;for(let r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(let a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(let a of s)a.reject(r);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((r,a)=>s.push({resolve:r,reject:a})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function eo(e,t){let{id:s,choices:n,created:r,model:a,system_fingerprint:i,...o}=e,l={...o,id:s,choices:n.map(({message:d,finish_reason:h,index:f,logprobs:u,...y})=>{if(!h)throw new w(`missing finish_reason for choice ${f}`);let{content:m=null,function_call:S,tool_calls:k,...I}=d,_=d.role;if(!_)throw new w(`missing role for choice ${f}`);if(S){let{arguments:j,name:R}=S;if(j==null)throw new w(`missing function_call.arguments for choice ${f}`);if(!R)throw new w(`missing function_call.name for choice ${f}`);return{...y,message:{content:m,function_call:{arguments:j,name:R},role:_,refusal:d.refusal??null},finish_reason:h,index:f,logprobs:u}}return k?{...y,index:f,finish_reason:h,logprobs:u,message:{...I,role:_,content:m,refusal:d.refusal??null,tool_calls:k.map((j,R)=>{let{function:O,type:P,id:N,...W}=j,{arguments:G,name:$,...Z}=O||{};if(N==null)throw new w(`missing choices[${f}].tool_calls[${R}].id
|
|
140
|
+
${dt(e)}`);if(P==null)throw new w(`missing choices[${f}].tool_calls[${R}].type
|
|
141
|
+
${dt(e)}`);if($==null)throw new w(`missing choices[${f}].tool_calls[${R}].function.name
|
|
142
|
+
${dt(e)}`);if(G==null)throw new w(`missing choices[${f}].tool_calls[${R}].function.arguments
|
|
143
|
+
${dt(e)}`);return{...W,id:N,type:P,function:{...Z,name:$,arguments:G}}})}}:{...y,message:{...I,content:m,role:_,refusal:d.refusal??null},finish_reason:h,index:f,logprobs:u}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Ui(l,t)}function dt(e){return JSON.stringify(e)}var to=class _s extends vr{static fromReadableStream(t){let s=new _s(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){let r=new _s(s),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,s,a)),r}},Es=class extends b{constructor(){super(...arguments),this.messages=new dr(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(p`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(p`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",C,{query:e,...t})}delete(e,t){return this._client.delete(p`/chat/completions/${e}`,t)}parse(e,t){return zi(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Ts(s,e))}runTools(e,t){return e.stream?to.runTools(this._client,e,t):Xi.runTools(this._client,e,t)}stream(e,t){return vr.createChatCompletion(this._client,e,t)}};Es.Messages=dr;var Rs=class extends b{constructor(){super(...arguments),this.completions=new Es(this._client)}};Rs.Completions=Es;var xr=Symbol("brand.privateNullableHeaders");function*so(e){if(!e)return;if(xr in e){let{values:n,nulls:r}=e;yield*n.entries();for(let a of r)yield[a,null];return}let t=!1,s;e instanceof Headers?s=e.entries():en(e)?s=e:(t=!0,s=Object.entries(e??{}));for(let n of s){let r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");let a=en(n[1])?n[1]:[n[1]],i=!1;for(let o of a)o!==void 0&&(t&&!i&&(i=!0,yield[r,null]),yield[r,o])}}var g=e=>{let t=new Headers,s=new Set;for(let n of e){let r=new Set;for(let[a,i]of so(n)){let o=a.toLowerCase();r.has(o)||(t.delete(a),r.add(o)),i===null?(t.delete(a),s.add(o)):(t.append(a,i),s.delete(o))}}return{[xr]:!0,values:t,nulls:s}},Sr=class extends b{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}},Ar=class extends b{create(e,t){return this._client.post("/audio/transcriptions",je({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},kr=class extends b{create(e,t){return this._client.post("/audio/translations",je({body:e,...t,__metadata:{model:e.model}},this._client))}},rt=class extends b{constructor(){super(...arguments),this.transcriptions=new Ar(this._client),this.translations=new kr(this._client),this.speech=new Sr(this._client)}};rt.Transcriptions=Ar;rt.Translations=kr;rt.Speech=Sr;var $r=class extends b{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(p`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",C,{query:e,...t})}cancel(e,t){return this._client.post(p`/batches/${e}/cancel`,t)}},Or=class extends b{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(p`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(p`/assistants/${e}`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",C,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(p`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}},Ir=class extends b{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}},Tr=class extends b{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}},qt=class extends b{constructor(){super(...arguments),this.sessions=new Ir(this._client),this.transcriptionSessions=new Tr(this._client)}};qt.Sessions=Ir;qt.TranscriptionSessions=Tr;var Pr=class extends b{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(p`/chatkit/sessions/${e}/cancel`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}},Er=class extends b{retrieve(e,t){return this._client.get(p`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Tt,{query:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(p`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,Tt,{query:t,...s,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}},Bt=class extends b{constructor(){super(...arguments),this.sessions=new Pr(this._client),this.threads=new Er(this._client)}};Bt.Sessions=Pr;Bt.Threads=Er;var Rr=class extends b{create(e,t,s){return this._client.post(p`/threads/${e}/messages`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(p`/threads/${n}/messages/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...r}=t;return this._client.post(p`/threads/${n}/messages/${e}`,{body:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(p`/threads/${e}/messages`,C,{query:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{thread_id:n}=t;return this._client.delete(p`/threads/${n}/messages/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}},jr=class extends b{retrieve(e,t,s){let{thread_id:n,run_id:r,...a}=t;return this._client.get(p`/threads/${n}/runs/${r}/steps/${e}`,{query:a,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){let{thread_id:n,...r}=t;return this._client.getAPIList(p`/threads/${n}/runs/${e}/steps`,C,{query:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}},no=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))}else{let t=atob(e),s=t.length,n=new Uint8Array(s);for(let r=0;r<s;r++)n[r]=t.charCodeAt(r);return Array.from(new Float32Array(n.buffer))}},Oe=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()},F,xe,vs,ue,xt,oe,Se,Re,ve,Ct,te,St,At,Ge,Xe,Ve,yn,bn,wn,_n,vn,xn,Sn,Qe=class extends Ps{constructor(){super(...arguments),F.add(this),vs.set(this,[]),ue.set(this,{}),xt.set(this,{}),oe.set(this,void 0),Se.set(this,void 0),Re.set(this,void 0),ve.set(this,void 0),Ct.set(this,void 0),te.set(this,void 0),St.set(this,void 0),At.set(this,void 0),Ge.set(this,void 0)}[(vs=new WeakMap,ue=new WeakMap,xt=new WeakMap,oe=new WeakMap,Se=new WeakMap,Re=new WeakMap,ve=new WeakMap,Ct=new WeakMap,te=new WeakMap,St=new WeakMap,At=new WeakMap,Ge=new WeakMap,F=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let r of t)r.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let r of t)r.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((n,r)=>t.push({resolve:n,reject:r})).then(n=>n?{value:n,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new xe;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=et.fromReadableStream(e,this.controller);for await(let r of n)c(this,F,"m",Xe).call(this,r);if(n.controller.signal?.aborted)throw new se;return this._addRun(c(this,F,"m",Ve).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){let r=new xe;return r._run(()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createToolAssistantStream(e,t,s,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));let a={...s,stream:!0},i=await e.submitToolOutputs(t,a,{...n,signal:this.controller.signal});this._connected();for await(let o of i)c(this,F,"m",Xe).call(this,o);if(i.controller.signal?.aborted)throw new se;return this._addRun(c(this,F,"m",Ve).call(this))}static createThreadAssistantStream(e,t,s){let n=new xe;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){let r=new xe;return r._run(()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return c(this,St,"f")}currentRun(){return c(this,At,"f")}currentMessageSnapshot(){return c(this,oe,"f")}currentRunStepSnapshot(){return c(this,Ge,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,ue,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,xt,"f"))}async finalRun(){if(await this.done(),!c(this,Se,"f"))throw Error("Final run was not received.");return c(this,Se,"f")}async _createThreadAssistantStream(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let r={...t,stream:!0},a=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(let i of a)c(this,F,"m",Xe).call(this,i);if(a.controller.signal?.aborted)throw new se;return this._addRun(c(this,F,"m",Ve).call(this))}async _createAssistantStream(e,t,s,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));let a={...s,stream:!0},i=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(let o of i)c(this,F,"m",Xe).call(this,o);if(i.controller.signal?.aborted)throw new se;return this._addRun(c(this,F,"m",Ve).call(this))}static accumulateDelta(e,t){for(let[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let r=e[s];if(r==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof r=="string"&&typeof n=="string")r+=n;else if(typeof r=="number"&&typeof n=="number")r+=n;else if(Gt(r)&&Gt(n))r=this.accumulateDelta(r,n);else if(Array.isArray(r)&&Array.isArray(n)){if(r.every(a=>typeof a=="string"||typeof a=="number")){r.push(...n);continue}for(let a of n){if(!Gt(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let o=r[i];o==null?r.push(a):r[i]=this.accumulateDelta(o,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${r}`);e[s]=r}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}};xe=Qe,Xe=function(e){if(!this.ended)switch(v(this,St,e,"f"),c(this,F,"m",wn).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":c(this,F,"m",Sn).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":c(this,F,"m",bn).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":c(this,F,"m",yn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Ve=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");if(!c(this,Se,"f"))throw Error("Final run has not been received");return c(this,Se,"f")},yn=function(e){let[t,s]=c(this,F,"m",vn).call(this,e,c(this,oe,"f"));v(this,oe,t,"f"),c(this,xt,"f")[t.id]=t;for(let n of s){let r=t.content[n.index];r?.type=="text"&&this._emit("textCreated",r.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 r=n.text,a=t.content[n.index];if(a&&a.type=="text")this._emit("textDelta",r,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,Re,"f")){if(c(this,ve,"f"))switch(c(this,ve,"f").type){case"text":this._emit("textDone",c(this,ve,"f").text,c(this,oe,"f"));break;case"image_file":this._emit("imageFileDone",c(this,ve,"f").image_file,c(this,oe,"f"));break}v(this,Re,n.index,"f")}v(this,ve,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Re,"f")!==void 0){let n=e.data.content[c(this,Re,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,oe,"f"));break;case"text":this._emit("textDone",n.text,c(this,oe,"f"));break}}c(this,oe,"f")&&this._emit("messageDone",e.data),v(this,oe,void 0,"f")}},bn=function(e){let t=c(this,F,"m",_n).call(this,e);switch(v(this,Ge,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let n of s.step_details.tool_calls)n.index==c(this,Ct,"f")?this._emit("toolCallDelta",n,t.step_details.tool_calls[n.index]):(c(this,te,"f")&&this._emit("toolCallDone",c(this,te,"f")),v(this,Ct,n.index,"f"),v(this,te,t.step_details.tool_calls[n.index],"f"),c(this,te,"f")&&this._emit("toolCallCreated",c(this,te,"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":v(this,Ge,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,te,"f")&&(this._emit("toolCallDone",c(this,te,"f")),v(this,te,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},wn=function(e){c(this,vs,"f").push(e),this._emit("event",e)},_n=function(e){switch(e.event){case"thread.run.step.created":return c(this,ue,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,ue,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=xe.accumulateDelta(t,s.delta);c(this,ue,"f")[e.data.id]=n}return c(this,ue,"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":c(this,ue,"f")[e.data.id]=e.data;break}if(c(this,ue,"f")[e.data.id])return c(this,ue,"f")[e.data.id];throw new Error("No snapshot available")},vn=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let r of n.delta.content)if(r.index in t.content){let a=t.content[r.index];t.content[r.index]=c(this,F,"m",xn).call(this,r,a)}else t.content[r.index]=r,s.push(r);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},xn=function(e,t){return xe.accumulateDelta(t,e)},Sn=function(e){switch(v(this,At,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":v(this,Se,e.data,"f"),c(this,te,"f")&&(this._emit("toolCallDone",c(this,te,"f")),v(this,te,void 0,"f"));break;case"thread.run.cancelling":break}};var js=class extends b{constructor(){super(...arguments),this.steps=new jr(this._client)}create(e,t,s){let{include:n,...r}=t;return this._client.post(p`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(p`/threads/${n}/runs/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...r}=t;return this._client.post(p`/threads/${n}/runs/${e}`,{body:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(p`/threads/${e}/runs`,C,{query:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{thread_id:n}=t;return this._client.post(p`/threads/${n}/runs/${e}/cancel`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return Qe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){let n=g([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:r,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(s?.pollIntervalMs)i=s.pollIntervalMs;else{let o=a.headers.get("openai-poll-after-ms");if(o){let l=parseInt(o);isNaN(l)||(i=l)}}await st(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return Qe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){let{thread_id:n,...r}=t;return this._client.post(p`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,s){let n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return Qe.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};js.Steps=jr;var Ft=class extends b{constructor(){super(...arguments),this.runs=new js(this._client),this.messages=new Rr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(p`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(p`/threads/${e}`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(p`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Qe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ft.Runs=js;Ft.Messages=Rr;var Ne=class extends b{constructor(){super(...arguments),this.realtime=new qt(this._client),this.chatkit=new Bt(this._client),this.assistants=new Or(this._client),this.threads=new Ft(this._client)}};Ne.Realtime=qt;Ne.ChatKit=Bt;Ne.Assistants=Or;Ne.Threads=Ft;var Nr=class extends b{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}},Cr=class extends b{retrieve(e,t,s){let{container_id:n}=t;return this._client.get(p`/containers/${n}/files/${e}/content`,{...s,headers:g([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}},Ns=class extends b{constructor(){super(...arguments),this.content=new Cr(this._client)}create(e,t,s){return this._client.post(p`/containers/${e}/files`,tt({body:t,...s},this._client))}retrieve(e,t,s){let{container_id:n}=t;return this._client.get(p`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(p`/containers/${e}/files`,C,{query:t,...s})}delete(e,t,s){let{container_id:n}=t;return this._client.delete(p`/containers/${n}/files/${e}`,{...s,headers:g([{Accept:"*/*"},s?.headers])})}};Ns.Content=Cr;var Cs=class extends b{constructor(){super(...arguments),this.files=new Ns(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(p`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",C,{query:e,...t})}delete(e,t){return this._client.delete(p`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Cs.Files=Ns;var Lr=class extends b{create(e,t,s){let{include:n,...r}=t;return this._client.post(p`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){let{conversation_id:n,...r}=t;return this._client.get(p`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(p`/conversations/${e}/items`,Tt,{query:t,...s})}delete(e,t,s){let{conversation_id:n}=t;return this._client.delete(p`/conversations/${n}/items/${e}`,s)}},Ls=class extends b{constructor(){super(...arguments),this.items=new Lr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(p`/conversations/${e}`,t)}update(e,t,s){return this._client.post(p`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(p`/conversations/${e}`,t)}};Ls.Items=Lr;var Mr=class extends b{create(e,t){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&B(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(B(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let o=i.embedding;i.embedding=no(o)}),a)))}},Dr=class extends b{retrieve(e,t,s){let{eval_id:n,run_id:r}=t;return this._client.get(p`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){let{eval_id:n,...r}=t;return this._client.getAPIList(p`/evals/${n}/runs/${e}/output_items`,C,{query:r,...s})}},Ms=class extends b{constructor(){super(...arguments),this.outputItems=new Dr(this._client)}create(e,t,s){return this._client.post(p`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){let{eval_id:n}=t;return this._client.get(p`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(p`/evals/${e}/runs`,C,{query:t,...s})}delete(e,t,s){let{eval_id:n}=t;return this._client.delete(p`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){let{eval_id:n}=t;return this._client.post(p`/evals/${n}/runs/${e}`,s)}};Ms.OutputItems=Dr;var Ds=class extends b{constructor(){super(...arguments),this.runs=new Ms(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(p`/evals/${e}`,t)}update(e,t,s){return this._client.post(p`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",C,{query:e,...t})}delete(e,t){return this._client.delete(p`/evals/${e}`,t)}};Ds.Runs=Ms;var qr=class extends b{create(e,t){return this._client.post("/files",je({body:e,...t},this._client))}retrieve(e,t){return this._client.get(p`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",C,{query:e,...t})}delete(e,t){return this._client.delete(p`/files/${e}`,t)}content(e,t){return this._client.get(p`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),r=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await st(t),a=await this.retrieve(e),Date.now()-r>s)throw new As({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}},Br=class extends b{},Fr=class extends b{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}},qs=class extends b{constructor(){super(...arguments),this.graders=new Fr(this._client)}};qs.Graders=Fr;var Ur=class extends b{create(e,t,s){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,Dt,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(p`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}},Bs=class extends b{constructor(){super(...arguments),this.permissions=new Ur(this._client)}};Bs.Permissions=Ur;var Wr=class extends b{list(e,t={},s){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,C,{query:t,...s})}},Fs=class extends b{constructor(){super(...arguments),this.checkpoints=new Wr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(p`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...t})}cancel(e,t){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,C,{query:t,...s})}pause(e,t){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,t)}};Fs.Checkpoints=Wr;var Ce=class extends b{constructor(){super(...arguments),this.methods=new Br(this._client),this.jobs=new Fs(this._client),this.checkpoints=new Bs(this._client),this.alpha=new qs(this._client)}};Ce.Methods=Br;Ce.Jobs=Fs;Ce.Checkpoints=Bs;Ce.Alpha=qs;var Zr=class extends b{},Us=class extends b{constructor(){super(...arguments),this.graderModels=new Zr(this._client)}};Us.GraderModels=Zr;var Hr=class extends b{createVariation(e,t){return this._client.post("/images/variations",je({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",je({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}},zr=class extends b{retrieve(e,t){return this._client.get(p`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Dt,e)}delete(e,t){return this._client.delete(p`/models/${e}`,t)}},Kr=class extends b{create(e,t){return this._client.post("/moderations",{body:e,...t})}},Jr=class extends b{accept(e,t,s){return this._client.post(p`/realtime/calls/${e}/accept`,{body:t,...s,headers:g([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(p`/realtime/calls/${e}/hangup`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(p`/realtime/calls/${e}/refer`,{body:t,...s,headers:g([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(p`/realtime/calls/${e}/reject`,{body:t,...s,headers:g([{Accept:"*/*"},s?.headers])})}},Xr=class extends b{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}},Ut=class extends b{constructor(){super(...arguments),this.clientSecrets=new Xr(this._client),this.calls=new Jr(this._client)}};Ut.ClientSecrets=Xr;Ut.Calls=Jr;function ro(e,t){return!t||!io(t)?{...e,output_parsed:null,output:e.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)}:Vr(e,t)}function Vr(e,t){let s=e.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:co(t,r)};if(r.type==="message"){let a=r.content.map(i=>i.type==="output_text"?{...i,parsed:ao(t,i.text)}:i);return{...r,content:a}}return r}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||xs(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let r of n.output)if(r.type==="message"){for(let a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function ao(e,t){return e.text?.format?.type!=="json_schema"?null:"$parseRaw"in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t)}function io(e){return!!Is(e.text?.format)}function oo(e){return e?.$brand==="auto-parseable-tool"}function lo(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function co(e,t){let s=lo(e.tools??[],t.name);return{...t,...t,parsed_arguments:oo(s)?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null}}function xs(e){let t=[];for(let s of e.output)if(s.type==="message")for(let n of s.content)n.type==="output_text"&&t.push(n.text);e.output_text=t.join("")}var Ie,pt,be,ft,An,kn,$n,On,uo=class Yr extends Ps{constructor(t){super(),Ie.add(this),pt.set(this,void 0),be.set(this,void 0),ft.set(this,void 0),v(this,pt,t,"f")}static createResponse(t,s,n){let r=new Yr(s);return r._run(()=>r._createOrRetrieveResponse(t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(t,s,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,Ie,"m",An).call(this);let a,i=null;"response_id"in s?(a=await t.responses.retrieve(s.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=s.starting_after??null):a=await t.responses.create({...s,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let o of a)c(this,Ie,"m",kn).call(this,o,i);if(a.controller.signal?.aborted)throw new se;return c(this,Ie,"m",$n).call(this)}[(pt=new WeakMap,be=new WeakMap,ft=new WeakMap,Ie=new WeakSet,An=function(){this.ended||v(this,be,void 0,"f")},kn=function(t,s){if(this.ended)return;let n=(a,i)=>{(s==null||i.sequence_number>s)&&this._emit(a,i)},r=c(this,Ie,"m",On).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let a=r.output[t.output_index];if(!a)throw new w(`missing output at index ${t.output_index}`);if(a.type==="message"){let i=a.content[t.content_index];if(!i)throw new w(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new w(`expected content to be 'output_text', got ${i.type}`);n("response.output_text.delta",{...t,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=r.output[t.output_index];if(!a)throw new w(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},$n=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");let t=c(this,be,"f");if(!t)throw new w("request ended without sending any events");v(this,be,void 0,"f");let s=ho(t,c(this,pt,"f"));return v(this,ft,s,"f"),s},On=function(t){let s=c(this,be,"f");if(!s){if(t.type!=="response.created")throw new w(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=v(this,be,t.response,"f"),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{let n=s.output[t.output_index];if(!n)throw new w(`missing output at index ${t.output_index}`);let r=n.type,a=t.part;r==="message"&&a.type!=="reasoning_text"?n.content.push(a):r==="reasoning"&&a.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(a));break}case"response.output_text.delta":{let n=s.output[t.output_index];if(!n)throw new w(`missing output at index ${t.output_index}`);if(n.type==="message"){let r=n.content[t.content_index];if(!r)throw new w(`missing content at index ${t.content_index}`);if(r.type!=="output_text")throw new w(`expected content to be 'output_text', got ${r.type}`);r.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=s.output[t.output_index];if(!n)throw new w(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=s.output[t.output_index];if(!n)throw new w(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let r=n.content?.[t.content_index];if(!r)throw new w(`missing content at index ${t.content_index}`);if(r.type!=="reasoning_text")throw new w(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=t.delta}break}case"response.completed":{v(this,be,t.response,"f");break}}return s},Symbol.asyncIterator)](){let t=[],s=[],n=!1;return this.on("event",r=>{let a=s.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{n=!0;for(let r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(let a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(let a of s)a.reject(r);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((r,a)=>s.push({resolve:r,reject:a})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let t=c(this,ft,"f");if(!t)throw new w("stream ended without producing a ChatCompletion");return t}};function ho(e,t){return ro(e,t)}var Gr=class extends b{list(e,t={},s){return this._client.getAPIList(p`/responses/${e}/input_items`,C,{query:t,...s})}},Qr=class extends b{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}},Wt=class extends b{constructor(){super(...arguments),this.inputItems=new Gr(this._client),this.inputTokens=new Qr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&xs(s),s))}retrieve(e,t={},s){return this._client.get(p`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&xs(n),n))}delete(e,t){return this._client.delete(p`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Vr(s,e))}stream(e,t){return uo.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(p`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};Wt.InputItems=Gr;Wt.InputTokens=Qr;var ea=class extends b{retrieve(e,t){return this._client.get(p`/skills/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}},ta=class extends b{retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(p`/skills/${n}/versions/${e}/content`,{...s,headers:g([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}},Ws=class extends b{constructor(){super(...arguments),this.content=new ta(this._client)}create(e,t={},s){return this._client.post(p`/skills/${e}/versions`,tt({body:t,...s},this._client))}retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(p`/skills/${n}/versions/${e}`,s)}list(e,t={},s){return this._client.getAPIList(p`/skills/${e}/versions`,C,{query:t,...s})}delete(e,t,s){let{skill_id:n}=t;return this._client.delete(p`/skills/${n}/versions/${e}`,s)}};Ws.Content=ta;var Zt=class extends b{constructor(){super(...arguments),this.content=new ea(this._client),this.versions=new Ws(this._client)}create(e={},t){return this._client.post("/skills",tt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(p`/skills/${e}`,t)}update(e,t,s){return this._client.post(p`/skills/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/skills",C,{query:e,...t})}delete(e,t){return this._client.delete(p`/skills/${e}`,t)}};Zt.Content=ea;Zt.Versions=Ws;var sa=class extends b{create(e,t,s){return this._client.post(p`/uploads/${e}/parts`,je({body:t,...s},this._client))}},Zs=class extends b{constructor(){super(...arguments),this.parts=new sa(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(p`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(p`/uploads/${e}/complete`,{body:t,...s})}};Zs.Parts=sa;var po=async e=>{let t=await Promise.allSettled(e),s=t.filter(r=>r.status==="rejected");if(s.length){for(let r of s)console.error(r.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}let n=[];for(let r of t)r.status==="fulfilled"&&n.push(r.value);return n},na=class extends b{create(e,t,s){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(p`/vector_stores/${n}/file_batches/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{vector_store_id:n}=t;return this._client.post(p`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){let{vector_store_id:n,...r}=t;return this._client.getAPIList(p`/vector_stores/${n}/file_batches/${e}/files`,C,{query:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){let n=g([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:r,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let i=5e3;if(s?.pollIntervalMs)i=s.pollIntervalMs;else{let o=a.headers.get("openai-poll-after-ms");if(o){let l=parseInt(o);isNaN(l)||(i=l)}}await st(i);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let r=n?.maxConcurrency??5,a=Math.min(r,t.length),i=this._client,o=t.values(),l=[...s];async function d(f){for(let u of f){let y=await i.files.create({file:u,purpose:"assistants"},n);l.push(y.id)}}let h=Array(a).fill(o).map(d);return await po(h),await this.createAndPoll(e,{file_ids:l})}},ra=class extends b{create(e,t,s){return this._client.post(p`/vector_stores/${e}/files`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(p`/vector_stores/${n}/files/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{vector_store_id:n,...r}=t;return this._client.post(p`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(p`/vector_stores/${e}/files`,C,{query:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{vector_store_id:n}=t;return this._client.delete(p`/vector_stores/${n}/files/${e}`,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){let n=g([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),a=r.data;switch(a.status){case"in_progress":let i=5e3;if(s?.pollIntervalMs)i=s.pollIntervalMs;else{let o=r.response.headers.get("openai-poll-after-ms");if(o){let l=parseInt(o);isNaN(l)||(i=l)}}await st(i);break;case"failed":case"completed":return a}}}async upload(e,t,s){let n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){let n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){let{vector_store_id:n}=t;return this._client.getAPIList(p`/vector_stores/${n}/files/${e}/content`,Dt,{...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}},Ht=class extends b{constructor(){super(...arguments),this.files=new ra(this._client),this.fileBatches=new na(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(p`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(p`/vector_stores/${e}`,{body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",C,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(p`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(p`/vector_stores/${e}/search`,Dt,{body:t,method:"post",...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}};Ht.Files=ra;Ht.FileBatches=na;var aa=class extends b{create(e,t){return this._client.post("/videos",tt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(p`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Tt,{query:e,...t})}delete(e,t){return this._client.delete(p`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(p`/videos/${e}/content`,{query:t,...s,headers:g([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(p`/videos/${e}/remix`,tt({body:t,...s},this._client))}},Ee,ia,kt,oa=class extends b{constructor(){super(...arguments),Ee.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Ee,"m",ia).call(this,s);let r=g([t]).values,a=c(this,Ee,"m",kt).call(this,r,"webhook-signature"),i=c(this,Ee,"m",kt).call(this,r,"webhook-timestamp"),o=c(this,Ee,"m",kt).call(this,r,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Fe("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>n)throw new Fe("Webhook timestamp is too old");if(l>d+n)throw new Fe("Webhook timestamp is too new");let h=a.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),f=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),u=o?`${o}.${i}.${e}`:`${i}.${e}`,y=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let m of h)try{let S=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",y,S,new TextEncoder().encode(u)))return}catch{continue}throw new Fe("The given webhook signature does not match the expected signature")}};Ee=new WeakSet,ia=function(e){if(typeof e!="string"||e.length===0)throw new 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")},kt=function(e,t){if(!e)throw new Error("Headers are required");let s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};var Ss,Hs,$t,la,x=class{constructor({baseURL:e=Oe("OPENAI_BASE_URL"),apiKey:t=Oe("OPENAI_API_KEY"),organization:s=Oe("OPENAI_ORG_ID")??null,project:n=Oe("OPENAI_PROJECT_ID")??null,webhookSecret:r=Oe("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Ss.add(this),$t.set(this,void 0),this.completions=new Nr(this),this.chat=new Rs(this),this.embeddings=new Mr(this),this.files=new qr(this),this.images=new Hr(this),this.audio=new rt(this),this.moderations=new Kr(this),this.models=new zr(this),this.fineTuning=new Ce(this),this.graders=new Us(this),this.vectorStores=new Ht(this),this.webhooks=new oa(this),this.beta=new Ne(this),this.batches=new $r(this),this.uploads=new Zs(this),this.responses=new Wt(this),this.realtime=new Ut(this),this.conversations=new Ls(this),this.evals=new Ds(this),this.containers=new Cs(this),this.skills=new Zt(this),this.videos=new aa(this),t===void 0)throw new w("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let i={apiKey:t,organization:s,project:n,webhookSecret:r,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&di())throw new w(`It looks like you're running in a browser-like environment.
|
|
144
|
+
|
|
145
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
146
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
147
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
148
|
+
|
|
149
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
150
|
+
|
|
151
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
152
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Hs.DEFAULT_TIMEOUT,this.logger=i.logger??console;let o="warn";this.logLevel=o,this.logLevel=hn(i.logLevel,"ClientOptions.logLevel",this)??hn(Oe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??yi(),v(this,$t,wi,"f"),this._options=i,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=s,this.project=n,this.webhookSecret=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ki(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Te}`}defaultIdempotencyKey(){return`stainless-node-retry-${Mn()}`}makeStatusError(e,t,s,n){return Y.generate(e,t,s,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof w?s:new w(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new w(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){let n=!c(this,Ss,"m",la).call(this)&&s||this.baseURL,r=oi(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return li(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}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,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ar(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){let n=await e,r=n.maxRetries??this.maxRetries;t==null&&(t=r),await this.prepareOptions(n);let{req:a,url:i,timeout:o}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(a,{url:i,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(B(this).debug(`[${l}] sending request`,_e({retryOfRequestLogID:s,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new se;let f=new AbortController,u=await this.fetchWithTimeout(i,a,o,f).catch(ls),y=Date.now();if(u instanceof globalThis.Error){let k=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new se;let I=os(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return B(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${k}`),B(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${k})`,_e({retryOfRequestLogID:s,url:i,durationMs:y-h,message:u.message})),this.retryRequest(n,t,s??l);throw B(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),B(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,_e({retryOfRequestLogID:s,url:i,durationMs:y-h,message:u.message})),I?new As:new Lt({cause:u})}let m=[...u.headers.entries()].filter(([k])=>k==="x-request-id").map(([k,I])=>", "+k+": "+JSON.stringify(I)).join(""),S=`[${l}${d}${m}] ${a.method} ${i} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${y-h}ms`;if(!u.ok){let k=await this.shouldRetry(u);if(t&&k){let O=`retrying, ${t} attempts remaining`;return await bi(u.body),B(this).info(`${S} - ${O}`),B(this).debug(`[${l}] response error (${O})`,_e({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:y-h})),this.retryRequest(n,t,s??l,u.headers)}let I=k?"error; no more retries left":"error; not retryable";B(this).info(`${S} - ${I}`);let _=await u.text().catch(O=>ls(O).message),j=hi(_),R=j?void 0:_;throw B(this).debug(`[${l}] response error (${I})`,_e({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:R,durationMs:Date.now()-h})),this.makeStatusError(u.status,j,R,u.headers)}return B(this).info(S),B(this).debug(`[${l}] response start`,_e({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:y-h})),{response:u,options:n,controller:f,requestLogID:l,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,t){let s=this.makeRequest(t,null,void 0);return new Ni(this,s,e)}async fetchWithTimeout(e,t,s,n){let{signal:r,method:a,...i}=t||{},o=this._makeAbort(n);r&&r.addEventListener("abort",o,{once:!0});let l=setTimeout(o,s),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,h={signal:n.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(h.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(l)}}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,s,n){let r,a=n?.get("retry-after-ms");if(a){let o=parseFloat(a);Number.isNaN(o)||(r=o)}let i=n?.get("retry-after");if(i&&!r){let o=parseFloat(i);Number.isNaN(o)?r=Date.parse(i)-Date.now():r=o*1e3}if(!(r&&0<=r&&r<60*1e3)){let o=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,o)}return await st(r),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,n=Math.min(.5*Math.pow(2,s),8),r=1-Math.random()*.25;return n*r*1e3}async buildRequest(e,{retryCount:t=0}={}){let s={...e},{method:n,path:r,query:a,defaultBaseURL:i}=s,o=this.buildURL(r,a,i);"timeout"in s&&ui("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:l,body:d}=this.buildBody({options:s}),h=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t});return{req:{method:n,headers:h,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...s.fetchOptions??{}},url:o,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let r={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);let a=g([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...gi(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Vn(e)}:typeof e=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:c(this,$t,"f").call(this,{body:e,headers:s})}};Hs=x,$t=new WeakMap,Ss=new WeakSet,la=function(){return this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=Hs;x.DEFAULT_TIMEOUT=6e5;x.OpenAIError=w;x.APIError=Y;x.APIConnectionError=Lt;x.APIConnectionTimeoutError=As;x.APIUserAbortError=se;x.NotFoundError=Fn;x.ConflictError=Un;x.RateLimitError=Zn;x.BadRequestError=Dn;x.AuthenticationError=qn;x.InternalServerError=Hn;x.PermissionDeniedError=Bn;x.UnprocessableEntityError=Wn;x.InvalidWebhookSignatureError=Fe;x.toFile=qi;x.Completions=Nr;x.Chat=Rs;x.Embeddings=Mr;x.Files=qr;x.Images=Hr;x.Audio=rt;x.Moderations=Kr;x.Models=zr;x.FineTuning=Ce;x.Graders=Us;x.VectorStores=Ht;x.Webhooks=oa;x.Beta=Ne;x.Batches=$r;x.Uploads=Zs;x.Responses=Wt;x.Realtime=Ut;x.Conversations=Ls;x.Evals=Ds;x.Containers=Cs;x.Skills=Zt;x.Videos=aa;async function fo(e,t,s){await e.evaluate(()=>{let h=document.getElementById("playwright-highlight-container");h&&h.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(f=>f()),window._highlightCleanupFunctions=[])});let n=await e.screenshot({type:"png",fullPage:!1}),{default:r}=await import("sharp"),a=r(n),i=await a.metadata(),o=i.width||0,l=i.height||0;le.log(`Screenshot actual dimensions: ${o}x${l}, viewport: ${t}x${s}`);let d;return o!==t||l!==s?(le.log(`Resizing screenshot from ${o}x${l} to ${t}x${s}`),d=await a.resize(t,s).png().toBuffer()):d=n,d.toString("base64")}async function is(e,t,s){let n=await e.evaluateHandle(l=>document.elementFromPoint(l.x,l.y),{x:t,y:s});if(!n)throw new Error(`No element found at (${t}, ${s})`);let r=n.asElement();if(!r)throw await n.dispose(),new Error(`No element found at (${t}, ${s})`);let a=await r.boundingBox();if(!a)throw await n.dispose(),new Error("Element has no bounding box");let i=t-(a.x+a.width/2),o=s-(a.y+a.height/2);return{relative_x:i,relative_y:o,element:r}}async function mo(e,t){return t?{xpath:void 0,locator:(t?await Xs(e,t):null)||void 0,frame_path:[]}:{xpath:void 0,locator:void 0,frame_path:[]}}async function go(e,t){let s=null,n=null;switch(t.type){case"click":{let a=t.button==="right"?"right_click_by_coordinates":"click_by_coordinates";if(t.x===void 0||t.y===void 0)break;let i=await is(e,t.x,t.y);s={action_name:a,kwargs:{relative_x:i.relative_x,relative_y:i.relative_y}},n=i.element;break}case"double_click":{if(t.x===void 0||t.y===void 0)break;let a=await is(e,t.x,t.y);s={action_name:"double_click_by_coordinates",kwargs:{relative_x:a.relative_x,relative_y:a.relative_y}},n=a.element;break}case"drag":{if(!t.path||t.path.length<2)break;let a=t.path[0].x,i=t.path[0].y,o=t.path[1].x,l=t.path[1].y,d=await is(e,a,i);s={action_name:"drag_drop",kwargs:{relative_x:d.relative_x,relative_y:d.relative_y,delta_x:o-a,delta_y:l-i}},n=d.element;break}}let r=await mo(e,n);return{action_data:s,locatorInfo:r}}async function ca(e,t,s={}){try{let{page:n}=t,r=n.viewportSize();if(!r)return{status:"error",error:"Viewport size not available"};let a=r.width,i=r.height;le.log(`Viewport size: ${a}x${i}`);let o=await fo(n,a,i),l=Js().env?.OPENAI_API_KEY;if(!l)return{status:"error",error:"OpenAI API key not found. Set OPENAI_API_KEY environment variable or configure via SDK config."};let d=new x({apiKey:l});le.log("Sending request to OpenAI CUA...");let h=[{role:"user",content:[{type:"input_text",text:`
|
|
153
|
+
You will be given an action to execute and screenshot of the current screen.
|
|
154
|
+
Output one computer_call object that will accomplish this action.
|
|
155
|
+
Action: ${e}
|
|
156
|
+
`},{type:"input_image",detail:"auto",image_url:`data:image/png;base64,${o}`}]}],f=await d.responses.create({model:"computer-use-preview",tools:[{type:"computer_use_preview",display_width:a,display_height:i,environment:"browser"}],input:h,truncation:"auto",temperature:.1});le.log("Received response from OpenAI CUA");let u=f.output.filter(k=>k.type==="computer_call")[0]??null;if(!u)return{status:"error",reasoning:f.output_text||""||"Invalid action generation response",error:"No computer_call action generated"};let y=u.action;le.log(`Generated action: ${JSON.stringify(y)}`);let{action_data:m,locatorInfo:S}=await go(n,y);return m?{status:"success",actionEntity:{action_description:e,action_data:m,locator:S.locator||void 0,xpath:S.xpath||void 0,frame_path:S.frame_path},reasoning:"Action generated successfully using pure vision mode",goalAccomplished:!0}:{status:"error",error:"Failed to map action to ActionDataEntity"}}catch(n){return le.error("Error generating CUA action",n),{status:"error",error:n.message||"Failed to generate action with pure vision"}}}function ua(e,t){return e?{prompt_tokens:e.promptTokens||e.inputTokens||0,completion_tokens:e.completionTokens||e.outputTokens||0,total_tokens:e.totalTokens||0,model:t}:null}async function yo(e){let t=e.context().pages(),s=null,n=[];for(let a=0;a<t.length;a++){let i=t[a];i===e&&(s=a);let o="(title unavailable)";try{o=await Promise.race([i.title(),new Promise((d,h)=>setTimeout(()=>h(new Error("timeout")),1e3))])}catch{}let l=`Tab ${a}: ${i.url()}`;o&&(l+=` - ${o.slice(0,50)}`),n.push(l)}let r=n.length>0?n.join(`
|
|
157
|
+
`):"";return{currentTabText:s!==null?`Current tab: ${s}
|
|
158
|
+
`:"",tabsText:r}}async function bo(e,t){let{currentTabText:s,tabsText:n}=await yo(e);return{elementsText:t,currentUrl:e.url(),currentTitle:await e.title(),currentTabText:s,tabsText:n}}async function ha(e,t){let{page:s,domService:n,agentServices:r}=e,a=typeof t=="boolean"?{useCleanScreenshot:t}:t||{},i=r.getInteractiveClassNames(),o=r.getIframeFallbackDomains(),{domState:l,screenshotBase64:d,slicedScreenshotsBase64:h}=await n.getClickableElementsWithScreenshot(s,{interactiveClassNames:i,playwrightFrameFallbackDomains:o,useCleanScreenshot:a.useCleanScreenshot,useSlicedScreenshots:a.useSlicedScreenshots,resizeSlicedScreenshots:a.resizeSlicedScreenshots,useAccessibilityTree:a.useAccessibilityTree,actionIntent:a.actionIntent}),f=l.elementTree.clickableElementsToString(),u=await bo(s,f);return h&&(u.slicedScreenshotsBase64=h),{domTree:f,screenshotBase64:d,slicedScreenshotsBase64:h,domState:l,pageContext:u}}function wo(e){let t=e.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(s=>s.test(t))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(s=>s.test(t))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(s=>s.test(t))?"click":"all"}function _o(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}function vo(e){return e.map(t=>({role:t.role,content:Array.isArray(t.content)?t.content.map(s=>{if(s.type==="image"){let n=s.image,r=_o(n);if(r)return{type:"image",file:r};let a=typeof n=="string"?n:"";return{type:"image",file:a.startsWith("data:")?a:`data:image/png;base64,${a}`}}return{type:"text",text:s.text}}):t.content}))}async function xo(e,t,s={}){let{page:n,agentServices:r}=t,a=r.getModel(),i=s.temperature??0,o=r.retrieveKnowledges(e).catch(U=>(le.log(`Failed to retrieve knowledges: ${U.message}`),[])),l=r.isSlicedScreenshotsEnabled(),d=r.isResizeSlicedScreenshotsEnabled(),h=r.isKnowledgeImagesEnabled(),f=r.isAccessibilityTreeEnabled(),u=r.isActionIntentFilteringEnabled(),y=u?wo(e):"all";u&&y!=="all"&&le.log(`Action intent filtering: detected '${y}' intent from statement`);let{screenshotBase64:m,domState:S,pageContext:k}=await ha(t,{useSlicedScreenshots:l,resizeSlicedScreenshots:d,useAccessibilityTree:f,actionIntent:y});t.domState=S;let I=new Ga(Me).getToolDefinitions().map(U=>{let ke=U.function;return`${ke.name}: ${ke.description}
|
|
159
|
+
Parameters: ${JSON.stringify(ke.parameters,null,2)}`}).join(`
|
|
160
|
+
|
|
161
|
+
`),_=ni(I),j=await o,R=ai(k,e,t.variables,t.executionHistory,j.length>0?j:void 0,m,l,void 0,h,t.sensitiveKeys),O=[];s.chatHistory&&s.chatHistory.length>0&&s.chatHistory.forEach(U=>{U.role==="user"?O.push({role:"user",content:U.content}):U.role==="assistant"&&O.push({role:"assistant",content:U.content})}),O.push({role:"user",content:R});let P=vo(O),N=Me.buildActionUnionSchema(),W=mt.object({thought:mt.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:mt.string().describe("Detailed description of the action to be performed").optional().default(""),action:N,completes_instruction:mt.boolean().describe("Whether this action completes the given instruction").optional().default(!1)}),G=Array.isArray(R)?R.filter(U=>U.type==="image").length:0,$=Jt(a,G),Z=await ot({model:Kt(a),system:_,messages:O,temperature:i,output:it.object({schema:W}),providerOptions:$}),pe=Z.reasoningText;zt.info(`Action Generation Reasoning: ${pe}`);let ne=Z.output,Ae=JSON.stringify(ne,null,2);zt.info(`Generate Action Raw Output: ${Ae}`);let we=[],Le=ua(Z.usage,a);Le&&we.push(Le);let fe={systemPrompt:_,userPrompt:P,rawLlmResponse:Ae,tokenUsages:we},me=ne.thought||"",ge=ne.description||"",L=ne.action||{},H=ne.completes_instruction||!1;if(!L||Object.keys(L).length===0)return{status:"error",reasoning:me||ge||"No action generated",goalAccomplished:H,error:"Agent did not generate any action",debugInfo:fe};let z=Object.keys(L)[0];if(z==="done")return{status:"error",reasoning:me||ge||"Task marked as done",goalAccomplished:H,error:"Agent indicated task is done without generating an action",debugInfo:fe};if(z==="perform_accurate_operation")return await ca(e,t,s);if(!H){let U="Can't complete the instruction in one action";return{status:"error",reasoning:me||ge||U,goalAccomplished:!1,error:U,debugInfo:fe}}let re=L[z]||{},zs={};if(typeof re.element_index=="number"){let U=re.element_index;if(U<0)return{status:"error",reasoning:me||ge||"No action generated",goalAccomplished:H,error:"Agent did not generate any action",debugInfo:fe};let ke=S.selectorMap.get(U);ke&&(zs=await Vs(n,ke))}let Ks=ge;return z==="verify"&&(Ks=e,re.statement=e),{status:"success",actionEntity:{...zs,action_description:Ks||me||`${z}(${JSON.stringify(re)})`,action_data:{action_name:z,kwargs:re}},reasoning:me||ge,goalAccomplished:H,debugInfo:fe}}function So(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}var Ao=gt.object({screenshotDescription:gt.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
|
|
162
|
+
and a description of their location: formatting example: [12] A red button with text "Submit", next to [11]
|
|
163
|
+
[45] A modal dialog titled "Confirmation",
|
|
164
|
+
in the center of the screen`),explanation:gt.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:gt.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")});async function da(e,t,s={}){return s.usePureVision?ca(e,t,s):xo(e,t,s)}function ko(){let e=new Date,t=e.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),s=e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:t,timeString:s}}function $o(){return`# Role
|
|
165
|
+
You are an experienced QA person for web applications.
|
|
166
|
+
You are tasked to verify the validity of a given statement based on the screenshot and element tree of a web page.
|
|
167
|
+
`}async function Oo(e,t,s={}){let{page:n,executionHistory:r}=t,a=t.agentServices.getModel();try{let i=t.agentServices.isSlicedScreenshotsEnabled(),o=t.agentServices.isResizeSlicedScreenshotsEnabled(),l=t.agentServices.isKnowledgeImagesEnabled(),d=t.agentServices.isAccessibilityTreeEnabled(),{domTree:h,screenshotBase64:f,slicedScreenshotsBase64:u,domState:y,pageContext:m}=await ha(t,{useCleanScreenshot:s.useCleanScreenshotForAssertion,useSlicedScreenshots:i,resizeSlicedScreenshots:o,useAccessibilityTree:d});t.domState=y;let S="";r&&r.length>0&&(S=`
|
|
168
|
+
# Previous actions in this session:
|
|
169
|
+
${r.map(([L,H],z)=>`${z+1}. Action: ${L}
|
|
170
|
+
Result: ${H}`).join(`
|
|
171
|
+
`)}
|
|
172
|
+
`);let{dateString:k,timeString:I}=ko(),_=`
|
|
173
|
+
# User statement
|
|
174
|
+
"${e}"
|
|
175
|
+
|
|
176
|
+
# UI Terminology (IMPORTANT - read carefully)
|
|
177
|
+
When the statement mentions a **Modal**, **Dialog**, **Popup**, or **Panel**, use this definition:
|
|
178
|
+
|
|
179
|
+
A modal is ANY distinct UI section that:
|
|
180
|
+
- Has a clear visual boundary separating it from other content
|
|
181
|
+
- Contains a specific title, heading, or purpose
|
|
182
|
+
- Presents options, forms, or content for user interaction
|
|
183
|
+
|
|
184
|
+
This includes ALL of the following:
|
|
185
|
+
- Traditional overlay/popup dialogs
|
|
186
|
+
- Side panels (left or right)
|
|
187
|
+
- Slide-out drawers
|
|
188
|
+
- Bottom sheets
|
|
189
|
+
- Floating panels
|
|
190
|
+
- Any visually distinct section with a title
|
|
191
|
+
|
|
192
|
+
**Important**: A side panel on the right or left side of the screen IS a modal if it has a distinct title and purpose. It does NOT need to overlay or block the main content to be considered a modal.
|
|
193
|
+
|
|
194
|
+
NOT modals: Loading spinners, toast notifications, tooltips, main content area.
|
|
195
|
+
|
|
196
|
+
# Current webpage state
|
|
197
|
+
## Tab information:
|
|
198
|
+
${m.currentTabText}Available tabs:
|
|
199
|
+
${m.tabsText}
|
|
200
|
+
|
|
201
|
+
## Element interaction guidelines:
|
|
202
|
+
- Each element has a unique index number (e.g., "[33]<button>")
|
|
203
|
+
- Elements marked with "[]Non-interactive text" are non-interactive (for context only)
|
|
204
|
+
- Elements are indented to show the structure of the element tree, with indentation level indicating depth
|
|
205
|
+
|
|
206
|
+
## Interactive elements from current page:
|
|
207
|
+
${h}
|
|
208
|
+
|
|
209
|
+
## Screenshot
|
|
210
|
+
${i&&u?"The following images are sliced screenshots of the current webpage (left, middle, right sections).":"The image provided is a screenshot of the current webpage."}
|
|
211
|
+
`,j="";if(t.variables&&Object.keys(t.variables).length>0){let L=[];for(let H of Object.keys(t.variables))if(!t.sensitiveKeys?.has(H)){let z=t.variables[H],re=typeof z=="string"?z:JSON.stringify(z);L.push(` - ${H}: "${re}"`)}L.length>0&&(j=`
|
|
212
|
+
## Available Variables
|
|
213
|
+
The following non-sensitive variables are available:
|
|
214
|
+
${L.join(`
|
|
215
|
+
`)}`)}let R=`
|
|
216
|
+
${j}
|
|
217
|
+
${S}
|
|
218
|
+
|
|
219
|
+
Today is ${k}. Current local time is ${I}.
|
|
220
|
+
Based on the above information, please determine if the statement is true.
|
|
221
|
+
`,O=await t.agentServices.retrieveKnowledges(e),P=[{type:"text",text:_}],N=0;if(i&&u&&u.length>0)for(let L of u)P.push({type:"image",image:L}),N++;else P.push({type:"image",image:f}),N=1;if(O&&O.length>0){let L=Ln(O,l);P.push(...L)}P.push({type:"text",text:R});let W=O?ti(O,l):0,G=N+W,$=Jt(a,G),Z=$o(),pe=await ot({model:Kt(a),system:Z,messages:[{role:"user",content:P}],output:it.object({schema:Ao}),temperature:0,providerOptions:$}),{conclusion:ne,explanation:Ae}=pe.output,we=JSON.stringify(pe.output,null,2),Le=[],fe=ua(pe.usage,a);fe&&Le.push(fe);let me=[{role:"user",content:P.map(L=>{if(L.type==="text")return{type:"text",text:L.text};if(L.type==="image"){let H=L.image,z=So(H);if(z)return{type:"image",file:z};let re=typeof H=="string"?H:"";return{type:"image",file:re.startsWith("data:")?re:`data:image/png;base64,${re}`}}return{type:"text",text:"[unknown content type]"}})}],ge={systemPrompt:Z,userPrompt:me,rawLlmResponse:we,screenshotWithSom:f,tokenUsages:Le,retrievedKnowledges:O&&O.length>0?O:void 0,elementTree:h};return{success:ne==="true",explanation:Ae,debugInfo:ge}}catch(i){return{success:!1,error:i.message}}}async function Io(e,t){try{if(!e.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:s,kwargs:n}=e.action_data;if(Me.has(s)){let r=await Me.execute(s,n,t),a=r?.success!==!1,i=r?.error||r?.message;return{success:a,error:a?void 0:i}}else{let{page:r,agentServices:a}=t;return await(await To()).execute(r,e,a),{success:!0,error:void 0}}}catch(s){return{success:!1,error:s.message}}}var yt=null;async function To(){if(yt)return yt;let e=await import("./handler-QSEXJ3YG-BK26HZ5S.js");return yt=new e.default,yt}async function Zo(e,t,s,n={},r){let a=r||{page:t,agentServices:s,domService:new at(s.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},i=s.replaceVariables(e),o=await da(i,a,n);return o.status==="error"?{status:"error",completed:o.goalAccomplished||!1,actionEntities:[],explanation:o.reasoning,error:o.error,debugInfo:o.debugInfo}:{status:"success",completed:o.goalAccomplished||!1,actionEntities:o.actionEntity?[o.actionEntity]:[],explanation:o.reasoning,debugInfo:o.debugInfo}}async function Ho(e,t,s,n={},r){let a=r||{page:t,agentServices:s,domService:new at(s.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},i=s.replaceVariables(e),o=await da(i,a,n);if(o.status==="error"||!o.actionEntity)return{status:"error",completed:o.goalAccomplished||!1,actionEntities:[],explanation:o.reasoning,error:o.error||"No action generated",debugInfo:o.debugInfo};let{actionEntity:l,reasoning:d,goalAccomplished:h,debugInfo:f}=o,u=await Io(l,a);return u.success?(d&&s.addNote(d),{status:"success",completed:h||!1,actionEntities:[l],explanation:d,debugInfo:f}):{status:"error",completed:!1,actionEntities:[l],error:u.error||"Action execution failed",debugInfo:f}}async function zo(e,t,s,n={}){let r={page:t,agentServices:s,domService:new at(s.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},a=s.replaceVariables(e);return n.useCleanScreenshotForAssertion??(n.useCleanScreenshotForAssertion=s.isUseCleanScreenshotForAssertion()),Oo(a,r,n)}async function Ko(e,t,s,n,r={}){let{runTaskLoop:a}=await import("./task-5N7K2U7O-UX3BL63L.js"),i=n?l=>{n(l)}:void 0,o=await a(e,{page:t,agentServices:s,domService:void 0,executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},{maxSteps:r.maxSteps,onEvent:i,abortSignal:r.abortSignal});return{status:o.success?"success":"error",completed:o.completed,actionEntities:o.trajectory.actions,explanation:o.summary,error:o.error,tokenUsages:o.metadata.tokenUsages}}export{qo as a,Ga as b,ca as c,Io as d,Zo as e,Ho as f,zo as g,Ko as h};
|