@ax-llm/ax 14.0.22 → 14.0.23
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/index.cjs +19 -19
- package/index.cjs.map +1 -1
- package/index.d.cts +6 -20
- package/index.d.ts +6 -20
- package/index.global.js +1 -1
- package/index.global.js.map +1 -1
- package/index.js +20 -20
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.d.cts
CHANGED
|
@@ -638,18 +638,18 @@ declare class AxSignatureBuilder<_TInput extends Record<string, any> = {}, _TOut
|
|
|
638
638
|
}
|
|
639
639
|
declare class AxFluentFieldType<TType extends AxFieldType['type'] = AxFieldType['type'], TIsArray extends boolean = false, TOptions extends readonly string[] | undefined = undefined, TIsOptional extends boolean = false, TIsInternal extends boolean = false> implements AxFieldType {
|
|
640
640
|
readonly type: TType;
|
|
641
|
-
readonly isArray
|
|
641
|
+
readonly isArray: TIsArray;
|
|
642
642
|
readonly options?: TOptions;
|
|
643
643
|
readonly description?: string;
|
|
644
|
-
readonly isOptional
|
|
645
|
-
readonly isInternal
|
|
644
|
+
readonly isOptional: TIsOptional;
|
|
645
|
+
readonly isInternal: TIsInternal;
|
|
646
646
|
constructor(fieldType: {
|
|
647
647
|
type: TType;
|
|
648
|
-
isArray
|
|
648
|
+
isArray: TIsArray;
|
|
649
649
|
options?: TOptions;
|
|
650
650
|
description?: string;
|
|
651
|
-
isOptional
|
|
652
|
-
isInternal
|
|
651
|
+
isOptional: TIsOptional;
|
|
652
|
+
isInternal: TIsInternal;
|
|
653
653
|
});
|
|
654
654
|
optional(): AxFluentFieldType<TType, TIsArray, TOptions, true, TIsInternal>;
|
|
655
655
|
array(): AxFluentFieldType<TType, true, TOptions, TIsOptional, TIsInternal>;
|
|
@@ -668,20 +668,6 @@ declare const f: (() => AxSignatureBuilder) & {
|
|
|
668
668
|
file: (desc?: string) => AxFluentFieldType<"file", false, undefined, false, false>;
|
|
669
669
|
url: (desc?: string) => AxFluentFieldType<"url", false, undefined, false, false>;
|
|
670
670
|
code: (language?: string, desc?: string) => AxFluentFieldType<"code", false, undefined, false, false>;
|
|
671
|
-
array: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => AxFluentFieldInfo<T["type"], true, T["options"], T["isOptional"]>;
|
|
672
|
-
optional: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => AxFluentFieldInfo<T["type"], T["isArray"], T["options"], true>;
|
|
673
|
-
internal: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => T & {
|
|
674
|
-
readonly isInternal: true;
|
|
675
|
-
};
|
|
676
|
-
legacyArray: <T extends AxFieldType>(baseType: T) => T & {
|
|
677
|
-
readonly isArray: true;
|
|
678
|
-
};
|
|
679
|
-
legacyOptional: <T extends AxFieldType>(baseType: T) => T & {
|
|
680
|
-
readonly isOptional: true;
|
|
681
|
-
};
|
|
682
|
-
legacyInternal: <T extends AxFieldType>(baseType: T) => T & {
|
|
683
|
-
readonly isInternal: true;
|
|
684
|
-
};
|
|
685
671
|
};
|
|
686
672
|
interface AxField {
|
|
687
673
|
name: string;
|
package/index.d.ts
CHANGED
|
@@ -638,18 +638,18 @@ declare class AxSignatureBuilder<_TInput extends Record<string, any> = {}, _TOut
|
|
|
638
638
|
}
|
|
639
639
|
declare class AxFluentFieldType<TType extends AxFieldType['type'] = AxFieldType['type'], TIsArray extends boolean = false, TOptions extends readonly string[] | undefined = undefined, TIsOptional extends boolean = false, TIsInternal extends boolean = false> implements AxFieldType {
|
|
640
640
|
readonly type: TType;
|
|
641
|
-
readonly isArray
|
|
641
|
+
readonly isArray: TIsArray;
|
|
642
642
|
readonly options?: TOptions;
|
|
643
643
|
readonly description?: string;
|
|
644
|
-
readonly isOptional
|
|
645
|
-
readonly isInternal
|
|
644
|
+
readonly isOptional: TIsOptional;
|
|
645
|
+
readonly isInternal: TIsInternal;
|
|
646
646
|
constructor(fieldType: {
|
|
647
647
|
type: TType;
|
|
648
|
-
isArray
|
|
648
|
+
isArray: TIsArray;
|
|
649
649
|
options?: TOptions;
|
|
650
650
|
description?: string;
|
|
651
|
-
isOptional
|
|
652
|
-
isInternal
|
|
651
|
+
isOptional: TIsOptional;
|
|
652
|
+
isInternal: TIsInternal;
|
|
653
653
|
});
|
|
654
654
|
optional(): AxFluentFieldType<TType, TIsArray, TOptions, true, TIsInternal>;
|
|
655
655
|
array(): AxFluentFieldType<TType, true, TOptions, TIsOptional, TIsInternal>;
|
|
@@ -668,20 +668,6 @@ declare const f: (() => AxSignatureBuilder) & {
|
|
|
668
668
|
file: (desc?: string) => AxFluentFieldType<"file", false, undefined, false, false>;
|
|
669
669
|
url: (desc?: string) => AxFluentFieldType<"url", false, undefined, false, false>;
|
|
670
670
|
code: (language?: string, desc?: string) => AxFluentFieldType<"code", false, undefined, false, false>;
|
|
671
|
-
array: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => AxFluentFieldInfo<T["type"], true, T["options"], T["isOptional"]>;
|
|
672
|
-
optional: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => AxFluentFieldInfo<T["type"], T["isArray"], T["options"], true>;
|
|
673
|
-
internal: <T extends AxFluentFieldInfo<any, any, any, any>>(baseType: T) => T & {
|
|
674
|
-
readonly isInternal: true;
|
|
675
|
-
};
|
|
676
|
-
legacyArray: <T extends AxFieldType>(baseType: T) => T & {
|
|
677
|
-
readonly isArray: true;
|
|
678
|
-
};
|
|
679
|
-
legacyOptional: <T extends AxFieldType>(baseType: T) => T & {
|
|
680
|
-
readonly isOptional: true;
|
|
681
|
-
};
|
|
682
|
-
legacyInternal: <T extends AxFieldType>(baseType: T) => T & {
|
|
683
|
-
readonly isInternal: true;
|
|
684
|
-
};
|
|
685
671
|
};
|
|
686
672
|
interface AxField {
|
|
687
673
|
name: string;
|
package/index.global.js
CHANGED
|
@@ -193,7 +193,7 @@ ${i.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try
|
|
|
193
193
|
`);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let p=uo(i,u);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},dl=(s,e,t=!1)=>{switch(s.type?.name){case"code":return gl(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return al(s,e,t);case"datetime":return ll(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*ml(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[i]??0,p=u===0,d=(t<0?0:t)+u,m=s.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let f=p?g.trimStart():g;r.currField?.type?.name==="code"&&(f=f.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),f.length>0&&(yield{index:o,delta:{[i]:f}},r.streamedIndex[i]=u+g.length)}function*Js(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*ml(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*ml(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(c=>c.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let c=n.streamedIndex?.[i]??0,u=l.slice(c);u&&u.length>0&&(yield{index:r,delta:{[i]:u}},n.streamedIndex[i]=c+u.length);continue}n.streamedIndex[i]||(yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=1)}}function uo(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw za(s)}let t;if(s.type?.name==="json")try{let n=gl(e);return t=JSON.parse(n),t}catch(n){throw ja(s,n.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=ul(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw Ha(s,n.message)}try{if(Array.isArray(t)){for(let[n,r]of t.entries())if(r!==void 0){let o=typeof r=="string"?r.trim():r;t[n]=dl(s,o,!0)}}else t=dl(s,e)}catch(n){throw Ka(s,e,n.message)}if(!(typeof t=="string"&&t===""))return t}var gl=s=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function Ys(s,e,t,n){for(let r of s){if(e[r.field.name]===void 0)continue;let o=r.process,i=await o(e[r.field.name],{sessionId:n,values:e,done:!0});hl(r.field,t,i,n)}}async function Qs(s,e,t,n,r,o,i=!1){for(let a of s){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let c=a.process,u=await c(l,{sessionId:o,values:r,done:i});hl(t.currField,n,u,o)}}var hl=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),o=ru(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function ru(s,e){let t=s.type?.name==="code",n=s.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*fl({res:s,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,i,a=[],l=s.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let p=u;p.modelUsage&&(i=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*ou({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*su({...r,state:c,debug:n});if(i){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());i.citations=c}if(e.push(i),n&&r.logger){let c=structuredClone(i);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),i.citations&&i.citations.length>0&&r.logger({name:"ChatResponseCitations",value:i.citations})}}}async function*ou({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:i,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(s.functionCalls&&s.functionCalls.length>0)Ir(i.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:i.functionCalls,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){if(s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[c]:s.thought}}),i.content+=s.content,e.updateResult({name:s.name,content:i.content,delta:s.content,index:s.index},t),Ws(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await Os(u,i.xstate,i.content),l.length!==0&&await Qs(l,i.content,i.xstate,e,i.values,t),yield*Js(a,i.content,i.values,i.xstate,s.index),await no(p,i.values)}else s.thought&&s.thought.length>0&&(i.values[c]=(i.values[c]??"")+s.thought,yield{index:s.index,delta:{[c]:s.thought}});if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
194
194
|
Content: ${i.content}`)}async function*su({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:h,logger:x,debug:A,stopFunctionNames:T}){let I=h?void 0:Fs(t,s.functionCalls,s.values,n);if(I){if(!r)throw new Error("Functions are not defined");let v=await lo({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...v]),s.functionCalls=[]}else{let v=h!==void 0;if(Vs(e,s.values,s.xstate,s.content,{strictMode:c,treatAllFieldsOptional:v,deferRequiredCheckForStreaming:!0,forceFinalize:!0}),h){let R=await h.processResults(s.values);if(R&&R.length>0){if(!r)throw new Error("Functions are not defined");let O=await lo({ai:t,functionList:r,functionCalls:R,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...O]),o.updateResult({name:void 0,content:s.content,functionCalls:R.map(k=>({id:k.id,type:"function",function:{name:k.name,params:k.args}})),index:s.index},i);return}}await Os(p,s.xstate,s.content,!0),await no(d,s.values),m.length&&await Ys(m,s.values,o,i),g.length!==0&&await Qs(g,s.content,s.xstate,o,s.values,i,!0),yield*Js(e,s.content,s.values,s.xstate,s.index)}}async function*Al({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:h,debug:x,signatureToolCallingManager:A,stopFunctionNames:T,disableMemoryCleanup:I}){let v=e.results??[],R=A!==void 0;t.addResponse(v,n);let O=[];for(let M of v)if(Array.isArray(M?.citations))for(let b of M.citations)b?.url&&O.push({url:b.url,title:b.title,description:b.description,license:b.license,publicationDate:b.publicationDate,snippet:b.snippet});for(let M of v){let b=l[M.index];if(!b)throw new Error(`No state found for result (index: ${M.index})`);if(e.modelUsage){let C=Array.from(new Map(O.filter(S=>S.url).map(S=>[S.url,S])).values()),y={...e.modelUsage,...C.length?{citations:C}:{}};if(c.push(y),x&&h){let S=structuredClone(y);delete S.citations,h({name:"ChatResponseUsage",value:S}),y.citations&&y.citations.length>0&&h({name:"ChatResponseCitations",value:y.citations})}}if(A&&M.content){M.thought&&M.thought.length>0&&(b.values[m]=M.thought),Ks(g,b.values,M.content,{strictMode:a,treatAllFieldsOptional:R});let y=(await A.processResults(b.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));y&&y.length>0&&t.updateResult({name:M.name,content:M.content,functionCalls:y,index:M.index},n)}if(M.functionCalls?.length){let C=Fs(s,M.functionCalls,b.values);if(C&&C.length>0){if(!o)throw new Error("Functions are not defined");let y;try{y=await lo({ai:s,functionList:o,functionCalls:C,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:u,index:M.index,functionResultFormatter:f,logger:h,debug:x,stopFunctionNames:T})}catch(S){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),S}b.functionsExecuted=new Set([...b.functionsExecuted,...y])}}else M.content&&(M.thought&&M.thought.length>0&&(b.values[m]=M.thought),Ks(g,b.values,M.content,{strictMode:a,treatAllFieldsOptional:R}));if(await no(p,b.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Ys(d,b.values,t,n),M.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
195
195
|
Content: ${M.content}`)}let k=l.map(M=>M.values);for(let M of k)for(let b of g.getOutputFields())b.isInternal&&delete M[b.name];let E=g.getOutputFields(),G=k.map((M,b)=>{let C={};for(let y of E)y.isInternal||(C[y.name]=M[y.name]);return M[m]!==void 0&&(C[m]=M[m]),{index:b,delta:C}});for(let M of G)yield M}function xl(s,e,t,n){let r=s.getLast(n);if(!r)return!0;for(let[o,i]of t.entries()){let a=e?Array.from(e).some(p=>i.functionsExecuted.has(p)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",u=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var cn=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var H=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Zs=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new H("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new H("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new H('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new H(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof H)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new H(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new H(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new H(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new H(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new H("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new H("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
|
|
196
|
-
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new H(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof H?r:new H(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new H(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof H?r:new H(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new H(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new H(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),i=this.match("[]");n={name:o,isArray:i}}catch(o){throw o instanceof H?o:new H(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new H(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new H(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new H(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new H(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new H(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(i==="audio")throw new H(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(i){throw i instanceof H?i:new H(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(ce.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new H(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new H(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new H(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new H(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${o}${i}`;throw new H(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new H("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new H(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new H(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(o,Math.min(this.position,o+20));throw new H(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new H(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function yl(s){return new Zs(s).parse()}var Qn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new he(e)}},Ie=class s{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new s({...this,isOptional:!0})}array(){return new s({...this,isArray:!0})}internal(){return new s({...this,isInternal:!0})}},un=Object.assign(()=>new Qn,{string:s=>new Ie({type:"string",isArray:!1,description:s}),number:s=>new Ie({type:"number",isArray:!1,description:s}),boolean:s=>new Ie({type:"boolean",isArray:!1,description:s}),json:s=>new Ie({type:"json",isArray:!1,description:s}),datetime:s=>new Ie({type:"datetime",isArray:!1,description:s}),date:s=>new Ie({type:"date",isArray:!1,description:s}),class:(s,e)=>new Ie({type:"class",isArray:!1,options:s,description:e}),image:s=>new Ie({type:"image",isArray:!1,description:s}),audio:s=>new Ie({type:"audio",isArray:!1,description:s}),file:s=>new Ie({type:"file",isArray:!1,description:s}),url:s=>new Ie({type:"url",isArray:!1,description:s}),code:(s,e)=>new Ie({type:"code",isArray:!1,description:e||s}),array:s=>({...s,isArray:!0}),optional:s=>({...s,isOptional:!0}),internal:s=>({...s,isInternal:!0}),legacyArray:s=>({...s,isArray:!0}),legacyOptional:s=>({...s,isOptional:!0}),legacyInternal:s=>({...s,isInternal:!0})});function po(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var N=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},he=class s{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=yl(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new N(`Invalid Signature: ${n.message}`,void 0,r)}throw new N(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new N("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new N("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof N?t:new N(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new N("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new s(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new N("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new N("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new N("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);nt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new N(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new N(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);nt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new N(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new N(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new N("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return nt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new N("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return nt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new s(this);return n.addInputField({name:e,...po(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...po(t)},o=n.parseField(r);nt(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new N(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===o.name)throw new N(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new s(this);return n.addOutputField({name:e,...po(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...po(t)},o=n.parseField(r);nt(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new N(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===o.name)throw new N(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.sigHash=dr("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Il(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof N?e:new N(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=dr("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Il(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof N?e:new N(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new N(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new N(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new N(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new N("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new N("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function bl(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function Il(s,e,t){let n=s?`"${s}" `:"",r=e.map(bl).join(", "),o=t.map(bl).join(", ");return`${n}${r} -> ${o}`}function iu(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function nt(s,e){if(!s.name||s.name.length===0)throw new N("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!iu(s.name))throw new N(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(ce.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new N(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new N(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new N(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&au(s,e)}function au(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new N(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new N("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new N("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new N("Empty class option found",s.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new N(`Invalid class option "${o}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new N("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new N("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new N("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var xt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new he(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new cn,this.key={id:this.signature.hash()}}getSignature(){return new he(this.signature)}setSignature(e){this.signature=new he(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of o){let c=i[l.name];c!==void 0&&(co(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return Yn(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var lu=`
|
|
196
|
+
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new H(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof H?r:new H(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new H(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof H?r:new H(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new H(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new H(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),i=this.match("[]");n={name:o,isArray:i}}catch(o){throw o instanceof H?o:new H(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new H(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new H(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new H(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new H(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new H(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(i==="audio")throw new H(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(i){throw i instanceof H?i:new H(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(ce.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new H(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new H(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new H(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new H(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${o}${i}`;throw new H(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new H("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new H(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new H(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(o,Math.min(this.position,o+20));throw new H(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new H(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function yl(s){return new Zs(s).parse()}var Qn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new he(e)}},Ie=class s{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new s({...this,isOptional:!0})}array(){return new s({...this,isArray:!0})}internal(){return new s({...this,isInternal:!0})}},un=Object.assign(()=>new Qn,{string:s=>new Ie({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new Ie({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new Ie({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new Ie({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new Ie({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new Ie({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new Ie({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new Ie({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new Ie({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new Ie({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new Ie({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),code:(s,e)=>new Ie({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1})});function po(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var N=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},he=class s{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=yl(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new N(`Invalid Signature: ${n.message}`,void 0,r)}throw new N(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new N("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new N("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof N?t:new N(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new N("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new s(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new N("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new N("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new N("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);nt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new N(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new N(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);nt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new N(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new N(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new N("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return nt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new N("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return nt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof N?t:new N(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new s(this);return n.addInputField({name:e,...po(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...po(t)},o=n.parseField(r);nt(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new N(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===o.name)throw new N(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new s(this);return n.addOutputField({name:e,...po(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...po(t)},o=n.parseField(r);nt(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new N(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===o.name)throw new N(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.sigHash=dr("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Il(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof N?e:new N(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=dr("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Il(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof N?e:new N(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new N(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new N(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new N(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new N("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new N("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function bl(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function Il(s,e,t){let n=s?`"${s}" `:"",r=e.map(bl).join(", "),o=t.map(bl).join(", ");return`${n}${r} -> ${o}`}function iu(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function nt(s,e){if(!s.name||s.name.length===0)throw new N("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!iu(s.name))throw new N(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(ce.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new N(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new N(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new N(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&au(s,e)}function au(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new N(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new N("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new N("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new N("Empty class option found",s.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new N(`Invalid class option "${o}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new N("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new N("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new N("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var xt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new he(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new cn,this.key={id:this.signature.hash()}}getSignature(){return new he(this.signature)}setSignature(e){this.signature=new he(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of o){let c=i[l.name];c!==void 0&&(co(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return Yn(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var lu=`
|
|
197
197
|
## Function Call Instructions
|
|
198
198
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
199
199
|
- Output fields should only be generated after all functions have been called.
|