@vibecontrols/vibe-plugin-ai-codex 2026.601.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +69 -0
- package/dist/__tests__/permission-flags.test.d.ts +1 -0
- package/dist/index.d.ts +170 -0
- package/dist/index.js +31 -0
- package/package.json +95 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
|
|
4
|
+
Algoshred Technologies Private Limited,
|
|
5
|
+
and all its sister companies.
|
|
6
|
+
|
|
7
|
+
Maintainer: Vignesh T.V <https://github.com/tvvignesh>
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is furnished
|
|
14
|
+
to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @vibecontrols/vibe-plugin-ai-codex
|
|
2
|
+
|
|
3
|
+
<!-- VIBECONTROLS_OSS_BODY_START -->
|
|
4
|
+
|
|
5
|
+
> OpenAI Codex CLI — agentic coding from OpenAI.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
vibe plugin install @vibecontrols/vibe-plugin-ai-codex
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or install the npm package directly into an existing project that hosts the VibeControls agent:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
bun add @vibecontrols/vibe-plugin-ai-codex
|
|
17
|
+
# or
|
|
18
|
+
npm install @vibecontrols/vibe-plugin-ai-codex
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## How it works
|
|
22
|
+
|
|
23
|
+
AI **providers** implement the `AIProvider` contract from `@vibecontrols/vibe-plugin-ai` (meta). Once installed and registered, the agent can route prompts, hooks and MCP requests through this provider alongside any others you have configured. The meta plugin handles fan-out, provider selection and capability negotiation.
|
|
24
|
+
|
|
25
|
+
This package is a **provider** registered against the `@vibecontrols/vibe-plugin-ai` meta plugin. Install the meta plugin first; this provider plugs into it.
|
|
26
|
+
|
|
27
|
+
## Upstream
|
|
28
|
+
|
|
29
|
+
- **OpenAI Codex CLI** — <https://github.com/openai/codex>
|
|
30
|
+
|
|
31
|
+
## More
|
|
32
|
+
|
|
33
|
+
- npm: <https://www.npmjs.com/package/@vibecontrols/vibe-plugin-ai-codex>
|
|
34
|
+
- Source: <https://github.com/algoshred/vibe-plugin-ai-codex>
|
|
35
|
+
- Plugin contract / SDK: <https://github.com/algoshred/vibecontrols-plugin-sdk>
|
|
36
|
+
- Plugin catalogue: <https://vibecontrols.com/plugins/ai-codex>
|
|
37
|
+
|
|
38
|
+
<!-- VIBECONTROLS_OSS_BODY_END -->
|
|
39
|
+
|
|
40
|
+
<!-- VIBECONTROLS_OSS_FOOTER_START -->
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## About VibeControls
|
|
45
|
+
|
|
46
|
+
**VibeControls** is the agentic engineering mission control for AI-native teams. Vibe-plugins extend the VibeControls agent with new providers, tools, sessions, tunnels, storage backends, and security stages.
|
|
47
|
+
|
|
48
|
+
- Website: <https://vibecontrols.com>
|
|
49
|
+
- Documentation: <https://docs.vibecontrols.com>
|
|
50
|
+
- Plugin SDK: <https://github.com/algoshred/vibecontrols-plugin-sdk>
|
|
51
|
+
- All plugins: <https://github.com/algoshred?q=vibe-plugin-&type=all>
|
|
52
|
+
|
|
53
|
+
## Credits
|
|
54
|
+
|
|
55
|
+
This plugin builds on the following upstream open-source projects. All trademarks and copyrights remain with their respective owners.
|
|
56
|
+
|
|
57
|
+
- **OpenAI Codex CLI** — <https://github.com/openai/codex>
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
Released under the [MIT License](./LICENSE).
|
|
62
|
+
|
|
63
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited, Algoshred Technologies Private Limited, and all its sister companies.
|
|
64
|
+
|
|
65
|
+
Maintainer: **Vignesh T.V** — <https://github.com/tvvignesh>
|
|
66
|
+
|
|
67
|
+
**Note**: this plugin is open source under MIT. The `@vibecontrols/agent` runtime that loads and orchestrates plugins is **closed source** and proprietary to Burdenoff Consultancy Services Pvt. Ltd. If you want a fully self-hostable agent, please open an issue or contact the maintainer.
|
|
68
|
+
|
|
69
|
+
<!-- VIBECONTROLS_OSS_FOOTER_END -->
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vibe-plugin-codex
|
|
3
|
+
*
|
|
4
|
+
* OpenAI Codex AI agent provider for VibeControls Agent.
|
|
5
|
+
* Implements the AIAgentProvider interface with dual-mode support:
|
|
6
|
+
* - SDK mode: Uses the openai SDK for direct API access
|
|
7
|
+
* - CLI mode: Uses the `codex` CLI with `--quiet -a full-auto` flags
|
|
8
|
+
*
|
|
9
|
+
* Mode auto-detection: SDK if OPENAI_API_KEY is set, CLI if `codex`
|
|
10
|
+
* binary is found, error if neither is available.
|
|
11
|
+
*/
|
|
12
|
+
import type { VibePlugin, ProfileContext } from "@vibecontrols/plugin-sdk";
|
|
13
|
+
type ProviderMode = "sdk" | "cli";
|
|
14
|
+
interface AIModelInfo {
|
|
15
|
+
id: string;
|
|
16
|
+
name: string;
|
|
17
|
+
provider: string;
|
|
18
|
+
contextWindow: number;
|
|
19
|
+
maxOutputTokens: number;
|
|
20
|
+
supportsVision: boolean;
|
|
21
|
+
supportsStreaming: boolean;
|
|
22
|
+
inputPricePerMToken: number;
|
|
23
|
+
outputPricePerMToken: number;
|
|
24
|
+
}
|
|
25
|
+
interface AIProviderCapabilities {
|
|
26
|
+
streaming: boolean;
|
|
27
|
+
vision: boolean;
|
|
28
|
+
fileAttachments: boolean;
|
|
29
|
+
toolUse: boolean;
|
|
30
|
+
mcpSupport: boolean;
|
|
31
|
+
voiceMode: boolean;
|
|
32
|
+
cancelSupport: boolean;
|
|
33
|
+
modelListing: boolean;
|
|
34
|
+
}
|
|
35
|
+
interface AIFileAttachment {
|
|
36
|
+
filename: string;
|
|
37
|
+
mimeType: string;
|
|
38
|
+
content: Buffer | string;
|
|
39
|
+
size: number;
|
|
40
|
+
}
|
|
41
|
+
type AISessionStatus = "active" | "idle" | "processing" | "error" | "terminated";
|
|
42
|
+
type AILogType = "input" | "output" | "thinking" | "event" | "error" | "metadata";
|
|
43
|
+
export type PermissionMode = "plan" | "acceptEdits" | "fullAuto";
|
|
44
|
+
interface AISessionConfig {
|
|
45
|
+
name: string;
|
|
46
|
+
agentType: string;
|
|
47
|
+
model?: string;
|
|
48
|
+
maxTokens?: number;
|
|
49
|
+
temperature?: number;
|
|
50
|
+
systemPrompt?: string;
|
|
51
|
+
workingDirectory?: string;
|
|
52
|
+
/** Autonomy level for CLI mode; ignored by the SDK adapter. */
|
|
53
|
+
permissionMode?: PermissionMode;
|
|
54
|
+
providerConfig?: Record<string, unknown>;
|
|
55
|
+
}
|
|
56
|
+
interface AISession {
|
|
57
|
+
id: string;
|
|
58
|
+
name: string;
|
|
59
|
+
status: AISessionStatus;
|
|
60
|
+
agentType: string;
|
|
61
|
+
provider: string;
|
|
62
|
+
config: AISessionConfig;
|
|
63
|
+
stats: AIUsageStats;
|
|
64
|
+
createdAt: string;
|
|
65
|
+
updatedAt: string;
|
|
66
|
+
}
|
|
67
|
+
interface AIContext {
|
|
68
|
+
id: string;
|
|
69
|
+
type: string;
|
|
70
|
+
content: string;
|
|
71
|
+
metadata?: Record<string, unknown>;
|
|
72
|
+
}
|
|
73
|
+
interface AIResponse {
|
|
74
|
+
content: string;
|
|
75
|
+
model: string;
|
|
76
|
+
inputTokens: number;
|
|
77
|
+
outputTokens: number;
|
|
78
|
+
thinkingSteps?: string[];
|
|
79
|
+
durationMs: number;
|
|
80
|
+
metadata?: Record<string, unknown>;
|
|
81
|
+
}
|
|
82
|
+
interface AIStreamChunk {
|
|
83
|
+
type: "text" | "thinking" | "error" | "done";
|
|
84
|
+
content: string;
|
|
85
|
+
tokensUsed?: number;
|
|
86
|
+
}
|
|
87
|
+
interface AILog {
|
|
88
|
+
id: string;
|
|
89
|
+
sessionId: string;
|
|
90
|
+
type: AILogType;
|
|
91
|
+
content: string;
|
|
92
|
+
tokenCount?: number;
|
|
93
|
+
model?: string;
|
|
94
|
+
durationMs?: number;
|
|
95
|
+
agentMetadata?: Record<string, unknown>;
|
|
96
|
+
createdAt: string;
|
|
97
|
+
}
|
|
98
|
+
interface AILogFilter {
|
|
99
|
+
types?: AILogType[];
|
|
100
|
+
startDate?: string;
|
|
101
|
+
endDate?: string;
|
|
102
|
+
search?: string;
|
|
103
|
+
limit?: number;
|
|
104
|
+
offset?: number;
|
|
105
|
+
}
|
|
106
|
+
interface AIUsageStats {
|
|
107
|
+
inputTokens: number;
|
|
108
|
+
outputTokens: number;
|
|
109
|
+
requestCount: number;
|
|
110
|
+
estimatedCostUsd: number;
|
|
111
|
+
modelBreakdown?: Record<string, {
|
|
112
|
+
inputTokens: number;
|
|
113
|
+
outputTokens: number;
|
|
114
|
+
requestCount: number;
|
|
115
|
+
}>;
|
|
116
|
+
}
|
|
117
|
+
interface AIAgentProvider {
|
|
118
|
+
readonly name: string;
|
|
119
|
+
createSession(config: AISessionConfig): Promise<AISession>;
|
|
120
|
+
sendPrompt(sessionId: string, prompt: string, context?: AIContext[]): Promise<AIResponse>;
|
|
121
|
+
streamPrompt?(sessionId: string, prompt: string, context?: AIContext[], onChunk?: (chunk: AIStreamChunk) => void): Promise<AIResponse>;
|
|
122
|
+
getSessionLogs(sessionId: string, filter?: AILogFilter): Promise<AILog[]>;
|
|
123
|
+
getUsageStats(sessionId: string): Promise<AIUsageStats>;
|
|
124
|
+
configureSession(sessionId: string, config: Partial<AISessionConfig>): Promise<void>;
|
|
125
|
+
destroySession(sessionId: string): Promise<void>;
|
|
126
|
+
listSessions(): Promise<AISession[]>;
|
|
127
|
+
getSessionStatus(sessionId: string): Promise<AISessionStatus>;
|
|
128
|
+
healthCheck(): Promise<{
|
|
129
|
+
ok: boolean;
|
|
130
|
+
message?: string;
|
|
131
|
+
}>;
|
|
132
|
+
listModels?(): Promise<AIModelInfo[]>;
|
|
133
|
+
cancelRequest?(sessionId: string): Promise<void>;
|
|
134
|
+
getCapabilities?(): AIProviderCapabilities;
|
|
135
|
+
attachFiles?(sessionId: string, files: AIFileAttachment[]): Promise<void>;
|
|
136
|
+
getMode?(): ProviderMode;
|
|
137
|
+
setMode?(mode: ProviderMode): void;
|
|
138
|
+
getCliLaunchSpec(): {
|
|
139
|
+
binary: string;
|
|
140
|
+
baseArgs?: string[];
|
|
141
|
+
env?: Record<string, string>;
|
|
142
|
+
} | null;
|
|
143
|
+
sdkOneShot(opts: {
|
|
144
|
+
prompt: string;
|
|
145
|
+
model?: string;
|
|
146
|
+
maxTokens?: number;
|
|
147
|
+
extras?: Record<string, unknown>;
|
|
148
|
+
}): Promise<{
|
|
149
|
+
text: string;
|
|
150
|
+
usage?: unknown;
|
|
151
|
+
}>;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Map the provider-agnostic permission mode to Codex CLI approval/sandbox
|
|
155
|
+
* flags (`codex --help`: -a/--ask-for-approval {untrusted|on-request|never},
|
|
156
|
+
* --sandbox {read-only|workspace-write}). We use the explicit `-a`/`--sandbox`
|
|
157
|
+
* pair for every level (including fullAuto → `-a never --sandbox workspace-write`,
|
|
158
|
+
* the documented expansion of the `--full-auto` convenience flag) so the mapping
|
|
159
|
+
* is unambiguous and stable across CLI versions rather than depending on the
|
|
160
|
+
* `--full-auto` shorthand existing. Unknown/undefined → acceptEdits (never the
|
|
161
|
+
* most-permissive level). Flags are CLI-version-dependent.
|
|
162
|
+
*/
|
|
163
|
+
export declare function permissionFlags(mode: PermissionMode | undefined): string[];
|
|
164
|
+
type CodexVibePlugin = VibePlugin & {
|
|
165
|
+
providers?: {
|
|
166
|
+
ai?: AIAgentProvider;
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
export declare const createPlugin: (_ctx: ProfileContext) => CodexVibePlugin;
|
|
170
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res)=>()=>(fn&&(res=fn(fn=0)),res);var default_format="RFC3986",formatters,RFC1738="RFC1738";var init_formats=__esm(()=>{formatters={RFC1738:(v)=>String(v).replace(/%20/g,"+"),RFC3986:(v)=>String(v)}});function is_buffer(obj){if(!obj||typeof obj!=="object")return!1;return!!(obj.constructor&&obj.constructor.isBuffer&&obj.constructor.isBuffer(obj))}function maybe_map(val,fn){if(is_array(val)){let mapped=[];for(let i=0;i<val.length;i+=1)mapped.push(fn(val[i]));return mapped}return fn(val)}var is_array,hex_table,limit=1024,encode=(str,_defaultEncoder,charset,_kind,format)=>{if(str.length===0)return str;let string=str;if(typeof str==="symbol")string=Symbol.prototype.toString.call(str);else if(typeof str!=="string")string=String(str);if(charset==="iso-8859-1")return escape(string).replace(/%u[0-9a-f]{4}/gi,function($0){return"%26%23"+parseInt($0.slice(2),16)+"%3B"});let out="";for(let j=0;j<string.length;j+=limit){let segment=string.length>=limit?string.slice(j,j+limit):string,arr=[];for(let i=0;i<segment.length;++i){let c=segment.charCodeAt(i);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||format===RFC1738&&(c===40||c===41)){arr[arr.length]=segment.charAt(i);continue}if(c<128){arr[arr.length]=hex_table[c];continue}if(c<2048){arr[arr.length]=hex_table[192|c>>6]+hex_table[128|c&63];continue}if(c<55296||c>=57344){arr[arr.length]=hex_table[224|c>>12]+hex_table[128|c>>6&63]+hex_table[128|c&63];continue}i+=1,c=65536+((c&1023)<<10|segment.charCodeAt(i)&1023),arr[arr.length]=hex_table[240|c>>18]+hex_table[128|c>>12&63]+hex_table[128|c>>6&63]+hex_table[128|c&63]}out+=arr.join("")}return out};var init_utils=__esm(()=>{init_formats();is_array=Array.isArray,hex_table=(()=>{let array=[];for(let i=0;i<256;++i)array.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return array})()});function is_non_nullish_primitive(v){return typeof v==="string"||typeof v==="number"||typeof v==="boolean"||typeof v==="symbol"||typeof v==="bigint"}function inner_stringify(object,prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,sideChannel){let obj=object,tmp_sc=sideChannel,step=0,find_flag=!1;while((tmp_sc=tmp_sc.get(sentinel))!==void 0&&!find_flag){let pos=tmp_sc.get(object);if(step+=1,typeof pos<"u")if(pos===step)throw RangeError("Cyclic object value");else find_flag=!0;if(typeof tmp_sc.get(sentinel)>"u")step=0}if(typeof filter==="function")obj=filter(prefix,obj);else if(obj instanceof Date)obj=serializeDate?.(obj);else if(generateArrayPrefix==="comma"&&is_array2(obj))obj=maybe_map(obj,function(value){if(value instanceof Date)return serializeDate?.(value);return value});if(obj===null){if(strictNullHandling)return encoder&&!encodeValuesOnly?encoder(prefix,defaults.encoder,charset,"key",format):prefix;obj=""}if(is_non_nullish_primitive(obj)||is_buffer(obj)){if(encoder){let key_value=encodeValuesOnly?prefix:encoder(prefix,defaults.encoder,charset,"key",format);return[formatter?.(key_value)+"="+formatter?.(encoder(obj,defaults.encoder,charset,"value",format))]}return[formatter?.(prefix)+"="+formatter?.(String(obj))]}let values=[];if(typeof obj>"u")return values;let obj_keys;if(generateArrayPrefix==="comma"&&is_array2(obj)){if(encodeValuesOnly&&encoder)obj=maybe_map(obj,encoder);obj_keys=[{value:obj.length>0?obj.join(",")||null:void 0}]}else if(is_array2(filter))obj_keys=filter;else{let keys=Object.keys(obj);obj_keys=sort?keys.sort(sort):keys}let encoded_prefix=encodeDotInKeys?String(prefix).replace(/\./g,"%2E"):String(prefix),adjusted_prefix=commaRoundTrip&&is_array2(obj)&&obj.length===1?encoded_prefix+"[]":encoded_prefix;if(allowEmptyArrays&&is_array2(obj)&&obj.length===0)return adjusted_prefix+"[]";for(let j=0;j<obj_keys.length;++j){let key=obj_keys[j],value=typeof key==="object"&&typeof key.value<"u"?key.value:obj[key];if(skipNulls&&value===null)continue;let encoded_key=allowDots&&encodeDotInKeys?key.replace(/\./g,"%2E"):key,key_prefix=is_array2(obj)?typeof generateArrayPrefix==="function"?generateArrayPrefix(adjusted_prefix,encoded_key):adjusted_prefix:adjusted_prefix+(allowDots?"."+encoded_key:"["+encoded_key+"]");sideChannel.set(object,step);let valueSideChannel=new WeakMap;valueSideChannel.set(sentinel,sideChannel),push_to_array(values,inner_stringify(value,key_prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,generateArrayPrefix==="comma"&&encodeValuesOnly&&is_array2(obj)?null:encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,valueSideChannel))}return values}function normalize_stringify_options(opts=defaults){if(typeof opts.allowEmptyArrays<"u"&&typeof opts.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof opts.encodeDotInKeys<"u"&&typeof opts.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(opts.encoder!==null&&typeof opts.encoder<"u"&&typeof opts.encoder!=="function")throw TypeError("Encoder has to be a function.");let charset=opts.charset||defaults.charset;if(typeof opts.charset<"u"&&opts.charset!=="utf-8"&&opts.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let format=default_format;if(typeof opts.format<"u"){if(!has.call(formatters,opts.format))throw TypeError("Unknown format option provided.");format=opts.format}let formatter=formatters[format],filter=defaults.filter;if(typeof opts.filter==="function"||is_array2(opts.filter))filter=opts.filter;let arrayFormat;if(opts.arrayFormat&&opts.arrayFormat in array_prefix_generators)arrayFormat=opts.arrayFormat;else if("indices"in opts)arrayFormat=opts.indices?"indices":"repeat";else arrayFormat=defaults.arrayFormat;if("commaRoundTrip"in opts&&typeof opts.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let allowDots=typeof opts.allowDots>"u"?!!opts.encodeDotInKeys===!0?!0:defaults.allowDots:!!opts.allowDots;return{addQueryPrefix:typeof opts.addQueryPrefix==="boolean"?opts.addQueryPrefix:defaults.addQueryPrefix,allowDots,allowEmptyArrays:typeof opts.allowEmptyArrays==="boolean"?!!opts.allowEmptyArrays:defaults.allowEmptyArrays,arrayFormat,charset,charsetSentinel:typeof opts.charsetSentinel==="boolean"?opts.charsetSentinel:defaults.charsetSentinel,commaRoundTrip:!!opts.commaRoundTrip,delimiter:typeof opts.delimiter>"u"?defaults.delimiter:opts.delimiter,encode:typeof opts.encode==="boolean"?opts.encode:defaults.encode,encodeDotInKeys:typeof opts.encodeDotInKeys==="boolean"?opts.encodeDotInKeys:defaults.encodeDotInKeys,encoder:typeof opts.encoder==="function"?opts.encoder:defaults.encoder,encodeValuesOnly:typeof opts.encodeValuesOnly==="boolean"?opts.encodeValuesOnly:defaults.encodeValuesOnly,filter,format,formatter,serializeDate:typeof opts.serializeDate==="function"?opts.serializeDate:defaults.serializeDate,skipNulls:typeof opts.skipNulls==="boolean"?opts.skipNulls:defaults.skipNulls,sort:typeof opts.sort==="function"?opts.sort:null,strictNullHandling:typeof opts.strictNullHandling==="boolean"?opts.strictNullHandling:defaults.strictNullHandling}}function stringify(object,opts={}){let obj=object,options=normalize_stringify_options(opts),obj_keys,filter;if(typeof options.filter==="function")filter=options.filter,obj=filter("",obj);else if(is_array2(options.filter))filter=options.filter,obj_keys=filter;let keys=[];if(typeof obj!=="object"||obj===null)return"";let generateArrayPrefix=array_prefix_generators[options.arrayFormat],commaRoundTrip=generateArrayPrefix==="comma"&&options.commaRoundTrip;if(!obj_keys)obj_keys=Object.keys(obj);if(options.sort)obj_keys.sort(options.sort);let sideChannel=new WeakMap;for(let i=0;i<obj_keys.length;++i){let key=obj_keys[i];if(options.skipNulls&&obj[key]===null)continue;push_to_array(keys,inner_stringify(obj[key],key,generateArrayPrefix,commaRoundTrip,options.allowEmptyArrays,options.strictNullHandling,options.skipNulls,options.encodeDotInKeys,options.encode?options.encoder:null,options.filter,options.sort,options.allowDots,options.serializeDate,options.format,options.formatter,options.encodeValuesOnly,options.charset,sideChannel))}let joined=keys.join(options.delimiter),prefix=options.addQueryPrefix===!0?"?":"";if(options.charsetSentinel)if(options.charset==="iso-8859-1")prefix+="utf8=%26%2310003%3B&";else prefix+="utf8=%E2%9C%93&";return joined.length>0?prefix+joined:""}var has,array_prefix_generators,is_array2,push,push_to_array=function(arr,value_or_array){push.apply(arr,is_array2(value_or_array)?value_or_array:[value_or_array])},to_ISO,defaults,sentinel;var init_stringify=__esm(()=>{init_utils();init_formats();has=Object.prototype.hasOwnProperty,array_prefix_generators={brackets(prefix){return String(prefix)+"[]"},comma:"comma",indices(prefix,key){return String(prefix)+"["+key+"]"},repeat(prefix){return String(prefix)}},is_array2=Array.isArray,push=Array.prototype.push,to_ISO=Date.prototype.toISOString,defaults={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:encode,encodeValuesOnly:!1,format:default_format,formatter:formatters[default_format],indices:!1,serializeDate(date){return to_ISO.call(date)},skipNulls:!1,strictNullHandling:!1};sentinel={}});var init_qs=__esm(()=>{init_stringify()});var VERSION="4.104.0";function setShims(shims,options={auto:!1}){if(auto)throw Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`);if(kind)throw Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``);auto=options.auto,kind=shims.kind,fetch2=shims.fetch,Request2=shims.Request,Response2=shims.Response,Headers2=shims.Headers,FormData2=shims.FormData,Blob2=shims.Blob,File2=shims.File,ReadableStream2=shims.ReadableStream,getMultipartRequestOptions=shims.getMultipartRequestOptions,getDefaultAgent=shims.getDefaultAgent,fileFromPath=shims.fileFromPath,isFsReadStream=shims.isFsReadStream}var auto=!1,kind=void 0,fetch2=void 0,Request2=void 0,Response2=void 0,Headers2=void 0,FormData2=void 0,Blob2=void 0,File2=void 0,ReadableStream2=void 0,getMultipartRequestOptions=void 0,getDefaultAgent=void 0,fileFromPath=void 0,isFsReadStream=void 0;var MultipartBody;var init_MultipartBody=__esm(()=>{MultipartBody=class MultipartBody{constructor(body){this.body=body}get[Symbol.toStringTag](){return"MultipartBody"}}});function getRuntime({manuallyImported}={}){let recommendation=manuallyImported?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",_fetch,_Request,_Response,_Headers;try{_fetch=fetch,_Request=Request,_Response=Response,_Headers=Headers}catch(error){throw Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`)}return{kind:"web",fetch:_fetch,Request:_Request,Response:_Response,Headers:_Headers,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`)}},getMultipartRequestOptions:async(form,opts)=>({...opts,body:new MultipartBody(form)}),getDefaultAgent:(url)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(value)=>!1}}var init_web_runtime=__esm(()=>{init_MultipartBody()});import{ReadStream as FsReadStream}from"fs";function getRuntime2(){let runtime=getRuntime();function isFsReadStream2(value){return value instanceof FsReadStream}return{...runtime,isFsReadStream:isFsReadStream2}}var init_bun_runtime=__esm(()=>{init_web_runtime()});var init_runtime_bun=__esm(()=>{init_bun_runtime()});var init=()=>{if(!kind)setShims(getRuntime2(),{auto:!0})};var init__shims=__esm(()=>{init_runtime_bun();init()});var OpenAIError,APIError,APIUserAbortError,APIConnectionError,APIConnectionTimeoutError,BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError,ConflictError,UnprocessableEntityError,RateLimitError,InternalServerError,LengthFinishReasonError,ContentFilterFinishReasonError;var init_error=__esm(()=>{init_core();OpenAIError=class OpenAIError extends Error{};APIError=class APIError extends OpenAIError{constructor(status,error,message,headers){super(`${APIError.makeMessage(status,error,message)}`);this.status=status,this.headers=headers,this.request_id=headers?.["x-request-id"],this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message==="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;if(status&&msg)return`${status} ${msg}`;if(status)return`${status} status code (no body)`;if(msg)return msg;return"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;if(status===400)return new BadRequestError(status,error,message,headers);if(status===401)return new AuthenticationError(status,error,message,headers);if(status===403)return new PermissionDeniedError(status,error,message,headers);if(status===404)return new NotFoundError(status,error,message,headers);if(status===409)return new ConflictError(status,error,message,headers);if(status===422)return new UnprocessableEntityError(status,error,message,headers);if(status===429)return new RateLimitError(status,error,message,headers);if(status>=500)return new InternalServerError(status,error,message,headers);return new APIError(status,error,message,headers)}};APIUserAbortError=class APIUserAbortError extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}};APIConnectionError=class APIConnectionError extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0);if(cause)this.cause=cause}};APIConnectionTimeoutError=class APIConnectionTimeoutError extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}};BadRequestError=class BadRequestError extends APIError{};AuthenticationError=class AuthenticationError extends APIError{};PermissionDeniedError=class PermissionDeniedError extends APIError{};NotFoundError=class NotFoundError extends APIError{};ConflictError=class ConflictError extends APIError{};UnprocessableEntityError=class UnprocessableEntityError extends APIError{};RateLimitError=class RateLimitError extends APIError{};InternalServerError=class InternalServerError extends APIError{};LengthFinishReasonError=class LengthFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}};ContentFilterFinishReasonError=class ContentFilterFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}});class LineDecoder{constructor(){_LineDecoder_carriageReturnIndex.set(this,void 0),this.buffer=new Uint8Array,__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk=chunk instanceof ArrayBuffer?new Uint8Array(chunk):typeof chunk==="string"?new TextEncoder().encode(chunk):chunk,newData=new Uint8Array(this.buffer.length+binaryChunk.length);newData.set(this.buffer),newData.set(binaryChunk,this.buffer.length),this.buffer=newData;let lines=[],patternIndex;while((patternIndex=findNewlineIndex(this.buffer,__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")))!=null){if(patternIndex.carriage&&__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")==null){__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,patternIndex.index,"f");continue}if(__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")!=null&&(patternIndex.index!==__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")+1||patternIndex.carriage)){lines.push(this.decodeText(this.buffer.slice(0,__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")-1))),this.buffer=this.buffer.slice(__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")),__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f");continue}let endIndex=__classPrivateFieldGet(this,_LineDecoder_carriageReturnIndex,"f")!==null?patternIndex.preceding-1:patternIndex.preceding,line=this.decodeText(this.buffer.slice(0,endIndex));lines.push(line),this.buffer=this.buffer.slice(patternIndex.index),__classPrivateFieldSet(this,_LineDecoder_carriageReturnIndex,null,"f")}return lines}decodeText(bytes){if(bytes==null)return"";if(typeof bytes==="string")return bytes;if(typeof Buffer<"u"){if(bytes instanceof Buffer)return bytes.toString();if(bytes instanceof Uint8Array)return Buffer.from(bytes).toString();throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(bytes instanceof Uint8Array||bytes instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(bytes);throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`)}throw new OpenAIError("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
|
|
3
|
+
`)}}function findNewlineIndex(buffer,startIndex){for(let i=startIndex??0;i<buffer.length;i++){if(buffer[i]===10)return{preceding:i,index:i+1,carriage:!1};if(buffer[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function findDoubleNewlineIndex(buffer){for(let i=0;i<buffer.length-1;i++){if(buffer[i]===10&&buffer[i+1]===10)return i+2;if(buffer[i]===13&&buffer[i+1]===13)return i+2;if(buffer[i]===13&&buffer[i+1]===10&&i+3<buffer.length&&buffer[i+2]===13&&buffer[i+3]===10)return i+4}return-1}var __classPrivateFieldSet=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_LineDecoder_carriageReturnIndex;var init_line=__esm(()=>{init_error();_LineDecoder_carriageReturnIndex=new WeakMap;LineDecoder.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();if(result?.done)reader.releaseLock();return result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function*_iterSSEMessages(response,controller){if(!response.body)throw controller.abort(),new OpenAIError("Attempted to iterate over a response with no body");let sseDecoder=new SSEDecoder,lineDecoder=new LineDecoder,iter=ReadableStreamToAsyncIterable(response.body);for await(let sseChunk of iterSSEChunks(iter))for(let line of lineDecoder.decode(sseChunk)){let sse=sseDecoder.decode(line);if(sse)yield sse}for(let line of lineDecoder.flush()){let sse=sseDecoder.decode(line);if(sse)yield sse}}async function*iterSSEChunks(iterator){let data=new Uint8Array;for await(let chunk of iterator){if(chunk==null)continue;let binaryChunk=chunk instanceof ArrayBuffer?new Uint8Array(chunk):typeof chunk==="string"?new TextEncoder().encode(chunk):chunk,newData=new Uint8Array(data.length+binaryChunk.length);newData.set(data),newData.set(binaryChunk,data.length),data=newData;let patternIndex;while((patternIndex=findDoubleNewlineIndex(data))!==-1)yield data.slice(0,patternIndex),data=data.slice(patternIndex)}if(data.length>0)yield data}class SSEDecoder{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(line){if(line.endsWith("\r"))line=line.substring(0,line.length-1);if(!line){if(!this.event&&!this.data.length)return null;let sse={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],sse}if(this.chunks.push(line),line.startsWith(":"))return null;let[fieldname,_,value]=partition(line,":");if(value.startsWith(" "))value=value.substring(1);if(fieldname==="event")this.event=value;else if(fieldname==="data")this.data.push(value);return null}}function partition(str,delimiter){let index=str.indexOf(delimiter);if(index!==-1)return[str.substring(0,index),delimiter,str.substring(index+delimiter.length)];return[str,"",""]}var Stream;var init_streaming=__esm(()=>{init__shims();init_error();init_line();init_core();init_error();Stream=class Stream{constructor(iterator,controller){this.iterator=iterator,this.controller=controller}static fromSSEResponse(response,controller){let consumed=!1;async function*iterator(){if(consumed)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let sse of _iterSSEMessages(response,controller)){if(done)continue;if(sse.data.startsWith("[DONE]")){done=!0;continue}if(sse.event===null||sse.event.startsWith("response.")||sse.event.startsWith("transcript.")){let data;try{data=JSON.parse(sse.data)}catch(e){throw console.error("Could not parse message into JSON:",sse.data),console.error("From chunk:",sse.raw),e}if(data&&data.error)throw new APIError(void 0,data.error,void 0,createResponseHeaders(response.headers));yield data}else{let data;try{data=JSON.parse(sse.data)}catch(e){throw console.error("Could not parse message into JSON:",sse.data),console.error("From chunk:",sse.raw),e}if(sse.event=="error")throw new APIError(void 0,data.error,data.message,void 0);yield{event:sse.event,data}}}done=!0}catch(e){if(e instanceof Error&&e.name==="AbortError")return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller)}static fromReadableStream(readableStream,controller){let consumed=!1;async function*iterLines(){let lineDecoder=new LineDecoder,iter=ReadableStreamToAsyncIterable(readableStream);for await(let chunk of iter)for(let line of lineDecoder.decode(chunk))yield line;for(let line of lineDecoder.flush())yield line}async function*iterator(){if(consumed)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let line of iterLines()){if(done)continue;if(line)yield JSON.parse(line)}done=!0}catch(e){if(e instanceof Error&&e.name==="AbortError")return;throw e}finally{if(!done)controller.abort()}}return new Stream(iterator,controller)}[Symbol.asyncIterator](){return this.iterator()}tee(){let left=[],right=[],iterator=this.iterator(),teeIterator=(queue)=>{return{next:()=>{if(queue.length===0){let result=iterator.next();left.push(result),right.push(result)}return queue.shift()}}};return[new Stream(()=>teeIterator(left),this.controller),new Stream(()=>teeIterator(right),this.controller)]}toReadableStream(){let self=this,iter,encoder=new TextEncoder;return new ReadableStream2({async start(){iter=self[Symbol.asyncIterator]()},async pull(ctrl){try{let{value,done}=await iter.next();if(done)return ctrl.close();let bytes=encoder.encode(JSON.stringify(value)+`
|
|
6
|
+
`);ctrl.enqueue(bytes)}catch(err){ctrl.error(err)}},async cancel(){await iter.return?.()}})}}});async function toFile(value,name,options){if(value=await value,isFileLike(value))return value;if(isResponseLike(value)){let blob=await value.blob();name||(name=new URL(value.url).pathname.split(/[\\/]/).pop()??"unknown_file");let data=isBlobLike(blob)?[await blob.arrayBuffer()]:[blob];return new File2(data,name,options)}let bits=await getBytes(value);if(name||(name=getName(value)??"unknown_file"),!options?.type){let type=bits[0]?.type;if(typeof type==="string")options={...options,type}}return new File2(bits,name,options)}async function getBytes(value){let parts=[];if(typeof value==="string"||ArrayBuffer.isView(value)||value instanceof ArrayBuffer)parts.push(value);else if(isBlobLike(value))parts.push(await value.arrayBuffer());else if(isAsyncIterableIterator(value))for await(let chunk of value)parts.push(chunk);else throw Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);return parts}function propsForError(value){return`[${Object.getOwnPropertyNames(value).map((p)=>`"${p}"`).join(", ")}]`}function getName(value){return getStringFromMaybeBuffer(value.name)||getStringFromMaybeBuffer(value.filename)||getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()}var isResponseLike=(value)=>value!=null&&typeof value==="object"&&typeof value.url==="string"&&typeof value.blob==="function",isFileLike=(value)=>value!=null&&typeof value==="object"&&typeof value.name==="string"&&typeof value.lastModified==="number"&&isBlobLike(value),isBlobLike=(value)=>value!=null&&typeof value==="object"&&typeof value.size==="number"&&typeof value.type==="string"&&typeof value.text==="function"&&typeof value.slice==="function"&&typeof value.arrayBuffer==="function",isUploadable=(value)=>{return isFileLike(value)||isResponseLike(value)||isFsReadStream(value)},getStringFromMaybeBuffer=(x)=>{if(typeof x==="string")return x;if(typeof Buffer<"u"&&x instanceof Buffer)return String(x);return},isAsyncIterableIterator=(value)=>value!=null&&typeof value==="object"&&typeof value[Symbol.asyncIterator]==="function",isMultipartBody=(body)=>body&&typeof body==="object"&&body.body&&body[Symbol.toStringTag]==="MultipartBody",multipartFormRequestOptions=async(opts)=>{let form=await createForm(opts.body);return getMultipartRequestOptions(form,opts)},createForm=async(body)=>{let form=new FormData2;return await Promise.all(Object.entries(body||{}).map(([key,value])=>addFormValue(form,key,value))),form},addFormValue=async(form,key,value)=>{if(value===void 0)return;if(value==null)throw TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);if(typeof value==="string"||typeof value==="number"||typeof value==="boolean")form.append(key,String(value));else if(isUploadable(value)){let file=await toFile(value);form.append(key,file)}else if(Array.isArray(value))await Promise.all(value.map((entry)=>addFormValue(form,key+"[]",entry)));else if(typeof value==="object")await Promise.all(Object.entries(value).map(([name,prop])=>addFormValue(form,`${key}[${name}]`,prop)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`)};var init_uploads=__esm(()=>{init__shims();init__shims()});async function defaultParseResponse(props){let{response}=props;if(props.options.stream){if(debug("response",response.status,response.url,response.headers,response.body),props.options.__streamClass)return props.options.__streamClass.fromSSEResponse(response,props.controller);return Stream.fromSSEResponse(response,props.controller)}if(response.status===204)return null;if(props.options.__binaryResponse)return response;let mediaType=response.headers.get("content-type")?.split(";")[0]?.trim();if(mediaType?.includes("application/json")||mediaType?.endsWith("+json")){let json=await response.json();return debug("response",response.status,response.url,response.headers,json),_addRequestID(json,response)}let text=await response.text();return debug("response",response.status,response.url,response.headers,text),text}function _addRequestID(value,response){if(!value||typeof value!=="object"||Array.isArray(value))return value;return Object.defineProperty(value,"_request_id",{value:response.headers.get("x-request-id"),enumerable:!1})}class APIClient{constructor({baseURL,maxRetries=2,timeout=600000,httpAgent,fetch:overriddenFetch}){this.baseURL=baseURL,this.maxRetries=validatePositiveInteger("maxRetries",maxRetries),this.timeout=validatePositiveInteger("timeout",timeout),this.httpAgent=httpAgent,this.fetch=overriddenFetch??fetch2}authHeaders(opts){return{}}defaultHeaders(opts){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...getPlatformHeaders(),...this.authHeaders(opts)}}validateHeaders(headers,customHeaders){}defaultIdempotencyKey(){return`stainless-node-retry-${uuid4()}`}get(path,opts){return this.methodRequest("get",path,opts)}post(path,opts){return this.methodRequest("post",path,opts)}patch(path,opts){return this.methodRequest("patch",path,opts)}put(path,opts){return this.methodRequest("put",path,opts)}delete(path,opts){return this.methodRequest("delete",path,opts)}methodRequest(method,path,opts){return this.request(Promise.resolve(opts).then(async(opts2)=>{let body=opts2&&isBlobLike(opts2?.body)?new DataView(await opts2.body.arrayBuffer()):opts2?.body instanceof DataView?opts2.body:opts2?.body instanceof ArrayBuffer?new DataView(opts2.body):opts2&&ArrayBuffer.isView(opts2?.body)?new DataView(opts2.body.buffer):opts2?.body;return{method,path,...opts2,body}}))}getAPIList(path,Page,opts){return this.requestAPIList(Page,{method:"get",path,...opts})}calculateContentLength(body){if(typeof body==="string"){if(typeof Buffer<"u")return Buffer.byteLength(body,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(body).length.toString()}else if(ArrayBuffer.isView(body))return body.byteLength.toString();return null}buildRequest(inputOptions,{retryCount=0}={}){let options={...inputOptions},{method,path,query,headers={}}=options,body=ArrayBuffer.isView(options.body)||options.__binaryRequest&&typeof options.body==="string"?options.body:isMultipartBody(options.body)?options.body.body:options.body?JSON.stringify(options.body,null,2):null,contentLength=this.calculateContentLength(body),url=this.buildURL(path,query);if("timeout"in options)validatePositiveInteger("timeout",options.timeout);options.timeout=options.timeout??this.timeout;let httpAgent=options.httpAgent??this.httpAgent??getDefaultAgent(url),minAgentTimeout=options.timeout+1000;if(typeof httpAgent?.options?.timeout==="number"&&minAgentTimeout>(httpAgent.options.timeout??0))httpAgent.options.timeout=minAgentTimeout;if(this.idempotencyHeader&&method!=="get"){if(!inputOptions.idempotencyKey)inputOptions.idempotencyKey=this.defaultIdempotencyKey();headers[this.idempotencyHeader]=inputOptions.idempotencyKey}let reqHeaders=this.buildHeaders({options,headers,contentLength,retryCount});return{req:{method,...body&&{body},headers:reqHeaders,...httpAgent&&{agent:httpAgent},signal:options.signal??null},url,timeout:options.timeout}}buildHeaders({options,headers,contentLength,retryCount}){let reqHeaders={};if(contentLength)reqHeaders["content-length"]=contentLength;let defaultHeaders=this.defaultHeaders(options);if(applyHeadersMut(reqHeaders,defaultHeaders),applyHeadersMut(reqHeaders,headers),isMultipartBody(options.body)&&kind!=="node")delete reqHeaders["content-type"];if(getHeader(defaultHeaders,"x-stainless-retry-count")===void 0&&getHeader(headers,"x-stainless-retry-count")===void 0)reqHeaders["x-stainless-retry-count"]=String(retryCount);if(getHeader(defaultHeaders,"x-stainless-timeout")===void 0&&getHeader(headers,"x-stainless-timeout")===void 0&&options.timeout)reqHeaders["x-stainless-timeout"]=String(Math.trunc(options.timeout/1000));return this.validateHeaders(reqHeaders,headers),reqHeaders}async prepareOptions(options){}async prepareRequest(request,{url,options}){}parseHeaders(headers){return!headers?{}:(Symbol.iterator in headers)?Object.fromEntries(Array.from(headers).map((header)=>[...header])):{...headers}}makeStatusError(status,error,message,headers){return APIError.generate(status,error,message,headers)}request(options,remainingRetries=null){return new APIPromise(this.makeRequest(options,remainingRetries))}async makeRequest(optionsInput,retriesRemaining){let options=await optionsInput,maxRetries=options.maxRetries??this.maxRetries;if(retriesRemaining==null)retriesRemaining=maxRetries;await this.prepareOptions(options);let{req,url,timeout}=this.buildRequest(options,{retryCount:maxRetries-retriesRemaining});if(await this.prepareRequest(req,{url,options}),debug("request",url,options,req.headers),options.signal?.aborted)throw new APIUserAbortError;let controller=new AbortController,response=await this.fetchWithTimeout(url,req,timeout,controller).catch(castToError);if(response instanceof Error){if(options.signal?.aborted)throw new APIUserAbortError;if(retriesRemaining)return this.retryRequest(options,retriesRemaining);if(response.name==="AbortError")throw new APIConnectionTimeoutError;throw new APIConnectionError({cause:response})}let responseHeaders=createResponseHeaders(response.headers);if(!response.ok){if(retriesRemaining&&this.shouldRetry(response)){let retryMessage2=`retrying, ${retriesRemaining} attempts remaining`;return debug(`response (error; ${retryMessage2})`,response.status,url,responseHeaders),this.retryRequest(options,retriesRemaining,responseHeaders)}let errText=await response.text().catch((e)=>castToError(e).message),errJSON=safeJSON(errText),errMessage=errJSON?void 0:errText;throw debug(`response (error; ${retriesRemaining?"(error; no more retries left)":"(error; not retryable)"})`,response.status,url,responseHeaders,errMessage),this.makeStatusError(response.status,errJSON,errMessage,responseHeaders)}return{response,options,controller}}requestAPIList(Page,options){let request=this.makeRequest(options,null);return new PagePromise(this,request,Page)}buildURL(path,query){let url=isAbsoluteURL(path)?new URL(path):new URL(this.baseURL+(this.baseURL.endsWith("/")&&path.startsWith("/")?path.slice(1):path)),defaultQuery=this.defaultQuery();if(!isEmptyObj(defaultQuery))query={...defaultQuery,...query};if(typeof query==="object"&&query&&!Array.isArray(query))url.search=this.stringifyQuery(query);return url.toString()}stringifyQuery(query){return Object.entries(query).filter(([_,value])=>typeof value<"u").map(([key,value])=>{if(typeof value==="string"||typeof value==="number"||typeof value==="boolean")return`${encodeURIComponent(key)}=${encodeURIComponent(value)}`;if(value===null)return`${encodeURIComponent(key)}=`;throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(url,init2,ms,controller){let{signal,...options}=init2||{};if(signal)signal.addEventListener("abort",()=>controller.abort());let timeout=setTimeout(()=>controller.abort(),ms),fetchOptions={signal:controller.signal,...options};if(fetchOptions.method)fetchOptions.method=fetchOptions.method.toUpperCase();return this.fetch.call(void 0,url,fetchOptions).finally(()=>{clearTimeout(timeout)})}shouldRetry(response){let shouldRetryHeader=response.headers.get("x-should-retry");if(shouldRetryHeader==="true")return!0;if(shouldRetryHeader==="false")return!1;if(response.status===408)return!0;if(response.status===409)return!0;if(response.status===429)return!0;if(response.status>=500)return!0;return!1}async retryRequest(options,retriesRemaining,responseHeaders){let timeoutMillis,retryAfterMillisHeader=responseHeaders?.["retry-after-ms"];if(retryAfterMillisHeader){let timeoutMs=parseFloat(retryAfterMillisHeader);if(!Number.isNaN(timeoutMs))timeoutMillis=timeoutMs}let retryAfterHeader=responseHeaders?.["retry-after"];if(retryAfterHeader&&!timeoutMillis){let timeoutSeconds=parseFloat(retryAfterHeader);if(!Number.isNaN(timeoutSeconds))timeoutMillis=timeoutSeconds*1000;else timeoutMillis=Date.parse(retryAfterHeader)-Date.now()}if(!(timeoutMillis&&0<=timeoutMillis&&timeoutMillis<60000)){let maxRetries=options.maxRetries??this.maxRetries;timeoutMillis=this.calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries)}return await sleep(timeoutMillis),this.makeRequest(options,retriesRemaining-1)}calculateDefaultRetryTimeoutMillis(retriesRemaining,maxRetries){let numRetries=maxRetries-retriesRemaining,sleepSeconds=Math.min(0.5*Math.pow(2,numRetries),8),jitter=1-Math.random()*0.25;return sleepSeconds*jitter*1000}getUserAgent(){return`${this.constructor.name}/JS ${VERSION}`}}function getBrowserInfo(){if(typeof navigator>"u"||!navigator)return null;let browserPatterns=[{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,pattern}of browserPatterns){let match=pattern.exec(navigator.userAgent);if(match){let major=match[1]||0,minor=match[2]||0,patch=match[3]||0;return{browser:key,version:`${major}.${minor}.${patch}`}}}return null}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function applyHeadersMut(targetHeaders,newHeaders){for(let k in newHeaders){if(!hasOwn(newHeaders,k))continue;let lowerKey=k.toLowerCase();if(!lowerKey)continue;let val=newHeaders[k];if(val===null)delete targetHeaders[lowerKey];else if(val!==void 0)targetHeaders[lowerKey]=val}}function debug(action,...args){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let modifiedArgs=args.map((arg)=>{if(!arg)return arg;if(arg.headers){let modifiedArg2={...arg,headers:{...arg.headers}};for(let header in arg.headers)if(SENSITIVE_HEADERS.has(header.toLowerCase()))modifiedArg2.headers[header]="REDACTED";return modifiedArg2}let modifiedArg=null;for(let header in arg)if(SENSITIVE_HEADERS.has(header.toLowerCase()))modifiedArg??(modifiedArg={...arg}),modifiedArg[header]="REDACTED";return modifiedArg??arg});console.log(`OpenAI:DEBUG:${action}`,...modifiedArgs)}}function isObj(obj){return obj!=null&&typeof obj==="object"&&!Array.isArray(obj)}var __classPrivateFieldSet2=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet2=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_AbstractPage_client,APIPromise,AbstractPage,PagePromise,createResponseHeaders=(headers)=>{return new Proxy(Object.fromEntries(headers.entries()),{get(target,name){let key=name.toString();return target[key.toLowerCase()]||target[key]}})},requestOptionsKeys,isRequestOptions=(obj)=>{return typeof obj==="object"&&obj!==null&&!isEmptyObj(obj)&&Object.keys(obj).every((k)=>hasOwn(requestOptionsKeys,k))},getPlatformProperties=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(Deno.build.os),"X-Stainless-Arch":normalizeArch(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":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(process.platform),"X-Stainless-Arch":normalizeArch(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let browserInfo=getBrowserInfo();if(browserInfo)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${browserInfo.browser}`,"X-Stainless-Runtime-Version":browserInfo.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},normalizeArch=(arch)=>{if(arch==="x32")return"x32";if(arch==="x86_64"||arch==="x64")return"x64";if(arch==="arm")return"arm";if(arch==="aarch64"||arch==="arm64")return"arm64";if(arch)return`other:${arch}`;return"unknown"},normalizePlatform=(platform)=>{if(platform=platform.toLowerCase(),platform.includes("ios"))return"iOS";if(platform==="android")return"Android";if(platform==="darwin")return"MacOS";if(platform==="win32")return"Windows";if(platform==="freebsd")return"FreeBSD";if(platform==="openbsd")return"OpenBSD";if(platform==="linux")return"Linux";if(platform)return`Other:${platform}`;return"Unknown"},_platformHeaders,getPlatformHeaders=()=>{return _platformHeaders??(_platformHeaders=getPlatformProperties())},safeJSON=(text)=>{try{return JSON.parse(text)}catch(err){return}},startsWithSchemeRegexp,isAbsoluteURL=(url)=>{return startsWithSchemeRegexp.test(url)},sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),validatePositiveInteger=(name,n)=>{if(typeof n!=="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n},castToError=(err)=>{if(err instanceof Error)return err;if(typeof err==="object"&&err!==null)try{return Error(JSON.stringify(err))}catch{}return Error(err)},readEnv=(env)=>{if(typeof process<"u")return process.env?.[env]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(env)?.trim();return},SENSITIVE_HEADERS,uuid4=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(c)=>{let r=Math.random()*16|0;return(c==="x"?r:r&3|8).toString(16)})},isRunningInBrowser=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},isHeadersProtocol=(headers)=>{return typeof headers?.get==="function"},getHeader=(headers,header)=>{let lowerCasedHeader=header.toLowerCase();if(isHeadersProtocol(headers)){let intercapsHeader=header[0]?.toUpperCase()+header.substring(1).replace(/([^\w])(\w)/g,(_m,g1,g2)=>g1+g2.toUpperCase());for(let key of[header,lowerCasedHeader,header.toUpperCase(),intercapsHeader]){let value=headers.get(key);if(value)return value}}for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===lowerCasedHeader){if(Array.isArray(value)){if(value.length<=1)return value[0];return console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`),value[0]}return value}return},toFloat32Array=(base64Str)=>{if(typeof Buffer<"u"){let buf=Buffer.from(base64Str,"base64");return Array.from(new Float32Array(buf.buffer,buf.byteOffset,buf.length/Float32Array.BYTES_PER_ELEMENT))}else{let binaryStr=atob(base64Str),len=binaryStr.length,bytes=new Uint8Array(len);for(let i=0;i<len;i++)bytes[i]=binaryStr.charCodeAt(i);return Array.from(new Float32Array(bytes.buffer))}};var init_core=__esm(()=>{init_streaming();init_error();init__shims();init_uploads();init_uploads();init();APIPromise=class APIPromise extends Promise{constructor(responsePromise,parseResponse=defaultParseResponse){super((resolve)=>{resolve(null)});this.responsePromise=responsePromise,this.parseResponse=parseResponse}_thenUnwrap(transform){return new APIPromise(this.responsePromise,async(props)=>_addRequestID(transform(await this.parseResponse(props),props),props.response))}asResponse(){return this.responsePromise.then((p)=>p.response)}async withResponse(){let[data,response]=await Promise.all([this.parse(),this.asResponse()]);return{data,response,request_id:response.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(onfulfilled,onrejected){return this.parse().then(onfulfilled,onrejected)}catch(onrejected){return this.parse().catch(onrejected)}finally(onfinally){return this.parse().finally(onfinally)}};AbstractPage=class AbstractPage{constructor(client,response,body,options){_AbstractPage_client.set(this,void 0),__classPrivateFieldSet2(this,_AbstractPage_client,client,"f"),this.options=options,this.response=response,this.body=body}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let nextInfo=this.nextPageInfo();if(!nextInfo)throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let nextOptions={...this.options};if("params"in nextInfo&&typeof nextOptions.query==="object")nextOptions.query={...nextOptions.query,...nextInfo.params};else if("url"in nextInfo){let params=[...Object.entries(nextOptions.query||{}),...nextInfo.url.searchParams.entries()];for(let[key,value]of params)nextInfo.url.searchParams.set(key,value);nextOptions.query=void 0,nextOptions.path=nextInfo.url.toString()}return await __classPrivateFieldGet2(this,_AbstractPage_client,"f").requestAPIList(this.constructor,nextOptions)}async*iterPages(){let page=this;yield page;while(page.hasNextPage())page=await page.getNextPage(),yield page}async*[(_AbstractPage_client=new WeakMap,Symbol.asyncIterator)](){for await(let page of this.iterPages())for(let item of page.getPaginatedItems())yield item}};PagePromise=class PagePromise extends APIPromise{constructor(client,request,Page){super(request,async(props)=>new Page(client,props.response,await defaultParseResponse(props),props.options))}async*[Symbol.asyncIterator](){let page=await this;for await(let item of page)yield item}};requestOptionsKeys={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0};startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i;SENSITIVE_HEADERS=new Set(["authorization","api-key"])});var Page,CursorPage;var init_pagination=__esm(()=>{init_core();Page=class Page extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.object=body.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}};CursorPage=class CursorPage extends AbstractPage{constructor(client,response,body,options){super(client,response,body,options);this.data=body.data||[],this.has_more=body.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let info=this.nextPageInfo();if(!info)return null;if("params"in info)return info.params;let params=Object.fromEntries(info.url.searchParams);if(!Object.keys(params).length)return null;return params}nextPageInfo(){let data=this.getPaginatedItems();if(!data.length)return null;let id=data[data.length-1]?.id;if(!id)return null;return{params:{after:id}}}}});class APIResource{constructor(client){this._client=client}}var Messages;var init_messages=__esm(()=>{init_core();init_completions();Messages=class Messages extends APIResource{list(completionId,query={},options){if(isRequestOptions(query))return this.list(completionId,{},query);return this._client.getAPIList(`/chat/completions/${completionId}/messages`,ChatCompletionStoreMessagesPage,{query,...options})}}});var Completions,ChatCompletionsPage,ChatCompletionStoreMessagesPage;var init_completions=__esm(()=>{init_core();init_messages();init_messages();init_pagination();Completions=class Completions extends APIResource{constructor(){super(...arguments);this.messages=new Messages(this._client)}create(body,options){return this._client.post("/chat/completions",{body,...options,stream:body.stream??!1})}retrieve(completionId,options){return this._client.get(`/chat/completions/${completionId}`,options)}update(completionId,body,options){return this._client.post(`/chat/completions/${completionId}`,{body,...options})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/chat/completions",ChatCompletionsPage,{query,...options})}del(completionId,options){return this._client.delete(`/chat/completions/${completionId}`,options)}};ChatCompletionsPage=class ChatCompletionsPage extends CursorPage{};ChatCompletionStoreMessagesPage=class ChatCompletionStoreMessagesPage extends CursorPage{};Completions.ChatCompletionsPage=ChatCompletionsPage;Completions.Messages=Messages});var Chat;var init_chat=__esm(()=>{init_completions();init_completions();Chat=class Chat extends APIResource{constructor(){super(...arguments);this.completions=new Completions(this._client)}};Chat.Completions=Completions;Chat.ChatCompletionsPage=ChatCompletionsPage});var init_chat2=__esm(()=>{init_chat()});var init_shared=()=>{};var Speech;var init_speech=__esm(()=>{Speech=class Speech extends APIResource{create(body,options){return this._client.post("/audio/speech",{body,...options,headers:{Accept:"application/octet-stream",...options?.headers},__binaryResponse:!0})}}});var Transcriptions;var init_transcriptions=__esm(()=>{init_core();Transcriptions=class Transcriptions extends APIResource{create(body,options){return this._client.post("/audio/transcriptions",multipartFormRequestOptions({body,...options,stream:body.stream??!1,__metadata:{model:body.model}}))}}});var Translations;var init_translations=__esm(()=>{init_core();Translations=class Translations extends APIResource{create(body,options){return this._client.post("/audio/translations",multipartFormRequestOptions({body,...options,__metadata:{model:body.model}}))}}});var Audio;var init_audio=__esm(()=>{init_speech();init_speech();init_transcriptions();init_transcriptions();init_translations();init_translations();Audio=class Audio extends APIResource{constructor(){super(...arguments);this.transcriptions=new Transcriptions(this._client),this.translations=new Translations(this._client),this.speech=new Speech(this._client)}};Audio.Transcriptions=Transcriptions;Audio.Translations=Translations;Audio.Speech=Speech});var Batches,BatchesPage;var init_batches=__esm(()=>{init_core();init_pagination();Batches=class Batches extends APIResource{create(body,options){return this._client.post("/batches",{body,...options})}retrieve(batchId,options){return this._client.get(`/batches/${batchId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/batches",BatchesPage,{query,...options})}cancel(batchId,options){return this._client.post(`/batches/${batchId}/cancel`,options)}};BatchesPage=class BatchesPage extends CursorPage{};Batches.BatchesPage=BatchesPage});class EventStream{constructor(){_EventStream_instances.add(this),this.controller=new AbortController,_EventStream_connectedPromise.set(this,void 0),_EventStream_resolveConnectedPromise.set(this,()=>{}),_EventStream_rejectConnectedPromise.set(this,()=>{}),_EventStream_endPromise.set(this,void 0),_EventStream_resolveEndPromise.set(this,()=>{}),_EventStream_rejectEndPromise.set(this,()=>{}),_EventStream_listeners.set(this,{}),_EventStream_ended.set(this,!1),_EventStream_errored.set(this,!1),_EventStream_aborted.set(this,!1),_EventStream_catchingPromiseCreated.set(this,!1),__classPrivateFieldSet3(this,_EventStream_connectedPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet3(this,_EventStream_resolveConnectedPromise,resolve,"f"),__classPrivateFieldSet3(this,_EventStream_rejectConnectedPromise,reject,"f")}),"f"),__classPrivateFieldSet3(this,_EventStream_endPromise,new Promise((resolve,reject)=>{__classPrivateFieldSet3(this,_EventStream_resolveEndPromise,resolve,"f"),__classPrivateFieldSet3(this,_EventStream_rejectEndPromise,reject,"f")}),"f"),__classPrivateFieldGet3(this,_EventStream_connectedPromise,"f").catch(()=>{}),__classPrivateFieldGet3(this,_EventStream_endPromise,"f").catch(()=>{})}_run(executor){setTimeout(()=>{executor().then(()=>{this._emitFinal(),this._emit("end")},__classPrivateFieldGet3(this,_EventStream_instances,"m",_EventStream_handleError).bind(this))},0)}_connected(){if(this.ended)return;__classPrivateFieldGet3(this,_EventStream_resolveConnectedPromise,"f").call(this),this._emit("connect")}get ended(){return __classPrivateFieldGet3(this,_EventStream_ended,"f")}get errored(){return __classPrivateFieldGet3(this,_EventStream_errored,"f")}get aborted(){return __classPrivateFieldGet3(this,_EventStream_aborted,"f")}abort(){this.controller.abort()}on(event,listener){return(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]||(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=[])).push({listener}),this}off(event,listener){let listeners=__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event];if(!listeners)return this;let index=listeners.findIndex((l)=>l.listener===listener);if(index>=0)listeners.splice(index,1);return this}once(event,listener){return(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]||(__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=[])).push({listener,once:!0}),this}emitted(event){return new Promise((resolve,reject)=>{if(__classPrivateFieldSet3(this,_EventStream_catchingPromiseCreated,!0,"f"),event!=="error")this.once("error",reject);this.once(event,resolve)})}async done(){__classPrivateFieldSet3(this,_EventStream_catchingPromiseCreated,!0,"f"),await __classPrivateFieldGet3(this,_EventStream_endPromise,"f")}_emit(event,...args){if(__classPrivateFieldGet3(this,_EventStream_ended,"f"))return;if(event==="end")__classPrivateFieldSet3(this,_EventStream_ended,!0,"f"),__classPrivateFieldGet3(this,_EventStream_resolveEndPromise,"f").call(this);let listeners=__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event];if(listeners)__classPrivateFieldGet3(this,_EventStream_listeners,"f")[event]=listeners.filter((l)=>!l.once),listeners.forEach(({listener})=>listener(...args));if(event==="abort"){let error=args[0];if(!__classPrivateFieldGet3(this,_EventStream_catchingPromiseCreated,"f")&&!listeners?.length)Promise.reject(error);__classPrivateFieldGet3(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet3(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end");return}if(event==="error"){let error=args[0];if(!__classPrivateFieldGet3(this,_EventStream_catchingPromiseCreated,"f")&&!listeners?.length)Promise.reject(error);__classPrivateFieldGet3(this,_EventStream_rejectConnectedPromise,"f").call(this,error),__classPrivateFieldGet3(this,_EventStream_rejectEndPromise,"f").call(this,error),this._emit("end")}}_emitFinal(){}}var __classPrivateFieldSet3=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet3=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_EventStream_instances,_EventStream_connectedPromise,_EventStream_resolveConnectedPromise,_EventStream_rejectConnectedPromise,_EventStream_endPromise,_EventStream_resolveEndPromise,_EventStream_rejectEndPromise,_EventStream_listeners,_EventStream_ended,_EventStream_errored,_EventStream_aborted,_EventStream_catchingPromiseCreated,_EventStream_handleError;var init_EventStream=__esm(()=>{init_error();_EventStream_connectedPromise=new WeakMap,_EventStream_resolveConnectedPromise=new WeakMap,_EventStream_rejectConnectedPromise=new WeakMap,_EventStream_endPromise=new WeakMap,_EventStream_resolveEndPromise=new WeakMap,_EventStream_rejectEndPromise=new WeakMap,_EventStream_listeners=new WeakMap,_EventStream_ended=new WeakMap,_EventStream_errored=new WeakMap,_EventStream_aborted=new WeakMap,_EventStream_catchingPromiseCreated=new WeakMap,_EventStream_instances=new WeakSet,_EventStream_handleError=function(error){if(__classPrivateFieldSet3(this,_EventStream_errored,!0,"f"),error instanceof Error&&error.name==="AbortError")error=new APIUserAbortError;if(error instanceof APIUserAbortError)return __classPrivateFieldSet3(this,_EventStream_aborted,!0,"f"),this._emit("abort",error);if(error instanceof OpenAIError)return this._emit("error",error);if(error instanceof Error){let openAIError=new OpenAIError(error.message);return openAIError.cause=error,this._emit("error",openAIError)}return this._emit("error",new OpenAIError(String(error)))}});function assertNever(_x){}var __classPrivateFieldGet4=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},__classPrivateFieldSet4=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},_AssistantStream_instances,_AssistantStream_events,_AssistantStream_runStepSnapshots,_AssistantStream_messageSnapshots,_AssistantStream_messageSnapshot,_AssistantStream_finalRun,_AssistantStream_currentContentIndex,_AssistantStream_currentContent,_AssistantStream_currentToolCallIndex,_AssistantStream_currentToolCall,_AssistantStream_currentEvent,_AssistantStream_currentRunSnapshot,_AssistantStream_currentRunStepSnapshot,_AssistantStream_addEvent,_AssistantStream_endRequest,_AssistantStream_handleMessage,_AssistantStream_handleRunStep,_AssistantStream_handleEvent,_AssistantStream_accumulateRunStep,_AssistantStream_accumulateMessage,_AssistantStream_accumulateContent,_AssistantStream_handleRun,AssistantStream;var init_AssistantStream=__esm(()=>{init_core();init_streaming();init_error();init_EventStream();AssistantStream=class AssistantStream extends EventStream{constructor(){super(...arguments);_AssistantStream_instances.add(this),_AssistantStream_events.set(this,[]),_AssistantStream_runStepSnapshots.set(this,{}),_AssistantStream_messageSnapshots.set(this,{}),_AssistantStream_messageSnapshot.set(this,void 0),_AssistantStream_finalRun.set(this,void 0),_AssistantStream_currentContentIndex.set(this,void 0),_AssistantStream_currentContent.set(this,void 0),_AssistantStream_currentToolCallIndex.set(this,void 0),_AssistantStream_currentToolCall.set(this,void 0),_AssistantStream_currentEvent.set(this,void 0),_AssistantStream_currentRunSnapshot.set(this,void 0),_AssistantStream_currentRunStepSnapshot.set(this,void 0)}[(_AssistantStream_events=new WeakMap,_AssistantStream_runStepSnapshots=new WeakMap,_AssistantStream_messageSnapshots=new WeakMap,_AssistantStream_messageSnapshot=new WeakMap,_AssistantStream_finalRun=new WeakMap,_AssistantStream_currentContentIndex=new WeakMap,_AssistantStream_currentContent=new WeakMap,_AssistantStream_currentToolCallIndex=new WeakMap,_AssistantStream_currentToolCall=new WeakMap,_AssistantStream_currentEvent=new WeakMap,_AssistantStream_currentRunSnapshot=new WeakMap,_AssistantStream_currentRunStepSnapshot=new WeakMap,_AssistantStream_instances=new WeakSet,Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("event",(event)=>{let reader=readQueue.shift();if(reader)reader.resolve(event);else pushQueue.push(event)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((chunk2)=>chunk2?{value:chunk2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(stream){let runner=new AssistantStream;return runner._run(()=>runner._fromReadableStream(stream)),runner}async _fromReadableStream(readableStream,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller);for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(threadId,runId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runToolAssistantStream(threadId,runId,runs,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createToolAssistantStream(run,threadId,runId,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await run.submitToolOutputs(threadId,runId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static createThreadAssistantStream(params,thread,options){let runner=new AssistantStream;return runner._run(()=>runner._threadAssistantStream(params,thread,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}static createAssistantStream(threadId,runs,params,options){let runner=new AssistantStream;return runner._run(()=>runner._runAssistantStream(threadId,runs,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}currentEvent(){return __classPrivateFieldGet4(this,_AssistantStream_currentEvent,"f")}currentRun(){return __classPrivateFieldGet4(this,_AssistantStream_currentRunSnapshot,"f")}currentMessageSnapshot(){return __classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f")}currentRunStepSnapshot(){return __classPrivateFieldGet4(this,_AssistantStream_currentRunStepSnapshot,"f")}async finalRunSteps(){return await this.done(),Object.values(__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f"))}async finalMessages(){return await this.done(),Object.values(__classPrivateFieldGet4(this,_AssistantStream_messageSnapshots,"f"))}async finalRun(){if(await this.done(),!__classPrivateFieldGet4(this,_AssistantStream_finalRun,"f"))throw Error("Final run was not received.");return __classPrivateFieldGet4(this,_AssistantStream_finalRun,"f")}async _createThreadAssistantStream(thread,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await thread.createAndRun(body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}async _createAssistantStream(run,threadId,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}let body={...params,stream:!0},stream=await run.create(threadId,body,{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,event);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static accumulateDelta(acc,delta){for(let[key,deltaValue]of Object.entries(delta)){if(!acc.hasOwnProperty(key)){acc[key]=deltaValue;continue}let accValue=acc[key];if(accValue===null||accValue===void 0){acc[key]=deltaValue;continue}if(key==="index"||key==="type"){acc[key]=deltaValue;continue}if(typeof accValue==="string"&&typeof deltaValue==="string")accValue+=deltaValue;else if(typeof accValue==="number"&&typeof deltaValue==="number")accValue+=deltaValue;else if(isObj(accValue)&&isObj(deltaValue))accValue=this.accumulateDelta(accValue,deltaValue);else if(Array.isArray(accValue)&&Array.isArray(deltaValue)){if(accValue.every((x)=>typeof x==="string"||typeof x==="number")){accValue.push(...deltaValue);continue}for(let deltaEntry of deltaValue){if(!isObj(deltaEntry))throw Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);let index=deltaEntry.index;if(index==null)throw console.error(deltaEntry),Error("Expected array delta entry to have an `index` property");if(typeof index!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);let accEntry=accValue[index];if(accEntry==null)accValue.push(deltaEntry);else accValue[index]=this.accumulateDelta(accEntry,deltaEntry)}continue}else throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);acc[key]=accValue}return acc}_addRun(run){return run}async _threadAssistantStream(params,thread,options){return await this._createThreadAssistantStream(thread,params,options)}async _runAssistantStream(threadId,runs,params,options){return await this._createAssistantStream(runs,threadId,params,options)}async _runToolAssistantStream(threadId,runId,runs,params,options){return await this._createToolAssistantStream(runs,threadId,runId,params,options)}};_AssistantStream_addEvent=function(event){if(this.ended)return;switch(__classPrivateFieldSet4(this,_AssistantStream_currentEvent,event,"f"),__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleEvent).call(this,event),event.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":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleRun).call(this,event);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":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleRunStep).call(this,event);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_handleMessage).call(this,event);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:assertNever(event)}},_AssistantStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");if(!__classPrivateFieldGet4(this,_AssistantStream_finalRun,"f"))throw Error("Final run has not been received");return __classPrivateFieldGet4(this,_AssistantStream_finalRun,"f")},_AssistantStream_handleMessage=function(event){let[accumulatedMessage,newContent]=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateMessage).call(this,event,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));__classPrivateFieldSet4(this,_AssistantStream_messageSnapshot,accumulatedMessage,"f"),__classPrivateFieldGet4(this,_AssistantStream_messageSnapshots,"f")[accumulatedMessage.id]=accumulatedMessage;for(let content of newContent){let snapshotContent=accumulatedMessage.content[content.index];if(snapshotContent?.type=="text")this._emit("textCreated",snapshotContent.text)}switch(event.event){case"thread.message.created":this._emit("messageCreated",event.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",event.data.delta,accumulatedMessage),event.data.delta.content)for(let content of event.data.delta.content){if(content.type=="text"&&content.text){let textDelta=content.text,snapshot=accumulatedMessage.content[content.index];if(snapshot&&snapshot.type=="text")this._emit("textDelta",textDelta,snapshot.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(content.index!=__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")){if(__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f"))switch(__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").type){case"text":this._emit("textDone",__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").text,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break;case"image_file":this._emit("imageFileDone",__classPrivateFieldGet4(this,_AssistantStream_currentContent,"f").image_file,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break}__classPrivateFieldSet4(this,_AssistantStream_currentContentIndex,content.index,"f")}__classPrivateFieldSet4(this,_AssistantStream_currentContent,accumulatedMessage.content[content.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")!==void 0){let currentContent=event.data.content[__classPrivateFieldGet4(this,_AssistantStream_currentContentIndex,"f")];if(currentContent)switch(currentContent.type){case"image_file":this._emit("imageFileDone",currentContent.image_file,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break;case"text":this._emit("textDone",currentContent.text,__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"));break}}if(__classPrivateFieldGet4(this,_AssistantStream_messageSnapshot,"f"))this._emit("messageDone",event.data);__classPrivateFieldSet4(this,_AssistantStream_messageSnapshot,void 0,"f")}},_AssistantStream_handleRunStep=function(event){let accumulatedRunStep=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateRunStep).call(this,event);switch(__classPrivateFieldSet4(this,_AssistantStream_currentRunStepSnapshot,accumulatedRunStep,"f"),event.event){case"thread.run.step.created":this._emit("runStepCreated",event.data);break;case"thread.run.step.delta":let delta=event.data.delta;if(delta.step_details&&delta.step_details.type=="tool_calls"&&delta.step_details.tool_calls&&accumulatedRunStep.step_details.type=="tool_calls")for(let toolCall of delta.step_details.tool_calls)if(toolCall.index==__classPrivateFieldGet4(this,_AssistantStream_currentToolCallIndex,"f"))this._emit("toolCallDelta",toolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index]);else{if(__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"));if(__classPrivateFieldSet4(this,_AssistantStream_currentToolCallIndex,toolCall.index,"f"),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,accumulatedRunStep.step_details.tool_calls[toolCall.index],"f"),__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallCreated",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))}this._emit("runStepDelta",event.data.delta,accumulatedRunStep);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(__classPrivateFieldSet4(this,_AssistantStream_currentRunStepSnapshot,void 0,"f"),event.data.step_details.type=="tool_calls"){if(__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,void 0,"f")}this._emit("runStepDone",event.data,accumulatedRunStep);break;case"thread.run.step.in_progress":break}},_AssistantStream_handleEvent=function(event){__classPrivateFieldGet4(this,_AssistantStream_events,"f").push(event),this._emit("event",event)},_AssistantStream_accumulateRunStep=function(event){switch(event.event){case"thread.run.step.created":return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=event.data,event.data;case"thread.run.step.delta":let snapshot=__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id];if(!snapshot)throw Error("Received a RunStepDelta before creation of a snapshot");let data=event.data;if(data.delta){let accumulated=AssistantStream.accumulateDelta(snapshot,data.delta);__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=accumulated}return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.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":__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id]=event.data;break}if(__classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id])return __classPrivateFieldGet4(this,_AssistantStream_runStepSnapshots,"f")[event.data.id];throw Error("No snapshot available")},_AssistantStream_accumulateMessage=function(event,snapshot){let newContent=[];switch(event.event){case"thread.message.created":return[event.data,newContent];case"thread.message.delta":if(!snapshot)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let data=event.data;if(data.delta.content)for(let contentElement of data.delta.content)if(contentElement.index in snapshot.content){let currentContent=snapshot.content[contentElement.index];snapshot.content[contentElement.index]=__classPrivateFieldGet4(this,_AssistantStream_instances,"m",_AssistantStream_accumulateContent).call(this,contentElement,currentContent)}else snapshot.content[contentElement.index]=contentElement,newContent.push(contentElement);return[snapshot,newContent];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(snapshot)return[snapshot,newContent];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_AssistantStream_accumulateContent=function(contentElement,currentContent){return AssistantStream.accumulateDelta(currentContent,contentElement)},_AssistantStream_handleRun=function(event){switch(__classPrivateFieldSet4(this,_AssistantStream_currentRunSnapshot,event.data,"f"),event.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":if(__classPrivateFieldSet4(this,_AssistantStream_finalRun,event.data,"f"),__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f"))this._emit("toolCallDone",__classPrivateFieldGet4(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet4(this,_AssistantStream_currentToolCall,void 0,"f");break;case"thread.run.cancelling":break}}});var Assistants,AssistantsPage;var init_assistants=__esm(()=>{init_core();init_pagination();Assistants=class Assistants extends APIResource{create(body,options){return this._client.post("/assistants",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(assistantId,options){return this._client.get(`/assistants/${assistantId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(assistantId,body,options){return this._client.post(`/assistants/${assistantId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/assistants",AssistantsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(assistantId,options){return this._client.delete(`/assistants/${assistantId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};AssistantsPage=class AssistantsPage extends CursorPage{};Assistants.AssistantsPage=AssistantsPage});function isRunnableFunctionWithParse(fn){return typeof fn.parse==="function"}var isAssistantMessage=(message)=>{return message?.role==="assistant"},isFunctionMessage=(message)=>{return message?.role==="function"},isToolMessage=(message)=>{return message?.role==="tool"};function isAutoParsableResponseFormat(response_format){return response_format?.$brand==="auto-parseable-response-format"}function isAutoParsableTool(tool){return tool?.$brand==="auto-parseable-tool"}function maybeParseChatCompletion(completion,params){if(!params||!hasAutoParseableInput(params))return{...completion,choices:completion.choices.map((choice)=>({...choice,message:{...choice.message,parsed:null,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls}:void 0}}))};return parseChatCompletion(completion,params)}function parseChatCompletion(completion,params){let choices=completion.choices.map((choice)=>{if(choice.finish_reason==="length")throw new LengthFinishReasonError;if(choice.finish_reason==="content_filter")throw new ContentFilterFinishReasonError;return{...choice,message:{...choice.message,...choice.message.tool_calls?{tool_calls:choice.message.tool_calls?.map((toolCall)=>parseToolCall(params,toolCall))??void 0}:void 0,parsed:choice.message.content&&!choice.message.refusal?parseResponseFormat(params,choice.message.content):null}}});return{...completion,choices}}function parseResponseFormat(params,content){if(params.response_format?.type!=="json_schema")return null;if(params.response_format?.type==="json_schema"){if("$parseRaw"in params.response_format)return params.response_format.$parseRaw(content);return JSON.parse(content)}return null}function parseToolCall(params,toolCall){let inputTool=params.tools?.find((inputTool2)=>inputTool2.function?.name===toolCall.function.name);return{...toolCall,function:{...toolCall.function,parsed_arguments:isAutoParsableTool(inputTool)?inputTool.$parseRaw(toolCall.function.arguments):inputTool?.function.strict?JSON.parse(toolCall.function.arguments):null}}}function shouldParseToolCall(params,toolCall){if(!params)return!1;let inputTool=params.tools?.find((inputTool2)=>inputTool2.function?.name===toolCall.function.name);return isAutoParsableTool(inputTool)||inputTool?.function.strict||!1}function hasAutoParseableInput(params){if(isAutoParsableResponseFormat(params.response_format))return!0;return params.tools?.some((t)=>isAutoParsableTool(t)||t.type==="function"&&t.function.strict===!0)??!1}function validateInputTools(tools){for(let tool of tools??[]){if(tool.type!=="function")throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);if(tool.function.strict!==!0)throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var init_parser=__esm(()=>{init_error()});var __classPrivateFieldGet5=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_AbstractChatCompletionRunner_instances,_AbstractChatCompletionRunner_getFinalContent,_AbstractChatCompletionRunner_getFinalMessage,_AbstractChatCompletionRunner_getFinalFunctionCall,_AbstractChatCompletionRunner_getFinalFunctionCallResult,_AbstractChatCompletionRunner_calculateTotalUsage,_AbstractChatCompletionRunner_validateParams,_AbstractChatCompletionRunner_stringifyFunctionCallResult,DEFAULT_MAX_CHAT_COMPLETIONS=10,AbstractChatCompletionRunner;var init_AbstractChatCompletionRunner=__esm(()=>{init_error();init_EventStream();init_parser();AbstractChatCompletionRunner=class AbstractChatCompletionRunner extends EventStream{constructor(){super(...arguments);_AbstractChatCompletionRunner_instances.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(chatCompletion){this._chatCompletions.push(chatCompletion),this._emit("chatCompletion",chatCompletion);let message=chatCompletion.choices[0]?.message;if(message)this._addMessage(message);return chatCompletion}_addMessage(message,emit=!0){if(!("content"in message))message.content=null;if(this.messages.push(message),emit){if(this._emit("message",message),(isFunctionMessage(message)||isToolMessage(message))&&message.content)this._emit("functionCallResult",message.content);else if(isAssistantMessage(message)&&message.function_call)this._emit("functionCall",message.function_call);else if(isAssistantMessage(message)&&message.tool_calls){for(let tool_call of message.tool_calls)if(tool_call.type==="function")this._emit("functionCall",tool_call.function)}}}async finalChatCompletion(){await this.done();let completion=this._chatCompletions[this._chatCompletions.length-1];if(!completion)throw new OpenAIError("stream ended without producing a ChatCompletion");return completion}async finalContent(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this)}async finalMessage(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this)}async finalFunctionCall(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this)}async finalFunctionCallResult(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this)}async totalUsage(){return await this.done(),__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let completion=this._chatCompletions[this._chatCompletions.length-1];if(completion)this._emit("finalChatCompletion",completion);let finalMessage=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this);if(finalMessage)this._emit("finalMessage",finalMessage);let finalContent=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this);if(finalContent)this._emit("finalContent",finalContent);let finalFunctionCall=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this);if(finalFunctionCall)this._emit("finalFunctionCall",finalFunctionCall);let finalFunctionCallResult=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);if(finalFunctionCallResult!=null)this._emit("finalFunctionCallResult",finalFunctionCallResult);if(this._chatCompletions.some((c)=>c.usage))this._emit("totalUsage",__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this))}async _createChatCompletion(client,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_validateParams).call(this,params);let chatCompletion=await client.chat.completions.create({...params,stream:!1},{...options,signal:this.controller.signal});return this._connected(),this._addChatCompletion(parseChatCompletion(chatCompletion,params))}async _runChatCompletion(client,params,options){for(let message of params.messages)this._addMessage(message,!1);return await this._createChatCompletion(client,params,options)}async _runFunctions(client,params,options){let{function_call="auto",stream,...restParams}=params,singleFunctionToCall=typeof function_call!=="string"&&function_call?.name,{maxChatCompletions=DEFAULT_MAX_CHAT_COMPLETIONS}=options||{},functionsByName={};for(let f of params.functions)functionsByName[f.name||f.function.name]=f;let functions=params.functions.map((f)=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(let message of params.messages)this._addMessage(message,!1);for(let i=0;i<maxChatCompletions;++i){let message=(await this._createChatCompletion(client,{...restParams,function_call,functions,messages:[...this.messages]},options)).choices[0]?.message;if(!message)throw new OpenAIError("missing message in ChatCompletion response");if(!message.function_call)return;let{name,arguments:args}=message.function_call,fn=functionsByName[name];if(!fn){let content2=`Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f)=>JSON.stringify(f.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name,content:content2});continue}else if(singleFunctionToCall&&singleFunctionToCall!==name){let content2=`Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;this._addMessage({role:"function",name,content:content2});continue}let parsed;try{parsed=isRunnableFunctionWithParse(fn)?await fn.parse(args):args}catch(error){this._addMessage({role:"function",name,content:error instanceof Error?error.message:String(error)});continue}let rawContent=await fn.function(parsed,this),content=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,rawContent);if(this._addMessage({role:"function",name,content}),singleFunctionToCall)return}}async _runTools(client,params,options){let{tool_choice="auto",stream,...restParams}=params,singleFunctionToCall=typeof tool_choice!=="string"&&tool_choice?.function?.name,{maxChatCompletions=DEFAULT_MAX_CHAT_COMPLETIONS}=options||{},inputTools=params.tools.map((tool)=>{if(isAutoParsableTool(tool)){if(!tool.$callback)throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:tool.$callback,name:tool.function.name,description:tool.function.description||"",parameters:tool.function.parameters,parse:tool.$parseRaw,strict:!0}}}return tool}),functionsByName={};for(let f of inputTools)if(f.type==="function")functionsByName[f.function.name||f.function.function.name]=f.function;let tools="tools"in params?inputTools.map((t)=>t.type==="function"?{type:"function",function:{name:t.function.name||t.function.function.name,parameters:t.function.parameters,description:t.function.description,strict:t.function.strict}}:t):void 0;for(let message of params.messages)this._addMessage(message,!1);for(let i=0;i<maxChatCompletions;++i){let message=(await this._createChatCompletion(client,{...restParams,tool_choice,tools,messages:[...this.messages]},options)).choices[0]?.message;if(!message)throw new OpenAIError("missing message in ChatCompletion response");if(!message.tool_calls?.length)return;for(let tool_call of message.tool_calls){if(tool_call.type!=="function")continue;let tool_call_id=tool_call.id,{name,arguments:args}=tool_call.function,fn=functionsByName[name];if(!fn){let content2=`Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2)=>JSON.stringify(name2)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id,content:content2});continue}else if(singleFunctionToCall&&singleFunctionToCall!==name){let content2=`Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id,content:content2});continue}let parsed;try{parsed=isRunnableFunctionWithParse(fn)?await fn.parse(args):args}catch(error){let content2=error instanceof Error?error.message:String(error);this._addMessage({role:"tool",tool_call_id,content:content2});continue}let rawContent=await fn.function(parsed,this),content=__classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,rawContent);if(this._addMessage({role:"tool",tool_call_id,content}),singleFunctionToCall)return}}return}};_AbstractChatCompletionRunner_instances=new WeakSet,_AbstractChatCompletionRunner_getFinalContent=function(){return __classPrivateFieldGet5(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this).content??null},_AbstractChatCompletionRunner_getFinalMessage=function(){let i=this.messages.length;while(i-- >0){let message=this.messages[i];if(isAssistantMessage(message)){let{function_call,...rest}=message,ret={...rest,content:message.content??null,refusal:message.refusal??null};if(function_call)ret.function_call=function_call;return ret}}throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},_AbstractChatCompletionRunner_getFinalFunctionCall=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isAssistantMessage(message)&&message?.function_call)return message.function_call;if(isAssistantMessage(message)&&message?.tool_calls?.length)return message.tool_calls.at(-1)?.function}return},_AbstractChatCompletionRunner_getFinalFunctionCallResult=function(){for(let i=this.messages.length-1;i>=0;i--){let message=this.messages[i];if(isFunctionMessage(message)&&message.content!=null)return message.content;if(isToolMessage(message)&&message.content!=null&&typeof message.content==="string"&&this.messages.some((x)=>x.role==="assistant"&&x.tool_calls?.some((y)=>y.type==="function"&&y.id===message.tool_call_id)))return message.content}return},_AbstractChatCompletionRunner_calculateTotalUsage=function(){let total={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage}of this._chatCompletions)if(usage)total.completion_tokens+=usage.completion_tokens,total.prompt_tokens+=usage.prompt_tokens,total.total_tokens+=usage.total_tokens;return total},_AbstractChatCompletionRunner_validateParams=function(params){if(params.n!=null&¶ms.n>1)throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_AbstractChatCompletionRunner_stringifyFunctionCallResult=function(rawContent){return typeof rawContent==="string"?rawContent:rawContent===void 0?"undefined":JSON.stringify(rawContent)}});var ChatCompletionRunner;var init_ChatCompletionRunner=__esm(()=>{init_AbstractChatCompletionRunner();ChatCompletionRunner=class ChatCompletionRunner extends AbstractChatCompletionRunner{static runFunctions(client,params,options){let runner=new ChatCompletionRunner,opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return runner._run(()=>runner._runFunctions(client,params,opts)),runner}static runTools(client,params,options){let runner=new ChatCompletionRunner,opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runTools"}};return runner._run(()=>runner._runTools(client,params,opts)),runner}_addMessage(message,emit=!0){if(super._addMessage(message,emit),isAssistantMessage(message)&&message.content)this._emit("content",message.content)}}});function parseJSON(jsonString,allowPartial=Allow.ALL){if(typeof jsonString!=="string")throw TypeError(`expecting str, got ${typeof jsonString}`);if(!jsonString.trim())throw Error(`${jsonString} is empty`);return _parseJSON(jsonString.trim(),allowPartial)}var Allow,PartialJSON,MalformedJSON,_parseJSON=(jsonString,allow)=>{let length=jsonString.length,index=0,markPartialJSON=(msg)=>{throw new PartialJSON(`${msg} at position ${index}`)},throwMalformedError=(msg)=>{throw new MalformedJSON(`${msg} at position ${index}`)},parseAny=()=>{if(skipBlank(),index>=length)markPartialJSON("Unexpected end of input");if(jsonString[index]==='"')return parseStr();if(jsonString[index]==="{")return parseObj();if(jsonString[index]==="[")return parseArr();if(jsonString.substring(index,index+4)==="null"||Allow.NULL&allow&&length-index<4&&"null".startsWith(jsonString.substring(index)))return index+=4,null;if(jsonString.substring(index,index+4)==="true"||Allow.BOOL&allow&&length-index<4&&"true".startsWith(jsonString.substring(index)))return index+=4,!0;if(jsonString.substring(index,index+5)==="false"||Allow.BOOL&allow&&length-index<5&&"false".startsWith(jsonString.substring(index)))return index+=5,!1;if(jsonString.substring(index,index+8)==="Infinity"||Allow.INFINITY&allow&&length-index<8&&"Infinity".startsWith(jsonString.substring(index)))return index+=8,1/0;if(jsonString.substring(index,index+9)==="-Infinity"||Allow.MINUS_INFINITY&allow&&1<length-index&&length-index<9&&"-Infinity".startsWith(jsonString.substring(index)))return index+=9,-1/0;if(jsonString.substring(index,index+3)==="NaN"||Allow.NAN&allow&&length-index<3&&"NaN".startsWith(jsonString.substring(index)))return index+=3,NaN;return parseNum()},parseStr=()=>{let start=index,escape2=!1;index++;while(index<length&&(jsonString[index]!=='"'||escape2&&jsonString[index-1]==="\\"))escape2=jsonString[index]==="\\"?!escape2:!1,index++;if(jsonString.charAt(index)=='"')try{return JSON.parse(jsonString.substring(start,++index-Number(escape2)))}catch(e){throwMalformedError(String(e))}else if(Allow.STR&allow)try{return JSON.parse(jsonString.substring(start,index-Number(escape2))+'"')}catch(e){return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("\\"))+'"')}markPartialJSON("Unterminated string literal")},parseObj=()=>{index++,skipBlank();let obj={};try{while(jsonString[index]!=="}"){if(skipBlank(),index>=length&&Allow.OBJ&allow)return obj;let key=parseStr();skipBlank(),index++;try{let value=parseAny();Object.defineProperty(obj,key,{value,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Allow.OBJ&allow)return obj;else throw e}if(skipBlank(),jsonString[index]===",")index++}}catch(e){if(Allow.OBJ&allow)return obj;else markPartialJSON("Expected '}' at end of object")}return index++,obj},parseArr=()=>{index++;let arr=[];try{while(jsonString[index]!=="]")if(arr.push(parseAny()),skipBlank(),jsonString[index]===",")index++}catch(e){if(Allow.ARR&allow)return arr;markPartialJSON("Expected ']' at end of array")}return index++,arr},parseNum=()=>{if(index===0){if(jsonString==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString)}catch(e){if(Allow.NUM&allow)try{if(jsonString[jsonString.length-1]===".")return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf(".")));return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf("e")))}catch(e2){}throwMalformedError(String(e))}}let start=index;if(jsonString[index]==="-")index++;while(jsonString[index]&&!",]}".includes(jsonString[index]))index++;if(index==length&&!(Allow.NUM&allow))markPartialJSON("Unterminated number literal");try{return JSON.parse(jsonString.substring(start,index))}catch(e){if(jsonString.substring(start,index)==="-"&&Allow.NUM&allow)markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("e")))}catch(e2){throwMalformedError(String(e2))}}},skipBlank=()=>{while(index<length&&`
|
|
7
|
+
\r `.includes(jsonString[index]))index++};return parseAny()},partialParse=(input)=>parseJSON(input,Allow.ALL^Allow.NUM);var init_parser2=__esm(()=>{Allow={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};PartialJSON=class PartialJSON extends Error{};MalformedJSON=class MalformedJSON extends Error{}});function finalizeChatCompletion(snapshot,params){let{id,choices,created,model,system_fingerprint,...rest}=snapshot,completion={...rest,id,choices:choices.map(({message,finish_reason,index,logprobs,...choiceRest})=>{if(!finish_reason)throw new OpenAIError(`missing finish_reason for choice ${index}`);let{content=null,function_call,tool_calls,...messageRest}=message,role=message.role;if(!role)throw new OpenAIError(`missing role for choice ${index}`);if(function_call){let{arguments:args,name}=function_call;if(args==null)throw new OpenAIError(`missing function_call.arguments for choice ${index}`);if(!name)throw new OpenAIError(`missing function_call.name for choice ${index}`);return{...choiceRest,message:{content,function_call:{arguments:args,name},role,refusal:message.refusal??null},finish_reason,index,logprobs}}if(tool_calls)return{...choiceRest,index,finish_reason,logprobs,message:{...messageRest,role,content,refusal:message.refusal??null,tool_calls:tool_calls.map((tool_call,i)=>{let{function:fn,type,id:id2,...toolRest}=tool_call,{arguments:args,name,...fnRest}=fn||{};if(id2==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
|
|
8
|
+
${str(snapshot)}`);if(type==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
|
|
9
|
+
${str(snapshot)}`);if(name==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name
|
|
10
|
+
${str(snapshot)}`);if(args==null)throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
|
|
11
|
+
${str(snapshot)}`);return{...toolRest,id:id2,type,function:{...fnRest,name,arguments:args}}})}};return{...choiceRest,message:{...messageRest,content,role,refusal:message.refusal??null},finish_reason,index,logprobs}}),created,model,object:"chat.completion",...system_fingerprint?{system_fingerprint}:{}};return maybeParseChatCompletion(completion,params)}function str(x){return JSON.stringify(x)}function assertIsEmpty(obj){return}function assertNever2(_x){}var __classPrivateFieldSet5=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet6=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_ChatCompletionStream_instances,_ChatCompletionStream_params,_ChatCompletionStream_choiceEventStates,_ChatCompletionStream_currentChatCompletionSnapshot,_ChatCompletionStream_beginRequest,_ChatCompletionStream_getChoiceEventState,_ChatCompletionStream_addChunk,_ChatCompletionStream_emitToolCallDoneEvent,_ChatCompletionStream_emitContentDoneEvents,_ChatCompletionStream_endRequest,_ChatCompletionStream_getAutoParseableResponseFormat,_ChatCompletionStream_accumulateChatCompletion,ChatCompletionStream;var init_ChatCompletionStream=__esm(()=>{init_error();init_AbstractChatCompletionRunner();init_streaming();init_parser();init_parser2();ChatCompletionStream=class ChatCompletionStream extends AbstractChatCompletionRunner{constructor(params){super();_ChatCompletionStream_instances.add(this),_ChatCompletionStream_params.set(this,void 0),_ChatCompletionStream_choiceEventStates.set(this,void 0),_ChatCompletionStream_currentChatCompletionSnapshot.set(this,void 0),__classPrivateFieldSet5(this,_ChatCompletionStream_params,params,"f"),__classPrivateFieldSet5(this,_ChatCompletionStream_choiceEventStates,[],"f")}get currentChatCompletionSnapshot(){return __classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f")}static fromReadableStream(stream){let runner=new ChatCompletionStream(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}static createChatCompletion(client,params,options){let runner=new ChatCompletionStream(params);return runner._run(()=>runner._runChatCompletion(client,{...params,stream:!0},{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createChatCompletion(client,params,options){super._createChatCompletion;let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this);let stream=await client.chat.completions.create({...params,stream:!0},{...options,signal:this.controller.signal});this._connected();for await(let chunk of stream)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}async _fromReadableStream(readableStream,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this),this._connected();let stream=Stream.fromReadableStream(readableStream,this.controller),chatId;for await(let chunk of stream){if(chatId&&chatId!==chunk.id)this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this));__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,chunk),chatId=chunk.id}if(stream.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}[(_ChatCompletionStream_params=new WeakMap,_ChatCompletionStream_choiceEventStates=new WeakMap,_ChatCompletionStream_currentChatCompletionSnapshot=new WeakMap,_ChatCompletionStream_instances=new WeakSet,_ChatCompletionStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f")},_ChatCompletionStream_getChoiceEventState=function(choice){let state=__classPrivateFieldGet6(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index];if(state)return state;return state={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},__classPrivateFieldGet6(this,_ChatCompletionStream_choiceEventStates,"f")[choice.index]=state,state},_ChatCompletionStream_addChunk=function(chunk){if(this.ended)return;let completion=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_accumulateChatCompletion).call(this,chunk);this._emit("chunk",chunk,completion);for(let choice of chunk.choices){let choiceSnapshot=completion.choices[choice.index];if(choice.delta.content!=null&&choiceSnapshot.message?.role==="assistant"&&choiceSnapshot.message?.content)this._emit("content",choice.delta.content,choiceSnapshot.message.content),this._emit("content.delta",{delta:choice.delta.content,snapshot:choiceSnapshot.message.content,parsed:choiceSnapshot.message.parsed});if(choice.delta.refusal!=null&&choiceSnapshot.message?.role==="assistant"&&choiceSnapshot.message?.refusal)this._emit("refusal.delta",{delta:choice.delta.refusal,snapshot:choiceSnapshot.message.refusal});if(choice.logprobs?.content!=null&&choiceSnapshot.message?.role==="assistant")this._emit("logprobs.content.delta",{content:choice.logprobs?.content,snapshot:choiceSnapshot.logprobs?.content??[]});if(choice.logprobs?.refusal!=null&&choiceSnapshot.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:choice.logprobs?.refusal,snapshot:choiceSnapshot.logprobs?.refusal??[]});let state=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(choiceSnapshot.finish_reason){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}for(let toolCall of choice.delta.tool_calls??[]){if(state.current_tool_call_index!==toolCall.index){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,choiceSnapshot),state.current_tool_call_index!=null)__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,choiceSnapshot,state.current_tool_call_index)}state.current_tool_call_index=toolCall.index}for(let toolCallDelta of choice.delta.tool_calls??[]){let toolCallSnapshot=choiceSnapshot.message.tool_calls?.[toolCallDelta.index];if(!toolCallSnapshot?.type)continue;if(toolCallSnapshot?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:toolCallSnapshot.function?.name,index:toolCallDelta.index,arguments:toolCallSnapshot.function.arguments,parsed_arguments:toolCallSnapshot.function.parsed_arguments,arguments_delta:toolCallDelta.function?.arguments??""});else assertNever2(toolCallSnapshot?.type)}}},_ChatCompletionStream_emitToolCallDoneEvent=function(choiceSnapshot,toolCallIndex){if(__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot).done_tool_calls.has(toolCallIndex))return;let toolCallSnapshot=choiceSnapshot.message.tool_calls?.[toolCallIndex];if(!toolCallSnapshot)throw Error("no tool call snapshot");if(!toolCallSnapshot.type)throw Error("tool call snapshot missing `type`");if(toolCallSnapshot.type==="function"){let inputTool=__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")?.tools?.find((tool)=>tool.type==="function"&&tool.function.name===toolCallSnapshot.function.name);this._emit("tool_calls.function.arguments.done",{name:toolCallSnapshot.function.name,index:toolCallIndex,arguments:toolCallSnapshot.function.arguments,parsed_arguments:isAutoParsableTool(inputTool)?inputTool.$parseRaw(toolCallSnapshot.function.arguments):inputTool?.function.strict?JSON.parse(toolCallSnapshot.function.arguments):null})}else assertNever2(toolCallSnapshot.type)},_ChatCompletionStream_emitContentDoneEvents=function(choiceSnapshot){let state=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,choiceSnapshot);if(choiceSnapshot.message.content&&!state.content_done){state.content_done=!0;let responseFormat=__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this);this._emit("content.done",{content:choiceSnapshot.message.content,parsed:responseFormat?responseFormat.$parseRaw(choiceSnapshot.message.content):null})}if(choiceSnapshot.message.refusal&&!state.refusal_done)state.refusal_done=!0,this._emit("refusal.done",{refusal:choiceSnapshot.message.refusal});if(choiceSnapshot.logprobs?.content&&!state.logprobs_content_done)state.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:choiceSnapshot.logprobs.content});if(choiceSnapshot.logprobs?.refusal&&!state.logprobs_refusal_done)state.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:choiceSnapshot.logprobs.refusal})},_ChatCompletionStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any chunks");return __classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f"),__classPrivateFieldSet5(this,_ChatCompletionStream_choiceEventStates,[],"f"),finalizeChatCompletion(snapshot,__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"))},_ChatCompletionStream_getAutoParseableResponseFormat=function(){let responseFormat=__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")?.response_format;if(isAutoParsableResponseFormat(responseFormat))return responseFormat;return null},_ChatCompletionStream_accumulateChatCompletion=function(chunk){var _a,_b,_c,_d;let snapshot=__classPrivateFieldGet6(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f"),{choices,...rest}=chunk;if(!snapshot)snapshot=__classPrivateFieldSet5(this,_ChatCompletionStream_currentChatCompletionSnapshot,{...rest,choices:[]},"f");else Object.assign(snapshot,rest);for(let{delta,finish_reason,index,logprobs=null,...other}of chunk.choices){let choice=snapshot.choices[index];if(!choice)choice=snapshot.choices[index]={finish_reason,index,message:{},logprobs,...other};if(logprobs)if(!choice.logprobs)choice.logprobs=Object.assign({},logprobs);else{let{content:content2,refusal:refusal2,...rest3}=logprobs;if(assertIsEmpty(rest3),Object.assign(choice.logprobs,rest3),content2)(_a=choice.logprobs).content??(_a.content=[]),choice.logprobs.content.push(...content2);if(refusal2)(_b=choice.logprobs).refusal??(_b.refusal=[]),choice.logprobs.refusal.push(...refusal2)}if(finish_reason){if(choice.finish_reason=finish_reason,__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f")&&hasAutoParseableInput(__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"))){if(finish_reason==="length")throw new LengthFinishReasonError;if(finish_reason==="content_filter")throw new ContentFilterFinishReasonError}}if(Object.assign(choice,other),!delta)continue;let{content,refusal,function_call,role,tool_calls,...rest2}=delta;if(assertIsEmpty(rest2),Object.assign(choice.message,rest2),refusal)choice.message.refusal=(choice.message.refusal||"")+refusal;if(role)choice.message.role=role;if(function_call)if(!choice.message.function_call)choice.message.function_call=function_call;else{if(function_call.name)choice.message.function_call.name=function_call.name;if(function_call.arguments)(_c=choice.message.function_call).arguments??(_c.arguments=""),choice.message.function_call.arguments+=function_call.arguments}if(content){if(choice.message.content=(choice.message.content||"")+content,!choice.message.refusal&&__classPrivateFieldGet6(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this))choice.message.parsed=partialParse(choice.message.content)}if(tool_calls){if(!choice.message.tool_calls)choice.message.tool_calls=[];for(let{index:index2,id,type,function:fn,...rest3}of tool_calls){let tool_call=(_d=choice.message.tool_calls)[index2]??(_d[index2]={});if(Object.assign(tool_call,rest3),id)tool_call.id=id;if(type)tool_call.type=type;if(fn)tool_call.function??(tool_call.function={name:fn.name??"",arguments:""});if(fn?.name)tool_call.function.name=fn.name;if(fn?.arguments){if(tool_call.function.arguments+=fn.arguments,shouldParseToolCall(__classPrivateFieldGet6(this,_ChatCompletionStream_params,"f"),tool_call))tool_call.function.parsed_arguments=partialParse(tool_call.function.arguments)}}}}return snapshot},Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("chunk",(chunk)=>{let reader=readQueue.shift();if(reader)reader.resolve(chunk);else pushQueue.push(chunk)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((chunk2)=>chunk2?{value:chunk2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var ChatCompletionStreamingRunner;var init_ChatCompletionStreamingRunner=__esm(()=>{init_ChatCompletionStream();ChatCompletionStreamingRunner=class ChatCompletionStreamingRunner extends ChatCompletionStream{static fromReadableStream(stream){let runner=new ChatCompletionStreamingRunner(null);return runner._run(()=>runner._fromReadableStream(stream)),runner}static runFunctions(client,params,options){let runner=new ChatCompletionStreamingRunner(null),opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return runner._run(()=>runner._runFunctions(client,params,opts)),runner}static runTools(client,params,options){let runner=new ChatCompletionStreamingRunner(params),opts={...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"runTools"}};return runner._run(()=>runner._runTools(client,params,opts)),runner}}});var Completions2;var init_completions2=__esm(()=>{init_ChatCompletionRunner();init_ChatCompletionStreamingRunner();init_ChatCompletionStream();init_parser();Completions2=class Completions2 extends APIResource{parse(body,options){return validateInputTools(body.tools),this._client.chat.completions.create(body,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((completion)=>parseChatCompletion(completion,body))}runFunctions(body,options){if(body.stream)return ChatCompletionStreamingRunner.runFunctions(this._client,body,options);return ChatCompletionRunner.runFunctions(this._client,body,options)}runTools(body,options){if(body.stream)return ChatCompletionStreamingRunner.runTools(this._client,body,options);return ChatCompletionRunner.runTools(this._client,body,options)}stream(body,options){return ChatCompletionStream.createChatCompletion(this._client,body,options)}}});var Chat2;var init_chat3=__esm(()=>{init_completions2();Chat2=class Chat2 extends APIResource{constructor(){super(...arguments);this.completions=new Completions2(this._client)}};(function(Chat3){Chat3.Completions=Completions2})(Chat2||(Chat2={}))});var Sessions;var init_sessions=__esm(()=>{Sessions=class Sessions extends APIResource{create(body,options){return this._client.post("/realtime/sessions",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}}});var TranscriptionSessions;var init_transcription_sessions=__esm(()=>{TranscriptionSessions=class TranscriptionSessions extends APIResource{create(body,options){return this._client.post("/realtime/transcription_sessions",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}}});var Realtime;var init_realtime=__esm(()=>{init_sessions();init_sessions();init_transcription_sessions();init_transcription_sessions();Realtime=class Realtime extends APIResource{constructor(){super(...arguments);this.sessions=new Sessions(this._client),this.transcriptionSessions=new TranscriptionSessions(this._client)}};Realtime.Sessions=Sessions;Realtime.TranscriptionSessions=TranscriptionSessions});var Messages2,MessagesPage;var init_messages2=__esm(()=>{init_core();init_pagination();Messages2=class Messages2 extends APIResource{create(threadId,body,options){return this._client.post(`/threads/${threadId}/messages`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(threadId,messageId,options){return this._client.get(`/threads/${threadId}/messages/${messageId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,messageId,body,options){return this._client.post(`/threads/${threadId}/messages/${messageId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,query={},options){if(isRequestOptions(query))return this.list(threadId,{},query);return this._client.getAPIList(`/threads/${threadId}/messages`,MessagesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(threadId,messageId,options){return this._client.delete(`/threads/${threadId}/messages/${messageId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};MessagesPage=class MessagesPage extends CursorPage{};Messages2.MessagesPage=MessagesPage});var Steps,RunStepsPage;var init_steps=__esm(()=>{init_core();init_pagination();Steps=class Steps extends APIResource{retrieve(threadId,runId,stepId,query={},options){if(isRequestOptions(query))return this.retrieve(threadId,runId,stepId,{},query);return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,runId,query={},options){if(isRequestOptions(query))return this.list(threadId,runId,{},query);return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`,RunStepsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};RunStepsPage=class RunStepsPage extends CursorPage{};Steps.RunStepsPage=RunStepsPage});var Runs,RunsPage;var init_runs=__esm(()=>{init_core();init_AssistantStream();init_core();init_steps();init_steps();init_pagination();Runs=class Runs extends APIResource{constructor(){super(...arguments);this.steps=new Steps(this._client)}create(threadId,params,options){let{include,...body}=params;return this._client.post(`/threads/${threadId}/runs`,{query:{include},body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:params.stream??!1})}retrieve(threadId,runId,options){return this._client.get(`/threads/${threadId}/runs/${runId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,runId,body,options){return this._client.post(`/threads/${threadId}/runs/${runId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(threadId,query={},options){if(isRequestOptions(query))return this.list(threadId,{},query);return this._client.getAPIList(`/threads/${threadId}/runs`,RunsPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}cancel(threadId,runId,options){return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(threadId,body,options){let run=await this.create(threadId,body,options);return await this.poll(threadId,run.id,options)}createAndStream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}async poll(threadId,runId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let{data:run,response}=await this.retrieve(threadId,runId,{...options,headers:{...options?.headers,...headers}}).withResponse();switch(run.status){case"queued":case"in_progress":case"cancelling":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return run}}}stream(threadId,body,options){return AssistantStream.createAssistantStream(threadId,this._client.beta.threads.runs,body,options)}submitToolOutputs(threadId,runId,body,options){return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:body.stream??!1})}async submitToolOutputsAndPoll(threadId,runId,body,options){let run=await this.submitToolOutputs(threadId,runId,body,options);return await this.poll(threadId,run.id,options)}submitToolOutputsStream(threadId,runId,body,options){return AssistantStream.createToolAssistantStream(threadId,runId,this._client.beta.threads.runs,body,options)}};RunsPage=class RunsPage extends CursorPage{};Runs.RunsPage=RunsPage;Runs.Steps=Steps;Runs.RunStepsPage=RunStepsPage});var Threads;var init_threads=__esm(()=>{init_core();init_AssistantStream();init_messages2();init_messages2();init_runs();init_runs();Threads=class Threads extends APIResource{constructor(){super(...arguments);this.runs=new Runs(this._client),this.messages=new Messages2(this._client)}create(body={},options){if(isRequestOptions(body))return this.create({},body);return this._client.post("/threads",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(threadId,options){return this._client.get(`/threads/${threadId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(threadId,body,options){return this._client.post(`/threads/${threadId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(threadId,options){return this._client.delete(`/threads/${threadId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}createAndRun(body,options){return this._client.post("/threads/runs",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers},stream:body.stream??!1})}async createAndRunPoll(body,options){let run=await this.createAndRun(body,options);return await this.runs.poll(run.thread_id,run.id,options)}createAndRunStream(body,options){return AssistantStream.createThreadAssistantStream(body,this._client.beta.threads,options)}};Threads.Runs=Runs;Threads.RunsPage=RunsPage;Threads.Messages=Messages2;Threads.MessagesPage=MessagesPage});var Beta;var init_beta=__esm(()=>{init_assistants();init_chat3();init_assistants();init_realtime();init_realtime();init_threads();init_threads();Beta=class Beta extends APIResource{constructor(){super(...arguments);this.realtime=new Realtime(this._client),this.chat=new Chat2(this._client),this.assistants=new Assistants(this._client),this.threads=new Threads(this._client)}};Beta.Realtime=Realtime;Beta.Assistants=Assistants;Beta.AssistantsPage=AssistantsPage;Beta.Threads=Threads});var Completions3;var init_completions3=__esm(()=>{Completions3=class Completions3 extends APIResource{create(body,options){return this._client.post("/completions",{body,...options,stream:body.stream??!1})}}});var Content;var init_content=__esm(()=>{Content=class Content extends APIResource{retrieve(containerId,fileId,options){return this._client.get(`/containers/${containerId}/files/${fileId}/content`,{...options,headers:{Accept:"application/binary",...options?.headers},__binaryResponse:!0})}}});var Files,FileListResponsesPage;var init_files=__esm(()=>{init_core();init_core();init_content();init_content();init_pagination();Files=class Files extends APIResource{constructor(){super(...arguments);this.content=new Content(this._client)}create(containerId,body,options){return this._client.post(`/containers/${containerId}/files`,multipartFormRequestOptions({body,...options}))}retrieve(containerId,fileId,options){return this._client.get(`/containers/${containerId}/files/${fileId}`,options)}list(containerId,query={},options){if(isRequestOptions(query))return this.list(containerId,{},query);return this._client.getAPIList(`/containers/${containerId}/files`,FileListResponsesPage,{query,...options})}del(containerId,fileId,options){return this._client.delete(`/containers/${containerId}/files/${fileId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}};FileListResponsesPage=class FileListResponsesPage extends CursorPage{};Files.FileListResponsesPage=FileListResponsesPage;Files.Content=Content});var Containers,ContainerListResponsesPage;var init_containers=__esm(()=>{init_core();init_files();init_files();init_pagination();Containers=class Containers extends APIResource{constructor(){super(...arguments);this.files=new Files(this._client)}create(body,options){return this._client.post("/containers",{body,...options})}retrieve(containerId,options){return this._client.get(`/containers/${containerId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/containers",ContainerListResponsesPage,{query,...options})}del(containerId,options){return this._client.delete(`/containers/${containerId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}};ContainerListResponsesPage=class ContainerListResponsesPage extends CursorPage{};Containers.ContainerListResponsesPage=ContainerListResponsesPage;Containers.Files=Files;Containers.FileListResponsesPage=FileListResponsesPage});var Embeddings;var init_embeddings=__esm(()=>{init_core();Embeddings=class Embeddings extends APIResource{create(body,options){let hasUserProvidedEncodingFormat=!!body.encoding_format,encoding_format=hasUserProvidedEncodingFormat?body.encoding_format:"base64";if(hasUserProvidedEncodingFormat)debug("Request","User defined encoding_format:",body.encoding_format);let response=this._client.post("/embeddings",{body:{...body,encoding_format},...options});if(hasUserProvidedEncodingFormat)return response;return debug("response","Decoding base64 embeddings to float32 array"),response._thenUnwrap((response2)=>{if(response2&&response2.data)response2.data.forEach((embeddingBase64Obj)=>{let embeddingBase64Str=embeddingBase64Obj.embedding;embeddingBase64Obj.embedding=toFloat32Array(embeddingBase64Str)});return response2})}}});var OutputItems,OutputItemListResponsesPage;var init_output_items=__esm(()=>{init_core();init_pagination();OutputItems=class OutputItems extends APIResource{retrieve(evalId,runId,outputItemId,options){return this._client.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`,options)}list(evalId,runId,query={},options){if(isRequestOptions(query))return this.list(evalId,runId,{},query);return this._client.getAPIList(`/evals/${evalId}/runs/${runId}/output_items`,OutputItemListResponsesPage,{query,...options})}};OutputItemListResponsesPage=class OutputItemListResponsesPage extends CursorPage{};OutputItems.OutputItemListResponsesPage=OutputItemListResponsesPage});var Runs2,RunListResponsesPage;var init_runs2=__esm(()=>{init_core();init_output_items();init_output_items();init_pagination();Runs2=class Runs2 extends APIResource{constructor(){super(...arguments);this.outputItems=new OutputItems(this._client)}create(evalId,body,options){return this._client.post(`/evals/${evalId}/runs`,{body,...options})}retrieve(evalId,runId,options){return this._client.get(`/evals/${evalId}/runs/${runId}`,options)}list(evalId,query={},options){if(isRequestOptions(query))return this.list(evalId,{},query);return this._client.getAPIList(`/evals/${evalId}/runs`,RunListResponsesPage,{query,...options})}del(evalId,runId,options){return this._client.delete(`/evals/${evalId}/runs/${runId}`,options)}cancel(evalId,runId,options){return this._client.post(`/evals/${evalId}/runs/${runId}`,options)}};RunListResponsesPage=class RunListResponsesPage extends CursorPage{};Runs2.RunListResponsesPage=RunListResponsesPage;Runs2.OutputItems=OutputItems;Runs2.OutputItemListResponsesPage=OutputItemListResponsesPage});var Evals,EvalListResponsesPage;var init_evals=__esm(()=>{init_core();init_runs2();init_runs2();init_pagination();Evals=class Evals extends APIResource{constructor(){super(...arguments);this.runs=new Runs2(this._client)}create(body,options){return this._client.post("/evals",{body,...options})}retrieve(evalId,options){return this._client.get(`/evals/${evalId}`,options)}update(evalId,body,options){return this._client.post(`/evals/${evalId}`,{body,...options})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/evals",EvalListResponsesPage,{query,...options})}del(evalId,options){return this._client.delete(`/evals/${evalId}`,options)}};EvalListResponsesPage=class EvalListResponsesPage extends CursorPage{};Evals.EvalListResponsesPage=EvalListResponsesPage;Evals.Runs=Runs2;Evals.RunListResponsesPage=RunListResponsesPage});var Files2,FileObjectsPage;var init_files2=__esm(()=>{init_core();init_core();init_error();init_core();init_pagination();Files2=class Files2 extends APIResource{create(body,options){return this._client.post("/files",multipartFormRequestOptions({body,...options}))}retrieve(fileId,options){return this._client.get(`/files/${fileId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/files",FileObjectsPage,{query,...options})}del(fileId,options){return this._client.delete(`/files/${fileId}`,options)}content(fileId,options){return this._client.get(`/files/${fileId}/content`,{...options,headers:{Accept:"application/binary",...options?.headers},__binaryResponse:!0})}retrieveContent(fileId,options){return this._client.get(`/files/${fileId}/content`,options)}async waitForProcessing(id,{pollInterval=5000,maxWait=1800000}={}){let TERMINAL_STATES=new Set(["processed","error","deleted"]),start=Date.now(),file=await this.retrieve(id);while(!file.status||!TERMINAL_STATES.has(file.status))if(await sleep(pollInterval),file=await this.retrieve(id),Date.now()-start>maxWait)throw new APIConnectionTimeoutError({message:`Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`});return file}};FileObjectsPage=class FileObjectsPage extends CursorPage{};Files2.FileObjectsPage=FileObjectsPage});var Methods;var init_methods=__esm(()=>{Methods=class Methods extends APIResource{}});var Graders;var init_graders=__esm(()=>{Graders=class Graders extends APIResource{run(body,options){return this._client.post("/fine_tuning/alpha/graders/run",{body,...options})}validate(body,options){return this._client.post("/fine_tuning/alpha/graders/validate",{body,...options})}}});var Alpha;var init_alpha=__esm(()=>{init_graders();init_graders();Alpha=class Alpha extends APIResource{constructor(){super(...arguments);this.graders=new Graders(this._client)}};Alpha.Graders=Graders});var Permissions,PermissionCreateResponsesPage;var init_permissions=__esm(()=>{init_core();init_pagination();Permissions=class Permissions extends APIResource{create(fineTunedModelCheckpoint,body,options){return this._client.getAPIList(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,PermissionCreateResponsesPage,{body,method:"post",...options})}retrieve(fineTunedModelCheckpoint,query={},options){if(isRequestOptions(query))return this.retrieve(fineTunedModelCheckpoint,{},query);return this._client.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,{query,...options})}del(fineTunedModelCheckpoint,permissionId,options){return this._client.delete(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`,options)}};PermissionCreateResponsesPage=class PermissionCreateResponsesPage extends Page{};Permissions.PermissionCreateResponsesPage=PermissionCreateResponsesPage});var Checkpoints;var init_checkpoints=__esm(()=>{init_permissions();init_permissions();Checkpoints=class Checkpoints extends APIResource{constructor(){super(...arguments);this.permissions=new Permissions(this._client)}};Checkpoints.Permissions=Permissions;Checkpoints.PermissionCreateResponsesPage=PermissionCreateResponsesPage});var Checkpoints2,FineTuningJobCheckpointsPage;var init_checkpoints2=__esm(()=>{init_core();init_pagination();Checkpoints2=class Checkpoints2 extends APIResource{list(fineTuningJobId,query={},options){if(isRequestOptions(query))return this.list(fineTuningJobId,{},query);return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`,FineTuningJobCheckpointsPage,{query,...options})}};FineTuningJobCheckpointsPage=class FineTuningJobCheckpointsPage extends CursorPage{};Checkpoints2.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage});var Jobs,FineTuningJobsPage,FineTuningJobEventsPage;var init_jobs=__esm(()=>{init_core();init_checkpoints2();init_checkpoints2();init_pagination();Jobs=class Jobs extends APIResource{constructor(){super(...arguments);this.checkpoints=new Checkpoints2(this._client)}create(body,options){return this._client.post("/fine_tuning/jobs",{body,...options})}retrieve(fineTuningJobId,options){return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`,options)}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/fine_tuning/jobs",FineTuningJobsPage,{query,...options})}cancel(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`,options)}listEvents(fineTuningJobId,query={},options){if(isRequestOptions(query))return this.listEvents(fineTuningJobId,{},query);return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`,FineTuningJobEventsPage,{query,...options})}pause(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`,options)}resume(fineTuningJobId,options){return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`,options)}};FineTuningJobsPage=class FineTuningJobsPage extends CursorPage{};FineTuningJobEventsPage=class FineTuningJobEventsPage extends CursorPage{};Jobs.FineTuningJobsPage=FineTuningJobsPage;Jobs.FineTuningJobEventsPage=FineTuningJobEventsPage;Jobs.Checkpoints=Checkpoints2;Jobs.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage});var FineTuning;var init_fine_tuning=__esm(()=>{init_methods();init_methods();init_alpha();init_alpha();init_checkpoints();init_checkpoints();init_jobs();init_jobs();FineTuning=class FineTuning extends APIResource{constructor(){super(...arguments);this.methods=new Methods(this._client),this.jobs=new Jobs(this._client),this.checkpoints=new Checkpoints(this._client),this.alpha=new Alpha(this._client)}};FineTuning.Methods=Methods;FineTuning.Jobs=Jobs;FineTuning.FineTuningJobsPage=FineTuningJobsPage;FineTuning.FineTuningJobEventsPage=FineTuningJobEventsPage;FineTuning.Checkpoints=Checkpoints;FineTuning.Alpha=Alpha});var GraderModels;var init_grader_models=__esm(()=>{GraderModels=class GraderModels extends APIResource{}});var Graders2;var init_graders2=__esm(()=>{init_grader_models();init_grader_models();Graders2=class Graders2 extends APIResource{constructor(){super(...arguments);this.graderModels=new GraderModels(this._client)}};Graders2.GraderModels=GraderModels});var Images;var init_images=__esm(()=>{init_core();Images=class Images extends APIResource{createVariation(body,options){return this._client.post("/images/variations",multipartFormRequestOptions({body,...options}))}edit(body,options){return this._client.post("/images/edits",multipartFormRequestOptions({body,...options}))}generate(body,options){return this._client.post("/images/generations",{body,...options})}}});var Models,ModelsPage;var init_models=__esm(()=>{init_pagination();Models=class Models extends APIResource{retrieve(model,options){return this._client.get(`/models/${model}`,options)}list(options){return this._client.getAPIList("/models",ModelsPage,options)}del(model,options){return this._client.delete(`/models/${model}`,options)}};ModelsPage=class ModelsPage extends Page{};Models.ModelsPage=ModelsPage});var Moderations;var init_moderations=__esm(()=>{Moderations=class Moderations extends APIResource{create(body,options){return this._client.post("/moderations",{body,...options})}}});function maybeParseResponse(response,params){if(!params||!hasAutoParseableInput2(params))return{...response,output_parsed:null,output:response.output.map((item)=>{if(item.type==="function_call")return{...item,parsed_arguments:null};if(item.type==="message")return{...item,content:item.content.map((content)=>({...content,parsed:null}))};else return item})};return parseResponse(response,params)}function parseResponse(response,params){let output=response.output.map((item)=>{if(item.type==="function_call")return{...item,parsed_arguments:parseToolCall2(params,item)};if(item.type==="message"){let content=item.content.map((content2)=>{if(content2.type==="output_text")return{...content2,parsed:parseTextFormat(params,content2.text)};return content2});return{...item,content}}return item}),parsed=Object.assign({},response,{output});if(!Object.getOwnPropertyDescriptor(response,"output_text"))addOutputText(parsed);return Object.defineProperty(parsed,"output_parsed",{enumerable:!0,get(){for(let output2 of parsed.output){if(output2.type!=="message")continue;for(let content of output2.content)if(content.type==="output_text"&&content.parsed!==null)return content.parsed}return null}}),parsed}function parseTextFormat(params,content){if(params.text?.format?.type!=="json_schema")return null;if("$parseRaw"in params.text?.format)return(params.text?.format).$parseRaw(content);return JSON.parse(content)}function hasAutoParseableInput2(params){if(isAutoParsableResponseFormat(params.text?.format))return!0;return!1}function isAutoParsableTool2(tool){return tool?.$brand==="auto-parseable-tool"}function getInputToolByName(input_tools,name){return input_tools.find((tool)=>tool.type==="function"&&tool.name===name)}function parseToolCall2(params,toolCall){let inputTool=getInputToolByName(params.tools??[],toolCall.name);return{...toolCall,...toolCall,parsed_arguments:isAutoParsableTool2(inputTool)?inputTool.$parseRaw(toolCall.arguments):inputTool?.strict?JSON.parse(toolCall.arguments):null}}function addOutputText(rsp){let texts=[];for(let output of rsp.output){if(output.type!=="message")continue;for(let content of output.content)if(content.type==="output_text")texts.push(content.text)}rsp.output_text=texts.join("")}var init_ResponsesParser=__esm(()=>{init_parser()});var InputItems;var init_input_items=__esm(()=>{init_core();init_responses();InputItems=class InputItems extends APIResource{list(responseId,query={},options){if(isRequestOptions(query))return this.list(responseId,{},query);return this._client.getAPIList(`/responses/${responseId}/input_items`,ResponseItemsPage,{query,...options})}}});function finalizeResponse(snapshot,params){return maybeParseResponse(snapshot,params)}var __classPrivateFieldSet6=function(receiver,state,value,kind2,f){if(kind2==="m")throw TypeError("Private method is not writable");if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot write private member to an object whose class did not declare it");return kind2==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet7=function(receiver,state,kind2,f){if(kind2==="a"&&!f)throw TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw TypeError("Cannot read private member from an object whose class did not declare it");return kind2==="m"?f:kind2==="a"?f.call(receiver):f?f.value:state.get(receiver)},_ResponseStream_instances,_ResponseStream_params,_ResponseStream_currentResponseSnapshot,_ResponseStream_finalResponse,_ResponseStream_beginRequest,_ResponseStream_addEvent,_ResponseStream_endRequest,_ResponseStream_accumulateResponse,ResponseStream;var init_ResponseStream=__esm(()=>{init_error();init_EventStream();init_ResponsesParser();ResponseStream=class ResponseStream extends EventStream{constructor(params){super();_ResponseStream_instances.add(this),_ResponseStream_params.set(this,void 0),_ResponseStream_currentResponseSnapshot.set(this,void 0),_ResponseStream_finalResponse.set(this,void 0),__classPrivateFieldSet6(this,_ResponseStream_params,params,"f")}static createResponse(client,params,options){let runner=new ResponseStream(params);return runner._run(()=>runner._createOrRetrieveResponse(client,params,{...options,headers:{...options?.headers,"X-Stainless-Helper-Method":"stream"}})),runner}async _createOrRetrieveResponse(client,params,options){let signal=options?.signal;if(signal){if(signal.aborted)this.controller.abort();signal.addEventListener("abort",()=>this.controller.abort())}__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_beginRequest).call(this);let stream,starting_after=null;if("response_id"in params)stream=await client.responses.retrieve(params.response_id,{stream:!0},{...options,signal:this.controller.signal,stream:!0}),starting_after=params.starting_after??null;else stream=await client.responses.create({...params,stream:!0},{...options,signal:this.controller.signal});this._connected();for await(let event of stream)__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_addEvent).call(this,event,starting_after);if(stream.controller.signal?.aborted)throw new APIUserAbortError;return __classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_endRequest).call(this)}[(_ResponseStream_params=new WeakMap,_ResponseStream_currentResponseSnapshot=new WeakMap,_ResponseStream_finalResponse=new WeakMap,_ResponseStream_instances=new WeakSet,_ResponseStream_beginRequest=function(){if(this.ended)return;__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,void 0,"f")},_ResponseStream_addEvent=function(event,starting_after){if(this.ended)return;let maybeEmit=(name,event2)=>{if(starting_after==null||event2.sequence_number>starting_after)this._emit(name,event2)},response=__classPrivateFieldGet7(this,_ResponseStream_instances,"m",_ResponseStream_accumulateResponse).call(this,event);switch(maybeEmit("event",event),event.type){case"response.output_text.delta":{let output=response.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message"){let content=output.content[event.content_index];if(!content)throw new OpenAIError(`missing content at index ${event.content_index}`);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);maybeEmit("response.output_text.delta",{...event,snapshot:content.text})}break}case"response.function_call_arguments.delta":{let output=response.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="function_call")maybeEmit("response.function_call_arguments.delta",{...event,snapshot:output.arguments});break}default:maybeEmit(event.type,event);break}},_ResponseStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");let snapshot=__classPrivateFieldGet7(this,_ResponseStream_currentResponseSnapshot,"f");if(!snapshot)throw new OpenAIError("request ended without sending any events");__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,void 0,"f");let parsedResponse=finalizeResponse(snapshot,__classPrivateFieldGet7(this,_ResponseStream_params,"f"));return __classPrivateFieldSet6(this,_ResponseStream_finalResponse,parsedResponse,"f"),parsedResponse},_ResponseStream_accumulateResponse=function(event){let snapshot=__classPrivateFieldGet7(this,_ResponseStream_currentResponseSnapshot,"f");if(!snapshot){if(event.type!=="response.created")throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);return snapshot=__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,event.response,"f"),snapshot}switch(event.type){case"response.output_item.added":{snapshot.output.push(event.item);break}case"response.content_part.added":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message")output.content.push(event.part);break}case"response.output_text.delta":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="message"){let content=output.content[event.content_index];if(!content)throw new OpenAIError(`missing content at index ${event.content_index}`);if(content.type!=="output_text")throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);content.text+=event.delta}break}case"response.function_call_arguments.delta":{let output=snapshot.output[event.output_index];if(!output)throw new OpenAIError(`missing output at index ${event.output_index}`);if(output.type==="function_call")output.arguments+=event.delta;break}case"response.completed":{__classPrivateFieldSet6(this,_ResponseStream_currentResponseSnapshot,event.response,"f");break}}return snapshot},Symbol.asyncIterator)](){let pushQueue=[],readQueue=[],done=!1;return this.on("event",(event)=>{let reader=readQueue.shift();if(reader)reader.resolve(event);else pushQueue.push(event)}),this.on("end",()=>{done=!0;for(let reader of readQueue)reader.resolve(void 0);readQueue.length=0}),this.on("abort",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),this.on("error",(err)=>{done=!0;for(let reader of readQueue)reader.reject(err);readQueue.length=0}),{next:async()=>{if(!pushQueue.length){if(done)return{value:void 0,done:!0};return new Promise((resolve,reject)=>readQueue.push({resolve,reject})).then((event2)=>event2?{value:event2,done:!1}:{value:void 0,done:!0})}return{value:pushQueue.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let response=__classPrivateFieldGet7(this,_ResponseStream_finalResponse,"f");if(!response)throw new OpenAIError("stream ended without producing a ChatCompletion");return response}}});var Responses,ResponseItemsPage;var init_responses=__esm(()=>{init_ResponsesParser();init_input_items();init_input_items();init_ResponseStream();init_pagination();Responses=class Responses extends APIResource{constructor(){super(...arguments);this.inputItems=new InputItems(this._client)}create(body,options){return this._client.post("/responses",{body,...options,stream:body.stream??!1})._thenUnwrap((rsp)=>{if("object"in rsp&&rsp.object==="response")addOutputText(rsp);return rsp})}retrieve(responseId,query={},options){return this._client.get(`/responses/${responseId}`,{query,...options,stream:query?.stream??!1})}del(responseId,options){return this._client.delete(`/responses/${responseId}`,{...options,headers:{Accept:"*/*",...options?.headers}})}parse(body,options){return this._client.responses.create(body,options)._thenUnwrap((response)=>parseResponse(response,body))}stream(body,options){return ResponseStream.createResponse(this._client,body,options)}cancel(responseId,options){return this._client.post(`/responses/${responseId}/cancel`,{...options,headers:{Accept:"*/*",...options?.headers}})}};ResponseItemsPage=class ResponseItemsPage extends CursorPage{};Responses.InputItems=InputItems});var Parts;var init_parts=__esm(()=>{init_core();Parts=class Parts extends APIResource{create(uploadId,body,options){return this._client.post(`/uploads/${uploadId}/parts`,multipartFormRequestOptions({body,...options}))}}});var Uploads;var init_uploads2=__esm(()=>{init_parts();init_parts();Uploads=class Uploads extends APIResource{constructor(){super(...arguments);this.parts=new Parts(this._client)}create(body,options){return this._client.post("/uploads",{body,...options})}cancel(uploadId,options){return this._client.post(`/uploads/${uploadId}/cancel`,options)}complete(uploadId,body,options){return this._client.post(`/uploads/${uploadId}/complete`,{body,...options})}};Uploads.Parts=Parts});var allSettledWithThrow=async(promises)=>{let results=await Promise.allSettled(promises),rejected=results.filter((result)=>result.status==="rejected");if(rejected.length){for(let result of rejected)console.error(result.reason);throw Error(`${rejected.length} promise(s) failed - see the above errors`)}let values=[];for(let result of results)if(result.status==="fulfilled")values.push(result.value);return values};var Files3,VectorStoreFilesPage,FileContentResponsesPage;var init_files3=__esm(()=>{init_core();init_pagination();Files3=class Files3 extends APIResource{create(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/files`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,fileId,options){return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(vectorStoreId,fileId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(vectorStoreId,query={},options){if(isRequestOptions(query))return this.list(vectorStoreId,{},query);return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`,VectorStoreFilesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(vectorStoreId,fileId,options){return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(vectorStoreId,body,options){let file=await this.create(vectorStoreId,body,options);return await this.poll(vectorStoreId,file.id,options)}async poll(vectorStoreId,fileId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let fileResponse=await this.retrieve(vectorStoreId,fileId,{...options,headers}).withResponse(),file=fileResponse.data;switch(file.status){case"in_progress":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=fileResponse.response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"failed":case"completed":return file}}}async upload(vectorStoreId,file,options){let fileInfo=await this._client.files.create({file,purpose:"assistants"},options);return this.create(vectorStoreId,{file_id:fileInfo.id},options)}async uploadAndPoll(vectorStoreId,file,options){let fileInfo=await this.upload(vectorStoreId,file,options);return await this.poll(vectorStoreId,fileInfo.id,options)}content(vectorStoreId,fileId,options){return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`,FileContentResponsesPage,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};VectorStoreFilesPage=class VectorStoreFilesPage extends CursorPage{};FileContentResponsesPage=class FileContentResponsesPage extends Page{};Files3.VectorStoreFilesPage=VectorStoreFilesPage;Files3.FileContentResponsesPage=FileContentResponsesPage});var FileBatches;var init_file_batches=__esm(()=>{init_core();init_core();init_files3();FileBatches=class FileBatches extends APIResource{create(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,batchId,options){return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}cancel(vectorStoreId,batchId,options){return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async createAndPoll(vectorStoreId,body,options){let batch=await this.create(vectorStoreId,body);return await this.poll(vectorStoreId,batch.id,options)}listFiles(vectorStoreId,batchId,query={},options){if(isRequestOptions(query))return this.listFiles(vectorStoreId,batchId,{},query);return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`,VectorStoreFilesPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}async poll(vectorStoreId,batchId,options){let headers={...options?.headers,"X-Stainless-Poll-Helper":"true"};if(options?.pollIntervalMs)headers["X-Stainless-Custom-Poll-Interval"]=options.pollIntervalMs.toString();while(!0){let{data:batch,response}=await this.retrieve(vectorStoreId,batchId,{...options,headers}).withResponse();switch(batch.status){case"in_progress":let sleepInterval=5000;if(options?.pollIntervalMs)sleepInterval=options.pollIntervalMs;else{let headerInterval=response.headers.get("openai-poll-after-ms");if(headerInterval){let headerIntervalMs=parseInt(headerInterval);if(!isNaN(headerIntervalMs))sleepInterval=headerIntervalMs}}await sleep(sleepInterval);break;case"failed":case"cancelled":case"completed":return batch}}}async uploadAndPoll(vectorStoreId,{files,fileIds=[]},options){if(files==null||files.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let configuredConcurrency=options?.maxConcurrency??5,concurrencyLimit=Math.min(configuredConcurrency,files.length),client=this._client,fileIterator=files.values(),allFileIds=[...fileIds];async function processFiles(iterator){for(let item of iterator){let fileObj=await client.files.create({file:item,purpose:"assistants"},options);allFileIds.push(fileObj.id)}}let workers=Array(concurrencyLimit).fill(fileIterator).map(processFiles);return await allSettledWithThrow(workers),await this.createAndPoll(vectorStoreId,{file_ids:allFileIds})}}});var VectorStores,VectorStoresPage,VectorStoreSearchResponsesPage;var init_vector_stores=__esm(()=>{init_core();init_file_batches();init_file_batches();init_files3();init_files3();init_pagination();VectorStores=class VectorStores extends APIResource{constructor(){super(...arguments);this.files=new Files3(this._client),this.fileBatches=new FileBatches(this._client)}create(body,options){return this._client.post("/vector_stores",{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}retrieve(vectorStoreId,options){return this._client.get(`/vector_stores/${vectorStoreId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}update(vectorStoreId,body,options){return this._client.post(`/vector_stores/${vectorStoreId}`,{body,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}list(query={},options){if(isRequestOptions(query))return this.list({},query);return this._client.getAPIList("/vector_stores",VectorStoresPage,{query,...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}del(vectorStoreId,options){return this._client.delete(`/vector_stores/${vectorStoreId}`,{...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}search(vectorStoreId,body,options){return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`,VectorStoreSearchResponsesPage,{body,method:"post",...options,headers:{"OpenAI-Beta":"assistants=v2",...options?.headers}})}};VectorStoresPage=class VectorStoresPage extends CursorPage{};VectorStoreSearchResponsesPage=class VectorStoreSearchResponsesPage extends Page{};VectorStores.VectorStoresPage=VectorStoresPage;VectorStores.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage;VectorStores.Files=Files3;VectorStores.VectorStoreFilesPage=VectorStoreFilesPage;VectorStores.FileContentResponsesPage=FileContentResponsesPage;VectorStores.FileBatches=FileBatches});var init_resources=__esm(()=>{init_audio();init_batches();init_beta();init_completions3();init_containers();init_embeddings();init_evals();init_files2();init_fine_tuning();init_graders2();init_images();init_models();init_moderations();init_responses();init_uploads2();init_vector_stores();init_chat2();init_shared()});var exports_openai={};__export(exports_openai,{toFile:()=>toFile,fileFromPath:()=>fileFromPath,default:()=>openai_default,UnprocessableEntityError:()=>UnprocessableEntityError,RateLimitError:()=>RateLimitError,PermissionDeniedError:()=>PermissionDeniedError,OpenAIError:()=>OpenAIError,OpenAI:()=>OpenAI,NotFoundError:()=>NotFoundError,InternalServerError:()=>InternalServerError,ConflictError:()=>ConflictError,BadRequestError:()=>BadRequestError,AzureOpenAI:()=>AzureOpenAI,AuthenticationError:()=>AuthenticationError,APIUserAbortError:()=>APIUserAbortError,APIError:()=>APIError,APIConnectionTimeoutError:()=>APIConnectionTimeoutError,APIConnectionError:()=>APIConnectionError});var _a,OpenAI,AzureOpenAI,_deployments_endpoints,API_KEY_SENTINEL="<Missing Key>",openai_default;var init_openai=__esm(()=>{init_qs();init_core();init_error();init_uploads();init_resources();init_batches();init_completions3();init_embeddings();init_files2();init_images();init_models();init_moderations();init_audio();init_beta();init_chat();init_containers();init_evals();init_fine_tuning();init_graders2();init_responses();init_uploads2();init_vector_stores();init_completions();init_uploads();init_error();OpenAI=class OpenAI extends APIClient{constructor({baseURL=readEnv("OPENAI_BASE_URL"),apiKey=readEnv("OPENAI_API_KEY"),organization=readEnv("OPENAI_ORG_ID")??null,project=readEnv("OPENAI_PROJECT_ID")??null,...opts}={}){if(apiKey===void 0)throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let options={apiKey,organization,project,...opts,baseURL:baseURL||"https://api.openai.com/v1"};if(!options.dangerouslyAllowBrowser&&isRunningInBrowser())throw new OpenAIError(`It looks like you're running in a browser-like environment.
|
|
12
|
+
|
|
13
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
14
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
15
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
16
|
+
|
|
17
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
18
|
+
|
|
19
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
20
|
+
`);super({baseURL:options.baseURL,timeout:options.timeout??600000,httpAgent:options.httpAgent,maxRetries:options.maxRetries,fetch:options.fetch});this.completions=new Completions3(this),this.chat=new Chat(this),this.embeddings=new Embeddings(this),this.files=new Files2(this),this.images=new Images(this),this.audio=new Audio(this),this.moderations=new Moderations(this),this.models=new Models(this),this.fineTuning=new FineTuning(this),this.graders=new Graders2(this),this.vectorStores=new VectorStores(this),this.beta=new Beta(this),this.batches=new Batches(this),this.uploads=new Uploads(this),this.responses=new Responses(this),this.evals=new Evals(this),this.containers=new Containers(this),this._options=options,this.apiKey=apiKey,this.organization=organization,this.project=project}defaultQuery(){return this._options.defaultQuery}defaultHeaders(opts){return{...super.defaultHeaders(opts),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(opts){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(query){return stringify(query,{arrayFormat:"brackets"})}};_a=OpenAI;OpenAI.OpenAI=_a;OpenAI.DEFAULT_TIMEOUT=600000;OpenAI.OpenAIError=OpenAIError;OpenAI.APIError=APIError;OpenAI.APIConnectionError=APIConnectionError;OpenAI.APIConnectionTimeoutError=APIConnectionTimeoutError;OpenAI.APIUserAbortError=APIUserAbortError;OpenAI.NotFoundError=NotFoundError;OpenAI.ConflictError=ConflictError;OpenAI.RateLimitError=RateLimitError;OpenAI.BadRequestError=BadRequestError;OpenAI.AuthenticationError=AuthenticationError;OpenAI.InternalServerError=InternalServerError;OpenAI.PermissionDeniedError=PermissionDeniedError;OpenAI.UnprocessableEntityError=UnprocessableEntityError;OpenAI.toFile=toFile;OpenAI.fileFromPath=fileFromPath;OpenAI.Completions=Completions3;OpenAI.Chat=Chat;OpenAI.ChatCompletionsPage=ChatCompletionsPage;OpenAI.Embeddings=Embeddings;OpenAI.Files=Files2;OpenAI.FileObjectsPage=FileObjectsPage;OpenAI.Images=Images;OpenAI.Audio=Audio;OpenAI.Moderations=Moderations;OpenAI.Models=Models;OpenAI.ModelsPage=ModelsPage;OpenAI.FineTuning=FineTuning;OpenAI.Graders=Graders2;OpenAI.VectorStores=VectorStores;OpenAI.VectorStoresPage=VectorStoresPage;OpenAI.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage;OpenAI.Beta=Beta;OpenAI.Batches=Batches;OpenAI.BatchesPage=BatchesPage;OpenAI.Uploads=Uploads;OpenAI.Responses=Responses;OpenAI.Evals=Evals;OpenAI.EvalListResponsesPage=EvalListResponsesPage;OpenAI.Containers=Containers;OpenAI.ContainerListResponsesPage=ContainerListResponsesPage;AzureOpenAI=class AzureOpenAI extends OpenAI{constructor({baseURL=readEnv("OPENAI_BASE_URL"),apiKey=readEnv("AZURE_OPENAI_API_KEY"),apiVersion=readEnv("OPENAI_API_VERSION"),endpoint,deployment,azureADTokenProvider,dangerouslyAllowBrowser,...opts}={}){if(!apiVersion)throw new OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof azureADTokenProvider==="function")dangerouslyAllowBrowser=!0;if(!azureADTokenProvider&&!apiKey)throw new OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(azureADTokenProvider&&apiKey)throw new OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(apiKey??(apiKey=API_KEY_SENTINEL),opts.defaultQuery={...opts.defaultQuery,"api-version":apiVersion},!baseURL){if(!endpoint)endpoint=process.env.AZURE_OPENAI_ENDPOINT;if(!endpoint)throw new OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");baseURL=`${endpoint}/openai`}else if(endpoint)throw new OpenAIError("baseURL and endpoint are mutually exclusive");super({apiKey,baseURL,...opts,...dangerouslyAllowBrowser!==void 0?{dangerouslyAllowBrowser}:{}});this.apiVersion="",this._azureADTokenProvider=azureADTokenProvider,this.apiVersion=apiVersion,this.deploymentName=deployment}buildRequest(options,props={}){if(_deployments_endpoints.has(options.path)&&options.method==="post"&&options.body!==void 0){if(!isObj(options.body))throw Error("Expected request body to be an object");let model=this.deploymentName||options.body.model||options.__metadata?.model;if(model!==void 0&&!this.baseURL.includes("/deployments"))options.path=`/deployments/${model}${options.path}`}return super.buildRequest(options,props)}async _getAzureADToken(){if(typeof this._azureADTokenProvider==="function"){let token=await this._azureADTokenProvider();if(!token||typeof token!=="string")throw new OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);return token}return}authHeaders(opts){return{}}async prepareOptions(opts){if(opts.headers?.["api-key"])return super.prepareOptions(opts);let token=await this._getAzureADToken();if(opts.headers??(opts.headers={}),token)opts.headers.Authorization=`Bearer ${token}`;else if(this.apiKey!==API_KEY_SENTINEL)opts.headers["api-key"]=this.apiKey;else throw new OpenAIError("Unable to handle auth");return super.prepareOptions(opts)}};_deployments_endpoints=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/images/edits"]),openai_default=OpenAI});import{Elysia as Elysia2}from"elysia";import{Elysia}from"elysia";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
|
|
21
|
+
`);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}},BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};var CONTEXT_PROVIDER_TYPE="context",REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function registerContextProvider(provider,hostServices){if(!provider||typeof provider.name!=="string"||provider.name.length===0)throw Error("ContextProvider.name is required");if(typeof provider.getContext!=="function")throw Error("ContextProvider.getContext must be a function");getRegistry().set(provider.name,provider),hostServices?.serviceRegistry?.registerProvider?.(CONTEXT_PROVIDER_TYPE,provider,provider.name)}function listContextProviders(){return Array.from(getRegistry().values())}function getContextProvider(name){return getRegistry().get(name)}var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;registerContextProvider(provider){registerContextProvider(provider,this.hostServices)}listContextProviders(){return listContextProviders()}getContextProvider(name){return getContextProvider(name)}getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(reg.getProviderByName)return reg.getProviderByName(type,name);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}withCliContribution(contribution){let contributors=this.hostServices?.cliContributors;if(!contributors)return;for(let section of contribution.statusSections??[])contributors.addStatusSection?.(section);for(let check of contribution.doctorChecks??[])contributors.addDoctorCheck?.(check)}};var PROVIDER_NAME="codex",CLI_COMMAND="codex";function platformExeName(base){return process.platform==="win32"?`${base}.exe`:base}function resolveCliBin(){let found=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(CLI_COMMAND,{PATH:process.env.PATH}):null;if(found)return found;return platformExeName(CLI_COMMAND)}var CLI_BIN=resolveCliBin(),DISPLAY_NAME="OpenAI Codex",DEFAULT_MODEL="gpt-4.1-mini",DEFAULT_MAX_TOKENS=16384,API_PREFIX=`/api/ai-${PROVIDER_NAME}`,SUPPORTED_MODES=["sdk","cli"],CLI_INSTALL_COMMAND=["npm","install","-g","@openai/codex"],CODEX_MODELS=[{id:"codex-mini-latest",name:"Codex Mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!1,supportsStreaming:!0,inputPricePerMToken:1.5,outputPricePerMToken:6},{id:"gpt-4.1",name:"GPT-4.1",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:2,outputPricePerMToken:8},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.4,outputPricePerMToken:1.6},{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",provider:PROVIDER_NAME,contextWindow:1047576,maxOutputTokens:32768,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:0.1,outputPricePerMToken:0.4},{id:"o4-mini",name:"o4-mini",provider:PROVIDER_NAME,contextWindow:200000,maxOutputTokens:1e5,supportsVision:!0,supportsStreaming:!0,inputPricePerMToken:1.1,outputPricePerMToken:4.4}];class CodexSdkAdapter{mode="sdk";client=null;async getClient(){if(this.client)return this.client;try{let mod=await Promise.resolve().then(() => (init_openai(),exports_openai)),OpenAI2=mod.default??mod;return this.client=new OpenAI2({apiKey:process.env.OPENAI_API_KEY}),this.client}catch{throw Error("Failed to load openai SDK. Install it with: bun add openai")}}async sendPrompt(prompt,config,_signal){let client=await this.getClient(),startTime=Date.now(),params={model:config.model||DEFAULT_MODEL,input:prompt};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let response=await client.responses.create(params),durationMs=Date.now()-startTime;return{content:this.extractResponseText(response),model:response.model,inputTokens:response.usage.input_tokens,outputTokens:response.usage.output_tokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async streamPrompt(prompt,config,onChunk,_signal){let client=await this.getClient(),startTime=Date.now(),model=config.model||DEFAULT_MODEL,params={model,input:prompt,stream:!0};if(config.systemPrompt)params.instructions=config.systemPrompt;if(config.maxTokens)params.max_output_tokens=config.maxTokens;let stream=client.responses.create(params),collectedText=[],finalModel=model,inputTokens=0,outputTokens=0;for await(let event of stream)if(event.type==="response.output_text.delta"&&event.delta)collectedText.push(event.delta),onChunk({type:"text",content:event.delta});else if(event.type==="response.completed"){let completed=event;if(completed.response)finalModel=completed.response.model,inputTokens=completed.response.usage.input_tokens,outputTokens=completed.response.usage.output_tokens}let durationMs=Date.now()-startTime,content=collectedText.join("");if(inputTokens===0&&outputTokens===0)inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4);return onChunk({type:"done",content:""}),{content,model:finalModel,inputTokens,outputTokens,durationMs,metadata:{provider:PROVIDER_NAME,mode:"sdk"}}}async healthCheck(){try{return await this.getClient(),{ok:!0,message:`${DISPLAY_NAME} SDK ready (API key configured)`}}catch(err){return{ok:!1,message:err instanceof Error?err.message:"SDK initialization failed"}}}extractResponseText(response){let parts=[];for(let output of response.output)if(output.type==="message"&&output.content){for(let block of output.content)if(block.type==="output_text"&&block.text)parts.push(block.text)}return parts.join("")}}function permissionFlags(mode){switch(mode){case"plan":return["-a","untrusted","--sandbox","read-only"];case"fullAuto":return["-a","never","--sandbox","workspace-write"];case"acceptEdits":default:return["-a","on-request","--sandbox","workspace-write"]}}class CodexCliAdapter{mode="cli";buildCliArgs(config,prompt){let args=["--quiet",...permissionFlags(config.permissionMode)];if(config.model)args.push("--model",config.model);return args.push(prompt),args}async sendPrompt(prompt,config){let startTime=Date.now(),args=this.buildCliArgs(config,prompt),proc=Bun.spawn([CLI_BIN,...args],{stdout:"pipe",stderr:"pipe",cwd:config.workingDirectory||process.cwd(),timeout:config.providerConfig?.timeoutMs||300000}),stdout=await new Response(proc.stdout).text(),stderr=await new Response(proc.stderr).text(),exitCode=await proc.exited,durationMs=Date.now()-startTime;if(exitCode!==0&&!stdout)throw Error(`${DISPLAY_NAME} CLI exited with code ${exitCode}: ${stderr}`);let content=stdout.trim()||stderr.trim(),inputTokens=Math.ceil(prompt.length/4),outputTokens=Math.ceil(content.length/4),model=config.model||DEFAULT_MODEL;return{content,model,inputTokens,outputTokens,durationMs,metadata:{exitCode,provider:PROVIDER_NAME,mode:"cli"}}}async streamPrompt(prompt,config,onChunk){let result=await this.sendPrompt(prompt,config);return onChunk({type:"text",content:result.content}),onChunk({type:"done",content:""}),result}async healthCheck(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return{ok:!0,message:`${DISPLAY_NAME} CLI ${proc.stdout.toString().trim()}`};return{ok:!1,message:`${DISPLAY_NAME} CLI not available (exit code ${proc.exitCode})`}}catch{return{ok:!1,message:`${DISPLAY_NAME} CLI not installed or not in PATH`}}}}class CodexProvider{name=PROVIDER_NAME;sessions=new Map;logIngester=null;hostServices=null;logger=null;activeMode=null;adapter=null;setHostServices(hs){this.hostServices=hs,this.logger=new BoundLogger(hs.logger,`${PROVIDER_NAME}-provider`);let registry2=new ProviderRegistry(hs);this.logIngester=registry2.getProvider("ai","log-ingester")??null}getSupportedModes(){return[...SUPPORTED_MODES]}getDisplayName(){return DISPLAY_NAME}getPrereqApiPrefix(){return API_PREFIX}getMode(){if(this.activeMode)return this.activeMode;return this.detectMode()}setMode(mode){if(!SUPPORTED_MODES.includes(mode))throw Error(`${DISPLAY_NAME} does not support ${mode} mode`);this.activeMode=mode,this.adapter=null,this.log("info",`Mode explicitly set to: ${mode}`)}detectMode(){if(process.env.OPENAI_API_KEY)return"sdk";try{if(Bun.which(CLI_COMMAND,{PATH:process.env.PATH}))return"cli"}catch{}return"sdk"}getAdapter(){if(this.adapter)return this.adapter;let mode=this.getMode();return this.adapter=mode==="sdk"?new CodexSdkAdapter:new CodexCliAdapter,this.activeMode=mode,this.log("info",`Adapter initialized in ${mode} mode`),this.adapter}async createSession(config){let id=config.providerConfig?.sessionId||crypto.randomUUID(),now=new Date().toISOString(),existing=this.sessions.get(id);if(existing)return existing.status="active",existing.updatedAt=now,this.toAISession(existing);let session={id,config,status:"active",stats:{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0},abortController:null,files:[],createdAt:now,updatedAt:now};return this.sessions.set(id,session),this.log("info",`Session created: ${id} (${config.name})`),this.toAISession(session)}async sendPrompt(sessionId,prompt,context){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let result=await this.getAdapter().sendPrompt(fullPrompt,session.config,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async streamPrompt(sessionId,prompt,context,onChunk){let session=this.getSession(sessionId);session.status="processing",session.updatedAt=new Date().toISOString();let abortController=new AbortController;session.abortController=abortController;let fullPrompt=this.buildFullPrompt(prompt,context,session.files);this.logIngester?.append({sessionId,type:"input",content:prompt});try{let adapter=this.getAdapter(),chunkHandler=onChunk??((_c)=>{}),result=await adapter.streamPrompt(fullPrompt,session.config,chunkHandler,abortController.signal);return this.updateSessionStats(session,result.inputTokens,result.outputTokens),this.logIngester?.append({sessionId,type:"output",content:result.content,tokenCount:result.outputTokens,model:result.model,durationMs:result.durationMs}),{content:result.content,model:result.model,inputTokens:result.inputTokens,outputTokens:result.outputTokens,durationMs:result.durationMs,metadata:result.metadata}}catch(err){session.status="error",session.updatedAt=new Date().toISOString();let errorMsg=err instanceof Error?err.message:"Unknown error";throw this.logIngester?.append({sessionId,type:"error",content:errorMsg}),err}finally{session.abortController=null}}async listModels(){return[...CODEX_MODELS]}async cancelRequest(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.abortController)session.abortController.abort(),session.abortController=null,session.status="active",session.updatedAt=new Date().toISOString(),this.log("info",`Request cancelled for session: ${sessionId}`)}getCapabilities(){let mode=this.getMode();return{streaming:mode==="sdk",vision:mode==="sdk",fileAttachments:!0,toolUse:!1,mcpSupport:!1,voiceMode:!1,cancelSupport:mode==="sdk",modelListing:!0}}async attachFiles(sessionId,files){let session=this.getSession(sessionId);session.files.push(...files),session.updatedAt=new Date().toISOString(),this.log("debug",`Attached ${files.length} file(s) to session ${sessionId}`)}async getSessionLogs(_sessionId,_filter){return[]}async getUsageStats(sessionId){return this.sessions.get(sessionId)?.stats??{inputTokens:0,outputTokens:0,requestCount:0,estimatedCostUsd:0}}async configureSession(sessionId,config){let session=this.getSession(sessionId);Object.assign(session.config,config),session.updatedAt=new Date().toISOString()}async destroySession(sessionId){let session=this.sessions.get(sessionId);if(session){if(session.abortController)session.abortController.abort(),session.abortController=null;session.status="terminated",session.files=[],session.updatedAt=new Date().toISOString(),this.log("info",`Session terminated: ${sessionId}`)}}async listSessions(){return Array.from(this.sessions.values()).map((s)=>this.toAISession(s))}async getSessionStatus(sessionId){return this.sessions.get(sessionId)?.status??"terminated"}async healthCheck(){return this.getAdapter().healthCheck()}getCliLaunchSpec(){let env={},apiKey=process.env.OPENAI_API_KEY?.trim();if(apiKey)env.OPENAI_API_KEY=apiKey;return{binary:CLI_COMMAND,env}}async sdkOneShot(opts){let adapter=new CodexSdkAdapter,config={name:"vibe-ai-sdk",agentType:PROVIDER_NAME,model:opts.model??DEFAULT_MODEL,maxTokens:opts.maxTokens??DEFAULT_MAX_TOKENS,providerConfig:opts.extras},result=await adapter.sendPrompt(opts.prompt,config);return{text:result.content,usage:{inputTokens:result.inputTokens,outputTokens:result.outputTokens,model:result.model,durationMs:result.durationMs}}}getSession(sessionId){let session=this.sessions.get(sessionId);if(!session)throw Error(`Session ${sessionId} not found`);if(session.status==="terminated")throw Error("Session is terminated");return session}buildFullPrompt(prompt,context,files){let fullPrompt=prompt;if(context&&context.length>0){let contextStr=context.map((c)=>`--- Context (${c.type}): ---
|
|
22
|
+
${c.content}`).join(`
|
|
23
|
+
|
|
24
|
+
`);fullPrompt=`${prompt}
|
|
25
|
+
|
|
26
|
+
${contextStr}`}if(files&&files.length>0){let fileStr=files.map((f)=>{let textContent=typeof f.content==="string"?f.content:f.content.toString("utf-8");return`--- File: ${f.filename} (${f.mimeType}, ${f.size} bytes) ---
|
|
27
|
+
${textContent}`}).join(`
|
|
28
|
+
|
|
29
|
+
`);fullPrompt=`${fullPrompt}
|
|
30
|
+
|
|
31
|
+
${fileStr}`}return fullPrompt}updateSessionStats(session,inputTokens,outputTokens){let model=session.config.model||DEFAULT_MODEL,modelInfo=CODEX_MODELS.find((m)=>m.id===model);if(session.stats.inputTokens+=inputTokens,session.stats.outputTokens+=outputTokens,session.stats.requestCount+=1,modelInfo){let cost=inputTokens/1e6*modelInfo.inputPricePerMToken+outputTokens/1e6*modelInfo.outputPricePerMToken;session.stats.estimatedCostUsd+=cost}if(!session.stats.modelBreakdown)session.stats.modelBreakdown={};let breakdown=session.stats.modelBreakdown[model]??{inputTokens:0,outputTokens:0,requestCount:0};breakdown.inputTokens+=inputTokens,breakdown.outputTokens+=outputTokens,breakdown.requestCount+=1,session.stats.modelBreakdown[model]=breakdown,session.status="active",session.updatedAt=new Date().toISOString()}toAISession(s){return{id:s.id,name:s.config.name,status:s.status,agentType:s.config.agentType,provider:PROVIDER_NAME,config:s.config,stats:s.stats,createdAt:s.createdAt,updatedAt:s.updatedAt}}log(level,msg){this.logger?.[level](msg)}}function getCliVersion(){try{let proc=Bun.spawnSync([CLI_BIN,"--version"],{timeout:5000,stdout:"pipe",stderr:"ignore"});if(proc.exitCode===0)return proc.stdout.toString().trim()}catch{}return null}function createPrereqsRoutes(){return new Elysia2({prefix:"/prereqs"}).get("/status",()=>{let version=getCliVersion();return{satisfied:Boolean(version),missing:version?[]:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1,description:`${DISPLAY_NAME} CLI for CLI mode`}]}}).post("/install",()=>{if(getCliVersion())return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};let proc=Bun.spawnSync(CLI_INSTALL_COMMAND,{timeout:120000,stdout:"pipe",stderr:"pipe"});if(proc.exitCode===0)return{ok:!0,installed:[CLI_COMMAND],pendingSudo:[],errors:[]};return{ok:!1,installed:[],pendingSudo:[],errors:[{name:CLI_COMMAND,message:proc.stderr.toString().trim()||`Run manually: ${CLI_INSTALL_COMMAND.join(" ")}`}]}})}var PLUGIN_NAME="codex",PLUGIN_VERSION="1.0.0",provider=new CodexProvider,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"ai.provider.ready",onInit:(hostServices)=>{provider.setHostServices(hostServices),new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emit("ai.provider.ready",{provider:PLUGIN_NAME})},onShutdown:()=>{for(let[id]of provider.sessions)provider.destroySession(id).catch(()=>{})}}),createPlugin=(_ctx)=>({capabilities:{secrets:"read",subprocess:!0,gateway:!1,telemetry:!0},name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"OpenAI Codex AI agent provider for VibeControls (dual-mode: SDK + CLI)",tags:["provider","integration"],apiPrefix:API_PREFIX,prerequisites:[{name:CLI_COMMAND,kind:"npm",requiresSudo:!1}],providers:{ai:provider},createRoutes:()=>createPrereqsRoutes(),onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop});export{permissionFlags,createPlugin};
|
package/package.json
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vibecontrols/vibe-plugin-ai-codex",
|
|
3
|
+
"version": "2026.601.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"description": "OpenAI Codex AI agent provider for VibeControls Agent",
|
|
7
|
+
"engines": {
|
|
8
|
+
"bun": ">=1.3.14"
|
|
9
|
+
},
|
|
10
|
+
"author": {
|
|
11
|
+
"name": "Vignesh T.V",
|
|
12
|
+
"url": "https://github.com/tvvignesh"
|
|
13
|
+
},
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun --minify-syntax --minify-whitespace --external elysia && tsc --emitDeclarationOnly --declaration --outDir ./dist",
|
|
17
|
+
"dev": "tsc --watch",
|
|
18
|
+
"lint": "eslint ./src",
|
|
19
|
+
"format": "bunx prettier . --write",
|
|
20
|
+
"format:check": "bunx prettier . --check",
|
|
21
|
+
"type:check": "tsc --noEmit",
|
|
22
|
+
"clean": "rimraf dist",
|
|
23
|
+
"prebuild": "bun run clean",
|
|
24
|
+
"prepublishOnly": "bun run build",
|
|
25
|
+
"sanity": "bun run format:check && bun run lint && bun run type:check && bun run build"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@vibecontrols/plugin-sdk": "2026.601.1",
|
|
29
|
+
"elysia": "^1.3.0",
|
|
30
|
+
"openai": "^4.80.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@eslint/js": "^10.0.1",
|
|
34
|
+
"@types/node": "^22.0.0",
|
|
35
|
+
"bun-types": "^1.3.9",
|
|
36
|
+
"eslint": "^9.30.1",
|
|
37
|
+
"globals": "^17.3.0",
|
|
38
|
+
"prettier": "^3.6.2",
|
|
39
|
+
"rimraf": "^6.0.1",
|
|
40
|
+
"typescript": "^5.9.3",
|
|
41
|
+
"typescript-eslint": "^8.56.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@vibecontrols/agent": ">=2.0.0",
|
|
45
|
+
"@vibecontrols/vibe-plugin-ai": "2026.509.1"
|
|
46
|
+
},
|
|
47
|
+
"peerDependenciesMeta": {
|
|
48
|
+
"@vibecontrols/agent": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"keywords": [
|
|
53
|
+
"vibecontrols",
|
|
54
|
+
"vibe",
|
|
55
|
+
"vibe-plugin",
|
|
56
|
+
"codex",
|
|
57
|
+
"ai",
|
|
58
|
+
"bun"
|
|
59
|
+
],
|
|
60
|
+
"repository": {
|
|
61
|
+
"type": "git",
|
|
62
|
+
"url": "git+https://github.com/algoshred/vibe-plugin-ai-codex.git"
|
|
63
|
+
},
|
|
64
|
+
"bugs": {
|
|
65
|
+
"url": "https://github.com/algoshred/vibe-plugin-ai-codex/issues"
|
|
66
|
+
},
|
|
67
|
+
"homepage": "https://vibecontrols.com",
|
|
68
|
+
"publishConfig": {
|
|
69
|
+
"access": "public",
|
|
70
|
+
"registry": "https://registry.npmjs.org/"
|
|
71
|
+
},
|
|
72
|
+
"files": [
|
|
73
|
+
"dist/**/*",
|
|
74
|
+
"!dist/**/*.map",
|
|
75
|
+
"README.md",
|
|
76
|
+
"LICENSE"
|
|
77
|
+
],
|
|
78
|
+
"overrides": {
|
|
79
|
+
"lodash": ">=4.17.21",
|
|
80
|
+
"lodash-es": ">=4.17.21",
|
|
81
|
+
"dompurify": ">=3.3.4",
|
|
82
|
+
"fast-xml-parser": ">=4.5.5",
|
|
83
|
+
"@xmldom/xmldom": ">=0.8.12",
|
|
84
|
+
"swiper": ">=12.1.2",
|
|
85
|
+
"brace-expansion": ">=1.1.13",
|
|
86
|
+
"follow-redirects": ">=1.15.12",
|
|
87
|
+
"smol-toml": ">=1.6.1",
|
|
88
|
+
"axios": ">=1.15.0",
|
|
89
|
+
"flatted": ">=3.4.1",
|
|
90
|
+
"yaml": ">=2.8.3",
|
|
91
|
+
"picomatch": ">=2.3.2",
|
|
92
|
+
"immutable": ">=3.8.3",
|
|
93
|
+
"minimatch": ">=3.1.3"
|
|
94
|
+
}
|
|
95
|
+
}
|