@fifthrevision/axle 0.5.0 → 0.6.3
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/dist/cli.js +3 -3
- package/dist/consoleWriter-Cx-CPHU8.js +33 -0
- package/dist/index.d.ts +390 -90
- package/dist/index.js +2 -2
- package/package.json +25 -22
- package/dist/consoleWriter-CtNNCSna.js +0 -38
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var D=Object.defineProperty;var u=(i,e)=>D(i,"name",{value:e,configurable:!0});import{Command as L}from"@commander-js/extra-typings";import{
|
|
3
|
-
`);this.pendingWrites.push(e);try{await e,this.initialized=!0}finally{const t=this.pendingWrites.indexOf(e);t!==-1&&this.pendingWrites.splice(t,1)}}async writeToLog(e){const{time:t,level:a,payload:l}=e;this.initialized||await this.initialize();const
|
|
4
|
-
`,c=R(this.filename,g).catch(r=>{console.error(`Failed to write to log file: ${r}`)});this.pendingWrites.push(c);try{await c}finally{const r=this.pendingWrites.indexOf(c);r!==-1&&this.pendingWrites.splice(r,1)}}async handleEvent(e){await this.writeToLog(e)}async flush(){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites)}}const f=new L().name("axle").description("Axle is a CLI tool for running AI workflows").version($.version).option("--dry-run","Run the application without executing against the AI providers").option("-c, --config <path>","Path to the config file").option("-j, --job <path>","Path to the job file").option("--no-log","Do not write the output to a log file").option("--no-warn-unused","Do not warn about unused variables").option("--no-inline","Do not inline the console output").option("-d, --debug","Print additional debug information").option("--truncate <num>","Truncate printed strings to a certain number of characters, 0 to disable",parseInt,100).option("--args <args...>","Additional arguments in the form key=value");f.parse(process.argv);const s=f.opts(),m={};s.args&&s.args.forEach(i=>{const[e,t]=i.split("=");e&&t&&(m[e.trim()]=t.trim())}),process.on("uncaughtException",async i=>{console.error("Uncaught exception:"),console.error(i),
|
|
2
|
+
var D=Object.defineProperty;var u=(i,e)=>D(i,"name",{value:e,configurable:!0});import{Command as L}from"@commander-js/extra-typings";import{t as y,u as k,L as v,R as x,C as O,g as E,v as T,d as F}from"./consoleWriter-Cx-CPHU8.js";import w from"yaml";import{access as C,mkdir as I,writeFile as W,appendFile as R}from"node:fs/promises";import{homedir as S}from"node:os";import"@anthropic-ai/sdk";import"zod";import"@google/genai";import"openai";import"serialize-error";import"fs/promises";import"glob";import"node:path";import"chalk";import"node:readline";var _="0.6.3",$={version:_};function J(i,e){if(typeof i!="object"||i===null)return e&&(e.value="Config: must be a non-null object"),!1;if("openai"in i){const t=i.openai;if(typeof t!="object"||t===null)return e&&(e.value="Config: openai must be an object"),!1;if(typeof t["api-key"]!="string")return e&&(e.value="Config: openai.api-key must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Config: openai.model must be a string"),!1}if("anthropic"in i){const t=i.anthropic;if(typeof t!="object"||t===null)return e&&(e.value="Config: anthropic must be an object"),!1;if(typeof t["api-key"]!="string")return e&&(e.value="Config: anthropic.api-key must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Config: anthropic.model must be a string"),!1}if("ollama"in i){const t=i.ollama;if(typeof t!="object"||t===null)return e&&(e.value="Config: ollama must be an object"),!1;if("url"in t&&typeof t.url!="string")return e&&(e.value="Config: ollama.url must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Config: ollama.model must be a string"),!1}if("gemini"in i){const t=i.gemini;if(typeof t!="object"||t===null)return e&&(e.value="Config: gemini must be an object"),!1;if(typeof t["api-key"]!="string")return e&&(e.value="Config: gemini.api-key must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Config: gemini.model must be a string"),!1}if("brave"in i){const t=i.brave;if(typeof t!="object"||t===null)return e&&(e.value="Config: brave must be an object"),!1;if(typeof t["api-key"]!="string")return e&&(e.value="Config: brave.api-key must be a string"),!1;if("rateLimit"in t&&typeof t.rateLimit!="number")return e&&(e.value="Config: brave.rateLimit must be a number"),!1}return!0}u(J,"isServiceConfig");const N="ax.job",P=["yaml","yml","json"];async function U(i,e){const{recorder:t}=e,{content:a,format:l}=await y(i,{defaults:{name:N,formats:P},tag:"Job File"});let o=null;if(l==="json")o=JSON.parse(a);else if(l==="yaml"||l==="yml")o=w.parse(a);else throw new Error("Invalid job file format");t?.debug?.heading.log("The Job Object"),t?.debug?.log(o);const g={value:""};if(k(o,g))return o;throw new Error(`The job file is not valid: ${g.value}`)}u(U,"getJobConfig");const z="ax.config",M=["yaml","yml","json"];async function G(i,e){const{recorder:t}=e,{content:a,format:l}=await y(i,{defaults:{name:z,formats:M},tag:"Config File"});let o=null;if(l==="json")o=JSON.parse(a);else if(l==="yaml"||l==="yml")o=w.parse(a);else throw new Error("Invalid config file format");t?.debug?.heading.log("The Config Object"),t?.debug?.log(o);const g={value:""};if(J(o,g))return o;throw new Error(g.value)}u(G,"getServiceConfig");const p="./logs/",B="~/.axle/logs/";class H{static{u(this,"LogWriter")}time;initialized=!1;logDir=p;pendingWrites=[];constructor(){this.time=new Date().toISOString()}get filename(){return`${this.logDir}${this.time}.log`}async initialize(){try{await C(p),this.logDir=p}catch{const a=B.replace("~",S());try{await C(a),this.logDir=a}catch{await I(a,{recursive:!0}),this.logDir=a}}const e=W(this.filename,`AXLE: New run at ${this.time}
|
|
3
|
+
`);this.pendingWrites.push(e);try{await e,this.initialized=!0}finally{const t=this.pendingWrites.indexOf(e);t!==-1&&this.pendingWrites.splice(t,1)}}async writeToLog(e){const{time:t,level:a,payload:l}=e;this.initialized||await this.initialize();const o=l.map(r=>typeof r=="string"?r:JSON.stringify(r)),g=`${v[a]} ${new Date(t).toISOString()} > ${o.join(" >> ")}
|
|
4
|
+
`,c=R(this.filename,g).catch(r=>{console.error(`Failed to write to log file: ${r}`)});this.pendingWrites.push(c);try{await c}finally{const r=this.pendingWrites.indexOf(c);r!==-1&&this.pendingWrites.splice(r,1)}}async handleEvent(e){await this.writeToLog(e)}async flush(){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites)}}const f=new L().name("axle").description("Axle is a CLI tool for running AI workflows").version($.version).option("--dry-run","Run the application without executing against the AI providers").option("-c, --config <path>","Path to the config file").option("-j, --job <path>","Path to the job file").option("--no-log","Do not write the output to a log file").option("--no-warn-unused","Do not warn about unused variables").option("--no-inline","Do not inline the console output").option("-d, --debug","Print additional debug information").option("--truncate <num>","Truncate printed strings to a certain number of characters, 0 to disable",parseInt,100).option("--args <args...>","Additional arguments in the form key=value");f.parse(process.argv);const s=f.opts(),m={};s.args&&s.args.forEach(i=>{const[e,t]=i.split("=");e&&t&&(m[e.trim()]=t.trim())}),process.on("uncaughtException",async i=>{console.error("Uncaught exception:"),console.error(i),n&&(n.error?.log("Uncaught exception:"),n.error?.log(i.message),n.error?.log(i.stack||""),await n.shutdown()),process.exit(1)});const n=new x;s.debug&&(n.level=v.Debug);const X=new O(s);if(n.subscribe(X),s.log){const i=new H;await i.initialize(),n.subscribe(i)}s.debug&&(n.debug?.heading.log("Options"),n.debug?.log(s),n.debug?.heading.log("Additional Arguments:"),n.debug?.log(m));let d,b;try{d=await G(s.config??null,{recorder:n}),b=await U(s.job??null,{recorder:n})}catch(i){n.error.log(i.message),n.debug?.log(i.stack),await n.shutdown(),f.outputHelp(),process.exit(1)}let j;try{const{engine:i,...e}=b.using,t={...d[i],...e};j=E(i,t)}catch(i){n.error.log(i.message),n.error.log(i.stack),await n.shutdown(),f.outputHelp(),process.exit(1)}T().setConfig(d),n.info?.heading.log("All systems operational. Running job...");const K=Date.now();s.dryRun&&n.info?.log("Dry run mode enabled. No API calls will be made.");const h={in:0,out:0},A=await F(b.jobs).execute({provider:j,variables:m,options:s,stats:h,recorder:n});A&&(n.info?.heading.log("Response"),n.info.log(A)),n.info?.heading.log("Usage"),n.info?.log(`Total run time: ${Date.now()-K}ms`),n.info?.log(`Input tokens: ${h.in} `),n.info?.log(`Output tokens: ${h.out} `),n.info?.heading.log("Complete. Goodbye"),await n.shutdown();
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
var ze=Object.defineProperty;var l=(t,e)=>ze(t,"name",{value:e,configurable:!0});import Xe from"@anthropic-ai/sdk";import*as I from"zod";import F,{z as q}from"zod";import{FinishReason as O,GoogleGenAI as Ze}from"@google/genai";import Ye from"openai";import{serializeError as Qe}from"serialize-error";import{readFile as Ve,access as et,constants as tt}from"fs/promises";import{glob as ue}from"glob";import{readFile as U,access as le,stat as nt,writeFile as st,mkdir as rt}from"node:fs/promises";import{resolve as te,extname as fe,dirname as ot}from"node:path";import T from"chalk";import pe from"node:readline";class A extends Error{static{l(this,"AxleError")}code;id;details;constructor(e,n){super(e,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||"AXLE_ERROR",this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,A.prototype)}}function it(t){const{text:e,files:n}=t,s=[];if(e&&s.push({type:"text",text:e}),n)for(const r of n)s.push({type:"file",file:r});return s}l(it,"toContentParts");function G(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
+
|
|
3
|
+
`)}l(G,"getTextContent");function at(t){return t.filter(e=>e.type==="tool-call")}l(at,"getToolCalls");var y=(t=>(t[t.Stop=0]="Stop",t[t.Length=1]="Length",t[t.FunctionCall=2]="FunctionCall",t[t.Error=3]="Error",t[t.Custom=4]="Custom",t))(y||{});function W(t){if(t==null)return{type:"error",error:{type:"Undetermined",message:"Unknown error occurred"},usage:{in:0,out:0},raw:t};if(t instanceof Error)return{type:"error",error:{type:t.name||"Error",message:t.message||"Unexpected error"},usage:{in:0,out:0},raw:t};if(typeof t=="object"){const e=t,n=e?.error?.error?.type||e?.error?.type||e?.type||e?.code||e?.status||"Undetermined",s=e?.error?.error?.message||e?.error?.message||e?.message||e?.error||"Unexpected error";return{type:"error",error:{type:String(n),message:String(s)},usage:{in:0,out:0},raw:t}}return{type:"error",error:{type:"Undetermined",message:String(t)},usage:{in:0,out:0},raw:t}}l(W,"getUndefinedError");function de(t){return t.map(e=>{if(e.role==="assistant"){const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="thinking"?s.redacted?n.push({type:"redacted_thinking",data:s.text}):n.push({type:"thinking",thinking:s.text,signature:s.signature}):s.type==="tool-call"&&n.push({type:"tool_use",id:s.id,name:s.name,input:s.parameters});return{role:"assistant",content:n}}if(e.role==="tool")return{role:"user",content:e.content.map(n=>({type:"tool_result",tool_use_id:n.id,content:n.content}))};if(typeof e.content=="string")return{role:"user",content:e.content};{const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="file"&&(s.file.type==="image"?n.push({type:"image",source:{type:"base64",media_type:s.file.mimeType,data:s.file.base64}}):s.file.type==="document"&&s.file.mimeType==="application/pdf"&&n.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:s.file.base64}}));return{role:"user",content:n}}})}l(de,"convertToProviderMessages");function _e(t){return t.map(e=>{const n=F.toJSONSchema(e.schema);if(!ct(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}l(_e,"convertToProviderTools");function ge(t){const e=[];for(const n of t)if(n.type==="text")e.push({type:"text",text:n.text});else if(n.type==="thinking")e.push({type:"thinking",text:n.text||"",redacted:!1});else if(n.type==="redacted_thinking")e.push({type:"thinking",text:n.text||"",redacted:!0});else if(n.type==="tool_use"){if(typeof n.input!="object"||n.input===null||Array.isArray(n.input))throw new Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);e.push({type:"tool-call",id:n.id,name:n.name,parameters:n.input})}return e}l(ge,"convertToAxleContentParts");function ne(t){switch(t){case"max_tokens":return y.Length;case"end_turn":return y.Stop;case"stop_sequence":return y.Stop;case"tool_use":return y.FunctionCall;case"pause_turn":case"refusal":default:return y.Error}}l(ne,"convertStopReason$2");function ct(t){return t&&typeof t=="object"&&t.type==="object"}l(ct,"isObjectSchema");async function ut(t){const{client:e,model:n,messages:s,system:r,tools:o,context:i,options:c}=t,{recorder:u}=i,a=c?{...c}:{};a.stop&&(a.stop_sequences=Array.isArray(a.stop)?a.stop:[a.stop],delete a.stop);const p={model:n,max_tokens:4096,messages:de(s),...r&&{system:r},...o&&{tools:_e(o)},...a};u?.debug?.log(p);let d;try{const f=await e.messages.create(p);d=lt(f)}catch(f){d=W(f)}return u?.debug?.log(d),d}l(ut,"createGenerationRequest$2");function lt(t){const e=ne(t.stop_reason);if(e===y.Error)return{type:"error",error:{type:"Uncaught error",message:`Stop reason is not recognized or unhandled: ${t.stop_reason}`},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t};if(e===y.FunctionCall){const n=ge(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:y.FunctionCall,content:n,text:G(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=ge(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:G(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}l(lt,"convertToAIResponse");function ft(){const t=new Map;function e(n){const s=[];switch(n.type){case"message_start":s.push({type:"start",id:n.message.id,data:{model:n.message.model,timestamp:Date.now()}});break;case"message_delta":n.delta.stop_reason&&s.push({type:"complete",data:{finishReason:ne(n.delta.stop_reason),usage:n.usage?{in:n.usage.input_tokens||0,out:n.usage.output_tokens||0}:void 0}});case"message_stop":break;case"content_block_start":if(n.content_block.type==="text")n.index;else if(n.content_block.type==="tool_use"){const o=n.content_block;t.set(n.index,{id:o.id,name:o.name,argumentsBuffer:""}),s.push({type:"tool-call-start",data:{index:n.index,id:o.id,name:o.name}})}else n.content_block.type==="thinking"?s.push({type:"thinking-start",data:{index:n.index,redacted:!1}}):n.content_block.type==="redacted_thinking"?s.push({type:"thinking-start",data:{index:n.index,redacted:!0}}):n.content_block.type==="server_tool_use"||n.content_block.type;break;case"content_block_delta":if(n.delta.type==="text_delta")s.push({type:"text",data:{text:n.delta.text,index:n.index}});else if(n.delta.type==="input_json_delta"){const o=t.get(n.index);o&&(o.argumentsBuffer+=n.delta.partial_json)}else n.delta.type==="thinking_delta"?s.push({type:"thinking-delta",data:{text:n.delta.thinking,index:n.index}}):n.delta.type==="signature_delta"||n.delta.type;break;case"content_block_stop":const r=t.get(n.index);if(r){try{const o=JSON.parse(r.argumentsBuffer);s.push({type:"tool-call-complete",data:{index:n.index,id:r.id,name:r.name,arguments:o}})}catch(o){throw new Error(`Failed to parse tool call arguments for ${r.name}: ${o instanceof Error?o.message:String(o)}`)}t.delete(n.index)}break;default:console.warn("Unknown Anthropic stream event type")}return s}return l(e,"handleEvent"),{handleEvent:e}}l(ft,"createAnthropicStreamingAdapter");async function*pt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i,a=c?{...c}:{};a.stop&&(a.stop_sequences=Array.isArray(a.stop)?a.stop:[a.stop],delete a.stop);const p={model:n,max_tokens:4096,messages:de(s),...r&&{system:r},...o&&{tools:_e(o)},...a};u?.debug?.log(p);const d=ft();try{const f=await e.messages.create({...p,stream:!0});for await(const _ of f){const m=d.handleEvent(_);for(const w of m)yield w}}catch(f){yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}l(pt,"createStreamingRequest$3");const S={CLAUDE_SONNET_4_5_20250929:"claude-sonnet-4-5-20250929",CLAUDE_SONNET_4_5_LATEST:"claude-sonnet-4-5",CLAUDE_HAIKU_4_5:"claude-haiku-4-5",CLAUDE_OPUS_4_1_20250805:"claude-opus-4-1-20250805",CLAUDE_OPUS_4_1_LATEST:"claude-opus-4-1",CLAUDE_OPUS_4_20250514:"claude-opus-4-20250514",CLAUDE_OPUS_4_LATEST:"claude-opus-4-0",CLAUDE_SONNET_4_20250514:"claude-sonnet-4-20250514",CLAUDE_SONNET_4_LATEST:"claude-sonnet-4-0",CLAUDE_3_7_SONNET_20250219:"claude-3-7-sonnet-20250219",CLAUDE_3_7_SONNET_LATEST:"claude-3-7-sonnet-latest",CLAUDE_3_5_SONNET_20241022:"claude-3-5-sonnet-20241022",CLAUDE_3_5_HAIKU_20241022:"claude-3-5-haiku-20241022",CLAUDE_3_5_HAIKU_LATEST:"claude-3-5-haiku-latest",CLAUDE_3_5_SONNET_20240620:"claude-3-5-sonnet-20240620"};S.CLAUDE_SONNET_4_5_20250929,S.CLAUDE_SONNET_4_5_LATEST,S.CLAUDE_HAIKU_4_5,S.CLAUDE_OPUS_4_1_20250805,S.CLAUDE_OPUS_4_1_LATEST,S.CLAUDE_OPUS_4_20250514,S.CLAUDE_OPUS_4_LATEST,S.CLAUDE_SONNET_4_20250514,S.CLAUDE_SONNET_4_LATEST,S.CLAUDE_3_7_SONNET_20250219,S.CLAUDE_3_7_SONNET_LATEST,S.CLAUDE_3_5_SONNET_20241022,S.CLAUDE_3_5_HAIKU_20241022,S.CLAUDE_3_5_HAIKU_LATEST,S.CLAUDE_3_5_SONNET_20240620;const me=S.CLAUDE_HAIKU_4_5,he="anthorpic";class dt{static{l(this,"AnthropicProvider")}name=he;client;model;constructor(e,n){this.model=n??me,this.client=new Xe({apiKey:e})}async createGenerationRequest(e){return await ut({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return pt({client:this.client,model:this.model,messages:n,system:s,tools:r,runtime:o,options:i})}}function ye(t,e,n){const s={};return e&&(s.systemInstruction=e),t&&t.length>0&&(s.tools=t.map(r=>({functionDeclarations:[{name:r.name,description:r.description,parametersJsonSchema:F.toJSONSchema(r.schema)}]}))),n&&Object.assign(s,n),s}l(ye,"prepareConfig");function Ee(t){return t.map(_t).filter(e=>e!==void 0)}l(Ee,"convertAxleMessagesToGemini");function _t(t){switch(t.role){case"tool":return gt(t);case"assistant":return mt(t);case"user":return ht(t)}}l(_t,"convertMessage$3");function gt(t){return{role:"user",parts:t.content.map(e=>({functionResponse:{id:e.id??void 0,name:e.name,response:{output:e.content}}}))}}l(gt,"convertToolMessage$3");function mt(t){const e=[],n=t.content.filter(r=>r.type==="text");if(n.length>0){const r=n.map(o=>o.text).join("");r&&e.push({text:r})}const s=t.content.filter(r=>r.type==="tool-call");return s.length>0&&e.push(...s.map(r=>({functionCall:{id:r.id??void 0,name:r.name,args:r.parameters}}))),{role:"assistant",parts:e}}l(mt,"convertAssistantMessage$3");function ht(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map(yt).filter(n=>n!==null)}}l(ht,"convertUserMessage$3");function yt(t){return t.type==="text"||t.type==="instructions"?{text:t.type==="text"?t.text:t.instructions}:t.type==="file"&&(t.file.type==="image"||t.file.type==="document")?{inlineData:{mimeType:t.file.mimeType,data:t.file.base64}}:null}l(yt,"convertContentPart$3");function Ie(t){switch(t){case O.STOP:return[!0,y.Stop];case O.MAX_TOKENS:return[!0,y.Length];case O.FINISH_REASON_UNSPECIFIED:case O.SAFETY:case O.RECITATION:case O.LANGUAGE:case O.OTHER:case O.BLOCKLIST:case O.PROHIBITED_CONTENT:case O.SPII:case O.MALFORMED_FUNCTION_CALL:case O.IMAGE_SAFETY:return[!1,y.Error]}}l(Ie,"convertStopReason$1");async function Et(t){const{client:e,model:n,messages:s,system:r,tools:o,context:i,options:c}=t,{recorder:u}=i,a=c?{...c}:{};a.max_tokens&&(a.maxOutputTokens=a.max_tokens,delete a.max_tokens),a.stop&&(a.stopSequences=Array.isArray(a.stop)?a.stop:[a.stop],delete a.stop),a.top_p!==void 0&&(a.topP=a.top_p,delete a.top_p);const p={contents:Ee(s),config:ye(o,r,a)};u?.debug?.log(p);let d;try{const f=await e.models.generateContent({model:n,...p});d=It(f,{recorder:u})}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(Et,"createGenerationRequest$1");function It(t,e){const{recorder:n}=e,s=t.usageMetadata.promptTokenCount,r=t.usageMetadata.totalTokenCount-s,o={in:s,out:r};if(!t)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};if(t.promptFeedback&&t.promptFeedback.blockReason)return{type:"error",error:{type:"Blocked",message:`Response blocked by Google AI: ${t.promptFeedback.blockReason}, ${t.promptFeedback.blockReasonMessage}`},usage:o,raw:t};if(!t.candidates||t.candidates.length===0)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};t.candidates.length>1&&n?.warn?.log(`We received ${t.candidates.length} response candidates`);const i=t.candidates[0],u=(i.content?.parts||[]).map(d=>d.text).filter(d=>d!==void 0).join(""),[a,p]=Ie(i.finishReason);if(a){const d=[];if(u&&d.push({type:"text",text:u}),t.functionCalls)for(const f of t.functionCalls){if(typeof f.args!="object"||f.args===null||Array.isArray(f.args))throw new Error(`Invalid tool call arguments for ${f.name}: expected object, got ${typeof f.args}`);d.push({type:"tool-call",id:f.id,name:f.name,parameters:f.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?y.FunctionCall:p,content:d,text:G(d)??"",usage:o,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${p}`},usage:o,raw:t}}l(It,"fromModelResponse$3");function wt(){let t=0,e=-1,n="",s="",r=0,o=0;function i(c){const u=[];n||(n=c.responseId||`gemini-${Date.now()}`,s=c.modelVersion||"gemini",u.push({type:"start",id:n,data:{model:s,timestamp:Date.now()}})),c.usageMetadata&&(r=c.usageMetadata.promptTokenCount||0,o=(c.usageMetadata.totalTokenCount||0)-r);const a=c.candidates?.[0];if(!a)return u;const p=a.content?.parts||[];for(const d of p){const f="thought"in d&&d.thought===!0;if(f&&d.text?(e===-1&&(e=t+1,u.push({type:"thinking-start",data:{index:e}})),u.push({type:"thinking-delta",data:{index:e,text:d.text}})):d.text&&!f&&u.push({type:"text",data:{text:d.text,index:t}}),d.functionCall){t++;const _=`tool-${t}`;u.push({type:"tool-call-start",data:{index:t,id:_,name:d.functionCall.name}}),u.push({type:"tool-call-complete",data:{index:t,id:_,name:d.functionCall.name,arguments:d.functionCall.args}})}}if(a.finishReason){const[d,f]=Ie(a.finishReason);d?u.push({type:"complete",data:{finishReason:f,usage:{in:r,out:o}}}):u.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${a.finishReason}`,usage:{in:r,out:o},raw:c}})}return u}return l(i,"handleChunk"),{handleChunk:i}}l(wt,"createGeminiStreamingAdapter");async function*Tt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i,a=c?{...c}:{};a.max_tokens&&(a.maxOutputTokens=a.max_tokens,delete a.max_tokens),a.stop&&(a.stopSequences=Array.isArray(a.stop)?a.stop:[a.stop],delete a.stop),a.top_p!==void 0&&(a.topP=a.top_p,delete a.top_p);const p={contents:Ee(s),config:ye(o,r,a)};u?.debug?.log(p);const d=wt();try{const f=await e.models.generateContentStream({model:n,...p});for await(const _ of f){const m=d.handleChunk(_);for(const w of m)yield w}}catch(f){u?.error?.log(f),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}l(Tt,"createStreamingRequest$2");const h={GEMINI_2_5_PRO:"gemini-2.5-pro",GEMINI_2_5_FLASH:"gemini-2.5-flash",GEMINI_2_5_FLASH_PREVIEW_05_20:"gemini-2.5-flash-preview-05-20",GEMINI_2_5_FLASH_LITE:"gemini-2.5-flash-lite",GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:"gemini-2.5-flash-lite-preview-06-17",GEMINI_2_5_FLASH_LIVE_PREVIEW:"gemini-live-2.5-flash-preview",GEMINI_2_5_FLASH_PREVIEW_NATIVE_AUDIO_DIALOG:"gemini-2.5-flash-preview-native-audio-dialog",GEMINI_2_5_FLASH_EXP_NATIVE_AUDIO_THINKING_DIALOG:"gemini-2.5-flash-exp-native-audio-thinking-dialog",GEMINI_2_5_FLASH_IMAGE_PREVIEW:"gemini-2.5-flash-image-preview",GEMINI_2_5_FLASH_PREVIEW_TTS:"gemini-2.5-flash-preview-tts",GEMINI_2_5_PRO_PREVIEW_TTS:"gemini-2.5-pro-preview-tts",GEMINI_2_0_FLASH:"gemini-2.0-flash",GEMINI_2_0_FLASH_001:"gemini-2.0-flash-001",GEMINI_2_0_FLASH_EXP:"gemini-2.0-flash-exp",GEMINI_2_0_FLASH_PREVIEW_IMAGE_GENERATION:"gemini-2.0-flash-preview-image-generation",GEMINI_2_0_FLASH_LITE:"gemini-2.0-flash-lite",GEMINI_2_0_FLASH_LITE_001:"gemini-2.0-flash-lite-001",GEMINI_2_0_FLASH_LIVE_001:"gemini-2.0-flash-live-001",GEMINI_1_5_PRO:"gemini-1.5-pro",GEMINI_1_5_PRO_LATEST:"gemini-1.5-pro-latest",GEMINI_1_5_PRO_001:"gemini-1.5-pro-001",GEMINI_1_5_PRO_002:"gemini-1.5-pro-002",GEMINI_1_5_FLASH:"gemini-1.5-flash",GEMINI_1_5_FLASH_LATEST:"gemini-1.5-flash-latest",GEMINI_1_5_FLASH_001:"gemini-1.5-flash-001",GEMINI_1_5_FLASH_002:"gemini-1.5-flash-002",GEMINI_1_5_FLASH_8B:"gemini-1.5-flash-8b",GEMINI_1_5_FLASH_8B_LATEST:"gemini-1.5-flash-8b-latest",GEMINI_1_5_FLASH_8B_001:"gemini-1.5-flash-8b-001",GEMMA_3N_E4B_IT:"gemma-3n-e4b-it",GEMMA_3_1B_IT:"gemma-3-1b-it",GEMMA_3_4B_IT:"gemma-3-4b-it",GEMMA_3_12B_IT:"gemma-3-12b-it",GEMMA_3_27B_IT:"gemma-3-27b-it",LEARNLM_2_0_FLASH_EXPERIMENTAL:"learnlm-2.0-flash-experimental",EMBEDDING_001:"embedding-001",TEXT_EMBEDDING_004:"text-embedding-004"};h.GEMINI_2_5_PRO,h.GEMINI_2_5_FLASH,h.GEMINI_2_5_FLASH_PREVIEW_05_20,h.GEMINI_2_5_FLASH_LITE,h.GEMINI_2_5_FLASH_LITE_PREVIEW_06_17,h.GEMINI_2_5_FLASH_LIVE_PREVIEW,h.GEMINI_2_5_FLASH_PREVIEW_NATIVE_AUDIO_DIALOG,h.GEMINI_2_5_FLASH_EXP_NATIVE_AUDIO_THINKING_DIALOG,h.GEMINI_2_5_FLASH_IMAGE_PREVIEW,h.GEMINI_2_0_FLASH,h.GEMINI_2_0_FLASH_001,h.GEMINI_2_0_FLASH_EXP,h.GEMINI_2_0_FLASH_PREVIEW_IMAGE_GENERATION,h.GEMINI_2_0_FLASH_LITE,h.GEMINI_2_0_FLASH_LITE_001,h.GEMINI_2_0_FLASH_LIVE_001,h.GEMINI_1_5_PRO,h.GEMINI_1_5_PRO_LATEST,h.GEMINI_1_5_PRO_001,h.GEMINI_1_5_PRO_002,h.GEMINI_1_5_FLASH,h.GEMINI_1_5_FLASH_LATEST,h.GEMINI_1_5_FLASH_001,h.GEMINI_1_5_FLASH_002,h.GEMINI_1_5_FLASH_8B,h.GEMINI_1_5_FLASH_8B_LATEST,h.GEMINI_1_5_FLASH_8B_001,h.GEMMA_3N_E4B_IT,h.GEMMA_3_1B_IT,h.GEMMA_3_4B_IT,h.GEMMA_3_12B_IT,h.GEMMA_3_27B_IT,h.LEARNLM_2_0_FLASH_EXPERIMENTAL;const we=h.GEMINI_2_5_FLASH,Te="Gemini";class xt{static{l(this,"GeminiProvider")}name=Te;client;model;constructor(e,n){this.model=n??we,this.client=new Ze({apiKey:e})}async createGenerationRequest(e){return await Et({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return Tt({client:this.client,model:this.model,messages:n,system:s,tools:r,runtime:o,options:i})}}function xe(t){return t.map(At).flat(1)}l(xe,"convertAxleMessagesToOllama");function Ae(t){return t&&t.length>0?t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:F.toJSONSchema(e.schema)}})):void 0}l(Ae,"convertToolDefToOllama");function At(t){switch(t.role){case"tool":return St(t);case"assistant":return kt(t);default:return Rt(t)}}l(At,"convertMessage$2");function St(t){return t.content.map(e=>({role:"tool",tool_call_id:e.id,content:e.content}))}l(St,"convertToolMessage$2");function kt(t){const e=t.content.filter(r=>r.type==="tool-call"),n=t.content.filter(r=>r.type==="text"),s=e.length>0?e.map(r=>({type:"function",id:r.id,function:{name:r.name,arguments:r.parameters}})):void 0;return{role:t.role,content:n.map(r=>r.text).join(""),...s&&{toolCalls:s}}}l(kt,"convertAssistantMessage$2");function Rt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=[],n=[];for(const s of t.content){const r=Pt(s);r.text!==null&&e.push(r.text),r.image!==null&&n.push(r.image)}return{role:t.role,content:e.join(""),...n.length>0&&{images:n}}}}l(Rt,"convertUserMessage$2");function Pt(t){return t.type==="text"||t.type==="instructions"?{text:t.type==="text"?t.text:t.instructions,image:null}:t.type==="file"&&t.file.type==="image"?{text:null,image:t.file.base64}:{text:null,image:null}}l(Pt,"convertContentPart$2");async function Ot(t){const{url:e,model:n,messages:s,system:r,tools:o,context:i,options:c}=t,{recorder:u}=i,a=Ae(o),p=c?{...c}:{temperature:.7};p.max_tokens&&(p.num_predict=p.max_tokens,delete p.max_tokens);const d={model:n,messages:xe(s),stream:!1,options:p,...r&&{system:r},...a&&{tools:a}};u?.debug?.log(d);let f;try{const _=await fetch(`${e}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!_.ok)throw new Error(`HTTP error! status: ${_.status}`);const m=await _.json();f=bt(m)}catch(_){u?.error?.log("Error fetching Ollama response:",_),f=W(_)}return u?.debug?.log(f),f}l(Ot,"createGenerationRequest");function bt(t){if(t.done_reason==="stop"&&t.message){const e=[];if(t.message.content!==void 0&&e.push({type:"text",text:t.message.content}),t.message.tool_calls)for(const s of t.message.tool_calls){if(typeof s.function.arguments!="object"||s.function.arguments===null||Array.isArray(s.function.arguments))throw new Error(`Invalid tool call arguments for ${s.function.name}: expected object, got ${typeof s.function.arguments}`);e.push({type:"tool-call",id:s.id,name:s.function.name,parameters:s.function.arguments})}const n=e.some(s=>s.type==="tool-call");return{type:"success",id:`ollama-${Date.now()}`,model:t.model,role:"assistant",finishReason:n?y.FunctionCall:y.Stop,content:e,text:G(e)??"",usage:{in:t.prompt_eval_count||0,out:t.eval_count||0},raw:t}}return{type:"error",error:{type:"OllamaError",message:"Unexpected error from Ollama"},usage:{in:0,out:0},raw:t}}l(bt,"fromModelResponse$2");function vt(){let t="",e=0,n=-1,s=0;function r(o){const i=[];if(t||(t=`ollama-${Date.now()}`,i.push({type:"start",id:t,data:{model:o.model,timestamp:Date.now()}})),o.message?.thinking&&(n===-1&&(n=e+1,i.push({type:"thinking-start",data:{index:n}})),i.push({type:"thinking-delta",data:{index:n,text:o.message.thinking}})),o.message?.content&&i.push({type:"text",data:{text:o.message.content,index:e}}),o.message?.tool_calls)for(const c of o.message.tool_calls){s++;const u=c.id||`tool-${s}`;if(typeof c.function.arguments!="object"||c.function.arguments===null||Array.isArray(c.function.arguments))throw new Error(`Invalid tool call arguments for ${c.function.name}: expected object, got ${typeof c.function.arguments}`);i.push({type:"tool-call-start",data:{index:s,id:u,name:c.function.name}}),i.push({type:"tool-call-complete",data:{index:s,id:u,name:c.function.name,arguments:c.function.arguments}})}if(o.done){const c=Nt(o.done_reason);i.push({type:"complete",data:{finishReason:c,usage:{in:o.prompt_eval_count||0,out:o.eval_count||0}}})}return i}return l(r,"handleChunk"),{handleChunk:r}}l(vt,"createOllamaStreamingAdapter");function Nt(t){switch(t){case"stop":return y.Stop;case"length":return y.Length;default:return y.Stop}}l(Nt,"convertStopReason");async function*$t(t){const{url:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i,a=Ae(o),p=c?{...c}:{temperature:.7};p.max_tokens&&(p.num_predict=p.max_tokens,delete p.max_tokens);const d={model:n,messages:xe(s),stream:!0,options:p,...r&&{system:r},...a&&{tools:a}};u?.debug?.log(d);const f=vt();try{const _=await fetch(`${e}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!_.ok)throw new Error(`HTTP error! status: ${_.status}`);if(!_.body)throw new Error("Response body is null");const m=_.body.getReader(),w=new TextDecoder;let k="";for(;;){const{done:P,value:M}=await m.read();if(P)break;k+=w.decode(M,{stream:!0});const v=k.split(`
|
|
4
|
+
`);k=v.pop()||"";for(const $ of v)if($.trim())try{const R=JSON.parse($),D=f.handleChunk(R);for(const N of D)yield N}catch(R){u?.error?.log("Error parsing Ollama stream chunk:",R,$)}}}catch(_){u?.error?.log("Error in Ollama streaming request:",_),yield{type:"error",data:{type:"STREAMING_ERROR",message:_ instanceof Error?_.message:String(_),raw:_}}}}l($t,"createStreamingRequest$1");const Se="http://localhost:11434",Mt="Ollama";class Gt{static{l(this,"OllamaProvider")}name="Ollama";url;model;recorder;constructor(e,n){this.url=n||Se,this.model=e}async createGenerationRequest(e){return await Ot({url:this.url,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return $t({url:this.url,model:this.model,messages:n,system:s,tools:r,runtime:o,options:i})}}function ke(t){if(t&&t.length>0)return t.map(e=>{const n=F.toJSONSchema(e.schema);return{type:"function",function:{name:e.name,description:e.description,parameters:n}}})}l(ke,"toModelTools");function Re(t,e){const n=t.map(Ct).flat(1);return e?[{role:"system",content:e},...n]:n}l(Re,"convertAxleMessagesToChatCompletion");function Ct(t){switch(t.role){case"tool":return Lt(t);case"assistant":return Dt(t);default:return Ft(t)}}l(Ct,"convertMessage$1");function Lt(t){return t.content.map(e=>({role:"tool",tool_call_id:e.id,content:e.content}))}l(Lt,"convertToolMessage$1");function Dt(t){const e=t.content.filter(r=>r.type==="tool-call"),n=t.content.filter(r=>r.type==="text"),s=e.length>0?e.map(r=>({type:"function",id:r.id,function:{name:r.name,arguments:JSON.stringify(r.parameters)}})):void 0;return{role:t.role,content:n.map(r=>r.text).join(""),...s&&{tool_calls:s}}}l(Dt,"convertAssistantMessage$1");function Ft(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(Ut).filter(n=>n!==null);return{role:t.role,content:e}}}l(Ft,"convertUserMessage$1");function Ut(t){if(t.type==="text"||t.type==="instructions")return{type:"text",text:t.type==="text"?t.text:t.instructions};if(t.type==="file"){if(t.file.type==="image")return{type:"image_url",image_url:{url:`data:${t.file.mimeType};base64,${t.file.base64}`}};if(t.file.type==="document")return{type:"file",file:{filename:t.file.name,file_data:`data:${t.file.mimeType};base64,${t.file.base64}`}}}return null}l(Ut,"convertContentPart$1");async function Wt(t){const{client:e,model:n,messages:s,system:r,tools:o,context:i,options:c}=t,{recorder:u}=i;let a=ke(o);const p={model:n,messages:Re(s,r),...a&&{tools:a},...c};u?.debug?.log(p);let d;try{const f=await e.chat.completions.create(p);d=Ht(f)}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(Wt,"createGenerationRequestWithChatCompletion");function Ht(t){if(t.choices.length>0){const e=t.choices[0],n=[];if(e.message.content&&n.push({type:"text",text:e.message.content}),e.message.tool_calls){for(const s of e.message.tool_calls)if(s.type==="function")try{n.push({type:"tool-call",id:s.id,name:s.function.name,parameters:JSON.parse(s.function.arguments)})}catch(r){throw new Error(`Failed to parse tool call arguments for ${s.function.name}: ${r instanceof Error?r.message:String(r)}`)}}return{type:"success",id:t.id,model:t.model,role:e.message.role,finishReason:ne(e.finish_reason),content:n,text:G(n)??"",usage:{in:t.usage?.prompt_tokens??0,out:t.usage?.completion_tokens??0},raw:t}}return{type:"error",error:{type:"undetermined",message:"Unexpected response from OpenAI"},usage:{in:t.usage?.prompt_tokens??0,out:t.usage?.completion_tokens??0},raw:t}}l(Ht,"fromModelResponse$1");function Bt(){const t=new Map;let e=0,n="",s="";function r(o){const i=[],c=o.choices[0];if(!c)return i;n||(n=o.id,s=o.model,i.push({type:"start",id:n,data:{model:s,timestamp:Date.now()}}));const u=c.delta;if(u.content&&i.push({type:"text",data:{text:u.content,index:e}}),u.tool_calls)for(const a of u.tool_calls){const p=a.index;if(!t.has(p)){const f=e+p+1,_=a.id||`tool-${f}`;t.set(p,{id:_,name:a.function?.name||"",argumentsBuffer:""}),i.push({type:"tool-call-start",data:{index:f,id:_,name:a.function?.name||""}})}const d=t.get(p);a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),a.function?.arguments&&(d.argumentsBuffer+=a.function.arguments)}if(c.finish_reason){for(const[p,d]of t){const f=e+p+1;try{const _=JSON.parse(d.argumentsBuffer);i.push({type:"tool-call-complete",data:{index:f,id:d.id,name:d.name,arguments:_}})}catch(_){throw new Error(`Failed to parse tool call arguments for ${d.name}: ${_ instanceof Error?_.message:String(_)}`)}}const a=qt(c.finish_reason);i.push({type:"complete",data:{finishReason:a,usage:o.usage?{in:o.usage.prompt_tokens,out:o.usage.completion_tokens}:{in:0,out:0}}})}return i}return l(r,"handleChunk"),{handleChunk:r}}l(Bt,"createChatCompletionStreamingAdapter");function qt(t){switch(t){case"stop":return y.Stop;case"length":return y.Length;case"tool_calls":case"function_call":return y.FunctionCall;case"content_filter":return y.Error;default:return y.Stop}}l(qt,"convertFinishReason");function Jt(){let t="",e="",n=0,s=0,r=0;const o=new Map,i=new Set;function c(u){const a=[];switch(u.type){case"response.created":{t=u.response.id||`openai-${Date.now()}`,e=u.response.model,a.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{a.push({type:"text",data:{text:u.delta,index:n}});break}case"response.function_call_arguments.delta":{const p=u.item_id;o.has(p)||(s++,o.set(p,{id:p,name:"",argumentsBuffer:""}),a.push({type:"tool-call-start",data:{index:s,id:p,name:""}}));const d=o.get(p);d.argumentsBuffer+=u.delta;break}case"response.function_call_arguments.done":{const p=u.item_id;if(o.get(p)){try{const f=JSON.parse(u.arguments);a.push({type:"tool-call-complete",data:{index:s,id:p,name:u.name,arguments:f}})}catch(f){throw new Error(`Failed to parse function call arguments for ${u.name}: ${f instanceof Error?f.message:String(f)}`)}o.delete(p)}break}case"response.completed":{const p=u.response.usage;a.push({type:"complete",data:{finishReason:u.response.incomplete_details?y.Error:y.Stop,usage:{in:p?.input_tokens||0,out:p?.output_tokens||0}}});break}case"response.failed":{a.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${u.response.status}`,raw:u}});break}case"response.output_item.added":{if(u.item?.type==="reasoning"){const p=u.item.id;i.add(p),r++,a.push({type:"thinking-start",data:{index:r}})}break}case"response.reasoning_text.delta":{u.delta&&a.push({type:"thinking-delta",data:{index:r,text:u.delta}});break}case"response.reasoning_summary_text.delta":{u.delta&&a.push({type:"thinking-delta",data:{index:r,text:u.delta}});break}case"response.output_item.done":{if(u.item?.type==="reasoning"){const p=u.item.id;i.delete(p)}break}}return a}return l(c,"handleEvent"),{handleEvent:c}}l(Jt,"createResponsesAPIStreamingAdapter");const g={GPT_5:"gpt-5",GPT_5_MINI:"gpt-5-mini",GPT_5_NANO:"gpt-5-nano",GPT_5_CHAT_LATEST:"gpt-5-chat-latest",GPT_5_PRO:"gpt-5-pro",GPT_5_CODEX:"gpt-5-codex",GPT_4_5_PREVIEW:"gpt-4.5-preview",GPT_4_5_PREVIEW_2025_02_27:"gpt-4.5-preview-2025-02-27",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_MINI:"gpt-4o-mini",GPT_4O_MINI_2024_07_18:"gpt-4o-mini-2024-07-18",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_AUDIO_PREVIEW:"gpt-4o-mini-audio-preview",GPT_4O_MINI_AUDIO_PREVIEW_2024_12_17:"gpt-4o-mini-audio-preview-2024-12-17",GPT_REALTIME:"gpt-realtime",GPT_REALTIME_MINI:"gpt-realtime-mini",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_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_SEARCH_PREVIEW:"gpt-4o-search-preview",GPT_4O_SEARCH_PREVIEW_2025_03_11:"gpt-4o-search-preview-2025-03-11",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_TRANSCRIBE:"gpt-4o-transcribe",GPT_4O_MINI_TRANSCRIBE:"gpt-4o-mini-transcribe",GPT_4O_MINI_TTS:"gpt-4o-mini-tts",GPT_IMAGE_1:"gpt-image-1",GPT_IMAGE_1_MINI:"gpt-image-1-mini",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16",O3:"o3",O3_PRO:"o3-pro",O3_MINI:"o3-mini",O3_MINI_2025_01_31:"o3-mini-2025-01-31",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19",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_PREVIEW:"o1-preview",O1_PREVIEW_2024_09_12:"o1-preview-2024-09-12",GPT_OSS_120B:"gpt-oss-120b",GPT_OSS_7B:"gpt-oss-7b",SORA_2:"sora-2",SORA_2025_05_02:"sora-2025-05-02",CODEX_MINI:"codex-mini",COMPUTER_USE_PREVIEW:"computer-use-preview"},Pe=[g.GPT_5,g.GPT_5_MINI,g.GPT_5_NANO,g.GPT_5_CHAT_LATEST,g.GPT_5_PRO,g.GPT_5_CODEX,g.GPT_4_1,g.GPT_4_1_2025_04_14,g.GPT_4_1_MINI,g.GPT_4_1_MINI_2025_04_14,g.GPT_4_1_NANO,g.GPT_4_1_NANO_2025_04_14,g.GPT_4O,g.GPT_4O_2024_05_13,g.GPT_4O_2024_08_06,g.GPT_4O_2024_11_20,g.GPT_4O_MINI,g.GPT_4O_MINI_2024_07_18,g.GPT_4O_AUDIO_PREVIEW,g.GPT_4O_AUDIO_PREVIEW_2024_10_01,g.GPT_4O_AUDIO_PREVIEW_2024_12_17,g.GPT_4O_AUDIO_PREVIEW_2025_06_03,g.GPT_4O_MINI_AUDIO_PREVIEW,g.GPT_4O_MINI_AUDIO_PREVIEW_2024_12_17,g.GPT_REALTIME,g.GPT_REALTIME_MINI,g.GPT_4O_REALTIME_PREVIEW,g.GPT_4O_REALTIME_PREVIEW_2024_10_01,g.GPT_4O_REALTIME_PREVIEW_2024_12_17,g.GPT_4O_REALTIME_PREVIEW_2025_06_03,g.GPT_4O_MINI_REALTIME_PREVIEW,g.GPT_4O_MINI_REALTIME_PREVIEW_2024_12_17,g.GPT_4O_SEARCH_PREVIEW,g.GPT_4O_SEARCH_PREVIEW_2025_03_11,g.GPT_4O_MINI_SEARCH_PREVIEW,g.GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11,g.GPT_4O_TRANSCRIBE,g.GPT_4O_MINI_TRANSCRIBE,g.O4_MINI,g.O4_MINI_2025_04_16,g.O3,g.O3_PRO,g.O3_MINI,g.O3_MINI_2025_01_31],Oe=g.GPT_5;function be(t){if(t&&t.length>0)return t.map(e=>{const n=F.toJSONSchema(e.schema);return{type:"function",strict:!0,name:e.name,description:e.description,parameters:n}})}l(be,"prepareTools");function ve(t){return t.map(jt).flat(1)}l(ve,"convertAxleMessageToResponseInput");function jt(t){switch(t.role){case"tool":return Kt(t);case"assistant":return zt(t);default:return Xt(t)}}l(jt,"convertMessage");function Kt(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:e.content}))}l(Kt,"convertToolMessage");function zt(t){const e=[],n=t.content.filter(i=>i.type==="thinking");if(n.length>0)for(const i of n)e.push({type:"reasoning",id:`reasoning_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,summary:[{type:"summary_text",text:i.text}]});const s=G(t.content),r=t.content.filter(i=>i.type==="tool-call"),o=r.length>0?r.map(i=>({type:"function",id:i.id,function:{name:i.name,arguments:JSON.stringify(i.parameters)}})):void 0;return(s||o)&&e.push({role:t.role,content:s,...o&&{toolCalls:o}}),e}l(zt,"convertAssistantMessage");function Xt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(Zt).filter(n=>n!==null);return{role:t.role,content:e}}}l(Xt,"convertUserMessage");function Zt(t){if(t.type==="text")return{type:"input_text",text:t.text};if(t.type==="file"){if(t.file.type==="image")return{type:"input_image",image_url:`data:${t.file.mimeType};base64,${t.file.base64}`,detail:"auto"};if(t.file.type==="document")return{type:"input_file",filename:t.file.path,file_data:`data:${t.file.mimeType};base64,${t.file.base64}`}}return t.type==="thinking",null}l(Zt,"convertContentPart");async function*Yt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i;Pe.includes(n)?yield*Vt({client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}):yield*Qt({client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c})}l(Yt,"createStreamingRequest");async function*Qt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i,a=ke(o),p={model:n,messages:Re(s,r),...a&&{tools:a},...c,stream:!0};u?.debug?.log(p);const d=Bt();try{const f=await e.chat.completions.create(p);for await(const _ of f){const m=d.handleChunk(_);for(const w of m)yield w}}catch(f){u?.error?.log(f),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}l(Qt,"createChatCompletionStream");async function*Vt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i;console.log(c);const a=be(o),p={model:n,input:ve(s),...r&&{instructions:r},stream:!0,...a?{tools:a}:{},...c};u?.debug?.log(p);const d=Jt();try{const f=e.responses.stream(p);for await(const _ of f){const m=d.handleEvent(_);for(const w of m)yield w}}catch(f){u?.error?.log(f),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}l(Vt,"createResponsesAPIStream");async function en(t){const{client:e,model:n,messages:s,system:r,tools:o,context:i,options:c}=t,{recorder:u}=i,a=be(o),p={model:n,input:ve(s),...r&&{instructions:r},...a?{tools:a}:{},...c};u?.debug?.log(p);let d;try{const f=await e.responses.create(p);d=tn(f)}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(en,"createGenerationRequestWithResponsesAPI");function tn(t){if(t.error)return{type:"error",error:{type:t.error.code||"undetermined",message:t.error.message||"Response generation failed"},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t};const e=t.output?.filter(r=>r.type==="reasoning")?.map(r=>r),n=[];if(e&&e.length>0)for(const r of e){const o=r.summary?.[0]?.text||r.content?.[0]?.text||"";(o||r.encrypted_content)&&n.push({type:"thinking",text:o,...r.encrypted_content&&{encrypted:r.encrypted_content}})}t.output_text&&n.push({type:"text",text:t.output_text});const s=t.output?.filter(r=>r.type==="function_call");if(s&&s.length>0)for(const r of s){const o=r;try{n.push({type:"tool-call",id:o.id||"",name:o.name||"",parameters:o.arguments?JSON.parse(o.arguments):{}})}catch(i){throw new Error(`Failed to parse tool call arguments for ${o.name}: ${i instanceof Error?i.message:String(i)}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?y.Error:y.Stop,content:n,text:G(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}l(tn,"fromModelResponse");const Ne="OpenAI";class nn{static{l(this,"OpenAIProvider")}name=Ne;client;model;constructor(e,n){this.model=n||Oe,this.client=new Ye({apiKey:e})}async createGenerationRequest(e){return Pe.includes(this.model)?await en({client:this.client,model:this.model,...e}):await Wt({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return Yt({client:this.client,model:this.model,messages:n,system:s,tools:r,runtime:o,options:i})}}async function $e(t){const{provider:e,messages:n,system:s,tools:r,recorder:o,options:i}=t;return e.createGenerationRequest({messages:n,system:s,tools:r,context:{recorder:o},options:i})}l($e,"generate");function sn(t,e){if(!e||Object.keys(e).length===0)throw new A(`The provider ${t} is not configured. Please check your configuration.`);switch(t){case"openai":return new nn(e["api-key"],e.model);case"anthropic":return new dt(e["api-key"],e.model);case"gemini":return new xt(e["api-key"],e.model);case"ollama":{const n=e;return new Gt(n.model,n.url)}default:throw new A("The provider is unsupported")}}l(sn,"getProvider");class ae extends A{static{l(this,"TaskError")}constructor(e,n){super(e,{code:"TASK_ERROR",id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,ae.prototype)}}const E={Running:"running",Success:"success",PartialSuccess:"partialSuccess",Fail:"fail"};var x=(t=>(t[t.Trace=10]="Trace",t[t.Debug=20]="Debug",t[t.Info=30]="Info",t[t.Warn=40]="Warn",t[t.Error=50]="Error",t[t.Fatal=60]="Fatal",t))(x||{});class rn{static{l(this,"Recorder")}instanceId=crypto.randomUUID();currentLevel=x.Info;logs=[];writers=[];_debug;_info;_warn;_error;constructor(){this.buildMethods()}buildMethods(){this._debug=x.Debug>=this.currentLevel?this.createLoggingFunction(x.Debug):null,this._info=x.Info>=this.currentLevel?this.createLoggingFunction(x.Info):null,this._warn=x.Warn>=this.currentLevel?this.createLoggingFunction(x.Warn):null,this._error=this.createLoggingFunction(x.Error)}set level(e){this.currentLevel=e,this.buildMethods()}get level(){return this.currentLevel}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}get debug(){return this._debug}subscribe(e){this.writers.includes(e)||this.writers.push(e)}unsubscribe(e){const n=this.writers.indexOf(e);n!==-1&&this.writers.splice(n,1)}publish(e){this.logs.push(e);for(const n of this.writers)n.handleEvent(e)}logFunction(e,n,...s){let r=s.map(o=>typeof o=="string"?{message:o}:o instanceof Error?Qe(o):o);this.publish({level:e,time:Date.now(),kind:n,payload:r})}createLoggingFunction(e){return{log:this.logFunction.bind(this,e,"body"),heading:{log:this.logFunction.bind(this,e,"heading")}}}getLogs(e=x.Info){return this.logs.filter(n=>n.level>=e)}async shutdown(){for(const e of this.writers)typeof e.flush=="function"&&await e.flush()}}async function on(t,e){const{defaults:n,tag:s}=e;let r=null,o="";if(t)try{o=te(t),r=await U(o,{encoding:"utf-8"})}catch{throw new Error(`${s} not found, see --help for details`)}else{for(const i of n.formats)try{o=te(n.name+"."+i),r=await U(o,{encoding:"utf-8"});break}catch{continue}if(r===null)throw new Error(`${s} not found, see --help for details`)}return{content:r,format:o.split(".").pop()??""}}l(on,"searchAndLoadFile");async function an(t,e){let n="";for(const s of t){const r=await ue(s);e?.debug?.log(`many-files parser. For glob "${s}", found ${r.length} files.`);const o=await Promise.all(r.map(async i=>{const c=await U(i,"utf-8");return i+`:
|
|
5
|
+
`+c}));n+=o.join(`
|
|
6
|
+
`)}return n}l(an,"loadManyFiles");function cn(t,e){t=t.replace("**/*","**");const n=/(?<asterisks>\*{1,2})(?<extension>\.[^\\/]+)?/,s=t.match(n);if(s){let r="";return s.groups?.asterisks.length==1?r+=e.stem:r+=e.dir+e.stem,s.groups?.extension?r+=s.groups.extension:r+=e.ext,t.replace(s[0],r)}return t}l(cn,"replaceFilePattern");function un(t){const e=/(?<name>[^\\/]+)(?<extension>\.[^\\/]+)$/,n=t.match(e);return n&&n.length>0&&n.groups?{abs:t,dir:t.replace(n[0],""),ext:n.groups.extension,stem:n.groups.name,name:n[0]}:null}l(un,"pathToComponents");async function Me(t){const e=ot(t);try{await le(e)}catch{await rt(e),await Me(e)}}l(Me,"ensureDirectoryExistence");async function ln({filePath:t,content:e}){await Me(t),await st(t,e)}l(ln,"writeFileWithDirectories");const J=[".jpg",".jpeg",".png",".gif",".webp",".bmp",".tiff"],j=[".pdf"],K=[".txt",".md",".markdown"],Ge=20*1024*1024;function fn(t){return t.type==="text"}l(fn,"isTextFileInfo");function pn(t){return t.type==="image"||t.type==="document"}l(pn,"isBase64FileInfo");function dn(t){const e=fe(t).toLowerCase();if(K.includes(e))return"utf-8";if(J.includes(e)||j.includes(e))return"base64";{const n=[...K,...J,...j];throw new Error(`Unsupported file type: ${e}. Supported types: ${n.join(", ")}`)}}l(dn,"getEncodingForFile");async function z(t,e){const n=te(t);try{await le(n)}catch{throw new Error(`File not found: ${t}`)}const s=await nt(n);if(s.size>Ge)throw new Error(`File too large: ${s.size} bytes. Maximum allowed: ${Ge} bytes`);const r=fe(n).toLowerCase(),o=n.split("/").pop()||"";if((e||dn(n))==="utf-8"){if(!K.includes(r))throw new Error(`Unsupported text file type: ${r}. Supported types: ${K.join(", ")}`);let c;switch(r){case".txt":c="text/plain";break;case".md":case".markdown":c="text/markdown";break;default:c="text/plain"}const u=await U(n,"utf-8");return{path:n,content:u,mimeType:c,size:s.size,name:o,type:"text"}}else{let c,u;if(J.includes(r))switch(c="image",r){case".jpg":case".jpeg":u="image/jpeg";break;case".png":u="image/png";break;case".gif":u="image/gif";break;case".webp":u="image/webp";break;case".bmp":u="image/bmp";break;case".tiff":u="image/tiff";break;default:u="image/jpeg"}else if(j.includes(r))c="document",u="application/pdf";else throw new Error(`Unsupported file type: ${r}. Supported types: ${[...J,...j].join(", ")}`);const p=(await U(n)).toString("base64");return{path:n,base64:p,mimeType:u,size:s.size,name:o,type:c}}}l(z,"loadFileContent");function _n(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):gn(t.using,e)?!t.jobs||typeof t.jobs!="object"?(e&&(e.value="Missing or invalid 'jobs' property"),!1):Ce(t.jobs,e)?!0:(e&&(e.value=`Invalid 'jobs' property: ${e?.value}`),!1):(e&&(e.value=`Invalid 'using' property: ${e?.value}`),!1)}l(_n,"isJobConfig");function gn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(typeof t.engine!="string")return e&&(e.value="Missing or invalid 'engine' property"),!1;if(!["openai","anthropic","ollama","gemini"].includes(t.engine))return e&&(e.value="Invalid provider type. Must be 'openai', 'anthropic', 'gemini', or 'ollama'"),!1;switch(t.engine){case"ollama":if("model"in t&&typeof t.model!="string")return e&&(e.value="Property 'model' must be a string"),!1;if("url"in t&&typeof t.url!="string")return e&&(e.value="Property 'url' must be a string"),!1;break;case"gemini":case"anthropic":case"openai":if("api-key"in t&&typeof t["api-key"]!="string")return e&&(e.value="Property 'api-key' must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Property 'model' must be a string"),!1;break}return!0}l(gn,"isUsing");function Ce(t,e){for(const[n,s]of Object.entries(t))if(!mn(s,e))return e&&(e.value=`Invalid job '${n}': ${e?.value}`),!1;return!0}l(Ce,"isDAGJob");function mn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(!hn(t,e))return!1;if("dependsOn"in t&&t.dependsOn!==void 0){const n=t.dependsOn;if(typeof n!="string")if(Array.isArray(n)){for(let s=0;s<n.length;s++)if(typeof n[s]!="string")return e&&(e.value=`Dependency at index ${s} must be a string`),!1}else return e&&(e.value="Property 'dependsOn' must be a string or array of strings"),!1}return!0}l(mn,"isDAGJobValue");function hn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):"batch"in t?En(t,e):yn(t,e)}l(hn,"isJob");function yn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if("batch"in t)return e&&(e.value="Serial job should not have a batch property"),!1;if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const n of t.tools)if(typeof n!="string")return e&&(e.value="All tools must be strings"),!1}if(!Array.isArray(t.steps))return e&&(e.value="Property 'steps' must be an array"),!1;for(let n=0;n<t.steps.length;n++)if(!Le(t.steps[n],e))return e&&(e.value=`Invalid step at index ${n}: ${e?.value}`),!1;return!0}l(yn,"isSerialJob");function En(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const n of t.tools)if(typeof n!="string")return e&&(e.value="All tools must be strings"),!1}if(!Array.isArray(t.batch))return e&&(e.value="Property 'batch' must be an array"),!1;for(let n=0;n<t.batch.length;n++)if(!In(t.batch[n],e))return e&&(e.value=`Invalid batch item at index ${n}: ${e?.value}`),!1;if(!Array.isArray(t.steps))return e&&(e.value="Property 'steps' must be an array"),!1;for(let n=0;n<t.steps.length;n++)if(!Le(t.steps[n],e))return e&&(e.value=`Invalid step at index ${n}: ${e?.value}`),!1;return!0}l(En,"isBatchJob");function In(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.type!=="files")return e&&(e.value="Property 'type' must be 'files'"),!1;if(typeof t.source!="string")return e&&(e.value="Property 'source' must be a string"),!1;if(typeof t.bind!="string")return e&&(e.value="Property 'bind' must be a string"),!1;if(t["skip-if"]!==void 0){if(!Array.isArray(t["skip-if"]))return e&&(e.value="Property 'skip-if' must be an array"),!1;for(let n=0;n<t["skip-if"].length;n++)if(!wn(t["skip-if"][n],e))return e&&(e.value=`Invalid skip condition at index ${n}: ${e?.value}`),!1}return!0}l(In,"isBatchOptions");function wn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):t.type!=="file-exist"?(e&&(e.value="Property 'type' must be 'file-exist'"),!1):typeof t.pattern!="string"?(e&&(e.value="Property 'pattern' must be a string"),!1):!0}l(wn,"isSkipOptions");function Le(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):!t.uses||typeof t.uses!="string"?(e&&(e.value="Step must have a string 'uses' property"),!1):t.uses==="chat"?Tn(t,e):t.uses==="write-to-disk"?xn(t,e):(e&&(e.value=`Unknown uses type: ${t.uses}`),!1)}l(Le,"isStep");function Tn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.uses!=="chat")return e&&(e.value="Uses must be 'chat'"),!1;if(typeof t.message!="string")return e&&(e.value="Property 'message' must be a string"),!1;if(t.output!==void 0){if(!t.output||typeof t.output!="object"||Array.isArray(t.output))return e&&(e.value="Property 'output' must be an object"),!1;const n=["string","string[]","number","boolean"];for(const[s,r]of Object.entries(t.output))if(typeof s!="string"||typeof r!="string"||!n.includes(r))return e&&(e.value="Property 'output' must be a Record<string, ResTypeStrings> where ResTypeStrings is 'string' | 'string[]' | 'number' | 'boolean'"),!1}if(t.system!==void 0&&typeof t.system!="string")return e&&(e.value="Property 'system' must be a string"),!1;if(t.replace!==void 0){if(!Array.isArray(t.replace))return e&&(e.value="Property 'replace' must be an array"),!1;for(let n=0;n<t.replace.length;n++)if(!An(t.replace[n],e))return e&&(e.value=`Invalid replace at index ${n}: ${e?.value}`),!1}if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const n of t.tools)if(typeof n!="string")return e&&(e.value="All tools must be strings"),!1}if(t.images!==void 0){if(!Array.isArray(t.images))return e&&(e.value="Property 'images' must be an array"),!1;for(let n=0;n<t.images.length;n++)if(!Sn(t.images[n],e))return e&&(e.value=`Invalid image at index ${n}: ${e?.value}`),!1}if(t.documents!==void 0){if(!Array.isArray(t.documents))return e&&(e.value="Property 'documents' must be an array"),!1;for(let n=0;n<t.documents.length;n++)if(!kn(t.documents[n],e))return e&&(e.value=`Invalid document at index ${n}: ${e?.value}`),!1}if(t.references!==void 0){if(!Array.isArray(t.references))return e&&(e.value="Property 'references' must be an array"),!1;for(let n=0;n<t.references.length;n++)if(!Rn(t.references[n],e))return e&&(e.value=`Invalid reference at index ${n}: ${e?.value}`),!1}return!0}l(Tn,"isChatStep");function xn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.uses!=="write-to-disk")return e&&(e.value="Uses must be 'write-to-disk'"),!1;if(typeof t.output!="string")return e&&(e.value="Property 'output' must be a string"),!1;if(t.keys!==void 0&&typeof t.keys!="string")if(Array.isArray(t.keys)){for(let n=0;n<t.keys.length;n++)if(typeof t.keys[n]!="string")return e&&(e.value=`Key at index ${n} must be a string`),!1}else return e&&(e.value="Property 'keys' must be a string or array of strings"),!1;return!0}l(xn,"isWriteToDiskStep");function An(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(typeof t.pattern!="string")return e&&(e.value="Property 'pattern' must be a string"),!1;if(t.source!=="file")return e&&(e.value="Property 'source' must be 'file'"),!1;if(typeof t.files!="string"&&!Array.isArray(t.files))return e&&(e.value="Property 'files' must be a string or an array of strings"),!1;if(Array.isArray(t.files)){for(let n=0;n<t.files.length;n++)if(typeof t.files[n]!="string")return e&&(e.value=`Files entry at index ${n} must be a string`),!1}return!0}l(An,"isReplace");function Sn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}l(Sn,"isImageReference");function kn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}l(kn,"isDocumentReference");function Rn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}l(Rn,"isTextFileReference");class Pn{static{l(this,"FileRunPlanner")}constructor(e,n,s=[]){this.source=e,this.bind=n,this.skipConditions=s}async plan(e){const n=[],s=await ue(this.source,{withFileTypes:!0});for(const r of s){const o=r.fullpath(),i=un(o);let c=!1;for(const u of this.skipConditions)if(c=await u.eval({components:i}),c)break;if(!c){const u=await Ve(o,"utf-8"),a={variables:{[this.bind]:u,...i},tasks:e};n.push(a)}}return n}}class On{static{l(this,"MultiPlanner")}planners;constructor(e){this.planners=e}async plan(e){const n=this.planners.map(async r=>await r.plan(e));return(await Promise.all(n)).flat()}}function se(t,e,n="{{}}"){const s=n==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(s,(r,o)=>{if(o=o.trim(),Object.prototype.hasOwnProperty.call(e,o)){const i=e[o];return i==null?"":String(i)}return r}),t}l(se,"replaceVariables");class bn{static{l(this,"FileExistSkipCondition")}constructor(e){this.pattern=e}type="file-exist";async eval(e){const n=se(this.pattern,e.components,"{}");try{return await et(n,tt.F_OK),!0}catch{return!1}}}function X(t,e=0){const n={};for(const[s,r]of Object.entries(t))if(typeof r=="string")switch(r){case"string":n[s]=e===0?I.string():I.string().optional();break;case"number":n[s]=e===0?I.number():I.number().optional();break;case"boolean":n[s]=e===0?I.boolean():I.boolean().optional();break;case"string[]":n[s]=I.array(I.string());break;default:throw new Error(`Unsupported declarative type: ${r}`)}else if(Array.isArray(r))if(r.length===1&&typeof r[0]=="object"){const o=X(r[0],e+1);n[s]=I.array(I.object(o))}else throw new Error(`Unsupported array format for key ${s}. Expected [DeclarativeSchema].`);else n[s]=I.object(X(r,e+1));return n}l(X,"declarativeToOutputSchema");function Z(t){if(t instanceof I.ZodString)return["string","Your answer"];if(t instanceof I.ZodNumber)return["number",42];if(t instanceof I.ZodBoolean)return["boolean",!0];if(t instanceof I.ZodArray){const e=t.element;if(e instanceof I.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof I.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof I.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof I.ZodObject){const[n,s]=Z(e);return["object array",[s,s]]}return["array",[]]}if(t instanceof I.ZodObject){const e=t.shape,n={};for(const[s,r]of Object.entries(e)){const[o,i]=Z(r);n[s]=i}return["JSON object",n]}if(t instanceof I.ZodOptional){const e=t.unwrap(),[n,s]=Z(e);return[`${n} | undefined`,s]}}l(Z,"zodToExample");function De(t){return typeof t=="object"&&Object.values(t).every(e=>e&&typeof e=="object"&&"_def"in e)}l(De,"isOutputSchema");class Fe{static{l(this,"AbstractInstruct")}type="instruct";prompt;system=null;inputs={};tools={};files=[];textReferences=[];instructions=[];schema;rawResponse;_taggedSections=void 0;_result=void 0;constructor(e,n){this.prompt=e,this.schema=n}setInputs(e){this.inputs=e}addInput(e,n){this.inputs[e]=n}addTools(e){for(const n of e)this.tools[n.name]=n}addTool(e){this.tools[e.name]=e}addImage(e){if(e.type!=="image")throw new Error(`Expected image file, got ${e.type}`);const n=e;this.files.push(n)}addDocument(e){if(e.type!=="document")throw new Error(`Expected document file, got ${e.type}`);const n=e;this.files.push(n)}addFile(e){if(!pn(e))throw new Error(`Expected image or document file, got ${e.type}`);this.files.push(e)}addReference(e,n){if(typeof e=="string"){this.textReferences.push({content:e,name:n?.name});return}if(fn(e))this.textReferences.push({content:e.content,name:n?.name??e.name});else throw new Error(`Expected text file, got ${e.type}`)}addInstructions(e){if(typeof e!="string"||e.trim()==="")throw new Error("Instruction must be a non-empty string");this.instructions.push(e)}hasTools(){return Object.keys(this.tools).length>0}hasFiles(){return this.files.length>0}get result(){return this._result}compile(e,n={}){const s=this.createUserMessage(e,n),r=this.createInstructions();return{message:s,instructions:r}}createUserMessage(e,n={}){const{recorder:s,options:r}=n,o={...e,...this.inputs};let i=se(this.prompt,o);if(this.textReferences.length>0)for(const[c,u]of this.textReferences.entries()){const a=u.name?`: ${u.name}`:"";i+=`
|
|
7
|
+
|
|
8
|
+
## Reference ${c+1}${a}
|
|
9
|
+
|
|
10
|
+
\`\`\`${u.content}'''`}if(r?.warnUnused){const c=i.match(/\{\{(.*?)\}\}/g);if(c)throw s?.error.log(`Warning unused variables ${c.join(", ")}`),new Error(`Unused variables: ${c.join(", ")}`)}return i}createInstructions(e=""){if(e=`# Instructions
|
|
11
|
+
|
|
12
|
+
`+e,Object.keys(this.schema).length>0){e+=`## Output Format Instructions
|
|
13
|
+
`,e+=`
|
|
14
|
+
Here is how you should format your output. Follow the instructions strictly.
|
|
15
|
+
`;for(const[s,r]of Object.entries(this.schema)){const o=this.generateFieldInstructions(s,r);e+=o}}if(this.instructions.length>0){e+=`
|
|
16
|
+
## Additional Instructions
|
|
17
|
+
|
|
18
|
+
`;for(const s of this.instructions)e+=`- ${s}
|
|
19
|
+
`}return e}generateFieldInstructions(e,n){const[s,r]=Z(n);return`
|
|
20
|
+
- Use <${e}></${e}> tags to indicate the answer for ${e}. The answer must be a ${s}.
|
|
21
|
+
Example: <${e}>${JSON.stringify(r)}</${e}>
|
|
22
|
+
`}finalize(e,n={}){const{recorder:s}=n;if(this.rawResponse=e,Object.keys(this.schema).length===0){if(e.trim()==="{}"||e.trim()==="")return this._result={},this._result;throw new Error("Schema is empty, but rawValue is not an empty object representation or empty string.")}this._taggedSections=this._taggedSections||this.parseTaggedSections(e);const o={};for(const[i,c]of Object.entries(this.schema)){const u=this._taggedSections.tags[i];if(u!==void 0)o[i]=this.preprocessValue(c,u);else if(c.def.type!=="optional")throw new Error(`Expected results with tag ${i} but it does not exist`)}try{const i={};for(const[c,u]of Object.entries(this.schema))c in o&&(i[c]=u.parse(o[c]));return this._result=i,this._result}catch(i){if(i&&typeof i=="object"&&"issues"in i){const c=i.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ");throw new Error(`Validation failed: ${c}`)}throw i}}preprocessValue(e,n){switch(n=n.trim(),e.def.type){case"string":try{return JSON.parse(n)}catch{if(typeof n=="string")return n;throw new Error(`Cannot parse '${n}' as string. Ensure it is a valid JSON string or a plain string.`)}case"number":{const s=parseFloat(n);if(isNaN(s))throw new Error(`Cannot parse '${n}' as number`);return s}case"boolean":{const s=n.toLowerCase();if(s==="true")return!0;if(s==="false")return!1;throw new Error(`Cannot parse '${n}' as boolean. Expected 'true' or 'false'`)}case"array":{if(n==="")return[];try{const s=JSON.parse(n);if(Array.isArray(s))return s}catch{}if(n.includes(","))return n.split(",").map(s=>{const r=s.trim();try{return JSON.parse(r)}catch{return r}}).filter(s=>s!=="")}case"object":{n.includes("```json")&&(n=n.replace(/```json/g,"").replace(/```/g,""));try{return JSON.parse(n)}catch(s){throw new Error(`Cannot parse object as JSON: ${s.message}`)}}case"optional":{const s=e.def.innerType;return this.preprocessValue(s,n)}default:return n}}parseTaggedSections(e){e.trim().startsWith("```json")&&e.trim().endsWith("```")&&(e=e.trim().slice(7,-3).trim());const n=/<(\w+)>(.*?)<\/\1>/gs,s={};let r=e;r=r.replace(n,(i,c,u)=>(s[c]=u,""));const o=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return r=r.replace(o,(i,c,u)=>(s[c]=u,"")),{tags:s,remaining:r.trim()}}}class C extends Fe{static{l(this,"Instruct")}constructor(e,n){super(e,n)}static with(e,n){if(!n)return new C(e,{response:I.string()});if(De(n))return new C(e,n);{const s=X(n);return new C(e,s)}}}function H(t){return Array.isArray(t)?t:[t]}l(H,"arrayify");function b(t,e){return e?`${e}:${t.slice(0,8)}`:t.slice(0,8)}l(b,"friendly");function vn(t){return new Promise(e=>setTimeout(e,t))}l(vn,"delay");const Nn=I.object({searchTerm:I.string().describe("The search term to query")});class $n{static{l(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=Nn;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.setConfig(e)}setConfig(e){const{rateLimit:n}=e;this.apiKey=e["api-key"],this.throttle=n?1100/n:void 0}async execute(e){const{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await vn(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const s=this.apiKey,r="https://api.search.brave.com/res/v1/web/search",o=new URL(r);o.searchParams.append("q",n),o.searchParams.append("format","json");const i=await fetch(o.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":s}});if(!i.ok)throw new Error(`[Brave] HTTP error ${i.status}: ${i.statusText}`);const c=await i.json();return JSON.stringify(c)}catch(s){throw s instanceof Error?new Error(`[Brave] Error fetching search results: ${s.message}`):s}}}const Mn=new $n,Gn=q.object({operation:q.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:q.number().describe("First operand"),b:q.number().describe("Second operand")}),Cn={name:"calculator",description:"Performs basic arithmetic operations",schema:Gn,execute:l(async({operation:t,a:e,b:n})=>{switch(t){case"add":return`${e} + ${n} = ${e+n}`;case"subtract":return`${e} - ${n} = ${e-n}`;case"multiply":return`${e} * ${n} = ${e*n}`;case"divide":if(n===0)throw new Error("Cannot divide by zero");return`${e} / ${n} = ${e/n}`;default:throw new Error(`Unknown operation: ${t}`)}},"execute")};class Ln{static{l(this,"ToolRegistry")}executables={};config;setConfig(e){this.config=e}register(e){if(this.executables[e.name])throw new Error(`Tool with name '${e.name}' is already registered`);this.executables[e.name]=e}get(e){const n=this.executables[e];if(!n)throw new Error(`Tool '${e}' is not registered`);return n.setConfig?.(this.config[e]),n}}let B;function Ue(){return B||(B=new Ln,B.register(Cn),B.register(Mn)),B}l(Ue,"getToolRegistry");const Dn={async convert(t,e){const{recorder:n,toolNames:s}=e,{message:r,system:o,replace:i}=t;let c;t.output?c=C.with(r,t.output):c=C.with(r),o&&(c.system=o);const u=[...new Set([...s??[],...t.tools??[]])];for(const a of u){const p=Ue().get(a);c.addTool(p)}if(i){for(const a of i)if(a.source==="file"){const p=H(a.files),d=await an(p,n);c.addInput(a.pattern,d)}}if(t.images)for(const a of t.images)try{const p=await z(a.file,"base64");c.addFile(p)}catch(p){throw new Error(`Failed to load image '${a.file}': ${p.message}`)}if(t.documents)for(const a of t.documents)try{const p=await z(a.file,"base64");c.addFile(p)}catch(p){throw new Error(`Failed to load document '${a.file}': ${p.message}`)}if(t.references)for(const a of t.references)try{const p=await z(a.file,"utf-8");c.addReference(p)}catch(p){throw new Error(`Failed to load reference file '${a.file}': ${p.message}`)}return c}};class Fn{static{l(this,"StepToClassRegistry")}converters=new Map;get(e){const n=this.converters.get(e);if(!n)throw new Error(`No converter registered for step: ${e}`);return n}register(e,n){this.converters.set(e,n)}}class re{static{l(this,"WriteOutputTask")}constructor(e,n=["response"]){this.output=e,this.keys=n}type="write-to-disk"}const Un={async convert(t){if(t.keys){const e=H(t.keys);return new re(t.output,e)}return new re(t.output)}},oe=new Fn;oe.register("write-to-disk",Un),oe.register("chat",Dn);async function Y(t,e){const{recorder:n}=e,s=t.tools??void 0,r=t.steps.map(async o=>(o.uses,await oe.get(o.uses).convert(o,{recorder:n,toolNames:s})));return Promise.all(r)}l(Y,"configToTasks");async function We(t,e){const{batch:n}=t;return n.length===1?He(n[0]):new On(n.map(s=>He(s)))}l(We,"configToPlanner");function He(t){switch(t.type){case"files":let e;return t["skip-if"]&&(e=t["skip-if"].map(s=>Wn(s))),new Pn(t.source,t.bind,e)}}l(He,"batchOptionsToPlanner");function Wn(t){switch(t.type){case"file-exist":return new bn(t.pattern)}}l(Wn,"skipOptionsToSkipConditions");function Hn(t){return t.success===!1&&t.error!==void 0}l(Hn,"isErrorResult");function Q(t,e){return{response:t,stats:e,success:!0}}l(Q,"createResult");function V(t,e,n){return{response:e,stats:n,error:t,success:!1}}l(V,"createErrorResult");class Be{static{l(this,"Conversation")}system;_messages=[];constructor(e){e&&(this._messages=e)}get messages(){return[...this._messages]}addSystem(e){this.system=e}addUser(e){typeof e=="string"?this._messages.push({role:"user",content:[{type:"text",text:e}]}):this._messages.push({role:"user",content:e})}addAssistant(e){if(typeof e=="string"){const n=e;this._messages.push({role:"assistant",id:crypto.randomUUID(),content:[{type:"text",text:n}],model:"user",finishReason:y.Custom})}else this._messages.push({role:"assistant",...e})}addToolResults(e){this._messages.push({role:"tool",content:e})}latest(){return this._messages[this._messages.length-1]}toString(){return JSON.stringify({system:this.system,messages:this._messages})}}class Bn{static{l(this,"WriteToDiskTaskHandler")}taskType="write-to-disk";canHandle(e){return e&&typeof e=="object"&&"type"in e&&e.type==="write-to-disk"}async execute(e){const{task:n,variables:s,options:r={},recorder:o}=e,i=n.output,c=n.keys??[];if(r?.warnUnused){const p=c.filter(d=>!(d in s));p.length>0&&o?.warn?.log(`[Write To Disk] The following keys were not found in the variables: ${p.join(", ")}`)}let u="";if(c.length===1?u=s[c[0]]??"<not found>":u=c.map(p=>`[${p}]:
|
|
23
|
+
${s[p]??"<not found>"}
|
|
24
|
+
`).join(`
|
|
25
|
+
`),r?.dryRun){o?.info?.log("[Dry run] Write to Disk is not executed.");return}let a="";i.includes("*")?a=cn(i,s.file):a=se(i,s,"{}"),await ln({filePath:a,content:u})}}var ee=(t=>(t.LastResult="lastResult",t))(ee||{});function qn(t,e,n){const{options:s,recorder:r}=n,o=s?.warnUnused??!0;for(const[i,c]of Object.entries(t))o&&e[i]&&r?.warn?.log(`Warning: Variable "${i}" is being overwritten. Previous value: ${e[i]}, new value: ${c}`),e[i]=c}l(qn,"setResultsIntoVariables");class Jn{static{l(this,"ChatTaskHandler")}taskType="instruct";canHandle(e){return e&&typeof e=="object"&&"type"in e&&e.type==="instruct"}async execute(e){const{task:n,...s}=e;await jn({instruct:n,...s})}}async function jn(t){const{instruct:e,chat:n,provider:s,stats:r,variables:o,options:i,recorder:c}=t;e.system&&n.addSystem(e.system);const{message:u,instructions:a}=e.compile(o,{recorder:c,options:i}),p=e.files;if(n.addUser(it({text:a+u,files:p})),i?.dryRun)return c?.debug?.log(n),{action:"complete"};let d=!0;for(;d;){const f=await $e({provider:s,messages:n.messages,tools:Object.values(e.tools),recorder:c});if(r.in+=f.usage.in,r.out+=f.usage.out,f.type==="error")throw new Error(JSON.stringify(f.error));if(f.type==="success")switch(f.finishReason){case y.Stop:{if(f.content){const _=f.content;n.addAssistant({id:f.id,model:f.model,content:f.content,finishReason:f.finishReason});const m=G(_),w=e.finalize(m,{recorder:c});qn(w,o,{options:i,recorder:c}),o[ee.LastResult]=w}return d=!1,{action:"continue"}}case y.Length:throw new Error("Incomplete model output due to `max_tokens` parameter or token limit");case y.FunctionCall:{f.content&&n.addAssistant({id:f.id,model:f.model,content:f.content,finishReason:f.finishReason});const _=at(f.content);if(_&&_.length>0){const m=await Kn(_,e,{recorder:c});c?.debug?.log(m),n.addToolResults(m),d=!0}else d=!1;break}}if(f.type!=="success")throw c?.debug?.log(f),new Error("Unexpected response type")}return{action:"continue"}}l(jn,"executeChatAction");async function Kn(t,e,n={}){const{recorder:s}=n,r=[];for(const o of t)r.push(new Promise((i,c)=>{const u=e.tools[o.name];if(!u){c(`Tool not found: ${o.name}`);return}s?.debug?.heading.log(`Executing tool ${u.name}`);const a=o.parameters;u.execute(a).then(p=>{s?.debug?.log(`Complete tool ${u.name}: ${o.id}`),i({id:o.id,name:o.name,content:JSON.stringify(p)})}).catch(c)}));return Promise.all(r)}l(Kn,"executeToolCalls");class zn{static{l(this,"TaskRegistry")}handlers=new Map;register(e){this.handlers.set(e.taskType,e)}getHandler(e){return this.handlers.get(e.type)}hasHandler(e){return this.handlers.has(e.type)}async executeTask(e){const{task:n}=e,s=n.type,r=this.getHandler(n);if(!r)throw new Error(`No handler registered for action type: ${s}`);if(!r.canHandle(n))throw new Error(`Handler found but action does not match expected format: ${s}`);await r.execute(e)}}function Xn(){const t=new zn;return t.register(new Jn),t}l(Xn,"createBaseRegistry");function Zn(){const t=Xn();return t.register(new Bn),t}l(Zn,"createNodeRegistry");const ie=l((t,...e)=>{const n=l(async r=>{const{recorder:o}=r;let i=[];return"steps"in t?i=await Y(t,{recorder:o}):i=[t,...e],i},"prepare");return{execute:l(async r=>{const{provider:o,variables:i,options:c,stats:u,recorder:a,name:p}=r,d=crypto.randomUUID(),f=Zn();a?.info?.log({type:"task",id:d,status:E.Running,message:`[${b(d,p)}] Starting job`});try{const _=await n({recorder:a}),m=new Be;for(const[w,k]of _.entries()){a?.info?.log({type:"task",id:d,status:E.Running,message:`[${b(d,p)}] Processing step ${w+1}: ${k.type}`});try{await f.executeTask({task:k,chat:m,provider:o,variables:i,options:c,stats:u,recorder:a})}catch(P){throw P instanceof A?P:new ae(`Error executing task ${k.type}`,{id:d,taskType:k.type,taskIndex:w,cause:P instanceof Error?P:new Error(String(P))})}}return a?.info?.log({type:"task",status:E.Success,id:d,message:`[${b(d,p)}] Completed ${_.length} steps`}),Q(i[ee.LastResult],u)}catch(_){const m=_ instanceof A?_:new A("Serial workflow execution failed",{id:d,cause:_ instanceof Error?_:new Error(String(_))});return a?.info?.log({type:"task",status:E.Fail,id:d,message:`[${b(d,p)}] Failed: ${m.message}`}),a?.error.log(m),V(m,i[ee.LastResult],u)}},"execute")}},"serialWorkflow"),qe=l((t,...e)=>{const n=l(async r=>{const{recorder:o}=r;let i=[],c=null;if("batch"in t){const u=t;c=await We(u),i=await Y(u,{recorder:o})}else c=t,i=[...e];return[c,i]},"prepare");return{execute:l(async r=>{const{provider:o,variables:i,options:c,stats:u,recorder:a,name:p}=r,d=crypto.randomUUID();try{const[f,_]=await n({recorder:a}),m=await f.plan(_);if(a?.debug?.heading.log("Runs",m),m.length===0)return a?.info?.log("No runs to execute"),Q([],u);let w=0;a?.info?.log({type:"task",status:E.Running,id:d,message:`[${b(d,"CRW")}] Working on 0/${m.length}`});const k=l(async(R,D)=>{try{return await ie(...R.tasks).execute({provider:o,variables:{...R.variables,...i},options:c,stats:u,recorder:a,name:`${p}-${D}`})}catch(N){const ce=N instanceof A?N:new A("Error executing run",{cause:N instanceof Error?N:new Error(String(N))});return a?.error?.log(ce),V(ce,null,u)}finally{w++,a?.info?.log({type:"task",status:E.Running,id:d,message:`[${b(d,"CRW")}] Working on ${w}/${m.length}`})}},"executeRun"),P=5;let M=[];for(let R=0;R<m.length;R+=P){const D=m.slice(R,R+P),N=await Promise.all(D.map(k));M=M.concat(N)}const v=M.some(Hn);a?.info?.log({type:"task",status:v?E.PartialSuccess:E.Success,id:d,message:`[${b(d,"CRW")}] All jobs (${m.length}) completed${v?" with some errors":""}`});const $=M.map(R=>R.response);return Q($,u)}catch(f){const _=f instanceof A?f:new A("Concurrent workflow execution failed",{id:d,cause:f instanceof Error?f:new Error(String(f))});return a?.error?.log(_),V(_,null,u)}},"execute")}},"concurrentWorkflow");class Yn{static{l(this,"DAGParser")}static parse(e){const n=new Map;for(const[r,o]of Object.entries(e)){const i=this.parseNodeDefinition(r,o);n.set(r,i)}return this.validateDependencies(n),this.checkForCycles(n),{stages:this.createExecutionStages(n),nodes:n}}static parseNodeDefinition(e,n){if(this.isSimpleTask(n))return{id:e,tasks:Array.isArray(n)?n:[n],dependencies:[],executionType:"serial"};if(this.isConcurrentNodeDefinition(n)){const i=n,c=i.dependsOn?H(i.dependsOn):[];return{id:e,tasks:i.tasks,dependencies:c,planner:i.planner,executionType:"concurrent"}}const s=n,r=s.dependsOn?H(s.dependsOn):[],o=H(s.task);return{id:e,tasks:o,dependencies:r,executionType:"serial"}}static isSimpleTask(e){return e.type||Array.isArray(e)}static isConcurrentNodeDefinition(e){return e&&typeof e=="object"&&"planner"in e}static validateDependencies(e){for(const n of e.values())for(const s of n.dependencies)if(!e.has(s))throw new A(`Node "${n.id}" depends on non-existent node "${s}"`)}static checkForCycles(e){const n=new Set,s=new Set,r=l(o=>{if(s.has(o))return!0;if(n.has(o))return!1;n.add(o),s.add(o);const i=e.get(o);for(const c of i.dependencies)if(r(c))return!0;return s.delete(o),!1},"hasCycle");for(const o of e.keys())if(r(o))throw new A(`Circular dependency detected involving node "${o}"`)}static createExecutionStages(e){const n=[],s=new Set,r=new Set(e.keys());for(;r.size>0;){const o=[];for(const i of r)e.get(i).dependencies.every(a=>s.has(a))&&o.push(i);if(o.length===0)throw new A("Unable to resolve DAG dependencies - possible circular reference");n.push(o),o.forEach(i=>{s.add(i),r.delete(i)})}return n}}class Qn{static{l(this,"DAGJobToDefinition")}static async convert(e,n){const{recorder:s}=n,r={};for(const[o,i]of Object.entries(e)){const{dependsOn:c,...u}=i;if("batch"in u){const a=u,p=await We(a),d=await Y(a,{recorder:s}),f={planner:p,tasks:d,...c?{dependsOn:c}:{}};r[o]=f}else{const a=await Y(u,{recorder:s});if(c){const p={task:a,dependsOn:c};r[o]=p}else r[o]=a}}return r}}async function Vn(t,e,n,s={}){const{variables:r}=n,o=e.nodes.get(t);try{let i;if(o.executionType==="concurrent"&&o.planner?i=await qe(o.planner,...o.tasks).execute({...n,variables:r,name:t}):i=await ie(...o.tasks).execute({...n,variables:r,name:t}),!i.success)throw new A(`Node "${t}" failed: ${i.error?.message}`);return i.response}catch(i){if(!s.continueOnError)throw i;return null}}l(Vn,"executeNode");const es=l((t,e={})=>{const n=l(async(r,o)=>{const{recorder:i}=o,c={value:""};return Ce(r,c)?await Qn.convert(r,o):(i?.warn?.log(c),r)},"prepare");return{execute:l(async r=>{const{stats:o,recorder:i}=r,{maxConcurrency:c=3}=e,u=crypto.randomUUID();try{const a=await n(t,{recorder:i});i?.debug?.log(a);const p=Yn.parse(a),d=new Map;i?.info?.log({type:"task",id:u,status:E.Running,message:`[${b(u)}] Starting workflow execution with ${p.stages.length} stages`});for(const[_,m]of p.stages.entries()){i?.info?.log({type:"task",id:u,status:E.Running,message:`[${b(u)}] Stage ${_+1}/${p.stages.length}, executing ${m.length} nodes: ${m.join(", ")}`});const w=Math.min(m.length,c);for(let k=0;k<m.length;k+=w){const P=m.slice(k,k+w);(await Promise.all(P.map(async v=>{const $=await Vn(v,p,r,e);return{nodeId:v,result:$}}))).forEach(({nodeId:v,result:$})=>{d.set(v,$)})}}i?.info?.log({type:"task",status:E.Success,id:u,message:`[${b(u)}] Workflow execution completed successfully`});const f=Object.fromEntries(d);return Q(f,o)}catch(a){const p=a instanceof A?a:new A("DAG workflow execution failed",{id:u,cause:a instanceof Error?a:new Error(String(a))});return i?.info?.log({type:"task",status:E.Fail,id:u,message:`[${b(u)}] Workflow execution failed: ${p.message}`}),i?.error?.log(p),V(p,null,o)}},"execute")}},"dagWorkflow"),ts=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],L={success:"\u2713",fail:"\u2717",spinning:ts};class ns{static{l(this,"ConsoleWriter")}tasks=new Map;entries=[];truncate=0;intervalId=null;spinnerInterval=80;lastRender="";isRendering=!1;inline=!0;constructor(e={}){this.truncate=e.truncate??0,this.inline=e.inline??!0}startSpinner(){this.intervalId===null&&(this.intervalId=setInterval(()=>{[...this.tasks.values()].some(n=>n.status===E.Running)&&this.renderTasks()},this.spinnerInterval))}stopSpinner(){this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}renderTasks(){if(this.isRendering)return;if(this.isRendering=!0,this.inline&&this.lastRender){const o=this.lastRender.split(`
|
|
26
|
+
`).length;pe.moveCursor(process.stdout,0,-o+1),pe.clearScreenDown(process.stdout)}const e=[...this.tasks.values()],n=e.filter(o=>o.status===E.Running),s=e.filter(o=>o.status===E.Success||o.status===E.Fail);if(n.length===0&&s.length>0){let o="";for(const i of s){if(i.status===E.Success){const c=T.green(L.success);o+=`${c} ${i.text}
|
|
27
|
+
`}else if(i.status===E.Fail){const c=T.red(L.fail);o+=`${c} ${i.text}
|
|
28
|
+
`}this.tasks.delete(i.id)}console.log(o)}for(const o of this.entries){const{level:i,time:c,kind:u,payload:a}=o;u==="heading"?rs(i,a,{truncate:this.truncate}):os(i,a,{truncate:this.truncate})}this.entries=[];let r="";for(const o of this.tasks.values())if(o.status===E.Running){const i=T.cyan(L.spinning[o.frameIndex]);o.frameIndex=(o.frameIndex+1)%L.spinning.length,r+=`${i} ${o.text}
|
|
29
|
+
`}else if(o.status===E.Success){const i=T.green(L.success);r+=`${i} ${o.text}
|
|
30
|
+
`}else if(o.status===E.Fail){const i=T.red(L.fail);r+=`${i} ${o.text}
|
|
31
|
+
`}this.lastRender=r,process.stdout.write(r),this.isRendering=!1}handleEvent(e){const{level:n,time:s,payload:r}=e;if(r.length>0&&ss(r[0])){const i=r[0],{id:c,message:u,status:a}=i;if(a===E.Running)this.tasks.set(c,{id:c,text:u,status:a,frameIndex:0});else if((a===E.Success||a===E.Fail)&&this.tasks.has(c)){const p=this.tasks.get(c);p.status=a,p.text=u}}else this.entries.push(e);this.renderTasks();const o=[...this.tasks.values()].some(i=>i.status===E.Running);o&&this.intervalId===null?this.startSpinner():!o&&this.intervalId!==null&&this.stopSpinner()}destroy(){this.stopSpinner()}}function ss(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.type!=="task"||typeof e.id!="string"||typeof e.message!="string")return!1;switch(e.status){case E.Running:case E.Success:case E.PartialSuccess:case E.Fail:return!0;default:return!1}}l(ss,"isTask");function rs(t,e,n){let s,r;t===x.Error?(s=T.red,r=T.redBright.bold):t===x.Warn?(s=T.yellow,r=T.yellowBright.bold):t>=x.Info?(s=T.blue,r=T.whiteBright.bold):(s=T.gray,r=T.white);const{message:o,data:i}=Ke(e);console.log(`${s("==>")} ${r(o)}`),je(t,i,n)}l(rs,"heading");function os(t,e,n){let s;t===x.Error?s=T.red:t===x.Warn?s=T.yellow:t>=x.Info?s=T.white:s=T.gray;const{message:r,data:o}=Ke(e);r&&console.log(s(r)),je(t,o,n)}l(os,"body");const Je=" ";function je(t,e,n){let s;t===x.Error?(s=T.red,n.truncate=0):t==x.Warn?s=T.yellow:t>=x.Info?s=T.white:s=T.gray,e.forEach(r=>{if(typeof r=="string"){console.log(s(`${Je}${r}`));return}for(const[o,i]of Object.entries(r)){let c=JSON.stringify(i,is(n.truncate)," ");const u=`${o}: ${c}`.split(`
|
|
32
|
+
`).map(a=>Je+a).join(`
|
|
33
|
+
`);console.log(s(u))}})}l(je,"values");function Ke(t){const[e,...n]=t;let s="",r=n;if(e){let{message:o,...i}=e;s=o&&typeof o=="string"?o:"",Object.keys(i).length>0&&(r=[i,...r])}return{message:s,data:r}}l(Ke,"toMsgData");function is(t){return t===0?null:(e,n)=>typeof n=="string"&&n.length>t?n.slice(0,t)+"<...>":n}l(is,"truncator");export{A,ns as C,me as D,C as I,x as L,S as M,he as N,rn as R,re as W,we as a,h as b,Te as c,es as d,Se as e,Mt as f,sn as g,Oe as h,g as i,Ne as j,Fe as k,z as l,De as m,X as n,$e as o,qe as p,y as q,Be as r,ie as s,on as t,_n as u,Ue as v};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import * as z from 'zod
|
|
2
|
-
import z__default from 'zod
|
|
1
|
+
import * as z from 'zod';
|
|
2
|
+
import z__default, { ZodObject, z as z$1 } from 'zod';
|
|
3
3
|
|
|
4
4
|
type PlainObject = Record<string, unknown>;
|
|
5
5
|
type ProgramOptions = {
|
|
@@ -45,6 +45,75 @@ interface RecorderWriter {
|
|
|
45
45
|
flush?(): Promise<void>;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
interface StreamChunk {
|
|
49
|
+
type: "start" | "text" | "tool-call-start" | "tool-call-delta" | "tool-call-complete" | "thinking-start" | "thinking-delta" | "complete" | "error";
|
|
50
|
+
id?: string;
|
|
51
|
+
data?: any;
|
|
52
|
+
}
|
|
53
|
+
interface StreamStartChunk extends StreamChunk {
|
|
54
|
+
type: "start";
|
|
55
|
+
id: string;
|
|
56
|
+
data: {
|
|
57
|
+
model: string;
|
|
58
|
+
timestamp: number;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
interface StreamCompleteChunk extends StreamChunk {
|
|
62
|
+
type: "complete";
|
|
63
|
+
data: {
|
|
64
|
+
finishReason: AxleStopReason;
|
|
65
|
+
usage: Stats;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
interface StreamTextChunk extends StreamChunk {
|
|
69
|
+
type: "text";
|
|
70
|
+
data: {
|
|
71
|
+
text: string;
|
|
72
|
+
index: number;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
interface StreamThinkingStartChunk extends StreamChunk {
|
|
76
|
+
type: "thinking-start";
|
|
77
|
+
data: {
|
|
78
|
+
index: number;
|
|
79
|
+
redacted?: boolean;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
interface StreamThinkingDeltaChunk extends StreamChunk {
|
|
83
|
+
type: "thinking-delta";
|
|
84
|
+
data: {
|
|
85
|
+
index: number;
|
|
86
|
+
text: string;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
interface StreamToolCallStartChunk extends StreamChunk {
|
|
90
|
+
type: "tool-call-start";
|
|
91
|
+
data: {
|
|
92
|
+
index: number;
|
|
93
|
+
id: string;
|
|
94
|
+
name: string;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
interface StreamToolCallCompleteChunk extends StreamChunk {
|
|
98
|
+
type: "tool-call-complete";
|
|
99
|
+
data: {
|
|
100
|
+
index: number;
|
|
101
|
+
id: string;
|
|
102
|
+
name: string;
|
|
103
|
+
arguments: any;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
interface StreamErrorChunk extends StreamChunk {
|
|
107
|
+
type: "error";
|
|
108
|
+
data: {
|
|
109
|
+
type: string;
|
|
110
|
+
message: string;
|
|
111
|
+
usage?: Stats;
|
|
112
|
+
raw?: any;
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamTextChunk | StreamToolCallStartChunk | StreamToolCallCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamErrorChunk;
|
|
116
|
+
|
|
48
117
|
declare class Recorder {
|
|
49
118
|
instanceId: `${string}-${string}-${string}-${string}-${string}`;
|
|
50
119
|
private currentLevel;
|
|
@@ -95,41 +164,61 @@ type Base64FileInfo = FileInfo & {
|
|
|
95
164
|
type: "image" | "document";
|
|
96
165
|
};
|
|
97
166
|
|
|
98
|
-
|
|
167
|
+
type AxleMessage = AxleUserMessage | AxleAssistantMessage | AxleToolCallMessage;
|
|
168
|
+
interface AxleUserMessage {
|
|
169
|
+
role: "user";
|
|
170
|
+
name?: string;
|
|
171
|
+
content: string | Array<ContentPart>;
|
|
172
|
+
}
|
|
173
|
+
interface AxleAssistantMessage {
|
|
174
|
+
role: "assistant";
|
|
175
|
+
id: string;
|
|
176
|
+
model?: string;
|
|
177
|
+
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall>;
|
|
178
|
+
finishReason?: AxleStopReason;
|
|
179
|
+
}
|
|
180
|
+
interface AxleToolCallMessage {
|
|
181
|
+
role: "tool";
|
|
182
|
+
content: Array<AxleToolCallResult>;
|
|
183
|
+
}
|
|
184
|
+
interface AxleToolCallResult {
|
|
185
|
+
id: string;
|
|
99
186
|
name: string;
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
187
|
+
content: string;
|
|
188
|
+
}
|
|
189
|
+
type ContentPart = ContentPartText | ContentPartFile | ContentPartToolCall | ContentPartThinking;
|
|
190
|
+
interface ContentPartText {
|
|
191
|
+
type: "text";
|
|
192
|
+
text: string;
|
|
193
|
+
}
|
|
194
|
+
interface ContentPartFile {
|
|
195
|
+
type: "file";
|
|
196
|
+
file: FileInfo;
|
|
197
|
+
}
|
|
198
|
+
interface ContentPartThinking {
|
|
199
|
+
type: "thinking";
|
|
200
|
+
text: string;
|
|
201
|
+
redacted?: boolean;
|
|
202
|
+
encrypted?: string;
|
|
203
|
+
signature?: string;
|
|
106
204
|
}
|
|
107
|
-
interface
|
|
205
|
+
interface ContentPartToolCall {
|
|
206
|
+
type: "tool-call";
|
|
207
|
+
id: string;
|
|
208
|
+
name: string;
|
|
209
|
+
parameters: Record<string, unknown>;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
type ToolDefinition<Z extends ZodObject = ZodObject> = {
|
|
108
213
|
name: string;
|
|
109
|
-
|
|
214
|
+
description?: string;
|
|
215
|
+
schema: Z;
|
|
216
|
+
};
|
|
217
|
+
interface ToolExecutable<Z extends ZodObject = ZodObject> extends ToolDefinition<Z> {
|
|
110
218
|
setConfig?: (config: {
|
|
111
219
|
[key: string]: any;
|
|
112
220
|
}) => void;
|
|
113
|
-
execute: (params:
|
|
114
|
-
[key: string]: any;
|
|
115
|
-
}) => Promise<string>;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
declare class Chat {
|
|
119
|
-
system: string;
|
|
120
|
-
messages: ChatItem[];
|
|
121
|
-
tools: ToolSchema[];
|
|
122
|
-
setToolSchemas(schemas: ToolSchema[]): void;
|
|
123
|
-
addSystem(message: string): void;
|
|
124
|
-
addUser(message: string): void;
|
|
125
|
-
addUser(message: string, instruction: string): void;
|
|
126
|
-
addUser(message: string, instruction: string, files: FileInfo[]): void;
|
|
127
|
-
addUser(message: string, files: FileInfo[]): any;
|
|
128
|
-
addAssistant(message: string, toolCalls?: ToolCall[]): void;
|
|
129
|
-
addTools(input: Array<ChatItemToolCallResult>): void;
|
|
130
|
-
hasFiles(): boolean;
|
|
131
|
-
latest(): ChatItem | undefined;
|
|
132
|
-
toString(): string;
|
|
221
|
+
execute: (params: z$1.infer<Z>) => Promise<string>;
|
|
133
222
|
}
|
|
134
223
|
|
|
135
224
|
type OllamaProviderConfig = {
|
|
@@ -144,7 +233,7 @@ type OpenAIProviderConfig = {
|
|
|
144
233
|
"api-key": string;
|
|
145
234
|
model?: string;
|
|
146
235
|
};
|
|
147
|
-
type
|
|
236
|
+
type GeminiProviderConfig = {
|
|
148
237
|
"api-key": string;
|
|
149
238
|
model?: string;
|
|
150
239
|
};
|
|
@@ -152,83 +241,73 @@ interface AIProviderConfig {
|
|
|
152
241
|
ollama: OllamaProviderConfig;
|
|
153
242
|
anthropic: AnthropicProviderConfig;
|
|
154
243
|
openai: OpenAIProviderConfig;
|
|
155
|
-
|
|
244
|
+
gemini: GeminiProviderConfig;
|
|
156
245
|
}
|
|
157
246
|
interface AIProvider {
|
|
158
247
|
get name(): string;
|
|
159
248
|
get model(): string;
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
249
|
+
createGenerationRequest(params: {
|
|
250
|
+
messages: Array<AxleMessage>;
|
|
251
|
+
system?: string;
|
|
252
|
+
tools?: Array<ToolDefinition>;
|
|
253
|
+
context: {
|
|
254
|
+
recorder?: Recorder;
|
|
255
|
+
};
|
|
256
|
+
options?: {
|
|
257
|
+
temperature?: number;
|
|
258
|
+
top_p?: number;
|
|
259
|
+
max_tokens?: number;
|
|
260
|
+
frequency_penalty?: number;
|
|
261
|
+
presence_penalty?: number;
|
|
262
|
+
stop?: string | string[];
|
|
263
|
+
[key: string]: any;
|
|
264
|
+
};
|
|
265
|
+
}): Promise<ModelResult>;
|
|
266
|
+
createStreamingRequest?(params: {
|
|
267
|
+
messages: Array<AxleMessage>;
|
|
268
|
+
system?: string;
|
|
269
|
+
tools?: Array<ToolDefinition>;
|
|
270
|
+
context: {
|
|
271
|
+
recorder?: Recorder;
|
|
272
|
+
};
|
|
273
|
+
options?: {
|
|
274
|
+
temperature?: number;
|
|
275
|
+
top_p?: number;
|
|
276
|
+
max_tokens?: number;
|
|
277
|
+
frequency_penalty?: number;
|
|
278
|
+
presence_penalty?: number;
|
|
279
|
+
stop?: string | string[];
|
|
280
|
+
[key: string]: any;
|
|
281
|
+
};
|
|
282
|
+
}): AsyncGenerator<AnyStreamChunk, void, unknown>;
|
|
173
283
|
}
|
|
174
|
-
|
|
175
|
-
interface AISuccessResponse {
|
|
284
|
+
interface ModelResponse {
|
|
176
285
|
type: "success";
|
|
286
|
+
role: "assistant";
|
|
177
287
|
id: string;
|
|
178
|
-
reason: StopReason;
|
|
179
|
-
message: ChatItemAssistant;
|
|
180
288
|
model: string;
|
|
181
|
-
|
|
289
|
+
text: string;
|
|
290
|
+
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall>;
|
|
291
|
+
finishReason: AxleStopReason;
|
|
182
292
|
usage: Stats;
|
|
183
293
|
raw: any;
|
|
184
294
|
}
|
|
185
|
-
interface
|
|
295
|
+
interface ModelError {
|
|
186
296
|
type: "error";
|
|
187
297
|
error: {
|
|
188
298
|
type: string;
|
|
189
299
|
message: string;
|
|
190
300
|
};
|
|
191
|
-
usage
|
|
192
|
-
raw
|
|
301
|
+
usage?: Stats;
|
|
302
|
+
raw?: any;
|
|
193
303
|
}
|
|
194
|
-
|
|
304
|
+
type ModelResult = ModelResponse | ModelError;
|
|
305
|
+
declare enum AxleStopReason {
|
|
195
306
|
Stop = 0,
|
|
196
307
|
Length = 1,
|
|
197
308
|
FunctionCall = 2,
|
|
198
|
-
Error = 3
|
|
199
|
-
|
|
200
|
-
type ChatItem = ChatItemUser | ChatItemAssistant | ChatItemToolCall;
|
|
201
|
-
interface ChatItemUser {
|
|
202
|
-
role: "user";
|
|
203
|
-
name?: string;
|
|
204
|
-
content: string | ChatContent[];
|
|
205
|
-
}
|
|
206
|
-
interface ChatItemAssistant {
|
|
207
|
-
role: "assistant";
|
|
208
|
-
content?: string;
|
|
209
|
-
toolCalls?: ToolCall[];
|
|
210
|
-
}
|
|
211
|
-
interface ChatItemToolCallResult {
|
|
212
|
-
id: string;
|
|
213
|
-
name: string;
|
|
214
|
-
content: string;
|
|
215
|
-
}
|
|
216
|
-
interface ChatItemToolCall {
|
|
217
|
-
role: "tool";
|
|
218
|
-
content: Array<ChatItemToolCallResult>;
|
|
219
|
-
}
|
|
220
|
-
type ChatContent = ChatContentText | ChatContentFile | ChatContentInstructions;
|
|
221
|
-
interface ChatContentText {
|
|
222
|
-
type: "text";
|
|
223
|
-
text: string;
|
|
224
|
-
}
|
|
225
|
-
interface ChatContentInstructions {
|
|
226
|
-
type: "instructions";
|
|
227
|
-
instructions: string;
|
|
228
|
-
}
|
|
229
|
-
interface ChatContentFile {
|
|
230
|
-
type: "file";
|
|
231
|
-
file: FileInfo;
|
|
309
|
+
Error = 3,
|
|
310
|
+
Custom = 4
|
|
232
311
|
}
|
|
233
312
|
|
|
234
313
|
declare class AxleError extends Error {
|
|
@@ -321,6 +400,211 @@ declare class Axle {
|
|
|
321
400
|
static loadFileContent(filePath: string, encoding: "base64"): Promise<Base64FileInfo>;
|
|
322
401
|
}
|
|
323
402
|
|
|
403
|
+
declare const Models$2: {
|
|
404
|
+
readonly CLAUDE_SONNET_4_5_20250929: "claude-sonnet-4-5-20250929";
|
|
405
|
+
readonly CLAUDE_SONNET_4_5_LATEST: "claude-sonnet-4-5";
|
|
406
|
+
readonly CLAUDE_HAIKU_4_5: "claude-haiku-4-5";
|
|
407
|
+
readonly CLAUDE_OPUS_4_1_20250805: "claude-opus-4-1-20250805";
|
|
408
|
+
readonly CLAUDE_OPUS_4_1_LATEST: "claude-opus-4-1";
|
|
409
|
+
readonly CLAUDE_OPUS_4_20250514: "claude-opus-4-20250514";
|
|
410
|
+
readonly CLAUDE_OPUS_4_LATEST: "claude-opus-4-0";
|
|
411
|
+
readonly CLAUDE_SONNET_4_20250514: "claude-sonnet-4-20250514";
|
|
412
|
+
readonly CLAUDE_SONNET_4_LATEST: "claude-sonnet-4-0";
|
|
413
|
+
readonly CLAUDE_3_7_SONNET_20250219: "claude-3-7-sonnet-20250219";
|
|
414
|
+
readonly CLAUDE_3_7_SONNET_LATEST: "claude-3-7-sonnet-latest";
|
|
415
|
+
readonly CLAUDE_3_5_SONNET_20241022: "claude-3-5-sonnet-20241022";
|
|
416
|
+
readonly CLAUDE_3_5_HAIKU_20241022: "claude-3-5-haiku-20241022";
|
|
417
|
+
readonly CLAUDE_3_5_HAIKU_LATEST: "claude-3-5-haiku-latest";
|
|
418
|
+
readonly CLAUDE_3_5_SONNET_20240620: "claude-3-5-sonnet-20240620";
|
|
419
|
+
};
|
|
420
|
+
declare const DEFAULT_MODEL$2: "claude-haiku-4-5";
|
|
421
|
+
|
|
422
|
+
declare const NAME$3: "anthorpic";
|
|
423
|
+
|
|
424
|
+
declare namespace index$3 {
|
|
425
|
+
export {
|
|
426
|
+
DEFAULT_MODEL$2 as DEFAULT_MODEL,
|
|
427
|
+
Models$2 as Models,
|
|
428
|
+
NAME$3 as NAME,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
declare const Models$1: {
|
|
433
|
+
readonly GEMINI_2_5_PRO: "gemini-2.5-pro";
|
|
434
|
+
readonly GEMINI_2_5_FLASH: "gemini-2.5-flash";
|
|
435
|
+
readonly GEMINI_2_5_FLASH_PREVIEW_05_20: "gemini-2.5-flash-preview-05-20";
|
|
436
|
+
readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
|
|
437
|
+
readonly GEMINI_2_5_FLASH_LITE_PREVIEW_06_17: "gemini-2.5-flash-lite-preview-06-17";
|
|
438
|
+
readonly GEMINI_2_5_FLASH_LIVE_PREVIEW: "gemini-live-2.5-flash-preview";
|
|
439
|
+
readonly GEMINI_2_5_FLASH_PREVIEW_NATIVE_AUDIO_DIALOG: "gemini-2.5-flash-preview-native-audio-dialog";
|
|
440
|
+
readonly GEMINI_2_5_FLASH_EXP_NATIVE_AUDIO_THINKING_DIALOG: "gemini-2.5-flash-exp-native-audio-thinking-dialog";
|
|
441
|
+
readonly GEMINI_2_5_FLASH_IMAGE_PREVIEW: "gemini-2.5-flash-image-preview";
|
|
442
|
+
readonly GEMINI_2_5_FLASH_PREVIEW_TTS: "gemini-2.5-flash-preview-tts";
|
|
443
|
+
readonly GEMINI_2_5_PRO_PREVIEW_TTS: "gemini-2.5-pro-preview-tts";
|
|
444
|
+
readonly GEMINI_2_0_FLASH: "gemini-2.0-flash";
|
|
445
|
+
readonly GEMINI_2_0_FLASH_001: "gemini-2.0-flash-001";
|
|
446
|
+
readonly GEMINI_2_0_FLASH_EXP: "gemini-2.0-flash-exp";
|
|
447
|
+
readonly GEMINI_2_0_FLASH_PREVIEW_IMAGE_GENERATION: "gemini-2.0-flash-preview-image-generation";
|
|
448
|
+
readonly GEMINI_2_0_FLASH_LITE: "gemini-2.0-flash-lite";
|
|
449
|
+
readonly GEMINI_2_0_FLASH_LITE_001: "gemini-2.0-flash-lite-001";
|
|
450
|
+
readonly GEMINI_2_0_FLASH_LIVE_001: "gemini-2.0-flash-live-001";
|
|
451
|
+
readonly GEMINI_1_5_PRO: "gemini-1.5-pro";
|
|
452
|
+
readonly GEMINI_1_5_PRO_LATEST: "gemini-1.5-pro-latest";
|
|
453
|
+
readonly GEMINI_1_5_PRO_001: "gemini-1.5-pro-001";
|
|
454
|
+
readonly GEMINI_1_5_PRO_002: "gemini-1.5-pro-002";
|
|
455
|
+
readonly GEMINI_1_5_FLASH: "gemini-1.5-flash";
|
|
456
|
+
readonly GEMINI_1_5_FLASH_LATEST: "gemini-1.5-flash-latest";
|
|
457
|
+
readonly GEMINI_1_5_FLASH_001: "gemini-1.5-flash-001";
|
|
458
|
+
readonly GEMINI_1_5_FLASH_002: "gemini-1.5-flash-002";
|
|
459
|
+
readonly GEMINI_1_5_FLASH_8B: "gemini-1.5-flash-8b";
|
|
460
|
+
readonly GEMINI_1_5_FLASH_8B_LATEST: "gemini-1.5-flash-8b-latest";
|
|
461
|
+
readonly GEMINI_1_5_FLASH_8B_001: "gemini-1.5-flash-8b-001";
|
|
462
|
+
readonly GEMMA_3N_E4B_IT: "gemma-3n-e4b-it";
|
|
463
|
+
readonly GEMMA_3_1B_IT: "gemma-3-1b-it";
|
|
464
|
+
readonly GEMMA_3_4B_IT: "gemma-3-4b-it";
|
|
465
|
+
readonly GEMMA_3_12B_IT: "gemma-3-12b-it";
|
|
466
|
+
readonly GEMMA_3_27B_IT: "gemma-3-27b-it";
|
|
467
|
+
readonly LEARNLM_2_0_FLASH_EXPERIMENTAL: "learnlm-2.0-flash-experimental";
|
|
468
|
+
readonly EMBEDDING_001: "embedding-001";
|
|
469
|
+
readonly TEXT_EMBEDDING_004: "text-embedding-004";
|
|
470
|
+
};
|
|
471
|
+
declare const DEFAULT_MODEL$1: "gemini-2.5-flash";
|
|
472
|
+
|
|
473
|
+
declare const NAME$2: "Gemini";
|
|
474
|
+
|
|
475
|
+
declare namespace index$2 {
|
|
476
|
+
export {
|
|
477
|
+
DEFAULT_MODEL$1 as DEFAULT_MODEL,
|
|
478
|
+
Models$1 as Models,
|
|
479
|
+
NAME$2 as NAME,
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
declare const DEFAULT_OLLAMA_URL = "http://localhost:11434";
|
|
484
|
+
declare const NAME$1: "Ollama";
|
|
485
|
+
|
|
486
|
+
declare const index$1_DEFAULT_OLLAMA_URL: typeof DEFAULT_OLLAMA_URL;
|
|
487
|
+
declare namespace index$1 {
|
|
488
|
+
export {
|
|
489
|
+
index$1_DEFAULT_OLLAMA_URL as DEFAULT_OLLAMA_URL,
|
|
490
|
+
NAME$1 as NAME,
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
declare const Models: {
|
|
495
|
+
readonly GPT_5: "gpt-5";
|
|
496
|
+
readonly GPT_5_MINI: "gpt-5-mini";
|
|
497
|
+
readonly GPT_5_NANO: "gpt-5-nano";
|
|
498
|
+
readonly GPT_5_CHAT_LATEST: "gpt-5-chat-latest";
|
|
499
|
+
readonly GPT_5_PRO: "gpt-5-pro";
|
|
500
|
+
readonly GPT_5_CODEX: "gpt-5-codex";
|
|
501
|
+
readonly GPT_4_5_PREVIEW: "gpt-4.5-preview";
|
|
502
|
+
readonly GPT_4_5_PREVIEW_2025_02_27: "gpt-4.5-preview-2025-02-27";
|
|
503
|
+
readonly GPT_4_1: "gpt-4.1";
|
|
504
|
+
readonly GPT_4_1_2025_04_14: "gpt-4.1-2025-04-14";
|
|
505
|
+
readonly GPT_4_1_MINI: "gpt-4.1-mini";
|
|
506
|
+
readonly GPT_4_1_MINI_2025_04_14: "gpt-4.1-mini-2025-04-14";
|
|
507
|
+
readonly GPT_4_1_NANO: "gpt-4.1-nano";
|
|
508
|
+
readonly GPT_4_1_NANO_2025_04_14: "gpt-4.1-nano-2025-04-14";
|
|
509
|
+
readonly GPT_4O: "gpt-4o";
|
|
510
|
+
readonly GPT_4O_2024_05_13: "gpt-4o-2024-05-13";
|
|
511
|
+
readonly GPT_4O_2024_08_06: "gpt-4o-2024-08-06";
|
|
512
|
+
readonly GPT_4O_2024_11_20: "gpt-4o-2024-11-20";
|
|
513
|
+
readonly GPT_4O_MINI: "gpt-4o-mini";
|
|
514
|
+
readonly GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18";
|
|
515
|
+
readonly GPT_4O_AUDIO_PREVIEW: "gpt-4o-audio-preview";
|
|
516
|
+
readonly GPT_4O_AUDIO_PREVIEW_2024_10_01: "gpt-4o-audio-preview-2024-10-01";
|
|
517
|
+
readonly GPT_4O_AUDIO_PREVIEW_2024_12_17: "gpt-4o-audio-preview-2024-12-17";
|
|
518
|
+
readonly GPT_4O_AUDIO_PREVIEW_2025_06_03: "gpt-4o-audio-preview-2025-06-03";
|
|
519
|
+
readonly GPT_4O_MINI_AUDIO_PREVIEW: "gpt-4o-mini-audio-preview";
|
|
520
|
+
readonly GPT_4O_MINI_AUDIO_PREVIEW_2024_12_17: "gpt-4o-mini-audio-preview-2024-12-17";
|
|
521
|
+
readonly GPT_REALTIME: "gpt-realtime";
|
|
522
|
+
readonly GPT_REALTIME_MINI: "gpt-realtime-mini";
|
|
523
|
+
readonly GPT_4O_REALTIME_PREVIEW: "gpt-4o-realtime-preview";
|
|
524
|
+
readonly GPT_4O_REALTIME_PREVIEW_2024_10_01: "gpt-4o-realtime-preview-2024-10-01";
|
|
525
|
+
readonly GPT_4O_REALTIME_PREVIEW_2024_12_17: "gpt-4o-realtime-preview-2024-12-17";
|
|
526
|
+
readonly GPT_4O_REALTIME_PREVIEW_2025_06_03: "gpt-4o-realtime-preview-2025-06-03";
|
|
527
|
+
readonly GPT_4O_MINI_REALTIME_PREVIEW: "gpt-4o-mini-realtime-preview";
|
|
528
|
+
readonly GPT_4O_MINI_REALTIME_PREVIEW_2024_12_17: "gpt-4o-mini-realtime-preview-2024-12-17";
|
|
529
|
+
readonly GPT_4O_SEARCH_PREVIEW: "gpt-4o-search-preview";
|
|
530
|
+
readonly GPT_4O_SEARCH_PREVIEW_2025_03_11: "gpt-4o-search-preview-2025-03-11";
|
|
531
|
+
readonly GPT_4O_MINI_SEARCH_PREVIEW: "gpt-4o-mini-search-preview";
|
|
532
|
+
readonly GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11: "gpt-4o-mini-search-preview-2025-03-11";
|
|
533
|
+
readonly GPT_4O_TRANSCRIBE: "gpt-4o-transcribe";
|
|
534
|
+
readonly GPT_4O_MINI_TRANSCRIBE: "gpt-4o-mini-transcribe";
|
|
535
|
+
readonly GPT_4O_MINI_TTS: "gpt-4o-mini-tts";
|
|
536
|
+
readonly GPT_IMAGE_1: "gpt-image-1";
|
|
537
|
+
readonly GPT_IMAGE_1_MINI: "gpt-image-1-mini";
|
|
538
|
+
readonly O4_MINI: "o4-mini";
|
|
539
|
+
readonly O4_MINI_2025_04_16: "o4-mini-2025-04-16";
|
|
540
|
+
readonly O3: "o3";
|
|
541
|
+
readonly O3_PRO: "o3-pro";
|
|
542
|
+
readonly O3_MINI: "o3-mini";
|
|
543
|
+
readonly O3_MINI_2025_01_31: "o3-mini-2025-01-31";
|
|
544
|
+
readonly O1_PRO: "o1-pro";
|
|
545
|
+
readonly O1_PRO_2025_03_19: "o1-pro-2025-03-19";
|
|
546
|
+
readonly O1: "o1";
|
|
547
|
+
readonly O1_2024_12_17: "o1-2024-12-17";
|
|
548
|
+
readonly O1_MINI: "o1-mini";
|
|
549
|
+
readonly O1_MINI_2024_09_12: "o1-mini-2024-09-12";
|
|
550
|
+
readonly O1_PREVIEW: "o1-preview";
|
|
551
|
+
readonly O1_PREVIEW_2024_09_12: "o1-preview-2024-09-12";
|
|
552
|
+
readonly GPT_OSS_120B: "gpt-oss-120b";
|
|
553
|
+
readonly GPT_OSS_7B: "gpt-oss-7b";
|
|
554
|
+
readonly SORA_2: "sora-2";
|
|
555
|
+
readonly SORA_2025_05_02: "sora-2025-05-02";
|
|
556
|
+
readonly CODEX_MINI: "codex-mini";
|
|
557
|
+
readonly COMPUTER_USE_PREVIEW: "computer-use-preview";
|
|
558
|
+
};
|
|
559
|
+
declare const DEFAULT_MODEL: "gpt-5";
|
|
560
|
+
|
|
561
|
+
declare const NAME: "OpenAI";
|
|
562
|
+
|
|
563
|
+
declare const index_DEFAULT_MODEL: typeof DEFAULT_MODEL;
|
|
564
|
+
declare const index_Models: typeof Models;
|
|
565
|
+
declare const index_NAME: typeof NAME;
|
|
566
|
+
declare namespace index {
|
|
567
|
+
export {
|
|
568
|
+
index_DEFAULT_MODEL as DEFAULT_MODEL,
|
|
569
|
+
index_Models as Models,
|
|
570
|
+
index_NAME as NAME,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
interface GenerateOptions {
|
|
575
|
+
temperature?: number;
|
|
576
|
+
top_p?: number;
|
|
577
|
+
max_tokens?: number;
|
|
578
|
+
frequency_penalty?: number;
|
|
579
|
+
presence_penalty?: number;
|
|
580
|
+
stop?: string | string[];
|
|
581
|
+
[key: string]: any;
|
|
582
|
+
}
|
|
583
|
+
interface GenerateProps {
|
|
584
|
+
provider: AIProvider;
|
|
585
|
+
messages: Array<AxleMessage>;
|
|
586
|
+
system?: string;
|
|
587
|
+
tools?: Array<ToolDefinition>;
|
|
588
|
+
recorder?: Recorder;
|
|
589
|
+
options?: GenerateOptions;
|
|
590
|
+
}
|
|
591
|
+
declare function generate(props: GenerateProps): Promise<ModelResult>;
|
|
592
|
+
|
|
593
|
+
interface StreamProps {
|
|
594
|
+
provider: AIProvider;
|
|
595
|
+
messages: Array<AxleMessage>;
|
|
596
|
+
system?: string;
|
|
597
|
+
tools?: Array<ToolDefinition>;
|
|
598
|
+
recorder?: Recorder;
|
|
599
|
+
options?: GenerateOptions;
|
|
600
|
+
}
|
|
601
|
+
interface StreamResult {
|
|
602
|
+
get final(): Promise<ModelResult>;
|
|
603
|
+
get current(): AxleAssistantMessage;
|
|
604
|
+
[Symbol.asyncIterator](): AsyncIterator<AnyStreamChunk>;
|
|
605
|
+
}
|
|
606
|
+
declare function stream(props: StreamProps): StreamResult;
|
|
607
|
+
|
|
324
608
|
declare enum ResultType {
|
|
325
609
|
String = "string",
|
|
326
610
|
List = "string[]",
|
|
@@ -530,4 +814,20 @@ declare class ConsoleWriter implements RecorderWriter {
|
|
|
530
814
|
destroy(): void;
|
|
531
815
|
}
|
|
532
816
|
|
|
533
|
-
|
|
817
|
+
declare class Conversation {
|
|
818
|
+
system: string;
|
|
819
|
+
private _messages;
|
|
820
|
+
constructor(messages?: AxleMessage[]);
|
|
821
|
+
get messages(): AxleMessage[];
|
|
822
|
+
addSystem(message: string): void;
|
|
823
|
+
addUser(message: string): void;
|
|
824
|
+
addUser(parts: AxleUserMessage["content"]): void;
|
|
825
|
+
addAssistant(message: string): void;
|
|
826
|
+
addAssistant(params: Omit<AxleAssistantMessage, "role">): void;
|
|
827
|
+
addToolResults(input: Array<AxleToolCallResult>): void;
|
|
828
|
+
latest(): AxleMessage | undefined;
|
|
829
|
+
toString(): string;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
export { index$3 as Anthropic, Axle, AxleStopReason, ChainOfThought, ConsoleWriter, Conversation, index$2 as Gemini, Instruct, LogLevel, index$1 as Ollama, index as OpenAI, WriteOutputTask, concurrentWorkflow, dagWorkflow, generate, serialWorkflow, stream };
|
|
833
|
+
export type { AIProvider, AxleAssistantMessage, AxleMessage, AxleToolCallMessage, AxleToolCallResult, AxleUserMessage, ContentPart, ContentPartFile, ContentPartText, ContentPartThinking, ContentPartToolCall, DAGDefinition, DAGWorkflowOptions, FileInfo, SerializedExecutionResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var i=(o,t)=>m(o,"name",{value:t,configurable:!0});import{R as g,A as n,g as f,s as p,d,l as h,D as w,M as x,N as k,a as E,b as y,c as L,e as b,f as A,h as P,i as v,j as M,k as S,m as T,n as _}from"./consoleWriter-Cx-CPHU8.js";import{q as tt,C as et,r as rt,I as st,L as at,W as it,p as nt,o as ot}from"./consoleWriter-Cx-CPHU8.js";import"@anthropic-ai/sdk";import*as O from"zod";import"@google/genai";import"openai";import"serialize-error";import"fs/promises";import"glob";import"node:fs/promises";import"node:path";import"chalk";import"node:readline";class D{static{i(this,"StreamParts")}listeners={start:new Set,text:new Set,thinking:new Set,"tool-call":new Set,"tool-call-complete":new Set,complete:new Set};isComplete=!1;on(t,e){return this.listeners[t].add(e),this}emit(t,...e){const r=this.listeners[t];if(r)for(const a of r)a(...e)}id="";model="";parts=[];finishReason;stats;get partsLength(){return this.parts.length}get currentId(){return this.id}start(t,e){this.id=t,this.model=e,this.emit("start",t)}complete(t,e){if(this.isComplete)return;this.finishReason=t,this.stats=e,this.isComplete=!0;const r=this.parts.filter(s=>s.type==="text").map(s=>s.text).join(""),a={type:"success",role:"assistant",id:this.id,model:this.model,content:this.parts,finishReason:t,usage:e,text:r,raw:{}};this.emit("complete",a)}error(t,e,r,a){if(this.isComplete)return;this.isComplete=!0;const s={type:"error",error:{type:t,message:e},usage:r,raw:a};this.emit("complete",s)}createText(t,e){if(t<this.parts.length)throw new Error(`Cannot create text at index ${t} because it already exists`);this.parts.push({type:"text",text:e}),this.emit("text",e)}updateText(t,e){const r=this.getPart(t,"text");r&&(r.text+=e,this.emit("text",r.text))}createToolCall(t,e,r){if(t<this.parts.length)throw new Error(`Cannot create tool-call at index ${t} because it already exists`);this.parts.push({type:"tool-call",id:e,name:r,parameters:{}}),this.emit("tool-call",e,r)}completeToolCall(t,e){const r=this.getPart(t,"tool-call");r&&(r.parameters=e,this.emit("tool-call-complete",r.id,r.name,e))}createThinking(t,e){if(t<this.parts.length)throw new Error(`Cannot create thinking at index ${t} because it already exists`);this.parts.push({type:"thinking",text:e}),this.emit("thinking",e)}updateThinking(t,e){const r=this.getPart(t,"thinking");r&&(r.text+=e,this.emit("thinking",e))}getPart(t,e){if(t<0||t>=this.parts.length)return null;const r=this.parts[t];return r.type===e?r:null}get currentMessage(){return{role:"assistant",content:[...this.parts],id:this.id,model:this.model,...this.finishReason?{finishReason:this.finishReason}:{}}}}function R(o){const{provider:t,messages:e,system:r,tools:a,recorder:s,options:c}=o,u=t.createStreamingRequest?.({messages:e,system:r,tools:a,context:{recorder:s},options:c});return console.log(u),new C(u)}i(R,"stream");class C{static{i(this,"StreamResultImpl")}constructor(t){this.streamSource=t,this.streamParts=new D,this.finalPromise=new Promise((e,r)=>{this.resolveFinal=e,this.rejectFinal=r}),this.streamParts.on("complete",e=>{this.resolveFinal?.(e)}),this.startProcessing()}streamParts;finalPromise;resolveFinal;rejectFinal;chunkListeners=new Set;processingStarted=!1;async*[Symbol.asyncIterator](){const t=[];let e=null,r=!1;const a=i(s=>{e?(e(s),e=null):t.push(s)},"listener");this.chunkListeners.add(a);try{for(;!r;){let s;t.length>0?s=t.shift():s=await new Promise(c=>{e=c}),s===null?r=!0:(yield s,(s.type==="complete"||s.type==="error")&&(r=!0))}}finally{this.chunkListeners.delete(a)}}async startProcessing(){if(!this.processingStarted){this.processingStarted=!0;try{for await(const t of this.streamSource)switch(this.chunkListeners.forEach(e=>e(t)),t.type){case"start":this.streamParts.start(t.id,t.data.model);break;case"text":const e=t.data.index;e>=this.streamParts.partsLength?this.streamParts.createText(e,t.data.text):this.streamParts.updateText(e,t.data.text);break;case"thinking-start":this.streamParts.createThinking(t.data.index,"");break;case"thinking-delta":this.streamParts.updateThinking(t.data.index,t.data.text);break;case"tool-call-start":this.streamParts.createToolCall(t.data.index,t.data.id,t.data.name);break;case"tool-call-complete":this.streamParts.completeToolCall(t.data.index,t.data.arguments);break;case"complete":this.streamParts.complete(t.data.finishReason,t.data.usage);break;case"error":this.streamParts.error(t.data.type,t.data.message,t.data.usage,t.data.raw);return}}catch(t){this.rejectFinal?.(t instanceof Error?t:new Error(String(t)))}finally{this.chunkListeners.forEach(t=>t(null))}}}get final(){return this.finalPromise}get current(){return this.streamParts.currentMessage}}class F{static{i(this,"Axle")}provider;stats={in:0,out:0};variables={};recorder=new g;constructor(t){if(Object.entries(t).length!==1)throw new n("Must have exactly one config");try{const e=Object.keys(t)[0],r=t[e];this.provider=f(e,r)}catch(e){throw e instanceof n?e:new n("Failed to initialize provider",{code:"PROVIDER_INIT_ERROR",cause:e instanceof Error?e:new Error(String(e))})}}addWriter(t){this.recorder.subscribe(t)}async execute(...t){try{let e;return e=await p(...t).execute({provider:this.provider,variables:this.variables,stats:this.stats,recorder:this.recorder}),e}catch(e){const r=e instanceof n?e:new n("Execution failed",{cause:e instanceof Error?e:new Error(String(e))});return this.recorder.error?.log(r),{response:null,error:r,success:!1}}}async executeDAG(t,e={},r){try{return await d(t,r).execute({provider:this.provider,variables:{...this.variables,...e},stats:this.stats,recorder:this.recorder})}catch(a){const s=a instanceof n?a:new n("DAG execution failed",{cause:a instanceof Error?a:new Error(String(a))});return this.recorder.error?.log(s),{response:null,error:s,success:!1}}}get logs(){return this.recorder.getLogs()}static async loadFileContent(t,e){return e==="utf-8"?h(t,"utf-8"):e==="base64"?h(t,"base64"):h(t)}}var N=Object.freeze({__proto__:null,DEFAULT_MODEL:w,Models:x,NAME:k}),I=Object.freeze({__proto__:null,DEFAULT_MODEL:E,Models:y,NAME:L}),$=Object.freeze({__proto__:null,DEFAULT_OLLAMA_URL:b,NAME:A}),j=Object.freeze({__proto__:null,DEFAULT_MODEL:P,Models:v,NAME:M});class l extends S{static{i(this,"ChainOfThought")}constructor(t,e){super(t,e)}static with(t,e){if(!e)return new l(t,{response:O.string()});if(T(e))return new l(t,e);{const r=_(e);return new l(t,r)}}createInstructions(t=""){return super.createInstructions(`Let's think step by step. Use <thinking></thinking> tags to show your reasoning and thought process.
|
|
2
2
|
|
|
3
|
-
`)}finalize(e
|
|
3
|
+
`)}finalize(t,e={}){const r=super.finalize(t,e),a=this.parseTaggedSections(t);let s="thinking";return"thinking"in a.tags||("think"in a.tags?(s="think",e.recorder?.warn?.log("No <thinking> section found in the response but found <think> instead. This may be a limitation of the model or prompt.")):e.recorder?.warn?.log("No <thinking> section found in the response. Please ensure your response includes a <thinking> tag.")),{...r,thinking:a.tags[s]||""}}}export{N as Anthropic,F as Axle,tt as AxleStopReason,l as ChainOfThought,et as ConsoleWriter,rt as Conversation,I as Gemini,st as Instruct,at as LogLevel,$ as Ollama,j as OpenAI,it as WriteOutputTask,nt as concurrentWorkflow,d as dagWorkflow,ot as generate,p as serialWorkflow,R as stream};
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fifthrevision/axle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
|
-
"url": "https://github.com/johncch/axle.git"
|
|
6
|
+
"url": "git+https://github.com/johncch/axle.git"
|
|
7
7
|
},
|
|
8
8
|
"description": "axle is a command line tool for running workflows against LLM APIs.",
|
|
9
9
|
"type": "module",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
18
|
"bin": {
|
|
19
|
-
"axle": "
|
|
19
|
+
"axle": "dist/cli.js"
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"dist"
|
|
@@ -28,32 +28,35 @@
|
|
|
28
28
|
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
|
29
29
|
"get-models": "npx tsx scripts/getModels.ts",
|
|
30
30
|
"prompt-scenarios": "npx tsx ./scripts/prompt.scenarios.ts",
|
|
31
|
-
"test-providers": "npx tsx ./scripts/testProviders.ts"
|
|
31
|
+
"test-providers": "npx tsx ./scripts/testProviders.ts",
|
|
32
|
+
"sanity-check": "npx tsx ./scripts/sanity-check.ts",
|
|
33
|
+
"release": "npm test && npm run build && npm version"
|
|
32
34
|
},
|
|
33
35
|
"author": "",
|
|
34
36
|
"license": "ISC",
|
|
35
37
|
"dependencies": {
|
|
36
|
-
"@anthropic-ai/sdk": "^0",
|
|
37
|
-
"@commander-js/extra-typings": "^14",
|
|
38
|
-
"@google/genai": "^1.
|
|
39
|
-
"chalk": "^5.
|
|
40
|
-
"commander": "^14",
|
|
41
|
-
"glob": "^11.0.
|
|
42
|
-
"openai": "^
|
|
38
|
+
"@anthropic-ai/sdk": "^0.68.0",
|
|
39
|
+
"@commander-js/extra-typings": "^14.0.0",
|
|
40
|
+
"@google/genai": "^1.29.0",
|
|
41
|
+
"chalk": "^5.6.2",
|
|
42
|
+
"commander": "^14.0.2",
|
|
43
|
+
"glob": "^11.0.3",
|
|
44
|
+
"openai": "^6.8.1",
|
|
43
45
|
"serialize-error": "^12.0.0",
|
|
44
|
-
"yaml": "^2.
|
|
45
|
-
"zod": "^
|
|
46
|
+
"yaml": "^2.8.1",
|
|
47
|
+
"zod": "^4.1.12"
|
|
46
48
|
},
|
|
47
49
|
"devDependencies": {
|
|
48
|
-
"@
|
|
49
|
-
"
|
|
50
|
-
"
|
|
50
|
+
"@jest/globals": "^29.7.0",
|
|
51
|
+
"@types/jest": "^29.5.14",
|
|
52
|
+
"dotenv": "^17.2.3",
|
|
53
|
+
"husky": "^9.1.7",
|
|
51
54
|
"jest": "^29.7.0",
|
|
52
|
-
"pkgroll": "^2.
|
|
53
|
-
"prettier": "^3.
|
|
54
|
-
"prettier-plugin-organize-imports": "^4.
|
|
55
|
-
"ts-jest": "^29.
|
|
56
|
-
"tsx": "^4.
|
|
57
|
-
"typescript": "^5.
|
|
55
|
+
"pkgroll": "^2.20.1",
|
|
56
|
+
"prettier": "^3.6.2",
|
|
57
|
+
"prettier-plugin-organize-imports": "^4.3.0",
|
|
58
|
+
"ts-jest": "^29.4.5",
|
|
59
|
+
"tsx": "^4.20.6",
|
|
60
|
+
"typescript": "^5.9.3"
|
|
58
61
|
}
|
|
59
62
|
}
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var u=(t,e)=>Ne(t,"name",{value:e,configurable:!0});import Re from"@anthropic-ai/sdk";import{GoogleGenAI as Oe,Type as be,FinishReason as P}from"@google/genai";import ke from"openai";import{serializeError as Me}from"serialize-error";import{readFile as $e,access as Ge,constants as xe}from"fs/promises";import{glob as ae}from"glob";import{readFile as C,access as ce,stat as Le,writeFile as Ce,mkdir as Fe}from"node:fs/promises";import{resolve as ee,extname as ue,dirname as De}from"node:path";import*as I from"zod/v4";import w from"chalk";import le from"node:readline";class A extends Error{static{u(this,"AxleError")}code;id;details;constructor(e,s){super(e,{cause:s?.cause}),this.name=this.constructor.name,this.code=s?.code||"AXLE_ERROR",this.id=s?.id,this.details=s?.details,Object.setPrototypeOf(this,A.prototype)}}const O={CLAUDE_OPUS_4_20250514:"claude-opus-4-20250514",CLAUDE_OPUS_4_LATEST:"claude-opus-4-0",CLAUDE_SONNET_4_20250514:"claude-sonnet-4-20250514",CLAUDE_SONNET_4_LATEST:"claude-sonnet-4-0",CLAUDE_3_7_SONNET_20250219:"claude-3-7-sonnet-20250219",CLAUDE_3_7_SONNET_LATEST:"claude-3-7-sonnet-latest",CLAUDE_3_5_HAIKU_20241022:"claude-3-5-haiku-20241022",CLAUDE_3_5_HAIKU_LATEST:"claude-3-5-haiku-latest"},fe=[O.CLAUDE_3_7_SONNET_LATEST,O.CLAUDE_3_7_SONNET_20250219,O.CLAUDE_3_5_HAIKU_LATEST,O.CLAUDE_3_5_HAIKU_20241022,O.CLAUDE_SONNET_4_LATEST,O.CLAUDE_SONNET_4_20250514,O.CLAUDE_OPUS_4_LATEST,O.CLAUDE_OPUS_4_20250514];class Ue{static{u(this,"Chat")}system;messages=[];tools=[];setToolSchemas(e){this.tools=e}addSystem(e){this.system=e}addUser(e,s,n){let o,r=[];if(typeof s=="string"?(o=s,r=n||[]):Array.isArray(s)&&(r=s),!o&&r.length===0){this.messages.push({role:"user",content:e});return}const i=[{type:"text",text:e}];o&&i.push({type:"instructions",instructions:o});for(const a of r)i.push({type:"file",file:a});this.messages.push({role:"user",content:i})}addAssistant(e,s){this.messages.push({role:"assistant",content:e,...s&&{toolCalls:s}})}addTools(e){this.messages.push({role:"tool",content:e})}hasFiles(){return this.messages.some(e=>Array.isArray(e.content)&&e.content.some(s=>s.type==="file"))}latest(){return this.messages[this.messages.length-1]}toString(){return JSON.stringify({system:this.system,messages:this.messages,tools:this.tools})}}function H(t,e=`
|
|
2
|
-
|
|
3
|
-
`){if(typeof t=="string")return t;const s=t.filter(o=>o.type==="text").map(o=>o.text),n=t.filter(o=>o.type==="instructions").map(o=>o.instructions);return s.length===0&&n.length===0?null:[...s,...n].join(e)}u(H,"getTextAndInstructions");function He(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
4
|
-
|
|
5
|
-
`)}u(He,"getTextContent");function We(t){if(typeof t=="string")return null;const e=t.filter(s=>s.type==="instructions").map(s=>s.instructions);return e.length>0?e.join(`
|
|
6
|
-
|
|
7
|
-
`):null}u(We,"getInstructions");function W(t){return typeof t=="string"?[]:t.filter(e=>e.type==="file"&&e.file.type==="document").map(e=>e.file)}u(W,"getDocuments");function F(t){return typeof t=="string"?[]:t.filter(e=>e.type==="file"&&e.file.type==="image").map(e=>e.file)}u(F,"getImages");var E=(t=>(t[t.Stop=0]="Stop",t[t.Length=1]="Length",t[t.FunctionCall=2]="FunctionCall",t[t.Error=3]="Error",t))(E||{});const Be=O.CLAUDE_SONNET_4_LATEST;class Je{static{u(this,"AnthropicProvider")}name="Anthropic";client;model;constructor(e,s){this.model=s??Be,this.client=new Re({apiKey:e})}createChatRequest(e,s={}){const{recorder:n}=s;return e.hasFiles()&&!fe.includes(this.model)&&n?.warn?.log(`Model ${this.model} may not support multimodal content. Use one of: ${fe.join(", ")}`),new Xe(this,e)}}class Xe{static{u(this,"AnthropicChatRequest")}constructor(e,s){this.provider=e,this.chat=s}async execute(e){const{recorder:s}=e,{client:n,model:o}=this.provider,r={model:o,max_tokens:4096,...qe(this.chat)};s?.debug?.log(r);let i;try{const a=await n.messages.create(r);i=Ke(a)}catch(a){i={type:"error",error:{type:a.error.error.type??"Undetermined",message:a.error.error.message??"Unexpected error from Anthropic"},usage:{in:0,out:0},raw:a}}return s?.debug?.log(i),i}}function pe(t){switch(t){case"max_tokens":return E.Length;case"end_turn":return E.Stop;case"stop_sequence":return E.Stop;case"tool_use":return E.FunctionCall;default:return E.Error}}u(pe,"getStopReason$2");function qe(t){const e=t.messages.map(n=>{if(n.role==="assistant"){const o=[];return o.push({type:"text",text:n.content}),n.toolCalls&&o.push(...n.toolCalls.map(r=>({type:"tool_use",id:r.id,name:r.name,input:r.arguments}))),{role:"assistant",content:o}}if(n.role==="tool")return{role:"user",content:n.content.map(o=>({type:"tool_result",tool_use_id:o.id,content:o.content}))};if(typeof n.content=="string")return{role:"user",content:n.content};{const o=[],r=H(n.content);r&&o.push({type:"text",text:r});const i=F(n.content);i.length>0&&o.push(...i.map(c=>({type:"image",source:{type:"base64",media_type:c.mimeType,data:c.base64}})));const a=W(n.content);return a.length>0&&o.push(...a.filter(c=>c.mimeType==="application/pdf").map(c=>({type:"document",source:{type:"base64",media_type:"application/pdf",data:c.base64}}))),{role:"user",content:o}}}),s=t.tools.map(n=>({name:n.name,description:n.description,input_schema:n.parameters}));return{system:t.system,messages:e,tools:s}}u(qe,"prepareRequest$4");function Ke(t){const e=pe(t.stop_reason);if(e===E.Error)return{type:"error",error:{type:"Uncaught error",message:"Stop reason is not recognized."},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t};if(e===E.FunctionCall){const s=t.content[0],n=s.type==="text"?s.text:"",o=t.content.slice(1).map(r=>{if(r.type==="tool_use")return{id:r.id,name:r.name,arguments:r.input}}).filter(r=>r!==null);return{type:"success",id:t.id,model:t.model,reason:E.FunctionCall,message:{role:t.role,content:n,toolCalls:o},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const s=t.content[0];if(s.type=="text")return{type:"success",id:t.id,model:t.model,reason:pe(t.stop_reason),message:{role:t.role,content:s.text},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}u(Ke,"translate");const p={GEMINI_1_0_PRO_VISION_LATEST:"gemini-1.0-pro-vision-latest",GEMINI_PRO_VISION:"gemini-pro-vision",GEMINI_1_5_PRO_LATEST:"gemini-1.5-pro-latest",GEMINI_1_5_PRO_001:"gemini-1.5-pro-001",GEMINI_1_5_PRO_002:"gemini-1.5-pro-002",GEMINI_1_5_PRO:"gemini-1.5-pro",GEMINI_1_5_FLASH_LATEST:"gemini-1.5-flash-latest",GEMINI_1_5_FLASH_001:"gemini-1.5-flash-001",GEMINI_1_5_FLASH_001_TUNING:"gemini-1.5-flash-001-tuning",GEMINI_1_5_FLASH:"gemini-1.5-flash",GEMINI_1_5_FLASH_002:"gemini-1.5-flash-002",GEMINI_1_5_FLASH_8B:"gemini-1.5-flash-8b",GEMINI_1_5_FLASH_8B_001:"gemini-1.5-flash-8b-001",GEMINI_1_5_FLASH_8B_LATEST:"gemini-1.5-flash-8b-latest",GEMINI_1_5_FLASH_8B_EXP_0827:"gemini-1.5-flash-8b-exp-0827",GEMINI_1_5_FLASH_8B_EXP_0924:"gemini-1.5-flash-8b-exp-0924",GEMINI_2_5_PRO_EXP_03_25:"gemini-2.5-pro-exp-03-25",GEMINI_2_5_PRO_PREVIEW_03_25:"gemini-2.5-pro-preview-03-25",GEMINI_2_5_FLASH_PREVIEW_04_17:"gemini-2.5-flash-preview-04-17",GEMINI_2_5_FLASH_PREVIEW_05_20:"gemini-2.5-flash-preview-05-20",GEMINI_2_5_FLASH_PREVIEW_04_17_THINKING:"gemini-2.5-flash-preview-04-17-thinking",GEMINI_2_5_PRO_PREVIEW_05_06:"gemini-2.5-pro-preview-05-06",GEMINI_2_5_PRO_PREVIEW_06_05:"gemini-2.5-pro-preview-06-05",GEMINI_2_0_FLASH_EXP:"gemini-2.0-flash-exp",GEMINI_2_0_FLASH:"gemini-2.0-flash",GEMINI_2_0_FLASH_001:"gemini-2.0-flash-001",GEMINI_2_0_FLASH_EXP_IMAGE_GENERATION:"gemini-2.0-flash-exp-image-generation",GEMINI_2_0_FLASH_LITE_001:"gemini-2.0-flash-lite-001",GEMINI_2_0_FLASH_LITE:"gemini-2.0-flash-lite",GEMINI_2_0_FLASH_PREVIEW_IMAGE_GENERATION:"gemini-2.0-flash-preview-image-generation",GEMINI_2_0_FLASH_LITE_PREVIEW_02_05:"gemini-2.0-flash-lite-preview-02-05",GEMINI_2_0_FLASH_LITE_PREVIEW:"gemini-2.0-flash-lite-preview",GEMINI_2_0_PRO_EXP:"gemini-2.0-pro-exp",GEMINI_2_0_PRO_EXP_02_05:"gemini-2.0-pro-exp-02-05",GEMINI_EXP_1206:"gemini-exp-1206",GEMINI_2_0_FLASH_THINKING_EXP_01_21:"gemini-2.0-flash-thinking-exp-01-21",GEMINI_2_0_FLASH_THINKING_EXP:"gemini-2.0-flash-thinking-exp",GEMINI_2_0_FLASH_THINKING_EXP_1219:"gemini-2.0-flash-thinking-exp-1219",GEMINI_2_5_FLASH_PREVIEW_TTS:"gemini-2.5-flash-preview-tts",GEMINI_2_5_PRO_PREVIEW_TTS:"gemini-2.5-pro-preview-tts",LEARNLM_2_0_FLASH_EXPERIMENTAL:"learnlm-2.0-flash-experimental",GEMMA_3_1B_IT:"gemma-3-1b-it",GEMMA_3_4B_IT:"gemma-3-4b-it",GEMMA_3_12B_IT:"gemma-3-12b-it",GEMMA_3_27B_IT:"gemma-3-27b-it",GEMMA_3N_E4B_IT:"gemma-3n-e4b-it"},_e=[p.GEMINI_1_0_PRO_VISION_LATEST,p.GEMINI_PRO_VISION,p.GEMINI_1_5_PRO_LATEST,p.GEMINI_1_5_PRO_001,p.GEMINI_1_5_PRO_002,p.GEMINI_1_5_PRO,p.GEMINI_1_5_FLASH_LATEST,p.GEMINI_1_5_FLASH_001,p.GEMINI_1_5_FLASH_001_TUNING,p.GEMINI_1_5_FLASH,p.GEMINI_1_5_FLASH_002,p.GEMINI_1_5_FLASH_8B,p.GEMINI_1_5_FLASH_8B_001,p.GEMINI_1_5_FLASH_8B_LATEST,p.GEMINI_1_5_FLASH_8B_EXP_0827,p.GEMINI_1_5_FLASH_8B_EXP_0924,p.GEMINI_2_5_PRO_EXP_03_25,p.GEMINI_2_5_PRO_PREVIEW_03_25,p.GEMINI_2_5_FLASH_PREVIEW_04_17,p.GEMINI_2_5_FLASH_PREVIEW_05_20,p.GEMINI_2_5_FLASH_PREVIEW_04_17_THINKING,p.GEMINI_2_5_PRO_PREVIEW_05_06,p.GEMINI_2_5_PRO_PREVIEW_06_05,p.GEMINI_2_0_FLASH_EXP,p.GEMINI_2_0_FLASH,p.GEMINI_2_0_FLASH_001,p.GEMINI_2_0_FLASH_EXP_IMAGE_GENERATION,p.GEMINI_2_0_FLASH_LITE_001,p.GEMINI_2_0_FLASH_LITE,p.GEMINI_2_0_FLASH_PREVIEW_IMAGE_GENERATION,p.GEMINI_2_0_FLASH_LITE_PREVIEW_02_05,p.GEMINI_2_0_FLASH_LITE_PREVIEW,p.GEMINI_2_0_PRO_EXP,p.GEMINI_2_0_PRO_EXP_02_05,p.GEMINI_EXP_1206,p.GEMINI_2_0_FLASH_THINKING_EXP_01_21,p.GEMINI_2_0_FLASH_THINKING_EXP,p.GEMINI_2_0_FLASH_THINKING_EXP_1219,p.GEMINI_2_5_FLASH_PREVIEW_TTS,p.GEMINI_2_5_PRO_PREVIEW_TTS,p.LEARNLM_2_0_FLASH_EXPERIMENTAL,p.GEMMA_3_1B_IT,p.GEMMA_3_4B_IT,p.GEMMA_3_12B_IT,p.GEMMA_3_27B_IT,p.GEMMA_3N_E4B_IT],ze=p.GEMINI_2_5_FLASH_PREVIEW_05_20;class Ze{static{u(this,"GoogleAIProvider")}name="GoogleAI";client;model;constructor(e,s){this.model=s??ze,this.client=new Oe({apiKey:e})}createChatRequest(e,s={}){const{recorder:n}=s;return e.hasFiles()&&!_e.includes(this.model)&&n?.warn.log(`Model ${this.model} does not support multimodal content. Use one of: ${_e.join(", ")}`),new je(this,e)}}class je{static{u(this,"GoogleAIChatRequest")}constructor(e,s){this.provider=e,this.chat=s}async execute(e){const{recorder:s}=e,{client:n,model:o}=this.provider,r=Ye(this.chat);s?.debug?.log(r);let i;try{const a=await n.models.generateContent({model:o,...r});i=Qe(a,e)}catch(a){s?.error?.log(a),i={type:"error",error:{type:a.name??"Undetermined",message:a.message??"Unexpected error from Google AI"},usage:{in:0,out:0},raw:a}}return s?.debug?.log(i),i}}function Ye(t){let e;t.messages.length===1&&t.messages[0].role=="user"&&typeof t.messages[0].content=="string"?e=t.messages[0].content:e=t.messages.map(n=>{if(n.role==="user"){if(typeof n.content=="string")return{role:"user",parts:[{text:n.content}]};{const o=[],r=H(n.content);r&&o.push({text:r});const i=F(n.content);i.length>0&&o.push(...i.map(c=>({inlineData:{mimeType:c.mimeType,data:c.base64}})));const a=W(n.content);return a.length>0&&o.push(...a.map(c=>({inlineData:{mimeType:c.mimeType,data:c.base64}}))),{role:"user",parts:o}}}else if(n.role==="assistant"){const o={role:"assistant",parts:[]};return n.content!==void 0&&o.parts.push({text:n.content}),n.toolCalls&&(o.parts=o.parts.concat(n.toolCalls.map(r=>{let i;return typeof r.arguments=="string"?i=JSON.parse(r.arguments):i=r.arguments,{functionCall:{id:r.id??void 0,name:r.name,args:i}}}))),o}else if(n.role==="tool")return{role:"user",parts:n.content.map(o=>({functionResponse:{id:o.id??void 0,name:o.name,response:{output:o.content}}}))}});const s={};return t.system&&(s.systemInstruction=t.system),t.tools.length>0&&(s.tools=t.tools.map(n=>({functionDeclarations:[{name:n.name,description:n.description,parameters:{...n.parameters,type:be.OBJECT}}]}))),{contents:e,config:s}}u(Ye,"prepareRequest$3");function Qe(t,e){const{recorder:s}=e,n=t.usageMetadata.promptTokenCount,o=t.usageMetadata.totalTokenCount-n,r={in:n,out:o};if(!t)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};if(t.promptFeedback&&t.promptFeedback.blockReason)return{type:"error",error:{type:"Blocked",message:`Response blocked by Google AI: ${t.promptFeedback.blockReason}, ${t.promptFeedback.blockReasonMessage}`},usage:r,raw:t};if(!t.candidates||t.candidates.length===0)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};t.candidates.length>1&&s?.warn?.log(`We received ${t.candidates.length} response candidates`);const i=t.candidates[0],c=(i.content?.parts||[]).map(_=>_.text).filter(_=>_!==void 0).join(""),[l,f]=Ve(i.finishReason);if(l){let _;return t.functionCalls&&(_=t.functionCalls.map(g=>({id:g.id,name:g.name,arguments:JSON.stringify(g.args)}))),{type:"success",id:t.responseId,model:t.modelVersion,reason:t.functionCalls?E.FunctionCall:f,message:{role:"assistant",...c?{content:c}:{},..._?{toolCalls:_}:{}},usage:r,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${f}`},usage:r,raw:t}}u(Qe,"translateResponse$2");function Ve(t){switch(t){case P.STOP:return[!0,E.Stop];case P.MAX_TOKENS:return[!0,E.Length];case P.FINISH_REASON_UNSPECIFIED:case P.SAFETY:case P.RECITATION:case P.LANGUAGE:case P.OTHER:case P.BLOCKLIST:case P.PROHIBITED_CONTENT:case P.SPII:case P.MALFORMED_FUNCTION_CALL:case P.IMAGE_SAFETY:return[!1,E.Error]}}u(Ve,"getStopReason$1");const et="http://localhost:11434";class tt{static{u(this,"OllamaProvider")}name="Ollama";url;model;recorder;constructor(e,s){this.url=s||et,this.model=e}createChatRequest(e,s={}){const{recorder:n}=s;return e.hasFiles()&&n?.warn?.log(`Ollama model ${this.model} multimodal support depends on the specific model. Ensure you're using a vision-capable model like llava.`),new st(this.url,this.model,e)}}class st{static{u(this,"OllamaChatCompletionRequest")}chat;url;model;constructor(e,s,n){this.url=e,this.model=s,this.chat=n}async execute(e){const{recorder:s}=e,n={stream:!1,options:{temperature:.7},...nt(this.chat,this.model)};s?.debug?.log(n);let o;try{const r=await fetch(`${this.url}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw console.log(r),new Error(`HTTP error! status: ${r.status}`);const i=await r.json();o=rt(i)}catch(r){s?.error?.log("Error fetching Ollama response:",r),o={type:"error",error:{type:"OllamaError",message:r.message||"Unexpected error from Ollama"},usage:{in:0,out:0},raw:JSON.stringify(r)}}return s?.debug?.log(o),o}}function nt(t,e){const s=[];t.system&&s.push({role:"system",content:t.system});let n;t.tools.length>0&&(n=t.tools.map(r=>({type:"function",function:r})));const o=t.messages.map(r=>{if(r.role==="tool")return r.content.map(i=>({role:"tool",tool_call_id:i.id,content:i.content}));if(r.role==="assistant"){const i=r.toolCalls?.map(a=>{const c=a.id;return{type:"function",function:{name:a.name,arguments:a.arguments},...c&&{id:c}}});return{role:r.role,content:r.content,...i&&{toolCalls:i}}}if(typeof r.content=="string")return{role:r.role,content:r.content};{const i=H(r.content),a=F(r.content).map(c=>c.base64);return{role:r.role,content:i,...a.length>0&&{images:a}}}}).flat(1);return{model:e,messages:[...s,...o],...n&&{tools:n}}}u(nt,"prepareRequest$2");function rt(t){if(t.done_reason==="stop"&&t.message){const e=t.message.content,s=[];if(t.message.tool_calls)for(const o of t.message.tool_calls)s.push({id:o.id,name:o.function.name,arguments:o.function.arguments});const n=s.length>0;return{type:"success",id:`ollama-${Date.now()}`,model:t.model,reason:n?E.FunctionCall:E.Stop,message:{role:"assistant",content:e,...n&&{toolCalls:s}},usage:{in:t.prompt_eval_count||0,out:t.eval_count||0},raw:t}}return{type:"error",error:{type:"OllamaError",message:"Unexpected error from Ollama"},usage:{in:0,out:0},raw:t}}u(rt,"translateResponse$1");const d={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",O3_MINI:"o3-mini",O3_MINI_2025_01_31:"o3-mini-2025-01-31",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16"},ot=[d.GPT_4_1,d.GPT_4_1_2025_04_14,d.GPT_4_1_MINI,d.GPT_4_1_MINI_2025_04_14,d.GPT_4_1_NANO,d.GPT_4_1_NANO_2025_04_14,d.GPT_4O,d.GPT_4O_2024_05_13,d.GPT_4O_2024_08_06,d.GPT_4O_2024_11_20,d.GPT_4O_AUDIO_PREVIEW,d.GPT_4O_AUDIO_PREVIEW_2024_10_01,d.GPT_4O_AUDIO_PREVIEW_2024_12_17,d.GPT_4O_AUDIO_PREVIEW_2025_06_03,d.GPT_4O_MINI,d.GPT_4O_MINI_2024_07_18,d.GPT_4O_MINI_AUDIO_PREVIEW,d.GPT_4O_MINI_AUDIO_PREVIEW_2024_12_17,d.GPT_4O_MINI_REALTIME_PREVIEW,d.GPT_4O_MINI_REALTIME_PREVIEW_2024_12_17,d.GPT_4O_MINI_SEARCH_PREVIEW,d.GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11,d.GPT_4O_MINI_TRANSCRIBE,d.GPT_4O_MINI_TTS,d.GPT_4O_REALTIME_PREVIEW,d.GPT_4O_REALTIME_PREVIEW_2024_10_01,d.GPT_4O_REALTIME_PREVIEW_2024_12_17,d.GPT_4O_REALTIME_PREVIEW_2025_06_03,d.GPT_4O_SEARCH_PREVIEW,d.GPT_4O_SEARCH_PREVIEW_2025_03_11,d.GPT_4O_TRANSCRIBE,d.O3_MINI,d.O3_MINI_2025_01_31,d.O4_MINI,d.O4_MINI_2025_04_16];class it{static{u(this,"OpenAIChatCompletionRequest")}constructor(e,s){this.provider=e,this.chat=s}async execute(e){const{recorder:s}=e,{client:n,model:o}=this.provider,r=ct(this.chat,o);s?.debug?.heading.log("[Open AI Provider] Using the ChatCompletion API"),s?.debug?.log(r);let i;try{const a=await n.chat.completions.create(r);i=ut(a)}catch(a){s?.error?.log(a),i={type:"error",error:{type:a.type??"Undetermined",message:a.message??"Unexpected error from OpenAI"},usage:{in:0,out:0},raw:a}}return s?.debug?.log(i),i}}function at(t){switch(t){case"length":return E.Length;case"stop":return E.Stop;case"tool_calls":return E.FunctionCall;default:return E.Error}}u(at,"getStopReason");function ct(t,e){const s=[];t.system&&s.push({role:"system",content:t.system});let n;t.tools.length>0&&(n=t.tools.map(r=>({type:"function",function:r})));const o=t.messages.map(r=>{if(r.role==="tool")return r.content.map(i=>({role:"tool",tool_call_id:i.id,content:i.content}));if(r.role==="assistant"){const i=r.toolCalls?.map(a=>{const c=a.id;return{type:"function",function:{name:a.name,arguments:typeof a.arguments=="string"?a.arguments:JSON.stringify(a.arguments)},...c&&{id:c}}});return{role:r.role,content:r.content,...i&&{toolCalls:i}}}if(typeof r.content=="string")return{role:r.role,content:r.content};{const i=[],a=H(r.content);a&&i.push({type:"text",text:a});const c=F(r.content);c.length>0&&i.push(...c.map(f=>({type:"image_url",image_url:{url:`data:${f.mimeType};base64,${f.base64}`}})));const l=W(r.content);return l.length>0&&i.push(...l.map(f=>({type:"file",file:{filename:f.name,file_data:`data:${f.mimeType};base64,${f.base64}`}}))),{role:r.role,content:i}}}).flat(1);return{model:e,messages:[...s,...o],...n&&{tools:n}}}u(ct,"prepareRequest$1");function ut(t){if(t.choices.length>0){const e=t.choices[0],s=e.message.tool_calls?.map(n=>({id:n.id,name:n.function.name,arguments:n.function.arguments}));return{type:"success",id:t.id,model:t.model,reason:at(e.finish_reason),message:{content:e.message.content??"",role:e.message.role,toolCalls:s},usage:{in:t.usage?.prompt_tokens??0,out:t.usage?.completion_tokens??0},raw:t}}return{type:"error",error:{type:"undetermined",message:"Unexpected response from OpenAI"},usage:{in:t.usage?.prompt_tokens??0,out:t.usage?.completion_tokens??0},raw:t}}u(ut,"translateResponse");class lt{static{u(this,"OpenAIResponsesAPI")}constructor(e,s){this.provider=e,this.chat=s}async execute(e){const{recorder:s}=e,{client:n,model:o}=this.provider,r=ft(this.chat,o);s?.debug?.heading.log("[Open AI Provider] Using the Responses API"),s?.debug?.log(r);let i;try{const a=await n.responses.create(r);i=pt(a)}catch(a){s?.error?.log(a),i={type:"error",error:{type:a.type??"Undetermined",message:a.message??"Unexpected error from OpenAI"},usage:{in:0,out:0},raw:a}}return s?.debug?.log(i),i}}function ft(t,e){const s=t.messages.map(r=>{if(r.role==="tool")return r.content.map(i=>({type:"function_call_output",call_id:i.id,output:i.content}));if(r.role==="assistant"){const i=r.toolCalls?.map(a=>{const c=a.id;return{type:"function",function:{name:a.name,arguments:typeof a.arguments=="string"?a.arguments:JSON.stringify(a.arguments)},...c&&{id:c}}});return{role:r.role,content:r.content,...i&&{toolCalls:i}}}if(typeof r.content=="string")return{role:r.role,content:r.content};{const i=[],a=He(r.content);a&&i.push({type:"input_text",text:a});const c=F(r.content);c.length>0&&i.push(...c.map(f=>({type:"input_image",image_url:`data:${f.mimeType};base64,${f.base64}`})));const l=W(r.content);return l.length>0&&i.push(...l.map(f=>({type:"input_file",filename:f.path,file_data:`data:${f.mimeType};base64,${f.base64}`}))),{role:r.role,content:i}}}).flat(1),n={model:e,input:s},o=t.latest();if(o&&o.role==="user"){let r="";const i=We(o.content);t.system&&(r=t.system),i&&(r=r?`${r}
|
|
8
|
-
|
|
9
|
-
${i}`:i),r&&(n.instructions=r)}return t.tools.length>0&&(n.tools=t.tools.map(r=>({type:"function",strict:!0,...r}))),n}u(ft,"prepareRequest");function pt(t){if(t.error)return{type:"error",error:{type:t.error.code||"undetermined",message:t.error.message||"Response generation failed"},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t};const e=t.output?.filter(s=>s.type==="function_call")?.map(s=>({id:s.id||"",name:s.function?.name||"",arguments:s.function?.arguments||""}));return{type:"success",id:t.id,model:t.model||"",reason:t.incomplete_details?E.Error:E.Stop,message:{content:t.output_text||"",role:"assistant",...e?.length&&{toolCalls:e}},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}u(pt,"translateResponseToAIResponse");const _t=d.GPT_4_1;class dt{static{u(this,"OpenAIProvider")}name="OpenAI";client;model;constructor(e,s){this.model=s||_t,this.client=new ke({apiKey:e})}createChatRequest(e,s={}){const{recorder:n}=s;return ot.includes(this.model)?new lt(this,e):new it(this,e)}}function gt(t,e){if(!e||Object.keys(e).length===0)throw new A(`The provider ${t} is not configured. Please check your configuration.`);switch(t){case"openai":return new dt(e["api-key"],e.model);case"anthropic":return new Je(e["api-key"],e.model);case"googleai":return new Ze(e["api-key"],e.model);case"ollama":{const s=e;return new tt(s.model,s.url)}default:throw new A("The provider is unsupported")}}u(gt,"getProvider");class oe extends A{static{u(this,"TaskError")}constructor(e,s){super(e,{code:"TASK_ERROR",id:s?.id,details:{taskType:s?.taskType,taskIndex:s?.taskIndex,...s?.details},cause:s?.cause}),Object.setPrototypeOf(this,oe.prototype)}}const m={Running:"running",Success:"success",PartialSuccess:"partialSuccess",Fail:"fail"};var T=(t=>(t[t.Trace=10]="Trace",t[t.Debug=20]="Debug",t[t.Info=30]="Info",t[t.Warn=40]="Warn",t[t.Error=50]="Error",t[t.Fatal=60]="Fatal",t))(T||{});class mt{static{u(this,"Recorder")}instanceId=crypto.randomUUID();currentLevel=T.Info;logs=[];writers=[];_debug;_info;_warn;_error;constructor(){this.buildMethods()}buildMethods(){this._debug=T.Debug>=this.currentLevel?this.createLoggingFunction(T.Debug):null,this._info=T.Info>=this.currentLevel?this.createLoggingFunction(T.Info):null,this._warn=T.Warn>=this.currentLevel?this.createLoggingFunction(T.Warn):null,this._error=this.createLoggingFunction(T.Error)}set level(e){this.currentLevel=e,this.buildMethods()}get level(){return this.currentLevel}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}get debug(){return this._debug}subscribe(e){this.writers.includes(e)||this.writers.push(e)}unsubscribe(e){const s=this.writers.indexOf(e);s!==-1&&this.writers.splice(s,1)}publish(e){this.logs.push(e);for(const s of this.writers)s.handleEvent(e)}logFunction(e,s,...n){let o=n.map(r=>typeof r=="string"?{message:r}:r instanceof Error?Me(r):r);this.publish({level:e,time:Date.now(),kind:s,payload:o})}createLoggingFunction(e){return{log:this.logFunction.bind(this,e,"body"),heading:{log:this.logFunction.bind(this,e,"heading")}}}getLogs(e=T.Info){return this.logs.filter(s=>s.level>=e)}async shutdown(){for(const e of this.writers)typeof e.flush=="function"&&await e.flush()}}async function ht(t,e){const{defaults:s,tag:n}=e;let o=null,r="";if(t)try{r=ee(t),o=await C(r,{encoding:"utf-8"})}catch{throw new Error(`${n} not found, see --help for details`)}else{for(const i of s.formats)try{r=ee(s.name+"."+i),o=await C(r,{encoding:"utf-8"});break}catch{continue}if(o===null)throw new Error(`${n} not found, see --help for details`)}return{content:o,format:r.split(".").pop()??""}}u(ht,"searchAndLoadFile");async function yt(t,e){let s="";for(const n of t){const o=await ae(n);e?.debug?.log(`many-files parser. For glob "${n}", found ${o.length} files.`);const r=await Promise.all(o.map(async i=>{const a=await C(i,"utf-8");return i+`:
|
|
10
|
-
`+a}));s+=r.join(`
|
|
11
|
-
`)}return s}u(yt,"loadManyFiles");function Et(t,e){t=t.replace("**/*","**");const s=/(?<asterisks>\*{1,2})(?<extension>\.[^\\/]+)?/,n=t.match(s);if(n){let o="";return n.groups?.asterisks.length==1?o+=e.stem:o+=e.dir+e.stem,n.groups?.extension?o+=n.groups.extension:o+=e.ext,t.replace(n[0],o)}return t}u(Et,"replaceFilePattern");function It(t){const e=/(?<name>[^\\/]+)(?<extension>\.[^\\/]+)$/,s=t.match(e);return s&&s.length>0&&s.groups?{abs:t,dir:t.replace(s[0],""),ext:s.groups.extension,stem:s.groups.name,name:s[0]}:null}u(It,"pathToComponents");async function de(t){const e=De(t);try{await ce(e)}catch{await Fe(e),await de(e)}}u(de,"ensureDirectoryExistence");async function wt({filePath:t,content:e}){await de(t),await Ce(t,e)}u(wt,"writeFileWithDirectories");const B=[".jpg",".jpeg",".png",".gif",".webp",".bmp",".tiff"],J=[".pdf"],X=[".txt",".md",".markdown"],ge=20*1024*1024;function Tt(t){return t.type==="text"}u(Tt,"isTextFileInfo");function At(t){return t.type==="image"||t.type==="document"}u(At,"isBase64FileInfo");function Pt(t){const e=ue(t).toLowerCase();if(X.includes(e))return"utf-8";if(B.includes(e)||J.includes(e))return"base64";{const s=[...X,...B,...J];throw new Error(`Unsupported file type: ${e}. Supported types: ${s.join(", ")}`)}}u(Pt,"getEncodingForFile");async function q(t,e){const s=ee(t);try{await ce(s)}catch{throw new Error(`File not found: ${t}`)}const n=await Le(s);if(n.size>ge)throw new Error(`File too large: ${n.size} bytes. Maximum allowed: ${ge} bytes`);const o=ue(s).toLowerCase(),r=s.split("/").pop()||"";if((e||Pt(s))==="utf-8"){if(!X.includes(o))throw new Error(`Unsupported text file type: ${o}. Supported types: ${X.join(", ")}`);let a;switch(o){case".txt":a="text/plain";break;case".md":case".markdown":a="text/markdown";break;default:a="text/plain"}const c=await C(s,"utf-8");return{path:s,content:c,mimeType:a,size:n.size,name:r,type:"text"}}else{let a,c;if(B.includes(o))switch(a="image",o){case".jpg":case".jpeg":c="image/jpeg";break;case".png":c="image/png";break;case".gif":c="image/gif";break;case".webp":c="image/webp";break;case".bmp":c="image/bmp";break;case".tiff":c="image/tiff";break;default:c="image/jpeg"}else if(J.includes(o))a="document",c="application/pdf";else throw new Error(`Unsupported file type: ${o}. Supported types: ${[...B,...J].join(", ")}`);const f=(await C(s)).toString("base64");return{path:s,base64:f,mimeType:c,size:n.size,name:r,type:a}}}u(q,"loadFileContent");function vt(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):St(t.using,e)?!t.jobs||typeof t.jobs!="object"?(e&&(e.value="Missing or invalid 'jobs' property"),!1):me(t.jobs,e)?!0:(e&&(e.value=`Invalid 'jobs' property: ${e?.value}`),!1):(e&&(e.value=`Invalid 'using' property: ${e?.value}`),!1)}u(vt,"isJobConfig");function St(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(typeof t.engine!="string")return e&&(e.value="Missing or invalid 'engine' property"),!1;if(!["openai","anthropic","ollama","googleai"].includes(t.engine))return e&&(e.value="Invalid provider type. Must be 'openai', 'anthropic', 'googleai', or 'ollama'"),!1;switch(t.engine){case"ollama":if("model"in t&&typeof t.model!="string")return e&&(e.value="Property 'model' must be a string"),!1;if("url"in t&&typeof t.url!="string")return e&&(e.value="Property 'url' must be a string"),!1;break;case"googleai":case"anthropic":case"openai":if("api-key"in t&&typeof t["api-key"]!="string")return e&&(e.value="Property 'api-key' must be a string"),!1;if("model"in t&&typeof t.model!="string")return e&&(e.value="Property 'model' must be a string"),!1;break}return!0}u(St,"isUsing");function me(t,e){for(const[s,n]of Object.entries(t))if(!Nt(n,e))return e&&(e.value=`Invalid job '${s}': ${e?.value}`),!1;return!0}u(me,"isDAGJob");function Nt(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(!Rt(t,e))return!1;if("dependsOn"in t&&t.dependsOn!==void 0){const s=t.dependsOn;if(typeof s!="string")if(Array.isArray(s)){for(let n=0;n<s.length;n++)if(typeof s[n]!="string")return e&&(e.value=`Dependency at index ${n} must be a string`),!1}else return e&&(e.value="Property 'dependsOn' must be a string or array of strings"),!1}return!0}u(Nt,"isDAGJobValue");function Rt(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):"batch"in t?bt(t,e):Ot(t,e)}u(Rt,"isJob");function Ot(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if("batch"in t)return e&&(e.value="Serial job should not have a batch property"),!1;if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const s of t.tools)if(typeof s!="string")return e&&(e.value="All tools must be strings"),!1}if(!Array.isArray(t.steps))return e&&(e.value="Property 'steps' must be an array"),!1;for(let s=0;s<t.steps.length;s++)if(!he(t.steps[s],e))return e&&(e.value=`Invalid step at index ${s}: ${e?.value}`),!1;return!0}u(Ot,"isSerialJob");function bt(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const s of t.tools)if(typeof s!="string")return e&&(e.value="All tools must be strings"),!1}if(!Array.isArray(t.batch))return e&&(e.value="Property 'batch' must be an array"),!1;for(let s=0;s<t.batch.length;s++)if(!kt(t.batch[s],e))return e&&(e.value=`Invalid batch item at index ${s}: ${e?.value}`),!1;if(!Array.isArray(t.steps))return e&&(e.value="Property 'steps' must be an array"),!1;for(let s=0;s<t.steps.length;s++)if(!he(t.steps[s],e))return e&&(e.value=`Invalid step at index ${s}: ${e?.value}`),!1;return!0}u(bt,"isBatchJob");function kt(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.type!=="files")return e&&(e.value="Property 'type' must be 'files'"),!1;if(typeof t.source!="string")return e&&(e.value="Property 'source' must be a string"),!1;if(typeof t.bind!="string")return e&&(e.value="Property 'bind' must be a string"),!1;if(t["skip-if"]!==void 0){if(!Array.isArray(t["skip-if"]))return e&&(e.value="Property 'skip-if' must be an array"),!1;for(let s=0;s<t["skip-if"].length;s++)if(!Mt(t["skip-if"][s],e))return e&&(e.value=`Invalid skip condition at index ${s}: ${e?.value}`),!1}return!0}u(kt,"isBatchOptions");function Mt(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):t.type!=="file-exist"?(e&&(e.value="Property 'type' must be 'file-exist'"),!1):typeof t.pattern!="string"?(e&&(e.value="Property 'pattern' must be a string"),!1):!0}u(Mt,"isSkipOptions");function he(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):!t.uses||typeof t.uses!="string"?(e&&(e.value="Step must have a string 'uses' property"),!1):t.uses==="chat"?$t(t,e):t.uses==="write-to-disk"?Gt(t,e):(e&&(e.value=`Unknown uses type: ${t.uses}`),!1)}u(he,"isStep");function $t(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.uses!=="chat")return e&&(e.value="Uses must be 'chat'"),!1;if(typeof t.message!="string")return e&&(e.value="Property 'message' must be a string"),!1;if(t.output!==void 0){if(!t.output||typeof t.output!="object"||Array.isArray(t.output))return e&&(e.value="Property 'output' must be an object"),!1;const s=["string","string[]","number","boolean"];for(const[n,o]of Object.entries(t.output))if(typeof n!="string"||typeof o!="string"||!s.includes(o))return e&&(e.value="Property 'output' must be a Record<string, ResTypeStrings> where ResTypeStrings is 'string' | 'string[]' | 'number' | 'boolean'"),!1}if(t.system!==void 0&&typeof t.system!="string")return e&&(e.value="Property 'system' must be a string"),!1;if(t.replace!==void 0){if(!Array.isArray(t.replace))return e&&(e.value="Property 'replace' must be an array"),!1;for(let s=0;s<t.replace.length;s++)if(!xt(t.replace[s],e))return e&&(e.value=`Invalid replace at index ${s}: ${e?.value}`),!1}if(t.tools!==void 0){if(!Array.isArray(t.tools))return e&&(e.value="Property 'tools' must be an array"),!1;for(const s of t.tools)if(typeof s!="string")return e&&(e.value="All tools must be strings"),!1}if(t.images!==void 0){if(!Array.isArray(t.images))return e&&(e.value="Property 'images' must be an array"),!1;for(let s=0;s<t.images.length;s++)if(!Lt(t.images[s],e))return e&&(e.value=`Invalid image at index ${s}: ${e?.value}`),!1}if(t.documents!==void 0){if(!Array.isArray(t.documents))return e&&(e.value="Property 'documents' must be an array"),!1;for(let s=0;s<t.documents.length;s++)if(!Ct(t.documents[s],e))return e&&(e.value=`Invalid document at index ${s}: ${e?.value}`),!1}if(t.references!==void 0){if(!Array.isArray(t.references))return e&&(e.value="Property 'references' must be an array"),!1;for(let s=0;s<t.references.length;s++)if(!Ft(t.references[s],e))return e&&(e.value=`Invalid reference at index ${s}: ${e?.value}`),!1}return!0}u($t,"isChatStep");function Gt(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(t.uses!=="write-to-disk")return e&&(e.value="Uses must be 'write-to-disk'"),!1;if(typeof t.output!="string")return e&&(e.value="Property 'output' must be a string"),!1;if(t.keys!==void 0&&typeof t.keys!="string")if(Array.isArray(t.keys)){for(let s=0;s<t.keys.length;s++)if(typeof t.keys[s]!="string")return e&&(e.value=`Key at index ${s} must be a string`),!1}else return e&&(e.value="Property 'keys' must be a string or array of strings"),!1;return!0}u(Gt,"isWriteToDiskStep");function xt(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(typeof t.pattern!="string")return e&&(e.value="Property 'pattern' must be a string"),!1;if(t.source!=="file")return e&&(e.value="Property 'source' must be 'file'"),!1;if(typeof t.files!="string"&&!Array.isArray(t.files))return e&&(e.value="Property 'files' must be a string or an array of strings"),!1;if(Array.isArray(t.files)){for(let s=0;s<t.files.length;s++)if(typeof t.files[s]!="string")return e&&(e.value=`Files entry at index ${s} must be a string`),!1}return!0}u(xt,"isReplace");function Lt(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}u(Lt,"isImageReference");function Ct(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}u(Ct,"isDocumentReference");function Ft(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):typeof t.file!="string"?(e&&(e.value="Property 'file' must be a string"),!1):!0}u(Ft,"isTextFileReference");class Dt{static{u(this,"FileRunPlanner")}constructor(e,s,n=[]){this.source=e,this.bind=s,this.skipConditions=n}async plan(e){const s=[],n=await ae(this.source,{withFileTypes:!0});for(const o of n){const r=o.fullpath(),i=It(r);let a=!1;for(const c of this.skipConditions)if(a=await c.eval({components:i}),a)break;if(!a){const c=await $e(r,"utf-8"),l={variables:{[this.bind]:c,...i},tasks:e};s.push(l)}}return s}}class Ut{static{u(this,"MultiPlanner")}planners;constructor(e){this.planners=e}async plan(e){const s=this.planners.map(async o=>await o.plan(e));return(await Promise.all(s)).flat()}}function te(t,e,s="{{}}"){const n=s==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(n,(o,r)=>{if(r=r.trim(),Object.prototype.hasOwnProperty.call(e,r)){const i=e[r];return i==null?"":String(i)}return o}),t}u(te,"replaceVariables");class Ht{static{u(this,"FileExistSkipCondition")}constructor(e){this.pattern=e}type="file-exist";async eval(e){const s=te(this.pattern,e.components,"{}");try{return await Ge(s,xe.F_OK),!0}catch{return!1}}}function K(t,e=0){const s={};for(const[n,o]of Object.entries(t))if(typeof o=="string")switch(o){case"string":s[n]=e===0?I.string():I.string().optional();break;case"number":s[n]=e===0?I.number():I.number().optional();break;case"boolean":s[n]=e===0?I.boolean():I.boolean().optional();break;case"string[]":s[n]=I.array(I.string());break;default:throw new Error(`Unsupported declarative type: ${o}`)}else if(Array.isArray(o))if(o.length===1&&typeof o[0]=="object"){const r=K(o[0],e+1);s[n]=I.array(I.object(r))}else throw new Error(`Unsupported array format for key ${n}. Expected [DeclarativeSchema].`);else s[n]=I.object(K(o,e+1));return s}u(K,"declarativeToOutputSchema");function z(t){if(t instanceof I.ZodString)return["string","Your answer"];if(t instanceof I.ZodNumber)return["number",42];if(t instanceof I.ZodBoolean)return["boolean",!0];if(t instanceof I.ZodArray){const e=t.element;if(e instanceof I.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof I.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof I.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof I.ZodObject){const[s,n]=z(e);return["object array",[n,n]]}return["array",[]]}if(t instanceof I.ZodObject){const e=t.shape,s={};for(const[n,o]of Object.entries(e)){const[r,i]=z(o);s[n]=i}return["JSON object",s]}if(t instanceof I.ZodOptional){const e=t.unwrap(),[s,n]=z(e);return[`${s} | undefined`,n]}}u(z,"zodToExample");function ye(t){return typeof t=="object"&&Object.values(t).every(e=>e&&typeof e=="object"&&"_def"in e)}u(ye,"isOutputSchema");class Ee{static{u(this,"AbstractInstruct")}type="instruct";prompt;system=null;inputs={};tools={};files=[];textReferences=[];instructions=[];schema;rawResponse;_taggedSections=void 0;_result=void 0;constructor(e,s){this.prompt=e,this.schema=s}setInputs(e){this.inputs=e}addInput(e,s){this.inputs[e]=s}addTools(e){for(const s of e)this.tools[s.name]=s}addTool(e){this.tools[e.name]=e}addImage(e){if(e.type!=="image")throw new Error(`Expected image file, got ${e.type}`);const s=e;this.files.push(s)}addDocument(e){if(e.type!=="document")throw new Error(`Expected document file, got ${e.type}`);const s=e;this.files.push(s)}addFile(e){if(!At(e))throw new Error(`Expected image or document file, got ${e.type}`);this.files.push(e)}addReference(e,s){if(typeof e=="string"){this.textReferences.push({content:e,name:s?.name});return}if(Tt(e))this.textReferences.push({content:e.content,name:s?.name??e.name});else throw new Error(`Expected text file, got ${e.type}`)}addInstructions(e){if(typeof e!="string"||e.trim()==="")throw new Error("Instruction must be a non-empty string");this.instructions.push(e)}hasTools(){return Object.keys(this.tools).length>0}hasFiles(){return this.files.length>0}get result(){return this._result}compile(e,s={}){const n=this.createUserMessage(e,s),o=this.createInstructions();return{message:n,instructions:o}}createUserMessage(e,s={}){const{recorder:n,options:o}=s,r={...e,...this.inputs};let i=te(this.prompt,r);if(this.textReferences.length>0)for(const[a,c]of this.textReferences.entries()){const l=c.name?`: ${c.name}`:"";i+=`
|
|
12
|
-
|
|
13
|
-
## Reference ${a+1}${l}
|
|
14
|
-
|
|
15
|
-
\`\`\`${c.content}'''`}if(o?.warnUnused){const a=i.match(/\{\{(.*?)\}\}/g);if(a)throw n?.error.log(`Warning unused variables ${a.join(", ")}`),new Error(`Unused variables: ${a.join(", ")}`)}return i}createInstructions(e=""){if(e=`# Instructions
|
|
16
|
-
|
|
17
|
-
`+e,Object.keys(this.schema).length>0){e+=`## Output Format Instructions
|
|
18
|
-
`,e+=`
|
|
19
|
-
Here is how you should format your output. Follow the instructions strictly.
|
|
20
|
-
`;for(const[n,o]of Object.entries(this.schema)){const r=this.generateFieldInstructions(n,o);e+=r}}if(this.instructions.length>0){e+=`
|
|
21
|
-
## Additional Instructions
|
|
22
|
-
|
|
23
|
-
`;for(const n of this.instructions)e+=`- ${n}
|
|
24
|
-
`}return e}generateFieldInstructions(e,s){const[n,o]=z(s);return`
|
|
25
|
-
- Use <${e}></${e}> tags to indicate the answer for ${e}. The answer must be a ${n}.
|
|
26
|
-
Example: <${e}>${JSON.stringify(o)}</${e}>
|
|
27
|
-
`}finalize(e,s={}){const{recorder:n}=s;if(this.rawResponse=e,Object.keys(this.schema).length===0){if(e.trim()==="{}"||e.trim()==="")return this._result={},this._result;throw new Error("Schema is empty, but rawValue is not an empty object representation or empty string.")}this._taggedSections=this._taggedSections||this.parseTaggedSections(e);const r={};for(const[i,a]of Object.entries(this.schema)){const c=this._taggedSections.tags[i];if(c!==void 0)r[i]=this.preprocessValue(a,c);else if(a.def.type!=="optional")throw new Error(`Expected results with tag ${i} but it does not exist`)}try{const i={};for(const[a,c]of Object.entries(this.schema))a in r&&(i[a]=c.parse(r[a]));return this._result=i,this._result}catch(i){if(i&&typeof i=="object"&&"issues"in i){const a=i.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ");throw new Error(`Validation failed: ${a}`)}throw i}}preprocessValue(e,s){switch(s=s.trim(),e.def.type){case"string":try{return JSON.parse(s)}catch{if(typeof s=="string")return s;throw new Error(`Cannot parse '${s}' as string. Ensure it is a valid JSON string or a plain string.`)}case"number":{const n=parseFloat(s);if(isNaN(n))throw new Error(`Cannot parse '${s}' as number`);return n}case"boolean":{const n=s.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;throw new Error(`Cannot parse '${s}' as boolean. Expected 'true' or 'false'`)}case"array":{if(s==="")return[];try{const n=JSON.parse(s);if(Array.isArray(n))return n}catch{}if(s.includes(","))return s.split(",").map(n=>{const o=n.trim();try{return JSON.parse(o)}catch{return o}}).filter(n=>n!=="")}case"object":{s.includes("```json")&&(s=s.replace(/```json/g,"").replace(/```/g,""));try{return JSON.parse(s)}catch(n){throw new Error(`Cannot parse object as JSON: ${n.message}`)}}case"optional":{const n=e.def.innerType;return this.preprocessValue(n,s)}default:return s}}parseTaggedSections(e){e.trim().startsWith("```json")&&e.trim().endsWith("```")&&(e=e.trim().slice(7,-3).trim());const s=/<(\w+)>(.*?)<\/\1>/gs,n={};let o=e;o=o.replace(s,(i,a,c)=>(n[a]=c,""));const r=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return o=o.replace(r,(i,a,c)=>(n[a]=c,"")),{tags:n,remaining:o.trim()}}}class $ extends Ee{static{u(this,"Instruct")}constructor(e,s){super(e,s)}static with(e,s){if(!s)return new $(e,{response:I.string()});if(ye(s))return new $(e,s);{const n=K(s);return new $(e,n)}}}function D(t){return Array.isArray(t)?t:[t]}u(D,"arrayify");function S(t,e){return e?`${e}:${t.slice(0,8)}`:t.slice(0,8)}u(S,"friendly");function Wt(t){return new Promise(e=>setTimeout(e,t))}u(Wt,"delay");const Bt={name:"brave",description:"Perform a search using the Brave search engine",parameters:{type:"object",properties:{searchTerm:{type:"string",description:"The search term to query"}},required:["searchTerm"]}};class Jt{static{u(this,"BraveSearchTool")}name="brave";schema=Bt;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.setConfig(e)}setConfig(e){const{rateLimit:s}=e;this.apiKey=e["api-key"],this.throttle=s?1100/s:void 0}async execute(e,s={}){const{searchTerm:n}=e,{recorder:o}=s;if(o?.debug?.heading.log(`Brave: searching for ${n}`),this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await Wt(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const r=this.apiKey,i="https://api.search.brave.com/res/v1/web/search",a=new URL(i);a.searchParams.append("q",n),a.searchParams.append("format","json");const c=await fetch(a.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":r}});if(!c.ok)throw new Error(`[Brave] HTTP error ${c.status}: ${c.statusText}`);return await c.json()}catch(r){throw o?.error.log("[Brave] Error fetching search results:",r),r}}}const Xt=new Jt,qt={name:"calculator",description:"Performs basic arithmetic operations",parameters:{type:"object",properties:{operation:{type:"string",description:"The operation to perform (add, subtract, multiply, divide)",enum:["add","subtract","multiply","divide"]},a:{type:"number",description:"First operand"},b:{type:"number",description:"Second operand"}},required:["operation","a","b"]}},Kt={name:"calculator",schema:qt,execute:u(async t=>{const{operation:e,a:s,b:n}=t;switch(e){case"add":return`${s} + ${n} = ${s+n}`;case"subtract":return`${s} - ${n} = ${s-n}`;case"multiply":return`${s} * ${n} = ${s*n}`;case"divide":if(n===0)throw new Error("Cannot divide by zero");return`${s} / ${n} = ${s/n}`;default:throw new Error(`Unknown operation: ${e}`)}},"execute")};class zt{static{u(this,"ToolRegistry")}executables={};config;setConfig(e){this.config=e}register(e){if(this.executables[e.name])throw new Error(`Tool with name '${e.name}' is already registered`);this.executables[e.name]=e}get(e){const s=this.executables[e];if(!s)throw new Error(`Tool '${e}' is not registered`);return s.setConfig?.(this.config[e]),s}}let U;function Ie(){return U||(U=new zt,U.register(Kt),U.register(Xt)),U}u(Ie,"getToolRegistry");const Zt={async convert(t,e){const{recorder:s,toolNames:n}=e,{message:o,system:r,replace:i}=t;let a;t.output?a=$.with(o,t.output):a=$.with(o),r&&(a.system=r);const c=[...new Set([...n??[],...t.tools??[]])];for(const l of c){const f=Ie().get(l);a.addTool(f)}if(i){for(const l of i)if(l.source==="file"){const f=D(l.files),_=await yt(f,s);a.addInput(l.pattern,_)}}if(t.images)for(const l of t.images)try{const f=await q(l.file,"base64");a.addFile(f)}catch(f){throw new Error(`Failed to load image '${l.file}': ${f.message}`)}if(t.documents)for(const l of t.documents)try{const f=await q(l.file,"base64");a.addFile(f)}catch(f){throw new Error(`Failed to load document '${l.file}': ${f.message}`)}if(t.references)for(const l of t.references)try{const f=await q(l.file,"utf-8");a.addReference(f)}catch(f){throw new Error(`Failed to load reference file '${l.file}': ${f.message}`)}return a}};class jt{static{u(this,"StepToClassRegistry")}converters=new Map;get(e){const s=this.converters.get(e);if(!s)throw new Error(`No converter registered for step: ${e}`);return s}register(e,s){this.converters.set(e,s)}}class se{static{u(this,"WriteOutputTask")}constructor(e,s=["response"]){this.output=e,this.keys=s}type="write-to-disk"}const Yt={async convert(t){if(t.keys){const e=D(t.keys);return new se(t.output,e)}return new se(t.output)}},ne=new jt;ne.register("write-to-disk",Yt),ne.register("chat",Zt);async function Z(t,e){const{recorder:s}=e,n=t.tools??void 0,o=t.steps.map(async r=>(r.uses,await ne.get(r.uses).convert(r,{recorder:s,toolNames:n})));return Promise.all(o)}u(Z,"configToTasks");async function we(t,e){const{batch:s}=t;return s.length===1?Te(s[0]):new Ut(s.map(n=>Te(n)))}u(we,"configToPlanner");function Te(t){switch(t.type){case"files":let e;return t["skip-if"]&&(e=t["skip-if"].map(n=>Qt(n))),new Dt(t.source,t.bind,e)}}u(Te,"batchOptionsToPlanner");function Qt(t){switch(t.type){case"file-exist":return new Ht(t.pattern)}}u(Qt,"skipOptionsToSkipConditions");function Vt(t){return t.success===!1&&t.error!==void 0}u(Vt,"isErrorResult");function j(t,e){return{response:t,stats:e,success:!0}}u(j,"createResult");function Y(t,e,s){return{response:e,stats:s,error:t,success:!1}}u(Y,"createErrorResult");class es{static{u(this,"WriteToDiskTaskHandler")}taskType="write-to-disk";canHandle(e){return e&&typeof e=="object"&&"type"in e&&e.type==="write-to-disk"}async execute(e){const{task:s,variables:n,options:o={},recorder:r}=e,i=s.output,a=s.keys??[];if(o?.warnUnused){const f=a.filter(_=>!(_ in n));f.length>0&&r?.warn?.log(`[Write To Disk] The following keys were not found in the variables: ${f.join(", ")}`)}let c="";if(a.length===1?c=n[a[0]]??"<not found>":c=a.map(f=>`[${f}]:
|
|
28
|
-
${n[f]??"<not found>"}
|
|
29
|
-
`).join(`
|
|
30
|
-
`),o?.dryRun){r?.info?.log("[Dry run] Write to Disk is not executed.");return}let l="";i.includes("*")?l=Et(i,n.file):l=te(i,n,"{}"),await wt({filePath:l,content:c})}}var Q=(t=>(t.LastResult="lastResult",t))(Q||{});function ts(t,e,s){const{options:n,recorder:o}=s,r=n?.warnUnused??!0;for(const[i,a]of Object.entries(t))r&&e[i]&&o?.warn?.log(`Warning: Variable "${i}" is being overwritten. Previous value: ${e[i]}, new value: ${a}`),e[i]=a}u(ts,"setResultsIntoVariables");class ss{static{u(this,"ChatTaskHandler")}taskType="instruct";canHandle(e){return e&&typeof e=="object"&&"type"in e&&e.type==="instruct"}async execute(e){const{task:s,...n}=e;await ns({instruct:s,...n})}}async function ns(t){const{instruct:e,chat:s,provider:n,stats:o,variables:r,options:i,recorder:a}=t;e.system&&s.addSystem(e.system);const{message:c,instructions:l}=e.compile(r,{recorder:a,options:i});if(e.hasFiles()?s.addUser(c,l,e.files):s.addUser(c,l),e.hasTools()){const _=os(e.tools);s.setToolSchemas(_)}if(i?.dryRun)return a?.debug?.log(s),{action:"complete"};let f=!0;for(;f;){const g=await n.createChatRequest(s,{recorder:a}).execute({recorder:a});if(o.in+=g.usage.in,o.out+=g.usage.out,g.type==="error")throw new Error(JSON.stringify(g.error));if(g.type==="success")switch(g.reason){case E.Stop:{if(g.message.content){const y=g.message.content;s.addAssistant(y);const h=e.finalize(y,{recorder:a});ts(h,r,{options:i,recorder:a}),r[Q.LastResult]=h}return f=!1,{action:"continue"}}case E.Length:throw new Error("Incomplete model output due to `max_tokens` parameter or token limit");case E.FunctionCall:{let y=g.message;if(g.message&&s.addAssistant(y.content,y.toolCalls),y.toolCalls&&y.toolCalls.length>0){const h=await rs(y.toolCalls,e,{recorder:a});a?.debug?.log(h),s.addTools(h),f=!0}else f=!1;break}}if(g.type!=="success")throw a?.debug?.log(g),new Error("Unexpected response type")}return{action:"continue"}}u(ns,"executeChatAction");async function rs(t,e,s={}){const{recorder:n}=s,o=[];for(const r of t)o.push(new Promise((i,a)=>{const c=e.tools[r.name];if(!c){a(`Tool not found: ${r.name}`);return}n?.debug?.heading.log(`Executing tool ${c.name}`);let l={};try{l=typeof r.arguments=="string"?JSON.parse(r.arguments):r.arguments}catch{a(`argument for tool ${r.name} is not valid: ${JSON.stringify(r.arguments)}`)}c.execute(l).then(f=>{n?.debug?.log(`Complete tool ${c.name}: ${r.id}`),i({id:r.id,name:r.name,content:JSON.stringify(f)})}).catch(a)}));return Promise.all(o)}u(rs,"executeToolCalls");function os(t){const e=[];for(const[s,n]of Object.entries(t))e.push(n.schema);return e}u(os,"getToolSchemas");class is{static{u(this,"TaskRegistry")}handlers=new Map;register(e){this.handlers.set(e.taskType,e)}getHandler(e){return this.handlers.get(e.type)}hasHandler(e){return this.handlers.has(e.type)}async executeTask(e){const{task:s}=e,n=s.type,o=this.getHandler(s);if(!o)throw new Error(`No handler registered for action type: ${n}`);if(!o.canHandle(s))throw new Error(`Handler found but action does not match expected format: ${n}`);await o.execute(e)}}function as(){const t=new is;return t.register(new ss),t}u(as,"createBaseRegistry");function cs(){const t=as();return t.register(new es),t}u(cs,"createNodeRegistry");const re=u((t,...e)=>{const s=u(async o=>{const{recorder:r}=o;let i=[];return"steps"in t?i=await Z(t,{recorder:r}):i=[t,...e],i},"prepare");return{execute:u(async o=>{const{provider:r,variables:i,options:a,stats:c,recorder:l,name:f}=o,_=crypto.randomUUID(),g=cs();l?.info?.log({type:"task",id:_,status:m.Running,message:`[${S(_,f)}] Starting job`});try{const y=await s({recorder:l}),h=new Ue;for(const[b,v]of y.entries()){l?.info?.log({type:"task",id:_,status:m.Running,message:`[${S(_,f)}] Processing step ${b+1}: ${v.type}`});try{await g.executeTask({task:v,chat:h,provider:r,variables:i,options:a,stats:c,recorder:l})}catch(N){throw N instanceof A?N:new oe(`Error executing task ${v.type}`,{id:_,taskType:v.type,taskIndex:b,cause:N instanceof Error?N:new Error(String(N))})}}return l?.info?.log({type:"task",status:m.Success,id:_,message:`[${S(_,f)}] Completed ${y.length} steps`}),j(i[Q.LastResult],c)}catch(y){const h=y instanceof A?y:new A("Serial workflow execution failed",{id:_,cause:y instanceof Error?y:new Error(String(y))});return l?.info?.log({type:"task",status:m.Fail,id:_,message:`[${S(_,f)}] Failed: ${h.message}`}),l?.error.log(h),Y(h,i[Q.LastResult],c)}},"execute")}},"serialWorkflow"),Ae=u((t,...e)=>{const s=u(async o=>{const{recorder:r}=o;let i=[],a=null;if("batch"in t){const c=t;a=await we(c),i=await Z(c,{recorder:r})}else a=t,i=[...e];return[a,i]},"prepare");return{execute:u(async o=>{const{provider:r,variables:i,options:a,stats:c,recorder:l,name:f}=o,_=crypto.randomUUID();try{const[g,y]=await s({recorder:l}),h=await g.plan(y);if(l?.debug?.heading.log("Runs",h),h.length===0)return l?.info?.log("No runs to execute"),j([],c);let b=0;l?.info?.log({type:"task",status:m.Running,id:_,message:`[${S(_,"CRW")}] Working on 0/${h.length}`});const v=u(async(R,V)=>{try{return await re(...R.tasks).execute({provider:r,variables:{...R.variables,...i},options:a,stats:c,recorder:l,name:`${f}-${V}`})}catch(k){const ie=k instanceof A?k:new A("Error executing run",{cause:k instanceof Error?k:new Error(String(k))});return l?.error?.log(ie),Y(ie,null,c)}finally{b++,l?.info?.log({type:"task",status:m.Running,id:_,message:`[${S(_,"CRW")}] Working on ${b}/${h.length}`})}},"executeRun"),N=5;let G=[];for(let R=0;R<h.length;R+=N){const V=h.slice(R,R+N),k=await Promise.all(V.map(v));G=G.concat(k)}const M=G.some(Vt);l?.info?.log({type:"task",status:M?m.PartialSuccess:m.Success,id:_,message:`[${S(_,"CRW")}] All jobs (${h.length}) completed${M?" with some errors":""}`});const L=G.map(R=>R.response);return j(L,c)}catch(g){const y=g instanceof A?g:new A("Concurrent workflow execution failed",{id:_,cause:g instanceof Error?g:new Error(String(g))});return l?.error?.log(y),Y(y,null,c)}},"execute")}},"concurrentWorkflow");class us{static{u(this,"DAGParser")}static parse(e){const s=new Map;for(const[o,r]of Object.entries(e)){const i=this.parseNodeDefinition(o,r);s.set(o,i)}return this.validateDependencies(s),this.checkForCycles(s),{stages:this.createExecutionStages(s),nodes:s}}static parseNodeDefinition(e,s){if(this.isSimpleTask(s))return{id:e,tasks:Array.isArray(s)?s:[s],dependencies:[],executionType:"serial"};if(this.isConcurrentNodeDefinition(s)){const i=s,a=i.dependsOn?D(i.dependsOn):[];return{id:e,tasks:i.tasks,dependencies:a,planner:i.planner,executionType:"concurrent"}}const n=s,o=n.dependsOn?D(n.dependsOn):[],r=D(n.task);return{id:e,tasks:r,dependencies:o,executionType:"serial"}}static isSimpleTask(e){return e.type||Array.isArray(e)}static isConcurrentNodeDefinition(e){return e&&typeof e=="object"&&"planner"in e}static validateDependencies(e){for(const s of e.values())for(const n of s.dependencies)if(!e.has(n))throw new A(`Node "${s.id}" depends on non-existent node "${n}"`)}static checkForCycles(e){const s=new Set,n=new Set,o=u(r=>{if(n.has(r))return!0;if(s.has(r))return!1;s.add(r),n.add(r);const i=e.get(r);for(const a of i.dependencies)if(o(a))return!0;return n.delete(r),!1},"hasCycle");for(const r of e.keys())if(o(r))throw new A(`Circular dependency detected involving node "${r}"`)}static createExecutionStages(e){const s=[],n=new Set,o=new Set(e.keys());for(;o.size>0;){const r=[];for(const i of o)e.get(i).dependencies.every(l=>n.has(l))&&r.push(i);if(r.length===0)throw new A("Unable to resolve DAG dependencies - possible circular reference");s.push(r),r.forEach(i=>{n.add(i),o.delete(i)})}return s}}class ls{static{u(this,"DAGJobToDefinition")}static async convert(e,s){const{recorder:n}=s,o={};for(const[r,i]of Object.entries(e)){const{dependsOn:a,...c}=i;if("batch"in c){const l=c,f=await we(l),_=await Z(l,{recorder:n}),g={planner:f,tasks:_,...a?{dependsOn:a}:{}};o[r]=g}else{const l=await Z(c,{recorder:n});if(a){const f={task:l,dependsOn:a};o[r]=f}else o[r]=l}}return o}}async function fs(t,e,s,n={}){const{variables:o}=s,r=e.nodes.get(t);try{let i;if(r.executionType==="concurrent"&&r.planner?i=await Ae(r.planner,...r.tasks).execute({...s,variables:o,name:t}):i=await re(...r.tasks).execute({...s,variables:o,name:t}),!i.success)throw new A(`Node "${t}" failed: ${i.error?.message}`);return i.response}catch(i){if(!n.continueOnError)throw i;return null}}u(fs,"executeNode");const ps=u((t,e={})=>{const s=u(async(o,r)=>{const{recorder:i}=r,a={value:""};return me(o,a)?await ls.convert(o,r):(i?.warn?.log(a),o)},"prepare");return{execute:u(async o=>{const{stats:r,recorder:i}=o,{maxConcurrency:a=3}=e,c=crypto.randomUUID();try{const l=await s(t,{recorder:i});i?.debug?.log(l);const f=us.parse(l),_=new Map;i?.info?.log({type:"task",id:c,status:m.Running,message:`[${S(c)}] Starting workflow execution with ${f.stages.length} stages`});for(const[y,h]of f.stages.entries()){i?.info?.log({type:"task",id:c,status:m.Running,message:`[${S(c)}] Stage ${y+1}/${f.stages.length}, executing ${h.length} nodes: ${h.join(", ")}`});const b=Math.min(h.length,a);for(let v=0;v<h.length;v+=b){const N=h.slice(v,v+b);(await Promise.all(N.map(async M=>{const L=await fs(M,f,o,e);return{nodeId:M,result:L}}))).forEach(({nodeId:M,result:L})=>{_.set(M,L)})}}i?.info?.log({type:"task",status:m.Success,id:c,message:`[${S(c)}] Workflow execution completed successfully`});const g=Object.fromEntries(_);return j(g,r)}catch(l){const f=l instanceof A?l:new A("DAG workflow execution failed",{id:c,cause:l instanceof Error?l:new Error(String(l))});return i?.info?.log({type:"task",status:m.Fail,id:c,message:`[${S(c)}] Workflow execution failed: ${f.message}`}),i?.error?.log(f),Y(f,null,r)}},"execute")}},"dagWorkflow"),_s=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],x={success:"\u2713",fail:"\u2717",spinning:_s};class ds{static{u(this,"ConsoleWriter")}tasks=new Map;entries=[];truncate=0;intervalId=null;spinnerInterval=80;lastRender="";isRendering=!1;inline=!0;constructor(e={}){this.truncate=e.truncate??0,this.inline=e.inline??!0}startSpinner(){this.intervalId===null&&(this.intervalId=setInterval(()=>{[...this.tasks.values()].some(s=>s.status===m.Running)&&this.renderTasks()},this.spinnerInterval))}stopSpinner(){this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}renderTasks(){if(this.isRendering)return;if(this.isRendering=!0,this.inline&&this.lastRender){const r=this.lastRender.split(`
|
|
31
|
-
`).length;le.moveCursor(process.stdout,0,-r+1),le.clearScreenDown(process.stdout)}const e=[...this.tasks.values()],s=e.filter(r=>r.status===m.Running),n=e.filter(r=>r.status===m.Success||r.status===m.Fail);if(s.length===0&&n.length>0){let r="";for(const i of n){if(i.status===m.Success){const a=w.green(x.success);r+=`${a} ${i.text}
|
|
32
|
-
`}else if(i.status===m.Fail){const a=w.red(x.fail);r+=`${a} ${i.text}
|
|
33
|
-
`}this.tasks.delete(i.id)}console.log(r)}for(const r of this.entries){const{level:i,time:a,kind:c,payload:l}=r;c==="heading"?ms(i,l,{truncate:this.truncate}):hs(i,l,{truncate:this.truncate})}this.entries=[];let o="";for(const r of this.tasks.values())if(r.status===m.Running){const i=w.cyan(x.spinning[r.frameIndex]);r.frameIndex=(r.frameIndex+1)%x.spinning.length,o+=`${i} ${r.text}
|
|
34
|
-
`}else if(r.status===m.Success){const i=w.green(x.success);o+=`${i} ${r.text}
|
|
35
|
-
`}else if(r.status===m.Fail){const i=w.red(x.fail);o+=`${i} ${r.text}
|
|
36
|
-
`}this.lastRender=o,process.stdout.write(o),this.isRendering=!1}handleEvent(e){const{level:s,time:n,payload:o}=e;if(o.length>0&&gs(o[0])){const i=o[0],{id:a,message:c,status:l}=i;if(l===m.Running)this.tasks.set(a,{id:a,text:c,status:l,frameIndex:0});else if((l===m.Success||l===m.Fail)&&this.tasks.has(a)){const f=this.tasks.get(a);f.status=l,f.text=c}}else this.entries.push(e);this.renderTasks();const r=[...this.tasks.values()].some(i=>i.status===m.Running);r&&this.intervalId===null?this.startSpinner():!r&&this.intervalId!==null&&this.stopSpinner()}destroy(){this.stopSpinner()}}function gs(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.type!=="task"||typeof e.id!="string"||typeof e.message!="string")return!1;switch(e.status){case m.Running:case m.Success:case m.PartialSuccess:case m.Fail:return!0;default:return!1}}u(gs,"isTask");function ms(t,e,s){let n,o;t===T.Error?(n=w.red,o=w.redBright.bold):t===T.Warn?(n=w.yellow,o=w.yellowBright.bold):t>=T.Info?(n=w.blue,o=w.whiteBright.bold):(n=w.gray,o=w.white);const{message:r,data:i}=Se(e);console.log(`${n("==>")} ${o(r)}`),ve(t,i,s)}u(ms,"heading");function hs(t,e,s){let n;t===T.Error?n=w.red:t===T.Warn?n=w.yellow:t>=T.Info?n=w.white:n=w.gray;const{message:o,data:r}=Se(e);o&&console.log(n(o)),ve(t,r,s)}u(hs,"body");const Pe=" ";function ve(t,e,s){let n;t===T.Error?(n=w.red,s.truncate=0):t==T.Warn?n=w.yellow:t>=T.Info?n=w.white:n=w.gray,e.forEach(o=>{if(typeof o=="string"){console.log(n(`${Pe}${o}`));return}for(const[r,i]of Object.entries(o)){let a=JSON.stringify(i,ys(s.truncate)," ");const c=`${r}: ${a}`.split(`
|
|
37
|
-
`).map(l=>Pe+l).join(`
|
|
38
|
-
`);console.log(n(c))}})}u(ve,"values");function Se(t){const[e,...s]=t;let n="",o=s;if(e){let{message:r,...i}=e;n=r&&typeof r=="string"?r:"",Object.keys(i).length>0&&(o=[i,...o])}return{message:n,data:o}}u(Se,"toMsgData");function ys(t){return t===0?null:(e,s)=>typeof s=="string"&&s.length>t?s.slice(0,t)+"<...>":s}u(ys,"truncator");export{A,ds as C,$ as I,T as L,mt as R,se as W,Ee as a,K as b,Ae as c,ps as d,ht as e,vt as f,gt as g,Ie as h,ye as i,q as l,re as s};
|