promptgun 0.18.12 → 0.20.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/blackhole.png ADDED
Binary file
package/build/index.d.ts CHANGED
@@ -17,9 +17,9 @@ export declare class AIClient {
17
17
  chat<T extends undefined>(userMessage: string): BasicPrompt<T>;
18
18
  chat<T extends undefined>(...messages: (Message | undefined)[]): BasicPrompt<T>;
19
19
  chat<T extends undefined>(messages: (Message | undefined)[]): BasicPrompt<T>;
20
- chat<T extends undefined>(toPrompt: (args?: T) => Prompt): BasicPrompt<T>;
21
- chat<T>(toPrompt: (args: T) => Prompt, args: T): BasicPrompt<T>;
22
- chat<T = undefined>(toPrompt: (args?: T) => Prompt, args?: T): BasicPrompt<T>;
20
+ chat<T extends undefined>(toPrompt: (args?: T, typeSpecMessage?: TypeSpecMessage) => Prompt): BasicPrompt<T>;
21
+ chat<T>(toPrompt: (args: T, typeSpecMessage?: TypeSpecMessage) => Prompt, args: T): BasicPrompt<T>;
22
+ chat<T = undefined>(toPrompt: (args?: T, typeSpecMessage?: TypeSpecMessage) => Prompt, args?: T): BasicPrompt<T>;
23
23
  image(prompt: string): ImagePrompt;
24
24
  }
25
25
 
@@ -984,7 +984,7 @@ export declare type AssistantMessage = {
984
984
  system?: undefined;
985
985
  user?: undefined;
986
986
  assistant: string;
987
- developer?: string;
987
+ developer?: undefined;
988
988
  };
989
989
 
