@fifthrevision/axle 0.4.2 → 0.6.2

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 CHANGED
@@ -1,12 +1,4 @@
1
1
  #!/usr/bin/env node
2
- var A=Object.defineProperty;var g=(i,t)=>A(i,"name",{value:t,configurable:!0});import{Command as F}from"@commander-js/extra-typings";import{b as I,i as L,T as u,L as p,R as W,g as _,e as J,d as N}from"./dag-CE2X29BG.js";import x from"yaml";import r from"chalk";import R from"node:readline";import{access as T,mkdir as P,writeFile as M,appendFile as U}from"node:fs/promises";import{homedir as z}from"node:os";import"@anthropic-ai/sdk";import"@google/genai";import"openai";import"serialize-error";import"fs/promises";import"glob";import"node:path";var B="0.4.2",G={version:B};function H(i,t){if(typeof i!="object"||i===null)return t&&(t.value="Config: must be a non-null object"),!1;if("openai"in i){const e=i.openai;if(typeof e!="object"||e===null)return t&&(t.value="Config: openai must be an object"),!1;if(typeof e["api-key"]!="string")return t&&(t.value="Config: openai.api-key must be a string"),!1;if("model"in e&&typeof e.model!="string")return t&&(t.value="Config: openai.model must be a string"),!1}if("anthropic"in i){const e=i.anthropic;if(typeof e!="object"||e===null)return t&&(t.value="Config: anthropic must be an object"),!1;if(typeof e["api-key"]!="string")return t&&(t.value="Config: anthropic.api-key must be a string"),!1;if("model"in e&&typeof e.model!="string")return t&&(t.value="Config: anthropic.model must be a string"),!1}if("ollama"in i){const e=i.ollama;if(typeof e!="object"||e===null)return t&&(t.value="Config: ollama must be an object"),!1;if("url"in e&&typeof e.url!="string")return t&&(t.value="Config: ollama.url must be a string"),!1;if("model"in e&&typeof e.model!="string")return t&&(t.value="Config: ollama.model must be a string"),!1}if("googleai"in i){const e=i.googleai;if(typeof e!="object"||e===null)return t&&(t.value="Config: googleai must be an object"),!1;if(typeof e["api-key"]!="string")return t&&(t.value="Config: googleai.api-key must be a string"),!1;if("model"in e&&typeof e.model!="string")return t&&(t.value="Config: googleai.model must be a string"),!1}if("brave"in i){const e=i.brave;if(typeof e!="object"||e===null)return t&&(t.value="Config: brave must be an object"),!1;if(typeof e["api-key"]!="string")return t&&(t.value="Config: brave.api-key must be a string"),!1;if("rateLimit"in e&&typeof e.rateLimit!="number")return t&&(t.value="Config: brave.rateLimit must be a number"),!1}return!0}g(H,"isServiceConfig");const X="ax.job",K=["yaml","yml","json"];async function V(i,t){const{recorder:e}=t,{content:s,format:o}=await I(i,{defaults:{name:X,formats:K},tag:"Job File"});let n=null;if(o==="json")n=JSON.parse(s);else if(o==="yaml"||o==="yml")n=x.parse(s);else throw new Error("Invalid job file format");e?.debug?.heading.log("The Job Object"),e?.debug?.log(n);const a={value:""};if(L(n,a))return n;throw new Error(`The job file is not valid: ${a.value}`)}g(V,"getJobConfig");const Y="ax.config",q=["yaml","yml","json"];async function Q(i,t){const{recorder:e}=t,{content:s,format:o}=await I(i,{defaults:{name:Y,formats:q},tag:"Config File"});let n=null;if(o==="json")n=JSON.parse(s);else if(o==="yaml"||o==="yml")n=x.parse(s);else throw new Error("Invalid config file format");e?.debug?.heading.log("The Config Object"),e?.debug?.log(n);const a={value:""};if(H(n,a))return n;throw new Error(a.value)}g(Q,"getServiceConfig");const Z=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],m={success:"\u2713",fail:"\u2717",spinning:Z};class tt{static{g(this,"ConsoleWriter")}tasks=new Map;entries=[];truncate=0;intervalId=null;spinnerInterval=80;lastRender="";isRendering=!1;inline=!0;constructor(t={}){this.truncate=t.truncate??0,this.inline=t.inline??!0}startSpinner(){this.intervalId===null&&(this.intervalId=setInterval(()=>{[...this.tasks.values()].some(e=>e.status===u.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 n=this.lastRender.split(`
3
- `).length;R.moveCursor(process.stdout,0,-n+1),R.clearScreenDown(process.stdout)}const t=[...this.tasks.values()],e=t.filter(n=>n.status===u.Running),s=t.filter(n=>n.status===u.Success||n.status===u.Fail);if(e.length===0&&s.length>0){let n="";for(const a of s){if(a.status===u.Success){const f=r.green(m.success);n+=`${f} ${a.text}
4
- `}else if(a.status===u.Fail){const f=r.red(m.fail);n+=`${f} ${a.text}
5
- `}this.tasks.delete(a.id)}console.log(n)}for(const n of this.entries){const{level:a,time:f,kind:c,payload:h}=n;c==="heading"?it(a,h,{truncate:this.truncate}):nt(a,h,{truncate:this.truncate})}this.entries=[];let o="";for(const n of this.tasks.values())if(n.status===u.Running){const a=r.cyan(m.spinning[n.frameIndex]);n.frameIndex=(n.frameIndex+1)%m.spinning.length,o+=`${a} ${n.text}
6
- `}else if(n.status===u.Success){const a=r.green(m.success);o+=`${a} ${n.text}
7
- `}else if(n.status===u.Fail){const a=r.red(m.fail);o+=`${a} ${n.text}
8
- `}this.lastRender=o,process.stdout.write(o),this.isRendering=!1}handleEvent(t){const{level:e,time:s,payload:o}=t;if(o.length>0&&et(o[0])){const a=o[0],{id:f,message:c,status:h}=a;if(h===u.Running)this.tasks.set(f,{id:f,text:c,status:h,frameIndex:0});else if((h===u.Success||h===u.Fail)&&this.tasks.has(f)){const j=this.tasks.get(f);j.status=h,j.text=c}}else this.entries.push(t);this.renderTasks();const n=[...this.tasks.values()].some(a=>a.status===u.Running);n&&this.intervalId===null?this.startSpinner():!n&&this.intervalId!==null&&this.stopSpinner()}destroy(){this.stopSpinner()}}function et(i){if(typeof i!="object"||i===null)return!1;const t=i;if(t.type!=="task"||typeof t.id!="string"||typeof t.message!="string")return!1;switch(t.status){case u.Running:case u.Success:case u.PartialSuccess:case u.Fail:return!0;default:return!1}}g(et,"isTask");function it(i,t,e){let s,o;i===p.Error?(s=r.red,o=r.redBright.bold):i===p.Warn?(s=r.yellow,o=r.yellowBright.bold):i>=p.Info?(s=r.blue,o=r.whiteBright.bold):(s=r.gray,o=r.white);const{message:n,data:a}=D(t);console.log(`${s("==>")} ${o(n)}`),S(i,a,e)}g(it,"heading");function nt(i,t,e){let s;i===p.Error?s=r.red:i===p.Warn?s=r.yellow:i>=p.Info?s=r.white:s=r.gray;const{message:o,data:n}=D(t);o&&console.log(s(o)),S(i,n,e)}g(nt,"body");const $=" ";function S(i,t,e){let s;i===p.Error?(s=r.red,e.truncate=0):i==p.Warn?s=r.yellow:i>=p.Info?s=r.white:s=r.gray,t.forEach(o=>{if(typeof o=="string"){console.log(s(`${$}${o}`));return}for(const[n,a]of Object.entries(o)){let f=JSON.stringify(a,st(e.truncate)," ");const c=`${n}: ${f}`.split(`
9
- `).map(h=>$+h).join(`
10
- `);console.log(s(c))}})}g(S,"values");function D(i){const[t,...e]=i;let s="",o=e;if(t){let{message:n,...a}=t;s=n&&typeof n=="string"?n:"",Object.keys(a).length>0&&(o=[a,...o])}return{message:s,data:o}}g(D,"toMsgData");function st(i){return i===0?null:(t,e)=>typeof e=="string"&&e.length>i?e.slice(0,i)+"<...>":e}g(st,"truncator");const y="./logs/",ot="~/.axle/logs/";class at{static{g(this,"LogWriter")}time;initialized=!1;logDir=y;pendingWrites=[];constructor(){this.time=new Date().toISOString()}get filename(){return`${this.logDir}${this.time}.log`}async initialize(){try{await T(y),this.logDir=y}catch{const s=ot.replace("~",z());try{await T(s),this.logDir=s}catch{await P(s,{recursive:!0}),this.logDir=s}}const t=M(this.filename,`AXLE: New run at ${this.time}
11
- `);this.pendingWrites.push(t);try{await t,this.initialized=!0}finally{const e=this.pendingWrites.indexOf(t);e!==-1&&this.pendingWrites.splice(e,1)}}async writeToLog(t){const{time:e,level:s,payload:o}=t;this.initialized||await this.initialize();const n=o.map(c=>typeof c=="string"?c:JSON.stringify(c)),a=`${p[s]} ${new Date(e).toISOString()} > ${n.join(" >> ")}
12
- `,f=U(this.filename,a).catch(c=>{console.error(`Failed to write to log file: ${c}`)});this.pendingWrites.push(f);try{await f}finally{const c=this.pendingWrites.indexOf(f);c!==-1&&this.pendingWrites.splice(c,1)}}async handleEvent(t){await this.writeToLog(t)}async flush(){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites)}}const b=new F().name("axle").description("Axle is a CLI tool for running AI workflows").version(G.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");b.parse(process.argv);const d=b.opts(),v={};d.args&&d.args.forEach(i=>{const[t,e]=i.split("=");t&&e&&(v[t.trim()]=e.trim())}),process.on("uncaughtException",async i=>{console.error("Uncaught exception:"),console.error(i),l&&(l.error?.log("Uncaught exception:"),l.error?.log(i.message),l.error?.log(i.stack||""),await l.shutdown()),process.exit(1)});const l=new W;d.debug&&(l.level=p.Debug);const lt=new tt(d);if(l.subscribe(lt),d.log){const i=new at;await i.initialize(),l.subscribe(i)}d.debug&&(l.debug?.heading.log("Options"),l.debug?.log(d),l.debug?.heading.log("Additional Arguments:"),l.debug?.log(v));let w,k;try{w=await Q(d.config??null,{recorder:l}),k=await V(d.job??null,{recorder:l})}catch(i){l.error.log(i.message),l.debug?.log(i.stack),await l.shutdown(),b.outputHelp(),process.exit(1)}let E;try{const{engine:i,...t}=k.using,e={...w[i],...t};E=_(i,e)}catch(i){l.error.log(i.message),l.error.log(i.stack),await l.shutdown(),b.outputHelp(),process.exit(1)}J().setConfig(w),l.info?.heading.log("All systems operational. Running job...");const rt=Date.now();d.dryRun&&l.info?.log("Dry run mode enabled. No API calls will be made.");const C={in:0,out:0},O=await N(k.jobs).execute({provider:E,variables:v,options:d,stats:C,recorder:l});O&&(l.info?.heading.log("Response"),l.info.log(O)),l.info?.heading.log("Usage"),l.info?.log(`Total run time: ${Date.now()-rt}ms`),l.info?.log(`Input tokens: ${C.in} `),l.info?.log(`Output tokens: ${C.out} `),l.info?.heading.log("Complete. Goodbye"),await l.shutdown();
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{q as y,r as k,L as v,R as x,C as O,g as E,t as T,d as F}from"./consoleWriter-RwD37QOu.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.2",$={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 q=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()-q}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 Ke=Object.defineProperty;var l=(t,e)=>Ke(t,"name",{value:e,configurable:!0});import ze from"@anthropic-ai/sdk";import*as I from"zod";import F,{z as q}from"zod";import{FinishReason as O,GoogleGenAI as Xe}from"@google/genai";import Ze from"openai";import{serializeError as Ye}from"serialize-error";import{readFile as Qe,access as Ve,constants as et}from"fs/promises";import{glob as ue}from"glob";import{readFile as U,access as le,stat as tt,writeFile as nt,mkdir as st}from"node:fs/promises";import{resolve as te,extname as fe,dirname as rt}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 ot(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(ot,"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 it(t){return t.filter(e=>e.type==="tool-call")}l(it,"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(!at(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 at(t){return t&&typeof t=="object"&&t.type==="object"}l(at,"isObjectSchema");async function ct(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=ut(f)}catch(f){d=W(f)}return u?.debug?.log(d),d}l(ct,"createGenerationRequest$2");function ut(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(ut,"convertToAIResponse");function lt(){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(lt,"createAnthropicStreamingAdapter");async function*ft(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=lt();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(ft,"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 pt{static{l(this,"AnthropicProvider")}name=he;client;model;constructor(e,n){this.model=n??me,this.client=new ze({apiKey:e})}async createGenerationRequest(e){return await ct({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return ft({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(dt).filter(e=>e!==void 0)}l(Ee,"convertAxleMessagesToGemini");function dt(t){switch(t.role){case"tool":return _t(t);case"assistant":return gt(t);case"user":return mt(t)}}l(dt,"convertMessage$3");function _t(t){return{role:"user",parts:t.content.map(e=>({functionResponse:{id:e.id??void 0,name:e.name,response:{output:e.content}}}))}}l(_t,"convertToolMessage$3");function gt(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(gt,"convertAssistantMessage$3");function mt(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map(ht).filter(n=>n!==null)}}l(mt,"convertUserMessage$3");function ht(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(ht,"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 yt(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=Et(f,{recorder:u})}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(yt,"createGenerationRequest$1");function Et(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(Et,"fromModelResponse$3");function It(){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(It,"createGeminiStreamingAdapter");async function*wt(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=It();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(wt,"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 Tt{static{l(this,"GeminiProvider")}name=Te;client;model;constructor(e,n){this.model=n??we,this.client=new Xe({apiKey:e})}async createGenerationRequest(e){return await yt({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return wt({client:this.client,model:this.model,messages:n,system:s,tools:r,runtime:o,options:i})}}function xe(t){return t.map(xt).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 xt(t){switch(t.role){case"tool":return At(t);case"assistant":return St(t);default:return kt(t)}}l(xt,"convertMessage$2");function At(t){return t.content.map(e=>({role:"tool",tool_call_id:e.id,content:e.content}))}l(At,"convertToolMessage$2");function St(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(St,"convertAssistantMessage$2");function kt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=[],n=[];for(const s of t.content){const r=Rt(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(kt,"convertUserMessage$2");function Rt(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(Rt,"convertContentPart$2");async function Pt(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=Ot(m)}catch(_){u?.error?.log("Error fetching Ollama response:",_),f=W(_)}return u?.debug?.log(f),f}l(Pt,"createGenerationRequest");function Ot(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(Ot,"fromModelResponse$2");function bt(){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=vt(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(bt,"createOllamaStreamingAdapter");function vt(t){switch(t){case"stop":return y.Stop;case"length":return y.Length;default:return y.Stop}}l(vt,"convertStopReason");async function*Nt(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=bt();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(Nt,"createStreamingRequest$1");const Se="http://localhost:11434",$t="Ollama";class Mt{static{l(this,"OllamaProvider")}name="Ollama";url;model;recorder;constructor(e,n){this.url=n||Se,this.model=e}async createGenerationRequest(e){return await Pt({url:this.url,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return Nt({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(Gt).flat(1);return e?[{role:"system",content:e},...n]:n}l(Re,"convertAxleMessagesToChatCompletion");function Gt(t){switch(t.role){case"tool":return Ct(t);case"assistant":return Lt(t);default:return Dt(t)}}l(Gt,"convertMessage$1");function Ct(t){return t.content.map(e=>({role:"tool",tool_call_id:e.id,content:e.content}))}l(Ct,"convertToolMessage$1");function Lt(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(Lt,"convertAssistantMessage$1");function Dt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(Ft).filter(n=>n!==null);return{role:t.role,content:e}}}l(Dt,"convertUserMessage$1");function Ft(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(Ft,"convertContentPart$1");async function Ut(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=Wt(f)}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(Ut,"createGenerationRequestWithChatCompletion");function Wt(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(Wt,"fromModelResponse$1");function Ht(){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=Bt(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(Ht,"createChatCompletionStreamingAdapter");function Bt(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(Bt,"convertFinishReason");function qt(){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(qt,"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 jt(t);case"assistant":return Kt(t);default:return zt(t)}}l(Jt,"convertMessage");function jt(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:e.content}))}l(jt,"convertToolMessage");function Kt(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(Kt,"convertAssistantMessage");function zt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(Xt).filter(n=>n!==null);return{role:t.role,content:e}}}l(zt,"convertUserMessage");function Xt(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(Xt,"convertContentPart");async function*Zt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}=t,{recorder:u}=i;Pe.includes(n)?yield*Qt({client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c}):yield*Yt({client:e,model:n,messages:s,system:r,tools:o,runtime:i,options:c})}l(Zt,"createStreamingRequest");async function*Yt(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=Ht();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(Yt,"createChatCompletionStream");async function*Qt(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=qt();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(Qt,"createResponsesAPIStream");async function Vt(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=en(f)}catch(f){u?.error?.log(f),d=W(f)}return u?.debug?.log(d),d}l(Vt,"createGenerationRequestWithResponsesAPI");function en(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(en,"fromModelResponse");const Ne="OpenAI";class tn{static{l(this,"OpenAIProvider")}name=Ne;client;model;constructor(e,n){this.model=n||Oe,this.client=new Ze({apiKey:e})}async createGenerationRequest(e){return Pe.includes(this.model)?await Vt({client:this.client,model:this.model,...e}):await Ut({client:this.client,model:this.model,...e})}createStreamingRequest(e){const{messages:n,system:s,tools:r,context:o,options:i}=e;return Zt({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 nn(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 tn(e["api-key"],e.model);case"anthropic":return new pt(e["api-key"],e.model);case"gemini":return new Tt(e["api-key"],e.model);case"ollama":{const n=e;return new Mt(n.model,n.url)}default:throw new A("The provider is unsupported")}}l(nn,"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 sn{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?Ye(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 rn(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(rn,"searchAndLoadFile");async function on(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(on,"loadManyFiles");function an(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(an,"replaceFilePattern");function cn(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(cn,"pathToComponents");async function Me(t){const e=rt(t);try{await le(e)}catch{await st(e),await Me(e)}}l(Me,"ensureDirectoryExistence");async function un({filePath:t,content:e}){await Me(t),await nt(t,e)}l(un,"writeFileWithDirectories");const J=[".jpg",".jpeg",".png",".gif",".webp",".bmp",".tiff"],j=[".pdf"],K=[".txt",".md",".markdown"],Ge=20*1024*1024;function ln(t){return t.type==="text"}l(ln,"isTextFileInfo");function fn(t){return t.type==="image"||t.type==="document"}l(fn,"isBase64FileInfo");function pn(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(pn,"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 tt(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||pn(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 dn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):_n(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(dn,"isJobConfig");function _n(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(_n,"isUsing");function Ce(t,e){for(const[n,s]of Object.entries(t))if(!gn(s,e))return e&&(e.value=`Invalid job '${n}': ${e?.value}`),!1;return!0}l(Ce,"isDAGJob");function gn(t,e){if(!t||typeof t!="object")return e&&(e.value="Not an object"),!1;if(!mn(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(gn,"isDAGJobValue");function mn(t,e){return!t||typeof t!="object"?(e&&(e.value="Not an object"),!1):"batch"in t?yn(t,e):hn(t,e)}l(mn,"isJob");function hn(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(hn,"isSerialJob");function yn(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(!En(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(yn,"isBatchJob");function En(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(!In(t["skip-if"][n],e))return e&&(e.value=`Invalid skip condition at index ${n}: ${e?.value}`),!1}return!0}l(En,"isBatchOptions");function In(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(In,"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"?wn(t,e):t.uses==="write-to-disk"?Tn(t,e):(e&&(e.value=`Unknown uses type: ${t.uses}`),!1)}l(Le,"isStep");function wn(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(!xn(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(!An(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(!Sn(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(!kn(t.references[n],e))return e&&(e.value=`Invalid reference at index ${n}: ${e?.value}`),!1}return!0}l(wn,"isChatStep");function Tn(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(Tn,"isWriteToDiskStep");function xn(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(xn,"isReplace");function An(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(An,"isImageReference");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,"isDocumentReference");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,"isTextFileReference");class Rn{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=cn(o);let c=!1;for(const u of this.skipConditions)if(c=await u.eval({components:i}),c)break;if(!c){const u=await Qe(o,"utf-8"),a={variables:{[this.bind]:u,...i},tasks:e};n.push(a)}}return n}}class Pn{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 On{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 Ve(n,et.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(!fn(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(ln(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 bn(t){return new Promise(e=>setTimeout(e,t))}l(bn,"delay");const vn=I.object({searchTerm:I.string().describe("The search term to query")});class Nn{static{l(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=vn;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 bn(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 $n=new Nn,Mn=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")}),Gn={name:"calculator",description:"Performs basic arithmetic operations",schema:Mn,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 Cn{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 Cn,B.register(Gn),B.register($n)),B}l(Ue,"getToolRegistry");const Ln={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 on(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 Dn{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 Fn={async convert(t){if(t.keys){const e=H(t.keys);return new re(t.output,e)}return new re(t.output)}},oe=new Dn;oe.register("write-to-disk",Fn),oe.register("chat",Ln);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 Pn(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=>Un(s))),new Rn(t.source,t.bind,e)}}l(He,"batchOptionsToPlanner");function Un(t){switch(t.type){case"file-exist":return new On(t.pattern)}}l(Un,"skipOptionsToSkipConditions");function Wn(t){return t.success===!1&&t.error!==void 0}l(Wn,"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 Hn{static{l(this,"Conversation")}system;_messages=[];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=an(i,s.file):a=se(i,s,"{}"),await un({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(ot({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 _=it(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 Hn;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"),Be=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(Wn);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 Be(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}=je(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}=je(e);r&&console.log(s(r)),Je(t,o,n)}l(os,"body");const qe=" ";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(`${qe}${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=>qe+a).join(`
33
+ `);console.log(s(u))}})}l(Je,"values");function je(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(je,"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,sn as R,re as W,we as a,h as b,Te as c,es as d,Se as e,$t as f,nn 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,Be as p,rn as q,dn as r,ie as s,Ue as t};