promptgun 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -14
- package/build/index.d.ts +32 -2
- package/build/index.js +1 -1
- package/build/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,29 +1,34 @@
|
|
|
1
1
|
# Promptgun
|
|
2
2
|
|
|
3
|
-
The simplest, most advanced LLM prompting and agent library
|
|
3
|
+
The simplest, most advanced LLM prompting and agent client library for OpenAI:
|
|
4
|
+
|
|
5
|
+
- **Type-safe** structured output, even when streaming
|
|
6
|
+
- **Function calling / tools** with inline or reusable definitions
|
|
7
|
+
- **Feedback loops**, response iteration based on response check
|
|
8
|
+
- **Conversations**: trivally do multiple prompts while retaining context
|
|
9
|
+
- **Strict JSON mode**: a prompting superpower for guaranteed schema compliance
|
|
10
|
+
- **Image generation**: easy-to-use, well-documented, type-safe
|
|
11
|
+
- **Live model docs right in your IDE**, hourly-updated from OpenAI website
|
|
12
|
+
- Future: multi-provider support (drop me a message if you need it)
|
|
13
|
+
|
|
14
|
+
For example:
|
|
4
15
|
|
|
5
16
|
```typescript
|
|
6
17
|
const restaurants = ai
|
|
7
18
|
.chat("Recommend 3 restaurants in Paris perfect for today's weather")
|
|
8
|
-
.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const response = await fetch(`https://api.weather.com/v1/current?location=${location}`)
|
|
14
|
-
return response.json()
|
|
15
|
-
}
|
|
16
|
-
})
|
|
17
|
-
)
|
|
18
|
-
.getArray(spec => spec.object(o => o
|
|
19
|
+
.tool('get-weather', s => s.string(), async loc => {
|
|
20
|
+
const res = await fetch(`https://api.weather.com/v1/current?location=${loc}`)
|
|
21
|
+
return res.json()
|
|
22
|
+
})
|
|
23
|
+
.getArray(s => s.object(o => o
|
|
19
24
|
.hasString('name')
|
|
20
25
|
.hasString('cuisine')
|
|
21
26
|
.hasString('weatherReason', 'Why this restaurant fits today\'s weather')
|
|
22
27
|
))
|
|
23
28
|
|
|
24
|
-
// Process each restaurant as it streams in
|
|
25
29
|
for await (const restaurant of restaurants) {
|
|
26
|
-
|
|
30
|
+
// do stuff with a type-safe restaurant object,
|
|
31
|
+
// streamed as soon as they come in
|
|
27
32
|
}
|
|
28
33
|
```
|
|
29
34
|
|
|
@@ -65,6 +70,7 @@ for await (const parsedPartialJson of parsedPartialJsonStream) {
|
|
|
65
70
|
```
|
|
66
71
|
|
|
67
72
|
### Data output - single
|
|
73
|
+
Simply put `await` in front of your prompt to make it a single output rather than a streamed one:
|
|
68
74
|
```typescript
|
|
69
75
|
const restaurants /* type: {name: string, address?: string}[] */ = await ai
|
|
70
76
|
.chat('Give 5 top restaurants in London')
|
|
@@ -201,6 +207,112 @@ const result = await ai
|
|
|
201
207
|
- **Text responses**: `.check()` works with both JSON (`.getObject()`, `.getArray()`) and text responses
|
|
202
208
|
- **Feedback loop**: Failed validations are sent back to the AI as feedback, allowing it to learn and correct
|
|
203
209
|
|
|
210
|
+
## Tools
|
|
211
|
+
|
|
212
|
+
### Inline Tool Definitions
|
|
213
|
+
Tools can be added directly using `.tool()`:
|
|
214
|
+
```typescript
|
|
215
|
+
const result = await ai
|
|
216
|
+
.chat("What's the weather in Paris?")
|
|
217
|
+
.tool('get-weather', s => s.string(), async location => {
|
|
218
|
+
const res = await fetch(`https://api.weather.com/v1/current?location=${location}`)
|
|
219
|
+
return res.json()
|
|
220
|
+
})
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Reusable Tool Definitions
|
|
224
|
+
For tools used across multiple prompts, define them once with `aiTool()`:
|
|
225
|
+
```typescript
|
|
226
|
+
const getWeather = aiTool('get-weather', s => s.string(), async location => {
|
|
227
|
+
const res = await fetch(`https://api.weather.com/v1/current?location=${location}`)
|
|
228
|
+
return res.json()
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
// Use in multiple prompts
|
|
232
|
+
const parisWeather = await ai
|
|
233
|
+
.chat("What's the weather in Paris?")
|
|
234
|
+
.tools(getWeather)
|
|
235
|
+
|
|
236
|
+
const londonWeather = await ai
|
|
237
|
+
.chat("What's the weather in London?")
|
|
238
|
+
.tools(getWeather)
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
You can pass multiple tools using `.tools()`:
|
|
242
|
+
```typescript
|
|
243
|
+
await ai
|
|
244
|
+
.chat("Plan a trip")
|
|
245
|
+
.tools(getWeather, getFlights, getHotels)
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Or add them one by one with `.tool()`:
|
|
249
|
+
```typescript
|
|
250
|
+
await ai
|
|
251
|
+
.chat("Plan a trip")
|
|
252
|
+
.tool(getWeather)
|
|
253
|
+
.tool(getFlights)
|
|
254
|
+
.tool(getHotels)
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
## Strict JSON Mode
|
|
258
|
+
|
|
259
|
+
Enable OpenAI's strict JSON mode for guaranteed type-safe responses using `.strict()`:
|
|
260
|
+
```typescript
|
|
261
|
+
const user = await ai
|
|
262
|
+
.chat("Get user info")
|
|
263
|
+
.getObject(o => o
|
|
264
|
+
.hasString('name')
|
|
265
|
+
.hasNumber('age')
|
|
266
|
+
)
|
|
267
|
+
.strict()
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
### Important: Nullable vs Optional Properties
|
|
271
|
+
|
|
272
|
+
In strict mode, you **cannot use optional properties** (TypeScript's `?`). Instead, use nullable types:
|
|
273
|
+
|
|
274
|
+
```typescript
|
|
275
|
+
// ❌ Not allowed in strict mode - optional properties
|
|
276
|
+
const user = await ai
|
|
277
|
+
.chat("Get user info")
|
|
278
|
+
.getObject(o => o
|
|
279
|
+
.hasString('name')
|
|
280
|
+
.canHaveString('nickname') // ❌ This is {nickname?: string}
|
|
281
|
+
)
|
|
282
|
+
.strict()
|
|
283
|
+
|
|
284
|
+
// ✅ Allowed in strict mode - nullable properties
|
|
285
|
+
const user = await ai
|
|
286
|
+
.chat("Get user info")
|
|
287
|
+
.getObject(o => o
|
|
288
|
+
.hasString('name')
|
|
289
|
+
.has('nickname', s => s.string().orNull()) // ✅ This is {nickname: string | null}
|
|
290
|
+
)
|
|
291
|
+
.strict()
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
**The difference:**
|
|
295
|
+
- **Optional** (`canHaveString`): Property may or may not exist → `{nickname?: string}` → Not allowed in strict mode
|
|
296
|
+
- **Nullable** (`string().orNull()`): Property always exists but value can be null → `{nickname: string | null}` → Allowed in strict mode
|
|
297
|
+
|
|
298
|
+
## Model Selection
|
|
299
|
+
|
|
300
|
+
Switch models using either a string or the `AiModel` enum:
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
// Using a string
|
|
304
|
+
const result = await ai
|
|
305
|
+
.chat('Hello')
|
|
306
|
+
.model('gpt-5')
|
|
307
|
+
|
|
308
|
+
// Using the enum - get in-place documentation!
|
|
309
|
+
const result = await ai
|
|
310
|
+
.chat('Hello')
|
|
311
|
+
.model(AiModel.GPT_5)
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
**Why use the enum?** The `AiModel` enum provides in-place documentation for each model, updated hourly from the OpenAI website. This gives you real-time information about capabilities, context windows, and pricing right in your IDE.
|
|
315
|
+
|
|
204
316
|
## Other options
|
|
205
317
|
Using the flex tier
|
|
206
318
|
```typescript
|
package/build/index.d.ts
CHANGED
|
@@ -1125,6 +1125,17 @@ export declare const AiModel: {
|
|
|
1125
1125
|
|
|
1126
1126
|
export declare type AiModelId = (typeof AiModel)[keyof typeof AiModel];
|
|
1127
1127
|
|
|
1128
|
+
export declare function aiTool<T>(name: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): ToolDefinition<T>;
|
|
1129
|
+
|
|
1130
|
+
export declare function aiTool<T>(name: string, description: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): ToolDefinition<T>;
|
|
1131
|
+
|
|
1132
|
+
export declare function aiTool<T>(config: {
|
|
1133
|
+
name: string;
|
|
1134
|
+
description?: string;
|
|
1135
|
+
parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>;
|
|
1136
|
+
function: ToolFunction<T>;
|
|
1137
|
+
}): ToolDefinition<T>;
|
|
1138
|
+
|
|
1128
1139
|
export declare type AnyJson = string | null | boolean | number | JsonArray | JsonObject;
|
|
1129
1140
|
|
|
1130
1141
|
export declare type ApiKeyChain = {
|
|
@@ -1279,6 +1290,14 @@ export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Prom
|
|
|
1279
1290
|
getObject<T_obj extends {}>(properties: (arg: TypeMemberSpec<{}>) => TypeMemberSpec<T_obj>): JsonPrompt<PSArgs, T_obj>;
|
|
1280
1291
|
getArray<T_arr extends AnyJson>(element: (arg: EmptyTypeSpec<unknown>) => TypeSpec<T_arr>): JsonArrayPrompt<PSArgs, T_arr>;
|
|
1281
1292
|
getAny(): JsonPrompt<PSArgs, AnyJson>;
|
|
1293
|
+
tool<T>(name: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): BasicPrompt<PSArgs>;
|
|
1294
|
+
tool<T>(name: string, description: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): BasicPrompt<PSArgs>;
|
|
1295
|
+
tool<T>(config: {
|
|
1296
|
+
name: string;
|
|
1297
|
+
description?: string;
|
|
1298
|
+
parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>;
|
|
1299
|
+
function: ToolFunction<T>;
|
|
1300
|
+
}): BasicPrompt<PSArgs>;
|
|
1282
1301
|
tools(tools: ToolDefinition[]): this;
|
|
1283
1302
|
tools(...tools: (ToolDefinition | undefined)[]): this;
|
|
1284
1303
|
private getResponseAsString;
|
|
@@ -1320,12 +1339,15 @@ export declare type DeepPartial<T> = T extends object ? {
|
|
|
1320
1339
|
[P in keyof T]?: DeepPartial<T[P]>;
|
|
1321
1340
|
} : T;
|
|
1322
1341
|
|
|
1323
|
-
|
|
1342
|
+
/**
|
|
1343
|
+
* @deprecated Use {@link aiTool} instead
|
|
1344
|
+
*/
|
|
1345
|
+
export declare function defineTool<T>(nameOrConfig: string | {
|
|
1324
1346
|
name: string;
|
|
1325
1347
|
description?: string;
|
|
1326
1348
|
parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>;
|
|
1327
1349
|
function: ToolFunction<T>;
|
|
1328
|
-
}): ToolDefinition<T>;
|
|
1350
|
+
}, parametersOrDescription?: string | ((spec: EmptyTypeSpec<unknown>) => TypeSpec<T>), fnOrParameters?: ToolFunction<T> | ((spec: EmptyTypeSpec<unknown>) => TypeSpec<T>), maybeFn?: ToolFunction<T>): ToolDefinition<T>;
|
|
1329
1351
|
|
|
1330
1352
|
export declare type DeveloperMessage = {
|
|
1331
1353
|
system?: undefined;
|
|
@@ -1639,6 +1661,14 @@ export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends
|
|
|
1639
1661
|
protected getResponse(): Promise<Json>;
|
|
1640
1662
|
private _responseAsStringPromise?;
|
|
1641
1663
|
protected getResponseAsString(): Promise<string>;
|
|
1664
|
+
tool<T>(name: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): JsonPrompt<PSArgs, Json>;
|
|
1665
|
+
tool<T>(name: string, description: string, parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>, fn: ToolFunction<T>): JsonPrompt<PSArgs, Json>;
|
|
1666
|
+
tool<T>(config: {
|
|
1667
|
+
name: string;
|
|
1668
|
+
description?: string;
|
|
1669
|
+
parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>;
|
|
1670
|
+
function: ToolFunction<T>;
|
|
1671
|
+
}): JsonPrompt<PSArgs, Json>;
|
|
1642
1672
|
tools(tools: ToolDefinition[]): this;
|
|
1643
1673
|
tools(...tools: (ToolDefinition | undefined)[]): this;
|
|
1644
1674
|
protected _getResponseAsString(): Promise<string>;
|
package/build/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var t=Object.create,e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.getPrototypeOf,s={}.hasOwnProperty,o=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),a=(o,a,u)=>(u=null!=o?t(n(o)):{},((t,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let o of i(n))!s.call(t,o)&&void 0!==o&&e(t,o,{get:()=>n[o],enumerable:!(a=r(n,o))||a.enumerable});return t})(!a&&o&&o.t?u:e(u,"default",{value:o,enumerable:!0}),o)),u=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=class t{generator;upstream;handleCancel;i=!1;constructor(t,e,i){let n=this;this.generator=async function*(){try{yield*t}catch(t){throw yield r,t}finally{n.i=!0}}(),this.upstream=e,this.handleCancel=i}[Symbol.asyncIterator](){return this}async next(...t){let e=await this.generator.next(t);return e.value!==r?e:await this.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}async cancel(t){if(!this.closed){if(void 0!==this.upstream)return this.upstream.cancel(t);void 0!==this.handleCancel?this.handleCancel(t):await this.throw(t)}}async then(t,e){try{let e=await this.asList();return null!=t?await t(e):e}catch(t){if(null!=e)return e(t);throw t}}async catch(t){try{return this.asList()}catch(e){if(null!=t)return t(e);throw e}}async finally(t){let e=await this.asList();return t?.(),e}get[Symbol.toStringTag](){return"Flux"}subscribe(t){let e=void 0!==t?this.doOnEach(t):this,r=()=>{e.next().then((t=>{t.done||r()})).catch((t=>{console.error(t)}))};return r(),{unsubscribe:()=>this.return()}}filter(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t)&&(yield t)}),this)}untilExcl(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){if(e(t))break;yield t}}),this)}doOnEach(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t),yield t}),this)}doAfterLast(e){let r=this,i=[];return t.constructFromGeneratorFunction((async function*(){for await(let t of r)i.push(t),yield t;await e(i)}),this)}map(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield e(t)}),this)}take(e){let r=this;return t.constructFromGeneratorFunction((async function*(){let t=0;for await(let i of r){if(t>=e){r.cancel();break}t++,yield i}}),this)}flatMap(e,r){let i=this;return t.constructFromGeneratorFunction((async function*(){let n=i[Symbol.asyncIterator](),s=await n.next();if(s.done)return;let o=e(s.value),a=r?.concurrency;Array.isArray(o)?yield*function(t,e,r,i){return async function*(){for(let t of r)yield t;let e=await i.next();for(;!e.done;){let r=t(e.value);for(let t of r)yield t;e=await i.next()}}()}(e,0,o,n):o instanceof t?yield*function(t,e,r,i,n){return async function*(){let s=[e],o=await i.next();for(;!o.done;)s.push(o.value),o=await i.next();let a=Array(s.length),u=new Map,l=new Set,h=0;if(void 0===n)for(let e=0;e<s.length;e++){let i=0===e?r:t(s[e]);a[e]=i,u.set(e,[]),(async()=>{try{for await(let t of i)u.get(e).push(t)}catch(t){u.get(e).push({o:t})}finally{l.add(e)}})()}else{let e=0,i=0,o=()=>{for(;i<n&&e<s.length;){let n=e;e++,i++;let h=0===n?r:t(s[n]);a[n]=h,u.set(n,[]),(async()=>{try{for await(let t of h)u.get(n).push(t)}catch(t){u.get(n).push({o:t})}finally{l.add(n),i--,o()}})()}};o()}for(;h<a.length;){let t=u.get(h);for(;0===t.length&&!l.has(h);)await new Promise((t=>setTimeout(t,1)));for(;t.length>0;){let e=t.shift();if(e&&"object"==typeof e&&"o"in e)throw e.o;yield e}h++}}()}(e,s.value,o,n,a):yield*function(t,e,r,i,n){return async function*(){let s=[],o=[],a=[],u=new Set,l=0,h=0,p=!1,c=0,f=(e,r,i)=>{let l=i||t(e);s[r]=l,l.then((t=>{o[r]=t,u.add(r),void 0!==n&&c--})).catch((t=>{a[r]=t,u.add(r),void 0!==n&&c--})),void 0!==n&&c++};f(e,h++,r);let d=(async()=>{let t=await i.next();for(;!t.done;){if(void 0!==n)for(;c>=n;)await new Promise((t=>setTimeout(t,0)));f(t.value,h++),t=await i.next()}p=!0})();for(;;){for(;!u.has(l);){if(p&&l>=s.length)return;await new Promise((t=>setTimeout(t,0)))}if(p&&l>=s.length)break;if(void 0!==a[l])throw a[l];void 0!==o[l]&&(yield o[l]),l++}await d}()}(e,s.value,o,n,a)}),this)}transform(e){let r=e(this);return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield t}),this)}async reduce(t,e){let r=e;for await(let e of this)r=t(r,e);return r}async asList(){let t=[];for await(let e of this)t.push(e);return t}async whenComplete(){for await(let t of this);}static create(e){let r,i=[],n=[],s=!1,o=t=>{if(s)throw Error("Cannot push to a completed generator");n.length>0?n.shift().resolve({done:!1,value:t}):i.push(t)},a=()=>{for(s=!0;n.length>0;)n.shift().resolve({done:!0,value:void 0})},u=t=>{r={value:t},n.shift()?.reject(t)};return(async()=>{try{await e(o,a,u),(!s||void 0===r)&&a()}catch(t){u(t)}})(),t.fromGenerator({[Symbol.asyncIterator](){return this},next(...t){if(r){let t=r.value;return r=void 0,Promise.reject(t)}if(i.length>0){let t=i.shift();return Promise.resolve({done:!1,value:t})}return s?Promise.resolve({done:!0,value:void 0}):new Promise(((t,e)=>{n.push({resolve:t,reject:e})}))},return:()=>(a(),Promise.resolve({done:!0,value:void 0})),throw:t=>(u(t),Promise.reject(t))})}static just(...e){return t.from(e)}static from(e,r){if(Array.isArray(e))return t.fromArray(e);if("function"==typeof e)return t.fromGeneratorFunction(e,r);if(e instanceof ReadableStream)return t.fromReadableStream(e,r);if(function(t){return null!==t&&"object"==typeof t&&"function"==typeof t.next&&"function"==typeof t.return&&"function"==typeof t.throw&&Symbol.asyncIterator in t}(e))return t.fromGenerator(e,r);throw new TypeError("Source must be an Array, AsyncGenerator, ReadableStream, or a generator function")}static fromArray(e){return t.fromGeneratorFunction((async function*(){for(let t of e)yield t}))}static constructFromGeneratorFunction(e,r,i){return new t(e(),r,i)}static fromGeneratorFunction(e,r){return t.constructFromGeneratorFunction(e,void 0,r)}static fromGenerator(e,r){return new t(e,void 0,r)}static fromReadableStream(e,r){return t.fromGeneratorFunction((async function*(){let t=e.getReader();try{let e;for(;!(e=await t.read()).done;)yield e.value}finally{await t.cancel()}}),r)}get closed(){return this.i}};t.Flux=e;var r={}})),l=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=u();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),h=a(l(),1);function p(t){return!(t.startsWith("gpt-")||t.startsWith("o1-")||"o1"===t||"o3-mini"===t||"o3"===t)}var c=a(l(),1);function f(t,e){let r={url:"https://api.openai.com/v1/responses",method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${e.slice(0,7)}...${e.slice(-4)}`},body:t};return{flux:c.Flux.fromGeneratorFunction((async function*(){let r=new AbortController,i=await fetch("https://api.openai.com/v1/responses",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+e},method:"POST",signal:r.signal,body:JSON.stringify(t)});if(i.status<200||i.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await i.text());throw Error("OpenAPI reported: "+t)}if(null===i.body)throw Error("illegal state");let n="";yield*c.Flux.fromReadableStream(i.body,(()=>r.abort())).map((t=>d.decode(t,{stream:!0}))).flatMap((t=>{n+=t;let e=[],r=n.split("\n\n");n=r.pop()||"";for(let t of r)t.trim()&&e.push(t.trim());return e})).flatMap((t=>{let e=t.split("\n"),r="";for(let t of e)t.startsWith("data: ")&&(r+=t.substring(6));if(!r)return[];try{return[JSON.parse(r)]}catch{return[]}}))})),httpRequest:r}}var d=new TextDecoder,m=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(E).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function y(t){return new g([],t)}function _(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:_(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(..._(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t!==e.value||Number.isNaN(t)?[{expectedType:[e],path:r,value:t}]:[]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var w,g=class t{type;value;constructor(t=[],e){this.type=t,this.value=e}canBeArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}canBeObject(e){let r=e(new t([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}hasString(t){return this.has(t,(t=>t.canBeString()))}hasNumber(t){return this.has(t,(t=>t.canBeNumber()))}canHaveProperty(t,e){return this.has(t,e,!0)}has(e,r,i=!1){let n=1===this.type.length?this.type[0]:void 0;if(void 0===n||"object"!==n.type)throw Error("illegal state");let{type:s}=r(new t([],this.value));return new t([{...n,props:{...n.props,[e]:{optional:i,type:s}}}],this.value)}canBeString(){return new t([...this.type,{type:"string"}],this.value)}canBeNumber(){return new t([...this.type,{type:"number"}],this.value)}canBeBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}canBeConstant(e){return new t([...this.type,{type:"constant",value:e}],this.value)}canBeNull(){return new t([...this.type,{type:"null"}],this.value)}canBeUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}andNothingElse(t={}){let e=_(this.value,this.type,"root",t);if(e.length>0)throw new m(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return _(this.value,this.type,"root",e).length>0?t:this.value}describe(){return v(this.type)}};function v(t,e=0){if(Array.isArray(t))return t.map((t=>v(t,e))).join(" | ");switch(t.type){case"array":return v(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${b(e+1)}${r}: ${v(t.props[r].type,e+1)}`)).join(",\n")+`\n${b(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function b(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function E(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as A}from"dotenv";function T(){if(!w){A();let t=function(){let t="t";t+="ps",t="ht"+t,t+=":",t+="/",t+="/ap",t+="i.pr";let e="i";return e="d.a"+e,e="gri"+e,t+="ompt",t+e}();w=y(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return w}var S=class{constructor(t,e,r,i,n=!1){this.type=t,this.source=e,this.value=r,this.fieldName=i,this.maybeIncomplete=n}},N=class t{jsonBuffer="";highestOffsetParsed=-1;static toJsonTokenFlux(e){return(new t).processDataBuffer(e)}processDataBuffer(t){return t.flatMap((t=>this.getExcerpts(t)))}getExcerpts(t){this.jsonBuffer+=t;let e,r=[],i=new x(this.jsonBuffer);for(;e=this.nextToken(i);)i.currentTokenLocation().getCharOffset()>this.highestOffsetParsed&&!e.maybeIncomplete&&(r.push({token:e}),this.highestOffsetParsed=i.currentTokenLocation().getCharOffset());return r.push({source:t}),r}nextToken(t){let e=t.nextToken();return"string"!=typeof e?e:void 0}},x=class{constructor(t){this.content=t}position=0;currentTokenType;parentFieldName;currentValue=null;context=[];nextToken(){let t=this.position;if(this.position>=this.content.length)return"string-ended";for(;this.position<this.content.length&&/\s/.test(this.content[this.position]);)this.position++;if(this.position>=this.content.length)return"string-ended";let e=e=>this.content.substring(t,e),r=this.content[this.position];switch(r){case"{":return this.position++,this.currentTokenType="START_OBJECT",this.pushContext("object"),new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT";let t=new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,this.popContext("object"),"field"===this.currentContextType&&this.popContext("field"),t}case"[":return this.position++,this.currentTokenType="START_ARRAY",this.pushContext("array"),new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY";let t=new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,this.popContext("array"),"field"===this.currentContextType&&this.popContext("field"),t}case'"':if("object"===this.currentContextType){this.currentTokenType="FIELD_NAME";let t=++this.position,r=this.content.indexOf('"',t);for(;r>=0&&"\\"===this.content[r-1];)r=this.content.indexOf('"',r+1);if(-1===r)return"token-incomplete";let i=this.content.substring(t,r);for(r++;r<this.content.length&&/\s/.test(this.content[r]);)r++;if(r===this.content.length)return"token-incomplete";if(":"!==this.content[r])throw Error("Expected token ':'");r++,this.position=r;let n=new S(this.currentTokenType,e(this.position),i,void 0);return this.parentFieldName=i,this.pushContext("field"),n}{this.currentTokenType="VALUE_STRING";let t=++this.position,r=this.content.indexOf('"',t);for(;r>0&&"\\"===this.content[r-1];)r=this.content.indexOf('"',r+1);if(-1===r)return"token-incomplete";let i=this.content.substring(t,r);this.position=r+1,this.currentValue=i;let n=new S(this.currentTokenType,e(this.position),i,"VALUE_STRING"===this.currentTokenType?this.parentFieldName:void 0);return this.parentFieldName=void 0,"field"===this.currentContextType&&this.popContext("field"),n}case"t":{let t=this.content.substring(this.position,this.position+4);if("true"===t)return this.position+=4,this.currentTokenType="VALUE_TRUE",this.currentValue=!0,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case"f":{let t=this.content.substring(this.position,this.position+5);if("false"===t)return this.position+=5,this.currentTokenType="VALUE_FALSE",this.currentValue=!1,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<5)return"token-incomplete";break}case"n":{let t=this.content.substring(this.position,this.position+4);if("null"===t)return this.position+=4,this.currentTokenType="VALUE_NULL",this.currentValue=null,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case",":return this.position++,this.currentTokenType="COMMA",new S(this.currentTokenType,e(this.position),void 0,void 0,!1);default:if(/[0-9-]/.test(r)){let t="",r=!1;for(;this.position<this.content.length&&(/[0-9]/.test(this.content[this.position])||"-"===this.content[this.position]||"."===this.content[this.position]||"e"===this.content[this.position]||"E"===this.content[this.position]||"+"===this.content[this.position]);)"."===this.content[this.position]&&(r=!0),t+=this.content[this.position++];r?(this.currentTokenType="VALUE_NUMBER_FLOAT",this.currentValue=parseFloat(t)):(this.currentTokenType="VALUE_NUMBER_INT",this.currentValue=parseInt(t,10));let i=this.position>=this.content.length;return"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName,i)}}throw new U(`Invalid JSON at position ${this.position} of content: ${this.content}`)}currentTokenLocation(){return{getCharOffset:()=>this.position}}get currentContextType(){return this.context[this.context.length-1]}pushContext(t){this.context.push(t)}popContext(t){if(0===this.context.length)throw Error("Cannot pop context, context empty");let e=this.currentContextType;if(e!==t)throw Error(`Cannot pop context \`${t}', current context '${e}'`);this.context.pop()}},U=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},P=a(l(),1);function L(t){return null!=t}var j=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new O;receivedExcerpts=[];onElement(t){return this.onElementCallbacks.add(t),this}onProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push(e),this}onJsonStringProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push((t=>{let r=new J,i=[],n=new M;t.onEachExcerpt((t=>{void 0!==t.source&&i.push(t.source);let e=i.join(""),s=this.endsOnUnevenNumberOfBackslashes(e)?e.substring(0,e.length-1):e;i.length=0;let o=s.replace(/\\"/g,'"').substring(1),a=null!=t.token?o.substring(0,o.length-1):o;r.getExcerpts(a).forEach((t=>n.push(t)))})),e(n)})),this}onEachExcerpt(t){return this.onEachExcerptCallbacks.add(t),this.receivedExcerpts.forEach(t),this}async then(t,e){try{let e=await this.getResponseAsPromise();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsPromise()}finally{t?.()}}get[Symbol.toStringTag](){return"StreamedJsonElement"}getResponseAsPromise(){return new Promise((t=>{this.onCompleteAs(t)}))}onComplete(t){this.u(this.toAsync(t),void 0)}u(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.u(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.u((e=>{let r=e.replace(/,$/,""),i=(()=>{try{return JSON.parse(r)}catch(t){throw t.message=`${t.message}. JSON string was: ${r}`,t}})();return t(i)}),void 0)}onCompleteAsString(t){this.u(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.u(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.u(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.u(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.u(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.u(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.u(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.u(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return P.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.u((async()=>e()))}))}whenCompleteAs(){return new Promise((t=>{this.onCompleteAs(t)}))}async push(t){let e=t.token;if(this.onEachExcerptCallbacks.forEach((e=>e(t))),this.isState(k))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(O))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new V,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new R,void this.receivedJson.push(e.source);case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":return this.receivedJson.push(e.source),this.end();default:throw new B(e)}else if(this.isState(V))switch(r){case"FIELD_NAME":case"COMMA":return void this.receivedJson.push(e.source);case"END_OBJECT":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let r=new M;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new V})),this.state=new $(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>{t(r)})),r.push(t)}default:throw new B(e)}else if(this.isState(R))switch(r){case"END_ARRAY":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let e=new M;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new R})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new I(e),e.push(t)}case"COMMA":return void this.receivedJson.push(e.source);default:throw new B(e)}throw Error("Unknown state")}async end(){if(void 0===this.currentToken)throw Error("Illegal state");this.onCompleteCallbacks.forEach((t=>{let e=t.expectedTokenType,r=(()=>{if(void 0===e)return this.receivedJson.join("");if(!e.has(this.currentToken.type))throw Error(`Expected token type ${Array.from(e).join(", ")} but got ${this.currentToken.type}`);return this.currentToken.value})();t.consumer(r)}))}isState(t){return this.state instanceof t}endsOnUnevenNumberOfBackslashes(t){let e=0;for(let r=t.length-1;r>=0&&"\\"===t[r];r--)e++;return e%2==1}toAsync(t){return async e=>{t(e)}}},C=class{},k=class extends C{constructor(t){super(),this.child=t}},O=class extends C{},R=class extends C{},I=class extends k{constructor(t){super(t)}},V=class extends C{},$=class extends k{constructor(t){super(t)}},B=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},J=class{getExcerpts(t){return[{source:t}]}},M=class extends j{constructor(){super()}},F=a(l(),1),G=class extends j{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=F.Flux.fromGeneratorFunction((async function*(){let r;for await(let i of t)void 0!==i.token&&(r?.token?.maybeIncomplete&&r.token.type===i.token.type&&!i.token.maybeIncomplete&&await e.push(i),r=i.token),(void 0===i.token||!i.token.maybeIncomplete)&&await e.push(i),yield i;r?.token?.maybeIncomplete&&await e.push(r)}))}whenComplete(){return this.jsonTokenFlux.then((()=>this.receivedJson.join("")))}asJsonFlux(){return this.jsonTokenFlux.map((t=>t.source)).filter((t=>void 0!==t))}},Y=class{parse(t){return new G(t)}};function D(t){try{return JSON.parse(t)}catch(e){throw Error(`Failed to parse JSON with error '${e.message}'. JSON was: ${t}`)}}function q(t){if(""===t.trim())return;let e=[],r=!1,i=t=>e.push(t),n=(...t)=>{let r=e[e.length-1];if(void 0===r||!t.includes(r))throw Error("illegal state");e.pop()},s=()=>Error(`Illegal state (json: ${t})`);for(let o of t){let t=e.length>0?e[e.length-1]:null,a=!1;if('"'===o)if(null===t)i('"value');else if("["===t||null===t)i('"value');else if("{"===t)i('"prop');else if('"prop":'===t)n('"prop":'),i('"value');else if('"prop'===t)r||(n('"prop'),i('"prop"'));else{if('"value'!==t)throw s();r||n('"value')}else if("["===o){if("["===t||null===t)i("[");else if('"prop":'===t)n('"prop":'),i("[");else if('"prop'!==t&&'"value'!==t)throw s()}else if("{"===o){if(null===t||"["===t||'"prop":'===t)i("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("\\"===o){if('"prop'!==t&&'"value'!==t)throw s();r||(a=!0)}else if(":"===o){if('"prop"'===t)n('"prop"'),i('"prop":');else if('"prop'!==t&&'"value'!==t)throw s()}else if("n"===o){if('"prop":'===t)n('"prop":'),i("n");else if("["===t||null===t)i("n");else if('"prop'!==t&&'"value'!==t)throw s()}else if("u"===o){if("n"===t)n("n"),i("nu");else if("tr"===t)n("tr"),i("tru");else if('"prop'!==t&&'"value'!==t)throw s()}else if("l"===o){if("nu"===t)n("nu"),i("nul");else if("nul"===t)n("nul");else if("fa"===t)n("fa"),i("fal");else if('"prop'!==t&&'"value'!==t)throw s()}else if("t"===o){if('"prop":'===t)n('"prop":'),i("t");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("t")}}else if("r"===o){if("t"===t)n("t"),i("tr");else if('"prop'!==t&&'"value'!==t)throw s()}else if("e"===o){if("tru"===t)n("tru");else if("fals"===t)n("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("f"===o){if('"prop":'===t)n('"prop":'),i("f");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("f")}}else if("a"===o){if("f"===t)n("f"),i("fa");else if('"prop'!==t&&'"value'!==t)throw s()}else if("s"===o){if("fal"===t)n("fal"),i("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("."===o){if('"prop":'===t)n('"prop":'),i("number.");else if('"prop'!==t&&'"value'!==t)if("{"===t)i("number.");else{if("["!==t&&null!==t)throw s();i("number.")}}else if(o.match(/[0-9]/)){if("number."===t)n("number.");else if('"prop'!==t&&'"value'!==t)if('"prop":'===t)n('"prop":');else if("{"!==t&&"["!==t&&null!==t)throw s()}else if("}"===o){if("{"===t)n("{");else if("number."===t)n("number."),n("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("]"===o){if("["===t)n("[");else if('"prop'!==t&&'"value'!==t)throw s()}else","===o&&"number."===t&&n("number.");r=a}let o=e.reverse().map((t=>{switch(t){case"{":return"}";case"[":return"]";case'"prop':return'": null';case'"prop"':return": null";case'"prop":':return" null";case"n":return"ull";case"nu":return"ll";case"nul":return"l";case"t":return"rue";case"tr":return"ue";case"tru":case"fals":return"e";case"f":return"alse";case"fa":return"lse";case"fal":return"se";case'"value':return'"';case"number.":return"0";default:throw s()}})).join("");return D((r?t.substring(0,t.length-1):t).replace(/( |\n|,)+$/,"")+o)}function z(t){if(void 0===t)throw Error("Value is undefined");return t}var H=[];for(let t=0;t<256;++t)H.push((t+256).toString(16).slice(1));import{randomFillSync as K}from"crypto";var Q=new Uint8Array(256),W=Q.length;import{randomUUID as X}from"crypto";var Z={randomUUID:X},tt=function(t,e,r){if(Z.randomUUID&&!e&&!t)return Z.randomUUID();let i=(t=t||{}).random??t.rng?.()??(W>Q.length-16&&(K(Q),W=0),Q.slice(W,W+=16));if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,e){if((r=r||0)<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[r+t]=i[t];return e}return function(t,e=0){return(H[t[e+0]]+H[t[e+1]]+H[t[e+2]]+H[t[e+3]]+"-"+H[t[e+4]]+H[t[e+5]]+"-"+H[t[e+6]]+H[t[e+7]]+"-"+H[t[e+8]]+H[t[e+9]]+"-"+H[t[e+10]]+H[t[e+11]]+H[t[e+12]]+H[t[e+13]]+H[t[e+14]]+H[t[e+15]]).toLowerCase()}(i)},et=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(mt).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function rt(t){return new st([],t)}function it(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0,juggleBetweenNullAndUndefined:s=!1}=i,{problems:o=[],juggleTo:a}=(()=>{switch(e.type){case"array":{if(!Array.isArray(t))return{problems:[{expectedType:[e],path:r,value:t}]};if(0===t.length)return{};let n=t.map((t=>it(t,e.elementType,r+"[..]",i))),s=(()=>{if(0!==n.filter((t=>t.juggleTo)).length)return{value:n.map((t=>void 0===t.juggleTo?t.value:t.juggleTo.value))}})();return{problems:n.flatMap((t=>t.problems)),juggleTo:s}}case"boolean":return"boolean"!=typeof t?{problems:[{expectedType:[e],path:r,value:t}]}:{};case"undefined":return void 0===t?{}:s&&null===t?{juggleTo:{value:void 0}}:{problems:[{expectedType:[e],path:r,value:t}]};case"object":{if("object"!=typeof t||null===t)return{problems:[{expectedType:[e],path:r,value:t}]};let s=[],o=[];for(let n in e.props){let a=e.props[n],u=it(n in t?t[n]:void 0,a.optional?[...a.type,{type:"undefined"}]:a.type,r+"."+n,i);void 0!==u.juggleTo&&o.push({key:n,juggleTo:u.juggleTo.value}),s.push(...u.problems)}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return{problems:s,juggleTo:(()=>{if(0===o.length)return;let e={...t};for(let t of o)e[t.key]=t.juggleTo;return{value:e}})()}}case"string":return{problems:"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}]};case"null":return null===t?{}:s&&void 0===t?{juggleTo:{value:null}}:{problems:[{expectedType:[e],path:r,value:t}]};case"number":return{problems:"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}]};case"constant":return{problems:t===e.value?[]:[{expectedType:[e],path:r,value:t}]}}})();return{type:e,value:t,problems:o,juggleTo:a}}(t,e,r,i)));if(function(t){return t.some((t=>0===t.problems.length&&void 0===t.juggleTo))}(n))return{types:e,value:t,problems:[]};let s=function(t){let e=t.filter((t=>0===t.problems.length&&void 0!==t.juggleTo));if(e.length>1)throw Error("Illegal State");return e[0]?.juggleTo}(n);if(void 0!==s)return{types:e,value:t,problems:[],juggleTo:s};let o=n.flatMap((t=>t.problems.filter((t=>void 0!==t.expectedType&&t.path===r))));return o.length>0?{types:e,value:t,problems:[{expectedType:o.flatMap((t=>t.expectedType)),path:r,value:t}]}:{types:e,value:t,problems:n.flatMap((t=>t.problems))}}var nt=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.l=r}},st=class t extends nt{array(e){let r=e(new t([],this.value)),i=new ot([{type:"array",elementType:r.type}],this.value);return new ot([...this.type,...i.type],this.value)}object(t){let e=t(new at([{type:"object",props:{}}],this.value));return new ot([...this.type,...e.type],this.value)}string(){return new ot([...this.type,{type:"string"}],this.value)}number(){return new ot([...this.type,{type:"number"}],this.value)}boolean(){return new ot([...this.type,{type:"boolean"}],this.value)}constant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}null(){return new ot([...this.type,{type:"null"}],this.value)}undefined(){return new ot([...this.type,{type:"undefined"}],this.value)}any(){return new ot([],this.value)}},ot=class t extends nt{orArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new at([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}},at=class t{constructor(t,e){this.type=t,this.value=e}mayHave(t,e,r){return this.has(t,e,!0,r)}canHaveString(t,e){return this.mayHave(t,(t=>t.string()),e)}canHaveNumber(t,e){return this.mayHave(t,(t=>t.number()),e)}canHaveBoolean(t,e){return this.mayHave(t,(t=>t.boolean()),e)}canHaveConstant(t,[e,...r],i){return this.mayHave(t,(t=>t.constant(e,...r)),i)}has(e,r,i=!1,n){let{optional:s,comment:o}="string"==typeof i?{optional:!1,comment:i}:{optional:i,comment:n},a=1===this.type.length?this.type[0]:void 0;if(void 0===a||"object"!==a.type)throw Error("illegal state");let u=r(new lt([],this.value)),l=u.type,h=u.h;return new t([{...a,props:{...a.props,[e]:{optional:s,type:l,comment:(()=>{let t=[...h,...void 0!==o?[o]:[]];return t.length>0?t.join(". "):void 0})()}}}],this.value)}hasString(t,e){return this.has(t,(t=>t.string()),!1,e)}hasNumber(t,e){return this.has(t,(t=>t.number()),!1,e)}hasBoolean(t,e){return this.has(t,(t=>t.boolean()),!1,e)}hasConstant(t,e,r,...i){let{constants:n,comment:s}=Array.isArray(e)?{constants:e,comment:r}:{constants:[e,...void 0!==r?[r]:[],...i],comment:void 0};return this.has(t,(t=>t.constant(...n)),!1,s)}},ut=class extends nt{constructor(t,e,r=[]){super(t,e),this.h=r}withComment(t){return new ht(this.type,this.value,[...this.h,t])}},lt=class extends ut{array(t){let e=t(new st([],this.value)),r=new ot([{type:"array",elementType:e.type}],this.value);return new ht([...this.type,...r.type],this.value)}object(t){let e=t(new at([{type:"object",props:{}}],this.value));return new ht([...this.type,...e.type],this.value)}string(){return new ht([...this.type,{type:"string"}],this.value)}number(){return new ht([...this.type,{type:"number"}],this.value)}boolean(){return new ht([...this.type,{type:"boolean"}],this.value)}constant(...t){return new ht([...this.type,...t.map((t=>({type:"constant",value:t})))],this.value)}null(){return new ht([...this.type,{type:"null"}],this.value)}undefined(){return new ht([...this.type,{type:"undefined"}],this.value)}},ht=class t extends ut{orArray(e){let r=e(new ot([],this.value)),i=new ot([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new at([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(...e){return new t([...this.type,...e.map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}};function pt(t,e,r={}){let{problems:i,juggleTo:n}=it(t,e.type,"root",r);if(i.length>0)throw new et(i,r.errorMessage);return void 0!==n?n.value:t}function ct(t){return ft(t.type)}function ft(t,e=0){if(Array.isArray(t))return t.map((t=>ft(t,e))).join(" | ");switch(t.type){case"array":return ft(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":{let r=Object.keys(t.props);return"{\n"+r.map(((i,n)=>{let s=t.props[i],o=ft(s.type,e+1),a=n<r.length-1?",":"",u=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${dt(e+1)}${i}?: ${o}${a}${u}\n`:`${dt(e+1)}${i}: ${o}${a}${u}\n`})).join("")+dt(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function dt(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function mt(t){return"constant"===t.type?`'${t.value}'`:t.type}async function yt(t,e,r="gpt-image-1",i){let n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},body:JSON.stringify({model:r,prompt:e,size:i})});if(!n.ok){let t=await n.json();throw Error(`OpenAI API error: ${n.status} ${JSON.stringify(t)}`)}let s=await n.json();if(!s.data?.[0]?.b64_json)throw Error("Invalid response structure from OpenAI API");return Uint8Array.from(atob(s.data[0].b64_json),(t=>t.charCodeAt(0)))}import{writeFile as _t}from"fs";function wt(t){let e=t=>{if(Array.isArray(t))return 1===t.length?e(t[0]):t.every((t=>"constant"===t.type))?{type:"string",enum:t.map((t=>t.value))}:{anyOf:t.map((t=>e(t)))};switch(t.type){case"object":{let r={},i=[];for(let[n,s]of Object.entries(t.props)){let t=e(s.type);r[n]=s.comment?{...t,description:s.comment}:t,s.optional||i.push(n)}return{type:"object",properties:r,required:i.length>0?i:void 0,additionalProperties:!1}}case"array":return{type:"array",items:e(t.elementType)};case"string":default:return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":case"undefined":return{type:"null"};case"constant":return Array.isArray(t.value)?{type:"string",enum:t.value}:{type:"string",const:t.value}}};return e(t.type)}function gt({model:t,prompt:e,temperature:r,topP:i,requireJsonResponse:n,jsonSchema:s,serviceTier:o,tools:a}){return{model:t,input:e.map((t=>t.llmPlatformConversationItem&&"openai"===t.llmPlatform?t.llmPlatformConversationItem:"function_call_output"===t.type?{type:"function_call_output",call_id:t.functionCallId,output:t.content}:"assistant"===t.role?{type:"message",role:t.role,content:[{type:"output_text",text:t.content}]}:{role:t.role,content:[{type:"input_text",text:t.content}]})),stream:!0,temperature:r,top_p:i,text:s?{format:{type:"json_schema",name:s.name,schema:s.schema,strict:s.strict}}:n?{format:{type:"json_object",name:"response"}}:void 0,service_tier:vt(o),tools:a}}function vt(t){switch(t){case void 0:return;case"normal":return"default";case"flex":return"flex";case"priority":return"priority";case"auto":return"auto"}}var bt={gpt_3_5_turbo:"gpt-3.5-turbo",gpt_3_5_turbo_0125:"gpt-3.5-turbo-0125",gpt_3_5_turbo_1106:"gpt-3.5-turbo-1106",gpt_3_5_turbo_16k:"gpt-3.5-turbo-16k",gpt_3_5_turbo_instruct:"gpt-3.5-turbo-instruct",gpt_3_5_turbo_instruct_0914:"gpt-3.5-turbo-instruct-0914",gpt_4:"gpt-4",gpt_4_0125_preview:"gpt-4-0125-preview",gpt_4_0613:"gpt-4-0613",gpt_4_1106_preview:"gpt-4-1106-preview",gpt_4_turbo:"gpt-4-turbo",gpt_4_turbo_2024_04_09:"gpt-4-turbo-2024-04-09",gpt_4_turbo_preview:"gpt-4-turbo-preview",gpt_4_1:"gpt-4.1",gpt_4_1_2025_04_14:"gpt-4.1-2025-04-14",gpt_4_1_mini:"gpt-4.1-mini",gpt_4_1_mini_2025_04_14:"gpt-4.1-mini-2025-04-14",gpt_4_1_nano:"gpt-4.1-nano",gpt_4_1_nano_2025_04_14:"gpt-4.1-nano-2025-04-14",gpt_4o:"gpt-4o",gpt_4o_2024_05_13:"gpt-4o-2024-05-13",gpt_4o_2024_08_06:"gpt-4o-2024-08-06",gpt_4o_2024_11_20:"gpt-4o-2024-11-20",gpt_4o_audio_preview:"gpt-4o-audio-preview",gpt_4o_audio_preview_2024_10_01:"gpt-4o-audio-preview-2024-10-01",gpt_4o_audio_preview_2024_12_17:"gpt-4o-audio-preview-2024-12-17",gpt_4o_audio_preview_2025_06_03:"gpt-4o-audio-preview-2025-06-03",gpt_4o_mini:"gpt-4o-mini",gpt_4o_mini_2024_07_18:"gpt-4o-mini-2024-07-18",gpt_4o_mini_audio_preview:"gpt-4o-mini-audio-preview",gpt_4o_mini_audio_preview_2024_12_17:"gpt-4o-mini-audio-preview-2024-12-17",gpt_4o_mini_realtime_preview:"gpt-4o-mini-realtime-preview",gpt_4o_mini_realtime_preview_2024_12_17:"gpt-4o-mini-realtime-preview-2024-12-17",gpt_4o_mini_search_preview:"gpt-4o-mini-search-preview",gpt_4o_mini_search_preview_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",gpt_4o_mini_transcribe:"gpt-4o-mini-transcribe",gpt_4o_mini_tts:"gpt-4o-mini-tts",gpt_4o_realtime_preview:"gpt-4o-realtime-preview",gpt_4o_realtime_preview_2024_10_01:"gpt-4o-realtime-preview-2024-10-01",gpt_4o_realtime_preview_2024_12_17:"gpt-4o-realtime-preview-2024-12-17",gpt_4o_realtime_preview_2025_06_03:"gpt-4o-realtime-preview-2025-06-03",gpt_4o_search_preview:"gpt-4o-search-preview",gpt_4o_search_preview_2025_03_11:"gpt-4o-search-preview-2025-03-11",gpt_4o_transcribe:"gpt-4o-transcribe",gpt_5:"gpt-5",gpt_5_2025_08_07:"gpt-5-2025-08-07",gpt_5_chat_latest:"gpt-5-chat-latest",gpt_5_codex:"gpt-5-codex",gpt_5_mini:"gpt-5-mini",gpt_5_mini_2025_08_07:"gpt-5-mini-2025-08-07",gpt_5_nano:"gpt-5-nano",gpt_5_nano_2025_08_07:"gpt-5-nano-2025-08-07",gpt_5_pro:"gpt-5-pro",gpt_5_pro_2025_10_06:"gpt-5-pro-2025-10-06",gpt_audio:"gpt-audio",gpt_audio_2025_08_28:"gpt-audio-2025-08-28",gpt_audio_mini:"gpt-audio-mini",gpt_audio_mini_2025_10_06:"gpt-audio-mini-2025-10-06",gpt_image_1:"gpt-image-1",gpt_image_1_mini:"gpt-image-1-mini",gpt_realtime:"gpt-realtime",gpt_realtime_2025_08_28:"gpt-realtime-2025-08-28",gpt_realtime_mini:"gpt-realtime-mini",gpt_realtime_mini_2025_10_06:"gpt-realtime-mini-2025-10-06",o1:"o1",o1_2024_12_17:"o1-2024-12-17",o1_mini:"o1-mini",o1_mini_2024_09_12:"o1-mini-2024-09-12",o1_pro:"o1-pro",o1_pro_2025_03_19:"o1-pro-2025-03-19",o3:"o3",o3_2025_04_16:"o3-2025-04-16",o3_deep_research:"o3-deep-research",o3_deep_research_2025_06_26:"o3-deep-research-2025-06-26",o3_mini:"o3-mini",o3_mini_2025_01_31:"o3-mini-2025-01-31",o3_pro:"o3-pro",o3_pro_2025_06_10:"o3-pro-2025-06-10",o4_mini:"o4-mini",o4_mini_2025_04_16:"o4-mini-2025-04-16",o4_mini_deep_research:"o4-mini-deep-research",o4_mini_deep_research_2025_06_26:"o4-mini-deep-research-2025-06-26",omni_moderation_2024_09_26:"omni-moderation-2024-09-26",omni_moderation_latest:"omni-moderation-latest"},Et={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},At=class{config;p;m;constructor(t){this.config=Lt(t)}createConversation(){let t=new Tt(this.config);return t.p=this.p,t.m={uuid:tt(),messages:[]},t}get apiKeyChain(){return void 0===this.p&&(this.p=kt(this.config)),this.p}get conversation(){return this.m}chat(t,e,...r){let{toPrompt:i}=(()=>{if("function"==typeof t)return{toPrompt:t,args:e};if("string"==typeof t)return{toPrompt:()=>t,args:void 0};if(Array.isArray(t)){let e=0===t.length?[{user:""}]:t.filter((t=>void 0!==t));return{toPrompt:()=>e,args:void 0}}{let i=[t,...void 0!==e?[e]:[],...r].filter((t=>void 0!==t)),n=0===i.length?[{user:""}]:i;return{toPrompt:()=>n,args:void 0}}})();return new Vt(this,i,e,Ht(),void 0,void 0,void 0,void 0,!1,!1)}image(t){return new St(t,void 0,void 0,this)}},Tt=class t extends At{constructor(t){super(t)}copyConversation(){if(void 0===this.m)throw Error("This method only works on copy conversation: no conversation exists");let e=new t(this.config);return e.p=this.p,e.m={uuid:tt(),messages:this.m.messages.map((t=>({...t,uuid:tt()})))},e}},St=class{constructor(t,e,r,i){this.prompt=t,this._=e,this.v=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"ImagePrompt"}model(t){return this._=t,this}size(t){return this.v=t,this}toFile(t){return new Nt(this.prompt,this._,this.v,t,this.aiClient)}async getResponseAsString(){let t=y(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await yt(t,this.prompt)}},Nt=class{constructor(t,e,r,i,n){this.prompt=t,this._=e,this.v=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsFile()}finally{t?.()}}get[Symbol.toStringTag](){return"ImageFilePrompt"}model(t){return this._=t,this}size(t){return this.v=t,this}async getResponseAsFile(){let t=y(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await yt(t,this.prompt,this._,this.v);return new Promise(((t,r)=>{_t(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},xt=new At({});function Ut(t){let e=Lt(t);xt.config=e,xt.p=kt(e)}function Pt(t){let e=Lt(t);return new At(e)}function Lt(t){return"string"==typeof t?{promptGridApiKey:jt(t),debugMode:!1,attemptsPerCall:1}:{promptGridApiKey:jt(t.promptGridApiKey),apiKeys:t.apiKeys,debugMode:t.debugMode??!1,attemptsPerCall:Ct(t.attemptsPerCall)}}function jt(t){return pt(t,rt(t).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+t})}function Ct(t){let e=pt(t,rt(t).number().orUndefined(),{errorMessage:"Please provide a valid number of attempts per call; got "+t})??1;if(e<1)throw Error("Please provide a valid number of attempts per call; minimum is 1; got "+e);return e}function kt(t){let e=t.promptGridApiKey,r=t.apiKeys;return{promptgrid:e,openai:(async()=>{if(r?.openai)return r.openai;if(void 0===e)return;let t=await(async()=>{try{return await fetch(T()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+e}})}catch{throw Error("HTTP called failed when doing handshake")}})();if(200!==t.status){let e=await t.text();throw Error(`Handshake failed with status ${t.status}, body: ${e}`)}return(await t.json()).apiKeys.openai})()}}var Ot=new Map;function Rt(t){let e=t??xt;if(void 0===e.apiKeyChain)throw Error("No LLM set up. Call setupPromptGun first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return new It(e,Ht())}var It=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new Vt(this.aiClient,t,e,Ht(),void 0,void 0,void 0,void 0,!1,!1)}},Vt=class t{constructor(t,e,r,i,n,s,o,a,u,l=!1,h,p=[],c=[]){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.A=n,this.T=s,this.S=o,this._=a,this.N=u,this.U=l,this.promptName=h,this.P=p,this.L=c,this.j=this.computeGenericPrompt();let f=this;this.generator=async function*(){yield*await Ft(f.aiClient,Qt(a),f.j,!1,f.promptName,n,s,o,i,f.U,f.P,f.L,void 0)}(),this.stringGenerator=async function*(){for await(let t of f.generator)t!==Wt&&(yield t)}()}generator;stringGenerator;j;name(t){return this.copy({promptName:t})}model(t){return this.copy({model:t})}firstThink(t=!0){return this.copy({firstThink:t})}temperature(t){return this.copy({temperature:t})}topP(t){return this.copy({topP:t})}flex(t=!0){return this.copy({serviceTier:t?"flex":void 0})}priority(t=!0){return this.copy({serviceTier:t?"priority":void 0})}tier(t){return this.copy({serviceTier:t})}strict(t=!0){return this.copy({strict:t})}check(t,e=10){if(e<1)throw Error("The number of attempts must be at least 1");return this.copy({checks:[...this.L,{callback:t,attempts:e}]})}copy({aiClient:e,promptSupplier:r,promptSupplierArgs:i,callingCodeLine:n,temperature:s,topP:o,serviceTier:a,model:u,firstThink:l,strict:h,promptName:p,tools:c,checks:f}){return new t(e??this.aiClient,r??this.promptSupplier,i??this.promptSupplierArgs,n??this.callingCodeLine,s??this.A,o??this.T,a??this.S,u??this._,l??this.N,h??this.U,p??this.promptName,c??this.P,f??this.L)}get result(){return this}get messages(){return this.j.map(Kt)}get json(){return!1}computeGenericPrompt(){let t=this.promptSupplier(this.promptSupplierArgs,zt),{messages:e,typeSpecIndex:r}=Mt(t);if(!this.json)return e;let i=qt(Qt(this._),this.json,this.N);if(null===i)return e;let n={uuid:tt(),type:"input_message",role:"user",content:i};return void 0!==r?[...e.slice(0,r),n,...e.slice(r)]:[...e,n]}next(...[t]){return this.stringGenerator.next(t)}return(t){return this.stringGenerator.return(t)}throw(t){return this.stringGenerator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}get(t){return new Bt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,Ht(),this.promptName,this.A,this.T,this.S,this._,this.N,this.P,this.U)}getBoolean(){return this.get((t=>t.boolean()))}getString(){return this.get((t=>t.string()))}getNumber(){return this.get((t=>t.number()))}getObject(t){return this.get((e=>e.object(t)))}getArray(t){return new Jt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,(e=>e.array(t)),this.callingCodeLine,this.promptName,this.A,this.T,this.S,this._,this.N,this.P,this.U)}getAny(){return this.get((t=>t.any()))}tools(...t){let e=Array.isArray(t[0])&&1===t.length?t[0].filter((t=>void 0!==t)):t.filter((t=>void 0!==t));return this.P.push(...e),this}async getResponseAsString(){let t="";for await(let e of this)e!==Wt?t+=e:t="";return t}};function $t(t){return{name:t.name,description:t.description,parameters:t.parameters(rt(void 0)),function:t.function}}var Bt=class t extends M{constructor(t,e,r,i,n,s,o,a,u,l,p,c=[],f=!1,d=[]){super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.A=o,this.T=a,this.S=u,this._=l,this.N=p,this.P=c,this.U=f,this.L=d;let m=this;this.j=this.computePrompt();let y,_,w,g=()=>{let e=new N;return y||(y=h.Flux.fromGenerator(async function*(){yield*await Ft(t,Qt(l),m.j,m.json,s,o,a,u,n,m.U,m.P,m.L,i)}()),_=e.processDataBuffer(y),w=(new Y).parse(_),void 0!==i?w.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))):w.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)}))),{flux:y,jsonTokenFlux:_,streamingJsonRootElement:w,jsonTokenProcessor:e}};this.stringGenerator=async function*(){let{flux:t,streamingJsonRootElement:e,jsonTokenProcessor:r}=g();for await(let i of t){if(i===Wt){yield i;continue}let t=r.getExcerpts(i);for(let r of t)void 0!==r.token?e.push(r):void 0!==r.source&&(yield r.source)}}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of m.stringGenerator){if(e===Wt){t="";continue}t+=e;let r=q(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;j;next(...[t]){return this.partialJsonGenerator.next(t)}return(t){return this.partialJsonGenerator.return(t)}throw(t){return this.partialJsonGenerator.throw(t)}[Symbol.asyncIterator](){return this.partialJsonGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonPrompt"}name(t){return this.copy({promptName:t})}model(t){return this.copy({model:t})}firstThink(t=!0){return this.copy({firstThink:t})}temperature(t){return this.copy({temperature:t})}topP(t){return this.copy({topP:t})}flex(t=!0){return this.copy({serviceTier:t?"flex":void 0})}priority(t=!0){return this.copy({serviceTier:t?"priority":void 0})}tier(t){return this.copy({serviceTier:t})}strict(t=!0){return this.copy({strict:t})}check(t,e=10){if(e<1)throw Error("The number of attempts must be at least 1");return this.copy({checks:[...this.L,{callback:t,attempts:e}]})}copy({aiClient:e,promptSupplier:r,promptSupplierArgs:i,jsonTypeSupplier:n,callingCodeLine:s,temperature:o,topP:a,serviceTier:u,model:l,firstThink:h,strict:p,promptName:c,tools:f,checks:d}){return new t(e??this.aiClient,r??this.promptSupplier,i??this.promptSupplierArgs,n??this.jsonTypeSupplier,s??this.callingCodeLine,c??this.promptName,o??this.A,a??this.T,u??this.S,l??this._,h??this.N,f??this.P,p??this.U,d??this.L)}get result(){return this}get messages(){return this.j.map(Kt)}computePrompt(){let t=this.promptSupplier(this.promptSupplierArgs,zt),{messages:e,typeSpecIndex:r}=Mt(t);if(!this.json)return e;let i=qt(Qt(this._),this.json,this.N);if(null===i)return e;let n={type:"input_message",uuid:tt(),role:"user",content:i};return void 0!==r?[...e.slice(0,r),n,...e.slice(r)]:[...e,n]}get json(){return void 0===this.jsonTypeSupplier||this.jsonTypeSupplier(rt(void 0))}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=D(t);return(()=>void 0!==e&&(!!p(Qt(this._))||"object"!==wt(e(rt(void 0))).type))()?r?.result:r}C;getResponseAsString(){return void 0===this.C&&(this.C=this.k()),this.C}tools(...t){let e=Array.isArray(t[0])&&1===t.length?t[0].filter((t=>void 0!==t)):t.filter((t=>void 0!==t));return this.P.push(...e),this}async k(){let t="";for await(let e of this.stringGenerator)e!==Wt?t+=e:t="";return t}},Jt=class extends Bt{arrayElementGenerator;constructor(t,e,r,i,n,s,o,a,u,l,p,c,f=!1){super(t,e,r,i,n,s,o,a,u,l,p,c,f);let d=this;this.arrayElementGenerator=h.Flux.create((async(t,e)=>{await d.onElement((async e=>{t(await e)})),e()}))}next(...[t]){return this.arrayElementGenerator.next(t)}return(t){return this.arrayElementGenerator.return(t)}throw(t){return this.arrayElementGenerator.throw(t)}[Symbol.asyncIterator](){return this.arrayElementGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonArrayPrompt"}};function Mt(t,e){let r=t=>void 0===t||"typeSpec"in t?null:{type:"input_message",uuid:tt(),role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:z(t.user??t.system??t.assistant)};if("string"==typeof t)return{messages:[{type:"input_message",uuid:tt(),role:"user",content:t}]};if(Array.isArray(t)){let e,i=[];for(let n=0;n<t.length;n++){let s=t[n];if("typeSpec"in s)e=i.length;else{let t=r(s);t&&i.push(t)}}return{messages:i,typeSpecIndex:e}}{let e=r(t);return{messages:e?[e]:[]}}}async function*Ft(t,e,r,i,n,s,o,a,u,l,h,c,d){let m=new Map;try{let{fileName:_,lineNumber:w}=u;if(_&&void 0!==w&&Array.from(Ot.keys()).filter((t=>t.startsWith(_+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${_}. Please specify a name using .name() method.`);let g={id:n,callingCodeLine:u},v=t.conversation?.uuid??tt(),b={},E=t.conversation?.messages??[],A=e=>{let r=tt();for(let t of e.messages){let e=E.find((e=>e.uuid===t.uuid));if(void 0!==e){if(e.role!==t.role)throw Error("Illegal state");e.content=t.content}else E.push(t)}let i=async()=>{b.currentSave=b.nextSave,b.nextSave=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(T()+"/api/conversations",{method:"PUT",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e},body:JSON.stringify(t)});if(!r.ok)throw Error(`Got ${r.status} when attempting to save conversation, with body: ${await r.text()}`)}catch(t){console.error("Error saving conversation",t)}}({prompt:e.prompt,conversationUuid:e.conversationUuid,messages:E},t.apiKeyChain.promptgrid),await(b.nextSave?.callback()),b.currentSave=void 0};void 0!==b.nextSave&&m.delete(b.nextSave.uuid),b.nextSave={uuid:r,callback:i},void 0===b.currentSave&&m.set(r,{promise:i().then()})},S=[...t.conversation?.messages??[],...r];A({conversationUuid:v,prompt:g,messages:S});let N=!1,x=1,U=c.reduce(((t,e)=>t.set(e,1)),new Map);for(;!N;){tt();try{let r=y(await t.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),n=h?.map((t=>({type:"function",name:t.name,description:t.description,parameters:wt(t.parameters),strict:!0}))),{flux:u,httpRequest:m}=f(gt({model:Qt(e),prompt:S,apiToken:r,temperature:s,topP:o,requireJsonResponse:!1!==i,jsonSchema:Yt(d,i,e,l),serviceTier:a,tools:n}),r),_="",w=[];yield*u.flatMap((t=>{switch(t.type){case"response.output_text.delta":return[{type:"content",content:t.delta}];case"response.created":case"response.in_progress":case"response.completed":for(let[e,r]of t.response.output.entries()){let t=w.findIndex((t=>t.llmPlatformConversationItem.id===r.id)),i=t>=0?w[t]:void 0,n=(()=>{let t={uuid:i?.uuid??tt(),llmPlatform:"openai",llmPlatformConversationItem:r,httpRequest:0===e?JSON.stringify(m):void 0,role:"assistant"};switch(r.type){case"message":return{...t,type:"output_message",content:r.content.flatMap((t=>"output_text"===t.type?[t.text]:[])).join("")};case"reasoning":return{...t,type:"reasoning",content:r.content?.map((t=>t.text)).join("")??r.summary.map((t=>t.text)).join("")};case"function_call":return{...t,type:"function_call_input",name:r.name,arguments:r.arguments,content:`${r.name}(${r.arguments})`,functionCallId:r.call_id}}})();A({conversationUuid:v,prompt:g,messages:[n]}),t>=0?w[t]=n:w.push(n)}return[];case"error":throw Error(`${t.error.type}: ${t.error.message}`);default:return[]}})).doOnEach((t=>{"content"===t.type&&(_+=t.content)})).flatMap((t=>"content"===t.type?[t.content]:[]));let b=w.flatMap((t=>"function_call_input"===t.type?(()=>{let e=t.llmPlatformConversationItem;return{id:e.call_id,name:e.name,arguments:e.arguments}})():[]));if(w.map((t=>t.llmPlatformConversationItem)),b.length>0){let t=(await Dt(b,h)).map((t=>({type:"function_call_output",uuid:tt(),role:"user",functionCallId:t.tool_call_id,content:`Tool result for ${t.call.name}: ${t.content}`})));A({conversationUuid:v,prompt:g,messages:t}),S=[...S,...w,...t],x=1;continue}let E=(()=>{let t=w.filter((t=>"output_message"===t.type));if(1!==t.length)throw Error("Expected 1 output message, got "+JSON.stringify(w));return t[0].content})(),T=(()=>{if(void 0===d)return E;try{let t=D(E),r=p(e)||"object"!==wt(d(rt(void 0))).type?t?.result:t;return pt(r,d(rt(r)),{juggleBetweenNullAndUndefined:!0})}catch(t){try{let t=D(E);return pt(t,d(rt(t)),{juggleBetweenNullAndUndefined:!0})}catch{throw Error("JSON response failed type validation: "+(t instanceof Error?t.message:t+""))}}})();if(c.length>0){let t=c.map((async t=>({result:await(async()=>{try{return await t.callback(T)??void 0}catch(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;throw t}})(),check:t}))),e=(await Promise.all(t)).flatMap((({result:t,check:e})=>{let r="string"==typeof t?[t]:Array.isArray(t)?t.flatMap((t=>"string"==typeof t?[t]:[])):[];if(r.length>0){let t=z(U.get(e));if(t>=e.attempts)throw new Gt(e,e.attempts,t,r);U.set(e,t+1)}return r}));if(e.length>0){let t={type:"input_message",uuid:tt(),role:"user",content:"Your result was rejected because:\n"+e.map((t=>"- "+t)).join("\n")};A({conversationUuid:v,prompt:g,messages:[t]}),S=[...S,...w,t],yield Wt,x=1;continue}}S=[...S,...w],N=!0}catch(e){if(e instanceof Error&&e.name===Gt.name||x>=t.config.attemptsPerCall)throw e;await new Promise((t=>setTimeout(t,1e3))),console.warn(`AI call failed, retrying (try ${x+1}/${t.config.attemptsPerCall})`,e),yield Wt,x++}}}finally{if(t.config.debugMode){let t=Array.from(m.values()).map((t=>t.promise));await Promise.all(t)}}}var Gt=class extends Error{constructor(t,e,r,i,n){super(n),this.check=t,this.maxAttempts=e,this.attempts=r,this.problemsOnLastAttempt=i}};function Yt(t,e,r,i){if(void 0===t||!1===e||p(r))return;let n=wt(t(rt(void 0)));return{name:"response",schema:"object"===n.type?n:{type:"object",properties:{result:n},required:["result"],additionalProperties:!1},strict:i}}async function Dt(t,e){if(void 0===e)throw Error("Illegal state: no tools defined");let r=[];for(let i of t){let t=e.find((t=>t.name===i.name)),n=await(async()=>{if(void 0===t)return`Error: Tool ${i.name} not found`;try{let e=""===i.arguments.trim()?{}:JSON.parse(i.arguments);return await t.function(e)}catch(t){return"Error: "+(t instanceof Error?t.message:t+"")}})();r.push({call:i,tool:t,tool_call_id:i.id,role:"tool",content:n})}return r}function qt(t,e,r){if(!p(t))return function(t){return!(!t.startsWith("gpt-")&&!t.startsWith("o1-")&&"o1"!==t&&"o3-mini"!==t&&"o3"!==t)}(t)?"Respond with JSON":null;{if(!0===e)return"TYPE SPEC :: IGNORE ALL PREVIOUS TYPE SPECS\n\nIn your next message only, respond with JSON";let t=e;return"TYPE SPEC :: IGNORE ALL PREVIOUS TYPE SPECS\n\nIn its next message only, the assistant will respond with JSON matching the Typescript type below.\n- strictNullChecks, exactOptionalPropertyTypes are both on\n- a value can ONLY be null if explicitly stated, e.g. 'string | null'\n- optional properties (e.g. `{foo?: string}`) can only be achieved by not including it, NOT by setting them to null\n\nThe type:\n"+ct(new st([],void 0).object((e=>{let i=e;return r&&(i=i.hasString("reasoning","Elaborate your reasoning here. Think step by step. Give your thinking steps in a numbered list or in markdown with headers if the task requires it.")),i.has("result",(()=>new ht(t.type,t.value)))})))}}var zt={typeSpec:!0};function Ht(){let t=(Error().stack??"").split("\n").map((t=>t.trim())).filter((t=>t.startsWith("at ")))[2],e=t.match(/[^(]+\([^)]+\)/),{functionName:r,fileName:i,lineNumber:n}=e?t.match("at (?<functionName>[^(]*) ((?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+))").groups:t.match("at (?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+)").groups;return{stacktraceFrame:y(t).canBeString().andNothingElse(),fileName:y(i).canBeString().andNothingElse(),lineNumber:y(parseInt(n)).canBeNumber().andNothingElse(),functionName:y(r).canBeString().canBeUndefined().andNothingElse()}}function Kt(t){switch(t.type){case"input_message":case"output_message":return{[t.role]:t.content};case"reasoning":case"function_call_input":return{assistant:t.content};case"function_call_output":return{user:t.content}}}function Qt(t){return t??"gpt-4o"}var Wt="retry-signal-"+tt();export{At as AIClient,Tt as AIConversation,bt as AiModel,Vt as BasicPrompt,lt as EmptyPropTypeSpec,st as EmptyTypeSpec,ht as FullPropTypeSpec,ot as FullTypeSpec,Nt as ImageFilePrompt,St as ImagePrompt,Jt as JsonArrayPrompt,Bt as JsonPrompt,Et as OpenaiImageModel,It as PromptBase,ut as PropTypeSpec,M as StreamedJsonChildElement,G as StreamedJsonRootElement,at as TypeMemberSpec,nt as TypeSpec,zt as TypeSpecMarker,xt as ai,$t as defineTool,Ht as getCallerFileNameAndLineNumber,Pt as newAIClient,kt as obtainAiClientData,q as parsePartialJson,Rt as promptAI,Ut as setupAI,wt as typeSpecToJsonSchema};
|
|
1
|
+
var t=Object.create,e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.getPrototypeOf,s={}.hasOwnProperty,o=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),a=(o,a,u)=>(u=null!=o?t(n(o)):{},((t,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let o of i(n))!s.call(t,o)&&void 0!==o&&e(t,o,{get:()=>n[o],enumerable:!(a=r(n,o))||a.enumerable});return t})(!a&&o&&o.t?u:e(u,"default",{value:o,enumerable:!0}),o)),u=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=class t{generator;upstream;handleCancel;i=!1;constructor(t,e,i){let n=this;this.generator=async function*(){try{yield*t}catch(t){throw yield r,t}finally{n.i=!0}}(),this.upstream=e,this.handleCancel=i}[Symbol.asyncIterator](){return this}async next(...t){let e=await this.generator.next(t);return e.value!==r?e:await this.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}async cancel(t){if(!this.closed){if(void 0!==this.upstream)return this.upstream.cancel(t);void 0!==this.handleCancel?this.handleCancel(t):await this.throw(t)}}async then(t,e){try{let e=await this.asList();return null!=t?await t(e):e}catch(t){if(null!=e)return e(t);throw t}}async catch(t){try{return this.asList()}catch(e){if(null!=t)return t(e);throw e}}async finally(t){let e=await this.asList();return t?.(),e}get[Symbol.toStringTag](){return"Flux"}subscribe(t){let e=void 0!==t?this.doOnEach(t):this,r=()=>{e.next().then((t=>{t.done||r()})).catch((t=>{console.error(t)}))};return r(),{unsubscribe:()=>this.return()}}filter(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t)&&(yield t)}),this)}untilExcl(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){if(e(t))break;yield t}}),this)}doOnEach(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t),yield t}),this)}doAfterLast(e){let r=this,i=[];return t.constructFromGeneratorFunction((async function*(){for await(let t of r)i.push(t),yield t;await e(i)}),this)}map(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield e(t)}),this)}take(e){let r=this;return t.constructFromGeneratorFunction((async function*(){let t=0;for await(let i of r){if(t>=e){r.cancel();break}t++,yield i}}),this)}flatMap(e,r){let i=this;return t.constructFromGeneratorFunction((async function*(){let n=i[Symbol.asyncIterator](),s=await n.next();if(s.done)return;let o=e(s.value),a=r?.concurrency;Array.isArray(o)?yield*function(t,e,r,i){return async function*(){for(let t of r)yield t;let e=await i.next();for(;!e.done;){let r=t(e.value);for(let t of r)yield t;e=await i.next()}}()}(e,0,o,n):o instanceof t?yield*function(t,e,r,i,n){return async function*(){let s=[e],o=await i.next();for(;!o.done;)s.push(o.value),o=await i.next();let a=Array(s.length),u=new Map,l=new Set,h=0;if(void 0===n)for(let e=0;e<s.length;e++){let i=0===e?r:t(s[e]);a[e]=i,u.set(e,[]),(async()=>{try{for await(let t of i)u.get(e).push(t)}catch(t){u.get(e).push({o:t})}finally{l.add(e)}})()}else{let e=0,i=0,o=()=>{for(;i<n&&e<s.length;){let n=e;e++,i++;let h=0===n?r:t(s[n]);a[n]=h,u.set(n,[]),(async()=>{try{for await(let t of h)u.get(n).push(t)}catch(t){u.get(n).push({o:t})}finally{l.add(n),i--,o()}})()}};o()}for(;h<a.length;){let t=u.get(h);for(;0===t.length&&!l.has(h);)await new Promise((t=>setTimeout(t,1)));for(;t.length>0;){let e=t.shift();if(e&&"object"==typeof e&&"o"in e)throw e.o;yield e}h++}}()}(e,s.value,o,n,a):yield*function(t,e,r,i,n){return async function*(){let s=[],o=[],a=[],u=new Set,l=0,h=0,p=!1,c=0,f=(e,r,i)=>{let l=i||t(e);s[r]=l,l.then((t=>{o[r]=t,u.add(r),void 0!==n&&c--})).catch((t=>{a[r]=t,u.add(r),void 0!==n&&c--})),void 0!==n&&c++};f(e,h++,r);let m=(async()=>{let t=await i.next();for(;!t.done;){if(void 0!==n)for(;c>=n;)await new Promise((t=>setTimeout(t,0)));f(t.value,h++),t=await i.next()}p=!0})();for(;;){for(;!u.has(l);){if(p&&l>=s.length)return;await new Promise((t=>setTimeout(t,0)))}if(p&&l>=s.length)break;if(void 0!==a[l])throw a[l];void 0!==o[l]&&(yield o[l]),l++}await m}()}(e,s.value,o,n,a)}),this)}transform(e){let r=e(this);return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield t}),this)}async reduce(t,e){let r=e;for await(let e of this)r=t(r,e);return r}async asList(){let t=[];for await(let e of this)t.push(e);return t}async whenComplete(){for await(let t of this);}static create(e){let r,i=[],n=[],s=!1,o=t=>{if(s)throw Error("Cannot push to a completed generator");n.length>0?n.shift().resolve({done:!1,value:t}):i.push(t)},a=()=>{for(s=!0;n.length>0;)n.shift().resolve({done:!0,value:void 0})},u=t=>{r={value:t},n.shift()?.reject(t)};return(async()=>{try{await e(o,a,u),(!s||void 0===r)&&a()}catch(t){u(t)}})(),t.fromGenerator({[Symbol.asyncIterator](){return this},next(...t){if(r){let t=r.value;return r=void 0,Promise.reject(t)}if(i.length>0){let t=i.shift();return Promise.resolve({done:!1,value:t})}return s?Promise.resolve({done:!0,value:void 0}):new Promise(((t,e)=>{n.push({resolve:t,reject:e})}))},return:()=>(a(),Promise.resolve({done:!0,value:void 0})),throw:t=>(u(t),Promise.reject(t))})}static just(...e){return t.from(e)}static from(e,r){if(Array.isArray(e))return t.fromArray(e);if("function"==typeof e)return t.fromGeneratorFunction(e,r);if(e instanceof ReadableStream)return t.fromReadableStream(e,r);if(function(t){return null!==t&&"object"==typeof t&&"function"==typeof t.next&&"function"==typeof t.return&&"function"==typeof t.throw&&Symbol.asyncIterator in t}(e))return t.fromGenerator(e,r);throw new TypeError("Source must be an Array, AsyncGenerator, ReadableStream, or a generator function")}static fromArray(e){return t.fromGeneratorFunction((async function*(){for(let t of e)yield t}))}static constructFromGeneratorFunction(e,r,i){return new t(e(),r,i)}static fromGeneratorFunction(e,r){return t.constructFromGeneratorFunction(e,void 0,r)}static fromGenerator(e,r){return new t(e,void 0,r)}static fromReadableStream(e,r){return t.fromGeneratorFunction((async function*(){let t=e.getReader();try{let e;for(;!(e=await t.read()).done;)yield e.value}finally{await t.cancel()}}),r)}get closed(){return this.i}};t.Flux=e;var r={}})),l=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=u();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),h=a(l(),1);function p(t){return!(t.startsWith("gpt-")||t.startsWith("o1-")||"o1"===t||"o3-mini"===t||"o3"===t)}var c=a(l(),1);function f(t,e){let r={url:"https://api.openai.com/v1/responses",method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${e.slice(0,7)}...${e.slice(-4)}`},body:t};return{flux:c.Flux.fromGeneratorFunction((async function*(){let r=new AbortController,i=await fetch("https://api.openai.com/v1/responses",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+e},method:"POST",signal:r.signal,body:JSON.stringify(t)});if(i.status<200||i.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await i.text());throw Error("OpenAPI reported: "+t)}if(null===i.body)throw Error("illegal state");let n="";yield*c.Flux.fromReadableStream(i.body,(()=>r.abort())).map((t=>m.decode(t,{stream:!0}))).flatMap((t=>{n+=t;let e=[],r=n.split("\n\n");n=r.pop()||"";for(let t of r)t.trim()&&e.push(t.trim());return e})).flatMap((t=>{let e=t.split("\n"),r="";for(let t of e)t.startsWith("data: ")&&(r+=t.substring(6));if(!r)return[];try{return[JSON.parse(r)]}catch{return[]}}))})),httpRequest:r}}var m=new TextDecoder,d=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(E).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function y(t){return new g([],t)}function _(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:_(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(..._(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t!==e.value||Number.isNaN(t)?[{expectedType:[e],path:r,value:t}]:[]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var w,g=class t{type;value;constructor(t=[],e){this.type=t,this.value=e}canBeArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}canBeObject(e){let r=e(new t([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}hasString(t){return this.has(t,(t=>t.canBeString()))}hasNumber(t){return this.has(t,(t=>t.canBeNumber()))}canHaveProperty(t,e){return this.has(t,e,!0)}has(e,r,i=!1){let n=1===this.type.length?this.type[0]:void 0;if(void 0===n||"object"!==n.type)throw Error("illegal state");let{type:s}=r(new t([],this.value));return new t([{...n,props:{...n.props,[e]:{optional:i,type:s}}}],this.value)}canBeString(){return new t([...this.type,{type:"string"}],this.value)}canBeNumber(){return new t([...this.type,{type:"number"}],this.value)}canBeBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}canBeConstant(e){return new t([...this.type,{type:"constant",value:e}],this.value)}canBeNull(){return new t([...this.type,{type:"null"}],this.value)}canBeUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}andNothingElse(t={}){let e=_(this.value,this.type,"root",t);if(e.length>0)throw new d(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return _(this.value,this.type,"root",e).length>0?t:this.value}describe(){return v(this.type)}};function v(t,e=0){if(Array.isArray(t))return t.map((t=>v(t,e))).join(" | ");switch(t.type){case"array":return v(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${b(e+1)}${r}: ${v(t.props[r].type,e+1)}`)).join(",\n")+`\n${b(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function b(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function E(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as A}from"dotenv";function T(){if(!w){A();let t=function(){let t="t";t+="ps",t="ht"+t,t+=":",t+="/",t+="/ap",t+="i.pr";let e="i";return e="d.a"+e,e="gri"+e,t+="ompt",t+e}();w=y(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return w}var S=class{constructor(t,e,r,i,n=!1){this.type=t,this.source=e,this.value=r,this.fieldName=i,this.maybeIncomplete=n}},N=class t{jsonBuffer="";highestOffsetParsed=-1;static toJsonTokenFlux(e){return(new t).processDataBuffer(e)}processDataBuffer(t){return t.flatMap((t=>this.getExcerpts(t)))}getExcerpts(t){this.jsonBuffer+=t;let e,r=[],i=new x(this.jsonBuffer);for(;e=this.nextToken(i);)i.currentTokenLocation().getCharOffset()>this.highestOffsetParsed&&!e.maybeIncomplete&&(r.push({token:e}),this.highestOffsetParsed=i.currentTokenLocation().getCharOffset());return r.push({source:t}),r}nextToken(t){let e=t.nextToken();return"string"!=typeof e?e:void 0}},x=class{constructor(t){this.content=t}position=0;currentTokenType;parentFieldName;currentValue=null;context=[];nextToken(){let t=this.position;if(this.position>=this.content.length)return"string-ended";for(;this.position<this.content.length&&/\s/.test(this.content[this.position]);)this.position++;if(this.position>=this.content.length)return"string-ended";let e=e=>this.content.substring(t,e),r=this.content[this.position];switch(r){case"{":return this.position++,this.currentTokenType="START_OBJECT",this.pushContext("object"),new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT";let t=new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,this.popContext("object"),"field"===this.currentContextType&&this.popContext("field"),t}case"[":return this.position++,this.currentTokenType="START_ARRAY",this.pushContext("array"),new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY";let t=new S(this.currentTokenType,e(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,this.popContext("array"),"field"===this.currentContextType&&this.popContext("field"),t}case'"':if("object"===this.currentContextType){this.currentTokenType="FIELD_NAME";let t=++this.position,r=this.content.indexOf('"',t);for(;r>=0&&"\\"===this.content[r-1];)r=this.content.indexOf('"',r+1);if(-1===r)return"token-incomplete";let i=this.content.substring(t,r);for(r++;r<this.content.length&&/\s/.test(this.content[r]);)r++;if(r===this.content.length)return"token-incomplete";if(":"!==this.content[r])throw Error("Expected token ':'");r++,this.position=r;let n=new S(this.currentTokenType,e(this.position),i,void 0);return this.parentFieldName=i,this.pushContext("field"),n}{this.currentTokenType="VALUE_STRING";let t=++this.position,r=this.content.indexOf('"',t);for(;r>0&&"\\"===this.content[r-1];)r=this.content.indexOf('"',r+1);if(-1===r)return"token-incomplete";let i=this.content.substring(t,r);this.position=r+1,this.currentValue=i;let n=new S(this.currentTokenType,e(this.position),i,"VALUE_STRING"===this.currentTokenType?this.parentFieldName:void 0);return this.parentFieldName=void 0,"field"===this.currentContextType&&this.popContext("field"),n}case"t":{let t=this.content.substring(this.position,this.position+4);if("true"===t)return this.position+=4,this.currentTokenType="VALUE_TRUE",this.currentValue=!0,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case"f":{let t=this.content.substring(this.position,this.position+5);if("false"===t)return this.position+=5,this.currentTokenType="VALUE_FALSE",this.currentValue=!1,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<5)return"token-incomplete";break}case"n":{let t=this.content.substring(this.position,this.position+4);if("null"===t)return this.position+=4,this.currentTokenType="VALUE_NULL",this.currentValue=null,"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case",":return this.position++,this.currentTokenType="COMMA",new S(this.currentTokenType,e(this.position),void 0,void 0,!1);default:if(/[0-9-]/.test(r)){let t="",r=!1;for(;this.position<this.content.length&&(/[0-9]/.test(this.content[this.position])||"-"===this.content[this.position]||"."===this.content[this.position]||"e"===this.content[this.position]||"E"===this.content[this.position]||"+"===this.content[this.position]);)"."===this.content[this.position]&&(r=!0),t+=this.content[this.position++];r?(this.currentTokenType="VALUE_NUMBER_FLOAT",this.currentValue=parseFloat(t)):(this.currentTokenType="VALUE_NUMBER_INT",this.currentValue=parseInt(t,10));let i=this.position>=this.content.length;return"field"===this.currentContextType&&this.popContext("field"),new S(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName,i)}}throw new U(`Invalid JSON at position ${this.position} of content: ${this.content}`)}currentTokenLocation(){return{getCharOffset:()=>this.position}}get currentContextType(){return this.context[this.context.length-1]}pushContext(t){this.context.push(t)}popContext(t){if(0===this.context.length)throw Error("Cannot pop context, context empty");let e=this.currentContextType;if(e!==t)throw Error(`Cannot pop context \`${t}', current context '${e}'`);this.context.pop()}},U=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},P=a(l(),1);function L(t){return null!=t}var j=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new O;receivedExcerpts=[];onElement(t){return this.onElementCallbacks.add(t),this}onProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push(e),this}onJsonStringProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push((t=>{let r=new J,i=[],n=new M;t.onEachExcerpt((t=>{void 0!==t.source&&i.push(t.source);let e=i.join(""),s=this.endsOnUnevenNumberOfBackslashes(e)?e.substring(0,e.length-1):e;i.length=0;let o=s.replace(/\\"/g,'"').substring(1),a=null!=t.token?o.substring(0,o.length-1):o;r.getExcerpts(a).forEach((t=>n.push(t)))})),e(n)})),this}onEachExcerpt(t){return this.onEachExcerptCallbacks.add(t),this.receivedExcerpts.forEach(t),this}async then(t,e){try{let e=await this.getResponseAsPromise();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsPromise()}finally{t?.()}}get[Symbol.toStringTag](){return"StreamedJsonElement"}getResponseAsPromise(){return new Promise((t=>{this.onCompleteAs(t)}))}onComplete(t){this.u(this.toAsync(t),void 0)}u(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.u(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.u((e=>{let r=e.replace(/,$/,""),i=(()=>{try{return JSON.parse(r)}catch(t){throw t.message=`${t.message}. JSON string was: ${r}`,t}})();return t(i)}),void 0)}onCompleteAsString(t){this.u(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.u(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.u(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.u(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.u(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.u(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.u(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.u(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return P.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.u((async()=>e()))}))}whenCompleteAs(){return new Promise((t=>{this.onCompleteAs(t)}))}async push(t){let e=t.token;if(this.onEachExcerptCallbacks.forEach((e=>e(t))),this.isState(k))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(O))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new V,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new R,void this.receivedJson.push(e.source);case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":return this.receivedJson.push(e.source),this.end();default:throw new B(e)}else if(this.isState(V))switch(r){case"FIELD_NAME":case"COMMA":return void this.receivedJson.push(e.source);case"END_OBJECT":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let r=new M;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new V})),this.state=new $(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>{t(r)})),r.push(t)}default:throw new B(e)}else if(this.isState(R))switch(r){case"END_ARRAY":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let e=new M;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new R})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new I(e),e.push(t)}case"COMMA":return void this.receivedJson.push(e.source);default:throw new B(e)}throw Error("Unknown state")}async end(){if(void 0===this.currentToken)throw Error("Illegal state");this.onCompleteCallbacks.forEach((t=>{let e=t.expectedTokenType,r=(()=>{if(void 0===e)return this.receivedJson.join("");if(!e.has(this.currentToken.type))throw Error(`Expected token type ${Array.from(e).join(", ")} but got ${this.currentToken.type}`);return this.currentToken.value})();t.consumer(r)}))}isState(t){return this.state instanceof t}endsOnUnevenNumberOfBackslashes(t){let e=0;for(let r=t.length-1;r>=0&&"\\"===t[r];r--)e++;return e%2==1}toAsync(t){return async e=>{t(e)}}},C=class{},k=class extends C{constructor(t){super(),this.child=t}},O=class extends C{},R=class extends C{},I=class extends k{constructor(t){super(t)}},V=class extends C{},$=class extends k{constructor(t){super(t)}},B=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},J=class{getExcerpts(t){return[{source:t}]}},M=class extends j{constructor(){super()}},F=a(l(),1),G=class extends j{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=F.Flux.fromGeneratorFunction((async function*(){let r;for await(let i of t)void 0!==i.token&&(r?.token?.maybeIncomplete&&r.token.type===i.token.type&&!i.token.maybeIncomplete&&await e.push(i),r=i.token),(void 0===i.token||!i.token.maybeIncomplete)&&await e.push(i),yield i;r?.token?.maybeIncomplete&&await e.push(r)}))}whenComplete(){return this.jsonTokenFlux.then((()=>this.receivedJson.join("")))}asJsonFlux(){return this.jsonTokenFlux.map((t=>t.source)).filter((t=>void 0!==t))}},Y=class{parse(t){return new G(t)}};function D(t){try{return JSON.parse(t)}catch(e){throw Error(`Failed to parse JSON with error '${e.message}'. JSON was: ${t}`)}}function q(t){if(""===t.trim())return;let e=[],r=!1,i=t=>e.push(t),n=(...t)=>{let r=e[e.length-1];if(void 0===r||!t.includes(r))throw Error("illegal state");e.pop()},s=()=>Error(`Illegal state (json: ${t})`);for(let o of t){let t=e.length>0?e[e.length-1]:null,a=!1;if('"'===o)if(null===t)i('"value');else if("["===t||null===t)i('"value');else if("{"===t)i('"prop');else if('"prop":'===t)n('"prop":'),i('"value');else if('"prop'===t)r||(n('"prop'),i('"prop"'));else{if('"value'!==t)throw s();r||n('"value')}else if("["===o){if("["===t||null===t)i("[");else if('"prop":'===t)n('"prop":'),i("[");else if('"prop'!==t&&'"value'!==t)throw s()}else if("{"===o){if(null===t||"["===t||'"prop":'===t)i("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("\\"===o){if('"prop'!==t&&'"value'!==t)throw s();r||(a=!0)}else if(":"===o){if('"prop"'===t)n('"prop"'),i('"prop":');else if('"prop'!==t&&'"value'!==t)throw s()}else if("n"===o){if('"prop":'===t)n('"prop":'),i("n");else if("["===t||null===t)i("n");else if('"prop'!==t&&'"value'!==t)throw s()}else if("u"===o){if("n"===t)n("n"),i("nu");else if("tr"===t)n("tr"),i("tru");else if('"prop'!==t&&'"value'!==t)throw s()}else if("l"===o){if("nu"===t)n("nu"),i("nul");else if("nul"===t)n("nul");else if("fa"===t)n("fa"),i("fal");else if('"prop'!==t&&'"value'!==t)throw s()}else if("t"===o){if('"prop":'===t)n('"prop":'),i("t");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("t")}}else if("r"===o){if("t"===t)n("t"),i("tr");else if('"prop'!==t&&'"value'!==t)throw s()}else if("e"===o){if("tru"===t)n("tru");else if("fals"===t)n("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("f"===o){if('"prop":'===t)n('"prop":'),i("f");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("f")}}else if("a"===o){if("f"===t)n("f"),i("fa");else if('"prop'!==t&&'"value'!==t)throw s()}else if("s"===o){if("fal"===t)n("fal"),i("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("."===o){if('"prop":'===t)n('"prop":'),i("number.");else if('"prop'!==t&&'"value'!==t)if("{"===t)i("number.");else{if("["!==t&&null!==t)throw s();i("number.")}}else if(o.match(/[0-9]/)){if("number."===t)n("number.");else if('"prop'!==t&&'"value'!==t)if('"prop":'===t)n('"prop":');else if("{"!==t&&"["!==t&&null!==t)throw s()}else if("}"===o){if("{"===t)n("{");else if("number."===t)n("number."),n("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("]"===o){if("["===t)n("[");else if('"prop'!==t&&'"value'!==t)throw s()}else","===o&&"number."===t&&n("number.");r=a}let o=e.reverse().map((t=>{switch(t){case"{":return"}";case"[":return"]";case'"prop':return'": null';case'"prop"':return": null";case'"prop":':return" null";case"n":return"ull";case"nu":return"ll";case"nul":return"l";case"t":return"rue";case"tr":return"ue";case"tru":case"fals":return"e";case"f":return"alse";case"fa":return"lse";case"fal":return"se";case'"value':return'"';case"number.":return"0";default:throw s()}})).join("");return D((r?t.substring(0,t.length-1):t).replace(/( |\n|,)+$/,"")+o)}function z(t){if(void 0===t)throw Error("Value is undefined");return t}var H=[];for(let t=0;t<256;++t)H.push((t+256).toString(16).slice(1));import{randomFillSync as K}from"crypto";var Q=new Uint8Array(256),W=Q.length;import{randomUUID as X}from"crypto";var Z={randomUUID:X},tt=function(t,e,r){if(Z.randomUUID&&!e&&!t)return Z.randomUUID();let i=(t=t||{}).random??t.rng?.()??(W>Q.length-16&&(K(Q),W=0),Q.slice(W,W+=16));if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,e){if((r=r||0)<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[r+t]=i[t];return e}return function(t,e=0){return(H[t[e+0]]+H[t[e+1]]+H[t[e+2]]+H[t[e+3]]+"-"+H[t[e+4]]+H[t[e+5]]+"-"+H[t[e+6]]+H[t[e+7]]+"-"+H[t[e+8]]+H[t[e+9]]+"-"+H[t[e+10]]+H[t[e+11]]+H[t[e+12]]+H[t[e+13]]+H[t[e+14]]+H[t[e+15]]).toLowerCase()}(i)},et=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(dt).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function rt(t){return new st([],t)}function it(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0,juggleBetweenNullAndUndefined:s=!1}=i,{problems:o=[],juggleTo:a}=(()=>{switch(e.type){case"array":{if(!Array.isArray(t))return{problems:[{expectedType:[e],path:r,value:t}]};if(0===t.length)return{};let n=t.map((t=>it(t,e.elementType,r+"[..]",i))),s=(()=>{if(0!==n.filter((t=>t.juggleTo)).length)return{value:n.map((t=>void 0===t.juggleTo?t.value:t.juggleTo.value))}})();return{problems:n.flatMap((t=>t.problems)),juggleTo:s}}case"boolean":return"boolean"!=typeof t?{problems:[{expectedType:[e],path:r,value:t}]}:{};case"undefined":return void 0===t?{}:s&&null===t?{juggleTo:{value:void 0}}:{problems:[{expectedType:[e],path:r,value:t}]};case"object":{if("object"!=typeof t||null===t)return{problems:[{expectedType:[e],path:r,value:t}]};let s=[],o=[];for(let n in e.props){let a=e.props[n],u=it(n in t?t[n]:void 0,a.optional?[...a.type,{type:"undefined"}]:a.type,r+"."+n,i);void 0!==u.juggleTo&&o.push({key:n,juggleTo:u.juggleTo.value}),s.push(...u.problems)}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return{problems:s,juggleTo:(()=>{if(0===o.length)return;let e={...t};for(let t of o)e[t.key]=t.juggleTo;return{value:e}})()}}case"string":return{problems:"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}]};case"null":return null===t?{}:s&&void 0===t?{juggleTo:{value:null}}:{problems:[{expectedType:[e],path:r,value:t}]};case"number":return{problems:"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}]};case"constant":return{problems:t===e.value?[]:[{expectedType:[e],path:r,value:t}]}}})();return{type:e,value:t,problems:o,juggleTo:a}}(t,e,r,i)));if(function(t){return t.some((t=>0===t.problems.length&&void 0===t.juggleTo))}(n))return{types:e,value:t,problems:[]};let s=function(t){let e=t.filter((t=>0===t.problems.length&&void 0!==t.juggleTo));if(e.length>1)throw Error("Illegal State");return e[0]?.juggleTo}(n);if(void 0!==s)return{types:e,value:t,problems:[],juggleTo:s};let o=n.flatMap((t=>t.problems.filter((t=>void 0!==t.expectedType&&t.path===r))));return o.length>0?{types:e,value:t,problems:[{expectedType:o.flatMap((t=>t.expectedType)),path:r,value:t}]}:{types:e,value:t,problems:n.flatMap((t=>t.problems))}}var nt=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.l=r}},st=class t extends nt{array(e){let r=e(new t([],this.value)),i=new ot([{type:"array",elementType:r.type}],this.value);return new ot([...this.type,...i.type],this.value)}object(t){let e=t(new at([{type:"object",props:{}}],this.value));return new ot([...this.type,...e.type],this.value)}string(){return new ot([...this.type,{type:"string"}],this.value)}number(){return new ot([...this.type,{type:"number"}],this.value)}boolean(){return new ot([...this.type,{type:"boolean"}],this.value)}constant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}null(){return new ot([...this.type,{type:"null"}],this.value)}undefined(){return new ot([...this.type,{type:"undefined"}],this.value)}any(){return new ot([],this.value)}},ot=class t extends nt{orArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new at([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}},at=class t{constructor(t,e){this.type=t,this.value=e}mayHave(t,e,r){return this.has(t,e,!0,r)}canHaveString(t,e){return this.mayHave(t,(t=>t.string()),e)}canHaveNumber(t,e){return this.mayHave(t,(t=>t.number()),e)}canHaveBoolean(t,e){return this.mayHave(t,(t=>t.boolean()),e)}canHaveConstant(t,[e,...r],i){return this.mayHave(t,(t=>t.constant(e,...r)),i)}has(e,r,i=!1,n){let{optional:s,comment:o}="string"==typeof i?{optional:!1,comment:i}:{optional:i,comment:n},a=1===this.type.length?this.type[0]:void 0;if(void 0===a||"object"!==a.type)throw Error("illegal state");let u=r(new lt([],this.value)),l=u.type,h=u.h;return new t([{...a,props:{...a.props,[e]:{optional:s,type:l,comment:(()=>{let t=[...h,...void 0!==o?[o]:[]];return t.length>0?t.join(". "):void 0})()}}}],this.value)}hasString(t,e){return this.has(t,(t=>t.string()),!1,e)}hasNumber(t,e){return this.has(t,(t=>t.number()),!1,e)}hasBoolean(t,e){return this.has(t,(t=>t.boolean()),!1,e)}hasConstant(t,e,r,...i){let{constants:n,comment:s}=Array.isArray(e)?{constants:e,comment:r}:{constants:[e,...void 0!==r?[r]:[],...i],comment:void 0};return this.has(t,(t=>t.constant(...n)),!1,s)}},ut=class extends nt{constructor(t,e,r=[]){super(t,e),this.h=r}withComment(t){return new ht(this.type,this.value,[...this.h,t])}},lt=class extends ut{array(t){let e=t(new st([],this.value)),r=new ot([{type:"array",elementType:e.type}],this.value);return new ht([...this.type,...r.type],this.value)}object(t){let e=t(new at([{type:"object",props:{}}],this.value));return new ht([...this.type,...e.type],this.value)}string(){return new ht([...this.type,{type:"string"}],this.value)}number(){return new ht([...this.type,{type:"number"}],this.value)}boolean(){return new ht([...this.type,{type:"boolean"}],this.value)}constant(...t){return new ht([...this.type,...t.map((t=>({type:"constant",value:t})))],this.value)}null(){return new ht([...this.type,{type:"null"}],this.value)}undefined(){return new ht([...this.type,{type:"undefined"}],this.value)}},ht=class t extends ut{orArray(e){let r=e(new ot([],this.value)),i=new ot([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new at([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(...e){return new t([...this.type,...e.map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}};function pt(t,e,r={}){let{problems:i,juggleTo:n}=it(t,e.type,"root",r);if(i.length>0)throw new et(i,r.errorMessage);return void 0!==n?n.value:t}function ct(t){return ft(t.type)}function ft(t,e=0){if(Array.isArray(t))return t.map((t=>ft(t,e))).join(" | ");switch(t.type){case"array":return ft(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":{let r=Object.keys(t.props);return"{\n"+r.map(((i,n)=>{let s=t.props[i],o=ft(s.type,e+1),a=n<r.length-1?",":"",u=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${mt(e+1)}${i}?: ${o}${a}${u}\n`:`${mt(e+1)}${i}: ${o}${a}${u}\n`})).join("")+mt(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function mt(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function dt(t){return"constant"===t.type?`'${t.value}'`:t.type}async function yt(t,e,r="gpt-image-1",i){let n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},body:JSON.stringify({model:r,prompt:e,size:i})});if(!n.ok){let t=await n.json();throw Error(`OpenAI API error: ${n.status} ${JSON.stringify(t)}`)}let s=await n.json();if(!s.data?.[0]?.b64_json)throw Error("Invalid response structure from OpenAI API");return Uint8Array.from(atob(s.data[0].b64_json),(t=>t.charCodeAt(0)))}import{writeFile as _t}from"fs";function wt(t){let e=t=>{if(Array.isArray(t))return 1===t.length?e(t[0]):t.every((t=>"constant"===t.type))?{type:"string",enum:t.map((t=>t.value))}:{anyOf:t.map((t=>e(t)))};switch(t.type){case"object":{let r={},i=[];for(let[n,s]of Object.entries(t.props)){let t=e(s.type);r[n]=s.comment?{...t,description:s.comment}:t,s.optional||i.push(n)}return{type:"object",properties:r,required:i.length>0?i:void 0,additionalProperties:!1}}case"array":return{type:"array",items:e(t.elementType)};case"string":default:return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":case"undefined":return{type:"null"};case"constant":return Array.isArray(t.value)?{type:"string",enum:t.value}:{type:"string",const:t.value}}};return e(t.type)}function gt({model:t,prompt:e,temperature:r,topP:i,requireJsonResponse:n,jsonSchema:s,serviceTier:o,tools:a}){return{model:t,input:e.map((t=>t.llmPlatformConversationItem&&"openai"===t.llmPlatform?t.llmPlatformConversationItem:"function_call_output"===t.type?{type:"function_call_output",call_id:t.functionCallId,output:t.content}:"assistant"===t.role?{type:"message",role:t.role,content:[{type:"output_text",text:t.content}]}:{role:t.role,content:[{type:"input_text",text:t.content}]})),stream:!0,temperature:r,top_p:i,text:s?{format:{type:"json_schema",name:s.name,schema:s.schema,strict:s.strict}}:n?{format:{type:"json_object",name:"response"}}:void 0,service_tier:vt(o),tools:a}}function vt(t){switch(t){case void 0:return;case"normal":return"default";case"flex":return"flex";case"priority":return"priority";case"auto":return"auto"}}var bt={gpt_3_5_turbo:"gpt-3.5-turbo",gpt_3_5_turbo_0125:"gpt-3.5-turbo-0125",gpt_3_5_turbo_1106:"gpt-3.5-turbo-1106",gpt_3_5_turbo_16k:"gpt-3.5-turbo-16k",gpt_3_5_turbo_instruct:"gpt-3.5-turbo-instruct",gpt_3_5_turbo_instruct_0914:"gpt-3.5-turbo-instruct-0914",gpt_4:"gpt-4",gpt_4_0125_preview:"gpt-4-0125-preview",gpt_4_0613:"gpt-4-0613",gpt_4_1106_preview:"gpt-4-1106-preview",gpt_4_turbo:"gpt-4-turbo",gpt_4_turbo_2024_04_09:"gpt-4-turbo-2024-04-09",gpt_4_turbo_preview:"gpt-4-turbo-preview",gpt_4_1:"gpt-4.1",gpt_4_1_2025_04_14:"gpt-4.1-2025-04-14",gpt_4_1_mini:"gpt-4.1-mini",gpt_4_1_mini_2025_04_14:"gpt-4.1-mini-2025-04-14",gpt_4_1_nano:"gpt-4.1-nano",gpt_4_1_nano_2025_04_14:"gpt-4.1-nano-2025-04-14",gpt_4o:"gpt-4o",gpt_4o_2024_05_13:"gpt-4o-2024-05-13",gpt_4o_2024_08_06:"gpt-4o-2024-08-06",gpt_4o_2024_11_20:"gpt-4o-2024-11-20",gpt_4o_audio_preview:"gpt-4o-audio-preview",gpt_4o_audio_preview_2024_10_01:"gpt-4o-audio-preview-2024-10-01",gpt_4o_audio_preview_2024_12_17:"gpt-4o-audio-preview-2024-12-17",gpt_4o_audio_preview_2025_06_03:"gpt-4o-audio-preview-2025-06-03",gpt_4o_mini:"gpt-4o-mini",gpt_4o_mini_2024_07_18:"gpt-4o-mini-2024-07-18",gpt_4o_mini_audio_preview:"gpt-4o-mini-audio-preview",gpt_4o_mini_audio_preview_2024_12_17:"gpt-4o-mini-audio-preview-2024-12-17",gpt_4o_mini_realtime_preview:"gpt-4o-mini-realtime-preview",gpt_4o_mini_realtime_preview_2024_12_17:"gpt-4o-mini-realtime-preview-2024-12-17",gpt_4o_mini_search_preview:"gpt-4o-mini-search-preview",gpt_4o_mini_search_preview_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",gpt_4o_mini_transcribe:"gpt-4o-mini-transcribe",gpt_4o_mini_tts:"gpt-4o-mini-tts",gpt_4o_realtime_preview:"gpt-4o-realtime-preview",gpt_4o_realtime_preview_2024_10_01:"gpt-4o-realtime-preview-2024-10-01",gpt_4o_realtime_preview_2024_12_17:"gpt-4o-realtime-preview-2024-12-17",gpt_4o_realtime_preview_2025_06_03:"gpt-4o-realtime-preview-2025-06-03",gpt_4o_search_preview:"gpt-4o-search-preview",gpt_4o_search_preview_2025_03_11:"gpt-4o-search-preview-2025-03-11",gpt_4o_transcribe:"gpt-4o-transcribe",gpt_5:"gpt-5",gpt_5_2025_08_07:"gpt-5-2025-08-07",gpt_5_chat_latest:"gpt-5-chat-latest",gpt_5_codex:"gpt-5-codex",gpt_5_mini:"gpt-5-mini",gpt_5_mini_2025_08_07:"gpt-5-mini-2025-08-07",gpt_5_nano:"gpt-5-nano",gpt_5_nano_2025_08_07:"gpt-5-nano-2025-08-07",gpt_5_pro:"gpt-5-pro",gpt_5_pro_2025_10_06:"gpt-5-pro-2025-10-06",gpt_audio:"gpt-audio",gpt_audio_2025_08_28:"gpt-audio-2025-08-28",gpt_audio_mini:"gpt-audio-mini",gpt_audio_mini_2025_10_06:"gpt-audio-mini-2025-10-06",gpt_image_1:"gpt-image-1",gpt_image_1_mini:"gpt-image-1-mini",gpt_realtime:"gpt-realtime",gpt_realtime_2025_08_28:"gpt-realtime-2025-08-28",gpt_realtime_mini:"gpt-realtime-mini",gpt_realtime_mini_2025_10_06:"gpt-realtime-mini-2025-10-06",o1:"o1",o1_2024_12_17:"o1-2024-12-17",o1_mini:"o1-mini",o1_mini_2024_09_12:"o1-mini-2024-09-12",o1_pro:"o1-pro",o1_pro_2025_03_19:"o1-pro-2025-03-19",o3:"o3",o3_2025_04_16:"o3-2025-04-16",o3_deep_research:"o3-deep-research",o3_deep_research_2025_06_26:"o3-deep-research-2025-06-26",o3_mini:"o3-mini",o3_mini_2025_01_31:"o3-mini-2025-01-31",o3_pro:"o3-pro",o3_pro_2025_06_10:"o3-pro-2025-06-10",o4_mini:"o4-mini",o4_mini_2025_04_16:"o4-mini-2025-04-16",o4_mini_deep_research:"o4-mini-deep-research",o4_mini_deep_research_2025_06_26:"o4-mini-deep-research-2025-06-26",omni_moderation_2024_09_26:"omni-moderation-2024-09-26",omni_moderation_latest:"omni-moderation-latest"},Et={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},At=class{config;p;m;constructor(t){this.config=Lt(t)}createConversation(){let t=new Tt(this.config);return t.p=this.p,t.m={uuid:tt(),messages:[]},t}get apiKeyChain(){return void 0===this.p&&(this.p=kt(this.config)),this.p}get conversation(){return this.m}chat(t,e,...r){let{toPrompt:i}=(()=>{if("function"==typeof t)return{toPrompt:t,args:e};if("string"==typeof t)return{toPrompt:()=>t,args:void 0};if(Array.isArray(t)){let e=0===t.length?[{user:""}]:t.filter((t=>void 0!==t));return{toPrompt:()=>e,args:void 0}}{let i=[t,...void 0!==e?[e]:[],...r].filter((t=>void 0!==t)),n=0===i.length?[{user:""}]:i;return{toPrompt:()=>n,args:void 0}}})();return new Vt(this,i,e,Kt(),void 0,void 0,void 0,void 0,!1,!1)}image(t){return new St(t,void 0,void 0,this)}},Tt=class t extends At{constructor(t){super(t)}copyConversation(){if(void 0===this.m)throw Error("This method only works on copy conversation: no conversation exists");let e=new t(this.config);return e.p=this.p,e.m={uuid:tt(),messages:this.m.messages.map((t=>({...t,uuid:tt()})))},e}},St=class{constructor(t,e,r,i){this.prompt=t,this._=e,this.v=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"ImagePrompt"}model(t){return this._=t,this}size(t){return this.v=t,this}toFile(t){return new Nt(this.prompt,this._,this.v,t,this.aiClient)}async getResponseAsString(){let t=y(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await yt(t,this.prompt)}},Nt=class{constructor(t,e,r,i,n){this.prompt=t,this._=e,this.v=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsFile()}finally{t?.()}}get[Symbol.toStringTag](){return"ImageFilePrompt"}model(t){return this._=t,this}size(t){return this.v=t,this}async getResponseAsFile(){let t=y(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await yt(t,this.prompt,this._,this.v);return new Promise(((t,r)=>{_t(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},xt=new At({});function Ut(t){let e=Lt(t);xt.config=e,xt.p=kt(e)}function Pt(t){let e=Lt(t);return new At(e)}function Lt(t){return"string"==typeof t?{promptGridApiKey:jt(t),debugMode:!1,attemptsPerCall:1}:{promptGridApiKey:jt(t.promptGridApiKey),apiKeys:t.apiKeys,debugMode:t.debugMode??!1,attemptsPerCall:Ct(t.attemptsPerCall)}}function jt(t){return pt(t,rt(t).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+t})}function Ct(t){let e=pt(t,rt(t).number().orUndefined(),{errorMessage:"Please provide a valid number of attempts per call; got "+t})??1;if(e<1)throw Error("Please provide a valid number of attempts per call; minimum is 1; got "+e);return e}function kt(t){let e=t.promptGridApiKey,r=t.apiKeys;return{promptgrid:e,openai:(async()=>{if(r?.openai)return r.openai;if(void 0===e)return;let t=await(async()=>{try{return await fetch(T()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+e}})}catch{throw Error("HTTP called failed when doing handshake")}})();if(200!==t.status){let e=await t.text();throw Error(`Handshake failed with status ${t.status}, body: ${e}`)}return(await t.json()).apiKeys.openai})()}}var Ot=new Map;function Rt(t){let e=t??xt;if(void 0===e.apiKeyChain)throw Error("No LLM set up. Call setupPromptGun first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return new It(e,Kt())}var It=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new Vt(this.aiClient,t,e,Kt(),void 0,void 0,void 0,void 0,!1,!1)}},Vt=class t{constructor(t,e,r,i,n,s,o,a,u,l=!1,h,p=[],c=[]){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.A=n,this.T=s,this.S=o,this._=a,this.N=u,this.U=l,this.promptName=h,this.P=p,this.L=c,this.j=this.computeGenericPrompt();let f=this;this.generator=async function*(){yield*await Gt(f.aiClient,Wt(a),f.j,!1,f.promptName,n,s,o,i,f.U,f.P,f.L,void 0)}(),this.stringGenerator=async function*(){for await(let t of f.generator)t!==Xt&&(yield t)}()}generator;stringGenerator;j;name(t){return this.copy({promptName:t})}model(t){return this.copy({model:t})}firstThink(t=!0){return this.copy({firstThink:t})}temperature(t){return this.copy({temperature:t})}topP(t){return this.copy({topP:t})}flex(t=!0){return this.copy({serviceTier:t?"flex":void 0})}priority(t=!0){return this.copy({serviceTier:t?"priority":void 0})}tier(t){return this.copy({serviceTier:t})}strict(t=!0){return this.copy({strict:t})}check(t,e=10){if(e<1)throw Error("The number of attempts must be at least 1");return this.copy({checks:[...this.L,{callback:t,attempts:e}]})}copy({aiClient:e,promptSupplier:r,promptSupplierArgs:i,callingCodeLine:n,temperature:s,topP:o,serviceTier:a,model:u,firstThink:l,strict:h,promptName:p,tools:c,checks:f}){return new t(e??this.aiClient,r??this.promptSupplier,i??this.promptSupplierArgs,n??this.callingCodeLine,s??this.A,o??this.T,a??this.S,u??this._,l??this.N,h??this.U,p??this.promptName,c??this.P,f??this.L)}get result(){return this}get messages(){return this.j.map(Qt)}get json(){return!1}computeGenericPrompt(){let t=this.promptSupplier(this.promptSupplierArgs,Ht),{messages:e,typeSpecIndex:r}=Ft(t);if(!this.json)return e;let i=zt(Wt(this._),this.json,this.N);if(null===i)return e;let n={uuid:tt(),type:"input_message",role:"user",content:i};return void 0!==r?[...e.slice(0,r),n,...e.slice(r)]:[...e,n]}next(...[t]){return this.stringGenerator.next(t)}return(t){return this.stringGenerator.return(t)}throw(t){return this.stringGenerator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}get(t){return new Jt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,Kt(),this.promptName,this.A,this.T,this.S,this._,this.N,this.P,this.U)}getBoolean(){return this.get((t=>t.boolean()))}getString(){return this.get((t=>t.string()))}getNumber(){return this.get((t=>t.number()))}getObject(t){return this.get((e=>e.object(t)))}getArray(t){return new Mt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,(e=>e.array(t)),this.callingCodeLine,this.promptName,this.A,this.T,this.S,this._,this.N,this.P,this.U)}getAny(){return this.get((t=>t.any()))}tool(t,e,r,i){return this.copy({tools:[...this.P,$t("string"==typeof t?"string"==typeof e?{name:t,description:e,parameters:r,function:i}:{name:t,parameters:e,function:r}:t)]})}tools(...t){let e=Array.isArray(t[0])&&1===t.length?t[0].filter((t=>void 0!==t)):t.filter((t=>void 0!==t));return this.P.push(...e),this}async getResponseAsString(){let t="";for await(let e of this)e!==Xt?t+=e:t="";return t}};function $t(t,e,r,i){let n="string"==typeof t?"string"==typeof e?{name:t,description:e,parameters:r,function:i}:{name:t,parameters:e,function:r}:t;return{name:n.name,description:n.description,parameters:n.parameters(rt(void 0)),function:n.function}}function Bt(t,e,r,i){return $t(t,e,r,i)}var Jt=class t extends M{constructor(t,e,r,i,n,s,o,a,u,l,p,c=[],f=!1,m=[]){super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.A=o,this.T=a,this.S=u,this._=l,this.N=p,this.P=c,this.U=f,this.L=m;let d=this;this.j=this.computePrompt();let y,_,w,g=()=>{let e=new N;return y||(y=h.Flux.fromGenerator(async function*(){yield*await Gt(t,Wt(l),d.j,d.json,s,o,a,u,n,d.U,d.P,d.L,i)}()),_=e.processDataBuffer(y),w=(new Y).parse(_),void 0!==i?w.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))):w.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)}))),{flux:y,jsonTokenFlux:_,streamingJsonRootElement:w,jsonTokenProcessor:e}};this.stringGenerator=async function*(){let{flux:t,streamingJsonRootElement:e,jsonTokenProcessor:r}=g();for await(let i of t){if(i===Xt){yield i;continue}let t=r.getExcerpts(i);for(let r of t)void 0!==r.token?e.push(r):void 0!==r.source&&(yield r.source)}}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of d.stringGenerator){if(e===Xt){t="";continue}t+=e;let r=q(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;j;next(...[t]){return this.partialJsonGenerator.next(t)}return(t){return this.partialJsonGenerator.return(t)}throw(t){return this.partialJsonGenerator.throw(t)}[Symbol.asyncIterator](){return this.partialJsonGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonPrompt"}name(t){return this.copy({promptName:t})}model(t){return this.copy({model:t})}firstThink(t=!0){return this.copy({firstThink:t})}temperature(t){return this.copy({temperature:t})}topP(t){return this.copy({topP:t})}flex(t=!0){return this.copy({serviceTier:t?"flex":void 0})}priority(t=!0){return this.copy({serviceTier:t?"priority":void 0})}tier(t){return this.copy({serviceTier:t})}strict(t=!0){return this.copy({strict:t})}check(t,e=10){if(e<1)throw Error("The number of attempts must be at least 1");return this.copy({checks:[...this.L,{callback:t,attempts:e}]})}copy({aiClient:e,promptSupplier:r,promptSupplierArgs:i,jsonTypeSupplier:n,callingCodeLine:s,temperature:o,topP:a,serviceTier:u,model:l,firstThink:h,strict:p,promptName:c,tools:f,checks:m}){return new t(e??this.aiClient,r??this.promptSupplier,i??this.promptSupplierArgs,n??this.jsonTypeSupplier,s??this.callingCodeLine,c??this.promptName,o??this.A,a??this.T,u??this.S,l??this._,h??this.N,f??this.P,p??this.U,m??this.L)}get result(){return this}get messages(){return this.j.map(Qt)}computePrompt(){let t=this.promptSupplier(this.promptSupplierArgs,Ht),{messages:e,typeSpecIndex:r}=Ft(t);if(!this.json)return e;let i=zt(Wt(this._),this.json,this.N);if(null===i)return e;let n={type:"input_message",uuid:tt(),role:"user",content:i};return void 0!==r?[...e.slice(0,r),n,...e.slice(r)]:[...e,n]}get json(){return void 0===this.jsonTypeSupplier||this.jsonTypeSupplier(rt(void 0))}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=D(t);return(()=>void 0!==e&&(!!p(Wt(this._))||"object"!==wt(e(rt(void 0))).type))()?r?.result:r}C;getResponseAsString(){return void 0===this.C&&(this.C=this.k()),this.C}tool(t,e,r,i){return this.copy({tools:[...this.P,$t("string"==typeof t?"string"==typeof e?{name:t,description:e,parameters:r,function:i}:{name:t,parameters:e,function:r}:t)]})}tools(...t){let e=Array.isArray(t[0])&&1===t.length?t[0].filter((t=>void 0!==t)):t.filter((t=>void 0!==t));return this.P.push(...e),this}async k(){let t="";for await(let e of this.stringGenerator)e!==Xt?t+=e:t="";return t}},Mt=class extends Jt{arrayElementGenerator;constructor(t,e,r,i,n,s,o,a,u,l,p,c,f=!1){super(t,e,r,i,n,s,o,a,u,l,p,c,f);let m=this;this.arrayElementGenerator=h.Flux.create((async(t,e)=>{await m.onElement((async e=>{t(await e)})),e()}))}next(...[t]){return this.arrayElementGenerator.next(t)}return(t){return this.arrayElementGenerator.return(t)}throw(t){return this.arrayElementGenerator.throw(t)}[Symbol.asyncIterator](){return this.arrayElementGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonArrayPrompt"}};function Ft(t,e){let r=t=>void 0===t||"typeSpec"in t?null:{type:"input_message",uuid:tt(),role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:z(t.user??t.system??t.assistant)};if("string"==typeof t)return{messages:[{type:"input_message",uuid:tt(),role:"user",content:t}]};if(Array.isArray(t)){let e,i=[];for(let n=0;n<t.length;n++){let s=t[n];if("typeSpec"in s)e=i.length;else{let t=r(s);t&&i.push(t)}}return{messages:i,typeSpecIndex:e}}{let e=r(t);return{messages:e?[e]:[]}}}async function*Gt(t,e,r,i,n,s,o,a,u,l,h,c,m){let d=new Map;try{let{fileName:_,lineNumber:w}=u;if(_&&void 0!==w&&Array.from(Ot.keys()).filter((t=>t.startsWith(_+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${_}. Please specify a name using .name() method.`);let g={id:n,callingCodeLine:u},v=t.conversation?.uuid??tt(),b={},E=t.conversation?.messages??[],A=e=>{let r=tt();for(let t of e.messages){let e=E.find((e=>e.uuid===t.uuid));if(void 0!==e){if(e.role!==t.role)throw Error("Illegal state");e.content=t.content}else E.push(t)}let i=async()=>{b.currentSave=b.nextSave,b.nextSave=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(T()+"/api/conversations",{method:"PUT",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e},body:JSON.stringify(t)});if(!r.ok)throw Error(`Got ${r.status} when attempting to save conversation, with body: ${await r.text()}`)}catch(t){console.error("Error saving conversation",t)}}({prompt:e.prompt,conversationUuid:e.conversationUuid,messages:E},t.apiKeyChain.promptgrid),await(b.nextSave?.callback()),b.currentSave=void 0};void 0!==b.nextSave&&d.delete(b.nextSave.uuid),b.nextSave={uuid:r,callback:i},void 0===b.currentSave&&d.set(r,{promise:i().then()})},S=[...t.conversation?.messages??[],...r];A({conversationUuid:v,prompt:g,messages:S});let N=!1,x=1,U=c.reduce(((t,e)=>t.set(e,1)),new Map);for(;!N;){tt();try{let r=y(await t.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),n=h?.map((t=>({type:"function",name:t.name,description:t.description,parameters:wt(t.parameters),strict:!0}))),{flux:u,httpRequest:d}=f(gt({model:Wt(e),prompt:S,apiToken:r,temperature:s,topP:o,requireJsonResponse:!1!==i,jsonSchema:Dt(m,i,e,l),serviceTier:a,tools:n}),r),_="",w=[];yield*u.flatMap((t=>{switch(t.type){case"response.output_text.delta":return[{type:"content",content:t.delta}];case"response.created":case"response.in_progress":case"response.completed":for(let[e,r]of t.response.output.entries()){let t=w.findIndex((t=>t.llmPlatformConversationItem.id===r.id)),i=t>=0?w[t]:void 0,n=(()=>{let t={uuid:i?.uuid??tt(),llmPlatform:"openai",llmPlatformConversationItem:r,httpRequest:0===e?JSON.stringify(d):void 0,role:"assistant"};switch(r.type){case"message":return{...t,type:"output_message",content:r.content.flatMap((t=>"output_text"===t.type?[t.text]:[])).join("")};case"reasoning":return{...t,type:"reasoning",content:r.content?.map((t=>t.text)).join("")??r.summary.map((t=>t.text)).join("")};case"function_call":return{...t,type:"function_call_input",name:r.name,arguments:r.arguments,content:`${r.name}(${r.arguments})`,functionCallId:r.call_id}}})();A({conversationUuid:v,prompt:g,messages:[n]}),t>=0?w[t]=n:w.push(n)}return[];case"error":throw Error(`${t.error.type}: ${t.error.message}`);default:return[]}})).doOnEach((t=>{"content"===t.type&&(_+=t.content)})).flatMap((t=>"content"===t.type?[t.content]:[]));let b=w.flatMap((t=>"function_call_input"===t.type?(()=>{let e=t.llmPlatformConversationItem;return{id:e.call_id,name:e.name,arguments:e.arguments}})():[]));if(w.map((t=>t.llmPlatformConversationItem)),b.length>0){let t=(await qt(b,h)).map((t=>({type:"function_call_output",uuid:tt(),role:"user",functionCallId:t.tool_call_id,content:`Tool result for ${t.call.name}: ${t.content}`})));A({conversationUuid:v,prompt:g,messages:t}),S=[...S,...w,...t],x=1;continue}let E=(()=>{let t=w.filter((t=>"output_message"===t.type));if(1!==t.length)throw Error("Expected 1 output message, got "+JSON.stringify(w));return t[0].content})(),T=(()=>{if(void 0===m)return E;try{let t=D(E),r=p(e)||"object"!==wt(m(rt(void 0))).type?t?.result:t;return pt(r,m(rt(r)),{juggleBetweenNullAndUndefined:!0})}catch(t){try{let t=D(E);return pt(t,m(rt(t)),{juggleBetweenNullAndUndefined:!0})}catch{throw Error("JSON response failed type validation: "+(t instanceof Error?t.message:t+""))}}})();if(c.length>0){let t=c.map((async t=>({result:await(async()=>{try{return await t.callback(T)??void 0}catch(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;throw t}})(),check:t}))),e=(await Promise.all(t)).flatMap((({result:t,check:e})=>{let r="string"==typeof t?[t]:Array.isArray(t)?t.flatMap((t=>"string"==typeof t?[t]:[])):[];if(r.length>0){let t=z(U.get(e));if(t>=e.attempts)throw new Yt(e,e.attempts,t,r);U.set(e,t+1)}return r}));if(e.length>0){let t={type:"input_message",uuid:tt(),role:"user",content:"Your result was rejected because:\n"+e.map((t=>"- "+t)).join("\n")};A({conversationUuid:v,prompt:g,messages:[t]}),S=[...S,...w,t],yield Xt,x=1;continue}}S=[...S,...w],N=!0}catch(e){if(e instanceof Error&&e.name===Yt.name||x>=t.config.attemptsPerCall)throw e;await new Promise((t=>setTimeout(t,1e3))),console.warn(`AI call failed, retrying (try ${x+1}/${t.config.attemptsPerCall})`,e),yield Xt,x++}}}finally{if(t.config.debugMode){let t=Array.from(d.values()).map((t=>t.promise));await Promise.all(t)}}}var Yt=class extends Error{constructor(t,e,r,i,n){super(n),this.check=t,this.maxAttempts=e,this.attempts=r,this.problemsOnLastAttempt=i}};function Dt(t,e,r,i){if(void 0===t||!1===e||p(r))return;let n=wt(t(rt(void 0)));return{name:"response",schema:"object"===n.type?n:{type:"object",properties:{result:n},required:["result"],additionalProperties:!1},strict:i}}async function qt(t,e){if(void 0===e)throw Error("Illegal state: no tools defined");let r=[];for(let i of t){let t=e.find((t=>t.name===i.name)),n=await(async()=>{if(void 0===t)return`Error: Tool ${i.name} not found`;try{let e=""===i.arguments.trim()?{}:JSON.parse(i.arguments);return await t.function(e)}catch(t){return"Error: "+(t instanceof Error?t.message:t+"")}})();r.push({call:i,tool:t,tool_call_id:i.id,role:"tool",content:n})}return r}function zt(t,e,r){if(!p(t))return function(t){return!(!t.startsWith("gpt-")&&!t.startsWith("o1-")&&"o1"!==t&&"o3-mini"!==t&&"o3"!==t)}(t)?"Respond with JSON":null;{if(!0===e)return"TYPE SPEC :: IGNORE ALL PREVIOUS TYPE SPECS\n\nIn your next message only, respond with JSON";let t=e;return"TYPE SPEC :: IGNORE ALL PREVIOUS TYPE SPECS\n\nIn its next message only, the assistant will respond with JSON matching the Typescript type below.\n- strictNullChecks, exactOptionalPropertyTypes are both on\n- a value can ONLY be null if explicitly stated, e.g. 'string | null'\n- optional properties (e.g. `{foo?: string}`) can only be achieved by not including it, NOT by setting them to null\n\nThe type:\n"+ct(new st([],void 0).object((e=>{let i=e;return r&&(i=i.hasString("reasoning","Elaborate your reasoning here. Think step by step. Give your thinking steps in a numbered list or in markdown with headers if the task requires it.")),i.has("result",(()=>new ht(t.type,t.value)))})))}}var Ht={typeSpec:!0};function Kt(){let t=(Error().stack??"").split("\n").map((t=>t.trim())).filter((t=>t.startsWith("at ")))[2],e=t.match(/[^(]+\([^)]+\)/),{functionName:r,fileName:i,lineNumber:n}=e?t.match("at (?<functionName>[^(]*) ((?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+))").groups:t.match("at (?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+)").groups;return{stacktraceFrame:y(t).canBeString().andNothingElse(),fileName:y(i).canBeString().andNothingElse(),lineNumber:y(parseInt(n)).canBeNumber().andNothingElse(),functionName:y(r).canBeString().canBeUndefined().andNothingElse()}}function Qt(t){switch(t.type){case"input_message":case"output_message":return{[t.role]:t.content};case"reasoning":case"function_call_input":return{assistant:t.content};case"function_call_output":return{user:t.content}}}function Wt(t){return t??"gpt-5"}var Xt="retry-signal-"+tt();export{At as AIClient,Tt as AIConversation,bt as AiModel,Vt as BasicPrompt,lt as EmptyPropTypeSpec,st as EmptyTypeSpec,ht as FullPropTypeSpec,ot as FullTypeSpec,Nt as ImageFilePrompt,St as ImagePrompt,Mt as JsonArrayPrompt,Jt as JsonPrompt,Et as OpenaiImageModel,It as PromptBase,ut as PropTypeSpec,M as StreamedJsonChildElement,G as StreamedJsonRootElement,at as TypeMemberSpec,nt as TypeSpec,Ht as TypeSpecMarker,xt as ai,$t as aiTool,Bt as defineTool,Kt as getCallerFileNameAndLineNumber,Pt as newAIClient,kt as obtainAiClientData,q as parsePartialJson,Rt as promptAI,Ut as setupAI,wt as typeSpecToJsonSchema};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|