990
990
  export declare type BaseType<TT extends TypeType> = {
@@ -1003,7 +1003,8 @@ export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Prom
1003
1003
  private _firstThink;
1004
1004
  private readonly generator;
1005
1005
  private promptName?;
1006
- constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, callingCodeLine: CodeLine, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1006
+ private _tools?;
1007
+ constructor(aiClient: AIClient, promptSupplier: (args: PSArgs, typeSpecMessage?: TypeSpecMessage) => Prompt, promptSupplierArgs: PSArgs, callingCodeLine: CodeLine, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1007
1008
  name(name: string): this;
1008
1009
  model(model: AiModelId): this;
1009
1010
  /**
@@ -1054,6 +1055,8 @@ export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Prom
1054
1055
  getObject<T_obj extends {}>(properties: (arg: TypeMemberSpec<{}>) => TypeMemberSpec<T_obj>): JsonPrompt<PSArgs, T_obj>;
1055
1056
  getArray<T_arr extends AnyJson>(element: (arg: EmptyTypeSpec<unknown>) => TypeSpec<T_arr>): JsonArrayPrompt<PSArgs, T_arr>;
1056
1057
  getAny(): JsonPrompt<PSArgs, AnyJson>;
1058
+ tools(tools: ToolDefinition[]): this;
1059
+ tools(...tools: (ToolDefinition | undefined)[]): this;
1057
1060
  private getResponseAsString;
1058
1061
  }
1059
1062
 
@@ -1081,10 +1084,17 @@ export declare type DeepPartial<T> = T extends object ? {
1081
1084
  [P in keyof T]?: DeepPartial<T[P]>;
1082
1085
  } : T;
1083
1086
 
1087
+ export declare function defineTool<T>(config: {
1088
+ name: string;
1089
+ description: string;
1090
+ parameters: (spec: EmptyTypeSpec<unknown>) => TypeSpec<T>;
1091
+ function: ToolFunction<T>;
1092
+ }): ToolDefinition<T>;
1093
+
1084
1094
  export declare type DeveloperMessage = {
1085
1095
  system?: undefined;
1086
1096
  user?: undefined;
1087
- assistant?: string;
1097
+ assistant?: undefined;
1088
1098
  developer: string;
1089
1099
  };
1090
1100
 
@@ -1201,7 +1211,7 @@ export declare type JsonArray = AnyJson[];
1201
1211
 
1202
1212
  export declare class JsonArrayPrompt<PSArgs, T_arr extends AnyJson = AnyJson> extends JsonPrompt<PSArgs, T_arr[]> {
1203
1213
  protected readonly arrayElementGenerator: Flux<T_arr>;
1204
- constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<T_arr[]>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1214
+ constructor(aiClient: AIClient, promptSupplier: (args: PSArgs, typeSpecMessage?: TypeSpecMessage) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<T_arr[]>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1205
1215
  next(...[value]: [] | [any]): Promise<IteratorResult<T_arr>>;
1206
1216
  return(value: any): Promise<IteratorResult<T_arr, any>>;
1207
1217
  throw(e: any): Promise<IteratorResult<T_arr, any>>;
@@ -1223,7 +1233,7 @@ export declare type JsonObject = {
1223
1233
 
1224
1234
  export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends StreamedJsonChildElement<Json> implements AsyncGenerator<AnyJson>, Promise<Json> {
1225
1235
  protected aiClient: AIClient;
1226
- protected promptSupplier: (args: PSArgs) => Prompt;
1236
+ protected promptSupplier: (args: PSArgs, typeSpecMessage?: TypeSpecMessage) => Prompt;
1227
1237
  protected promptSupplierArgs: PSArgs;
1228
1238
  protected jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<Json>) | undefined;
1229
1239
  protected callingCodeLine: CodeLine;
@@ -1235,7 +1245,8 @@ export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends
1235
1245
  protected _firstThink: boolean;
1236
1246
  protected readonly stringGenerator: AsyncGenerator<string>;
1237
1247
  protected readonly partialJsonGenerator: AsyncGenerator<AnyJson>;
1238
- constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<Json>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1248
+ protected _tools?: ToolDefinition[];
1249
+ constructor(aiClient: AIClient, promptSupplier: (args: PSArgs, typeSpecMessage?: TypeSpecMessage) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<Json>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _serviceTier: ServiceTier | undefined, _model: AiModelId | undefined, _firstThink: boolean);
1239
1250
  next(...[value]: [] | [any]): Promise<IteratorResult<AnyJson, any>>;
1240
1251
  return(value: any): Promise<IteratorResult<AnyJson, any>>;
1241
1252
  throw(e: any): Promise<IteratorResult<AnyJson, any>>;
@@ -1282,10 +1293,12 @@ export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends
1282
1293
  protected getResponse(): Promise<Json>;
1283
1294
  private _responseAsStringPromise?;
1284
1295
  protected getResponseAsString(): Promise<string>;
1296
+ tools(tools: ToolDefinition[]): this;
1297
+ tools(...tools: (ToolDefinition | undefined)[]): this;
1285
1298
  protected _getResponseAsString(): Promise<string>;
1286
1299
  }
1287
1300
 
1288
- export declare type Message = SystemMessage | UserMessage | AssistantMessage | DeveloperMessage;
1301
+ export declare type Message = SystemMessage | UserMessage | AssistantMessage | DeveloperMessage | TypeSpecMessage;
1289
1302
 
1290
1303
  export declare function newAIClient(promptGridApiKey: string): AIClient;
1291
1304
 
@@ -1322,7 +1335,7 @@ export declare type Opts = {
1322
1335
 
1323
1336
  export declare function parsePartialJson<T>(partialJson: string): DeepPartial<T> | undefined;
1324
1337
 
1325
- export declare type Prompt = string | Message | Message[];
1338
+ export declare type Prompt = string | Message | (Message | undefined)[];
1326
1339
 
1327
1340
  export declare function promptAI(client?: AIClient): PromptBase;
1328
1341
 
@@ -1330,9 +1343,9 @@ export declare class PromptBase {
1330
1343
  private aiClient;
1331
1344
  private callingCodeLine;
1332
1345
  constructor(aiClient: AIClient, callingCodeLine: CodeLine);
1333
- completeChat<T extends undefined>(toPrompt: (args?: T) => Prompt): BasicPrompt<T>;
1334
- completeChat<T>(toPrompt: (args: T) => Prompt, args: T): BasicPrompt<T>;
1335
- completeChat<T = undefined>(toPrompt: (args?: T) => Prompt, args?: T): BasicPrompt<T>;
1346
+ completeChat<T extends undefined>(toPrompt: (args?: T, typeSpecMessage?: TypeSpecMessage) => Prompt): BasicPrompt<T>;
1347
+ completeChat<T>(toPrompt: (args: T, typeSpecMessage?: TypeSpecMessage) => Prompt, args: T): BasicPrompt<T>;
1348
+ completeChat<T = undefined>(toPrompt: (args?: T, typeSpecMessage?: TypeSpecMessage) => Prompt, args?: T): BasicPrompt<T>;
1336
1349
  }
1337
1350
 
1338
1351
  export declare type PromptGunConfig = {
@@ -1443,7 +1456,7 @@ export declare type SystemMessage = {
1443
1456
  system: string;
1444
1457
  user?: undefined;
1445
1458
  assistant?: undefined;
1446
- developer?: string;
1459
+ developer?: undefined;
1447
1460
  };
1448
1461
 
1449
1462
  export declare class Token {
@@ -1470,6 +1483,15 @@ export declare enum TokenType {
1470
1483
  COMMA = "COMMA"
1471
1484
  }
1472
1485
 
1486
+ export declare type ToolDefinition<T = any> = {
1487
+ name: string;
1488
+ description: string;
1489
+ parameters: TypeSpec<T>;
1490
+ function: ToolFunction<T>;
1491
+ };
1492
+
1493
+ export declare type ToolFunction<T = any> = (args: T) => Promise<string> | string;
1494
+
1473
1495
  export declare type Type = UndefinedType | NullType | BooleanType | StringType | NumberType | ObjectType | ArrayType | ConstantType<any>;
1474
1496
 
1475
1497
  export declare class TypeMemberSpec<T> {
@@ -1498,6 +1520,18 @@ export declare abstract class TypeSpec<T> {
1498
1520
  constructor(type: Type[], value: unknown, _?: T);
1499
1521
  }
1500
1522
 
1523
+ export declare const TypeSpecMarker: {
1524
+ readonly typeSpec: true;
1525
+ };
1526
+
1527
+ export declare type TypeSpecMessage = {
1528
+ system?: undefined;
1529
+ user?: undefined;
1530
+ assistant?: undefined;
1531
+ developer?: undefined;
1532
+ typeSpec: true;
1533
+ };
1534
+
1501
1535
  export declare type TypeType = 'undefined' | 'null' | 'boolean' | 'string' | 'number' | 'object' | 'array' | 'constant';
1502
1536
 
1503
1537
  export declare type UndefinedType = BaseType<'undefined'>;
@@ -1506,7 +1540,7 @@ export declare type UserMessage = {
1506
1540
  system?: undefined;
1507
1541
  user: string;
1508
1542
  assistant?: undefined;
1509
- developer?: string;
1543
+ developer?: undefined;
1510
1544
  };
1511
1545
 
1512
1546
  export { }
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,l)=>(l=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?l:e(l,"default",{value:o,enumerable:!0}),o)),l=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){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){let r=e(t);if(Array.isArray(r))for(let t of r)yield t;else yield await r}}),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})},l=t=>{r={value:t},n.shift()?.reject(t)};return(async()=>{try{await e(o,a,l)}catch(t){l(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=>(l(t),Promise.reject(t))})}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={}})),h=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=l();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),u=a(h(),1),p=a(h(),1);function c({model:t,prompt:e,apiToken:r,temperature:i,topP:n,requireJsonResponse:s,serviceTier:o}){return p.Flux.fromGeneratorFunction((async function*(){let a=new AbortController,l=await fetch("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+r},method:"POST",signal:a.signal,body:JSON.stringify({model:t,messages:e,stream:!0,temperature:i,top_p:n,response_format:s?{type:"json_object"}:void 0,service_tier:"flex"===o?"flex":"default"})});if(l.status<200||l.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await l.text());throw Error("OpenAPI reported: "+t)}if(null===l.body)throw Error("illegal state");let h="";yield*p.Flux.fromReadableStream(l.body,(()=>a.abort())).map((t=>f.decode(t,{stream:!0}))).flatMap((t=>t.replaceAll("data: [DONE]","").replace(/^data: /,"").split("data: "))).map((t=>t.replace(/[\n ]*$/,"").trim())).flatMap((t=>{h+=t;try{let t=JSON.parse(h);return h="",[t]}catch{return[]}})).map((t=>t.choices[0])).untilExcl((t=>null!=t.finish_reason)).map((t=>t.delta.content)).filter((t=>void 0!==t))}))}var f=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(b).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 w(t){return new y([],t)}function m(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?[]:m(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(...m(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 _,y=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.hasProperty(t,(t=>t.canBeString()))}canHaveProperty(t,e){return this.hasProperty(t,e,!0)}hasProperty(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=m(this.value,this.type,"root",t);if(e.length>0)throw new d(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return m(this.value,this.type,"root",e).length>0?t:this.value}describe(){return g(this.type)}};function g(t,e=0){if(Array.isArray(t))return t.map((t=>g(t,e))).join(" | ");switch(t.type){case"array":return g(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${v(e+1)}${r}: ${g(t.props[r].type,e+1)}`)).join(",\n")+`\n${v(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function v(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function b(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as A}from"dotenv";function E(){if(!_){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(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return _}var T=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 U(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}},U=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 T(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT";let t=new T(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 T(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY";let t=new T(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 T(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 T(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 T(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 T(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 T(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 T(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 T(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName,i)}}throw new S("Invalid JSON at position "+this.position)}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()}},S=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},L=a(h(),1);function x(t){return null!=t}var P=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new R;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 M,i=[],n=new $;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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(x(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.o(this.toAsync(t),void 0)}o(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.o(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.o((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.o(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.o(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.o(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.o(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return L.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.o((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(O))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(R))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new I,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new k,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 V(e)}else if(this.isState(I))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 $;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new I})),this.state=new B(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>{t(r)})),r.push(t)}default:throw new V(e)}else if(this.isState(k))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 $;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new k})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new j(e),e.push(t)}case"COMMA":return void this.receivedJson.push(e.source);default:throw new V(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{},O=class extends C{constructor(t){super(),this.child=t}},R=class extends C{},k=class extends C{},j=class extends O{constructor(t){super(t)}},I=class extends C{},B=class extends O{constructor(t){super(t)}},V=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},M=class{getExcerpts(t){return[{source:t}]}},$=class extends P{constructor(){super()}},J=a(h(),1),F=class extends P{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=J.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))}},G=class{parse(t){return new F(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 Y(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 H(t){if(void 0===t)throw Error("Value is undefined");return t}var z=[];for(let t=0;t<256;++t)z.push((t+256).toString(16).slice(1));import{randomFillSync as K}from"crypto";var q=new Uint8Array(256),Q=q.length;import{randomUUID as W}from"crypto";var X={randomUUID:W},Z=function(t,e,r){if(X.randomUUID&&!e&&!t)return X.randomUUID();let i=(t=t||{}).random??t.rng?.()??(Q>q.length-16&&(K(q),Q=0),q.slice(Q,Q+=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(z[t[e+0]]+z[t[e+1]]+z[t[e+2]]+z[t[e+3]]+"-"+z[t[e+4]]+z[t[e+5]]+"-"+z[t[e+6]]+z[t[e+7]]+"-"+z[t[e+8]]+z[t[e+9]]+"-"+z[t[e+10]]+z[t[e+11]]+z[t[e+12]]+z[t[e+13]]+z[t[e+14]]+z[t[e+15]]).toLowerCase()}(i)},tt=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 et(t){return new nt([],t)}function rt(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=>rt(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],l=rt(n in t?t[n]:void 0,a.optional?[...a.type,{type:"undefined"}]:a.type,r+"."+n,i);void 0!==l.juggleTo&&o.push({key:n,juggleTo:l.juggleTo.value}),s.push(...l.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 it=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.l=r}},nt=class t extends it{array(e){let r=e(new t([],this.value)),i=new st([{type:"array",elementType:r.type}],this.value);return new st([...this.type,...i.type],this.value)}object(t){let e=t(new ot([{type:"object",props:{}}],this.value));return new st([...this.type,...e.type],this.value)}string(){return new st([...this.type,{type:"string"}],this.value)}number(){return new st([...this.type,{type:"number"}],this.value)}boolean(){return new st([...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 st([...this.type,{type:"null"}],this.value)}undefined(){return new st([...this.type,{type:"undefined"}],this.value)}any(){return new st([],this.value)}},st=class t extends it{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 ot([{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)}},ot=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 l=r(new lt([],this.value)),h=l.type,u=l.h;return new t([{...a,props:{...a.props,[e]:{optional:s,type:h,comment:(()=>{let t=[...u,...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)}},at=class extends it{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 at{array(t){let e=t(new nt([],this.value)),r=new st([{type:"array",elementType:e.type}],this.value);return new ht([...this.type,...r.type],this.value)}object(t){let e=t(new ot([{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 at{orArray(e){let r=e(new st([],this.value)),i=new st([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new ot([{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 ut(t,e,r={}){let{problems:i,juggleTo:n}=rt(t,e.type,"root",r);if(i.length>0)throw new tt(i,r.errorMessage);return void 0!==n?n.value:t}function pt(t){return ct(t.type)}function ct(t,e=0){if(Array.isArray(t))return t.map((t=>ct(t,e))).join(" | ");switch(t.type){case"array":return ct(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=ct(s.type,e+1),a=n<r.length-1?",":"",l=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${ft(e+1)}${i}?: ${o}${a}${l}\n`:`${ft(e+1)}${i}: ${o}${a}${l}\n`})).join("")+ft(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function ft(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 wt(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 mt}from"fs";var _t={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_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_image_1:"gpt-image-1",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"},yt={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},gt=class{config;u;p;constructor(t){this.config=Ut(t)}createConversation(){let t=new vt(this.config);return t.u=this.u,t.p={uuid:Z(),messages:[]},t}get apiKeyChain(){return void 0===this.u&&(this.u=xt(this.config)),this.u}get conversation(){return this.p}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 Rt(this,i,e,$t(),void 0,void 0,void 0,void 0,!1)}image(t){return new bt(t,void 0,void 0,this)}},vt=class t extends gt{constructor(t){super(t)}copyConversation(){if(void 0===this.p)throw Error("This method only works on copy conversation: no conversation exists");let e=new t(this.config);return e.u=this.u,e.p={uuid:Z(),messages:this.p.messages.map((t=>({...t,uuid:Z()})))},e}},bt=class{constructor(t,e,r,i){this.prompt=t,this.m=e,this._=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(x(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.m=t,this}size(t){return this._=t,this}toFile(t){return new At(this.prompt,this.m,this._,t,this.aiClient)}async getResponseAsString(){let t=w(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await wt(t,this.prompt)}},At=class{constructor(t,e,r,i,n){this.prompt=t,this.m=e,this._=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(x(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.m=t,this}size(t){return this._=t,this}async getResponseAsFile(){let t=w(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await wt(t,this.prompt,this.m,this._);return new Promise(((t,r)=>{mt(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},Et=new gt({});function Tt(t){let e=Ut(t);Et.config=e,Et.u=xt(e)}function Nt(t){let e=Ut(t);return new gt(e)}function Ut(t){return"string"==typeof t?{promptGridApiKey:St(t),debugMode:!1,attemptsPerCall:1}:{promptGridApiKey:St(t.promptGridApiKey),apiKeys:t.apiKeys,debugMode:t.debugMode??!1,attemptsPerCall:Lt(t.attemptsPerCall)}}function St(t){return ut(t,et(t).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+t})}function Lt(t){let e=ut(t,et(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 xt(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(E()+"/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 Pt=new Map;function Ct(t){let e=t??Et;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 Ot(e,$t())}var Ot=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new Rt(this.aiClient,t,e,$t(),void 0,void 0,void 0,void 0,!1)}},Rt=class{constructor(t,e,r,i,n,s,o,a,l){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.v=n,this.A=s,this.T=o,this.m=a,this.N=l;let h=this;this.generator=async function*(){yield*await Vt(h.aiClient,a,h.genericMessages,!1,h.promptName,n,s,o,i)}()}generator;promptName;name(t){return this.promptName=t,this}model(t){return this.m=t,this}firstThink(t=!0){return this.N=t,this}temperature(t){return this.v=t,this}topP(t){return this.A=t,this}flex(t=!0){return this.T=t?"flex":void 0,this}get result(){return this}get messages(){return this.genericMessages.map((t=>({[t.role]:t.content})))}get json(){return!1}get genericMessages(){let t=Bt(this.promptSupplier(this.promptSupplierArgs));if(!this.json)return t;let e=(()=>{let e=t.length-1;for(;e>=0&&"user"===t[e].role;)e--;return e})();return[...t.slice(0,e+1),{role:"system",content:Mt(0,this.json,this.N)},...t.slice(e+1)]}next(...[t]){return this.generator.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(x(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 kt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,$t(),this.promptName,this.v,this.A,this.T,this.m,this.N)}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.v,this.A,this.T,this.m,this.N)}getAny(){return this.get((t=>t.any()))}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}},kt=class extends ${constructor(t,e,r,i,n,s,o,a,l,h,p){super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.v=o,this.A=a,this.T=l,this.m=h,this.N=p;let c=this,f=async function*(){yield*await Vt(t,h,c.genericMessages,c.json,s,o,a,l,n)}(),d=u.Flux.fromGenerator(f),w=(new N).processDataBuffer(d),m=(new G).parse(w);void 0!==i?m.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))):m.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})),this.stringGenerator=async function*(){for await(let t of w)void 0!==t.token?m.push(t):void 0!==t.source&&(yield t.source)}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of c.stringGenerator){t+=e;let r=Y(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(x(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.promptName=t,this}model(t){return this.m=t,this}firstThink(t=!0){return this.N=t,this}temperature(t){return this.v=t,this}topP(t){return this.A=t,this}flex(t=!0){return this.T=t?"flex":void 0,this}get result(){return this}get messages(){return this.genericMessages.map((t=>({[t.role]:t.content})))}get genericMessages(){let t=Bt(this.promptSupplier(this.promptSupplierArgs));if(!this.json)return t;let e=(()=>{let e=t.length-1;for(;e>=0&&"user"===t[e].role;)e--;return e})();return[...t.slice(0,e+1),{role:"system",content:Mt(0,this.json,this.N)},...t.slice(e+1)]}get json(){return void 0===this.jsonTypeSupplier||this.jsonTypeSupplier(et(void 0))}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=D(t),i=void 0!==e?r?.result:r;if(void 0===e)return i;try{return ut(i,e(et(i)),{juggleBetweenNullAndUndefined:!0})}catch{return console.debug('AI forgot to pack result in {"result": ...} wrapper, continuing by using complete result'),ut(r,e(et(i)),{juggleBetweenNullAndUndefined:!0})}}U;getResponseAsString(){return void 0===this.U&&(this.U=this.S()),this.U}async S(){let t="";for await(let e of this.stringGenerator)t+=e;return t}},jt=class extends kt{arrayElementGenerator;constructor(t,e,r,i,n,s,o,a,l,h,p){super(t,e,r,i,n,s,o,a,l,h,p);let c=this;this.arrayElementGenerator=u.Flux.create((async(t,e)=>{await c.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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(x(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonArrayPrompt"}};function It(t){return t??"gpt-4o"}function Bt(t){let e=t=>({role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:H(t.user??t.system??t.assistant)});return"string"==typeof t?[{role:"user",content:t}]:Array.isArray(t)?t.map(e):[e(t)]}async function*Vt(t,e,r,i,n,s,o,a="normal",l){let h=new Map;try{let{fileName:u,lineNumber:p}=l;if(u&&void 0!==p&&Array.from(Pt.keys()).filter((t=>t.startsWith(u+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${u}. Please specify a name using .name() method.`);let f={id:n,callingCodeLine:l},d=t.conversation?.uuid??Z(),m={},_=(e,r)=>{let i=Z(),n=async()=>{if(void 0!==t.conversation){for(let r of e.messages){let e=t.conversation.messages.find((t=>t.messageUuid===r.messageUuid));if(void 0!==e){if(e.role!==r.role)throw Error("Illegal state");e.content=r.content}else t.conversation.messages.push(r)}t.conversation.messages=[...t.conversation.messages]}m.currentSave=m.save,m.save=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(E()+"/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)}}(e,t.apiKeyChain.promptgrid),await new Promise((t=>setTimeout(t,100))),await(m.save?.callback()),m.currentSave=void 0};void 0!==m.save&&h.delete(m.save.uuid),m.save={uuid:i,callback:n},void 0===m.currentSave&&h.set(i,{chunk:r,promise:n().then()})};_({conversationUuid:d,prompt:f,messages:r.map((t=>({messageUuid:Z(),role:t.role,content:t.content||""})))});let y=Z();_({conversationUuid:d,prompt:f,messages:[{messageUuid:y,role:"assistant",content:""}]});let g=!0,v=1;for(;g;)try{let n=w(await t.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),l=c({model:It(e),prompt:[...t.conversation?.messages??[],...r],apiToken:n,temperature:s,topP:o,requireJsonResponse:!1!==i,serviceTier:a}),h="";yield*l.doOnEach((t=>{h+=t,_({conversationUuid:d,prompt:f,messages:[{messageUuid:y,role:"assistant",content:h}]},t)})),g=!1}catch(e){if(v>=t.config.attemptsPerCall)throw e;await new Promise((t=>setTimeout(t,1e3))),console.warn(`AI call failed, retrying (${v}/${t.config.attemptsPerCall-1})`,e)}finally{v++}}finally{if(t.config.debugMode){let t=Array.from(h.values()).map((t=>t.promise));await Promise.all(t)}}}function Mt(t,e,r){{if(!0===e)return"Respond with JSON";let t=e;return"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"+pt(new nt([],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)))})))}}function $t(){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:w(t).canBeString().andNothingElse(),fileName:w(i).canBeString().andNothingElse(),lineNumber:w(parseInt(n)).canBeNumber().andNothingElse(),functionName:w(r).canBeString().canBeUndefined().andNothingElse()}}export{gt as AIClient,vt as AIConversation,_t as AiModel,Rt as BasicPrompt,lt as EmptyPropTypeSpec,nt as EmptyTypeSpec,ht as FullPropTypeSpec,st as FullTypeSpec,At as ImageFilePrompt,bt as ImagePrompt,jt as JsonArrayPrompt,kt as JsonPrompt,yt as OpenaiImageModel,Ot as PromptBase,at as PropTypeSpec,$ as StreamedJsonChildElement,F as StreamedJsonRootElement,ot as TypeMemberSpec,it as TypeSpec,Et as ai,$t as getCallerFileNameAndLineNumber,Nt as newAIClient,xt as obtainAiClientData,Y as parsePartialJson,Ct as promptAI,Tt as setupAI};
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,l)=>(l=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?l:e(l,"default",{value:o,enumerable:!0}),o)),l=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){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){let r=e(t);if(Array.isArray(r))for(let t of r)yield t;else yield await r}}),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})},l=t=>{r={value:t},n.shift()?.reject(t)};return(async()=>{try{await e(o,a,l)}catch(t){l(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=>(l(t),Promise.reject(t))})}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={}})),u=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=l();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),h=a(u(),1),p=a(u(),1);function c({model:t,prompt:e,apiToken:r,temperature:i,topP:n,requireJsonResponse:s,serviceTier:o,tools:a}){return p.Flux.fromGeneratorFunction((async function*(){let l=new AbortController,u=await fetch("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+r},method:"POST",signal:l.signal,body:JSON.stringify({model:t,messages:e,stream:!0,temperature:i,top_p:n,response_format:s?{type:"json_object"}:void 0,service_tier:"flex"===o?"flex":"default",tools:a})});if(u.status<200||u.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await u.text());throw Error("OpenAPI reported: "+t)}if(null===u.body)throw Error("illegal state");let h="",c={};yield*p.Flux.fromReadableStream(u.body,(()=>l.abort())).map((t=>f.decode(t,{stream:!0}))).flatMap((t=>t.replaceAll("data: [DONE]","").replace(/^data: /,"").split("data: "))).map((t=>t.replace(/[\n ]*$/,"").trim())).flatMap((t=>{h+=t;try{let t=JSON.parse(h);return h="",[t]}catch{return[]}})).map((t=>t.choices[0])).flatMap((t=>{if(t.delta.tool_calls)for(let e of t.delta.tool_calls)if(e.id&&e.function?.name)c[e.id]={id:e.id,name:e.function.name,arguments:e.function.arguments||""};else if(e.id&&c[e.id])c[e.id].arguments+=e.function?.arguments||"";else if(void 0!==e.index&&e.function?.arguments){let t=Object.values(c)[e.index];t&&(t.arguments+=e.function.arguments)}return"tool_calls"===t.finish_reason?[{type:"toolCalls",toolCalls:Object.values(c)}]:t.delta.content?[{type:"content",content:t.delta.content}]:[]})).filter((t=>null!=t))}))}var f=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(b).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 m(t){return new _([],t)}function w(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?[]:w(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(...w(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 y,_=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.hasProperty(t,(t=>t.canBeString()))}canHaveProperty(t,e){return this.hasProperty(t,e,!0)}hasProperty(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=w(this.value,this.type,"root",t);if(e.length>0)throw new d(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return w(this.value,this.type,"root",e).length>0?t:this.value}describe(){return g(this.type)}};function g(t,e=0){if(Array.isArray(t))return t.map((t=>g(t,e))).join(" | ");switch(t.type){case"array":return g(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${v(e+1)}${r}: ${g(t.props[r].type,e+1)}`)).join(",\n")+`\n${v(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function v(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function b(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as A}from"dotenv";function E(){if(!y){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}();y=m(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return y}var T=class{constructor(t,e,r,i,n=!1){this.type=t,this.source=e,this.value=r,this.fieldName=i,this.maybeIncomplete=n}},U=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 N(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}},N=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 T(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT";let t=new T(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 T(this.currentTokenType,e(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY";let t=new T(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 T(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 T(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 T(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 T(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 T(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 T(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 T(this.currentTokenType,e(this.position),this.currentValue,this.parentFieldName,i)}}throw new S("Invalid JSON at position "+this.position)}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()}},S=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},L=a(u(),1);function x(t){return null!=t}var P=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new R;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 $,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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(x(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.o(this.toAsync(t),void 0)}o(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.o(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.o((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.o(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.o(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.o(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.o(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return L.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.o((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(C))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(R))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new k,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new j,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(k))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 k})),this.state=new V(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>{t(r)})),r.push(t)}default:throw new B(e)}else if(this.isState(j))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 j})),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)}}},O=class{},C=class extends O{constructor(t){super(),this.child=t}},R=class extends O{},j=class extends O{},I=class extends C{constructor(t){super(t)}},k=class extends O{},V=class extends C{constructor(t){super(t)}},B=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},$=class{getExcerpts(t){return[{source:t}]}},M=class extends P{constructor(){super()}},J=a(u(),1),F=class extends P{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=J.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))}},G=class{parse(t){return new F(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 Y(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 H(t){if(void 0===t)throw Error("Value is undefined");return t}var z=[];for(let t=0;t<256;++t)z.push((t+256).toString(16).slice(1));import{randomFillSync as K}from"crypto";var q=new Uint8Array(256),Q=q.length;import{randomUUID as W}from"crypto";var X={randomUUID:W},Z=function(t,e,r){if(X.randomUUID&&!e&&!t)return X.randomUUID();let i=(t=t||{}).random??t.rng?.()??(Q>q.length-16&&(K(q),Q=0),q.slice(Q,Q+=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(z[t[e+0]]+z[t[e+1]]+z[t[e+2]]+z[t[e+3]]+"-"+z[t[e+4]]+z[t[e+5]]+"-"+z[t[e+6]]+z[t[e+7]]+"-"+z[t[e+8]]+z[t[e+9]]+"-"+z[t[e+10]]+z[t[e+11]]+z[t[e+12]]+z[t[e+13]]+z[t[e+14]]+z[t[e+15]]).toLowerCase()}(i)},tt=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 et(t){return new nt([],t)}function rt(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=>rt(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],l=rt(n in t?t[n]:void 0,a.optional?[...a.type,{type:"undefined"}]:a.type,r+"."+n,i);void 0!==l.juggleTo&&o.push({key:n,juggleTo:l.juggleTo.value}),s.push(...l.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 it=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.l=r}},nt=class t extends it{array(e){let r=e(new t([],this.value)),i=new st([{type:"array",elementType:r.type}],this.value);return new st([...this.type,...i.type],this.value)}object(t){let e=t(new ot([{type:"object",props:{}}],this.value));return new st([...this.type,...e.type],this.value)}string(){return new st([...this.type,{type:"string"}],this.value)}number(){return new st([...this.type,{type:"number"}],this.value)}boolean(){return new st([...this.type,{type:"boolean"}],this.value)}constant(t,...e){return new ut([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}null(){return new st([...this.type,{type:"null"}],this.value)}undefined(){return new st([...this.type,{type:"undefined"}],this.value)}any(){return new st([],this.value)}},st=class t extends it{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 ot([{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 ut([...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)}},ot=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 l=r(new lt([],this.value)),u=l.type,h=l.u;return new t([{...a,props:{...a.props,[e]:{optional:s,type:u,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)}},at=class extends it{constructor(t,e,r=[]){super(t,e),this.u=r}withComment(t){return new ut(this.type,this.value,[...this.u,t])}},lt=class extends at{array(t){let e=t(new nt([],this.value)),r=new st([{type:"array",elementType:e.type}],this.value);return new ut([...this.type,...r.type],this.value)}object(t){let e=t(new ot([{type:"object",props:{}}],this.value));return new ut([...this.type,...e.type],this.value)}string(){return new ut([...this.type,{type:"string"}],this.value)}number(){return new ut([...this.type,{type:"number"}],this.value)}boolean(){return new ut([...this.type,{type:"boolean"}],this.value)}constant(...t){return new ut([...this.type,...t.map((t=>({type:"constant",value:t})))],this.value)}null(){return new ut([...this.type,{type:"null"}],this.value)}undefined(){return new ut([...this.type,{type:"undefined"}],this.value)}},ut=class t extends at{orArray(e){let r=e(new st([],this.value)),i=new st([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new ot([{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 ht(t,e,r={}){let{problems:i,juggleTo:n}=rt(t,e.type,"root",r);if(i.length>0)throw new tt(i,r.errorMessage);return void 0!==n?n.value:t}function pt(t){return ct(t.type)}function ct(t,e=0){if(Array.isArray(t))return t.map((t=>ct(t,e))).join(" | ");switch(t.type){case"array":return ct(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=ct(s.type,e+1),a=n<r.length-1?",":"",l=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${ft(e+1)}${i}?: ${o}${a}${l}\n`:`${ft(e+1)}${i}: ${o}${a}${l}\n`})).join("")+ft(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function ft(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 mt(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 wt}from"fs";var yt={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_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_image_1:"gpt-image-1",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"},_t={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},gt=class{config;h;p;constructor(t){this.config=Nt(t)}createConversation(){let t=new vt(this.config);return t.h=this.h,t.p={uuid:Z(),messages:[]},t}get apiKeyChain(){return void 0===this.h&&(this.h=xt(this.config)),this.h}get conversation(){return this.p}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 Rt(this,i,e,Gt(),void 0,void 0,void 0,void 0,!1)}image(t){return new bt(t,void 0,void 0,this)}},vt=class t extends gt{constructor(t){super(t)}copyConversation(){if(void 0===this.p)throw Error("This method only works on copy conversation: no conversation exists");let e=new t(this.config);return e.h=this.h,e.p={uuid:Z(),messages:this.p.messages.map((t=>({...t,messageUuid:Z()})))},e}},bt=class{constructor(t,e,r,i){this.prompt=t,this.m=e,this._=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(x(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.m=t,this}size(t){return this._=t,this}toFile(t){return new At(this.prompt,this.m,this._,t,this.aiClient)}async getResponseAsString(){let t=m(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await mt(t,this.prompt)}},At=class{constructor(t,e,r,i,n){this.prompt=t,this.m=e,this._=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(x(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.m=t,this}size(t){return this._=t,this}async getResponseAsFile(){let t=m(await this.aiClient.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await mt(t,this.prompt,this.m,this._);return new Promise(((t,r)=>{wt(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},Et=new gt({});function Tt(t){let e=Nt(t);Et.config=e,Et.h=xt(e)}function Ut(t){let e=Nt(t);return new gt(e)}function Nt(t){return"string"==typeof t?{promptGridApiKey:St(t),debugMode:!1,attemptsPerCall:1}:{promptGridApiKey:St(t.promptGridApiKey),apiKeys:t.apiKeys,debugMode:t.debugMode??!1,attemptsPerCall:Lt(t.attemptsPerCall)}}function St(t){return ht(t,et(t).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+t})}function Lt(t){let e=ht(t,et(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 xt(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(E()+"/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 Pt=new Map;function Ot(t){let e=t??Et;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 Ct(e,Gt())}var Ct=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new Rt(this.aiClient,t,e,Gt(),void 0,void 0,void 0,void 0,!1)}},Rt=class{constructor(t,e,r,i,n,s,o,a,l){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.v=n,this.A=s,this.T=o,this.m=a,this.U=l;let u=this;this.generator=async function*(){yield*await Mt(u.aiClient,a,u.genericMessages,!1,u.promptName,n,s,o,i,void 0,u.N)}()}generator;promptName;N;name(t){return this.promptName=t,this}model(t){return this.m=t,this}firstThink(t=!0){return this.U=t,this}temperature(t){return this.v=t,this}topP(t){return this.A=t,this}flex(t=!0){return this.T=t?"flex":void 0,this}get result(){return this}get messages(){return this.genericMessages.map((t=>({[t.role]:t.content})))}get json(){return!1}get genericMessages(){let t=this.promptSupplier(this.promptSupplierArgs,Ft),{messages:e,typeSpecIndex:r}=$t(t);if(!this.json)return e;let i={role:"user",content:Jt(0,this.json,this.U)};return void 0!==r?[...e.slice(0,r),i,...e.slice(r)]:[...e,i]}next(...[t]){return this.generator.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(x(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 kt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,Gt(),this.promptName,this.v,this.A,this.T,this.m,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 Vt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,(e=>e.array(t)),this.callingCodeLine,this.promptName,this.v,this.A,this.T,this.m,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.N=e,this}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}};function jt(t){let e=t=>{if(Array.isArray(t))return e(t[0]);switch(t.type){case"object":{let r={},i=[];for(let[n,s]of Object.entries(t.props))r[n]=e(s.type),s.optional||i.push(n);return{type:"object",properties:r,required:i.length>0?i:void 0}}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{const:t.value}}};return e(t.type)}function It(t){return{name:t.name,description:t.description,parameters:t.parameters(et(void 0)),function:t.function}}var kt=class extends M{constructor(t,e,r,i,n,s,o,a,l,u,p){super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.v=o,this.A=a,this.T=l,this.m=u,this.U=p;let c=this,f=async function*(){yield*await Mt(t,u,c.genericMessages,c.json,s,o,a,l,n,i,c.N)}(),d=h.Flux.fromGenerator(f),m=(new U).processDataBuffer(d),w=(new G).parse(m);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)})),this.stringGenerator=async function*(){for await(let t of m)void 0!==t.token?w.push(t):void 0!==t.source&&(yield t.source)}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of c.stringGenerator){t+=e;let r=Y(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;N;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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(x(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.promptName=t,this}model(t){return this.m=t,this}firstThink(t=!0){return this.U=t,this}temperature(t){return this.v=t,this}topP(t){return this.A=t,this}flex(t=!0){return this.T=t?"flex":void 0,this}get result(){return this}get messages(){return this.genericMessages.map((t=>({[t.role]:t.content})))}get genericMessages(){let t=this.promptSupplier(this.promptSupplierArgs,Ft),{messages:e,typeSpecIndex:r}=$t(t);if(!this.json)return e;let i={role:"user",content:Jt(0,this.json,this.U)};return void 0!==r?[...e.slice(0,r),i,...e.slice(r)]:[...e,i]}get json(){return void 0===this.jsonTypeSupplier||this.jsonTypeSupplier(et(void 0))}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=D(t);return void 0!==e?r?.result:r}S;getResponseAsString(){return void 0===this.S&&(this.S=this.L()),this.S}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.N=e,this}async L(){let t="";for await(let e of this.stringGenerator)t+=e;return t}},Vt=class extends kt{arrayElementGenerator;constructor(t,e,r,i,n,s,o,a,l,u,p){super(t,e,r,i,n,s,o,a,l,u,p);let c=this;this.arrayElementGenerator=h.Flux.create((async(t,e)=>{await c.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 x(t)?await t(e):e}catch(t){if(x(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(x(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonArrayPrompt"}};function Bt(t){return t??"gpt-4o"}function $t(t,e){let r=t=>void 0===t||"typeSpec"in t?null:{role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:H(t.user??t.system??t.assistant)};if("string"==typeof t)return{messages:[{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*Mt(t,e,r,i,n,s,o,a="normal",l,u,h){let p=new Map;try{let{fileName:f,lineNumber:d}=l;if(f&&void 0!==d&&Array.from(Pt.keys()).filter((t=>t.startsWith(f+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${f}. Please specify a name using .name() method.`);let w={id:n,callingCodeLine:l},y=t.conversation?.uuid??Z(),_={},g=(e,r)=>{let i=Z(),n=async()=>{if(void 0!==t.conversation)for(let r of e.messages){let e=t.conversation.messages.find((t=>t.messageUuid===r.messageUuid));if(void 0!==e){if(e.role!==r.role)throw Error("Illegal state");e.content=r.content}else t.conversation.messages.push(r)}_.currentSave=_.save,_.save=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(E()+"/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)}}(e,t.apiKeyChain.promptgrid),await new Promise((t=>setTimeout(t,100))),await(_.save?.callback()),_.currentSave=void 0};void 0!==_.save&&p.delete(_.save.uuid),_.save={uuid:i,callback:n},void 0===_.currentSave&&p.set(i,{chunk:r,promise:n().then()})},v=[...t.conversation?.messages??[],...r];g({conversationUuid:y,prompt:w,messages:v.map((t=>({messageUuid:t.messageUuid??Z(),role:t.role,content:t.content||""})))});let b=Z();g({conversationUuid:y,prompt:w,messages:[{messageUuid:b,role:"assistant",content:""}]});let A=!0,T=1;for(;A;)try{let r=m(await t.apiKeyChain.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),n=h?.map((t=>({type:"function",function:{name:t.name,description:t.description,parameters:jt(t.parameters)}}))),l=c({model:Bt(e),prompt:v,apiToken:r,temperature:s,topP:o,requireJsonResponse:!1!==i,serviceTier:a,tools:n}),p="",f=[],d=l.doOnEach((t=>{"content"===t.type?(p+=t.content,g({conversationUuid:y,prompt:w,messages:[{messageUuid:b,role:"assistant",content:p}]},t.content)):"toolCalls"===t.type&&(f=t.toolCalls)}));for await(let t of d)"content"===t.type&&(yield t.content);if(f.length>0&&h){let t=[];for(let e of f){let r=h.find((t=>t.name===e.name));if(r)try{let i=""===e.arguments.trim()?{}:JSON.parse(e.arguments),n=await r.function(i);t.push({tool_call_id:e.id,role:"tool",content:n})}catch(r){t.push({tool_call_id:e.id,role:"tool",content:"Error: "+(r instanceof Error?r.message:r+"")})}else t.push({tool_call_id:e.id,role:"tool",content:`Error: Tool ${e.name} not found`})}let e={messageUuid:b,role:"assistant",content:p||"",tool_calls:f.map((t=>({id:t.id,type:"function",function:{name:t.name,arguments:t.arguments}})))},r=e.tool_calls.map((t=>`${t.function.name}(${t.function.arguments})`)).join("\n");g({conversationUuid:y,prompt:w,messages:[{messageUuid:b,role:"assistant",content:e.content+(e.content?"\n\n":"")+r}]});let i=t.map((t=>{let e=f.find((e=>e.id===t.tool_call_id)).name;return{messageUuid:Z(),role:"user",content:`${e}: ${t.content}`}}));g({conversationUuid:y,prompt:w,messages:i}),v=[...v,e,...t],p="",f=[],b=Z();continue}if(void 0!==u)try{let t=D(p),e=t?.result??t;ht(e,u(et(e)),{juggleBetweenNullAndUndefined:!0}),A=!1}catch(t){try{let t=D(p);ht(t,u(et(t)),{juggleBetweenNullAndUndefined:!0}),A=!1}catch{throw Error("JSON response failed type validation: "+(t instanceof Error?t.message:t+""))}}else A=!1}catch(e){if(T>=t.config.attemptsPerCall)throw e;await new Promise((t=>setTimeout(t,1e3))),console.warn(`AI call failed, retrying (${T}/${t.config.attemptsPerCall})`,e)}finally{T++}}finally{if(t.config.debugMode){let t=Array.from(p.values()).map((t=>t.promise));await Promise.all(t)}}}function Jt(t,e,r){{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"+pt(new nt([],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 ut(t.type,t.value)))})))}}var Ft={typeSpec:!0};function Gt(){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:m(t).canBeString().andNothingElse(),fileName:m(i).canBeString().andNothingElse(),lineNumber:m(parseInt(n)).canBeNumber().andNothingElse(),functionName:m(r).canBeString().canBeUndefined().andNothingElse()}}export{gt as AIClient,vt as AIConversation,yt as AiModel,Rt as BasicPrompt,lt as EmptyPropTypeSpec,nt as EmptyTypeSpec,ut as FullPropTypeSpec,st as FullTypeSpec,At as ImageFilePrompt,bt as ImagePrompt,Vt as JsonArrayPrompt,kt as JsonPrompt,_t as OpenaiImageModel,Ct as PromptBase,at as PropTypeSpec,M as StreamedJsonChildElement,F as StreamedJsonRootElement,ot as TypeMemberSpec,it as TypeSpec,Ft as TypeSpecMarker,Et as ai,It as defineTool,Gt as getCallerFileNameAndLineNumber,Ut as newAIClient,xt as obtainAiClientData,Y as parsePartialJson,Ot as promptAI,Tt as setupAI};
2
2
  //# sourceMappingURL=index.js.map